function sanitizeOptions (o) { let ref = Number(o.dayStart || 0); let dayStart = !_.isNaN(ref) && ref >= 0 && ref <= 24 ? ref : 0; let timezoneOffset; let timezoneOffsetDefault = Number(moment().zone()); if (_.isFinite(o.timezoneOffsetOverride)) { timezoneOffset = Number(o.timezoneOffsetOverride); } else if (_.isFinite(o.timezoneOffset)) { timezoneOffset = Number(o.timezoneOffset); } else { timezoneOffset = timezoneOffsetDefault; } if (timezoneOffset > 720 || timezoneOffset < -840) { // timezones range from -12 (offset +720) to +14 (offset -840) timezoneOffset = timezoneOffsetDefault; } let now = o.now ? moment(o.now).zone(timezoneOffset) : moment().zone(timezoneOffset); // return a new object, we don't want to add "now" to user object return { dayStart, timezoneOffset, now, }; }
get: function(){ const assessment = this.toObject(); if( !assessment.comparisons ){ return {}; } let pA = assessment.comparisons.perAssessor || 0; let pR = assessment.comparisons.perRepresentation || 0; const rN = _.get( assessment, [ 'cache', 'representationsNum' ], 0 ); const aN = _.get( assessment, [ 'cache', 'assessorsNum' ], 0 ); switch( assessment.comparisons.dimension ){ case 'representation': pA = (rN * pR) / (2 * aN ); if( !_.isFinite( pA ) ){ pA = 0; } break; case 'assessor': default: pR = pA * 2 * aN / rN; if( !_.isFinite( pR ) ){ pR = 0; } break; } return { comparisonsNum: { perAssessor: pA, perRepresentation: pR }, assessorsNum: _.get( assessment, [ 'assessors', 'minimum' ], 0 ) }; },
constructor(image, columns, rows, subimageCount=0) { super(image, 'scaleToFill'); if (!_.isFinite(columns) || columns <= 0 || !_.isFinite(rows) || rows <= 0) { throw new Error('invalid geometry for composite image'); } this._columns = columns|0; this._rows = rows|0; if (_.isFinite(subimageCount) && subimageCount > 0 && subimageCount < this._columns * this._rows) { this._subimageCount = subimageCount|0; } else { this._subimageCount = this._columns * this._rows; } this._index = 0; if (image.complete) { this._imageLoaded(); } else { this.on('loaded', this._imageLoaded.bind(this)); } }
render() { const margin = _.isNumber(this.props.margin) ? {top: this.props.margin, bottom: this.props.margin, left: this.props.margin, right: this.props.margin} : _.defaults({}, this.props.margin, DEFAULT_PROPS.margin); // sizes fallback based on provided info: given dimension -> radius + margin -> other dimension -> default const width = this.props.width || (this.props.radius ? (this.props.radius * 2) + margin.left + margin.right : this.props.height) || DEFAULT_SIZE; const height = this.props.height || (this.props.radius ? (this.props.radius * 2) + margin.top + margin.bottom : this.props.width) || DEFAULT_SIZE; const radius = this.props.radius || Math.min((width - (margin.left + margin.right)) / 2, (height - (margin.top + margin.bottom)) / 2); const {holeRadius} = this.props; const center = {x: margin.left + radius, y: margin.top + radius}; const {markerLineValue, markerLineClass, markerLineOverhangInner, markerLineOverhangOuter} = this.props; const valueAccessor = makeAccessor(this.props.getValue); const sum = _.sumBy(this.props.data, valueAccessor); const total = this.props.total || sum; const markerLinePercent = _.isFinite(markerLineValue) ? markerLineValue / total : null; let startPercent = 0; return <svg className="pie-chart" {...{width, height}}> {this.props.data.map((d, i) => { const [onMouseEnter, onMouseMove, onMouseLeave] = ['onMouseEnterSlice', 'onMouseMoveSlice', 'onMouseLeaveSlice'].map(eventName => { // partially apply this bar's data point as 2nd callback argument const callback = methodIfFuncProp(eventName, this.props, this); return _.isFunction(callback) ? _.partial(callback, _, d) : null; }); const className = `pie-slice pie-slice-${i}`; const slicePercent = valueAccessor(d) / total; const endPercent = startPercent + slicePercent; const pathStr = pieSlicePath(startPercent, endPercent, center, radius, holeRadius); startPercent += slicePercent; const key = `pie-slice-${i}`; return <path {...{className, d: pathStr, onMouseEnter, onMouseMove, onMouseLeave, key}} />; })} {sum < total ? // draw empty slice if the sum of slices is less than expected total <path className='pie-slice pie-slice-empty' d={pieSlicePath(startPercent, 1, center, radius, holeRadius)} key="pie-slice-empty" /> : null } {_.isFinite(markerLinePercent) ? this.renderMarkerLine(markerLineClass, markerLine(markerLinePercent, center, radius, holeRadius, markerLineOverhangOuter, markerLineOverhangInner), 'pie-slice-marker-line') : null } {this.props.centerLabel ? this.renderCenterLabel(center) : null} </svg> }
blur: function(args) { var x = _.isFinite(args.x) ? args.x : 2; return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', { stdDeviation: _.isFinite(args.y) ? [x, args.y] : x }); },
static fromString(str) { var [lat, lng] = str.split(',').map(x => parseFloat(x)); if (!(_.isFinite(lat) && _.isFinite(lng))) { return; } return new Waypoint(new L.LatLng(lat, lng)); }
venue.geoPoint = (function (coord) { if (coord) { var pair = coord.split(',').map(parseFloat); if (pair.length === 2 && _.isFinite(pair[0]) && _.isFinite(pair[1])) { return { lat: pair[0], lon: pair[1] }; } } }(dojoListing.coordinates));
var isMap = function(obj) { var keys = []; if (obj) { keys = _.keys(obj); } return _.isEqual(_.size(keys), 4) && _.contains(keys, 'x') && _.isFinite(obj.x) && _.contains(keys, 'y') && _.isFinite(obj.y) && _.contains(keys, 'h') && _.isFinite(obj.h) && _.contains(keys, 'w') && _.isFinite(obj.w); };
env.toNumberOrThrow = function(val, msg) { msg = msg || ''; if(_.isFinite(val) || _.isFinite(Number(val))) { return +val; } throw new Error(util.format( '%s -> Received invalid numeric argument -> %s', msg, val )); };
dropShadow: function(args) { var tpl = 'SVGFEDropShadowElement' in window ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>' : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; return _.template(tpl, { dx: args.dx || 0, dy: args.dy || 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1, color: args.color || 'black', blur: _.isFinite(args.blur) ? args.blur : 4 }); },
exports.formatStats = function (stats) { // if reply rate is a well-behaved number, we convert the fraction to % var replyRate = (_.isFinite(stats.replyRate)) ? Math.round(stats.replyRate * 100) + '%' : ''; // if replyTime is a well-behaved number, we convert the milliseconds to // a human readable string var replyTime = (_.isFinite(stats.replyTime)) ? moment.duration(stats.replyTime).humanize() : ''; return { replyRate: replyRate, replyTime: replyTime }; };
return data.featuredOrder.reduce(function(acc, item) { if (!_.isFinite(Number(item.id)) || !_.isFinite(Number(item.position))) { acc = false; } else if (Number(item.position) > MAX_FEATURED_SURVEYS || Number(item.position) < 0) { acc = false; } else if (duplicates.id.indexOf(Number(item.id)) > -1 || duplicates.position.indexOf(Number(item.position)) > -1) { acc = false; } else { duplicates.id.push(Number(item.id)); duplicates.position.push(Number(item.position)); } return acc; }, true);
constructor(top=0, left=0, bottom=0, right=0) { if (!_.isFinite(top) || !_.isFinite(left) || !_.isFinite(bottom) || !_.isFinite(right)) { throw new Error('number required'); } super(); this._top = Math.abs(top); this._left = Math.abs(left); this._bottom = Math.abs(bottom); this._right = Math.abs(right); }
SubStream.prototype._transform = function(chunk, enc, cb){ var len = chunk.length , total = this.bytesRead , start = this.start , end = this.end || Infinity , data, isLast; this.bytesRead += chunk.length; if ( total <= start && this.bytesRead > start){ //first chunk if ( _.isFinite(end) ) end = this.end - total; if ( end > len) end = undefined; data = chunk.slice(start - total, end); console.log('First Chunk', total, start, end) } else if ( this.bytesRead >= end ) { //last chunk data = chunk.slice(0, this.end - this.total); isLast = true; console.log('Last Chunk') } else if ( total >= start) { data = chunk; console.log('n Chunk', total, len) } if ( data ) this.push(data); if ( isLast ) this._finish(); cb(); }
publishUpdate: function (id, changes, req) { // Ensure that we're working with a clean, unencumbered object changes = _.clone(changes); // Enforce valid usage var validId = _.isString(id) || _.isFinite(id); if ( !validId ) { throw new Error( 'Invalid usage of ' + '`' + this.identity + '.publishUpdate(id, changes, [socketToOmit])`' ); } var data = { model: this.identity, verb: 'update', data: changes, id: id }; // If a request object was sent, get its socket, otherwise assume a socket was sent. var socketToOmit = req && req.socket ? req.socket : req; // Old-style comet message; this may be phased out in future releases. this.publish(id, data, socketToOmit); data.verb = 'updated'; delete data.model; // Broadcast to the model room this.publish(id, this.identity, data, socketToOmit); },
return _.map(models, function (model) { if ( _.isString(model) || _.isFinite(model) ) { var id = model; return { id: id }; } return model; });
participant.invalidYear = (birthyear) => { const isNumber = _.isFinite(_.toNumber(birthyear)); const isPresent = !_.isUndefined(birthyear) && !_.isEmpty(birthyear); const greaterZero = _.toNumber(birthyear) > 0; return isPresent && (!isNumber || !greaterZero); };
exports.loadDetail = function *(hid) { const id = +hashids.decode(hid) if (!isFinite(id)) return {} return yield models.users.findOne({ where: { id: id }, attributes: ['id', 'name', 'email', 'created_at', 'status'], include: [{ model: models.usersInfo, attributes: [ 'ocname', 'contact', 'country', 'city', 'address', 'place', 'zipcode', 'tel', 'fax', 'url', 'email' ], required: false }], raw: true }) }
function computeConfidenceScore(hit) { // non-number or invalid distance should be given confidence 0.0 if (!_.isFinite(hit.distance) || hit.distance < 0) { hit.confidence = SCORES.INVALID; return hit; } var distance = hit.distance * 1000.0; // figure out which range the distance lies in and assign confidence accordingly if (distance < BUCKETS._1_METER) { hit.confidence = SCORES.EXACT; } else if (distance < BUCKETS._10_METERS) { hit.confidence = SCORES.EXCELLENT; } else if (distance < BUCKETS._100_METERS) { hit.confidence = SCORES.GOOD; } else if (distance < BUCKETS._250_METERS) { hit.confidence = SCORES.OKAY; } else if (distance < BUCKETS._1_KILOMETER) { hit.confidence = SCORES.POOR; } else { hit.confidence = SCORES.NONE; } return hit; }
var threshold = getParam(req, "threshold", function(p) { if (_.isFinite(p)) { return p; } else { return 5000; } }, 5000);
th: function(integer) { if(_.isFinite(+integer) && Math.floor(+integer) === +integer) { var lastDigit = +integer % 10; var lastTwoDigits = +integer % 100; var response = integer + ""; // Handle n-teen case if(lastTwoDigits >= 11 && lastTwoDigits <= 13) { return response + "th"; } // Handle general case switch(lastDigit) { case 1: return response + "st"; case 2: return response + "nd"; case 3: return response + "rd"; default: return response + "th"; } } else { sails.log.debug("You specified: ", integer); throw new Error("But _.th only works on integers!"); } },
exports.ordinal = function(integer) { if(_.isFinite(+integer) && Math.floor(+integer) === +integer) { var lastDigit = +integer % 10; var lastTwoDigits = +integer % 100; var response = integer + ""; // Handle n-teen case if(lastTwoDigits >= 11 && lastTwoDigits <= 13) { return response + "th"; } // Handle general case switch(lastDigit) { case 1: return response + "st"; case 2: return response + "nd"; case 3: return response + "rd"; default: return response + "th"; } } throw new Error("sails.util.ordinal() only works on integers!"); };
prettifyBytes: function(bytes) { if (_.isFinite(bytes)) { return prettyBytes(bytes); } else { return ''; } },
number: (n) => { if(_.isFinite(n) && ((n | 0) === n)) { // integers return <ReplOutputInteger int={n} /> } return <span className='number'>{n}</span>; },
this.fillInUTCInfo = function(obj, jsDate) { if (typeof obj !== 'object' || Array.isArray(obj)) { throw new Error('Must provide an object!'); } if (_.isEmpty(obj)) { throw new Error('Object must not be empty!'); } if (isNaN(jsDate.valueOf())) { throw new Error('Date must be provided!'); } var lookupIndex = _.get(obj, 'index', null); if (!(_.isFinite(obj.index) && obj.index >= 0)) { lookupIndex = null; } var res = this.lookup(jsDate, lookupIndex); if (!res) { debug('Could not look up UTC info for:', obj); throw new Error('Failed to look up UTC info!'); } obj.time = res.time; obj.timezoneOffset = res.timezoneOffset; obj.clockDriftOffset = res.clockDriftOffset; obj.conversionOffset = res.conversionOffset; if (obj.index == null) { annotate.annotateEvent(obj, 'uncertain-timestamp'); } return obj; };
exports.createOrUpdate = function *(hid, info) { const fillable = [ 'uid', 'cid', 'ocname', 'contact', 'country', 'city', 'address', 'place', 'zipcode', 'lat', 'lng', 'tel', 'fax', 'url', 'email' ] const id = +hashids.decode(hid) if (!isFinite(id)) return false const userInfo = yield models.usersInfo.findOne({ where: { uid: id } }) if (!userInfo) { info.uid = id return yield models.usersInfo.create(info, { fields: fillable }) } else { return yield userInfo.update(info, { fields: fillable }) } }
function updateItems() { var maxItems = parseInt($scope.maxItems); if (!_.isFinite(maxItems) || (maxItems < 0)) { maxItems = 0; } var items = _.isArray($scope.items) ? $scope.items : []; if ((maxItems > 0) && (items.length > maxItems)) { items = _.filter(items, function(item) { return !isSelected(item.key); }); } items = $filter('filter')(items, $scope.filter); items = $filter('orderBy')(items, 'label'); $scope.hasMoreItems = false; if (maxItems > 0) { $scope.hasMoreItems = items.length > maxItems; items = items.slice(0, maxItems); } $scope.itemsToDisplay = items; updateSelectedItems(); }
function parseInteger(schema, value, propPath) { // Handle missing, required, and default value = getValueToValidate(schema, value); // Make sure it's a properly-formatted integer var parsedValue = parseInt(value); if (_.isNaN(parsedValue) || !_.isFinite(parsedValue) || !dataTypePatterns.integer.test(value)) { throw ono({status: 400}, '"%s" is not a properly-formatted whole number', propPath || value); } // Force the schema to be validated as an integer var originalType = schema.type; schema.type = 'integer'; // Validate against the schema try { jsonValidate(schema, parsedValue, propPath); } finally { // Restore the original schema type schema.type = originalType; } // Validate the format var range = ranges[schema.format]; if (range) { if (parsedValue < range.min || parsedValue > range.max) { throw ono({status: 400}, '"%s" is not a valid %s. Must be between %d and %d', propPath || parsedValue, schema.format, range.min, range.max); } } return parsedValue; }
it('should return a finite number', function () { var sample = _.sample(mapData.features); var distance = markerLayer._geohashMinDistance(sample); expect(distance).to.be.a('number'); expect(_.isFinite(distance)).to.be(true); });
Cluster.prototype.initalizeNodes = function (path) { var self = this; var nodes = []; if (_.isFinite(this.options.nodes)) { _.times(this.options.nodes, function (index) { nodes.push(_.cloneDeep(self.options.config)); }); } else { nodes = _.map(this.options.nodes, function (node) { return _.defaults(node, self.options.config); }); } this.nodes = _.map(nodes, function (config) { var options = _.defaults({ config: config, path: path }, self.options); if (self.options.clusterNameOverride) { options.clusterNameOverride = self.options.clusterNameOverride; } var node = new Node(options); var log = _.bindKey(self, 'log'); node.on('log', log); node.on('error', function (error) { self.emit('error', error); }); return node; }); return this.nodes; };