<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html

// Build time configuration, substituted in Javascript file headers by Makefile.mk
const CONFIG = { MAXINT: 2147483647, MAXUINT: 4294967295,              // plus delayed package.json values
		 files: [], p: '', m: '', norc: false, uiscript: '' };
Object.assign (CONFIG, require ('./package.json').config);

let win;
let bse_proc; // assigned spawn.child
let verbose = false, verbose_binary = false, withgdb = false;

// Load Electron module for BrowserWindow, etc
const Electron = require ('electron');
const ElectronDefaultApp = process.defaultApp !== undefined; // indicates unpackaged electron app
const Eapp = Electron.app;
// Avoid stale sources and storing non-network resources in users home
Eapp.commandLine.appendSwitch ('disable-http-cache');

// create the main ebeast window
function create_window ()
{
  const FS = require ('fs');
  // avoid menu flicker, leave menu construction to the window
  Electron.Menu.setApplicationMenu (null);
  // find some CSS presets needed as BrowserWindow defaults
  let appcss = FS.readFileSync (__dirname + '/assets/stylesheets.css', 'UTF-8');
  let rex = /\bBrowserWindowDefaults\s*{([^}]*)}/m;
  appcss = rex.exec (appcss)[1];       // extract BrowserWindowDefaults section
  rex = /\/\*([^*]|\*[^\/])*\*\//;
  appcss = appcss.replace (rex, ' ');  // remove comments
  rex = /\bbackgroundColor\s*:\s*([^;}]*)\s*[;}]/mi;
  const backgroundColor = rex.exec (appcss)[1];
  rex = /\bdefaultFontSize\s*:\s*([^;}]*)\s*[;}]/mi;
  const defaultFontSize = rex.exec (appcss)[1];
  rex = /\bdefaultMonospaceFontSize\s*:\s*([^;}]*)\s*[;}]/mi;
  const defaultMonospaceFontSize = rex.exec (appcss)[1];
  // window configuraiton
  const options = {
    width: 				1820, // calling win.maximize() causes flicker
    height: 				1365, // using a big initial size avoids flickering
    backgroundColor: 			backgroundColor,
    autoHideMenuBar:			false,
    webPreferences: {
      nodeIntegration:			true,
      devTools:				CONFIG.debug,
      defaultEncoding:			'UTF-8',
      defaultFontSize:			parseInt (defaultFontSize),
      defaultMonospaceFontSize:		parseInt (defaultMonospaceFontSize),
      defaultFontFamily: {
	standard:	'sans',		// 'Times New Roman',
	serif:		'Constantia',	// 'Times New Roman',
	sansSerif:	'Candara',	// 'Arial',
	monospace:	'Consolas',	// 'Courier New',
	cursive:	'Script',	// 'Script',
	fantasy:	'Impact',	// 'Impact',
      },
    },
    show: false, // avoid incremental load effect, see 'ready-to-show'
    darkTheme: true,
  };
  let win = new Electron.BrowserWindow (options);
  win.MAINCONFIG = CONFIG;
  win.webContents.once ('crashed', e => {
    seen_crashed = true;
    if (seen_will_quit && seen_crashed)
      Eapp.exit (143); // will-quit + crashed is caused by SIGHUP or SIGTERM
  });
  win.webContents.printout = function (...args) { console.log (...args); };
  win.webContents.printerr = function (...args) { console.error (...args); };
  return win;
}

// Start BeastSoundEngine in private mode
function create_beast_sound_engine (datacb, errorcb) {
  const { spawn, spawnSync } = require ('child_process');
  let args = [ '--embed', '3' ];
  if (verbose)
    args.push ('--verbose');
  if (verbose_binary)
    args.push ('--binary');
  if (CONFIG.norc)
    {
      args.push ('--bse-rcfile');
      args.push ('/dev/null');
    }
  if (CONFIG.p)
    {
      args.push ('--bse-pcm-driver');
      args.push (CONFIG.p);
    }
  if (CONFIG.m)
    {
      args.push ('--bse-midi-driver');
      args.push (CONFIG.m);
    }
  const beastsoundengine = __dirname + '/../lib/BeastSoundEngine-' + CONFIG['version'] + '-rt';
  const bse_proc = spawn (beastsoundengine, args, { stdio: [ 'pipe', 'inherit', 'inherit', 'pipe' ] });
  if (withgdb)
    {
      console.log ('DEBUGGING:\n  gdb --pid', bse_proc.pid, '#', beastsoundengine);
      spawnSync ('/usr/bin/sleep', [ 3 ]);
    }
  bse_proc.stdio[3].once ('data', (bytes) => datacb (bytes.toString()));
  if (errorcb)
    {
      bse_proc.stdio[3].once ('end', () => errorcb());
      bse_proc.stdio[3].once ('error', (err) => errorcb());
    }
  return bse_proc;
}

// split command line options and return one at a time
function pop_arg (args) {
  if (!args.length)
    return undefined;
  let a = args.shift();
  if (args.__nonoption__) {		// yield saved option argument
    args.__nonoption__--;
    return a;
  }
  if (args.skip_defaultapp) {		// finding defaultApp has precedence
    if (/^[^-]/.test (a)) {
      args.skip_defaultapp = false;	// consume process.defaultApp
      return pop_arg (args);
    }
  }
  if (args.seen_separator)		// yield only non-options after '--'
    return a;
  if (/^-[^-]+/.test (a)) {		// pop single letter option
    const rest = a.slice (2);
    if (/^=/.test (rest)) {		// save single letter option argument
      args.unshift (rest.slice (1));
      args.__nonoption__ = 1;
    } else if (rest)
      args.unshift ('-' + rest);	// save adjunct single letter options
    return '-' + a[1];
  } else if (/^--[^-]+/.test (a)) {	// pop long option
    const eq = a.indexOf ('=');
    if (eq > 0) {
      args.unshift (a.slice (eq + 1));	// save long option argument
      args.__nonoption__ = 1;
      return a.slice (0, eq);
    }
    return a;
  } else if (/^--$/.test (a)) {		// stop option parsing
    args.seen_separator = true;
    return pop_arg (args);
  }
  return a;
}

// Print help/usage
function print_help () {
  const lines = [
    `Usage: ${Eapp.getName()} [OPTIONS] [projectfiles...]`,
    'Options:',
    '--help        Print command line option help',
    '--version     Print version information',
    '--gdb         Print command to debug BSE',
    '--norc        Skip reading of ~/.config/beast/bserc.xml',
    '-p DRIVER     Set the default PCM driver (for --norc)',
    '-m DRIVER     Set the default MIDI driver (for --norc)',
  ];
  console.log (lines.join ('\n'));
}

// parse command line arguments
{
  let args = process.argv.slice (1);
  args.skip_defaultapp = ElectronDefaultApp;
  while (args.length) {
    const arg = pop_arg (args);
    if (args.seen_separator) {
      CONFIG.files.push (arg);
      continue;
    }
    switch (arg) {
      case '--help':
	print_help();
	main_exit (0);
	break;
      case '--version':
	console.log (Eapp.getName() + ' ' + Eapp.getVersion());
	main_exit (0);
	break;
      case '--verbose':
	verbose = true;
	break;
      case '--binary':
	verbose_binary = true;
	break;
      case '--gdb':
	withgdb = true;
	break;
      case '-p':
	CONFIG.p = args.length ? pop_arg (args) : '';
	break;
      case '-m':
	CONFIG.m = args.length ? pop_arg (args) : '';
	break;
      case '--norc':
	CONFIG.norc = true;
	break;
      case '--uiscript':
	CONFIG.uiscript = args.length ? pop_arg (args) : '';
	break;
      default:
	if (/^-/.test (arg)) {
	  console.err ('Unknown option: ' + arg);
	  print_help();
	  main_exit (5);
	}
	CONFIG.files.push (arg);
	break;
    }
  }
}

// Start BeastSoundEngine and BrowserWindow
async function startup_components() {
  // configure BrowserWindow with BeastSoundEngine embedding info
  win = create_window();
  win.on ('closed', () => win = null);
  // TODO: when this BrowserWindow is close, also force closing of the beast-manual or other related (child) windows
  let win_ready = new Promise (resolve => win.once ('ready-to-show', () => resolve ()));
  let embedding_info = new Promise (resolve => bse_proc = create_beast_sound_engine (msg => resolve (msg), () => main_exit (3)));
  const auth = JSON.parse (await embedding_info); // yields JSON: { "url": "http://127.0.0.1:<PORT>/index.html?subprotocol=<STRING>" }
  if (!auth.url)
    main_exit (2);
  win.loadURL (auth.url);
  await win_ready;
  win.show();
}
Eapp.once ('ready', startup_components); // create BeastSoundEngine and BrowserWindow once everything is loaded

// End process and main_exit all dependent processes
function main_exit (exitcode) {
  if (main_exit.shuttingdown)
    return;
  main_exit.shuttingdown = true;
  if (win)
    {
      win.destroy();
      win = null;
    }
  if (bse_proc)
    bse_proc.kill();
  Eapp.exit (exitcode ? exitcode : 0);
}

// Valid exit
Eapp.once ('window-all-closed', () => {
  win = null; // this *may* be emitted before win.closed
  main_exit (0);
});

// Invalid exit conditions
process.on ('uncaughtException', function (err) {
  console.error (process.argv[0] + ": uncaughtException (" + (new Date).toUTCString() + '):');
  console.error (err);
  main_exit (7);
});

/* Note, Electron hijacks SIGINT, SIGHUP, SIGTERM to trigger app.quit()
 * which has a 0 exit status. We simply don't use quit() and force a
 * non-0 status if it's used. See also:
 * https://github.com/electron/electron/issues/19650
 * https://github.com/electron/electron/issues/5273
 */
let seen_crashed = false, seen_will_quit = false;
Electron.app.once ('will-quit', e => {
  seen_will_quit = true;
  if (seen_will_quit && seen_crashed)
    Eapp.exit (143);    // will-quit + crashed is caused by SIGHUP or SIGTERM
  Eapp.exit (130);	// assume SIGINT
});
<commit_msg>EBEAST: main.js: abort if BeastSoundEngine crashes and print reason<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html

// Build time configuration, substituted in Javascript file headers by Makefile.mk
const CONFIG = { MAXINT: 2147483647, MAXUINT: 4294967295,              // plus delayed package.json values
		 files: [], p: '', m: '', norc: false, uiscript: '' };
Object.assign (CONFIG, require ('./package.json').config);

let win;
let bse_proc; // assigned spawn.child
let verbose = false, verbose_binary = false, withgdb = false;

// Load Electron module for BrowserWindow, etc
const Electron = require ('electron');
const ElectronDefaultApp = process.defaultApp !== undefined; // indicates unpackaged electron app
const Eapp = Electron.app;
// Avoid stale sources and storing non-network resources in users home
Eapp.commandLine.appendSwitch ('disable-http-cache');

// create the main ebeast window
function create_window ()
{
  const FS = require ('fs');
  // avoid menu flicker, leave menu construction to the window
  Electron.Menu.setApplicationMenu (null);
  // find some CSS presets needed as BrowserWindow defaults
  let appcss = FS.readFileSync (__dirname + '/assets/stylesheets.css', 'UTF-8');
  let rex = /\bBrowserWindowDefaults\s*{([^}]*)}/m;
  appcss = rex.exec (appcss)[1];       // extract BrowserWindowDefaults section
  rex = /\/\*([^*]|\*[^\/])*\*\//;
  appcss = appcss.replace (rex, ' ');  // remove comments
  rex = /\bbackgroundColor\s*:\s*([^;}]*)\s*[;}]/mi;
  const backgroundColor = rex.exec (appcss)[1];
  rex = /\bdefaultFontSize\s*:\s*([^;}]*)\s*[;}]/mi;
  const defaultFontSize = rex.exec (appcss)[1];
  rex = /\bdefaultMonospaceFontSize\s*:\s*([^;}]*)\s*[;}]/mi;
  const defaultMonospaceFontSize = rex.exec (appcss)[1];
  // window configuraiton
  const options = {
    width: 				1820, // calling win.maximize() causes flicker
    height: 				1365, // using a big initial size avoids flickering
    backgroundColor: 			backgroundColor,
    autoHideMenuBar:			false,
    webPreferences: {
      nodeIntegration:			true,
      devTools:				CONFIG.debug,
      defaultEncoding:			'UTF-8',
      defaultFontSize:			parseInt (defaultFontSize),
      defaultMonospaceFontSize:		parseInt (defaultMonospaceFontSize),
      defaultFontFamily: {
	standard:	'sans',		// 'Times New Roman',
	serif:		'Constantia',	// 'Times New Roman',
	sansSerif:	'Candara',	// 'Arial',
	monospace:	'Consolas',	// 'Courier New',
	cursive:	'Script',	// 'Script',
	fantasy:	'Impact',	// 'Impact',
      },
    },
    show: false, // avoid incremental load effect, see 'ready-to-show'
    darkTheme: true,
  };
  let win = new Electron.BrowserWindow (options);
  win.MAINCONFIG = CONFIG;
  win.webContents.once ('crashed', e => {
    seen_crashed = true;
    if (seen_will_quit && seen_crashed)
      Eapp.exit (143); // will-quit + crashed is caused by SIGHUP or SIGTERM
  });
  win.webContents.printout = function (...args) { console.log (...args); };
  win.webContents.printerr = function (...args) { console.error (...args); };
  return win;
}

// Start BeastSoundEngine in private mode
function create_beast_sound_engine (datacb, errorcb) {
  const { spawn, spawnSync } = require ('child_process');
  let args = [ '--embed', '3' ];
  if (verbose)
    args.push ('--verbose');
  if (verbose_binary)
    args.push ('--binary');
  if (CONFIG.norc)
    {
      args.push ('--bse-rcfile');
      args.push ('/dev/null');
    }
  if (CONFIG.p)
    {
      args.push ('--bse-pcm-driver');
      args.push (CONFIG.p);
    }
  if (CONFIG.m)
    {
      args.push ('--bse-midi-driver');
      args.push (CONFIG.m);
    }
  const beastsoundengine = __dirname + '/../lib/BeastSoundEngine-' + CONFIG['version'] + '-rt';
  const bse_proc = spawn (beastsoundengine, args, { stdio: [ 'pipe', 'inherit', 'inherit', 'pipe' ] });
  if (withgdb)
    {
      console.log ('DEBUGGING:\n  gdb --pid', bse_proc.pid, '#', beastsoundengine);
      spawnSync ('/usr/bin/sleep', [ 3 ]);
    }
  bse_proc.stdio[3].once ('data', (bytes) => datacb (bytes.toString()));
  if (errorcb)
    {
      const prefix = beastsoundengine.split ('/').pop() + ':';
      bse_proc.on ('exit', async (code, sig) => {
	const reason = sig || bse_proc.signalCode || code || bse_proc.exitCode;
	await new Promise (r => setTimeout (() => r(), 17)); // first allow normal Exit e.g. due to X11 SIGTERM
	console.error (prefix, 'exited:', reason);
	errorcb();
      });
      bse_proc.stdio[3].once ('end', async () => {
	await new Promise (r => setTimeout (() => r(), 35)); // allow 'exit' handler to run first
	console.error (prefix, 'connection closed');
	errorcb();
      });
      bse_proc.stdio[3].once ('error', (err) => {
	console.error (prefix + ' ' + err);
	errorcb();
      });
      bse_proc.once ('error', (err) => {
	console.error (prefix + ' ' + err);
	errorcb();
      });
    }
  return bse_proc;
}

// split command line options and return one at a time
function pop_arg (args) {
  if (!args.length)
    return undefined;
  let a = args.shift();
  if (args.__nonoption__) {		// yield saved option argument
    args.__nonoption__--;
    return a;
  }
  if (args.skip_defaultapp) {		// finding defaultApp has precedence
    if (/^[^-]/.test (a)) {
      args.skip_defaultapp = false;	// consume process.defaultApp
      return pop_arg (args);
    }
  }
  if (args.seen_separator)		// yield only non-options after '--'
    return a;
  if (/^-[^-]+/.test (a)) {		// pop single letter option
    const rest = a.slice (2);
    if (/^=/.test (rest)) {		// save single letter option argument
      args.unshift (rest.slice (1));
      args.__nonoption__ = 1;
    } else if (rest)
      args.unshift ('-' + rest);	// save adjunct single letter options
    return '-' + a[1];
  } else if (/^--[^-]+/.test (a)) {	// pop long option
    const eq = a.indexOf ('=');
    if (eq > 0) {
      args.unshift (a.slice (eq + 1));	// save long option argument
      args.__nonoption__ = 1;
      return a.slice (0, eq);
    }
    return a;
  } else if (/^--$/.test (a)) {		// stop option parsing
    args.seen_separator = true;
    return pop_arg (args);
  }
  return a;
}

// Print help/usage
function print_help () {
  const lines = [
    `Usage: ${Eapp.getName()} [OPTIONS] [projectfiles...]`,
    'Options:',
    '--help        Print command line option help',
    '--version     Print version information',
    '--gdb         Print command to debug BSE',
    '--norc        Skip reading of ~/.config/beast/bserc.xml',
    '-p DRIVER     Set the default PCM driver (for --norc)',
    '-m DRIVER     Set the default MIDI driver (for --norc)',
  ];
  console.log (lines.join ('\n'));
}

// parse command line arguments
{
  let args = process.argv.slice (1);
  args.skip_defaultapp = ElectronDefaultApp;
  while (args.length) {
    const arg = pop_arg (args);
    if (args.seen_separator) {
      CONFIG.files.push (arg);
      continue;
    }
    switch (arg) {
      case '--help':
	print_help();
	main_exit (0);
	break;
      case '--version':
	console.log (Eapp.getName() + ' ' + Eapp.getVersion());
	main_exit (0);
	break;
      case '--verbose':
	verbose = true;
	break;
      case '--binary':
	verbose_binary = true;
	break;
      case '--gdb':
	withgdb = true;
	break;
      case '-p':
	CONFIG.p = args.length ? pop_arg (args) : '';
	break;
      case '-m':
	CONFIG.m = args.length ? pop_arg (args) : '';
	break;
      case '--norc':
	CONFIG.norc = true;
	break;
      case '--inspect':
	break; // nodejs debugging
      case '--uiscript':
	CONFIG.uiscript = args.length ? pop_arg (args) : '';
	break;
      default:
	if (/^-/.test (arg)) {
	  console.error ('Unknown option: ' + arg);
	  print_help();
	  main_exit (5);
	}
	CONFIG.files.push (arg);
	break;
    }
  }
}

// Start BeastSoundEngine and BrowserWindow
async function startup_components() {
  // configure BrowserWindow with BeastSoundEngine embedding info
  win = create_window();
  win.on ('closed', () => win = null);
  // TODO: when this BrowserWindow is close, also force closing of the beast-manual or other related (child) windows
  let win_ready = new Promise (resolve => win.once ('ready-to-show', () => resolve ()));
  let embedding_info = new Promise (resolve => bse_proc = create_beast_sound_engine (msg => resolve (msg), () => main_exit (-1)));
  const auth = JSON.parse (await embedding_info); // yields JSON: { "url": "http://127.0.0.1:<PORT>/index.html?subprotocol=<STRING>" }
  if (!auth.url)
    {
      console.error ('Failed to launch BeastSoundEngine');
      main_exit (-1);
    }
  win.loadURL (auth.url);
  await win_ready;
  win.show();
}
Eapp.once ('ready', startup_components); // create BeastSoundEngine and BrowserWindow once everything is loaded

// End process and main_exit all dependent processes
function main_exit (exitcode) {
  if (main_exit.shuttingdown)
    return;
  main_exit.shuttingdown = true;
  if (win)
    {
      win.destroy();
      win = null;
    }
  if (bse_proc)
    bse_proc.kill();
  if (exitcode < 0)
    process.abort();
  Eapp.exit (exitcode ? exitcode : 0);
}

// Valid exit
Eapp.once ('window-all-closed', () => {
  win = null; // this *may* be emitted before win.closed
  main_exit (0);
});

// Invalid exit conditions
process.on ('uncaughtException', function (err) {
  console.error (process.argv[0] + ": uncaughtException (" + (new Date).toUTCString() + '):');
  console.error (err);
  main_exit (-1);
});

/* Note, Electron hijacks SIGINT, SIGHUP, SIGTERM to trigger app.quit()
 * which has a 0 exit status. We simply don't use quit() and force a
 * non-0 status if it's used. See also:
 * https://github.com/electron/electron/issues/19650
 * https://github.com/electron/electron/issues/5273
 */
let seen_crashed = false, seen_will_quit = false;
Electron.app.once ('will-quit', e => {
  seen_will_quit = true;
  if (seen_will_quit && seen_crashed)
    Eapp.exit (143);    // will-quit + crashed is caused by SIGHUP or SIGTERM
  Eapp.exit (130);	// assume SIGINT
});
<|endoftext|>


<commit_before>angular.module('focus.services', [])
.factory('AthleteData', function() {
    var athletes = [
      {
        name: "Helene Olafsen",
        img: "img/athletes/heleneO_150x150.jpg",
        subtext: "Snøbrettkjører",
        quote: "Å være tilstede mentalt er helt avgjørende for å kunne forbedre de små tingene som gir deg motivasjon, som gir deg glede, som gjør deg bedre – som gjør deg best"
      },
      {
        name: "Olaf Tufte",
        img: "img/athletes/olaf_tufte.jpg",
        subtext: "Roer",
        quote: "Et viktig element i iMax:Focus er å øve seg på å bruke energien på det som kan gjøre deg bedre. La ikke uvesentligheter og mulige energitappere 'sette seg fast i hodet' og forstyrre fokus. Det som ikke er viktig skal man kun 'Registrere og ikke engasjere' seg i."
      },
      {
        name: "Alexander Dale Oen",
        img: "img/athletes/alexander_dale_oen.jpg",
        subtext: "Svømmer",
        quote: "iMax:Focus er selve forskjellen mellom et topp løp og et middels løp. Alle mine fysiske forberedelser kan være optimale, men det er bortkastet om jeg ikke er tilstede og mentalt fokusert på målet og utførelsen."
      },

      {
        name: "Mette Solli",
        img: "img/athletes/mette_solli.jpg",
        subtext: "Kickbokser",
        quote: "Tilstedeværelse i det du gjør er mer enn bare å være fokusert og konsentrert. Det handler om å være tilstede i kroppen og sinnet, få kontroll på pusten. Det handler om å kjenne etter å være våken i seg selv for å prestere bedre, håndtere ytre og indre stress, og for å kjenne på de små opplevelsene i treningen som bidrar til de store opplevelsene i kamp."
      },
      {
        name: "Suzann Pettersen",
        img: "img/athletes/tutta1.jpg",
        subtext: "Golfer",
        quote: "iMax:Focus er kritisk god prioritering og å ta de rette valg underveis, for så å ta ut dette i konkurransene."
      },
      {
        name: "Fredrik Meek",
        img: "img/athletes/fredrik_m_150x150.jpg",
        subtext: "World Skills/Billakkering",
        quote: "Mental trening har lært meg en tenkemåte som gjør at jeg takler stress under konkurranse. Jeg har mine arbeidsoppgaver mer klart i fokus."
      },
      {
        name: "Anders Nilsen",
        img: "img/athletes/andersnilsen_1.jpg",
        subtext: "Fotojournalist / Grunder av Fotografiutdanningen ved Norges Kreative Fagskole",
        quote: "Det handler om å rydde opp i hodet, prioritere de viktige tingene i riktig rekkefølge, sette seg overkommelige, (eller høye mål) og finne den riktige motivasjonen du trenger for å glede deg over det du gjør på jobb eller på trening, noe som igjen skaper bedre resultater."
      },
      {
        name: "Marit Breivik",
        img: "/img/athletes/MaritBreivik_NIFS_crop_blackwhite_150x150.jpg",
        subtext: "Hovedcoach Lagspillidretter / Landslagstrener 1994-2009, med 13 mesterskapsmedaljer (EM, VM, OL)",
        quote: "Topp prestasjon handler om å være i 'nuet'! Til stede, på trening og i konkurranse, her og nå! Nøkkelen til dette? Oppmerksomhetsprogrammene i iMax:Focus gir deg god veiledning i å øke tilstedeværelsen din både i hverdagen og på trening!"
      },
      {
        name: "Frank Eirik Abrahamsen",
        img: "img/athletes/frank_abrahamsen_150x150.jpg",
        subtext: "Doktorgrad i idrettspsykologi ved Norges Idrettshøgskole, med motivasjon og prestasjonsangst i eliteidrett i fokus.",
        quote: "'Sammenhengen mellom å tenke rett og gjøre rett er ikke 100%, men sammenhengen mellom å tenke feil og gjøre feil er mye større' (Bob Rotella). Å lære seg å tenke rett til rett tid – tar tid. Mange utøvere sender e-poster og takker for bedre prestasjoner etter at de har øvd på å være til stede, med rett fokus til rett tid. iMax:Focus gir deg en 'head start'!"
      }
    ];

    return {
      getAthletes: function() {
        return athletes;
      }
    }
  });
<commit_msg>Fix minor bug<commit_after>angular.module('focus.services')
.factory('AthleteData', function() {
    var athletes = [
      {
        name: "Helene Olafsen",
        img: "img/athletes/heleneO_150x150.jpg",
        subtext: "Snøbrettkjører",
        quote: "Å være tilstede mentalt er helt avgjørende for å kunne forbedre de små tingene som gir deg motivasjon, som gir deg glede, som gjør deg bedre – som gjør deg best"
      },
      {
        name: "Olaf Tufte",
        img: "img/athletes/olaf_tufte.jpg",
        subtext: "Roer",
        quote: "Et viktig element i iMax:Focus er å øve seg på å bruke energien på det som kan gjøre deg bedre. La ikke uvesentligheter og mulige energitappere 'sette seg fast i hodet' og forstyrre fokus. Det som ikke er viktig skal man kun 'Registrere og ikke engasjere' seg i."
      },
      {
        name: "Alexander Dale Oen",
        img: "img/athletes/alexander_dale_oen.jpg",
        subtext: "Svømmer",
        quote: "iMax:Focus er selve forskjellen mellom et topp løp og et middels løp. Alle mine fysiske forberedelser kan være optimale, men det er bortkastet om jeg ikke er tilstede og mentalt fokusert på målet og utførelsen."
      },

      {
        name: "Mette Solli",
        img: "img/athletes/mette_solli.jpg",
        subtext: "Kickbokser",
        quote: "Tilstedeværelse i det du gjør er mer enn bare å være fokusert og konsentrert. Det handler om å være tilstede i kroppen og sinnet, få kontroll på pusten. Det handler om å kjenne etter å være våken i seg selv for å prestere bedre, håndtere ytre og indre stress, og for å kjenne på de små opplevelsene i treningen som bidrar til de store opplevelsene i kamp."
      },
      {
        name: "Suzann Pettersen",
        img: "img/athletes/tutta1.jpg",
        subtext: "Golfer",
        quote: "iMax:Focus er kritisk god prioritering og å ta de rette valg underveis, for så å ta ut dette i konkurransene."
      },
      {
        name: "Fredrik Meek",
        img: "img/athletes/fredrik_m_150x150.jpg",
        subtext: "World Skills/Billakkering",
        quote: "Mental trening har lært meg en tenkemåte som gjør at jeg takler stress under konkurranse. Jeg har mine arbeidsoppgaver mer klart i fokus."
      },
      {
        name: "Anders Nilsen",
        img: "img/athletes/andersnilsen_1.jpg",
        subtext: "Fotojournalist / Grunder av Fotografiutdanningen ved Norges Kreative Fagskole",
        quote: "Det handler om å rydde opp i hodet, prioritere de viktige tingene i riktig rekkefølge, sette seg overkommelige, (eller høye mål) og finne den riktige motivasjonen du trenger for å glede deg over det du gjør på jobb eller på trening, noe som igjen skaper bedre resultater."
      },
      {
        name: "Marit Breivik",
        img: "/img/athletes/MaritBreivik_NIFS_crop_blackwhite_150x150.jpg",
        subtext: "Hovedcoach Lagspillidretter / Landslagstrener 1994-2009, med 13 mesterskapsmedaljer (EM, VM, OL)",
        quote: "Topp prestasjon handler om å være i 'nuet'! Til stede, på trening og i konkurranse, her og nå! Nøkkelen til dette? Oppmerksomhetsprogrammene i iMax:Focus gir deg god veiledning i å øke tilstedeværelsen din både i hverdagen og på trening!"
      },
      {
        name: "Frank Eirik Abrahamsen",
        img: "img/athletes/frank_abrahamsen_150x150.jpg",
        subtext: "Doktorgrad i idrettspsykologi ved Norges Idrettshøgskole, med motivasjon og prestasjonsangst i eliteidrett i fokus.",
        quote: "'Sammenhengen mellom å tenke rett og gjøre rett er ikke 100%, men sammenhengen mellom å tenke feil og gjøre feil er mye større' (Bob Rotella). Å lære seg å tenke rett til rett tid – tar tid. Mange utøvere sender e-poster og takker for bedre prestasjoner etter at de har øvd på å være til stede, med rett fokus til rett tid. iMax:Focus gir deg en 'head start'!"
      }
    ];

    return {
      getAthletes: function() {
        return athletes;
      }
    }
  });
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
 *
 * @APPPLANT_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apache License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/Apache-2.0/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPPLANT_LICENSE_HEADER_END@
 */

var exec    = require('cordova/exec'),
    channel = require('cordova/channel');

/***********
 * MEMBERS *
 ***********/

// Default values
exports._defaults = {
    text:  '',
    title: '',
    sound: 'res://platform_default',
    badge: 0,
    id:    0,
    data:  undefined,
    every: undefined,
    at:    undefined
};

// listener
exports._listener = {};

// Registered permission flag
exports._registered = false;

/********
 * UTIL *
 ********/

/**
 * Merge platform specific properties into the default ones.
 *
 * @return {Object}
 *      The default properties for the platform
 */
exports.applyPlatformSpecificOptions = function () {
    var defaults = this._defaults;

    switch (device.platform) {
    case 'Android':
        defaults.icon      = 'res://ic_popup_reminder';
        defaults.smallIcon = undefined;
        defaults.ongoing   = false;
        defaults.autoClear = true;
        defaults.led       = 'FF0000';
        defaults.color     = undefined;
        break;
    }

    return defaults;
};

/**
 * Merge custom properties with the default values.
 *
 * @param {Object} options
 *      Set of custom values
 *
 * @retrun {Object}
 *      The merged property list
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    options.at   = this.getValueFor(options, 'at', 'firstAt', 'date');
    options.text = this.getValueFor(options, 'text', 'message');
    options.data = this.getValueFor(options, 'data', 'json');

    if (defaults.hasOwnProperty('autoClear')) {
        options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
    }

    if (options.autoClear !== true && options.ongoing) {
        options.autoClear = false;
    }

    if (options.at === undefined || options.at === null) {
        options.at = new Date();
    }

    for (var key in defaults) {
        if (options[key] === null || options[key] === undefined) {
            if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
                options[key] = undefined;
            } else {
                options[key] = defaults[key];
            }
        }
    }

    for (key in options) {
        if (!defaults.hasOwnProperty(key)) {
            delete options[key];
            console.warn('Unknown property: ' + key);
        }
    }

    return options;
};

/**
 * Convert the passed values to their required type.
 *
 * @param {Object} options
 *      Set of custom values
 *
 * @retrun {Object}
 *      The converted property list
 */
exports.convertProperties = function (options) {

    if (options.id) {
        if (isNaN(options.id)) {
            options.id = this.getDefaults().id;
            console.warn('Id is not a number: ' + options.id);
        } else {
            options.id = Number(options.id);
        }
    }

    if (options.title) {
        options.title = options.title.toString();
    }

    if (options.text) {
        options.text  = options.text.toString();
    }

    if (options.badge) {
        if (isNaN(options.badge)) {
            options.badge = this.getDefaults().badge;
            console.warn('Badge number is not a number: ' + options.id);
        } else {
            options.badge = Number(options.badge);
        }
    }

    if (options.at) {
        if (typeof options.at == 'object') {
            options.at = options.at.getTime();
        }

        options.at = Math.round(options.at/1000);
    }

    if (typeof options.data == 'object') {
        options.data = JSON.stringify(options.data);
    }

    return options;
};

/**
 * Create callback, which will be executed within a specific scope.
 *
 * @param {Function} callbackFn
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 *
 * @return {Function}
 *      The new callback function
 */
exports.createCallbackFn = function (callbackFn, scope) {

    if (typeof callbackFn != 'function')
        return;

    return function () {
        callbackFn.apply(scope || this, arguments);
    };
};

/**
 * Convert the IDs to numbers.
 *
 * @param {String/Number[]} ids
 *
 * @return Array of Numbers
 */
exports.convertIds = function (ids) {
    var convertedIds = [];

    for (var i = 0; i < ids.length; i++) {
        convertedIds.push(Number(ids[i]));
    }

    return convertedIds;
};

/**
 * First found value for the given keys.
 *
 * @param {Object} options
 *      Object with key-value properties
 * @param {String[]} keys*
 *      Key list
 */
exports.getValueFor = function (options) {
    var keys = Array.apply(null, arguments).slice(1);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (options.hasOwnProperty(key)) {
            return options[key];
        }
    }
};

/**
 * Fire event with given arguments.
 *
 * @param {String} event
 *      The event's name
 * @param {args*}
 *      The callback's arguments
 */
exports.fireEvent = function (event) {
    var args     = Array.apply(null, arguments).slice(1),
        listener = this._listener[event];

    if (!listener)
        return;

    for (var i = 0; i < listener.length; i++) {
        var fn    = listener[i][0],
            scope = listener[i][1];

        fn.apply(scope, args);
    }
};

/**
 * Execute the native counterpart.
 *
 * @param {String} action
 *      The name of the action
 * @param args[]
 *      Array of arguments
 * @param {Function} callback
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 */
exports.exec = function (action, args, callback, scope) {
    var fn = this.createCallbackFn(callback, scope),
        params = [];

    if (Array.isArray(args)) {
        params = args;
    } else if (args) {
        params.push(args);
    }

    exec(fn, null, 'LocalNotification', action, params);
};

/*********
 * HOOKS *
 *********/

// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
    // Device is ready now, the listeners are registered
    // and all queued events can be executed.
    exec(null, null, 'LocalNotification', 'deviceready', []);
});

// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
    // Device plugin is ready now
    channel.onCordovaInfoReady.subscribe(function () {
        // Merge platform specifics into defaults
        exports.applyPlatformSpecificOptions();
    });
});
<commit_msg>expect the every option to always be a string on iOS. display a warning if it is not.<commit_after>/*
 * Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
 *
 * @APPPLANT_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apache License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/Apache-2.0/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPPLANT_LICENSE_HEADER_END@
 */

var exec    = require('cordova/exec'),
    channel = require('cordova/channel');

/***********
 * MEMBERS *
 ***********/

// Default values
exports._defaults = {
    text:  '',
    title: '',
    sound: 'res://platform_default',
    badge: 0,
    id:    0,
    data:  undefined,
    every: undefined,
    at:    undefined
};

// listener
exports._listener = {};

// Registered permission flag
exports._registered = false;

/********
 * UTIL *
 ********/

/**
 * Merge platform specific properties into the default ones.
 *
 * @return {Object}
 *      The default properties for the platform
 */
exports.applyPlatformSpecificOptions = function () {
    var defaults = this._defaults;

    switch (device.platform) {
    case 'Android':
        defaults.icon      = 'res://ic_popup_reminder';
        defaults.smallIcon = undefined;
        defaults.ongoing   = false;
        defaults.autoClear = true;
        defaults.led       = 'FF0000';
        defaults.color     = undefined;
        break;
    }

    return defaults;
};

/**
 * Merge custom properties with the default values.
 *
 * @param {Object} options
 *      Set of custom values
 *
 * @retrun {Object}
 *      The merged property list
 */
exports.mergeWithDefaults = function (options) {
    var defaults = this.getDefaults();

    options.at   = this.getValueFor(options, 'at', 'firstAt', 'date');
    options.text = this.getValueFor(options, 'text', 'message');
    options.data = this.getValueFor(options, 'data', 'json');

    if (defaults.hasOwnProperty('autoClear')) {
        options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
    }

    if (options.autoClear !== true && options.ongoing) {
        options.autoClear = false;
    }

    if (options.at === undefined || options.at === null) {
        options.at = new Date();
    }

    for (var key in defaults) {
        if (options[key] === null || options[key] === undefined) {
            if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
                options[key] = undefined;
            } else {
                options[key] = defaults[key];
            }
        }
    }

    for (key in options) {
        if (!defaults.hasOwnProperty(key)) {
            delete options[key];
            console.warn('Unknown property: ' + key);
        }
    }

    return options;
};

/**
 * Convert the passed values to their required type.
 *
 * @param {Object} options
 *      Set of custom values
 *
 * @retrun {Object}
 *      The converted property list
 */
exports.convertProperties = function (options) {

    if (options.id) {
        if (isNaN(options.id)) {
            options.id = this.getDefaults().id;
            console.warn('Id is not a number: ' + options.id);
        } else {
            options.id = Number(options.id);
        }
    }

    if (options.title) {
        options.title = options.title.toString();
    }

    if (options.text) {
        options.text  = options.text.toString();
    }

    if (options.badge) {
        if (isNaN(options.badge)) {
            options.badge = this.getDefaults().badge;
            console.warn('Badge number is not a number: ' + options.id);
        } else {
            options.badge = Number(options.badge);
        }
    }

    if (options.at) {
        if (typeof options.at == 'object') {
            options.at = options.at.getTime();
        }

        options.at = Math.round(options.at/1000);
    }

    if (typeof options.data == 'object') {
        options.data = JSON.stringify(options.data);
    }

    if (options.every)
        if (device.platform == 'iOS' && typeof options.every != 'string') {
            options.every = this.getDefaults().every;
            var warning = 'Every option is not a string: ' + options.id;
            warning += '. Expects one of: second, minute, hour, day, week, ';
            warning += 'month, year on iOS.';
            console.warn(warning);
        }
    }

    return options;
};

/**
 * Create callback, which will be executed within a specific scope.
 *
 * @param {Function} callbackFn
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 *
 * @return {Function}
 *      The new callback function
 */
exports.createCallbackFn = function (callbackFn, scope) {

    if (typeof callbackFn != 'function')
        return;

    return function () {
        callbackFn.apply(scope || this, arguments);
    };
};

/**
 * Convert the IDs to numbers.
 *
 * @param {String/Number[]} ids
 *
 * @return Array of Numbers
 */
exports.convertIds = function (ids) {
    var convertedIds = [];

    for (var i = 0; i < ids.length; i++) {
        convertedIds.push(Number(ids[i]));
    }

    return convertedIds;
};

/**
 * First found value for the given keys.
 *
 * @param {Object} options
 *      Object with key-value properties
 * @param {String[]} keys*
 *      Key list
 */
exports.getValueFor = function (options) {
    var keys = Array.apply(null, arguments).slice(1);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (options.hasOwnProperty(key)) {
            return options[key];
        }
    }
};

/**
 * Fire event with given arguments.
 *
 * @param {String} event
 *      The event's name
 * @param {args*}
 *      The callback's arguments
 */
exports.fireEvent = function (event) {
    var args     = Array.apply(null, arguments).slice(1),
        listener = this._listener[event];

    if (!listener)
        return;

    for (var i = 0; i < listener.length; i++) {
        var fn    = listener[i][0],
            scope = listener[i][1];

        fn.apply(scope, args);
    }
};

/**
 * Execute the native counterpart.
 *
 * @param {String} action
 *      The name of the action
 * @param args[]
 *      Array of arguments
 * @param {Function} callback
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 */
exports.exec = function (action, args, callback, scope) {
    var fn = this.createCallbackFn(callback, scope),
        params = [];

    if (Array.isArray(args)) {
        params = args;
    } else if (args) {
        params.push(args);
    }

    exec(fn, null, 'LocalNotification', action, params);
};

/*********
 * HOOKS *
 *********/

// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
    // Device is ready now, the listeners are registered
    // and all queued events can be executed.
    exec(null, null, 'LocalNotification', 'deviceready', []);
});

// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
    // Device plugin is ready now
    channel.onCordovaInfoReady.subscribe(function () {
        // Merge platform specifics into defaults
        exports.applyPlatformSpecificOptions();
    });
});
<|endoftext|>


<commit_before>
// fullscreen
(function(){var a={supportsFullScreen:!1,nonNativeSupportsFullScreen:!1,isFullScreen:function(){return!1},requestFullScreen:function(){},cancelFullScreen:function(){},fullScreenEventName:"",prefix:""},b="webkit moz o ms khtml".split(" ");if(typeof document.cancelFullScreen!="undefined")a.supportsFullScreen=!0;else for(var c=0,d=b.length;c<d;c++){a.prefix=b[c];if(typeof document[a.prefix+"CancelFullScreen"]!="undefined"){a.supportsFullScreen=!0;break}}a.supportsFullScreen?(a.fullScreenEventName=a.prefix+"fullscreenchange",a.isFullScreen=function(){switch(this.prefix){case"":return document.fullScreen;case"webkit":return document.webkitIsFullScreen;default:return document[this.prefix+"FullScreen"]}},a.requestFullScreen=function(a){return this.prefix===""?a.requestFullScreen():a[this.prefix+"RequestFullScreen"]()},a.cancelFullScreen=function(a){return this.prefix===""?document.cancelFullScreen():document[this.prefix+"CancelFullScreen"]()}):typeof window.ActiveXObject!="undefined"&&(a.nonNativeSupportsFullScreen=!0,a.requestFullScreen=a.requestFullScreen=function(a){var b=new ActiveXObject("WScript.Shell");b!==null&&b.SendKeys("{F11}")},a.isFullScreen=function(){return document.body.clientHeight==screen.height&&document.body.clientWidth==screen.width}),typeof jQuery!="undefined"&&(jQuery.fn.requestFullScreen=function(){return this.each(function(){a.supportsFullScreen&&a.requestFullScreen(this)})}),window.fullScreenApi=a})();

(function() {

    var chart,
        old_chart_attributes;

    function renderChart() {
        if (__dw.vis && !__dw.vis.supportsSmartRendering()) {
            // a current visualization exists but it is not smart
            // enough to re-render itself properly, so we need to
            // reset and remove it
            __dw.vis.reset();
        }

        // compute chart dimensions
        var w = $('#chart').innerWidth(),
            h = dw.utils.getMaxChartHeight($('#chart'));

        if (!$.support.leadingWhitespace) w -= 10; // IE Fix
        w -= $('body').css('padding-left').replace('px', '');
        w -= $('body').css('padding-right').replace('px', '');

        var vis;
        if (__dw.vis && __dw.vis.supportsSmartRendering()) {
            // a current visualization exists and it is smart enough
            // to re-render itself
            vis = __dw.vis;
        } else {
            // we have to create a new vis
            vis = __dw.vis = getVis();
            chart.vis(vis);
        }

        vis.size(w, h);

        initResizeHandler();
        initFullscreen();

        // update data link to point to edited dataset
        if (!window['__ltie9']) {
            $('a[href=data]')
                .attr('download', 'data-'+chart.get('id')+'.csv')
                .attr('href', 'data:application/octet-stream;charset=utf-8,' +
                    encodeURIComponent(chart.dataset().toCSV()));
        }

        chart.render($('#chart'));
    }

    function chartLoaded() {
        chart = dw.chart(__dw.params.chartJSON)
                .locale(__dw.params.chartLocale)
                .metricPrefix(__dw.params.metricPrefix)
                .theme(dw.theme(__dw.params.themeId));
        return chart.load();
    }

    function getVis() {
        var vis = dw.visualization(__dw.params.visId);
        vis.meta = __dw.params.visJSON;
        vis.lang = __dw.params.lang;
        return vis;
    }

    function initResizeHandler() {
        var reload_timer;
        // IE continuosly reloads the chart for some strange reasons
        if (navigator.userAgent.match(/iPad|msie/i) == null) {
            $(window).off('resize').on('resize', function() {
                // IMPORTANT: throttle resize events, do not remover timeout
                if (reload_timer) clearTimeout(reload_timer);
                reload_timer = setTimeout(function() {
                    renderChart();
                }, 300);
            });
        }
    }

    function initFullscreen() {
        var isFullScreen = false;
        $(window).bind('resize', function() {
            if (isFullScreen != fullScreenApi.isFullScreen()) { // video fullscreen mode has changed
                isFullScreen = fullScreenApi.isFullScreen();

                if (isFullScreen) {
                    $('.chart').addClass('fullscreen');
                    // you have just ENTERED full screen video
                } else {
                    $('.chart').removeClass('fullscreen');
                    // you have just EXITED full screen video
                }
            }
        });

        $("a[data-toggle='fullscreen']").click(function(e) {
            if (fullScreenApi.supportsFullScreen) {
                e.preventDefault();
                $('html').requestFullScreen();
            }
        });
    }

    window.__dw = {
        init: function(params) {
            __dw.params = params;
            __dw.old_attrs = old_chart_attributes = params.chartJSON;
            if(!getVis().checkBrowserCompatibility()){
                window.location.href = 'static.html';
                return;
            }
            $.when($.ready(), chartLoaded()).done(renderChart);
        },
        render: (function() {
            var timeout;
            return function() {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    renderChart();
                }, 200);
            };
        })()
    };

})();
<commit_msg>comment<commit_after>
/*
 * This piece of code is inserted at the bottom of every Datawrapper
 * chart. It's main purpose is to trigger the chart rendering.
 */

// fullscreen
(function(){var a={supportsFullScreen:!1,nonNativeSupportsFullScreen:!1,isFullScreen:function(){return!1},requestFullScreen:function(){},cancelFullScreen:function(){},fullScreenEventName:"",prefix:""},b="webkit moz o ms khtml".split(" ");if(typeof document.cancelFullScreen!="undefined")a.supportsFullScreen=!0;else for(var c=0,d=b.length;c<d;c++){a.prefix=b[c];if(typeof document[a.prefix+"CancelFullScreen"]!="undefined"){a.supportsFullScreen=!0;break}}a.supportsFullScreen?(a.fullScreenEventName=a.prefix+"fullscreenchange",a.isFullScreen=function(){switch(this.prefix){case"":return document.fullScreen;case"webkit":return document.webkitIsFullScreen;default:return document[this.prefix+"FullScreen"]}},a.requestFullScreen=function(a){return this.prefix===""?a.requestFullScreen():a[this.prefix+"RequestFullScreen"]()},a.cancelFullScreen=function(a){return this.prefix===""?document.cancelFullScreen():document[this.prefix+"CancelFullScreen"]()}):typeof window.ActiveXObject!="undefined"&&(a.nonNativeSupportsFullScreen=!0,a.requestFullScreen=a.requestFullScreen=function(a){var b=new ActiveXObject("WScript.Shell");b!==null&&b.SendKeys("{F11}")},a.isFullScreen=function(){return document.body.clientHeight==screen.height&&document.body.clientWidth==screen.width}),typeof jQuery!="undefined"&&(jQuery.fn.requestFullScreen=function(){return this.each(function(){a.supportsFullScreen&&a.requestFullScreen(this)})}),window.fullScreenApi=a})();

(function() {

    var chart,
        old_chart_attributes;

    function renderChart() {
        if (__dw.vis && !__dw.vis.supportsSmartRendering()) {
            // a current visualization exists but it is not smart
            // enough to re-render itself properly, so we need to
            // reset and remove it
            __dw.vis.reset();
        }

        // compute chart dimensions
        var w = $('#chart').innerWidth(),
            h = dw.utils.getMaxChartHeight($('#chart'));

        if (!$.support.leadingWhitespace) w -= 10; // IE Fix
        w -= $('body').css('padding-left').replace('px', '');
        w -= $('body').css('padding-right').replace('px', '');

        var vis;
        if (__dw.vis && __dw.vis.supportsSmartRendering()) {
            // a current visualization exists and it is smart enough
            // to re-render itself
            vis = __dw.vis;
        } else {
            // we have to create a new vis
            vis = __dw.vis = getVis();
            chart.vis(vis);
        }

        vis.size(w, h);

        initResizeHandler();
        initFullscreen();

        // update data link to point to edited dataset
        if (!window['__ltie9']) {
            $('a[href=data]')
                .attr('download', 'data-'+chart.get('id')+'.csv')
                .attr('href', 'data:application/octet-stream;charset=utf-8,' +
                    encodeURIComponent(chart.dataset().toCSV()));
        }

        chart.render($('#chart'));
    }

    function chartLoaded() {
        chart = dw.chart(__dw.params.chartJSON)
                .locale(__dw.params.chartLocale)
                .metricPrefix(__dw.params.metricPrefix)
                .theme(dw.theme(__dw.params.themeId));
        return chart.load();
    }

    function getVis() {
        var vis = dw.visualization(__dw.params.visId);
        vis.meta = __dw.params.visJSON;
        vis.lang = __dw.params.lang;
        return vis;
    }

    function initResizeHandler() {
        var reload_timer;
        // IE continuosly reloads the chart for some strange reasons
        if (navigator.userAgent.match(/iPad|msie/i) == null) {
            $(window).off('resize').on('resize', function() {
                // IMPORTANT: throttle resize events, do not remover timeout
                if (reload_timer) clearTimeout(reload_timer);
                reload_timer = setTimeout(function() {
                    renderChart();
                }, 300);
            });
        }
    }

    function initFullscreen() {
        var isFullScreen = false;
        $(window).bind('resize', function() {
            if (isFullScreen != fullScreenApi.isFullScreen()) { // video fullscreen mode has changed
                isFullScreen = fullScreenApi.isFullScreen();

                if (isFullScreen) {
                    $('.chart').addClass('fullscreen');
                    // you have just ENTERED full screen video
                } else {
                    $('.chart').removeClass('fullscreen');
                    // you have just EXITED full screen video
                }
            }
        });

        $("a[data-toggle='fullscreen']").click(function(e) {
            if (fullScreenApi.supportsFullScreen) {
                e.preventDefault();
                $('html').requestFullScreen();
            }
        });
    }

    window.__dw = {
        init: function(params) {
            __dw.params = params;
            __dw.old_attrs = old_chart_attributes = params.chartJSON;
            if(!getVis().checkBrowserCompatibility()){
                window.location.href = 'static.html';
                return;
            }
            $.when($.ready(), chartLoaded()).done(renderChart);
        },
        render: (function() {
            var timeout;
            return function() {
                clearTimeout(timeout);
                timeout = setTimeout(function() {
                    renderChart();
                }, 200);
            };
        })()
    };

})();
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/;
const RESERVED_IDENTIFER = [
	"break",
	"case",
	"catch",
	"class",
	"const",
	"continue",
	"debugger",
	"default",
	"delete",
	"do",
	"else",
	"export",
	"extends",
	"finally",
	"for",
	"function",
	"if",
	"import",
	"in",
	"instanceof",
	"new",
	"return",
	"super",
	"switch",
	"this",
	"throw",
	"try",
	"typeof",
	"var",
	"void",
	"while",
	"with",
	"enum",
	// strict mode
	"implements",
	"interface",
	"let",
	"package",
	"private",
	"protected",
	"public",
	"static",
	"yield",
	"yield",
	// module code
	"await",
	// skip future reserved keywords defined under ES1 till ES3
	// additional
	"null",
	"true",
	"false"
];

const propertyAccess = (properties, start = 0) => {
	let str = "";
	for (let i = start; i < properties.length; i++) {
		const p = properties[i];
		if (`${+p}` === p) {
			str += `[${p}]`;
		} else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFER.includes(p)) {
			str += `.${p}`;
		} else {
			str += `[${JSON.stringify(p)}]`;
		}
	}
	return str;
};

module.exports = propertyAccess;
<commit_msg>use a Set for better performance<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/;
const RESERVED_IDENTIFER = new Set([
	"break",
	"case",
	"catch",
	"class",
	"const",
	"continue",
	"debugger",
	"default",
	"delete",
	"do",
	"else",
	"export",
	"extends",
	"finally",
	"for",
	"function",
	"if",
	"import",
	"in",
	"instanceof",
	"new",
	"return",
	"super",
	"switch",
	"this",
	"throw",
	"try",
	"typeof",
	"var",
	"void",
	"while",
	"with",
	"enum",
	// strict mode
	"implements",
	"interface",
	"let",
	"package",
	"private",
	"protected",
	"public",
	"static",
	"yield",
	"yield",
	// module code
	"await",
	// skip future reserved keywords defined under ES1 till ES3
	// additional
	"null",
	"true",
	"false"
]);

const propertyAccess = (properties, start = 0) => {
	let str = "";
	for (let i = start; i < properties.length; i++) {
		const p = properties[i];
		if (`${+p}` === p) {
			str += `[${p}]`;
		} else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFER.has(p)) {
			str += `.${p}`;
		} else {
			str += `[${JSON.stringify(p)}]`;
		}
	}
	return str;
};

module.exports = propertyAccess;
<|endoftext|>


<commit_before>onmessage = function(event) {
  if (event.data.type === 'ping') {
    postMessage('Pinged: ' + event.data.value);
  }
};<commit_msg>Some instructional comments for index.worker.js<commit_after>onmessage = function(event) {

  // event.data is an object from the community page
  // the type property tells you what kind of message is sent

  if (event.data.type === 'ping') {

    // use postMessage() to send anything you want back
    // to the main community page!

    postMessage('Pinged: ' + event.data.value);
  }
};
<|endoftext|>


<commit_before><commit_msg>#5404 Rename functionality for page and product<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import ModelObserver from '../models/model-observer';

export default class ObserveModel extends React.Component {
  static propTypes = {
    model: PropTypes.shape({
      onDidUpdate: PropTypes.func.isRequired,
    }),
    fetchData: PropTypes.func.isRequired,
    children: PropTypes.func.isRequired,
  }

  constructor(props, context) {
    super(props, context);

    this.state = {data: null};
    this.modelObserver = new ModelObserver({fetchData: this.fetchData, didUpdate: this.didUpdate});
  }

  componentWillMount() {
    this.mounted = true;
    this.modelObserver.setActiveModel(this.props.model);
  }

  componentWillReceiveProps(nextProps) {
    this.modelObserver.setActiveModel(nextProps.model);
  }

  fetchData = model => this.props.fetchData(model);

  didUpdate = () => {
    if (this.mounted) {
      const data = this.modelObserver.getActiveModelData();
      this.setState({data});
    }
  }

  render() {
    return this.props.children(this.state.data);
  }

  componentWillUnmount() {
    this.mounted = false;
    this.modelObserver.destroy();
  }
}
<commit_msg>Remove deprecated lifecycle methods from ObserveModel<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import ModelObserver from '../models/model-observer';

export default class ObserveModel extends React.Component {
  static propTypes = {
    model: PropTypes.shape({
      onDidUpdate: PropTypes.func.isRequired,
    }),
    fetchData: PropTypes.func.isRequired,
    children: PropTypes.func.isRequired,
  }

  constructor(props, context) {
    super(props, context);

    this.state = {data: null};
    this.modelObserver = new ModelObserver({fetchData: this.fetchData, didUpdate: this.didUpdate});
  }

  componentDidMount() {
    this.mounted = true;
    this.modelObserver.setActiveModel(this.props.model);
  }

  componentDidUpdate() {
    this.modelObserver.setActiveModel(this.props.model);
  }

  fetchData = model => this.props.fetchData(model);

  didUpdate = () => {
    if (this.mounted) {
      const data = this.modelObserver.getActiveModelData();
      this.setState({data});
    }
  }

  render() {
    return this.props.children(this.state.data);
  }

  componentWillUnmount() {
    this.mounted = false;
    this.modelObserver.destroy();
  }
}
<|endoftext|>


<commit_before>
define([
    'service/vertex',
    'util/vertex/formatters'
], function(VertexService, F) {

    var PROPERTIES_TO_INSPECT_FOR_CHANGES = [
        'http://lumify.io#visibility',
        'http://lumify.io#visibilityJson',
        'detectedObjects',
        'properties',
        'sandboxStatus'
    ];

    return withVertexCache;

    function withVertexCache() {

        this.cachedVertices = {};
        this.workspaceVertices = {};
        if (!this.vertexService) {
            this.vertexService = new VertexService();
        }

        this.resemblesVertices = function(val) {
            return val && val.length && val[0].id && val[0].properties;
        };

        this.verticesInWorkspace = function() {
            return _.values(_.pick(this.cachedVertices, _.keys(this.workspaceVertices)));
        };

        this.copy = function(obj) {
            return JSON.parse(JSON.stringify(obj));
        };

        this.workspaceOnlyVertexCopy = function(vertex) {
            return {
                id: vertex.id,
                workspace: this.copy(vertex.workspace || this.workspaceVertices[vertex.id] || {})
            };
        };

        this.workspaceOnlyVertex = function(id) {
            return {
                id: id,
                workspace: this.workspaceVertices[id] || {}
            };
        };

        this.inWorkspace = function(vertex) {
            return !!this.workspaceVertices[_.isString(vertex) ? vertex : vertex.id];
        };

        this.vertex = function(id) {
            return this.cachedVertices['' + id];
        };

        this.vertices = function(ids) {
            if (ids.toArray) {
                ids = ids.toArray();
            }

            ids = ids.map(function(id) {
                return id.id ? id.id : '' + id;
            });

            return _.values(_.pick(this.cachedVertices, ids));
        };

        this.refresh = function(vertex) {
            var self = this,
                deferred = null;

            if (_.isArray(vertex)) {
                var vertices = [], toRequest = [];
                vertex.forEach(function(v) {
                    var cachedVertex = self.vertex(v);
                    if (cachedVertex) {
                        vertices.push(cachedVertex);
                    } else {
                        toRequest.push(v);
                    }
                })
                deferred = $.Deferred();

                if (toRequest.length) {
                    this.vertexService.getMultiple(toRequest)
                        .done(function(data) {
                            deferred.resolve(vertices.concat(data.vertices));
                        })
                } else {
                    deferred.resolve(vertices);
                }

                return deferred;
            } else if (_.isString(vertex) || _.isNumber(vertex)) {
                deferred = this.vertexService.getVertexProperties(vertex);
            } else {
                deferred = this.vertexService.getVertexProperties(vertex.id);
            }

            return deferred;
        };

        this.getVertexTitle = function(vertexId) {
            var deferredTitle = $.Deferred(),
                v,
                vertexTitle;

            v = this.vertex(vertexId);
            if (v) {
                vertexTitle = F.vertex.title(v);
                return deferredTitle.resolve(vertexTitle);
            }

            this.refresh(vertexId).done(function(vertex) {
                vertexTitle = F.vertex.title(vertex);
                deferredTitle.resolve(vertexTitle);
            });

            return deferredTitle;
        };

        this.updateCacheWithVertex = function(vertex, options) {
            var id = vertex.id,
                cache = this.cachedVertices[id] || (this.cachedVertices[id] = { id: id }),
                hasChanged = !_.isEqual(
                    _.pick.apply(_, [cache].concat(PROPERTIES_TO_INSPECT_FOR_CHANGES)),
                    _.pick.apply(_, [vertex].concat(PROPERTIES_TO_INSPECT_FOR_CHANGES))
                );

            if (!cache.properties) cache.properties = [];
            if (!cache.workspace) cache.workspace = {};

            verifyVisibility(vertex);

            cache.properties = _.isUndefined(vertex.properties) ? cache.properties : vertex.properties;
            cache.workspace = $.extend(true, {}, cache.workspace, vertex.workspace || {});

            $.extend(cache, _.pick(vertex, [
                'http://lumify.io#visibility',
                'http://lumify.io#visibilityJson',
                'sandboxStatus']));

            cache.detectedObjects = vertex.detectedObjects;

            if (this.workspaceVertices[id]) {
                this.workspaceVertices[id] = cache.workspace;
            }

            var conceptType = F.vertex.prop(cache, 'conceptType', 'http://www.w3.org/2002/07/owl#Thing');
            cache.concept = this.cachedConcepts.byId[conceptType];
            if (cache.concept) {
                setPreviewsForVertex(cache, this.workspaceId);
            } else {
                console.error('Unable to attach concept to vertex', conceptType);
            }

            cache.detectedObjects = cache.detectedObjects || [];

            $.extend(true, vertex, cache);

            return (options && options.returnNullIfNotChanged === true && !hasChanged) ? null : cache;
        };

        function verifyVisibility(vertex) {
            if (!vertex) return;

            var key = 'http://lumify.io#visibilityJson',
                defaultJson = {
                    source: '',
                    _addedToPreventErrors: ''
                };

            if (!(key in vertex)) {
                vertex[key] = defaultJson;
            }

            if (vertex.properties) {
                _.each(vertex.properties, function(property) {
                    if (!(key in property)) {
                        property[key] = defaultJson;
                    }
                });
            }
        }

        function setPreviewsForVertex(vertex, currentWorkspace) {
            var params = {
                    workspaceId: currentWorkspace,
                    graphVertexId: vertex.id
                },
                artifactUrl = function(type, p) {
                    return _.template('artifact/{ type }?' + $.param($.extend(params, p || {})), { type: type });
                },
                entityImageVertexId = F.vertex.prop(vertex, 'entityImageVertexId');

            vertex.imageSrcIsFromConcept = false;

            if (entityImageVertexId) {
                vertex.imageSrc = artifactUrl('thumbnail', { graphVertexId: entityImageVertexId, width: 150 });
                vertex.imageDetailSrc = artifactUrl('thumbnail', { graphVertexId: entityImageVertexId, width: 800 });
            } else {

                // TODO: scale glyphs
                vertex.imageSrc = vertex.concept.glyphIconHref;
                vertex.imageRawSrc = artifactUrl('raw');
                vertex.imageSrcIsFromConcept = true;

                switch (vertex.concept.displayType) {

                    case 'image':
                        vertex.imageSrc = artifactUrl('thumbnail', { width: 150 });
                        vertex.imageSrcIsFromConcept = false;
                        vertex.imageDetailSrc = artifactUrl('thumbnail', { width: 800 });
                        break;

                    case 'video':
                        vertex.properties.forEach(function(p) {
                            if (p.name === 'http://lumify.io#rawPosterFrame') {
                                vertex.imageSrc = artifactUrl('poster-frame');
                                vertex.imageSrcIsFromConcept = false;
                            } else if (p.name === 'http://lumify.io#videoPreviewImage') {
                                vertex.imageFramesSrc = artifactUrl('video-preview');
                            }
                        });
                        break;
                }
            }
        }
    }
});
<commit_msg>Fix detail image for glyphs<commit_after>
define([
    'service/vertex',
    'util/vertex/formatters'
], function(VertexService, F) {

    var PROPERTIES_TO_INSPECT_FOR_CHANGES = [
        'http://lumify.io#visibility',
        'http://lumify.io#visibilityJson',
        'detectedObjects',
        'properties',
        'sandboxStatus'
    ];

    return withVertexCache;

    function withVertexCache() {

        this.cachedVertices = {};
        this.workspaceVertices = {};
        if (!this.vertexService) {
            this.vertexService = new VertexService();
        }

        this.resemblesVertices = function(val) {
            return val && val.length && val[0].id && val[0].properties;
        };

        this.verticesInWorkspace = function() {
            return _.values(_.pick(this.cachedVertices, _.keys(this.workspaceVertices)));
        };

        this.copy = function(obj) {
            return JSON.parse(JSON.stringify(obj));
        };

        this.workspaceOnlyVertexCopy = function(vertex) {
            return {
                id: vertex.id,
                workspace: this.copy(vertex.workspace || this.workspaceVertices[vertex.id] || {})
            };
        };

        this.workspaceOnlyVertex = function(id) {
            return {
                id: id,
                workspace: this.workspaceVertices[id] || {}
            };
        };

        this.inWorkspace = function(vertex) {
            return !!this.workspaceVertices[_.isString(vertex) ? vertex : vertex.id];
        };

        this.vertex = function(id) {
            return this.cachedVertices['' + id];
        };

        this.vertices = function(ids) {
            if (ids.toArray) {
                ids = ids.toArray();
            }

            ids = ids.map(function(id) {
                return id.id ? id.id : '' + id;
            });

            return _.values(_.pick(this.cachedVertices, ids));
        };

        this.refresh = function(vertex) {
            var self = this,
                deferred = null;

            if (_.isArray(vertex)) {
                var vertices = [], toRequest = [];
                vertex.forEach(function(v) {
                    var cachedVertex = self.vertex(v);
                    if (cachedVertex) {
                        vertices.push(cachedVertex);
                    } else {
                        toRequest.push(v);
                    }
                })
                deferred = $.Deferred();

                if (toRequest.length) {
                    this.vertexService.getMultiple(toRequest)
                        .done(function(data) {
                            deferred.resolve(vertices.concat(data.vertices));
                        })
                } else {
                    deferred.resolve(vertices);
                }

                return deferred;
            } else if (_.isString(vertex) || _.isNumber(vertex)) {
                deferred = this.vertexService.getVertexProperties(vertex);
            } else {
                deferred = this.vertexService.getVertexProperties(vertex.id);
            }

            return deferred;
        };

        this.getVertexTitle = function(vertexId) {
            var deferredTitle = $.Deferred(),
                v,
                vertexTitle;

            v = this.vertex(vertexId);
            if (v) {
                vertexTitle = F.vertex.title(v);
                return deferredTitle.resolve(vertexTitle);
            }

            this.refresh(vertexId).done(function(vertex) {
                vertexTitle = F.vertex.title(vertex);
                deferredTitle.resolve(vertexTitle);
            });

            return deferredTitle;
        };

        this.updateCacheWithVertex = function(vertex, options) {
            var id = vertex.id,
                cache = this.cachedVertices[id] || (this.cachedVertices[id] = { id: id }),
                hasChanged = !_.isEqual(
                    _.pick.apply(_, [cache].concat(PROPERTIES_TO_INSPECT_FOR_CHANGES)),
                    _.pick.apply(_, [vertex].concat(PROPERTIES_TO_INSPECT_FOR_CHANGES))
                );

            if (!cache.properties) cache.properties = [];
            if (!cache.workspace) cache.workspace = {};

            verifyVisibility(vertex);

            cache.properties = _.isUndefined(vertex.properties) ? cache.properties : vertex.properties;
            cache.workspace = $.extend(true, {}, cache.workspace, vertex.workspace || {});

            $.extend(cache, _.pick(vertex, [
                'http://lumify.io#visibility',
                'http://lumify.io#visibilityJson',
                'sandboxStatus']));

            cache.detectedObjects = vertex.detectedObjects;

            if (this.workspaceVertices[id]) {
                this.workspaceVertices[id] = cache.workspace;
            }

            var conceptType = F.vertex.prop(cache, 'conceptType', 'http://www.w3.org/2002/07/owl#Thing');
            cache.concept = this.cachedConcepts.byId[conceptType];
            if (cache.concept) {
                setPreviewsForVertex(cache, this.workspaceId);
            } else {
                console.error('Unable to attach concept to vertex', conceptType);
            }

            cache.detectedObjects = cache.detectedObjects || [];

            $.extend(true, vertex, cache);

            return (options && options.returnNullIfNotChanged === true && !hasChanged) ? null : cache;
        };

        function verifyVisibility(vertex) {
            if (!vertex) return;

            var key = 'http://lumify.io#visibilityJson',
                defaultJson = {
                    source: '',
                    _addedToPreventErrors: ''
                };

            if (!(key in vertex)) {
                vertex[key] = defaultJson;
            }

            if (vertex.properties) {
                _.each(vertex.properties, function(property) {
                    if (!(key in property)) {
                        property[key] = defaultJson;
                    }
                });
            }
        }

        function setPreviewsForVertex(vertex, currentWorkspace) {
            var params = {
                    workspaceId: currentWorkspace,
                    graphVertexId: vertex.id
                },
                artifactUrl = function(type, p) {
                    return _.template('artifact/{ type }?' + $.param($.extend(params, p || {})), { type: type });
                },
                entityImageVertexId = F.vertex.prop(vertex, 'entityImageVertexId');

            vertex.imageSrcIsFromConcept = false;

            if (entityImageVertexId) {
                vertex.imageSrc = artifactUrl('thumbnail', { graphVertexId: entityImageVertexId, width: 150 });
                vertex.imageDetailSrc = artifactUrl('thumbnail', { graphVertexId: entityImageVertexId, width: 800 });
            } else {

                // TODO: scale glyphs
                vertex.imageSrc = vertex.concept.glyphIconHref;
                vertex.imageDetailSrc = vertex.concept.glyphIconHref;
                vertex.imageRawSrc = artifactUrl('raw');
                vertex.imageSrcIsFromConcept = true;

                switch (vertex.concept.displayType) {

                    case 'image':
                        vertex.imageSrc = artifactUrl('thumbnail', { width: 150 });
                        vertex.imageSrcIsFromConcept = false;
                        vertex.imageDetailSrc = artifactUrl('thumbnail', { width: 800 });
                        break;

                    case 'video':
                        vertex.properties.forEach(function(p) {
                            if (p.name === 'http://lumify.io#rawPosterFrame') {
                                vertex.imageSrc = artifactUrl('poster-frame');
                                vertex.imageDetailSrc = artifactUrl('poster-frame');
                                vertex.imageSrcIsFromConcept = false;
                            } else if (p.name === 'http://lumify.io#videoPreviewImage') {
                                vertex.imageFramesSrc = artifactUrl('video-preview');
                            }
                        });
                        break;
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.view_pagination = function(debug) {
    var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
    db.deleteDb();
    db.createDb();
    if (debug) debugger;

    var docs = makeDocs(0, 100);
    db.bulkSave(docs);

    var queryFun = function(doc) { emit(doc.integer, null); };
    var i;

    // page through the view ascending
    for (i = 0; i < docs.length; i += 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == i);
      var j;
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }

      // test aliases start_key and start_key_doc_id
      queryResults = db.query(queryFun, null, {
        start_key: i,
        start_key_doc_id: i,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == i);
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }
    }

    // page through the view descending
    for (i = docs.length - 1; i >= 0; i -= 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        descending: true,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == docs.length - i - 1);
      var j;
      for (j = 0; j < 10; j++) {
        T(queryResults.rows[j].key == i - j);
      }
    }

    // ignore decending=false. CouchDB should just ignore that.
    for (i = 0; i < docs.length; i += 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        descending: false,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == i);
      var j;
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }
    }

    function testEndkeyDocId(queryResults) {
      T(queryResults.rows.length == 35);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == 1);
      T(queryResults.rows[0].id == "1");
      T(queryResults.rows[1].id == "10");
      T(queryResults.rows[2].id == "11");
      T(queryResults.rows[3].id == "12");
      T(queryResults.rows[4].id == "13");
      T(queryResults.rows[5].id == "14");
      T(queryResults.rows[6].id == "15");
      T(queryResults.rows[7].id == "16");
      T(queryResults.rows[8].id == "17");
      T(queryResults.rows[9].id == "18");
      T(queryResults.rows[10].id == "19");
      T(queryResults.rows[11].id == "2");
      T(queryResults.rows[12].id == "20");
      T(queryResults.rows[13].id == "21");
      T(queryResults.rows[14].id == "22");
      T(queryResults.rows[15].id == "23");
      T(queryResults.rows[16].id == "24");
      T(queryResults.rows[17].id == "25");
      T(queryResults.rows[18].id == "26");
      T(queryResults.rows[19].id == "27");
      T(queryResults.rows[20].id == "28");
      T(queryResults.rows[21].id == "29");
      T(queryResults.rows[22].id == "3");
      T(queryResults.rows[23].id == "30");
      T(queryResults.rows[24].id == "31");
      T(queryResults.rows[25].id == "32");
      T(queryResults.rows[26].id == "33");
      T(queryResults.rows[27].id == "34");
      T(queryResults.rows[28].id == "35");
      T(queryResults.rows[29].id == "36");
      T(queryResults.rows[30].id == "37");
      T(queryResults.rows[31].id == "38");
      T(queryResults.rows[32].id == "39");
      T(queryResults.rows[33].id == "4");
      T(queryResults.rows[34].id == "40");
    }

    // test endkey_docid
    var queryResults = db.query(function(doc) { emit(null, null); }, null, {
      startkey: null,
      startkey_docid: 1,
      endkey: null,
      endkey_docid: 40
    });
    testEndkeyDocId(queryResults);

    // test aliases end_key_doc_id and end_key
    queryResults = db.query(function(doc) { emit(null, null); }, null, {
      start_key: null,
      start_key_doc_id: 1,
      end_key: null,
      end_key_doc_id: 40
    });
    testEndkeyDocId(queryResults);

  };
<commit_msg>JS test: update view_pagination.js for 2.0<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.view_pagination = function(debug) {
    var db_name = get_random_db_name();
    var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
    db.createDb();
    if (debug) debugger;

    var docs = makeDocs(0, 100);
    db.bulkSave(docs);

    var queryFun = function(doc) { emit(doc.integer, null); };
    var i;

    // page through the view ascending
    for (i = 0; i < docs.length; i += 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      TEquals(docs.length, queryResults.total_rows, "doc.length should match query.length");
      T(queryResults.offset == i);
      var j;
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }

      // test aliases start_key and start_key_doc_id
      queryResults = db.query(queryFun, null, {
        start_key: i,
        start_key_doc_id: i,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == i);
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }
    }

    // page through the view descending
    for (i = docs.length - 1; i >= 0; i -= 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        descending: true,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == docs.length - i - 1);
      var j;
      for (j = 0; j < 10; j++) {
        T(queryResults.rows[j].key == i - j);
      }
    }

    // ignore decending=false. CouchDB should just ignore that.
    for (i = 0; i < docs.length; i += 10) {
      var queryResults = db.query(queryFun, null, {
        startkey: i,
        startkey_docid: i,
        descending: false,
        limit: 10
      });
      T(queryResults.rows.length == 10);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == i);
      var j;
      for (j = 0; j < 10;j++) {
        T(queryResults.rows[j].key == i + j);
      }
    }

    function testEndkeyDocId(queryResults) {
      T(queryResults.rows.length == 35);
      T(queryResults.total_rows == docs.length);
      T(queryResults.offset == 1);
      T(queryResults.rows[0].id == "1");
      T(queryResults.rows[1].id == "10");
      T(queryResults.rows[2].id == "11");
      T(queryResults.rows[3].id == "12");
      T(queryResults.rows[4].id == "13");
      T(queryResults.rows[5].id == "14");
      T(queryResults.rows[6].id == "15");
      T(queryResults.rows[7].id == "16");
      T(queryResults.rows[8].id == "17");
      T(queryResults.rows[9].id == "18");
      T(queryResults.rows[10].id == "19");
      T(queryResults.rows[11].id == "2");
      T(queryResults.rows[12].id == "20");
      T(queryResults.rows[13].id == "21");
      T(queryResults.rows[14].id == "22");
      T(queryResults.rows[15].id == "23");
      T(queryResults.rows[16].id == "24");
      T(queryResults.rows[17].id == "25");
      T(queryResults.rows[18].id == "26");
      T(queryResults.rows[19].id == "27");
      T(queryResults.rows[20].id == "28");
      T(queryResults.rows[21].id == "29");
      T(queryResults.rows[22].id == "3");
      T(queryResults.rows[23].id == "30");
      T(queryResults.rows[24].id == "31");
      T(queryResults.rows[25].id == "32");
      T(queryResults.rows[26].id == "33");
      T(queryResults.rows[27].id == "34");
      T(queryResults.rows[28].id == "35");
      T(queryResults.rows[29].id == "36");
      T(queryResults.rows[30].id == "37");
      T(queryResults.rows[31].id == "38");
      T(queryResults.rows[32].id == "39");
      T(queryResults.rows[33].id == "4");
      T(queryResults.rows[34].id == "40");
    }

    // test endkey_docid
    var queryResults = db.query(function(doc) { emit(null, null); }, null, {
      startkey: null,
      startkey_docid: 1,
      endkey: null,
      endkey_docid: 40
    });
    testEndkeyDocId(queryResults);

    // test aliases end_key_doc_id and end_key
    queryResults = db.query(function(doc) { emit(null, null); }, null, {
      start_key: null,
      start_key_doc_id: 1,
      end_key: null,
      end_key_doc_id: 40
    });
    testEndkeyDocId(queryResults);

    // cleanup
    db.deleteDb();
  };
<|endoftext|>


<commit_before>describe("BaseModel", function() {

	describe("Serialization", function() {

		xit("escapes HTML");

		describe("mergeOptions", function() {

			xit("should be tested");

		});

		describe("serialize", function() {

			xit("does not require arguments");

			xit("takes a type");

			xit("takes a type and options");

		});

	});

});
<commit_msg>Fleshing out a test for BaseModel.Serialization#mergeOptions<commit_after>describe("BaseModel", function() {

	describe("Serialization", function() {

		xit("escapes HTML");

		describe("mergeOptions", function() {

			it("performs a shallow merge of one argument into the next", function() {
				var model = new BaseModel();
				var a = {
					format: "queryString",
					foo: {bar: 1}
				};
				var b = {
					rootElement: "test",
					foo: {bar: 2}
				};
				var c = model.mergeOptions(a, b);

				expect(c.format).toEqual("queryString");
				expect(c.rootElement).toEqual("test");
				expect(c.foo).toStrictlyEqual(b.foo);
				expect(c.foo.bar).toEqual(b.foo.bar);
			});

		});

		describe("serialize", function() {

			xit("does not require arguments");

			xit("takes a type");

			xit("takes a type and options");

		});

	});

});
<|endoftext|>


<commit_before>/**
 * @file webpack.config.base.js
 * @author 刘巍峰 <weifeng3@staff.weibo.com>
 * Created on 2016-02-13 23:53
 */
/**
 * Created by liuweifeng on 16/1/14.
 */
'use strict';
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = function (options) {
    const localConfig = require(process.cwd() + '/package.json')['xianyu'] || {};
    options = Object.assign(options, localConfig);

    const template = path.join(__dirname, 'index.ejs');
    let plugins = [];
    let entry = {};
    if (typeof options.entry === 'string') {
        options.entry = {
            'app': options.entry
        }
    }
    Object.keys(options.entry).forEach(function (e) {
        entry[e] = process.cwd() + '/' + options.entry[e];
        let hwpConfig = {
            title: options.title || '咸鱼 - 前端开发脚手架',
            template: template,
            chunks: [e],
            filename: e + '.html'
        };
        if (options.template) {
            let content = fs.readFileSync(path.resolve(path.join(process.cwd(), options.template)));
            if (content.indexOf('<body>') == -1) {
                hwpConfig.content = content;
            } else {
                hwpConfig.templateContent = content;
            }
        }
        plugins[plugins.length] = new HtmlWebpackPlugin(hwpConfig);
    });
    return {
        entry: entry,
        output: {
            path: path.join(process.cwd(), ''),
            filename: '[name].js',
            publicPath: `${options.devHost || 'http://dev.js.weibo.cn'}/${options.module}/build/`
        },
        plugins: plugins,
        resolve: {
            extensions: ['', '.js', '.vue', '.css', '.jsx'],
            root: [path.join(process.cwd(), 'node_modules'), path.join(__dirname, '../node_modules')]
        },
        resolveLoader: {
            root: [path.join(process.cwd(), 'node_modules'), path.join(__dirname, '../node_modules')]
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    loaders: ['babel'],
                    exclude: [/node_modules/]
                },
                {
                    test: /\.json/,
                    loaders: ['json']
                },
                {
                    test: /\.svg$/,
                    loaders: ['raw']
                }
            ]
        },
        babel: {
            presets: [require('babel-preset-es2015'), require('babel-preset-stage-0')],
            plugins: [require('babel-plugin-transform-runtime')]
        }
    };
};
<commit_msg>支持查找与js同名的模板文件<commit_after>/**
 * @file webpack.config.base.js
 * @author 刘巍峰 <weifeng3@staff.weibo.com>
 * Created on 2016-02-13 23:53
 */
/**
 * Created by liuweifeng on 16/1/14.
 */
'use strict';
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = function (options) {
    const localConfig = require(process.cwd() + '/package.json')['xianyu'] || {};
    options = Object.assign(options, localConfig);

    const template = path.join(__dirname, 'index.ejs');
    let plugins = [];
    let entry = {};
    if (typeof options.entry === 'string') {
        options.entry = {
            'app': options.entry
        }
    }
    Object.keys(options.entry).forEach(function (e) {
        entry[e] = process.cwd() + '/' + options.entry[e];
        let hwpConfig = {
            title: options.title || '咸鱼 - 前端开发脚手架',
            template: template,
            chunks: [e],
            filename: e + '.html'
        };
        let tpl;
        if (options.template) {
            tpl = path.resolve(path.join(process.cwd(), options.template));
        }else {
            tpl = path.resolve(path.join(process.cwd(), `src/html/${e}.html`));
        }
        if(fs.existsSync(tpl)){
            let content =fs.readFileSync(tpl, 'utf-8');
            if (content.indexOf('<body>') == -1) {
                hwpConfig.content = content;
            } else {
                hwpConfig.templateContent = content;
            }
        }
        plugins[plugins.length] = new HtmlWebpackPlugin(hwpConfig);
    });
    return {
        entry: entry,
        output: {
            path: path.join(process.cwd(), ''),
            filename: '[name].js',
            publicPath: `${options.devHost || 'http://dev.js.weibo.cn'}/${options.module}/build/`
        },
        plugins: plugins,
        resolve: {
            extensions: ['', '.js', '.vue', '.css', '.jsx'],
            root: [path.join(process.cwd(), 'node_modules'), path.join(__dirname, '../node_modules')]
        },
        resolveLoader: {
            root: [path.join(process.cwd(), 'node_modules'), path.join(__dirname, '../node_modules')]
        },
        module: {
            loaders: [
                {
                    test: /\.jsx?$/,
                    loaders: ['babel'],
                    exclude: [/node_modules/]
                },
                {
                    test: /\.json/,
                    loaders: ['json']
                },
                {
                    test: /\.svg$/,
                    loaders: ['raw']
                }
            ]
        },
        babel: {
            presets: [require('babel-preset-es2015'), require('babel-preset-stage-0')],
            plugins: [require('babel-plugin-transform-runtime')]
        }
    };
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var shell = require('shelljs')
var prompt = require('prompt')
var chalk = require('chalk')

var prompts = require('./prompts')
var spinner = require('../cli-helpers/install-spinner')
var clientFiles = require('./clientFiles')

/**
 * Handle errors from the cli prompts.
 * @param err
 * @returns {number}
 */
function onErr(err) {
  console.log(err)
  return 1
}

/**
 * Runs the spinner for a given amount of time. Currently this isn't being used for any kind of asynchronous action
 * but rather is there to improve the UX of the CLI too. After postinstall the terminal get's flooded with a list of
 * install modules, which hides the postinstall instructions.
 * @param {number} time - How long you want the spinner to run.
 */
function preventFinishFor(time) {
  spinner.start()
  setTimeout(function () {
    spinner.stop()
  }, time)
}

/**
 * An object of strings used for inserting the start script into the user's package.json file with
 * the `shell.sed` command.
 * @type {{flag: string, insertionPoint: string, addition: string, file: string}}
 */
var insertScript = {
  flag: '-i',
  insertionPoint: '"scripts": {',
  addition: '"scripts": {\n    "enclave-serve": "enclave",\n    "enclave-build": "node node_modules/enclave/src/build.js", \n    "enclave-eject": "node node_modules/enclave/src/eject/index.js",',
  file: clientFiles.package
}

/**
 * This method is really ugly and implicit, I'm sorry.
 *
 * It loops through the prompt's result object, and adds each result to a file in the user's root
 * to be referenced later.
 *
 * It also console logs the result object with this weird color library that extends the String
 * prototype to have color properties, god this is terrible.
 * @param err
 * @param {object} result
 * @returns {number}
 */
function configureConfigFile(err, result) {
  for (var key in result) {
    if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) {
      shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config)
    } else {
      shell.echo('exports.' + key + ' = ' + JSON.stringify(result[key]) + '\n').toEnd(clientFiles.config)
    }
  }
  if (err) {
    return onErr(err)
  }
  console.log(chalk.yellow('Here\'s what I\'ve got down, if something is wrong you can edit this in your enclave.js file.:'))
  console.log(chalk.red('  entry: ') + chalk.magenta(result.entry))
  console.log(chalk.red('  output: ') + chalk.magenta(result.output))
  console.log(!result.port ? chalk.red('  port: 8080') : chalk.red('  port: ') + chalk.magenta(result.port))
  console.log(chalk.red('  index: ') + chalk.magenta(result.index))
  console.log(chalk.red('  live: ') + chalk.magenta(result.live))
  console.log(chalk.green('To run your app, just type'), chalk.green.bold('$ npm start'))
  shell.sed(insertScript.flag, insertScript.insertionPoint, insertScript.addition, insertScript.file)
  preventFinishFor(5000)
}

/**
 * Start the CLI prompt.
 */
prompt.start()

/**
 * Throw down that postinstall logo.
 */
shell.exec('bash ./src/cli-helpers/postinstall-logo')

/**
 * Clean out any currently existing config file for a fresh one.
 */
shell.exec('rm ' + clientFiles.config)
shell.exec('touch ' + clientFiles.config)

/**
 * Actually executing all of this magic.
 */
prompt.get(prompts, configureConfigFile)
<commit_msg>update postinstall instructions<commit_after>#!/usr/bin/env node
var shell = require('shelljs')
var prompt = require('prompt')
var chalk = require('chalk')

var prompts = require('./prompts')
var spinner = require('../cli-helpers/install-spinner')
var clientFiles = require('./clientFiles')

/**
 * Handle errors from the cli prompts.
 * @param err
 * @returns {number}
 */
function onErr(err) {
  console.log(err)
  return 1
}

/**
 * Runs the spinner for a given amount of time. Currently this isn't being used for any kind of asynchronous action
 * but rather is there to improve the UX of the CLI too. After postinstall the terminal get's flooded with a list of
 * install modules, which hides the postinstall instructions.
 * @param {number} time - How long you want the spinner to run.
 */
function preventFinishFor(time) {
  spinner.start()
  setTimeout(function () {
    spinner.stop()
  }, time)
}

/**
 * An object of strings used for inserting the start script into the user's package.json file with
 * the `shell.sed` command.
 * @type {{flag: string, insertionPoint: string, addition: string, file: string}}
 */
var insertScript = {
  flag: '-i',
  insertionPoint: '"scripts": {',
  addition: '"scripts": {\n    "enclave-serve": "enclave",\n    "enclave-build": "node node_modules/enclave/src/build.js", \n    "enclave-eject": "node node_modules/enclave/src/eject/index.js",',
  file: clientFiles.package
}

/**
 * This method is really ugly and implicit, I'm sorry.
 *
 * It loops through the prompt's result object, and adds each result to a file in the user's root
 * to be referenced later.
 *
 * It also console logs the result object with this weird color library that extends the String
 * prototype to have color properties, god this is terrible.
 * @param err
 * @param {object} result
 * @returns {number}
 */
function configureConfigFile(err, result) {
  for (var key in result) {
    if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) {
      shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config)
    } else {
      shell.echo('exports.' + key + ' = ' + JSON.stringify(result[key]) + '\n').toEnd(clientFiles.config)
    }
  }
  if (err) {
    return onErr(err)
  }
  console.log(chalk.yellow('Here\'s what I\'ve got down, if something is wrong you can edit this in your enclave.js file.:'))
  console.log(chalk.red('  entry: ') + chalk.magenta(result.entry))
  console.log(chalk.red('  output: ') + chalk.magenta(result.output))
  console.log(!result.port ? chalk.red('  port: 8080') : chalk.red('  port: ') + chalk.magenta(result.port))
  console.log(chalk.red('  index: ') + chalk.magenta(result.index))
  console.log(chalk.red('  live: ') + chalk.magenta(result.live))
  console.log(chalk.green('To run your app, just type'), chalk.green.bold('$ npm run enclave-serve'))
  shell.sed(insertScript.flag, insertScript.insertionPoint, insertScript.addition, insertScript.file)
  preventFinishFor(5000)
}

/**
 * Start the CLI prompt.
 */
prompt.start()

/**
 * Throw down that postinstall logo.
 */
shell.exec('bash ./src/cli-helpers/postinstall-logo')

/**
 * Clean out any currently existing config file for a fresh one.
 */
shell.exec('rm ' + clientFiles.config)
shell.exec('touch ' + clientFiles.config)

/**
 * Actually executing all of this magic.
 */
prompt.get(prompts, configureConfigFile)
<|endoftext|>