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

// Module dependencies.
var http = require('http');
var url = require('url');
var util = require('util');
var qs = require('qs');
var crypto = require('crypto');
var xml2js = require('xml2js');

var azureutil = require('../../util/util');

var ServiceClient = require('./serviceclient');
var Constants = require('../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HttpConstants = Constants.HttpConstants;
var Logger = require('../../diagnostics/logger');

// Expose 'StorageServiceClient'.
exports = module.exports = StorageServiceClient;

// Validation error messages
StorageServiceClient.incorrectStorageAccountErr = 'Account name must be a non empty string. Set AZURE_STORAGE_ACCOUNT';
StorageServiceClient.incorrectStorageAccessKeyErr = 'AccessKey must be a non empty string. Set AZURE_STORAGE_ACCESS_KEY';

/**
* Creates a new ServiceClient object.
*
* @constructor
* @param {string} storageAccountOrConnectionString    The storage account or connection string.
* @param {string} storageAccessKey                    The storage access key.
* @param {string} host                                The host for the service.
* @param {object} authenticationProvider              The authentication provider object (e.g. sharedkey / sharedkeytable / sharedaccesssignature).
*/
function StorageServiceClient(storageAccountOrConnectionString, storageAccessKey, host, authenticationProvider) {
  var storageAccount = storageAccountOrConnectionString;

  this._setAccountCredentials(storageAccount, storageAccessKey);
  this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
  this.usePathStyleUri = ServiceClient.isEmulated(host);

  StorageServiceClient.super_.call(this, host, authenticationProvider);

  this._initDefaultFilter();
}

util.inherits(StorageServiceClient, ServiceClient);

/**
* Builds the request options to be passed to the http.request method.
*
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object}      options     The request options.
* @param {function(error, requestOptions)}  callback  The callback function.
* @return {undefined}
*/
StorageServiceClient.prototype._buildRequestOptions = function (webResource, options, callback) {
  var self = this;

  if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_TYPE]) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, '');
  }

  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_LENGTH, 0);
  } else if(webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_LENGTH];
  }

  webResource.addOptionalHeader(HeaderConstants.STORAGE_VERSION_HEADER, this.apiVersion);
  webResource.addOptionalHeader(HeaderConstants.DATE_HEADER, new Date().toUTCString());
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_HEADER, 'application/atom+xml,application/xml');
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8');

  webResource.addOptionalHeader(HeaderConstants.HOST_HEADER, this._getHostname() + ':' + this.port);

  if (options) {
    if (options.timeoutIntervalInMs) {
      webResource.addOptionalQueryParam(QueryStringConstants.TIMEOUT, options.timeoutIntervalInMs);
    }

    if (options.accessConditions) {
      webResource.addOptionalAccessConditionHeader(options.accessConditions);
    }

    if (options.sourceAccessConditions) {
      webResource.addOptionalSourceAccessConditionHeader(options.sourceAccessConditions);
    }
  }

  // Sets the request url in the web resource.
  this._setRequestUrl(webResource);

  // Now that the web request is finalized, sign it
  this.authenticationProvider.signRequest(webResource, function (error) {
    var requestOptions = null;

    if (!error) {
      requestOptions = {
        url: url.format({
          protocol: self._isHttps() ? 'https:' : 'http:',
          hostname: self._getHostname(),
          port: self.port,
          pathname: webResource.path + webResource.getQueryString(true)
        }),
        method: webResource.httpVerb,
        headers: webResource.headers
      };

      self._setRequestOptionsProxy(requestOptions);
    }

    callback(error, requestOptions);
  });
};

/**
* Retrieves the normalized path to be used in a request.
* This takes into consideration the usePathStyleUri object field
* which specifies if the request is against the emulator or against
* the live service. It also adds a leading "/" to the path in case
* it's not there before.
*
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
StorageServiceClient.prototype._getPath = function (path) {
  if (path === null || path === undefined) {
    path = '/';
  } else if (path.indexOf('/') !== 0) {
    path = '/' + path;
  }

  if (this.usePathStyleUri) {
    path = '/' + this.storageAccount + path;
  }

  return path;
};

/**
* Retrives the hostname taking into consideration the usePathStyleUri flag which indicates whether the account
* should be a prefix for it or not.
*
* @return {string} The hostname.
*/
StorageServiceClient.prototype._getHostname = function () {
  if (this.usePathStyleUri) {
    return this.host;
  }

  return this.storageAccount + '.' + this.host;
};

/**
* Sets the account credentials taking into consideration the isEmulated value and the environment variables:
* AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY.
*
* @param {string} storageAccount          The storage account.
* @param {string} storageAccessKey        The storage access key.
* @return {undefined}
*/
StorageServiceClient.prototype._setAccountCredentials = function (storageAccount, storageAccessKey) {
  if (azureutil.objectIsNull(storageAccount)) {
    if (ServiceClient.isEmulated()) {
      storageAccount = ServiceClient.DEVSTORE_STORAGE_ACCOUNT;
    } else {
      storageAccount = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
    }
  }

  if (azureutil.objectIsNull(storageAccessKey)) {
    if (ServiceClient.isEmulated()) {
      storageAccessKey = ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY;
    } else {
      storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
    }
  }

  if (!azureutil.objectIsString(storageAccount) || azureutil.stringIsEmpty(storageAccount)) {
    throw new Error(StorageServiceClient.incorrectStorageAccountErr);
  }

  if (!azureutil.objectIsString(storageAccessKey) || azureutil.stringIsEmpty(storageAccessKey)) {
    throw new Error(StorageServiceClient.incorrectStorageAccessKeyErr);
  }

  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
};<commit_msg>Implementing storage connection strings.<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Module dependencies.
var http = require('http');
var url = require('url');
var util = require('util');
var qs = require('qs');
var crypto = require('crypto');
var xml2js = require('xml2js');

var azureutil = require('../../util/util');

var ServiceClient = require('./serviceclient');
var Constants = require('../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var HttpConstants = Constants.HttpConstants;
var Logger = require('../../diagnostics/logger');

// Expose 'StorageServiceClient'.
exports = module.exports = StorageServiceClient;

// Validation error messages
StorageServiceClient.incorrectStorageAccountErr = 'Account name must be a non empty string. Set AZURE_STORAGE_ACCOUNT';
StorageServiceClient.incorrectStorageAccessKeyErr = 'AccessKey must be a non empty string. Set AZURE_STORAGE_ACCESS_KEY';

/**
* Creates a new ServiceClient object.
*
* @constructor
* @param {string} storageAccountOrConnectionString    The storage account or connection string.
* @param {string} storageAccessKey                    The storage access key.
* @param {string} host                                The host for the service.
* @param {object} authenticationProvider              The authentication provider object (e.g. sharedkey / sharedkeytable / sharedaccesssignature).
*/
function StorageServiceClient(storageAccountOrConnectionString, storageAccessKey, host, authenticationProvider) {
  var storageAccount = storageAccountOrConnectionString;

  if (storageAccountOrConnectionString && !storageAccessKey) {
    if (connectionString['accountname']) {
      storageAccount = connectionString['accountname'];
    }

    if (connectionString['accountkey']) {
      storageAccessKey = connectionString['accountkey'];
    }
  }

  this._setAccountCredentials(storageAccount, storageAccessKey);
  this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
  this.usePathStyleUri = ServiceClient.isEmulated(host);

  StorageServiceClient.super_.call(this, host, authenticationProvider);

  this._initDefaultFilter();
}

util.inherits(StorageServiceClient, ServiceClient);

/**
* Builds the request options to be passed to the http.request method.
*
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object}      options     The request options.
* @param {function(error, requestOptions)}  callback  The callback function.
* @return {undefined}
*/
StorageServiceClient.prototype._buildRequestOptions = function (webResource, options, callback) {
  var self = this;

  if (!webResource.headers || !webResource.headers[HeaderConstants.CONTENT_TYPE]) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, '');
  }

  if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) {
    webResource.addOptionalHeader(HeaderConstants.CONTENT_LENGTH, 0);
  } else if(webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) {
    delete webResource.headers[HeaderConstants.CONTENT_LENGTH];
  }

  webResource.addOptionalHeader(HeaderConstants.STORAGE_VERSION_HEADER, this.apiVersion);
  webResource.addOptionalHeader(HeaderConstants.DATE_HEADER, new Date().toUTCString());
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_HEADER, 'application/atom+xml,application/xml');
  webResource.addOptionalHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8');

  webResource.addOptionalHeader(HeaderConstants.HOST_HEADER, this._getHostname() + ':' + this.port);

  if (options) {
    if (options.timeoutIntervalInMs) {
      webResource.addOptionalQueryParam(QueryStringConstants.TIMEOUT, options.timeoutIntervalInMs);
    }

    if (options.accessConditions) {
      webResource.addOptionalAccessConditionHeader(options.accessConditions);
    }

    if (options.sourceAccessConditions) {
      webResource.addOptionalSourceAccessConditionHeader(options.sourceAccessConditions);
    }
  }

  // Sets the request url in the web resource.
  this._setRequestUrl(webResource);

  // Now that the web request is finalized, sign it
  this.authenticationProvider.signRequest(webResource, function (error) {
    var requestOptions = null;

    if (!error) {
      requestOptions = {
        url: url.format({
          protocol: self._isHttps() ? 'https:' : 'http:',
          hostname: self._getHostname(),
          port: self.port,
          pathname: webResource.path + webResource.getQueryString(true)
        }),
        method: webResource.httpVerb,
        headers: webResource.headers
      };

      self._setRequestOptionsProxy(requestOptions);
    }

    callback(error, requestOptions);
  });
};

/**
* Retrieves the normalized path to be used in a request.
* This takes into consideration the usePathStyleUri object field
* which specifies if the request is against the emulator or against
* the live service. It also adds a leading "/" to the path in case
* it's not there before.
*
* @param {string} path The path to be normalized.
* @return {string} The normalized path.
*/
StorageServiceClient.prototype._getPath = function (path) {
  if (path === null || path === undefined) {
    path = '/';
  } else if (path.indexOf('/') !== 0) {
    path = '/' + path;
  }

  if (this.usePathStyleUri) {
    path = '/' + this.storageAccount + path;
  }

  return path;
};

/**
* Retrives the hostname taking into consideration the usePathStyleUri flag which indicates whether the account
* should be a prefix for it or not.
*
* @return {string} The hostname.
*/
StorageServiceClient.prototype._getHostname = function () {
  if (this.usePathStyleUri) {
    return this.host;
  }

  return this.storageAccount + '.' + this.host;
};

/**
* Sets the account credentials taking into consideration the isEmulated value and the environment variables:
* AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY.
*
* @param {string} storageAccount          The storage account.
* @param {string} storageAccessKey        The storage access key.
* @return {undefined}
*/
StorageServiceClient.prototype._setAccountCredentials = function (storageAccount, storageAccessKey) {
  if (azureutil.objectIsNull(storageAccount)) {
    if (ServiceClient.isEmulated()) {
      storageAccount = ServiceClient.DEVSTORE_STORAGE_ACCOUNT;
    } else {
      storageAccount = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
    }
  }

  if (azureutil.objectIsNull(storageAccessKey)) {
    if (ServiceClient.isEmulated()) {
      storageAccessKey = ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY;
    } else {
      storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
    }
  }

  if (!azureutil.objectIsString(storageAccount) || azureutil.stringIsEmpty(storageAccount)) {
    throw new Error(StorageServiceClient.incorrectStorageAccountErr);
  }

  if (!azureutil.objectIsString(storageAccessKey) || azureutil.stringIsEmpty(storageAccessKey)) {
    throw new Error(StorageServiceClient.incorrectStorageAccessKeyErr);
  }

  this.storageAccount = storageAccount;
  this.storageAccessKey = storageAccessKey;
};<|endoftext|>


<commit_before>// @flow

const AstNode = require('../../../ast-node.js')
const AstNodeList = require('../../../ast-node-list.js')
const OpenTagTracker = require('../../helpers/open-tag-tracker.js')

module.exports = function (
  node: Object,
  openTags: OpenTagTracker,
  file: string,
  line: number
): AstNodeList {
  const result = new AstNodeList()
  const resultNode = new AstNode({
    type: node.type,
    tag: 'a',
    file,
    line,
    content: '',
    attributes: {}
  })
  openTags.add(resultNode)
  result.push(resultNode)
  return result
}
<commit_msg>Fix external links<commit_after>// @flow

const AstNode = require('../../../ast-node.js')
const AstNodeList = require('../../../ast-node-list.js')
const OpenTagTracker = require('../../helpers/open-tag-tracker.js')

module.exports = function (
  node: Object,
  openTags: OpenTagTracker,
  file: string,
  line: number
): AstNodeList {
  const result = new AstNodeList()
  const resultNode = new AstNode({
    type: node.type,
    tag: 'a',
    file,
    line,
    content: '',
    attributes: {
      href: node.href,
      title: node.title
    }
  })
  openTags.add(resultNode)
  result.push(resultNode)
  return result
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Custom configuration object for Buffer configuration
 * @author Roy Braam
 */
Ext.define("viewer.components.CustomConfiguration",{
    extend: "viewer.components.SelectionWindowConfig",
    constructor: function (parentId,configObject){
        if (configObject === null){
            configObject = {};
        }
        configObject.showLabelconfig =true;
        viewer.components.CustomConfiguration.superclass.constructor.call(this, parentId,configObject);
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectGroups || true,
            name: "selectGroups",
            fieldLabel: "Kaarten selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectLayers || true,
            name: "selectLayers",
            fieldLabel: "Kaartlagen selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectOwnServices || true,
            name: "selectOwnServices",
            fieldLabel: "Eigen services selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
    }
});

<commit_msg>Fix #64. Configuration of true/false values in SelectionModule are now correctly set in the form.<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Custom configuration object for Buffer configuration
 * @author Roy Braam
 */
Ext.define("viewer.components.CustomConfiguration",{
    extend: "viewer.components.SelectionWindowConfig",
    constructor: function (parentId,configObject){
        if (configObject === null){
            configObject = {};
        }
        configObject.showLabelconfig =true;
        viewer.components.CustomConfiguration.superclass.constructor.call(this, parentId,configObject);
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectGroups !== undefined ? configObject.selectGroups : true,
            name: "selectGroups",
            fieldLabel: "Kaarten selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectLayers !== undefined ? configObject.selectLayers : true,
            name: "selectLayers",
            fieldLabel: "Kaartlagen selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
        this.form.add({
            xtype: "combo",
            fields: ['value', 'text'],
            value: configObject.selectOwnServices !== undefined ? configObject.selectOwnServices : true,
            name: "selectOwnServices",
            fieldLabel: "Eigen services selecteren",
            store: [
                [true, "true"],
                [false, "false"]
            ]
        });
    }
});

<|endoftext|>


<commit_before>import previewImage from '../../../mp-weixin/helpers/normalize-preview-image'

// 不支持的 API 列表
const todos = [
  'createCameraContext',
  'createLivePlayerContext',
  'getSavedFileInfo',
  'createMapContext',
  'onMemoryWarning',
  'onGyroscopeChange',
  'startGyroscope',
  'stopGyroscope',
  'setScreenBrightness',
  'getScreenBrightness',
  'addPhoneContact',
  'openBluetoothAdapter',
  'startBluetoothDevicesDiscovery',
  'onBluetoothDeviceFound',
  'stopBluetoothDevicesDiscovery',
  'onBluetoothAdapterStateChange',
  'getConnectedBluetoothDevices',
  'getBluetoothDevices',
  'getBluetoothAdapterState',
  'closeBluetoothAdapter',
  'writeBLECharacteristicValue',
  'readBLECharacteristicValue',
  'onBLEConnectionStateChange',
  'onBLECharacteristicValueChange',
  'notifyBLECharacteristicValueChange',
  'getBLEDeviceServices',
  'getBLEDeviceCharacteristics',
  'createBLEConnection',
  'closeBLEConnection',
  'onBeaconServiceChange',
  'onBeaconUpdate',
  'getBeacons',
  'startBeaconDiscovery',
  'stopBeaconDiscovery',
  'setNavigationBarColor',
  'showNavigationBarLoading',
  'hideNavigationBarLoading',
  'setTabBarItem',
  'setTabBarStyle',
  'hideTabBar',
  'showTabBar',
  'setTabBarBadge',
  'removeTabBarBadge',
  'showTabBarRedDot',
  'hideTabBarRedDot',
  'setBackgroundColor',
  'setBackgroundTextStyle',
  'chooseInvoiceTitle',
  'addTemplate',
  'deleteTemplate',
  'getTemplateLibraryById',
  'getTemplateLibraryList',
  'getTemplateList',
  'sendTemplateMessage',
  'setEnableDebug',
  'onWindowResize',
  'offWindowResize',
  'createOffscreenCanvas',
  'vibrate'
]

// 存在兼容性的 API 列表
// 头条小程序自1.35.0+支持canIUses
const canIUses = [
  // 'createIntersectionObserver',
  // 'getSavedFileList',
  // 'removeSavedFile',
  // 'hideKeyboard',
  // 'getImageInfo',
  // 'createVideoContext',
  // 'onSocketOpen',
  // 'onSocketError',
  // 'sendSocketMessage',
  // 'onSocketMessage',
  // 'closeSocket',
  // 'onSocketClose',
  // 'getExtConfig',
  // 'getExtConfigSync',
  // 'navigateToMiniProgram',
  // 'navigateBackMiniProgram',
  // 'compressImage',
  // 'chooseLocation',
  // 'openDocument',
  // 'onUserCaptureScreen',
  // 'getBackgroundAudioManager',
]

// 需要做转换的 API 列表
const protocols = {
  chooseImage: {
    args: {
      sizeType: false
    }
  },
  previewImage,
  connectSocket: {
    args: {
      method: false
    }
  },
  chooseVideo: {
    args: {
      camera: false
    }
  },
  scanCode: {
    args: {
      onlyFromCamera: false,
      scanType: false
    }
  },
  startAccelerometer: {
    args: {
      interval: false
    }
  },
  showToast: {
    args: {
      image: false,
      mask: false
    }
  },
  showLoading: {
    args: {
      mask: false
    }
  },
  showModal: {
    args: {
      cancelColor: false,
      confirmColor: false
    }
  },
  showActionSheet: {
    args: {
      itemColor: false
    }
  },
  login: {
    args: {
      scopes: false,
      timeout: false
    }
  },
  getUserInfo: {
    args: {
      lang: false,
      timeout: false
    }
  },
  requestPayment: {
    name: tt.canIUse && tt.canIUse('pay') ? 'pay' : 'requestPayment',
    args: {
      orderInfo: tt.canIUse && tt.canIUse('pay') ? 'orderInfo' : 'data'
    }
  },
  getFileInfo: {
    args: {
      digestAlgorithm: false
    }
  }
}

export {
  protocols,
  todos,
  canIUses
}
<commit_msg>Update protocols.js<commit_after>import previewImage from '../../../mp-weixin/helpers/normalize-preview-image'

// 不支持的 API 列表
const todos = [
  'createCameraContext',
  'createLivePlayerContext',
  'getSavedFileInfo',
  'createMapContext',
  'onMemoryWarning',
  'onGyroscopeChange',
  'startGyroscope',
  'stopGyroscope',
  'setScreenBrightness',
  'getScreenBrightness',
  'addPhoneContact',
  'openBluetoothAdapter',
  'startBluetoothDevicesDiscovery',
  'onBluetoothDeviceFound',
  'stopBluetoothDevicesDiscovery',
  'onBluetoothAdapterStateChange',
  'getConnectedBluetoothDevices',
  'getBluetoothDevices',
  'getBluetoothAdapterState',
  'closeBluetoothAdapter',
  'writeBLECharacteristicValue',
  'readBLECharacteristicValue',
  'onBLEConnectionStateChange',
  'onBLECharacteristicValueChange',
  'notifyBLECharacteristicValueChange',
  'getBLEDeviceServices',
  'getBLEDeviceCharacteristics',
  'createBLEConnection',
  'closeBLEConnection',
  'onBeaconServiceChange',
  'onBeaconUpdate',
  'getBeacons',
  'startBeaconDiscovery',
  'stopBeaconDiscovery',
  'setNavigationBarColor',
  'showNavigationBarLoading',
  'hideNavigationBarLoading',
  'setTabBarItem',
  'setTabBarStyle',
  'hideTabBar',
  'showTabBar',
  'setTabBarBadge',
  'removeTabBarBadge',
  'showTabBarRedDot',
  'hideTabBarRedDot',
  'setBackgroundColor',
  'setBackgroundTextStyle',
  'chooseInvoiceTitle',
  'addTemplate',
  'deleteTemplate',
  'getTemplateLibraryById',
  'getTemplateLibraryList',
  'getTemplateList',
  'sendTemplateMessage',
  'setEnableDebug',
  'onWindowResize',
  'offWindowResize',
  'createOffscreenCanvas',
  'vibrate'
]

// 存在兼容性的 API 列表
// 头条小程序自1.35.0+支持canIUses
const canIUses = [
  // 'createIntersectionObserver',
  // 'getSavedFileList',
  // 'removeSavedFile',
  // 'hideKeyboard',
  // 'getImageInfo',
  // 'createVideoContext',
  // 'onSocketOpen',
  // 'onSocketError',
  // 'sendSocketMessage',
  // 'onSocketMessage',
  // 'closeSocket',
  // 'onSocketClose',
  // 'getExtConfig',
  // 'getExtConfigSync',
  // 'navigateToMiniProgram',
  // 'navigateBackMiniProgram',
  // 'compressImage',
  // 'chooseLocation',
  // 'openDocument',
  // 'onUserCaptureScreen',
  // 'getBackgroundAudioManager',
]

// 需要做转换的 API 列表
const protocols = {
  chooseImage: {
    args: {
      sizeType: false
    }
  },
  previewImage,
  connectSocket: {
    args: {
      method: false
    }
  },
  chooseVideo: {
    args: {
      camera: false
    }
  },
  scanCode: {
    args: {
      onlyFromCamera: false,
      scanType: false
    }
  },
  startAccelerometer: {
    args: {
      interval: false
    }
  },
  showToast: {
    args: {
      image: false,
      mask: false
    }
  },
  showLoading: {
    args: {
      mask: false
    }
  },
  showModal: {
    args: {
      cancelColor: false,
      confirmColor: false
    }
  },
  showActionSheet: {
    args: {
      itemColor: false
    }
  },
  login: {
    args: {
      scopes: false,
      timeout: false
    }
  },
  getUserInfo: {
    args: {
      lang: false,
      timeout: false
    }
  },
  requestPayment: {
    name: tt.pay ? 'pay' : 'requestPayment',
    args: {
      orderInfo: tt.pay ? 'orderInfo' : 'data'
    }
  },
  getFileInfo: {
    args: {
      digestAlgorithm: false
    }
  }
}

export {
  protocols,
  todos,
  canIUses
}
<|endoftext|>


<commit_before>var map;
var devices = {}

function initialize(latLng) {
	var mapOptions = {
		center: latLng,
		zoom: 11
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions);
}

google.maps.event.addDomListener(window, 'load', function(){

});

function displayData(data){
	$ul = $('
');
	$.each(data, function(index, value) {
		$ul.append($('
').html("" + index + "" + value + ""));
	});

	$(".data").html($ul);
}

function getDevice(uid){
	return devices[uid] || null;
}

function checkIfMapExists(latLng){
	if(!map) {
		initialize(latLng);
	}
}

function addDevice(uid, latLng){
	checkIfMapExists(latLng);

	var marker = new google.maps.Marker({
		position: latLng,
		map: map,
		animation: google.maps.Animation.DROP,
		title: 'UID: ' + uid,
		uid: uid

	});

	marker.setMap(map);

	google.maps.event.addListener(marker, 'click', function(){
		var deviceData = getDevice(this.uid).lastData;
		console.log(deviceData);

		displayData(deviceData);
	});

	devices[uid] = {
		uid: uid,
		marker: marker,
		path: null
	}

	return devices[uid];
}

function checkIfDeviceExists(data){
	var uid = data.uid;

	if(typeof devices[uid] == "undefined") {
		return addDevice(uid, new google.maps.LatLng(data.latitude, data.longitude));
	}

	return devices[uid];
}

var socket = io.connect(window.location.host);
socket.on('ping', function (data) {

	var device = checkIfDeviceExists(data);
	device.lastData = data;

	socket.emit('my other event', { my: 'data' });
});

socket.on('positions', function (data) {
	var device;
	console.log(positions);

	$.each(data.positions, function(index, value) {
		device = checkIfDeviceExists(value);

		if(!device.path)
		{
			device.path = new google.maps.Polyline({
				path: [],
				geodesic: true,
				strokeColor: '#FF0000',
				strokeOpacity: 1.0,
				strokeWeight: 2
		  	});
		  	device.path.setMap(map);
		}

		device.path.getPath().push(new google.maps.LatLng(value.latitude, value.longitude));
	})

});

<commit_msg>Now retrieve 300 and bugfix<commit_after>var map;
var devices = {}

function initialize(latLng) {
	var mapOptions = {
		center: latLng,
		zoom: 11
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),
			mapOptions);
}

google.maps.event.addDomListener(window, 'load', function(){

});

function displayData(data){
	$ul = $('
');
	$.each(data, function(index, value) {
		$ul.append($('
').html("" + index + "" + value + ""));
	});

	$(".data").html($ul);
}

function getDevice(uid){
	return devices[uid] || null;
}

function checkIfMapExists(latLng){
	if(!map) {
		initialize(latLng);
	}
}

function addDevice(uid, latLng){
	checkIfMapExists(latLng);

	var marker = new google.maps.Marker({
		position: latLng,
		map: map,
		animation: google.maps.Animation.DROP,
		title: 'UID: ' + uid,
		uid: uid

	});

	marker.setMap(map);

	google.maps.event.addListener(marker, 'click', function(){
		var deviceData = getDevice(this.uid).lastData;
		console.log(deviceData);

		displayData(deviceData);
	});

	devices[uid] = {
		uid: uid,
		marker: marker,
		path: null
	}

	return devices[uid];
}

function checkIfDeviceExists(data){
	var uid = data.uid;

	if(typeof devices[uid] == "undefined") {
		return addDevice(uid, new google.maps.LatLng(data.latitude, data.longitude));
	}

	return devices[uid];
}

var socket = io.connect(window.location.host);
socket.on('ping', function (data) {

	var device = checkIfDeviceExists(data);
	device.lastData = data;

	socket.emit('my other event', { my: 'data' });
});

socket.on('positions', function (data) {
	var device;
	console.log(data.positions);

	$.each(data.positions, function(index, value) {
		device = checkIfDeviceExists(value);

		if(!device.path)
		{
			device.path = new google.maps.Polyline({
				path: [],
				geodesic: true,
				strokeColor: '#FF0000',
				strokeOpacity: 1.0,
				strokeWeight: 2
		  	});
		  	device.path.setMap(map);
		}

		device.path.getPath().push(new google.maps.LatLng(value.latitude, value.longitude));
	})

});

<|endoftext|>


<commit_before>module('users.timfelgentreff.babelsberg.deltablue_ext').requires('users.timfelgentreff.deltablue.deltablue').toRun(function() {

Function.addMethods({
    shouldBeSatisfiedWith: function(priority, methods, ctx) {
        // method for deltablue constraint (for now)
        if (!ctx) {
            ctx = methods;
            methods = priority;
            priority = DBStrength.required;
        }
        return DBPlanner.getInstance().always({
            priority: priority,
            methods: methods,
            ctx: ctx
        }, this);
    }
});

DBPlanner.addMethods({
    isConstraintObject: function() {
        return true;
    },
    constraintVariableFor: function(value, ivarname) {
        return new DBVariable(ivarname, value, this);
    },
    get strength() {
        return DBStrength;
    },
    always: function(opts, func) {
        var planner = this,
            ctx = opts.ctx,
            priority = opts.priority,
            methods = opts.methods;
        func.varMapping = ctx;
        if (!methods) methods = func;
        func = undefined;

        if (methods) {
            methods.varMapping = ctx;
            var formulas = new Constraint(methods, planner).constraintvariables.collect(function (v) {
                var v = v.externalVariables(planner);
                return v ? v.removeFormula() : null;
            }).compact();
        }

        var constraint = new UserDBConstraint(priority, func, function (c) {
            formulas.each(function (m) {
                var inputs = m.inputs.select(function (input) {
                    return input instanceof DBVariable
                });
                dbgOn(inputs.length !== m.inputs.length);
                c.formula(m.output, inputs, m.func);
            });
        }, planner);
        constraint.priority = priority;
        constraint.enable();
        return constraint;
    },

    weight: 100,
    addEditVar: function(v) {
        if (!this.currentEdits) {
            this.currentEdits = new DBOrderedCollection();
        }
        var edit = new EditDBConstraint(v, DBStrength.REQUIRED, this);
        this.currentEdits.add(edit);
        return edit;
    },

    beginEdit: function() {
        if (this.currentEditPlan) {
            throw "Trying to run nested edits - this isn't supported"
        }
        if (!this.currentEdits) {
            throw "No edit variables - cannot beginEdit"
        }
        this.currentEditPlan = this.extractDBPlanFromDBConstraints(this.currentEdits);
    },
    endEdit: function() {
        if (this.currentEdits && this.currentEdits.length !== 0) {
            this.currentEdits.each(function (edit) {
                edit.destroyDBConstraint();
            })
        }
        this.currentEditPlan = null;
    },
    resolveArray: function(newValues) {
        if (!this.currentEdits) {
            throw "resolveArray only valid in edit"
        }
        this.currentEdits.elms.each(function (edit, idx) {
            edit.myOutput.value = newValues[idx];
        })
        this.currentEditPlan.execute();
    }
})

Object.extend(DBPlanner, {
    getInstance: function() {
        if (!this["$$instance"]) {
            this["$$instance"] = new DBPlanner();
        }
        return this["$$instance"];
    },

    resetInstance: function() {
        this["$$instance"] = undefined;
    }
});

Object.extend(DBStrength, {
    required: DBStrength.REQUIRED,
    strong: DBStrength.STRONG_DEFAULT,
    medium: DBStrength.NORMAL,
    weak: DBStrength.WEAK_DEFAULT
});

DBVariable.addMethods({
    isConstraintObject: function() {
        return true;
    },

    stay: function(strength) {
        var cn = new StayDBConstraint(this, strength || DBStrength.WEAK_DEFAULT, this.planner);
        cn.enable();
        this._stayConstraint = cn;
        return cn;
    },
    setReadonly: function(bool) {
        if (bool && !this.readonlyConstraint) {
            var cn = new StayDBConstraint(this, DBStrength.required, this.planner);
            cn.enable();
            this.readonlyConstraint = cn;
            return cn;
        } else if (!bool && this.readonlyConstraint) {
            this.readonlyConstraint.disable();
            this.readonlyConstraint = undefined;
        }
    },
    isReadonly: function() {
        return !!this.readonlyConstraint;
    },

    formula: function (inputs, func) {
        if (!Constraint.current) {
            throw "invalid outside constraint construction"
        }
        // var constraint = new Constraint(func, Constraint.current.solver),
        //     inputs = constraint.constraintvariables
        if (this.__formula__) {
            throw "two formulas for the same variable " + this;
        }
        this.__formula__ = {output: this, inputs: inputs, func: func};
    },

    removeFormula: function () {
        var f = this.__formula__;
        this.__formula__ = undefined;
        return f;
    },

    removeStay: function() {
        if (this._stayConstraint) {
            try {
                this.planner.removeConstraint(this._stayConstraint);
            } catch(_) {
                this._stayConstraint = null;
            }
        }
    },

    suggestValue: function(value) {
        this.assignValue(value);
    },

    prepareEdit: function() {
        if (this.editConstraint) {
            // ignore?
        } else {
            this.editConstraint = this.planner.addEditVar(this);
        }
    },

    finishEdit: function() {
        this.editConstraint = null;
    },
})

DBConstraint.addMethods({
    isConstraintObject: function () {
        return true;
    },

    enable: function (priority) {
        this.strength = priority || this.strength;
        this.addDBConstraint()
    },

    disable: function () {
        this.destroyDBConstraint()
    }
});
}) // end of module<commit_msg>fix edit with deltablue<commit_after>module('users.timfelgentreff.babelsberg.deltablue_ext').requires('users.timfelgentreff.deltablue.deltablue').toRun(function() {

Function.addMethods({
    shouldBeSatisfiedWith: function(priority, methods, ctx) {
        // method for deltablue constraint (for now)
        if (!ctx) {
            ctx = methods;
            methods = priority;
            priority = DBStrength.required;
        }
        return DBPlanner.getInstance().always({
            priority: priority,
            methods: methods,
            ctx: ctx
        }, this);
    }
});

DBPlanner.addMethods({
    isConstraintObject: function() {
        return true;
    },
    constraintVariableFor: function(value, ivarname) {
        return new DBVariable(ivarname, value, this);
    },
    get strength() {
        return DBStrength;
    },
    always: function(opts, func) {
        var planner = this,
            ctx = opts.ctx,
            priority = opts.priority,
            methods = opts.methods;
        func.varMapping = ctx;
        if (!methods) methods = func;
        func = undefined;

        if (methods) {
            methods.varMapping = ctx;
            var formulas = new Constraint(methods, planner).constraintvariables.collect(function (v) {
                var v = v.externalVariables(planner);
                return v ? v.removeFormula() : null;
            }).compact();
        }

        var constraint = new UserDBConstraint(priority, func, function (c) {
            formulas.each(function (m) {
                var inputs = m.inputs.select(function (input) {
                    return input instanceof DBVariable
                });
                dbgOn(inputs.length !== m.inputs.length);
                c.formula(m.output, inputs, m.func);
            });
        }, planner);
        constraint.priority = priority;
        constraint.enable();
        return constraint;
    },

    weight: 100,
    addEditVar: function(v) {
        if (!this.currentEdits) {
            this.currentEdits = new DBOrderedCollection();
        }
        var edit = new EditDBConstraint(v, DBStrength.REQUIRED, this);
        this.currentEdits.add(edit);
        return edit;
    },

    beginEdit: function() {
        if (this.currentEditPlan) {
            throw "Trying to run nested edits - this isn't supported"
        }
        if (!this.currentEdits) {
            throw "No edit variables - cannot beginEdit"
        }
        this.currentEditPlan = this.extractDBPlanFromDBConstraints(this.currentEdits);
    },
    endEdit: function() {
        if (this.currentEdits && this.currentEdits.length !== 0) {
            this.currentEdits.elms.each(function (edit) {
                edit.destroyDBConstraint();
            })
        }
        this.currentEditPlan = null;
    },
    resolveArray: function(newValues) {
        if (!this.currentEdits) {
            throw "resolveArray only valid in edit"
        }
        this.currentEdits.elms.each(function (edit, idx) {
            edit.myOutput.value = newValues[idx];
        })
        this.currentEditPlan.execute();
    }
})

Object.extend(DBPlanner, {
    getInstance: function() {
        if (!this["$$instance"]) {
            this["$$instance"] = new DBPlanner();
        }
        return this["$$instance"];
    },

    resetInstance: function() {
        this["$$instance"] = undefined;
    }
});

Object.extend(DBStrength, {
    required: DBStrength.REQUIRED,
    strong: DBStrength.STRONG_DEFAULT,
    medium: DBStrength.NORMAL,
    weak: DBStrength.WEAK_DEFAULT
});

DBVariable.addMethods({
    isConstraintObject: function() {
        return true;
    },

    stay: function(strength) {
        var cn = new StayDBConstraint(this, strength || DBStrength.WEAK_DEFAULT, this.planner);
        cn.enable();
        this._stayConstraint = cn;
        return cn;
    },
    setReadonly: function(bool) {
        if (bool && !this.readonlyConstraint) {
            var cn = new StayDBConstraint(this, DBStrength.required, this.planner);
            cn.enable();
            this.readonlyConstraint = cn;
            return cn;
        } else if (!bool && this.readonlyConstraint) {
            this.readonlyConstraint.disable();
            this.readonlyConstraint = undefined;
        }
    },
    isReadonly: function() {
        return !!this.readonlyConstraint;
    },

    formula: function (inputs, func) {
        if (!Constraint.current) {
            throw "invalid outside constraint construction"
        }
        // var constraint = new Constraint(func, Constraint.current.solver),
        //     inputs = constraint.constraintvariables
        if (this.__formula__) {
            throw "two formulas for the same variable " + this;
        }
        this.__formula__ = {output: this, inputs: inputs, func: func};
    },

    removeFormula: function () {
        var f = this.__formula__;
        this.__formula__ = undefined;
        return f;
    },

    removeStay: function() {
        if (this._stayConstraint) {
            try {
                this.planner.removeConstraint(this._stayConstraint);
            } catch(_) {
                this._stayConstraint = null;
            }
        }
    },

    suggestValue: function(value) {
        this.assignValue(value);
    },

    prepareEdit: function() {
        if (this.editConstraint) {
            // ignore?
        } else {
            this.editConstraint = this.planner.addEditVar(this);
        }
    },

    finishEdit: function() {
        this.editConstraint = null;
    },
})

DBConstraint.addMethods({
    isConstraintObject: function () {
        return true;
    },

    enable: function (priority) {
        this.strength = priority || this.strength;
        this.addDBConstraint()
    },

    disable: function () {
        this.destroyDBConstraint()
    }
});
}) // end of module<|endoftext|>


<commit_before>;(function() {

	/* Game Logic */
	function Game(canvasId) {

		var self = this;
		var can = document.getElementById(canvasId);
		var screen = can.getContext('2d');

		this.size = {x: can.width, y: can.height };
		this.playable = true; // game is not over
		this.score = 0; // score

		/* physics */
		this.gravity = -2;

		var tick = function() {
			self.update();
			self.draw(screen);
			requestAnimationFrame(tick);
		};

		tick();
		Mountains(screen,this.size);

	};

	Game.prototype.update = function() {
		//var self = this;
	};

	Game.prototype.draw = function(screen) {

	};

	/* Player / tank logic */
	function Tank(game) {

	};

	Tank.prototype.update = function() {

	};

	Tank.prototype.draw = function() {

	};

	/* Bullet logic */
	function Bullet(game) {

	};

	Bullet.prototype.update = function() {

	};

	Bullet.prototype.draw = function() {

	};

	/* mountains, background */
	function Mountains(screen,size) {

		var step = 60;

		screen.rect(0,0,size.x,size.y);
		screen.fillStyle = 'blue';
		screen.fill();

		screen.beginPath();
		screen.moveTo(0,size.y)

		var i=60;
		while(i <= size.x) {
			screen.lineTo(i,size.y-Math.random()*200);
			console.log(i);
			i += step;
		}
		screen.lineTo(size.x,size.y);
      	screen.lineWidth = 5;
      	screen.strokeStyle = 'green';
      	screen.fillStyle = 'green';
      	screen.stroke();
      	screen.fill();
	};

	/* Keyboard handler */
	function Keyboard() {
		var keyState = {};
		this.KEYS = { LEFT: 37, RIGHT:39, FIRE:32 };

		window.onkeydown = function(e) {
			keyState[e.keyCode] = true;
		};

		window.onkeyup = function(e) {
			keyState[e.keyCode] = false;
		};

		this.isDown = function(keyCode) {
			return keyState[keyCode] === true;
		};

	};

	/* Helpers */

	var game = new Game("myGame");
})();

<commit_msg>working player + bullets<commit_after>;(function() {

	/* Game Logic */
	function Game(canvasId) {

		var self = this;
		var can = document.getElementById(canvasId);
		var screen = can.getContext('2d');

		this.size = {x: can.width, y: can.height };
		this.playable = true; // game is not over
		this.score = 0; // score

		this.bodies = [];

		/* physics */
		this.gravity = -2;

		// initiate and draw new background
		this.mtns = new Mountains();
		this.mtns.generate(screen,this.size);

		// initialize a player
		this.tank = new Tank(game,screen,this.mtns.getPeaks());

		var tick = function() {
			self.update();
			self.draw(screen);
			requestAnimationFrame(tick);
		};

		tick();

	};

	Game.prototype.update = function() {
		//var self = this;
		this.tank.update(game);
		this.bodies.forEach(function(val,key) {
 			val.update();
		});
	};

	Game.prototype.draw = function(screen) {
		this.mtns.draw(screen,this.size);
		this.tank.draw(screen);
		this.bodies.forEach(function(val,key) {
			val.draw(screen);
		});

	};

	/* Player / tank logic */
	function Tank(game,screen,peaks) {

		this.game = game;
		this.radius = 20;
		this.turretAngle = 90;
		this.center = {x: peaks[4].x , y: peaks[4].y };
		var self = this;
		this.keys = new Keyboard();

	};

	Tank.prototype.update = function(game) {
		if(this.keys.isDown(this.keys.KEYS.LEFT)) {
			this.turretAngle -= 2;
		}
		else if(this.keys.isDown(this.keys.KEYS.RIGHT)) {
			this.turretAngle += 2;
		}
		else if(this.keys.isDown(this.keys.KEYS.FIRE)) {
			console.log("Fire");
			var bullet = new Bullet(game,this.center,this.turretAngle);
			game.bodies.push(bullet);
		}
	};

	Tank.prototype.draw = function(screen,angle) {

		//this turretAngle = (angle > 0 || angle < 360) ? angle : 90 ;

		// tank base
		screen.beginPath();
		screen.arc(this.center.x,this.center.y,this.radius,Math.PI,false);
		screen.closePath();
		screen.lineWidth = 5;
		screen.fillStyle = 'red';
		screen.fill();

		// turret angle
		screen.beginPath();
		screen.moveTo(this.center.x,this.center.y);

		// period + starting angle offset
		var angleUnit = (2*Math.PI)/360.0;

		screen.lineTo(this.center.x+30*Math.cos(angleUnit*this.turretAngle),this.center.y+30*-Math.sin(angleUnit*this.turretAngle));
		screen.lineWidth = 5;
		screen.strokeStyle = 'red';
		screen.stroke();

	};

	/* Bullet logic */
	function Bullet(game,center,angle) {
		this.angle = angle;
		this.velocity = {x:3,y:8};
		this.center = { x:center.x,y:center.y };
	};

	Bullet.prototype.update = function() {
		var angleUnit = (2*Math.PI)/360.0;
		this.center.x +=Math.cos(this.angle*angleUnit)*this.velocity.x;
		this.center.y +=-Math.sin(this.angle*angleUnit)*this.velocity.y;
		this.velocity.y -=0.1;
	};

	Bullet.prototype.draw = function(screen) {
		screen.rect(this.center.x,this.center.y,3,3);
		screen.fillStyle = 'black';
		screen.fill();
	};

	/* mountains, background */
	function Mountains() {
		this.step = 60; // peaks in steps
		this.points = []; // points of peaks
	};

	// draw initial mountain range
	Mountains.prototype.generate = function (screen,size) {
		screen.rect(0,0,size.x,size.y);
		screen.fillStyle = 'blue';
		screen.fill();

		screen.beginPath();
		screen.moveTo(0,size.y);
		var i = this.step;

		while(i <= size.x) {
			var peak = size.y-Math.random()*200;
			this.points.push({ x:i, y:peak });
			screen.lineTo(i,peak);
			i += this.step;
		}

		screen.lineTo(size.x,size.y);
      	screen.lineWidth = 5;
      	screen.strokeStyle = 'green';
      	screen.fillStyle = 'green';
      	screen.stroke();
      	screen.fill();

	};

	// redraw as needed
	Mountains.prototype.draw = function(screen,size) {

		screen.rect(0,0,size.x,size.y);
		screen.fillStyle = 'blue';
		screen.fill();

		screen.beginPath();
		screen.moveTo(0,size.y);

		this.points.forEach(function(val,key) {
			screen.lineTo(val.x,val.y);
		});
		screen.lineTo(size.x,size.y);
      	screen.lineWidth = 5;
      	screen.strokeStyle = 'green';
      	screen.fillStyle = 'green';
      	screen.stroke();
      	screen.fill();

	};

	Mountains.prototype.getPeaks = function() {
		return this.points;
	};

	/* Keyboard handler */
	function Keyboard() {
		var keyState = {};
		this.KEYS = { LEFT: 37, RIGHT:39, FIRE:32 };

		window.onkeydown = function(e) {
			keyState[e.keyCode] = true;
		};

		window.onkeyup = function(e) {
			keyState[e.keyCode] = false;
		};

		this.isDown = function(keyCode) {
			return keyState[keyCode] === true;
		};

	};

	/* Helpers */

	var game = new Game("myGame");
})();

<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var process = global.process;
var bufrw = require('bufrw');
var setTimeout = require('timers').setTimeout;
var console = require('console');

/*eslint no-console: 0*/
var v2 = require('../../v2/index.js');

var spanId = [0, 1];
var CN_BUFFER = new Buffer('cn');
var parentId = [2, 3];
var traceId = [4, 5];
var tracing = new v2.Tracing(
    spanId, parentId, traceId
);

var frame = new v2.Frame(24,    // frame id
    new v2.CallRequest(
        42,                     // flags
        99,                     // ttl
        tracing,                // tracing
        'castle',               // service
        {                       // headers
            'cn': 'mario',      // headers.cn
            'as': 'plumber'     // headers.as
        },                      //
        v2.Checksum.Types.None, // csum
        ['door', 'key', 'turn'] // args
    )
);

function main(mode, ITER) {
    var buf = bufrw.toBuffer(v2.Frame.RW, frame);

    runLoop(buf, mode, 1000);
    console.log('done warmup');
    setTimeout(pastWarmup, 250);

    function pastWarmup() {
        console.log('running bench', process.pid);
        var start = Date.now();
        runLoop(buf, mode, ITER);
        var end = Date.now();
        console.log('finised bench', end - start);
    }
}

function runLoop(buf, mode, ITER) {
    if (mode === 'optimized') {
        runOptimizedLoop(buf, ITER);
    } else if (mode === 'default') {
        runDefaultLoop(buf, ITER);
    } else {
        console.warn('noop');
    }
}

function runDefaultLoop(buf, ITER) {
    var resArr = new Array(10);
    var lazyFrame = bufrw.fromBuffer(v2.LazyFrame.RW, buf);

    for (var i = 0; i < ITER; i++) {
        var res = lazyFrame.bodyRW.lazy.readHeaders(lazyFrame);
        var headers = res.value;

        resArr[i % 10] = new FrameData(
            String(headers.getValue(CN_BUFFER))
        );

        // Naughty; reset cache
        lazyFrame.cache.callerNameStr = null;
        lazyFrame.cache.headerStartOffset = null;
        lazyFrame.cache.csumStartOffset = null;
        lazyFrame.cache.cnValueOffset = null;
    }
}

function runOptimizedLoop(buf, ITER) {
    var resArr = new Array(10);
    var lazyFrame = bufrw.fromBuffer(v2.LazyFrame.RW, buf);

    for (var i = 0; i < ITER; i++) {
        var callerName = lazyFrame.bodyRW.lazy.readCallerNameStr(lazyFrame);

        resArr[i % 10] = new FrameData(callerName);

        // Naughty; reset cache
        lazyFrame.cache.callerNameStr = null;
        lazyFrame.cache.headerStartOffset = null;
        lazyFrame.cache.csumStartOffset = null;
        lazyFrame.cache.cnValueOffset = null;
    }
}

function FrameData(callerName) {
    this.callerName = callerName;
}

if (require.main === module) {
    var arg = process.argv[2];
    var mode = process.argv[3] || 'optimized';
    var ITERATIONS = 1000 * 1000 * 2;
    if (arg) {
        ITERATIONS = 1000 * 1000 * 2 * parseInt(arg, 10);
    }

    main(mode, ITERATIONS);
}
<commit_msg>import Buffer + lint<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var process = global.process;
var bufrw = require('bufrw');
var setTimeout = require('timers').setTimeout;
var console = require('console');
var Buffer = require('buffer').Buffer;

/*eslint no-console: 0*/
var v2 = require('../../v2/index.js');

var spanId = [0, 1];
var CN_BUFFER = new Buffer('cn');
var parentId = [2, 3];
var traceId = [4, 5];
var tracing = new v2.Tracing(
    spanId, parentId, traceId
);

var frame = new v2.Frame(24,    // frame id
    new v2.CallRequest(
        42,                     // flags
        99,                     // ttl
        tracing,                // tracing
        'castle',               // service
        {                       // headers
            'cn': 'mario',      // headers.cn
            'as': 'plumber'     // headers.as
        },                      //
        v2.Checksum.Types.None, // csum
        ['door', 'key', 'turn'] // args
    )
);

function main(mode, ITER) {
    var buf = bufrw.toBuffer(v2.Frame.RW, frame);

    runLoop(buf, mode, 1000);
    console.log('done warmup');
    setTimeout(pastWarmup, 250);

    function pastWarmup() {
        console.log('running bench', process.pid);
        var start = Date.now();
        runLoop(buf, mode, ITER);
        var end = Date.now();
        console.log('finised bench', end - start);
    }
}

function runLoop(buf, mode, ITER) {
    if (mode === 'optimized') {
        runOptimizedLoop(buf, ITER);
    } else if (mode === 'default') {
        runDefaultLoop(buf, ITER);
    } else {
        console.warn('noop');
    }
}

function runDefaultLoop(buf, ITER) {
    var resArr = new Array(10);
    var lazyFrame = bufrw.fromBuffer(v2.LazyFrame.RW, buf);

    for (var i = 0; i < ITER; i++) {
        var res = lazyFrame.bodyRW.lazy.readHeaders(lazyFrame);
        var headers = res.value;

        resArr[i % 10] = new FrameData(
            String(headers.getValue(CN_BUFFER))
        );

        // Naughty; reset cache
        lazyFrame.cache.callerNameStr = null;
        lazyFrame.cache.headerStartOffset = null;
        lazyFrame.cache.csumStartOffset = null;
        lazyFrame.cache.cnValueOffset = null;
    }
}

function runOptimizedLoop(buf, ITER) {
    var resArr = new Array(10);
    var lazyFrame = bufrw.fromBuffer(v2.LazyFrame.RW, buf);

    for (var i = 0; i < ITER; i++) {
        var callerName = lazyFrame.bodyRW.lazy.readCallerNameStr(lazyFrame);

        resArr[i % 10] = new FrameData(callerName);

        // Naughty; reset cache
        lazyFrame.cache.callerNameStr = null;
        lazyFrame.cache.headerStartOffset = null;
        lazyFrame.cache.csumStartOffset = null;
        lazyFrame.cache.cnValueOffset = null;
    }
}

function FrameData(callerName) {
    this.callerName = callerName;
}

if (require.main === module) {
    var arg = process.argv[2];
    var mode = process.argv[3] || 'optimized';
    var ITERATIONS = 1000 * 1000 * 2;
    if (arg) {
        ITERATIONS = 1000 * 1000 * 2 * parseInt(arg, 10);
    }

    main(mode, ITERATIONS);
}
<|endoftext|>


<commit_before>var router = require('express').Router();
var fs = require('fs');

router.get('/', function(req, res)
	{
		fs.readdir('./apis', function(err, files)
			{
				if(err)
				{
					res.json({"error":true});
					console.error(err.stack);
				}
				else
				{
					console.log(files);
					//var aux = JSON.parse(files);
					res.send(files);
				}
			});
	});

module.exports = router;<commit_msg>Aprobado<commit_after>var router = require('express').Router();
var fs = require('fs');

router.get('/', function(req, res)
	{
		fs.readdir('./apis', function(err, files)
			{
				if(err)
				{
					res.json({"error":true});
					console.error(err.stack);
				}
				else
				{
					res.send(files);
				}
			});
	});

module.exports = router;<|endoftext|>


<commit_before>import EventEmitter from 'events';
import React from 'react';
import Router from 'react-router';
import Modal from 'react-bootstrap';

import './ui/navbar.js';

import Home from './pages/home.js';
import LoginModal from './modals/login.js';

var Route = Router.Route;
var RouteHandler = Router.RouteHandler

window.modal_instances = {}
React.render(<LoginModal/>, document.getElementById('modals'));

class App extends React.Component
{
    render() {
        return (<RouteHandler/>)
    }
}

var page_routes = (
    <Route handler={App}>
        <Route handler={Home} path="/" />
        <Route handler={LoginModal} path="login" />
    </Route>
);
var page_router = Router.create({
    routes: page_routes,
    location: Router.HistoryLocation
});
page_router.run((Root) => {
    if (Object.keys(modal_instances).indexOf(document.location.pathname) !== -1)
        modal_instances[document.location.pathname].setState({ show: true });
    else
        React.render(<Root/>, document.getElementById('app'));
});

document.body.addEventListener('click', (e) => {
    if (e.target.pathname) {
        history.pushState({}, '', e.target.pathname);
        page_router.refresh();
        e.preventDefault();
    }
});
<commit_msg>noop route<commit_after>import EventEmitter from 'events';
import React from 'react';
import Router from 'react-router';
import Modal from 'react-bootstrap';

import './ui/navbar.js';

import Home from './pages/home.js';
import LoginModal from './modals/login.js';

var Route = Router.Route;
var RouteHandler = Router.RouteHandler

window.modal_instances = {}
React.render(<LoginModal/>, document.getElementById('modals'));

class App extends React.Component
{
    render() {
        return (<RouteHandler/>)
    }
}

class NoopRoute extends React.Component { render() { return null }}

var page_routes = (
    <Route handler={App}>
        <Route handler={Home} path="/home" />
        <Route handler={NoopRoute} path="login" />
    </Route>
);
var page_router = Router.create({
    routes: page_routes,
    location: Router.HistoryLocation
});
page_router.run((Root) => {
    if (Object.keys(modal_instances).indexOf(document.location.pathname) !== -1)
        modal_instances[document.location.pathname].setState({ show: true });
    else
        React.render(<Root/>, document.getElementById('app'));
});

document.body.addEventListener('click', (e) => {
    if (e.target.pathname) {
        history.pushState({}, '', e.target.pathname);
        page_router.refresh();
        e.preventDefault();
    }
});
<|endoftext|>


<commit_before>
/**
 * builds the 0th node, the content-node, in the create message graph
 *
 * Created by ksinger on 29.06.2015.
 */
//TODO switch to requirejs for dependency mngmt (so this lib isn't angular-bound)
//TODO replace calls to `won` object to `require('util')`
import won from "./won.js";
// import { useCases } from "useCaseDefinitions";
import { getAllDetails } from "../won-utils";

(function() {
  // <need-builder-js> scope

  function hasPriceSpecification() {
    return false; //TODO price-specification not fully implemented yet
  }
  function hasTimeConstraint() {
    return false; //TODO time-constraint-attachment not implemented yet
  }
  function hasAttachmentUrls(args) {
    return (
      args.attachmentUris &&
      Array.isArray(args.attachmentUris) &&
      args.attachmentUris.length > 0
    );
  }

  /**
   * Usage:  `won.buildNeedRdf(args)`
   * Where args consists of:
   *
   * **mandatory parameters:**
   *
   * * args.type: the type of the need (e.g. 'won:Supply')
   * * args.title: a string with the title (e.g. 'Couch to give away')
   * * args.description: a longer string describing the need in detail
   *
   * **optional parameters:**
   *    ```
   *    //comma-separated
   *    args.tags = 'Couch, furniture';
   *
   *    // this is the default
   *    args.facet = 'won:OwnerFacet';
   *    // the options here are:
   *    // * won.WON.OwnerFacetCompacted
   *    // * won.WON.GroupFacetCompacted
   *    // * won.WON.CoordinatorFacetCompacted
   *    // * won.WON.ParticipantFacetCompacted
   *    // * won.WON.CommentFacetCompacted
   *    // * 'won:CommentModeratedFacet'
   *    // * 'won:CommentUnrestrictedFacet'
   *    // * 'won:ControlFacet'
   *    // * 'won:BAPCCordinatorFacet'
   *    // * 'won:BAPCParticipantFacet'
   *    // * 'won:BACCCoordinatorFacet'
   *    // * 'won:BACCParticipantFacet'
   *    // * 'won:BAAtomicPCCoordinatorFacet'
   *    // * 'won:BAAtomicCCCoordinatorFacet'
   *
   *    args.latitude = 12.345678;
   *    args.longitude = 12.345678;
   *
   *    //no format assumed. this will just be attached as a string
   *    args.address = 'Yellowbrick Rd. 7, 12345 Oz';
   *
   *    // the URIs where attachments can be found / will be published
   *    args.attachmentUris = ['http://example.org/.../1234.png', 'http://example.org/.../1234.pdf']
   *
   *    // the triples will be put in the graph that's build here anyway, so there's no need to pass graph-uri
   *    args.arbitraryJsonLdGraph = [{ '@id': 'http://example.org/.../1234', 'dc:title': 'hi}, {...}, {...}]
   *
   *    args.recurInfinite =
   *    args.recursIn =
   *    args.startTime =
   *    args.endTime =
   *
   *    args.currency =
   *    args.lowerLimit =
   *    args.upperLimit =
   *    ```
   * @returns {{@id: string, @graph: {...}*}}
   *
   * NOTE: the function below makes heavy use of the fact that `undefined`
   * properties won't be included for stringification. This allows to
   * keep it readable (the alternative is a myriad of ternary statements or
   * splitting the graph-building in as many sub-functions)
   *
   *
   * //TODO mandatory but specify later:
   * contentId, e.g. 'http://localhost:8080/won/resource/event/1997814854983652400#content-need';
   */
  won.buildNeedRdf = function(args) {
    if (!args.is && !args.seeks) {
      throw new Error(
        "Expected an object with an is- and/or a seeks-subobject. Something like `{ is: {...}, seeks: {...} }`. Got " +
          JSON.stringify(args)
      );
    }

    /*
        const putIntoBoth =
            args.type === won.WON.BasicNeedTypeDotogetherCompacted;

        const putIntoIs =
            putIntoBoth ||
            args.type === won.WON.BasicNeedTypeSupplyCompacted;

        const putIntoSeeks =
            putIntoBoth ||
            args.type === won.WON.BasicNeedTypeDemandCompacted;

        let hasFlag = [];

        if(!!won.debugmode) {
            hasFlag.push("won:UsedForTesting");
        }

        if(!!args.whatsAround){
            hasFlag.push("won:WhatsAround");
            hasFlag.push("won:NoHintForCounterpart");
        }

        if(!!args.noHints){
            hasFlag.push("won:NoHintForMe");
            hasFlag.push("won:NoHintForCounterpart");
        }
        *

        //remove possible duplicates in hasFlag
        const result = [];
        hasFlag.forEach(function(item) {
            if(result.indexOf(item) < 0) {
                result.push(item);
            }
        });
        hasFlag = result;
        */

    const buildContentNode = (id, isOrSeeksData) => {
      let contentNode = {
        "@id": id,
        "dc:title": isOrSeeksData.title,
        "won:hasAttachment": hasAttachmentUrls(isOrSeeksData)
          ? isOrSeeksData.attachmentUris.map(uri => ({ "@id": uri }))
          : undefined,

        //TODO: Different id for is and seeks
        "won:hasTimeSpecification": !hasTimeConstraint(isOrSeeksData)
          ? undefined
          : {
              "@id": "_:timeSpecification",
              "@type": "won:TimeSpecification",
              "won:hasRecurInfiniteTimes": isOrSeeksData.recurInfinite,
              "won:hasRecursIn": isOrSeeksData.recursIn,
              "won:hasStartTime": isOrSeeksData.startTime,
              "won:hasEndTime": isOrSeeksData.endTime,
            },

        "won:hasPriceSpecificationhas": !hasPriceSpecification(isOrSeeksData)
          ? undefined
          : {
              "@id": "_:priceSpecification",
              "@type": "won:PriceSpecification",
              "won:hasCurrency": isOrSeeksData.currency,
              "won:hasLowerPriceLimit": isOrSeeksData.lowerPriceLimit,
              "won:hasUpperPriceLimit": isOrSeeksData.upperPriceLimit,
            },
        //TODO images, time, currency(?)
      };

      const detailList = getAllDetails();

      for (const detailName in detailList) {
        const detail = detailList[detailName];
        const detailRDF = {
          ...detail.parseToRDF({
            value: isOrSeeksData[detail.identifier],
            identifier: detail.identifier,
          }),
        };
        // add to content node
        for (const key in detailRDF) {
          contentNode[key] = detailRDF[key];
        }
      }
      return contentNode;
    };

    // TODO: if both is and seeks are present, the seeks content gets ignored here
    const isWhatsAround = args.is
      ? args.is.whatsAround
      : args.seeks.whatsAround;
    const isWhatsNew = args.is ? args.is.whatsNew : args.seeks.whatsNew;
    const noHints = args.is ? args.is.noHints : args.seeks.noHints;
    const matchingContext = args.matchingContext;
    const searchString = args.searchString;
    const noHintForCounterpart = isWhatsAround
      ? true
      : isWhatsNew
        ? true
        : args.searchString && args.useCase === 'pureSearch' //hack: no hint for counterpart only if it's a pure search
          ? true
          : false;
    let isContentUri, seeksContentUri;
    if (isWhatsAround) {
      isContentUri = won.WON.contentNodeBlankUri.whatsAround;
      seeksContentUri = won.WON.contentNodeBlankUri.whatsAround;
    } else if (isWhatsNew) {
      isContentUri = won.WON.contentNodeBlankUri.whatsNew;
      seeksContentUri = won.WON.contentNodeBlankUri.whatsNew;
    } else {
      isContentUri = args.is ? won.WON.contentNodeBlankUri.is : undefined;
      seeksContentUri = args.seeks
        ? won.WON.contentNodeBlankUri.seeks
        : undefined;
    }
    const graph = [
      {
        "@id": args.is
          ? args.is.publishedContentUri
          : args.seeks.publishedContentUri,
        "@type": "won:Need",
        "won:is": isContentUri ? { "@id": isContentUri } : undefined,
        "won:seeks": seeksContentUri ? { "@id": seeksContentUri } : undefined,
        "won:hasFacet": args.facet ? args.facet : "won:OwnerFacet",
        "won:hasFlag": new Set([
          won.debugmode ? "won:UsedForTesting" : undefined,

          isWhatsAround ? "won:WhatsAround" : undefined,
          isWhatsNew ? "won:WhatsNew" : undefined,
          noHintForCounterpart ? "won:NoHintForCounterpart" : undefined,

          noHints ? "won:NoHintForMe" : undefined,
          noHints ? "won:NoHintForCounterpart" : undefined,
        ]), ///.toArray().filter(f => f),
        "won:hasMatchingContext": matchingContext ? matchingContext : undefined,
        "won:hasSearchString": searchString ? searchString : undefined,
      },
      //, <if _hasModalities> {... (see directly below) } </if>
      args.is ? buildContentNode(isContentUri, args.is) : {},
      args.seeks && !isWhatsAround
        ? buildContentNode(seeksContentUri, args.seeks)
        : {},
      ...(args.is && args.is.arbitraryJsonLd ? args.is.arbitraryJsonLd : []),
      ...(args.seeks && args.seeks.arbitraryJsonLd
        ? args.seeks.arbitraryJsonLd
        : []),
    ];
    return {
      "@graph": graph,
      "@context": {
        ...won.defaultContext, // needed for the arbitrary rdf

        //TODO probably an alias instead of an type declaration as it's intended here
        "won:hasCurrency": "xsd:string",
        "won:hasLowerPriceLimit": "xsd:float",
        "won:hasUpperPriceLimit": "xsd:float",

        //'geo:latitude': 'xsd:float',
        //'geo:longitude':'xsd:float',
        //'won:hasAddress': 'xsd:string',

        "won:hasStartTime": "xsd:dateTime",
        "won:hasEndTime": "xsd:dateTime",

        "won:hasFacet": {
          "@id": won.WON.hasFacet,
          "@type": "@id",
        },
        "won:hasFlag": {
          "@id": won.WON.hasFlag,
          "@type": "@id",
        },
      },
    };
  };
})(); // </need-builder-js>
<commit_msg>Prettyfy js<commit_after>/**
 * builds the 0th node, the content-node, in the create message graph
 *
 * Created by ksinger on 29.06.2015.
 */
//TODO switch to requirejs for dependency mngmt (so this lib isn't angular-bound)
//TODO replace calls to `won` object to `require('util')`
import won from "./won.js";
// import { useCases } from "useCaseDefinitions";
import { getAllDetails } from "../won-utils";

(function() {
  // <need-builder-js> scope

  function hasPriceSpecification() {
    return false; //TODO price-specification not fully implemented yet
  }
  function hasTimeConstraint() {
    return false; //TODO time-constraint-attachment not implemented yet
  }
  function hasAttachmentUrls(args) {
    return (
      args.attachmentUris &&
      Array.isArray(args.attachmentUris) &&
      args.attachmentUris.length > 0
    );
  }

  /**
   * Usage:  `won.buildNeedRdf(args)`
   * Where args consists of:
   *
   * **mandatory parameters:**
   *
   * * args.type: the type of the need (e.g. 'won:Supply')
   * * args.title: a string with the title (e.g. 'Couch to give away')
   * * args.description: a longer string describing the need in detail
   *
   * **optional parameters:**
   *    ```
   *    //comma-separated
   *    args.tags = 'Couch, furniture';
   *
   *    // this is the default
   *    args.facet = 'won:OwnerFacet';
   *    // the options here are:
   *    // * won.WON.OwnerFacetCompacted
   *    // * won.WON.GroupFacetCompacted
   *    // * won.WON.CoordinatorFacetCompacted
   *    // * won.WON.ParticipantFacetCompacted
   *    // * won.WON.CommentFacetCompacted
   *    // * 'won:CommentModeratedFacet'
   *    // * 'won:CommentUnrestrictedFacet'
   *    // * 'won:ControlFacet'
   *    // * 'won:BAPCCordinatorFacet'
   *    // * 'won:BAPCParticipantFacet'
   *    // * 'won:BACCCoordinatorFacet'
   *    // * 'won:BACCParticipantFacet'
   *    // * 'won:BAAtomicPCCoordinatorFacet'
   *    // * 'won:BAAtomicCCCoordinatorFacet'
   *
   *    args.latitude = 12.345678;
   *    args.longitude = 12.345678;
   *
   *    //no format assumed. this will just be attached as a string
   *    args.address = 'Yellowbrick Rd. 7, 12345 Oz';
   *
   *    // the URIs where attachments can be found / will be published
   *    args.attachmentUris = ['http://example.org/.../1234.png', 'http://example.org/.../1234.pdf']
   *
   *    // the triples will be put in the graph that's build here anyway, so there's no need to pass graph-uri
   *    args.arbitraryJsonLdGraph = [{ '@id': 'http://example.org/.../1234', 'dc:title': 'hi}, {...}, {...}]
   *
   *    args.recurInfinite =
   *    args.recursIn =
   *    args.startTime =
   *    args.endTime =
   *
   *    args.currency =
   *    args.lowerLimit =
   *    args.upperLimit =
   *    ```
   * @returns {{@id: string, @graph: {...}*}}
   *
   * NOTE: the function below makes heavy use of the fact that `undefined`
   * properties won't be included for stringification. This allows to
   * keep it readable (the alternative is a myriad of ternary statements or
   * splitting the graph-building in as many sub-functions)
   *
   *
   * //TODO mandatory but specify later:
   * contentId, e.g. 'http://localhost:8080/won/resource/event/1997814854983652400#content-need';
   */
  won.buildNeedRdf = function(args) {
    if (!args.is && !args.seeks) {
      throw new Error(
        "Expected an object with an is- and/or a seeks-subobject. Something like `{ is: {...}, seeks: {...} }`. Got " +
          JSON.stringify(args)
      );
    }

    /*
        const putIntoBoth =
            args.type === won.WON.BasicNeedTypeDotogetherCompacted;

        const putIntoIs =
            putIntoBoth ||
            args.type === won.WON.BasicNeedTypeSupplyCompacted;

        const putIntoSeeks =
            putIntoBoth ||
            args.type === won.WON.BasicNeedTypeDemandCompacted;

        let hasFlag = [];

        if(!!won.debugmode) {
            hasFlag.push("won:UsedForTesting");
        }

        if(!!args.whatsAround){
            hasFlag.push("won:WhatsAround");
            hasFlag.push("won:NoHintForCounterpart");
        }

        if(!!args.noHints){
            hasFlag.push("won:NoHintForMe");
            hasFlag.push("won:NoHintForCounterpart");
        }
        *

        //remove possible duplicates in hasFlag
        const result = [];
        hasFlag.forEach(function(item) {
            if(result.indexOf(item) < 0) {
                result.push(item);
            }
        });
        hasFlag = result;
        */

    const buildContentNode = (id, isOrSeeksData) => {
      let contentNode = {
        "@id": id,
        "dc:title": isOrSeeksData.title,
        "won:hasAttachment": hasAttachmentUrls(isOrSeeksData)
          ? isOrSeeksData.attachmentUris.map(uri => ({ "@id": uri }))
          : undefined,

        //TODO: Different id for is and seeks
        "won:hasTimeSpecification": !hasTimeConstraint(isOrSeeksData)
          ? undefined
          : {
              "@id": "_:timeSpecification",
              "@type": "won:TimeSpecification",
              "won:hasRecurInfiniteTimes": isOrSeeksData.recurInfinite,
              "won:hasRecursIn": isOrSeeksData.recursIn,
              "won:hasStartTime": isOrSeeksData.startTime,
              "won:hasEndTime": isOrSeeksData.endTime,
            },

        "won:hasPriceSpecificationhas": !hasPriceSpecification(isOrSeeksData)
          ? undefined
          : {
              "@id": "_:priceSpecification",
              "@type": "won:PriceSpecification",
              "won:hasCurrency": isOrSeeksData.currency,
              "won:hasLowerPriceLimit": isOrSeeksData.lowerPriceLimit,
              "won:hasUpperPriceLimit": isOrSeeksData.upperPriceLimit,
            },
        //TODO images, time, currency(?)
      };

      const detailList = getAllDetails();

      for (const detailName in detailList) {
        const detail = detailList[detailName];
        const detailRDF = {
          ...detail.parseToRDF({
            value: isOrSeeksData[detail.identifier],
            identifier: detail.identifier,
          }),
        };
        // add to content node
        for (const key in detailRDF) {
          contentNode[key] = detailRDF[key];
        }
      }
      return contentNode;
    };

    // TODO: if both is and seeks are present, the seeks content gets ignored here
    const isWhatsAround = args.is
      ? args.is.whatsAround
      : args.seeks.whatsAround;
    const isWhatsNew = args.is ? args.is.whatsNew : args.seeks.whatsNew;
    const noHints = args.is ? args.is.noHints : args.seeks.noHints;
    const matchingContext = args.matchingContext;
    const searchString = args.searchString;
    const noHintForCounterpart = isWhatsAround
      ? true
      : isWhatsNew
        ? true
        : args.searchString && args.useCase === "pureSearch" //hack: no hint for counterpart only if it's a pure search
          ? true
          : false;
    let isContentUri, seeksContentUri;
    if (isWhatsAround) {
      isContentUri = won.WON.contentNodeBlankUri.whatsAround;
      seeksContentUri = won.WON.contentNodeBlankUri.whatsAround;
    } else if (isWhatsNew) {
      isContentUri = won.WON.contentNodeBlankUri.whatsNew;
      seeksContentUri = won.WON.contentNodeBlankUri.whatsNew;
    } else {
      isContentUri = args.is ? won.WON.contentNodeBlankUri.is : undefined;
      seeksContentUri = args.seeks
        ? won.WON.contentNodeBlankUri.seeks
        : undefined;
    }
    const graph = [
      {
        "@id": args.is
          ? args.is.publishedContentUri
          : args.seeks.publishedContentUri,
        "@type": "won:Need",
        "won:is": isContentUri ? { "@id": isContentUri } : undefined,
        "won:seeks": seeksContentUri ? { "@id": seeksContentUri } : undefined,
        "won:hasFacet": args.facet ? args.facet : "won:OwnerFacet",
        "won:hasFlag": new Set([
          won.debugmode ? "won:UsedForTesting" : undefined,

          isWhatsAround ? "won:WhatsAround" : undefined,
          isWhatsNew ? "won:WhatsNew" : undefined,
          noHintForCounterpart ? "won:NoHintForCounterpart" : undefined,

          noHints ? "won:NoHintForMe" : undefined,
          noHints ? "won:NoHintForCounterpart" : undefined,
        ]), ///.toArray().filter(f => f),
        "won:hasMatchingContext": matchingContext ? matchingContext : undefined,
        "won:hasSearchString": searchString ? searchString : undefined,
      },
      //, <if _hasModalities> {... (see directly below) } </if>
      args.is ? buildContentNode(isContentUri, args.is) : {},
      args.seeks && !isWhatsAround
        ? buildContentNode(seeksContentUri, args.seeks)
        : {},
      ...(args.is && args.is.arbitraryJsonLd ? args.is.arbitraryJsonLd : []),
      ...(args.seeks && args.seeks.arbitraryJsonLd
        ? args.seeks.arbitraryJsonLd
        : []),
    ];
    return {
      "@graph": graph,
      "@context": {
        ...won.defaultContext, // needed for the arbitrary rdf

        //TODO probably an alias instead of an type declaration as it's intended here
        "won:hasCurrency": "xsd:string",
        "won:hasLowerPriceLimit": "xsd:float",
        "won:hasUpperPriceLimit": "xsd:float",

        //'geo:latitude': 'xsd:float',
        //'geo:longitude':'xsd:float',
        //'won:hasAddress': 'xsd:string',

        "won:hasStartTime": "xsd:dateTime",
        "won:hasEndTime": "xsd:dateTime",

        "won:hasFacet": {
          "@id": won.WON.hasFacet,
          "@type": "@id",
        },
        "won:hasFlag": {
          "@id": won.WON.hasFlag,
          "@type": "@id",
        },
      },
    };
  };
})(); // </need-builder-js>
<|endoftext|>


<commit_before>/* global phantom, document, window, btoa */
'use strict';
var system = require('system');
var page = require('webpage').create();
var objectAssign = require('object-assign');
var opts = JSON.parse(system.args[1]);
var log = console.log;

function formatTrace(trace) {
	var src = trace.file || trace.sourceURL;
	var fn = (trace.function ? ' in function ' + trace.function : '');
	return ' → ' + src + ' on line ' + trace.line + fn;
}

console.log = console.error = function () {
	system.stderr.writeLine([].slice.call(arguments).join(' '));
};

if (opts.username && opts.password) {
	opts.headers = objectAssign({}, opts.headers, {
		Authorization: 'Basic ' + btoa(opts.username + ':' + opts.password)
	});
}

if (opts.userAgent) {
	page.settings.userAgent = opts.userAgent;
}

opts.cookies.forEach(function (cookie) {
	if (!phantom.addCookie(cookie)) {
		console.error('Couldn\'t add cookie: ' + JSON.stringify(cookie));
		phantom.exit(1);
	}
});

phantom.onError = function (err, trace) {
	console.error('PHANTOM ERROR: ' + err + formatTrace(trace[0]));
	phantom.exit(1);
};

page.onError = function (err, trace) {
	console.error('WARN: ' + err + formatTrace(trace[0]));
};

if (opts.es5shim) {
	page.onResourceReceived = function () {
		page.injectJs(opts.es5shim);
	};
}

page.viewportSize = {
	width: opts.width,
	height: opts.height
};

page.customHeaders = opts.headers || {};
page.zoomFactor = opts.scale;

page.open(opts.url, function (status) {
	if (status === 'fail') {
		console.error('Couldn\'t load url: ' + opts.url);
		phantom.exit(1);
		return;
	}

	if (opts.crop) {
		page.clipRect = {
			top: 0,
			left: 0,
			width: opts.width,
			height: opts.height
		};
	}

	page.evaluate(function () {
		var bgColor = window
			.getComputedStyle(document.body)
			.getPropertyValue('background-color');

		if (!bgColor || bgColor === 'rgba(0, 0, 0, 0)') {
			document.body.style.backgroundColor = 'white';
		}
	});

	window.setTimeout(function () {
		if (opts.hide) {
			page.evaluate(function (els) {
				els.forEach(function (el) {
					[].forEach.call(document.querySelectorAll(el), function (e) {
						e.style.visibility = 'hidden';
					});
				});
			}, opts.hide);
		}

		if (opts.selector) {
			page.clipRect = page.evaluate(function (el) {
				return document
					.querySelector(el)
					.getBoundingClientRect();
			}, opts.selector);
		}

		log.call(console, page.renderBase64(opts.format));
		phantom.exit();
	}, opts.delay * 1000);
});
<commit_msg>use a better way to set cookies<commit_after>/* global phantom, document, window, btoa */
'use strict';
var system = require('system');
var page = require('webpage').create();
var objectAssign = require('object-assign');
var opts = JSON.parse(system.args[1]);
var log = console.log;

function formatTrace(trace) {
	var src = trace.file || trace.sourceURL;
	var fn = (trace.function ? ' in function ' + trace.function : '');
	return ' → ' + src + ' on line ' + trace.line + fn;
}

console.log = console.error = function () {
	system.stderr.writeLine([].slice.call(arguments).join(' '));
};

if (opts.username && opts.password) {
	opts.headers = objectAssign({}, opts.headers, {
		Authorization: 'Basic ' + btoa(opts.username + ':' + opts.password)
	});
}

if (opts.userAgent) {
	page.settings.userAgent = opts.userAgent;
}

phantom.cookies = opts.cookies;

phantom.onError = function (err, trace) {
	console.error('PHANTOM ERROR: ' + err + formatTrace(trace[0]));
	phantom.exit(1);
};

page.onError = function (err, trace) {
	console.error('WARN: ' + err + formatTrace(trace[0]));
};

if (opts.es5shim) {
	page.onResourceReceived = function () {
		page.injectJs(opts.es5shim);
	};
}

page.viewportSize = {
	width: opts.width,
	height: opts.height
};

page.customHeaders = opts.headers || {};
page.zoomFactor = opts.scale;

page.open(opts.url, function (status) {
	if (status === 'fail') {
		console.error('Couldn\'t load url: ' + opts.url);
		phantom.exit(1);
		return;
	}

	if (opts.crop) {
		page.clipRect = {
			top: 0,
			left: 0,
			width: opts.width,
			height: opts.height
		};
	}

	page.evaluate(function () {
		var bgColor = window
			.getComputedStyle(document.body)
			.getPropertyValue('background-color');

		if (!bgColor || bgColor === 'rgba(0, 0, 0, 0)') {
			document.body.style.backgroundColor = 'white';
		}
	});

	window.setTimeout(function () {
		if (opts.hide) {
			page.evaluate(function (els) {
				els.forEach(function (el) {
					[].forEach.call(document.querySelectorAll(el), function (e) {
						e.style.visibility = 'hidden';
					});
				});
			}, opts.hide);
		}

		if (opts.selector) {
			page.clipRect = page.evaluate(function (el) {
				return document
					.querySelector(el)
					.getBoundingClientRect();
			}, opts.selector);
		}

		log.call(console, page.renderBase64(opts.format));
		phantom.exit();
	}, opts.delay * 1000);
});
<|endoftext|>


<commit_before>Application.Controllers.controller("FilesController",
    ["$scope", "projectFiles", "applySearch",
        "pubsub", "mcfile", "$state", "pubsub", FilesController]);
function FilesController($scope, projectFiles, applySearch,
                         $filter, mcfile, $state, pubsub) {

    var f = projectFiles.model.projects[$scope.project.id].dir;

    // Root is name of project. Have it opened by default.
    $scope.files = [f];
    applySearch($scope, "searchInput", applyQuery);

    function applyQuery() {
        var search = {
            name: ""
        };

        if ($scope.searchInput === "") {
            $scope.files = [projectFiles.model.projects[$scope.project.id].dir];
        } else {
            var filesToSearch = projectFiles.model.projects[$scope.project.id].byMediaType.all;
            search.name = $scope.searchInput;
            $scope.files = $filter('filter')(filesToSearch, search);
        }
    }

    $scope.fileSrc = function (file) {
        return mcfile.src(file.id);
    };

    var columnDefs = [
        {
            displayName: "",
            field: "name",
            width: 350,
            cellClicked: cellClicked,
            cellRenderer: function (params) {
                return '' +
                    '' +
                    params.node.name + '';
            }
        }];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: $scope.files,
        rowSelection: 'multiple',
        rowsAlreadyGrouped: true,
        enableColResize: true,
        enableSorting: true,
        rowHeight: 30,
        angularCompileRows: true,
        icons: {
            groupExpanded: '',
            groupContracted: ''
        },
        groupInnerCellRenderer: groupInnerCellRenderer
    };

    //groupInnerCellRenderer does not have ability to add ng click. So as
    // an alternative i used event listener to display the data directory
    function groupInnerCellRenderer(params) {
        var eCell = document.createElement('span');
        eCell.innerHTML = params.node.displayname;
        eCell.addEventListener('click', function () {
            projectFiles.setActiveDirectory(params.node);
            if ($state.current.name === 'projects.project.files') {
                $state.go('projects.project.files.edit', {'file_id': ''});
            } else {
                pubsub.send('display-directory');
            }

        });
        return eCell;
    }

    function cellClicked(params) {
        projectFiles.setActiveFile(params.node);
        $state.go('projects.project.files.edit', {'file_id': params.node.df_id});
    }

}
<commit_msg>Allows force the state for displaying files to be called even if the url state hasn't changed. This ways the file always loads.<commit_after>Application.Controllers.controller("FilesController",
    ["$scope", "projectFiles", "applySearch",
        "pubsub", "mcfile", "$state", "pubsub", FilesController]);
function FilesController($scope, projectFiles, applySearch,
                         $filter, mcfile, $state, pubsub) {

    var f = projectFiles.model.projects[$scope.project.id].dir;

    // Root is name of project. Have it opened by default.
    $scope.files = [f];
    applySearch($scope, "searchInput", applyQuery);

    function applyQuery() {
        var search = {
            name: ""
        };

        if ($scope.searchInput === "") {
            $scope.files = [projectFiles.model.projects[$scope.project.id].dir];
        } else {
            var filesToSearch = projectFiles.model.projects[$scope.project.id].byMediaType.all;
            search.name = $scope.searchInput;
            $scope.files = $filter('filter')(filesToSearch, search);
        }
    }

    $scope.fileSrc = function (file) {
        return mcfile.src(file.id);
    };

    var columnDefs = [
        {
            displayName: "",
            field: "name",
            width: 350,
            cellClicked: cellClicked,
            cellRenderer: function (params) {
                return '' +
                    '' +
                    params.node.name + '';
            }
        }];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: $scope.files,
        rowSelection: 'multiple',
        rowsAlreadyGrouped: true,
        enableColResize: true,
        enableSorting: true,
        rowHeight: 30,
        angularCompileRows: true,
        icons: {
            groupExpanded: '',
            groupContracted: ''
        },
        groupInnerCellRenderer: groupInnerCellRenderer
    };

    //groupInnerCellRenderer does not have ability to add ng click. So as
    // an alternative i used event listener to display the data directory
    function groupInnerCellRenderer(params) {
        var eCell = document.createElement('span');
        eCell.innerHTML = params.node.displayname;
        eCell.addEventListener('click', function () {
            projectFiles.setActiveDirectory(params.node);
            if ($state.current.name === 'projects.project.files') {
                $state.go('projects.project.files.edit', {'file_id': ''}, {reload: true});
            } else {
                pubsub.send('display-directory');
            }

        });
        return eCell;
    }

    function cellClicked(params) {
        projectFiles.setActiveFile(params.node);
        $state.go('projects.project.files.edit', {'file_id': params.node.df_id}, {reload: true});
    }

}
<|endoftext|>