Best Python code snippet using localstack_python
UserDashboard.js
Source:UserDashboard.js  
1'use strict'2const Cache = use('Cache')3const AnnotationModel = use('App/Models/Annotation')4const StringHelper = use('App/Helpers/StringHelper')5const AnnotationCommentModel = use('App/Models/AnnotationComment')6const AnnotationRateModel = use('App/Models/AnnotationRate')7const AnnotationCommentRateModel = use('App/Models/AnnotationCommentRate')8const DatabaseHelper = use('App/Helpers/DatabaseHelper')9class UserDashboard {10  register(Model) {11    12    Model.prototype.getAnnotationsInStep = async function (webpage, start_timestamp, end_timestamp) {13      let cacheKey = Cache.key(`User.getAnnotationsInStep`, start_timestamp, end_timestamp)14      15      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {16        let query = AnnotationModel17                .query()18                .with('notes')19                .where('deleted', false)20                .whereNot('type', 'SectionMainIdea')21                .where('user_id', this.primaryKeyValue)22                .where('webpage_id', webpage.primaryKeyValue)23        if (typeof(start_timestamp) === 'number') {24          query.where('created_at_unixms', '>=', start_timestamp)25        }26        if (typeof(end_timestamp) === 'number') {27          query.where('created_at_unixms', '<=', end_timestamp)28        }29        let result = await query.fetch()30        return result.toJSON()31      })32      return output33    }34    35    Model.prototype.getSectionAnnotationsInStep = async function (webpage, start_timestamp, end_timestamp) {36      let cacheKey = Cache.key(`User.getSectionAnnotationsInStep`, start_timestamp, end_timestamp)37      38      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {39        let query = AnnotationModel40                .query()41                .with('notes')42                .with('anchorPositions')43                .where('deleted', false)44                .where('type', 'SectionMainIdea')45                .where('user_id', this.primaryKeyValue)46                .where('webpage_id', webpage.primaryKeyValue)47        if (typeof(start_timestamp) === 'number') {48          query.where('created_at_unixms', '>=', start_timestamp)49        }50        if (typeof(end_timestamp) === 'number') {51          query.where('created_at_unixms', '<=', end_timestamp)52        }53        let result = await query.fetch()54        return result.toJSON()55      })56      return output57    }58    59    Model.prototype.countAnnotations = async function (webpage, start_timestamp, end_timestamp) {60      let cacheKey = Cache.key(`User.countAnnotations`, start_timestamp, end_timestamp)61      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {62        let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)63        //console.log(annotations)64        return annotations.length65      })66      return output67    }68    69    Model.prototype.countAnnotationNoteWords = async function (webpage, start_timestamp, end_timestamp) {70      let cacheKey = Cache.key(`User.countAnnotationNoteWords`, start_timestamp, end_timestamp)71      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {72        let wordCount = 073        74        let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)75        //console.log(annotations.length)76        annotations.forEach((annotation) => {77          annotation.notes.forEach((note) => {78            let noteText = note.note79            noteText = StringHelper.htmlToText(noteText, true)80            wordCount = wordCount + StringHelper.countWords(noteText)81          })82        })83        84        return wordCount85      })86      return output87    }88    89    Model.prototype.countAnnotationTypes = async function (webpage, start_timestamp, end_timestamp) {90      let cacheKey = Cache.key(`User.countAnnotationTypes`, start_timestamp, end_timestamp)91      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {92        let types = {}93        94        let annotations = await this.getAnnotationsInStep(webpage, start_timestamp, end_timestamp)95        annotations.forEach((annotation) => {96          let type = annotation.type97          98          if (typeof(types[type]) !== 'number') {99            types[type] = 0100          }101          types[type]++102        })103        104        return types105      })106      return output107    }108    109    110    Model.prototype.getSectionNotes = async function (webpage, start_timestamp, end_timestamp) {111      let cacheKey = Cache.key(`User.getSectionNotes`, start_timestamp, end_timestamp)112      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {113        let notes = []114        115        let annotations = await this.getSectionAnnotationsInStep(webpage, start_timestamp, end_timestamp)116        annotations.forEach((annotation) => {117          let sectionID = annotation.anchorPositions[0].section_id118          notes[sectionID] = annotation.notes[0].note119        })120        121        return notes122      })123      return output124    }125    126    127    // -----------------------------------------128    129    Model.prototype.getCommentsInStep = async function (webpage, start_timestamp, end_timestamp) {130      let cacheKey = Cache.key(`User.getCommentsInStep`, start_timestamp, end_timestamp)131      132      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {133        let query = AnnotationCommentModel134                .query()135                .whereHas('annotation', (builder) => {136                  builder.where('deleted', false)137                         .where('webpage_id', webpage.primaryKeyValue)138                }, '>', 0)139                .with('annotation', (builder) => {140                  builder.with('user')141                })142                .where('deleted', false)143                .where('user_id', this.primaryKeyValue)144                //.where('webpage_id', webpage.primaryKeyValue)145        if (typeof(start_timestamp) === 'number') {146          query.where('created_at_unixms', '>=', start_timestamp)147        }148        if (typeof(end_timestamp) === 'number') {149          query.where('created_at_unixms', '<=', end_timestamp)150        }151        let result = await query.fetch()152        let resultJSON = result.toJSON()153        154        resultJSON.sort((a, b) => {155          if (a.annotation.id !== b.annotation.id) {156            return a.annotation.id - b.annotation.id157          }158        })159        160        return resultJSON161      })162      return output163    }164    165    Model.prototype.getInteracts = async function (webpage, start_timestamp, end_timestamp) {166      let cacheKey = Cache.key(`User.getInteracts`, start_timestamp, end_timestamp)167      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {168        let interactTo = {}169        170        let initUser = (user) => {171          if (!interactTo[user.id]) {172            interactTo[user.id] = {173              avatar_url: user.avatar_url,174              name: user.display_name,175              count: 0,176              annotationIDList: []177            }178          }179        }180        181        // ----------------------------------------------182        183        let comments = await this.getCommentsInStep(webpage, start_timestamp, end_timestamp)184        185        let lastAnnotationID186        187        comments.forEach((comment) => {188          let annotationID = comment.annotation.id189          if (!lastAnnotationID || lastAnnotationID !== annotationID) {190            lastAnnotationID = annotationID191          }192          else {193            return false194          }195          196          //console.log(JSON.stringify(comment, null, 2))197          let user = comment.annotation.user198          199          initUser(user)200          if (interactTo[user.id].annotationIDList.indexOf(annotationID) === -1) {201            interactTo[user.id].count++202            interactTo[user.id].annotationIDList.push(annotationID)203          }204        })205        206        // ------------------------------------------207        208        let annotationRates = await this.getAnnotationRatesInStep(webpage, start_timestamp, end_timestamp)209        //console.log(annotationRates)210        annotationRates.forEach((rate) => {211          let user = rate.annotation.user212          let annotationID = rate.annotation.id213          initUser(user)214          if (interactTo[user.id].annotationIDList.indexOf(annotationID) === -1) {215            interactTo[user.id].count++216            interactTo[user.id].annotationIDList.push(annotationID)217          }218        })219        220        // ------------------------------------------221        222        let commentRates = await this.getAnnotationCommentRatesInStep(webpage, start_timestamp, end_timestamp)223        //console.log(commentRates)224        commentRates.forEach((rate) => {225          let user = rate.comment.user226          initUser(user)227          interactTo[user.id].count++228        })229        230        // ------------------------------------------231        232        return interactTo233      })234      return output235    }236    237    Model.prototype.getComments = async function (webpage, start_timestamp, end_timestamp) {238      let cacheKey = Cache.key(`User.getComments`, start_timestamp, end_timestamp)239      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {240        let commentTo = {}241        242        let comments = await this.getCommentsInStep(webpage, start_timestamp, end_timestamp)243        244        let lastAnnotationID245        246        comments.forEach((comment) => {247          let annotationID = comment.annotation.id248          if (!lastAnnotationID || annotationID !== comment.annotation.id) {249            lastAnnotationID = comment.annotation.id250          }251          else {252            return false253          }254          255          //console.log(JSON.stringify(comment, null, 2))256          let user = comment.annotation.user257          258          if (!commentTo[user.id]) {259            commentTo[user.id] = {260              avatar_url: user.avatar_url,261              name: user.display_name,262              count: 0263            }264          }265          commentTo[user.id].count++266        })267        268        return commentTo269      })270      return output271    }272    273    // -----------------------------------------274    275    Model.prototype.getCommentedInStep = async function (webpage, start_timestamp, end_timestamp) {276      let cacheKey = Cache.key(`User.getCommentedInStep`, start_timestamp, end_timestamp)277      278      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {279        let query = AnnotationCommentModel280                .query()281                .whereHas('annotation', (builder) => {282                  builder.where('deleted', false)283                         .where('user_id', this.primaryKeyValue)284                         .where('webpage_id', webpage.primaryKeyValue)285                }, '>', 0)286                //.with('annotation', (builder) => {287                  //builder.with('user')288                //})289                .with('user')290                .where('deleted', false)291                292                //.where('webpage_id', webpage.primaryKeyValue)293        if (typeof(start_timestamp) === 'number') {294          query.where('created_at_unixms', '>=', start_timestamp)295        }296        if (typeof(end_timestamp) === 'number') {297          query.where('created_at_unixms', '<=', end_timestamp)298        }299        let result = await query.fetch()300        let resultJSON = result.toJSON()301        302        resultJSON.sort((a, b) => {303          if (a.annotation.id !== b.annotation.id) {304            return a.annotation.id - b.annotation.id305          }306        })307        308        return resultJSON309      })310      return output311    }312    313    Model.prototype.getCommented = async function (webpage, start_timestamp, end_timestamp) {314      let cacheKey = Cache.key(`User.getCommented`, start_timestamp, end_timestamp)315      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {316        let output = {}317        318        let comments = await this.getCommentedInStep(webpage, start_timestamp, end_timestamp)319        comments.forEach((comment) => {320          //console.log(JSON.stringify(comment, null, 2))321          let user = comment.user322          323          if (!output[user.id]) {324            output[user.id] = {325              avatar_url: user.avatar_url,326              name: user.display_name,327              count: 0328            }329          }330          output[user.id].count++331        })332        333        return output334      })335      return output336    }337    338    // -----------------------------------------------------------------339    340    Model.prototype.getAnnotationRatesInStep = async function (webpage, start_timestamp, end_timestamp) {341      let cacheKey = Cache.key(`User.getAnnotationRatesInStep`, start_timestamp, end_timestamp)342      343      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {344        let query = AnnotationRateModel345                .query()346                .whereHas('annotation', (builder) => {347                  builder.where('deleted', false)348                         //.where('user_id', this.primaryKeyValue)349                         .where('webpage_id', webpage.primaryKeyValue)350                }, '>', 0)351                .with('annotation', (builder) => {352                  builder.with('user')353                })354                .where('user_id', this.primaryKeyValue)355                .where('deleted', false)356                //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')357                358                //.where('webpage_id', webpage.primaryKeyValue)359        let startOffset = ((new Date()).getTimezoneOffset()) * 60 * 1000360        let endOffset = startOffset361        //console.log(start_timestamp)362        if (start_timestamp < 1588077090978) {363          // å°æç¨å¼é¯èª¤ #507364          startOffset = ''365        }366        367        if (typeof(start_timestamp) === 'number') {368          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${startOffset}) >= ?`, [start_timestamp])369          //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) >= ?`, [start_timestamp])370        }371        if (typeof(end_timestamp) === 'number') {372          //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)373          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${endOffset}) <= ?`, [end_timestamp])374          //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) <= ?`, [end_timestamp])375        }376        //DatabaseHelper.consoleSQL(query)377        let result = await query.fetch()378        return result.toJSON()379      })380      return output381    }382    383    Model.prototype.getAnnotationCommentRatesInStep = async function (webpage, start_timestamp, end_timestamp) {384      let cacheKey = Cache.key(`User.getAnnotationCommentRatesInStep`, start_timestamp, end_timestamp)385      386      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {387        let query = AnnotationCommentRateModel388                .query()389                .whereHas('comment', (builder) => {390                  builder.where('deleted', false)391                         //.where('user_id', this.primaryKeyValue)392                         .whereHas('annotation', (builder) => {393                           builder.where('webpage_id', webpage.primaryKeyValue)394                                  .where('deleted', false)395                         }, '>', 0)396                }, '>', 0)397                .with('comment', (builder) => {398                  builder.with('user')399                })400                .where('user_id', this.primaryKeyValue)401                .where('deleted', false)402                //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')403                //.where('webpage_id', webpage.primaryKeyValue)404        let startOffset = ((new Date()).getTimezoneOffset()) * 60 * 1000405        let endOffset = startOffset406        //console.log(start_timestamp)407        if (start_timestamp < 1588077090978) {408          // å°æç¨å¼é¯èª¤ #507409          startOffset = ''410          //endOffset = ''411        }412        //offset = offset * -1413        //offset = '+' + offset414        //console.log(this.display_name, startOffset, endOffset)415        416        if (typeof(start_timestamp) === 'number') {417          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${startOffset} ) >= ?`, [start_timestamp])418          //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ) >= ?`, [start_timestamp])419        }420        if (typeof(end_timestamp) === 'number') {421          //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)422          423          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${endOffset}) <= ?`, [end_timestamp])424          //query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000) <= ?`, [end_timestamp])425        }426        //DatabaseHelper.consoleSQL(query)427        let result = await query.fetch()428        return result.toJSON()429      })430      return output431    }432    433    Model.prototype.getRates = async function (webpage, start_timestamp, end_timestamp) {434      let cacheKey = Cache.key(`User.getRates`, start_timestamp, end_timestamp)435      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {436        let rates437        438        let annotationRates = {}439        let commentRates = {}440        441        rates = await this.getAnnotationRatesInStep(webpage, start_timestamp, end_timestamp)442        //console.log(rates.length)443        rates.forEach((rate) => {444          //console.log(JSON.stringify(comment, null, 2))445          let type = rate.type446          let user = rate.annotation.user447          448          if (!annotationRates[type]) {449            annotationRates[type] = {}450          }451          452          //console.log(type, user.id)453          454          if (!annotationRates[type][user.id]) {455            annotationRates[type][user.id] = {456              avatar_url: user.avatar_url,457              name: user.display_name,458              count: 0459            }460          }461          annotationRates[type][user.id].count++462        })463        //console.log(JSON.stringify(annotationRates, null, 2))464        465        // --------------------------------------------------------------466        467        rates = await this.getAnnotationCommentRatesInStep(webpage, start_timestamp, end_timestamp)468        rates.forEach((rate) => {469          //console.log(JSON.stringify(comment, null, 2))470          let type = rate.type471          let user = rate.comment.user472          let userID = user.id + ''473          474          if (!commentRates[type]) {475            commentRates[type] = {}476          }477          478          //console.log(type, userID)479          if (!commentRates[type][userID]) {480            commentRates[type][userID] = {481              avatar_url: user.avatar_url,482              name: user.display_name,483              count: 0484            }485          }486          commentRates[type][userID].count++487        })488        // --------------------------------------------------------------489        490        return {491          annotation: annotationRates,492          comment: commentRates493        }494      })495      return output496    }497    498    499    // -----------------------------------------------------------------500    501    Model.prototype.getAnnotationRatedInStep = async function (webpage, start_timestamp, end_timestamp) {502      let cacheKey = Cache.key(`User.getAnnotationRatedInStep`, start_timestamp, end_timestamp)503      504      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {505        let query = AnnotationRateModel506                .query()507                .whereHas('annotation', (builder) => {508                  builder.where('deleted', false)509                         .where('user_id', this.primaryKeyValue)510                         .where('webpage_id', webpage.primaryKeyValue)511                }, '>', 0)512                //.with('annotation', (builder) => {513                //  builder.with('user')514                //})515                .with('rater')516                //.where('user_id', this.primaryKeyValue)517                .where('deleted', false)518                //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')519                520                //.where('webpage_id', webpage.primaryKeyValue)521        let offset = ((new Date()).getTimezoneOffset()) * 60 * 1000522        if (typeof(start_timestamp) === 'number') {523          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) >= ?`, [start_timestamp])524        }525        if (typeof(end_timestamp) === 'number') {526          //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)527          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) <= ?`, [end_timestamp])528        }529        //DatabaseHelper.consoleSQL(query)530        let result = await query.fetch()531        return result.toJSON()532      })533      return output534    }535    536    Model.prototype.getAnnotationCommentRatedInStep = async function (webpage, start_timestamp, end_timestamp) {537      let cacheKey = Cache.key(`User.getAnnotationCommentRatedInStep`, start_timestamp, end_timestamp)538      539      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {540        let query = AnnotationCommentRateModel541                .query()542                .whereHas('comment', (builder) => {543                  builder.where('deleted', false)544                         .where('user_id', this.primaryKeyValue)545                         .whereHas('annotation', (builder) => {546                           builder.where('webpage_id', webpage.primaryKeyValue)547                         }, '>', 0)548                }, '>', 0)549                //.with('comment', (builder) => {550                //  builder.with('user')551                //})552                .where('user_id', this.primaryKeyValue)553                .with('user')554                .where('deleted', false)555                //.select('EXTRACT(EPOCH FROM created_at) as created_at_unixms')556                //.where('webpage_id', webpage.primaryKeyValue)557        let offset = ((new Date()).getTimezoneOffset()) * 60 * 1000558        if (typeof(start_timestamp) === 'number') {559          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) >= ?`, [start_timestamp])560        }561        if (typeof(end_timestamp) === 'number') {562          //query.where('EXTRACT(EPOCH FROM created_at)', '<=', end_timestamp)563          query.whereRaw(`(EXTRACT(EPOCH FROM created_at) * 1000 ${offset}) <= ?`, [end_timestamp])564        }565        let result = await query.fetch()566        return result.toJSON()567      })568      return output569    }570    571    Model.prototype.getRated = async function (webpage, start_timestamp, end_timestamp) {572      let cacheKey = Cache.key(`User.getRated`, start_timestamp, end_timestamp)573      let output = await Cache.rememberWait([webpage, this, 'User'], cacheKey, async () => {574        let rates575        576        let annotationRates = {}577        let commentRates = {}578        579        rates = await this.getAnnotationRatedInStep(webpage, start_timestamp, end_timestamp)580        //console.log(rates.length)581        rates.forEach((rate) => {582          //console.log(JSON.stringify(comment, null, 2))583          let type = rate.type584          let user = rate.rater585          586          if (!annotationRates[type]) {587            annotationRates[type] = {}588          }589          590          //console.log(type, user.id)591          592          if (!annotationRates[type][user.id]) {593            annotationRates[type][user.id] = {594              avatar_url: user.avatar_url,595              name: user.display_name,596              count: 0597            }598          }599          annotationRates[type][user.id].count++600        })601        //console.log(JSON.stringify(annotationRates, null, 2))602        603        // --------------------------------------------------------------604        605        rates = await this.getAnnotationCommentRatedInStep(webpage, start_timestamp, end_timestamp)606        rates.forEach((rate) => {607          //console.log(JSON.stringify(comment, null, 2))608          let type = rate.type609          let user = rate.user610          611          if (!commentRates[type]) {612            commentRates[type] = {}613          }614          615          if (!commentRates[type][user.id]) {616            commentRates[type][user.id] = {617              avatar_url: user.avatar_url,618              name: user.display_name,619              count: 0620            }621          }622          commentRates[type][user.id].count++623        })624        // --------------------------------------------------------------625        626        return {627          annotation: annotationRates,628          comment: commentRates629        }630      })631      return output632    }633    634  } // register (Model) {635}...timestamp.js
Source:timestamp.js  
1// Licensed under the Apache License, Version 2.0 (the "License");2// you may not use this file except in compliance with the License.3// You may obtain a copy of the License at4//5//     http://www.apache.org/licenses/LICENSE-2.06//7// Unless required by applicable law or agreed to in writing, software8// distributed under the License is distributed on an "AS IS" BASIS,9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10// See the License for the specific language governing permissions and11// limitations under the License.12//13// Copyright 2009 Google Inc. All Rights Reserved14/**15 * This type is for INTERNAL use in MongoDB only and should not be used in applications.16 * The appropriate corresponding type is the JavaScript Date type.17 * 18 * Defines a Timestamp class for representing a 64-bit two's-complement19 * integer value, which faithfully simulates the behavior of a Java "Timestamp". This20 * implementation is derived from TimestampLib in GWT.21 *22 * Constructs a 64-bit two's-complement integer, given its low and high 32-bit23 * values as *signed* integers.  See the from* functions below for more24 * convenient ways of constructing Timestamps.25 *26 * The internal representation of a Timestamp is the two given signed, 32-bit values.27 * We use 32-bit pieces because these are the size of integers on which28 * Javascript performs bit-operations.  For operations like addition and29 * multiplication, we split each number into 16-bit pieces, which can easily be30 * multiplied within Javascript's floating-point representation without overflow31 * or change in sign.32 *33 * In the algorithms below, we frequently reduce the negative case to the34 * positive case by negating the input(s) and then post-processing the result.35 * Note that we must ALWAYS check specially whether those values are MIN_VALUE36 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as37 * a positive number, it overflows back into a negative).  Not handling this38 * case would often result in infinite recursion.39 *40 * @class41 * @param {number} low  the low (signed) 32 bits of the Timestamp.42 * @param {number} high the high (signed) 32 bits of the Timestamp.43 */44function Timestamp(low, high) {45  if (!(this instanceof Timestamp)) return new Timestamp(low, high);46  this._bsontype = 'Timestamp';47  /**48   * @type {number}49   * @ignore50   */51  this.low_ = low | 0; // force into 32 signed bits.52  /**53   * @type {number}54   * @ignore55   */56  this.high_ = high | 0; // force into 32 signed bits.57}58/**59 * Return the int value.60 *61 * @return {number} the value, assuming it is a 32-bit integer.62 */63Timestamp.prototype.toInt = function() {64  return this.low_;65};66/**67 * Return the Number value.68 *69 * @method70 * @return {number} the closest floating-point representation to this value.71 */72Timestamp.prototype.toNumber = function() {73  return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned();74};75/**76 * Return the JSON value.77 *78 * @method79 * @return {string} the JSON representation.80 */81Timestamp.prototype.toJSON = function() {82  return this.toString();83};84/**85 * Return the String value.86 *87 * @method88 * @param {number} [opt_radix] the radix in which the text should be written.89 * @return {string} the textual representation of this value.90 */91Timestamp.prototype.toString = function(opt_radix) {92  var radix = opt_radix || 10;93  if (radix < 2 || 36 < radix) {94    throw Error('radix out of range: ' + radix);95  }96  if (this.isZero()) {97    return '0';98  }99  if (this.isNegative()) {100    if (this.equals(Timestamp.MIN_VALUE)) {101      // We need to change the Timestamp value before it can be negated, so we remove102      // the bottom-most digit in this base and then recurse to do the rest.103      var radixTimestamp = Timestamp.fromNumber(radix);104      var div = this.div(radixTimestamp);105      var rem = div.multiply(radixTimestamp).subtract(this);106      return div.toString(radix) + rem.toInt().toString(radix);107    } else {108      return '-' + this.negate().toString(radix);109    }110  }111  // Do several (6) digits each time through the loop, so as to112  // minimize the calls to the very expensive emulated div.113  var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));114  rem = this;115  var result = '';116  while (!rem.isZero()) {117    var remDiv = rem.div(radixToPower);118    var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();119    var digits = intval.toString(radix);120    rem = remDiv;121    if (rem.isZero()) {122      return digits + result;123    } else {124      while (digits.length < 6) {125        digits = '0' + digits;126      }127      result = '' + digits + result;128    }129  }130};131/**132 * Return the high 32-bits value.133 *134 * @method135 * @return {number} the high 32-bits as a signed value.136 */137Timestamp.prototype.getHighBits = function() {138  return this.high_;139};140/**141 * Return the low 32-bits value.142 *143 * @method144 * @return {number} the low 32-bits as a signed value.145 */146Timestamp.prototype.getLowBits = function() {147  return this.low_;148};149/**150 * Return the low unsigned 32-bits value.151 *152 * @method153 * @return {number} the low 32-bits as an unsigned value.154 */155Timestamp.prototype.getLowBitsUnsigned = function() {156  return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;157};158/**159 * Returns the number of bits needed to represent the absolute value of this Timestamp.160 *161 * @method162 * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp.163 */164Timestamp.prototype.getNumBitsAbs = function() {165  if (this.isNegative()) {166    if (this.equals(Timestamp.MIN_VALUE)) {167      return 64;168    } else {169      return this.negate().getNumBitsAbs();170    }171  } else {172    var val = this.high_ !== 0 ? this.high_ : this.low_;173    for (var bit = 31; bit > 0; bit--) {174      if ((val & (1 << bit)) !== 0) {175        break;176      }177    }178    return this.high_ !== 0 ? bit + 33 : bit + 1;179  }180};181/**182 * Return whether this value is zero.183 *184 * @method185 * @return {boolean} whether this value is zero.186 */187Timestamp.prototype.isZero = function() {188  return this.high_ === 0 && this.low_ === 0;189};190/**191 * Return whether this value is negative.192 *193 * @method194 * @return {boolean} whether this value is negative.195 */196Timestamp.prototype.isNegative = function() {197  return this.high_ < 0;198};199/**200 * Return whether this value is odd.201 *202 * @method203 * @return {boolean} whether this value is odd.204 */205Timestamp.prototype.isOdd = function() {206  return (this.low_ & 1) === 1;207};208/**209 * Return whether this Timestamp equals the other210 *211 * @method212 * @param {Timestamp} other Timestamp to compare against.213 * @return {boolean} whether this Timestamp equals the other214 */215Timestamp.prototype.equals = function(other) {216  return this.high_ === other.high_ && this.low_ === other.low_;217};218/**219 * Return whether this Timestamp does not equal the other.220 *221 * @method222 * @param {Timestamp} other Timestamp to compare against.223 * @return {boolean} whether this Timestamp does not equal the other.224 */225Timestamp.prototype.notEquals = function(other) {226  return this.high_ !== other.high_ || this.low_ !== other.low_;227};228/**229 * Return whether this Timestamp is less than the other.230 *231 * @method232 * @param {Timestamp} other Timestamp to compare against.233 * @return {boolean} whether this Timestamp is less than the other.234 */235Timestamp.prototype.lessThan = function(other) {236  return this.compare(other) < 0;237};238/**239 * Return whether this Timestamp is less than or equal to the other.240 *241 * @method242 * @param {Timestamp} other Timestamp to compare against.243 * @return {boolean} whether this Timestamp is less than or equal to the other.244 */245Timestamp.prototype.lessThanOrEqual = function(other) {246  return this.compare(other) <= 0;247};248/**249 * Return whether this Timestamp is greater than the other.250 *251 * @method252 * @param {Timestamp} other Timestamp to compare against.253 * @return {boolean} whether this Timestamp is greater than the other.254 */255Timestamp.prototype.greaterThan = function(other) {256  return this.compare(other) > 0;257};258/**259 * Return whether this Timestamp is greater than or equal to the other.260 *261 * @method262 * @param {Timestamp} other Timestamp to compare against.263 * @return {boolean} whether this Timestamp is greater than or equal to the other.264 */265Timestamp.prototype.greaterThanOrEqual = function(other) {266  return this.compare(other) >= 0;267};268/**269 * Compares this Timestamp with the given one.270 *271 * @method272 * @param {Timestamp} other Timestamp to compare against.273 * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.274 */275Timestamp.prototype.compare = function(other) {276  if (this.equals(other)) {277    return 0;278  }279  var thisNeg = this.isNegative();280  var otherNeg = other.isNegative();281  if (thisNeg && !otherNeg) {282    return -1;283  }284  if (!thisNeg && otherNeg) {285    return 1;286  }287  // at this point, the signs are the same, so subtraction will not overflow288  if (this.subtract(other).isNegative()) {289    return -1;290  } else {291    return 1;292  }293};294/**295 * The negation of this value.296 *297 * @method298 * @return {Timestamp} the negation of this value.299 */300Timestamp.prototype.negate = function() {301  if (this.equals(Timestamp.MIN_VALUE)) {302    return Timestamp.MIN_VALUE;303  } else {304    return this.not().add(Timestamp.ONE);305  }306};307/**308 * Returns the sum of this and the given Timestamp.309 *310 * @method311 * @param {Timestamp} other Timestamp to add to this one.312 * @return {Timestamp} the sum of this and the given Timestamp.313 */314Timestamp.prototype.add = function(other) {315  // Divide each number into 4 chunks of 16 bits, and then sum the chunks.316  var a48 = this.high_ >>> 16;317  var a32 = this.high_ & 0xffff;318  var a16 = this.low_ >>> 16;319  var a00 = this.low_ & 0xffff;320  var b48 = other.high_ >>> 16;321  var b32 = other.high_ & 0xffff;322  var b16 = other.low_ >>> 16;323  var b00 = other.low_ & 0xffff;324  var c48 = 0,325    c32 = 0,326    c16 = 0,327    c00 = 0;328  c00 += a00 + b00;329  c16 += c00 >>> 16;330  c00 &= 0xffff;331  c16 += a16 + b16;332  c32 += c16 >>> 16;333  c16 &= 0xffff;334  c32 += a32 + b32;335  c48 += c32 >>> 16;336  c32 &= 0xffff;337  c48 += a48 + b48;338  c48 &= 0xffff;339  return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);340};341/**342 * Returns the difference of this and the given Timestamp.343 *344 * @method345 * @param {Timestamp} other Timestamp to subtract from this.346 * @return {Timestamp} the difference of this and the given Timestamp.347 */348Timestamp.prototype.subtract = function(other) {349  return this.add(other.negate());350};351/**352 * Returns the product of this and the given Timestamp.353 *354 * @method355 * @param {Timestamp} other Timestamp to multiply with this.356 * @return {Timestamp} the product of this and the other.357 */358Timestamp.prototype.multiply = function(other) {359  if (this.isZero()) {360    return Timestamp.ZERO;361  } else if (other.isZero()) {362    return Timestamp.ZERO;363  }364  if (this.equals(Timestamp.MIN_VALUE)) {365    return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;366  } else if (other.equals(Timestamp.MIN_VALUE)) {367    return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;368  }369  if (this.isNegative()) {370    if (other.isNegative()) {371      return this.negate().multiply(other.negate());372    } else {373      return this.negate()374        .multiply(other)375        .negate();376    }377  } else if (other.isNegative()) {378    return this.multiply(other.negate()).negate();379  }380  // If both Timestamps are small, use float multiplication381  if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) {382    return Timestamp.fromNumber(this.toNumber() * other.toNumber());383  }384  // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.385  // We can skip products that would overflow.386  var a48 = this.high_ >>> 16;387  var a32 = this.high_ & 0xffff;388  var a16 = this.low_ >>> 16;389  var a00 = this.low_ & 0xffff;390  var b48 = other.high_ >>> 16;391  var b32 = other.high_ & 0xffff;392  var b16 = other.low_ >>> 16;393  var b00 = other.low_ & 0xffff;394  var c48 = 0,395    c32 = 0,396    c16 = 0,397    c00 = 0;398  c00 += a00 * b00;399  c16 += c00 >>> 16;400  c00 &= 0xffff;401  c16 += a16 * b00;402  c32 += c16 >>> 16;403  c16 &= 0xffff;404  c16 += a00 * b16;405  c32 += c16 >>> 16;406  c16 &= 0xffff;407  c32 += a32 * b00;408  c48 += c32 >>> 16;409  c32 &= 0xffff;410  c32 += a16 * b16;411  c48 += c32 >>> 16;412  c32 &= 0xffff;413  c32 += a00 * b32;414  c48 += c32 >>> 16;415  c32 &= 0xffff;416  c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;417  c48 &= 0xffff;418  return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);419};420/**421 * Returns this Timestamp divided by the given one.422 *423 * @method424 * @param {Timestamp} other Timestamp by which to divide.425 * @return {Timestamp} this Timestamp divided by the given one.426 */427Timestamp.prototype.div = function(other) {428  if (other.isZero()) {429    throw Error('division by zero');430  } else if (this.isZero()) {431    return Timestamp.ZERO;432  }433  if (this.equals(Timestamp.MIN_VALUE)) {434    if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) {435      return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE436    } else if (other.equals(Timestamp.MIN_VALUE)) {437      return Timestamp.ONE;438    } else {439      // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.440      var halfThis = this.shiftRight(1);441      var approx = halfThis.div(other).shiftLeft(1);442      if (approx.equals(Timestamp.ZERO)) {443        return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;444      } else {445        var rem = this.subtract(other.multiply(approx));446        var result = approx.add(rem.div(other));447        return result;448      }449    }450  } else if (other.equals(Timestamp.MIN_VALUE)) {451    return Timestamp.ZERO;452  }453  if (this.isNegative()) {454    if (other.isNegative()) {455      return this.negate().div(other.negate());456    } else {457      return this.negate()458        .div(other)459        .negate();460    }461  } else if (other.isNegative()) {462    return this.div(other.negate()).negate();463  }464  // Repeat the following until the remainder is less than other:  find a465  // floating-point that approximates remainder / other *from below*, add this466  // into the result, and subtract it from the remainder.  It is critical that467  // the approximate value is less than or equal to the real value so that the468  // remainder never becomes negative.469  var res = Timestamp.ZERO;470  rem = this;471  while (rem.greaterThanOrEqual(other)) {472    // Approximate the result of division. This may be a little greater or473    // smaller than the actual value.474    approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));475    // We will tweak the approximate result by changing it in the 48-th digit or476    // the smallest non-fractional digit, whichever is larger.477    var log2 = Math.ceil(Math.log(approx) / Math.LN2);478    var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);479    // Decrease the approximation until it is smaller than the remainder.  Note480    // that if it is too large, the product overflows and is negative.481    var approxRes = Timestamp.fromNumber(approx);482    var approxRem = approxRes.multiply(other);483    while (approxRem.isNegative() || approxRem.greaterThan(rem)) {484      approx -= delta;485      approxRes = Timestamp.fromNumber(approx);486      approxRem = approxRes.multiply(other);487    }488    // We know the answer can't be zero... and actually, zero would cause489    // infinite recursion since we would make no progress.490    if (approxRes.isZero()) {491      approxRes = Timestamp.ONE;492    }493    res = res.add(approxRes);494    rem = rem.subtract(approxRem);495  }496  return res;497};498/**499 * Returns this Timestamp modulo the given one.500 *501 * @method502 * @param {Timestamp} other Timestamp by which to mod.503 * @return {Timestamp} this Timestamp modulo the given one.504 */505Timestamp.prototype.modulo = function(other) {506  return this.subtract(this.div(other).multiply(other));507};508/**509 * The bitwise-NOT of this value.510 *511 * @method512 * @return {Timestamp} the bitwise-NOT of this value.513 */514Timestamp.prototype.not = function() {515  return Timestamp.fromBits(~this.low_, ~this.high_);516};517/**518 * Returns the bitwise-AND of this Timestamp and the given one.519 *520 * @method521 * @param {Timestamp} other the Timestamp with which to AND.522 * @return {Timestamp} the bitwise-AND of this and the other.523 */524Timestamp.prototype.and = function(other) {525  return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);526};527/**528 * Returns the bitwise-OR of this Timestamp and the given one.529 *530 * @method531 * @param {Timestamp} other the Timestamp with which to OR.532 * @return {Timestamp} the bitwise-OR of this and the other.533 */534Timestamp.prototype.or = function(other) {535  return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);536};537/**538 * Returns the bitwise-XOR of this Timestamp and the given one.539 *540 * @method541 * @param {Timestamp} other the Timestamp with which to XOR.542 * @return {Timestamp} the bitwise-XOR of this and the other.543 */544Timestamp.prototype.xor = function(other) {545  return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);546};547/**548 * Returns this Timestamp with bits shifted to the left by the given amount.549 *550 * @method551 * @param {number} numBits the number of bits by which to shift.552 * @return {Timestamp} this shifted to the left by the given amount.553 */554Timestamp.prototype.shiftLeft = function(numBits) {555  numBits &= 63;556  if (numBits === 0) {557    return this;558  } else {559    var low = this.low_;560    if (numBits < 32) {561      var high = this.high_;562      return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits)));563    } else {564      return Timestamp.fromBits(0, low << (numBits - 32));565    }566  }567};568/**569 * Returns this Timestamp with bits shifted to the right by the given amount.570 *571 * @method572 * @param {number} numBits the number of bits by which to shift.573 * @return {Timestamp} this shifted to the right by the given amount.574 */575Timestamp.prototype.shiftRight = function(numBits) {576  numBits &= 63;577  if (numBits === 0) {578    return this;579  } else {580    var high = this.high_;581    if (numBits < 32) {582      var low = this.low_;583      return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits);584    } else {585      return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1);586    }587  }588};589/**590 * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.591 *592 * @method593 * @param {number} numBits the number of bits by which to shift.594 * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.595 */596Timestamp.prototype.shiftRightUnsigned = function(numBits) {597  numBits &= 63;598  if (numBits === 0) {599    return this;600  } else {601    var high = this.high_;602    if (numBits < 32) {603      var low = this.low_;604      return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits);605    } else if (numBits === 32) {606      return Timestamp.fromBits(high, 0);607    } else {608      return Timestamp.fromBits(high >>> (numBits - 32), 0);609    }610  }611};612/**613 * Returns a Timestamp representing the given (32-bit) integer value.614 *615 * @method616 * @param {number} value the 32-bit integer in question.617 * @return {Timestamp} the corresponding Timestamp value.618 */619Timestamp.fromInt = function(value) {620  if (-128 <= value && value < 128) {621    var cachedObj = Timestamp.INT_CACHE_[value];622    if (cachedObj) {623      return cachedObj;624    }625  }626  var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);627  if (-128 <= value && value < 128) {628    Timestamp.INT_CACHE_[value] = obj;629  }630  return obj;631};632/**633 * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.634 *635 * @method636 * @param {number} value the number in question.637 * @return {Timestamp} the corresponding Timestamp value.638 */639Timestamp.fromNumber = function(value) {640  if (isNaN(value) || !isFinite(value)) {641    return Timestamp.ZERO;642  } else if (value <= -Timestamp.TWO_PWR_63_DBL_) {643    return Timestamp.MIN_VALUE;644  } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {645    return Timestamp.MAX_VALUE;646  } else if (value < 0) {647    return Timestamp.fromNumber(-value).negate();648  } else {649    return new Timestamp(650      (value % Timestamp.TWO_PWR_32_DBL_) | 0,651      (value / Timestamp.TWO_PWR_32_DBL_) | 0652    );653  }654};655/**656 * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.657 *658 * @method659 * @param {number} lowBits the low 32-bits.660 * @param {number} highBits the high 32-bits.661 * @return {Timestamp} the corresponding Timestamp value.662 */663Timestamp.fromBits = function(lowBits, highBits) {664  return new Timestamp(lowBits, highBits);665};666/**667 * Returns a Timestamp representation of the given string, written using the given radix.668 *669 * @method670 * @param {string} str the textual representation of the Timestamp.671 * @param {number} opt_radix the radix in which the text is written.672 * @return {Timestamp} the corresponding Timestamp value.673 */674Timestamp.fromString = function(str, opt_radix) {675  if (str.length === 0) {676    throw Error('number format error: empty string');677  }678  var radix = opt_radix || 10;679  if (radix < 2 || 36 < radix) {680    throw Error('radix out of range: ' + radix);681  }682  if (str.charAt(0) === '-') {683    return Timestamp.fromString(str.substring(1), radix).negate();684  } else if (str.indexOf('-') >= 0) {685    throw Error('number format error: interior "-" character: ' + str);686  }687  // Do several (8) digits each time through the loop, so as to688  // minimize the calls to the very expensive emulated div.689  var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));690  var result = Timestamp.ZERO;691  for (var i = 0; i < str.length; i += 8) {692    var size = Math.min(8, str.length - i);693    var value = parseInt(str.substring(i, i + size), radix);694    if (size < 8) {695      var power = Timestamp.fromNumber(Math.pow(radix, size));696      result = result.multiply(power).add(Timestamp.fromNumber(value));697    } else {698      result = result.multiply(radixToPower);699      result = result.add(Timestamp.fromNumber(value));700    }701  }702  return result;703};704// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the705// from* methods on which they depend.706/**707 * A cache of the Timestamp representations of small integer values.708 * @type {Object}709 * @ignore710 */711Timestamp.INT_CACHE_ = {};712// NOTE: the compiler should inline these constant values below and then remove713// these variables, so there should be no runtime penalty for these.714/**715 * Number used repeated below in calculations.  This must appear before the716 * first call to any from* function below.717 * @type {number}718 * @ignore719 */720Timestamp.TWO_PWR_16_DBL_ = 1 << 16;721/**722 * @type {number}723 * @ignore724 */725Timestamp.TWO_PWR_24_DBL_ = 1 << 24;726/**727 * @type {number}728 * @ignore729 */730Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;731/**732 * @type {number}733 * @ignore734 */735Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;736/**737 * @type {number}738 * @ignore739 */740Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;741/**742 * @type {number}743 * @ignore744 */745Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;746/**747 * @type {number}748 * @ignore749 */750Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;751/** @type {Timestamp} */752Timestamp.ZERO = Timestamp.fromInt(0);753/** @type {Timestamp} */754Timestamp.ONE = Timestamp.fromInt(1);755/** @type {Timestamp} */756Timestamp.NEG_ONE = Timestamp.fromInt(-1);757/** @type {Timestamp} */758Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0);759/** @type {Timestamp} */760Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);761/**762 * @type {Timestamp}763 * @ignore764 */765Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);766/**767 * Expose.768 */769module.exports = Timestamp;...TimestampForm.js
Source:TimestampForm.js  
1import React, { Fragment } from 'react';2import { Form as FinalForm, Field } from 'react-final-form';3import { Button, Form, Header, Search } from 'semantic-ui-react';4import TextInput from '../../app/common/form/TextInput';5import { FORM_ERROR } from 'final-form';6import { formatDateTime, reverseFormatDateTime } from '../../app/common/util';7import { combineValidators, isRequired } from 'revalidate';8import ErrorMessage from '../../app/common/form/ErrorMessage';9import DateTimeCustomInput from '../../app/common/form/DateTimeCustomInput';10import { Timestamps, Jobsites } from '../../app/api/agent';11import { useModalDispatch } from '../../app/context/modal/modalContext';12import { useAlertDispatch } from '../../app/context/alerts/alertContext';13import { setAlert } from '../../app/context/alerts/alertActions';14import { useTimestampDispatch } from '../../app/context/timestamps/timestampContext';15const validate = combineValidators({16  username: isRequired('Username'),17  moniker: isRequired('Moniker'),18  clockedInStamp: isRequired('Clocked In Time'),19  clockedOutStamp: isRequired('Clocked Out Time'),20});21// modal - form used to add/edit a timestamp22//if editTimestamp is true, will load form with data and prevent changing jobsite23const TimestampForm = ({ username, editTimestamp = false }) => {24  const modalDispatch = useModalDispatch();25  const alertDispatch = useAlertDispatch();26  const timestampDispatch = useTimestampDispatch();27  const pageSize = 10;28  const [timestamp, setTimestamp] = React.useState({29    username: username,30    moniker: '',31    clockedInStamp: '',32    clockedOutStamp: '',33  });34  React.useEffect(() => {35    if (editTimestamp) {36      setTimestamp({37        username: username,38        moniker: editTimestamp.moniker,39        clockedInStamp: reverseFormatDateTime(editTimestamp.clockedInStamp),40        clockedOutStamp: reverseFormatDateTime(editTimestamp.clockedOutStamp),41      });42      setSelectionValue(editTimestamp.moniker);43    }44  }, [editTimestamp, username]);45  const handleFinalFormSubmit = async (values) => {46    try {47      //format values into a timestamp48      const timestamp = {49        username: values.username,50        moniker: values.moniker,51        clockedInStamp: formatDateTime(values.clockedInStamp),52        clockedOutStamp: formatDateTime(values.clockedOutStamp),53      };54      //editing timestamp requires only two fields55      if (editTimestamp) {56        const clockedStamps = {57          clockedInStamp: timestamp.clockedInStamp,58          clockedOutStamp: timestamp.clockedOutStamp,59        };60        await Timestamps.editTimestamp(61          editTimestamp.timestampId,62          clockedStamps63        );64        modalDispatch({ type: 'CLOSE_MODAL' });65        timestampDispatch({ type: 'REFRESH' });66        setAlert(alertDispatch, `Timestamp Updated`, 'update');67      } else {68        await Timestamps.addTimestamp(timestamp);69        modalDispatch({ type: 'CLOSE_MODAL' });70        timestampDispatch({ type: 'REFRESH' });71        setAlert(alertDispatch, `New Timestamp added`, 'success');72      }73    } catch (error) {74      return { [FORM_ERROR]: error };75    }76  };77  //Ccode here supports the job search bar component----------------78  const [results, setResults] = React.useState([]);79  const [loading, setLoading] = React.useState(false);80  const [selectionValue, setSelectionValue] = React.useState('');81  const handleSearchChange = async (e, { value }) => {82    setSelectionValue(value);83    setLoading(true);84    let searchResults = await Jobsites.listJobsites(value, pageSize, 1);85    searchResults = searchResults.data;86    let newResults = [];87    searchResults.forEach((jobsite) => {88      newResults.push({89        title: jobsite.moniker,90        description: `${jobsite.name} - ${jobsite.location.cityTown}`,91      });92    });93    setLoading(false);94    setResults(newResults);95  };96  const handleResultSelect = (e, { result }) => {97    setSelectionValue(result.title);98    setTimestamp({ ...timestamp, moniker: result.title });99  };100  // end of job search bar component -----------------------------101  return (102    <Fragment>103      <FinalForm104        onSubmit={handleFinalFormSubmit}105        validate={validate}106        initialValues={timestamp}107        render={({108          handleSubmit,109          submitting,110          submitError,111          invalid,112          pristine,113          dirtySinceLastSubmit,114          form,115        }) => (116          <Form onSubmit={handleSubmit} error>117            <Header118              as='h2'119              content={editTimestamp ? 'Edit Timestamp' : 'Add Timestamp'}120              color='teal'121              textAlign='center'122            />123            <Field124              name='username'125              component={TextInput}126              placeholder='Username'127              value={timestamp.username}128              disabled129            />130            {!editTimestamp && pristine && (131              <p style={{ fontStyle: 'italic', color: 'red' }}>132                Choose a jobsite first133              </p>134            )}135            <Search136              placeholder='Search jobsites...'137              loading={loading}138              onResultSelect={handleResultSelect}139              onSearchChange={handleSearchChange}140              results={results}141              value={selectionValue}142              disabled={editTimestamp ? true : false}143            />144            <Field145              name='moniker'146              component={TextInput}147              placeholder='Moniker'148              value={timestamp.moniker}149              style={{ display: 'none' }}150            />151            <Field152              name='clockedInStamp'153              value={timestamp.clockedInStamp}154              component={DateTimeCustomInput}155              placeholder='Clocked In Time'156              dateFormat='MM-DD-YYYY'157              clearable158              closable159            />160            <Field161              name='clockedOutStamp'162              value={timestamp.clockedOutStamp}163              component={DateTimeCustomInput}164              placeholder='Clocked Out Time'165              dateFormat='MM-DD-YYYY'166              clearable167              closable168            />169            {submitError && !dirtySinceLastSubmit && (170              <ErrorMessage error={submitError} />171            )}172            <Button173              disabled={(invalid && !dirtySinceLastSubmit) || pristine}174              loading={submitting}175              color='teal'176              content='Submit'177              fluid178            />179            {/* <pre>{JSON.stringify(form.getState(), null, 2)}</pre> */}180          </Form>181        )}182      />183    </Fragment>184  );185};...App.js
Source:App.js  
...45  }46  insert_continue=(tx,event,lat1,long1,speed,bearing,timestamp,event_row)=>{47    tx.executeSql("Insert into Events "+event_query+" values('"+event+"',"+event_row.curr_timestamp+","+timestamp+",'"+event_row.curr_lat+"','"+lat1+"','"+event_row.curr_long+"','"+long1+"',"+event_row.curr_bearing+","+bearing+","+event_row.curr_speed+","+speed+");")48  }49  //insert event in non continious timestamp(next.current_timestamp == next.previous_timestamp)50  insert_new=(activity,timestamp,event_row,tx)=>{51    console.log("Incerting new")52    tx.executeSql("Insert into Events (activity,prev_timestamp,curr_timestamp,confidence) values('"+activity.type+"',"+timestamp+","+timestamp+","+activity.confidence+");")53  }54  componentDidMount(){55    //this.getLocation()56  }57  //extend the event58  update=(activity,timestamp,event_row,tx)=>{59    tx.executeSql("UPDATE Events set "+60                "activity ='"+activity.type+ "',"+61                "curr_timestamp ="+timestamp+ ","+62                "confidence ="+activity.confidence +63                " where id ="+event_row.id);...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
