<commit_before>// @flow

import * as React from 'react'
import {StyleSheet, FlatList} from 'react-native'
import {View, Text} from 'glamorous-native'
import Map, {Marker, Polygon, UrlTile} from 'react-native-maps'
import * as c from '../components/colors'
import {Button} from '../components/button'
import type {TopLevelViewPropsType} from '../types'
import {SearchBar} from '../components/searchbar'
import {ListSeparator, Title, Detail, ListRow} from '../components/list'
import {Row, Column} from '../components/layout'
import sortBy from 'lodash/sortBy'
import uniq from 'lodash/uniq'

const MAP_DATA_URL = 'https://carls-app.github.io/map-data/map.json'
const CARLETON_TILE_TEMPLATE =
	'https://www.carleton.edu/global_stock/images/campus_map/tiles/base/{z}_{x}_{y}.png'
const GITHUB_TILE_TEMPLATE =
	'https://carls-app.github.io/map-data/tiles/{z}/{x}_{y}.png'

type Props = TopLevelViewPropsType

type State = {|
	region: Region,
	buildings: Array<Building>,
	visibleMarkers: Array<string>,
	highlighted: Array<string>,
	buildingPickerState: 'min' | 'mid' | 'max',
|}

type Region = {
	latitude: number,
	longitude: number,
	latitudeDelta: number,
	longitudeDelta: number,
}

type LatLon = {
	latitude: number,
	longitude: number,
}

type MarkerT = {
	coordinate: LatLon,
	title: string,
	description: string,
	key: string,
}

type OutlineT = {
	coordinates: Array<LatLon>,
	key: string,
}

type Building = {
	accessibility: 'none' | 'wheelchair' | 'unknown',
	address: ?string,
	categories: {
		administrative?: true,
		academic?: true,
		outdoors?: true,
		building?: true,
		'employee-housing'?: true,
		'student-housing'?: true,
		hall?: true,
		parking?: true,
		house?: true,
	},
	center: ?[number, number],
	departments: Array<{href: string, label: string}>,
	description: ?string,
	floors: Array<{href: string, label: string}>,
	id: string,
	name: string,
	offices: Array<{href: string, label: string}>,
	outline: Array<[number, number]>,
	photo: ?string,
}

const originalCenterpoint = {
	latitude: 44.460800862266,
	longitude: -93.15488752015,
	latitudeDelta: 0.004617,
	longitudeDelta: 0.004023,
}

export class MapView extends React.Component<Props, State> {
	static navigationOptions = {
		title: 'Campus Map',
		headerBackTitle: 'Map',
	}

	state = {
		region: originalCenterpoint,
		buildings: [],
		highlighted: [],
		visibleMarkers: [],
		buildingPickerState: 'min',
	}

	componentDidMount() {
		this.fetchData()
	}

	fetchData = async () => {
		const data: Array<Building> = await fetchJson(MAP_DATA_URL)

		this.setState(() => ({
			buildings: data,
			highlighted: [],
			visibleMarkers: [],
		}))
	}

	buildingToMarker = (b: Building) => {
		// $FlowExpectedError
		const coord = {latitude: b.center[0], longitude: b.center[1]}
		return (
			<Marker
				key={b.id}
				coordinate={coord}
				description={b.address || ''}
				title={b.name}
			/>
		)
	}

	buildingToOutline = (b: Building) => {
		const coords = b.outline.map(([latitude, longitude]) => ({
			latitude,
			longitude,
		}))
		return (
			<Polygon
				key={b.id}
				coordinates={coords}
				fillColor={c.black75Percent}
				strokeColor={c.black50Percent}
			/>
		)
	}

	buildingToHighlightedOutline = (b: Building) => {
		const coords = b.outline.map(([latitude, longitude]) => ({
			latitude,
			longitude,
		}))

		return (
			<Polygon
				key={b.id}
				coordinates={coords}
				fillColor={c.brickRed}
				strokeColor={c.brickRed}
			/>
		)
	}

	onPickerFocus = () => {
		this.setState(() => ({buildingPickerState: 'max'}))
	}

	onPickerSearchCancel = () => {
		this.setState(() => ({buildingPickerState: 'mid'}))
	}

	onPickerSelect = (id: string) => {
		const match = this.state.buildings.find(b => b.id === id)

		if (!match) {
			return
		}

		const newCenter = match.center
			? {latitude: match.center[0], longitude: match.center[1]}
			: originalCenterpoint

		const zoom = {
			latitudeDelta: 0.002252,
			longitudeDelta: 0.001962,
		}

		this.setState(state => {
			return {
				region: {
					...newCenter,
					...zoom,
				},
				buildingPickerState: 'min',
				visibleMarkers: uniq([...state.visibleMarkers, id]),
				highlighted: uniq([...state.highlighted, id]),
			}
		})
	}

	onRegionChange = (region: Region) => {
		this.setState(() => ({region}))
	}

	render() {
		return (
			<View {...StyleSheet.absoluteFillObject}>
				<Map
					onRegionChange={this.onRegionChange}
					region={this.state.region}
					showsPointsOfInterest={false}
					showsUserLocation={true}
					style={styles.map}
				>
					<UrlTile maximumZ={19} urlTemplate={GITHUB_TILE_TEMPLATE} />

					{this.state.buildings
						.filter(b => this.state.visibleMarkers.includes(b.id))
						.map(this.buildingToMarker)}

					{this.state.buildings
						.filter(b => !this.state.highlighted.includes(b.id))
						.map(this.buildingToOutline)}

					{this.state.buildings
						.filter(b => this.state.highlighted.includes(b.id))
						.map(this.buildingToHighlightedOutline)}
				</Map>

				<BuildingPicker
					viewState={this.state.buildingPickerState}
					buildings={this.state.buildings}
					onFocus={this.onPickerFocus}
					onCancel={this.onPickerSearchCancel}
					onSelect={this.onPickerSelect}
				/>

				<View style={styles.infoOverlay}>
					<Text>latitude: {this.state.region.latitude}</Text>
					<Text>longitude: {this.state.region.longitude}</Text>
					<Text>
						latitudeDelta: {this.state.region.latitudeDelta}
					</Text>
					<Text>
						longitudeDelta: {this.state.region.longitudeDelta}
					</Text>
				</View>
			</View>
		)
	}
}

type BuildingPickerProps = {
	viewState: 'min' | 'mid' | 'max',
	buildings: Array<Building>,
	onFocus: () => any,
	onCancel: () => any,
	onSelect: string => any,
}

type BuildingPickerState = {
	query: string,
}

class BuildingPicker extends React.Component<
	BuildingPickerProps,
	BuildingPickerState,
> {
	searchBar: any = null

	state = {
		query: '',
	}

	componentWillReceiveProps(nextProps) {
		if (
			this.props.viewState === 'max' &&
			this.props.viewState !== nextProps.viewState
		) {
			this.dismissKeyboard()
		}
	}

	dismissKeyboard = () => {
		this.searchBar.unFocus()
	}

	onSearch = (text: ?string) => {
		let query = text || ''
		query = query.toLowerCase()
		this.setState(() => ({query}))
	}

	performSearch = (text: string) => {
		// Android clear button returns an object
		if (typeof text !== 'string') {
			return this.onSearch(null)
		}

		return this.onSearch(text)
	}

	onSelectBuilding = (id: string) => this.props.onSelect(id)

	render() {
		const {viewState} = this.props

		const search = (
			<SearchBar
				getRef={ref => (this.searchBar = ref)}
				onSearchButtonPress={() => this.searchBar.unFocus()}
				onChangeText={this.performSearch}
				onSearchButtonPress={() => {}}
				onFocus={this.props.onFocus}
				onCancel={this.props.onCancel}
				textFieldBackgroundColor={c.iosGray}
				placeholder="Search for a place"
			/>
		)

		let matches = this.state.query
			? this.props.buildings.filter(b =>
					b.name.toLowerCase().startsWith(this.state.query),
				)
			: this.props.buildings

		matches = sortBy(matches, m => m.name)

		if (viewState === 'min') {
			return (
				<View style={[styles.overlay, styles.overlayMin]}>
					<GrabberBar />
					{search}
				</View>
			)
		} else if (viewState === 'mid') {
			return (
				<View style={[styles.overlay, styles.overlayMid]}>
					<GrabberBar />
					{search}
					<BuildingResults
						buildings={matches}
						onSelect={this.onSelectBuilding}
					/>
				</View>
			)
		} else if (viewState === 'max') {
			return (
				<View style={[styles.overlay, styles.overlayMax]}>
					<GrabberBar />
					{search}
					<BuildingResults
						buildings={matches}
						onSelect={this.onSelectBuilding}
					/>
				</View>
			)
		}
	}
}

const GrabberBar = () => <View style={styles.grabber} />

class BuildingResults extends React.Component<{
	buildings: Array<Building>,
	onSelect: string => any,
}> {
	keyExtractor = (item: Building) => item.id

	onPress = (id: string) => this.props.onSelect(id)

	renderItem = ({item}: {item: Building}) => {
		const detail = item.address || (item.center || []).join(',') || ''
		return (
			<ListRow spacing={{left: 4}} onPress={() => this.onPress(item.id)}>
				<Row>
					<View
						width={24}
						height={24}
						borderRadius={24}
						backgroundColor={c.success}
						alignSelf="center"
						marginRight={6}
					/>
					<Column>
						<Title>{item.name}</Title>
						<Detail>{detail}</Detail>
					</Column>
				</Row>
			</ListRow>
		)
	}

	separator = () => <ListSeparator spacing={{left: 4}} />

	render() {
		return (
			<FlatList
				data={this.props.buildings}
				keyExtractor={this.keyExtractor}
				ItemSeparatorComponent={this.separator}
				renderItem={this.renderItem}
			/>
		)
	}
}

const styles = StyleSheet.create({
	map: {
		flex: 1,
	},
	grabber: {
		backgroundColor: c.iosGray,
		borderRadius: 4,
		height: 4,
		width: 30,
		alignSelf: 'center',
		marginBottom: 1,
		marginTop: 6,
	},
	infoOverlay: {
		position: 'absolute',
		top: 0,
		left: 0,
		zIndex: 1,
	},
	overlay: {
		backgroundColor: c.white,
		borderTopLeftRadius: 10,
		borderTopRightRadius: 10,
		bottom: 0,
		left: 0,
		paddingHorizontal: 6,
		paddingTop: 0,
		position: 'absolute',
		right: 0,
		shadowColor: c.black,
		shadowOffset: {height: -4},
		shadowOpacity: 0.15,
		shadowRadius: 4,
		zIndex: 2,
	},
	overlayMin: {
		height: 80,
	},
	overlayMid: {
		height: 200,
	},
	overlayMax: {
		top: 20,
	},
})
<commit_msg>fix center access with no centerpoint<commit_after>// @flow

import * as React from 'react'
import {StyleSheet, FlatList} from 'react-native'
import {View, Text} from 'glamorous-native'
import Map, {Marker, Polygon, UrlTile} from 'react-native-maps'
import * as c from '../components/colors'
import {Button} from '../components/button'
import type {TopLevelViewPropsType} from '../types'
import {SearchBar} from '../components/searchbar'
import {ListSeparator, Title, Detail, ListRow} from '../components/list'
import {Row, Column} from '../components/layout'
import sortBy from 'lodash/sortBy'
import uniq from 'lodash/uniq'

const MAP_DATA_URL = 'https://carls-app.github.io/map-data/map.json'
const CARLETON_TILE_TEMPLATE =
	'https://www.carleton.edu/global_stock/images/campus_map/tiles/base/{z}_{x}_{y}.png'
const GITHUB_TILE_TEMPLATE =
	'https://carls-app.github.io/map-data/tiles/{z}/{x}_{y}.png'

type Props = TopLevelViewPropsType

type State = {|
	region: Region,
	buildings: Array<Building>,
	visibleMarkers: Array<string>,
	highlighted: Array<string>,
	buildingPickerState: 'min' | 'mid' | 'max',
|}

type Region = {
	latitude: number,
	longitude: number,
	latitudeDelta: number,
	longitudeDelta: number,
}

type LatLon = {
	latitude: number,
	longitude: number,
}

type MarkerT = {
	coordinate: LatLon,
	title: string,
	description: string,
	key: string,
}

type OutlineT = {
	coordinates: Array<LatLon>,
	key: string,
}

type Building = {
	accessibility: 'none' | 'wheelchair' | 'unknown',
	address: ?string,
	categories: {
		administrative?: true,
		academic?: true,
		outdoors?: true,
		building?: true,
		'employee-housing'?: true,
		'student-housing'?: true,
		hall?: true,
		parking?: true,
		house?: true,
	},
	center: ?[number, number],
	departments: Array<{href: string, label: string}>,
	description: ?string,
	floors: Array<{href: string, label: string}>,
	id: string,
	name: string,
	offices: Array<{href: string, label: string}>,
	outline: Array<[number, number]>,
	photo: ?string,
}

const originalCenterpoint = {
	latitude: 44.460800862266,
	longitude: -93.15488752015,
	latitudeDelta: 0.004617,
	longitudeDelta: 0.004023,
}

export class MapView extends React.Component<Props, State> {
	static navigationOptions = {
		title: 'Campus Map',
		headerBackTitle: 'Map',
	}

	state = {
		region: originalCenterpoint,
		buildings: [],
		highlighted: [],
		visibleMarkers: [],
		buildingPickerState: 'min',
	}

	componentDidMount() {
		this.fetchData()
	}

	fetchData = async () => {
		const data: Array<Building> = await fetchJson(MAP_DATA_URL)

		this.setState(() => ({
			buildings: data,
			highlighted: [],
			visibleMarkers: [],
		}))
	}

	buildingToMarker = (b: Building) => {
		if (!b.center) {
			return
		}

		const coord = {latitude: b.center[0], longitude: b.center[1]}
		return (
			<Marker
				key={b.id}
				coordinate={coord}
				description={b.address || ''}
				title={b.name}
			/>
		)
	}

	buildingToOutline = (b: Building) => {
		const coords = b.outline.map(([latitude, longitude]) => ({
			latitude,
			longitude,
		}))
		return (
			<Polygon
				key={b.id}
				coordinates={coords}
				fillColor={c.black75Percent}
				strokeColor={c.black50Percent}
			/>
		)
	}

	buildingToHighlightedOutline = (b: Building) => {
		const coords = b.outline.map(([latitude, longitude]) => ({
			latitude,
			longitude,
		}))

		return (
			<Polygon
				key={b.id}
				coordinates={coords}
				fillColor={c.brickRed}
				strokeColor={c.brickRed}
			/>
		)
	}

	onPickerFocus = () => {
		this.setState(() => ({buildingPickerState: 'max'}))
	}

	onPickerSearchCancel = () => {
		this.setState(() => ({buildingPickerState: 'mid'}))
	}

	onPickerSelect = (id: string) => {
		const match = this.state.buildings.find(b => b.id === id)

		if (!match) {
			return
		}

		const newCenter = match.center
			? {latitude: match.center[0], longitude: match.center[1]}
			: originalCenterpoint

		const zoom = {
			latitudeDelta: 0.002252,
			longitudeDelta: 0.001962,
		}

		this.setState(state => {
			return {
				region: {
					...newCenter,
					...zoom,
				},
				buildingPickerState: 'min',
				visibleMarkers: uniq([...state.visibleMarkers, id]),
				highlighted: uniq([...state.highlighted, id]),
			}
		})
	}

	onRegionChange = (region: Region) => {
		this.setState(() => ({region}))
	}

	render() {
		return (
			<View {...StyleSheet.absoluteFillObject}>
				<Map
					onRegionChange={this.onRegionChange}
					region={this.state.region}
					showsPointsOfInterest={false}
					showsUserLocation={true}
					style={styles.map}
				>
					<UrlTile maximumZ={19} urlTemplate={GITHUB_TILE_TEMPLATE} />

					{this.state.buildings
						.filter(b => this.state.visibleMarkers.includes(b.id))
						.map(this.buildingToMarker)}

					{this.state.buildings
						.filter(b => !this.state.highlighted.includes(b.id))
						.map(this.buildingToOutline)}

					{this.state.buildings
						.filter(b => this.state.highlighted.includes(b.id))
						.map(this.buildingToHighlightedOutline)}
				</Map>

				<BuildingPicker
					viewState={this.state.buildingPickerState}
					buildings={this.state.buildings}
					onFocus={this.onPickerFocus}
					onCancel={this.onPickerSearchCancel}
					onSelect={this.onPickerSelect}
				/>

				<View style={styles.infoOverlay}>
					<Text>latitude: {this.state.region.latitude}</Text>
					<Text>longitude: {this.state.region.longitude}</Text>
					<Text>
						latitudeDelta: {this.state.region.latitudeDelta}
					</Text>
					<Text>
						longitudeDelta: {this.state.region.longitudeDelta}
					</Text>
				</View>
			</View>
		)
	}
}

type BuildingPickerProps = {
	viewState: 'min' | 'mid' | 'max',
	buildings: Array<Building>,
	onFocus: () => any,
	onCancel: () => any,
	onSelect: string => any,
}

type BuildingPickerState = {
	query: string,
}

class BuildingPicker extends React.Component<
	BuildingPickerProps,
	BuildingPickerState,
> {
	searchBar: any = null

	state = {
		query: '',
	}

	componentWillReceiveProps(nextProps) {
		if (
			this.props.viewState === 'max' &&
			this.props.viewState !== nextProps.viewState
		) {
			this.dismissKeyboard()
		}
	}

	dismissKeyboard = () => {
		this.searchBar.unFocus()
	}

	onSearch = (text: ?string) => {
		let query = text || ''
		query = query.toLowerCase()
		this.setState(() => ({query}))
	}

	performSearch = (text: string) => {
		// Android clear button returns an object
		if (typeof text !== 'string') {
			return this.onSearch(null)
		}

		return this.onSearch(text)
	}

	onSelectBuilding = (id: string) => this.props.onSelect(id)

	render() {
		const {viewState} = this.props

		const search = (
			<SearchBar
				getRef={ref => (this.searchBar = ref)}
				onSearchButtonPress={() => this.searchBar.unFocus()}
				onChangeText={this.performSearch}
				onSearchButtonPress={() => {}}
				onFocus={this.props.onFocus}
				onCancel={this.props.onCancel}
				textFieldBackgroundColor={c.iosGray}
				placeholder="Search for a place"
			/>
		)

		let matches = this.state.query
			? this.props.buildings.filter(b =>
					b.name.toLowerCase().startsWith(this.state.query),
				)
			: this.props.buildings

		matches = sortBy(matches, m => m.name)

		if (viewState === 'min') {
			return (
				<View style={[styles.overlay, styles.overlayMin]}>
					<GrabberBar />
					{search}
				</View>
			)
		} else if (viewState === 'mid') {
			return (
				<View style={[styles.overlay, styles.overlayMid]}>
					<GrabberBar />
					{search}
					<BuildingResults
						buildings={matches}
						onSelect={this.onSelectBuilding}
					/>
				</View>
			)
		} else if (viewState === 'max') {
			return (
				<View style={[styles.overlay, styles.overlayMax]}>
					<GrabberBar />
					{search}
					<BuildingResults
						buildings={matches}
						onSelect={this.onSelectBuilding}
					/>
				</View>
			)
		}
	}
}

const GrabberBar = () => <View style={styles.grabber} />

class BuildingResults extends React.Component<{
	buildings: Array<Building>,
	onSelect: string => any,
}> {
	keyExtractor = (item: Building) => item.id

	onPress = (id: string) => this.props.onSelect(id)

	renderItem = ({item}: {item: Building}) => {
		const detail = item.address || (item.center || []).join(',') || ''
		return (
			<ListRow spacing={{left: 4}} onPress={() => this.onPress(item.id)}>
				<Row>
					<View
						width={24}
						height={24}
						borderRadius={24}
						backgroundColor={c.success}
						alignSelf="center"
						marginRight={6}
					/>
					<Column>
						<Title>{item.name}</Title>
						<Detail>{detail}</Detail>
					</Column>
				</Row>
			</ListRow>
		)
	}

	separator = () => <ListSeparator spacing={{left: 4}} />

	render() {
		return (
			<FlatList
				data={this.props.buildings}
				keyExtractor={this.keyExtractor}
				ItemSeparatorComponent={this.separator}
				renderItem={this.renderItem}
			/>
		)
	}
}

const styles = StyleSheet.create({
	map: {
		flex: 1,
	},
	grabber: {
		backgroundColor: c.iosGray,
		borderRadius: 4,
		height: 4,
		width: 30,
		alignSelf: 'center',
		marginBottom: 1,
		marginTop: 6,
	},
	infoOverlay: {
		position: 'absolute',
		top: 0,
		left: 0,
		zIndex: 1,
	},
	overlay: {
		backgroundColor: c.white,
		borderTopLeftRadius: 10,
		borderTopRightRadius: 10,
		bottom: 0,
		left: 0,
		paddingHorizontal: 6,
		paddingTop: 0,
		position: 'absolute',
		right: 0,
		shadowColor: c.black,
		shadowOffset: {height: -4},
		shadowOpacity: 0.15,
		shadowRadius: 4,
		zIndex: 2,
	},
	overlayMin: {
		height: 80,
	},
	overlayMid: {
		height: 200,
	},
	overlayMax: {
		top: 20,
	},
})
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const fs = require('fs');

const invertBitmap = require('../lib/invertBitmap');
const restoreInvertedBitmap = require('../lib/restoreInvertedBitmap');

describe('create an inverted bitmap of the original', function() {
  var originalBitmapArray = [];
  var invertBitmapArray = [];
  var restoredBitmapArray = [];
  before(function(done) {
    fs.readFile('./test/palette-bitmap.bmp', function(err, data) {
      if(err) console.log(err);
      originalBitmapArray.push(data.toString());
      done();
    });
  });

  it('the invert bitmap should be output', function(done) {
    invertBitmap('./test/palette-bitmap.bmp', function(err, data) {
      if(err) console.log(err);
      console.log('inverting bitmap');
      invertBitmapArray.push(data.toString());
    });
    done();
  });

  it('the restored bitmap should match the original bitmap', function(done) {
    restoreInvertedBitmap('./test/inverted-palette-bitmap.bmp', function(err, data) {
      console.log('restoring original bitmap');
      restoredBitmapArray.push(data.toString());
      expect(originalBitmapArray).to.eql(restoredBitmapArray);
    });
    done();
  });
});
<commit_msg>basic test using mocha to verify already created files<commit_after>const expect = require('chai').expect;
const fs = require('fs');

const invertBitmap = require('../lib/invertBitmap');
const restoreBitmap = require('../lib/restoreBitmap');

describe('hooks', function() {
  var fileData = [];
  var restoredFileData = [];

  before(function(done) {
    fs.readFile('../test/palette-bitmap.bmp', function(err, data) {
      fileData.push(data.toString());
      if(err) console.log(err);
      fs.readFile('../test/restored-palette-bitmap.bmp', function(err, data) {
        restoredFileData.push(data.toString());
        if(err) console.log(err);
        done();
      });
    });
  });

  it('should restore the bitmap', function(done) {
    expect(fileData.length).to.eql(1);
    expect(restoredFileData.length).to.eql(1);
    expect(fileData).to.eql(restoredFileData);
    done();
  });
});
<|endoftext|>


<commit_before>// m3u8adskipper.js
// ================
var exec = require('child_process').exec;
var fs = require('fs');

exports.version = "0.1.0";

var endsWith = function(str, suffix)
{
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

exports.skip = function(masterPlayListFile, skipAds, outputFile, callback)
{
    var res = masterPlayListFile.split("/");
    var rootDir = masterPlayListFile.replace(res[res.length-1],'');
    var content = "";
    try
    {
        content = fs.readFileSync(masterPlayListFile, 'utf-8');
    }
    catch(err)
    {
        callback("error: ", err);
    }
    var masterPlayListContents = content.split("\n");
    var removeURL = '';
    for(i in masterPlayListContents)
    {
        if(endsWith(masterPlayListContents[i],"m3u8"))
        {
            var res2 = masterPlayListContents[i].split("/");
            var playListDir = rootDir + masterPlayListContents[i].replace(res2[res2.length-1],'');
            if (masterPlayListContents[i].indexOf("://") > -1)
            {
                removeURL = res2[0] + '//' + res2[1] + res2[2] + '/' + res2[3] + '/';
                masterPlayListContents[i] = masterPlayListContents[i].replace(removeURL,'');
            }
            var masterDir = masterPlayListContents[i].replace(res2[res2.length-1],'');
            try
            {
                content2 = fs.readFileSync(rootDir + masterPlayListContents[i], "utf-8");
            }
            catch(err)
            {
                callback('error:', err);
            }
            var mediaPlayListContents = content2.split("\n");
            var k = -1;
            var mediaSegments = new Array();
            var xMediaSegments = new Array();
            var yMediaSegments = new Array();
            var command = "ffmpeg -y -loglevel quiet -i ";
            var curDir = "";
            var currentStream = 0, adsPresent = false;
            for(j in mediaPlayListContents)
            {
                if(endsWith(mediaPlayListContents[j],"ts"))
                {
                    k++;
                    var fileName = mediaPlayListContents[j].split("/");
                    if(skipAds)
                    {
                        if(currentStream == 0)
                        {
                            xMediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                        }
                        else
                        {
                            yMediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                        }
                        mediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                    }
                }
                else if(endsWith(mediaPlayListContents[j],"EXT-X-DISCONTINUITY"))
                {
                    callback("content transition from/to ads");
                    adsPresent = true;
                    if(currentStream == 0)
                        currentStream = 1;
                    else
                        currentStream = 0;
                }
                else if(endsWith(mediaPlayListContents[j],"ENDLIST"))
                {
                    currentStream = 0;
                }
            }
            k = 0;
            var concatParam = '"concat:';
            if(adsPresent && skipAds)
            {
                if(xMediaSegments.length > yMediaSegments.length)
                {
                    for(k in xMediaSegments)
                    {
                        if(k != 0)
                            concatParam += '|';
                        concatParam += xMediaSegments[k];
                    }
                }
                else
                {
                    for(k in yMediaSegments)
                    {
                        if(k != 0)
                            concatParam += '|';
                        concatParam += yMediaSegments[k];
                    }
                }
            }
            else
            {
                for(k in mediaSegments)
                {
                    if(k != 0)
                        concatParam += '|';
                    concatParam += mediaSegments[k];
                }
            }
            concatParam += '"';
            outputFileName = rootDir + masterDir + outputFile;
            if(concatParam != '"concat:"')
            {
                // the -bsf:a option is required for handling malformed aac bitstream
                // ==================================================================
                command += concatParam + ' -bsf:a aac_adtstoasc  -c copy -f mp4 ' + outputFileName;
                var child = exec(command, function(err, stdout, stderr)
                {
                    if (stderr)
                        callback('error',stderr);
                    else
                        callback('successfully transmuxed ');
                });
            }
        }
    }
}
<commit_msg>changed the version<commit_after>// m3u8adskipper.js
// ================
var exec = require('child_process').exec;
var fs = require('fs');

exports.version = "0.2.0";

var endsWith = function(str, suffix)
{
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

exports.skip = function(masterPlayListFile, skipAds, outputFile, callback)
{
    var res = masterPlayListFile.split("/");
    var rootDir = masterPlayListFile.replace(res[res.length-1],'');
    var content = "";
    try
    {
        content = fs.readFileSync(masterPlayListFile, 'utf-8');
    }
    catch(err)
    {
        callback("error: ", err);
    }
    var masterPlayListContents = content.split("\n");
    var removeURL = '';
    for(i in masterPlayListContents)
    {
        if(endsWith(masterPlayListContents[i],"m3u8"))
        {
            var res2 = masterPlayListContents[i].split("/");
            var playListDir = rootDir + masterPlayListContents[i].replace(res2[res2.length-1],'');
            if (masterPlayListContents[i].indexOf("://") > -1)
            {
                removeURL = res2[0] + '//' + res2[1] + res2[2] + '/' + res2[3] + '/';
                masterPlayListContents[i] = masterPlayListContents[i].replace(removeURL,'');
            }
            var masterDir = masterPlayListContents[i].replace(res2[res2.length-1],'');
            try
            {
                content2 = fs.readFileSync(rootDir + masterPlayListContents[i], "utf-8");
            }
            catch(err)
            {
                callback('error:', err);
            }
            var mediaPlayListContents = content2.split("\n");
            var k = -1;
            var mediaSegments = new Array();
            var xMediaSegments = new Array();
            var yMediaSegments = new Array();
            var command = "ffmpeg -y -loglevel quiet -i ";
            var curDir = "";
            var currentStream = 0, adsPresent = false;
            for(j in mediaPlayListContents)
            {
                if(endsWith(mediaPlayListContents[j],"ts"))
                {
                    k++;
                    var fileName = mediaPlayListContents[j].split("/");
                    if(skipAds)
                    {
                        if(currentStream == 0)
                        {
                            xMediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                        }
                        else
                        {
                            yMediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                        }
                        mediaSegments[k] = rootDir + masterDir + fileName[fileName.length-1];
                    }
                }
                else if(endsWith(mediaPlayListContents[j],"EXT-X-DISCONTINUITY"))
                {
                    callback("content transition from/to ads");
                    adsPresent = true;
                    if(currentStream == 0)
                        currentStream = 1;
                    else
                        currentStream = 0;
                }
                else if(endsWith(mediaPlayListContents[j],"ENDLIST"))
                {
                    currentStream = 0;
                }
            }
            k = 0;
            var concatParam = '"concat:';
            if(adsPresent && skipAds)
            {
                if(xMediaSegments.length > yMediaSegments.length)
                {
                    for(k in xMediaSegments)
                    {
                        if(k != 0)
                            concatParam += '|';
                        concatParam += xMediaSegments[k];
                    }
                }
                else
                {
                    for(k in yMediaSegments)
                    {
                        if(k != 0)
                            concatParam += '|';
                        concatParam += yMediaSegments[k];
                    }
                }
            }
            else
            {
                for(k in mediaSegments)
                {
                    if(k != 0)
                        concatParam += '|';
                    concatParam += mediaSegments[k];
                }
            }
            concatParam += '"';
            outputFileName = rootDir + masterDir + outputFile;
            if(concatParam != '"concat:"')
            {
                // the -bsf:a option is required for handling malformed aac bitstream
                // ==================================================================
                command += concatParam + ' -bsf:a aac_adtstoasc  -c copy -f mp4 ' + outputFileName;
                var child = exec(command, function(err, stdout, stderr)
                {
                    if (stderr)
                        callback('error',stderr);
                    else
                        callback('successfully transmuxed ');
                });
            }
        }
    }
}
<|endoftext|>


<commit_before>(function() {
  window.BasicGame.Level1 = function (game) { };

  var isoGroup,
    groundGroup,
    obstacleGroup,
    explosionGroup,
    player,
    theBomb,
    pip2;

  var map = [
    [10,1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1,11,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0,10, 1, 1, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [3, 1, 1, 1, 1, 1,13, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,12, 1, 4, 1, 1, 1, 5,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 1, 1, 1, 1, 1, 1,13, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,13, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [12,1, 1, 1, 1, 1, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,13,],
  ];

  BasicGame.Level1.prototype ={
  preload: function () {
    // single images
    game.load.image('cube_', 'assets/cube.png');
    game.load.image('ground', 'assets/floor.png');
    game.load.image('wall1', 'assets/wall-y.png');
    game.load.image('wall2', 'assets/wall-x.png');
    game.load.image('wall3', 'assets/wall-t--y.png');
    game.load.image('wall4', 'assets/wall-t--x.png');
    game.load.image('wall5', 'assets/wall-t-py.png');
    game.load.image('wall6', 'assets/wall-t--x.png');
    game.load.image('wall7', 'assets/wall-tp-x.png');
    game.load.image('wall10', 'assets/wall-l-top.png');
    game.load.image('wall11', 'assets/wall-l-right.png');
    game.load.image('wall12', 'assets/wall-l-left.png');
    game.load.image('wall13', 'assets/wall-l-bottom.png');
    game.load.image('bomb', 'assets/bomb.png');
    game.load.image('letter_a', 'assets/letters/a.png');

    game.load.spritesheet('robot', 'assets/robot.png', 120, 80);
    game.load.spritesheet('kid', 'assets/girl.png', 130, 150);
    // sprites
    game.load.spritesheet('robot', 'assets/robot.png', 120, 80);
    game.load.spritesheet('kid', 'assets/kid.png', 130, 150);
    game.load.spritesheet('sonic-bomb', 'assets/sonic-bomb.png', 130, 116);
    game.load.spritesheet('kaboom', 'assets/explode.png', 128, 128);
    // audio
    game.load.audio('pip2', ['assets/pip2.ogg']);

    game.time.advancedTiming = true;

    // Add and enable the plug-in.
    game.plugins.add(new Phaser.Plugin.Isometric(game));

    // In order to have the camera move, we need to increase the size of our world bounds.
    game.world.setBounds(0, 0, 4096, 4096);

    // Start the IsoArcade physics system.
    game.physics.startSystem(Phaser.Plugin.Isometric.ISOARCADE);

    // In order to have the camera move, we need to increase the size of our world bounds.

    // This is used to set a game canvas-based offset for the 0, 0, 0 isometric coordinate - by default
    // this point would be at screen coordinates 0, 0 (top left) which is usually undesirable.
    game.iso.anchor.setTo(0.5, 0.1);
    game.iso.projectionAngle = 0.52359878;
  },

  create: function () {
    // Background color.
    game.stage.background = 0xB91717;
    // get explosion audio
    pip2 = game.add.audio('pip2');

    // Physics.
    game.physics.isoArcade.gravity.setTo(0, 0, -1000);

    groundGroup = game.add.group();
    obstacleGroup = game.add.group();
    explosionGroup = game.add.group();
    window.obstacleGroup = obstacleGroup;

    // Letters in the level.
    this.lettersGroup = game.add.group();
    var lettersTile = game.add.isoSprite(100, 100, 0, 'letter_a', 0, this.lettersGroup);
    lettersTile.anchor.set(0.5);

    var floorTile, i, j;
    for (var xt = 2048; xt > 0; xt -= 35) {
      for (var yt = 2048; yt > 0; yt -= 35) {
        floorTile = game.add.isoSprite(xt, yt, 0, 'ground', 0, groundGroup);
        floorTile.anchor.set(0.5);
      }
    }

    var a1;
    for(i = 0; i < map.length; ++i) {
      for(j = 0; j < map[i].length; ++j) {
        if (map[i][j] !== 0) {
          a1 = game.add.isoSprite(j*65, i*65, 0, 'wall' + map[i][j], 0, obstacleGroup);
          a1.anchor.set(0.5);
          game.physics.isoArcade.enable(a1);
          a1.body.collideWorldBounds = true;
          a1.body.immovable = true;
        }
      }
    }

    player = new Player(this, {
      x: 830, y: 600, z: 0, group: obstacleGroup, tint: 0x00ff00,
      onBombMounted: onBombMounted.bind(this),
      onExplosion: onExplosion.bind(this)
    });

    // Make the camera follow the player.
    game.camera.follow(player.get());

    // Set up our controls.
    this.cursors = game.input.keyboard.createCursorKeys();

    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      // Phaser.Keyboard.SPACEBAR
    ]);
    this.cursors.jump = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    // Robots Creation
    this.robots = robotClass(this);
  },
  update: function () {
    // For show the position of the player ;)
    //console.log(player.get().body.velocity.x + ' - ' + player.get().body.velocity.y + ' - ' + player.get().body.velocity.z);

    // Move the player at this speed.
    var speed = 500;
    player.move(this.cursors, speed);

    // Our collision and sorting code again.
    game.physics.isoArcade.collide(obstacleGroup);
    game.iso.topologicalSort(obstacleGroup);

    this.lettersGroup.forEach( function (letter) {
      if(Math.abs(player.get().isoPosition.x - letter.isoPosition.x) < 70 &&
        Math.abs(player.get().isoPosition.y - letter.isoPosition.y) < 70) {
        letter.kill();
      }
    });

    animatePlayer(player.get(), this.cursors);

    //console.log(player.get().x);
    obstacleGroup.forEach( function (obstacle) {
      if(obstacle.key == 'robot') {
        animateRobots(obstacle);
        //console.log(Math.abs(player.get().isoPosition.x - obstacle.isoPosition.x));
        if(Math.abs(player.get().isoPosition.x - obstacle.isoPosition.x) < 70 &&
          Math.abs(player.get().isoPosition.y - obstacle.isoPosition.y) < 70) {
          game.state.start('Level1'); // :O
        }
      }
    });
  },
  render: function () {
  //   game.debug.text(game.time.fps || '--', 2, 14, "#a7aebe");
  //   groundGroup.forEach(function (tile) {
  //     game.debug.body(tile, 'rgba(255, 221, 235, 0.6)', false);
  //   });
  //   obstacleGroup.forEach(function (tile) {
  //     game.debug.body(tile, 'rgba(189, 221, 235, 0.6)', false);
  //   });
  }
};

  function onBombMounted(e) {
    console.log('mounted');
    theBomb = game.add.isoSprite(e.row*65, e.col*65, 0, 'sonic-bomb', 0, groundGroup);
    theBomb.anchor.set(0.5);

    theBomb.animations.add('bomb-sequence', [1,2,3,4], 6, true);
    theBomb.animations.play('bomb-sequence');
    pip2.play();
  }

  function onExplosion(e) {
    if(theBomb) {
      console.log('boom!!');
      var kaboom = game.add.isoSprite(theBomb.isoPosition.x-100, theBomb.isoPosition.y-20, 0,'kaboom',explosionGroup);
      kaboom.animations.add('kaboom', [1,2,3,4,5,6,7,8,9,10], 6, false);
      kaboom.animations.play('kaboom');
      setTimeout(function() {
        theBomb.destroy();
        kaboom.destroy();
        var explosions = [];
        obstacleGroup.forEach(function(tile) {
          if(!tile) return;
          if(tile.key === 'robot') {
            var x1 = tile.isoPosition.x;
            var y1 = tile.isoPosition.y;
            var x2 = e.x; var y2 = e.y;

            var dist = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
            if(dist <= 250) {
              kaboom = game.add.isoSprite(tile.isoPosition.x-100, tile.isoPosition.y-20, 0,'kaboom',explosionGroup);
              kaboom.animations.add('kaboom', [1,2,3,4,5,6,7,8,9,10], 6, false);
              kaboom.animations.play('kaboom');
              explosions.push(kaboom);
              tile.destroy();
            }
          }
        });
        setTimeout(function() {
          for(var i = 0; i < explosions.length; ++i) {
            explosions[i].destroy();
          }
        }, 200);
      }, 200);

    }
  }

}).call(document);

<commit_msg>Added Explosion when player is near of explosion radio<commit_after>(function() {
  window.BasicGame.Level1 = function (game) { };

  var isoGroup,
    groundGroup,
    obstacleGroup,
    explosionGroup,
    player,
    theBomb,
    pip2;

  var map = [
    [10,1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1,11,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0,10, 1, 1, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [3, 1, 1, 1, 1, 1,13, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,12, 1, 4, 1, 1, 1, 5,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 1, 1, 1, 1, 1, 1,13, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2,],
    [2, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,13, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,],
    [12,1, 1, 1, 1, 1, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,13,],
  ];

  BasicGame.Level1.prototype ={
  preload: function () {
    // single images
    game.load.image('cube_', 'assets/cube.png');
    game.load.image('ground', 'assets/floor.png');
    game.load.image('wall1', 'assets/wall-y.png');
    game.load.image('wall2', 'assets/wall-x.png');
    game.load.image('wall3', 'assets/wall-t--y.png');
    game.load.image('wall4', 'assets/wall-t--x.png');
    game.load.image('wall5', 'assets/wall-t-py.png');
    game.load.image('wall6', 'assets/wall-t--x.png');
    game.load.image('wall7', 'assets/wall-tp-x.png');
    game.load.image('wall10', 'assets/wall-l-top.png');
    game.load.image('wall11', 'assets/wall-l-right.png');
    game.load.image('wall12', 'assets/wall-l-left.png');
    game.load.image('wall13', 'assets/wall-l-bottom.png');
    game.load.image('bomb', 'assets/bomb.png');
    game.load.image('letter_a', 'assets/letters/a.png');

    game.load.spritesheet('robot', 'assets/robot.png', 120, 80);
    game.load.spritesheet('kid', 'assets/girl.png', 130, 150);
    // sprites
    game.load.spritesheet('robot', 'assets/robot.png', 120, 80);
    game.load.spritesheet('kid', 'assets/kid.png', 130, 150);
    game.load.spritesheet('sonic-bomb', 'assets/sonic-bomb.png', 130, 116);
    game.load.spritesheet('kaboom', 'assets/explode.png', 128, 128);
    // audio
    game.load.audio('pip2', ['assets/pip2.ogg']);

    game.time.advancedTiming = true;

    // Add and enable the plug-in.
    game.plugins.add(new Phaser.Plugin.Isometric(game));

    // In order to have the camera move, we need to increase the size of our world bounds.
    game.world.setBounds(0, 0, 4096, 4096);

    // Start the IsoArcade physics system.
    game.physics.startSystem(Phaser.Plugin.Isometric.ISOARCADE);

    // In order to have the camera move, we need to increase the size of our world bounds.

    // This is used to set a game canvas-based offset for the 0, 0, 0 isometric coordinate - by default
    // this point would be at screen coordinates 0, 0 (top left) which is usually undesirable.
    game.iso.anchor.setTo(0.5, 0.1);
    game.iso.projectionAngle = 0.52359878;
  },

  create: function () {
    // Background color.
    game.stage.background = 0xB91717;
    // get explosion audio
    pip2 = game.add.audio('pip2');

    // Physics.
    game.physics.isoArcade.gravity.setTo(0, 0, -1000);

    groundGroup = game.add.group();
    obstacleGroup = game.add.group();
    explosionGroup = game.add.group();
    window.obstacleGroup = obstacleGroup;

    // Letters in the level.
    this.lettersGroup = game.add.group();
    var lettersTile = game.add.isoSprite(100, 100, 0, 'letter_a', 0, this.lettersGroup);
    lettersTile.anchor.set(0.5);

    var floorTile, i, j;
    for (var xt = 2048; xt > 0; xt -= 35) {
      for (var yt = 2048; yt > 0; yt -= 35) {
        floorTile = game.add.isoSprite(xt, yt, 0, 'ground', 0, groundGroup);
        floorTile.anchor.set(0.5);
      }
    }

    var a1;
    for(i = 0; i < map.length; ++i) {
      for(j = 0; j < map[i].length; ++j) {
        if (map[i][j] !== 0) {
          a1 = game.add.isoSprite(j*65, i*65, 0, 'wall' + map[i][j], 0, obstacleGroup);
          a1.anchor.set(0.5);
          game.physics.isoArcade.enable(a1);
          a1.body.collideWorldBounds = true;
          a1.body.immovable = true;
        }
      }
    }

    player = new Player(this, {
      x: 830, y: 600, z: 0, group: obstacleGroup, tint: 0x00ff00,
      onBombMounted: onBombMounted.bind(this),
      onExplosion: onExplosion.bind(this)
    });

    // Make the camera follow the player.
    game.camera.follow(player.get());

    // Set up our controls.
    this.cursors = game.input.keyboard.createCursorKeys();

    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      // Phaser.Keyboard.SPACEBAR
    ]);
    this.cursors.jump = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

    // Robots Creation
    this.robots = robotClass(this);
  },
  update: function () {
    // For show the position of the player ;)
    //console.log(player.get().body.velocity.x + ' - ' + player.get().body.velocity.y + ' - ' + player.get().body.velocity.z);

    // Move the player at this speed.
    var speed = 500;
    player.move(this.cursors, speed);

    // Our collision and sorting code again.
    game.physics.isoArcade.collide(obstacleGroup);
    game.iso.topologicalSort(obstacleGroup);

    this.lettersGroup.forEach( function (letter) {
      if(Math.abs(player.get().isoPosition.x - letter.isoPosition.x) < 70 &&
        Math.abs(player.get().isoPosition.y - letter.isoPosition.y) < 70) {
        letter.kill();
      }
    });

    animatePlayer(player.get(), this.cursors);

    //console.log(player.get().x);
    obstacleGroup.forEach( function (obstacle) {
      if(obstacle.key == 'robot') {
        animateRobots(obstacle);
        //console.log(Math.abs(player.get().isoPosition.x - obstacle.isoPosition.x));
        if(Math.abs(player.get().isoPosition.x - obstacle.isoPosition.x) < 70 &&
          Math.abs(player.get().isoPosition.y - obstacle.isoPosition.y) < 70) {
          game.state.start('Level1'); // :O
        }
      }
    });
  },
  render: function () {
  //   game.debug.text(game.time.fps || '--', 2, 14, "#a7aebe");
  //   groundGroup.forEach(function (tile) {
  //     game.debug.body(tile, 'rgba(255, 221, 235, 0.6)', false);
  //   });
  //   obstacleGroup.forEach(function (tile) {
  //     game.debug.body(tile, 'rgba(189, 221, 235, 0.6)', false);
  //   });
  }
};

  function onBombMounted(e) {
    console.log('mounted');
    theBomb = game.add.isoSprite(e.row*65, e.col*65, 0, 'sonic-bomb', 0, groundGroup);
    theBomb.anchor.set(0.5);

    theBomb.animations.add('bomb-sequence', [1,2,3,4], 6, true);
    theBomb.animations.play('bomb-sequence');
    pip2.play();
  }

  function onExplosion(e) {
    if(theBomb) {
      console.log('boom!!');
      var kaboom = game.add.isoSprite(theBomb.isoPosition.x-100, theBomb.isoPosition.y-20, 0,'kaboom',explosionGroup);
      kaboom.animations.add('kaboom', [1,2,3,4,5,6,7,8,9,10], 6, false);
      kaboom.animations.play('kaboom');
      setTimeout(function() {
        theBomb.destroy();
        kaboom.destroy();
        var explosions = [];
        obstacleGroup.forEach(function(tile) {
          if(!tile) return;
          if(tile.key === 'robot' || tile.key === 'kid') {
            var x1 = tile.isoPosition.x;
            var y1 = tile.isoPosition.y;
            var x2 = e.x; var y2 = e.y;

            var dist = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
            if(dist <= 250) {
              kaboom = game.add.isoSprite(tile.isoPosition.x-100, tile.isoPosition.y-20, 0,'kaboom',explosionGroup);
              kaboom.animations.add('kaboom', [1,2,3,4,5,6,7,8,9,10,11,12,13,14], 6, false);
              kaboom.animations.play('kaboom');
              explosions.push(kaboom);
              if(tile.key === 'kid') {
                setTimeout(function() {
                  game.state.start('Level1');
                }, 200);
              } else {
                tile.destroy();
              }
            }
          }
        });
        setTimeout(function() {
          for(var i = 0; i < explosions.length; ++i) {
            explosions[i].destroy();
          }
        }, 200);
      }, 200);

    }
  }

}).call(document);

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import classNames from 'classnames';

const propTypes = {
  children: PropTypes.node,
  type: PropTypes.string,
  size: PropTypes.string,
  state: PropTypes.string,
  tag: PropTypes.string,
  static: PropTypes.bool,
  addon: PropTypes.bool,
  className: PropTypes.string,
};

const defaultProps = {
  tag: 'p',
  type: 'text',
};

const Input = (props) => {
  const {
    className,
    type,
    size,
    state,
    tag,
    addon,
    static: staticInput,
    ...attributes,
  } = props;

  const checkInput = ['radio', 'checkbox'].indexOf(type) > -1;

  const fileInput = type === 'file';
  const textareaInput = type === 'textarea';
  const selectInput = type === 'select';
  let Tag = selectInput || textareaInput ? type : 'input';

  let formControlClass = 'form-control';

  if (staticInput) {
    formControlClass = `${formControlClass}-static`;
    Tag = tag;
  } else if (fileInput) {
    formControlClass = `${formControlClass}-file`;
  } else if (checkInput) {
    if (addon) {
      formControlClass = null;
    } else {
      formControlClass = 'form-check-input';
    }
  }

  const classes = classNames(
    className,
    state ? `form-control-${state}` : false,
    size ? `form-control-${size}` : false,
    formControlClass
  );

  if (Tag === 'input') {
    attributes.type = type;
  }

  return (
    <Tag {...attributes} className={classes} />
  );
};

Input.propTypes = propTypes;
Input.defaultProps = defaultProps;

export default Input;
<commit_msg>feat(Input): enable refs on Input components (#178)<commit_after>/* eslint react/prefer-stateless-function: 0 */

import React, { PropTypes } from 'react';
import classNames from 'classnames';

const propTypes = {
  children: PropTypes.node,
  type: PropTypes.string,
  size: PropTypes.string,
  state: PropTypes.string,
  tag: PropTypes.string,
  static: PropTypes.bool,
  addon: PropTypes.bool,
  className: PropTypes.string,
};

const defaultProps = {
  tag: 'p',
  type: 'text',
};

class Input extends React.Component {
  render() {
    const {
      className,
      type,
      size,
      state,
      tag,
      addon,
      static: staticInput,
      ...attributes,
    } = this.props;

    const checkInput = ['radio', 'checkbox'].indexOf(type) > -1;

    const fileInput = type === 'file';
    const textareaInput = type === 'textarea';
    const selectInput = type === 'select';
    let Tag = selectInput || textareaInput ? type : 'input';

    let formControlClass = 'form-control';

    if (staticInput) {
      formControlClass = `${formControlClass}-static`;
      Tag = tag;
    } else if (fileInput) {
      formControlClass = `${formControlClass}-file`;
    } else if (checkInput) {
      if (addon) {
        formControlClass = null;
      } else {
        formControlClass = 'form-check-input';
      }
    }

    const classes = classNames(
      className,
      state ? `form-control-${state}` : false,
      size ? `form-control-${size}` : false,
      formControlClass
    );

    if (Tag === 'input') {
      attributes.type = type;
    }

    return (
      <Tag {...attributes} className={classes} />
    );
  }
}

Input.propTypes = propTypes;
Input.defaultProps = defaultProps;

export default Input;
<|endoftext|>


<commit_before>var tl = require("vsts-task-lib");
var CodePushSdk = require("code-push");

// The main function to be executed.
function performPatchTask(accessKey, appName, deploymentName, label, description, isDisabled, isMandatory, rollout, appStoreVersion) {
    // If function arguments are provided (e.g. during test), use those, else, get user inputs provided by VSTS.
    var authType = tl.getInput("authType", false);
    if (authType === "AccessKey") {
        accessKey = tl.getInput("accessKey", true);
    } else if (authType === "ServiceEndpointCodePush" || authType === "ServiceEndpointHockeyApp") {
        var serviceAccount = tl.getEndpointAuthorization(tl.getInput(authType, true));
        accessKey = serviceAccount.parameters.password;
    }

    appName = appName || tl.getInput("appName", true);
    deploymentName = deploymentName || tl.getInput("deploymentName", true);
    label = label || tl.getInput("releaseLabel", false);
    description = description || tl.getInput("description", false);
    isDisabled = isDisabled || tl.getInput("isDisabled", false);
    isMandatory = isMandatory || tl.getInput("isMandatory", false);
    rollout = rollout || tl.getInput("rollout", false);
    appStoreVersion = appStoreVersion || tl.getInput("appStoreVersion", true);

    if (!accessKey) {
        console.error("Access key required");
        tl.setResult(1, "Access key required");
    }

    var codePushSdk = new CodePushSdk(accessKey);
    codePushSdk.patchRelease(
        appName, deploymentName, label,
        {
            label: (label === "latest" ? false : label),
            description: (description === "noChange" ? false : description),
            disabled: (isDisabled === "noChange" ? false : isDisabled),
            mandatory: (isMandatory === "noChange" ? false : isMandatory),
            rollout: (rollout === "noChange" ? null : parseInt(rollout.replace("%", ""))),
            targetBinaryVersion: (appStoreVersion === "noChange" ? false : appStoreVersion)
        })
        .done(function() {
            console.log("Successfully patched " + appName + " - " + deploymentName + " (" + label + ")");
        }, function(error) {
            tl.setResult(1, error.message);
            throw error;
        });
}

module.exports = {
    performPatchTask: performPatchTask
}

if (require.main === module) {
    // Only run the patch task if the script is being run directly, and not imported as a module (eg. during test)
    performPatchTask();
}
<commit_msg>fix patch task<commit_after>var tl = require("vsts-task-lib");
var CodePushSdk = require("code-push");

// The main function to be executed.
function performPatchTask(accessKey, appName, deploymentName, label, description, isDisabled, isMandatory, rollout, appStoreVersion) {
    // If function arguments are provided (e.g. during test), use those, else, get user inputs provided by VSTS.
    var authType = tl.getInput("authType", false);
    if (authType === "AccessKey") {
        accessKey = tl.getInput("accessKey", true);
    } else if (authType === "ServiceEndpointCodePush" || authType === "ServiceEndpointHockeyApp") {
        var serviceAccount = tl.getEndpointAuthorization(tl.getInput(authType, true));
        accessKey = serviceAccount.parameters.password;
    }

    appName = appName || tl.getInput("appName", true);
    deploymentName = deploymentName || tl.getInput("deploymentName", true);
    label = label || tl.getInput("releaseLabel", false);
    description = description || tl.getInput("description", false);
    isDisabled = isDisabled || tl.getInput("isDisabled", false);
    isMandatory = isMandatory || tl.getInput("isMandatory", false);
    rollout = rollout || tl.getInput("rollout", false);
    appStoreVersion = appStoreVersion || tl.getInput("appStoreVersion", true);

    if (!accessKey) {
        console.error("Access key required");
        tl.setResult(1, "Access key required");
    }

    var codePushSdk = new CodePushSdk(accessKey);
    codePushSdk.patchRelease(
        appName, deploymentName, (label === "latest" ? null : label),
        {
            description: (description === "noChange" ? null : description),
            disabled: (isDisabled === "noChange" ? null : isDisabled),
            mandatory: (isMandatory === "noChange" ? null : isMandatory),
            rollout: (rollout === "noChange" ? null : parseInt(rollout.replace("%", ""))),
            targetBinaryVersion: (appStoreVersion === "noChange" ? null : appStoreVersion)
        })
        .done(function() {
            console.log("Successfully patched " + appName + " - " + deploymentName + " (" + label + ")");
        }, function(error) {
            tl.setResult(1, error.message);
            throw error;
        });
}

module.exports = {
    performPatchTask: performPatchTask
}

if (require.main === module) {
    // Only run the patch task if the script is being run directly, and not imported as a module (eg. during test)
    performPatchTask();
}
<|endoftext|>


<commit_before>var helper = require("../../../test-helper");
var buster = require("buster");
var stdioLogger = require("buster-cli/lib/stdio-logger");
var assert = buster.assert;
var refute = buster.refute;
var browserRunner = helper.require("cli/runners/browser-runner");
var busterClient = require("buster-client").client;
var busterConfigExt = helper.require("config");
var busterPromise = require("buster-promise");
var remoteRunner = helper.require("test-runner/remote-runner");
var progressReporter = helper.require("test-runner/progress-reporter");
var reporters = require("buster-test").reporters;
var http = require("http");

buster.testCase("Browser runner", {
    setUp: function () {
        this.sessionPromise = busterPromise.create();
        this.client = { createSession: this.stub().returns(this.sessionPromise) };
        this.stub(busterClient, "create").returns(this.client);
        this.stub(busterConfigExt, "extendConfigurationGroup");
        this.options = { server: "http://127.0.0.1:1200" };
        this.runner = Object.create(browserRunner);

        var self = this;
        this.stdout = "";
        this.stderr = "";

        this.runner.logger = stdioLogger.create(
            { puts: function (msg) { self.stdout += msg + "\n"; } },
            { puts: function (msg) { self.stderr += msg + "\n"; } });
    },

    "should create client for configured location": function () {
        this.runner.run({ load: [] }, this.options);

        assert.calledWith(busterClient.create, "1200", "127.0.0.1");
    },

    "should extend configuration": function () {
        var config = { id: 42 };
        this.runner.run(config, this.options);

        assert.calledOnce(busterConfigExt.extendConfigurationGroup);
        assert.calledWith(busterConfigExt.extendConfigurationGroup, config);
    },

    "should create session using provided session configuration": function () {
        this.runner.run({ sessionConfig: { id: 41 } }, this.options);

        assert.calledOnce(this.client.createSession);
        assert.calledWith(this.client.createSession, { id: 41 });
    },

    "should be run with runSession": function () {
        this.stub(this.runner, "runSession");
        this.runner.run({ sessionConfig: { id: 41 } }, this.options);

        this.sessionPromise.resolve({ id: 47 });

        assert.calledOnce(this.runner.runSession);
        assert.calledOn(this.runner.runSession, this.runner);
        assert.calledWith(this.runner.runSession, { id: 47 });
    },

    "session": {
        setUp: function () {
            this.session = buster.eventEmitter.create();
            this.closePromise = busterPromise.create();
            this.session.close = this.stub().returns(this.closePromise);
            this.session.multicaster = buster.eventEmitter.create();

            this.emitSessionMessage = function (event, data) {
                this.session.emit(event, { data: data });
            };
        },

        "should listen for uncaught exceptions": function () {
            this.runner.runSession(this.session);

            this.emitSessionMessage("uncaughtException", { message: "Oh noes" });

            assert.match(this.stderr, "Uncaught exception:");
            assert.match(this.stderr, "Oh noes");
        },

        "should create remote runner": function () {
            this.spy(remoteRunner, "create");
            this.runner.runSession(this.session);

            assert.calledOnce(remoteRunner.create);
            assert.calledWith(remoteRunner.create, this.session.multicaster, {
                failOnNoAssertions: false
            });
        },

        "should create remote runner that fails on no assertions": function () {
            this.spy(remoteRunner, "create");
            this.runner.options = { failOnNoAssertions: true };
            this.runner.runSession(this.session);

            assert.calledWith(remoteRunner.create, this.session.multicaster, {
                failOnNoAssertions: true
            });
        },

        "should create progress reporter": function () {
            this.spy(progressReporter, "create");

            this.runner.runSession(this.session);

            assert.calledOnce(progressReporter.create);
            assert.match(progressReporter.create.args[0][0], {
                color: false, bright: false
            });
        },

        "progress reporter should respect color settings": function () {
            this.spy(progressReporter, "create");

            this.runner.options = { color: true, bright: true };
            this.runner.runSession(this.session);

            assert.match(progressReporter.create.args[0][0], {
                color: true, bright: true
            });
        },

        // Problem: The logger is unable to 'print' messages (i.e. without a
        // trailing newline. Need to modify stdio-logger
        "//should use logger as io backend for remote reporter": function () {
            this.spy(progressReporter, "create");

            this.runner.runSession(this.session);
            var io = progressReporter.create.args[0][0].io;
            io.print(".");
            io.print(".");
            io.puts(" OK!");

            assert.match(this.stdout, ".. OK!");
        },

        "should add client on progress reporter when client connects": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.stub(progressReporter, "addClient");

            this.runner.runSession(this.session);
            var client = { id: 42 };
            runner.emit("client:connect", client);

            assert.calledOnce(progressReporter.addClient);
            assert.calledWith(progressReporter.addClient, 42, client);
        },

        "should initialize reporter": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                color: false, bright: false, displayProgress: false
            });
        },

        "should initialize reporter with custom properties": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.options = { color: true, bright: true, displayProgress: true };
            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                color: true, bright: true, displayProgress: true
            });
        },

        "should build cwd from session server and root": function () {
            this.runner.server = { hostname: "localhost", port: 1111 };
            this.session.rootPath = "/aaa-bbb";
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                cwd: "http://localhost:1111/aaa-bbb/resources"
            });
        },

        "should build cwd from non-default session server and root": function () {
            this.runner.server = { hostname: "somewhere", port: 2524 };
            this.session.rootPath = "/aaa-ccc";
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                cwd: "http://somewhere:2524/aaa-ccc/resources"
            });
        },

        "should set number of contexts in package name": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.equals(reporters.xUnitConsole.create.returnValues[0].contextsInPackageName, 2);
        },

        "should set stackFilter.filters": function () {
            this.runner.runSession(this.session);

            assert.equals(buster.stackFilter.filters, ["/buster/bundle-"]);
        },

        "should close session on suite:end": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);

            this.runner.runSession(this.session);
            runner.emit("suite:end");

            assert.calledOnce(this.session.close);
        },

        "should print to stdout on succesful session close": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.closePromise.resolve();

            this.runner.runSession(this.session);
            var stdout = this.stdout;
            runner.emit("suite:end");

            refute.equals(this.stdout, stdout);
        },

        "should print to stderr on unsuccesful session close": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.closePromise.reject({ message: "Oops" });

            this.runner.runSession(this.session);
            var stderr = this.stderr;
            runner.emit("suite:end");
            console.log(this.stderr, stderr);
            refute.equals(this.stderr, stderr);
        }
    },

    "error handling": {
        setUp: function () {
            this.runner.run({ sessionConfig: { id: 41 } }, this.options);
        },

        "should print session creation error to stderr": function () {
            this.sessionPromise.reject({ id: 47 });

            assert.match(this.stderr, "Failed creating session");
        },

        "should print understandable error if server cannot be reached": function () {
            this.sessionPromise.reject(new Error("ECONNREFUSED, Connection refused"));

            assert.match(this.stderr, "Unable to connect to server");
            assert.match(this.stderr, "http://127.0.0.1:1200");
            assert.match(this.stderr, "Please make sure that buster-server is running");
        }
    }
});
<commit_msg>Update stdioLogger usage to new API<commit_after>var helper = require("../../../test-helper");
var buster = require("buster");
var stdioLogger = require("buster-cli/lib/stdio-logger");
var assert = buster.assert;
var refute = buster.refute;
var browserRunner = helper.require("cli/runners/browser-runner");
var busterClient = require("buster-client").client;
var busterConfigExt = helper.require("config");
var busterPromise = require("buster-promise");
var remoteRunner = helper.require("test-runner/remote-runner");
var progressReporter = helper.require("test-runner/progress-reporter");
var reporters = require("buster-test").reporters;
var http = require("http");

buster.testCase("Browser runner", {
    setUp: function () {
        this.sessionPromise = busterPromise.create();
        this.client = { createSession: this.stub().returns(this.sessionPromise) };
        this.stub(busterClient, "create").returns(this.client);
        this.stub(busterConfigExt, "extendConfigurationGroup");
        this.options = { server: "http://127.0.0.1:1200" };
        this.runner = Object.create(browserRunner);

        var self = this;
        this.stdout = "";
        this.stderr = "";

        this.runner.logger = stdioLogger(
            { write: function (msg) { self.stdout += msg; } },
            { write: function (msg) { self.stderr += msg; } });
    },

    "should create client for configured location": function () {
        this.runner.run({ load: [] }, this.options);

        assert.calledWith(busterClient.create, "1200", "127.0.0.1");
    },

    "should extend configuration": function () {
        var config = { id: 42 };
        this.runner.run(config, this.options);

        assert.calledOnce(busterConfigExt.extendConfigurationGroup);
        assert.calledWith(busterConfigExt.extendConfigurationGroup, config);
    },

    "should create session using provided session configuration": function () {
        this.runner.run({ sessionConfig: { id: 41 } }, this.options);

        assert.calledOnce(this.client.createSession);
        assert.calledWith(this.client.createSession, { id: 41 });
    },

    "should be run with runSession": function () {
        this.stub(this.runner, "runSession");
        this.runner.run({ sessionConfig: { id: 41 } }, this.options);

        this.sessionPromise.resolve({ id: 47 });

        assert.calledOnce(this.runner.runSession);
        assert.calledOn(this.runner.runSession, this.runner);
        assert.calledWith(this.runner.runSession, { id: 47 });
    },

    "session": {
        setUp: function () {
            this.session = buster.eventEmitter.create();
            this.closePromise = busterPromise.create();
            this.session.close = this.stub().returns(this.closePromise);
            this.session.multicaster = buster.eventEmitter.create();

            this.emitSessionMessage = function (event, data) {
                this.session.emit(event, { data: data });
            };
        },

        "should listen for uncaught exceptions": function () {
            this.runner.runSession(this.session);

            this.emitSessionMessage("uncaughtException", { message: "Oh noes" });

            assert.match(this.stderr, "Uncaught exception:");
            assert.match(this.stderr, "Oh noes");
        },

        "should create remote runner": function () {
            this.spy(remoteRunner, "create");
            this.runner.runSession(this.session);

            assert.calledOnce(remoteRunner.create);
            assert.calledWith(remoteRunner.create, this.session.multicaster, {
                failOnNoAssertions: false
            });
        },

        "should create remote runner that fails on no assertions": function () {
            this.spy(remoteRunner, "create");
            this.runner.options = { failOnNoAssertions: true };
            this.runner.runSession(this.session);

            assert.calledWith(remoteRunner.create, this.session.multicaster, {
                failOnNoAssertions: true
            });
        },

        "should create progress reporter": function () {
            this.spy(progressReporter, "create");

            this.runner.runSession(this.session);

            assert.calledOnce(progressReporter.create);
            assert.match(progressReporter.create.args[0][0], {
                color: false, bright: false
            });
        },

        "progress reporter should respect color settings": function () {
            this.spy(progressReporter, "create");

            this.runner.options = { color: true, bright: true };
            this.runner.runSession(this.session);

            assert.match(progressReporter.create.args[0][0], {
                color: true, bright: true
            });
        },

        // Problem: The logger is unable to 'print' messages (i.e. without a
        // trailing newline. Need to modify stdio-logger
        "//should use logger as io backend for remote reporter": function () {
            this.spy(progressReporter, "create");

            this.runner.runSession(this.session);
            var io = progressReporter.create.args[0][0].io;
            io.print(".");
            io.print(".");
            io.puts(" OK!");

            assert.match(this.stdout, ".. OK!");
        },

        "should add client on progress reporter when client connects": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.stub(progressReporter, "addClient");

            this.runner.runSession(this.session);
            var client = { id: 42 };
            runner.emit("client:connect", client);

            assert.calledOnce(progressReporter.addClient);
            assert.calledWith(progressReporter.addClient, 42, client);
        },

        "should initialize reporter": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                color: false, bright: false, displayProgress: false
            });
        },

        "should initialize reporter with custom properties": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.options = { color: true, bright: true, displayProgress: true };
            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                color: true, bright: true, displayProgress: true
            });
        },

        "should build cwd from session server and root": function () {
            this.runner.server = { hostname: "localhost", port: 1111 };
            this.session.rootPath = "/aaa-bbb";
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                cwd: "http://localhost:1111/aaa-bbb/resources"
            });
        },

        "should build cwd from non-default session server and root": function () {
            this.runner.server = { hostname: "somewhere", port: 2524 };
            this.session.rootPath = "/aaa-ccc";
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.match(reporters.xUnitConsole.create.args[0][0], {
                cwd: "http://somewhere:2524/aaa-ccc/resources"
            });
        },

        "should set number of contexts in package name": function () {
            this.spy(reporters.xUnitConsole, "create");

            this.runner.runSession(this.session);

            assert.equals(reporters.xUnitConsole.create.returnValues[0].contextsInPackageName, 2);
        },

        "should set stackFilter.filters": function () {
            this.runner.runSession(this.session);

            assert.equals(buster.stackFilter.filters, ["/buster/bundle-"]);
        },

        "should close session on suite:end": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);

            this.runner.runSession(this.session);
            runner.emit("suite:end");

            assert.calledOnce(this.session.close);
        },

        "should print to stdout on succesful session close": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.closePromise.resolve();

            this.runner.runSession(this.session);
            var stdout = this.stdout;
            runner.emit("suite:end");

            refute.equals(this.stdout, stdout);
        },

        "should print to stderr on unsuccesful session close": function () {
            var runner = buster.eventEmitter.create();
            this.stub(remoteRunner, "create").returns(runner);
            this.closePromise.reject({ message: "Oops" });

            this.runner.runSession(this.session);
            var stderr = this.stderr;
            runner.emit("suite:end");
            console.log(this.stderr, stderr);
            refute.equals(this.stderr, stderr);
        }
    },

    "error handling": {
        setUp: function () {
            this.runner.run({ sessionConfig: { id: 41 } }, this.options);
        },

        "should print session creation error to stderr": function () {
            this.sessionPromise.reject({ id: 47 });

            assert.match(this.stderr, "Failed creating session");
        },

        "should print understandable error if server cannot be reached": function () {
            this.sessionPromise.reject(new Error("ECONNREFUSED, Connection refused"));

            assert.match(this.stderr, "Unable to connect to server");
            assert.match(this.stderr, "http://127.0.0.1:1200");
            assert.match(this.stderr, "Please make sure that buster-server is running");
        }
    }
});
<|endoftext|>