<commit_before>/* global Bloodhound */

import angular from 'angular';

import gmfDatasourceExternalDataSourcesManager from 'gmf/datasource/ExternalDataSourcesManager.js';

import gmfImportWmsCapabilityLayertreeComponent from 'gmf/import/wmsCapabilityLayertreeComponent.js';

import gmfImportWmtsCapabilityLayertreeComponent from 'gmf/import/wmtsCapabilityLayertreeComponent.js';

import ngeoQueryQuerent from 'ngeo/query/Querent.js';
import {guessServiceTypeByUrl, Type} from 'ngeo/datasource/OGC.js';

/**
 * The definition of an external OGC server
 * @typedef {Object} ExternalOGCServer
 * @property {string} name
 * @property {string} type
 * @property {string} url
 */

/**
 * @type {angular.IModule}
 * @hidden
 */
const module = angular.module('gmfImportdatasource', [
  gmfDatasourceExternalDataSourcesManager.name,
  gmfImportWmsCapabilityLayertreeComponent.name,
  gmfImportWmtsCapabilityLayertreeComponent.name,
  ngeoQueryQuerent.name,
]);

module.run(
  /**
   * @ngInject
   * @param {angular.ITemplateCacheService} $templateCache
   */
  ($templateCache) => {
    // @ts-ignore: webpack
    $templateCache.put('gmf/import/importdatasourceComponent', require('./importdatasourceComponent.html'));
  });

module.value('gmfImportdatasourceTemplateUrl',
  /**
   * @param {angular.IAttributes} $attrs Attributes.
   * @return {string} The template url.
   */
  ($attrs) => {
    const templateUrl = $attrs.gmfImportdatasourceTemplateUrl;
    return templateUrl !== undefined ? templateUrl :
      'gmf/import/importdatasourceComponent';
  });

/**
 * @param {angular.IAttributes} $attrs Attributes.
 * @param {function(angular.IAttributes): string} gmfImportdatasourceTemplateUrl Template function.
 * @return {string} Template URL.
 * @ngInject
 * @private
 * @hidden
 */
function gmfImportdatasourceTemplateUrl($attrs, gmfImportdatasourceTemplateUrl) {
  return gmfImportdatasourceTemplateUrl($attrs);
}

/**
 * @enum {string}
 * @hidden
 */
const Mode = {
  LOCAL: 'Local',
  ONLINE: 'Online'
};

/**
 * @private
 * @hidden
 */
class Controller {

  /**
   * @param {JQuery} $element Element.
   * @param {angular.IFilterService} $filter Angular filter.
   * @param {angular.auto.IInjectorService} $injector Main injector.
   * @param {angular.IScope} $scope Angular scope.
   * @param {angular.ITimeoutService} $timeout Angular timeout service.
   * @param {import("gmf/datasource/ExternalDataSourcesManager.js").ExternalDatSourcesManager}
   *     gmfExternalDataSourcesManager GMF service responsible of managing
   *     external data sources.
   * @param {import("ngeo/query/Querent.js").Querent} ngeoQuerent Ngeo querent service.
   * @private
   * @ngInject
   * @ngdoc controller
   * @ngname GmfImportdatasourceController
   */
  constructor($element, $filter, $injector, $scope, $timeout,
    gmfExternalDataSourcesManager, ngeoQuerent) {

    // Binding properties

    /**
     * @type {?import("ol/Map.js").default}
     */
    this.map = null;

    // Injected properties

    /**
     * @type {JQuery}
     * @private
     */
    this.element_ = $element;

    /**
     * @type {angular.IScope}
     * @private
     */
    this.scope_ = $scope;

    /**
     * @type {angular.ITimeoutService}
     * @private
     */
    this.timeout_ = $timeout;

    /**
     * @type {import("gmf/datasource/ExternalDataSourcesManager.js").ExternalDatSourcesManager}
     * @private
     */
    this.gmfExternalDataSourcesManager_ = gmfExternalDataSourcesManager;

    /**
     * @type {import("ngeo/query/Querent.js").Querent}
     * @private
     */
    this.ngeoQuerent_ = ngeoQuerent;

    // Model properties

    /**
     * @type {?File}
     */
    this.file = null;

    /**
     * @type {?string}
     */
    this.url = null;

    // Inner properties

    /**
     * @type {JQuery}
     * @private
     */
    this.fileInput_ = $element.find('input[type=file]');

    /**
     * @type {boolean}
     */
    this.hasError = false;

    /**
     * @type {?angular.IPromise<void>}
     * @private
     */
    this.hasErrorPromise_ = null;

    /**
     * @type {string}
     */
    this.mode = Mode.ONLINE;

    /**
     * @type {string[]}
     */
    this.modes = [Mode.LOCAL, Mode.ONLINE];

    /**
     * @type {boolean}
     */
    this.pending = false;

    /**
     * @type {import('ngeo/misc/filters.js').unitPrefix}
     * @private
     */
    this.unitPrefixFormat_ = /** @type {import('ngeo/misc/filters.js').unitPrefix} */ (
      $filter('ngeoUnitPrefix'));

    /**
     * Current WMS Capabilities that were connected.
     * @type {?Object}
     */
    this.wmsCapabilities = null;

    /**
     * Current WTMS Capabilities that were connected.
     * @type {?Object}
     */
    this.wmtsCapabilities = null;

    /**
     * @type {?Bloodhound<string>}
     * @private
     */
    this.serversEngine_ = null;

    /** @type {?ExternalOGCServer[]} */
    const servers = $injector.has('gmfExternalOGCServers') ? $injector.get('gmfExternalOGCServers')
      : null;

    if (servers) {
      const serverUrls = servers.map(server => server.url);
      this.serversEngine_ = new Bloodhound({
        /**
         * Allows search queries to match from string from anywhere within
         * the url, and not only from the beginning of the string (which is
         * the default, non-configurable behaviour of bloodhound).
         *
         * Borrowed from:
         * https://stackoverflow.com/questions/22059933/twitter-typeahead-js-how-to-return-all-matched-elements-within-a-string
         *
         * @param {string} datum Datum.
         * @return {string[]} List of datum tokenizers.
         */
        datumTokenizer: (datum) => {
          if (typeof datum != 'string') {
            throw new Error('Wrong datum type');
          }
          const originalDatumTokenizers = Bloodhound.tokenizers.whitespace(datum);
          if (!originalDatumTokenizers) {
            throw new Error('Missing originalDatumTokenizers');
          }
          const datumTokenizers = [];
          for (const originalDatumTokenizer of originalDatumTokenizers) {
            let i = 0;
            while ((i + 1) < originalDatumTokenizer.length) {
              datumTokenizers.push(
                originalDatumTokenizer.substr(
                  i,
                  originalDatumTokenizer.length
                )
              );
              i++;
            }
          }
          return datumTokenizers;
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: serverUrls
      });
    }

    // Register input[type=file] onchange event, use HTML5 File api
    this.fileInput_.on('change', () => {
      const fileInput = /** @type {HTMLInputElement} */(this.fileInput_[0]);
      const files = fileInput.files;
      this.file = files && files[0] ? files[0] : null;
      this.scope_.$apply();
    });
  }

  /**
   * Called on initialization of the component.
   */
  $onInit() {
    this.gmfExternalDataSourcesManager_.map = this.map;

    if (this.serversEngine_) {
      // Timeout to let Angular render the placeholder of the input properly,
      // otherwise typeahead would copy the string with {{}} in it...
      this.timeout_(() => {
        if (!this.serversEngine_) {
          throw new Error('Missing serversEngine');
        }
        const $urlInput = this.element_.find('input[name=url]');
        const $connectBtn = this.element_.find('button.gmf-importdatasource-connect-btn');
        $urlInput.typeahead({
          hint: true,
          highlight: true,
          minLength: 1
        }, {
          name: 'url',
          source: this.serversEngine_.ttAdapter()
        }).bind('typeahead:select', (ev, suggestion) => {
          this.timeout_(() => {
            this.url = suggestion;
            this.scope_.$apply();
            $connectBtn.focus();
          });
        });
      });
    }
  }

  /**
   * Triggers a 'click' on the "Browse" button.
   */
  browse() {
    this.hasError = false;
    this.element_.find('input[type=file][name=file]').click();
  }

  /**
   * Connect to given online resource URL.
   */
  connect() {
    if (!this.url) {
      throw new Error('Missing url');
    }
    const url = this.url;
    const serviceType = guessServiceTypeByUrl(url);

    this.startWorking_();
    if (serviceType === Type.WMS) {
      this.ngeoQuerent_.wmsGetCapabilities(url).then(
        (wmsCapabilities) => {
          this.wmsCapabilities = wmsCapabilities;
          this.stopWorking_();
        },
        () => {
          // Something went wrong...
          this.stopWorking_(true);
        }
      );
    } else if (serviceType === Type.WMTS) {
      this.ngeoQuerent_.wmtsGetCapabilities(url).then(
        (wmtsCapabilities) => {
          this.wmtsCapabilities = wmtsCapabilities;
          this.stopWorking_();
        },
        () => {
          // Something went wrong...
          this.stopWorking_(true);
        }
      );
    } else {
      // Could not determine the type of url
      this.timeout_(() => {
        this.stopWorking_(true);
      });
    }
  }

  /**
   * Create data source from file.
   */
  load() {
    if (!this.file) {
      throw new Error('Missing file');
    }
    const file = this.file;
    this.gmfExternalDataSourcesManager_.createAndAddDataSourceFromFile(file, (success) => {
      if (!success) {
        this.hasError = true;
      }
    });
  }

  /**
   * @return {string} The name of the file and human-readable size.
   */
  get fileNameAndSize() {
    if (!this.file) {
      return '';
    }
    let nameAndSize = '';

    const file = this.file;
    if (file !== undefined) {
      const fileSize = this.unitPrefixFormat_(file.size, 'o');
      nameAndSize = `${file.name}, ${fileSize}`;
    }

    return nameAndSize;
  }

  // === Private methods ===

  /**
   * @private
   */
  startWorking_() {
    this.pending = true;
    this.hasError = false;

    // Clear any previous objects
    this.wmsCapabilities = null;
    this.wmtsCapabilities = null;
  }

  /**
   * @param {boolean=} opt_hasError Whether we stopped working because of after
   *     an error.
   * @private
   */
  stopWorking_(opt_hasError = false) {
    this.pending = false;
    if (opt_hasError) {
      this.hasError = true;
      if (this.hasErrorPromise_) {
        this.timeout_.cancel(this.hasErrorPromise_);
      }
      this.hasErrorPromise_ = this.timeout_(() => {
        this.hasError = false;
        this.hasErrorPromise_ = null;
      }, 3000);
    }
  }
}

module.component('gmfImportdatasource', {
  bindings: {
    'map': '<'
  },
  controller: Controller,
  templateUrl: gmfImportdatasourceTemplateUrl
});

export default module;
<commit_msg>Display the list of online servers by default<commit_after>/* global Bloodhound */

import angular from 'angular';

import gmfDatasourceExternalDataSourcesManager from 'gmf/datasource/ExternalDataSourcesManager.js';

import gmfImportWmsCapabilityLayertreeComponent from 'gmf/import/wmsCapabilityLayertreeComponent.js';

import gmfImportWmtsCapabilityLayertreeComponent from 'gmf/import/wmtsCapabilityLayertreeComponent.js';

import ngeoQueryQuerent from 'ngeo/query/Querent.js';
import {guessServiceTypeByUrl, Type} from 'ngeo/datasource/OGC.js';

/**
 * The definition of an external OGC server
 * @typedef {Object} ExternalOGCServer
 * @property {string} name
 * @property {string} type
 * @property {string} url
 */

/**
 * @type {angular.IModule}
 * @hidden
 */
const module = angular.module('gmfImportdatasource', [
  gmfDatasourceExternalDataSourcesManager.name,
  gmfImportWmsCapabilityLayertreeComponent.name,
  gmfImportWmtsCapabilityLayertreeComponent.name,
  ngeoQueryQuerent.name,
]);

module.run(
  /**
   * @ngInject
   * @param {angular.ITemplateCacheService} $templateCache
   */
  ($templateCache) => {
    // @ts-ignore: webpack
    $templateCache.put('gmf/import/importdatasourceComponent', require('./importdatasourceComponent.html'));
  });

module.value('gmfImportdatasourceTemplateUrl',
  /**
   * @param {angular.IAttributes} $attrs Attributes.
   * @return {string} The template url.
   */
  ($attrs) => {
    const templateUrl = $attrs.gmfImportdatasourceTemplateUrl;
    return templateUrl !== undefined ? templateUrl :
      'gmf/import/importdatasourceComponent';
  });

/**
 * @param {angular.IAttributes} $attrs Attributes.
 * @param {function(angular.IAttributes): string} gmfImportdatasourceTemplateUrl Template function.
 * @return {string} Template URL.
 * @ngInject
 * @private
 * @hidden
 */
function gmfImportdatasourceTemplateUrl($attrs, gmfImportdatasourceTemplateUrl) {
  return gmfImportdatasourceTemplateUrl($attrs);
}

/**
 * @enum {string}
 * @hidden
 */
const Mode = {
  LOCAL: 'Local',
  ONLINE: 'Online'
};

/**
 * @private
 * @hidden
 */
class Controller {

  /**
   * @param {JQuery} $element Element.
   * @param {angular.IFilterService} $filter Angular filter.
   * @param {angular.auto.IInjectorService} $injector Main injector.
   * @param {angular.IScope} $scope Angular scope.
   * @param {angular.ITimeoutService} $timeout Angular timeout service.
   * @param {import("gmf/datasource/ExternalDataSourcesManager.js").ExternalDatSourcesManager}
   *     gmfExternalDataSourcesManager GMF service responsible of managing
   *     external data sources.
   * @param {import("ngeo/query/Querent.js").Querent} ngeoQuerent Ngeo querent service.
   * @private
   * @ngInject
   * @ngdoc controller
   * @ngname GmfImportdatasourceController
   */
  constructor($element, $filter, $injector, $scope, $timeout,
    gmfExternalDataSourcesManager, ngeoQuerent) {

    // Binding properties

    /**
     * @type {?import("ol/Map.js").default}
     */
    this.map = null;

    // Injected properties

    /**
     * @type {JQuery}
     * @private
     */
    this.element_ = $element;

    /**
     * @type {angular.IScope}
     * @private
     */
    this.scope_ = $scope;

    /**
     * @type {angular.ITimeoutService}
     * @private
     */
    this.timeout_ = $timeout;

    /**
     * @type {import("gmf/datasource/ExternalDataSourcesManager.js").ExternalDatSourcesManager}
     * @private
     */
    this.gmfExternalDataSourcesManager_ = gmfExternalDataSourcesManager;

    /**
     * @type {import("ngeo/query/Querent.js").Querent}
     * @private
     */
    this.ngeoQuerent_ = ngeoQuerent;

    // Model properties

    /**
     * @type {?File}
     */
    this.file = null;

    /**
     * @type {?string}
     */
    this.url = null;

    // Inner properties

    /**
     * @type {JQuery}
     * @private
     */
    this.fileInput_ = $element.find('input[type=file]');

    /**
     * @type {boolean}
     */
    this.hasError = false;

    /**
     * @type {?angular.IPromise<void>}
     * @private
     */
    this.hasErrorPromise_ = null;

    /**
     * @type {string}
     */
    this.mode = Mode.ONLINE;

    /**
     * @type {string[]}
     */
    this.modes = [Mode.LOCAL, Mode.ONLINE];

    /**
     * @type {boolean}
     */
    this.pending = false;

    /**
     * @type {import('ngeo/misc/filters.js').unitPrefix}
     * @private
     */
    this.unitPrefixFormat_ = /** @type {import('ngeo/misc/filters.js').unitPrefix} */ (
      $filter('ngeoUnitPrefix'));

    /**
     * Current WMS Capabilities that were connected.
     * @type {?Object}
     */
    this.wmsCapabilities = null;

    /**
     * Current WTMS Capabilities that were connected.
     * @type {?Object}
     */
    this.wmtsCapabilities = null;

    /**
     * @type {?Bloodhound<string>}
     * @private
     */
    this.serversEngine_ = null;

    /** @type {?ExternalOGCServer[]} */
    const servers = $injector.has('gmfExternalOGCServers') ? $injector.get('gmfExternalOGCServers')
      : null;

    if (servers) {
      const serverUrls = servers.map(server => server.url);
      this.serversEngine_ = new Bloodhound({
        /**
         * Allows search queries to match from string from anywhere within
         * the url, and not only from the beginning of the string (which is
         * the default, non-configurable behaviour of bloodhound).
         *
         * Borrowed from:
         * https://stackoverflow.com/questions/22059933/twitter-typeahead-js-how-to-return-all-matched-elements-within-a-string
         *
         * @param {string} datum Datum.
         * @return {string[]} List of datum tokenizers.
         */
        datumTokenizer: (datum) => {
          if (typeof datum != 'string') {
            throw new Error('Wrong datum type');
          }
          const originalDatumTokenizers = Bloodhound.tokenizers.whitespace(datum);
          if (!originalDatumTokenizers) {
            throw new Error('Missing originalDatumTokenizers');
          }
          const datumTokenizers = [];
          for (const originalDatumTokenizer of originalDatumTokenizers) {
            let i = 0;
            while ((i + 1) < originalDatumTokenizer.length) {
              datumTokenizers.push(
                originalDatumTokenizer.substr(
                  i,
                  originalDatumTokenizer.length
                )
              );
              i++;
            }
          }
          return datumTokenizers;
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: serverUrls
      });
    }

    // Register input[type=file] onchange event, use HTML5 File api
    this.fileInput_.on('change', () => {
      const fileInput = /** @type {HTMLInputElement} */(this.fileInput_[0]);
      const files = fileInput.files;
      this.file = files && files[0] ? files[0] : null;
      this.scope_.$apply();
    });
  }

  /**
   * Called on initialization of the component.
   */
  $onInit() {
    this.gmfExternalDataSourcesManager_.map = this.map;

    if (this.serversEngine_) {

      /**
       * @param {string} query Query string.
       * @param {function(Array<string>):void} sync
       */
      const serversEngineWithDefaults = (query, sync) => {
        if (!this.serversEngine_) {
          throw new Error('Missing serversEngine');
        }
        if (query === '') {
          sync(this.serversEngine_.all());
        } else {
          this.serversEngine_.search(query, sync);
        }
      };
      // Timeout to let Angular render the placeholder of the input properly,
      // otherwise typeahead would copy the string with {{}} in it...
      this.timeout_(() => {
        const $urlInput = this.element_.find('input[name=url]');
        const $connectBtn = this.element_.find('button.gmf-importdatasource-connect-btn');
        $urlInput.typeahead({
          hint: true,
          highlight: true,
          minLength: 0
        }, {
          name: 'url',
          source: serversEngineWithDefaults
        }).bind('typeahead:select', (ev, suggestion) => {
          this.timeout_(() => {
            this.url = suggestion;
            this.scope_.$apply();
            $connectBtn.focus();
          });
        });
      });
    }
  }

  /**
   * Triggers a 'click' on the "Browse" button.
   */
  browse() {
    this.hasError = false;
    this.element_.find('input[type=file][name=file]').click();
  }

  /**
   * Connect to given online resource URL.
   */
  connect() {
    if (!this.url) {
      throw new Error('Missing url');
    }
    const url = this.url;
    const serviceType = guessServiceTypeByUrl(url);

    this.startWorking_();
    if (serviceType === Type.WMS) {
      this.ngeoQuerent_.wmsGetCapabilities(url).then(
        (wmsCapabilities) => {
          this.wmsCapabilities = wmsCapabilities;
          this.stopWorking_();
        },
        () => {
          // Something went wrong...
          this.stopWorking_(true);
        }
      );
    } else if (serviceType === Type.WMTS) {
      this.ngeoQuerent_.wmtsGetCapabilities(url).then(
        (wmtsCapabilities) => {
          this.wmtsCapabilities = wmtsCapabilities;
          this.stopWorking_();
        },
        () => {
          // Something went wrong...
          this.stopWorking_(true);
        }
      );
    } else {
      // Could not determine the type of url
      this.timeout_(() => {
        this.stopWorking_(true);
      });
    }
  }

  /**
   * Create data source from file.
   */
  load() {
    if (!this.file) {
      throw new Error('Missing file');
    }
    const file = this.file;
    this.gmfExternalDataSourcesManager_.createAndAddDataSourceFromFile(file, (success) => {
      if (!success) {
        this.hasError = true;
      }
    });
  }

  /**
   * @return {string} The name of the file and human-readable size.
   */
  get fileNameAndSize() {
    if (!this.file) {
      return '';
    }
    let nameAndSize = '';

    const file = this.file;
    if (file !== undefined) {
      const fileSize = this.unitPrefixFormat_(file.size, 'o');
      nameAndSize = `${file.name}, ${fileSize}`;
    }

    return nameAndSize;
  }

  // === Private methods ===

  /**
   * @private
   */
  startWorking_() {
    this.pending = true;
    this.hasError = false;

    // Clear any previous objects
    this.wmsCapabilities = null;
    this.wmtsCapabilities = null;
  }

  /**
   * @param {boolean=} opt_hasError Whether we stopped working because of after
   *     an error.
   * @private
   */
  stopWorking_(opt_hasError = false) {
    this.pending = false;
    if (opt_hasError) {
      this.hasError = true;
      if (this.hasErrorPromise_) {
        this.timeout_.cancel(this.hasErrorPromise_);
      }
      this.hasErrorPromise_ = this.timeout_(() => {
        this.hasError = false;
        this.hasErrorPromise_ = null;
      }, 3000);
    }
  }
}

module.component('gmfImportdatasource', {
  bindings: {
    'map': '<'
  },
  controller: Controller,
  templateUrl: gmfImportdatasourceTemplateUrl
});

export default module;
<|endoftext|>


<commit_before>'use strict';

(function (angular, window) {
  angular
    .module('eventsFeedPluginDesign')
    .controller('DesignHomeCtrl', ['$scope', 'Buildfire', 'LAYOUTS', 'DataStore', 'TAG_NAMES',
      function ($scope, Buildfire, LAYOUTS, DataStore, TAG_NAMES) {
        var DesignHome = this;
        var DesignHomeMaster;

        DesignHome.layouts = {
          itemDetailsLayout: [
            {name: "Event_Item_1"},
            {name: "Event_Item_2"},
            {name: "Event_Item_3"},
            {name: "Event_Item_4"}
          ]
        };

        /*On layout click event*/
        DesignHome.changeItemLayout = function (layoutName) {
          if (layoutName && DesignHome.data.design) {
            DesignHome.data.design.itemDetailsLayout = layoutName;
            saveData(function (err, data) {
                if (err) {
                  return DesignHome.data = angular.copy(DesignHomeMaster);
                }
                else if (data && data.obj) {

                  return DesignHomeMaster = data.obj;

                }
                $scope.$digest();
              }
            )
          }
        };

        /*save method*/
        var saveData = function(callback) {
          callback = callback || function () {

          };
          Buildfire.datastore.save(DesignHome.data, TAG_NAMES.EVENTS_FEED_INFO, callback);
        };

        /* background image add <start>*/
        var background = new Buildfire.components.images.thumbnail("#background");
        var eventTitleImage = new Buildfire.components.images.thumbnail("#eventTitleImage",{ title: "Events Title Background Image"});

        /**
         * init()
         * It is used to fetch previously saved user's data
         */
        var init = function() {
          var _data = {
            design: {
              itemDetailsLayout: "",
              itemDetailsBgImage: ""
            },
            content: {
              feedUrl: ""
            }
          };

          /* background image add </end>*/
          Buildfire.datastore.get(TAG_NAMES.EVENTS_FEED_INFO, function (err, data) {
            if (err) {
              Console.log('------------Error in Design of People Plugin------------', err);
            }
            else if (data && data.data) {
              DesignHome.data = angular.copy(data.data);
              console.log("init Data:", DesignHome.data);
              if (!DesignHome.data.design)
                DesignHome.data.design = {};
              if (!DesignHome.data.design.itemDetailsLayout)
                DesignHome.data.design.itemDetailsLayout = DesignHome.layouts.itemDetailsLayout[0].name;
              DesignHomeMaster = angular.copy(data.data);
              if (DesignHome.data.design.itemDetailsBgImage) {
                background.loadbackground(DesignHome.data.design.itemDetailsBgImage);
              }
              if (DesignHome.data.design.eventTitleImage) {
                eventTitleImage.loadbackground(DesignHome.data.design.eventTitleImage);
              }
              $scope.$digest();
            }
            else {
              DesignHome.data = _data;
              console.info('------------------unable to load data---------------');
            }
          });
        };

        background.onChange = function (url) {
          DesignHome.data.design.itemDetailsBgImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        background.onDelete = function (url) {
          DesignHome.data.design.itemDetailsBgImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        eventTitleImage.onChange = function (url) {
          DesignHome.data.design.eventTitleImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        eventTitleImage.onDelete = function (url) {
          DesignHome.data.design.eventTitleImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };
        init();

        /*watch the change event and update in database*/
        $scope.$watch(function () {
          return DesignHome.data;
        }, function (oldObj,newObj) {
          if (oldObj!=newObj&&newObj){
            console.log("Updated Object:", newObj);
            Buildfire.datastore.save(DesignHome.data, TAG_NAMES.EVENTS_FEED_INFO, function (err, data) {
              if (err) {
                return DesignHome.data = angular.copy(DesignHomeMaster);
              }
              else if (data && data.obj) {
                return DesignHomeMaster = data.obj;

              }
              $scope.$digest();
            });}
        }, true);
      }]);
})(window.angular);
<commit_msg>Fixed the customer service ticket issue #1017 in design section.<commit_after>'use strict';

(function (angular, window) {
  angular
    .module('eventsFeedPluginDesign')
    .controller('DesignHomeCtrl', ['$scope', 'Buildfire', 'LAYOUTS', 'DataStore', 'TAG_NAMES',
      function ($scope, Buildfire, LAYOUTS, DataStore, TAG_NAMES) {
        var DesignHome = this;
        var DesignHomeMaster;

        DesignHome.layouts = {
          itemDetailsLayout: [
            {name: "Event_Item_1"},
            {name: "Event_Item_2"},
            {name: "Event_Item_3"},
            {name: "Event_Item_4"}
          ]
        };

        /*On layout click event*/
        DesignHome.changeItemLayout = function (layoutName) {
          if (layoutName && DesignHome.data.design) {
            DesignHome.data.design.itemDetailsLayout = layoutName;
            saveData(function (err, data) {
                if (err) {
                  return DesignHome.data = angular.copy(DesignHomeMaster);
                }
                else if (data && data.obj) {

                  return DesignHomeMaster = data.obj;

                }
                $scope.$digest();
              }
            )
          }
        };

        /*save method*/
        var saveData = function(callback) {
          callback = callback || function () {

          };
          Buildfire.datastore.save(DesignHome.data, TAG_NAMES.EVENTS_FEED_INFO, callback);
        };

        /* background image add <start>*/
        var background = new Buildfire.components.images.thumbnail("#background",{ title: "Event Details Background Image"});
        var eventTitleImage = new Buildfire.components.images.thumbnail("#eventTitleImage",{ title: "Top Image for Event Details"});

        /**
         * init()
         * It is used to fetch previously saved user's data
         */
        var init = function() {
          var _data = {
            design: {
              itemDetailsLayout: "",
              itemDetailsBgImage: ""
            },
            content: {
              feedUrl: ""
            }
          };

          /* background image add </end>*/
          Buildfire.datastore.get(TAG_NAMES.EVENTS_FEED_INFO, function (err, data) {
            if (err) {
              Console.log('------------Error in Design of People Plugin------------', err);
            }
            else if (data && data.data) {
              DesignHome.data = angular.copy(data.data);
              console.log("init Data:", DesignHome.data);
              if (!DesignHome.data.design)
                DesignHome.data.design = {};
              if (!DesignHome.data.design.itemDetailsLayout)
                DesignHome.data.design.itemDetailsLayout = DesignHome.layouts.itemDetailsLayout[0].name;
              DesignHomeMaster = angular.copy(data.data);
              if (DesignHome.data.design.itemDetailsBgImage) {
                background.loadbackground(DesignHome.data.design.itemDetailsBgImage);
              }
              if (DesignHome.data.design.eventTitleImage) {
                eventTitleImage.loadbackground(DesignHome.data.design.eventTitleImage);
              }
              $scope.$digest();
            }
            else {
              DesignHome.data = _data;
              console.info('------------------unable to load data---------------');
            }
          });
        };

        background.onChange = function (url) {
          DesignHome.data.design.itemDetailsBgImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        background.onDelete = function (url) {
          DesignHome.data.design.itemDetailsBgImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        eventTitleImage.onChange = function (url) {
          DesignHome.data.design.eventTitleImage = url;
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };

        eventTitleImage.onDelete = function (url) {
          DesignHome.data.design.eventTitleImage = "";
          if (!$scope.$$phase && !$scope.$root.$$phase) {
            $scope.$apply();
          }
        };
        init();

        /*watch the change event and update in database*/
        $scope.$watch(function () {
          return DesignHome.data;
        }, function (oldObj,newObj) {
          if (oldObj!=newObj&&newObj){
            console.log("Updated Object:", newObj);
            Buildfire.datastore.save(DesignHome.data, TAG_NAMES.EVENTS_FEED_INFO, function (err, data) {
              if (err) {
                return DesignHome.data = angular.copy(DesignHomeMaster);
              }
              else if (data && data.obj) {
                return DesignHomeMaster = data.obj;

              }
              $scope.$digest();
            });}
        }, true);
      }]);
})(window.angular);
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  navBar,
  View
} from 'react-native';

// var GiftedListView = require('react-native-gifted-listview');
var weather = require('./tableview.ios.js')
// class nam extends Component {
//    _onFetch(page = 1, callback, options) {
//     setTimeout(() => {
//       var rows = ['row '+((page - 1) * 3 + 1), 'row '+((page - 1) * 3 + 2), 'row '+((page - 1) * 3 + 3)];
//       if (page === 3) {
//         callback(rows, {
//           allLoaded: true, // the end of the list is reached
//         });
//       } else {
//         callback(rows);
//       }
//     }, 1000); // simulating network fetching
//   }
//   _onPress(rowData) {
//     console.log(rowData+' pressed');
//   }

//   /**
//    * Render a row
//    * @param {object} rowData Row data
//    */
//   _renderRowView(rowData) {
//     return (
//       <TouchableHighlight
//         style={styles.row}
//         underlayColor='#c8c7cc'
//         onPress={() => this._onPress(rowData)}
//       >
//         <Text>{rowData}</Text>
//       </TouchableHighlight>
//     );
//   }

//   render() {
//     return (
//       <View style={styles.container}>
//         <View style={styles.navBar} />
//         <GiftedListView
//           rowView={this._renderRowView}
//           onFetch={this._onFetch}
//           onPress={this._onPress}
//           firstLoader={true} // display a loader for the first fetching
//           pagination={true} // enable infinite scrolling using touch to load more
//           refreshable={true} // enable pull-to-refresh for iOS and touch-to-refresh for Android
//           withSections={false} // enable sections
//           customStyles={{
//             paginationView: {
//               backgroundColor: '#eee',
//             },
//           }}

//           refreshableTintColor="blue"
//         />
//       </View>
//     );
//   }
// }

// var styles = {
//   container: {
//     flex: 1,
//     backgroundColor: '#FFF',
//   },
//   navBar: {
//     height: 64,
//     backgroundColor: '#CCC'
//   },
//   row: {
//     padding: 10,
//     height: 44,
//   },
// };

AppRegistry.registerComponent('weather', () => weather);
<commit_msg>backup<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  NavigatorIOS,
  View
} from 'react-native';

var weatherTable = require('./tableview.ios.js')
var weather = React.createClass({
  getInitialState() {
    return {
      navigationBarHidden: false
    };
  },

  toggleNavBar() {
    this.setState({
      navigationBarHidden: !this.state.navigationBarHidden
    });
  },

  render() {
    return (
      <NavigatorIOS ref="nav"
                    itemWrapperStyle={styles.navWrap}
                    style={styles.nav}
                    navigationBarHidden={this.state.navigationBarHidden}
                    initialRoute={{
                      title: "城市列表",
                      component: weatherTable,
                      passProps: {
                        toggleNavBar: this.toggleNavBar,
                      }
                    }} />
    );
  }
});

var styles = StyleSheet.create({
  navWrap: {
    flex: 1,
   	marginTop: 70
  },
  nav: {
    flex: 1,
  },
  button: {
    backgroundColor: "#009DDD",
    padding: 10,
    margin: 10,
  },
  buttonText: {
    color: "#fff"
  }
});

AppRegistry.registerComponent('weather', () => weather);
<|endoftext|>


<commit_before>Layouts.application = function(delegate) {
	var tabButtons;

	var win = Ti.UI.createWindow({
		backgroundImage:'images/main_bg.png',
		orientationModes:[Ti.UI.LANDSCAPE_LEFT]
	});

	var main_window_view = Ti.UI.createView({
		left:0,
		width: 964,
		height: "100%"
	});

	var cover_view = Ti.UI.createView({
		backgroundImage: "images/closed_tab_page_bg.png",
		width: 1017,
		height: "100%",
		left: 0
	});

	var cover_image = Ti.UI.createView({
		backgroundImage: "images/closed_tab_all_content_flat.png",
		width: 925,
		height: 500,
		left:50,
		top: 80
	});

	var video = Ti.UI.createButton({
		backgroundImage:"images/video_button.png",
		title: "RF-TVA",
		font:{fontSize:15, fontWeight:"regular"},
		color:"black",
		width: 225,
		height: 50,
		bottom:40,
		left:100
	});

	video.addEventListener('click', function(){
		Controllers.content.video('PML2775.mp4');
	});

	cover_view.add(cover_image);
	cover_view.add(video);

	var main_content = Ti.UI.createView({
		left: 0,
		width: 1017,
		backgroundImage: "images/page_bg.png"
	});

	var nav_cover = Ti.UI.createView({
		right:0,
		width: 60,
		zIndex: 99
	});

	win.add(nav_cover);

	var openApp = function() {
		win.remove(nav_cover);
		// main_window_view.remove(cover_view);
		main_window_view.animate({transition:Ti.UI.iPhone.AnimationStyle.CURL_DOWN, view: main_content});
	}

	var addOpenListener = function() {
		cover_view.addEventListener("swipe", openApp);
		nav_cover.addEventListener("touchend", openApp);
	}

	addOpenListener();

	main_content.addEventListener('backToCover', function() {
		win.add(nav_cover);
		addOpenListener();
		main_window_view.animate({transition:Ti.UI.iPhone.AnimationStyle.CURL_UP, view: cover_view});
		// main_window_view.add(cover_view);
	});

	var nav = Ti.UI.createView({
		layout: "horizontal",
		right: 0,
		top: 37,
		height:"100%",
		width:60
	});

	var makeTab = function(attrs) {
		var tab = Ti.UI.createButton({
			backgroundImage:attrs.background,
			backgroundSelectedImage:attrs.background,
			width:60,
			height:attrs.height,
			top:(attrs.top || 0) - 40,
			right:0,
			id: attrs.name
		});

		tab.addEventListener('click', App.swapView(main_content, Controllers.content.index.p(Formatter.underscore(attrs.name))));
		nav.add(tab);
		return tab;
	}

	var tabs = [
		{name: "Technology", background: "images/tabs/tabs_technology.png", height:160, top:-2}
		, {name: "Results", background: "images/tabs/tabs_results.png", height:150, top:0}
		, {name: "Case Studies", background: "images/tabs/tabs_case_studies.png", height:190, top:0}
		, {name: "Cost", background: "images/tabs/tabs_cost.png", height:150, top: -10}
		, {name: "Reimbursment", background: "images/tabs/tabs_reimbursement.png", height:190,top:-20}
		, {name: "Dfine", background: "images/tabs/tabs_dfine.png", height:150, top: -9}
	]

	tabButtons = map(makeTab, tabs);

	var button_group = UI.ButtonGroup.apply(this, tabButtons);
	first(tabButtons).fireEvent('click');

	main_window_view.add(main_content);
	main_window_view.add(cover_view);
	win.add(main_window_view);
	win.add(nav);
	win.open();
}
<commit_msg>nav fix<commit_after>Layouts.application = function(delegate) {
	var tabButtons;

	var win = Ti.UI.createWindow({
		backgroundImage:'images/main_bg.png',
		orientationModes:[Ti.UI.LANDSCAPE_LEFT]
	});

	var main_window_view = Ti.UI.createView({
		left:0,
		width: 964,
		height: "100%"
	});

	var cover_view = Ti.UI.createView({
		backgroundImage: "images/closed_tab_page_bg.png",
		width: 1017,
		height: "100%",
		left: 0,
		zIndex: 2
	});

	var cover_image = Ti.UI.createView({
		backgroundImage: "images/closed_tab_all_content_flat.png",
		width: 925,
		height: 500,
		left:50,
		top: 80
	});

	var video = Ti.UI.createButton({
		backgroundImage:"images/video_button.png",
		title: "RF-TVA",
		font:{fontSize:15, fontWeight:"regular"},
		color:"black",
		width: 225,
		height: 50,
		bottom:40,
		left:100
	});

	video.addEventListener('click', function(){
		Controllers.content.video('PML2775.mp4');
	});

	cover_view.add(cover_image);
	cover_view.add(video);

	var main_content = Ti.UI.createView({
		left: 0,
		width: 1017,
		backgroundImage: "images/page_bg.png",
		zIndex: 1
	});

	var nav_cover = Ti.UI.createView({
		right:0,
		width: 60,
		zIndex: 99
	});

	win.add(nav_cover);

	var openApp = function() {
		win.remove(nav_cover);
		main_window_view.animate({transition:Ti.UI.iPhone.AnimationStyle.CURL_DOWN, view: main_content}, function() {
			cover_view.zIndex = 0;
		});
	}

	var addOpenListener = function() {
		cover_view.addEventListener("swipe", openApp);
		nav_cover.addEventListener("touchend", openApp);
	}

	addOpenListener();

	main_content.addEventListener('backToCover', function() {
		win.add(nav_cover);
		addOpenListener();
		main_window_view.animate({transition:Ti.UI.iPhone.AnimationStyle.CURL_UP, view: cover_view}, function() {
			cover_view.zIndex = 2;
		});
	});

	var nav = Ti.UI.createView({
		layout: "horizontal",
		right: 0,
		top: 37,
		height:"100%",
		width:60
	});

	var makeTab = function(attrs) {
		var tab = Ti.UI.createButton({
			backgroundImage:attrs.background,
			backgroundSelectedImage:attrs.background,
			width:60,
			height:attrs.height,
			top:(attrs.top || 0) - 40,
			right:0,
			id: attrs.name
		});

		tab.addEventListener('click', App.swapView(main_content, Controllers.content.index.p(Formatter.underscore(attrs.name))));
		nav.add(tab);
		return tab;
	}

	var tabs = [
		{name: "Technology", background: "images/tabs/tabs_technology.png", height:160, top:-2}
		, {name: "Results", background: "images/tabs/tabs_results.png", height:150, top:0}
		, {name: "Case Studies", background: "images/tabs/tabs_case_studies.png", height:190, top:0}
		, {name: "Cost", background: "images/tabs/tabs_cost.png", height:150, top: -10}
		, {name: "Reimbursment", background: "images/tabs/tabs_reimbursement.png", height:190,top:-20}
		, {name: "Dfine", background: "images/tabs/tabs_dfine.png", height:150, top: -9}
	]

	tabButtons = map(makeTab, tabs);

	var button_group = UI.ButtonGroup.apply(this, tabButtons);
	first(tabButtons).fireEvent('click');

	main_window_view.add(main_content);
	main_window_view.add(cover_view);
	win.add(main_window_view);
	win.add(nav);
	win.open();
}
<|endoftext|>


<commit_before>(function () {
    "use strict";
    window.Mapbender = Mapbender || {};
    window.Mapbender.Digitizer = Mapbender.Digitizer || {};

    Mapbender.Digitizer.StyleAdapter = {
        defaultStyle_: null,
        defaultText_: null,
        placeholderPattern_: /\${([^}]+)}/g,
        styleFunctionFromSvgRules: function(styleConfig, dataCallback) {
            var self = this;
            var labelPattern = this.placeholderPattern_;
            return (function() {
                var baseStyle = self.getBaseStyleObject(styleConfig);
                var labelValue = styleConfig.label;
                var textStyle = labelValue && self.getTextStyle(styleConfig);
                return function(feature) {
                    var styles = [baseStyle];
                    if (labelValue) {
                        var labelStyle = new ol.style.Style();
                        if (labelPattern.test(labelValue || '')) {
                            var attributes = dataCallback(feature) || {};
                            var label = labelValue.replace(labelPattern, function(match, attributeName) {
                                return attributes[attributeName] || '';
                            });
                            labelStyle.setText(textStyle.clone());
                            labelStyle.getText().setText(label);
                        } else {
                            textStyle.setText(labelValue);
                            labelStyle.setText(textStyle);
                        }
                        styles.push(labelStyle);
                    }
                    return styles;
                };
            })(styleConfig);
        },
        /**
         * @return {ol.style.Style}
         */
        getDefaultStyleObject: function() {
            if (!this.defaultStyle_) {
                this.defaultStyle_ = ol.style.Style.defaultFunction()[0].clone();
                this.enforceArrayColor_(this.defaultStyle_);
            }
            return this.defaultStyle_.clone();
        },
        getDefaultTextStyle: function() {
            if (!this.defaultText_) {
                this.defaultText_ = new ol.style.Text();
                this.enforceArrayColor_(this.defaultText_);
                this.defaultText_.setOverflow(true);
            }
            return this.defaultText_.clone();
        },
        getBaseStyleObject: function(ol2Style) {
            var newStyle = this.getDefaultStyleObject();

            if (ol2Style.fillColor || (typeof ol2Style.fillOpacity !== 'undefined')) {
                newStyle.getFill().setColor(this.parseSvgColor(ol2Style, 'fillColor', 'fillOpacity', newStyle.getFill().getColor()));
            }
            if (ol2Style.strokeColor || (typeof ol2Style.strokeOpacity !== 'undefined')) {
                newStyle.getStroke().setColor(this.parseSvgColor(ol2Style, 'strokeColor', 'strokeOpacity', newStyle.getStroke().getColor()));
            }

             if (typeof ol2Style.strokeWidth !== 'undefined') {
                 newStyle.getStroke().setWidth(ol2Style.strokeWidth);
             }
             if (typeof ol2Style.strokeLinecap !== 'undefined') {
                 newStyle.getStroke().setLineCap(ol2Style.strokeLinecap);
             }
             newStyle.getStroke().setLineDash(this.dashRuleToComponents(ol2Style.strokeDashstyle));

            newStyle.setZIndex(ol2Style.graphicZIndex || 0);

            var image = new ol.style.Circle({
                fill: newStyle.getFill().clone(),
                stroke: newStyle.getStroke().clone(),
                radius: ol2Style.pointRadius || newStyle.getImage().getRadius()
            });

            newStyle.setImage(image);
            return newStyle;
        },
        getTextStyle: function (ol2Style) {
            var textStyle = this.getDefaultTextStyle();
            textStyle.setFont(this.canvasFontRuleFromSvg(ol2Style));
            textStyle.setText(ol2Style.label);
            if (ol2Style.fontColor || (typeof ol2Style.fontOpacity !== 'undefined')) {
                textStyle.getFill().setColor(this.parseSvgColor(ol2Style, 'fontColor', 'fontOpacity', textStyle.getFill().getColor()));
            }
            return textStyle;
        },
        /**
         * @param {Object} style
         * @param {string} colorProp
         * @param {string} opacityProp
         * @param {Array<Number>} [defaults]
         * @return {Array<Number>}
         */
        parseSvgColor: function(style, colorProp, opacityProp, defaults) {
            var color = Mapbender.StyleUtil.parseSvgColor(style, colorProp, opacityProp);
            // Unlinke Mapbender.StyleUtil, fill in missing properties using native OL6 defaults, instead of
            // OL2 SVG defaults
            if (!style[colorProp] && defaults) {
                Array.prototype.splice.apply(color, [0, 3].concat(defaults.slice(0, 3)));
            }
            if (!style[opacityProp] && defaults) {
                color.splice(3, 1, defaults[3]);
            }
            return color;
        },
        /**
         * @param {Object} style
         * @param {String} [style.fontFamily]
         * @param {Number} [style.fontSize]
         * @param {String} [style.fontWeight]
         * @return {string}
         */
        canvasFontRuleFromSvg: function(style) {
            var fontFamily = style.fontFamily || "sans-serif";
            var fontSize = style.fontSize && ([style.fontSize, 'px'].join('')) || '';
            var fontWeight = style.fontWeight || "";

            /** @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font */
            return [fontWeight, fontSize, fontFamily].join(" ");
        },
        /**
         * @param {String} dashStyle
         * @return {null|number[]}
         */
        dashRuleToComponents: function(dashStyle) {
            switch (dashStyle) {
                default:
                case 'solid':
                    return null;
                case 'dot':
                    return [1, 5];
                case 'dash':
                    return [10, 10];
                case 'longdash':
                    return [20, 20];
                case 'dashdot':
                    return [5, 10, 1];
                case 'longdashdot':
                    return [5, 20, 1];
            }
        },
        /**
         * @param {ol.style.Style|ol.style.Text} styleComponent
         */
        enforceArrayColor_: function(styleComponent) {
            // Enforce Array types for fill and stroke colors, to support amending missing props with array slices
            if (styleComponent.getStroke() && (typeof (styleComponent.getStroke().getColor()) === 'string')) {
                styleComponent.getStroke().setColor(Mapbender.StyleUtil.parseCssColor(styleComponent.getStroke().getColor()));
            }
            if (styleComponent.getFill() && (typeof (styleComponent.getFill().getColor()) === 'string')) {
                styleComponent.getFill().setColor(Mapbender.StyleUtil.parseCssColor(styleComponent.getFill().getColor()));
            }
        }
    };
})();
<commit_msg>Split StyleAdapter style object methods<commit_after>(function () {
    "use strict";
    window.Mapbender = Mapbender || {};
    window.Mapbender.Digitizer = Mapbender.Digitizer || {};

    Mapbender.Digitizer.StyleAdapter = {
        defaultStyle_: null,
        defaultText_: null,
        placeholderPattern_: /\${([^}]+)}/g,
        styleFunctionFromSvgRules: function(styleConfig, dataCallback) {
            var self = this;
            var labelPattern = this.placeholderPattern_;
            return (function() {
                var baseStyle = self.getBaseStyleObject(styleConfig);
                var labelValue = styleConfig.label;
                var textStyle = labelValue && self.getTextStyle(styleConfig);
                return function(feature) {
                    var styles = [baseStyle];
                    if (labelValue) {
                        var labelStyle = new ol.style.Style();
                        if (labelPattern.test(labelValue || '')) {
                            var attributes = dataCallback(feature) || {};
                            var label = labelValue.replace(labelPattern, function(match, attributeName) {
                                return attributes[attributeName] || '';
                            });
                            labelStyle.setText(textStyle.clone());
                            labelStyle.getText().setText(label);
                        } else {
                            textStyle.setText(labelValue);
                            labelStyle.setText(textStyle);
                        }
                        styles.push(labelStyle);
                    }
                    return styles;
                };
            })(styleConfig);
        },
        /**
         * @return {ol.style.Style}
         */
        getDefaultStyleObject: function() {
            if (!this.defaultStyle_) {
                this.defaultStyle_ = ol.style.Style.defaultFunction()[0].clone();
                this.enforceArrayColor_(this.defaultStyle_);
            }
            return this.defaultStyle_.clone();
        },
        getDefaultTextStyle: function() {
            if (!this.defaultText_) {
                this.defaultText_ = new ol.style.Text();
                this.enforceArrayColor_(this.defaultText_);
                this.defaultText_.setOverflow(true);
            }
            return this.defaultText_.clone();
        },
        /**
         * @param {ol.style.Style} targetStyle
         * @param {Object} styleConfig
         * @private
         */
        resolveColors_: function(targetStyle, styleConfig) {
            if (styleConfig.fillColor || (typeof styleConfig.fillOpacity !== 'undefined')) {
                targetStyle.getFill().setColor(this.parseSvgColor(styleConfig, 'fillColor', 'fillOpacity', targetStyle.getFill().getColor()));
            }
            if (styleConfig.strokeColor || (typeof styleConfig.strokeOpacity !== 'undefined')) {
                targetStyle.getStroke().setColor(this.parseSvgColor(styleConfig, 'strokeColor', 'strokeOpacity', targetStyle.getStroke().getColor()));
            }
        },
        getBaseStyleObject: function(ol2Style) {
            var newStyle = this.getDefaultStyleObject();
            this.resolveColors_(newStyle, ol2Style);

             if (typeof ol2Style.strokeWidth !== 'undefined') {
                 newStyle.getStroke().setWidth(ol2Style.strokeWidth);
             }
             if (typeof ol2Style.strokeLinecap !== 'undefined') {
                 newStyle.getStroke().setLineCap(ol2Style.strokeLinecap);
             }
             newStyle.getStroke().setLineDash(this.dashRuleToComponents(ol2Style.strokeDashstyle));

            newStyle.setZIndex(ol2Style.graphicZIndex || 0);

            var image = new ol.style.Circle({
                fill: newStyle.getFill().clone(),
                stroke: newStyle.getStroke().clone(),
                radius: ol2Style.pointRadius || newStyle.getImage().getRadius()
            });

            newStyle.setImage(image);
            return newStyle;
        },
        getTextStyle: function (ol2Style) {
            var textStyle = this.getDefaultTextStyle();
            textStyle.setFont(this.canvasFontRuleFromSvg(ol2Style));
            this.resolveTextStyle_(textStyle, ol2Style);
            return textStyle;
        },
        /**
         * @param {ol.style.Text} targetStyle
         * @param {Object} styleConfig
         * @private
         */
        resolveTextStyle_: function(targetStyle, styleConfig) {
            targetStyle.setText(styleConfig.label);
            if (styleConfig.fontColor || (typeof styleConfig.fontOpacity !== 'undefined')) {
                targetStyle.getFill().setColor(this.parseSvgColor(styleConfig, 'fontColor', 'fontOpacity', targetStyle.getFill().getColor()));
            }
        },
        /**
         * @param {Object} style
         * @param {string} colorProp
         * @param {string} opacityProp
         * @param {Array<Number>} [defaults]
         * @return {Array<Number>}
         */
        parseSvgColor: function(style, colorProp, opacityProp, defaults) {
            var color = Mapbender.StyleUtil.parseSvgColor(style, colorProp, opacityProp);
            // Unlinke Mapbender.StyleUtil, fill in missing properties using native OL6 defaults, instead of
            // OL2 SVG defaults
            if (!style[colorProp] && defaults) {
                Array.prototype.splice.apply(color, [0, 3].concat(defaults.slice(0, 3)));
            }
            if (!style[opacityProp] && defaults) {
                color.splice(3, 1, defaults[3]);
            }
            return color;
        },
        /**
         * @param {Object} style
         * @param {String} [style.fontFamily]
         * @param {Number} [style.fontSize]
         * @param {String} [style.fontWeight]
         * @return {string}
         */
        canvasFontRuleFromSvg: function(style) {
            var fontFamily = style.fontFamily || "sans-serif";
            var fontSize = style.fontSize && ([style.fontSize, 'px'].join('')) || '';
            var fontWeight = style.fontWeight || "";

            /** @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font */
            return [fontWeight, fontSize, fontFamily].join(" ");
        },
        /**
         * @param {String} dashStyle
         * @return {null|number[]}
         */
        dashRuleToComponents: function(dashStyle) {
            switch (dashStyle) {
                default:
                case 'solid':
                    return null;
                case 'dot':
                    return [1, 5];
                case 'dash':
                    return [10, 10];
                case 'longdash':
                    return [20, 20];
                case 'dashdot':
                    return [5, 10, 1];
                case 'longdashdot':
                    return [5, 20, 1];
            }
        },
        /**
         * @param {ol.style.Style|ol.style.Text} styleComponent
         */
        enforceArrayColor_: function(styleComponent) {
            // Enforce Array types for fill and stroke colors, to support amending missing props with array slices
            if (styleComponent.getStroke() && (typeof (styleComponent.getStroke().getColor()) === 'string')) {
                styleComponent.getStroke().setColor(Mapbender.StyleUtil.parseCssColor(styleComponent.getStroke().getColor()));
            }
            if (styleComponent.getFill() && (typeof (styleComponent.getFill().getColor()) === 'string')) {
                styleComponent.getFill().setColor(Mapbender.StyleUtil.parseCssColor(styleComponent.getFill().getColor()));
            }
        }
    };
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc overview
 * @name sayonaraAdminApp
 * @description
 * # sayonaraAdminApp
 *
 * Main module of the application.
 */
angular
	.module('sayonaraAdminApp', [
		'ngAnimate',
		'ngCookies',
		'ngResource',
		'ngRoute',
		'ngSanitize',
		'ngMaterial',
		'angular-loading-bar',
		'ngQuill',
		'sayonaraAuth',
		'sayonaraPages',
    'sayonaraEntries',
		'sayonaraEntryType',
		'sayonaraCategory',
		'sayonaraAdmin',
	])
	.config(function($routeProvider, $locationProvider,
			$mdThemingProvider, ngQuillConfigProvider) {

		//Configure our Application hash
		//this will remove the default '!'
		$locationProvider.hashPrefix('');

		//Configure the ngmaterial theme
		$mdThemingProvider.theme('default')
			.primaryPalette('indigo')
			.accentPalette('indigo')
			.warnPalette('red')
			.backgroundPalette('grey');

		//Configure our wysiwig
		//ngQuillConfigProvider.set(modules, theme,
		//  placeholder, formats, boundary, readOnly)
		// Image handler from: https://github.com/quilljs/quill/issues/863
		var toolbarOptions = [
		  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
		  ['blockquote', 'code-block'],
		  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
		  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
		  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
		  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
		  [{ 'direction': 'rtl' }],                         // text direction
		  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
		  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
		  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
		  [{ 'font': [] }],
		  [{ 'align': [] }],
		  ['clean'],                                        // remove formatting button
			['link', 'image', 'video']
		];
		ngQuillConfigProvider.set({
        toolbar: {
          container: toolbarOptions,
          handlers: {
            image: function() {
							var range = this.quill.getSelection();
						  var value = prompt('Please enter the image URL');
						  this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
						}
          }
        }
    }, null, 'Sayonara Editor');

		$routeProvider
			.when('/', {
				templateUrl: 'views/main.html',
				controller: 'MainCtrl',
				controllerAs: 'main'
			})
			.when('/login', {
				templateUrl: 'views/login.html',
				controller: 'LoginCtrl',
				controllerAs: 'login'
			})
			.when('/allpages', {
				templateUrl: 'views/allpages.html',
				controller: 'AllpagesCtrl',
				controllerAs: 'allPages'
			})
			.when('/page/edit', {
				templateUrl: 'views/pageedit.html',
				controller: 'PageeditCtrl',
				controllerAs: 'pageEdit'
			})
			.when('/allentries', {
			  templateUrl: 'views/allentries.html',
			  controller: 'AllentriesCtrl',
			  controllerAs: 'allEntries'
			})
      .when('/entry/edit', {
        templateUrl: 'views/entryedit.html',
        controller: 'EntryeditCtrl',
        controllerAs: 'entryEdit'
      })
			.when('/settings', {
			  templateUrl: 'views/settings.html',
			  controller: 'SettingsCtrl',
			  controllerAs: 'settings'
			})
		.when('/admin', {
		  templateUrl: 'views/admin.html',
		  controller: 'AdminCtrl',
		  controllerAs: 'admin'
		})
		.when('/admin/users', {
		  templateUrl: 'views/editusers.html',
		  controller: 'EditusersCtrl',
		  controllerAs: 'editusers'
		})
		.when('/admin/sayonaraconfig', {
		  templateUrl: 'views/sayonaraconfig.html',
		  controller: 'SayonaraconfigCtrl',
		  controllerAs: 'sayonaraConfig'
		})
			.otherwise({
				redirectTo: '/'
			});
	});
<commit_msg>Added a nice if statement for cancelled image inserts<commit_after>'use strict';

/**
 * @ngdoc overview
 * @name sayonaraAdminApp
 * @description
 * # sayonaraAdminApp
 *
 * Main module of the application.
 */
angular
	.module('sayonaraAdminApp', [
		'ngAnimate',
		'ngCookies',
		'ngResource',
		'ngRoute',
		'ngSanitize',
		'ngMaterial',
		'angular-loading-bar',
		'ngQuill',
		'sayonaraAuth',
		'sayonaraPages',
    'sayonaraEntries',
		'sayonaraEntryType',
		'sayonaraCategory',
		'sayonaraAdmin',
	])
	.config(function($routeProvider, $locationProvider,
			$mdThemingProvider, ngQuillConfigProvider) {

		//Configure our Application hash
		//this will remove the default '!'
		$locationProvider.hashPrefix('');

		//Configure the ngmaterial theme
		$mdThemingProvider.theme('default')
			.primaryPalette('indigo')
			.accentPalette('indigo')
			.warnPalette('red')
			.backgroundPalette('grey');

		//Configure our wysiwig
		//ngQuillConfigProvider.set(modules, theme,
		//  placeholder, formats, boundary, readOnly)
		// Image handler from: https://github.com/quilljs/quill/issues/863
		var toolbarOptions = [
		  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
		  ['blockquote', 'code-block'],
		  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
		  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
		  [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
		  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
		  [{ 'direction': 'rtl' }],                         // text direction
		  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
		  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
		  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
		  [{ 'font': [] }],
		  [{ 'align': [] }],
		  ['clean'],                                        // remove formatting button
			['link', 'image', 'video']
		];
		ngQuillConfigProvider.set({
        toolbar: {
          container: toolbarOptions,
          handlers: {
            image: function() {
							var range = this.quill.getSelection();
						  var value = prompt('Please enter the image URL');
							if(!value || value.length <= 0) return true;
						  this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
						}
          }
        }
    }, null, 'Sayonara Editor');

		$routeProvider
			.when('/', {
				templateUrl: 'views/main.html',
				controller: 'MainCtrl',
				controllerAs: 'main'
			})
			.when('/login', {
				templateUrl: 'views/login.html',
				controller: 'LoginCtrl',
				controllerAs: 'login'
			})
			.when('/allpages', {
				templateUrl: 'views/allpages.html',
				controller: 'AllpagesCtrl',
				controllerAs: 'allPages'
			})
			.when('/page/edit', {
				templateUrl: 'views/pageedit.html',
				controller: 'PageeditCtrl',
				controllerAs: 'pageEdit'
			})
			.when('/allentries', {
			  templateUrl: 'views/allentries.html',
			  controller: 'AllentriesCtrl',
			  controllerAs: 'allEntries'
			})
      .when('/entry/edit', {
        templateUrl: 'views/entryedit.html',
        controller: 'EntryeditCtrl',
        controllerAs: 'entryEdit'
      })
			.when('/settings', {
			  templateUrl: 'views/settings.html',
			  controller: 'SettingsCtrl',
			  controllerAs: 'settings'
			})
		.when('/admin', {
		  templateUrl: 'views/admin.html',
		  controller: 'AdminCtrl',
		  controllerAs: 'admin'
		})
		.when('/admin/users', {
		  templateUrl: 'views/editusers.html',
		  controller: 'EditusersCtrl',
		  controllerAs: 'editusers'
		})
		.when('/admin/sayonaraconfig', {
		  templateUrl: 'views/sayonaraconfig.html',
		  controller: 'SayonaraconfigCtrl',
		  controllerAs: 'sayonaraConfig'
		})
			.otherwise({
				redirectTo: '/'
			});
	});
<|endoftext|>


<commit_before>cc.Class({
    extends: cc.Component,

    properties: {
    	player: {
    		default: null,
    		type: cc.Sprite
    	},

    	background: {
    		default: null,
    		type: cc.Node
    	}

    },

    // use this for initialization
    onLoad: function () {

    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
    	let moveBackground = this.player.getComponent('PlayerScript').moveBackground;
    	moveBackground !== 0 && this.background.getComponent('BackgroundScript').moveBackgroundChildren(moveBackground, dt);
    },
});
<commit_msg>implement winGame functionality<commit_after>cc.Class({
    extends: cc.Component,

    properties: {
    	player: {
    		default: null,
    		type: cc.Sprite
    	},

    	background: {
    		default: null,
    		type: cc.Node
    	},
        winLoseLabel: {
            default: null,
            type: cc.Label
        },
        winDistance: 0
    },

    // use this for initialization
    onLoad: function () {
        this.wonFlag = false;
        this.wonPositionX = 0;
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
    	let moveBackground = this.player.getComponent('PlayerScript').moveBackground;
        if (moveBackground !== 0) {
            this.background.getComponent('BackgroundScript').moveBackgroundChildren(moveBackground, dt);
        }

        let floor = this.background.getChildByName('Floor')
        // winGameMessage is, at the moment, called, when the player reaches a certain point in the world
        // this, of course, has to be replaced by a better way to check, whether the player has won (all enemies dead for example)
        if (floor.x < -500 && !this.wonFlag) {
            this.wonFlag = true;
            this.wonPositionX = floor.x;
            this.winGameMessage();
        } else if (this.wonFlag) {
            this.winGame(floor.x, this.wonPositionX)
        }
    },

    winGameMessage: function () {
        this.winLoseLabel.string = 'You Won! Continue to the right for the next Stage >>>';
    },
    winGame: function (floorX, wonPositionX) {
        if (floorX < wonPositionX - this.winDistance) {
            this.wonFlag = false;
            // this loadScene has to load the next stage
            cc.director.loadScene('01startMenu')
        }
    }
});
<|endoftext|>


<commit_before>var canonnEd3d_challenge = {
	//Define Categories
	systemsData: {
		categories: {
			'Challenge': {
				/*'10': {
					name: 'Varati',
					color: 'f5a142',
				},
				'20': {
					name: 'Waypoint',
					color: '42f557',
				},*/

				'30': {
					name: 'Adamastor Planned Route',
					color: 'FF6666',
				},
				'40': {
					name: 'Adamastor Actual Route',
					color: '66ff66',
				},
				'50': {
					name: 'Extrapolated Route',
					color: '666666',
				},
			},
		},
		systems: [],
		"routes": [
			{
				cat: ["30"], 'points': [
					{ 's': 'Synuefe XE-Y c17-7', 'label': 'Synuefe XE-Y c17-7' },
					{ 's': 'HIP 33386', 'label': 'HIP 33386' },
					{ 's': 'HIP 39748', 'label': 'HIP 39748' },
				], 'circle': false
			},
			{
				cat: ["40"], 'points': [
					{ 's': 'Synuefe XE-Y c17-7', 'label': 'Synuefe XE-Y c17-7' },
					{ 's': 'Musca Dark Region PJ-P B6-1', 'label': 'Musca Dark Region PJ-P B6-1' },
					{ 's': 'HIP 69200', 'label': 'HIP 69200' },
				], 'circle': false
			},
			{
				cat: ["50"], 'points': [
					{ 's': 'HIP 39748', 'label': 'HIP 39748' },
					{ 's': 'Chukchan', 'label': 'Chukchan' },
				], 'circle': false
			},
		]
	},

	formatChallenge: function (data) {
		//Here you format POI & Gnosis JSON to ED3D acceptable object

		// this is assuming data is an array []
		for (var i = 0; i < data.length; i++) {
			if (data[i].name && data[i].name.replace(' ', '').length > 1) {
				var poiSite = {};
				poiSite['name'] = data[i].name;
				poiSite['infos'] = data[i].infos + '
EDSM
Signals';
				//Check Site Type and match categories

				var component = data[i].name.split(' ');
				if (poiSite['name'] == 'Varati') {
					poiSite['details'] == 'Start and Finish';
					poiSite['cat'] = [10];

				} else {
					poiSite['cat'] = [20];
				}

				poiSite['url'] = "https://tools.canonn.tech/Signals/?system=" + poiSite['name']
				poiSite['coords'] = {
					x: parseFloat(data[i].pos_x),
					y: parseFloat(data[i].pos_y),
					z: parseFloat(data[i].pos_z),
				};

				// We can then push the site to the object that stores all systems
				canonnEd3d_challenge.systemsData.systems.push(poiSite);
			}
		}
	},

	parseCSVData: function (url, callBack, resolvePromise) {
		Papa.parse(url, {
			download: true,
			header: true,
			complete: function (results) {
				callBack(results.data);

				// after we called the callback
				// (which is synchronous, so we know it's safe here)
				// we can resolve the promise

				document.getElementById("loading").style.display = "none";
				resolvePromise();
			},
		});
	},

	init: function () {
		var p1 = new Promise(function (resolve, reject) {
			canonnEd3d_challenge.parseCSVData('data/csvCache/adamastor.csv', canonnEd3d_challenge.formatChallenge, resolve);
		});

		Promise.all([p1]).then(function () {
			Ed3d.init({
				container: 'edmap',
				json: canonnEd3d_challenge.systemsData,
				withFullscreenToggle: false,
				withHudPanel: true,
				hudMultipleSelect: true,
				effectScaleSystem: [20, 500],
				startAnim: false,
				showGalaxyInfos: true,
				cameraPos: [25, 14100, -12900],
				systemColor: '#FF9D00',
			});
		});
	},
};
<commit_msg>Setting Coords<commit_after>var canonnEd3d_challenge = {
	//Define Categories
	systemsData: {
		categories: {
			'Challenge': {
				/*'10': {
					name: 'Varati',
					color: 'f5a142',
				},
				'20': {
					name: 'Waypoint',
					color: '42f557',
				},*/

				'30': {
					name: 'Adamastor Planned Route',
					color: 'FF6666',
				},
				'40': {
					name: 'Adamastor Actual Route',
					color: '66ff66',
				},
				'50': {
					name: 'Extrapolated Route',
					color: '666666',
				},
			},
		},
		systems: [],
		"routes": [
			{
				cat: ["30"], 'points': [
					{ 's': 'Synuefe XE-Y c17-7', 'label': 'Synuefe XE-Y c17-7' },
					{ 's': 'HIP 33386', 'label': 'HIP 33386' },
					{ 's': 'HIP 39748', 'label': 'HIP 39748' },
				], 'circle': false
			},
			{
				cat: ["40"], 'points': [
					{ 's': 'Synuefe XE-Y c17-7', 'label': 'Synuefe XE-Y c17-7' },
					{ 's': 'Musca Dark Region PJ-P B6-1', 'label': 'Musca Dark Region PJ-P B6-1' },
					{ 's': 'HIP 69200', 'label': 'HIP 69200' },
				], 'circle': false
			},
			{
				cat: ["50"], 'points': [
					{ 's': 'HIP 39748', 'label': 'HIP 39748' },
					{ 's': 'Chukchan', 'label': 'Chukchan' },
				], 'circle': false
			},
		]
	},

	formatChallenge: function (data) {
		//Here you format POI & Gnosis JSON to ED3D acceptable object

		// this is assuming data is an array []
		for (var i = 0; i < data.length; i++) {
			if (data[i].name && data[i].name.replace(' ', '').length > 1) {
				var poiSite = {};
				poiSite['name'] = data[i].name;
				poiSite['infos'] = data[i].infos + '
EDSM
Signals';
				//Check Site Type and match categories

				var component = data[i].name.split(' ');
				if (poiSite['name'] == 'Varati') {
					poiSite['details'] == 'Start and Finish';
					poiSite['cat'] = [10];

				} else {
					poiSite['cat'] = [20];
				}

				poiSite['url'] = "https://tools.canonn.tech/Signals/?system=" + poiSite['name']
				poiSite['coords'] = {
					x: parseFloat(data[i].pos_x),
					y: parseFloat(data[i].pos_y),
					z: parseFloat(data[i].pos_z),
				};

				// We can then push the site to the object that stores all systems
				canonnEd3d_challenge.systemsData.systems.push(poiSite);
			}
		}
	},

	parseCSVData: function (url, callBack, resolvePromise) {
		Papa.parse(url, {
			download: true,
			header: true,
			complete: function (results) {
				callBack(results.data);

				// after we called the callback
				// (which is synchronous, so we know it's safe here)
				// we can resolve the promise

				document.getElementById("loading").style.display = "none";
				resolvePromise();
			},
		});
	},

	init: function () {
		var p1 = new Promise(function (resolve, reject) {
			canonnEd3d_challenge.parseCSVData('data/csvCache/adamastor.csv', canonnEd3d_challenge.formatChallenge, resolve);
		});

		Promise.all([p1]).then(function () {
			Ed3d.init({
				container: 'edmap',
				json: canonnEd3d_challenge.systemsData,
				withFullscreenToggle: false,
				withHudPanel: true,
				hudMultipleSelect: true,
				effectScaleSystem: [20, 500],
				startAnim: false,
				showGalaxyInfos: true,
				playerPos: [142, 56, 40],
				cameraPos: [218, 1000, -279],
				systemColor: '#FF9D00',
			});
		});
	},
};
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import getConfig from "next/config";

import { getAPI, getService } from "../utils/api";

import withErrors from "../components/hoc/with-errors";

import Page from "../layouts/page";

import Header from "../components/api/header";
import Menu from "../components/api/menu";

import Access from "../components/api/access";
import Support from "../components/api/Support";
import Monitoring from "../components/api/monitoring";
import RateLimiting from "../components/api/rate-limiting";
import Partners from "../components/api/partners";
import TechnicalDocumentation from "../components/api/technical-documentation";
import Services from "../components/api/services";
import Content from "../components/api/content";

const { publicRuntimeConfig } = getConfig();
const DEFAULT_LOGO =
  publicRuntimeConfig.DEFAULT_LOGO || "logo-generique-startup-carre.jpg";

const API = ({ api, services }) => {
  const {
    title,
    tagline,
    logo,
    stat,
    score: { detail },
    external_site,
    content,
    clients,
    contract,
    partners
  } = api;

  const { contact, doc_tech, access, monitoring, rate_limiting } = detail;

  const { link: contact_link, description: contact_description } =
    contact || {};

  const {
    link: doc_tech_link,
    external: doc_tech_external,
    description: doc_tech_description
  } = doc_tech || {};

  const {
    is_open: access_open,
    link: access_link,
    description: access_description
  } = access || {};

  const { link: monitoring_link, description: monitoring_description } =
    monitoring || {};

  const { description: rate_limiting_description } = rate_limiting || {};

  return (
    <Page>

      <Menu detail={detail} />

        <Content content={content} />

        <Access
          access_open={access_open}
          access_link={access_link}
          access_description={access_description}
          contract={contract}
          clients={clients}
        />

        <Support
          contact_description={contact_description}
          contact_link={contact_link}
        />

        <Monitoring
          monitoring_description={monitoring_description}
          monitoring_link={monitoring_link}
        />

        <RateLimiting rate_limiting_description={rate_limiting_description} />

        <Partners partners={partners} />

        <TechnicalDocumentation
          doc_tech_description={doc_tech_description}
          doc_tech_link={doc_tech_link}
          doc_tech_external={doc_tech_external}
        />

        <Services services={services} />

    </Page>
  );
};

API.defaultProps = {
  services: null
};

API.propTypes = {
  services: PropTypes.array,
  api: PropTypes.shape({
    logo: PropTypes.string,
    title: PropTypes.string.isRequired,
    tagline: PropTypes.string,
    external_site: PropTypes.string.isRequired,
    stat: PropTypes.shape({
      url: PropTypes.string,
      path: PropTypes.array,
      label: PropTypes.string,
      lastXdays: PropTypes.number
    }),
    score: PropTypes.shape({
      detail: PropTypes.shape({
        contact: PropTypes.shape({
          link: PropTypes.string,
          description: PropTypes.string
        }),
        doc_tech: PropTypes.shape({
          link: PropTypes.string,
          external: PropTypes.string,
          description: PropTypes.string
        }),
        access: PropTypes.shape({
          is_open: PropTypes.bool,
          link: PropTypes.string,
          description: PropTypes.string
        }),
        monitoring: PropTypes.shape({
          link: PropTypes.string,
          description: PropTypes.string
        }),
        rate_limiting: PropTypes.shape({
          description: PropTypes.string
        })
      }).isRequired
    }).isRequired,
    content: PropTypes.string.isRequired,
    clients: PropTypes.array,
    contract: PropTypes.string,
    partners: PropTypes.array
  }).isRequired
};

API.getInitialProps = async ({ query }) => {
  const api = await getAPI(query.apiId);
  let services = null;

  if (api.services && api.services.length > 0) {
    services = await Promise.all(
      api.services.map(service => getService(service))
    );
  }

  return { api, services };
};

export default withErrors(API);
<commit_msg>Fix Support import typo<commit_after>import React from "react";
import PropTypes from "prop-types";
import getConfig from "next/config";

import { getAPI, getService } from "../utils/api";

import withErrors from "../components/hoc/with-errors";

import Page from "../layouts/page";

import Header from "../components/api/header";
import Menu from "../components/api/menu";

import Access from "../components/api/access";
import Support from "../components/api/support";
import Monitoring from "../components/api/monitoring";
import RateLimiting from "../components/api/rate-limiting";
import Partners from "../components/api/partners";
import TechnicalDocumentation from "../components/api/technical-documentation";
import Services from "../components/api/services";
import Content from "../components/api/content";

const { publicRuntimeConfig } = getConfig();
const DEFAULT_LOGO =
  publicRuntimeConfig.DEFAULT_LOGO || "logo-generique-startup-carre.jpg";

const API = ({ api, services }) => {
  const {
    title,
    tagline,
    logo,
    stat,
    score: { detail },
    external_site,
    content,
    clients,
    contract,
    partners
  } = api;

  const { contact, doc_tech, access, monitoring, rate_limiting } = detail;

  const { link: contact_link, description: contact_description } =
    contact || {};

  const {
    link: doc_tech_link,
    external: doc_tech_external,
    description: doc_tech_description
  } = doc_tech || {};

  const {
    is_open: access_open,
    link: access_link,
    description: access_description
  } = access || {};

  const { link: monitoring_link, description: monitoring_description } =
    monitoring || {};

  const { description: rate_limiting_description } = rate_limiting || {};

  return (
    <Page>

      <Menu detail={detail} />

        <Content content={content} />

        <Access
          access_open={access_open}
          access_link={access_link}
          access_description={access_description}
          contract={contract}
          clients={clients}
        />

        <Support
          contact_description={contact_description}
          contact_link={contact_link}
        />

        <Monitoring
          monitoring_description={monitoring_description}
          monitoring_link={monitoring_link}
        />

        <RateLimiting rate_limiting_description={rate_limiting_description} />

        <Partners partners={partners} />

        <TechnicalDocumentation
          doc_tech_description={doc_tech_description}
          doc_tech_link={doc_tech_link}
          doc_tech_external={doc_tech_external}
        />

        <Services services={services} />

    </Page>
  );
};

API.defaultProps = {
  services: null
};

API.propTypes = {
  services: PropTypes.array,
  api: PropTypes.shape({
    logo: PropTypes.string,
    title: PropTypes.string.isRequired,
    tagline: PropTypes.string,
    external_site: PropTypes.string.isRequired,
    stat: PropTypes.shape({
      url: PropTypes.string,
      path: PropTypes.array,
      label: PropTypes.string,
      lastXdays: PropTypes.number
    }),
    score: PropTypes.shape({
      detail: PropTypes.shape({
        contact: PropTypes.shape({
          link: PropTypes.string,
          description: PropTypes.string
        }),
        doc_tech: PropTypes.shape({
          link: PropTypes.string,
          external: PropTypes.string,
          description: PropTypes.string
        }),
        access: PropTypes.shape({
          is_open: PropTypes.bool,
          link: PropTypes.string,
          description: PropTypes.string
        }),
        monitoring: PropTypes.shape({
          link: PropTypes.string,
          description: PropTypes.string
        }),
        rate_limiting: PropTypes.shape({
          description: PropTypes.string
        })
      }).isRequired
    }).isRequired,
    content: PropTypes.string.isRequired,
    clients: PropTypes.array,
    contract: PropTypes.string,
    partners: PropTypes.array
  }).isRequired
};

API.getInitialProps = async ({ query }) => {
  const api = await getAPI(query.apiId);
  let services = null;

  if (api.services && api.services.length > 0) {
    services = await Promise.all(
      api.services.map(service => getService(service))
    );
  }

  return { api, services };
};

export default withErrors(API);
<|endoftext|>


<commit_before>L.NanocubeLayer = L.TileLayer.Canvas.extend({
    initialize: function(options){
        L.TileLayer.Canvas.prototype.initialize.call(this, options);
        this.model = options.model;
        this.variable = options.variable;
        this.colormap = d3.scale.linear()
            .domain(options.colormap.domain)
            .range(options.colormap.colors);

        this.coarselevels = 1;
        this.smooth = false;

        this.show_count = false;
        this.log = true;
    }
});

L.NanocubeLayer.prototype.toggleLog = function(){
    this.log = !this.log;
    this.redraw();
};

L.NanocubeLayer.prototype.toggleShowCount = function(){
    this.show_count = !this.show_count;
    this.redraw();
};

L.NanocubeLayer.prototype.redraw = function(){
    if (this._map) {
	this._reset({hard: false});  //no hard resetting
	this._update();
    }
    for (var i in this._tiles) {
	this._redrawTile(this._tiles[i]);
    }
    return this;
};

L.NanocubeLayer.prototype.drawTile = function(canvas, tilePoint, zoom){
    var drill = Math.min(this.variable.maxlevel-zoom,8) - this.coarselevels ;
    drill = Math.max(0,drill);
    drill = Math.min(8,drill);

    var size = Math.pow(2,drill);
    var ntiles = Math.pow(2,zoom);

    //fix negative tiles
    while(tilePoint.x < 0){
        tilePoint.x += ntiles;
    }

    while(tilePoint.y < 0){
        tilePoint.y += ntiles;
    }

    //fix overflow tiles
    while(tilePoint.x > ntiles){
        tilePoint.x -= ntiles;
    }

    while(tilePoint.y > ntiles){
        tilePoint.y -= ntiles;
    }

    //flip y for nanocubes
    var ty = (ntiles-1)-tilePoint.y;

    var tile = new Tile(tilePoint.x,ty,zoom);
    tile.canvas = canvas;
    tile.drill = drill;
    tile.tilePoint = tilePoint;
    this.tilelist.push(tile);
    console.log('t',this.tilelist);
};

L.NanocubeLayer.prototype.renderTile = function(canvas, size,tilePoint,zoom,
                                                minv,maxv,data){
    var ctx = canvas.getContext('2d');

    if (data == null){
        var imgBlankData = ctx.createImageData(canvas.width,canvas.height);
        ctx.putImageData(imgBlankData,0,0);

        if (this.show_count){//draw grid box
            this.drawGridCount(ctx,tilePoint,zoom,data);
        }
        return;
    }

    var imgData=ctx.createImageData(size,size);
    var pixels = imgData.data;
    var length = pixels.length;

    if (! this.smooth){ //blocky rendering
        ctx.imageSmoothingEnabled = false;
        ctx.webkitImageSmoothingEnabled = false;
        ctx.mozImageSmoothingEnabled = false;
    }

    //set color
    var that = this;
    if (this.log){
        minv = Math.log(minv+1);
        maxv = Math.log(maxv);
    }

    data.forEach(function(d){
        if(d.v < 1e-6){
            return;
        }

        var v = d.v;
        if (that.log){
            v = Math.log(v+1);
        }

        v = (v-minv)/maxv;
        var color = d3.rgb(that.colormap(v));
        var idx = (imgData.height-1-d.y)*imgData.width + d.x;
        pixels[idx*4]=color.r;
        pixels[idx*4+1]=color.g ;
        pixels[idx*4+2]=color.b;
        pixels[idx*4+3]= v*255*2;
    });

    //set image
    var sc = canvas.width*1.0/size;

    //clear the canvas
    imgBlankData = ctx.createImageData(canvas.width,canvas.height);
    ctx.putImageData(imgBlankData,0,0);

    //scale
    if (sc !=1){
        //create a proxy canvas
        var newCanvas = $('<canvas>')
                .attr("width", imgData.width)
                .attr("height", imgData.height)[0];
        newCanvas.getContext("2d").putImageData(imgData, 0, 0);

        ctx.drawImage(newCanvas,0,0,canvas.width,canvas.height);
    }
    else{
        ctx.putImageData(imgData,0,0);
    }

    if (this.show_count){//draw grid box
        this.drawGridCount(ctx,tilePoint,zoom,data);
    }
};

L.NanocubeLayer.prototype.drawGridCount = function(ctx,tilePoint,zoom,data){
    ctx.lineWidth="0.5";
    ctx.strokeStyle="white";
    ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
    ctx.stroke();

    var totalstr =  "("+tilePoint.x + "," + tilePoint.y +","+zoom+")   ";
    if(data != null){
        //Total count
        var total = data.reduce(function(prev,curr){return prev+curr.v;},0);
        totalstr +=  total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    ctx.font="10pt sans-serif";
    ctx.fillStyle="white";
    ctx.fillText(totalstr,10,20);

};

L.NanocubeLayer.prototype.processData = function(bindata){
    if(bindata == null){
        return null;
    }

    var record_size = 10;
    var view = new DataView(bindata);
    var n_records = bindata.byteLength / record_size;
    if (n_records < 1) {
        return null;
    }

    var data = [];
    for (var i=0; i<n_records; ++i) {
        var rx = view.getUint8( record_size*i+1 );
        var ry = view.getUint8( record_size*i   );
        var rv = view.getFloat64( record_size*i+2, true );
        if (rv < 1e-6){ //skip zeros
            continue;
        }
        data.push({x:rx, y:ry, v: rv});
    }

    return data;
};

L.NanocubeLayer.prototype._addTilesFromCenterOut = function(bounds){
    this.tilelist = []; //empty the list
    console.log('clear');
    L.TileLayer.Canvas.prototype._addTilesFromCenterOut.call(this, bounds);
    console.log('d',this.tilelist);

    if (this.tilelist.length < 1){
        return;
    }
    var tilelist=this.tilelist.slice(0); //copy the tilelit

    var that = this;
    var promises = tilelist.map(function(t){
        return that.queryTile(t);
    });

    //Process the tile
    $.when.apply($,promises).then(function(){
        //After querying
        var value_arr = tilelist.map(function(t){
            if (t.data==null){
                return [];
            }
            else{
                return t.data.map(function(d){ return d.v;});
            }
        });

        //flatten the arrays
        var min_arr = value_arr.reduce(function(a, b){
            return a.concat(Math.min.apply(null,b));
        });
        var max_arr = value_arr.reduce(function(a, b){
            return a.concat(Math.max.apply(null,b));
        });

        //find max and min
        var minv = Math.min.apply(null,min_arr);
        var maxv = Math.max.apply(null,max_arr);

        //render the tiles
        tilelist.map(function(t){
            var size = Math.pow(2,t.drill);
            that.renderTile(t.canvas, size, t.tilePoint,
                            t.z, minv,maxv,t.data);
        });
    });
};

L.NanocubeLayer.prototype.queryTile = function(tile){
    var that = this;
    var dfd = $.Deferred();
    this.model.tileQuery(that.variable,tile,tile.drill, function(data){
        tile.data = that.processData(data);
        dfd.resolve();
    });
    return dfd.promise();
};
<commit_msg>t.z -> t.level<commit_after>L.NanocubeLayer = L.TileLayer.Canvas.extend({
    initialize: function(options){
        L.TileLayer.Canvas.prototype.initialize.call(this, options);
        this.model = options.model;
        this.variable = options.variable;
        this.colormap = d3.scale.linear()
            .domain(options.colormap.domain)
            .range(options.colormap.colors);

        this.coarselevels = 1;
        this.smooth = false;

        this.show_count = false;
        this.log = true;
    }
});

L.NanocubeLayer.prototype.toggleLog = function(){
    this.log = !this.log;
    this.redraw();
};

L.NanocubeLayer.prototype.toggleShowCount = function(){
    this.show_count = !this.show_count;
    this.redraw();
};

L.NanocubeLayer.prototype.redraw = function(){
    if (this._map) {
	this._reset({hard: false});  //no hard resetting
	this._update();
    }
    for (var i in this._tiles) {
	this._redrawTile(this._tiles[i]);
    }
    return this;
};

L.NanocubeLayer.prototype.drawTile = function(canvas, tilePoint, zoom){
    var drill = Math.min(this.variable.maxlevel-zoom,8) - this.coarselevels ;
    drill = Math.max(0,drill);
    drill = Math.min(8,drill);

    var size = Math.pow(2,drill);
    var ntiles = Math.pow(2,zoom);

    //fix negative tiles
    while(tilePoint.x < 0){
        tilePoint.x += ntiles;
    }

    while(tilePoint.y < 0){
        tilePoint.y += ntiles;
    }

    //fix overflow tiles
    while(tilePoint.x > ntiles){
        tilePoint.x -= ntiles;
    }

    while(tilePoint.y > ntiles){
        tilePoint.y -= ntiles;
    }

    //flip y for nanocubes
    var ty = (ntiles-1)-tilePoint.y;

    var tile = new Tile(tilePoint.x,ty,zoom);
    tile.canvas = canvas;
    tile.drill = drill;
    tile.tilePoint = tilePoint;
    this.tilelist.push(tile);
    console.log('t',this.tilelist);
};

L.NanocubeLayer.prototype.renderTile = function(canvas, size,tilePoint,zoom,
                                                minv,maxv,data){
    var ctx = canvas.getContext('2d');

    if (data == null){
        var imgBlankData = ctx.createImageData(canvas.width,canvas.height);
        ctx.putImageData(imgBlankData,0,0);

        if (this.show_count){//draw grid box
            this.drawGridCount(ctx,tilePoint,zoom,data);
        }
        return;
    }

    var imgData=ctx.createImageData(size,size);
    var pixels = imgData.data;
    var length = pixels.length;

    if (! this.smooth){ //blocky rendering
        ctx.imageSmoothingEnabled = false;
        ctx.webkitImageSmoothingEnabled = false;
        ctx.mozImageSmoothingEnabled = false;
    }

    //set color
    var that = this;
    if (this.log){
        minv = Math.log(minv+1);
        maxv = Math.log(maxv);
    }

    data.forEach(function(d){
        if(d.v < 1e-6){
            return;
        }

        var v = d.v;
        if (that.log){
            v = Math.log(v+1);
        }

        v = (v-minv)/maxv;
        var color = d3.rgb(that.colormap(v));
        var idx = (imgData.height-1-d.y)*imgData.width + d.x;
        pixels[idx*4]=color.r;
        pixels[idx*4+1]=color.g ;
        pixels[idx*4+2]=color.b;
        pixels[idx*4+3]= v*255*2;
    });

    //set image
    var sc = canvas.width*1.0/size;

    //clear the canvas
    imgBlankData = ctx.createImageData(canvas.width,canvas.height);
    ctx.putImageData(imgBlankData,0,0);

    //scale
    if (sc !=1){
        //create a proxy canvas
        var newCanvas = $('<canvas>')
                .attr("width", imgData.width)
                .attr("height", imgData.height)[0];
        newCanvas.getContext("2d").putImageData(imgData, 0, 0);

        ctx.drawImage(newCanvas,0,0,canvas.width,canvas.height);
    }
    else{
        ctx.putImageData(imgData,0,0);
    }

    if (this.show_count){//draw grid box
        this.drawGridCount(ctx,tilePoint,zoom,data);
    }
};

L.NanocubeLayer.prototype.drawGridCount = function(ctx,tilePoint,zoom,data){
    ctx.lineWidth="0.5";
    ctx.strokeStyle="white";
    ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
    ctx.stroke();

    var totalstr =  "("+tilePoint.x + "," + tilePoint.y +","+zoom+")   ";
    if(data != null){
        //Total count
        var total = data.reduce(function(prev,curr){return prev+curr.v;},0);
        totalstr +=  total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    ctx.font="10pt sans-serif";
    ctx.fillStyle="white";
    ctx.fillText(totalstr,10,20);

};

L.NanocubeLayer.prototype.processData = function(bindata){
    if(bindata == null){
        return null;
    }

    var record_size = 10;
    var view = new DataView(bindata);
    var n_records = bindata.byteLength / record_size;
    if (n_records < 1) {
        return null;
    }

    var data = [];
    for (var i=0; i<n_records; ++i) {
        var rx = view.getUint8( record_size*i+1 );
        var ry = view.getUint8( record_size*i   );
        var rv = view.getFloat64( record_size*i+2, true );
        if (rv < 1e-6){ //skip zeros
            continue;
        }
        data.push({x:rx, y:ry, v: rv});
    }

    return data;
};

L.NanocubeLayer.prototype._addTilesFromCenterOut = function(bounds){
    this.tilelist = []; //empty the list
    console.log('clear');
    L.TileLayer.Canvas.prototype._addTilesFromCenterOut.call(this, bounds);
    console.log('d',this.tilelist);

    if (this.tilelist.length < 1){
        return;
    }
    var tilelist=this.tilelist.slice(0); //copy the tilelit

    var that = this;
    var promises = tilelist.map(function(t){
        return that.queryTile(t);
    });

    //Process the tile
    $.when.apply($,promises).then(function(){
        //After querying
        var value_arr = tilelist.map(function(t){
            if (t.data==null){
                return [];
            }
            else{
                return t.data.map(function(d){ return d.v;});
            }
        });

        //flatten the arrays
        var min_arr = value_arr.reduce(function(a, b){
            return a.concat(Math.min.apply(null,b));
        });
        var max_arr = value_arr.reduce(function(a, b){
            return a.concat(Math.max.apply(null,b));
        });

        //find max and min
        var minv = Math.min.apply(null,min_arr);
        var maxv = Math.max.apply(null,max_arr);

        //render the tiles
        tilelist.map(function(t){
            var size = Math.pow(2,t.drill);
            that.renderTile(t.canvas, size, t.tilePoint,
                            t.level, minv,maxv,t.data);
        });
    });
};

L.NanocubeLayer.prototype.queryTile = function(tile){
    var that = this;
    var dfd = $.Deferred();
    this.model.tileQuery(that.variable,tile,tile.drill, function(data){
        tile.data = that.processData(data);
        dfd.resolve();
    });
    return dfd.promise();
};
<|endoftext|>