Пример #1
0
participant.invalidYear = (birthyear) => {
  const isNumber = _.isFinite(_.toNumber(birthyear));
  const isPresent = !_.isUndefined(birthyear) && !_.isEmpty(birthyear);
  const greaterZero = _.toNumber(birthyear) > 0;

  return isPresent && (!isNumber || !greaterZero);
};
Пример #2
0
 setClaimTimeout: function (timeout) {
   
   if (_.isInteger(_.toNumber(timeout))) {
     localClaimsExpiry = _.toNumber(timeout);
     console.log("localClaims expiry has been successfully set to", timeout, "ms");
   } else {
     console.log("timeout needs to be an integer");
   }
 }
Пример #3
0
 (decimalsR, symbol) => {
   const decimalsFormat = _.toNumber(decimalsR)
   let decimals = decimalsFormat
   if (decimals > 0) {
     decimals = Math.pow(10, decimals)
   } else {
     decimals = 1
   }
   return (_.toNumber(payload.balanceContact) / decimals).toFixed(decimalsFormat) + ' ' + symbol
 }
Пример #4
0
 (tokenEmission, holder, token, percentage, balanceContact, emissionLimit) => (
   {
     tokenEmission,
     token: (token !== '0x0000000000000000000000000000000000000000') ? token : '',
     holder,
     percentage: _.toNumber(percentage),
     balanceContact: _.toNumber(balanceContact),
     limit: _.toNumber(emissionLimit)
   }
 )
Пример #5
0
participant.from = (body) => {
  if (participant.invalidData(body)) {
    throw new TypeError('Required attributes are not present');
  }

  if (participant.invalidYear(body.birthyear)) {
    throw new TypeError(`Malformed year-of-birth: '${body.birthyear}'. Please provide a 4 digit number i.e. '1969'`);
  }

  let p = {
    firstname: body.firstname,
    lastname: body.lastname,
    email: body.email,
    visibility: body.visibility,
    discount: _.isUndefined(body.discount) ? 'no' : body.discount,
    couponcode: body.couponcode,
    category: body.category,
    birthyear: _.isFinite(_.toNumber(body.birthyear)) ? _.toNumber(body.birthyear) : 0,
    team: body.team,
    tshirt: tshirt.from(body),
    goal: body.goal
  };

  p.with = function (property) {
    return _.assignIn(p, property);
  };

  p.withStartNr = (nr) => {
    return p.with({start_number: nr});
  };

  p.withToken = (token) => {
    return p.with({paymentToken: token});
  };

  p.withSecureId = (id) => {
    return p.with({secureID: id});
  };

  p.withStartBlock = (block) => {
    return p.with({start_block: block});
  };

  p.withRegistrationTime = (time) => {
    return p.with({registrationTime: time});
  };
  p.withConfirmedResult = (confirmation) => {
    return p.with({confirmed_result: confirmation});
  };

  return p;
};
Пример #6
0
 (name, decimalsR, symbol, balance, totalSupply) => {
   const decimalsFormat = _.toNumber(decimalsR)
   let decimals = decimalsFormat
   if (decimals > 0) {
     decimals = Math.pow(10, decimals)
   } else {
     decimals = 1
   }
   return {
     name,
     balance: (_.toNumber(balance) / decimals).toFixed(decimalsFormat) + ' ' + symbol,
     totalSupply: (_.toNumber(totalSupply) / decimals).toFixed(decimalsFormat) + ' ' + symbol
   }
 }
Пример #7
0
function getDefault() {
  return {
    label: 'New File',
    mode: 'python',
    id: cid(),
    tabId: cid(),
    hasFocus: true,
    keyBindings: store.get('aceKeyBindings') || 'default',
    tabSpaces: _.toNumber(store.get('aceTabSpaces')) || 4,
    icon: 'file-code-o',
    isCloseable: true,
    fontSize: _.toNumber(store.get('fontSize')) || 12,
    theme: 'chrome'
  };
}
Пример #8
0
 .then((tokenInfo) => {
   dispatch({
     type: LOAD_MODULE,
     payload: {
       ...payload,
       balanceTokenEmission: (_.toNumber(tokenInfo.balance) / tokenInfo.decimals).toFixed(tokenInfo.decimalsFormat) + ' ' + tokenInfo.symbol,
       limit: (_.toNumber(payload.limit) / tokenInfo.decimals)
         .toFixed(tokenInfo.decimalsFormat),
       limitStr: (_.toNumber(payload.limit) / tokenInfo.decimals)
         .toFixed(tokenInfo.decimalsFormat) + ' ' + tokenInfo.symbol
     }
   })
   hett.watcher.addAddress(commitmentAddress, 'loadModule', (address) => {
     dispatch(loadModule(address))
   })
 })
OpenExchangeRatesProvider.prototype.fetchRateSync = function (currencyPair) {
  var self = this;

  if (!self.enterprise && currencyPair.getBaseCurrency() !== 'USD') {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }

  var url = "";
  if (self.enterprise) {
    url = sprintf(ENTERPRISE_URL, self.appId, currencyPair.getBaseCurrency(), currencyPair.getQuoteCurrency());
  }
  else {
    url = sprintf(FREE_URL, self.appId);
  }

  var content = this.fetchContentSync(url);

  // Parse the content fetch from open exchange rate
  var data = self.parseContent(content);

  if (!_.isUndefined(data['error'])) {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }

  if (data.base !== currencyPair.getBaseCurrency() || _.isUndefined(data.rates[currencyPair.getQuoteCurrency()])) {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }

  var date = data.timestamp ? new Date(data.timestamp * 1000) : new Date();
  return new Rate(_.toNumber(data.rates[currencyPair.getQuoteCurrency()]), date, Provider);
};
EuropeanCentralBankProvider.prototype.fetchRateSync = function (currencyPair) {
  var self = this;

  if (currencyPair.getBaseCurrency() !== 'EUR') {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }
  var content = this.fetchContentSync(URL);

  // Parse the content fetch from european central bank
  var xmlObj = self.parseContent(content);
  var rootCube = xmlObj.childNamed("Cube");
  var cube = rootCube.childNamed("Cube");

  // throw exception if date is not available
  if (cube === null || _.isUndefined(cube) || _.isUndefined(cube.attr)) {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }

  // search for quote currency rate
  var rateElement = cube.childWithAttribute('currency', currencyPair.getQuoteCurrency());

  // throw exception if rate is not available
  if (rateElement === null || _.isUndefined(rateElement) || _.isUndefined(rateElement.attr) || _.isUndefined(
      rateElement.attr.rate)) {
    throw new UnsupportedCurrencyPairException(currencyPair, Provider);
  }

  var date = cube.attr.time ? new Date(cube.attr.time) : new Date();
  return new Rate(_.toNumber(rateElement.attr.rate), date, Provider);
};
  self.fetchContent(URL, function (err, content) {
    if (err) {
      return callback(err, null);
    }

    // Parse the content fetch from european central bank
    var xmlObj = self.parseContent(content);
    var rootCube = xmlObj.childNamed("Cube");
    var cube = rootCube.childNamed("Cube");

    if (cube === null || _.isUndefined(cube) || _.isUndefined(cube.attr)) {
      return callback(new UnsupportedCurrencyPairException(currencyPair, Provider), null);
    }

    // search for quote currency rate
    var rateElement = cube.childWithAttribute('currency', currencyPair.getQuoteCurrency());

    // return error if rate is not available
    if (rateElement === null || _.isUndefined(rateElement) || _.isUndefined(rateElement.attr) || _.isUndefined(
        rateElement.attr.rate)) {
      return callback(new UnsupportedCurrencyPairException(currencyPair, Provider), null);
    }

    var date = cube.attr.time ? new Date(cube.attr.time) : new Date();
    return callback(null, new Rate(_.toNumber(rateElement.attr.rate), date, Provider));
  });
Пример #12
0
  handleChange = ({ target }) => {
    let value = target.type === 'number' && target.value !== '' ? toNumber(target.value) : target.value;
    let name = target.name;

    if (this.props.match.params.slug === 'security') {
      // the only case where the input doesn't have a name
      if (target.name === '') {
        name = 'security.xframe.value.nested';
        value = target.value;
      }
    }

    if (this.props.match.params.slug === 'databases') {
      if (name === this.props.home.dbNameTarget) {
        const formErrors = value === this.props.home.addDatabaseSection.sections[1].items[0].value ?
          [{ target: name, errors: [{ id: 'settings-manager.request.error.database.exist' }] }] : [];
        this.props.setErrors(formErrors);
      } else if (endsWith(name, '.settings.client')) {
        const item = find(this.props.home.addDatabaseSection.sections[0].items[1].items, { value });
        this.props.changeInput('database.connections.${name}.settings.port', item.port);
        this.props.changeInput(`database.connections.${this.props.home.addDatabaseSection.sections[1].items[0].value}.settings.port`, item.port);
      } else {
        this.props.setErrors([]);
      }
    }
    this.props.changeInput(name, value);
  }
Пример #13
0
function all(req, res) {
  var page = req.query.page || 1,
    pageSize = req.query.pageSize || 10,
    sort = req.query.sort || 'name',
    deferred = Q.defer();
  page--;
  debug(`page=${page}, pageSize=${pageSize}, sort=${sort}`);
  Venue.count({}, function (err, total) {
    if (err) {
      deferred.resolve(0);
    } else {
      deferred.resolve(total);
    }
  });

  Venue.find({})
    .sort(sort)
    .skip(page * pageSize)
    .limit(_.toNumber(pageSize))
    .exec(function (err, venues) {
      if (err) {
        debug(err);
        res.status(500).send({ message: 'db error' });
      }
      var result = venues ? venues : [];
      Q.when(deferred.promise, function (total) {
        res.set('X-Total-Elements', total);

        res.set('X-Page-Size', pageSize);
        res.set('X-Page', page + 1);
        res.send(result);
      });
    });
}
Пример #14
0
    _.map(whereParams, (value, key) => {

        // Wildcard (*)
        if (key === 'fullTextSearch') {
            query = query.find({ $text: { $search: value } });

        // Greater than (min)
        } else if (_.startsWith(key, 'min')) {
            key = _.toLower(key.replace('min', ''));

            // Protpery is number
            if (isPropertyNumber(rawModel, key)) {
                value = _.toNumber(value);
                query = query.where(key).gt(value);

            // Property is date
            } else if (isPropertyDate(rawModel, key)) {
                value = getDateObject(value);
                query = query.where(key).gt(value);

            } else {
                logger.debug(`${ options.url } - tried to filter by MIN "${ key }" property but it is missing from model`);
            }

        // Less than (max)
        } else if (_.startsWith(key, 'max')) {
            key = _.toLower(key.replace('max', ''));

            // Protpery is number
            if (isPropertyNumber(rawModel, key)) {
                value = _.toNumber(value);
                query = query.where(key).lt(value);

            // Property is date
            } else if (isPropertyDate(rawModel, key)) {
                value = getDateObject(value);
                query = query.where(key).lt(value);

            } else {
                logger.debug(`${ options.url } - tried to filter by MAX "${ key }" property but it is missing from model`);
            }

        // Equality
        } else {
            query = query.where(key).equals(value);
        }
    });
Пример #15
0
 .then((symbol) => {
   if (decimals > 0) {
     decimals = Math.pow(10, decimals)
   } else {
     decimals = 1
   }
   return (_.toNumber(output) / decimals).toFixed(decimalsFormat) + ' ' + symbol
 })
Пример #16
0
export function receiveResponseStatus(responseStatus, fpErrorMask = null) {
    let action = { type: actionTypes.RESPONSE_STATUS_RECEIVED,
                   responseStatus: responseStatus }
    if (!_.isEmpty(fpErrorMask)) {
        action.fpErrorMask = _.toNumber(fpErrorMask)
    }
    return action
}
function defaultParser(line, parsedComments) {
  const [isAbusive, ...comment] = _.map(line.split(','));

  parsedComments.push([
    _.toNumber(isAbusive),
    comment.join().replace(/"""/g, ''),
  ]);
}
Пример #18
0
 _.forEach(themes, (_theme, index) => {
   if (_.toNumber(_theme.id) == options.theme.id) {
     _theme.type = typeTheme(_theme);
     options.theme.current = _theme;
     conf.set('options', options);
     resolve(_theme);
   }
 });
function processPlace(places //jshint ignore:line
) {

    var data;

    //jshint ignore:start

    if (places) {
        var place = _.find(places.address_components, function (o) {
            return o.types[0] === 'locality';
        });
        var postalCode = _.find(places.address_components, function (o) {
            return o.types[0] === 'postal_code';
        });

        if (!postalCode) {
            return new Promise(function (resolve, reject) {
                return reject(new StandardError({
                    msgInfo: 'We could not fetch details of your area.',
                    msgCode: 'no_results_found'
                }));
            });
        }
        var pCode = _.toNumber(postalCode.long_name);

        if (_.isNaN(pCode)) {
            return new Promise(function (resolve, reject) {
                return reject(new StandardError({
                    msgInfo: 'We could not fetch details of your area.',
                    msgCode: 'no_results_found'
                }));
            });
        }

        data = {
            city: place.long_name,
            postalCode: postalCode.long_name,
            address: places.formatted_address,
            found: true

        };


        data.available = place.long_name.toLowerCase() === 'boston';

    } else {
        data = {
            city: 'N/A',
            postalCode: 'N/A',
            found: false

        };
        data.available = false;
    }

    //jshint ignore:end
    return data;
}
 getNumberOfCommitsOnBranch: function getNumberOfCommitsOnBranch (branch) {
   const refArgument = `$(git for-each-ref '--format=%(refname)' refs/ | grep /${branch} | head -1)`
   const notArgument = `$(git for-each-ref '--format=%(refname)' refs/ | grep -v /${branch})`
   return _.toNumber(
     exec(
       `git log ${refArgument} --oneline --not ${notArgument} | wc -l`
     ).toString()
   )
 },
Пример #21
0
    _.forEach(lines, (line) => {
        let dimensions = _.split(line, 'x')

        let length = _.toNumber(dimensions[0])
        let width = _.toNumber(dimensions[1])
        let height = _.toNumber(dimensions[2])

        let areas = [
            length * width,
            width * height,
            height * length
        ]

        let surfaceArea = _.sum(areas) * 2
        let smallestArea = _.min(areas)

        totalSurfaceArea += surfaceArea + smallestArea
    })
Пример #22
0
MessageModel.prototype.distinctRooms = function(userID,groupIds,callBack){
    var groupIds = groupIds.split(",")
    var gIds = _.map(groupIds, function(v){ return _.toNumber(v) } );
    this.model.distinct('roomID',
        { $and: [ { $or: [ 
                    { 'attributes.receiverType': 'User', 'attributes.receiverID': _.toNumber(userID )},
                    { 'attributes.receiverType': 'Group', 'attributes.receiverID': { $in: gIds  } },
                    { userID: _.toNumber(userID) } ]
                  }
                ]
        },
        function (err, roomIds) {
        if (err) 
            console.error(err);
        if(callBack)
            callBack(err,roomIds);
    });
}
Пример #23
0
  insertColumn(index) {
    const [body] = this.descendant(TableBody);
    if (body == null || body.children.head == null) return;

    // calculate table width
    const currTableWidth = this.domNode.offsetWidth;
    const headRow = body.children.head;
    const targetRowHeadCell = headRow.children.at(index);
    const targetCell = targetRowHeadCell ?
      targetRowHeadCell.prev || targetRowHeadCell : headRow.children.tail;
    const targetCellFormats = TableCellContent.formats(targetCell.children.head.domNode);
    if (targetCellFormats['data-width'] && currTableWidth <= Quill.DEFAULTS.minTableWidth) {
      const rootWidth = this.scroll.domNode.offsetWidth - 5;
      const cellWidth = _.toNumber(_.replace(targetCellFormats['data-width'], 'px', ''));
      const adjustedCellWidth = (cellWidth / (currTableWidth + cellWidth)) * rootWidth;
      targetCellFormats['data-width'] = `${Math.floor(adjustedCellWidth)}px`;
      targetCellFormats['data-cell'] = cellId();
      const cellToCreate = this.scroll.create(TableCellContent.blotName, targetCellFormats);

      body.children.forEach(row => {
        if (row === headRow) {
          row.children.forEach(cell => {
            const originWidth = Number.parseInt(cell.domNode.style.width.replace('px', ''));
            const newWidth = (originWidth / (currTableWidth + cellWidth)) * rootWidth;
            const newWidthString = `${newWidth}px`;

            cell.children.head.format('data-width', newWidthString);
            cell.domNode.style.width = newWidthString;
            cell.domNode.style.minWidth = newWidthString;
            if (cell === targetCell) {
              cell.insertBefore(cellToCreate);
            }
          });
        } else {
          const ref = row.children.at(index);
          const targetCell = ref ? ref.prev || ref : row.children.tail;
          const value = TableCellContent.formats(targetCell.children.head.domNode);

          value['data-cell'] = cellId();
          const cell = this.scroll.create(TableCellContent.blotName, value);
          row.insertBefore(cell, ref);
        }
      });
      this.domNode.style.width = `${rootWidth}px`;
    } else {
      body.children.forEach(row => {
        const ref = row.children.at(index);
        const targetCell = ref ? ref.prev || ref : row.children.tail;
        const value = TableCellContent.formats(targetCell.children.head.domNode);

        value['data-cell'] = cellId();
        const cell = this.scroll.create(TableCellContent.blotName, value);
        row.insertBefore(cell, ref);
      });
    }
  }
Пример #24
0
  count: async ctx => {
    const { source } = ctx.request.query;

    // Count using `queries` system
    const count = await strapi.plugins['content-manager'].services['contentmanager'].count(ctx.params, source);

    ctx.body = {
      count: _.isNumber(count) ? count : _.toNumber(count)
    };
  },
Пример #25
0
 .then((result) => {
   let decimals = _.toNumber(result)
   if (decimals > 0) {
     decimals = Math.pow(10, decimals)
   } else {
     decimals = 1
   }
   formData.value *= decimals
   dispatch(submitContract('FormToken', address, 'TokenEmission', action, formData))
 })
Пример #26
0
  count: async ctx => {
    // Search
    const count = !_.isEmpty(ctx.request.query._q)
      ? await strapi.plugins['content-manager'].services['contentmanager'].countSearch(ctx.params, ctx.request.query)
      : await strapi.plugins['content-manager'].services['contentmanager'].count(ctx.params, ctx.request.query);

    ctx.body = {
      count: _.isNumber(count) ? count : _.toNumber(count)
    };
  },
Пример #27
0
module.exports = function (value) {
  const num = _.toNumber(value)
  const bool = toBoolean(value)

  return _
  .chain([num, bool])
  .find(isValue(value))
  .defaultTo(value)
  .value()
}
Пример #28
0
router.get('/diaries/:diary/meetings', function(req, res, next) {
  var db = req.db;
  db.get('meetings').find({'diary': _.toNumber(req.params.diary), 'meeting': { '$gte': new Date() }}, {}, function(err, docs) {
    if (docs.length > 0)
		  res.send(docs);
    else {
      res.status(500);
      res.send(docs);
    }
	});
});
Пример #29
0
          redis.cache = async ({ expired = 60 * 60, serial }, cb, type) => {
            if (_.isEmpty(serial)) {
              strapi.log.warn(
                `Be careful, you're using cache() function of strapi-redis without serial`
              );

              const traces = stackTrace.get();

              strapi.log.warn(
                `> [${traces[1].getLineNumber()}] ${traces[1]
                  .getFileName()
                  .replace(strapi.config.appPath, '')}`
              );

              return await cb();
            }

            let cache = await redis.get(serial);

            if (!cache) {
              cache = await cb();

              if (
                cache &&
                _.get(connection, 'options.disabledCaching') !== true
              ) {
                switch (type) {
                  case 'json':
                    redis.set(serial, JSON.stringify(cache), 'ex', expired);
                    break;
                  case 'int':
                  default:
                    redis.set(serial, cache, 'ex', expired);
                    break;
                }

              }
            }

            switch (type) {
              case 'int':
                return parseInt(cache);
              case 'float':
                return _.toNumber(cache);
              case 'json':
                try {
                  return _.isObject(cache) ? cache : JSON.parse(cache);
                } catch (e) {
                  return cache;
                }
              default:
                return cache;
            }
          };
Пример #30
0
 value: function(isFirstTime) {
     this.super(isFirstTime);
     var parts = _.split(this.object.subnet, '/');
     this.object._subnet = [
         {
             type: 'INET',
             address: parts[0],
             netmask: parts[1] ? _.toNumber(parts[1]) : null
         }
     ];
 }