<commit_before>"use strict";
/**
 * @module thisissoon.core
 * @author SOON_
 * @requires ngRoute {@link https://docs.angularjs.org/api/ngRoute}
 * @requires ngAnimate: {@link https://docs.angularjs.org/api/ngAnimate}
 * @requires ui-bootstrap: {@link http://angular-ui.github.io/bootstrap}
 * @requires soon.ui
 * @requires soon.utils
 * @requires thisissoon.api
 * @requires sn.velocity
 * @requires duScroll
 */
angular.module("thisissoon.core", [
    "config",
    "ngRoute",
    "ngSanitize",
    "soon.ui",
    "thisissoon.api",
    "thisissoon.nav",
    "thisissoon.cache",
    "thisissoon.animation",
    "sn.velocity",
    "sn.skrollr",
    "sn.addthis",
    "duScroll"
])

.run([
    "$rootScope",
    "ResizeService",
    "$window",
    "$timeout",
    "CacheService",
    "snSkrollr",
    "ENV",
    /**
     * @constructor
     * @param {Service} $rootScope
     * @param {Service} CacheService
     */
    function ($rootScope, ResizeService, $window, $timeout, CacheService, snSkrollr, ENV) {

        ResizeService.add($rootScope.$id, function(event, size) {
            if (size.width >= 1024 && !$rootScope.skrollrInitialised) {
                snSkrollr.init();
                $rootScope.skrollrInitialised = true;
            } else if (size.width < 1024 && $rootScope.skrollrInitialised) {
                $rootScope.skrollrInitialised = false;
                snSkrollr.destroy();
            }
        });

        $rootScope.cache = CacheService;
        $rootScope.env = ENV;

        CacheService.put("navOpen", false);
        CacheService.put("loading", true);
        CacheService.put("projectList", false);

        // close nav menu when changing views
        $rootScope.$on("$routeChangeStart", function() {
            CacheService.put("navOpen", false);
            CacheService.put("loading", true);
        });

        // close nav menu when changing views
        $rootScope.$on("$routeChangeSuccess", function() {
            CacheService.put("loading", false);
            $timeout(snSkrollr.refresh, 200);
        });

    }
]);
<commit_msg>add skrollrInitialised check skrollr.refresh<commit_after>"use strict";
/**
 * @module thisissoon.core
 * @author SOON_
 * @requires ngRoute {@link https://docs.angularjs.org/api/ngRoute}
 * @requires ngAnimate: {@link https://docs.angularjs.org/api/ngAnimate}
 * @requires ui-bootstrap: {@link http://angular-ui.github.io/bootstrap}
 * @requires soon.ui
 * @requires soon.utils
 * @requires thisissoon.api
 * @requires sn.velocity
 * @requires duScroll
 */
angular.module("thisissoon.core", [
    "config",
    "ngRoute",
    "ngSanitize",
    "soon.ui",
    "thisissoon.api",
    "thisissoon.nav",
    "thisissoon.cache",
    "thisissoon.animation",
    "sn.velocity",
    "sn.skrollr",
    "sn.addthis",
    "duScroll"
])

.run([
    "$rootScope",
    "ResizeService",
    "$window",
    "$timeout",
    "CacheService",
    "snSkrollr",
    "ENV",
    /**
     * @constructor
     * @param {Service} $rootScope
     * @param {Service} CacheService
     */
    function ($rootScope, ResizeService, $window, $timeout, CacheService, snSkrollr, ENV) {

        ResizeService.add($rootScope.$id, function(event, size) {
            if (size.width >= 1024 && !$rootScope.skrollrInitialised) {
                snSkrollr.init();
                $rootScope.skrollrInitialised = true;
            } else if (size.width < 1024 && $rootScope.skrollrInitialised) {
                $rootScope.skrollrInitialised = false;
                snSkrollr.destroy();
            }
        });

        $rootScope.cache = CacheService;
        $rootScope.env = ENV;

        CacheService.put("navOpen", false);
        CacheService.put("loading", true);
        CacheService.put("projectList", false);

        // close nav menu when changing views
        $rootScope.$on("$routeChangeStart", function() {
            CacheService.put("navOpen", false);
            CacheService.put("loading", true);
        });

        // close nav menu when changing views
        $rootScope.$on("$routeChangeSuccess", function() {
            CacheService.put("loading", false);
            if ($rootScope.skrollrInitialised) {
                $timeout(snSkrollr.refresh, 200);
            }
        });

    }
]);
<|endoftext|>


<commit_before>const
  fs = require('fs'),
  fse = require('fs-extra'),
  appPaths = require('../app-paths'),
  logger = require('../helpers/logger'),
  log = logger('app:mode-electron'),
  warn = logger('app:mode-electron', 'red'),
  { spawnSync } = require('../helpers/spawn'),
  nodePackager = require('../helpers/node-packager')

const
  electronDeps = {
    'electron': '4.0.5',
    'electron-debug': '2.1.0',
    'electron-devtools-installer': '2.2.4',
    'devtron': '1.4.0'
  }

class Mode {
  get isInstalled () {
    return fs.existsSync(appPaths.electronDir)
  }

  add (params) {
    if (this.isInstalled) {
      warn(`Electron support detected already. Aborting.`)
      return
    }

    const cmdParam = nodePackager === 'npm'
      ? ['install', '--save-dev']
      : ['add', '--dev']

    log(`Installing Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(Object.keys(electronDeps).map(dep => {
        return `${dep}@${electronDeps[dep]}`
      })),
      appPaths.appDir,
      () => warn('Failed to install Electron dependencies')
    )

    log(`Creating Electron source folder...`)
    fse.copySync(appPaths.resolve.cli('templates/electron'), appPaths.electronDir)
    log(`Electron support was added`)
  }

  remove () {
    if (!this.isInstalled) {
      warn(`No Electron support detected. Aborting.`)
      return
    }

    log(`Removing Electron source folder`)
    fse.removeSync(appPaths.electronDir)

    const cmdParam = nodePackager === 'npm'
      ? ['uninstall', '--save-dev']
      : ['remove', '--dev']

    log(`Uninstalling Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(Object.keys(electronDeps)),
      appPaths.appDir,
      () => warn('Failed to uninstall Electron dependencies')
    )

    log(`Electron support was removed`)
  }
}

module.exports = Mode
<commit_msg>feat(quasar/app): Electron now uses semver notation, so install latest compatible version<commit_after>const
  fs = require('fs'),
  fse = require('fs-extra'),
  appPaths = require('../app-paths'),
  logger = require('../helpers/logger'),
  log = logger('app:mode-electron'),
  warn = logger('app:mode-electron', 'red'),
  { spawnSync } = require('../helpers/spawn'),
  nodePackager = require('../helpers/node-packager')

const
  electronDeps = {
    'electron': '^4.0.5',
    'electron-debug': '^2.1.0',
    'electron-devtools-installer': '^2.2.4',
    'devtron': '^1.4.0'
  }

class Mode {
  get isInstalled () {
    return fs.existsSync(appPaths.electronDir)
  }

  add (params) {
    if (this.isInstalled) {
      warn(`Electron support detected already. Aborting.`)
      return
    }

    const cmdParam = nodePackager === 'npm'
      ? ['install', '--save-dev']
      : ['add', '--dev']

    log(`Installing Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(Object.keys(electronDeps).map(dep => {
        return `${dep}@${electronDeps[dep]}`
      })),
      appPaths.appDir,
      () => warn('Failed to install Electron dependencies')
    )

    log(`Creating Electron source folder...`)
    fse.copySync(appPaths.resolve.cli('templates/electron'), appPaths.electronDir)
    log(`Electron support was added`)
  }

  remove () {
    if (!this.isInstalled) {
      warn(`No Electron support detected. Aborting.`)
      return
    }

    log(`Removing Electron source folder`)
    fse.removeSync(appPaths.electronDir)

    const cmdParam = nodePackager === 'npm'
      ? ['uninstall', '--save-dev']
      : ['remove', '--dev']

    log(`Uninstalling Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(Object.keys(electronDeps)),
      appPaths.appDir,
      () => warn('Failed to uninstall Electron dependencies')
    )

    log(`Electron support was removed`)
  }
}

module.exports = Mode
<|endoftext|>


<commit_before>'use strict';

var enc = new TextEncoder();

exports.stringToBuffer = function(str) {
  return enc.encode(str);
};

exports.stringToSocketData = function(str) {
  return enc.encode(str);
};

/* global runtime */
var TCPServerSocket = runtime.net.TCPServerSocket;

exports.createServerHandle = function(httpServer) {
  var socket = new TCPServerSocket();
  socket.onconnect = function(connSocket) {
    connSocket.ondata = function(u8) {
      httpServer._dataHandler(connSocket, u8);
    };

    connSocket.onend = function() {
      httpServer._endHandler(connSocket);
    };

    httpServer._connectionHandler(connSocket);
  };

  return socket;
};

exports.listen = function(handle, port) {
  handle.listen(port);
};

exports.unlisten = function(handle) {
  handle.close();
};

exports.sendAndClose = function(socket, u8) {
  socket.send(u8);
  socket.close();
};

exports.send = function(socket, u8) {
  socket.send(u8);
};
<commit_msg>Fix runtime backend<commit_after>'use strict';

var enc = new TextEncoder();

exports.stringToBuffer = function(str) {
  return enc.encode(str);
};

exports.stringToSocketData = function(str) {
  return enc.encode(str);
};

/* global runtime */
var TCPServerSocket = runtime.net.TCPServerSocket;

exports.createServerHandle = function(httpServer) {
  var socket = new TCPServerSocket();
  socket.onconnect = function(connSocket) {
    connSocket.ondata = function(u8) {
      httpServer._dataHandler(connSocket, u8);
    };

    connSocket.onend = function() {
      httpServer._endHandler(connSocket);
    };

    httpServer._connectionHandler(connSocket);
  };

  return socket;
};

exports.listen = function(handle, port) {
  handle.listen(port);
};

exports.unlisten = function(handle) {
  handle.close();
};

exports.sendAndClose = function(socket, u8) {
  socket.send(u8);
  socket.close();
};

exports.close = function(socket) {
  socket.close();
};

exports.send = function(socket, u8) {
  socket.send(u8);
};
<|endoftext|>


<commit_before>import React, { Component } from "react"
import PropTypes from "prop-types"
import { withStyles, createStyleSheet } from "material-ui/styles"
import Typography from "material-ui/Typography"
import Collapse from "material-ui/transitions/Collapse"
import IconButton from "material-ui/IconButton"
import ExpandMoreIcon from "material-ui-icons/ExpandMore"
import { CardContent } from "material-ui/Card"
import classnames from "classnames"

const styleSheet = createStyleSheet("ExpandableInstructors", theme => ({
  button: {
    paddingLeft: 0
  },
  links: {
    color: "#3344dd",
    display: "flex",
    flexDirection: "column",
    borderLeftStyle: "solid",
    borderLeftColor: theme.palette.accent[400],
    borderLeftWidth: "0.3em",
    paddingLeft: "1em"
  },
  link: {
    marginBottom: 10
  },
  teacher: {
    fontSize: 16,
    color: theme.palette.text.secondary,
    marginBottom: "0.5em"
  },
  expand: {
    transform: "rotate(0deg)",
    transition: theme.transitions.create("transform", {
      duration: theme.transitions.duration.shortest
    })
  },
  expandOpen: {
    transform: "rotate(180deg)"
  },
  flexGrow: { flex: "1 1 auto" },
  meet: {
    color: "rgba(0, 0, 0, 0.54)"
  }
}))

class ExpandableInstructors extends Component {
  state = { expanded: false }
  handleExpandClick = () => {
    this.setState({ expanded: !this.state.expanded })
  }
  getInstructor = () => {
    const classes = this.props.classes
    return (

        <Typography
          type="headline"
          component="h3"
          className={classes.teacher}
          tabIndex="0"
        >
          {this.props.teachers[0].firstName +
            " " +
            this.props.teachers[0].lastName}
        </Typography>

            {this.props.teachers[0].office}

            {this.props.teachers[0].email}

    )
  }

  getExpandedInstructors = () => {
    const classes = this.props.classes
    let elements = []
    for (let i = 0, total = this.props.teachers.length; i < total; i++) {
      elements.push(

          <Typography
            type="headline"
            component="h3"
            className={classes.teacher}
            tabIndex="0"
            key={this.props.teachers[0].lastName + Math.random() + 2}
          >
            {this.props.teachers[i].firstName +
              " " +
              this.props.teachers[i].lastName}
          </Typography>

              {this.props.teachers[i].office}

              {this.props.teachers[i].email}

      )
    }
    return elements
  }
  render() {
    const classes = this.props.classes
    return (

          {this.getInstructor()}
          <IconButton
            aria-label={
              this.state.expanded
                ? "Close more instructors"
                : "Open more instructors"
            }
            className={classnames(classes.expand, {
              [classes.expandOpen]: this.state.expanded
            })}
            onClick={this.handleExpandClick}
          >
            <ExpandMoreIcon />
          </IconButton>

        <Collapse
          in={this.state.expanded}
          transitionDuration="auto"
          unmountOnExit
        >
          <CardContent>
            {this.getExpandedInstructors()}
          </CardContent>
        </Collapse>

    )
  }
}

ExpandableInstructors.propTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(styleSheet)(ExpandableInstructors)
<commit_msg>Begin index from correct position #6<commit_after>import React, { Component } from "react"
import PropTypes from "prop-types"
import { withStyles, createStyleSheet } from "material-ui/styles"
import Typography from "material-ui/Typography"
import Collapse from "material-ui/transitions/Collapse"
import IconButton from "material-ui/IconButton"
import ExpandMoreIcon from "material-ui-icons/ExpandMore"
import { CardContent } from "material-ui/Card"
import classnames from "classnames"

const styleSheet = createStyleSheet("ExpandableInstructors", theme => ({
  button: {
    paddingLeft: 0
  },
  links: {
    color: "#3344dd",
    display: "flex",
    flexDirection: "column",
    borderLeftStyle: "solid",
    borderLeftColor: theme.palette.accent[400],
    borderLeftWidth: "0.3em",
    paddingLeft: "1em"
  },
  link: {
    marginBottom: 10
  },
  teacher: {
    fontSize: 16,
    color: theme.palette.text.secondary,
    marginBottom: "0.5em"
  },
  expand: {
    transform: "rotate(0deg)",
    transition: theme.transitions.create("transform", {
      duration: theme.transitions.duration.shortest
    })
  },
  expandOpen: {
    transform: "rotate(180deg)"
  },
  flexGrow: { flex: "1 1 auto" },
  meet: {
    color: "rgba(0, 0, 0, 0.54)"
  }
}))

class ExpandableInstructors extends Component {
  state = { expanded: false }
  handleExpandClick = () => {
    this.setState({ expanded: !this.state.expanded })
  }
  getInstructor = () => {
    const classes = this.props.classes
    return (

        <Typography
          type="headline"
          component="h3"
          className={classes.teacher}
          tabIndex="0"
        >
          {this.props.teachers[0].firstName +
            " " +
            this.props.teachers[0].lastName}
        </Typography>

            {this.props.teachers[0].office}

            {this.props.teachers[0].email}

    )
  }

  getExpandedInstructors = () => {
    const classes = this.props.classes
    let elements = []
    for (let i = 1, total = this.props.teachers.length; i < total; i++) {
      elements.push(

          <Typography
            type="headline"
            component="h3"
            className={classes.teacher}
            tabIndex="0"
            key={this.props.teachers[0].lastName + Math.random() + 2}
          >
            {this.props.teachers[i].firstName +
              " " +
              this.props.teachers[i].lastName}
          </Typography>

              {this.props.teachers[i].office}

              {this.props.teachers[i].email}

      )
    }
    return elements
  }
  render() {
    const classes = this.props.classes
    return (

          {this.getInstructor()}
          <IconButton
            aria-label={
              this.state.expanded
                ? "Close more instructors"
                : "Open more instructors"
            }
            className={classnames(classes.expand, {
              [classes.expandOpen]: this.state.expanded
            })}
            onClick={this.handleExpandClick}
          >
            <ExpandMoreIcon />
          </IconButton>

        <Collapse
          in={this.state.expanded}
          transitionDuration="auto"
          unmountOnExit
        >
          <CardContent>
            {this.getExpandedInstructors()}
          </CardContent>
        </Collapse>

    )
  }
}

ExpandableInstructors.propTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(styleSheet)(ExpandableInstructors)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text, View, Image} from 'react-native';
import { StackNavigator } from 'react-navigation';
import styles from './styles/LaunchScreenStyle';
import StartButton from '../components/StartButton';
import GameStart from './GameStart';

export default class LaunchScreen extends Component {
  render() {
    const { navigate } = this.props.navigation;
		return (
		<View style={styles.container} >
      <Image source={require('../assets/images/cold-kevin.jpg')} style={styles.kevin} >
        <View>
          <Text style={styles.header}>Cold Bacon</Text>
        </View>
        <View>
          <StartButton text='Start' onPress={() => navigate('GameStart')} />
        </View>
      </Image>
    </View>
		);
	}
}

//  <View>
//   <Image source={require('../assets/cold-kevin.jpg')} style={styles.kevin} >
//     <View>
//       <Text style={styles.header}>Cold Bacon</Text>
//     </View>
//     <View>
//       <StartButton text='Start' onPress={() => navigate('GameStart')} />
//     </View>
//   </Image>
// </View>
<commit_msg>Add animation to cold bacon text<commit_after>import React, { Component } from 'react';
import { Text, View, Image} from 'react-native';
import { StackNavigator } from 'react-navigation';
import styles from './styles/LaunchScreenStyle';
import StartButton from '../components/StartButton';
import GameStart from './GameStart';
import * as Animatable from 'react-native-animatable';

export default class LaunchScreen extends Component {
  render() {
    const { navigate } = this.props.navigation;
		return (
		<View style={styles.container} >
      <Image source={require('../assets/images/cold-kevin.jpg')} style={styles.kevin} >
        <View>
          <Animatable.Text animation="bounceInLeft" style={styles.header}>Cold Bacon</Animatable.Text>
        </View>
        <View>
          <StartButton text='Start' onPress={() => navigate('GameStart')} />
        </View>
      </Image>
    </View>
		);
	}
}

//  <View>
//   <Image source={require('../assets/cold-kevin.jpg')} style={styles.kevin} >
//     <View>
//       <Text style={styles.header}>Cold Bacon</Text>
//     </View>
//     <View>
//       <StartButton text='Start' onPress={() => navigate('GameStart')} />
//     </View>
//   </Image>
// </View>
// lightSpeedIn
<|endoftext|>


<commit_before>var PagerBehavior;
(function ($, _, Backbone, Marionette, App, PagerListView) {
    PagerBehavior = Marionette.Behavior.extend({
        onShowPager: function (entityCollection) {
            var pagerRegion = this.view.getRegion('pagerRegion');
            if (pagerRegion.currentView !== null) {
                pagerRegion.reset();
            }

            var count = window.indexes[this.view.key],
                currentPage = this.view.listView.currentPage,
                collection = new Backbone.Collection(),
                noOfPages = Math.ceil(count / window.pageSize);

            if (noOfPages === 1) {
                pagerRegion.empty();
                if (this.view.routing) {
                    location.hash = '/' + this.view.route + '/' + 1 + '/' + this.view.additionalParams;
                }

                return;
            }

            for (var i = 1; i <= noOfPages; i++) {
                var pagerItem = new Backbone.Model(),
                    route = '/' + this.view.route + '/' + i + '/' + this.view.additionalParams;

                pagerItem.set({route: route, currentPage: i == currentPage, number: i});
                collection.add(pagerItem);
            }

            this.view.showChildView('pagerRegion', new PagerListView({
                collection: collection,
                parentViewCid: this.view.cid,
                routing: this.view.routing,
                route: this.view.route
            }));
        }
    });
})(jQuery, _, Backbone, Marionette, App, PagerListView);<commit_msg>adding check to see if indexes have been defined on the window<commit_after>var PagerBehavior;
(function ($, _, Backbone, Marionette, App, PagerListView) {
    PagerBehavior = Marionette.Behavior.extend({
        onShowPager: function (entityCollection) {
            var pagerRegion = this.view.getRegion('pagerRegion');
            if (pagerRegion.currentView !== null) {
                pagerRegion.reset();
            }

            if (_.isUndefined(window.indexes)) {
                return;
            }

            var count = window.indexes[this.view.key],
                currentPage = this.view.listView.currentPage,
                collection = new Backbone.Collection(),
                noOfPages = Math.ceil(count / window.pageSize);

            if (noOfPages === 1) {
                pagerRegion.empty();
                if (this.view.routing) {
                    location.hash = '/' + this.view.route + '/' + 1 + '/' + this.view.additionalParams;
                }

                return;
            }

            for (var i = 1; i <= noOfPages; i++) {
                var pagerItem = new Backbone.Model(),
                    route = '/' + this.view.route + '/' + i + '/' + this.view.additionalParams;

                pagerItem.set({route: route, currentPage: i == currentPage, number: i});
                collection.add(pagerItem);
            }

            this.view.showChildView('pagerRegion', new PagerListView({
                collection: collection,
                parentViewCid: this.view.cid,
                routing: this.view.routing,
                route: this.view.route
            }));
        }
    });
})(jQuery, _, Backbone, Marionette, App, PagerListView);<|endoftext|>


<commit_before>/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 "use strict";

var manager = {

  prefWindowObj: null,

  load: async function () {
  },

  unload: async function () {
    //close window (if open)
    if (this.prefWindowObj !== null) this.prefWindowObj.close();
  },

  openManagerWindow: function(event) {
    if (!event.button) { //catches zero or undefined
      if (tbSync.enabled) {
        // check, if a window is already open and just put it in focus
        if (this.prefWindowObj === null) {
          this.prefWindowObj = tbSync.window.open("chrome://tbsync/content/manager/accountManager.xul", "TbSyncAccountManagerWindow", "chrome,centerscreen");
        }
        this.prefWindowObj.focus();
      } else {
        //this.popupNotEnabled();
      }
    }
  },

  popupNotEnabled: function () {
    tbSync.dump("Oops", "Trying to open account manager, but init sequence not yet finished");
    let msg = tbSync.getString("OopsMessage") + "\n\n";
    let v = Services.appinfo.platformVersion;
    if (!tbSync.prefs.getBoolPref("log.tofile")) {
      if (tbSync.window.confirm(msg + tbSync.getString("UnableToTraceError"))) {
        tbSync.prefs.setBoolPref("log.tofile", true);
        tbSync.window.alert(tbSync.getString("RestartThunderbirdAndTryAgain"));
      }
    } else {
      if (tbSync.window.confirm(msg + tbSync.getString("HelpFixStartupError"))) {
        this.createBugReport("john.bieling@gmx.de", msg, "");
      }
    }
  },

  openTBtab: function (url) {
    let tabmail = null;
    if (tbSync.window) {
      tabmail = tbSync.window.document.getElementById("tabmail");
      tbSync.window.focus();
      tabmail.openTab("contentTab", {
        contentPage: url
      });
    }
    return (tabmail !== null);
  },

  openTranslatedLink: function (url) {
    let googleCode = tbSync.getString("google.translate.code");
    if (googleCode != "en" && googleCode != "google.translate.code") {
      this.openLink("https://translate.google.com/translate?hl=en&sl=en&tl="+tbSync.getString("google.translate.code")+"&u="+url);
    } else {
      this.openLink(url);
    }
  },

  openLink: function (url) {
    let ioservice = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    let uriToOpen = ioservice.newURI(url, null, null);
    let extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"].getService(Components.interfaces.nsIExternalProtocolService);
    extps.loadURI(uriToOpen, null);
  },

  openBugReportWizard: function () {
    if (!tbSync.debugMode) {
      this.prefWindowObj.alert(tbSync.getString("NoDebugLog"));
    } else {
      this.prefWindowObj.openDialog("chrome://tbsync/content/manager/support-wizard/support-wizard.xul", "support-wizard", "dialog,centerscreen,chrome,resizable=no");
    }
  },

  createBugReport: function (email, subject, description) {
    let fields = Components.classes["@mozilla.org/messengercompose/composefields;1"].createInstance(Components.interfaces.nsIMsgCompFields);
    let params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);

    fields.to = email;
    fields.subject = "TbSync " + tbSync.addon.version.toString() + " bug report: " + subject;
    fields.body = "Hi,\n\n" +
      "attached you find my debug.log for the following error:\n\n" +
      description;

    params.composeFields = fields;
    params.format = Components.interfaces.nsIMsgCompFormat.PlainText;

    let attachment = Components.classes["@mozilla.org/messengercompose/attachment;1"].createInstance(Components.interfaces.nsIMsgAttachment);
    attachment.contentType = "text/plain";
    attachment.url =  'file://' + tbSync.io.getAbsolutePath("debug.log");
    attachment.name = "debug.log";
    attachment.temporary = false;

    params.composeFields.addAttachment(attachment);
    MailServices.compose.OpenComposeWindowWithParams (null, params);
  },

  /**
   * Functions used by the folderlist in the main account settings tab
   */
  DefaultFolderList : class {
    constructor(provider) {
      this.provider = provider
    }

    /**
     * Is called before the context menu of the folderlist is shown, allows to
     * show/hide custom menu options based on selected folder
     *
     * @param document       [in] document object of the account settings window - element.ownerDocument - menuentry?
     * @param folderData         [in] FolderData of the selected folder
     */
    onContextMenuShowing(document, folderData) {
      return tbSync.providers[this.provider].standardFolderList.onContextMenuShowing(document, folderData);
    }

    /**
     * Returns an array of attribute objects, which define the number of columns
     * and the look of the header
     */
    getHeader() {
      return [
        {style: "font-weight:bold;", label: "", width: "93"},
        {style: "font-weight:bold;", label: tbSync.getString("manager.resource"), width:"150"},
        {style: "font-weight:bold;", label: tbSync.getString("manager.status"), flex :"1"},
      ]
    }

    /**
     * Is called to add a row to the folderlist. After this call, updateRow is called as well.
     *
     * @param document        [in] document object of the account settings window
     * @param folderData         [in] FolderData of the folder in the row
     */
    getRow(document, folderData) {
      //create checkBox for select state
      let itemSelCheckbox = document.createElement("checkbox");
      itemSelCheckbox.setAttribute("updatefield", "selectbox");
      itemSelCheckbox.setAttribute("style", "margin: 0px 0px 0px 3px;");
      itemSelCheckbox.addEventListener("command", this.toggleFolder);

      //icon
      let itemType = document.createElement("image");
      itemType.setAttribute("src", tbSync.providers[this.provider].standardFolderList.getTypeImage(folderData));
      itemType.setAttribute("style", "margin: 0px 9px 0px 3px;");

      //ACL
      let roAttributes = tbSync.providers[this.provider].standardFolderList.getAttributesRoAcl(folderData);
      let rwAttributes = tbSync.providers[this.provider].standardFolderList.getAttributesRwAcl(folderData);
      let itemACL = document.createElement("button");
      itemACL.setAttribute("image", "chrome://tbsync/skin/acl_" + (folderData.getFolderProperty("downloadonly") ? "ro" : "rw") + ".png");
      itemACL.setAttribute("class", "plain");
      itemACL.setAttribute("style", "width: 35px; min-width: 35px; margin: 0; height:26px");
      itemACL.setAttribute("updatefield", "acl");
      if (roAttributes && rwAttributes) {
        itemACL.setAttribute("type", "menu");
        let menupopup = document.createElement("menupopup");
        {
          let menuitem = document.createElement("menuitem");
          menuitem.downloadonly = false;
          menuitem.setAttribute("class", "menuitem-iconic");
          menuitem.setAttribute("image", "chrome://tbsync/skin/acl_rw2.png");
          menuitem.addEventListener("command", this.updateReadOnly);
          for (const [attr, value] of Object.entries(rwAttributes)) {
            menuitem.setAttribute(attr, value);
          }
          menupopup.appendChild(menuitem);
        }

        {
          let menuitem = document.createElement("menuitem");
          menuitem.downloadonly = true;
          menuitem.setAttribute("class", "menuitem-iconic");
          menuitem.setAttribute("image", "chrome://tbsync/skin/acl_ro2.png");
          menuitem.addEventListener("command", this.updateReadOnly);
          for (const [attr, value] of Object.entries(roAttributes)) {
            menuitem.setAttribute(attr, value);
          }
          menupopup.appendChild(menuitem);
        }
        itemACL.appendChild(menupopup);
      }

      //folder name
      let itemLabel = document.createElement("description");
      itemLabel.setAttribute("updatefield", "name");

      //status
      let itemStatus = document.createElement("description");
      itemStatus.setAttribute("updatefield", "status");

      //group1
      let itemHGroup1 = document.createElement("hbox");
      itemHGroup1.setAttribute("align", "center");
      itemHGroup1.appendChild(itemSelCheckbox);
      itemHGroup1.appendChild(itemType);
      if (itemACL) itemHGroup1.appendChild(itemACL);

      let itemVGroup1 = document.createElement("vbox");
      itemVGroup1.setAttribute("width", "93");
      itemVGroup1.appendChild(itemHGroup1);

      //group2
      let itemHGroup2 = document.createElement("hbox");
      itemHGroup2.setAttribute("align", "center");
      itemHGroup2.setAttribute("width", "146");
      itemHGroup2.appendChild(itemLabel);

      let itemVGroup2 = document.createElement("vbox");
      itemVGroup2.setAttribute("style", "padding: 3px");
      itemVGroup2.appendChild(itemHGroup2);

      //group3
      let itemHGroup3 = document.createElement("hbox");
      itemHGroup3.setAttribute("align", "center");
      itemHGroup3.setAttribute("width", "227");
      itemHGroup3.appendChild(itemStatus);

      let itemVGroup3 = document.createElement("vbox");
      itemVGroup3.setAttribute("style", "padding: 3px");
      itemVGroup3.appendChild(itemHGroup3);

      //final row
      let row = document.createElement("hbox");
      row.setAttribute("style", "min-height: 24px;");
      row.appendChild(itemVGroup1);
      row.appendChild(itemVGroup2);
      row.appendChild(itemVGroup3);
      return row;
    }

    toggleFolder(event) {
      let element = event.target;
      let folderList = element.ownerDocument.getElementById("tbsync.accountsettings.folderlist");
      if (folderList.selectedItem !== null && !folderList.disabled) {
        // the folderData obj of the selected folder is attached to its row entry
        let folder = folderList.selectedItem.folderData;

        if (!folder.accountData.isEnabled())
          return;

        if (folder.getFolderProperty("selected")) {
          let target = folder.getFolderProperty("target");
          if (!target || element.ownerDocument.defaultView.confirm(tbSync.getString("prompt.Unsubscribe"))) {
            if (target) {
              folder.targetData.removeTarget();
              tbSync.db.clearChangeLog(target);
            }
            folder.setFolderProperty("selected", false);

          } else {
            if (element) {
              //undo users action
              element.setAttribute("checked", true);
            }
          }
        } else {
          //select and update status
          folder.setFolderProperty("selected", true);
          folder.setFolderProperty("status", "aborted");
          folder.accountData.setAccountProperty("status", "notsyncronized");
        }
        Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", folder.accountID);
      }
    }

    updateReadOnly(event) {
      let element = event.target;
      let folderList = element.ownerDocument.getElementById("tbsync.accountsettings.folderlist");
      if (folderList.selectedItem !== null && !folderList.disabled) {
        //the folderData obj of the selected folder is attached to its row entry
        let  folder = folderList.selectedItem.folderData;

        //update value
        let value = element.downloadonly;
        folder.setFolderProperty("downloadonly", value);

        //update icon
        let button = element.parentNode.parentNode;
        if (value == "0") {
          button.setAttribute('image','chrome://tbsync/skin/acl_rw.png');
        } else {
          button.setAttribute('image','chrome://tbsync/skin/acl_ro.png');
        }

        //update ro flag if calendar (the default folderlist only support addressbook and calendar target)
        let type = folder.getFolderProperty("targetType");
        switch (type) {
          case "addressbook":
            break;
          case "calendar":
            {
              // get it, if it exists, does not create it
              let target = folder.targetData.checkTarget();
              if (target) {
                target.setProperty("readOnly", value == '1');
              }
            }
            break;
        }
      }
    }

    /**
     * Is called to update a row of the folderlist (the first cell is a select checkbox inserted by TbSync)
     *
     * @param document       [in] document object of the account settings window
     * @param listItem       [in] the listitem of the row, which needs to be updated
     * @param folderData        [in] FolderData for that row
     */
    updateRow(document, listItem, folderData) {
      let name = folderData.getFolderProperty("name");
      let status = folderData.getFolderStatus();
      let selected = folderData.getFolderProperty("selected");

      // get updatefields
      let fields = {}
      for (let f of listItem.querySelectorAll("[updatefield]")) {
        fields[f.getAttribute("updatefield")] = f;
      }

      // update fields
      fields.name.setAttribute("disabled", !selected);
      fields.name.setAttribute("style", selected ? "" : "font-style:italic");
      if (fields.name.textContent != name) fields.name.textContent = name;

      fields.status.setAttribute("style", selected ? "" : "font-style:italic");
      if (fields.status.textContent != status) {
        fields.status.textContent = status;
        fields.status.flex = "1";
      }

      if (fields.hasOwnProperty("acl")) {
        fields.acl.setAttribute("image", "chrome://tbsync/skin/acl_" + (folderData.getFolderProperty("downloadonly") ? "ro" : "rw") + ".png");
        fields.acl.setAttribute("disabled", folderData.accountData.isSyncing());
      }

      // update selectbox
      let selbox = fields.selectbox;
      if (selbox) {
        if (folderData.getFolderProperty("selected")) {
          selbox.setAttribute("checked", true);
        } else {
          selbox.removeAttribute("checked");
        }

        if (folderData.accountData.isSyncing()) {
          selbox.setAttribute("disabled", true);
        } else {
          selbox.removeAttribute("disabled");
        }
      }
    }
  }
}
<commit_msg>API update<commit_after>/*
 * This file is part of TbSync.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

 "use strict";

var manager = {

  prefWindowObj: null,

  load: async function () {
  },

  unload: async function () {
    //close window (if open)
    if (this.prefWindowObj !== null) this.prefWindowObj.close();
  },

  openManagerWindow: function(event) {
    if (!event.button) { //catches zero or undefined
      if (tbSync.enabled) {
        // check, if a window is already open and just put it in focus
        if (this.prefWindowObj === null) {
          this.prefWindowObj = tbSync.window.open("chrome://tbsync/content/manager/accountManager.xul", "TbSyncAccountManagerWindow", "chrome,centerscreen");
        }
        this.prefWindowObj.focus();
      } else {
        //this.popupNotEnabled();
      }
    }
  },

  popupNotEnabled: function () {
    tbSync.dump("Oops", "Trying to open account manager, but init sequence not yet finished");
    let msg = tbSync.getString("OopsMessage") + "\n\n";
    let v = Services.appinfo.platformVersion;
    if (!tbSync.prefs.getBoolPref("log.tofile")) {
      if (tbSync.window.confirm(msg + tbSync.getString("UnableToTraceError"))) {
        tbSync.prefs.setBoolPref("log.tofile", true);
        tbSync.window.alert(tbSync.getString("RestartThunderbirdAndTryAgain"));
      }
    } else {
      if (tbSync.window.confirm(msg + tbSync.getString("HelpFixStartupError"))) {
        this.createBugReport("john.bieling@gmx.de", msg, "");
      }
    }
  },

  openTBtab: function (url) {
    let tabmail = null;
    if (tbSync.window) {
      tabmail = tbSync.window.document.getElementById("tabmail");
      tbSync.window.focus();
      tabmail.openTab("contentTab", {
        contentPage: url
      });
    }
    return (tabmail !== null);
  },

  openTranslatedLink: function (url) {
    let googleCode = tbSync.getString("google.translate.code");
    if (googleCode != "en" && googleCode != "google.translate.code") {
      this.openLink("https://translate.google.com/translate?hl=en&sl=en&tl="+tbSync.getString("google.translate.code")+"&u="+url);
    } else {
      this.openLink(url);
    }
  },

  openLink: function (url) {
    let ioservice = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    let uriToOpen = ioservice.newURI(url, null, null);
    let extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"].getService(Components.interfaces.nsIExternalProtocolService);
    extps.loadURI(uriToOpen, null);
  },

  openBugReportWizard: function () {
    if (!tbSync.debugMode) {
      this.prefWindowObj.alert(tbSync.getString("NoDebugLog"));
    } else {
      this.prefWindowObj.openDialog("chrome://tbsync/content/manager/support-wizard/support-wizard.xul", "support-wizard", "dialog,centerscreen,chrome,resizable=no");
    }
  },

  createBugReport: function (email, subject, description) {
    let fields = Components.classes["@mozilla.org/messengercompose/composefields;1"].createInstance(Components.interfaces.nsIMsgCompFields);
    let params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);

    fields.to = email;
    fields.subject = "TbSync " + tbSync.addon.version.toString() + " bug report: " + subject;
    fields.body = "Hi,\n\n" +
      "attached you find my debug.log for the following error:\n\n" +
      description;

    params.composeFields = fields;
    params.format = Components.interfaces.nsIMsgCompFormat.PlainText;

    let attachment = Components.classes["@mozilla.org/messengercompose/attachment;1"].createInstance(Components.interfaces.nsIMsgAttachment);
    attachment.contentType = "text/plain";
    attachment.url =  'file://' + tbSync.io.getAbsolutePath("debug.log");
    attachment.name = "debug.log";
    attachment.temporary = false;

    params.composeFields.addAttachment(attachment);
    MailServices.compose.OpenComposeWindowWithParams (null, params);
  },

  /**
   * Functions used by the folderlist in the main account settings tab
   */
  DefaultFolderList : class {
    constructor(provider) {
      this.provider = provider
    }

    /**
     * Is called before the context menu of the folderlist is shown, allows to
     * show/hide custom menu options based on selected folder
     *
     * @param document       [in] document object of the account settings window - element.ownerDocument - menuentry?
     * @param folderData         [in] FolderData of the selected folder
     */
    onContextMenuShowing(document, folderData) {
      return tbSync.providers[this.provider].standardFolderList.onContextMenuShowing(document, folderData);
    }

    /**
     * Returns an array of attribute objects, which define the number of columns
     * and the look of the header
     */
    getHeader() {
      return [
        {style: "font-weight:bold;", label: "", width: "93"},
        {style: "font-weight:bold;", label: tbSync.getString("manager.resource"), width:"150"},
        {style: "font-weight:bold;", label: tbSync.getString("manager.status"), flex :"1"},
      ]
    }

    /**
     * Is called to add a row to the folderlist. After this call, updateRow is called as well.
     *
     * @param document        [in] document object of the account settings window
     * @param folderData         [in] FolderData of the folder in the row
     */
    getRow(document, folderData) {
      //create checkBox for select state
      let itemSelCheckbox = document.createElement("checkbox");
      itemSelCheckbox.setAttribute("updatefield", "selectbox");
      itemSelCheckbox.setAttribute("style", "margin: 0px 0px 0px 3px;");
      itemSelCheckbox.addEventListener("command", this.toggleFolder);

      //icon
      let itemType = document.createElement("image");
      itemType.setAttribute("src", tbSync.providers[this.provider].standardFolderList.getTypeImage(folderData));
      itemType.setAttribute("style", "margin: 0px 9px 0px 3px;");

      //ACL
      let roAttributes = tbSync.providers[this.provider].standardFolderList.getAttributesRoAcl(folderData);
      let rwAttributes = tbSync.providers[this.provider].standardFolderList.getAttributesRwAcl(folderData);
      let itemACL = document.createElement("button");
      itemACL.setAttribute("image", "chrome://tbsync/skin/acl_" + (folderData.getFolderProperty("downloadonly") ? "ro" : "rw") + ".png");
      itemACL.setAttribute("class", "plain");
      itemACL.setAttribute("style", "width: 35px; min-width: 35px; margin: 0; height:26px");
      itemACL.setAttribute("updatefield", "acl");
      if (roAttributes && rwAttributes) {
        itemACL.setAttribute("type", "menu");
        let menupopup = document.createElement("menupopup");
        {
          let menuitem = document.createElement("menuitem");
          menuitem.downloadonly = false;
          menuitem.setAttribute("class", "menuitem-iconic");
          menuitem.setAttribute("image", "chrome://tbsync/skin/acl_rw2.png");
          menuitem.addEventListener("command", this.updateReadOnly);
          for (const [attr, value] of Object.entries(rwAttributes)) {
            menuitem.setAttribute(attr, value);
          }
          menupopup.appendChild(menuitem);
        }

        {
          let menuitem = document.createElement("menuitem");
          menuitem.downloadonly = true;
          menuitem.setAttribute("class", "menuitem-iconic");
          menuitem.setAttribute("image", "chrome://tbsync/skin/acl_ro2.png");
          menuitem.addEventListener("command", this.updateReadOnly);
          for (const [attr, value] of Object.entries(roAttributes)) {
            menuitem.setAttribute(attr, value);
          }
          menupopup.appendChild(menuitem);
        }
        itemACL.appendChild(menupopup);
      }

      //folder name
      let itemLabel = document.createElement("description");
      itemLabel.setAttribute("updatefield", "name");

      //status
      let itemStatus = document.createElement("description");
      itemStatus.setAttribute("updatefield", "status");

      //group1
      let itemHGroup1 = document.createElement("hbox");
      itemHGroup1.setAttribute("align", "center");
      itemHGroup1.appendChild(itemSelCheckbox);
      itemHGroup1.appendChild(itemType);
      if (itemACL) itemHGroup1.appendChild(itemACL);

      let itemVGroup1 = document.createElement("vbox");
      itemVGroup1.setAttribute("width", "93");
      itemVGroup1.appendChild(itemHGroup1);

      //group2
      let itemHGroup2 = document.createElement("hbox");
      itemHGroup2.setAttribute("align", "center");
      itemHGroup2.setAttribute("width", "146");
      itemHGroup2.appendChild(itemLabel);

      let itemVGroup2 = document.createElement("vbox");
      itemVGroup2.setAttribute("style", "padding: 3px");
      itemVGroup2.appendChild(itemHGroup2);

      //group3
      let itemHGroup3 = document.createElement("hbox");
      itemHGroup3.setAttribute("align", "center");
      itemHGroup3.setAttribute("width", "227");
      itemHGroup3.appendChild(itemStatus);

      let itemVGroup3 = document.createElement("vbox");
      itemVGroup3.setAttribute("style", "padding: 3px");
      itemVGroup3.appendChild(itemHGroup3);

      //final row
      let row = document.createElement("hbox");
      row.setAttribute("style", "min-height: 24px;");
      row.appendChild(itemVGroup1);
      row.appendChild(itemVGroup2);
      row.appendChild(itemVGroup3);
      return row;
    }

    toggleFolder(event) {
      let element = event.target;
      let folderList = element.ownerDocument.getElementById("tbsync.accountsettings.folderlist");
      if (folderList.selectedItem !== null && !folderList.disabled) {
        // the folderData obj of the selected folder is attached to its row entry
        let folder = folderList.selectedItem.folderData;

        if (!folder.accountData.isEnabled())
          return;

        if (folder.getFolderProperty("selected")) {
          let target = folder.getFolderProperty("target");
          if (!target || element.ownerDocument.defaultView.confirm(tbSync.getString("prompt.Unsubscribe"))) {
            if (target) {
              folder.targetData.removeTarget();
              tbSync.db.clearChangeLog(target);
            }
            folder.setFolderProperty("selected", false);

          } else {
            if (element) {
              //undo users action
              element.setAttribute("checked", true);
            }
          }
        } else {
          //select and update status
          folder.setFolderProperty("selected", true);
          folder.setFolderProperty("status", "aborted");
          folder.accountData.setAccountProperty("status", "notsyncronized");
        }
        Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", folder.accountID);
      }
    }

    updateReadOnly(event) {
      let element = event.target;
      let folderList = element.ownerDocument.getElementById("tbsync.accountsettings.folderlist");
      if (folderList.selectedItem !== null && !folderList.disabled) {
        //the folderData obj of the selected folder is attached to its row entry
        let  folder = folderList.selectedItem.folderData;

        //update value
        let value = element.downloadonly;
        folder.setFolderProperty("downloadonly", value);

        //update icon
        let button = element.parentNode.parentNode;
        if (value == "0") {
          button.setAttribute('image','chrome://tbsync/skin/acl_rw.png');
        } else {
          button.setAttribute('image','chrome://tbsync/skin/acl_ro.png');
        }

        //update ro flag if calendar (the default folderlist only support addressbook and calendar target)
        let type = folder.getFolderProperty("targetType");
        switch (type) {
          case "addressbook":
            break;
          case "calendar":
            {
              // get it, if it exists, does not create it
              let target = folder.targetData.checkTarget();
              if (target) {
                target.setProperty("readOnly", value == '1');
              }
            }
            break;
        }
      }
    }

    /**
     * Is called to update a row of the folderlist (the first cell is a select checkbox inserted by TbSync)
     *
     * @param document       [in] document object of the account settings window
     * @param listItem       [in] the listitem of the row, which needs to be updated
     * @param folderData        [in] FolderData for that row
     */
    updateRow(document, listItem, folderData) {
      let name = tbSync.providers[this.provider].standardFolderList.getFolderDisplayName(folderData);
      let status = folderData.getFolderStatus();
      let selected = folderData.getFolderProperty("selected");

      // get updatefields
      let fields = {}
      for (let f of listItem.querySelectorAll("[updatefield]")) {
        fields[f.getAttribute("updatefield")] = f;
      }

      // update fields
      fields.name.setAttribute("disabled", !selected);
      fields.name.setAttribute("style", selected ? "" : "font-style:italic");
      if (fields.name.textContent != name) fields.name.textContent = name;

      fields.status.setAttribute("style", selected ? "" : "font-style:italic");
      if (fields.status.textContent != status) {
        fields.status.textContent = status;
        fields.status.flex = "1";
      }

      if (fields.hasOwnProperty("acl")) {
        fields.acl.setAttribute("image", "chrome://tbsync/skin/acl_" + (folderData.getFolderProperty("downloadonly") ? "ro" : "rw") + ".png");
        fields.acl.setAttribute("disabled", folderData.accountData.isSyncing());
      }

      // update selectbox
      let selbox = fields.selectbox;
      if (selbox) {
        if (folderData.getFolderProperty("selected")) {
          selbox.setAttribute("checked", true);
        } else {
          selbox.removeAttribute("checked");
        }

        if (folderData.accountData.isSyncing()) {
          selbox.setAttribute("disabled", true);
        } else {
          selbox.removeAttribute("disabled");
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>(function(w){
  /* We can request an image at every possible width, but let's limit it to a reasonable number
   We can set these so they correspond to our more common sizes.
   */
  var IMAGE_URL = w.BETTY_IMAGE_URL || "{{ BETTY_IMAGE_URL }}",
      RATIOS = {{ BETTY_RATIOS|safe }},
      ASPECT_RATIO_TOLERANCE = .1, // 10% tolerance.
      MAX_WIDTH = {{ BETTY_MAX_WIDTH }},
      PICTUREFILL_SELECTOR = w.PICTUREFILL_SELECTOR || "div",
      breakpoints = [{{ BETTY_WIDTHS|join:","}}];

  // Credit to https://remysharp.com/2010/07/21/throttling-function-calls
  function throttle(fn, threshhold, scope) {
    threshhold || (threshhold = 250);
    var last,
        deferTimer;
    return function () {
      var context = scope || this;

      var now = +new Date,
          args = arguments;
      if (last && now < last + threshhold) {
        // hold on to it
        clearTimeout(deferTimer);
        deferTimer = setTimeout(function () {
          last = now;
          fn.apply(context, args);
        }, threshhold);
      } else {
        last = now;
        fn.apply(context, args);
      }
    };
  }

  w.picturefill = function(elements, forceRerender) {

    // get elements to picturefill
    var ps;
    if (elements instanceof Array) {
      ps = elements;
    } else if (elements instanceof HTMLElement) {
      ps = [elements];
    } else {
      ps = w.document.querySelector(PICTUREFILL_SELECTOR);
    }

    // loop through elements and fill them in
    var imageData = [];
    for (var i = 0, il = ps.length; i < il; i++){
      var el = ps[i];

      // ensure this element is actually a image to picturefill
      if(el.getAttribute("data-type") !== "image" ){
        // not image to fill, skip this one
        continue;
      }

      // check if image is in viewport for lazy loading, and
      // preload images if they're within 100px of being shown.
      var innerHeight = w.innerHeight || w.document.documentElement.clientHeight,
          visible = el.getBoundingClientRect().top <= (innerHeight + 250);

      // this is a div to picturefill, start working on it if it hasn't been rendered yet
      if (el.getAttribute("data-image-id") !== null
          && visible
          && (forceRerender || !el.getAttribute("data-rendered"))) {
        var imageContainer = el.getElementsByTagName("div")[0],
            imageId = el.getAttribute("data-image-id"),
            imageCrop = el.getAttribute("data-crop"),
            format = el.getAttribute("data-format") || "jpg";

        // construct ID path for image
        var idStr = "";
        for(var ii = 0; ii < imageId.length; ii++) {
          if ((ii % 4) === 0) {
            idStr += "/";
          }
          idStr += imageId.charAt(ii);
        }

        // find any existing img element in the picture element
        var picImg = imageContainer.getElementsByTagName("img")[0];
        if(!picImg){
          // for performance reasons this will be added to the dom later
          picImg = w.document.createElement("img");

          var alt = el.getAttribute("data-alt");
          if (alt) {
            picImg.alt = alt;
          }
        }

        // determine what to do based on format
        if (format === "gif") {
          // for GIFs, we just dump out original
          imageData.push({
            'div': imageContainer,
            'img': picImg,
            'url': IMAGE_URL + idStr + "/animated/original.gif"
          });
        } else {
          // determine size & crop for PNGs & JPGs.
          var _w = imageContainer.offsetWidth,
              _h = imageContainer.offsetHeight;

          if (!imageCrop || imageCrop === "") {
            imageCrop = computeAspectRatio(_w, _h);
          }

          // scale up to the pixel ratio if there's some pixel ratio defined
          if (w.devicePixelRatio) {
            _w = Math.round(w.devicePixelRatio * _w);
            _h = Math.round(w.devicePixelRatio * _h);
          }

          // determine if a breakpoint width should be used, otherwise use previously defined width
          var width = null;
          for (var j = 0; j < breakpoints.length; j++) {
            if (_w <= breakpoints[j]) {
              width = breakpoints[j];
              break;
            }
          }
          if (width === null) {
            if (_w > MAX_WIDTH) {
              width = MAX_WIDTH;
            } else {
              width = _w;
            }
          }

          // if the existing image is larger (or the same) than the one we're about to load, do not update.
          //  however if the crop changes, we need to reload.
          if (width > 0) {
            //ie8 doesn't support natural width, always load.
            if (typeof picImg.naturalWidth === "undefined" || picImg.naturalWidth < width
                || imageCrop !== computeAspectRatio(picImg.naturalWidth, picImg.naturalHeight)) {
              // put image in image data to render
              imageData.push({
                'div': imageContainer,
                'img': picImg,
                'url': IMAGE_URL + idStr + "/" + imageCrop + "/" + width + "." + format
              });
            }
          }
        }
      }
    }
    // loop through image data and insert images, all DOM updates should probably go here
    for(var i = 0; i < imageData.length; i++) {
      var data = imageData[i];
      data.img.src = data.url;
      if (!data.img.parentNode) {
        data.div.appendChild(data.img);
        data.div.parentNode.setAttribute("data-rendered", "true");
      }
    }
  };

  /**
   * Figure out best aspect ratio based on width, height, and given aspect ratios.
   */
  function computeAspectRatio(_w, _h) {
    if (_w !== 0 && _h !== 0) {
      var aspectRatio = _w/_h;
      for (var i in RATIOS) {
        if (Math.abs(aspectRatio - RATIOS[i][1]) / RATIOS[i][1] < ASPECT_RATIO_TOLERANCE) {
          return RATIOS[i][0];
        }
      }
    } else {
      return "16x9";
    }
  }

  function addEventListener(ele, event, callback) {
    if (ele.addEventListener) {
      ele.addEventListener(event, callback, false);
    } else if (ele.attachEvent) {
      ele.attachEvent("on" + event, callback);
    }
  }

  function removeEventListener(ele, event, callback) {
    if (ele.removeEventListener) {
        ele.removeEventListener(event, callback, false);
    } else if (ele.detachEvent) {
        ele.detachEvent("on" + event, callback);
    }
  }

  // Run on resize and domready (w.load as a fallback)
  if (!w.IMAGE_LISTENERS_DISABLED) {

    addEventListener(w, "load", w.picturefill);
    addEventListener(w, "DOMContentLoaded", function () {
      w.picturefill();
      removeEventListener(w, "load");
    });

    var resizeTimeout;
    addEventListener(w, "resize", function () {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(function () {
        w.picturefill(null, true);
      }, 100);
    });

    addEventListener(w, "scroll", throttle(w.picturefill, 100));

  }

}(this));<commit_msg>I'm a real dum-dum<commit_after>(function(w){
  /* We can request an image at every possible width, but let's limit it to a reasonable number
   We can set these so they correspond to our more common sizes.
   */
  var IMAGE_URL = w.BETTY_IMAGE_URL || "{{ BETTY_IMAGE_URL }}",
      RATIOS = {{ BETTY_RATIOS|safe }},
      ASPECT_RATIO_TOLERANCE = .1, // 10% tolerance.
      MAX_WIDTH = {{ BETTY_MAX_WIDTH }},
      PICTUREFILL_SELECTOR = w.PICTUREFILL_SELECTOR || "div",
      breakpoints = [{{ BETTY_WIDTHS|join:","}}];

  // Credit to https://remysharp.com/2010/07/21/throttling-function-calls
  function throttle(fn, threshhold, scope) {
    threshhold || (threshhold = 250);
    var last,
        deferTimer;
    return function () {
      var context = scope || this;

      var now = +new Date,
          args = arguments;
      if (last && now < last + threshhold) {
        // hold on to it
        clearTimeout(deferTimer);
        deferTimer = setTimeout(function () {
          last = now;
          fn.apply(context, args);
        }, threshhold);
      } else {
        last = now;
        fn.apply(context, args);
      }
    };
  }

  w.picturefill = function(elements, forceRerender) {

    // get elements to picturefill
    var ps;
    if (elements instanceof Array) {
      ps = elements;
    } else if (elements instanceof HTMLElement) {
      ps = [elements];
    } else {
      ps = w.document.querySelectorAll(PICTUREFILL_SELECTOR);
    }

    // loop through elements and fill them in
    var imageData = [];
    for (var i = 0, il = ps.length; i < il; i++){
      var el = ps[i];

      // ensure this element is actually a image to picturefill
      if(el.getAttribute("data-type") !== "image" ){
        // not image to fill, skip this one
        continue;
      }

      // check if image is in viewport for lazy loading, and
      // preload images if they're within 100px of being shown.
      var innerHeight = w.innerHeight || w.document.documentElement.clientHeight,
          visible = el.getBoundingClientRect().top <= (innerHeight + 250);

      // this is a div to picturefill, start working on it if it hasn't been rendered yet
      if (el.getAttribute("data-image-id") !== null
          && visible
          && (forceRerender || !el.getAttribute("data-rendered"))) {
        var imageContainer = el.getElementsByTagName("div")[0],
            imageId = el.getAttribute("data-image-id"),
            imageCrop = el.getAttribute("data-crop"),
            format = el.getAttribute("data-format") || "jpg";

        // construct ID path for image
        var idStr = "";
        for(var ii = 0; ii < imageId.length; ii++) {
          if ((ii % 4) === 0) {
            idStr += "/";
          }
          idStr += imageId.charAt(ii);
        }

        // find any existing img element in the picture element
        var picImg = imageContainer.getElementsByTagName("img")[0];
        if(!picImg){
          // for performance reasons this will be added to the dom later
          picImg = w.document.createElement("img");

          var alt = el.getAttribute("data-alt");
          if (alt) {
            picImg.alt = alt;
          }
        }

        // determine what to do based on format
        if (format === "gif") {
          // for GIFs, we just dump out original
          imageData.push({
            'div': imageContainer,
            'img': picImg,
            'url': IMAGE_URL + idStr + "/animated/original.gif"
          });
        } else {
          // determine size & crop for PNGs & JPGs.
          var _w = imageContainer.offsetWidth,
              _h = imageContainer.offsetHeight;

          if (!imageCrop || imageCrop === "") {
            imageCrop = computeAspectRatio(_w, _h);
          }

          // scale up to the pixel ratio if there's some pixel ratio defined
          if (w.devicePixelRatio) {
            _w = Math.round(w.devicePixelRatio * _w);
            _h = Math.round(w.devicePixelRatio * _h);
          }

          // determine if a breakpoint width should be used, otherwise use previously defined width
          var width = null;
          for (var j = 0; j < breakpoints.length; j++) {
            if (_w <= breakpoints[j]) {
              width = breakpoints[j];
              break;
            }
          }
          if (width === null) {
            if (_w > MAX_WIDTH) {
              width = MAX_WIDTH;
            } else {
              width = _w;
            }
          }

          // if the existing image is larger (or the same) than the one we're about to load, do not update.
          //  however if the crop changes, we need to reload.
          if (width > 0) {
            //ie8 doesn't support natural width, always load.
            if (typeof picImg.naturalWidth === "undefined" || picImg.naturalWidth < width
                || imageCrop !== computeAspectRatio(picImg.naturalWidth, picImg.naturalHeight)) {
              // put image in image data to render
              imageData.push({
                'div': imageContainer,
                'img': picImg,
                'url': IMAGE_URL + idStr + "/" + imageCrop + "/" + width + "." + format
              });
            }
          }
        }
      }
    }
    // loop through image data and insert images, all DOM updates should probably go here
    for(var i = 0; i < imageData.length; i++) {
      var data = imageData[i];
      data.img.src = data.url;
      if (!data.img.parentNode) {
        data.div.appendChild(data.img);
        data.div.parentNode.setAttribute("data-rendered", "true");
      }
    }
  };

  /**
   * Figure out best aspect ratio based on width, height, and given aspect ratios.
   */
  function computeAspectRatio(_w, _h) {
    if (_w !== 0 && _h !== 0) {
      var aspectRatio = _w/_h;
      for (var i in RATIOS) {
        if (Math.abs(aspectRatio - RATIOS[i][1]) / RATIOS[i][1] < ASPECT_RATIO_TOLERANCE) {
          return RATIOS[i][0];
        }
      }
    } else {
      return "16x9";
    }
  }

  function addEventListener(ele, event, callback) {
    if (ele.addEventListener) {
      ele.addEventListener(event, callback, false);
    } else if (ele.attachEvent) {
      ele.attachEvent("on" + event, callback);
    }
  }

  function removeEventListener(ele, event, callback) {
    if (ele.removeEventListener) {
        ele.removeEventListener(event, callback, false);
    } else if (ele.detachEvent) {
        ele.detachEvent("on" + event, callback);
    }
  }

  // Run on resize and domready (w.load as a fallback)
  if (!w.IMAGE_LISTENERS_DISABLED) {

    addEventListener(w, "load", w.picturefill);
    addEventListener(w, "DOMContentLoaded", function () {
      w.picturefill();
      removeEventListener(w, "load");
    });

    var resizeTimeout;
    addEventListener(w, "resize", function () {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(function () {
        w.picturefill(null, true);
      }, 100);
    });

    addEventListener(w, "scroll", throttle(w.picturefill, 100));

  }

}(this));<|endoftext|>


<commit_before>/*
 *  Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var ENTER_KEY_CODE = 13;
var widgets = require('@jupyter-widgets/base');
var controls = require('@jupyter-widgets/controls');
var _ = require('underscore');

var selectMultipleWidget = require('./easyForm/selectMultipleWidget');
var selectMultipleSingleWidget = require('./easyForm/selectMultipleSingleWidget');
var datePickerWidget = require('./easyForm/datePickerWidget');
var textWidget = require('./easyForm/textWidget');
var comboBoxWidget = require('./easyForm/comboBoxWidget');

controls.TextView.prototype.handleEnterKeyPress = function() {
  if (e.keyCode == 13) {
    this.send({ event: 'submit' });
    e.preventDefault();
  }
};

require('./easyForm/css/jupyter-easyform.scss');
require('flatpickr/dist/flatpickr.css');
require('jquery-ui/themes/base/all.css');

var EasyFormModel = widgets.DOMWidgetModel.extend({
  defaults: function() {
    return _.extend({}, widgets.DOMWidgetModel.prototype.defaults.apply(this), {
      _model_name: 'EasyFormModel',
      _view_name: 'EasyFormView',
      _model_module: 'beakerx',
      _view_module: 'beakerx',
      children: []
    });
  }
}, {
  serializers: _.extend({
    children: {deserialize: widgets.unpack_models},
  }, widgets.DOMWidgetModel.serializers)
});

var EasyFormView = controls.BoxView.extend({
  render: function() {
    var that = this;

    EasyFormView.__super__.render.apply(this);

    this.$el
      .addClass('beaker-easyform-container')
      .addClass('widget-vbox');

    var formTitle = this.model.get('easyFormName');

    this.$fieldset = $('<fieldset></fieldset>').addClass('beaker-fieldset');
    this.$legend = $('<legend>'+formTitle+'</legend>');

    this.displayed.then(function() {
      that.$el.wrap(that.$fieldset);
      if (formTitle) {
        that.$el.before(that.$legend);
      }
    });
  }
});

EasyFormView.prototype.events = function () {
  return {
    'keypress': 'handleEnterKeyPress'
  };
};

EasyFormView.prototype.handleEnterKeyPress = function(event) {
  if (event.which !== ENTER_KEY_CODE) {
    return event;
  }

  var $button = this.$el.find('> .widget-button');

  $(event.target).is('[type="text"]') && $button.first().trigger('click');
};

module.exports = {
  EasyFormModel: EasyFormModel,
  EasyFormView: EasyFormView
};

_.extend(module.exports, selectMultipleWidget);
_.extend(module.exports, selectMultipleSingleWidget);
_.extend(module.exports, datePickerWidget);
_.extend(module.exports, textWidget);
_.extend(module.exports, comboBoxWidget);
<commit_msg>#5968 fix missing jquery-ui widgets (#5969)<commit_after>/*
 *  Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var ENTER_KEY_CODE = 13;
var widgets = require('@jupyter-widgets/base');
var controls = require('@jupyter-widgets/controls');
var _ = require('underscore');

var selectMultipleWidget = require('./easyForm/selectMultipleWidget');
var selectMultipleSingleWidget = require('./easyForm/selectMultipleSingleWidget');
var datePickerWidget = require('./easyForm/datePickerWidget');
var textWidget = require('./easyForm/textWidget');
var comboBoxWidget = require('./easyForm/comboBoxWidget');

controls.TextView.prototype.handleEnterKeyPress = function() {
  if (e.keyCode == 13) {
    this.send({ event: 'submit' });
    e.preventDefault();
  }
};

require('./easyForm/css/jupyter-easyform.scss');
require('flatpickr/dist/flatpickr.css');
require('jquery-ui/themes/base/all.css');
require('jquery-ui/ui/widgets/button');
require('jquery-ui/ui/widgets/autocomplete');

var EasyFormModel = widgets.DOMWidgetModel.extend({
  defaults: function() {
    return _.extend({}, widgets.DOMWidgetModel.prototype.defaults.apply(this), {
      _model_name: 'EasyFormModel',
      _view_name: 'EasyFormView',
      _model_module: 'beakerx',
      _view_module: 'beakerx',
      children: []
    });
  }
}, {
  serializers: _.extend({
    children: {deserialize: widgets.unpack_models},
  }, widgets.DOMWidgetModel.serializers)
});

var EasyFormView = controls.BoxView.extend({
  render: function() {
    var that = this;

    EasyFormView.__super__.render.apply(this);

    this.$el
      .addClass('beaker-easyform-container')
      .addClass('widget-vbox');

    var formTitle = this.model.get('easyFormName');

    this.$fieldset = $('<fieldset></fieldset>').addClass('beaker-fieldset');
    this.$legend = $('<legend>'+formTitle+'</legend>');

    this.displayed.then(function() {
      that.$el.wrap(that.$fieldset);
      if (formTitle) {
        that.$el.before(that.$legend);
      }
    });
  }
});

EasyFormView.prototype.events = function () {
  return {
    'keypress': 'handleEnterKeyPress'
  };
};

EasyFormView.prototype.handleEnterKeyPress = function(event) {
  if (event.which !== ENTER_KEY_CODE) {
    return event;
  }

  var $button = this.$el.find('> .widget-button');

  $(event.target).is('[type="text"]') && $button.first().trigger('click');
};

module.exports = {
  EasyFormModel: EasyFormModel,
  EasyFormView: EasyFormView
};

_.extend(module.exports, selectMultipleWidget);
_.extend(module.exports, selectMultipleSingleWidget);
_.extend(module.exports, datePickerWidget);
_.extend(module.exports, textWidget);
_.extend(module.exports, comboBoxWidget);
<|endoftext|>


<commit_before>var geocoder = require('node-geocoder');
var util = require('util');
var BaseLocation = require('./BaseLocation');

util.inherits(OpenStreetMapLocation, BaseLocation);

/**
 * Create GM instance
 * @constructor
 */
function OpenStreetMapLocation() {
  BaseLocation.apply(this, arguments);

  this.setProvider(geocoder('openstreetmap', 'http', this.get()));
}

/**
 * Geocode address and get latitude\longitude for it
 * @param {String} address
 * @returns {Promise}
 */
OpenStreetMapLocation.prototype.geocode = function (address) {
  return this.getProvider().geocode(address);
};

/**
 * Reverse geocode to address
 * @param {Number} latitude
 * @param {Number} longitude
 * @returns {Promise}
 */
OpenStreetMapLocation.prototype.reverse = function (latitude, longitude) {
  return this.getProvider().reverse({lat: latitude, lon: longitude});
};

module.exports = OpenStreetMapLocation;
<commit_msg>Rewrite OpenStreetMapLocation with ES6<commit_after>import geocoder from 'node-geocoder';
import BaseLocation from './BaseLocation';

export default class OpenStreetMapLocation extends BaseLocation {
  constructor(...args) {
    super(...args);

    this.setProvider(geocoder('openstreetmap', 'http', this.get()));
  }

  /**
   * Geocode address and get latitude\longitude for it
   * @param {String} address
   * @returns {Promise}
   */
  geocode(address) {
    return this.getProvider().geocode(address);
  }

  /**
   * Reverse geocode to address
   * @param {Number} latitude
   * @param {Number} longitude
   * @returns {Promise}
   */
  reverse(latitude, longitude) {
    return this.getProvider().reverse({lat: latitude, lon: longitude});
  }
}
<|endoftext|>


<commit_before>// Which Unicode version should be used?
var version = '8.0.0';

var start = require('unicode-' + version + '/properties/ID_Start/code-points')
    .filter(function(ch) { return ch > 127; });
var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/properties/ID_Continue/code-points')
    .filter(function(ch) { return ch > 127 && start.indexOf(ch) == -1; }));

function pad(str, width) {
  while (str.length < width) str = "0" + str;
  return str;
}

function esc(code) {
  var hex = code.toString(16);
  if (hex.length <= 2) return "\\x" + pad(hex, 2);
  else return "\\u" + pad(hex, 4);
}

function generate(chars) {
  var astral = [], re = "";
  for (var i = 0, at = 0x10000; i < chars.length; i++) {
    var from = chars[i], to = from;
    while (i < chars.length - 1 && chars[i + 1] == to + 1) {
      i++;
      to++;
    }
    if (to <= 0xffff) {
      if (from == to) re += esc(from);
      else if (from + 1 == to) re += esc(from) + esc(to);
      else re += esc(from) + "-" + esc(to);
    } else {
      astral.push(from - at, to - from);
      at = to;
    }
  }
  return {nonASCII: re, astral: astral};
}

var startData = generate(start), contData = generate(cont);

console.log("let nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\"");
console.log("let nonASCIIidentifierChars = \"" + contData.nonASCII + "\"");
console.log("const astralIdentifierStartCodes = " + JSON.stringify(startData.astral));
console.log("const astralIdentifierCodes = " + JSON.stringify(contData.astral));
<commit_msg>Speed up generate-identifier-regex<commit_after>// Which Unicode version should be used?
var version = '8.0.0';

var start = require('unicode-' + version + '/properties/ID_Start/code-points')
    .filter(function(ch) { return ch > 127; });
var last = -1;
var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/properties/ID_Continue/code-points')
    .filter(function(ch) { return ch > 127 && search(start, ch, last + 1) == -1; }));

function search(arr, ch, starting) {
  for (var i = starting; arr[i] <= ch && i < arr.length; last = i++)
    if (arr[i] === ch)
      return i;
  return -1;
}

function pad(str, width) {
  while (str.length < width) str = "0" + str;
  return str;
}

function esc(code) {
  var hex = code.toString(16);
  if (hex.length <= 2) return "\\x" + pad(hex, 2);
  else return "\\u" + pad(hex, 4);
}

function generate(chars) {
  var astral = [], re = "";
  for (var i = 0, at = 0x10000; i < chars.length; i++) {
    var from = chars[i], to = from;
    while (i < chars.length - 1 && chars[i + 1] == to + 1) {
      i++;
      to++;
    }
    if (to <= 0xffff) {
      if (from == to) re += esc(from);
      else if (from + 1 == to) re += esc(from) + esc(to);
      else re += esc(from) + "-" + esc(to);
    } else {
      astral.push(from - at, to - from);
      at = to;
    }
  }
  return {nonASCII: re, astral: astral};
}

var startData = generate(start), contData = generate(cont);

console.log("let nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\"");
console.log("let nonASCIIidentifierChars = \"" + contData.nonASCII + "\"");
console.log("const astralIdentifierStartCodes = " + JSON.stringify(startData.astral));
console.log("const astralIdentifierCodes = " + JSON.stringify(contData.astral));
<|endoftext|>


<commit_before>'use strict';

angular.module('robcolbertApp')
.controller('VideosCtrl', [
  '$window',
  '$scope',
  '$sce',
  '$timeout',
  '$interval',
  function ($window, $scope, $sce, $timeout, $interval) {
    $scope.$emit('setPageGroup', 'videos');
    $scope.videos = [
      /*{
        'type':'hosted',
        'title':'ASO-RT Demo: Dynamic Data Sources',
        'description': 'Demonstration of creating new dataSource instances and the charts and grids that display them.',
        'url': 'videos/asort-mean.001.ogv'
      },*/
      {
        'type':'youtube',
        'title':'',
        'description':'',
        'videoId':'GdAz5nd7Uj8'
      },
      {
        'type':'youtube',
        'title':'Quadski (One Awesome Vehicle)',
        'description':'Possibly the most awesome vehicle on the surface of Earth right now. Would love to commute to work on this!',
        'videoId':'xOCxT89ynbA'
      },
      {
        'type':'youtube',
        'title':'Adventure Club - Wonder (Dabin Remix)',
        'description':'Published on Feb 14, 2014',
        'videoId':'2xXMqJwndTU'
      },
      {
        'type':'youtube',
        'title':'Reach For The Sky (Ft. Diane Charlemagne) (The Others Remix)',
        'description':'Published on Feb 10, 2014',
        'videoId':'XKNOc6XDyRo'
      }
    ];

    $scope.players = { };

    $scope.playVideo = function (videoId) {
      $scope.players[videoId].playVideo();
    };

    $scope.pauseVideo = function (videoId) {
      $scope.players[videoId].pauseVideo();
    };

    $window.onYouTubeIframeAPIReady = function ( ) {
      console.log('YouTube  API ready');
      $scope.videos.forEach(function (video) {
        switch (video.type) {
          case 'youtube':
//             $timeout(function ( ) {
//               var params = { 'allowScriptAccess': 'always' };
//               var atts = { 'id': video.videoId };
//               // var embedUrl = 'http://www.youtube.com/embed/'+video.videoId+'?enablejsapi=1&playerapiid='+video.videoId+'&version=3';
//               var embedUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid='+video.videoId;
//               video.url = $sce.trustAsResourceUrl(embedUrl);
//               swfobject.embedSWF(embedUrl, video.videoId, '425', '356', '8', null, null, params, atts);
//             }, 0);

            $timeout(function ( ) {
              $scope.players[video.videoId] = new $window.YT.Player(video.videoId, {
                height: '390',
                width: '640',
                videoId: video.videoId,
                playerVars: {
                  controls: 0,
                  modestbranding: 1,
                  playsinline: 0 /* full-screen on iProducts, please */,
                  showinfo: 0
                },
                events: {
                  'onReady': function onReady ( ) {
                    console.log('YouTube video', video.videoId, 'is ready');
                  },
                  'onStateChange': function onPlayerStateChange (newState) {
                    if ($scope.videoUpdateIntervalId !== null) {
                      clearInterval($scope.videoUpdateIntervalId);
                      $scope.videoUpdateIntervalId = null;
                    }
                    console.log('onPlayerStateChange', video.videoId, 'newState', video.state);
                    $scope.$apply(function ( ) {
                      video.state = newState.data;
                      switch (video.state) {
                        case -1:
                          video.stateLabel = '';
                          break;
                        case 0:
                          video.stateLabel = 'end';
                          break;
                        case 1:
                          video.stateLabel = 'play';
                          $scope.videoUpdateIntervalId = $interval(function ( ) {
                            var player = $scope.players[video.videoId];
                            video.currentTime = Math.round(player.getCurrentTime());
                            video.duration = Math.round(player.getDuration().toFixed(2));
                            video.playedFraction = (video.currentTime / video.duration).toFixed(2);
                            video.loadedFraction = (player.getVideoLoadedFraction()).toFixed(2);
                          }, 100);
                          break;
                        case 2:
                          video.stateLabel = 'pause';
                          break;
                        case 3:
                          video.stateLabel = 'buffer';
                          break;
                        case 4:
                          video.stateLabel = 'cued';
                          break;
                      }
                    });
                  }
                }
              });
            }, 0);
            break;
        }
      });
    };

    $window.onYouTubePlayerReady = function (/*playerId*/) {
      console.log('YouTube Player API ready');
    };

  }
]);
<commit_msg>Added title & desc for new video on videos page<commit_after>'use strict';

angular.module('robcolbertApp')
.controller('VideosCtrl', [
  '$window',
  '$scope',
  '$sce',
  '$timeout',
  '$interval',
  function ($window, $scope, $sce, $timeout, $interval) {
    $scope.$emit('setPageGroup', 'videos');

    /*
     * 'type':'hosted',
     * 'title':'ASO-RT Demo: Dynamic Data Sources',
     * 'description': 'Demonstration of creating new dataSource instances and the charts and grids that display them.',
     * 'url': 'videos/asort-mean.001.ogv'
     */
    $scope.videos = [
      {
        'type':'youtube',
        'title':'Krewella - Live For The Night (Pegboard Nerds Remix)',
        'videoId':'GdAz5nd7Uj8',
        'description':
        'Sorry to keep you waiting but we didn\'t have time to upload anything, we are very sorry and from now on we will upload every 2 days.' +
          'Another great upload of ours this time its a remix from Pegboard Nerds they made an exellent job of remixing "Live For The Night" by Krewella so we hope you like it ;)'
      },
      {
        'type':'youtube',
        'title':'Quadski (One Awesome Vehicle)',
        'description':'Possibly the most awesome vehicle on the surface of Earth right now. Would love to commute to work on this!',
        'videoId':'xOCxT89ynbA'
      },
      {
        'type':'youtube',
        'title':'Adventure Club - Wonder (Dabin Remix)',
        'description':'Published on Feb 14, 2014',
        'videoId':'2xXMqJwndTU'
      },
      {
        'type':'youtube',
        'title':'Reach For The Sky (Ft. Diane Charlemagne) (The Others Remix)',
        'description':'Published on Feb 10, 2014',
        'videoId':'XKNOc6XDyRo'
      }
    ];

    $scope.players = { };

    $scope.playVideo = function (videoId) {
      $scope.players[videoId].playVideo();
    };

    $scope.pauseVideo = function (videoId) {
      $scope.players[videoId].pauseVideo();
    };

    $window.onYouTubeIframeAPIReady = function ( ) {
      console.log('YouTube  API ready');
      $scope.videos.forEach(function (video) {
        switch (video.type) {
          case 'youtube':
//             $timeout(function ( ) {
//               var params = { 'allowScriptAccess': 'always' };
//               var atts = { 'id': video.videoId };
//               // var embedUrl = 'http://www.youtube.com/embed/'+video.videoId+'?enablejsapi=1&playerapiid='+video.videoId+'&version=3';
//               var embedUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid='+video.videoId;
//               video.url = $sce.trustAsResourceUrl(embedUrl);
//               swfobject.embedSWF(embedUrl, video.videoId, '425', '356', '8', null, null, params, atts);
//             }, 0);

            $timeout(function ( ) {
              $scope.players[video.videoId] = new $window.YT.Player(video.videoId, {
                height: '390',
                width: '640',
                videoId: video.videoId,
                playerVars: {
                  controls: 0,
                  modestbranding: 1,
                  playsinline: 0 /* full-screen on iProducts, please */,
                  showinfo: 0
                },
                events: {
                  'onReady': function onReady ( ) {
                    console.log('YouTube video', video.videoId, 'is ready');
                  },
                  'onStateChange': function onPlayerStateChange (newState) {
                    if ($scope.videoUpdateIntervalId !== null) {
                      clearInterval($scope.videoUpdateIntervalId);
                      $scope.videoUpdateIntervalId = null;
                    }
                    console.log('onPlayerStateChange', video.videoId, 'newState', video.state);
                    $scope.$apply(function ( ) {
                      video.state = newState.data;
                      switch (video.state) {
                        case -1:
                          video.stateLabel = '';
                          break;
                        case 0:
                          video.stateLabel = 'end';
                          break;
                        case 1:
                          video.stateLabel = 'play';
                          $scope.videoUpdateIntervalId = $interval(function ( ) {
                            var player = $scope.players[video.videoId];
                            video.currentTime = Math.round(player.getCurrentTime());
                            video.duration = Math.round(player.getDuration().toFixed(2));
                            video.playedFraction = (video.currentTime / video.duration).toFixed(2);
                            video.loadedFraction = (player.getVideoLoadedFraction()).toFixed(2);
                          }, 100);
                          break;
                        case 2:
                          video.stateLabel = 'pause';
                          break;
                        case 3:
                          video.stateLabel = 'buffer';
                          break;
                        case 4:
                          video.stateLabel = 'cued';
                          break;
                      }
                    });
                  }
                }
              });
            }, 0);
            break;
        }
      });
    };

    $window.onYouTubePlayerReady = function (/*playerId*/) {
      console.log('YouTube Player API ready');
    };

  }
]);
<|endoftext|>


<commit_before>angular.module('app.cases').controller('PostponeModal', PostponeModal);

PostponeModal.$inject = ['$uibModalInstance', '$scope', 'data', '$injector', 'HLUtils'];
function PostponeModal($uibModalInstance, $scope, data, $injector, HLUtils) {
    var vm = this;

    vm.type = data.type;
    vm.object = data.object;
    vm.dateField = data.dateField;
    vm.pickerIsOpen = false;
    vm.dateFormat = 'dd MMMM yyyy';
    vm.datepickerOptions = {
        startingDay: 1,
    };

    vm.disabledDates = disabledDates;
    vm.openDatePicker = openDatePicker;
    vm.postponeWithDays = postponeWithDays;
    vm.getFutureDate = getFutureDate;

    activate();

    ////

    function activate() {
        if (vm.object[vm.dateField]) {
            vm.date = moment(vm.object[vm.dateField]);
        } else {
            vm.date = moment();
        }

        vm.date = vm.date.format();

        _watchCloseDatePicker();
    }

    /**
     * When the datepicker popup is closed, update model and close modal.
     *
     * @private
     */
    function _watchCloseDatePicker() {
        $scope.$watch('vm.pickerIsOpen', function(newValue, oldValue) {
            if (!newValue && oldValue) {
                _updateDayAndCloseModal();
            }
        });
    }

    function _updateDayAndCloseModal() {
        var newDate;
        var args;

        if (!moment(vm.date).isSame(moment(vm.object[vm.dateField]))) {
            // Update the due date for this case.
            newDate = moment(vm.date).format('YYYY-MM-DD');

            args = {
                id: vm.object.id,
            };

            args[vm.dateField] = newDate;
            // Update the model so changes are reflected instantly.
            vm.object[vm.dateField] = newDate;

            // Dynamically get the model that should be updated.
            $injector.get(vm.type).patch(args, function() {
                $uibModalInstance.close();
            });
        } else {
            $uibModalInstance.close();
        }
    }

    function disabledDates(currentDate, mode) {
        var date = moment.isMoment(currentDate) ? currentDate : moment(currentDate);

        // Disable Saturday and Sunday.
        return ( mode === 'day' && ( date.day() === 6 || date.day() === 0 ) );
    }

    function openDatePicker($event) {
        $event.preventDefault();
        $event.stopPropagation();
        vm.pickerIsOpen = true;
    }

    function postponeWithDays(days) {
        vm.date = getFutureDate(days);

        _updateDayAndCloseModal();
    }

    function getFutureDate(days) {
        var futureDate = moment();

        if (futureDate.isBefore(vm.date)) {
            futureDate = moment(vm.date);
        }

        if (days !== 7) {
            // Only skip weekends if we're postponing by 1 or 2 days.
            futureDate = HLUtils.addBusinessDays(days, futureDate);
        } else {
            futureDate = futureDate.add(days, 'days').format('YYYY-MM-DD');
        }

        return futureDate;
    }
}
<commit_msg>LILY-1801: Postpone by 7 days should skip weekends<commit_after>angular.module('app.cases').controller('PostponeModal', PostponeModal);

PostponeModal.$inject = ['$uibModalInstance', '$scope', 'data', '$injector', 'HLUtils'];
function PostponeModal($uibModalInstance, $scope, data, $injector, HLUtils) {
    var vm = this;

    vm.type = data.type;
    vm.object = data.object;
    vm.dateField = data.dateField;
    vm.pickerIsOpen = false;
    vm.dateFormat = 'dd MMMM yyyy';
    vm.datepickerOptions = {
        startingDay: 1,
    };

    vm.disabledDates = disabledDates;
    vm.openDatePicker = openDatePicker;
    vm.postponeWithDays = postponeWithDays;
    vm.getFutureDate = getFutureDate;

    activate();

    ////

    function activate() {
        if (vm.object[vm.dateField]) {
            vm.date = moment(vm.object[vm.dateField]);
        } else {
            vm.date = moment();
        }

        vm.date = vm.date.format();

        _watchCloseDatePicker();
    }

    /**
     * When the datepicker popup is closed, update model and close modal.
     *
     * @private
     */
    function _watchCloseDatePicker() {
        $scope.$watch('vm.pickerIsOpen', function(newValue, oldValue) {
            if (!newValue && oldValue) {
                _updateDayAndCloseModal();
            }
        });
    }

    function _updateDayAndCloseModal() {
        var newDate;
        var args;

        if (!moment(vm.date).isSame(moment(vm.object[vm.dateField]))) {
            // Update the due date for this case.
            newDate = moment(vm.date).format('YYYY-MM-DD');

            args = {
                id: vm.object.id,
            };

            args[vm.dateField] = newDate;
            // Update the model so changes are reflected instantly.
            vm.object[vm.dateField] = newDate;

            // Dynamically get the model that should be updated.
            $injector.get(vm.type).patch(args, function() {
                $uibModalInstance.close();
            });
        } else {
            $uibModalInstance.close();
        }
    }

    function disabledDates(currentDate, mode) {
        var date = moment.isMoment(currentDate) ? currentDate : moment(currentDate);

        // Disable Saturday and Sunday.
        return ( mode === 'day' && ( date.day() === 6 || date.day() === 0 ) );
    }

    function openDatePicker($event) {
        $event.preventDefault();
        $event.stopPropagation();
        vm.pickerIsOpen = true;
    }

    function postponeWithDays(days) {
        vm.date = getFutureDate(days);

        _updateDayAndCloseModal();
    }

    function getFutureDate(days) {
        var futureDate = moment();

        if (futureDate.isBefore(vm.date)) {
            futureDate = moment(vm.date);
        }

        futureDate = HLUtils.addBusinessDays(days, futureDate);

        return futureDate;
    }
}
<|endoftext|>