Example #1
0
export default (keyword, weatherTime, sunrise, sunset, clouds) => {
  if (!sunrise || !sunset || clouds > 80) {
    return icons[keyword]
  }

  // Assume forecast is in the future, and if not the same day it must be the next
  // Subtract a day and use todays sunrise/sunset to calculate
  const time = weatherTime.isSame(moment(), 'day')
    ? weatherTime
    : weatherTime.subtract(1, 'days')

  const sinceSunrise = time.diff(moment.unix(sunrise), 'hours')
  const untillSunset = moment.unix(sunset).diff(time, 'hours')
  const nextDay = moment().diff(time, 'days')

  if (untillSunset < 1) {
    return icons[`night-${keyword}`]
  } else if (sinceSunrise > 1) {
    return icons[`day-${keyword}`]
  }

  return icons[keyword]
}
Example #2
0
 const txTimeLineItems = currentBlockTxList.map((txItem, i) =>
   <Timeline.Item>
     <p>
       txId:
       {/*<Tooltip overlayClassName={styles.tooltipOverlay} placement="bottomLeft" title={txItem.id}>*/}
         <a onClick={() => onClickTx(txItem.id)}>
           {txItem.id}
         </a>
       {/*</Tooltip>*/}
     </p>
     <p>
       timestamp: {moment.unix(txItem.timestamp).format("YYYY-MM-DD HH:mm:ss")}
     </p>
   </Timeline.Item>
Example #3
0
const detailsRow = data => html`
  <td colspan="4">
    <ul>
      <li>
        <i class="wi wi-sunrise"></i> ${moment.unix(data.sunriseTime).format('h:mm a')}
      </li>
      <li>
        <i class="wi wi-sunset"></i> ${moment.unix(data.sunsetTime).format('h:mm a')}
      </li>
      <li>
        <i class="wi wi-humidity"></i> ${percent(data.humidity)}
      </li>
      <li>
        <i class="wi wi-raindrops"></i> ${percent(data.precipProbability)}
      </li>
      <li>
        <i class="wi wi-strong-wind"></i>
        <i class="wi wi-wind towards-${closestInt(windDegrees, data.windBearing)}-deg"></i>
        ${data.windSpeed} mph
      </li>
    </ul>
  </td>  
`;
Example #4
0
        async.eachSeries(entries, function (entry, cb) {
          var content = entry.content || entry.summary;

          feed.item({
            title: entry.title,
            description: content,
            date: moment.unix(entry.published),
            author: entry.author.displayName,
            url: entry.permalinkUrl,
            guid: entry._id.toHexString()
          });

          return cb();
        }, function (err) {
Example #5
0
  static formattedTimestampFromAt(at) {
    const mAt = moment.unix(Number(at) / 1000);

    const WHEN_STARTED_TO_CRAWL_RATE_5_MIN = this.parseTime('2016-08-09-16-30');

    let formattedTimestamp = '';
    if (WHEN_STARTED_TO_CRAWL_RATE_5_MIN.valueOf() < mAt.valueOf()) {
      mAt.minute( mAt.minute() - mAt.minute() % 5 );
      formattedTimestamp = mAt.utcOffset(0).format('YYYY/MM/DD/HH/mm');
    } else if (WHEN_STARTED_TO_CRAWL_RATE_5_MIN.valueOf() > mAt.valueOf()) {
      formattedTimestamp = mAt.utcOffset(0).format('YYYY/MM/DD/HH');
    }
    return formattedTimestamp;
  }
Example #6
0
    return co(function*() {
        const offerSum = yield models.dmd_offer_apply.sum('money', {
            where: {
                oid: offerApply.oid,
                state: 4
            }
        })

        if (offer.money === offerSum) {
            if (offerMember.ok === 0) {
                offerMember.ok = 1
                yield offerMember.save()
            }

            let ice = 0
            if (offer.fst === 1) {
                ice = models.dmd_config.getConfig(23)
            } else {
                let day = Math.ceil((moment().unix() - offer.the_time) / (60 * 60 * 24))

                const from_time = moment().format('MM/DD/YYYY') + " " + moment.unix(offer.the_time).format("hh:mm:ss")
                day = from_time >= moment().format("MM/DD/YYYY hh:mm:ss") ? day : day - 1

                day = day < 1 ? 1 : day
                const conf24 = Number(models.dmd_config.getConfig(24)) //15 投资周期(单位:天)
                ice = conf24 - day
            }
            offer.state = 100
            offer.income = offer.money
            offer.end_time = moment().unix()
            offer.ice = ice
            yield offer.save()

            let text = offer.fst === 0 ? "播种" : "购买激活币";
            yield models.dmd_income.create({
                member_id: offerMember.id,
                type: "money",
                money: offer.money,
                intro: "成功" + text + "¥" + offer.money + "元,本金将在冻结" + ice + "天后自动收入现金余额"
            })

            if (offer.fst === 0) {
                //发放奖励
                yield send_interest(offerMember, offer)
                //发放团队奖励(直推 + 团队奖)
                yield send_team_bonus(offerMember, offer)
            }
        }
    })
Example #7
0
		query(connection, 'SELECT * FROM duelhistory WHERE duelid = ?', args[0]).done(function(result) {
			if (result[0].length === 0) {
				send_MESSAGE_PRIVATE(userId, 'Invalid Duel Id')
				connection.release()
				return
			}
			var viewduelReply = '<center> <font color=#FFFF00> :::Duel ' +  args[0] + ' Results::: </font> </center> \n\n'
			viewduelReply += '<font color=#00FFFF>Attacker</font>: ' + result[0][0].attacker + '\n'
			viewduelReply += '<font color=#00FFFF>Defender</font>: ' + result[0][0].defender + '\n'
			viewduelReply += '<font color=#00FFFF>Winner</font>: ' + result[0][0].winner + '\n'
			viewduelReply += '<font color=#00FFFF>Date</font>: ' + moment(moment.unix(result[0][0].date)).fromNow() + '\n\n'
			viewduelReply += result[0][0].battlelog + '\n'
			send_MESSAGE_PRIVATE(userId, blob('View Duel Id '  + args[0], viewduelReply))
			connection.release()
		})
Example #8
0
		var favorites = body.items.map(function (fav) {
			return {
				itemId: fav.question_id.toString(),
				idInt: fav.question_id,
				user: state.user,
				userData: user,
				dateInt: fav.creation_date,
				created: moment.unix(fav.creation_date).toDate(),
				description: fav.title,
				authorName: fav.owner.display_name,
				avatarUrl: fav.owner.profile_image && fav.owner.profile_image.replace(/^http:\/\//i, 'https://'),
				source: 'http://stackoverflow.com/questions/' + fav.question_id,
				type: 'stackoverflow'
			};
		});
  load(){

    let list = fs.readdirSync(`./articles`);
    
    let len = list.length;
    for(let k=len-1;k>0;k--){
      let article = Object.assign({},require('../articles/'+list[k]));
      delete article.content;
      article.seq = Number.parseInt(article.modified);
      article.createdAt = moment.unix(article.createdAt).format('MM/DD/YYYY');
      article.modified = moment.unix(article.modified).format('MM/DD/YYYY');
      
      this.sortList.push(article);
      this.map[article.id]= article;
      for(let i in article.keywords){
        let word = article.keywords[i];
        
         this.se[word] = this.se[word] || [];
         this.se[word].push(article);
      }
    }
    this.updateDesc();
   //console.log(this.sortList);process.exit(0);
  }
        getGaleriaImages(nid, creator.modelId, function(err, images) {
          if(err) sails.log.error('Error on get geleria images', record);
          if (images) {
            images.forEach(function(i){
              relato.images.add(i);
            });
          }

          if ( record.field_experiencia_catespecificas ) {
            relato.categorias = [getRelatoTema(record, temas)];  
          }

          relato.atoresExt = atores;
          relato.autoresExt = autores;
					relato.descricao = formatBody(record);
					relato.creator = creator.modelId;
					relato.updatedAt = moment.unix(record.changed).toDate();
					relato.createdAt = moment.unix(record.created).toDate();
					relato.save(function(err){
						if( err ) sails.log.error('Error on save relato', record, relato);
						//sails.log.warn('will save',relato, record )
				    done();	
					})
				})
Example #11
0
                        _.each(toBeIs,function(data){
                            if(!data.employee){
                                return;
                            }
                            var employee=data.employee,
                                userName=employee?employee.name:"",
                                userId=data.employeeID,
                                //profileImage=FS.FILES_PATH+'/'+(employee?employee.profileImage:'')+'3.jpg',
                                profileImage=util.getAvatarLink(employee?employee.profileImage:'',3),
                                dateTime=moment.unix(data.dateTime).format('MM-DD HH:mm'),
                                feedId=data.feedID,
                                feedContent=data.feedContent;
                            approveRmylistHtml+="<div class='rightc-listwrap fn-clear'><a href='javascript:;' class='rlist-headimg-wrap'><img class='rlist-headimg' src='"+profileImage+"' /></a><p class='rlist-pname'><a href='#profile/=/empid-"+userId+"' class='fna-blue'>"+userName+"</a> <span class='rlist-pname-apvdate'>"+dateTime+"</span></p><a class='rlist-atext fna-grey' href='#stream/showfeed/=/id-"+feedId+"'>"+feedContent+"</a></div>";

                        });
Example #12
0
    request("https://api.crowdscores.com/v1/matches?api_key=e6b14abc4a0f4ae2b009b2a23af14801", function(error, response, body) {
        if (!error && response.statusCode == 200) {
            body = JSON.parse(body);

            for (var i = 0; i < body.length; i++) {
                body[i].start = moment.unix(body[i].start / 1000).format("YYYY MMM DD hh:mm:ss");
            }

            res.render(__dirname + "/public/html/sports/matches.ejs", {
                matches: body
            });
        } else {
            res.send("An error occured");
        }
    })
Example #13
0
    getMainSymbol(){
      const {weatherData} = this.props;
      const data = weatherData.data;
      
      const dataTime = parseInt(moment.unix(data.dt).format('Hmm'));
      const sunRise = parseInt(moment.unix(data.sys.sunrise).format('Hmm'));
      const sunSet = parseInt(moment.unix(data.sys.sunset).format('Hmm'));

      //console.log(dataTime);
      //console.log(sunRise);
      //console.log(sunSet);

      let symbolName ='wi wi-owm-' ;
      
      const beforeSun = dataTime < sunRise;
      const inSun = dataTime > sunRise && dataTime < sunSet;
      const afterSun = dataTime > sunSet;

      switch(true){
        case beforeSun:
          symbolName += 'night-';
          break;
        case inSun:
          symbolName += 'day-';
          break;
        case afterSun: 
          symbolName += 'night-';
          break;
      }

      symbolName += data.weather[0].id;
      symbolName += ' weather-main-icon'
      return(
        <i className={symbolName}></i>
      );
    }
 var getlist = function () {
     var list = [];
     for (var i = start, j = start + limit; i < j; i++) {
         var item = data.items[i];
         if (!item) {
             break;
         }
         list.push({
             'url': qiniuConfig.qiniuBucketUrl + item.key,
             'fsize': item.fsize,
             'create_time': moment.unix(item.putTime / 1e7).format('YYYY-MM-DD HH:mm:ss')//:SSS 毫秒
         });
     }
     return list;
 }
Example #15
0
 it('should increment the value of a rolling number', () => {
   // setup:
   const now = new Date();
   const clock = sinon.useFakeTimers(now.getTime());
   const unix = moment.unix(now).valueOf();
   const spy = sandbox.spy(rolling,'removeOldBuckets');
   // when:
   rolling.getCurrentBucket();
   const bucket = rolling.increment(1);
   // then:
   expect(bucket.value).to.equal(1);
   expect(spy.callCount).to.equal(1);
   // teardown:
   clock.restore();
 });
 .then(function (data) {
     returnResult.yelpData = data;
     var time_start = data.deals[0].time_start;
     var time_start_dateformat = moment.unix(time_start).format("MM/DD/YYYY");
     returnResult.time_start_dateformat = time_start_dateformat;
     //console.log('got search result', returnResult);
     if (req.session && req.session.user) { // Check if session exists
         res.render('restaurantsearch/detail', {
             account: req.session.user,
             output: returnResult
         });
     } else {
         res.redirect('/login');
     }
 })
Example #17
0
 .map(m =>
   <div className="message-node" key={`sorted-message-${m.key}`}>
     <div className="likes-wrap">
       <p className="likes">{m.likes}</p>
     </div>
     <div className="message-text">
       {m.text.split(/[\n\r]/).map((t, i) =>
         <p key={`sorted-message-text-${m.key}-${i}`}>{t}</p>
       )}
     </div>
     <div className="message-info">
       <div>{`No.${m.key}`}</div>
       <div>{`${Math.abs(moment.unix(m.time).diff(moment(), 'minutes'))} 分前`}</div>
     </div>
   </div>
Example #18
0
    return function(req, res, next){
        var user_id = req.user._id,
            token_expires = req.user.token_expires;

        if(!token_expires || moment.unix(token_expires).isBefore(new Date())){
            console.log('token expired, refreshing')
            authHelper.refresh(user_id).then(
                token => {
                    req.user.access_token = token;
                    next();
                }, next);
        }else{
            next();
        }
    };
            function (lnkdata) {
              for (var i = 0; i < lnkdata.rows.length; i++) {
                if (lnkdata.rows[i].typ === "FILE" || lnkdata.rows[i].typ === "EIMG") {
                  var ftime = moment.unix(lnkdata.rows[i].filetimestamp);
                  lnkdata.rows[i].filetime = ftime.format("DD.MM.YYYY HH:mm:ss");
                }
              }
              data.rows[0].links = lnkdata.rows;

              //parents:
              getParents(req.session, data.rows[0].parent, [], function (parents) {
                data.rows[0].parents = parents;
                send(res, data);
              });
            });
app.get('/:timestamp', (request, response) => {
  const timestamp = request.params.timestamp;

  let result = {};

  if (moment.unix(timestamp).isValid()) {
    result = {
      unix: parseInt(timestamp, 10),
      natural: moment.unix(timestamp).format('MMMM D, YYYY'),
    };
  } else if (moment(new Date(timestamp)).isValid()) {
    result = {
      unix: moment(new Date(timestamp)).format('X'),
      natural: moment(new Date(timestamp)).format('MMMM D, YYYY'),
    };
  } else {
    result = {
      unix: null,
      natural: null,
    };
  }

  response.json(result);
});
Example #21
0
 Object.keys(statuses).forEach(function(pid) {
     var worker_json = {
         "pid" : pid,
         "cpu" : statuses[pid].curr.cpu,
         "mem" : statuses[pid].curr.mem,
         "cpu_per_req" : statuses[pid].curr.cpuperreq,
         "jiffy_per_req" : statuses[pid].curr.jiffyperreq,
         "rps" : statuses[pid].curr.rps,
         "events" : statuses[pid].curr.events,
         "open_conns" : statuses[pid].curr.oconns,
         "open_requests" : statuses[pid].curr.oreqs,
         "total_requests" : statuses[pid].curr.reqstotal,
         "kbs_out" : statuses[pid].curr.kbs_out,
         "kbs_transferred" : statuses[pid].curr.kb_trans,
         "start_time" : statuses[pid].curr.utcstart * 1000, //convert sec in millis
         "start_time_format" : moment.unix(statuses[pid].curr.utcstart).fromNow()
     };
     if (statuses[pid].curr.health_status_timestamp) {
         //convert sec in millis
         worker_json.health_status_timestamp = statuses[pid].curr.health_status_timestamp * 1000;
         worker_json.health_time_format = moment.unix(statuses[pid].curr.health_status_timestamp).fromNow();
         worker_json.health_is_down = statuses[pid].curr.health_is_down;
         worker_json.health_status_code = statuses[pid].curr.health_status_code;
         hasHealthInfo = true;
         if(!response_obj.latest_health_timestamp ||
            statuses[pid].curr.health_status_timestamp > response_obj.latest_health_timestamp) {
             response_obj.latest_health_timestamp = statuses[pid].curr.health_status_timestamp;
             response_obj.latest_health_is_down = worker_json.health_is_down;
         }
     }
     response_obj.worker.push(worker_json);
     response_obj.total_requests = response_obj.total_requests + statuses[pid].curr.reqstotal;
     response_obj.total_kbs_transferred = response_obj.total_kbs_transferred + statuses[pid].curr.kb_trans;
     response_obj.total_kbs_out = response_obj.total_kbs_out + statuses[pid].curr.kbs_out;
     response_obj.total_rps = response_obj.total_rps + statuses[pid].curr.rps;
 });
Example #22
0
 it('increment() should throw an error if given a wrong type', () => {
   // setup:
   const now = new Date();
   const clock = sinon.useFakeTimers(now.getTime());
   const unix = moment.unix(now).valueOf();
   const spy = sandbox.spy(rolling,'removeOldBuckets');
   // when:
   const bucket = rolling.getCurrentBucket();
   // then:
   expect(rolling.increment.bind('a')).to.throw('Wrong type to increment by');
   expect(bucket.value).to.equal(0);
   expect(spy.callCount).to.equal(0);
   // teardown:
   clock.restore();
 });
Example #23
0
 render() {
   const {comment} = this.props;
   const time = moment.unix(parseInt(comment.created_time)).format('hh:mm YYYY-MM-DD');
   return (
     <div className="comments clearfix">
       <div className="comments__profile-picture"><img src={comment.from.profile_picture}/></div>
       <div className="comments__content">
         <div className="comments__header">{comment.from.username} at&nbsp;
           <time>{time}</time>
         </div>
         {comment.text}
       </div>
     </div>
   )
 }
Example #24
0
function get(req, res, next) {
    if(!req.params.postId) return res.status(400).end();
    var models = req.app.get('db').models;
    var db = models.Comment;

    var query = {
        include: [{
            model: models.User,
            as: 'Author',
            foreignKey: 'AuthorId',
            attributes: ['email', 'username', 'firstname', 'lastname', 'nickname', 'shownUsername', 'usercolor']
        }],
        order: [
            ['createdAt', 'DESC']
        ],
        limit: postLimit,
        attributes: ['AuthorId', 'id', 'title', 'text', 'createdAt'],
        where: {
            'PostId': req.params.postId
        }
    };
    var countQuery = {
        where: {
            'PostId': req.params.postId
        }
    };

    if (req.query.lastEntry) {
        query.where.createdAt = countQuery.where.createdAt = {
            lt: moment.unix(parseInt(req.query.lastEntry, 10)).toDate()
        };
    }

    new sequelize.Utils.QueryChainer()
        .add(db.findAll(query))
        .add(db.count(countQuery))
        .run()
        .success(function(results){
            var rows = results[0],
                count = results[1];

            rows.forEach(function(e){
                e.dataValues.editable =  req.user.id === e.AuthorId || req.user.isAdmin;
            });
            return res.json(responseHelpers.jsonPagedResponse(rows, (count - postLimit > 0)));
        })
        .error(responseHelpers.dbErrorHandler(res));
}
Example #25
0
utils.format = function(name, value) {

  var format = "";

  switch(name) {
    case 'repotag':
      var split = value.split(':');
      format = {
        'repository': split[0],
        'tag': split[1]
      };
      break;
    case 'id':
      format = value.substring(0,12);
      break;
    case 'command':
      format = value.substring(0,16);
      break;
    case 'date':
      format = moment.unix(value).fromNow();
      break;
    case 'size':
      format = (value/1000000).toFixed(1) + ' MB';
      break;
    case 'ports':
      var ports = [];
      for (var p = 0; p < value.length; p++) {
        if (value[p].IP && value[p].PublicPort) {
          ports.push(value[p].IP + ':' + value[p].PublicPort + '->' + value[p].PrivatePort + '/' + value[p].Type);
        }
        else {
          ports.push(value[p].PrivatePort + '/' + value[p].Type);
        }
      }
      format = ports.join(',');
      break;
    case 'names':
      var names = [];
      for (p = 0; p < value.length; p++) {
        names.push(value[p].replace('/', ''));
      }
      format = names.join(',');
      break;
  }
  
  return format;

};
Example #26
0
 }), (item) => {
   item.add_time = moment.unix(item.add_time).format(YMD);
   // today
   if (moment().format(YMD) === item.add_time) {
     item.add_time = 'today';
   }
   // yesterday
   if (moment().subtract(1, 'days').format(YMD) === item.add_time) {
     item.add_time = 'yesterday';
   }
   // the day before
   if (moment().subtract(2, 'days').format(YMD) === item.add_time) {
     item.add_time = 'daybefore';
   }
   return item;
 });
Example #27
0
        res.json().then(data => {
          if (data.filter(n => n).length === 0) {
            $('.water-level').textContent = `Service indisponible`
          } else {
            const curr = data.find(elt => elt.station === station)
            $('.water-level').textContent = `${curr.meas.toFixed(1)} m³/s`
            $('.water-level-time').textContent = moment.unix(curr.time / 1000).locale('fr').fromNow()
            $('meta[property=\'stationLabel\']').content = curr.label
            $('meta[property=\'level\']').content = curr.meas
            $('time[property=\'datetime\']').setAttribute('datetime', moment().format('YYYY-MM-DD'))
            console.log(curr)

            const levelMax = $('input[property=\'levelMax\']').value
            drawLastMonth(curr.historic, levelMax)
          }
        })
Example #28
0
function updateContent(_collection) {
    var rows = [], i = 0, len = _collection.length;
    for (; i < len; i++) {
        var _i = _collection.at(i);
        rows.push(Ti.UI.createTableViewRow({
            title : _i.get("item") + " " + (_i.get("done") ? "DONE" : ""),
            id : _i.id
        }));

        Ti.API.info(JSON.stringify(_i, null, 2));

        // moment.unix(i.date_update).calendar() 
        _i.get("date_completed") && Ti.API.info("time " + moment.unix(_i.get("date_completed")).calendar());
    }
    $.todoTable.setData(rows);
};
Example #29
0
        res.json().then(data => {
          if (data.filter(n => n).length === 0) {
            $('.temperature').textContent = `Service indisponible`
            reloadMetrics(city, station)()
          } else {
            const curr = data.find(elt => elt.city === city)
            $('.temperature').textContent = `${curr.meas.temperature.toFixed(1)} °C | ${curr.meas.windSpeed.toFixed(1)} km/h`

            $('.temperature-time').textContent = moment.unix(curr.time / 1000).locale('fr').fromNow()

            $('meta[property=\'temperature\']').content = curr.meas.temperature
            $('meta[property=\'icon\']').content = curr.icon
            $('meta[property=\'summary\']').content = `${lowerCase(curr.summary)} | Humid. ${(curr.meas.humidity * 100).toFixed(0)} % | Press. ${curr.meas.pressure.toFixed(0)} hPa`
            console.log(curr)
          }
        })
/**
 * Manipulates the array of data and removes useless information and
 * convert Epoch time into a countdown from current time
 * 
 * @param array an array given by the parse method
 */
function manipulateArray(array) {
    for(var i = 0; i < array.length; i++) {
        array[i].shift();                                               /*gets rid of the first item */
        array[i][0] = array[i][0].substr(1,array[i][0].length-2);       //gets rid of quotation marks for first item
        array[i][1] = array[i][1].substr(1,array[i][1].length-2);   // gets rid of quotation marks for destination
        array[i][2] = array[i][2].substr(0,10);                     // gets rid of \r at end
        array[i][2] = moment.unix(array[i][2]).fromNow();
        if(array[i][2] === "in a few seconds") {
            array[i][2] = "due";
        } else if(array[i][2] === "in a minute") {
            array[i][2] = "1 min";
        } else {
            array[i][2] = array[i][2].substr(3,array[i][2].length-7);
        }
    }
}