<commit_before>import React from "react"
import { connect } from "react-redux"
import { push } from 'react-router-redux';

import { calculateMinAmount, toT, displayBalance, caculateSourceAmount, caculateDestAmount } from "../../utils/converter"

import { PostExchangeWithKey } from "../Exchange"
import { ExchangeForm, TransactionConfig } from "../../components/Transaction"
import { SelectToken, TransactionLoading, Token } from "../CommonElements"

import { anyErrors } from "../../utils/validators"

import { openTokenModal, hideSelectToken } from "../../actions/utilActions"
import * as exchangeActions from "../../actions/exchangeActions"
import * as converters from "../../utils/converter"
import { randomForExchange } from "../../utils/random"
@connect((store) => {
  const ethereum = store.connection.ethereum
  const account = store.account
  const exchange = store.exchange
  const tokens = store.tokens.tokens
  return { account, ethereum, exchange, tokens }
})

export default class Exchange extends React.Component {

  openSourceToken = (e) => {
    this.props.dispatch(openTokenModal("source", this.props.exchange.sourceTokenSymbol))
  }

  openDesToken = (e) => {
    this.props.dispatch(openTokenModal("des", this.props.exchange.destTokenSymbol))
  }

  chooseToken = (symbol, address, type) => {
    this.props.dispatch(exchangeActions.selectTokenAsync(symbol, address, type, this.props.ethereum))
  }

  changeSourceAmount = (e) => {
    var value = e.target.value
    this.props.dispatch(exchangeActions.changeSourceAmout(value))
    this.props.dispatch(exchangeActions.changeDestAmout(caculateDestAmount(value, this.props.exchange.offeredRate, 6)))
  }

  changeDestAmount = (e) => {
    var value = e.target.value
    this.props.dispatch(exchangeActions.changeDestAmout(value))
    this.props.dispatch(exchangeActions.changeSourceAmout(caculateSourceAmount(value, this.props.exchange.offeredRate, 6)));
  }

  makeNewExchange = () => {
    this.props.dispatch(exchangeActions.makeNewExchange());
  }

  specifyGas = (event) => {
    var value = event.target.value
    this.props.dispatch(exchangeActions.specifyGas(value))
  }

  specifyGasPrice = (event) => {
    var value = event.target.value
    this.props.dispatch(exchangeActions.specifyGasPrice(value))
  }

  setAmount = () => {
    var tokenSymbol = this.props.exchange.sourceTokenSymbol
    var token = this.props.tokens[tokenSymbol]
    if (token) {
      var balanceBig = token.balance
      if (tokenSymbol === "ETH") {
        if (!balanceBig.greaterThanOrEqualTo(Math.pow(10, 17))) {
          return false
        }
        balanceBig = balanceBig.minus(Math.pow(10, 17))
      }
      var balance = balanceBig.div(Math.pow(10, token.decimal)).toString()
      this.props.dispatch(exchangeActions.changeSourceAmout(balance))
    }
  }

  render() {
    if (this.props.account.isStoreReady) {
      if (!!!this.props.account.account.address) {
        setTimeout(() => this.props.dispatch(push("/")), 1000)
        return (

        )
      }
    } else {
      return (

      )
    }

    var balance = ""
    var nameSource = ""
    var token = this.props.tokens[this.props.exchange.sourceTokenSymbol]
    if (token) {
      balance = displayBalance(token.balance, token.decimal, 8)
      nameSource = token.name
    }

    var balanceDest = ""
    var nameDest = ""
    var tokenDest = this.props.tokens[this.props.exchange.destTokenSymbol]
    if (tokenDest) {
      balanceDest = displayBalance(tokenDest.balance, tokenDest.decimal, 8)
      nameDest = tokenDest.name
    }

    var balanceInfo = {
      sourceTokenSymbol: this.props.exchange.sourceTokenSymbol,
      sourceAmount: balance,
      sourceTokenName: nameSource,
      destTokenSymbol: this.props.exchange.destTokenSymbol,
      destAmount: balanceDest,
      destTokenName: nameDest
    }

    var tokenSource = (
      <Token type="source"
        token={this.props.exchange.sourceTokenSymbol}
        onSelected={this.openSourceToken}
      />
    )
    var tokenDest = (
      <Token type="des"
        token={this.props.exchange.destTokenSymbol}
        onSelected={this.openDesToken}
      />
    )

    var errors = {
      selectSameToken: this.props.exchange.errors.selectSameToken,
      selectTokenToken: this.props.exchange.errors.selectTokenToken,
      sourceAmount: this.props.exchange.errors.sourceAmountError,
      tokenSource: ''
    }

    var input = {
      sourceAmount: {
        type: 'number',
        value: this.props.exchange.sourceAmount,
        onChange: this.changeSourceAmount
      },
      destAmount: {
        type: 'number',
        value: this.props.exchange.destAmount,
        onChange: this.changeDestAmount
      }
    }

    var selectTokenModal = (
      <SelectToken chooseToken={this.chooseToken} type="exchange" />
    )

    var exchangeRate = {
      sourceToken: this.props.exchange.sourceTokenSymbol,
      rate: toT(this.props.exchange.offeredRate, 6),
      destToken: this.props.exchange.destTokenSymbol,
      percent: "-"
    }
    var exchangeButton = (
      <PostExchangeWithKey />
    )
    var trasactionLoadingScreen = (
      <TransactionLoading tx={this.props.exchange.txHash}
        tempTx={this.props.exchange.tempTx}
        makeNewTransaction={this.makeNewExchange}
        type="exchange"
        balanceInfo={balanceInfo}
        broadcasting={this.props.exchange.broadcasting}
        broadcastingError={this.props.exchange.bcError}
      />
    )
    var gasConfig = (
      <TransactionConfig gas={this.props.exchange.gas}
        gasPrice={this.props.exchange.gasPrice}
        gasHandler={this.specifyGas}
        gasPriceHandler={this.specifyGasPrice}
        gasPriceError={this.props.exchange.errors.gasPriceError}
        gasError={this.props.exchange.errors.gasError}
        totalGas={converters.gweiToEth(this.props.exchange.gas * this.props.exchange.gasPrice)}
      />
    )

    return (
      <ExchangeForm step={this.props.exchange.step}
        tokenSource={tokenSource}
        tokenDest={tokenDest}
        selectTokenModal={selectTokenModal}
        exchangeRate={exchangeRate}
        gasConfig={gasConfig}
        exchangeButton={exchangeButton}
        trasactionLoadingScreen={trasactionLoadingScreen}
        errors={errors}
        input={input}
        balance={balance}
        sourceTokenSymbol={this.props.exchange.sourceTokenSymbol}
        setAmount={this.setAmount}
        isSelectToken = {this.props.exchange.isSelectToken}
      />
    )
  }
}
<commit_msg>fix exchange dest and source min amount<commit_after>import React from "react"
import { connect } from "react-redux"
import { push } from 'react-router-redux';

import { calculateMinAmount, toT, displayBalance, caculateSourceAmount, caculateDestAmount } from "../../utils/converter"

import { PostExchangeWithKey } from "../Exchange"
import { ExchangeForm, TransactionConfig } from "../../components/Transaction"
import { SelectToken, TransactionLoading, Token } from "../CommonElements"

import { anyErrors } from "../../utils/validators"

import { openTokenModal, hideSelectToken } from "../../actions/utilActions"
import * as exchangeActions from "../../actions/exchangeActions"
import * as converters from "../../utils/converter"
import { randomForExchange } from "../../utils/random"
@connect((store) => {
  const ethereum = store.connection.ethereum
  const account = store.account
  const exchange = store.exchange
  const tokens = store.tokens.tokens
  return { account, ethereum, exchange, tokens }
})

export default class Exchange extends React.Component {

  openSourceToken = (e) => {
    this.props.dispatch(openTokenModal("source", this.props.exchange.sourceTokenSymbol))
  }

  openDesToken = (e) => {
    this.props.dispatch(openTokenModal("des", this.props.exchange.destTokenSymbol))
  }

  chooseToken = (symbol, address, type) => {
    this.props.dispatch(exchangeActions.selectTokenAsync(symbol, address, type, this.props.ethereum))
  }

  changeSourceAmount = (e) => {
    var value = e.target.value
    if (value < 0) return
    this.props.dispatch(exchangeActions.changeSourceAmout(value))
    this.props.dispatch(exchangeActions.changeDestAmout(caculateDestAmount(value, this.props.exchange.offeredRate, 6)))
  }

  changeDestAmount = (e) => {
    var value = e.target.value
    if (value < 0) return
    this.props.dispatch(exchangeActions.changeDestAmout(value))
    this.props.dispatch(exchangeActions.changeSourceAmout(caculateSourceAmount(value, this.props.exchange.offeredRate, 6)));
  }

  makeNewExchange = () => {
    this.props.dispatch(exchangeActions.makeNewExchange());
  }

  specifyGas = (event) => {
    var value = event.target.value
    this.props.dispatch(exchangeActions.specifyGas(value))
  }

  specifyGasPrice = (event) => {
    var value = event.target.value
    this.props.dispatch(exchangeActions.specifyGasPrice(value))
  }

  setAmount = () => {
    var tokenSymbol = this.props.exchange.sourceTokenSymbol
    var token = this.props.tokens[tokenSymbol]
    if (token) {
      var balanceBig = token.balance
      if (tokenSymbol === "ETH") {
        if (!balanceBig.greaterThanOrEqualTo(Math.pow(10, 17))) {
          return false
        }
        balanceBig = balanceBig.minus(Math.pow(10, 17))
      }
      var balance = balanceBig.div(Math.pow(10, token.decimal)).toString()
      this.props.dispatch(exchangeActions.changeSourceAmout(balance))
    }
  }

  render() {
    if (this.props.account.isStoreReady) {
      if (!!!this.props.account.account.address) {
        setTimeout(() => this.props.dispatch(push("/")), 1000)
        return (

        )
      }
    } else {
      return (

      )
    }

    var balance = ""
    var nameSource = ""
    var token = this.props.tokens[this.props.exchange.sourceTokenSymbol]
    if (token) {
      balance = displayBalance(token.balance, token.decimal, 8)
      nameSource = token.name
    }

    var balanceDest = ""
    var nameDest = ""
    var tokenDest = this.props.tokens[this.props.exchange.destTokenSymbol]
    if (tokenDest) {
      balanceDest = displayBalance(tokenDest.balance, tokenDest.decimal, 8)
      nameDest = tokenDest.name
    }

    var balanceInfo = {
      sourceTokenSymbol: this.props.exchange.sourceTokenSymbol,
      sourceAmount: balance,
      sourceTokenName: nameSource,
      destTokenSymbol: this.props.exchange.destTokenSymbol,
      destAmount: balanceDest,
      destTokenName: nameDest
    }

    var tokenSource = (
      <Token type="source"
        token={this.props.exchange.sourceTokenSymbol}
        onSelected={this.openSourceToken}
      />
    )
    var tokenDest = (
      <Token type="des"
        token={this.props.exchange.destTokenSymbol}
        onSelected={this.openDesToken}
      />
    )

    var errors = {
      selectSameToken: this.props.exchange.errors.selectSameToken,
      selectTokenToken: this.props.exchange.errors.selectTokenToken,
      sourceAmount: this.props.exchange.errors.sourceAmountError,
      tokenSource: ''
    }

    var input = {
      sourceAmount: {
        type: 'number',
        value: this.props.exchange.sourceAmount,
        onChange: this.changeSourceAmount
      },
      destAmount: {
        type: 'number',
        value: this.props.exchange.destAmount,
        onChange: this.changeDestAmount
      }
    }

    var selectTokenModal = (
      <SelectToken chooseToken={this.chooseToken} type="exchange" />
    )

    var exchangeRate = {
      sourceToken: this.props.exchange.sourceTokenSymbol,
      rate: toT(this.props.exchange.offeredRate, 6),
      destToken: this.props.exchange.destTokenSymbol,
      percent: "-"
    }
    var exchangeButton = (
      <PostExchangeWithKey />
    )
    var trasactionLoadingScreen = (
      <TransactionLoading tx={this.props.exchange.txHash}
        tempTx={this.props.exchange.tempTx}
        makeNewTransaction={this.makeNewExchange}
        type="exchange"
        balanceInfo={balanceInfo}
        broadcasting={this.props.exchange.broadcasting}
        broadcastingError={this.props.exchange.bcError}
      />
    )
    var gasConfig = (
      <TransactionConfig gas={this.props.exchange.gas}
        gasPrice={this.props.exchange.gasPrice}
        gasHandler={this.specifyGas}
        gasPriceHandler={this.specifyGasPrice}
        gasPriceError={this.props.exchange.errors.gasPriceError}
        gasError={this.props.exchange.errors.gasError}
        totalGas={converters.gweiToEth(this.props.exchange.gas * this.props.exchange.gasPrice)}
      />
    )

    return (
      <ExchangeForm step={this.props.exchange.step}
        tokenSource={tokenSource}
        tokenDest={tokenDest}
        selectTokenModal={selectTokenModal}
        exchangeRate={exchangeRate}
        gasConfig={gasConfig}
        exchangeButton={exchangeButton}
        trasactionLoadingScreen={trasactionLoadingScreen}
        errors={errors}
        input={input}
        balance={balance}
        sourceTokenSymbol={this.props.exchange.sourceTokenSymbol}
        setAmount={this.setAmount}
        isSelectToken = {this.props.exchange.isSelectToken}
      />
    )
  }
}
<|endoftext|>


<commit_before>var $$ = React.createElement;

var stateHandlers = {

  handleSelectionChange: function(writerCtrl, sel) {
    var surface = writerCtrl.getSurface();
    if (surface.name !== "content") return;

    if (sel.isNull() || !sel.isPropertySelection()) return;

    var range = sel.getTextRange();
    var annotations = writerCtrl.doc.annotationIndex.get(sel.getPath(), range[0], range[1]);

    // Switch to a neutral state if no annotation matches have been found
    if (annotations.length === 0 && writerCtrl.state.contextId !== "editSubjectReference") {
      var prevContextId = writerCtrl.state.contextId;
      var nextContextId = "entities";

      if (prevContextId === "editSubjectReference" || prevContextId === "subjects") {
        nextContextId = "subjects";
      }

      writerCtrl.replaceState({
        contextId: nextContextId
      });
      return true;
    }
  }
};

module.exports = stateHandlers;<commit_msg>Check for reference handlers only when resetting to default state.<commit_after>var $$ = React.createElement;

var stateHandlers = {

  handleSelectionChange: function(writerCtrl, sel) {
    var surface = writerCtrl.getSurface();
    if (surface.name !== "content") return;

    if (sel.isNull() || !sel.isPropertySelection()) return;

    var range = sel.getTextRange();
    var annotations = writerCtrl.doc.annotationIndex.get(sel.getPath(), range[0], range[1], "reference");

    // Switch to a neutral state if no annotation matches have been found
    if (annotations.length === 0 && writerCtrl.state.contextId !== "editSubjectReference") {
      var prevContextId = writerCtrl.state.contextId;
      var nextContextId = "entities";

      if (prevContextId === "editSubjectReference" || prevContextId === "subjects") {
        nextContextId = "subjects";
      }

      writerCtrl.replaceState({
        contextId: nextContextId
      });
      return true;
    }
  }
};

module.exports = stateHandlers;<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport');

module.exports = function(app) {
	// User Routes
	var users = require('../../app/controllers/users.server.controller');
	var wgs = require('../../app/controllers/wgs.server.controller');

	// Setting up the users profile api
	app.route('/users/me').get(users.me);
	app.route('/users').put(users.update);
	app.route('/users/motd').put(users.updateMotd);
	app.route('/users/accounts').delete(users.removeOAuthProvider);

	// to delete user
	app.route('/user/delete').get(users.me);
	app.route('/user/delete').delete(users.deleteData);

	// Setting up the users password api
	app.route('/users/password').post(users.changePassword);
	app.route('/auth/forgot').post(users.forgot);
	app.route('/auth/reset/:token').get(users.validateResetToken);
	app.route('/auth/reset/:token').post(users.reset);

	// Setting up the users authentication api
	app.route('/auth/signup').post(users.signup);
	app.route('/auth/signin').post(users.signin);
	app.route('/auth/signout').get(users.signout);

	// Setting the facebook oauth routes
	app.route('/auth/facebook').get(passport.authenticate('facebook', {
		scope: ['email']
	}));
	app.route('/auth/facebook/callback').get(users.oauthCallback('facebook'));

	// Setting the twitter oauth routes
	app.route('/auth/twitter').get(passport.authenticate('twitter'));
	app.route('/auth/twitter/callback').get(users.oauthCallback('twitter'));

	// Setting the google oauth routes
	app.route('/auth/google').get(passport.authenticate('google', {
		scope: [
			'https://www.googleapis.com/auth/userinfo.profile',
			'https://www.googleapis.com/auth/userinfo.email'
		]
	}));
	app.route('/auth/google/callback').get(users.oauthCallback('google'));

	// Setting the linkedin oauth routes
	app.route('/auth/linkedin').get(passport.authenticate('linkedin'));
	app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin'));

	// Setting the github oauth routes
	app.route('/auth/github').get(passport.authenticate('github'));
	app.route('/auth/github/callback').get(users.oauthCallback('github'));

	// Finish by binding the user middleware
	app.param('userId', users.userByID);
};
<commit_msg>fix: user update<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport');

module.exports = function(app) {
	// User Routes
	var users = require('../../app/controllers/users.server.controller');
	var wgs = require('../../app/controllers/wgs.server.controller');

	// Setting up the users profile api
	app.route('/users/me').get(users.me);
	app.route('/users').put(users.update);
	app.route('/users/motd').put(users.updateMotd);
	app.route('/users/accounts').delete(users.removeOAuthProvider);
	app.route('/users/:userId').put(users.requiresLogin, users.update);

	// to delete user
	app.route('/user/delete').get(users.me);
	app.route('/user/delete').delete(users.deleteData);

	// Setting up the users password api
	app.route('/users/password').post(users.changePassword);
	app.route('/auth/forgot').post(users.forgot);
	app.route('/auth/reset/:token').get(users.validateResetToken);
	app.route('/auth/reset/:token').post(users.reset);

	// Setting up the users authentication api
	app.route('/auth/signup').post(users.signup);
	app.route('/auth/signin').post(users.signin);
	app.route('/auth/signout').get(users.signout);

	// Setting the facebook oauth routes
	app.route('/auth/facebook').get(passport.authenticate('facebook', {
		scope: ['email']
	}));
	app.route('/auth/facebook/callback').get(users.oauthCallback('facebook'));

	// Setting the twitter oauth routes
	app.route('/auth/twitter').get(passport.authenticate('twitter'));
	app.route('/auth/twitter/callback').get(users.oauthCallback('twitter'));

	// Setting the google oauth routes
	app.route('/auth/google').get(passport.authenticate('google', {
		scope: [
			'https://www.googleapis.com/auth/userinfo.profile',
			'https://www.googleapis.com/auth/userinfo.email'
		]
	}));
	app.route('/auth/google/callback').get(users.oauthCallback('google'));

	// Setting the linkedin oauth routes
	app.route('/auth/linkedin').get(passport.authenticate('linkedin'));
	app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin'));

	// Setting the github oauth routes
	app.route('/auth/github').get(passport.authenticate('github'));
	app.route('/auth/github/callback').get(users.oauthCallback('github'));

	// Finish by binding the user middleware
	app.param('userId', users.userByID);
};
<|endoftext|>


<commit_before>var express = require('express');
var connect = require('connect');
var db = require('monk')(process.env.OSSWEEPS_MONGO_HOST + '/data');

var app = express();
app.use(connect.bodyParser());

var DEBUG = true;

function errorHandler(err, req, res, next) {
  db.get('web_error').insert({
    dt: new Date(),
    stack: err.stack
  });
  res.status(500);
  res.render('error', { error: err });
}
app.use(errorHandler);

function isLegitimateEntry(hookBody) {
  if (hookBody.ref !== 'refs/heads/master' ||
      (DEBUG === true || hookBody.repository.private === true)) {
    return false;
  }
  return true;
}

function isLegitimateCommit(commit) {
  console.log(commit);
  if (commit.distinct === false ||
      commit.message.indexOf("Merge pull request") !== -1 ||
      commit.message.indexOf("Merge branch") !== -1) {
    return false;
  }
  return true;
}

function processEntry(hookBody) {
  if (!isLegitimateEntry(hookBody)) { return; }

  var users = {}
  var numCommits = 0;

  for (var i = 0; i < hookBody.commits.length; i++) {
    if (!isLegitimateCommit(hookBody.commits[i])) { continue; }
    var author = hookBody.commits[i].author;
    var username = author.username;
    users[username] = (users[username] || 0) + 1;
    numCommits++;
  }

  for (var user in users) {
    updateRepo(user, hookBody.repository, numCommits);
    updateUser(user, hookBody.repository, users[user]);
  }

  if (DEBUG) { writePayload(hookBody, users); }
}

function updateRepo(username, repo, numCommits) {
  db.get('repo').update(
    {_id: repo.id},
    {
      $set: {
        name: repo.name,
        url: repo.url
      },
      $inc: {entries: numCommits},
      $addToSet: {users: username}
    },
    {upsert: true}
  );
}

function updateUser(username, repo, numCommits) {
  var repoKey = 'repos.' + repo.id;
  db.get('user').update(
    {_id: username},
    {$inc: {repoKey: numCommits}},
    {upsert: true}
  );
}

function writePayload(hookBody, users) {
  db.get('payload').insert({
    dt: new Date(),
    payload: hookBody,
    users: users
  });
}

app.post('/', function(req, res) {
  try { processEntry(req.body); }
  catch (err) {
    db.get('error').insert({
      dt: new Date(),
      body: req.body,
      stack: err.stack
    });
  }
  res.end();
});

var server = app.listen(7777, function() {
  console.log('Hook server started on port %d', server.address().port);
});
<commit_msg>Here we go<commit_after>var express = require('express');
var connect = require('connect');
var db = require('monk')(process.env.OSSWEEPS_MONGO_HOST + '/data');

var app = express();
app.use(connect.bodyParser());

var DEBUG = true;

function errorHandler(err, req, res, next) {
  db.get('web_error').insert({
    dt: new Date(),
    stack: err.stack
  });
  res.status(500);
  res.render('error', { error: err });
}
app.use(errorHandler);

function isLegitimateEntry(hookBody) {
  if (hookBody.ref !== 'refs/heads/master' ||
      (DEBUG === false && hookBody.repository.private === true)) {
    return false;
  }
  return true;
}

function isLegitimateCommit(commit) {
  if (commit.distinct === false ||
      commit.message.indexOf("Merge pull request") !== -1 ||
      commit.message.indexOf("Merge branch") !== -1) {
    return false;
  }
  return true;
}

function processEntry(hookBody) {
  if (!isLegitimateEntry(hookBody)) { return; }

  var users = {}
  var numCommits = 0;

  for (var i = 0; i < hookBody.commits.length; i++) {
    if (!isLegitimateCommit(hookBody.commits[i])) { continue; }
    var author = hookBody.commits[i].author;
    var username = author.username;
    users[username] = (users[username] || 0) + 1;
    numCommits++;
  }

  for (var user in users) {
    updateRepo(user, hookBody.repository, numCommits);
    updateUser(user, hookBody.repository, users[user]);
  }

  if (DEBUG) { writePayload(hookBody, users); }
}

function updateRepo(username, repo, numCommits) {
  db.get('repo').update(
    {_id: repo.id},
    {
      $set: {
        name: repo.name,
        url: repo.url
      },
      $inc: {entries: numCommits},
      $addToSet: {users: username}
    },
    {upsert: true}
  );
}

function updateUser(username, repo, numCommits) {
  var repoKey = 'repos.' + repo.id;
  db.get('user').update(
    {_id: username},
    {$inc: {repoKey: numCommits}},
    {upsert: true}
  );
}

function writePayload(hookBody, users) {
  db.get('payload').insert({
    dt: new Date(),
    payload: hookBody,
    users: users
  });
}

app.post('/', function(req, res) {
  try { processEntry(req.body); }
  catch (err) {
    db.get('error').insert({
      dt: new Date(),
      body: req.body,
      stack: err.stack
    });
  }
  res.end();
});

var server = app.listen(7777, function() {
  console.log('Hook server started on port %d', server.address().port);
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

var assert = require('assert');
var ApplicationError = require('../lib/error');
var logger = require('../lib/logger');
var utils = require('../lib/utils');

module.exports = {

    /**
     * Error handler
     * @see http://www.joyent.com/developers/node/design/errors
     * @param err
     * @param req
     * @param res
     * @param next // without the next parameter, this is not recognized as a error handler
     */
    handler: function (err, req, res, next) {

        assert.ok(err instanceof Error);

        // Note: We want an ApplicationError to get all the properties we need for display and logging
        var error = err;
        var critical = false;
        if (!(err instanceof ApplicationError)) {
            error = new ApplicationError(err);
            // Since this is not an ApplicationError, it is an unexpected exception that we need to fix
            critical = true;
        }
        // Now we have an ApplicationError

        // Ensure a trace id that we can track in the browser
        if (typeof res.getLocale === 'function' && typeof res.__ === 'function' && typeof req.trace === 'undefined') {
            req.trace = utils.uuid();
        }

        // Log the error
        var entry = {
            module: 'middleware/error',
            method: 'handler',
            request: req,
            error: error
        };
        if (critical) {
            logger.critical(entry);
        } else if (entry.error && entry.error.status === 404) {
            logger.warn(entry); // not found
        } else {
            logger.error(entry);
        }

        if (typeof res.getLocale === 'function' && typeof res.__ === 'function') {

            /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */

            // Display error page for webapp
            res
                .status(error.status)
                .set({
                    'Cache-Control': 'no-cache',
                    'Content-Language': res.getLocale(),
                    'Content-Type': 'text/html; charset=utf-8'
                })
                .vary('Accept-Encoding') // See http://blog.maxcdn.com/accept-encoding-its-vary-important/
                .render('error', {
                    author: res.__('meta.author'),
                    description: error.message,
                    icon: res.__('error.icon'),
                    image: '', // <--------------------------------------------------------- TODO
                    keywords: res.__('meta.keywords'),
                    menu: [], // Do not display a menu to avoid any risks of errors fetching the menu, especially if accessing Github fails
                    results: [], // trick header into displaying robots noindex directive
                    trace: req.trace,
                    site_url: false, // trick header into not displaying a canonical link since we have a robots noindex directive
                    title: error.title
                });

            /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

        } else {

            // Return json error message for api server
            res
                .status(error.status)
                .json({ error: error });
        }
    }

};
<commit_msg>Added language to render method<commit_after>/**
 * Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

var assert = require('assert');
var ApplicationError = require('../lib/error');
var logger = require('../lib/logger');
var utils = require('../lib/utils');

module.exports = {

    /**
     * Error handler
     * @see http://www.joyent.com/developers/node/design/errors
     * @param err
     * @param req
     * @param res
     * @param next // without the next parameter, this is not recognized as a error handler
     */
    handler: function (err, req, res, next) {

        assert.ok(err instanceof Error);

        // Note: We want an ApplicationError to get all the properties we need for display and logging
        var error = err;
        var critical = false;
        if (!(err instanceof ApplicationError)) {
            error = new ApplicationError(err);
            // Since this is not an ApplicationError, it is an unexpected exception that we need to fix
            critical = true;
        }
        // Now we have an ApplicationError

        // Ensure a trace id that we can track in the browser
        if (typeof res.getLocale === 'function' && typeof res.__ === 'function' && typeof req.trace === 'undefined') {
            req.trace = utils.uuid();
        }

        // Log the error
        var entry = {
            module: 'middleware/error',
            method: 'handler',
            request: req,
            error: error
        };
        if (critical) {
            logger.critical(entry);
        } else if (entry.error && entry.error.status === 404) {
            logger.warn(entry); // not found
        } else {
            logger.error(entry);
        }

        if (typeof res.getLocale === 'function' && typeof res.__ === 'function') {

            /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */

            var language = res.getLocale();

            // Display error page for webapp
            res
                .status(error.status)
                .set({
                    'Cache-Control': 'no-cache',
                    'Content-Language': language,
                    'Content-Type': 'text/html; charset=utf-8'
                })
                .vary('Accept-Encoding') // See http://blog.maxcdn.com/accept-encoding-its-vary-important/
                .render('error', {
                    author: res.__('meta.author'),
                    description: error.message,
                    icon: res.__('error.icon'),
                    image: '', // <--------------------------------------------------------- TODO
                    keywords: res.__('meta.keywords'),
                    language: language,
                    menu: [], // Do not display a menu to avoid any risks of errors fetching the menu, especially if accessing Github fails
                    results: [], // trick header into displaying robots noindex directive
                    site_url: false, // trick header into not displaying a canonical link since we have a robots noindex directive
                    title: error.title,
                    trace: req.trace
                });

            /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

        } else {

            // Return json error message for api server
            res
                .status(error.status)
                .json({ error: error });
        }
    }

};
<|endoftext|>


<commit_before>describe('Exibicao da mensagem de boas-vindas', function(){
    beforeEach(function(){
        setFixtures('
');
        this.mensagem = $('#mensagem');
    });

    afterEach(function(){
        this.horas = [];
    });

    it("Deve exibir 'Bom-dia!' entre 5:00 e 11:59", function(){
        this.horas = ['05:00', '09:33', '10:22', '11:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Bom-dia!');
        }
    });

    it("Deve exibir 'Boa-tarde!' entre 12:00 e 17:59", function(){
        this.horas = ['15:00', '13:22', '17:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Boa-tarde!');
        }

    });

    it("Deve exibir 'Boa-noite!' entre 18:00 e 23:59", function(){
        this.horas = ['18:00', '20:22', '23:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Boa-noite!');
        }
    });

    it("Deve exibir, por padrão, a mensagem de acordo com a hora do cliente", function(){
        var data = new Date;
        data.setTime(data.getTime());
        var hora = data.getHours();

        saudacao();

        var texto = this.mensagem.text();
        if(hora < 5)
            expect(texto).toEqual('Dormir é para os fracos!');
        if(hora < 12)
            expect(texto).toEqual('Bom-dia!');
        else if(hora < 18)
            expect(texto).toEqual('Boa-tarde!');
        else
            expect(texto).toEqual('Boa-noite!');
    });
});

describe('Quando eu passar o soma para calculadora', function(){

    beforeEach(function(){
        setFixtures('
');
        this.mensagem = $('#mensagem');
    });

    afterEach(function(){
        this.primeiroValor = null;
        this.segundoValor = null;
    });

    it("passando 1 e 2! deve retornar 3", function(){
        var retorno = 0;
        this.primeiroValor = 1;
        this.segundoValor = 2;
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(3);
        expect('3').toEqual(this.mensagem.text())
    });

    it("passando valores vazio! deve retornar 0", function(){
        var retorno = 0;
        this.primeiroValor = '';
        this.segundoValor ='';
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(0);
        expect('0').toEqual(this.mensagem.text())
    });

    it("passando valores undefined! deve retornar 0", function(){
        var retorno = 0;
        retorno = objTeste.calculadora('soma');
        expect(retorno).toEqual(0);
        expect('0').toEqual(this.mensagem.text())
    });

    it("passando 1 e -2! deve retornar -1", function(){
        var retorno = -1;
        this.primeiroValor = 1;
        this.segundoValor =-2;
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(-1);
        expect('-1').toEqual(this.mensagem.text())
    });

});

describe("Quando eu chamar a calculadora", function(){

    beforeEach(function(){

    });

    afterEach(function(){
        this.primeiroValor = null;
        this.segundoValor = null;
    });

    it('Tem que passar uma vez pela soma!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'soma');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.soma).toHaveBeenCalled();
    });

    it('Tem que passar pela soma com os parametros 1 e 2!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'soma');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.soma).toHaveBeenCalledWith(this.primeiroValor,this.segundoValor);
    });

    it('Não deve passar pela subtração!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'subtracao');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.subtracao).not.toHaveBeenCalled();
    });
});

<commit_msg>Signed-off-by: joleques <joleques@gmail.com><commit_after>describe('Exibicao da mensagem de boas-vindas', function(){

    beforeEach(function(){
        setFixtures('
');
        this.mensagem = $('#mensagem');
    });

    afterEach(function(){
        this.horas = [];
    });

    it("Deve exibir 'Bom-dia!' entre 5:00 e 11:59", function(){
        this.horas = ['05:00', '09:33', '10:22', '11:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Bom-dia!');
        }
    });

    it("Deve exibir 'Boa-tarde!' entre 12:00 e 17:59", function(){
        this.horas = ['15:00', '13:22', '17:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Boa-tarde!');
        }

    });

    it("Deve exibir 'Boa-noite!' entre 18:00 e 23:59", function(){
        this.horas = ['18:00', '20:22', '23:59'];
        for(i in this.horas){
            saudacao(this.horas[i]);
            expect(this.mensagem.text()).toEqual('Boa-noite!');
        }
    });

    it("Deve exibir, por padrão, a mensagem de acordo com a hora do cliente", function(){
        var data = new Date;
        data.setTime(data.getTime());
        var hora = data.getHours();

        saudacao();

        var texto = this.mensagem.text();
        if(hora < 5)
            expect(texto).toEqual('Dormir é para os fracos!');
        if(hora < 12)
            expect(texto).toEqual('Bom-dia!');
        else if(hora < 18)
            expect(texto).toEqual('Boa-tarde!');
        else
            expect(texto).toEqual('Boa-noite!');
    });
});

describe('Quando eu passar o soma para calculadora', function(){

    beforeEach(function(){
        setFixtures('
');
        this.mensagem = $('#mensagem');
    });

    afterEach(function(){
        this.primeiroValor = null;
        this.segundoValor = null;
    });

    it("passando 1 e 2! deve retornar 3", function(){
        var retorno = 0;
        this.primeiroValor = 1;
        this.segundoValor = 2;
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(3);
        expect('3').toEqual(this.mensagem.text())
    });

    it("passando valores vazio! deve retornar 0", function(){
        var retorno = 0;
        this.primeiroValor = '';
        this.segundoValor ='';
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(0);
        expect('0').toEqual(this.mensagem.text())
    });

    it("passando valores undefined! deve retornar 0", function(){
        var retorno = 0;
        retorno = objTeste.calculadora('soma');
        expect(retorno).toEqual(0);
        expect('0').toEqual(this.mensagem.text())
    });

    it("passando 1 e -2! deve retornar -1", function(){
        var retorno = -1;
        this.primeiroValor = 1;
        this.segundoValor =-2;
        retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(retorno).toEqual(-1);
        expect('-1').toEqual(this.mensagem.text())
    });

});

describe("Quando eu chamar a calculadora", function(){

    beforeEach(function(){

    });

    afterEach(function(){
        this.primeiroValor = null;
        this.segundoValor = null;
    });

    it('Tem que passar uma vez pela soma!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'soma');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.soma).toHaveBeenCalled();
    });

    it('Tem que passar pela soma com os parametros 1 e 2!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'soma');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.soma).toHaveBeenCalledWith(this.primeiroValor,this.segundoValor);
    });

    it('Não deve passar pela subtração!', function(){
        this.primeiroValor = 1;
        this.segundoValor = 2;
        spyOn(objTeste, 'subtracao');
        objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
        expect(objTeste.subtracao).not.toHaveBeenCalled();
    });
});

<|endoftext|>


<commit_before>/**
 * asset function
 * @param asset
 * @param path
 * @param url
 * @returns {*}
 */
function asset(asset, path, url) {
  if (process.env.NODE_ENV === "production") {
    return "." + asset[path];
  }

  return asset[url];
}

module.exports = asset;
<commit_msg>updated asset utility to return undefined instead of string in case of undefined.<commit_after>/**
 * asset function
 * @param asset
 * @param path
 * @param url
 * @returns {*}
 */
function asset(asset, path, url) {
  if (process.env.NODE_ENV === "production") {
    if (asset[path] === undefined) {
      return undefined;
    }

    return "." + asset[path];
  }

  return asset[url];
}

module.exports = asset;
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

    grunt.initConfig({
        jshint: {
            options: JSON.parse(require('fs').readFileSync('.jshintrc')),
            all: ['**/*.js', '!node_modules/**/*']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-nsp-package');
    grunt.registerTask('hint', ['jshint']);
    grunt.registerTask('audit', ['validate-package']);
    grunt.registerTask('default', ['hint', 'audit']);
};
<commit_msg>exclude coverage directory from linting<commit_after>'use strict';

module.exports = function(grunt) {

    grunt.initConfig({
        jshint: {
            options: JSON.parse(require('fs').readFileSync('.jshintrc')),
            all: ['**/*.js', '!node_modules/**/*', '!coverage/**/*']
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-nsp-package');
    grunt.registerTask('hint', ['jshint']);
    grunt.registerTask('audit', ['validate-package']);
    grunt.registerTask('default', ['hint', 'audit']);
};
<|endoftext|>


<commit_before>const moment = require("moment");

exports.run = (client, guild) => {
    const embed = new client.methods.Embed()
        .setColor(0xF1C40F)
        .setTimestamp()
        .setTitle(`Greetings!`)
        .setDescription(`To the users of ${guild.name},`)
        .addField("Margarine's Message:", `Hello and thank you for inviting me to ${guild.name}! I am a somewhat helpful and lovely bot created using Komada, a Discord.js framework. To see how I will be able to assist you with, feel free to do m~help. I will send you a list of commands in which you can use. In addition, admins and mods of your server should check the guild configurations and set it as they please. Those commands and explanations are found in the help descriptions.
        \nIf you have any improvement ideas, found issues or bugs, or have any complaints, feel free to use my report command and let my creator know how to improve and make me better! However, if I am online, feel free to use me for fun and helpful commands!`)
        .addField("User notice!", `Currently, I have no way of storing permissions for user data based on the Discord's developer TOS. So, by using Margarine, users agree to have their info usable and manipulated for improving and usage of Margarine. Any data collected will be stored securely and safely and Margarine will not ask for any personal information such as a Discord password.`);

    if(guild.channels.exists("name", "general")) {
        Channel = guild.channels.find("name", "general");
    } else {
        Channel = guild.channels.find(c=> c.permissionsFor(guild.me).has("SEND_MESSAGES"));
    }

    if (!guild.available) { return; }

    console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] I have started working for ${guild.name}.`);
    client.user.setPresence({ game:  { name:` m~help  | Playing around with Butter on ${client.guilds.size} servers`, type: 0 } });
    client.configuration.insert(client, guild);
    return client.channels.get(Channel.id).send({embed});
};
<commit_msg>Update guildCreate.js<commit_after>const moment = require("moment");

exports.run = (client, guild) => {
    const embed = new client.methods.Embed()
        .setColor(0xF1C40F)
        .setTimestamp()
        .setTitle(`Greetings!`)
        .setDescription(`To the users of ${guild.name},`)
        .addField("Margarine's Message:", `Hello and thank you for inviting me to ${guild.name}! I am a somewhat helpful and lovely bot created using Komada, a Discord.js framework. To see how I will be able to assist you with, feel free to do m~help. I will send you a list of commands in which you can use. In addition, the admins and mods of your server should check the guild configurations and set it as they please. Those commands and explanations are found in the help descriptions.
        \nIf you have any improvement ideas, found issues or bugs, or have any complaints, feel free to use my report command and let my creator know how to improve and make me better! However, if I am online, feel free to use me for fun and helpful commands!`)
        .addField("User notice!", `Currently, I have no way of storing permissions for user data based on the Discord's developer TOS. So, by using Margarine, users agree to have their info usable and manipulated for improving and usage of Margarine. Any data collected will be stored securely and safely and Margarine will not ask for any personal information such as a Discord password.`);

    Channel = client.funcs.defaultChannel(client, Guild);

    if (!guild.available) { return; }

    console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] I have started working for ${guild.name}.`);
    client.user.setPresence({ game:  { name:` m~help  | Playing around with Butter on ${client.guilds.size} servers`, type: 0 } });
    client.configuration.insert(client, guild);
    return client.channels.get(Channel.id).send({embed});
};
<|endoftext|>


<commit_before>'use strict';

module.exports =

/*@ngInject*/
function GrammarActivitiesCreateCmsCtrl (
  $scope, _, GrammarActivity
) {
  $scope.grammarActivity = {};
  $scope.grammarActivity.question_set = [{}];

  function buildConcepts(set) {
    return _.chain(set)
      .map(function (s) {
        return [s.concept_level_0.$id, {
          quantity: s.number_of_questions,
          ruleNumber: s.concept_level_0.ruleNumber
        }];
      })
      .object()
      .value();
  }

  $scope.processGrammarActivityForm = function () {
    console.log('Processing ', $scope.grammarActivity);
    var ga = $scope.grammarActivity;
    var newGrammarActivity = {
      title: ga.title,
      description: ga.description,
      concepts: buildConcepts(ga.question_set)
    };

    console.log(newGrammarActivity);

    GrammarActivity.addToFB(newGrammarActivity).then(function () {
      console.log('Added', newGrammarActivity);
    });
  };
};
<commit_msg>Add standard, standard_level, theme to ga's<commit_after>'use strict';

module.exports =

/*@ngInject*/
function GrammarActivitiesCreateCmsCtrl (
  $scope, _, GrammarActivity, $state
) {
  $scope.grammarActivity = {};
  $scope.grammarActivity.question_set = [{}];

  function buildConcepts(set) {
    return _.chain(set)
      .map(function (s) {
        return [s.concept_level_0.$id, {
          quantity: s.number_of_questions,
          ruleNumber: s.concept_level_0.ruleNumber
        }];
      })
      .object()
      .value();
  }

  $scope.processGrammarActivityForm = function () {
    var ga = $scope.grammarActivity;
    var newGrammarActivity = {
      title: ga.title,
      description: ga.description,
      concepts: buildConcepts(ga.question_set),
      standard: ga.standard,
      standard_level: ga.standard_level,
      theme: ga.theme
    };

    GrammarActivity.addToFB(newGrammarActivity).then(function () {
      $state.go('cms-grammar-activities');
    });
  };
};
<|endoftext|>


<commit_before>cdb.admin.DEFAULT_LAYERS = [
  {
  url: 'https://{s}.maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?lg=eng&token=A7tBPacePg9Mj_zghvKt9Q&app_id=KuYppsdXZznpffJsKT24',
  subdomains: '1234',
  minZoom: 0,
  maxZoom: 21,
  name: 'Nokia Day',
  className: "nokia_day",
  attribution: "©2012 Nokia Terms of use"
}, {
  url: 'http://{s}.api.cartocdn.com/base-light/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Light',
  className: "light_cartodb",
  attribution: ""
}, {
  url: 'http://{s}.api.cartocdn.com/base-dark/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Dark',
  className: "dark_cartodb",
  attribution: ""
}, {
  url: 'http://{s}.api.cartocdn.com/base-antique/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Antique',
  className: "antique_cartodb",
  attribution: ""
}, {
  url: 'http://{s}.api.cartocdn.com/base-eco/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Eco',
  className: "eco_cartodb",
  attribution: ""
}, {
  url: 'http://{s}.api.cartocdn.com/base-flatblue/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Flat Blue',
  className: "flat_blue",
  attribution: ""
}, {
  url: 'http://{s}.api.cartocdn.com/base-midnight/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Midnight Commander',
  className: "midnight_cartodb",
  attribution: ""
}];
<commit_msg>using https urls for cartodb basemaps CDB-2711<commit_after>cdb.admin.DEFAULT_LAYERS = [
  {
  url: 'https://{s}.maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?lg=eng&token=A7tBPacePg9Mj_zghvKt9Q&app_id=KuYppsdXZznpffJsKT24',
  subdomains: '1234',
  minZoom: 0,
  maxZoom: 21,
  name: 'Nokia Day',
  className: "nokia_day",
  attribution: "©2012 Nokia Terms of use"
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-light/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Light',
  className: "light_cartodb",
  attribution: ""
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-dark/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Dark',
  className: "dark_cartodb",
  attribution: ""
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-antique/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Antique',
  className: "antique_cartodb",
  attribution: ""
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-eco/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Eco',
  className: "eco_cartodb",
  attribution: ""
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-flatblue/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Flat Blue',
  className: "flat_blue",
  attribution: ""
}, {
  url: 'https://cartocdn_{s}.global.ssl.fastly.net/base-midnight/{z}/{x}/{y}.png',
  minZoom: 0,
  maxZoom: 10,
  name: 'CartoDB Midnight Commander',
  className: "midnight_cartodb",
  attribution: ""
}];
<|endoftext|>


<commit_before>/*! piwik.js */
(function() {

    var b = ( 'http:' === document.location.protocol ? 'http' : 'https' ) + '://analytics.infop7.org/';

    $.getScript( b + 'piwik.js', function() {

        var piwikTracker = Piwik.getTracker(b + 'piwik.php', 1),
            p, navigation_time, page_load;

        // perfs
        if (   ( typeof ( p = window.performance ) === 'object' )
            && ( typeof (p = p.timing ) === 'object' ) ) {

            navigation_time = p.loadEventEnd - p.navigationStart;
            page_load       = p.loadEventEnd - p.responseEnd;

            if ( navigation_time > 0 || page_load > 0 ) {

                piwikTracker.setCustomVariable( 1, 'nt', '' + navigation_time, 'page' );
                piwikTracker.setCustomVariable( 2, 'pl', '' + page_load,       'page' );

            }

        }

        piwikTracker.trackPageView();
        piwikTracker.enableLinkTracking();

    });

})();
<commit_msg>comment removed from minified script.<commit_after>/* piwik.js */
(function() {

    var b = ( 'http:' === document.location.protocol ? 'http' : 'https' ) + '://analytics.infop7.org/';

    $.getScript( b + 'piwik.js', function() {

        var piwikTracker = Piwik.getTracker(b + 'piwik.php', 1),
            p, navigation_time, page_load;

        // perfs
        if (   ( typeof ( p = window.performance ) === 'object' )
            && ( typeof (p = p.timing ) === 'object' ) ) {

            navigation_time = p.loadEventEnd - p.navigationStart;
            page_load       = p.loadEventEnd - p.responseEnd;

            if ( navigation_time > 0 || page_load > 0 ) {

                piwikTracker.setCustomVariable( 1, 'nt', '' + navigation_time, 'page' );
                piwikTracker.setCustomVariable( 2, 'pl', '' + page_load,       'page' );

            }

        }

        piwikTracker.trackPageView();
        piwikTracker.enableLinkTracking();

    });

})();
<|endoftext|>


<commit_before>(() => {
  const COMPONENT_SELECTOR = '#thredded--container [data-time-ago]';
  const Thredded = window.Thredded;
  if ('timeago' in window) {
    const timeago = window.timeago;
    Thredded.onPageLoad(() => {
      const threddedContainer = document.querySelector('#thredded--container');
      if (!threddedContainer) return;
      timeago().render(
        document.querySelectorAll(COMPONENT_SELECTOR),
        threddedContainer.getAttribute('data-thredded-locale'));
    });
    document.addEventListener('turbolinks:before-cache', () => {
      timeago.cancel();
    });
  } else if ('jQuery' in window && 'timeago' in jQuery.fn) {
    const $ = window.jQuery;
    Thredded.onPageLoad(() => {
      const allowFutureWas = $.timeago.settings.allowFuture;
      $.timeago.settings.allowFuture = true;
      $(COMPONENT_SELECTOR).timeago();
      $.timeago.settings.allowFuture = allowFutureWas;
    });
  }
})();
<commit_msg>Fix time_stamps.es6 for locale names with a '-'<commit_after>(() => {
  const COMPONENT_SELECTOR = '#thredded--container [data-time-ago]';
  const Thredded = window.Thredded;
  if ('timeago' in window) {
    const timeago = window.timeago;
    Thredded.onPageLoad(() => {
      const threddedContainer = document.querySelector('#thredded--container');
      if (!threddedContainer) return;
      timeago().render(
        document.querySelectorAll(COMPONENT_SELECTOR),
        threddedContainer.getAttribute('data-thredded-locale').replace('-', '_'));
    });
    document.addEventListener('turbolinks:before-cache', () => {
      timeago.cancel();
    });
  } else if ('jQuery' in window && 'timeago' in jQuery.fn) {
    const $ = window.jQuery;
    Thredded.onPageLoad(() => {
      const allowFutureWas = $.timeago.settings.allowFuture;
      $.timeago.settings.allowFuture = true;
      $(COMPONENT_SELECTOR).timeago();
      $.timeago.settings.allowFuture = allowFutureWas;
    });
  }
})();
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var privateData = new WeakMap();

  function fire(name, target) {
    setTimeout(function() {
      var event = target.ownerDocument.createEvent('Event');
      event.initEvent(name, false, false);
      target.dispatchEvent(event);
    }, 0);
  }

  function handleData(el, data) {
    return data.then(function(html) {
      el.insertAdjacentHTML('afterend', html);
      el.parentNode.removeChild(el);
    }, function() {
      el.classList.add('is-error');
    });
  }

  var IncludeFragmentPrototype = Object.create(window.HTMLElement.prototype);

  Object.defineProperty(IncludeFragmentPrototype, 'src', {
    get: function() {
      var src = this.getAttribute('src');
      if (src) {
        var link = this.ownerDocument.createElement('a');
        link.href = src;
        return link.href;
      } else {
        return '';
      }
    },
    set: function(value) {
      this.setAttribute('src', value);
    }
  });

  function getData(el) {
    var src = el.src;
    var data = privateData.get(el);
    if (data && data.src === src) {
      return data.data;
    } else {
      if (src) {
        data = el.load();
      } else {
        data = Promise.reject(new Error('missing src'));
      }
      privateData.set(el, {src: src, data: data});
      return data;
    }
  }

  Object.defineProperty(IncludeFragmentPrototype, 'data', {
    get: function() {
      return getData(this);
    }
  });

  IncludeFragmentPrototype.attributeChangedCallback = function(attrName) {
    if (attrName === 'src') {
      // Reload data load cache.
      var data = getData(this);

      // Source changed after attached so replace element.
      if (this._attached) {
        handleData(this, data);
      }
    }
  };

  IncludeFragmentPrototype.createdCallback = function() {
    // Preload data cache
    getData(this)['catch'](function() {
      // Ignore `src missing` error on pre-load.
    });
  };

  IncludeFragmentPrototype.attachedCallback = function() {
    this._attached = true;
    if (this.src) {
      handleData(this, getData(this));
    }
  };

  IncludeFragmentPrototype.detachedCallback = function() {
    this._attached = false;
  };

  IncludeFragmentPrototype.request = function() {
    var src = this.src;
    if (!src) {
      throw new Error('missing src');
    }

    return new Request(src, {
      method: 'GET',
      credentials: 'same-origin',
      headers: {
        'Accept': 'text/html'
      }
    });
  };

  IncludeFragmentPrototype.load = function() {
    var self = this;

    return Promise.resolve().then(function() {
      var request = self.request();
      fire('loadstart', self);
      return self.fetch(request);
    }).then(function(response) {
      if (response.status !== 200) {
        throw new Error('Failed to load resource: ' +
          'the server responded with a status of ' + response.status);
      }

      var ct = response.headers.get('Content-Type');
      if (!ct || !ct.match(/^text\/html/)) {
        throw new Error('Failed to load resource: ' +
          'expected text/html but was ' + ct);
      }

      return response;
    }).then(function(response) {
      return response.text();
    }).then(function(data) {
      fire('load', self);
      fire('loadend', self);
      return data;
    }, function(error) {
      fire('error', self);
      fire('loadend', self);
      throw error;
    });
  };

  IncludeFragmentPrototype.fetch = function(request) {
    return fetch(request);
  };

  window.IncludeFragmentElement = document.registerElement('include-fragment', {
    prototype: IncludeFragmentPrototype
  });
})();
<commit_msg>Only replace when parentNode exists<commit_after>(function() {
  'use strict';

  var privateData = new WeakMap();

  function fire(name, target) {
    setTimeout(function() {
      var event = target.ownerDocument.createEvent('Event');
      event.initEvent(name, false, false);
      target.dispatchEvent(event);
    }, 0);
  }

  function handleData(el, data) {
    return data.then(function(html) {
      var parentNode = el.parentNode;
      if (parentNode) {
        el.insertAdjacentHTML('afterend', html);
        parentNode.removeChild(el);
      }
    }, function() {
      el.classList.add('is-error');
    });
  }

  var IncludeFragmentPrototype = Object.create(window.HTMLElement.prototype);

  Object.defineProperty(IncludeFragmentPrototype, 'src', {
    get: function() {
      var src = this.getAttribute('src');
      if (src) {
        var link = this.ownerDocument.createElement('a');
        link.href = src;
        return link.href;
      } else {
        return '';
      }
    },
    set: function(value) {
      this.setAttribute('src', value);
    }
  });

  function getData(el) {
    var src = el.src;
    var data = privateData.get(el);
    if (data && data.src === src) {
      return data.data;
    } else {
      if (src) {
        data = el.load();
      } else {
        data = Promise.reject(new Error('missing src'));
      }
      privateData.set(el, {src: src, data: data});
      return data;
    }
  }

  Object.defineProperty(IncludeFragmentPrototype, 'data', {
    get: function() {
      return getData(this);
    }
  });

  IncludeFragmentPrototype.attributeChangedCallback = function(attrName) {
    if (attrName === 'src') {
      // Reload data load cache.
      var data = getData(this);

      // Source changed after attached so replace element.
      if (this._attached) {
        handleData(this, data);
      }
    }
  };

  IncludeFragmentPrototype.createdCallback = function() {
    // Preload data cache
    getData(this)['catch'](function() {
      // Ignore `src missing` error on pre-load.
    });
  };

  IncludeFragmentPrototype.attachedCallback = function() {
    this._attached = true;
    if (this.src) {
      handleData(this, getData(this));
    }
  };

  IncludeFragmentPrototype.detachedCallback = function() {
    this._attached = false;
  };

  IncludeFragmentPrototype.request = function() {
    var src = this.src;
    if (!src) {
      throw new Error('missing src');
    }

    return new Request(src, {
      method: 'GET',
      credentials: 'same-origin',
      headers: {
        'Accept': 'text/html'
      }
    });
  };

  IncludeFragmentPrototype.load = function() {
    var self = this;

    return Promise.resolve().then(function() {
      var request = self.request();
      fire('loadstart', self);
      return self.fetch(request);
    }).then(function(response) {
      if (response.status !== 200) {
        throw new Error('Failed to load resource: ' +
          'the server responded with a status of ' + response.status);
      }

      var ct = response.headers.get('Content-Type');
      if (!ct || !ct.match(/^text\/html/)) {
        throw new Error('Failed to load resource: ' +
          'expected text/html but was ' + ct);
      }

      return response;
    }).then(function(response) {
      return response.text();
    }).then(function(data) {
      fire('load', self);
      fire('loadend', self);
      return data;
    }, function(error) {
      fire('error', self);
      fire('loadend', self);
      throw error;
    });
  };

  IncludeFragmentPrototype.fetch = function(request) {
    return fetch(request);
  };

  window.IncludeFragmentElement = document.registerElement('include-fragment', {
    prototype: IncludeFragmentPrototype
  });
})();
<|endoftext|>


<commit_before>const assert = require('chai').assert;
const webdriver = require('selenium-webdriver');
const {By, until} = webdriver;

/* To Use these functions the QA team needs to store their webElements in the below fashion,
and pass in the function

e.g. :

const elementOne = {
  locator : '.classname .otherClasses',
  locatorType: 'css'
}

const elementTwo = {
  locator : '//div[@name='test'],
  locatorType: 'xpath'
}
/*
-----------------------------------------------------------------
GET THE BY FUCNTIONS BASED UPON THE LOCATOR TYPE
-----------------------------------------------------------------
*/

//Function to get the By Type for for the locatorType
async function getByType(locatorType) {
  const locatorTypeLowerCase = locatorType.toLowerCase();
  if (locatorTypeLowerCase === 'css') {
    return By.css;
  } else if (locatorTypeLowerCase === 'id') {
    return By.id;
  } else if (locatorTypeLowerCase === 'xpath') {
    return By.xpath;
  } else if (locatorTypeLowerCase === 'classname') {
    return By.className;
  } else if (locatorTypeLowerCase === 'linktext') {
    return By.linkText;
  } else if (locatorTypeLowerCase === 'name') {
    return By.name;
  } else if (locatorTypeLowerCase === 'partialLinktext') {
    return By.partialLinkText;
  } else {
    return 'LocatorType is not supported, Please check the input!!';
  }
}

/*
-----------------------------------------------------------------
FUCNTIONS TO WAIT FOR THE ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

//Function to wait upto 60 secs by default to find the element, TIME can be customized by input
async function waitForElement(element, duration) {
  const byType = await getByType(element.locatorType);
  const time = duration === undefined ? 60000 : duration;
  try {
    await this.driver.wait(until.elementLocated(byType(element.locator)), time);
    return true;
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to Locate Element after ${time} milliseconds!!!
      Please find the error associated:  ${error}
      Hint:
      A: Please check your locator using Jquery once
      B: Please check the page load Time manually to wait properly for the Object
      `
    );
  }
}

//Function to wait upto 60 secs by default to find the elements, TIME can be customized by input
async function waitForElements(element, duration) {
  const byType = await getByType(element.locatorType);
  const time = duration === undefined ? 60000 : duration;
  try {
    await this.driver.wait(until.elementsLocated(byType(element.locator)), time);
    return true;
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to Locate Elements after ${time} milliseconds!!!
      Please find the error associated:  ${error}
      Hint:
      A: Please check your locator using Jquery once
      B: Please check the page load Time manually to wait properly for the Object
      `
    );
  }
}

/*
-----------------------------------------------------------------
FUCNTIONS TO FIND ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

/* Function to find the elements based upon the locator and locatorType
This can be used to check whether the elements are present in a page or not by catching the length */
async function findElements(elements) {
  await waitForElements.call(this, elements);
  const byType = await getByType(elements.locatorType);
  const currentElements = await this.driver.findElements(byType(elements.locator));
  return currentElements;
}

// Function to find the element based upon the locator and locatorType
async function findElement(element) {
  const isElementFound = await waitForElement.call(this, element);
  const byType = await getByType(element.locatorType);
  if (isElementFound) {
    const ele = await this.driver.findElement(byType(element.locator));
    return ele;
  }else {
    throw Error ('Element is not found, something happened after waiting for element, Please check!')
  }
}

/* How to use the below shadow root Fucntion
https://github.com/britishgas-engineering/ya-done/wiki/How-to-Use-the-Shadow-Root-Functions
*/
/*
-----------------------------------------------------------------
FUCNTIONS TO FIND SHADOW ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

/* Function to get innerText of elements inside shadow root */
async function getInnerTextOfShadowRootElement(shadowHostElement, shadowRootElement) {
  const shadowHost = await findElement.call(this, shadowHostElement);
  const shadowRoot = await this.driver.executeScript("return arguments[0].shadowRoot", shadowHost);
  const byType = await getByType(shadowRootElement.locatorType);
  const shadowRootElementFromWeb = await shadowRoot.findElement(byType(shadowRootElement.locator));
  return await this.driver.executeScript("return arguments[0].innerText;", shadowRootElementFromWeb);
}

async function clickShadowRootElement(shadowHostElement, shadowRootElement){
  const shadowHost = await findElement.call(this, shadowHostElement);
  const shadowRoot = await this.driver.executeScript("return arguments[0].shadowRoot", shadowHost);
  const byType = await getByType(shadowRootElement.locatorType);
  const shadowRootElementFromWeb = await shadowRoot.findElement(byType(shadowRootElement.locator));
  await this.driver.executeScript("arguments[0].click();", shadowRootElementFromWeb);
}

async function clickShadowRootElementByCssSelector(shadowHostSelector, shadowELementSelector) {
  const clickOperation =
  'document.querySelector(`'+shadowHostSelector.locator+'`).shadowRoot.querySelector(`'+shadowELementSelector.locator+'`).click();'
  await this.driver.executeScript(clickOperation);
}

async function getInnerTextShadowRootElementByCssSelector(shadowHostSelector, shadowELementSelector) {
  const innerTextOperation =
  'return document.querySelector(`'+shadowHostSelector.locator+'`).shadowRoot.querySelector(`'+shadowELementSelector.locator+'`).innerText;'
  return await this.driver.executeScript(innerTextOperation);
}

/* Function to perform Jquery Action */
export async function performJqueryAction(action) {
  try {
    await this.driver.executeScript(action);
    await this.driver.sleep(200);
  } catch (error) {
    assert.ok(false,
      `--> Error Description: Unable to Perfomr Action the element${error}`
    );
  }
}
/*
-----------------------------------------------------------------
FUCNTIONS TO CLICK ELEMENT, ENTER VALUE AND SELECT FROM DROPDOWN
-----------------------------------------------------------------
*/

//Function to Click any element and sleeping or 500ms for sync
async function clickElement(element) {
  const ele = await findElement.call(this, element);
  ele.click();
  await this.driver.sleep(500);
}

//Function to enter Value
async function enterValue(element, value) {
  const ele = await findElement.call(this, element);
  try {
    ele.sendKeys(value);
    await this.driver.sleep(300);
  } catch (error) {
    assert.ok(false,
      `--> Error Description: Unable to enter the Value${error}`
    );
  }
}

//Function to select Value from drop Down --> only for select type with css
async function dropdownSelectByVisibleText(element, visibleText) {
  const ele = {
    locator: `${element.locator}>option[value='${visibleText}']`,
    locatorType: element.locatorType
  };
  await clickElement.call(this, ele);
}

/*
-----------------------------------------------------------------
FUCNTIONS TO GET ELEMENT TEXT, ATTRIBUTE AND CURRENT URL
-----------------------------------------------------------------
*/

//Function to get the Text of an element, syncing for 200ms before getting the text
async function getTextOfElement(element) {
    const ele = await findElement.call(this, element);
    await this.driver.sleep(200);
    const elementText = await ele.getText();
    return elementText;
}

//Function to get any attribute for any element
async function getAttribute(element, attributeName) {
  const ele = await findElement.call(this, element);
  try {
    return ele.getAttribute(attributeName);
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to get the "${attributeName}" attribute of the element
      Selenium Error ::: ${error}
      `
    );
  }
}

//Function to get CurrentURL
async function getCurrentUrl() {
  try {
    return this.driver.getCurrentUrl();
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to get the current URL, ${error}`
    );
  }
}

/*
-----------------------------------------------------------------
DRIVER SLEEP FUNCTIONS
-----------------------------------------------------------------
*/

//Function to wait for one second
async function waitOneSec() {
  await this.driver.sleep(1000);
}

//Function to sleep for short time for loading the page 3 seconds is default value
async function waitForPageLoad(duration) {
  const time = duration === undefined ? 3000 : duration;
  await this.driver.sleep(time);
}

/*
-----------------------------------------------------------------
FUCNTIONS TO CHECK ELEMENTS ARE VISIBLE AND SCROLLING BY JQUERY
-----------------------------------------------------------------
*/

//Function to scroll to make the Object visible
async function scrollInto(element) {
  const ele = await findElement.call(this, element);
  try {
    await this.driver.executeScript('arguments[0].scrollIntoView(true);', ele);
    await this.driver.sleep(1000);
  } catch (error) {
    assert.ok(false,
      `Facing error while scrolling down using Jquery, please check in console once!!`
    );
  }
}

//Function to check Element is present or not
async function isElementPresent(element) {
  const byType = await getByType(element.locatorType);
  const elements = await this.driver.findElements(byType(element.locator));
  const result = (elements.length === 1) || (elements.length > 1);
  return result;
}

//Function to check if element is visible
async function isElementVisible(element) {
  try {
    const ele = await findElement.call(this, element);
    return await ele.isDisplayed();
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Element is not Visible: ${error}`);
  }

}

module.exports = {
  getByType: getByType,
  findElement: findElement,
  waitForElement: waitForElement,
  waitForElements: waitForElements,
  getTextOfElement: getTextOfElement,
  getAttribute: getAttribute,
  clickElement: clickElement,
  getCurrentUrl: getCurrentUrl,
  findElements: findElements,
  waitForPageLoad: waitForPageLoad,
  enterValue: enterValue,
  scrollInto: scrollInto,
  waitOneSec: waitOneSec,
  isElementPresent: isElementPresent,
  dropdownSelectByVisibleText: dropdownSelectByVisibleText,
  isElementVisible: isElementVisible,
  clickShadowRootElement: clickShadowRootElement,
  getInnerTextOfShadowRootElement: getInnerTextOfShadowRootElement,
  clickShadowRootElementByCssSelector: clickShadowRootElementByCssSelector,
  getInnerTextShadowRootElementByCssSelector: getInnerTextShadowRootElementByCssSelector,
  performJqueryAction: performJqueryAction
};<commit_msg>removing export<commit_after>const assert = require('chai').assert;
const webdriver = require('selenium-webdriver');
const {By, until} = webdriver;

/* To Use these functions the QA team needs to store their webElements in the below fashion,
and pass in the function

e.g. :

const elementOne = {
  locator : '.classname .otherClasses',
  locatorType: 'css'
}

const elementTwo = {
  locator : '//div[@name='test'],
  locatorType: 'xpath'
}
/*
-----------------------------------------------------------------
GET THE BY FUCNTIONS BASED UPON THE LOCATOR TYPE
-----------------------------------------------------------------
*/

//Function to get the By Type for for the locatorType
async function getByType(locatorType) {
  const locatorTypeLowerCase = locatorType.toLowerCase();
  if (locatorTypeLowerCase === 'css') {
    return By.css;
  } else if (locatorTypeLowerCase === 'id') {
    return By.id;
  } else if (locatorTypeLowerCase === 'xpath') {
    return By.xpath;
  } else if (locatorTypeLowerCase === 'classname') {
    return By.className;
  } else if (locatorTypeLowerCase === 'linktext') {
    return By.linkText;
  } else if (locatorTypeLowerCase === 'name') {
    return By.name;
  } else if (locatorTypeLowerCase === 'partialLinktext') {
    return By.partialLinkText;
  } else {
    return 'LocatorType is not supported, Please check the input!!';
  }
}

/*
-----------------------------------------------------------------
FUCNTIONS TO WAIT FOR THE ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

//Function to wait upto 60 secs by default to find the element, TIME can be customized by input
async function waitForElement(element, duration) {
  const byType = await getByType(element.locatorType);
  const time = duration === undefined ? 60000 : duration;
  try {
    await this.driver.wait(until.elementLocated(byType(element.locator)), time);
    return true;
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to Locate Element after ${time} milliseconds!!!
      Please find the error associated:  ${error}
      Hint:
      A: Please check your locator using Jquery once
      B: Please check the page load Time manually to wait properly for the Object
      `
    );
  }
}

//Function to wait upto 60 secs by default to find the elements, TIME can be customized by input
async function waitForElements(element, duration) {
  const byType = await getByType(element.locatorType);
  const time = duration === undefined ? 60000 : duration;
  try {
    await this.driver.wait(until.elementsLocated(byType(element.locator)), time);
    return true;
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to Locate Elements after ${time} milliseconds!!!
      Please find the error associated:  ${error}
      Hint:
      A: Please check your locator using Jquery once
      B: Please check the page load Time manually to wait properly for the Object
      `
    );
  }
}

/*
-----------------------------------------------------------------
FUCNTIONS TO FIND ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

/* Function to find the elements based upon the locator and locatorType
This can be used to check whether the elements are present in a page or not by catching the length */
async function findElements(elements) {
  await waitForElements.call(this, elements);
  const byType = await getByType(elements.locatorType);
  const currentElements = await this.driver.findElements(byType(elements.locator));
  return currentElements;
}

// Function to find the element based upon the locator and locatorType
async function findElement(element) {
  const isElementFound = await waitForElement.call(this, element);
  const byType = await getByType(element.locatorType);
  if (isElementFound) {
    const ele = await this.driver.findElement(byType(element.locator));
    return ele;
  }else {
    throw Error ('Element is not found, something happened after waiting for element, Please check!')
  }
}

/* How to use the below shadow root Fucntion
https://github.com/britishgas-engineering/ya-done/wiki/How-to-Use-the-Shadow-Root-Functions
*/
/*
-----------------------------------------------------------------
FUCNTIONS TO FIND SHADOW ELEMENT OR ELEMENTS
-----------------------------------------------------------------
*/

/* Function to get innerText of elements inside shadow root */
async function getInnerTextOfShadowRootElement(shadowHostElement, shadowRootElement) {
  const shadowHost = await findElement.call(this, shadowHostElement);
  const shadowRoot = await this.driver.executeScript("return arguments[0].shadowRoot", shadowHost);
  const byType = await getByType(shadowRootElement.locatorType);
  const shadowRootElementFromWeb = await shadowRoot.findElement(byType(shadowRootElement.locator));
  return await this.driver.executeScript("return arguments[0].innerText;", shadowRootElementFromWeb);
}

async function clickShadowRootElement(shadowHostElement, shadowRootElement){
  const shadowHost = await findElement.call(this, shadowHostElement);
  const shadowRoot = await this.driver.executeScript("return arguments[0].shadowRoot", shadowHost);
  const byType = await getByType(shadowRootElement.locatorType);
  const shadowRootElementFromWeb = await shadowRoot.findElement(byType(shadowRootElement.locator));
  await this.driver.executeScript("arguments[0].click();", shadowRootElementFromWeb);
}

async function clickShadowRootElementByCssSelector(shadowHostSelector, shadowELementSelector) {
  const clickOperation =
  'document.querySelector(`'+shadowHostSelector.locator+'`).shadowRoot.querySelector(`'+shadowELementSelector.locator+'`).click();'
  await this.driver.executeScript(clickOperation);
}

async function getInnerTextShadowRootElementByCssSelector(shadowHostSelector, shadowELementSelector) {
  const innerTextOperation =
  'return document.querySelector(`'+shadowHostSelector.locator+'`).shadowRoot.querySelector(`'+shadowELementSelector.locator+'`).innerText;'
  return await this.driver.executeScript(innerTextOperation);
}

/* Function to perform Jquery Action */
async function performJqueryAction(action) {
  try {
    await this.driver.executeScript(action);
    await this.driver.sleep(200);
  } catch (error) {
    assert.ok(false,
      `--> Error Description: Unable to Perfomr Action the element${error}`
    );
  }
}
/*
-----------------------------------------------------------------
FUCNTIONS TO CLICK ELEMENT, ENTER VALUE AND SELECT FROM DROPDOWN
-----------------------------------------------------------------
*/

//Function to Click any element and sleeping or 500ms for sync
async function clickElement(element) {
  const ele = await findElement.call(this, element);
  ele.click();
  await this.driver.sleep(500);
}

//Function to enter Value
async function enterValue(element, value) {
  const ele = await findElement.call(this, element);
  try {
    ele.sendKeys(value);
    await this.driver.sleep(300);
  } catch (error) {
    assert.ok(false,
      `--> Error Description: Unable to enter the Value${error}`
    );
  }
}

//Function to select Value from drop Down --> only for select type with css
async function dropdownSelectByVisibleText(element, visibleText) {
  const ele = {
    locator: `${element.locator}>option[value='${visibleText}']`,
    locatorType: element.locatorType
  };
  await clickElement.call(this, ele);
}

/*
-----------------------------------------------------------------
FUCNTIONS TO GET ELEMENT TEXT, ATTRIBUTE AND CURRENT URL
-----------------------------------------------------------------
*/

//Function to get the Text of an element, syncing for 200ms before getting the text
async function getTextOfElement(element) {
    const ele = await findElement.call(this, element);
    await this.driver.sleep(200);
    const elementText = await ele.getText();
    return elementText;
}

//Function to get any attribute for any element
async function getAttribute(element, attributeName) {
  const ele = await findElement.call(this, element);
  try {
    return ele.getAttribute(attributeName);
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to get the "${attributeName}" attribute of the element
      Selenium Error ::: ${error}
      `
    );
  }
}

//Function to get CurrentURL
async function getCurrentUrl() {
  try {
    return this.driver.getCurrentUrl();
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Unable to get the current URL, ${error}`
    );
  }
}

/*
-----------------------------------------------------------------
DRIVER SLEEP FUNCTIONS
-----------------------------------------------------------------
*/

//Function to wait for one second
async function waitOneSec() {
  await this.driver.sleep(1000);
}

//Function to sleep for short time for loading the page 3 seconds is default value
async function waitForPageLoad(duration) {
  const time = duration === undefined ? 3000 : duration;
  await this.driver.sleep(time);
}

/*
-----------------------------------------------------------------
FUCNTIONS TO CHECK ELEMENTS ARE VISIBLE AND SCROLLING BY JQUERY
-----------------------------------------------------------------
*/

//Function to scroll to make the Object visible
async function scrollInto(element) {
  const ele = await findElement.call(this, element);
  try {
    await this.driver.executeScript('arguments[0].scrollIntoView(true);', ele);
    await this.driver.sleep(1000);
  } catch (error) {
    assert.ok(false,
      `Facing error while scrolling down using Jquery, please check in console once!!`
    );
  }
}

//Function to check Element is present or not
async function isElementPresent(element) {
  const byType = await getByType(element.locatorType);
  const elements = await this.driver.findElements(byType(element.locator));
  const result = (elements.length === 1) || (elements.length > 1);
  return result;
}

//Function to check if element is visible
async function isElementVisible(element) {
  try {
    const ele = await findElement.call(this, element);
    return await ele.isDisplayed();
  } catch (error) {
    return assert.ok(false,
      `--> Error Description: Element is not Visible: ${error}`);
  }

}

module.exports = {
  getByType: getByType,
  findElement: findElement,
  waitForElement: waitForElement,
  waitForElements: waitForElements,
  getTextOfElement: getTextOfElement,
  getAttribute: getAttribute,
  clickElement: clickElement,
  getCurrentUrl: getCurrentUrl,
  findElements: findElements,
  waitForPageLoad: waitForPageLoad,
  enterValue: enterValue,
  scrollInto: scrollInto,
  waitOneSec: waitOneSec,
  isElementPresent: isElementPresent,
  dropdownSelectByVisibleText: dropdownSelectByVisibleText,
  isElementVisible: isElementVisible,
  clickShadowRootElement: clickShadowRootElement,
  getInnerTextOfShadowRootElement: getInnerTextOfShadowRootElement,
  clickShadowRootElementByCssSelector: clickShadowRootElementByCssSelector,
  getInnerTextShadowRootElementByCssSelector: getInnerTextShadowRootElementByCssSelector,
  performJqueryAction: performJqueryAction
};<|endoftext|>


<commit_before>import Application from '../../app';
import config from '../../config/environment';
import { run } from '@ember/runloop';
import { assign } from '@ember/polyfills';

export default function startApp(attrs) {
  let application;

  let attributes = Object.assign({}, config.APP);
  attributes = Object.assign(attributes, attrs); // use defaults, but you can override;

  run(() => {
    application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
  });

  return application;
}
<commit_msg>missing dependency<commit_after>import Application from '../../app';
import config from '../../config/environment';
import { run } from '@ember/runloop';

export default function startApp(attrs) {
  let application;

  let attributes = Object.assign({}, config.APP);
  attributes = Object.assign(attributes, attrs); // use defaults, but you can override;

  run(() => {
    application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
  });

  return application;
}
<|endoftext|>