<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {
  Box, LinearProgress, Typography,
  TextField, Button,
} from '@material-ui/core';
import * as cornerstone from 'cornerstone-core';
import * as api from '../api.js';
import {DICOM_TAGS} from '../dicomValues.js';
import DicomImageSequencer from '../dicomImageSequencer.js';

/**
 * React Component for viewing medical images
 */
export default class Viewer extends React.Component {
  /**
   * Creates a new instance of Viewer component
   * @param {Object} props React props for this component
   * @param {string} props.project Project
   * @param {string} props.location Location
   * @param {string} props.dataset Dataset
   * @param {string} props.dicomStore Dicom Store
   * @param {Object} props.study Study
   * @param {Object} props.series Series
   */
  constructor(props) {
    super(props);
    this.state = {
      instances: [],
      numReadyImages: 0,
      readyImagesProgress: 0,
      numRenderedImages: 0,
      renderedImagesProgress: 0,
      renderTimer: 0,
      fetchTimer: 0,
      totalTimer: 0,
      timeToFirstImage: 0,
      maxSimultaneousRequests: 20,
      isDisplaying: false,
    };

    this.dicomSequencer = new DicomImageSequencer(this.props.project,
        this.props.location,
        this.props.dataset,
        this.props.dicomStore,
        this.props.study,
        this.props.series,
    );

    this.totalImagesCount = 0;
    this.readyImages = [];
    this.readyImagesCount = 0;
    this.newSequence = false;
    this.fetchStartTime = 0;
    this.renderStartTime = 0,
    this.canvasElement;
    this.renderedImagesCount = 0;
    this.metricsIntervalId = 0;
  }

  /**
   * Set up cornerstone listeners and retrieve instance list on mount
   */
  componentDidMount() {
    cornerstone.enable(this.canvasElement);
    this.canvasElement.addEventListener('cornerstoneimagerendered',
        () => this.onImageRendered());
  }

  /**
   * Cancel ongoing fetches to avoid state change after unmount
   */
  componentWillUnmount() {
    this.getInstancesPromise.cancel();
    this.dicomSequencer.cancel();
    clearInterval(this.metricsIntervalId);
    cornerstone.disable(this.canvasElement);
  }

  /**
   * Runs when a new image is ready from the DicomImageSequencer
   * @param {Object} image Cornerstone image
   */
  onImageReady(image) {
    this.readyImages.push(image);
    this.readyImagesCount++;

    if (this.newSequence) {
      // If this is the first image in the sequence, render immediately
      this.displayNextImage();
      this.newSequence = false;
    }
  }

  /**
   * Runs when an image has been rendered to the cornerstone canvas
   */
  onImageRendered() {
    this.renderedImagesCount++;
    if (this.renderedImagesCount == 1) {
      this.renderStartTime = Date.now();
      this.setState({
        timeToFirstImage: Date.now() - this.fetchStartTime,
      });
    }

    if (this.renderedImagesCount == this.totalImagesCount) {
      // When last image is rendered, stop the
      // metrics interval and run one final time
      clearInterval(this.metricsIntervalId);
      this.updateMetrics();

      this.setState({
        isDisplaying: false,
      });
    }
    this.displayNextImage();
  }

  /**
   * Checks the queue of ready images and displays the next one if available
   */
  displayNextImage() {
    if (this.readyImages.length > 0) {
      const image = this.readyImages.shift();
      cornerstone.displayImage(this.canvasElement, image);
    } else {
      this.newSequence = true;
    }
  }

  /**
   * Updates the UI metrics for the currently running sequence
   */
  updateMetrics() {
    // Update progress bar
    this.setState({
      readyImagesProgress: this.readyImagesCount /
                              this.totalImagesCount * 100,
      numReadyImages: this.readyImagesCount,
      renderedImagesProgress: this.renderedImagesCount /
                              this.totalImagesCount * 100,
      renderTimer: Date.now() - this.renderStartTime,
      totalTimer: Date.now() - this.fetchStartTime,
      numRenderedImages: this.renderedImagesCount,
    });
  }

  /**
   * Begins fetching dicom images in sequence
   */
  startDisplayingInstances() {
    // Purge cornerstone cache
    cornerstone.imageCache.purgeCache();

    // Initialize dicomSequencer and begin fetching
    this.dicomSequencer.maxSimultaneousRequests =
        this.state.maxSimultaneousRequests;
    this.dicomSequencer.setInstances(this.state.instances);
    this.totalImagesCount =
        this.dicomSequencer.fetchInstances((image) => this.onImageReady(image));
  }

  /**
   * Retrieves a list of dicom instances in this series and then starts
   *    fetching images
   */
  getInstances() {
    // Reset metrics
    this.newSequence = true;
    this.renderedImagesCount = 0;
    this.readyImages = [];
    this.readyImagesCount = 0;
    this.fetchStartTime = Date.now();
    this.setState({
      renderTimer: 0,
      totalTimer: 0,
      fetchTimer: 0,
      numReadyImages: 0,
      readyImagesProgress: 0,
      numRenderedImages: 0,
      renderedImagesProgress: 0,
      timeToFirstImage: 0,
      isDisplaying: true,
    });

    // Set up an interval for updating metrics (10 times per second)
    this.metricsIntervalId = setInterval(() => this.updateMetrics(), 100);

    // Create a cancelable promise to allow this request to be cancelled
    // if the component is unmounted
    this.getInstancesPromise = api.makeCancelable(
        api.fetchMetadata(
            this.props.project, this.props.location,
            this.props.dataset, this.props.dicomStore,
            this.props.study[DICOM_TAGS.STUDY_UID].Value[0],
            this.props.series[DICOM_TAGS.SERIES_UID].Value[0],
        ),
    );

    // Fetch instances and then start displaying
    this.getInstancesPromise.promise
        .then((instances) => {
          this.setState({
            instances,
          });
          this.startDisplayingInstances();
        })
        .catch((reason) => {
          if (!reason.isCanceled) {
            console.error(reason);
          }
        });
  }

  /**
   * Renders the component
   * @return {ReactComponent} <Viewer/>
   */
  render() {
    return (
      <Box p={2} display="flex" flexWrap="wrap">
        <Box mr={2}>

 {
              this.canvasElement = input;
            }}
            style={{
              width: 500,
              height: 500,
              background: 'black',
            }}
          >
            <canvas className="cornerstone-canvas"></canvas>

          <LinearProgress variant="buffer"
            value={this.state.renderedImagesProgress}
            valueBuffer={this.state.readyImagesProgress} />

          <TextField
            label="Max Simultaneous Requests"
            style={{width: 250}}
            defaultValue={this.state.maxSimultaneousRequests}
            onChange={(e) => {
              this.setState({maxSimultaneousRequests: Number(e.target.value)});
            }} />

          <Button
            variant="contained"
            color="primary"
            disabled={this.state.isDisplaying}
            onClick={() => this.getInstances()}>
              Start
          </Button>
        </Box>
        <Box>
          <Typography variant="h5">
            Frames Loaded: {this.state.numReadyImages}
          </Typography>
          <Typography variant="h5">
            Frames Displayed: {this.state.numRenderedImages}
          </Typography>
          <Typography variant="h5">
            Total Time: {(this.state.totalTimer / 1000).toFixed(2)}s
          </Typography>
          <Typography variant="h5">
            Time to First Image: {
              (this.state.timeToFirstImage / 1000).toFixed(2)
            }s
          </Typography>
          <Typography variant="h5">
            Average FPS: {(this.state.numRenderedImages /
                        (this.state.renderTimer / 1000)).toFixed(2)}
          </Typography>
          <Typography variant="body1">
            Use your browser's developer tools to see bandwidth usage.
          </Typography>
        </Box>
      </Box>
    );
  }
}
Viewer.propTypes = {
  project: PropTypes.string.isRequired,
  location: PropTypes.string.isRequired,
  dataset: PropTypes.string.isRequired,
  dicomStore: PropTypes.string.isRequired,
  study: PropTypes.object.isRequired,
  series: PropTypes.object.isRequired,
};
<commit_msg>Added check that getInstancesPromise exists before cancel<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {
  Box, LinearProgress, Typography,
  TextField, Button,
} from '@material-ui/core';
import * as cornerstone from 'cornerstone-core';
import * as api from '../api.js';
import {DICOM_TAGS} from '../dicomValues.js';
import DicomImageSequencer from '../dicomImageSequencer.js';

let counter = 0;

/**
 * React Component for viewing medical images
 */
export default class Viewer extends React.Component {
  /**
   * Creates a new instance of Viewer component
   * @param {Object} props React props for this component
   * @param {string} props.project Project
   * @param {string} props.location Location
   * @param {string} props.dataset Dataset
   * @param {string} props.dicomStore Dicom Store
   * @param {Object} props.study Study
   * @param {Object} props.series Series
   */
  constructor(props) {
    super(props);
    this.state = {
      instances: [],
      numReadyImages: 0,
      readyImagesProgress: 0,
      numRenderedImages: 0,
      renderedImagesProgress: 0,
      renderTimer: 0,
      fetchTimer: 0,
      totalTimer: 0,
      timeToFirstImage: 0,
      maxSimultaneousRequests: 20,
      isDisplaying: false,
    };

    this.dicomSequencer = new DicomImageSequencer(this.props.project,
        this.props.location,
        this.props.dataset,
        this.props.dicomStore,
        this.props.study,
        this.props.series,
    );

    this.totalImagesCount = 0;
    this.readyImages = [];
    this.readyImagesCount = 0;
    this.newSequence = false;
    this.fetchStartTime = 0;
    this.renderStartTime = 0,
    this.canvasElement;
    this.renderedImagesCount = 0;
    this.metricsIntervalId = 0;
  }

  /**
   * Set up cornerstone listeners and retrieve instance list on mount
   */
  componentDidMount() {
    cornerstone.enable(this.canvasElement);
    this.canvasElement.addEventListener('cornerstoneimagerendered',
        () => this.onImageRendered());
  }

  /**
   * Cancel ongoing fetches to avoid state change after unmount
   */
  componentWillUnmount() {
    if (this.getInstancesPromise) {
      this.getInstancesPromise.cancel();
    }
    this.dicomSequencer.cancel();
    clearInterval(this.metricsIntervalId);
    cornerstone.disable(this.canvasElement);
  }

  /**
   * Runs when a new image is ready from the DicomImageSequencer
   * @param {Object} image Cornerstone image
   */
  onImageReady(image) {
    this.readyImages.push(image);
    this.readyImagesCount++;

    if (this.newSequence) {
      // If this is the first image in the sequence, render immediately
      this.displayNextImage();
      this.newSequence = false;
    }
  }

  /**
   * Runs when an image has been rendered to the cornerstone canvas
   */
  onImageRendered() {
    this.renderedImagesCount++;
    if (this.renderedImagesCount == 1) {
      this.renderStartTime = Date.now();
      this.setState({
        timeToFirstImage: Date.now() - this.fetchStartTime,
      });
    }

    if (this.renderedImagesCount == this.totalImagesCount) {
      // When last image is rendered, stop the
      // metrics interval and run one final time
      clearInterval(this.metricsIntervalId);
      this.updateMetrics();

      this.setState({
        isDisplaying: false,
      });
    }
    this.displayNextImage();
  }

  /**
   * Checks the queue of ready images and displays the next one if available
   */
  displayNextImage() {
    if (this.readyImages.length > 0) {
      const image = this.readyImages.shift();
      cornerstone.displayImage(this.canvasElement, image);
    } else {
      this.newSequence = true;
    }
  }

  /**
   * Updates the UI metrics for the currently running sequence
   */
  updateMetrics() {
    // Update progress bar
    this.setState({
      readyImagesProgress: this.readyImagesCount /
                              this.totalImagesCount * 100,
      numReadyImages: this.readyImagesCount,
      renderedImagesProgress: this.renderedImagesCount /
                              this.totalImagesCount * 100,
      renderTimer: Date.now() - this.renderStartTime,
      totalTimer: Date.now() - this.fetchStartTime,
      numRenderedImages: this.renderedImagesCount,
    });
  }

  /**
   * Begins fetching dicom images in sequence
   */
  startDisplayingInstances() {
    // Purge cornerstone cache
    cornerstone.imageCache.purgeCache();

    // Initialize dicomSequencer and begin fetching
    this.dicomSequencer.maxSimultaneousRequests =
        this.state.maxSimultaneousRequests;
    this.dicomSequencer.setInstances(this.state.instances);
    this.totalImagesCount =
        this.dicomSequencer.fetchInstances((image) => this.onImageReady(image));
  }

  /**
   * Retrieves a list of dicom instances in this series and then starts
   *    fetching images
   */
  getInstances() {
    // Reset metrics
    this.newSequence = true;
    this.renderedImagesCount = 0;
    this.readyImages = [];
    this.readyImagesCount = 0;
    this.fetchStartTime = Date.now();
    this.setState({
      renderTimer: 0,
      totalTimer: 0,
      fetchTimer: 0,
      numReadyImages: 0,
      readyImagesProgress: 0,
      numRenderedImages: 0,
      renderedImagesProgress: 0,
      timeToFirstImage: 0,
      isDisplaying: true,
    });

    // Set up an interval for updating metrics (10 times per second)
    this.metricsIntervalId = setInterval(() => this.updateMetrics(), 100);

    // Create a cancelable promise to allow this request to be cancelled
    // if the component is unmounted
    this.getInstancesPromise = api.makeCancelable(
        api.fetchMetadata(
            this.props.project, this.props.location,
            this.props.dataset, this.props.dicomStore,
            this.props.study[DICOM_TAGS.STUDY_UID].Value[0],
            this.props.series[DICOM_TAGS.SERIES_UID].Value[0],
        ),
    );

    // Fetch instances and then start displaying
    this.getInstancesPromise.promise
        .then((instances) => {
          this.setState({
            instances,
          });
          this.startDisplayingInstances();
        })
        .catch((reason) => {
          if (!reason.isCanceled) {
            console.error(reason);
          }
        });
  }

  /**
   * Renders the component
   * @return {ReactComponent} <Viewer/>
   */
  render() {
    return (
      <Box p={2} display="flex" flexWrap="wrap">
        <Box mr={2}>

 {
              this.canvasElement = input;
            }}
            style={{
              width: 500,
              height: 500,
              background: 'black',
            }}
          >
            <canvas className="cornerstone-canvas"></canvas>

          <LinearProgress variant="buffer"
            value={this.state.renderedImagesProgress}
            valueBuffer={this.state.readyImagesProgress} />

          <TextField
            label="Max Simultaneous Requests"
            style={{width: 250}}
            defaultValue={this.state.maxSimultaneousRequests}
            onChange={(e) => {
              this.setState({maxSimultaneousRequests: Number(e.target.value)});
            }} />

          <Button
            variant="contained"
            color="primary"
            disabled={this.state.isDisplaying}
            onClick={() => this.getInstances()}>
              Start
          </Button>
        </Box>
        <Box>
          <Typography variant="h5">
            Frames Loaded: {this.state.numReadyImages}
          </Typography>
          <Typography variant="h5">
            Frames Displayed: {this.state.numRenderedImages}
          </Typography>
          <Typography variant="h5">
            Total Time: {(this.state.totalTimer / 1000).toFixed(2)}s
          </Typography>
          <Typography variant="h5">
            Time to First Image: {
              (this.state.timeToFirstImage / 1000).toFixed(2)
            }s
          </Typography>
          <Typography variant="h5">
            Average FPS: {(this.state.numRenderedImages /
                        (this.state.renderTimer / 1000)).toFixed(2)}
          </Typography>
          <Typography variant="body1">
            Use your browser's developer tools to see bandwidth usage.
          </Typography>
        </Box>
      </Box>
    );
  }
}
Viewer.propTypes = {
  project: PropTypes.string.isRequired,
  location: PropTypes.string.isRequired,
  dataset: PropTypes.string.isRequired,
  dicomStore: PropTypes.string.isRequired,
  study: PropTypes.object.isRequired,
  series: PropTypes.object.isRequired,
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict'

var fs = require('fs')
var path = require('path')
var spawn = require('cross-spawn')
var chalk = require('chalk')
// var semver = require('semver')
var argv = require('minimist')(process.argv.slice(2))
var pathExists = require('path-exists')
var request = require('request')
var inquirer = require('inquirer')

var VERSION = require(path.resolve(__dirname, 'package.json')).version

// Command line prelude (version and usage)
var commands = argv._
if (commands.length === 0) {
  if (argv.version) {
    console.log(chalk.green('create-cycle-app version: ' + VERSION))
    process.exit()
  }
  console.error(chalk.red('Usage: create-cycle-app <project-directory> [--flavor] [--verbose]'))
  process.exit(1)
}

createApp(commands[0], argv.verbose, argv.flavor)

// Parse the command line options and run the setup
function createApp (name, verbose, flavor) {
  var appFolder = path.resolve(name)
  var appName = path.basename(appFolder)

  // Check the folder for files that can conflict
  if (!pathExists.sync(appFolder)) {
    fs.mkdirSync(appFolder)
  } else if (!isSafeToCreateProjectIn(appFolder)) {
    console.log(chalk.red('The directory `' + appFolder + '` contains file(s) that could conflict. Aborting.'))
    process.exit(1)
  }

  function byName (a, b) {
    return a.name > b.name
  }

  function notDiscovery (flavor) {
    return flavor.value !== 'run-discovery'
  }

  var discoverMore = {
    name: 'Discover more...',
    value: 'run-discovery'
  }

  var coreFlavors = require('./coreFlavors.json')

  var streamLibQuestion = {
    name: 'streamLib',
    message: 'Which stream library do you want to use?',
    type: 'list',
    choices: [
      {
        name: 'XStream, tailored for Cycle.js',
        value: 'xstream'
      },
      {
        name: 'Most.js, a blazing fast stream library',
        value: 'most'
      },
      {
        name: 'RxJS v5',
        value: 'rxjs'
      },
      {
        name: 'RxJS v4',
        value: 'rx'
      }
    ],
    when: function (currentAnswers) {
      return currentAnswers.flavor !== 'run-discovery'
    }
  }

  if (flavor) {
    // Ask just for the stream library
    inquirer.prompt([streamLibQuestion]).then(function (answers) {
      preparePackageJson(appFolder, appName, flavor, answers.streamLib, verbose)
    })
  } else {
    inquirer.prompt([
      {
        name: 'flavor',
        message: 'Which flavor do you want to use?',
        type: 'list',
        choices: coreFlavors.sort(byName).concat(discoverMore)
      },
      streamLibQuestion
    ]).then(function (answers) {
      // When run-discovery was choosed, we need to discover
      // flavors somewhere else
      if (answers.flavor === 'run-discovery') {
        discoverFlavors(function (err, flavors) {
          if (err) {
            throw err
          }

          inquirer.prompt([
            {
              name: 'flavor',
              message: 'Which flavor do you want to use?',
              type: 'list',
              choices: flavors.sort(byName).concat(coreFlavors.filter(notDiscovery))
            },
            streamLibQuestion
          ]).then(function (answers) {
            preparePackageJson(appFolder, appName, answers.flavor, answers.streamLib, verbose)
          })
        })
      } else {
        preparePackageJson(appFolder, appName, answers.flavor, answers.streamLib, verbose)
      }
    })
  }
}

function discoverFlavors (cb) {
  console.log()
  console.log(chalk.cyan('Searching for flavors on npm...'))
  console.log()

  var keyword = 'create-cycle-app-flavor'
  var level = 3
  var url = 'https://registry.npmjs.org/' +
    '-/_view/byKeyword?' +
    'startkey=[%22' + keyword + '%22]' +
    '&endkey=[%22' + keyword + '%22,%7B%7D]' +
    '&group_level=' + level

  request({
    url: url,
    headers: {
      'User-Agent': 'create-cycle-app ' + VERSION
    }
  }, function (err, res, body) {
    if (err) {
      cb(err)
    }
    if (res.statusCode !== 200) {
      console.error(chalk.red('Flavors request failed with status: ' + res.statusCode))
      return
    }

    var npmContent = JSON.parse(body).rows
    var communityFlavors = npmContent.map(function (itemFound) {
      return {
        // Use package.json description to show the name
        name: itemFound.key[2],
        value: itemFound.key[1]
      }
    })

    if (communityFlavors.length === 0) {
      console.log(chalk.yellow('...none found'))
      console.log()
    }
    cb(null, communityFlavors)
  })
}

function preparePackageJson (appFolder, appName, flavor, streamLib, verbose) {
  // Start creating the new app
  console.log(chalk.green('Creating a new Cycle.js app in ' + appFolder + '.'))
  console.log()

  // Write some package.json configuration
  var packageJson = {
    name: appName,
    version: '0.1.0',
    private: true
  }
  fs.writeFileSync(
    path.join(appFolder, 'package.json'),
    JSON.stringify(packageJson, null, 2)
  )

  installScripts(appFolder, appName, flavor, streamLib, verbose)
}

// Install and init scripts
function installScripts (appFolder, appName, flavor, streamLib, verbose) {
  var originalDirectory = process.cwd()
  process.chdir(appFolder)

  // Find the right version
  var local = ~flavor.indexOf('./')
  var packageName = getPackageName(flavor)

  // Install dependencies
  console.log(chalk.green('Installing packages. This might take a couple minutes.'))
  console.log(chalk.green('Installing ' + packageName + ' from ' + (local ? 'local' : 'npm') + '...'))
  console.log()

  var args = [
    'install',
    verbose && '--verbose',
    '--save-dev',
    '--save-exact',
    local ? path.resolve(originalDirectory, flavor) : flavor
  ].filter(function (a) { return a })

  // Trigger npm installation
  var proc = spawn('npm', args, {stdio: 'inherit'})
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error(chalk.red('`npm ' + args.join(' ') + '` failed'))
      return
    }

    // Validate node version
    // checkNodeVersion(packageName)

    var initScriptPath = path.resolve(
      process.cwd(),
      'node_modules',
      packageName,
      'scripts',
      'init.js'
    )
    var init = require(initScriptPath)

    // Execute the cycle-scripts's specific initialization
    init(appFolder, appName, streamLib, verbose, originalDirectory)
  })
}

function getPackageName (installPackage) {
  if (~installPackage.indexOf('.tgz')) {
    return installPackage.match(/^.+\/(.+)-.+\.tgz$/)[1]
  } else if (~installPackage.indexOf('@')) {
    return installPackage.split('@')[0]
  }
  return path.basename(installPackage)
}

// function checkNodeVersion (packageName) {
//   var packageJsonPath = path.resolve(
//     process.cwd(),
//     'node_modules',
//     packageName,
//     'package.json'
//   )
//   var packageJson = require(packageJsonPath)
//   if (!packageJson.engines || !packageJson.engines.node) {
//     return
//   }
//
//   if (!semver.satisfies(process.version, packageJsonPath.engines.node)) {
//     console.error(
//       chalk.red(
//         'You are currently running Node %s but create-cycle-app requires %s. ' +
//         'Please use a supported version of Node.\n'
//       ),
//       process.version,
//       packageJsonPath.engines.node
//     )
//     process.exit(1)
//   }
// }

function isSafeToCreateProjectIn (appFolder) {
  var whitelist = [
    '.DS_Store',
    'Thumbs.db',
    '.git',
    '.gitignore',
    '.idea',
    'README.md',
    'LICENSE'
  ]
  return fs.readdirSync(appFolder)
    .every(function (file) {
      return whitelist.indexOf(file) >= 0
    })
}
<commit_msg>feat(create-cycle-app): Allow to select stream library only for core flavors<commit_after>#!/usr/bin/env node

'use strict'

var fs = require('fs')
var path = require('path')
var spawn = require('cross-spawn')
var chalk = require('chalk')
// var semver = require('semver')
var argv = require('minimist')(process.argv.slice(2))
var pathExists = require('path-exists')
var request = require('request')
var inquirer = require('inquirer')
var VERSION = require(path.resolve(__dirname, 'package.json')).version

// Command line prelude (version and usage)
var commands = argv._
if (commands.length === 0) {
  if (argv.version) {
    console.log(chalk.green('create-cycle-app version: ' + VERSION))
    process.exit()
  }
  console.error(chalk.red('Usage: create-cycle-app <project-directory> [--flavor] [--verbose]'))
  process.exit(1)
}

createApp(commands[0], argv.verbose, argv.flavor)

// Parse the command line options and run the setup
function createApp (name, verbose, flavor) {
  var appFolder = path.resolve(name)
  var appName = path.basename(appFolder)
  var coreFlavors = require('./coreFlavors.json')
  var discoverMore = {
    name: 'Discover more...',
    value: 'run-discovery'
  }

  // Check the folder for files that can conflict
  if (!pathExists.sync(appFolder)) {
    fs.mkdirSync(appFolder)
  } else if (!isSafeToCreateProjectIn(appFolder)) {
    console.log(chalk.red('The directory `' + appFolder + '` contains file(s) that could conflict. Aborting.'))
    process.exit(1)
  }

  function byName (a, b) {
    return a.name > b.name
  }

  function notDiscovery (flavor) {
    return flavor.value !== 'run-discovery'
  }

  function isCoreFlavor (flavor) {
    return Boolean(
      coreFlavors.find(function (coreFlavor) { return coreFlavor.value === flavor })
    )
  }

  var streamLibQuestion = {
    name: 'streamLib',
    message: 'Which stream library do you want to use?',
    type: 'list',
    choices: [
      {
        name: 'XStream, tailored for Cycle.js',
        value: 'xstream'
      },
      {
        name: 'Most.js, a blazing fast stream library',
        value: 'most'
      },
      {
        name: 'RxJS v5',
        value: 'rxjs'
      },
      {
        name: 'RxJS v4',
        value: 'rx'
      }
    ],
    when: function (currentAnswers) {
      return (
        currentAnswers.flavor !== 'run-discovery' &&
        isCoreFlavor(currentAnswers.flavor)
      )
    }
  }

  if (flavor) {
    // Ask just for the stream library
    inquirer.prompt([streamLibQuestion]).then(function (answers) {
      preparePackageJson(appFolder, appName, flavor, answers.streamLib, verbose)
    })
  } else {
    inquirer.prompt([
      {
        name: 'flavor',
        message: 'Which flavor do you want to use?',
        type: 'list',
        choices: coreFlavors.sort(byName).concat(discoverMore)
      },
      streamLibQuestion
    ]).then(function (answers) {
      // When run-discovery was choosed, we need to discover
      // flavors somewhere else
      if (answers.flavor === 'run-discovery') {
        discoverFlavors(function (err, flavors) {
          if (err) {
            throw err
          }

          inquirer.prompt([
            {
              name: 'flavor',
              message: 'Which flavor do you want to use?',
              type: 'list',
              choices: flavors.sort(byName).concat(coreFlavors.filter(notDiscovery))
            },
            streamLibQuestion
          ]).then(function (answers) {
            preparePackageJson(appFolder, appName, answers.flavor, answers.streamLib, verbose)
          })
        })
      } else {
        preparePackageJson(appFolder, appName, answers.flavor, answers.streamLib, verbose)
      }
    })
  }
}

function discoverFlavors (cb) {
  console.log()
  console.log(chalk.cyan('Searching for flavors on npm...'))
  console.log()

  var keyword = 'create-cycle-app-flavor'
  var level = 3
  var url = 'https://registry.npmjs.org/' +
    '-/_view/byKeyword?' +
    'startkey=[%22' + keyword + '%22]' +
    '&endkey=[%22' + keyword + '%22,%7B%7D]' +
    '&group_level=' + level

  request({
    url: url,
    headers: {
      'User-Agent': 'create-cycle-app ' + VERSION
    }
  }, function (err, res, body) {
    if (err) {
      cb(err)
    }
    if (res.statusCode !== 200) {
      console.error(chalk.red('Flavors request failed with status: ' + res.statusCode))
      return
    }

    var npmContent = JSON.parse(body).rows
    var communityFlavors = npmContent.map(function (itemFound) {
      return {
        // Use package.json description to show the name
        name: itemFound.key[2],
        value: itemFound.key[1]
      }
    })

    if (communityFlavors.length === 0) {
      console.log(chalk.yellow('...none found'))
      console.log()
    }
    cb(null, communityFlavors)
  })
}

function preparePackageJson (appFolder, appName, flavor, streamLib, verbose) {
  // Start creating the new app
  console.log(chalk.green('Creating a new Cycle.js app in ' + appFolder + '.'))
  console.log()

  // Write some package.json configuration
  var packageJson = {
    name: appName,
    version: '0.1.0',
    private: true
  }
  fs.writeFileSync(
    path.join(appFolder, 'package.json'),
    JSON.stringify(packageJson, null, 2)
  )

  installScripts(appFolder, appName, flavor, streamLib, verbose)
}

// Install and init scripts
function installScripts (appFolder, appName, flavor, streamLib, verbose) {
  var originalDirectory = process.cwd()
  process.chdir(appFolder)

  // Find the right version
  var local = ~flavor.indexOf('./')
  var packageName = getPackageName(flavor)

  // Install dependencies
  console.log(chalk.green('Installing packages. This might take a couple minutes.'))
  console.log(chalk.green('Installing ' + packageName + ' from ' + (local ? 'local' : 'npm') + '...'))
  console.log()

  var args = [
    'install',
    verbose && '--verbose',
    '--save-dev',
    '--save-exact',
    local ? path.resolve(originalDirectory, flavor) : flavor
  ].filter(function (a) { return a })

  // Trigger npm installation
  var proc = spawn('npm', args, {stdio: 'inherit'})
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error(chalk.red('`npm ' + args.join(' ') + '` failed'))
      return
    }

    // Validate node version
    // checkNodeVersion(packageName)

    var initScriptPath = path.resolve(
      process.cwd(),
      'node_modules',
      packageName,
      'scripts',
      'init.js'
    )
    var init = require(initScriptPath)

    // Execute the cycle-scripts's specific initialization
    init(appFolder, appName, streamLib, verbose, originalDirectory)
  })
}

function getPackageName (installPackage) {
  if (~installPackage.indexOf('.tgz')) {
    return installPackage.match(/^.+\/(.+)-.+\.tgz$/)[1]
  } else if (~installPackage.indexOf('@')) {
    return installPackage.split('@')[0]
  }
  return path.basename(installPackage)
}

// function checkNodeVersion (packageName) {
//   var packageJsonPath = path.resolve(
//     process.cwd(),
//     'node_modules',
//     packageName,
//     'package.json'
//   )
//   var packageJson = require(packageJsonPath)
//   if (!packageJson.engines || !packageJson.engines.node) {
//     return
//   }
//
//   if (!semver.satisfies(process.version, packageJsonPath.engines.node)) {
//     console.error(
//       chalk.red(
//         'You are currently running Node %s but create-cycle-app requires %s. ' +
//         'Please use a supported version of Node.\n'
//       ),
//       process.version,
//       packageJsonPath.engines.node
//     )
//     process.exit(1)
//   }
// }

function isSafeToCreateProjectIn (appFolder) {
  var whitelist = [
    '.DS_Store',
    'Thumbs.db',
    '.git',
    '.gitignore',
    '.idea',
    'README.md',
    'LICENSE'
  ]
  return fs.readdirSync(appFolder)
    .every(function (file) {
      return whitelist.indexOf(file) >= 0
    })
}
<|endoftext|>


<commit_before>(function($) {
    var RabbitMQChat = function() {
        this.ws = null;
        this.since = new Date().getTime() - (60 * 60 * 1000); // Scope to the last hour initially
        this.clientId = "js_" + $.base64.encode(Math.floor(Math.random() * 4294967296));
        var that = this;
        window.onunload = function() {
            if(that.ws) {
                that.ws.close();
            }
        }
    };

    RabbitMQChat.prototype.connect = function() {
        if ("WebSocket" in window) {
          // browser supports websockets
          this.ws = new WebSocket("ws://" + window.location.host + "/service");
          var that = this;
          this.ws.onopen = function() {
              // websocket is connected
              that.toggleConnStatus('connected');
          };
          this.ws.onmessage = function (evt) {
              var obj = JSON.parse(evt.data);
              that.displayMessage(obj);
          };
          this.ws.onclose = function() {
              // websocket was closed
              that.toggleConnStatus('disconnected');
              this.displayError("You got disconnected from the server");
          };

        } else {
            // browser does not support websockets
            this.displayError("Sorry, your browser does not support websockets.");
        }
    };

    RabbitMQChat.prototype.displayError = function(msg) {
        alert(msg);
    };

    RabbitMQChat.prototype.toggleConnStatus = function(status) {
        console.log(status);
    };

    RabbitMQChat.prototype.displayMessage = function(item) {
        if($('#' + item.key).length == 0) {
            var elem = $('
');
            var avatar = $('').attr('src', 'http://gravatar.com/avatar/' + item.gravatar + '?s=40');
            var name = $('').text(item.name);
            var message = $('').text(item.message);
            var timestamp = $('').text(new Date(item.timestamp).toLocaleTimeString());
            elem.append(timestamp).append(avatar).append(name).append(message);
            if(item.name == this.name && item.gravatar == this.gravatar) {
                elem.addClass('me');
            }
            $('ol#chatlog').append(elem).attr({ scrollTop: $('ol#chatlog').attr("scrollHeight") });
        }
    };

    RabbitMQChat.prototype.postMessage = function(message) {
        message = $.trim(message);
        if(message.length > 0) {
            var key = hex_md5(this.clientId + new Date().toString());
            msg = {
                'key': key,
                'message': this.escape(message),
                'name': this.escape(this.name),
                'gravatar': this.gravatar,
                'timestamp': new Date().getTime()
            };
            this.ws.send(JSON.stringify(msg));
            this.displayMessage(msg);
        }
        $('form#chatbox').get(0).reset();
    };

    RabbitMQChat.prototype.escape = function(string) {
        return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    };

    var COOKIE_NAME = 'rmqchat.name';
    var COOKIE_GRAVATAR = 'rmqchat.gravatar';

    RabbitMQChat.prototype.start = function(name, email) {
        if($.trim(email) == 'videlalvaro@gmail.com') {
	    this.name = 'derp';
	    this.email = 'derp@derp.com';
	} else {
            this.name = name;
	    this.gravatar = (email && email.indexOf('@') != -1) ? hex_md5(email) : email;
        }
        if($.trim(this.name).length != 0) {
            if(Cookie.accept()) {
                Cookie.set(COOKIE_NAME, this.name, 4);
                Cookie.set(COOKIE_GRAVATAR, this.gravatar, 4);
            }
            $('form#login').hide();
            $('ol#chatlog, form#chatbox').show();
            this.connect();
        } else {
            alert("Please enter a name for yourself. An email would be nice too (not sent over the wire).");
        }
    };

    $(document).ready(function() {
        var rmqchat = new RabbitMQChat();
        if(Cookie.accept()) {
            var name = Cookie.get(COOKIE_NAME);
            var gravatar = Cookie.get(COOKIE_GRAVATAR);
            if(name) {
                rmqchat.start(name, gravatar);
            }
        }
        $('form#login').submit(function(e) {
            e.preventDefault();
            rmqchat.start($('#name').val(), $('#email').val());
            return false;
        });
        $('form#chatbox').submit(function(e) {
            e.preventDefault();
            rmqchat.postMessage($('#message').val());
        });
    });
})(jQuery);<commit_msg>tidies up JS<commit_after>(function($) {
     var RabbitMQChat = function() {
         this.ws = null;
         this.since = new Date().getTime() - (60 * 60 * 1000); // Scope to the last hour initially
         this.clientId = "js_" + $.base64.encode(Math.floor(Math.random() * 4294967296));
         var that = this;
         window.onunload = function() {
             if(that.ws) {
                 that.ws.close();
             }
         };
     };

     RabbitMQChat.prototype.connect = function() {
         if ("WebSocket" in window) {
             // browser supports websockets
             this.ws = new WebSocket("ws://" + window.location.host + "/service");
             var that = this;
             this.ws.onopen = function() {
                 // websocket is connected
                 that.toggleConnStatus('connected');
             };
             this.ws.onmessage = function (evt) {
                 var obj = JSON.parse(evt.data);
                 that.displayMessage(obj);
             };
             this.ws.onclose = function() {
                 // websocket was closed
                 that.toggleConnStatus('disconnected');
                 this.displayError("You got disconnected from the server");
             };

         } else {
             // browser does not support websockets
             this.displayError("Sorry, your browser does not support websockets.");
         }
     };

     RabbitMQChat.prototype.displayError = function(msg) {
         alert(msg);
     };

     RabbitMQChat.prototype.toggleConnStatus = function(status) {
         console.log(status);
     };

     RabbitMQChat.prototype.displayMessage = function(item) {
         if($('#' + item.key).length == 0) {
             var elem = $('
');
             var avatar = $('').attr('src', 'http://gravatar.com/avatar/' + item.gravatar + '?s=40');
             var name = $('').text(item.name);
             var message = $('').text(item.message);
             var timestamp = $('').text(new Date(item.timestamp).toLocaleTimeString());
             elem.append(timestamp).append(avatar).append(name).append(message);
             if(item.name == this.name && item.gravatar == this.gravatar) {
                 elem.addClass('me');
             }
             $('ol#chatlog').append(elem).attr({ scrollTop: $('ol#chatlog').attr("scrollHeight") });
         }
     };

     RabbitMQChat.prototype.postMessage = function(message) {
         message = $.trim(message);
         if(message.length > 0) {
             var key = hex_md5(this.clientId + new Date().toString());
             msg = {
                 'key': key,
                 'message': this.escape(message),
                 'name': this.escape(this.name),
                 'gravatar': this.gravatar,
                 'timestamp': new Date().getTime()
             };
             this.ws.send(JSON.stringify(msg));
             this.displayMessage(msg);
         }
         $('form#chatbox').get(0).reset();
     };

     RabbitMQChat.prototype.escape = function(string) {
         return string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
     };

     var COOKIE_NAME = 'rmqchat.name';
     var COOKIE_GRAVATAR = 'rmqchat.gravatar';

     RabbitMQChat.prototype.start = function(name, email) {
         this.name = name;
         this.gravatar = (email && email.indexOf('@') != -1) ? hex_md5(email) : email;
         if($.trim(this.name).length != 0) {
             if(Cookie.accept()) {
                 Cookie.set(COOKIE_NAME, this.name, 4);
                 Cookie.set(COOKIE_GRAVATAR, this.gravatar, 4);
             }
             $('form#login').hide();
             $('ol#chatlog, form#chatbox').show();
             this.connect();
         } else {
             alert("Please enter a name for yourself. An email would be nice too (not sent over the wire).");
         }
     };

     $(document).ready(function() {
                           var rmqchat = new RabbitMQChat();
                           if(Cookie.accept()) {
                               var name = Cookie.get(COOKIE_NAME);
                               var gravatar = Cookie.get(COOKIE_GRAVATAR);
                               if(name) {
                                   rmqchat.start(name, gravatar);
                               }
                           }
                           $('form#login').submit(function(e) {
                                                      e.preventDefault();
                                                      rmqchat.start($('#name').val(), $('#email').val());
                                                      return false;
                                                  });
                           $('form#chatbox').submit(function(e) {
                                                        e.preventDefault();
                                                        rmqchat.postMessage($('#message').val());
                                                    });
                       });
 })(jQuery);<|endoftext|>


<commit_before>var util = require('util');
var events = require('events');
var EventEmitter = events.EventEmitter;
var cheerio = require('cheerio');

var BandProcessor = function() {
  var self = this;
  EventEmitter.call(self);

  self.process = function(rawHtml) {
    var $ = cheerio.load(rawHtml);
    var content = $('#td_content');
    var bandsTable = content.children().first().find('table.bordercolor2');
    var bands = bandsTable.children();

    bands.each(function(index) {
      if(index === 0)
        return;
      var band = $(this).children().eq(1); // second child td
      var name = band.text().trim();
      var url = band.find('a').attr('href');
      var bandId = url.split('=')[1];
      self.emit('parse', {
        name: name,
        url: url,
        id: bandId
      });
    });
  };
};

util.inherits(BandProcessor, EventEmitter);
module.exports = BandProcessor;
<commit_msg>fix name<commit_after>var util = require('util');
var events = require('events');
var EventEmitter = events.EventEmitter;
var cheerio = require('cheerio');

var BandListProcessor = function() {
  var self = this;
  EventEmitter.call(self);

  self.process = function(rawHtml) {
    var $ = cheerio.load(rawHtml);
    var content = $('#td_content');
    var bandsTable = content.children().first().find('table.bordercolor2');
    var bands = bandsTable.children();

    bands.each(function(index) {
      if(index === 0)
        return;
      var band = $(this).children().eq(1); // second child td
      var name = band.text().trim();
      var url = band.find('a').attr('href');
      var bandId = url.split('=')[1];
      self.emit('parse', {
        name: name,
        url: url,
        id: bandId
      });
    });
  };
};

util.inherits(BandListProcessor, EventEmitter);
module.exports = BandListProcessor;
<|endoftext|>


<commit_before>import settings from './settings';

var messages = [];

var untranslated = {
  apiUnsupported: 'Your version of lichess app is too old! Please upgrade for free to the latest version.',
  apiDeprecated: 'Upgrade for free to the latest lichess app! Support for this version will be dropped on %s.',
  resourceNotFoundError: 'Resource not found',
  lichessIsUnavailableError: 'lichess.org is temporarily down for maintenance',
  mustSignIn: 'You must sign in to see this.',
  mustSignInToJoin: 'You must sign in to join it.',
  boardThemeBrown: 'Brown',
  boardThemeBlue: 'Blue',
  boardThemeGreen: 'Green',
  boardThemeGrey: 'Grey',
  boardThemePurple: 'Purple',
  boardThemeWood: 'Wood',
  boardThemeWood2: 'Wood 2',
  boardThemeWood3: 'Wood 3',
  boardThemeBlue2: 'Blue 2',
  boardThemeCanvas: 'Canvas',
  boardThemeMetal: 'Metal',
  playerisInvitingYou: '%s is inviting you',
  toATypeGame: 'To a %s game',
  unsupportedVariant: 'Variant %s is not supported in this version',
  language: 'Language'
};

var defaultCode = 'en';

function loadFile(code) {
  return m.request({
    url: 'i18n/' + code + '.json',
    method: 'GET',
    deserialize: function(text) {
      try {
        return JSON.parse(text);
      } catch (e) {
        throw { error: 'Lang not available' };
      }
    }
  }).then(function(data) {
    messages = data;
    return code;
  }, function(error) {
    // workaround for iOS: because xhr for local file has a 0 status it will
    // reject the promise and still have the response object
    if (error && error.playWithAFriend) {
      messages = error;
      return code;
    } else {
      if (code === defaultCode) throw new Error(error);
      return loadFile(defaultCode);
    }
  });
}

function loadMomentLocale(code) {
  if (code === 'en') return;
  var script = document.createElement('script');
  script.src = 'moment/locale/' + code + '.js';
  document.head.appendChild(script);
  window.moment.locale(code);
  return code;
}

function loadPreferredLanguage() {
  if (settings.general.lang())
    return loadFromSettings();

  var deferred = m.deferred();
  window.navigator.globalization.getPreferredLanguage(
    language => deferred.resolve(language.value.split('-')[0]),
    () => deferred.resolve(defaultCode)
  );
  return deferred.promise
    .then(code => {
      settings.general.lang(code);
      return code;
    })
    .then(loadFile)
    .then(loadMomentLocale);
}

function getAvailableLanguages() {
  return m.request({
    url: 'i18n/refs.json',
    method: 'GET'
  });
}

function loadFromSettings() {
  return loadFile(settings.general.lang()).then(loadMomentLocale);
}

module.exports = function(key) {
  var str = messages[key] || untranslated[key] || key;
  Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
    str = str.replace('%s', arg);
  });
  return str;
};
module.exports.loadPreferredLanguage = loadPreferredLanguage;
module.exports.getAvailableLanguages = getAvailableLanguages;
module.exports.loadFromSettings = loadFromSettings;
<commit_msg>Fix fetching langs in iOS<commit_after>import settings from './settings';

var messages = [];

var untranslated = {
  apiUnsupported: 'Your version of lichess app is too old! Please upgrade for free to the latest version.',
  apiDeprecated: 'Upgrade for free to the latest lichess app! Support for this version will be dropped on %s.',
  resourceNotFoundError: 'Resource not found',
  lichessIsUnavailableError: 'lichess.org is temporarily down for maintenance',
  mustSignIn: 'You must sign in to see this.',
  mustSignInToJoin: 'You must sign in to join it.',
  boardThemeBrown: 'Brown',
  boardThemeBlue: 'Blue',
  boardThemeGreen: 'Green',
  boardThemeGrey: 'Grey',
  boardThemePurple: 'Purple',
  boardThemeWood: 'Wood',
  boardThemeWood2: 'Wood 2',
  boardThemeWood3: 'Wood 3',
  boardThemeBlue2: 'Blue 2',
  boardThemeCanvas: 'Canvas',
  boardThemeMetal: 'Metal',
  playerisInvitingYou: '%s is inviting you',
  toATypeGame: 'To a %s game',
  unsupportedVariant: 'Variant %s is not supported in this version',
  language: 'Language'
};

var defaultCode = 'en';

function loadFile(code) {
  return m.request({
    url: 'i18n/' + code + '.json',
    method: 'GET',
    deserialize: function(text) {
      try {
        return JSON.parse(text);
      } catch (e) {
        throw { error: 'Lang not available' };
      }
    }
  }).then(function(data) {
    messages = data;
    return code;
  }, function(error) {
    // workaround for iOS: because xhr for local file has a 0 status it will
    // reject the promise and still have the response object
    if (error && error.playWithAFriend) {
      messages = error;
      return code;
    } else {
      if (code === defaultCode) throw new Error(error);
      return loadFile(defaultCode);
    }
  });
}

function loadMomentLocale(code) {
  if (code === 'en') return;
  var script = document.createElement('script');
  script.src = 'moment/locale/' + code + '.js';
  document.head.appendChild(script);
  window.moment.locale(code);
  return code;
}

function loadPreferredLanguage() {
  if (settings.general.lang())
    return loadFromSettings();

  var deferred = m.deferred();
  window.navigator.globalization.getPreferredLanguage(
    language => deferred.resolve(language.value.split('-')[0]),
    () => deferred.resolve(defaultCode)
  );
  return deferred.promise
    .then(code => {
      settings.general.lang(code);
      return code;
    })
    .then(loadFile)
    .then(loadMomentLocale);
}

function getAvailableLanguages() {
  return m.request({
    url: 'i18n/refs.json',
    method: 'GET'
  }).then(data => { return data; }, error => {
    // same workaround for iOS as above
    if (error && error[0][0] === 'af')
      return error;
    else
      throw { error: 'Cannot load languages' };
  });
}

function loadFromSettings() {
  return loadFile(settings.general.lang()).then(loadMomentLocale);
}

module.exports = function(key) {
  var str = messages[key] || untranslated[key] || key;
  Array.prototype.slice.call(arguments, 1).forEach(function(arg) {
    str = str.replace('%s', arg);
  });
  return str;
};
module.exports.loadPreferredLanguage = loadPreferredLanguage;
module.exports.getAvailableLanguages = getAvailableLanguages;
module.exports.loadFromSettings = loadFromSettings;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2020 allen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var teams;
var pairings;
var ballots;
var selectOptions = [];

$(document).ready(function () {
    //Pull all data from server
    updateData().then(data => {
        let currentRound = 1;
        for (var a = 0; a < pairings.length; a++) {
            if (pairings[a].round > currentRound) {
                currentRound = pairings[a].round;
            }
        }
        $("#round").val(`Round ${currentRound}`);
        fillPairingSelect();
    });
});

$("#round").on("change", function () {
    fillPairingSelect();
});

$("#pairing").on("change", function () {
    fillBallotSelect();
});

$("#ballot").on("change", function () {
    fillBallot();
});

$("#unlockButton").on("click", function () {
    let ballotNumber = Number($("#ballot").val().substring(7));
    let unlockData = {"id":ballotNumber};
    $.ajax({
        url: "../api/ballots/unlock.php",
        method: "POST",
        data: unlockData,
        dataType: "json"
    }).then(response => {
        if (response.message === 0) {
            warningModal(`Ballot Unlocked.\nYou can edit the ballot <a href="${response.url}">here</a>.`);
        } else {
            alert(response.message);
        }
    });
});

function fillPairingSelect() {
    //determine which round's pairings should be listed
    let pairingOptionsHTML = [];
    let selectedRound = Number($("#round").val().substring(6, 7));

    //create option HTML
    for (var a = 0; a < pairings.length; a++) {
        if (pairings[a].round === selectedRound) {
            pairingOptionsHTML.push(`<option>${pairings[a].plaintiff} v. ${pairings[a].defense}</option>\n`);
        }
    }

    //fill the select with the options
    $("#pairing").empty();
    pairingOptionsHTML.forEach(function (option) {
        $("#pairing").append(option);
    });
    fillBallotSelect();
}

function fillBallotSelect() {
    //determine which pairing should have its ballots listed
    let ballotOptionsHTML = [];
    let plaintiff = Number($("#pairing").val().substring(0, 4));
    let defense = Number($("#pairing").val().substring(8, 13));
    let pairingId = 0;
    for (var a = 0; a < pairings.length; a++) {
        if (pairings[a].plaintiff === plaintiff && pairings[a].defense === defense) {
            pairingId = pairings[a].id;
        }
    }

    //create option HTML
    for (var a = 0; a < ballots.length; a++) {
        if (ballots[a].pairing === pairingId) {
            ballotOptionsHTML.push(`<option>Ballot ${ballots[a].id}</option>\n`);
        }
    }

    //put the options into the select
    $("#ballot").empty();
    ballotOptionsHTML.forEach(function (option) {
        $("#ballot").append(option);
    });

    //fill in ballot data from default ballot
    fillBallot();
}

function fillBallot() {
    let ballotNumber = Number($("#ballot").val().substring(7));
    let ballot;
    for (var a = 0; a < ballots.length; a++) {
        if (ballots[a].id === ballotNumber) {
            ballot = ballots[a];
        }
    }
    //put numbers in ballot
    $("#pOpen").html(ballot.pOpen);
    $("#dOpen").html(ballot.dOpen);
    $("#pDx1").html(ballot.pDx1);
    $("#pDx2").html(ballot.pDx2);
    $("#pDx3").html(ballot.pDx3);
    $("#pWDx1").html(ballot.pWDx1);
    $("#pWDx2").html(ballot.pWDx2);
    $("#pWDx3").html(ballot.pWDx3);
    $("#pWCx1").html(ballot.pWCx1);
    $("#pWCx2").html(ballot.pWCx2);
    $("#pWCx3").html(ballot.pWCx3);
    $("#pCx1").html(ballot.pCx1);
    $("#pCx2").html(ballot.pCx2);
    $("#pCx3").html(ballot.pCx3);
    $("#dDx1").html(ballot.dDx1);
    $("#dDx2").html(ballot.dDx2);
    $("#dDx3").html(ballot.dDx3);
    $("#dWDx1").html(ballot.dWDx1);
    $("#dWDx2").html(ballot.dWDx2);
    $("#dWDx3").html(ballot.dWDx3);
    $("#dWCx1").html(ballot.dWCx1);
    $("#dWCx2").html(ballot.dWCx2);
    $("#dWCx3").html(ballot.dWCx3);
    $("#dCx1").html(ballot.dCx1);
    $("#dCx2").html(ballot.dCx2);
    $("#dCx3").html(ballot.dCx3);
    $("#pClose").html(ballot.pClose);
    $("#dClose").html(ballot.dClose);

    //calculate point totals
    let plaintiffPoints = ballot.pOpen +
            ballot.pDx1 +
            ballot.pDx2 +
            ballot.pDx3 +
            ballot.pWDx1 +
            ballot.pWDx2 +
            ballot.pWDx3 +
            ballot.pWCx1 +
            ballot.pWCx2 +
            ballot.pWCx3 +
            ballot.pCx1 +
            ballot.pCx2 +
            ballot.pCx3 + ballot.pClose;
    let defensePoints = ballot.dOpen +
            ballot.dDx1 +
            ballot.dDx2 +
            ballot.dDx3 +
            ballot.dWDx1 +
            ballot.dWDx2 +
            ballot.dWDx3 +
            ballot.dWCx1 +
            ballot.dWCx2 +
            ballot.dWCx3 +
            ballot.dCx1 +
            ballot.dCx2 +
            ballot.dCx3 + ballot.dClose;

    //determine lock status string
    let lockString = " (";
    if (ballot.locked) {
        lockString += "locked)";
        $("#unlockButton").prop("disabled", false);
    } else {
        lockString += "unlocked)";
        $("#unlockButton").prop("disabled", true);
    }
    if ((plaintiffPoints - defensePoints) > 0) {
        $("#tabRoomPD").html("Plaintiff wins: +" + (plaintiffPoints - defensePoints) + lockString);
    } else if ((plaintiffPoints - defensePoints) < 0) {
        $("#tabRoomPD").html("Defense wins: +" + (defensePoints - plaintiffPoints) + lockString);
    } else {
        $("#tabRoomPD").html("Tie" + lockString);
    }
}

function warningModal(text) {
    $("#warningModalText").html(text);
    $("#warningModal").modal();
}

function updateData() {
    return new Promise(function (resolve, reject) {
        Promise.all([getTeams(), getPairings(), getBallots()]).then(data => {
            teams = data[0];
            pairings = data[1];
            ballots = data[2];
            resolve();
        });
    });
}

function getTeams() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/teams/getAll.php",
            dataType: "json"
        }).then(teams => {
            resolve(teams);
        });
    });

}

function getPairings() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/pairings/getAll.php",
            dataType: "json"
        }).then(pairings => {
            resolve(pairings);
        });
    });
}

function getBallots() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/ballots/getAll.php",
            dataType: "json"
        }).then(ballots => {
            resolve(ballots);
        });
    });
}
<commit_msg>Ballot display now doubles one-judge panel ballots.<commit_after>/*
 * Copyright (C) 2020 allen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var teams;
var pairings;
var ballots;
var selectOptions = [];

$(document).ready(function () {
    //Pull all data from server
    updateData().then(data => {
        let currentRound = 1;
        for (var a = 0; a < pairings.length; a++) {
            if (pairings[a].round > currentRound) {
                currentRound = pairings[a].round;
            }
        }
        $("#round").val(`Round ${currentRound}`);
        fillPairingSelect();
    });
});

$("#round").on("change", function () {
    fillPairingSelect();
});

$("#pairing").on("change", function () {
    fillBallotSelect();
});

$("#ballot").on("change", function () {
    fillBallot();
});

$("#unlockButton").on("click", function () {
    let ballotNumber = Number($("#ballot").val().substring(7));
    let unlockData = {"id": ballotNumber};
    $.ajax({
        url: "../api/ballots/unlock.php",
        method: "POST",
        data: unlockData,
        dataType: "json"
    }).then(response => {
        if (response.message === 0) {
            warningModal(`Ballot Unlocked.\nYou can edit the ballot <a href="${response.url}">here</a>.`);
        } else {
            alert(response.message);
        }
    });
});

function fillPairingSelect() {
    //determine which round's pairings should be listed
    let pairingOptionsHTML = [];
    let selectedRound = Number($("#round").val().substring(6, 7));

    //create option HTML
    for (var a = 0; a < pairings.length; a++) {
        if (pairings[a].round === selectedRound) {
            pairingOptionsHTML.push(`<option>${pairings[a].plaintiff} v. ${pairings[a].defense}</option>\n`);
        }
    }

    //fill the select with the options
    $("#pairing").empty();
    pairingOptionsHTML.forEach(function (option) {
        $("#pairing").append(option);
    });
    fillBallotSelect();
}

function fillBallotSelect() {
    //determine which pairing should have its ballots listed
    let ballotOptionsHTML = [];
    let plaintiff = Number($("#pairing").val().substring(0, 4));
    let defense = Number($("#pairing").val().substring(8, 13));
    let pairingId = 0;
    for (var a = 0; a < pairings.length; a++) {
        if (pairings[a].plaintiff === plaintiff && pairings[a].defense === defense) {
            pairingId = pairings[a].id;
        }
    }

    //create option HTML
    for (var a = 0; a < ballots.length; a++) {
        if (ballots[a].pairing === pairingId) {
            ballotOptionsHTML.push(`<option>Ballot ${ballots[a].id}</option>\n`);
        }
    }

    //put the options into the select
    $("#ballot").empty();
    ballotOptionsHTML.forEach(function (option) {
        $("#ballot").append(option);
    });

    //fill in ballot data from default ballot
    fillBallot();
}

function fillBallot() {
    let ballotNumber = Number($("#ballot").val().substring(7));
    let ballot;
    for (var a = 0; a < ballots.length; a++) {
        if (ballots[a].id === ballotNumber) {
            if(ballots[a].judge !== 0){//check that not a one-judge panel
                ballot = ballots[a];
            }else{//if a one-judge panel, then need to find the ballot acutally used by the panel
                for(var b = 0;b<ballots.length;b++){
                    if(a !== b && ballots[a].pairing === ballots[b].pairing){
                        ballot = ballots[b];
                    }
                }
            }

        }
    }
    //put numbers in ballot
    $("#pOpen").html(ballot.pOpen);
    $("#dOpen").html(ballot.dOpen);
    $("#pDx1").html(ballot.pDx1);
    $("#pDx2").html(ballot.pDx2);
    $("#pDx3").html(ballot.pDx3);
    $("#pWDx1").html(ballot.pWDx1);
    $("#pWDx2").html(ballot.pWDx2);
    $("#pWDx3").html(ballot.pWDx3);
    $("#pWCx1").html(ballot.pWCx1);
    $("#pWCx2").html(ballot.pWCx2);
    $("#pWCx3").html(ballot.pWCx3);
    $("#pCx1").html(ballot.pCx1);
    $("#pCx2").html(ballot.pCx2);
    $("#pCx3").html(ballot.pCx3);
    $("#dDx1").html(ballot.dDx1);
    $("#dDx2").html(ballot.dDx2);
    $("#dDx3").html(ballot.dDx3);
    $("#dWDx1").html(ballot.dWDx1);
    $("#dWDx2").html(ballot.dWDx2);
    $("#dWDx3").html(ballot.dWDx3);
    $("#dWCx1").html(ballot.dWCx1);
    $("#dWCx2").html(ballot.dWCx2);
    $("#dWCx3").html(ballot.dWCx3);
    $("#dCx1").html(ballot.dCx1);
    $("#dCx2").html(ballot.dCx2);
    $("#dCx3").html(ballot.dCx3);
    $("#pClose").html(ballot.pClose);
    $("#dClose").html(ballot.dClose);

    //calculate point totals
    let plaintiffPoints = ballot.pOpen +
            ballot.pDx1 +
            ballot.pDx2 +
            ballot.pDx3 +
            ballot.pWDx1 +
            ballot.pWDx2 +
            ballot.pWDx3 +
            ballot.pWCx1 +
            ballot.pWCx2 +
            ballot.pWCx3 +
            ballot.pCx1 +
            ballot.pCx2 +
            ballot.pCx3 + ballot.pClose;
    let defensePoints = ballot.dOpen +
            ballot.dDx1 +
            ballot.dDx2 +
            ballot.dDx3 +
            ballot.dWDx1 +
            ballot.dWDx2 +
            ballot.dWDx3 +
            ballot.dWCx1 +
            ballot.dWCx2 +
            ballot.dWCx3 +
            ballot.dCx1 +
            ballot.dCx2 +
            ballot.dCx3 + ballot.dClose;

    //determine lock status string
    let lockString = " (";
    if (ballot.locked) {
        lockString += "locked)";
        $("#unlockButton").prop("disabled", false);
    } else {
        lockString += "unlocked)";
        $("#unlockButton").prop("disabled", true);
    }
    if ((plaintiffPoints - defensePoints) > 0) {
        $("#tabRoomPD").html("Plaintiff wins: +" + (plaintiffPoints - defensePoints) + lockString);
    } else if ((plaintiffPoints - defensePoints) < 0) {
        $("#tabRoomPD").html("Defense wins: +" + (defensePoints - plaintiffPoints) + lockString);
    } else {
        $("#tabRoomPD").html("Tie" + lockString);
    }
}

function warningModal(text) {
    $("#warningModalText").html(text);
    $("#warningModal").modal();
}

function updateData() {
    return new Promise(function (resolve, reject) {
        Promise.all([getTeams(), getPairings(), getBallots()]).then(data => {
            teams = data[0];
            pairings = data[1];
            ballots = data[2];
            resolve();
        });
    });
}

function getTeams() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/teams/getAll.php",
            dataType: "json"
        }).then(teams => {
            resolve(teams);
        });
    });

}

function getPairings() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/pairings/getAll.php",
            dataType: "json"
        }).then(pairings => {
            resolve(pairings);
        });
    });
}

function getBallots() {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "../api/ballots/getAll.php",
            dataType: "json"
        }).then(ballots => {
            resolve(ballots);
        });
    });
}
<|endoftext|>


<commit_before>// bitbucket.js
// https://confluence.atlassian.com/bitbucket/manage-webhooks-735643732.html
// ========
module.exports = {
    parse: function (req, discordPayload) {
        var body = req.body;
        var baseLink = 'https://bitbucket.org/';

        if (typeof body.push !== undefined) { // push event
            for(var i = 0; i < body.push.changes.length; i++){
                var change = body.push.changes[i];
                var project = {
                    name: body.repository.name,
                    url: baseLink + body.repository.full_name,
                    branch: (change.old != null) ? change.old.name : change.new.name,
                    commits: change.commits
                };
                var user = {
                    name: body.actor.display_name,
                    icon_url: body.actor.links.avatar.href,
                    url: baseLink + body.actor.username
                }

                var commits = "";
                for (var i = 0; i < project.commits.length; i++) {
                    var commit = project.commits[i];
                    var message = (commit.message.length > 50) ? commit.message.substring(0, 47) + "..." : commit.message;
                    commits = commits + "[`" + commit.hash.substring(0, 7) + "`](" + commit.links.html.href + ") " + message + " - " + commit.author.user.display_name + "\n";
                }

                discordPayload.embeds.push({
                    title: "[" + project.name + ":" + project.branch + "] " + project.commits.length + " commit" + ((project.commits.length > 1) ? "s" : ""),
                    url: project.url,
                    author: user,
                    description: commits,
                    footer: {
                        text: "Powered by skyhook",
                        icon_url: ""
                    }
                });
            }
        }
        //TODO: support of the other webhook methods of BitBucket
    }
};
<commit_msg>Added BitBucket fork event<commit_after>// bitbucket.js
// https://confluence.atlassian.com/bitbucket/manage-webhooks-735643732.html
// ========
module.exports = {
    parse: function (req, discordPayload) {
        var body = req.body;
        var baseLink = 'https://bitbucket.org/';

        discordPayload.embeds = [];

        if (typeof body.push !== "undefined") { // push event
            for (var i = 0; i < body.push.changes.length; i++) {
                var change = body.push.changes[i];
                var project = {
                    name: body.repository.name,
                    url: baseLink + body.repository.full_name,
                    branch: (change.old != null) ? change.old.name : change.new.name,
                    commits: change.commits
                };
                var user = {
                    name: body.actor.display_name,
                    icon_url: body.actor.links.avatar.href,
                    url: baseLink + body.actor.username
                }

                var commits = "";
                for (var i = 0; i < project.commits.length; i++) {
                    var commit = project.commits[i];
                    var message = (commit.message.length > 50) ? commit.message.substring(0, 47) + "..." : commit.message;
                    commits = commits + "[`" + commit.hash.substring(0, 7) + "`](" + commit.links.html.href + ") " + message + " - " + commit.author.user.display_name + "\n";
                }

                discordPayload.embeds.push({
                    title: "[" + project.name + ":" + project.branch + "] " + project.commits.length + " commit" + ((project.commits.length > 1) ? "s" : ""),
                    url: project.url,
                    author: user,
                    description: commits,
                    footer: {
                        text: "Powered by skyhook",
                        icon_url: ""
                    }
                });
            }
        } else if (typeof body.fork !== "undefined") { // fork event
            var user = {
                name: body.actor.display_name,
                icon_url: body.actor.links.avatar.href,
                url: baseLink + body.actor.username
            }
            discordPayload.embeds.push({
                author: user,
                description: "Created a [`fork`](" + baseLink + body.fork.full_name + ") of [`" + body.repository.name + "`](" + baseLink + body.repository.full_name + ")",
                footer: {
                    text: "Powered by skyhook",
                    icon_url: ""
                }
            });
        }
        //TODO: support of the other webhook methods of BitBucket
    }
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import Xray from 'x-ray';
import { sanitizeTitle } from '../utils/helpers';
import * as Consts from '../consts';

const x = Xray();

export function Process() {
  return new Promise((resolve, reject) => {

    x(Consts.PIRATEBAY_URI, '#main-content tr', [{
      movie: x('', {
        name: '.detName a',
        metadata: x('', {
          size: 'td:nth-child(2) font',
          seeders: 'td:nth-child(3)',
          leechers: 'td:nth-child(4)',
        }),
        links: x('', {
          magnet: 'td:nth-child(2) > a@href',
        })
      })
    }])(function(err, data) {
      if (err) {
        reject(err);
      }

      const result = _.chain(data)
        .filter(function(e) {
          return _.get(e, 'movie.name', false);
        })
        .map(function(e) {
          e.movie.name = _.startCase(sanitizeTitle(e.movie.name));

          return e;
        })
        .value();

      resolve(result);
    });

  });
};
<commit_msg>Process movie quality<commit_after>import _ from 'lodash';
import Xray from 'x-ray';
import { sanitizeTitle, sanitizeSize, movieQuality } from '../utils/helpers';
import * as Consts from '../consts';

const x = Xray();

export function Process() {
  return new Promise((resolve, reject) => {

    x(Consts.PIRATEBAY_URI, '#main-content tr', [{
      movie: x('', {
        name: '.detName a',
        metadata: x('', {
          size: 'td:nth-child(2) font',
          seeders: 'td:nth-child(3)',
          leechers: 'td:nth-child(4)',
        }),
        links: x('', {
          magnet: 'td:nth-child(2) > a@href',
        })
      })
    }])(function(err, data) {
      if (err) {
        reject(err);
      }

      const result = _.chain(data)
        .filter(function(e) {
          return _.get(e, 'movie.name', false);
        })
        .map(function(e) {
          e.movie.metadata.type = movieQuality(e.movie.name);
          e.movie.name = _.startCase(sanitizeTitle(e.movie.name));
          e.movie.metadata.size = sanitizeSize(e.movie.metadata.size);

          return e;
        })
        .value();

      resolve(result);
    });

  });
};
<|endoftext|>


<commit_before>/*
  proxy-https-to-http.js: Basic example of proxying over HTTPS to a target HTTP server

  Copyright (c) Nodejitsu 2013

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var https = require('https'),
    http  = require('http'),
    util  = require('util'),
    path  = require('path'),
    fs    = require('fs'),
    //colors = require('colors'), //deprecated
    httpProxy = require('./lib/http-proxy'),
    fixturesDir = path.join(__dirname, 'test', 'fixtures');

//
// Create the target HTTP server
//
http.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' });
  'Location':'https://'+req.headers.host+req.url
     res.end('Redirecting to SSL\n');
  }).listen(80);

//
// Create the HTTPS proxy server listening on port 8000
//
httpProxy.createServer({
  target: {
    host: '192.168.0.3',
    port: 8892
  },
  ssl: {
    key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
    cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
  }
}).listen(443);

util.puts('https proxy server'+ ' started ' + 'on port ' + '443');
//util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9009 '.yellow);
<commit_msg> fixed a minor bug<commit_after>/*
  proxy-https-to-http.js: Basic example of proxying over HTTPS to a target HTTP server

  Copyright (c) Nodejitsu 2013

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var https = require('https'),
    http  = require('http'),
    util  = require('util'),
    path  = require('path'),
    fs    = require('fs'),
    //colors = require('colors'), //deprecated
    httpProxy = require('./lib/http-proxy'),
    fixturesDir = path.join(__dirname, 'test', 'fixtures');

//
// Create the target HTTP server
//
http.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' ,
                       'Location'    : 'https://'+req.headers.host+req.url});

     res.end('Redirecting to SSL\n');
  }).listen(80);

//
// Create the HTTPS proxy server listening on port 8000
//
httpProxy.createServer({
  target: {
    host: '192.168.0.3',
    port: 8892
  },
  ssl: {
    key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
    cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
  }
}).listen(443);

util.puts('https proxy server'+ ' started ' + 'on port ' + '443');
//util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9009 '.yellow);
<|endoftext|>


<commit_before>import { setSources } from "../src/lazyload.setSources";
import expectExtend from "./lib/expectExtend";
import getFakeInstance from "./lib/getFakeInstance";
import { getExtendedSettings } from "../src/lazyload.defaults";

expectExtend(expect);

var img, div, settings;

beforeEach(() => {
    div = document.createElement("div");
    div.appendChild((img = document.createElement("img")));
    settings = getExtendedSettings();
});

afterEach(() => {
    div.removeChild(img);
    img = null;
    div = null;
    settings = null;
});

describe("setSources for image", () => {
    let img1 = "1.gif";
    let img200 = "200.gif";
    let img400 = "400.gif";

    test("...with initially empty src and srcset", () => {
        img.setAttribute("data-src", img200);
        img.setAttribute("data-srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial values in src and srcset", () => {
        img.setAttribute("data-src", img200);
        img.setAttribute("data-srcset", img400);
        img.setAttribute("src", img1);
        img.setAttribute("srcset", img1);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });
    test("...with initial values in src and srcset and empty data-*", () => {
        img.setAttribute("data-src", "");
        img.setAttribute("data-srcset", "");
        img.setAttribute("src", img200);
        img.setAttribute("srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });
});

describe("setSources for iframe", () => {
    let iframe;
    let srcToLoad = "http://www.google.it";
    let preloadedSrc = srcToLoad + "/doodle";

    beforeEach(() => {
        iframe = document.createElement("iframe");
    });
    test("...with initially empty src", () => {
        iframe.setAttribute("data-src", srcToLoad);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", srcToLoad);
    });
    test("...with initial value in src", () => {
        iframe.setAttribute("data-src", srcToLoad);
        iframe.setAttribute("src", preloadedSrc);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", srcToLoad);
    });
    test("...with initial value in src and empty data-src", () => {
        iframe.setAttribute("data-src", "");
        iframe.setAttribute("src", preloadedSrc);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", preloadedSrc);
    });
});

describe("setSources for background image", () => {
    let element;
    let img100 = "100.gif";
    let img200 = "200.gif";

    beforeEach(() => {
        element = document.createElement("div");
    });

    test("...with initially empty style attribute", () => {
        element.setAttribute("data-src", img200);
        setSources(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
    test("...with initially present style attribute", () => {
        element.setAttribute("data-src", img100);
        element.style = {
            padding: "1px"
        };
        setSources(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img100})`);
    });
    test("...with initially present style and background", () => {
        element.setAttribute("data-src", img200);
        element.style = {
            padding: "1px",
            backgroundImage: "url(" + img100 + ")"
        };
        setSources(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
});

describe("setSources for video", () => {
    let source1, source2, video;
    let videoUrlMp4 = "foobar.mp4";
    let videoUrlAvi = "foobar.avi";
    let videoUrlWebm = "foobar.webm";

    beforeEach(() => {
        video = document.createElement("video");
        video.appendChild(document.createElement("source"));
        video.appendChild(document.createElement("source"));
    });

    test("...with initially empty src", () => {
        video.load = jest.fn();
        video.setAttribute("data-src", videoUrlAvi);
        setSources(video, settings, getFakeInstance());
        expect(video).toHaveAttributeValue("src", videoUrlAvi);
        expect(video.load).toHaveBeenCalled();
    });

    test("...with source elements", () => {
        video.load = jest.fn();
        video.setAttribute("data-src", videoUrlAvi);
        video.appendChild((source1 = document.createElement("source")));
        video.appendChild((source2 = document.createElement("source")));
        source1.setAttribute("data-src", videoUrlMp4);
        source2.setAttribute("data-src", videoUrlWebm);
        setSources(video, settings, getFakeInstance());
        expect(video).toHaveAttributeValue("src", videoUrlAvi);
        expect(source1).toHaveAttributeValue("src", videoUrlMp4);
        expect(source2).toHaveAttributeValue("src", videoUrlWebm);
        expect(video.load).toHaveBeenCalled();
    });
});

describe("setSources for picture", () => {
    let picture, source1, source2, img;
    let img200 = "200.gif";
    let img400 = "400.gif";
    let img1 = "1.gif";

    beforeEach(() => {
        picture = document.createElement("picture");
        picture.appendChild((source1 = document.createElement("source")));
        picture.appendChild((source2 = document.createElement("source")));
        picture.appendChild((img = document.createElement("img")));
    });

    test("...with initially empty srcset", () => {
        source1.setAttribute("data-srcset", img200);
        source2.setAttribute("data-srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial value in srcset", () => {
        source1.setAttribute("data-srcset", img200);
        source2.setAttribute("data-srcset", img400);
        source1.setAttribute("srcset", img1);
        source2.setAttribute("srcset", img1);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial value in srcset and empty data-srcset", () => {
        source1.setAttribute("data-srcset", "");
        source2.setAttribute("data-srcset", "");
        source1.setAttribute("srcset", img200);
        source2.setAttribute("srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });
});

/*
TO TEST:
- getSourceTags
- setSourcesBgImage with data_bg option
-
*/
<commit_msg>Extended and adapted setSourcesTests<commit_after>import {
    setSources,
    setBackgroundFromDataSrc,
    setBackgroundFromDataBg
} from "../src/lazyload.setSources";
import expectExtend from "./lib/expectExtend";
import getFakeInstance from "./lib/getFakeInstance";
import { getExtendedSettings } from "../src/lazyload.defaults";

expectExtend(expect);

var img, div, settings;

beforeEach(() => {
    div = document.createElement("div");
    div.appendChild((img = document.createElement("img")));
    settings = getExtendedSettings();
});

afterEach(() => {
    div.removeChild(img);
    img = null;
    div = null;
    settings = null;
});

describe("setSources for image", () => {
    let img1 = "1.gif";
    let img200 = "200.gif";
    let img400 = "400.gif";

    test("...with initially empty src and srcset", () => {
        img.setAttribute("data-src", img200);
        img.setAttribute("data-srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial values in src and srcset", () => {
        img.setAttribute("data-src", img200);
        img.setAttribute("data-srcset", img400);
        img.setAttribute("src", img1);
        img.setAttribute("srcset", img1);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });
    test("...with initial values in src and srcset and empty data-*", () => {
        img.setAttribute("data-src", "");
        img.setAttribute("data-srcset", "");
        img.setAttribute("src", img200);
        img.setAttribute("srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(img).toHaveAttributeValue("src", img200);
        expect(img).toHaveAttributeValue("srcset", img400);
    });
});

describe("setSources for iframe", () => {
    let iframe;
    let srcToLoad = "http://www.google.it";
    let preloadedSrc = srcToLoad + "/doodle";

    beforeEach(() => {
        iframe = document.createElement("iframe");
    });
    test("...with initially empty src", () => {
        iframe.setAttribute("data-src", srcToLoad);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", srcToLoad);
    });
    test("...with initial value in src", () => {
        iframe.setAttribute("data-src", srcToLoad);
        iframe.setAttribute("src", preloadedSrc);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", srcToLoad);
    });
    test("...with initial value in src and empty data-src", () => {
        iframe.setAttribute("data-src", "");
        iframe.setAttribute("src", preloadedSrc);
        setSources(iframe, settings, getFakeInstance());
        expect(iframe).toHaveAttributeValue("src", preloadedSrc);
    });
});

describe("setSources for background image with data-src", () => {
    let element;
    let img100 = "100.gif";
    let img200 = "200.gif";

    beforeEach(() => {
        element = document.createElement("div");
        element.llTempImage = document.createElement("img");
    });

    test("...with initially empty style attribute", () => {
        element.setAttribute("data-src", img200);
        setBackgroundFromDataSrc(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
    test("...with initially present style attribute", () => {
        element.setAttribute("data-src", img100);
        element.style = {
            padding: "1px"
        };
        setBackgroundFromDataSrc(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img100})`);
    });
    test("...with initially present style and background", () => {
        element.setAttribute("data-src", img200);
        element.style = {
            padding: "1px",
            backgroundImage: `url(${img100})`
        };
        setBackgroundFromDataSrc(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
});

describe("setSources for background image with data-bg", () => {
    let element;
    let img100 = "100.gif";
    let img200 = "200.gif";

    beforeEach(() => {
        element = document.createElement("div");
    });

    test("...with initially empty style attribute", () => {
        element.setAttribute("data-bg", `url(${img200})`);
        setBackgroundFromDataBg(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
    test("...with initially present style attribute", () => {
        element.setAttribute("data-bg", `url(${img100})`);
        element.style = {
            padding: "1px"
        };
        setBackgroundFromDataBg(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img100})`);
    });
    test("...with initially present style and background", () => {
        element.setAttribute("data-bg", `url(${img200})`);
        element.style = {
            padding: "1px",
            backgroundImage: `url(${img100})`
        };
        setBackgroundFromDataBg(element, settings, getFakeInstance());
        // Test cheating: bug in JsDOM doesn't return the url("") with quotes inside
        expect(element.style.backgroundImage).toBe(`url(${img200})`);
    });
});

describe("setSources for video", () => {
    let source1, source2, video;
    let videoUrlMp4 = "foobar.mp4";
    let videoUrlAvi = "foobar.avi";
    let videoUrlWebm = "foobar.webm";

    beforeEach(() => {
        video = document.createElement("video");
        video.appendChild(document.createElement("source"));
        video.appendChild(document.createElement("source"));
    });

    test("...with initially empty src", () => {
        video.load = jest.fn();
        video.setAttribute("data-src", videoUrlAvi);
        setSources(video, settings, getFakeInstance());
        expect(video).toHaveAttributeValue("src", videoUrlAvi);
        expect(video.load).toHaveBeenCalled();
    });

    test("...with source elements", () => {
        video.load = jest.fn();
        video.setAttribute("data-src", videoUrlAvi);
        video.appendChild((source1 = document.createElement("source")));
        video.appendChild((source2 = document.createElement("source")));
        source1.setAttribute("data-src", videoUrlMp4);
        source2.setAttribute("data-src", videoUrlWebm);
        setSources(video, settings, getFakeInstance());
        expect(video).toHaveAttributeValue("src", videoUrlAvi);
        expect(source1).toHaveAttributeValue("src", videoUrlMp4);
        expect(source2).toHaveAttributeValue("src", videoUrlWebm);
        expect(video.load).toHaveBeenCalled();
    });
});

describe("setSources for picture", () => {
    let picture, source1, source2, img;
    let img200 = "200.gif";
    let img400 = "400.gif";
    let img1 = "1.gif";

    beforeEach(() => {
        picture = document.createElement("picture");
        picture.appendChild((source1 = document.createElement("source")));
        picture.appendChild((source2 = document.createElement("source")));
        picture.appendChild((img = document.createElement("img")));
    });

    test("...with initially empty srcset", () => {
        source1.setAttribute("data-srcset", img200);
        source2.setAttribute("data-srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial value in srcset", () => {
        source1.setAttribute("data-srcset", img200);
        source2.setAttribute("data-srcset", img400);
        source1.setAttribute("srcset", img1);
        source2.setAttribute("srcset", img1);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });

    test("...with initial value in srcset and empty data-srcset", () => {
        source1.setAttribute("data-srcset", "");
        source2.setAttribute("data-srcset", "");
        source1.setAttribute("srcset", img200);
        source2.setAttribute("srcset", img400);
        setSources(img, settings, getFakeInstance());
        expect(source1).toHaveAttributeValue("srcset", img200);
        expect(source2).toHaveAttributeValue("srcset", img400);
    });
});

/*
TO TEST:
- getSourceTags
- setSourcesBgImage with data_bg option
-
*/
<|endoftext|>


<commit_before>import * as bpost from '../../src/lib/methods/postalPointOptions';

describe(`Method: sourcePostalPoint`, () => {
  it(`should return the source postal point name`, async () => {
    const request = await bpost.sourcePostalPoint(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`PP PRESS SHOP WAASLAND`);
  });
});

describe(`Method: destinationPostalPoint`, () => {
  it(`should return the destination postal point name`, async () => {
    const request = await bpost.destinationPostalPoint(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`POSTPUNT OCTA+ BRUGGE`);
  });
});

describe(`Method: destinationAsAddress`, () => {
  it(`should return the destination postal point formatted as an address`, async () => {
    const request = await bpost.destinationAsAddress(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`Pathoekeweg 74-78, 8000 Brugge`);
  });
});

describe(`Method: openingHours`, () => {
  it(`should fail if no day is passed`, async () => {
    try {
      await bpost.openingHours(global.BPOST_ID_POSTAL);
    } catch (e) {
      expect(e).toThrow();
    }
  });

  it(`should return the opening hours`, async () => {
    const request = await bpost.openingHours(global.BPOST_ID_POSTAL, `monday`);
    expect(request).toMatchSnapshot(`openingHours`);
  });
});

describe(`Method: destinationCoordinate`, () => {
  it(`should return destination as 2D coordinate`, async () => {
    const request = await bpost.destinationCoordinate(global.BPOST_ID_POSTAL);
    expect(request).toMatchSnapshot(`destinationCoordinate`);
  });
});
<commit_msg>:green_heart: Fix for previous commit<commit_after>import * as bpost from '../../src/lib/methods/postalPointOptions';

describe(`Method: sourcePostalPoint`, () => {
  it(`should return the source postal point name`, async () => {
    const request = await bpost.sourcePostalPoint(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`PP PRESS SHOP WAASLAND`);
  });
});

describe(`Method: destinationPostalPoint`, () => {
  it(`should return the destination postal point name`, async () => {
    const request = await bpost.destinationPostalPoint(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`POSTPUNT OCTA+ BRUGGE`);
  });
});

describe(`Method: destinationAsAddress`, () => {
  it(`should return the destination postal point formatted as an address`, async () => {
    const request = await bpost.destinationAsAddress(global.BPOST_ID_POSTAL);
    expect(request).toEqual(`PATHOEKEWEG 74-78, 8000 BRUGGE`);
  });
});

describe(`Method: openingHours`, () => {
  it(`should fail if no day is passed`, async () => {
    try {
      await bpost.openingHours(global.BPOST_ID_POSTAL);
    } catch (e) {
      expect(e).toThrow();
    }
  });

  it(`should return the opening hours`, async () => {
    const request = await bpost.openingHours(global.BPOST_ID_POSTAL, `monday`);
    expect(request).toMatchSnapshot(`openingHours`);
  });
});

describe(`Method: destinationCoordinate`, () => {
  it(`should return destination as 2D coordinate`, async () => {
    const request = await bpost.destinationCoordinate(global.BPOST_ID_POSTAL);
    expect(request).toMatchSnapshot(`destinationCoordinate`);
  });
});
<|endoftext|>