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

const IPFS = require('ipfs')

// Node
const $nodeId = document.querySelector('.node-id')
const $nodeAddresses = document.querySelector('.node-addresses')
const $logs = document.querySelector('#logs')
// Peers
const $peers = document.querySelector('#peers')
const $peersList = $peers.querySelector('tbody')
const $multiaddrInput = document.querySelector('#multiaddr-input')
const $connectButton = document.querySelector('#peer-btn')
// Files
const $multihashInput = document.querySelector('#multihash-input')
const $fetchButton = document.querySelector('#fetch-btn')
const $dragContainer = document.querySelector('#drag-container')
const $progressBar = document.querySelector('#progress-bar')
const $fileHistory = document.querySelector('#file-history tbody')
const $emptyRow = document.querySelector('.empty-row')
// Misc
const $allDisabledButtons = document.querySelectorAll('button:disabled')
const $allDisabledInputs = document.querySelectorAll('input:disabled')
const $allDisabledElements = document.querySelectorAll('.disabled')

// Workspace inputs
const $workspaceInput = document.querySelector('#workspace-input')
const $workspaceBtn = document.querySelector('#workspace-btn')

let FILES = []
let workspace = location.hash

let fileSize = 0

let node
let info
let Buffer = IPFS.Buffer

/* ===========================================================================
   Start the IPFS node
   =========================================================================== */

function start () {
  if (!node) {
    const options = {
      EXPERIMENTAL: {
        pubsub: true
      },
      repo: 'ipfs-' + Math.random(),
      config: {
        Addresses: {
          Swarm: ['/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star']
        }
      }
    }

    node = new IPFS(options)

    node.once('start', () => {
      node.id()
        .then((id) => {
          info = id
          updateView('ready', node)
          onSuccess('Node is ready.')
          setInterval(refreshPeerList, 1000)
          setInterval(sendFileList, 10000)
        })
        .catch((error) => onError(error))

      subscribeToWorkpsace()

      window.addEventListener('hashchange', workspaceUpdated)
    })
  }
}

/* ===========================================================================
   Pubsub
   =========================================================================== */

const messageHandler = (message) => {
  const myNode = info.id
  const hash = message.data.toString()
  const messageSender = message.from

  // append new files when someone uploads them
  if (myNode !== messageSender && !isFileInList(hash)) {
    $multihashInput.value = hash
    getFile()
  }
}

const subscribeToWorkpsace = () => {
  node.pubsub.subscribe(workspace, messageHandler)
    .then(() => {
      const msg = `Subscribed to workspace ${workspace}`
      $logs.innerHTML = msg
    })
    .catch(() => onError('An error occurred when subscribing to the workspace.'))
}

// unsubscribe from old workspace and re-subscribe to new one
const workspaceUpdated = () => {
  node.pubsub.unsubscribe(workspace).then(() => {
    // clear files from old workspace
    FILES = []
    $fileHistory.innerHTML = ''

    workspace = location.hash
    subscribeToWorkpsace()
  })
}

const publishHash = (hash) => {
  const data = Buffer.from(hash)

  node.pubsub.publish(workspace, data)
    .catch(() => onError('An error occurred when publishing the message.'))
}

/* ===========================================================================
   Files handling
   =========================================================================== */

const isFileInList = (hash) => FILES.indexOf(hash) !== -1

const sendFileList = () => FILES.forEach((hash) => publishHash(hash))

const updateProgress = (bytesLoaded) => {
  let percent = 100 - ((bytesLoaded / fileSize) * 100)

  $progressBar.style.transform = `translateX(${-percent}%)`
}

const resetProgress = () => {
  $progressBar.style.transform = 'translateX(-100%)'
}

function appendFile (name, hash, size, data) {
  const file = new window.Blob([data], { type: 'application/octet-binary' })
  const url = window.URL.createObjectURL(file)
  const row = document.createElement('tr')

  const nameCell = document.createElement('td')
  nameCell.innerHTML = name

  const hashCell = document.createElement('td')
  hashCell.innerHTML = hash

  const sizeCell = document.createElement('td')
  sizeCell.innerText = size

  const downloadCell = document.createElement('td')
  const link = document.createElement('a')
  link.setAttribute('href', url)
  link.setAttribute('download', name)
  link.innerHTML = ''
  downloadCell.appendChild(link)

  row.appendChild(nameCell)
  row.appendChild(hashCell)
  row.appendChild(sizeCell)
  row.appendChild(downloadCell)

  $fileHistory.insertBefore(row, $fileHistory.firstChild)

  publishHash(hash)
}

function getFile () {
  const hash = $multihashInput.value

  $multihashInput.value = ''

  if (!hash) {
    return onError('No multihash was inserted.')
  } else if (isFileInList(hash)) {
    return onSuccess('The file is already in the current workspace.')
  }

  FILES.push(hash)

  node.get(hash)
    .then((files) => {
      files.forEach((file) => {
        if (file.content) {
          appendFile(file.name, hash, file.size, file.content)
          onSuccess(`The ${file.name} file was added.`)
          $emptyRow.style.display = 'none'
        }
      })
    })
    .catch(() => onError('An error occurred when fetching the files.'))
}

/* Drag & Drop
   =========================================================================== */

const onDragEnter = () => $dragContainer.classList.add('dragging')

const onDragLeave = () => $dragContainer.classList.remove('dragging')

function onDrop (event) {
  onDragLeave()
  event.preventDefault()

  const dt = event.dataTransfer
  const filesDropped = dt.files

  function readFileContents (file) {
    return new Promise((resolve) => {
      const reader = new window.FileReader()
      reader.onload = (event) => resolve(event.target.result)
      reader.readAsArrayBuffer(file)
    })
  }

  const files = []
  for (let i = 0; i < filesDropped.length; i++) {
    files.push(filesDropped[i])
  }

  files.forEach((file) => {
    readFileContents(file)
      .then((buffer) => {
        fileSize = file.size

        node.add({
          path: file.name,
          content: Buffer.from(buffer)
        }, { wrap: true, progress: updateProgress }, (err, filesAdded) => {
          if (err) {
            return onError(err)
          }

          // As we are wrapping the content we use that hash to keep
          // the original file name when adding it to the table
          $multihashInput.value = filesAdded[1].hash

          resetProgress()
          getFile()
        })
      })
      .catch(onError)
  })
}

/* ===========================================================================
   Peers handling
   =========================================================================== */

function connectToPeer (event) {
  const multiaddr = $multiaddrInput.value

  if (!multiaddr) {
    return onError('No multiaddr was inserted.')
  }

  node.swarm.connect(multiaddr)
    .then(() => {
      onSuccess(`Successfully connected to peer.`)
      $multiaddrInput.value = ''
    })
    .catch(() => onError('An error occurred when connecting to the peer.'))
}

function refreshPeerList () {
  node.swarm.peers()
    .then((peers) => {
      const peersAsHtml = peers.reverse()
        .map((peer) => {
          if (peer.addr) {
            const addr = peer.addr.toString()
            if (addr.indexOf('ipfs') >= 0) {
              return addr
            } else {
              return addr + peer.peer.id.toB58String()
            }
          }
        })
        .map((addr) => {
          return `<tr><td>${addr}</td></tr>`
        }).join('')

      $peersList.innerHTML = peersAsHtml
    })
    .catch((error) => onError(error))
}

/* ===========================================================================
   Error handling
   =========================================================================== */

function onSuccess (msg) {
  $logs.classList.add('success')
  $logs.innerHTML = msg
}

function onError (err) {
  let msg = 'An error occured, check the dev console'

  if (err.stack !== undefined) {
    msg = err.stack
  } else if (typeof err === 'string') {
    msg = err
  }

  $logs.classList.remove('success')
  $logs.innerHTML = msg
}

window.onerror = onError

/* ===========================================================================
   App states
   =========================================================================== */

const states = {
  ready: () => {
    const addressesHtml = info.addresses.map((address) => {
      return `<li><pre>${address}</pre></li>`
    }).join('')
    $nodeId.innerText = info.id
    $nodeAddresses.innerHTML = addressesHtml
    $allDisabledButtons.forEach(b => { b.disabled = false })
    $allDisabledInputs.forEach(b => { b.disabled = false })
    $allDisabledElements.forEach(el => { el.classList.remove('disabled') })
  }
}

function updateView (state, ipfs) {
  if (states[state] !== undefined) {
    states[state]()
  } else {
    throw new Error('Could not find state "' + state + '"')
  }
}

/* ===========================================================================
   Boot the app
   =========================================================================== */

const startApplication = () => {
  // Setup event listeners
  $dragContainer.addEventListener('dragenter', onDragEnter)
  $dragContainer.addEventListener('dragover', onDragEnter)
  $dragContainer.addEventListener('drop', onDrop)
  $dragContainer.addEventListener('dragleave', onDragLeave)
  $fetchButton.addEventListener('click', getFile)
  $connectButton.addEventListener('click', connectToPeer)
  $workspaceBtn.addEventListener('click', () => {
    window.location.hash = $workspaceInput.value
  })

  start()
}

startApplication()
<commit_msg>fix: update option in exchange files in browser example (#2087)<commit_after>/* global location */
'use strict'

const IPFS = require('ipfs')

// Node
const $nodeId = document.querySelector('.node-id')
const $nodeAddresses = document.querySelector('.node-addresses')
const $logs = document.querySelector('#logs')
// Peers
const $peers = document.querySelector('#peers')
const $peersList = $peers.querySelector('tbody')
const $multiaddrInput = document.querySelector('#multiaddr-input')
const $connectButton = document.querySelector('#peer-btn')
// Files
const $multihashInput = document.querySelector('#multihash-input')
const $fetchButton = document.querySelector('#fetch-btn')
const $dragContainer = document.querySelector('#drag-container')
const $progressBar = document.querySelector('#progress-bar')
const $fileHistory = document.querySelector('#file-history tbody')
const $emptyRow = document.querySelector('.empty-row')
// Misc
const $allDisabledButtons = document.querySelectorAll('button:disabled')
const $allDisabledInputs = document.querySelectorAll('input:disabled')
const $allDisabledElements = document.querySelectorAll('.disabled')

// Workspace inputs
const $workspaceInput = document.querySelector('#workspace-input')
const $workspaceBtn = document.querySelector('#workspace-btn')

let FILES = []
let workspace = location.hash

let fileSize = 0

let node
let info
let Buffer = IPFS.Buffer

/* ===========================================================================
   Start the IPFS node
   =========================================================================== */

function start () {
  if (!node) {
    const options = {
      EXPERIMENTAL: {
        pubsub: true
      },
      repo: 'ipfs-' + Math.random(),
      config: {
        Addresses: {
          Swarm: ['/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star']
        }
      }
    }

    node = new IPFS(options)

    node.once('start', () => {
      node.id()
        .then((id) => {
          info = id
          updateView('ready', node)
          onSuccess('Node is ready.')
          setInterval(refreshPeerList, 1000)
          setInterval(sendFileList, 10000)
        })
        .catch((error) => onError(error))

      subscribeToWorkpsace()

      window.addEventListener('hashchange', workspaceUpdated)
    })
  }
}

/* ===========================================================================
   Pubsub
   =========================================================================== */

const messageHandler = (message) => {
  const myNode = info.id
  const hash = message.data.toString()
  const messageSender = message.from

  // append new files when someone uploads them
  if (myNode !== messageSender && !isFileInList(hash)) {
    $multihashInput.value = hash
    getFile()
  }
}

const subscribeToWorkpsace = () => {
  node.pubsub.subscribe(workspace, messageHandler)
    .then(() => {
      const msg = `Subscribed to workspace ${workspace}`
      $logs.innerHTML = msg
    })
    .catch(() => onError('An error occurred when subscribing to the workspace.'))
}

// unsubscribe from old workspace and re-subscribe to new one
const workspaceUpdated = () => {
  node.pubsub.unsubscribe(workspace).then(() => {
    // clear files from old workspace
    FILES = []
    $fileHistory.innerHTML = ''

    workspace = location.hash
    subscribeToWorkpsace()
  })
}

const publishHash = (hash) => {
  const data = Buffer.from(hash)

  node.pubsub.publish(workspace, data)
    .catch(() => onError('An error occurred when publishing the message.'))
}

/* ===========================================================================
   Files handling
   =========================================================================== */

const isFileInList = (hash) => FILES.indexOf(hash) !== -1

const sendFileList = () => FILES.forEach((hash) => publishHash(hash))

const updateProgress = (bytesLoaded) => {
  let percent = 100 - ((bytesLoaded / fileSize) * 100)

  $progressBar.style.transform = `translateX(${-percent}%)`
}

const resetProgress = () => {
  $progressBar.style.transform = 'translateX(-100%)'
}

function appendFile (name, hash, size, data) {
  const file = new window.Blob([data], { type: 'application/octet-binary' })
  const url = window.URL.createObjectURL(file)
  const row = document.createElement('tr')

  const nameCell = document.createElement('td')
  nameCell.innerHTML = name

  const hashCell = document.createElement('td')
  hashCell.innerHTML = hash

  const sizeCell = document.createElement('td')
  sizeCell.innerText = size

  const downloadCell = document.createElement('td')
  const link = document.createElement('a')
  link.setAttribute('href', url)
  link.setAttribute('download', name)
  link.innerHTML = ''
  downloadCell.appendChild(link)

  row.appendChild(nameCell)
  row.appendChild(hashCell)
  row.appendChild(sizeCell)
  row.appendChild(downloadCell)

  $fileHistory.insertBefore(row, $fileHistory.firstChild)

  publishHash(hash)
}

function getFile () {
  const hash = $multihashInput.value

  $multihashInput.value = ''

  if (!hash) {
    return onError('No multihash was inserted.')
  } else if (isFileInList(hash)) {
    return onSuccess('The file is already in the current workspace.')
  }

  FILES.push(hash)

  node.get(hash)
    .then((files) => {
      files.forEach((file) => {
        if (file.content) {
          appendFile(file.name, hash, file.size, file.content)
          onSuccess(`The ${file.name} file was added.`)
          $emptyRow.style.display = 'none'
        }
      })
    })
    .catch(() => onError('An error occurred when fetching the files.'))
}

/* Drag & Drop
   =========================================================================== */

const onDragEnter = () => $dragContainer.classList.add('dragging')

const onDragLeave = () => $dragContainer.classList.remove('dragging')

function onDrop (event) {
  onDragLeave()
  event.preventDefault()

  const dt = event.dataTransfer
  const filesDropped = dt.files

  function readFileContents (file) {
    return new Promise((resolve) => {
      const reader = new window.FileReader()
      reader.onload = (event) => resolve(event.target.result)
      reader.readAsArrayBuffer(file)
    })
  }

  const files = []
  for (let i = 0; i < filesDropped.length; i++) {
    files.push(filesDropped[i])
  }

  files.forEach((file) => {
    readFileContents(file)
      .then((buffer) => {
        fileSize = file.size

        node.add({
          path: file.name,
          content: Buffer.from(buffer)
        }, { wrapWithDirectory: true, progress: updateProgress }, (err, filesAdded) => {
          if (err) {
            return onError(err)
          }

          // As we are wrapping the content we use that hash to keep
          // the original file name when adding it to the table
          $multihashInput.value = filesAdded[1].hash

          resetProgress()
          getFile()
        })
      })
      .catch(onError)
  })
}

/* ===========================================================================
   Peers handling
   =========================================================================== */

function connectToPeer (event) {
  const multiaddr = $multiaddrInput.value

  if (!multiaddr) {
    return onError('No multiaddr was inserted.')
  }

  node.swarm.connect(multiaddr)
    .then(() => {
      onSuccess(`Successfully connected to peer.`)
      $multiaddrInput.value = ''
    })
    .catch(() => onError('An error occurred when connecting to the peer.'))
}

function refreshPeerList () {
  node.swarm.peers()
    .then((peers) => {
      const peersAsHtml = peers.reverse()
        .map((peer) => {
          if (peer.addr) {
            const addr = peer.addr.toString()
            if (addr.indexOf('ipfs') >= 0) {
              return addr
            } else {
              return addr + peer.peer.id.toB58String()
            }
          }
        })
        .map((addr) => {
          return `<tr><td>${addr}</td></tr>`
        }).join('')

      $peersList.innerHTML = peersAsHtml
    })
    .catch((error) => onError(error))
}

/* ===========================================================================
   Error handling
   =========================================================================== */

function onSuccess (msg) {
  $logs.classList.add('success')
  $logs.innerHTML = msg
}

function onError (err) {
  let msg = 'An error occured, check the dev console'

  if (err.stack !== undefined) {
    msg = err.stack
  } else if (typeof err === 'string') {
    msg = err
  }

  $logs.classList.remove('success')
  $logs.innerHTML = msg
}

window.onerror = onError

/* ===========================================================================
   App states
   =========================================================================== */

const states = {
  ready: () => {
    const addressesHtml = info.addresses.map((address) => {
      return `<li><pre>${address}</pre></li>`
    }).join('')
    $nodeId.innerText = info.id
    $nodeAddresses.innerHTML = addressesHtml
    $allDisabledButtons.forEach(b => { b.disabled = false })
    $allDisabledInputs.forEach(b => { b.disabled = false })
    $allDisabledElements.forEach(el => { el.classList.remove('disabled') })
  }
}

function updateView (state, ipfs) {
  if (states[state] !== undefined) {
    states[state]()
  } else {
    throw new Error('Could not find state "' + state + '"')
  }
}

/* ===========================================================================
   Boot the app
   =========================================================================== */

const startApplication = () => {
  // Setup event listeners
  $dragContainer.addEventListener('dragenter', onDragEnter)
  $dragContainer.addEventListener('dragover', onDragEnter)
  $dragContainer.addEventListener('drop', onDrop)
  $dragContainer.addEventListener('dragleave', onDragLeave)
  $fetchButton.addEventListener('click', getFile)
  $connectButton.addEventListener('click', connectToPeer)
  $workspaceBtn.addEventListener('click', () => {
    window.location.hash = $workspaceInput.value
  })

  start()
}

startApplication()
<|endoftext|>


<commit_before>/*
 * One Controller per layout view
 */

const express = require('express');

const router = express.Router();
const moment = require('moment');
const authHelper = require('../helpers/authentication');
const api = require('../api');

moment.locale('de');
const recurringEventsHelper = require('../helpers/recurringEvents');

// secure routes
router.use(authHelper.authChecker);

router.get('/', (req, res, next) => {
	// we display time from 7 a.m. to 5 p.m.
	const timeStart = 7;
	const timeEnd = 17;
	const numHours = timeEnd - timeStart;
	const numMinutes = numHours * 60;
	const hours = [];

	for (let j = 0; j <= numHours; j += 1) {
		hours.push(j + timeStart);
	}
	const start = new Date();
	start.setUTCHours(timeStart, 0, 0, 0);
	const end = new Date();
	end.setUTCHours(timeEnd, 0, 0, 0);

	const currentTime = new Date();
	// eslint-disable-next-line max-len
	let currentTimePercentage = 100 * (((currentTime.getHours() - timeStart) * 60) + currentTime.getMinutes()) / numMinutes;
	if (currentTimePercentage < 0) currentTimePercentage = 0;
	else if (currentTimePercentage > 100) currentTimePercentage = 100;

	const eventsPromise = api(req).get('/calendar/', {
		qs: {
			all: true,
			until: end.toLocalISOString(),
		},
	}).then(eve => Promise.all(
		eve.map(event => recurringEventsHelper.mapEventProps(event, req)),
	).then((evnts) => {
		// because the calender service is *§$" and is not
		// returning recurring events for a given time period
		// now we have to load all events from the beginning of time
		// until end of the current day, map recurring events and
		// display only the correct ones.
		// I'm not happy with the solution but don't see any other less
		// crappy way for this without changing the
		// calendar service in it's core.
		const mappedEvents = evnts.map(recurringEventsHelper.mapRecurringEvent);
		const flatEvents = [].concat(...mappedEvents);
		const events = flatEvents.filter((event) => {
			const eventStart = new Date(event.start);
			const eventEnd = new Date(event.end);

			return eventStart < end && eventEnd > start;
		});

		return (events || []).map((event) => {
			const eventStart = new Date(event.start);
			let eventEnd = new Date(event.end);

			// cur events that are too long
			if (eventEnd > end) {
				eventEnd = end;
				event.end = eventEnd.toLocalISOString();
			}

			// subtract timeStart so we can use these values for left alignment
			const eventStartRelativeMinutes = ((eventStart.getUTCHours() - timeStart) * 60) + eventStart.getMinutes();
			const eventEndRelativeMinutes = ((eventEnd.getUTCHours() - timeStart) * 60) + eventEnd.getMinutes();
			const eventDuration = eventEndRelativeMinutes - eventStartRelativeMinutes;

			event.comment = `${moment.utc(eventStart).format('kk:mm')} - ${moment.utc(eventEnd).format('kk:mm')}`;
			event.style = {
				left: 100 * (eventStartRelativeMinutes / numMinutes), // percent
				width: 100 * (eventDuration / numMinutes), // percent
			};

			return event;
		});
	})).catch(() => []);

	const homeworksPromise = api(req).get('/homework/', {
		qs: {
			$populate: ['courseId'],
			$sort: 'dueDate',
			archived: { $ne: res.locals.currentUser._id },
			$or: [
				{
					dueDate: null,
				},
				{
					dueDate: {
						$gte: new Date().getTime(),
						$lte: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
					},
				},
			],
		},
	}).then(data => data.data.map((homeworks) => {
		homeworks.secondaryTitle = (homeworks.dueDate)
			? moment(homeworks.dueDate).fromNow()
			: 'Kein Abgabedatum festgelegt';
		if (homeworks.courseId != null) {
			homeworks.title = `[${homeworks.courseId.name}] ${homeworks.name}`;
			homeworks.background = homeworks.courseId.color;
		} else {
			homeworks.title = homeworks.name;
			homeworks.private = true;
		}
		homeworks.url = `/homework/${homeworks._id}`;
		homeworks.content = homeworks.description;
		return homeworks;
	}));

	function sortFunction(a, b) {
		if (a.displayAt === b.displayAt) {
			return 0;
		}

		return (a.displayAt < b.displayAt) ? 1 : -1;
	}
	// Somehow $lte doesn't work in normal query so I manually put it into a request
	const newsPromise = api(req).get('/news/', {
		qs: {
			schoolId: res.locals.currentSchool,
			displayAt: {
				$lte: new Date().getTime(),
			},
		},
	}).then(news => news.data.map((n) => {
		n.url = `/news/${n._id}`;
		n.secondaryTitle = moment(n.displayAt).fromNow();
		return n;
	}).sort(sortFunction).slice(0, 3));

	const newestReleasePromise = api(req).get('/releases', {
		qs: {
			$limit: 1,
			$sort: {
				createdAt: -1,
			},
		},
	}).then(({ data }) => data);

	Promise.all([
		eventsPromise,
		homeworksPromise,
		newsPromise,
		newestReleasePromise,
	]).then(([events, homeworks, news, newestReleases]) => {
		homeworks.sort((a, b) => {
			if (a.dueDate > b.dueDate || !a.dueDate) {
				return 1;
			}
			return -1;
		});

		const user = res.locals.currentUser || {};
		const userPreferences = user.preferences || {};
		const newestRelease = newestReleases[0] || {};
		const newRelease = !!(Date.parse(userPreferences.releaseDate) < Date.parse(newestRelease.createdAt));

		if (newRelease || !userPreferences.releaseDate) {
			api(req).patch(`/users/${user._id}`, {
				json: { 'preferences.releaseDate': newestRelease.createdAt },
			}).catch(() => {});
		}

		res.render('dashboard/dashboard', {
			title: 'Übersicht',
			events: events.reverse(),
			eventsDate: moment().format('dddd, DD. MMMM YYYY'),
			homeworks: homeworks.filter(task => !task.private).slice(0, 4),
			myhomeworks: homeworks.filter(task => task.private).slice(0, 4),
			news,
			hours,
			currentTimePercentage,
			showNewReleaseModal: newRelease,
			currentTime: moment(currentTime).format('HH:mm'),
		});
	});
});

module.exports = router;
<commit_msg>only request the day<commit_after>/*
 * One Controller per layout view
 */

const express = require('express');

const router = express.Router();
const moment = require('moment');
const authHelper = require('../helpers/authentication');
const api = require('../api');

moment.locale('de');
const recurringEventsHelper = require('../helpers/recurringEvents');

// secure routes
router.use(authHelper.authChecker);

router.get('/', (req, res, next) => {
	// we display time from 7 a.m. to 5 p.m.
	const timeStart = 7;
	const timeEnd = 17;
	const numHours = timeEnd - timeStart;
	const numMinutes = numHours * 60;
	const hours = [];

	for (let j = 0; j <= numHours; j += 1) {
		hours.push(j + timeStart);
	}
	const start = new Date();
	start.setUTCHours(timeStart, 0, 0, 0);
	const end = new Date();
	end.setUTCHours(timeEnd, 0, 0, 0);

	const currentTime = new Date();
	// eslint-disable-next-line max-len
	let currentTimePercentage = 100 * (((currentTime.getHours() - timeStart) * 60) + currentTime.getMinutes()) / numMinutes;
	if (currentTimePercentage < 0) currentTimePercentage = 0;
	else if (currentTimePercentage > 100) currentTimePercentage = 100;

	const eventsPromise = api(req).get('/calendar/', {
		qs: {
			all: 'false',
			from: start.toLocalISOString(),
			until: end.toLocalISOString(),
		},
	}).then(eve => Promise.all(
		eve.map(event => recurringEventsHelper.mapEventProps(event, req)),
	).then((evnts) => {
		// because the calender service is *§$" and is not
		// returning recurring events for a given time period
		// now we have to load all events from the beginning of time
		// until end of the current day, map recurring events and
		// display only the correct ones.
		// I'm not happy with the solution but don't see any other less
		// crappy way for this without changing the
		// calendar service in it's core.
		const mappedEvents = evnts.map(recurringEventsHelper.mapRecurringEvent);
		const flatEvents = [].concat(...mappedEvents);
		const events = flatEvents.filter((event) => {
			const eventStart = new Date(event.start);
			const eventEnd = new Date(event.end);

			return eventStart < end && eventEnd > start;
		});

		return (events || []).map((event) => {
			const eventStart = new Date(event.start);
			let eventEnd = new Date(event.end);

			// cur events that are too long
			if (eventEnd > end) {
				eventEnd = end;
				event.end = eventEnd.toLocalISOString();
			}

			// subtract timeStart so we can use these values for left alignment
			const eventStartRelativeMinutes = ((eventStart.getUTCHours() - timeStart) * 60) + eventStart.getMinutes();
			const eventEndRelativeMinutes = ((eventEnd.getUTCHours() - timeStart) * 60) + eventEnd.getMinutes();
			const eventDuration = eventEndRelativeMinutes - eventStartRelativeMinutes;

			event.comment = `${moment.utc(eventStart).format('kk:mm')} - ${moment.utc(eventEnd).format('kk:mm')}`;
			event.style = {
				left: 100 * (eventStartRelativeMinutes / numMinutes), // percent
				width: 100 * (eventDuration / numMinutes), // percent
			};

			return event;
		});
	})).catch(() => []);

	const homeworksPromise = api(req).get('/homework/', {
		qs: {
			$populate: ['courseId'],
			$sort: 'dueDate',
			archived: { $ne: res.locals.currentUser._id },
			$or: [
				{
					dueDate: null,
				},
				{
					dueDate: {
						$gte: new Date().getTime(),
						$lte: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
					},
				},
			],
		},
	}).then(data => data.data.map((homeworks) => {
		homeworks.secondaryTitle = (homeworks.dueDate)
			? moment(homeworks.dueDate).fromNow()
			: 'Kein Abgabedatum festgelegt';
		if (homeworks.courseId != null) {
			homeworks.title = `[${homeworks.courseId.name}] ${homeworks.name}`;
			homeworks.background = homeworks.courseId.color;
		} else {
			homeworks.title = homeworks.name;
			homeworks.private = true;
		}
		homeworks.url = `/homework/${homeworks._id}`;
		homeworks.content = homeworks.description;
		return homeworks;
	}));

	function sortFunction(a, b) {
		if (a.displayAt === b.displayAt) {
			return 0;
		}

		return (a.displayAt < b.displayAt) ? 1 : -1;
	}
	// Somehow $lte doesn't work in normal query so I manually put it into a request
	const newsPromise = api(req).get('/news/', {
		qs: {
			schoolId: res.locals.currentSchool,
			displayAt: {
				$lte: new Date().getTime(),
			},
		},
	}).then(news => news.data.map((n) => {
		n.url = `/news/${n._id}`;
		n.secondaryTitle = moment(n.displayAt).fromNow();
		return n;
	}).sort(sortFunction).slice(0, 3));

	const newestReleasePromise = api(req).get('/releases', {
		qs: {
			$limit: 1,
			$sort: {
				createdAt: -1,
			},
		},
	}).then(({ data }) => data);

	Promise.all([
		eventsPromise,
		homeworksPromise,
		newsPromise,
		newestReleasePromise,
	]).then(([events, homeworks, news, newestReleases]) => {
		homeworks.sort((a, b) => {
			if (a.dueDate > b.dueDate || !a.dueDate) {
				return 1;
			}
			return -1;
		});

		const user = res.locals.currentUser || {};
		const userPreferences = user.preferences || {};
		const newestRelease = newestReleases[0] || {};
		const newRelease = !!(Date.parse(userPreferences.releaseDate) < Date.parse(newestRelease.createdAt));

		if (newRelease || !userPreferences.releaseDate) {
			api(req).patch(`/users/${user._id}`, {
				json: { 'preferences.releaseDate': newestRelease.createdAt },
			}).catch(() => {});
		}

		res.render('dashboard/dashboard', {
			title: 'Übersicht',
			events: events.reverse(),
			eventsDate: moment().format('dddd, DD. MMMM YYYY'),
			homeworks: homeworks.filter(task => !task.private).slice(0, 4),
			myhomeworks: homeworks.filter(task => task.private).slice(0, 4),
			news,
			hours,
			currentTimePercentage,
			showNewReleaseModal: newRelease,
			currentTime: moment(currentTime).format('HH:mm'),
		});
	});
});

module.exports = router;
<|endoftext|>


<commit_before>describe('The draw tool component', function () {
    let $compile,
        $rootScope,
        drawTool,
        store,
        ACTIONS,
        state,
        polygon,
        map,
        onFinishShape,
        onDrawingMode;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                store: {
                    dispatch: angular.noop
                },
                drawTool: {
                    initialize: (aMap, onFinish, onMode) => {
                        onFinishShape = onFinish;
                        onDrawingMode = onMode;
                    },
                    setPolygon: angular.noop,
                    isEnabled: angular.noop,
                    enable: angular.noop,
                    disable: angular.noop
                }
            });

        state = {};
        polygon = {
            markers: []
        };
        map = {};

        angular.mock.inject(function (_$compile_, _$rootScope_, _drawTool_, _store_, _ACTIONS_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            drawTool = _drawTool_;
            store = _store_;
            ACTIONS = _ACTIONS_;
        });
    });

    function getComponent () {
        let element = document.createElement('dp-draw-tool');
        element.setAttribute('state', 'state');
        element.setAttribute('polygon', 'polygon');
        element.setAttribute('map', 'map');

        let scope = $rootScope.$new();
        scope.state = state;
        scope.polygon = polygon;
        scope.map = map;

        let component = $compile(element)(scope);
        scope.$apply();

        return component;
    }

    describe('The state parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'enable');
            spyOn(drawTool, 'disable');
        });

        it('Uses this parameter to follow drawing mode, default is disable', function () {
            getComponent();
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).toHaveBeenCalled();
        });

        it('Uses this parameter to follow drawing mode disable', function () {
            getComponent();
            $rootScope.$digest();

            drawTool.enable.calls.reset();
            drawTool.disable.calls.reset();

            state.drawingMode = null;
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).toHaveBeenCalled();
        });

        it('Uses this parameter to follow drawing mode, not for enable', function () {
            getComponent();
            $rootScope.$digest();

            drawTool.enable.calls.reset();
            drawTool.disable.calls.reset();

            state.drawingMode = 'DRAW';
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).not.toHaveBeenCalled();
        });
    });

    describe('The map parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'initialize');
        });

        it('Uses this parameter to initialise the draw tool factory', function () {
            map = {
                aap: 'noot'
            };

            getComponent();
            expect(drawTool.initialize).toHaveBeenCalledWith(map, jasmine.any(Function), jasmine.any(Function));
        });
    });

    describe('The polygon parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'setPolygon');
            spyOn(drawTool, 'enable');
            spyOn(drawTool, 'disable');
        });

        it('Informs the draw tool factory of any changes', function () {
            getComponent();

            spyOn(drawTool, 'isEnabled').and.returnValue(false);
            polygon.markers = ['aap'];
            $rootScope.$digest();

            expect(drawTool.setPolygon).toHaveBeenCalledWith(polygon.markers);
        });

        it('Does not informs the draw tool factory when drawing mode is enabled', function () {
            spyOn(drawTool, 'isEnabled').and.returnValue(true);

            getComponent();
            polygon.markers = ['aap'];
            $rootScope.$digest();

            expect(drawTool.setPolygon).not.toHaveBeenCalled();
        });

        it('Does enable drawing mode when state drawing mode is enabled', function () {
            spyOn(drawTool, 'isEnabled').and.returnValue(false);

            getComponent();
            polygon.markers = ['aap'];
            state.drawingMode = 'DRAW';
            $rootScope.$digest();

            expect(drawTool.setPolygon).toHaveBeenCalled();
            expect(drawTool.enable).toHaveBeenCalled();
        });
    });

    describe('The dispatched actions', function () {
        beforeEach(function () {
            spyOn(store, 'dispatch');
        });

        it('dispatches a MAP_END_DRAWING action when a polygon is finished drawing or editing', function () {
            polygon.markers = ['aap'];
            getComponent();
            onFinishShape(polygon);
            expect(store.dispatch).toHaveBeenCalledWith({
                type: ACTIONS.MAP_END_DRAWING,
                payload: {
                    geometryFilter: polygon.markers
                }
            });
        });

        it('Dispatches a MAP_START_DRAWING action when the drawing or editing a polygon starts', function () {
            getComponent();
            let drawingMode = 'aap';
            onDrawingMode(drawingMode);
            expect(store.dispatch).toHaveBeenCalledWith({
                type: ACTIONS.MAP_START_DRAWING,
                payload: {
                    drawingMode
                }
            });
        });

        it('Does not dispatch a MAP_START_DRAWING action when the drawing or editing has finished', function () {
            getComponent();
            let drawingMode = null;
            onDrawingMode(drawingMode);
            expect(store.dispatch).not.toHaveBeenCalled();
        });
    });
});
<commit_msg>map coverage<commit_after>describe('The draw tool component', function () {
    let $compile,
        $rootScope,
        drawTool,
        store,
        ACTIONS,
        state,
        polygon,
        map,
        onFinishShape,
        onDrawingMode;

    beforeEach(function () {
        angular.mock.module(
            'dpMap',
            {
                store: {
                    dispatch: angular.noop
                },
                drawTool: {
                    initialize: (aMap, onFinish, onMode) => {
                        onFinishShape = onFinish;
                        onDrawingMode = onMode;
                    },
                    setPolygon: angular.noop,
                    isEnabled: angular.noop,
                    enable: angular.noop,
                    disable: angular.noop,
                    shape: {
                        distanceTxt: 'distance',
                        areaTxt: 'area'
                    }
                }
            });

        state = {};
        polygon = {
            markers: []
        };
        map = {};

        angular.mock.inject(function (_$compile_, _$rootScope_, _drawTool_, _store_, _ACTIONS_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
            drawTool = _drawTool_;
            store = _store_;
            ACTIONS = _ACTIONS_;
        });
    });

    function getComponent () {
        let element = document.createElement('dp-draw-tool');
        element.setAttribute('state', 'state');
        element.setAttribute('polygon', 'polygon');
        element.setAttribute('map', 'map');

        let scope = $rootScope.$new();
        scope.state = state;
        scope.polygon = polygon;
        scope.map = map;

        let component = $compile(element)(scope);
        scope.$apply();

        return component;
    }

    describe('The state parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'enable');
            spyOn(drawTool, 'disable');
        });

        it('Uses this parameter to follow drawing mode, default is disable', function () {
            getComponent();
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).toHaveBeenCalled();
        });

        it('Uses this parameter to follow drawing mode disable', function () {
            getComponent();
            $rootScope.$digest();

            drawTool.enable.calls.reset();
            drawTool.disable.calls.reset();

            state.drawingMode = null;
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).toHaveBeenCalled();
        });

        it('Uses this parameter to follow drawing mode, not for enable', function () {
            getComponent();
            $rootScope.$digest();

            drawTool.enable.calls.reset();
            drawTool.disable.calls.reset();

            state.drawingMode = 'DRAW';
            $rootScope.$digest();

            expect(drawTool.enable).not.toHaveBeenCalled();
            expect(drawTool.disable).not.toHaveBeenCalled();
        });
    });

    describe('The map parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'initialize');
        });

        it('Uses this parameter to initialise the draw tool factory', function () {
            map = {
                aap: 'noot'
            };

            getComponent();
            expect(drawTool.initialize).toHaveBeenCalledWith(map, jasmine.any(Function), jasmine.any(Function));
        });
    });

    describe('The polygon parameter', function () {
        beforeEach(function () {
            spyOn(drawTool, 'setPolygon');
            spyOn(drawTool, 'enable');
            spyOn(drawTool, 'disable');
        });

        it('Informs the draw tool factory of any changes', function () {
            getComponent();

            spyOn(drawTool, 'isEnabled').and.returnValue(false);
            polygon.markers = ['aap'];
            $rootScope.$digest();

            expect(drawTool.setPolygon).toHaveBeenCalledWith(polygon.markers);
        });

        it('Does not informs the draw tool factory when drawing mode is enabled', function () {
            spyOn(drawTool, 'isEnabled').and.returnValue(true);

            getComponent();
            polygon.markers = ['aap'];
            $rootScope.$digest();

            expect(drawTool.setPolygon).not.toHaveBeenCalled();
        });

        it('Does enable drawing mode when state drawing mode is enabled', function () {
            spyOn(drawTool, 'isEnabled').and.returnValue(false);

            getComponent();
            polygon.markers = ['aap'];
            state.drawingMode = 'DRAW';
            $rootScope.$digest();

            expect(drawTool.setPolygon).toHaveBeenCalled();
            expect(drawTool.enable).toHaveBeenCalled();
        });
    });

    describe('The dispatched actions', function () {
        beforeEach(function () {
            spyOn(store, 'dispatch');
        });

        it('dispatches a MAP_END_DRAWING action when a polygon is finished drawing or editing', function () {
            polygon.markers = ['aap'];
            getComponent();
            onFinishShape(polygon);
            expect(store.dispatch).toHaveBeenCalledWith({
                type: ACTIONS.MAP_END_DRAWING,
                payload: {
                    geometryFilter: polygon.markers,
                    geometryFilterDescription: 'distance, area'
                }
            });
        });

        it('Dispatches a MAP_START_DRAWING action when the drawing or editing a polygon starts', function () {
            getComponent();
            let drawingMode = 'aap';
            onDrawingMode(drawingMode);
            expect(store.dispatch).toHaveBeenCalledWith({
                type: ACTIONS.MAP_START_DRAWING,
                payload: {
                    drawingMode
                }
            });
        });

        it('Does not dispatch a MAP_START_DRAWING action when the drawing or editing has finished', function () {
            getComponent();
            let drawingMode = null;
            onDrawingMode(drawingMode);
            expect(store.dispatch).not.toHaveBeenCalled();
        });
    });
});
<|endoftext|>


<commit_before>const Phaser = require('./Phaser')
const Brain = require('./Brain')

class Animal {
  constructor (x, y, parent) {
    this.health = game.math.between(100, 150)
    this.age = 0
    this.score = 0
    this.generation = parent ? parent.generation + 1 : 1

    this.sprite = game.add.sprite(game.TILE_SIZE * (x + 0.5), game.TILE_SIZE * (y + 0.5), game.cache.getBitmapData('animal' + this.health))
    game.physics.enable(this.sprite, Phaser.Physics.ARCADE)
    this.sprite.body.setCircle(game.TILE_SIZE / 2)
    this.sprite.body.collideWorldBounds = true
    this.sprite.anchor.setTo(0.5, 0.5)
    this.updateColor()

    // Back-reference for collision handling based on sprites.
    this.sprite.animal = this

    this.sprite.angle = game.math.between(-180, 180)
    game.physics.arcade.velocityFromAngle(this.sprite.angle, game.math.between(10, 200), this.sprite.body.velocity)

    this.brain = parent ? new Brain(parent.brain) : new Brain(7, 10, 10, 3)
  }

  tick (tile) {
    this.health -= 2 + Math.sqrt(this.age * 0.01)
    this.age += 0.01

    let amountEating = 0

    if (tile.food >= 5) amountEating = 4
    else amountEating = tile.food

    if ((255 - this.health) < amountEating) amountEating = 255 - this.health

    if (amountEating) {
      this.health += amountEating
      this.score += amountEating
      tile.food -= amountEating
      tile.updateColor()
    }

    if (this.health < 0) this.health = 0

    const [speed, turn, wantToBreed] = this.brain.ask([
      tile.food,
      this.age,
      this.health,
      this.getFoodAhead(-30, 1),
      this.getFoodAhead(0, 2),
      this.getFoodAhead(30, 1),
      this.overlapWithAnother
    ])

    if (this.health > 250 && wantToBreed > 0.5) {
      this.health -= 70
      const {x, y} = this.getPosition()
      game.animals.add(new Animal(x, y, this))
    }

    this.sprite.angle += (turn - 0.5) * 100
    game.physics.arcade.velocityFromAngle(this.sprite.angle, speed * 200, this.sprite.body.velocity)
  }

  updateColor () {
    this.sprite.loadTexture(game.cache.getBitmapData('animal' + Math.floor(this.health)))
  }

  destroy () {
    this.sprite.destroy()
  }

  getPosition (point) {
    point = point || {x: this.sprite.centerX, y: this.sprite.centerY}
    return {
      x: Math.floor(point.x / game.TILE_SIZE),
      y: Math.floor(point.y / game.TILE_SIZE)
    }
  }

  getFoodAhead (angle, tiles) {
    const line = new Phaser.Line().fromAngle(this.sprite.centerX, this.sprite.centerY,
      game.math.degToRad(this.sprite.angle + angle), game.TILE_SIZE * tiles)

    const positionAhead = this.getPosition(line.end)
    const tileAhead = (game.tiles[positionAhead.x] || [])[positionAhead.y] || {}

    return tileAhead.food == null ? -1 : tileAhead.food
  }
}

module.exports = Animal
<commit_msg>refactor(index): tweak animal speed and aging for balance<commit_after>const Phaser = require('./Phaser')
const Brain = require('./Brain')

class Animal {
  constructor (x, y, parent) {
    this.health = game.math.between(100, 150)
    this.age = 0
    this.score = 0
    this.generation = parent ? parent.generation + 1 : 1

    this.sprite = game.add.sprite(game.TILE_SIZE * (x + 0.5), game.TILE_SIZE * (y + 0.5), game.cache.getBitmapData('animal' + this.health))
    game.physics.enable(this.sprite, Phaser.Physics.ARCADE)
    this.sprite.body.setCircle(game.TILE_SIZE / 2)
    this.sprite.body.collideWorldBounds = true
    this.sprite.anchor.setTo(0.5, 0.5)
    this.updateColor()

    // Back-reference for collision handling based on sprites.
    this.sprite.animal = this

    this.sprite.angle = game.math.between(-180, 180)
    game.physics.arcade.velocityFromAngle(this.sprite.angle, game.math.between(10, 200), this.sprite.body.velocity)

    this.brain = parent ? new Brain(parent.brain) : new Brain(7, 10, 10, 3)
  }

  tick (tile) {
    this.health -= 1 + Math.sqrt(this.age * 0.01)
    this.age += 0.01

    let amountEating = 0

    if (tile.food >= 5) amountEating = 4
    else amountEating = tile.food

    if ((255 - this.health) < amountEating) amountEating = 255 - this.health

    if (amountEating) {
      this.health += amountEating
      this.score += amountEating
      tile.food -= amountEating
      tile.updateColor()
    }

    if (this.health < 0) this.health = 0

    const [speed, turn, wantToBreed] = this.brain.ask([
      tile.food,
      this.age,
      this.health,
      this.getFoodAhead(-30, 1),
      this.getFoodAhead(0, 2),
      this.getFoodAhead(30, 1),
      this.overlapWithAnother
    ])

    if (this.health > 250 && wantToBreed > 0.5) {
      this.health -= 30
      const {x, y} = this.getPosition()
      game.animals.add(new Animal(x, y, this))
    }

    this.sprite.angle += (turn - 0.5) * 100
    game.physics.arcade.velocityFromAngle(this.sprite.angle, speed * 500, this.sprite.body.velocity)
  }

  updateColor () {
    this.sprite.loadTexture(game.cache.getBitmapData('animal' + Math.floor(this.health)))
  }

  destroy () {
    this.sprite.destroy()
  }

  getPosition (point) {
    point = point || {x: this.sprite.centerX, y: this.sprite.centerY}
    return {
      x: Math.floor(point.x / game.TILE_SIZE),
      y: Math.floor(point.y / game.TILE_SIZE)
    }
  }

  getFoodAhead (angle, tiles) {
    const line = new Phaser.Line().fromAngle(this.sprite.centerX, this.sprite.centerY,
      game.math.degToRad(this.sprite.angle + angle), game.TILE_SIZE * tiles)

    const positionAhead = this.getPosition(line.end)
    const tileAhead = (game.tiles[positionAhead.x] || [])[positionAhead.y] || {}

    return tileAhead.food == null ? -1 : tileAhead.food
  }
}

module.exports = Animal
<|endoftext|>


<commit_before>enableVerboseLogging();

require("./tests/testWeakRef");
require("./tests/tests");
require("./tests/testsForRuntimeBindingGenerator");
require("./tests/propertyAccessTests");
require("./tests/numericConversionTests");
require("./tests/inheritanceChainResolutionTest");
require("./tests/exceptionHandlingTests");
require("./tests/dispatchCallbacksOnUiThreadTests");
require("./tests/stringConversionTests");
require("./tests/testsForTypescript");
require("./tests/testGC");
require("./tests/testsMemoryManagement");
require("./tests/testIfAbleToRunExternalFile");
require("./tests/finalFieldsSetTests");
require("./tests/extendedClassesTests");
require("./tests/extendClassNameTests");

//var MainActivity = com.tns.NativeScriptActivity.extend("MainActivity", {
//			   onCreate: function() {
//					this.super.onCreate(null);
//
//					require("./tests/testsWithContext").run(this);
//
//					var layout = new android.widget.LinearLayout(this);
//					layout.setOrientation(1);
//					this.setContentView(layout);
//
//					var textView = new android.widget.TextView(this);
//					textView.setText("Hit that sucker");
//					layout.addView(textView);
//
//					var button = new android.widget.Button(this);
//					button.setText("Hit me");
//					layout.addView(button);
//					var counter = 0;
//					button.setOnClickListener(new android.view.View.OnClickListener("AppClickListener", {
//						onClick:  function() {
//			              Log("onClick called");
//			              button.setText("Hit that sucker one more time " + ++counter);
//			            }}));
//          }});

var MainActivity = (function (_super) {
    __extends(MainActivity, _super);
    function MainActivity() {
    }

    MainActivity.prototype.onCreate = function () {
    	Log("onCreate from js");
    	var k = this.toString();
    	Log("this.toString " + k);
    	_super.prototype.onCreate.call(this, null);
    	//this.super.onCreate(null);

    	require("./tests/testsWithContext").run(this);

    	var layout = new android.widget.LinearLayout(this);
    	layout.setOrientation(1);
    	this.setContentView(layout);

    	var textView = new android.widget.TextView(this);
    	textView.setText("Hit that sucker");
    	layout.addView(textView);

    	var button = new android.widget.Button(this);
    	button.setText("Hit me");
    	layout.addView(button);
    	var counter = 0;
    	button.setOnClickListener(new android.view.View.OnClickListener("AppClickListener", {
    		onClick:  function() {
    			Log("onClick called");
    			button.setText("Hit that sucker one more time " + ++counter);
    		}}));
    };
    return MainActivity;
})(com.tns.NativeScriptActivity);

app.init({

	getActivity: function(intent) {
		Log("intent=" + intent)
		if (intent.getAction() == android.content.Intent.ACTION_MAIN) {
			return MainActivity;
		}
		else {
			fail("Unknown action");
		}
	},

	onCreate: function() {
		Log("Application on create called");
	}
});<commit_msg>disabled verbose logging in master<commit_after>disableVerboseLogging();

require("./tests/testWeakRef");
require("./tests/tests");
require("./tests/testsForRuntimeBindingGenerator");
require("./tests/propertyAccessTests");
require("./tests/numericConversionTests");
require("./tests/inheritanceChainResolutionTest");
require("./tests/exceptionHandlingTests");
require("./tests/dispatchCallbacksOnUiThreadTests");
require("./tests/stringConversionTests");
require("./tests/testsForTypescript");
require("./tests/testGC");
require("./tests/testsMemoryManagement");
require("./tests/testIfAbleToRunExternalFile");
require("./tests/finalFieldsSetTests");
require("./tests/extendedClassesTests");
require("./tests/extendClassNameTests");

//var MainActivity = com.tns.NativeScriptActivity.extend("MainActivity", {
//			   onCreate: function() {
//					this.super.onCreate(null);
//
//					require("./tests/testsWithContext").run(this);
//
//					var layout = new android.widget.LinearLayout(this);
//					layout.setOrientation(1);
//					this.setContentView(layout);
//
//					var textView = new android.widget.TextView(this);
//					textView.setText("Hit that sucker");
//					layout.addView(textView);
//
//					var button = new android.widget.Button(this);
//					button.setText("Hit me");
//					layout.addView(button);
//					var counter = 0;
//					button.setOnClickListener(new android.view.View.OnClickListener("AppClickListener", {
//						onClick:  function() {
//			              Log("onClick called");
//			              button.setText("Hit that sucker one more time " + ++counter);
//			            }}));
//          }});

var MainActivity = (function (_super) {
    __extends(MainActivity, _super);
    function MainActivity() {
    }

    MainActivity.prototype.onCreate = function () {
    	Log("onCreate from js");
    	var k = this.toString();
    	Log("this.toString " + k);
    	_super.prototype.onCreate.call(this, null);
    	//this.super.onCreate(null);

    	require("./tests/testsWithContext").run(this);

    	var layout = new android.widget.LinearLayout(this);
    	layout.setOrientation(1);
    	this.setContentView(layout);

    	var textView = new android.widget.TextView(this);
    	textView.setText("Hit that sucker");
    	layout.addView(textView);

    	var button = new android.widget.Button(this);
    	button.setText("Hit me");
    	layout.addView(button);
    	var counter = 0;
    	button.setOnClickListener(new android.view.View.OnClickListener("AppClickListener", {
    		onClick:  function() {
    			Log("onClick called");
    			button.setText("Hit that sucker one more time " + ++counter);
    		}}));
    };
    return MainActivity;
})(com.tns.NativeScriptActivity);

app.init({

	getActivity: function(intent) {
		Log("intent=" + intent)
		if (intent.getAction() == android.content.Intent.ACTION_MAIN) {
			return MainActivity;
		}
		else {
			fail("Unknown action");
		}
	},

	onCreate: function() {
		Log("Application on create called");
	}
});<|endoftext|>


<commit_before>/*! uppie v1.0.3 | (c) silverwind | BSD license */
!function(e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else{if("function"==typeof define&&define.amd)return define([],e);this.Uppie=e()}}(function(){"use strict";function e(e,a){if("input"===e.tagName.toLowerCase()&&"file"===e.type)e.addEventListener("change",function(e){var t=e.target;t.files&&t.files.length?i(t,a.bind(null,e)):"getFilesAndDirectories"in t?n(t,a.bind(null,e)):a(e)});else{var r=function(e){e.preventDefault()};e.addEventListener("dragover",r),e.addEventListener("dragenter",r),e.addEventListener("drop",function(e){e.preventDefault();var r=e.dataTransfer;r.items&&r.items.length&&"webkitGetAsEntry"in r.items[0]?t(r.items,a.bind(null,e)):"getFilesAndDirectories"in r?n(r,a.bind(null,e)):r.files?i(r,a.bind(null,e)):a()})}}function n(e,n){var i=new FormData,t=[],a=function(e,n,r){var o=[];e.forEach(function(e){o.push(new Promise(function(r){if("getFilesAndDirectories"in e)e.getFilesAndDirectories().then(function(n){a(n,e.path+"/",r)});else{if(e.name){var o=(n+e.name).replace(/^[\/\\]/,"");i.append("files[]",e,o),t.push(o)}r()}}))}),Promise.all(o).then(r)};e.getFilesAndDirectories().then(function(e){new Promise(function(n){a(e,"/",n)}).then(n.bind(null,i,t))})}function i(e,n){var i=new FormData,t=[];[].slice.call(e.files).forEach(function(e){i.append("files[]",e,e.webkitRelativePath||e.name),t.push(e.webkitRelativePath||e.name)}),n(i,t)}function t(e,n){function i(e,n,t,a){var r=n||e.createReader();r.readEntries(function(n){var o=t?t.concat(n):n;n.length?setTimeout(i.bind(null,e,r,o,a),0):a(o)})}function t(e,n,o){n||(n=e.name),i(e,0,0,function(e){var i=[];e.forEach(function(e){i.push(new Promise(function(i){e.isFile?e.file(function(e){var t=n+"/"+e.name;a.append("files[]",e,t),r.push(t),i()},i.bind()):t(e,n+"/"+e.name,i)}))}),Promise.all(i).then(o.bind())})}var a=new FormData,r=[],o=[];[].slice.call(e).forEach(function(e){e=e.webkitGetAsEntry(),e&&o.push(new Promise(function(n){e.isFile?e.file(function(e){a.append("files[]",e,e.name),r.push(e.name),n()},n.bind()):e.isDirectory&&t(e,null,n)}))}),Promise.all(o).then(n.bind(null,a,r))}return function(){return function(n,i){n instanceof NodeList?[].slice.call(n).forEach(function(n){e(n,i)}):e(n,i)}}});
<commit_msg>rebuild<commit_after>/*! uppie v1.0.3 | (c) silverwind | BSD license */
!function(e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else{if("function"==typeof define&&define.amd)return define([],e);this.Uppie=e()}}(function(){"use strict";function e(e,a){if("input"===e.tagName.toLowerCase()&&"file"===e.type)e.addEventListener("change",function(e){var t=e.target;t.files&&t.files.length?i(t,a.bind(null,e)):"getFilesAndDirectories"in t?n(t,a.bind(null,e)):a(e)});else{var r=function(e){e.preventDefault()};e.addEventListener("dragover",r),e.addEventListener("dragenter",r),e.addEventListener("drop",function(e){e.preventDefault();var r=e.dataTransfer;r.items&&r.items.length&&"webkitGetAsEntry"in r.items[0]?t(r.items,a.bind(null,e)):"getFilesAndDirectories"in r?n(r,a.bind(null,e)):r.files?i(r,a.bind(null,e)):a()})}}function n(e,n){var i=new FormData,t=[],a=function(e,n,r){var o=[];e.forEach(function(e){o.push(new Promise(function(r){if("getFilesAndDirectories"in e)e.getFilesAndDirectories().then(function(n){a(n,e.path+"/",r)});else{if(e.name){var o=(n+e.name).replace(/^[\/\\]/,"");i.append("files[]",e,o),t.push(o)}r()}}))}),Promise.all(o).then(r)};e.getFilesAndDirectories().then(function(e){new Promise(function(n){a(e,"/",n)}).then(n.bind(null,i,t))})}function i(e,n){var i=new FormData,t=[];[].slice.call(e.files).forEach(function(e){i.append("files[]",e,e.webkitRelativePath||e.name),t.push(e.webkitRelativePath||e.name)}),n(i,t)}function t(e,n){function i(e,n,t,a){var r=n||e.createReader();r.readEntries(function(n){var o=t?t.concat(n):n;n.length?setTimeout(i.bind(null,e,r,o,a),0):a(o)})}function t(e,n,o){n||(n=e.name),i(e,0,0,function(e){var i=[];e.forEach(function(e){i.push(new Promise(function(i){e.isFile?e.file(function(e){var t=n+"/"+e.name;a.append("files[]",e,t),r.push(t),i()},i.bind()):t(e,n+"/"+e.name,i)}))}),Promise.all(i).then(o.bind())})}var a=new FormData,r=[],o=[];[].slice.call(e).forEach(function(e){e=e.webkitGetAsEntry(),e&&o.push(new Promise(function(n){e.isFile?e.file(function(e){a.append("files[]",e,e.name),r.push(e.name),n()},n.bind()):e.isDirectory&&t(e,null,n)}))}),Promise.all(o).then(n.bind(null,a,r))}return function(){return function(n,i){n instanceof NodeList?[].slice.call(n).forEach(function(n){e(n,i)}):e(n,i)}}});<|endoftext|>


<commit_before>'use strict';

describe('Todo controller', function () {
    var todoCtrl;
    var scope;
    var $httpBackend;

    beforeEach(module('todo.controllers'));

    beforeEach(inject(function(_$httpBackend_) {
        $httpBackend = _$httpBackend_;
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be empty by default', inject(function ($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false},
            {id: 2, text: 'task2', done: false}
        ]);

        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });

        expect(scope.todos).toEqual([]); //notice that default state is not undefined, but empty!
        $httpBackend.flush();
        expect(scope.todos.length).toBe(2);
    }));

    it('should create a task', inject(function ($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        expect(scope.todos).toEqual([]);

        $httpBackend.expectPOST("/tasks", {text: 'text', done: false}).respond({id: 1, text: 'text', done: false});

        scope.formTodoText = "text";
        scope.addTodo();
        $httpBackend.flush();
        expect(scope.todos[0]).toEqual(jasmine.objectContaining({id:1, text:'text', done: false}));
    }));

    it('should update a task', inject(function($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false}
        ]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        expect(scope.todos.length).toEqual(1);

        $httpBackend.expectPUT("/tasks/1", {id: 1, text: 'task1', done: true}).respond(204);
        scope.update({id: 1, text: 'task1', done: true});
        $httpBackend.flush();
    }));

    it('should delete a completed task', inject(function($controller, $rootScope) {
        // Given
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false}
        ]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        // When
        scope.todos[0].done = true;
        $httpBackend.expectDELETE("/tasks/1").respond(204);
        scope.clearCompleted();
        // Then
        $httpBackend.flush();
        scope.$apply();
        expect(scope.todos).toEqual([]);
    }));

    it('should log the user off', inject(function($controller, $rootScope, $location) {
        // Given
        $httpBackend.expectGET("/tasks").respond([]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        // When
        $httpBackend.expectDELETE("/login").respond(204);
        scope.logoff();
        // Then
        $httpBackend.flush();
        expect($rootScope.login).toEqual(jasmine.objectContaining({}));
        expect($location.url()).toBe('/landing');
    }));
});
<commit_msg>Update task to REST API using bound update function in JavaScript.<commit_after>'use strict';

describe('Todo controller', function () {
    var todoCtrl;
    var scope;
    var $httpBackend;

    beforeEach(module('todo.controllers'));

    beforeEach(inject(function(_$httpBackend_) {
        $httpBackend = _$httpBackend_;
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be empty by default', inject(function ($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false},
            {id: 2, text: 'task2', done: false}
        ]);

        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });

        expect(scope.todos).toEqual([]); //notice that default state is not undefined, but empty!
        $httpBackend.flush();
        expect(scope.todos.length).toBe(2);
    }));

    it('should create a task', inject(function ($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        expect(scope.todos).toEqual([]);

        $httpBackend.expectPOST("/tasks", {text: 'text', done: false}).respond({id: 1, text: 'text', done: false});

        scope.formTodoText = "text";
        scope.addTodo();
        $httpBackend.flush();
        expect(scope.todos[0]).toEqual(jasmine.objectContaining({id:1, text:'text', done: false}));
    }));

    it('should update a task', inject(function($controller, $rootScope) {
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false}
        ]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        expect(scope.todos.length).toEqual(1);

        $httpBackend.expectPUT("/tasks/1", {id: 1, text: 'task1', done: true}).respond(204);
        scope.todos[0].done = true;
        scope.update(scope.todos[0]);
        $httpBackend.flush();
    }));

    it('should delete a completed task', inject(function($controller, $rootScope) {
        // Given
        $httpBackend.expectGET("/tasks").respond([
            {id: 1, text: 'task1', done: false}
        ]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        // When
        scope.todos[0].done = true;
        $httpBackend.expectDELETE("/tasks/1").respond(204);
        scope.clearCompleted();
        // Then
        $httpBackend.flush();
        scope.$apply();
        expect(scope.todos).toEqual([]);
    }));

    it('should log the user off', inject(function($controller, $rootScope, $location) {
        // Given
        $httpBackend.expectGET("/tasks").respond([]);
        scope = $rootScope.$new();
        todoCtrl = $controller('TodoCtrl', {
            $scope: scope
        });
        $httpBackend.flush();
        // When
        $httpBackend.expectDELETE("/login").respond(204);
        scope.logoff();
        // Then
        $httpBackend.flush();
        expect($rootScope.login).toEqual(jasmine.objectContaining({}));
        expect($location.url()).toBe('/landing');
    }));
});
<|endoftext|>


<commit_before>Vps.Form.RadioGroup = Ext.extend(Ext.form.RadioGroup, {
    initComponent: function() {
        this.addEvents('changevalue');
        Vps.Form.RadioGroup.superclass.initComponent.call(this);
    },
    afterRender: function() {
        Vps.Form.RadioGroup.superclass.afterRender.call(this);
        if (this.value) {
            this.setValue(this.value);
        }
        this.items.each(function(c) {
            c.on('check', function(field, newValue, oldValue) {
                if (field.getValue()) {
                    this.fireEvent('change', this, field.inputValue, 'TODO');
                    this.fireEvent('changevalue', field.inputValue);
                }
            }, this);
        }, this);
    },
    getValue: function() {
        if (!this.rendered) {
            return this.value;
        } else {
            var ret = null;
            this.items.each(function(c) {
                if (c.getValue()) {
                    ret = c.inputValue;
                    return false;
                }
            }, this);
            return ret;
        }
    },
    setValue: function(v) {
        if (!this.rendered) {
            this.value = v;
        } else {
            this.items.each(function(c) {
                if (c.inputValue == v) {
                    c.setValue(true);
                } else {
                    c.setValue(false);
                }
            }, this);
        }
        this.fireEvent('changevalue', v);
    }
});
Ext.reg('radiogroup', Vps.Form.RadioGroup);
<commit_msg>da RadioGroup set/getValue hat muss es auch ein isDirty geben<commit_after>Vps.Form.RadioGroup = Ext.extend(Ext.form.RadioGroup, {
    initComponent: function() {
        this.addEvents('changevalue');
        Vps.Form.RadioGroup.superclass.initComponent.call(this);
    },
    afterRender: function() {
        Vps.Form.RadioGroup.superclass.afterRender.call(this);
        if (this.value) {
            this.setValue(this.value);
        }
        this.items.each(function(c) {
            c.on('check', function(field, newValue, oldValue) {
                if (field.getValue()) {
                    this.fireEvent('change', this, field.inputValue, 'TODO');
                    this.fireEvent('changevalue', field.inputValue);
                }
            }, this);
        }, this);
    },
    isDirty: function() {
        if(this.disabled || !this.rendered) {
            return false;
        }
        return String(this.getValue()) !== String(this.originalValue);
    },
    getValue: function() {
        if (!this.rendered) {
            return this.value;
        } else {
            var ret = null;
            this.items.each(function(c) {
                if (c.getValue()) {
                    ret = c.inputValue;
                    return false;
                }
            }, this);
            return ret;
        }
    },
    setValue: function(v) {
        if (!this.rendered) {
            this.value = v;
        } else {
            this.items.each(function(c) {
                if (c.inputValue == v) {
                    c.setValue(true);
                } else {
                    c.setValue(false);
                }
            }, this);
        }
        this.fireEvent('changevalue', v);
    }
});
Ext.reg('radiogroup', Vps.Form.RadioGroup);
<|endoftext|>


<commit_before>var GameEngine = ( function () {
    function start() {
        var x,
            y,
            color,
            i,
            j,
            lengthBoard,
            lengthField;

        var players = [];
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        var board = GameObjects.Board.init(players);

        GameDraw.background();

        lengthBoard = board.length;

        for (i = 0; i < lengthBoard; i += 1) {
            lengthField = board[i].length;

            for (j = 0; j < lengthField; j += 1) {
                x = i;
                y = j;
                color = board[i][j].color;

                GameDraw.createCircle(x, y, color);
            }
        }

        GameDraw.playGround();
    }

    function update(){
        // currentPlayer = GetCurrentPlayer - depending on player.isOnTurn or isFirstPlayerOnTurn

        // flag hasThrownDice -> if not - throw dice(allowedMoves = diceResult, currentPlayerMoves = 0); else - continue

        // if (currentPlayer.hasHitPiece) -> Call function(s) to deal with this situation.
            // if can't put piece -> playerMoves = allowedMoves

        // if ((currentPlayerMoves < allowedMoves) && hasMovedPiece (sets to true when called from onDrag event on piece)

            // Subcases: move from position to position/ collect piece
            // Call function(s) to deal with this situation. -> hasMovedPiece = false, currentPlayerMoves++;

        // Missed logic?

        // if current player has no pieces on the board -> He wins.

        // if (playerMoves === allowedMoves) -> change player, hasThrownDice = false
    }

    return {
        start: start,
        update: update
    };
}());

// All events will call GameEngine.Update() and GameDraw.Update().<commit_msg>Fix according to gameBoard changes<commit_after>var GameEngine = ( function () {
    function start() {
        var x,
            y,
            color,
            i,
            j,
            lengthBoard,
            lengthField;

        var players = [];
        players.push(Object.create(GameObjects.Player).init('First', 'white'));
        players.push(Object.create(GameObjects.Player).init('Second', 'black'));

        var board = GameObjects.Board.init(players);

        GameDraw.background();

        lengthBoard = board.length;

        for (i = 1; i < lengthBoard - 1; i += 1) {
            lengthField = board[i].length;

            for (j = 0; j < lengthField; j += 1) {
                x = i;
                y = j;
                color = board[i][j].color;

                GameDraw.createCircle(x, y, color);
            }
        }

        GameDraw.playGround();
    }

    function update(){
        // currentPlayer = GetCurrentPlayer - depending on player.isOnTurn or isFirstPlayerOnTurn

        // flag hasThrownDice -> if not - throw dice(allowedMoves = diceResult, currentPlayerMoves = 0); else - continue

        // if (currentPlayer.hasHitPiece) -> Call function(s) to deal with this situation.
            // if can't put piece -> playerMoves = allowedMoves

        // if ((currentPlayerMoves < allowedMoves) && hasMovedPiece (sets to true when called from onDrag event on piece)

            // Subcases: move from position to position/ collect piece
            // Call function(s) to deal with this situation. -> hasMovedPiece = false, currentPlayerMoves++;

        // Missed logic?

        // if current player has no pieces on the board -> He wins.

        // if (playerMoves === allowedMoves) -> change player, hasThrownDice = false
    }

    return {
        start: start,
        update: update
    };
}());

// All events will call GameEngine.Update() and GameDraw.Update().
<|endoftext|>