<commit_before>  //pass an array of keys to delete
  function _deleteFilesWithKey(objKey){

    try{
      AWS.config.update({
             accessKeyId: Meteor.settings.AWSAccessKeyId,
             secretAccessKey: Meteor.settings.AWSSecretAccessKey
          });

      var s3 = new AWS.S3();

      if(typeof objKey === "string"){
        objKey = [objKey];
      }

      for(var i =0; i< objKey.length; i++){
        var params = {
            Bucket: Meteor.settings.AWSBucket,
            Key : objKey[i]
          };

        //var deleteObject = Meteor.wrapAsync(s3.deleteObject , params,);

        s3.deleteObject(params, Meteor.bindEnvironment(
            function(err, data){
                if(err)
                    console.log(error);
                else
                  console.log("success");
            },
            function(e){
                //bind failure
                console.log(e);
            }
        ));
        //);

        //deleteObject(params);
      }

      //deleteObject(params);
    } catch( exception ) {
      console.log(exception);
      //return exception;
    }

  }

  Meteor.methods({
  /*cleanKey : function(key){
    return key.replace(/\+/g, " ").split(".")[-2];
  },*/
  storeUrlInDatabase: function( data) {
    //check( data.url, String );
    //check( data.name, String );
    //check( data.size, Number );
    //Modules.both.checkUrlValidity( data.filepath );

    /*if(data.type==="video" && data.key!==null){
      console.log(data.key);
        data.key =
    }*/

    try {
      var fileID = Files.insert({
        filepath: data.filepath,
        userId: Meteor.userId(),
        added: new Date(),
        name: data.name,
        size: data.size,
        key: data.key,
        resourceID: data.id,
        type: data.type,
        noShow: true,
      });

      if(data.type==="video" && data.key!==null){
        var callback = {finished:function(){
            Files.update({key:data.key},{$set:{noShow:false}})
          }
        };
        Meteor.call('videoEncoder', data.key, callback);
    }

      var result = Files.findOne({_id: fileID});

      return result;

    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  },
  nameFiles: function(firstKey){
    if(firstKey!==null){
      var key = firstKey;
      var breakIndex = key.lastIndexOf(".");
      var shortKey = key.substring(0, breakIndex);
      var end = key.substring(breakIndex);
      var count = 0;
      while(!!Files.findOne({key: key})){
        count++;
        key = shortKey+" ("+count+")"+end;
        if(count>300){
          break;
        }
      }
    }
    return key;
  },
  deleteS3File: function( id ) {
    check( id, String );

    try {

        var key = Files.findOne({_id: id}).key;
        var type = Files.findOne({_id: id}).type;

        Files.remove({_id: id});
        //if not just a link
        if(key){

          var objKey = [];
          if(type==="video"){
            var shortKey = key.substring(0, key.lastIndexOf("."));
            objKey.push(shortKey+".webm");
            objKey.push(shortKey+".mp4");
            objKey.push(+shortKey.replace("video/","video/thumbnails/")+"-00001.png");
          }
          else{
            objKey.push(key);
          }

          //Meteor.call("_deleteFilesWithKey",objKey);

          _deleteFilesWithKey(objKey);
        }

      //then delete from s3
    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  },

  getBucket: function(){
    return Meteor.settings.AWSBucket;
  },
  videoEncoder: function( key, callback ) {
    check( key, String );

    try {
       //var key = Files.findOne({_id: id}).key;

     var bucket = Meteor.settings.AWSBucket;

     var srcKey = decodeURIComponent(key.replace(/\+/g, " ")); //the object may have spaces
     var newKey = key.split(".")[0].split("/")[1];

        AWS.config.update({
           accessKeyId: Meteor.settings.AWSAccessKeyId,
           secretAccessKey: Meteor.settings.AWSSecretAccessKey
        });

        var s3 = new AWS.S3();

        var elastictranscoder = new AWS.ElasticTranscoder({
         apiVersion: "2012–09–25",
         region: "us-east-1"
        });

        var deleteKey = true;

        function outputsArray(){
             var array = [];
             if (!key.endsWith("webm")){
              array.push({Key: newKey + ".webm",
               //ThumbnailPattern: "thumbs-" + newKey,
               PresetId: '1351620000001-100240', //Webm 720p
               ThumbnailPattern: 'thumbnails/'+newKey+'-{count}',
               Rotate: 'auto'
              });
             }
             else{
              deleteKey = false;
             }

            if (!key.endsWith("mp4")){
              array.push({Key: newKey + ".mp4",
               //ThumbnailPattern: "thumbs/" + newKey,
               PresetId: '1351620000001-000010', //Webm 720p
              });
            }
            else{
              deleteKey = false;
             }

            return array;
          }

          var outputs = outputsArray();

        var params = {
          PipelineId: "1470942864170-m1y5ok",
          OutputKeyPrefix: "video/",
          Input: {
           Key: srcKey,
           FrameRate: "auto",
           Resolution: "auto",
           AspectRatio: "auto",
           Interlaced: "auto",
           Container: "auto"
          },
          Outputs: outputs

        };

        var elasticGo = //Meteor.wrapAsync(
           elastictranscoder.createJob(params, Meteor.bindEnvironment(function(error, data) {
              if(error) {
                 console.log(error);
              } else {
                 //console.log("Job well done");

                console.log(data);
                 var waitParam = {
                    Id: data.Job.Id /* required */
                };

                elastictranscoder.waitFor('jobComplete', waitParam, Meteor.bindEnvironment(function(err, data) {
                    if (err) console.log(err, err.stack); // an error occurred
                    else{
                      console.log("delete key: "+ key);

                      if(deleteKey){
                        _deleteFilesWithKey(key);
                       }

                      callback.finished();
                      }        // successful response
                }));

              }
           })
         );

        //);

      //then delete from s3
    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  }
});<commit_msg>fix youtube link processing<commit_after>  //pass an array of keys to delete
  function _deleteFilesWithKey(objKey){

    try{
      AWS.config.update({
             accessKeyId: Meteor.settings.AWSAccessKeyId,
             secretAccessKey: Meteor.settings.AWSSecretAccessKey
          });

      var s3 = new AWS.S3();

      if(typeof objKey === "string"){
        objKey = [objKey];
      }

      for(var i =0; i< objKey.length; i++){
        var params = {
            Bucket: Meteor.settings.AWSBucket,
            Key : objKey[i]
          };

        //var deleteObject = Meteor.wrapAsync(s3.deleteObject , params,);

        s3.deleteObject(params, Meteor.bindEnvironment(
            function(err, data){
                if(err)
                    console.log(error);
                else
                  console.log("success");
            },
            function(e){
                //bind failure
                console.log(e);
            }
        ));
        //);

        //deleteObject(params);
      }

      //deleteObject(params);
    } catch( exception ) {
      console.log(exception);
      //return exception;
    }

  }

  Meteor.methods({
  /*cleanKey : function(key){
    return key.replace(/\+/g, " ").split(".")[-2];
  },*/
  storeUrlInDatabase: function( data) {
    //check( data.url, String );
    //check( data.name, String );
    //check( data.size, Number );
    //Modules.both.checkUrlValidity( data.filepath );

    /*if(data.type==="video" && data.key!==null){
      console.log(data.key);
        data.key =
    }*/

    var noShow = data.key===null ? false : true;

    try {
      var fileID = Files.insert({
        filepath: data.filepath,
        userId: Meteor.userId(),
        added: new Date(),
        name: data.name,
        size: data.size,
        key: data.key,
        resourceID: data.id,
        type: data.type,
        noShow: noShow,
      });

      if(data.type==="video" && data.key!==null){
        var callback = {finished:function(){
            Files.update({key:data.key},{$set:{noShow:false}})
          }
        };
        Meteor.call('videoEncoder', data.key, callback);
    }

      var result = Files.findOne({_id: fileID});

      return result;

    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  },
  nameFiles: function(firstKey){
    if(firstKey!==null){
      var key = firstKey;
      var breakIndex = key.lastIndexOf(".");
      var shortKey = key.substring(0, breakIndex);
      var end = key.substring(breakIndex);
      var count = 0;
      while(!!Files.findOne({key: key})){
        count++;
        key = shortKey+" ("+count+")"+end;
        if(count>300){
          break;
        }
      }
    }
    return key;
  },
  deleteS3File: function( id ) {
    check( id, String );

    try {

        var key = Files.findOne({_id: id}).key;
        var type = Files.findOne({_id: id}).type;

        Files.remove({_id: id});
        //if not just a link
        if(key){

          var objKey = [];
          if(type==="video"){
            var shortKey = key.substring(0, key.lastIndexOf("."));
            objKey.push(shortKey+".webm");
            objKey.push(shortKey+".mp4");
            objKey.push(+shortKey.replace("video/","video/thumbnails/")+"-00001.png");
          }
          else{
            objKey.push(key);
          }

          //Meteor.call("_deleteFilesWithKey",objKey);

          _deleteFilesWithKey(objKey);
        }

      //then delete from s3
    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  },

  getBucket: function(){
    return Meteor.settings.AWSBucket;
  },
  videoEncoder: function( key, callback ) {
    check( key, String );

    try {
       //var key = Files.findOne({_id: id}).key;

     var bucket = Meteor.settings.AWSBucket;

     var srcKey = decodeURIComponent(key.replace(/\+/g, " ")); //the object may have spaces
     var newKey = key.split(".")[0].split("/")[1];

        AWS.config.update({
           accessKeyId: Meteor.settings.AWSAccessKeyId,
           secretAccessKey: Meteor.settings.AWSSecretAccessKey
        });

        var s3 = new AWS.S3();

        var elastictranscoder = new AWS.ElasticTranscoder({
         apiVersion: "2012–09–25",
         region: "us-east-1"
        });

        var deleteKey = true;

        function outputsArray(){
             var array = [];
             if (!key.endsWith("webm")){
              array.push({Key: newKey + ".webm",
               //ThumbnailPattern: "thumbs-" + newKey,
               PresetId: '1351620000001-100240', //Webm 720p
               ThumbnailPattern: 'thumbnails/'+newKey+'-{count}',
               Rotate: 'auto'
              });
             }
             else{
              deleteKey = false;
             }

            if (!key.endsWith("mp4")){
              array.push({Key: newKey + ".mp4",
               //ThumbnailPattern: "thumbs/" + newKey,
               PresetId: '1351620000001-000010', //Webm 720p
              });
            }
            else{
              deleteKey = false;
             }

            return array;
          }

          var outputs = outputsArray();

        var params = {
          PipelineId: "1470942864170-m1y5ok",
          OutputKeyPrefix: "video/",
          Input: {
           Key: srcKey,
           FrameRate: "auto",
           Resolution: "auto",
           AspectRatio: "auto",
           Interlaced: "auto",
           Container: "auto"
          },
          Outputs: outputs

        };

        var elasticGo = //Meteor.wrapAsync(
           elastictranscoder.createJob(params, Meteor.bindEnvironment(function(error, data) {
              if(error) {
                 console.log(error);
              } else {
                 //console.log("Job well done");

                console.log(data);
                 var waitParam = {
                    Id: data.Job.Id /* required */
                };

                elastictranscoder.waitFor('jobComplete', waitParam, Meteor.bindEnvironment(function(err, data) {
                    if (err) console.log(err, err.stack); // an error occurred
                    else{
                      console.log("delete key: "+ key);

                      if(deleteKey){
                        _deleteFilesWithKey(key);
                       }

                      callback.finished();
                      }        // successful response
                }));

              }
           })
         );

        //);

      //then delete from s3
    } catch( exception ) {
      console.log(exception);
      return exception;
    }
  }
});<|endoftext|>


<commit_before>/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot */

glowroot.config([
  '$provide',
  '$stateProvider',
  '$urlRouterProvider',
  function ($provide, $stateProvider, $urlRouterProvider) {
    var waitForLayout = function (needsTransactionType) {
      return ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
        if (window.layout) {
          if ($location.path() === '/login') {
            // no need to add transaction-type to url
            return;
          }
          var hasAgent = $location.search()['agent-id'] || $location.search()['agent-rollup'] || $rootScope.layout.fat;
          if (hasAgent && needsTransactionType && !$location.search()['transaction-type']) {
            $location.search('transaction-type', $rootScope.defaultTransactionType());
            $location.replace();
          }
          return function () {
          };
        } else {
          var deferred = $q.defer();
          var unregisterWatch = $rootScope.$watch('layout', function (value) {
            if (!value) {
              return;
            }
            if ($location.path() === '/login') {
              // no need to add transaction-type to url
              deferred.resolve();
              unregisterWatch();
              return;
            }
            var hasAgent = $location.search()['agent-id'] || $location.search()['agent-rollup']
                || $rootScope.layout.fat;
            if (hasAgent && needsTransactionType && !$location.search()['transaction-type']) {
              $location.search('transaction-type', $rootScope.defaultTransactionType());
              $location.replace();
            }
            deferred.resolve();
            unregisterWatch();
          });
          return deferred.promise;
        }
      }];
    };
    $urlRouterProvider.otherwise(function () {
      // TODO revisit this, especially for server
      if (!window.layout) {
        // don't seem able to return promise for 'otherwise', oh well, this is only for grunt serve anyways
        return 'transaction/average';
      }
      if (window.layout.showNavbarTransaction) {
        return 'transaction/average';
      } else if (window.layout.showNavbarError) {
        return 'error/messages';
      } else if (window.layout.showNavbarJvm) {
        // TODO this will not work if user has access to other JVM pages, but not gauges
        // (deal with this when revisiting entire 'otherwise', see comment above)
        return 'jvm/gauges';
      } else if (window.layout.showNavbarConfig) {
        return 'config/transaction';
      } else {
        return 'admin/user-list';
      }
    });
    $stateProvider.state('transaction', {
      abstract: true,
      url: '/transaction?agent-id&agent-rollup&transaction-type',
      templateUrl: 'views/transaction.html',
      controller: 'TransactionCtrl',
      resolve: {
        headerDisplay: function () {
          return 'Transactions';
        },
        shortName: function () {
          return 'transaction';
        },
        defaultSummarySortOrder: function () {
          return 'total-time';
        },
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('transaction.detail', {
      abstract: true,
      views: {
        sidebar: {
          templateUrl: 'views/transaction/sidebar.html',
          controller: 'TransactionSidebarCtrl',
          resolve: {
            summarySortOrders: function () {
              return {
                'total-time': 'By percent of total time',
                'average-time': 'By average time',
                'throughput': 'By throughput (per min)'
              };
            },
            summaryValueFn: [
              '$filter',
              function ($filter) {
                return function (summary, sortOrder, overallSummary, durationMillis) {
                  if (sortOrder === 'total-time') {
                    return (100 * summary.totalDurationNanos / overallSummary.totalDurationNanos).toFixed(1) + ' %';
                  } else if (sortOrder === 'average-time') {
                    return $filter('gtMillis')(summary.totalDurationNanos / (1000000 * summary.transactionCount)) + ' ms';
                  } else if (sortOrder === 'throughput') {
                    return (60 * 1000 * summary.transactionCount / durationMillis).toFixed(1) + '/min';
                  }
                };
              }
            ]
          }
        },
        tabs: {
          templateUrl: 'views/transaction/tabs.html',
          controller: 'TransactionTabCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.average', {
      url: '/average?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/average.html',
          controller: 'TransactionAverageCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.percentiles', {
      url: '/percentiles?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/percentiles.html',
          controller: 'TransactionPercentilesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.throughput', {
      url: '/throughput?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/throughput.html',
          controller: 'TransactionThroughputCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.traces', {
      url: '/traces?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/traces.html',
          controller: 'TracesCtrl',
          resolve: {
            traceKind: function () {
              return 'transaction';
            }
          }
        }
      }
    });
    $stateProvider.state('transaction.detail.queries', {
      url: '/queries?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/queries.html',
          controller: 'TransactionQueriesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.services', {
      url: '/services?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/services.html',
          controller: 'TransactionServicesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.threadProfile', {
      url: '/thread-profile?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/profile.html',
          controller: 'TransactionProfileCtrl'
        }
      }
    });
    var waitForD3 = ['$q', '$timeout', function ($q, $timeout) {
      var deferred = $q.defer();

      function checkForD3() {
        if (window.d3) {
          deferred.resolve();
        } else {
          $timeout(checkForD3, 100);
        }
      }

      $timeout(checkForD3, 100);
      return deferred.promise;
    }];
    $stateProvider.state('transaction-thread-flame-graph', {
      url: '/transaction/thread-flame-graph',
      templateUrl: 'views/transaction/flame-graph.html',
      controller: 'TransactionFlameGraphCtrl',
      resolve: {
        waitForD3: waitForD3,
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('error', {
      abstract: true,
      url: '/error?agent-id&agent-rollup&transaction-type',
      templateUrl: 'views/transaction.html',
      controller: 'TransactionCtrl',
      resolve: {
        headerDisplay: function () {
          return 'Errors';
        },
        shortName: function () {
          return 'error';
        },
        defaultSummarySortOrder: function () {
          return 'error-count';
        },
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('error.detail', {
      abstract: true,
      views: {
        sidebar: {
          templateUrl: 'views/transaction/sidebar.html',
          controller: 'TransactionSidebarCtrl',
          resolve: {
            summarySortOrders: function () {
              return {
                'error-count': 'By error count',
                'error-rate': 'By error rate'
              };
            },
            summaryValueFn: function () {
              return function (summary, sortOrder) {
                if (sortOrder === 'error-count') {
                  return summary.errorCount;
                } else if (sortOrder === 'error-rate') {
                  return (100 * summary.errorCount / summary.transactionCount).toFixed(1) + ' %';
                }
              };
            }
          }
        },
        tabs: {
          // same controller, just different html
          templateUrl: 'views/transaction/error-tabs.html',
          controller: 'TransactionTabCtrl'
        }
      }
    });
    $stateProvider.state('error.detail.messages', {
      url: '/messages?agent-id&transaction-type&transaction-name',
      views: {
        'main@error': {
          templateUrl: 'views/transaction/error-messages.html',
          controller: 'ErrorMessagesCtrl'
        }
      }
    });
    $stateProvider.state('error.detail.traces', {
      url: '/traces?agent-id&transaction-type&transaction-name',
      views: {
        'main@error': {
          templateUrl: 'views/transaction/traces.html',
          controller: 'TracesCtrl',
          resolve: {
            traceKind: function () {
              return 'error';
            }
          }
        }
      }
    });
    $stateProvider.state('jvm', {
      url: '/jvm',
      templateUrl: 'views/jvm.html',
      controller: 'JvmCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('jvm.gauges', {
      url: '/gauges?agent-id&agent-rollup',
      templateUrl: 'views/jvm/gauge-values.html',
      controller: 'JvmGaugeValuesCtrl'
    });
    $stateProvider.state('jvm.threadDump', {
      url: '/thread-dump?agent-id&agent-rollup',
      templateUrl: 'views/jvm/thread-dump.html',
      controller: 'JvmThreadDumpCtrl'
    });
    $stateProvider.state('jvm.jstack', {
      url: '/jstack?agent-id&agent-rollup',
      templateUrl: 'views/jvm/jstack.html',
      controller: 'JvmJstackCtrl'
    });
    $stateProvider.state('jvm.heapDump', {
      url: '/heap-dump?agent-id&agent-rollup',
      templateUrl: 'views/jvm/heap-dump.html',
      controller: 'JvmHeapDumpCtrl'
    });
    $stateProvider.state('jvm.heapHistogram', {
      url: '/heap-histogram?agent-id&agent-rollup',
      templateUrl: 'views/jvm/heap-histogram.html',
      controller: 'JvmHeapHistogramCtrl'
    });
    $stateProvider.state('jvm.gc', {
      url: '/gc?agent-id&agent-rollup',
      templateUrl: 'views/jvm/gc.html',
      controller: 'JvmGcCtrl'
    });
    $stateProvider.state('jvm.mbeanTree', {
      url: '/mbean-tree?agent-id&agent-rollup',
      templateUrl: 'views/jvm/mbean-tree.html',
      controller: 'JvmMBeanTreeCtrl'
    });
    $stateProvider.state('jvm.systemProperties', {
      url: '/system-properties?agent-id&agent-rollup',
      templateUrl: 'views/jvm/system-properties.html',
      controller: 'JvmSystemPropertiesCtrl'
    });
    $stateProvider.state('jvm.environment', {
      url: '/environment?agent-id&agent-rollup',
      templateUrl: 'views/jvm/environment.html',
      controller: 'JvmEnvironmentCtrl'
    });
    $stateProvider.state('jvm.capabilities', {
      url: '/capabilities?agent-id&agent-rollup',
      templateUrl: 'views/jvm/capabilities.html',
      controller: 'JvmCapabilitiesCtrl'
    });
    $stateProvider.state('config', {
      url: '/config',
      templateUrl: 'views/config.html',
      controller: 'ConfigCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('config.transaction', {
      url: '/transaction?agent-id',
      templateUrl: 'views/config/transaction.html',
      controller: 'ConfigCommonCtrl',
      resolve: {
        backendUrl: function () {
          return 'backend/config/transaction';
        }
      }
    });
    $stateProvider.state('config.gaugeList', {
      url: '/gauge-list?agent-id',
      templateUrl: 'views/config/gauge-list.html',
      controller: 'ConfigGaugeListCtrl'
    });
    $stateProvider.state('config.gauge', {
      url: '/gauge?agent-id&v',
      templateUrl: 'views/config/gauge.html',
      controller: 'ConfigGaugeCtrl'
    });
    $stateProvider.state('config.alertList', {
      url: '/alert-list?agent-id',
      templateUrl: 'views/config/alert-list.html',
      controller: 'ConfigAlertListCtrl'
    });
    $stateProvider.state('config.alert', {
      url: '/alert?agent-id&v',
      templateUrl: 'views/config/alert.html',
      controller: 'ConfigAlertCtrl'
    });
    $stateProvider.state('config.ui', {
      url: '/ui',
      templateUrl: 'views/config/ui.html',
      controller: 'ConfigUiCtrl'
    });
    $stateProvider.state('config.pluginList', {
      url: '/plugin-list?agent-id',
      templateUrl: 'views/config/plugin-list.html',
      controller: 'ConfigPluginListCtrl'
    });
    $stateProvider.state('config.plugin', {
      url: '/plugin?agent-id&plugin-id',
      templateUrl: 'views/config/plugin.html',
      controller: 'ConfigPluginCtrl'
    });
    $stateProvider.state('config.instrumentationList', {
      url: '/instrumentation-list?agent-id',
      templateUrl: 'views/config/instrumentation-list.html',
      controller: 'ConfigInstrumentationListCtrl'
    });
    $stateProvider.state('config.instrumentation', {
      url: '/instrumentation?agent-id&v',
      templateUrl: 'views/config/instrumentation.html',
      controller: 'ConfigInstrumentationCtrl'
    });
    $stateProvider.state('config.userRecording', {
      url: '/user-recording',
      templateUrl: 'views/config/user-recording.html',
      controller: 'ConfigUserRecordingCtrl'
    });
    $stateProvider.state('config.advanced', {
      url: '/advanced?agent-id',
      templateUrl: 'views/config/advanced.html',
      controller: 'ConfigCommonCtrl',
      resolve: {
        backendUrl: function () {
          return 'backend/config/advanced';
        }
      }
    });
    $stateProvider.state('admin', {
      url: '/admin',
      templateUrl: 'views/config.html',
      controller: 'ConfigCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('admin.userList', {
      url: '/user-list',
      templateUrl: 'views/admin/user-list.html',
      controller: 'AdminUserListCtrl'
    });
    $stateProvider.state('admin.user', {
      url: '/user',
      templateUrl: 'views/admin/user.html',
      controller: 'AdminUserCtrl'
    });
    $stateProvider.state('admin.roleList', {
      url: '/role-list',
      templateUrl: 'views/admin/role-list.html',
      controller: 'AdminRoleListCtrl'
    });
    $stateProvider.state('admin.role', {
      url: '/role',
      templateUrl: 'views/admin/role.html',
      controller: 'AdminRoleCtrl'
    });
    $stateProvider.state('admin.web', {
      url: '/web',
      templateUrl: 'views/admin/web.html',
      controller: 'AdminWebCtrl'
    });
    $stateProvider.state('admin.storage', {
      url: '/storage',
      templateUrl: 'views/admin/storage.html',
      controller: 'AdminStorageCtrl'
    });
    $stateProvider.state('admin.smtp', {
      url: '/smtp',
      templateUrl: 'views/admin/smtp.html',
      controller: 'AdminSmtpCtrl'
    });
    $stateProvider.state('admin.ldap', {
      url: '/ldap',
      templateUrl: 'views/admin/ldap.html',
      controller: 'AdminLdapCtrl'
    });
    $stateProvider.state('admin.changePassword', {
      url: '^/change-password',
      templateUrl: 'views/change-password.html',
      controller: 'ChangePasswordCtrl'
    });
    $stateProvider.state('login', {
      url: '/login',
      templateUrl: 'views/login.html',
      controller: 'LoginCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
  }
]);
<commit_msg>Fix initial redirect when lacking some permissions<commit_after>/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot */

glowroot.config([
  '$provide',
  '$stateProvider',
  '$urlRouterProvider',
  function ($provide, $stateProvider, $urlRouterProvider) {
    var waitForLayout = function (needsTransactionType) {
      return ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
        if (window.layout) {
          if ($location.path() === '/login') {
            // no need to add transaction-type to url
            return;
          }
          var hasAgent = $location.search()['agent-id'] || $location.search()['agent-rollup'] || $rootScope.layout.fat;
          if (hasAgent && needsTransactionType && !$location.search()['transaction-type']) {
            $location.search('transaction-type', $rootScope.defaultTransactionType());
            $location.replace();
          }
          return function () {
          };
        } else {
          var deferred = $q.defer();
          var unregisterWatch = $rootScope.$watch('layout', function (value) {
            if (!value) {
              return;
            }
            if ($location.path() === '/login') {
              // no need to add transaction-type to url
              deferred.resolve();
              unregisterWatch();
              return;
            }
            var hasAgent = $location.search()['agent-id'] || $location.search()['agent-rollup']
                || $rootScope.layout.fat;
            if (hasAgent && needsTransactionType && !$location.search()['transaction-type']) {
              $location.search('transaction-type', $rootScope.defaultTransactionType());
              $location.replace();
            }
            deferred.resolve();
            unregisterWatch();
          });
          return deferred.promise;
        }
      }];
    };
    $urlRouterProvider.otherwise(function () {
      // TODO revisit this, especially for server
      if (!window.layout) {
        // don't seem able to return promise for 'otherwise', oh well, this is only for grunt serve anyways
        return 'transaction/average';
      }
      if (window.layout.showNavbarTransaction) {
        return 'transaction/average';
      } else if (window.layout.showNavbarError) {
        return 'error/messages';
      } else if (window.layout.showNavbarJvm) {
        if (window.layout.fat) {
          var jvmPermissions = window.layout.agentRollups[''].permissions.jvm;
          if (jvmPermissions.gauges) {
            return 'jvm/gauges';
          } else if (jvmPermissions.threadDump) {
            return 'jvm/thread-dump';
          } else if (jvmPermissions.heapDump) {
            return 'jvm/heap-dump';
          } else if (jvmPermissions.heapHistogram) {
            return 'jvm/heap-histogram';
          } else if (jvmPermissions.mbeanTree) {
            return 'jvm/mbean-tree';
          } else if (jvmPermissions.systemProperties) {
            return 'jvm/system-properties';
          } else {
            // only remaining option when showNavbarJvm is true
            return 'jvm/environment';
          }
        } else {
          // TODO this will not work if user has access to other JVM pages, but not gauges
          // (deal with this when revisiting entire 'otherwise', see comment above)
          return 'jvm/gauges';
        }
      } else if (window.layout.showNavbarConfig) {
        return 'config/transaction';
      } else {
        return 'admin/user-list';
      }
    });
    $stateProvider.state('transaction', {
      abstract: true,
      url: '/transaction?agent-id&agent-rollup&transaction-type',
      templateUrl: 'views/transaction.html',
      controller: 'TransactionCtrl',
      resolve: {
        headerDisplay: function () {
          return 'Transactions';
        },
        shortName: function () {
          return 'transaction';
        },
        defaultSummarySortOrder: function () {
          return 'total-time';
        },
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('transaction.detail', {
      abstract: true,
      views: {
        sidebar: {
          templateUrl: 'views/transaction/sidebar.html',
          controller: 'TransactionSidebarCtrl',
          resolve: {
            summarySortOrders: function () {
              return {
                'total-time': 'By percent of total time',
                'average-time': 'By average time',
                'throughput': 'By throughput (per min)'
              };
            },
            summaryValueFn: [
              '$filter',
              function ($filter) {
                return function (summary, sortOrder, overallSummary, durationMillis) {
                  if (sortOrder === 'total-time') {
                    return (100 * summary.totalDurationNanos / overallSummary.totalDurationNanos).toFixed(1) + ' %';
                  } else if (sortOrder === 'average-time') {
                    return $filter('gtMillis')(summary.totalDurationNanos / (1000000 * summary.transactionCount)) + ' ms';
                  } else if (sortOrder === 'throughput') {
                    return (60 * 1000 * summary.transactionCount / durationMillis).toFixed(1) + '/min';
                  }
                };
              }
            ]
          }
        },
        tabs: {
          templateUrl: 'views/transaction/tabs.html',
          controller: 'TransactionTabCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.average', {
      url: '/average?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/average.html',
          controller: 'TransactionAverageCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.percentiles', {
      url: '/percentiles?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/percentiles.html',
          controller: 'TransactionPercentilesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.throughput', {
      url: '/throughput?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/throughput.html',
          controller: 'TransactionThroughputCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.traces', {
      url: '/traces?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/traces.html',
          controller: 'TracesCtrl',
          resolve: {
            traceKind: function () {
              return 'transaction';
            }
          }
        }
      }
    });
    $stateProvider.state('transaction.detail.queries', {
      url: '/queries?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/queries.html',
          controller: 'TransactionQueriesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.services', {
      url: '/services?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/services.html',
          controller: 'TransactionServicesCtrl'
        }
      }
    });
    $stateProvider.state('transaction.detail.threadProfile', {
      url: '/thread-profile?agent-id&transaction-type&transaction-name',
      views: {
        'main@transaction': {
          templateUrl: 'views/transaction/profile.html',
          controller: 'TransactionProfileCtrl'
        }
      }
    });
    var waitForD3 = ['$q', '$timeout', function ($q, $timeout) {
      var deferred = $q.defer();

      function checkForD3() {
        if (window.d3) {
          deferred.resolve();
        } else {
          $timeout(checkForD3, 100);
        }
      }

      $timeout(checkForD3, 100);
      return deferred.promise;
    }];
    $stateProvider.state('transaction-thread-flame-graph', {
      url: '/transaction/thread-flame-graph',
      templateUrl: 'views/transaction/flame-graph.html',
      controller: 'TransactionFlameGraphCtrl',
      resolve: {
        waitForD3: waitForD3,
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('error', {
      abstract: true,
      url: '/error?agent-id&agent-rollup&transaction-type',
      templateUrl: 'views/transaction.html',
      controller: 'TransactionCtrl',
      resolve: {
        headerDisplay: function () {
          return 'Errors';
        },
        shortName: function () {
          return 'error';
        },
        defaultSummarySortOrder: function () {
          return 'error-count';
        },
        waitForLayout: waitForLayout(true)
      }
    });
    $stateProvider.state('error.detail', {
      abstract: true,
      views: {
        sidebar: {
          templateUrl: 'views/transaction/sidebar.html',
          controller: 'TransactionSidebarCtrl',
          resolve: {
            summarySortOrders: function () {
              return {
                'error-count': 'By error count',
                'error-rate': 'By error rate'
              };
            },
            summaryValueFn: function () {
              return function (summary, sortOrder) {
                if (sortOrder === 'error-count') {
                  return summary.errorCount;
                } else if (sortOrder === 'error-rate') {
                  return (100 * summary.errorCount / summary.transactionCount).toFixed(1) + ' %';
                }
              };
            }
          }
        },
        tabs: {
          // same controller, just different html
          templateUrl: 'views/transaction/error-tabs.html',
          controller: 'TransactionTabCtrl'
        }
      }
    });
    $stateProvider.state('error.detail.messages', {
      url: '/messages?agent-id&transaction-type&transaction-name',
      views: {
        'main@error': {
          templateUrl: 'views/transaction/error-messages.html',
          controller: 'ErrorMessagesCtrl'
        }
      }
    });
    $stateProvider.state('error.detail.traces', {
      url: '/traces?agent-id&transaction-type&transaction-name',
      views: {
        'main@error': {
          templateUrl: 'views/transaction/traces.html',
          controller: 'TracesCtrl',
          resolve: {
            traceKind: function () {
              return 'error';
            }
          }
        }
      }
    });
    $stateProvider.state('jvm', {
      url: '/jvm',
      templateUrl: 'views/jvm.html',
      controller: 'JvmCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('jvm.gauges', {
      url: '/gauges?agent-id&agent-rollup',
      templateUrl: 'views/jvm/gauge-values.html',
      controller: 'JvmGaugeValuesCtrl'
    });
    $stateProvider.state('jvm.threadDump', {
      url: '/thread-dump?agent-id&agent-rollup',
      templateUrl: 'views/jvm/thread-dump.html',
      controller: 'JvmThreadDumpCtrl'
    });
    $stateProvider.state('jvm.jstack', {
      url: '/jstack?agent-id&agent-rollup',
      templateUrl: 'views/jvm/jstack.html',
      controller: 'JvmJstackCtrl'
    });
    $stateProvider.state('jvm.heapDump', {
      url: '/heap-dump?agent-id&agent-rollup',
      templateUrl: 'views/jvm/heap-dump.html',
      controller: 'JvmHeapDumpCtrl'
    });
    $stateProvider.state('jvm.heapHistogram', {
      url: '/heap-histogram?agent-id&agent-rollup',
      templateUrl: 'views/jvm/heap-histogram.html',
      controller: 'JvmHeapHistogramCtrl'
    });
    $stateProvider.state('jvm.gc', {
      url: '/gc?agent-id&agent-rollup',
      templateUrl: 'views/jvm/gc.html',
      controller: 'JvmGcCtrl'
    });
    $stateProvider.state('jvm.mbeanTree', {
      url: '/mbean-tree?agent-id&agent-rollup',
      templateUrl: 'views/jvm/mbean-tree.html',
      controller: 'JvmMBeanTreeCtrl'
    });
    $stateProvider.state('jvm.systemProperties', {
      url: '/system-properties?agent-id&agent-rollup',
      templateUrl: 'views/jvm/system-properties.html',
      controller: 'JvmSystemPropertiesCtrl'
    });
    $stateProvider.state('jvm.environment', {
      url: '/environment?agent-id&agent-rollup',
      templateUrl: 'views/jvm/environment.html',
      controller: 'JvmEnvironmentCtrl'
    });
    $stateProvider.state('jvm.capabilities', {
      url: '/capabilities?agent-id&agent-rollup',
      templateUrl: 'views/jvm/capabilities.html',
      controller: 'JvmCapabilitiesCtrl'
    });
    $stateProvider.state('config', {
      url: '/config',
      templateUrl: 'views/config.html',
      controller: 'ConfigCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('config.transaction', {
      url: '/transaction?agent-id',
      templateUrl: 'views/config/transaction.html',
      controller: 'ConfigCommonCtrl',
      resolve: {
        backendUrl: function () {
          return 'backend/config/transaction';
        }
      }
    });
    $stateProvider.state('config.gaugeList', {
      url: '/gauge-list?agent-id',
      templateUrl: 'views/config/gauge-list.html',
      controller: 'ConfigGaugeListCtrl'
    });
    $stateProvider.state('config.gauge', {
      url: '/gauge?agent-id&v',
      templateUrl: 'views/config/gauge.html',
      controller: 'ConfigGaugeCtrl'
    });
    $stateProvider.state('config.alertList', {
      url: '/alert-list?agent-id',
      templateUrl: 'views/config/alert-list.html',
      controller: 'ConfigAlertListCtrl'
    });
    $stateProvider.state('config.alert', {
      url: '/alert?agent-id&v',
      templateUrl: 'views/config/alert.html',
      controller: 'ConfigAlertCtrl'
    });
    $stateProvider.state('config.ui', {
      url: '/ui',
      templateUrl: 'views/config/ui.html',
      controller: 'ConfigUiCtrl'
    });
    $stateProvider.state('config.pluginList', {
      url: '/plugin-list?agent-id',
      templateUrl: 'views/config/plugin-list.html',
      controller: 'ConfigPluginListCtrl'
    });
    $stateProvider.state('config.plugin', {
      url: '/plugin?agent-id&plugin-id',
      templateUrl: 'views/config/plugin.html',
      controller: 'ConfigPluginCtrl'
    });
    $stateProvider.state('config.instrumentationList', {
      url: '/instrumentation-list?agent-id',
      templateUrl: 'views/config/instrumentation-list.html',
      controller: 'ConfigInstrumentationListCtrl'
    });
    $stateProvider.state('config.instrumentation', {
      url: '/instrumentation?agent-id&v',
      templateUrl: 'views/config/instrumentation.html',
      controller: 'ConfigInstrumentationCtrl'
    });
    $stateProvider.state('config.userRecording', {
      url: '/user-recording',
      templateUrl: 'views/config/user-recording.html',
      controller: 'ConfigUserRecordingCtrl'
    });
    $stateProvider.state('config.advanced', {
      url: '/advanced?agent-id',
      templateUrl: 'views/config/advanced.html',
      controller: 'ConfigCommonCtrl',
      resolve: {
        backendUrl: function () {
          return 'backend/config/advanced';
        }
      }
    });
    $stateProvider.state('admin', {
      url: '/admin',
      templateUrl: 'views/config.html',
      controller: 'ConfigCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
    $stateProvider.state('admin.userList', {
      url: '/user-list',
      templateUrl: 'views/admin/user-list.html',
      controller: 'AdminUserListCtrl'
    });
    $stateProvider.state('admin.user', {
      url: '/user',
      templateUrl: 'views/admin/user.html',
      controller: 'AdminUserCtrl'
    });
    $stateProvider.state('admin.roleList', {
      url: '/role-list',
      templateUrl: 'views/admin/role-list.html',
      controller: 'AdminRoleListCtrl'
    });
    $stateProvider.state('admin.role', {
      url: '/role',
      templateUrl: 'views/admin/role.html',
      controller: 'AdminRoleCtrl'
    });
    $stateProvider.state('admin.web', {
      url: '/web',
      templateUrl: 'views/admin/web.html',
      controller: 'AdminWebCtrl'
    });
    $stateProvider.state('admin.storage', {
      url: '/storage',
      templateUrl: 'views/admin/storage.html',
      controller: 'AdminStorageCtrl'
    });
    $stateProvider.state('admin.smtp', {
      url: '/smtp',
      templateUrl: 'views/admin/smtp.html',
      controller: 'AdminSmtpCtrl'
    });
    $stateProvider.state('admin.ldap', {
      url: '/ldap',
      templateUrl: 'views/admin/ldap.html',
      controller: 'AdminLdapCtrl'
    });
    $stateProvider.state('admin.changePassword', {
      url: '^/change-password',
      templateUrl: 'views/change-password.html',
      controller: 'ChangePasswordCtrl'
    });
    $stateProvider.state('login', {
      url: '/login',
      templateUrl: 'views/login.html',
      controller: 'LoginCtrl',
      resolve: {
        waitForLayout: waitForLayout(false)
      }
    });
  }
]);
<|endoftext|>


<commit_before>/**
* @Author: gyanl, ananayarora
* @Date:   2016-09-29T09:56:56+05:30
* @Last modified by:   ananayarora
* @Last modified time: 2016-09-29T10:00:14+05:30
*/

var newColour = [];
var format = 'hex';

function changeColorFormat() {
    format = document.querySelector('input[type="radio"]:checked').value;
}

function genColor() {
    var a = "";
    for (var i = 0; i < 3; i++)
        a = a.concat(Math.floor(Math.random() * 255).toString(16));

    if (a.length < 6) {
        for (var i = 0; i < (6 - a.length); i++)
            a = "0" + a;
    }
    return "#" + a;
}

function changeColour(num) {
    if (num != -1) {
        new_color = newColour[num];
        //outline();  either use the fn or just write the code here.
    } else {
        new_color = genColor();
        newColour.unshift(new_color);
        for (var i = 0; i < 6; i++) {
            var div_id = "c" + (i);
            document.getElementById(div_id).style.background = newColour[i];
            document.getElementById('c0').focus();
        }
    }
    document.body.style.backgroundColor = new_color;
    document.getElementById('clipboard').style.background = new_color;
    document.getElementById('generate').style.background = new_color;
    document.getElementById('clipboard').setAttribute("data-clipboard-text", formatColor(new_color));
}

function formatColor(color) {
    color = convertColor(color, format);
    return color;
}

function toast(yo) {
    yo.setAttribute("data-clipboard-text", formatColor(newColour[0]));
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function copyAll(yo) {
    var colors = formatColor(newColour[0]);
    for (var i = 1; i < 6; i++) {
        if (newColour[i]) {
            colors = colors + ", " + formatColor(newColour[i]);
        }
    }
    document.getElementById('copyall').setAttribute("data-clipboard-text", colors);
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function start() {
    var clipboard = new Clipboard('.btn');
    changeColour(-1);
}
<commit_msg>Make copyall color change<commit_after>/**
* @Author: gyanl, ananayarora
* @Date:   2016-09-29T09:56:56+05:30
* @Last modified by:   ananayarora
* @Last modified time: 2016-09-29T10:00:14+05:30
*/

var newColour = [];
var format = 'hex';

function changeColorFormat() {
    format = document.querySelector('input[type="radio"]:checked').value;
}

function genColor() {
    var a = "";
    for (var i = 0; i < 3; i++)
        a = a.concat(Math.floor(Math.random() * 255).toString(16));

    if (a.length < 6) {
        for (var i = 0; i < (6 - a.length); i++)
            a = "0" + a;
    }
    return "#" + a;
}

function changeColour(num) {
    if (num != -1) {
        new_color = newColour[num];
        //outline();  either use the fn or just write the code here.
    } else {
        new_color = genColor();
        newColour.unshift(new_color);
        for (var i = 0; i < 6; i++) {
            var div_id = "c" + (i);
            document.getElementById(div_id).style.background = newColour[i];
            document.getElementById('c0').focus();
        }
    }
    document.body.style.backgroundColor = new_color;
    document.getElementById('clipboard').style.background = new_color;
    document.getElementById('generate').style.background = new_color;
    document.getElementById('copyall').style.background = new_color;
    document.getElementById('clipboard').setAttribute("data-clipboard-text", formatColor(new_color));
}

function formatColor(color) {
    color = convertColor(color, format);
    return color;
}

function toast(yo) {
    yo.setAttribute("data-clipboard-text", formatColor(newColour[0]));
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function copyAll(yo) {
    var colors = formatColor(newColour[0]);
    for (var i = 1; i < 6; i++) {
        if (newColour[i]) {
            colors = colors + ", " + formatColor(newColour[i]);
        }
    }
    document.getElementById('copyall').setAttribute("data-clipboard-text", colors);
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function start() {
    var clipboard = new Clipboard('.btn');
    changeColour(-1);
}
<|endoftext|>


<commit_before>
  function recebe() {
    var img  = JSON.parse(sessionStorage.getItem('img'));
    var nome = JSON.parse(sessionStorage.getItem('nome-modulo'));

    if (nome == "Administração" || nome == "Recepção") {
      $("#triagem").remove();
      $("#consulta").remove();
      $("#fila").remove();
    }else if(nome == "Triagem") {
      $("#consulta").remove();
      $("#cadastro").remove();
      $("#fila").remove();
      $("#geoloc").remove();
    }else if (nome == "Portaria") {
      $("#cadastro").remove();
      $("#consulta").remove();
      $("#triagem").remove();
      $("#geoloc").remove();
    }else {
      $("#fila").remove();
      $("#cadastro").remove();
      $("#triagem").remove();
      $("#geoloc").remove();
    }

    $("#lbl_triagem").html(nome);
    $('.tit-image').css( {
      "background": "url("+img+") no-repeat",
      "background-size": "140px",
      "background-position": "15% -1%"
    });
  }

  /*Funçao que atualiza a hora*/
  setInterval(function() {

    if (typeof($("#hora")) !== "undefined") {
      var hora = new Date();
      $('#hora').html(hora.toLocaleTimeString());
    }

    if (screen.width > 650) {
      if ($("#lateral").css("margin-left") == "-390px") {
        $("#lateral").css("margin-left", "0px");
      }

      if ($("#config").css("visibility") == "hidden") {
        $("#config").css("visibility", "visible");
      }

      $('.tit-image').css( {
        "background-size": "140px",
      });
    } else {
      $('.tit-image').css( {
        "background-size": "70px",
      });
    }

    if (screen.width <= 711 && screen.width > 650 ) {
      $(".config").css("width", "44%");
    }
  }, 100);

  /* Função que mostra o menú lateral */
  var ok = false;
  function mostrarMenu() {

    var nav = document.getElementById('lateral');
    nav.style.transition = "1s margin-left";

    if (!ok) {
      nav.style.marginLeft = "0px";
      ok = true;
    } else {
      nav.style.marginLeft = "-390px";
      ok = false;
    }
  }

  /*Funçao que mostra os submodulos*/
  var okMostrar = false;
  function mostrar(){
    var submodulo = document.getElementById('submodulo_1');

    if (!okMostrar){
      submodulo.style.position   = "relative";
      submodulo.style.visibility = "visible";
      okMostrar = true;
    } else {
      submodulo.style.position   = "absolute";
      submodulo.style.visibility = "hidden";
      okMostrar = false;
    }
  }

  /*Funçao que mostra os as opções de salvar editar e imprimir*/
  var okConfig = false;
  function mostrarConfig(){
    var config = document.getElementById('config');

    if (!okConfig) {
      config.style.visibility = "visible";
      okConfig = true;
    } else {
      config.style.visibility = "hidden";
      okConfig = false;
    }
  }

  /*Função que mostra os conteudos das abas*/
  function mostrarAbas(nomeAba, url, num) {
    if (!$("#abas"+num ).is( ":visible")) {
      $('#abas').append("

"+nomeAba+"

");
      $('#content').append("

");
      $('#conteudo'+num).append("");
      window.open (url, 'frame'+num);
      abas(num);
      if (screen.width <= 650) {
        $("#lateral").css("margin-left", "-390px");
      }
    }
  }

  /*Função que implementa as abas*/
  function abas(num) {
    $("#content div:nth-child(1)").show();
    var primeiraTag = $(".abas li:nth-child(2) .aba").hasClass("selecionada");

    if (!primeiraTag) {
      $(".abas li:first div").addClass("selecionada");
    }

    /*Coloca o icone de fechar nas abas*/
    $('#abas'+num).append("");

    /*Adiciona o hover nos nomes das abas*/
    $(".aba").hover(
      function(){$(this).addClass("ativa");},
      function(){$(this).removeClass("ativa");}
    );

    /*permite a seleção das abas*/
    $(".aba").click(function() {
      $(".aba").removeClass("selecionada");
      $(this).addClass("selecionada");
      var indice = $(this).parent().index();
      indice++;
      $("#content div").hide();
      $("#content div:nth-child("+indice+")").show();
    });

    /*Fecha a aba*/
    $(".aba > img").click(function() {
      var aba    = $(this).parent().parent();
      var indice = aba.index() + 1;
      var num    = $(".abas li").length - 1;
      aba.remove();
      $("#content div:nth-child("+indice.toString()+")").remove();
      var id          = indice - 1;
      var primeiraTag = $(".abas li:nth-child(1) .aba").hasClass("selecionada");
      var ultimaTag   = $(".abas li:nth-child("+ num +") .aba").hasClass("selecionada");

      if(indice > 1) {
        if (!primeiraTag && !ultimaTag) {
          $("#content div:nth-child("+id.toString()+")").show();
          $(".abas li:nth-child("+id+") .aba").addClass("selecionada");
        }
      } else {
        $("#content div:nth-child("+indice.toString()+")").show();
        if (!ultimaTag) {
          $(".abas li:nth-child("+indice+") .aba").addClass("selecionada");
        }
      }
    });
  }
  $(document).ready(function(){
    $("#inp-env").click(function () {

      // $('.form input').each(function() {
      //   if ($(this).val() == "") {
      //     $(this).css({
      //       "border-color":"#f00"
      //     });
      //   }
      // });
      $(".visible-group").css({
        "position":"absolute",
        "display":"none"
      });

      $(".hidden-group").css({
        "position":"absolute",
        "display":"inline-block",
      });
    });

    $("#inp-voltar").click(function () {
      $(".visible-group").css({
        "position":"absolute",
        "display":"inline-block"
      });

      $(".hidden-group").css({
        "position":"absolute",
        "display":"none",
      });
    });
  });
  function enviar(val) {
    var img;
    var name;
    switch(val) {
      case 1:
          img  = $("#img-triagem").attr('src');
          name = $("#name-tri").html();
          break;
      case 2:
          img = $("#img-recepcao").attr('src');
          name = $("#name-recep").html();
          break;
      case 3:
          img = $("#img-admin").attr('src');
          name = $("#name-admin").html();
          break;
      case 4:
          img = $("#img-portaria").attr('src');
          name = $("#name-portaria").html();
          break;
      default:
      img = $("#img-medico").attr('src');
      name = $("#name-consultorio").html();
    }

    var image = JSON.stringify(img);
    var txt   = JSON.stringify(name);
    sessionStorage.setItem('img', image );
    sessionStorage.setItem('nome-modulo', txt );
  }
<commit_msg>FrontEnd: Ajustado a função que faz aparecer os fieldsets.<commit_after>
  function recebe() {
    var img  = JSON.parse(sessionStorage.getItem('img'));
    var nome = JSON.parse(sessionStorage.getItem('nome-modulo'));

    if (nome == "Administração" || nome == "Recepção") {
      $("#triagem").remove();
      $("#consulta").remove();
      $("#fila").remove();
    }else if(nome == "Triagem") {
      $("#consulta").remove();
      $("#cadastro").remove();
      $("#fila").remove();
      $("#geoloc").remove();
    }else if (nome == "Portaria") {
      $("#cadastro").remove();
      $("#consulta").remove();
      $("#triagem").remove();
      $("#geoloc").remove();
    }else {
      $("#fila").remove();
      $("#cadastro").remove();
      $("#triagem").remove();
      $("#geoloc").remove();
    }

    $("#lbl_triagem").html(nome);
    $('.tit-image').css( {
      "background": "url("+img+") no-repeat",
      "background-size": "140px",
      "background-position": "15% -1%"
    });
  }

  /*Funçao que atualiza a hora*/
  setInterval(function() {

    if (typeof($("#hora")) !== "undefined") {
      var hora = new Date();
      $('#hora').html(hora.toLocaleTimeString());
    }

    if (screen.width > 650) {
      if ($("#lateral").css("margin-left") == "-390px") {
        $("#lateral").css("margin-left", "0px");
      }

      if ($("#config").css("visibility") == "hidden") {
        $("#config").css("visibility", "visible");
      }

      $('.tit-image').css( {
        "background-size": "140px",
      });
    } else {
      $('.tit-image').css( {
        "background-size": "70px",
      });
    }

    if (screen.width <= 711 && screen.width > 650 ) {
      $(".config").css("width", "44%");
    }
  }, 100);

  /* Função que mostra o menú lateral */
  var ok = false;
  function mostrarMenu() {

    var nav = document.getElementById('lateral');
    nav.style.transition = "1s margin-left";

    if (!ok) {
      nav.style.marginLeft = "0px";
      ok = true;
    } else {
      nav.style.marginLeft = "-390px";
      ok = false;
    }
  }

  /*Funçao que mostra os submodulos*/
  var okMostrar = false;
  function mostrar(){
    var submodulo = document.getElementById('submodulo_1');

    if (!okMostrar){
      submodulo.style.position   = "relative";
      submodulo.style.visibility = "visible";
      okMostrar = true;
    } else {
      submodulo.style.position   = "absolute";
      submodulo.style.visibility = "hidden";
      okMostrar = false;
    }
  }

  /*Funçao que mostra os as opções de salvar editar e imprimir*/
  var okConfig = false;
  function mostrarConfig(){
    var config = document.getElementById('config');

    if (!okConfig) {
      config.style.visibility = "visible";
      okConfig = true;
    } else {
      config.style.visibility = "hidden";
      okConfig = false;
    }
  }

  /*Função que mostra os conteudos das abas*/
  function mostrarAbas(nomeAba, url, num) {
    if (!$("#abas"+num ).is( ":visible")) {
      $('#abas').append("

"+nomeAba+"

");
      $('#content').append("

");
      $('#conteudo'+num).append("");
      window.open (url, 'frame'+num);
      abas(num);
      if (screen.width <= 650) {
        $("#lateral").css("margin-left", "-390px");
      }
    }
  }

  /*Função que implementa as abas*/
  function abas(num) {
    $("#content div:nth-child(1)").show();
    var primeiraTag = $(".abas li:nth-child(2) .aba").hasClass("selecionada");

    if (!primeiraTag) {
      $(".abas li:first div").addClass("selecionada");
    }

    /*Coloca o icone de fechar nas abas*/
    $('#abas'+num).append("");

    /*Adiciona o hover nos nomes das abas*/
    $(".aba").hover(
      function(){$(this).addClass("ativa");},
      function(){$(this).removeClass("ativa");}
    );

    /*permite a seleção das abas*/
    $(".aba").click(function() {
      $(".aba").removeClass("selecionada");
      $(this).addClass("selecionada");
      var indice = $(this).parent().index();
      indice++;
      $("#content div").hide();
      $("#content div:nth-child("+indice+")").show();
    });

    /*Fecha a aba*/
    $(".aba > img").click(function() {
      var aba    = $(this).parent().parent();
      var indice = aba.index() + 1;
      var num    = $(".abas li").length - 1;
      aba.remove();
      $("#content div:nth-child("+indice.toString()+")").remove();
      var id          = indice - 1;
      var primeiraTag = $(".abas li:nth-child(1) .aba").hasClass("selecionada");
      var ultimaTag   = $(".abas li:nth-child("+ num +") .aba").hasClass("selecionada");

      if(indice > 1) {
        if (!primeiraTag && !ultimaTag) {
          $("#content div:nth-child("+id.toString()+")").show();
          $(".abas li:nth-child("+id+") .aba").addClass("selecionada");
        }
      } else {
        $("#content div:nth-child("+indice.toString()+")").show();
        if (!ultimaTag) {
          $(".abas li:nth-child("+indice+") .aba").addClass("selecionada");
        }
      }
    });
  }
  $(document).ready(function(){
    $("#inp-env").click(function () {

      // $('.form input').each(function() {
      //   if ($(this).val() == "") {
      //     $(this).css({
      //       "border-color":"#f00"
      //     });
      //   }
      // });
      $(".visible-group").css({
        "display":"none"
      });

      $(".hidden-group").css({
        "display":"inline-block",
      });
    });

    $("#inp-voltar").click(function () {
      $(".visible-group").css({
        "display":"inline-block"
      });

      $(".hidden-group").css({
        "display":"none",
      });
    });
  });
  function enviar(val) {
    var img;
    var name;
    switch(val) {
      case 1:
          img  = $("#img-triagem").attr('src');
          name = $("#name-tri").html();
          break;
      case 2:
          img = $("#img-recepcao").attr('src');
          name = $("#name-recep").html();
          break;
      case 3:
          img = $("#img-admin").attr('src');
          name = $("#name-admin").html();
          break;
      case 4:
          img = $("#img-portaria").attr('src');
          name = $("#name-portaria").html();
          break;
      default:
      img = $("#img-medico").attr('src');
      name = $("#name-consultorio").html();
    }

    var image = JSON.stringify(img);
    var txt   = JSON.stringify(name);
    sessionStorage.setItem('img', image );
    sessionStorage.setItem('nome-modulo', txt );
  }
<|endoftext|>


<commit_before>import React, { useRef, useEffect } from 'react';
import './chart.css';
import * as d3 from 'd3';
import * as fc from 'd3fc';

const Chart = ({ chartData }) => {
  useEffect(() => {
    if (chartData != null) {
      chartData.sort((a, b) => {
        return a.date - b.date;
      });
      makeChart(chartData);
    }

    // else {
    //   makeChart(fc.randomFinancial()(100))
    // }
  }, [chartData, makeChart]);

  const showcaseContainer = useRef(null);
  const navigationContainer = useRef(null);
  const legendContainer = useRef(null);

  const legend = () => {
    const labelJoin = fc.dataJoin('text', 'legend-label');
    const valueJoin = fc.dataJoin('text', 'legend-value');

    const instance = selection => {
      selection.each((data, selectionIndex, nodes) => {
        labelJoin(d3.select(nodes[selectionIndex]), data)
          .attr('transform', (_, i) => 'translate(5, ' + (i + 1) * 30 + ')')
          .attr('x', '10%')
          .text(d => d.name);

        valueJoin(d3.select(nodes[selectionIndex]), data)
          .attr('transform', (_, i) => 'translate(5, ' + (i + 1) * 30 + ')')
          .attr('x', '15%')
          .text(d => d.value);
      });
    };

    instance.xScale = () => instance;
    instance.yScale = () => instance;
    return instance;
  };

  const priceFormat = d3.format(',.2f');
  const volumeFormat = d3.format(',.4s');

  const legendData = datum => [
    { name: 'O', value: priceFormat(datum.open) },
    { name: 'H', value: priceFormat(datum.high) },
    { name: 'L', value: priceFormat(datum.low) },
    { name: 'C', value: priceFormat(datum.close) },
    { name: 'V', value: volumeFormat(datum.volume) }
  ];

  function makeChart(data) {
    //Extents calculate the domain/(min/max) of data
    var yExtent = fc
      .extentLinear()
      .accessors([
        function(d) {
          return d.high;
        },
        function(d) {
          return d.low;
        }
      ])
      .pad([0.1, 0.1]);

    var xExtent = fc.extentTime().accessors([
      function(d) {
        return d.date;
      }
    ]);

    // var format = d3.timeFormat('%b %Y');

    var xScale = d3.scaleTime().domain(xExtent(data));

    // xScale.ticks(1111)

    // var x2Scale = d3.scaleTime().domain(xExtent(data));
    // var x2Axis = d3.axisTop(x2Scale);
    // var xScaleSkip = fc.scaleDiscontinuous(d3.scaleTime()).discontinuityProvider(fc.discontinuitySkipWeekends()).domain(xExtent(data))
    var yScale = d3.scaleLinear().domain(yExtent(data));

    var chartData = {
      series: data,
      brushedRange: [0.75, 1],
      crosshair: [],
      currentValueCrosshair: []
    };

    var gridlines = fc
      .annotationSvgGridline()
      .yTicks(10)
      .xTicks(10);

    var area = fc
      .seriesSvgArea()
      .crossValue(function(d) {
        return d.date;
      })
      .mainValue(function(d) {
        return d.close;
      });

    var candlestick = fc.seriesSvgCandlestick();

    var brush = fc.brushX().on('brush', function(evt) {
      // if the brush has zero height there is no selection
      if (evt.selection) {
        chartData.brushedRange = evt.selection;
        mainChart.xDomain(evt.xDomain);
        render();
      }
    });

    var navigationMulti = fc
      .seriesSvgMulti()
      .series([area, brush])
      .mapping((data, index, series) => {
        switch (series[index]) {
          case area:
            return data.series;
          case brush:
            return data.brushedRange;
        }
      });

    const chartLegend = legend();
    const crosshair = fc
      .annotationSvgCrosshair()
      .x(d => xScale(d.date))
      .xLabel('')
      .y(d => yScale(d.close))
      .yLabel('');
    const currentValueCrosshair = fc
      .annotationSvgCrosshair()
      .y(d => yScale(d.close))
      .yLabel('Close');

    chartData.currentValueCrosshair[0] =
      chartData.series[chartData.series.length - 1];
    const mainMulti = fc
      .seriesSvgMulti()
      .series([gridlines, candlestick, crosshair, currentValueCrosshair])

      .mapping((data, index, series) => {
        switch (series[index]) {
          // case chartLegend:
          //   const lastPoint = data.series[data.series.length - 1];
          //   return legendData(lastPoint)
          case crosshair:
            return data.crosshair;
          case currentValueCrosshair:
            return data.currentValueCrosshair;
          default:
            return data.series;
        }
      });

    var mainChart = fc.chartCartesian(xScale, yScale).svgPlotArea(mainMulti);

    // {
    //   d3.select("#legend-container")
    //     .datum(legendData(data[data.length - 1]))
    //     .call(chartLegend);
    // });

    var navigatorChart = fc
      .chartCartesian(xScale.copy(), yScale.copy())

      // .decorate(selection => {
      //   selection.enter().append('d3fc-svg').style('grid-column', 3)
      //     .style('grid-row', 3).on('measure.x2-axis', () => {
      //       x2Scale.range([d3.event.detail.width, 0]);
      //       console.log(d3.event.detail.width)
      //     }).on('draw.x2-axis', (d, i, nodes) => {
      //       // draw the axis into the svg within the d3fc-svg element
      //       d3.select(nodes[i])
      //         .select('svg')
      //         .call(x2Axis);
      //     });
      // })
      .svgPlotArea(navigationMulti);

    var scale = d3.scaleTime().domain(xScale.domain());
    mainChart.xDomain(chartData.brushedRange.map(scale.invert));

    const render = () => {
      d3.selectAll('#legend-container > *').remove();
      d3.select('#showcase-container')
        .datum(chartData)
        .call(mainChart);

      if (chartData.crosshair[0] !== undefined) {
        d3.select('#legend-container')
          .datum(legendData(chartData.crosshair[0]))
          .call(chartLegend);
      } else {
        d3.select('#legend-container')
          .datum(legendData(chartData.series[chartData.series.length - 1]))
          .call(chartLegend);
      }
      const pointer = fc.pointer().on('point', event => {
        chartData.crosshair = event.map(({ x }) => {
          const closestIndex = d3
            .bisector(d => d.date)
            .left(chartData.series, xScale.invert(x));
          return chartData.series[closestIndex];
        });
        render();

        // chartData.crosshair = event.map(pointer => {
        //   console.log(pointer)
        //   closest(chartData, d =>
        //     Math.abs(xScale.invert(pointer.x).getTime() - d.date.getTime())
        //   )
        // }
        // );
        // render()
      });

      d3.select('#showcase-container .plot-area').call(pointer);
    };

    // d3.select("#legend-container").datum(legendData(data[data.length - 1])).call(chartLegend);

    d3.select('#navigation-container')
      .datum(chartData)
      .call(navigatorChart);

    render();
  }

  return (

      <svg ref={legendContainer} id="legend-container" />

  );
};
// .decorate(function (selection) {
//   var enter = selection.enter();
//   // console.log(enter)
//   // var handles = enter.select('.plot-line')
//   // console.log(handles)
//   var line = (d3.select('.plot-line'))
//   console.log("line", line)
//   var brush = (d3.select('.brush'))
//   console.log("brush", brush)
//   var handles = brush.selectAll('.handle')
//   console.log("handle", handles)
//   handles
//     .append('circle')
//     .attr('cy', 30)
//     .attr('r', 7)
//     .attr('class', 'outer-handle');
//   handles
//     .append('circle')
//     .attr('cy', 30)
//     .attr('r', 4)
//     .attr('class', 'inner-handle');
// })
export default Chart;
<commit_msg>fixed linting<commit_after>import React, { useRef, useEffect } from 'react';
import './chart.css';
import * as d3 from 'd3';
import * as fc from 'd3fc';

const Chart = ({ chartData }) => {
  useEffect(() => {
    if (chartData != null) {
      chartData.sort((a, b) => {
        return a.date - b.date;
      });
      makeChart(chartData);
    }

    // else {
    //   makeChart(fc.randomFinancial()(100))
    // }
  }, [chartData, makeChart]);

  const showcaseContainer = useRef(null);
  const navigationContainer = useRef(null);
  const legendContainer = useRef(null);

  const legend = () => {
    const labelJoin = fc.dataJoin('text', 'legend-label');
    const valueJoin = fc.dataJoin('text', 'legend-value');

    const instance = selection => {
      selection.each((data, selectionIndex, nodes) => {
        labelJoin(d3.select(nodes[selectionIndex]), data)
          .attr('transform', (_, i) => 'translate(5, ' + (i + 1) * 30 + ')')
          .attr('x', '10%')
          .text(d => d.name);

        valueJoin(d3.select(nodes[selectionIndex]), data)
          .attr('transform', (_, i) => 'translate(5, ' + (i + 1) * 30 + ')')
          .attr('x', '15%')
          .text(d => d.value);
      });
    };

    instance.xScale = () => instance;
    instance.yScale = () => instance;
    return instance;
  };

  const priceFormat = d3.format(',.2f');
  const volumeFormat = d3.format(',.4s');

  const legendData = datum => [
    { name: 'O', value: priceFormat(datum.open) },
    { name: 'H', value: priceFormat(datum.high) },
    { name: 'L', value: priceFormat(datum.low) },
    { name: 'C', value: priceFormat(datum.close) },
    { name: 'V', value: volumeFormat(datum.volume) }
  ];

  function makeChart(data) {
    //Extents calculate the domain/(min/max) of data
    var yExtent = fc
      .extentLinear()
      .accessors([
        function (d) {
          return d.high;
        },
        function (d) {
          return d.low;
        }
      ])
      .pad([0.1, 0.1]);

    var xExtent = fc.extentTime().accessors([
      function (d) {
        return d.date;
      }
    ]);

    // var format = d3.timeFormat('%b %Y');

    var xScale = d3.scaleTime().domain(xExtent(data));

    // xScale.ticks(1111)

    // var x2Scale = d3.scaleTime().domain(xExtent(data));
    // var x2Axis = d3.axisTop(x2Scale);
    // var xScaleSkip = fc.scaleDiscontinuous(d3.scaleTime()).discontinuityProvider(fc.discontinuitySkipWeekends()).domain(xExtent(data))
    var yScale = d3.scaleLinear().domain(yExtent(data));

    var chartData = {
      series: data,
      brushedRange: [0.75, 1],
      crosshair: [],
      currentValueCrosshair: []
    };

    var gridlines = fc
      .annotationSvgGridline()
      .yTicks(10)
      .xTicks(10);

    var area = fc
      .seriesSvgArea()
      .crossValue(function (d) {
        return d.date;
      })
      .mainValue(function (d) {
        return d.close;
      });

    var candlestick = fc.seriesSvgCandlestick();

    var brush = fc.brushX().on('brush', function (evt) {
      // if the brush has zero height there is no selection
      if (evt.selection) {
        chartData.brushedRange = evt.selection;
        mainChart.xDomain(evt.xDomain);
        render();
      }
    });

    var navigationMulti = fc
      .seriesSvgMulti()
      .series([area, brush])
      .mapping((data, index, series) => {
        switch (series[index]) {
          case area:
            return data.series;
          case brush:
            return data.brushedRange;
        }
      });

    const chartLegend = legend();
    const crosshair = fc
      .annotationSvgCrosshair()
      .x(d => xScale(d.date))
      .xLabel('')
      .y(d => yScale(d.close))
      .yLabel('');
    const currentValueCrosshair = fc
      .annotationSvgCrosshair()
      .y(d => yScale(d.close))
      .yLabel('Close');

    chartData.currentValueCrosshair[0] =
      chartData.series[chartData.series.length - 1];
    const mainMulti = fc
      .seriesSvgMulti()
      .series([gridlines, candlestick, crosshair, currentValueCrosshair])

      .mapping((data, index, series) => {
        switch (series[index]) {
          // case chartLegend:
          //   const lastPoint = data.series[data.series.length - 1];
          //   return legendData(lastPoint)
          case crosshair:
            return data.crosshair;
          case currentValueCrosshair:
            return data.currentValueCrosshair;
          default:
            return data.series;
        }
      });

    var mainChart = fc.chartCartesian(xScale, yScale).svgPlotArea(mainMulti);

    // {
    //   d3.select("#legend-container")
    //     .datum(legendData(data[data.length - 1]))
    //     .call(chartLegend);
    // });

    var navigatorChart = fc
      .chartCartesian(xScale.copy(), yScale.copy())

      // .decorate(selection => {
      //   selection.enter().append('d3fc-svg').style('grid-column', 3)
      //     .style('grid-row', 3).on('measure.x2-axis', () => {
      //       x2Scale.range([d3.event.detail.width, 0]);
      //       console.log(d3.event.detail.width)
      //     }).on('draw.x2-axis', (d, i, nodes) => {
      //       // draw the axis into the svg within the d3fc-svg element
      //       d3.select(nodes[i])
      //         .select('svg')
      //         .call(x2Axis);
      //     });
      // })
      .svgPlotArea(navigationMulti);

    var scale = d3.scaleTime().domain(xScale.domain());
    mainChart.xDomain(chartData.brushedRange.map(scale.invert));

    const render = () => {
      d3.selectAll('#legend-container > *').remove();
      d3.select('#showcase-container')
        .datum(chartData)
        .call(mainChart);

      if (chartData.crosshair[0] !== undefined) {
        d3.select('#legend-container')
          .datum(legendData(chartData.crosshair[0]))
          .call(chartLegend);
      } else {
        d3.select('#legend-container')
          .datum(legendData(chartData.series[chartData.series.length - 1]))
          .call(chartLegend);
      }
      const pointer = fc.pointer().on('point', event => {
        chartData.crosshair = event.map(({ x }) => {
          const closestIndex = d3
            .bisector(d => d.date)
            .left(chartData.series, xScale.invert(x));
          return chartData.series[closestIndex];
        });
        render();

        // chartData.crosshair = event.map(pointer => {
        //   console.log(pointer)
        //   closest(chartData, d =>
        //     Math.abs(xScale.invert(pointer.x).getTime() - d.date.getTime())
        //   )
        // }
        // );
        // render()
      });

      d3.select('#showcase-container .plot-area').call(pointer);
    };

    // d3.select("#legend-container").datum(legendData(data[data.length - 1])).call(chartLegend);

    d3.select('#navigation-container')
      .datum(chartData)
      .call(navigatorChart);

    render();
  }

  return (

      <svg ref={legendContainer} id="legend-container" />

  );
};
// .decorate(function (selection) {
//   var enter = selection.enter();
//   // console.log(enter)
//   // var handles = enter.select('.plot-line')
//   // console.log(handles)
//   var line = (d3.select('.plot-line'))
//   console.log("line", line)
//   var brush = (d3.select('.brush'))
//   console.log("brush", brush)
//   var handles = brush.selectAll('.handle')
//   console.log("handle", handles)
//   handles
//     .append('circle')
//     .attr('cy', 30)
//     .attr('r', 7)
//     .attr('class', 'outer-handle');
//   handles
//     .append('circle')
//     .attr('cy', 30)
//     .attr('r', 4)
//     .attr('class', 'inner-handle');
// })
export default Chart;
<|endoftext|>


<commit_before>$(document).ready(function(){
    console.log("sha");
    $('.popup__toggle').on('click', popup);
    $('.drawer__toggle').on('click', openDrawer);
    function popup() {
        $('#popup').toggleClass("open");
    }
    function openDrawer() {
        $('#drawer').toggleClass("open");
        console.log("sha");
    }
    function fileHandler(event){
        var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element)
        var reader = new FileReader();
        reader.onload = function(event){
            var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader).
            $("#preview-img").attr('src', data);
        };
        reader.readAsDataURL(file);
    }

    function addImgToInfo() {
        $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper');
    }

    $('#file').on("change", fileHandler);
    $('#submit-img').on('click', addImgToInfo);
});
var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });
}
<commit_msg>More logs<commit_after>$(document).ready(function(){
    console.log("sha");
    $('.popup__toggle').on('click', popup);
    $('.drawer__toggle').on('click', openDrawer);
    function popup() {
        $('#popup').toggleClass("open");
        console.log("sha");
    }
    function openDrawer() {
        $('#drawer').toggleClass("open");
        console.log("sha");
    }
    function fileHandler(event){
        var file = event.target.files[0]; //event.target references the object that dispatched the event (so here it is the input element)
        var reader = new FileReader();
        reader.onload = function(event){
            var data = event.target.result; //again event.target references the object that dispatched the event (here it is reader).
            $("#preview-img").attr('src', data);
        };
        reader.readAsDataURL(file);
    }

    function addImgToInfo() {
        $("#preview-img").clone().attr('id', '').appendTo('#image-wrapper');
    }

    $('#file').on("change", fileHandler);
    $('#submit-img').on('click', addImgToInfo);
});
var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });
}
<|endoftext|>