<commit_before>var chartOptions = {
	chartArea: {
		width: '100%',
		height: '100%',
		top: 75,
		right: 0,
		left: 75,
		bottom: 100
	},
	colors: ['#a11'],
	curveType: 'function',
	height: 600,
	hAxis: {
		textStyle: {
			fontSize: 12
		},
		slantedText: false,
		maxAlternation: 1
	},
	interpolateNulls: false,
	legend: {
		position: 'none',
	},
	vAxis: {
		minValue: 0,
		textStyle: {
			fontSize: 12
		},
		gridlines: {
			count: 11
		},
		minorGridlines: {
			count: 1
		},
		titleTextStyle: {
			fontSize: 14,
			italic: false
		}
	},
	pointShape: 'diamond',
	pointsVisible: true
}

function HistoryCtrl($scope, $http, $routeParams) {
	routeParams = $routeParams.params.split('|');

	var params = {
		component: routeParams[0],
		testCase: routeParams[1],
		metric: routeParams[2]
	};

	$scope.title = params.component + ' : ' + params.testCase;

	$http.get('api/v1/timeline', {params: params}).then(function(response) {
		var chartData = new google.visualization.DataTable();
		chartData.addColumn('string');
		chartData.addColumn('number');
		chartData.addRows(response.data);

		var div = document.createElement('div');
		div.id = 'history';
		$('#charts').append(div);

		chartOptions.title = params.metric;

		var lineChart = new google.visualization.LineChart(document.getElementById(div.id));
		lineChart.draw(chartData, chartOptions);
	});

	$http.get('api/v1/history', {params: params}).then(function(response) {
		$scope.history = response.data;
	});
}
<commit_msg>Reserve more space for the right side of the chart<commit_after>var chartOptions = {
	chartArea: {
		width: '100%',
		height: '100%',
		top: 75,
		right: 15,
		left: 75,
		bottom: 100
	},
	colors: ['#a11'],
	curveType: 'function',
	height: 600,
	hAxis: {
		textStyle: {
			fontSize: 12
		},
		slantedText: false,
		maxAlternation: 1
	},
	interpolateNulls: false,
	legend: {
		position: 'none',
	},
	vAxis: {
		minValue: 0,
		textStyle: {
			fontSize: 12
		},
		gridlines: {
			count: 11
		},
		minorGridlines: {
			count: 1
		},
		titleTextStyle: {
			fontSize: 14,
			italic: false
		}
	},
	pointShape: 'diamond',
	pointsVisible: true
}

function HistoryCtrl($scope, $http, $routeParams) {
	routeParams = $routeParams.params.split('|');

	var params = {
		component: routeParams[0],
		testCase: routeParams[1],
		metric: routeParams[2]
	};

	$scope.title = params.component + ' : ' + params.testCase;

	$http.get('api/v1/timeline', {params: params}).then(function(response) {
		var chartData = new google.visualization.DataTable();
		chartData.addColumn('string');
		chartData.addColumn('number');
		chartData.addRows(response.data);

		var div = document.createElement('div');
		div.id = 'history';
		$('#charts').append(div);

		chartOptions.title = params.metric;

		var lineChart = new google.visualization.LineChart(document.getElementById(div.id));
		lineChart.draw(chartData, chartOptions);
	});

	$http.get('api/v1/history', {params: params}).then(function(response) {
		$scope.history = response.data;
	});
}
<|endoftext|>


<commit_before>import {
    Animated,
    findNodeHandle,
    NativeModules,
    StyleSheet,
    Text,
    TextInput,
    TouchableWithoutFeedback,
    View,
} from 'react-native';
import { getColor } from '../helpers';
import { TYPO, PRIMARY, THEME_NAME, PRIMARY_COLORS } from '../config';
import Icon from '../Icon';
import IconToggle from '../IconToggle';
import isFunction from '../utils';
import React, { Component, PropTypes } from 'react';

const UIManager = NativeModules.UIManager;

const propTypes = {
    actions: PropTypes.arrayOf(PropTypes.shape({
        icon: PropTypes.string.isRequired,
        onPress: PropTypes.func,
    })),
    icon: PropTypes.string,
    iconProps: PropTypes.shape({
        size: PropTypes.number,
        color: PropTypes.string,
    }),
    isSearchActive: PropTypes.bool,
    menuActions: PropTypes.shape({
        onPress: PropTypes.func,
        labels: PropTypes.array
    }),
    onIconPress: PropTypes.func,
    onTitlePress: PropTypes.func,
    primary: PropTypes.oneOf(PRIMARY_COLORS),
    searchable: PropTypes.shape({
        onChangeText: PropTypes.func,
        onSearchClosed: PropTypes.func,
        placeholder: PropTypes.string,
        onSearchPressed: PropTypes.func,
        onSubmitEditing: PropTypes.func,
        autoFocus: PropTypes.bool
    }),
    style: PropTypes.shape({
        toolbarContainer: PropTypes.object,
        titleContainer: PropTypes.object,
        leftIconContainer: PropTypes.object,
        rightIconContainer: PropTypes.object,
    }),
    theme: PropTypes.oneOf(THEME_NAME),
    title: PropTypes.string,
    translucent: PropTypes.bool,
};

const defaultProps = {
    elevation: 4,
    iconProps: {
        size: 24,
        color: 'rgba(255,255,255,.87)',
    },
    primary: PRIMARY,
    style: {},
    theme: 'dark',
};

const styles = StyleSheet.create({
    toolbarContainer: {
        height: 56,
        flexDirection: 'row',
        alignItems: 'center',
        elevation: 4,
    },
    titleContainer: {
        flex: 1,
    },
    searchInput: TYPO.paperFontTitle,
    leftIconContainer: {
        margin: 16,
    },
    rightIconContainer: {
        margin: 16,
    },
    leftIcon: {
        margin: 16,
    },
    rightIcon: {
        margin: 16,
    }
});

class Toolbar extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isSearchActive: props.isSearchActive,
            searchValue: ''
        };
    }
    onMenuPressed = () => {
        const { menuActions } = this.props;

        UIManager.showPopupMenu(
            findNodeHandle(this.refs.menu),
            menuActions.labels,
            () => {},
            menuActions.onPress
        );
    };
    onSearchTextChanged = (value) => {
        const { searchable } = this.props;

        if (isFunction(searchable.onChangeText)) {
            searchable.onChangeText(value);
        }

        this.setState({ searchValue: value });
    };
    onSearchPressed = () => {
        const { searchable } = this.props;

        if (isFunction(searchable.onSearchPressed)) {
            searchable.onSearchPressed();
        }

        this.setState({
            isSearchActive: true,
            searchValue: ''
        });
    };
    onSearchClosePressed = () => {
        const { searchable } = this.props;

        if (isFunction(searchable.onSearchClosed)) {
            searchable.onSearchClosed();
        }

        this.setState({
            isSearchActive: false,
            searchValue: ''
        });
    };
    getStyle = () => {
        const { style, primary, theme, translucent, iconProps } = this.props;

        let selectedTheme = {};

        if (this.state.isSearchActive || theme === 'light') {
            selectedTheme = {
                backgroundColor: '#ffffff',
                color: 'rgba(0,0,0,.87)',
                leftIconColor: 'rgba(0,0,0,.54)',
                rightIconColor: 'rgba(0,0,0,.54)'
            };
        } else {
            selectedTheme = {
                backgroundColor: getColor(primary),
                color: 'rgba(255,255,255,.87)',
                leftIconColor: 'rgba(255,255,255,.87)',
                rightIconColor: 'rgba(255,255,255,.87)'
            };
        }

        const result = {};
        let searchStyle = {};

        if (this.state.isSearchActive) {
            searchStyle = {
                toolbarContainer: { backgroundColor: getColor('paperGrey100') },
                titleText: {
                    color: 'rgba(0,0,0,.87)',
                    fontSize: 16,
                    fontWeight: 'normal',
                },
                leftIcon: { color: 'rgba(0,0,0,.54)' },
                rightIcon: { color: 'rgba(0,0,0,.54)' },
            };
        }

        result.toolbarContainer = [
            styles.toolbarContainer,
            { backgroundColor: selectedTheme.backgroundColor },
            searchStyle.toolbarContainer,
            translucent ? {
                elevation: 0,
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
            } : null,
            style.toolbarContainer,
        ];
        result.titleContainer = [
            styles.titleContainer,
            searchStyle.titleContainer,
            style.titleContainer
        ];
        result.titleText = [
            styles.titleText,
            TYPO.paperFontTitle,
            { color: selectedTheme.color },
            searchStyle.titleText,
            style.titleText
        ];
        result.leftIconContainer = [
            styles.leftIconContainer,
            searchStyle.leftIconContainer,
            style.leftIconContainer
        ];
        result.rightIconContainer = [
            styles.rightIconContainer,
            searchStyle.rightIconContainer,
            style.rightIconContainer
        ];
        result.leftIcon = [
            styles.leftIcon,
            searchStyle.leftIcon,
            style.leftIcon
        ];
        result.rightIcon = [
            styles.rightIcon,
            searchStyle.rightIcon,
            style.rightIcon
        ];
        result.iconProps = {
            size: iconProps.size,
            color: selectedTheme.leftIconColor,
        };

        return result;
    }
    focusSearchField() {
        this._searchFieldRef.focus();
    }
    renderLeftSide = (style) => {
        const { icon, onIconPress } = this.props;

        let iconName = icon;
        let onPress = onIconPress;

        if (this.state.isSearchActive) {
            iconName = 'arrow-back';
            onPress = this.onSearchClosePressed;
        }

        return (
            <View style={style.leftIconContainer}>
                <IconToggle color={style.iconProps.color} onPress={onPress}>
                    <Icon
                      name={iconName}
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                    />
                </IconToggle>
            </View>
        );
    }
    renderCenter = (style) => {
        if (!this.state.isSearchActive) {
            const { title, onTitlePress } = this.props;

            return (
                <TouchableWithoutFeedback key="center" onPress={onTitlePress}>
                    <Animated.View style={style.titleContainer}>
                        <Text numberOfLines={1} style={style.titleText}>
                            {title}
                        </Text>
                    </Animated.View>
                </TouchableWithoutFeedback>
            );
        }

        const { searchable } = this.props;

        return (
            <View style={style.titleContainer}>
                <TextInput
                  ref={(ref) => { this._searchFieldRef = ref; }}
                  autoFocus={searchable.autoFocus}
                  onChangeText={this.onSearchTextChanged}
                  onSubmitEditing={searchable.onSubmitEditing}
                  placeholder={searchable.placeholder}
                  style={style.titleText}
                  underlineColorAndroid="transparent"
                  value={this.state.searchValue}
                />
            </View>
        );
    }
    renderRightSide = (style) => {
        const { actions, menuActions, searchable } = this.props;

        let actionsMap = actions;

        if (this.state.isSearchActive) {
            actionsMap = [{
                icon: 'clear',
                onPress: () => this.onSearchTextChanged('')
            }];
        }

        let result = [];

        if (actionsMap) {
            result = actionsMap.map((action, i) => (
                <IconToggle
                  key={i}
                  color={style.iconProps.color}
                  badge={action.badge}
                  onPress={action.onPress}
                  disabled={action.disabled}
                >
                    <Icon
                      name={action.icon}
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            ));
        }

        if (searchable && !this.state.isSearchActive) {
            result.push(
                <IconToggle
                  key="searchIcon"
                  color={style.iconProps.color}
                  onPress={this.onSearchPressed}
                >
                    <Icon name="search"
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            );
        }
        if (menuActions && !this.state.isSearchActive) {
            result.push(
                <IconToggle
                  key="menuIcon"
                  color={style.iconProps.color}
                  onPress={this.onMenuPressed}
                >
                    <Icon
                      ref="menu"
                      name="more-vert"
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            );
        }

        return result;
    }
    render() {
        const style = this.getStyle();

        return (
            <Animated.View style={style.toolbarContainer}>
                { this.renderLeftSide(style) }
                { this.renderCenter(style) }
                { this.renderRightSide(style) }
            </Animated.View>
        );
    }

}

Toolbar.propTypes = propTypes;
Toolbar.defaultProps = defaultProps;

export default Toolbar;
<commit_msg>Fix touch feedback of tolbar's left icon<commit_after>import {
    Animated,
    findNodeHandle,
    NativeModules,
    StyleSheet,
    Text,
    TextInput,
    TouchableWithoutFeedback,
    View,
} from 'react-native';
import { getColor } from '../helpers';
import { TYPO, PRIMARY, THEME_NAME, PRIMARY_COLORS } from '../config';
import Icon from '../Icon';
import IconToggle from '../IconToggle';
import isFunction from '../utils';
import React, { Component, PropTypes } from 'react';

const UIManager = NativeModules.UIManager;

const propTypes = {
    actions: PropTypes.arrayOf(PropTypes.shape({
        icon: PropTypes.string.isRequired,
        onPress: PropTypes.func,
    })),
    icon: PropTypes.string,
    iconProps: PropTypes.shape({
        size: PropTypes.number,
        color: PropTypes.string,
    }),
    isSearchActive: PropTypes.bool,
    menuActions: PropTypes.shape({
        onPress: PropTypes.func,
        labels: PropTypes.array
    }),
    onIconPress: PropTypes.func,
    onTitlePress: PropTypes.func,
    primary: PropTypes.oneOf(PRIMARY_COLORS),
    searchable: PropTypes.shape({
        onChangeText: PropTypes.func,
        onSearchClosed: PropTypes.func,
        placeholder: PropTypes.string,
        onSearchPressed: PropTypes.func,
        onSubmitEditing: PropTypes.func,
        autoFocus: PropTypes.bool
    }),
    style: PropTypes.shape({
        toolbarContainer: PropTypes.object,
        titleContainer: PropTypes.object,
        leftIconContainer: PropTypes.object,
        rightIconContainer: PropTypes.object,
    }),
    theme: PropTypes.oneOf(THEME_NAME),
    title: PropTypes.string,
    translucent: PropTypes.bool,
};

const defaultProps = {
    elevation: 4,
    iconProps: {
        size: 24,
        color: 'rgba(255,255,255,.87)',
    },
    primary: PRIMARY,
    style: {},
    theme: 'dark',
};

const styles = StyleSheet.create({
    toolbarContainer: {
        height: 56,
        flexDirection: 'row',
        alignItems: 'center',
        elevation: 4,
    },
    titleContainer: {
        flex: 1,
    },
    searchInput: TYPO.paperFontTitle,
    leftIconContainer: { },
    rightIconContainer: { },
    leftIcon: {
        margin: 16,
    },
    rightIcon: {
        margin: 16,
    }
});

class Toolbar extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isSearchActive: props.isSearchActive,
            searchValue: ''
        };
    }
    onMenuPressed = () => {
        const { menuActions } = this.props;

        UIManager.showPopupMenu(
            findNodeHandle(this.refs.menu),
            menuActions.labels,
            () => {},
            menuActions.onPress
        );
    };
    onSearchTextChanged = (value) => {
        const { searchable } = this.props;

        if (isFunction(searchable.onChangeText)) {
            searchable.onChangeText(value);
        }

        this.setState({ searchValue: value });
    };
    onSearchPressed = () => {
        const { searchable } = this.props;

        if (isFunction(searchable.onSearchPressed)) {
            searchable.onSearchPressed();
        }

        this.setState({
            isSearchActive: true,
            searchValue: ''
        });
    };
    onSearchClosePressed = () => {
        const { searchable } = this.props;

        if (isFunction(searchable.onSearchClosed)) {
            searchable.onSearchClosed();
        }

        this.setState({
            isSearchActive: false,
            searchValue: ''
        });
    };
    getStyle = () => {
        const { style, primary, theme, translucent, iconProps } = this.props;

        let selectedTheme = {};

        if (this.state.isSearchActive || theme === 'light') {
            selectedTheme = {
                backgroundColor: '#ffffff',
                color: 'rgba(0,0,0,.87)',
                leftIconColor: 'rgba(0,0,0,.54)',
                rightIconColor: 'rgba(0,0,0,.54)'
            };
        } else {
            selectedTheme = {
                backgroundColor: getColor(primary),
                color: 'rgba(255,255,255,.87)',
                leftIconColor: 'rgba(255,255,255,.87)',
                rightIconColor: 'rgba(255,255,255,.87)'
            };
        }

        const result = {};
        let searchStyle = {};

        if (this.state.isSearchActive) {
            searchStyle = {
                toolbarContainer: { backgroundColor: getColor('paperGrey100') },
                titleText: {
                    color: 'rgba(0,0,0,.87)',
                    fontSize: 16,
                    fontWeight: 'normal',
                },
                leftIcon: { color: 'rgba(0,0,0,.54)' },
                rightIcon: { color: 'rgba(0,0,0,.54)' },
            };
        }

        result.toolbarContainer = [
            styles.toolbarContainer,
            { backgroundColor: selectedTheme.backgroundColor },
            searchStyle.toolbarContainer,
            translucent ? {
                elevation: 0,
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
            } : null,
            style.toolbarContainer,
        ];
        result.titleContainer = [
            styles.titleContainer,
            searchStyle.titleContainer,
            style.titleContainer
        ];
        result.titleText = [
            styles.titleText,
            TYPO.paperFontTitle,
            { color: selectedTheme.color },
            searchStyle.titleText,
            style.titleText
        ];
        result.leftIconContainer = [
            styles.leftIconContainer,
            searchStyle.leftIconContainer,
            style.leftIconContainer
        ];
        result.rightIconContainer = [
            styles.rightIconContainer,
            searchStyle.rightIconContainer,
            style.rightIconContainer
        ];
        result.leftIcon = [
            styles.leftIcon,
            searchStyle.leftIcon,
            style.leftIcon
        ];
        result.rightIcon = [
            styles.rightIcon,
            searchStyle.rightIcon,
            style.rightIcon
        ];
        result.iconProps = {
            size: iconProps.size,
            color: selectedTheme.leftIconColor,
        };

        return result;
    }
    focusSearchField() {
        this._searchFieldRef.focus();
    }
    renderLeftSide = (style) => {
        const { icon, onIconPress } = this.props;

        let iconName = icon;
        let onPress = onIconPress;

        if (this.state.isSearchActive) {
            iconName = 'arrow-back';
            onPress = this.onSearchClosePressed;
        }

        return (
            <View style={style.leftIconContainer}>
                <IconToggle color={style.iconProps.color} onPress={onPress}>
                    <Icon
                      name={iconName}
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.leftIcon}
                    />
                </IconToggle>
            </View>
        );
    }
    renderCenter = (style) => {
        if (!this.state.isSearchActive) {
            const { title, onTitlePress } = this.props;

            return (
                <TouchableWithoutFeedback key="center" onPress={onTitlePress}>
                    <Animated.View style={style.titleContainer}>
                        <Text numberOfLines={1} style={style.titleText}>
                            {title}
                        </Text>
                    </Animated.View>
                </TouchableWithoutFeedback>
            );
        }

        const { searchable } = this.props;

        return (
            <View style={style.titleContainer}>
                <TextInput
                  ref={(ref) => { this._searchFieldRef = ref; }}
                  autoFocus={searchable.autoFocus}
                  onChangeText={this.onSearchTextChanged}
                  onSubmitEditing={searchable.onSubmitEditing}
                  placeholder={searchable.placeholder}
                  style={style.titleText}
                  underlineColorAndroid="transparent"
                  value={this.state.searchValue}
                />
            </View>
        );
    }
    renderRightSide = (style) => {
        const { actions, menuActions, searchable } = this.props;

        let actionsMap = actions;

        if (this.state.isSearchActive) {
            actionsMap = [{
                icon: 'clear',
                onPress: () => this.onSearchTextChanged('')
            }];
        }

        let result = [];

        if (actionsMap) {
            result = actionsMap.map((action, i) => (
                <IconToggle
                  key={i}
                  color={style.iconProps.color}
                  badge={action.badge}
                  onPress={action.onPress}
                  disabled={action.disabled}
                >
                    <Icon
                      name={action.icon}
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            ));
        }

        if (searchable && !this.state.isSearchActive) {
            result.push(
                <IconToggle
                  key="searchIcon"
                  color={style.iconProps.color}
                  onPress={this.onSearchPressed}
                >
                    <Icon name="search"
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            );
        }
        if (menuActions && !this.state.isSearchActive) {
            result.push(
                <IconToggle
                  key="menuIcon"
                  color={style.iconProps.color}
                  onPress={this.onMenuPressed}
                >
                    <Icon
                      ref="menu"
                      name="more-vert"
                      size={style.iconProps.size}
                      color={style.iconProps.color}
                      style={style.rightIcon}
                    />
                </IconToggle>
            );
        }

        return (
            <View style={style.rightIconContainer}>
                {result}
            </View>
        );
    }
    render() {
        const style = this.getStyle();

        return (
            <Animated.View style={style.toolbarContainer}>
                { this.renderLeftSide(style) }
                { this.renderCenter(style) }
                { this.renderRightSide(style) }
            </Animated.View>
        );
    }

}

Toolbar.propTypes = propTypes;
Toolbar.defaultProps = defaultProps;

export default Toolbar;
<|endoftext|>


<commit_before>import airportsData from './data/airports.js';

var seeMore = 0;

function getAirportList(call) {
	var dests;
	for (var dest in call."Destinations") {
		dests.push(dest);
	}
	return dests;
}

function getChosenTheme(name) {
	for (var theme in getThemes()) {
		if (theme["Name"] == name) {
			return theme["Theme"];
		}
	}
	return null;
}

function getThemes() {
	var apiThemes;
	apiGetThemeObjects(function callback(returnedThemeObject) {
						apiThemes = returnedThemeObject["Themes"];
						});
	var themes;
	for (var theme in apiThemes) {
		themes.push(formatTheme(theme));
	}
	return themes;
}

exports.formatTheme = function(theme) {
	var name = theme["Theme"];
	theme["Name"] = name[0] + name.slice(1,name.length).toLowerCase();
	return theme;
}

function getTopDestination() {
	return seeMore * 5;
}

function seeMore() {
	if (seeMore < 10) {
		seeMore ++;
		return true;
	} else {
		return false;
	}
}

function error() {
	console.warn('It is a no work');
}

exports.attemptToLocate = function() {
	if ("geolocation" in navigator) {
		var value = null;
		var looping = true;
		navigator.geolocation
		.getCurrentPosition(function getClosestAirport(pos)
		{
			var userLat = pos.coords.latitude;
			var userLon = pos.coords.longitude;
			var aptLat, aptLon;
			var distance = 8;
			var closestAirport;
			for (var airport in airportsData) {
				if ("lat" in airport && "lon" in airport) {
					aptLat = airport.lat;
					aptLon = airport.lon;
					if (Math.abs(aptLat - userLat) < 5 && Math.abs(aptLon - userLat) < 5) {
						var testDist = getDistance(aptLat, aptLon, userLat, userLon)
						if (testDist < distance) {
							distance = testDist;
							closestAirport = airport;
						}
					}
				}
			}
			value = closestAirport;
			looping = false;
		});
		while(looping){
			sleep(1);
		}
		return value;
	}
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds){
			break;
		}
	}
}

function getDestinations() {
	var destinations;
	apiLookupDestination(getClosestAirport(),
						getChosenTheme(),
						getChosenEarliestDate(),
						getChosenMaxFare(),
						getChosenRegion(),
						getTopDestinations(),
						function callback(dests) {
							destinations = dests
						});
	return destinations,
}

function getCityCode() {
	var closestAirport = attemptToLocate();
	if (closestAirport) {
		return closestAirport.iata;
	} else {
		return null;
	}
}

exports.getDistance = function(lat1, lon1, lat2, lon2) {
	var distance = Math.sqrt(Math.pow(lat1-lat2, 2) + Math.pow(lon1-lon2,2));
	console.log(distance);
}

exports.getChosenEarliestDate = function() {

}

exports.getChosenMaxFare = function() {

}

exports.getChosenRegion = function() {

}

exports.showFirstAirport = function() {
	console.log(airportsData[0].iata);
}
<commit_msg>messages never mean anything<commit_after>import airportsData from './data/airports.js';

var seeMore = 0;
/*
exports.getAirportList = function(call) {
	var dests;
	for (var dest in call."Destinations") {
		dests.push(dest);
	}
	return dests;
}
*/

exports.getChosenTheme = function(name) {
	for (var theme in getThemes()) {
		if (theme["Name"] == name) {
			return theme["Theme"];
		}
	}
	return null;
}

exports.getThemes = function() {
	var apiThemes;
	apiGetThemeObjects(function callback(returnedThemeObject) {
						apiThemes = returnedThemeObject["Themes"];
						});
	var themes;
	for (var theme in apiThemes) {
		themes.push(formatTheme(theme));
	}
	return themes;
}

exports.formatTheme = function(theme) {
	var name = theme["Theme"];
	theme["Name"] = name[0] + name.slice(1,name.length).toLowerCase();
	return theme;
}

/*

function seeMore() {
	if (seeMore < 10) {
		seeMore ++;
		return true;
	} else {
		return false;
	}
}

function error() {
	console.warn('It is a no work');
}

*/

exports.attemptToLocate = function() {
	if ("geolocation" in navigator) {
		var value = null;
		var looping = true;
		navigator.geolocation
		.getCurrentPosition(function getClosestAirport(pos)
		{
			userCoords = pos.coords;
			apiGetAirportsNearest(userCoords.latitude, userCoords.longitude, 5, function callback(airports){
				value = airports["airports"];
			})
			looping = false;
		});
		while(looping){
			sleep(1);
		}
		return value;
	}
}

exports.formatAirports = function(airports) {
	for (var airport in airports) {
		airport["Display"] = airport["city"] + " (" + airport["code"] + ")";
	}
}

exports.sleep = function(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds){
			break;
		}
	}
}

exports.getDestinations = function(closestAirport, chosenTheme, chosenLengthOfStay, chosenMaxFare) {
	var destinations;
	apiLookupDestination(closestAirport(),
						chosenTheme(),
						chosenLengthOfStay(),
						null,
						chosenMaxFare(),
						null,
						null,
						function callback(dests) {
							destinations = dests["FareInfo"];
						});
	return destinations;
}

export.getFormattedDestinations = function(closestAirport, chosenTheme, chosenLengthOfStay chosenMaxFare) {
	var unfDests = getDestinations(closestAirport, chosenTheme, chosenLengthOfStay chosenMaxFare);
	var fDests = new Array();
	for (var unfDest in unfDests) {
		fDests.push(function(){
			this["Code"] = unfDest["DestinationLocation"];
			this["Name"];
			this["Fare"] = unfDest["LowestFare"];
			var depdate = unfDest["DepartureDateTime"];
			this["DepartureDate"] = depdate.slice(0,4) + "/" + depdate.slice(4,6) + "/" + depdate.slice(6,8);
			var retdate = unfDest["ReturnDateTime"];
			this["ReturnDate"] = retdate.slice(0,4) + "/" + retdate.slice(4,6) + "/" + retdate.slice(6,8);
		})
	}
}

exports.getCityCode = function() {
	var closestAirport = attemptToLocate();
	if (closestAirport) {
		return closestAirport.iata;
	} else {
		return null;
	}
}

/*
exports.getDistance = function(lat1, lon1, lat2, lon2) {
	var distance = Math.sqrt(Math.pow(lat1-lat2, 2) + Math.pow(lon1-lon2,2));
	console.log(distance);
}
*/

/*
exports.showFirstAirport = function() {
	console.log(airportsData[0].iata);
}
*/
<|endoftext|>


<commit_before>'use strict';

var alerta = alerta || {};

alerta.loadAuth = function() {

angular.module('alerta')

.config(['$httpProvider',
  function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q, $location) {
        return {
            'response': function (response) {
                //Will only be called for HTTP up to 300
                return response;
            },
            'responseError': function (rejection) {
                if(rejection.status === 401) {
                    $location.path('/login');
                }
                return $q.reject(rejection);
            }
        };
    });
}])

.config(['configProvider', '$authProvider',
  function (configProvider, $authProvider) {
    var config = configProvider.getConfig();

    $authProvider.loginUrl = config.endpoint+'/auth/login';
    $authProvider.signupUrl = config.endpoint+'/auth/signup';
    $authProvider.logoutRedirect = '/login';
    $authProvider.google({
      url: config.endpoint+'/auth/google',
      clientId: config.client_id
    });
    $authProvider.github({
      url: config.endpoint+'/auth/github',
      clientId: config.client_id,
      scope: ['user:email', 'read:org'],
      authorizationEndpoint: (config.github_url || 'https://github.com')+'/login/oauth/authorize'
    });
    $authProvider.oauth2({
      name: 'gitlab',
      url: config.endpoint+'/auth/gitlab',
      redirectUri: window.location.origin,
      clientId: config.client_id,
      authorizationEndpoint: config.gitlab_url+'/oauth/authorize'
    });
    $authProvider.oauth2({
      name: 'keycloak',
      url: config.endpoint+'/auth/keycloak',
      redirectUri: window.location.origin,
      clientId: config.client_id,
      authorizationEndpoint: config.keycloak_url+'/auth/realms/'+config.keycloak_realm+'/protocol/openid-connect/auth'
    });
    $authProvider.oauth2({
      name: 'pingfederate',
      url: config.endpoint+'/auth/pingfederate',
      redirectUri: window.location.origin+'/',
      clientId: config.client_id,
      authorizationEndpoint: config.pingfederate_url,
      requiredUrlParams: ['pfidpadapterid', 'scope'],
      scope: 'openid+profile+email',
      pfidpadapterid: 'kerberos'
    });
}]);

};
<commit_msg>GitLab OAuth only needs openid scope (#149)<commit_after>'use strict';

var alerta = alerta || {};

alerta.loadAuth = function() {

angular.module('alerta')

.config(['$httpProvider',
  function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q, $location) {
        return {
            'response': function (response) {
                //Will only be called for HTTP up to 300
                return response;
            },
            'responseError': function (rejection) {
                if(rejection.status === 401) {
                    $location.path('/login');
                }
                return $q.reject(rejection);
            }
        };
    });
}])

.config(['configProvider', '$authProvider',
  function (configProvider, $authProvider) {
    var config = configProvider.getConfig();

    $authProvider.loginUrl = config.endpoint+'/auth/login';
    $authProvider.signupUrl = config.endpoint+'/auth/signup';
    $authProvider.logoutRedirect = '/login';
    $authProvider.google({
      url: config.endpoint+'/auth/google',
      clientId: config.client_id
    });
    $authProvider.github({
      url: config.endpoint+'/auth/github',
      clientId: config.client_id,
      scope: ['user:email', 'read:org'],
      authorizationEndpoint: (config.github_url || 'https://github.com')+'/login/oauth/authorize'
    });
    $authProvider.oauth2({
      name: 'gitlab',
      url: config.endpoint+'/auth/gitlab',
      redirectUri: window.location.origin,
      clientId: config.client_id,
      requiredUrlParams: ['scope'],
      scope: 'openid',
      authorizationEndpoint: config.gitlab_url+'/oauth/authorize'
    });
    $authProvider.oauth2({
      name: 'keycloak',
      url: config.endpoint+'/auth/keycloak',
      redirectUri: window.location.origin,
      clientId: config.client_id,
      authorizationEndpoint: config.keycloak_url+'/auth/realms/'+config.keycloak_realm+'/protocol/openid-connect/auth'
    });
    $authProvider.oauth2({
      name: 'pingfederate',
      url: config.endpoint+'/auth/pingfederate',
      redirectUri: window.location.origin+'/',
      clientId: config.client_id,
      authorizationEndpoint: config.pingfederate_url,
      requiredUrlParams: ['pfidpadapterid', 'scope'],
      scope: 'openid+profile+email',
      pfidpadapterid: 'kerberos'
    });
}]);

};
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            portions copyright @2009 Apple Inc.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */

var pane, view , view2;
var appleURL='http://photos4.meetupstatic.com/photos/event/4/6/9/9/600_4518073.jpeg';
module("SC.ScrollView",{
	setup: function() {
	  SC.RunLoop.begin();
	    pane = SC.MainPane.create({
		  childViews: [
		   SC.ScrollView.extend({
		     contentView: SC.ImageView.design({value: appleURL, layout: {height:4000, width:4000}})
		   }),
		   SC.ScrollView.extend({
		     contentView: SC.ImageView.design({value: appleURL, layout: {height:2000, width:2000}})
		   })

		   ],

		  expectedVertLine: function(line) {
			var ret = view.get('verticalLineScroll')*line;
			var alt = view.get('maximumVerticalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedHorzLine: function(line) {
			var ret = view.get('horizontalLineScroll')*line;
			var alt = view.get('maximumHorizontalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedVertPage: function(page) {
			var ret = view.get('verticalPageScroll')*page;
			var alt = view.get('maximumVerticalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedHorzPage: function(page) {
			var ret = view.get('horizontalPageScroll')*page;
			var alt = view.get('maximumHorizontalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  }
		});

		pane.append(); // make sure there is a layer...
	  SC.RunLoop.end();
	  view = pane.childViews[0];
	  view.get('containerView').get('frame').height = 100;
	  view.get('containerView').get('frame').width = 100;

	  view2 = pane.childViews[1];
	  view2.get('containerView').get('frame').height = 100;
	  view2.get('containerView').get('frame').width = 100;

	},

	teardown: function() {
    	pane.remove();
    	pane = view = null ;
  	}
});

test("Scrolling to a certain co-ordinate of the container view", function() {
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	SC.RunLoop.begin();
	view.scrollTo(100, 100);
	SC.RunLoop.end();

	equals(view.get('horizontalScrollOffset'), 100, "After scrolling to 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 100, "After scrolling to 100, vertical offset must be");
	view.scrollTo(5000, 5000);
	equals(view.get('horizontalScrollOffset'), view.get('maximumHorizontalScrollOffset'), "After scrolling to 400, horizontal offset must be maximum");
	equals(view.get('verticalScrollOffset'), view.get('maximumVerticalScrollOffset'), "After scrolling to 400, vertical offset must be maximum");
});

test("Scrolling relative to the current possition of the container view", function() {
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	view.scrollBy(100, 100);
	equals(view.get('horizontalScrollOffset'), 100, "After scrolling by 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 100, "After scrolling by 100, vertical offset must be");
	view.scrollBy(100, 100);
	equals(view.get('horizontalScrollOffset'), 200, "After scrolling by 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 200, "After scrolling by 100, vertical offset must be");
	view.scrollBy(5000, 5000);
	equals(view.get('horizontalScrollOffset'), view.get('maximumHorizontalScrollOffset'), "After scrolling by 400, horizontal offset must be maximum");
	equals(view.get('verticalScrollOffset'), view.get('maximumVerticalScrollOffset'), "After scrolling by 400, vertical offset must be maximum");
});

test("Scrolling through line by line", function() {
	var line = 3;
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	view.scrollDownLine(line);
	equals(view.get('horizontalScrollOffset'), 0, "After scrolling down by lines, horizontal offset is unchanged");
	equals(view.get('verticalScrollOffset'), pane.expectedVertLine(line), "After scrolling down by lines, vertical offset must be");
	view.scrollUpLine(line);
});

test("maximumHorizontalScrollOffset() returns the maximum horizontal scroll dimention", function() {
  var old_horizontalScrollOffset=2;
  var old_verticalScrollOffset=2;

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollRightPage(3);
  equals(view2.get('horizontalScrollOffset'),1900, 'maximum y coordinate should be 1900');

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollLeftPage(3);
  equals(view2.get('horizontalScrollOffset'),0, 'minimum y coordinate should be 0');

});

test("maximumVerticalScrollOffset() returns the maximum vertical scroll dimention", function() {
  var old_horizontalScrollOffset=2;
  var old_verticalScrollOffset=2;

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollDownPage(3);
  equals(view2.get('verticalScrollOffset'),1900, 'maximum coordinate should be 1900');

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollUpPage(3);
  equals(view2.get('verticalScrollOffset'),0, 'The minimum y coordinate should be 0');

});<commit_msg><rdar://problem/7042045> Decouple SC.ScrollView's unit tests from the size of the browser window.<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            portions copyright @2009 Apple Inc.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */

var pane, view , view2;
var appleURL='http://photos4.meetupstatic.com/photos/event/4/6/9/9/600_4518073.jpeg';
module("SC.ScrollView",{
	setup: function() {
	  SC.RunLoop.begin();
	    pane = SC.MainPane.create({
		  childViews: [
		   SC.ScrollView.extend({
		     contentView: SC.ImageView.design({value: appleURL, layout: {height:4000, width:4000}})
		   }),
		   SC.ScrollView.extend({
		     contentView: SC.ImageView.design({value: appleURL, layout: {height:2000, width:2000}})
		   })

		   ],

		  expectedVertLine: function(line) {
			var ret = view.get('verticalLineScroll')*line;
			var alt = view.get('maximumVerticalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedHorzLine: function(line) {
			var ret = view.get('horizontalLineScroll')*line;
			var alt = view.get('maximumHorizontalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedVertPage: function(page) {
			var ret = view.get('verticalPageScroll')*page;
			var alt = view.get('maximumVerticalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  },
		  expectedHorzPage: function(page) {
			var ret = view.get('horizontalPageScroll')*page;
			var alt = view.get('maximumHorizontalScrollOffset');
			ret = (ret > alt)? alt : ret;
		    return ret;
		  }
		});

		pane.append(); // make sure there is a layer...
	  SC.RunLoop.end();
	  view = pane.childViews[0];
	  view.get('containerView').get('frame').height = 100;
	  view.get('containerView').get('frame').width = 100;

	  view2 = pane.childViews[1];
	  view2.get('containerView').get('frame').height = 100;
	  view2.get('containerView').get('frame').width = 100;

	},

	teardown: function() {
    	pane.remove();
    	pane = view = null ;
  	}
});

test("Scrolling to a certain co-ordinate of the container view", function() {
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	SC.RunLoop.begin();
	view.scrollTo(100, 100);
	SC.RunLoop.end();

	equals(view.get('horizontalScrollOffset'), 100, "After scrolling to 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 100, "After scrolling to 100, vertical offset must be");
	view.scrollTo(5000, 5000);
	equals(view.get('horizontalScrollOffset'), view.get('maximumHorizontalScrollOffset'), "After scrolling to 400, horizontal offset must be maximum");
	equals(view.get('verticalScrollOffset'), view.get('maximumVerticalScrollOffset'), "After scrolling to 400, vertical offset must be maximum");
});

test("Scrolling relative to the current possition of the container view", function() {
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	view.scrollBy(100, 100);
	equals(view.get('horizontalScrollOffset'), 100, "After scrolling by 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 100, "After scrolling by 100, vertical offset must be");
	view.scrollBy(100, 100);
	equals(view.get('horizontalScrollOffset'), 200, "After scrolling by 100, horizontal offset must be");
	equals(view.get('verticalScrollOffset'), 200, "After scrolling by 100, vertical offset must be");
	view.scrollBy(5000, 5000);
	equals(view.get('horizontalScrollOffset'), view.get('maximumHorizontalScrollOffset'), "After scrolling by 400, horizontal offset must be maximum");
	equals(view.get('verticalScrollOffset'), view.get('maximumVerticalScrollOffset'), "After scrolling by 400, vertical offset must be maximum");
});

test("Scrolling through line by line", function() {
	var line = 3;
	equals(view.get('horizontalScrollOffset'), 0, "Initial horizontal offset must be zero");
	equals(view.get('verticalScrollOffset'), 0, "Initial vertical offset must be zero");
	view.scrollDownLine(line);
	equals(view.get('horizontalScrollOffset'), 0, "After scrolling down by lines, horizontal offset is unchanged");
	equals(view.get('verticalScrollOffset'), pane.expectedVertLine(line), "After scrolling down by lines, vertical offset must be");
	view.scrollUpLine(line);
});

test("maximumHorizontalScrollOffset() returns the maximum horizontal scroll dimention", function() {
  var old_horizontalScrollOffset=2;
  var old_verticalScrollOffset=2;

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollBy(5000, 0);
  view2.get('horizontalScrollOffset');

  equals(view2.get('horizontalScrollOffset'),1900, 'maximum y coordinate should be 1900');

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollBy(-5000,0);
  equals(view2.get('horizontalScrollOffset'),0, 'minimum y coordinate should be 0');

});

test("maximumVerticalScrollOffset() returns the maximum vertical scroll dimention", function() {
  var old_horizontalScrollOffset=2;
  var old_verticalScrollOffset=2;

  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollBy(0, 5000);
  view2.get('maximumVerticalScrollOffset');
  equals(view2.get('verticalScrollOffset'),1900, 'maximum coordinate should be 1900');
  view2.set('horizontalScrollOffset',old_horizontalScrollOffset);
  view2.set('verticalScrollOffset',old_verticalScrollOffset);
  view2.scrollBy(0,-5000);
  equals(view2.get('verticalScrollOffset'),0, 'The minimum y coordinate should be 0');

});<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.map', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/map', {
    templateUrl: 'map/map.html',
    controller: 'MapPageCtrl'
  });
}])

.controller('MapPageCtrl', ['$scope', function($scope) {

	$scope.mode = 'initial';
	$scope.currentPosition = false;

	$scope.currentTagging = false;

	$scope.watchId = false;

	$scope.startTrackingLocation = function () {
        if (navigator.geolocation) {
            $scope.watchId = navigator.geolocation.getCurrentPosition($scope.gotPosition);
        }
        else {
            alert('No geolocation');
        }
    }

    $scope.stopTrackingLocation = function() {
        if (navigator.geolocation && $scope.watchId !== false) {
        	navigator.geolocation.clearWatch($scope.watchId);
        	$scope.watchId = false;
        }
    }

    $scope.gotoMode = function(mode){
    	$scope.mode = mode;

    	if($scope.mode == 'tagging'){
    		console.log('Tagging mode');
    		$scope.hideBottomContent();
    		$scope.showActionsBar();

    	}else if($scope.mode == 'tag-detail'){
    		console.log('tag-detail mode');
    		$scope.showBottomContent();
			$scope.hideActionsBar();

    	}else if($scope.mode == 'begin-run'){
    		console.log('begin-run mode');
    		$scope.showBottomContent();
    		$scope.hideActionsBar();

    	}else if($scope.mode == 'during-run'){
    		console.log('during-run mode');
    		$scope.hideActionsBar();

    	}else if($scope.mode == 'after-run'){
    		console.log('after-run mode');
    		$scope.hideActionsBar();

    	}else if($scope.mode == 'initial'){
    		console.log('initial mode');
    		$scope.hideBottomContent();
    		$scope.hideActionsBar();

    	}

    	$scope.$broadcast ('mode-change', mode);

    }

	$scope.showActionsBar = function(){
		$('#map-page').addClass('show-actions');

	}

	$scope.hideActionsBar = function(){
		$('#map-page').removeClass('show-actions');

	}

	$scope.showBottomContent = function(){
		//Scroll to top
		//Disable scroll
		//Expand map
		//Show bottom bar
		$('#map-page').addClass('small');
		setTimeout(function(){
			window.dispatchEvent(new Event('resize'));
		}, 1000);
	}

	$scope.hideBottomContent = function(){
		//Scroll to top
		//Disable scroll
		//Expand map
		//Show bottom bar
		$('#map-page').removeClass('small');
		setTimeout(function(){
			window.dispatchEvent(new Event('resize'));
		}, 1000);

	}

	$scope.showError = function(){
		alert('An error happened');
	}

	$scope.gotPosition = function(position){
		$scope.currentPosition = position;
		$scope.$broadcast ('receivedUpdateLocation');
	}

    $scope.startTrackingLocation();

}])

.controller('TopNavController', ['$scope', function($scope) {

	$scope.currentActions = [];

	var startRunAction = {
		'label': 'Deliver',
		'toRun': function(){
			$scope.gotoMode('begin-run');
		}
	}

	var tagAction = {
		'label': 'Spot',
		'toRun': function(){
			$scope.gotoMode('tag-detail');
		}
	}

	var cancelAction = {
		'label': 'Cancel',
		'toRun': function(){
			$scope.gotoMode('initial');
		}
	}

	$scope.currentActions.push(startRunAction);
	$scope.currentActions.push(tagAction);

	$scope.$on('mode-change', function(e, newMode) {
        //Update the bottom form
        if(newMode == 'tagging'){
        	$scope.currentActions = [cancelAction];
        }else if(newMode == 'tag-detail'){
        	$scope.currentActions = [cancelAction];
        }else if(newMode == 'begin-run'){
        	$scope.currentActions = [cancelAction];
        }else if(newMode == 'during-run'){
        	$scope.currentActions = [cancelAction];
        }else if(newMode == 'after-run'){
        	$scope.currentActions = [cancelAction];
        }else if(newMode == 'initial'){
        	$scope.currentActions = [startRunAction,tagAction];
        }
    });

}])

.controller('ContentBelowController', ['$scope', function($scope) {

	$scope.currentContent = '';

	$scope.gotoTagForm = function(){
		$scope.currentContent = 'views/tagdetails.html';
	}

	$scope.gotoStartRunForm = function(){
		$scope.currentContent = 'views/startrun.html';
	}

	$scope.gotoDuringRunForm = function(){

	}

	$scope.gotoEndRunDetails = function(){

	}

	$scope.clear = function(){

	}

	$scope.$on('mode-change', function(e, newMode) {
        //Update the bottom form
        if(newMode == 'tagging'){
        	$scope.clear();
        }else if(newMode == 'tag-detail'){
        	$scope.gotoTagForm();
        }else if(newMode == 'begin-run'){
        	$scope.gotoStartRunForm();
        }else if(newMode == 'during-run'){
        	$scope.gotoDuringRunForm();
        }else if(newMode == 'after-run'){
        	$scope.gotoEndRunDetails();
        }else if(newMode == 'initial'){
        	$scope.clear();
        }
    });

}])

.controller('BottomActionsController', ['$scope', 'MapCenterService', 'TaggingService', function($scope, mapCenterService, taggingService) {

	$scope.currentActions = [];

	/*$scope.currentActions.push({
		'label': 'Tag',
		'toRun': function(){
			console.log('we are tagging a position');
			var center = mapCenterService.getCenter();
			taggingService.setPosition(center);
			$scope.gotoMode('tag-detail');
		}
	});*/

}])

.controller('MapController', ['$scope', '$http', 'MapCenterService', 'GlobalData',
	function($scope, $http, mapCenterService, globalData) {

	//Initialise
	//Create map
	//Get reference
	//Setup functions to interact with map

	$scope.displayedTags = [];
	$scope.renderedTags = [];

	// Watch for changes on globalData.tags.
	$scope.$watchCollection(function(){
		return globalData.tags;
	}, function(newArr, oldArr) {
		$scope.updateMapWithTags();
	});

	$scope.showCrosshair = false;

	$scope.map = false;
	$scope.isTrackingLocation = true;

	$scope.$on('receivedUpdateLocation', function(e) {
        console.log('Map received updated position');
		if($scope.isTrackingLocation){
			//Re-center map on current location
			$scope.map.panTo(new google.maps.LatLng($scope.currentPosition.coords.latitude, $scope.currentPosition.coords.longitude));
			$scope.map.setZoom(16);
		}
    });

	$scope.initMap = function(){

		$scope.map = new google.maps.Map(document.getElementById('mapFinalContainer'), {
			center: {lat: 0, lng: 0},
			zoom: 16
		});
		mapCenterService.setMap($scope.map);

	}

	$scope.destroyMap = function(){

	}

	$scope.updateMapWithTags = function(){
		for(var i = 0; i < globalData.tags.length; i++){
	    	var tag = globalData.tags[i];
	    	var newMarker = new google.maps.Marker({
		    	position: new google.maps.LatLng(tag.position.lat, tag.position.lng),
		    	map: $scope.map,
		    	title: 'TAG'
			});
			tag.marker = newMarker;
			newMarker.tag = tag;
	    	$scope.displayedTags.push(tag);
	    	$scope.renderedTags.push(newMarker);
	    }
	}

	$scope.startTrackingUserLocation = function(){
		$scope.isTrackingLocation = true;
	}

	$scope.stopTrackingUserLocation = function(){
		$scope.isTrackingLocation = false;
	}

	$scope.pullTagsFromServer = function(){

		//Clean up
		$scope.displayedTags = [];
		for(var i = 0; i < $scope.renderedTags; i++){
			$scope.renderedTags[i].setMap(null);
		}

		$http({
		  	method: 'GET',
		  	url: 'http://roughly-api.herokuapp.com/tag'
		}).then(function successCallback(response) {
		    console.log(response.data._embedded.tag);

		    $scope.tags = response.data._embedded.tag;
		    $scope.updateMapWithTags();
		}, function errorCallback(response) {

		});
	}

	$scope.initMap();
	$scope.pullTagsFromServer();

	$scope.$on('mode-change', function(e, newMode) {
        //Update the bottom form
        if(newMode == 'tagging'){
        	$scope.stopTrackingUserLocation();
			$scope.showCrosshair = true;
        }else if(newMode == 'tag-detail'){
        	$scope.stopTrackingUserLocation();
        	$scope.showCrosshair = true;
        }else if(newMode == 'begin-run'){
        	$scope.stopTrackingUserLocation();
        	$scope.showCrosshair = false;
        }else if(newMode == 'during-run'){
        	$scope.startTrackingUserLocation();
        	$scope.showCrosshair = false;
        }else if(newMode == 'after-run'){
        	$scope.stopTrackingUserLocation();
        	$scope.showCrosshair = false;
        }else if(newMode == 'initial'){
        	$scope.startTrackingUserLocation();
        	$scope.showCrosshair = false;
        }
    });

}])

.controller('TagDetailsForm', ['$scope', '$http', 'TaggingService', 'MapCenterService', 'GlobalData',
	function($scope, $http, taggingService, mapCenterService, globalData) {

	$scope.numPeople = 0;
	$scope.numDogs = 0;
	$scope.selectedType = '1';
	$scope.needs = [];
	$scope.items = globalData.items;
	$scope.tagTypes = globalData.tagTypes;

	$scope.addNeed = function(){
		var newNeed = {
			needType: "1",
			needQuantity: 1,
		}

		$scope.needs.push(newNeed);
	}

	$scope.removeNeed = function(need){
		$scope.needs = $scope.needs.filter(function (el) {
            return el !== need;
        });
	}

	$scope.submitTag = function(){

		//make lat lng object
		var position = {
			lat: mapCenterService.getCenter().lat(),
			lng: mapCenterService.getCenter().lng()
		}

		var needs = [];
		for(var i = 0; i < $scope.needs.length; i++){
			for(var j = 0; j < $scope.needs[i].needQuantity; j++){
				var need = {
					item: 'item/'+$scope.needs[i].needType
				}
				needs.push(need);
			}
		}

		//Send tag to servers
		var tagToAdd = {
			position: position,
			numberOfPeople: $scope.numPeople,
			numberOfDogs: $scope.numDogs,
			tagType: '/tagtype/'+$scope.selectedType,
			needs: needs
		};

		$http({
			headers: {'Content-Type': 'application/json'},
		  	method: 'POST',
		  	url: 'http://roughly-api.herokuapp.com/tag',
		  	data: tagToAdd

		}).then(function successCallback(response) {

			//We are happy, go back to initial mode
			$scope.gotoMode('initial');
			globalData.tags.push(tagToAdd);

		}, function errorCallback(response) {

		});

	}

}])

.service('MapCenterService', function() {
  var self = this;
  self.currentMap = false;

  self.setMap = function(map){
	self.currentMap = map;
  }

  self.getCenter = function(){
  	if(self.currentMap == false){
  		return false;
  	}
  	return self.currentMap.getCenter();
  }

})

.service('TaggingService', function() {
  	var self = this;
  	self.currentPosition = false;
	self.currentInfo = {};

	self.setPosition = function(position){
		self.currentPosition = position;
	}

	self.setData = function(data){
		self.currentInfo = data;
	}

 	self.submit = function(){
 		//Submit the current tag to the server
 		//Reject if data not complete
 	}

})

.service('GlobalData', function($http){
	var self = this;
	self.items = [];
	self.tagTypes = [];
	self.tags = [];

	// Load in items
	$http({
	  	method: 'GET',
	  	url: 'http://roughly-api.herokuapp.com/item'
	}).then(function successCallback(response) {
	    console.log(response.data._embedded.item);

	    self.items = response.data._embedded.item;
	}, function errorCallback(response) {

	});

	// And tag types.
	$http({
	  	method: 'GET',
	  	url: 'http://roughly-api.herokuapp.com/tagtype'
	}).then(function successCallback(response) {
	    console.log(response.data._embedded.tagtype);

	    self.tagTypes = response.data._embedded.tagtype;
	}, function errorCallback(response) {

	});

	// Also tags.
	$http({
	  	method: 'GET',
	  	url: 'http://roughly-api.herokuapp.com/tag'
	}).then(function successCallback(response) {
	    console.log(response.data._embedded.tag);

	    self.tags = response.data._embedded.tag;
	}, function errorCallback(response) {

	});

});
<commit_msg>Added directions to all waypoints<commit_after>'use strict';

angular.module('myApp.map', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/map', {
		templateUrl: 'map/map.html',
		controller: 'MapPageCtrl'
	});
}])

.controller('MapPageCtrl', ['$scope', function($scope) {

	$scope.mode = 'initial';
	$scope.currentPosition = false;

	$scope.currentTagging = false;

	$scope.watchId = false;

	$scope.startTrackingLocation = function () {
		if (navigator.geolocation) {
			$scope.watchId = navigator.geolocation.getCurrentPosition($scope.gotPosition);
		}
		else {
			alert('No geolocation');
		}
	}

	$scope.stopTrackingLocation = function() {
		if (navigator.geolocation && $scope.watchId !== false) {
			navigator.geolocation.clearWatch($scope.watchId);
			$scope.watchId = false;
		}
	}

	$scope.gotoMode = function(mode){
		$scope.mode = mode;

		if($scope.mode == 'tagging'){
			console.log('Tagging mode');
			$scope.hideBottomContent();
			$scope.showActionsBar();

		}else if($scope.mode == 'tag-detail'){
			console.log('tag-detail mode');
			$scope.showBottomContent();
			$scope.hideActionsBar();

		}else if($scope.mode == 'begin-run'){
			console.log('begin-run mode');
			$scope.showBottomContent();
			$scope.hideActionsBar();

		}else if($scope.mode == 'during-run'){
			console.log('during-run mode');
			$scope.hideActionsBar();

		}else if($scope.mode == 'after-run'){
			console.log('after-run mode');
			$scope.hideActionsBar();

		}else if($scope.mode == 'initial'){
			console.log('initial mode');
			$scope.hideBottomContent();
			$scope.hideActionsBar();

		}

		$scope.$broadcast ('mode-change', mode);

	}

	$scope.showActionsBar = function(){
		$('#map-page').addClass('show-actions');

	}

	$scope.hideActionsBar = function(){
		$('#map-page').removeClass('show-actions');

	}

	$scope.showBottomContent = function(){
		//Scroll to top
		//Disable scroll
		//Expand map
		//Show bottom bar
		$('#map-page').addClass('small');
		setTimeout(function(){
			window.dispatchEvent(new Event('resize'));
		}, 1000);
	}

	$scope.hideBottomContent = function(){
		//Scroll to top
		//Disable scroll
		//Expand map
		//Show bottom bar
		$('#map-page').removeClass('small');
		setTimeout(function(){
			window.dispatchEvent(new Event('resize'));
		}, 1000);

	}

	$scope.showError = function(){
		alert('An error happened');
	}

	$scope.gotPosition = function(position){
		$scope.currentPosition = position;
		$scope.$broadcast ('receivedUpdateLocation');
	}

	$scope.startTrackingLocation();

}])

.controller('TopNavController', ['$scope', function($scope) {

	$scope.currentActions = [];

	var startRunAction = {
		'label': 'Deliver',
		'toRun': function(){
			$scope.gotoMode('begin-run');
		}
	}

	var tagAction = {
		'label': 'Spot',
		'toRun': function(){
			$scope.gotoMode('tag-detail');
		}
	}

	var cancelAction = {
		'label': 'Cancel',
		'toRun': function(){
			$scope.gotoMode('initial');
		}
	}

	$scope.currentActions.push(startRunAction);
	$scope.currentActions.push(tagAction);

	$scope.$on('mode-change', function(e, newMode) {
		//Update the bottom form
		if(newMode == 'tagging'){
			$scope.currentActions = [cancelAction];
		}else if(newMode == 'tag-detail'){
			$scope.currentActions = [cancelAction];
		}else if(newMode == 'begin-run'){
			$scope.currentActions = [cancelAction];
		}else if(newMode == 'during-run'){
			$scope.currentActions = [cancelAction];
		}else if(newMode == 'after-run'){
			$scope.currentActions = [cancelAction];
		}else if(newMode == 'initial'){
			$scope.currentActions = [startRunAction,tagAction];
		}
	});

}])

.controller('ContentBelowController', ['$scope', function($scope) {

	$scope.currentContent = '';

	$scope.gotoTagForm = function(){
		$scope.currentContent = 'views/tagdetails.html';
	}

	$scope.gotoStartRunForm = function(){
		$scope.currentContent = 'views/startrun.html';
	}

	$scope.gotoDuringRunForm = function(){

	}

	$scope.gotoEndRunDetails = function(){

	}

	$scope.clear = function(){

	}

	$scope.$on('mode-change', function(e, newMode) {
		//Update the bottom form
		if(newMode == 'tagging'){
			$scope.clear();
		}else if(newMode == 'tag-detail'){
			$scope.gotoTagForm();
		}else if(newMode == 'begin-run'){
			$scope.gotoStartRunForm();
		}else if(newMode == 'during-run'){
			$scope.gotoDuringRunForm();
		}else if(newMode == 'after-run'){
			$scope.gotoEndRunDetails();
		}else if(newMode == 'initial'){
			$scope.clear();
		}
	});

}])

.controller('BottomActionsController', ['$scope', 'MapCenterService', 'TaggingService', function($scope, mapCenterService, taggingService) {

	$scope.currentActions = [];

	/*$scope.currentActions.push({
		'label': 'Tag',
		'toRun': function(){
			console.log('we are tagging a position');
			var center = mapCenterService.getCenter();
			taggingService.setPosition(center);
			$scope.gotoMode('tag-detail');
		}
	});*/

}])

.controller('MapController', ['$scope', '$http', 'MapCenterService', 'GlobalData',
	function($scope, $http, mapCenterService, globalData) {

	//Initialise
	//Create map
	//Get reference
	//Setup functions to interact with map

	$scope.displayedTags = [];
	$scope.renderedTags = [];

	// Watch for changes on globalData.tags.
	$scope.$watchCollection(function(){
		return globalData.tags;
	}, function(newArr, oldArr) {
		$scope.updateMapWithTags();
	});

	$scope.showCrosshair = false;

	$scope.map = false;
	$scope.isTrackingLocation = true;

	$scope.$on('receivedUpdateLocation', function(e) {
		console.log('Map received updated position');
		if($scope.isTrackingLocation){
			//Re-center map on current location
			$scope.map.panTo(new google.maps.LatLng($scope.currentPosition.coords.latitude, $scope.currentPosition.coords.longitude));
			$scope.map.setZoom(16);
		}
	});

	$scope.initMap = function(){

		$scope.map = new google.maps.Map(document.getElementById('mapFinalContainer'), {
			center: {lat: 0, lng: 0},
			zoom: 16
		});

		mapCenterService.setMap($scope.map);

	}

	$scope.destroyMap = function(){

	}

	$scope.updateMapWithTags = function(){
		for(var i = 0; i < globalData.tags.length; i++){
			var tag = globalData.tags[i];
			var newMarker = new google.maps.Marker({
				position: new google.maps.LatLng(tag.position.lat, tag.position.lng),
				map: $scope.map,
				title: 'TAG'
			});
			tag.marker = newMarker;
			newMarker.tag = tag;
			$scope.displayedTags.push(tag);
			$scope.renderedTags.push(newMarker);
		}
	}

	$scope.startTrackingUserLocation = function(){
		$scope.isTrackingLocation = true;
	}

	$scope.stopTrackingUserLocation = function(){
		$scope.isTrackingLocation = false;
	}

	$scope.pullTagsFromServer = function(){

		//Clean up
		$scope.displayedTags = [];
		for(var i = 0; i < $scope.renderedTags; i++){
			$scope.renderedTags[i].setMap(null);
		}

		$http({
			method: 'GET',
			url: 'http://roughly-api.herokuapp.com/tag'
		}).then(function successCallback(response) {
			console.log(response.data._embedded.tag);

			$scope.tags = response.data._embedded.tag;
			$scope.updateMapWithTags();
		}, function errorCallback(response) {

		});
	}

	$scope.initMap();
	$scope.pullTagsFromServer();

	$scope.$on('mode-change', function(e, newMode) {
		//Update the bottom form
		if(newMode == 'tagging'){
			$scope.stopTrackingUserLocation();
			$scope.showCrosshair = true;
		}else if(newMode == 'tag-detail'){
			$scope.stopTrackingUserLocation();
			$scope.showCrosshair = true;
		}else if(newMode == 'begin-run'){
			$scope.stopTrackingUserLocation();
			$scope.showCrosshair = false;
		}else if(newMode == 'during-run'){
			$scope.startTrackingUserLocation();
			$scope.showCrosshair = false;
		}else if(newMode == 'after-run'){
			$scope.stopTrackingUserLocation();
			$scope.showCrosshair = false;
		}else if(newMode == 'initial'){
			$scope.startTrackingUserLocation();
			$scope.showCrosshair = false;
		}
	});

}])

.controller('TagDetailsForm', ['$scope', '$http', 'TaggingService', 'MapCenterService', 'GlobalData',
	function($scope, $http, taggingService, mapCenterService, globalData) {

		$scope.numPeople = 0;
		$scope.numDogs = 0;
		$scope.selectedType = '1';
		$scope.needs = [];
		$scope.items = globalData.items;
		$scope.tagTypes = globalData.tagTypes;

		$scope.addNeed = function(){
			var newNeed = {
				needType: "1",
				needQuantity: 1,
			}

			$scope.needs.push(newNeed);
		}

		$scope.removeNeed = function(need){
			$scope.needs = $scope.needs.filter(function (el) {
				return el !== need;
			});
		}

		$scope.submitTag = function(){

		//make lat lng object
		var position = {
			lat: mapCenterService.getCenter().lat(),
			lng: mapCenterService.getCenter().lng()
		}

		var needs = [];
		for(var i = 0; i < $scope.needs.length; i++){
			for(var j = 0; j < $scope.needs[i].needQuantity; j++){
				var need = {
					item: 'item/'+$scope.needs[i].needType
				}
				needs.push(need);
			}
		}

		//Send tag to servers
		var tagToAdd = {
			position: position,
			numberOfPeople: $scope.numPeople,
			numberOfDogs: $scope.numDogs,
			tagType: '/tagtype/'+$scope.selectedType,
			needs: needs
		};

		$http({
			headers: {'Content-Type': 'application/json'},
			method: 'POST',
			url: 'http://roughly-api.herokuapp.com/tag',
			data: tagToAdd

		}).then(function successCallback(response) {

			//We are happy, go back to initial mode
			$scope.gotoMode('initial');
			globalData.tags.push(tagToAdd);

		}, function errorCallback(response) {

		});

	}

}])

.service('MapCenterService', ['GlobalData', function(globalData) {
	var self = this;
	self.currentMap = false;
	self.directions = false;

	self.setMap = function(map){
		self.currentMap = map;
		self.directions = new google.maps.DirectionsRenderer;
		self.directions.setMap(map);
	}

	self.getCenter = function(){
		if(self.currentMap == false){
			return false;
		}
		return self.currentMap.getCenter();
	}

	self.plotRoute = function(currentPosition){
		var directionsService = new google.maps.DirectionsService;

		var startEnd = currentPosition;

		var tags = globalData.tags;

		var waypts = [];

		for(var i = 0; i<tags.length;i++){

			var tag = tags[i];
			waypts.push({location: new google.maps.LatLng(tag.position.lat, tag.position.lng), stopover: false});

		}

		directionsService.route({
			origin: startEnd,
			destination: startEnd,
			waypoints: waypts,
			optimizeWaypoints: true,
			travelMode: google.maps.TravelMode.DRIVING
		}, function(response, status) {
			if (status === google.maps.DirectionsStatus.OK) {
				self.directions.setDirections(response);
			} else {
				window.alert('Directions request failed due to ' + status);
			}
		});
	}

}])

.service('TaggingService', function() {
	var self = this;
	self.currentPosition = false;
	self.currentInfo = {};

	self.setPosition = function(position){
		self.currentPosition = position;
	}

	self.setData = function(data){
		self.currentInfo = data;
	}

	self.submit = function(){
		//Submit the current tag to the server
		//Reject if data not complete
	}

})

.service('GlobalData', function($http){
	var self = this;
	self.items = [];
	self.tagTypes = [];
	self.tags = [];

	// Load in items
	$http({
		method: 'GET',
		url: 'http://roughly-api.herokuapp.com/item'
	}).then(function successCallback(response) {
		console.log(response.data._embedded.item);

		self.items = response.data._embedded.item;
	}, function errorCallback(response) {

	});

	// And tag types.
	$http({
		method: 'GET',
		url: 'http://roughly-api.herokuapp.com/tagtype'
	}).then(function successCallback(response) {
		console.log(response.data._embedded.tagtype);

		self.tagTypes = response.data._embedded.tagtype;
	}, function errorCallback(response) {

	});

	// Also tags.
	$http({
		method: 'GET',
		url: 'http://roughly-api.herokuapp.com/tag'
	}).then(function successCallback(response) {
		console.log(response.data._embedded.tag);

		self.tags = response.data._embedded.tag;
	}, function errorCallback(response) {

	});

});
<|endoftext|>


<commit_before>// @flow

import {
  LanguageClientConnection,
  type DocumentHighlight,
  type Location,
  type ServerCapabilities
} from '../languageclient';
import Convert from '../convert';
import Utils from '../utils';
import {Range} from 'atom';

// Public: Adapts the language server definition provider to the
// Atom IDE UI Definitions package for 'Go To Definition' functionality.
export default class DefinitionAdapter {
  // Public: Determine whether this adapter can be used to adapt a language server
  // based on the serverCapabilities matrix containing a definitionProvider.
  //
  // * `serverCapabilities` The {ServerCapabilities} of the language server to consider.
  //
  // Returns a {Boolean} indicating adapter can adapt the server based on the
  // given serverCapabilities.
  static canAdapt(serverCapabilities: ServerCapabilities): boolean {
    return serverCapabilities.definitionProvider === true;
  }

  // Public: Get the definitions for a symbol at a given {Point} within a
  // {TextEditor} including optionally highlighting all other references
  // within the document if the langauge server also supports highlighting.
  //
  // * `connection` A {LanguageClientConnection} to the language server that will provide the definitions and highlights.
  // * `serverCapabilities` The {ServerCapabilities} of the language server that will be used.
  // * `languageName` The name of the programming language.
  // * `editor` The Atom {TextEditor} containing the symbol and potential highlights.
  // * `point` The Atom {Point} containing the position of the text that represents the symbol
  //           for which the definition and highlights should be provided.
  //
  // Returns a {Promise} indicating adapter can adapt the server based on the
  // given serverCapabilities.
  async getDefinition(
    connection: LanguageClientConnection,
    serverCapabilities: ServerCapabilities,
    languageName: string,
    editor: TextEditor,
    point: atom$Point,
  ): Promise<?nuclide$DefinitionQueryResult> {
    const documentPositionParams = Convert.editorToTextDocumentPositionParams(editor, point);
    const definitionLocations = DefinitionAdapter.normalizeLocations(await connection.gotoDefinition(documentPositionParams));
    if (definitionLocations == null || definitionLocations.length === 0) { return null; }

    let queryRange;
    if (serverCapabilities.documentHighlightProvider) {
      const highlights = await connection.documentHighlight(documentPositionParams);
      if (highlights != null && highlights.length > 0) {
        queryRange = highlights.map(h => Convert.lsRangeToAtomRange(h.range));
      }
    }

    return {
      queryRange: queryRange || [Utils.getWordAtPosition(editor, point)],
      definitions: DefinitionAdapter.convertLocationsToDefinitions(definitions)
    };
  }

  // Public: Normalize the locations so a single {Location} becomes an {Array} of just
  // one. The language server protocol return either as the protocol evolved between v1 and v2.
  //
  // * `locationResult` either a single {Location} object or an {Array} of {Locations}
  //
  // Returns an {Array} of {Location}s or {null} if the locationResult was null.
  static normalizeLocations(locationResult: Location | Array<Location>): ?Array<Location> {
    if (locationResult == null) { return null; }
    return (Array.isArray(locationResult) ? locationResult : [locationResult]).filter(d => d.range.start != null);
  }

  // Public: Convert an {Array} of {Location} objects into an Array of {Definition}s.
  //
  // * `locations` An {Array} of {Location} objects to be converted.
  // * `languageName` The name of the language these objects are written in.
  //
  // Returns an {Array} of {Definition}s that represented the converted {Location}s.
  static convertLocationsToDefinitions(locations: Array<Location>, languageName: string): Array<nuclide$Definition> {
      return locations.map(d => ({
        path: Convert.uriToPath(d.uri),
        position: Convert.positionToPoint(d.range.start),
        range: Range.fromObject(Convert.lsRangeToAtomRange(d.range)),
        language: languageName
      }));
  }
}
<commit_msg>Fix definition adapter<commit_after>// @flow

import {
  LanguageClientConnection,
  type Location,
  type ServerCapabilities,
} from '../languageclient';
import Convert from '../convert';
import Utils from '../utils';
import {Range} from 'atom';

// Public: Adapts the language server definition provider to the
// Atom IDE UI Definitions package for 'Go To Definition' functionality.
export default class DefinitionAdapter {
  // Public: Determine whether this adapter can be used to adapt a language server
  // based on the serverCapabilities matrix containing a definitionProvider.
  //
  // * `serverCapabilities` The {ServerCapabilities} of the language server to consider.
  //
  // Returns a {Boolean} indicating adapter can adapt the server based on the
  // given serverCapabilities.
  static canAdapt(serverCapabilities: ServerCapabilities): boolean {
    return serverCapabilities.definitionProvider === true;
  }

  // Public: Get the definitions for a symbol at a given {Point} within a
  // {TextEditor} including optionally highlighting all other references
  // within the document if the langauge server also supports highlighting.
  //
  // * `connection` A {LanguageClientConnection} to the language server that will provide definitions and highlights.
  // * `serverCapabilities` The {ServerCapabilities} of the language server that will be used.
  // * `languageName` The name of the programming language.
  // * `editor` The Atom {TextEditor} containing the symbol and potential highlights.
  // * `point` The Atom {Point} containing the position of the text that represents the symbol
  //           for which the definition and highlights should be provided.
  //
  // Returns a {Promise} indicating adapter can adapt the server based on the
  // given serverCapabilities.
  async getDefinition(
    connection: LanguageClientConnection,
    serverCapabilities: ServerCapabilities,
    languageName: string,
    editor: TextEditor,
    point: atom$Point,
  ): Promise<?nuclide$DefinitionQueryResult> {
    const documentPositionParams = Convert.editorToTextDocumentPositionParams(editor, point);
    const definitionLocations = DefinitionAdapter.normalizeLocations(
      await connection.gotoDefinition(documentPositionParams),
    );
    if (definitionLocations == null || definitionLocations.length === 0) { return null; }

    let queryRange;
    if (serverCapabilities.documentHighlightProvider) {
      const highlights = await connection.documentHighlight(documentPositionParams);
      if (highlights != null && highlights.length > 0) {
        queryRange = highlights.map(h => Convert.lsRangeToAtomRange(h.range));
      }
    }

    return {
      queryRange: queryRange || [Utils.getWordAtPosition(editor, point)],
      definitions: DefinitionAdapter.convertLocationsToDefinitions(definitionLocations, languageName),
    };
  }

  // Public: Normalize the locations so a single {Location} becomes an {Array} of just
  // one. The language server protocol return either as the protocol evolved between v1 and v2.
  //
  // * `locationResult` either a single {Location} object or an {Array} of {Locations}
  //
  // Returns an {Array} of {Location}s or {null} if the locationResult was null.
  static normalizeLocations(locationResult: Location | Array<Location>): ?Array<Location> {
    if (locationResult == null) { return null; }
    return (Array.isArray(locationResult) ? locationResult : [locationResult]).filter(d => d.range.start != null);
  }

  // Public: Convert an {Array} of {Location} objects into an Array of {Definition}s.
  //
  // * `locations` An {Array} of {Location} objects to be converted.
  // * `languageName` The name of the language these objects are written in.
  //
  // Returns an {Array} of {Definition}s that represented the converted {Location}s.
  static convertLocationsToDefinitions(locations: Array<Location>, languageName: string): Array<nuclide$Definition> {
    return locations.map(d => ({
      path: Convert.uriToPath(d.uri),
      position: Convert.positionToPoint(d.range.start),
      range: Range.fromObject(Convert.lsRangeToAtomRange(d.range)),
      language: languageName,
    }));
  }
}
<|endoftext|>


<commit_before>// @flow
import * as React from "react";

export default function BrainSpinner() {
  return (

  );
}
<commit_msg>remove alt text for abstract brain loading image (#3930)<commit_after>// @flow
import * as React from "react";

export default function BrainSpinner() {
  return (

  );
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import assign from 'object-assign';

import { showMenu, hideMenu } from './actions';
import { callIfExists, cssClasses } from './helpers';

export default class ContextMenuTrigger extends Component {
    static propTypes = {
        id: PropTypes.string.isRequired,
        children: PropTypes.node.isRequired,
        attributes: PropTypes.object,
        collect: PropTypes.func,
        disable: PropTypes.bool,
        holdToDisplay: PropTypes.number,
        renderTag: PropTypes.oneOfType([
            PropTypes.node,
            PropTypes.func
        ])
    };

    static defaultProps = {
        attributes: {},
        collect() { return null; },
        disable: false,
        holdToDisplay: 1000,
        renderTag: 'div'
    };

    touchHandled = false;

    handleMouseDown = (event) => {
        if (this.props.holdToDisplay >= 0 && event.button === 0) {
            event.persist();

            this.mouseDownTimeoutId = setTimeout(
                () => this.handleContextClick(event),
                this.props.holdToDisplay
            );
        }
    }

    handleMouseUp = (event) => {
        if (event.button === 0) {
            clearTimeout(this.mouseDownTimeoutId);
        }
    }

    handleTouchstart = (event) => {
        if (this.props.holdToDisplay >= 0) {
            event.persist();

            this.touchstartTimeoutId = setTimeout(
                () => {
                    this.handleContextClick(event),
                    this.props.holdToDisplay,
                    this.touchHandled = true
                }
            );
        }
    }

    handleTouchEnd = (event) => {
        if (this.touchHandled) {
            event.preventDefault();
        }
        clearTimeout(this.touchstartTimeoutId);
    }

    handleContextClick = (event) => {
        if (this.props.disable) return;

        event.preventDefault();
        event.stopPropagation();

        const x = event.clientX || (event.touches && event.touches[0].pageX);
        const y = event.clientY || (event.touches && event.touches[0].pageY);

        hideMenu();

        showMenu({
            position: { x, y },
            target: this.elem,
            id: this.props.id,
            data: callIfExists(this.props.collect, this.props)
        });
    }

    elemRef = (c) => {
        this.elem = c;
    }

    render() {
        const { renderTag, attributes, children } = this.props;
        const newAttrs = assign({}, attributes, {
            className: cx(cssClasses.menuWrapper, attributes.className),
            onContextMenu: this.handleContextClick,
            onMouseDown: this.handleMouseDown,
            onMouseUp: this.handleMouseUp,
            onTouchStart: this.handleTouchstart,
            onTouchEnd: this.handleTouchEnd,
            onMouseOut: this.handleMouseUp,
            ref: this.elemRef
        });

        return React.createElement(renderTag, newAttrs, children);
    }
}
<commit_msg>Update ContextMenuTrigger.js<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import assign from 'object-assign';

import { showMenu, hideMenu } from './actions';
import { callIfExists, cssClasses } from './helpers';

export default class ContextMenuTrigger extends Component {
    static propTypes = {
        id: PropTypes.string.isRequired,
        children: PropTypes.node.isRequired,
        attributes: PropTypes.object,
        collect: PropTypes.func,
        disable: PropTypes.bool,
        holdToDisplay: PropTypes.number,
        renderTag: PropTypes.oneOfType([
            PropTypes.node,
            PropTypes.func
        ])
    };

    static defaultProps = {
        attributes: {},
        collect() { return null; },
        disable: false,
        holdToDisplay: 1000,
        renderTag: 'div'
    };

    touchHandled = false;

    handleMouseDown = (event) => {
        if (this.props.holdToDisplay >= 0 && event.button === 0) {
            event.persist();

            this.mouseDownTimeoutId = setTimeout(
                () => this.handleContextClick(event),
                this.props.holdToDisplay
            );
        }
    }

    handleMouseUp = (event) => {
        if (event.button === 0) {
            clearTimeout(this.mouseDownTimeoutId);
        }
    }

    handleTouchstart = (event) => {
        if (this.props.holdToDisplay >= 0) {
            event.persist();

            this.touchstartTimeoutId = setTimeout(
                () => {
                    this.handleContextClick(event);
                    this.touchHandled = true;
                },
                this.props.holdToDisplay
            );
        }
    }

    handleTouchEnd = (event) => {
        if (this.touchHandled) {
            event.preventDefault();
        }
        clearTimeout(this.touchstartTimeoutId);
    }

    handleContextClick = (event) => {
        if (this.props.disable) return;

        event.preventDefault();
        event.stopPropagation();

        const x = event.clientX || (event.touches && event.touches[0].pageX);
        const y = event.clientY || (event.touches && event.touches[0].pageY);

        hideMenu();

        showMenu({
            position: { x, y },
            target: this.elem,
            id: this.props.id,
            data: callIfExists(this.props.collect, this.props)
        });
    }

    elemRef = (c) => {
        this.elem = c;
    }

    render() {
        const { renderTag, attributes, children } = this.props;
        const newAttrs = assign({}, attributes, {
            className: cx(cssClasses.menuWrapper, attributes.className),
            onContextMenu: this.handleContextClick,
            onMouseDown: this.handleMouseDown,
            onMouseUp: this.handleMouseUp,
            onTouchStart: this.handleTouchstart,
            onTouchEnd: this.handleTouchEnd,
            onMouseOut: this.handleMouseUp,
            ref: this.elemRef
        });

        return React.createElement(renderTag, newAttrs, children);
    }
}
<|endoftext|>