Example #1
0
Outgoing.prototype.placeOrder = function (id, contract, order) {



  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS) {
    if (order.scaleInitLevelSize != Number.MAX_VALUE ||
        order.scalePriceIncrement != Number.MAX_VALUE) {
      return this._controller.emitError('It does not support Scale orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORT_COMBO_LEGS) {
    if (_.isArray(contract.comboLegs)) {
      contract.comboLegs.forEach(function (comboLeg) {
        if (comboLeg.shortSaleSlot !== 0 || !_.isEmpty(comboLeg.designatedLocation)) {
          return this._controller.emitError('It does not support SSHORT flag for combo legs.');
        }
      }.bind(this));
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.WHAT_IF_ORDERS) {
    if (order.whatIf) {
      return this._controller.emitError('It does not support what-if orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.UNDER_COMP) {
    if (contract.underComp) {
      return this._controller.emitError('It does not support delta-neutral orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS2) {
    if (order.scaleSubsLevelSize !== Number.MAX_VALUE) {
      return this._controller.emitError('It does not support Subsequent Level Size for Scale orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.ALGO_ORDERS) {
    if (!_.isEmpty(order.algoStrategy)) {
      return this._controller.emitError('It does not support algo orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.NOT_HELD) {
    if (order.notHeld) {
      return this._controller.emitError('It does not support notHeld parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SEC_ID_TYPE) {
    if (!_.isEmpty(contract.secIdType) || !_.isEmpty(contract.secId)) {
      return this._controller.emitError('It does not support secIdType and secId parameters.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.PLACE_ORDER_CONID) {
    if (contract.conId > 0) {
      return this._controller.emitError('It does not support conId parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORTX) {
    if (order.exemptCode !== -1) {
      return this._controller.emitError('It does not support exemptCode parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORTX) {
    if (_.isArray(contract.comboLegs)) {
      contract.comboLegs.forEach(function (comboLeg) {
        if (comboLeg.exemptCode !== -1) {
          return this._controller.emitError('It does not support exemptCode parameter.');
        }
      }.bind(this));
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.HEDGE_ORDERS) {
    if (!_.isEmpty(order.hedgeType)) {
      return this._controller.emitError('It does not support hedge orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.OPT_OUT_SMART_ROUTING) {
    if (order.optOutSmartRouting) {
      return this._controller.emitError('It does not support optOutSmartRouting parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.DELTA_NEUTRAL_CONID) {
    if (order.deltaNeutralConId > 0 ||
        !_.isEmpty(order.deltaNeutralSettlingFirm) ||
        !_.isEmpty(order.deltaNeutralClearingAccount) ||
        !_.isEmpty(order.deltaNeutralClearingIntent)) {
      return this._controller.emitError('It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.DELTA_NEUTRAL_OPEN_CLOSE) {
    if (!_.isEmpty(order.deltaNeutralOpenClose) ||
        order.deltaNeutralShortSale ||
        order.deltaNeutralShortSaleSlot > 0 ||
        !_.isEmpty(order.deltaNeutralDesignatedLocation)) {
      return this._controller.emitError('It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS3) {
    if (order.scalePriceIncrement > 0 && order.scalePriceIncrement != Number.MAX_VALUE) {
      if (order.scalePriceAdjustValue !== Number.MAX_VALUE ||
          order.scalePriceAdjustInterval !== Number.MAX_VALUE ||
          order.scaleProfitOffset !== Number.MAX_VALUE ||
          order.scaleAutoReset ||
          order.scaleInitPosition !== Number.MAX_VALUE ||
          order.scaleInitFillQty !== Number.MAX_VALUE ||
          order.scaleRandomPercent) {
        return this._controller.emitError('It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent');
      }
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (_.isArray(order.orderComboLegs)) {
      order.orderComboLegs.forEach(function (orderComboLeg) {
        if (orderComboLeg.price !== Number.MAX_VALUE) {
          return this._controller.emitError('It does not support per-leg prices for order combo legs.');
        }
      }.bind(this));
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRAILING_PERCENT) {
    if (order.trailingPercent !== Number.MAX_VALUE) {
      return this._controller.emitError('It does not support trailing percent parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRADING_CLASS) {
    if (!_.isEmpty(contract.tradingClass)) {
      return this._controller.emitError('It does not support tradingClass parameters in placeOrder.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_TABLE) {
    if (!_.isEmpty(order.scaleTable) ||
        !_.isEmpty(order.activeStartTime) ||
        !_.isEmpty(order.activeStopTime)) {
      return this._controller.emitError('It does not support scaleTable, activeStartTime and activeStopTime parameters.');
    }
  }

  var version = (this._controller._serverVersion < C.MIN_SERVER_VER.NOT_HELD ? 27 : 41);

  // send place order msg
  var args = [C.OUTGOING.PLACE_ORDER, version, id];

  // send contract fields
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.PLACE_ORDER_CONID) {
    args.push(contract.conId);
  }
  args.push(contract.symbol);
  args.push(contract.secType);
  args.push(contract.expiry);
  args.push(contract.strike);
  args.push(contract.right);
  if (this._controller._serverVersion >= 15) {
    args.push(contract.multiplier);
  }
  args.push(contract.exchange);
  if (this._controller._serverVersion >= 14) {
    args.push(contract.primaryExch);
  }
  args.push(contract.currency);
  if (this._controller._serverVersion >= 2) {
    args.push(contract.localSymbol);
  }
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.tradingClass);
  }
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SEC_ID_TYPE){
    args.push(contract.secIdType);
    args.push(contract.secId);
  }

  // send main order fields
  args.push(order.action);
  args.push(order.totalQuantity);
  args.push(order.orderType);
  if (this._controller._serverVersion < C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE) {
    args.push(order.lmtPrice === Number.MAX_VALUE ? 0 : order.lmtPrice);
  } else {
    args.push(_nullifyMax(order.lmtPrice));
  }
  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRAILING_PERCENT) {
    args.push(order.auxPrice === Number.MAX_VALUE ? 0 : order.auxPrice);
  } else {
    args.push(_nullifyMax(order.auxPrice));
  }

  // send extended order fields
  args.push(order.tif);
  args.push(order.ocaGroup);
  args.push(order.account);
  args.push(order.openClose);
  args.push(order.origin);
  args.push(order.orderRef);
  args.push(order.transmit);
  if (this._controller._serverVersion >= 4) {
    args.push(order.parentId);
  }

  if (this._controller._serverVersion >= 5) {
    args.push(order.blockOrder);
    args.push(order.sweepToFill);
    args.push(order.displaySize);
    args.push(order.triggerMethod);
    if (this._controller._serverVersion < 38) {
      // will never happen
      args.push(/* order.ignoreRth */ false);
    } else {
      args.push(order.outsideRth);
    }
  }

  if (this._controller._serverVersion >= 7) {
    args.push(order.hidden);
  }

  // Send combo legs for BAG requests
  if (this._controller._serverVersion >= 8 &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(contract.comboLegs)) {
      args.push(0);
    } else {
      args.push(contract.comboLegs.length);

      contract.comboLegs.forEach(function (comboLeg) {
        args.push(comboLeg.conId);
        args.push(comboLeg.ratio);
        args.push(comboLeg.action);
        args.push(comboLeg.exchange);
        args.push(comboLeg.openClose);

        if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORT_COMBO_LEGS) {
          args.push(comboLeg.shortSaleSlot);
          args.push(comboLeg.designatedLocation);
        }
        if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORTX_OLD) {
          args.push(comboLeg.exemptCode);
        }
      }.bind(this));
    }
  }

  // Send order combo legs for BAG requests
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(order.orderComboLegs)) {
      args.push(0);
    } else {
      args.push(order.orderComboLegs.length);
      order.orderComboLegs.forEach(function (orderComboLeg) {
        args.push(_nullifyMax(orderComboLeg.price));
      });
    }
  }

  var smartComboRoutingParamsCount;

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SMART_COMBO_ROUTING_PARAMS &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    smartComboRoutingParamsCount = !_.isArray(order.smartComboRoutingParams) ? 0 : order.smartComboRoutingParams.length;
    args.push(smartComboRoutingParamsCount);

    if (smartComboRoutingParamsCount > 0) {
      order.smartComboRoutingParams.forEach(function (tagValue) {
        args.push(tagValue.tag);
        args.push(tagValue.value);
      });
    }
  }

  if (this._controller._serverVersion >= 9) {
    // send deprecated sharesAllocation field
    args.push('');
  }

  if (this._controller._serverVersion >= 10) {
    args.push(order.discretionaryAmt);
  }

  if (this._controller._serverVersion >= 11) {
    args.push(order.goodAfterTime);
  }

  if (this._controller._serverVersion >= 12) {
    args.push(order.goodTillDate);
  }

  if (this._controller._serverVersion >= 13) {
    args.push(order.faGroup);
    args.push(order.faMethod);
    args.push(order.faPercentage);
    args.push(order.faProfile);
  }

  if (this._controller._serverVersion >= 18) {  // institutional short sale slot fields.
    args.push(order.shortSaleSlot);       // 0 only for retail, 1 or 2 only for institution.
    args.push(order.designatedLocation);  // only populate when order.shortSaleSlot = 2.
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORTX_OLD) {
    args.push(order.exemptCode);
  }

  var lower;
  var upper;

  if (this._controller._serverVersion >= 19) {
    args.push(order.ocaType);

    if (this._controller._serverVersion < 38) {
      // will never happen
      args.push(/* order.rthOnly */ false);
    }

    args.push(order.rule80A);
    args.push(order.settlingFirm);
    args.push(order.allOrNone);
    args.push(_nullifyMax(order.minQty));
    args.push(_nullifyMax(order.percentOffset));
    args.push(order.eTradeOnly);
    args.push(order.firmQuoteOnly);
    args.push(_nullifyMax(order.nbboPriceCap));
    args.push(_nullifyMax(order.auctionStrategy));
    args.push(_nullifyMax(order.startingPrice));
    args.push(_nullifyMax(order.stockRefPrice));
    args.push(_nullifyMax(order.delta));

    // Volatility orders had specific watermark price attribs in server version 26
    lower = ((this._controller._serverVersion == 26 && order.orderType === 'VOL') ?
        Number.MAX_VALUE :
        order.stockRangeLower);
    upper = (this._controller._serverVersion == 26 && order.orderType === 'VOL') ?
      Number.MAX_VALUE :
      order.stockRangeUpper;
    args.push(_nullifyMax(lower));
    args.push(_nullifyMax(upper));
  }

  if (this._controller._serverVersion >= 22) {
    args.push(order.overridePercentageConstraints);
  }

  if (this._controller._serverVersion >= 26) { // Volatility orders
     args.push(_nullifyMax(order.volatility));
     args.push(_nullifyMax(order.volatilityType));

    if (this._controller._serverVersion < 28) {
      args.push(order.deltaNeutralOrderType.toUpperCase() === 'MKT');
    } else {
      args.push(order.deltaNeutralOrderType);
      args.push(_nullifyMax(order.deltaNeutralAuxPrice));

      if (this._controller._serverVersion >= C.MIN_SERVER_VER.DELTA_NEUTRAL_CONID &&
          !_.isEmpty(order.deltaNeutralOrderType)){
        args.push(order.deltaNeutralConId);
        args.push(order.deltaNeutralSettlingFirm);
        args.push(order.deltaNeutralClearingAccount);
        args.push(order.deltaNeutralClearingIntent);
      }

      if (this._controller._serverVersion >= C.MIN_SERVER_VER.DELTA_NEUTRAL_OPEN_CLOSE &&
          !_.isEmpty(order.deltaNeutralOrderType)){
        args.push(order.deltaNeutralOpenClose);
        args.push(order.deltaNeutralShortSale);
        args.push(order.deltaNeutralShortSaleSlot);
        args.push(order.deltaNeutralDesignatedLocation);
      }
    }

    args.push(order.continuousUpdate);

    if (this._controller._serverVersion == 26) {
      // Volatility orders had specific watermark price attribs in server version 26
      lower = (order.orderType === 'VOL' ? order.stockRangeLower : Number.MAX_VALUE);
      upper = (order.orderType === 'VOL' ? order.stockRangeUpper : Number.MAX_VALUE);
      args.push(_nullifyMax(lower));
      args.push(_nullifyMax(upper));
    }

    args.push(_nullifyMax(order.referencePriceType));
  }

  if (this._controller._serverVersion >= 30) { // TRAIL_STOP_LIMIT stop price
    args.push(_nullifyMax(order.trailStopPrice));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRAILING_PERCENT){
    args.push(_nullifyMax(order.trailingPercent));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS) {
    if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS2) {
     args.push(_nullifyMax(order.scaleInitLevelSize));
     args.push(_nullifyMax(order.scaleSubsLevelSize));
    } else {
      args.push('');
      args.push(_nullifyMax(order.scaleInitLevelSize));
    }
    args.push(_nullifyMax(order.scalePriceIncrement));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS3 &&
      order.scalePriceIncrement > 0.0 &&
      order.scalePriceIncrement != Number.MAX_VALUE) {
    args.push(_nullifyMax(order.scalePriceAdjustValue));
    args.push(_nullifyMax(order.scalePriceAdjustInterval));
    args.push(_nullifyMax(order.scaleProfitOffset));
    args.push(order.scaleAutoReset);
    args.push(_nullifyMax(order.scaleInitPosition));
    args.push(_nullifyMax(order.scaleInitFillQty));
    args.push(order.scaleRandomPercent);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_TABLE) {
    args.push(order.scaleTable);
    args.push(order.activeStartTime);
    args.push(order.activeStopTime);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.HEDGE_ORDERS) {
    args.push(order.hedgeType);
    if (!_.isEmpty(order.hedgeType)) {
      args.push(order.hedgeParam);
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.OPT_OUT_SMART_ROUTING) {
    args.push(order.optOutSmartRouting);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.PTA_ORDERS) {
    args.push(order.clearingAccount);
    args.push(order.clearingIntent);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.NOT_HELD) {
    args.push(order.notHeld);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.UNDER_COMP) {
    if (_.isPlainObject(contract.underComp) && !_.isEmpty(contract.underComp)) {
      args.push(true);
      args.push(contract.underComp.conId);
      args.push(contract.underComp.delta);
      args.push(contract.underComp.price);
    } else {
      args.push(false);
    }
  }

  var algoParamsCount;

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.ALGO_ORDERS) {
    args.push(order.algoStrategy);
    if (!_.isEmpty(order.algoStrategy)) {
      algoParamsCount = (!_.isArray(order.algoParams) ? 0 : order.algoParams.length);
      args.push(algoParamsCount);
      if (algoParamsCount > 0) {
        order.algoParams.forEach(function (tagValue) {
          args.push(tagValue.tag);
          args.push(tagValue.value);
        });
      }
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.WHAT_IF_ORDERS) {
    args.push(order.whatIf);
  }

  this._send(args);
};
Example #2
0
const url = require('./utils/url');

module.exports = {
    read(apiConfig, frame) {
        if (frame.options.key === 'codeinjection_head') {
            frame.options.key = 'ghost_head';
        }

        if (frame.options.key === 'codeinjection_foot') {
            frame.options.key = 'ghost_foot';
        }
    },

    edit(apiConfig, frame) {
        // CASE: allow shorthand syntax where a single key and value are passed to edit instead of object and options
        if (_.isString(frame.data)) {
            frame.data = {settings: [{key: frame.data, value: frame.options}]};
        }

        frame.data.settings.forEach((setting) => {
            // CASE: transform objects/arrays into string (we store stringified objects in the db)
            // @TODO: This belongs into the model layer. We should stringify before saving and parse when fetching from db.
            // @TODO: Fix when dropping v0.1
            if (_.isObject(setting.value)) {
                setting.value = JSON.stringify(setting.value);
            }

            // @TODO: handle these transformations in a centralised API place (these rules should apply for ALL resources)

            // CASE: Ensure we won't forward strings, otherwise model events or model interactions can fail
            if (setting.value === '0' || setting.value === '1') {
 classesForAttr(attr, classes="") {
   return cx({
     [classes]: _.isString(classes),
     "has-error": !_.isEmpty(this._addressErrors()[attr])
   })
 }
Example #4
0
 _.each(object.settings, function (setting) {
     if (!_.isString(setting.value)) {
         setting.value = JSON.stringify(setting.value);
     }
 });
Example #5
0
 obj.forEach(function(arrayVal, i) {
   if(_.isString(arrayVal) && utils.matchMongoId(arrayVal)) {
     obj[i] = ObjectId(arrayVal);
   }
 });
Example #6
0
var formatter = function(params, depth, tssrc){
	var result,
		regex = new RegExp('^(\\d+)' + tssrc.defaultunit + '$'),
		temp = [];

	if (_.isString(params.value) &&
		params.value.match(/^__ALLOY_EXPR__--/)) {
		result = params.value.replace(/^__ALLOY_EXPR__--/, '').replace(/^Titanium\.|Ti\./, tssrc.titanium + '.');
	} else if (_.isArray(params.value)) {
		result = [];
		depth++;

		_.each(params.value, function(item, index){
			if (_.isArray(item)) {
				result.push(formatter({
						name: params.name,
						value: item
					}, depth, tssrc));
			} else if (_.isObject(item)) {
				temp = formatter({
						name: params.name,
						value: item
					}, depth, tssrc);

				_.each(temp, function(childitem, childindex){
					temp[childindex] = indent(depth + 2, tssrc) + childitem;
				});
				result.push('{\n' + temp.join(',\n') + '\n' + indent(depth + 1, tssrc) + '}');
			} else {
				result.push(formatter({
						name: params.name,
						value: item
					}, depth, tssrc));
			}
		});
	} else if (_.isObject(params.value)) {
		result = [];
		depth++;

		_.each(params.value, function(item, index){
			if (_.isArray(item)) {
				temp = formatter({
						name: index,
						value: item
					}, depth, tssrc);

				_.each(temp, function(childitem, childindex){
					temp[childindex] = indent(depth + 2, tssrc) + childitem;
				});
				result.push(index + ': [\n' + temp.join(',\n') + '\n' + indent(depth + 1, tssrc) + ']');
			} else if (_.isObject(item)) {
				temp = formatter({
						name: index,
						value: item
					}, depth, tssrc);

				_.each(temp, function(childitem, childindex){
					temp[childindex] = indent(depth + 2, tssrc) + childitem;
				});
				result.push(index + ': {\n' + temp.join(',\n') + '\n' + indent(depth + 1, tssrc) + '}');
			} else {
				result.push(index + ': ' + formatter({
						name: index,
						value: item
					}, depth, tssrc));
			}
		});
	} else if (_.isNull(params.value)) {
		result = 'null';
	} else if (_.isBoolean(params.value)) {
		if (params.value) {
			result = 'true';
		} else {
			result = 'false';
		}
	} else if (_.isNumber(params.value)) {
		result = params.value;
	} else {
		if (tssrc.strip_defaultunit &&
			_.indexOf(tssrc.guess_number, params.name) > -1 &&
			params.value.match(regex)) {
			result = params.value.replace(regex, '$1');
		} else if (_.indexOf(tssrc.guess_color, params.name) > -1 &&
			params.value !== 'transparent') {
			var color = parser(params.value) || hex4(params.value) || hex8(params.value);

			if (color) {
				if (0 === params.value.indexOf('rbg(') ||
					'#' === params.value[0] && 4 === params.value.length ||
					'#' === params.value[0] && 7 === params.value.length) {
					delete color.a;
				}

				switch (tssrc.color_format) {
					case 'hex':
						params.value = tohex(color);
						if (_.has(tssrc, 'color_hex_uppercase')) {
							if (tssrc.color_hex_uppercase) {
								params.value = params.value.toUpperCase();
							} else {
								params.value = params.value.toLowerCase();
							}
						}
						break;
					case 'rgb':
						params.value = torgb(color);
						break;
				}
			}

			result = tssrc.quote + params.value + tssrc.quote;
		} else {
			result = tssrc.quote + params.value + tssrc.quote;
		}
	}

	return result;
};
 return _.compact(_.map(builder.columns, function(column) {
   if (column.isCommented && _.isString(column.isCommented)) {
     return 'comment on column ' + this.wrapTable(builder) + '.' + this.wrap(column.name) + " is '" + column.isCommented + "'";
   }
 }, this));
Example #8
0
 function stripTrailingSlash (obj, field) {
     const url = obj[field];
     if (_.isString(url) && _.last(url) === '/') {
         obj[field] = url.substr(0, url.length - 1);
     }
 }
CriteriaProcessor.prototype.processSimple = function processSimple (tableName, parent, value, combinator, sensitive) {
  // Set lower logic to true
  var sensitiveTypes = ['text', 'string'],
      currentSchema = this.schema[tableName].definition,
      self = this,
      parentType,
      lower;

  if (currentSchema[parent]) {
    parentType = currentSchema[parent].type || currentSchema[parent];
  }

  lower = parentType && sensitiveTypes.indexOf(parentType) > -1;

  // Check if value is a string and if so add LOWER logic
  // to work with case in-sensitive queries

  if(!sensitive && lower && _.isString(value)) {
    // Add LOWER to parent
    parent = this.buildParam(this.getTableAlias(), parent, true);
    value = value.toLowerCase();

  } else {
    // Escape parent
    parent = this.buildParam(this.getTableAlias(), parent);
  }

  if(value === null) {
    return this.queryString += parent + ' IS NULL';
  }

  // Simple Key/Value attributes
  if(self.parameterized) {
    this.queryString += parent + ' ' + combinator + ' $' + this.paramCount;
    this.values.push(value);
    this.paramCount++;

    return;
  }

  // Check if the value is a DATE and if it's not a date turn it into one
  if(parentType === 'date' && !_.isDate(value)) {
    value = new Date(value);
  }

  if(_.isDate(value)) {
    var date = value;
    date = date.getFullYear() + '-' +
      ('00' + (date.getMonth()+1)).slice(-2) + '-' +
      ('00' + date.getDate()).slice(-2) + ' ' +
      ('00' + date.getHours()).slice(-2) + ':' +
      ('00' + date.getMinutes()).slice(-2) + ':' +
      ('00' + date.getSeconds()).slice(-2);

    value = date;
  }

  if (_.isString(value)) {
    value = '"' + utils.escapeString(value) +'"';
  }

  this.queryString += parent + ' ' + combinator + ' ' + value;
};
var __isValidTranslation = function (key) {
  return _.isString(key) && key !== "";
}
Example #11
0
	function choice(val) {
		if (_.isString(val))
			return val.charAt(randint(0, val.length - 1));
		
		return val[randint(0, val.length - 1)];
	}
Example #12
0
/**
 * Recursively converts a swagger type description into a typescript type, i.e., a model for our mustache
 * template.
 *
 * Not all type are currently supported, but they should be straightforward to add.
 *
 * @param swaggerType a swagger type definition, i.e., the right hand side of a swagger type definition.
 * @returns a recursive structure representing the type, which can be used as a template model.
 */
function convertType(swaggerType, swagger) {

    var typespec = { description: swaggerType.description, isEnum: false };

    if (swaggerType.hasOwnProperty('schema')) {
        return convertType(swaggerType.schema);
    } else if (_.isString(swaggerType.$ref)) {
        typespec.tsType = 'ref';
        typespec.target = swaggerType.$ref.substring(swaggerType.$ref.lastIndexOf('/') + 1);
    } else if (swaggerType.hasOwnProperty('enum')) {
        typespec.tsType = swaggerType.enum.map(function(str) { return JSON.stringify(str); }).join(' | ');
        typespec.isAtomic = true;
        typespec.isEnum = true;
    } else if (swaggerType.type === 'string') {
        typespec.tsType = 'string';
    } else if (swaggerType.type === 'number' || swaggerType.type === 'integer') {
        typespec.tsType = 'number';
    } else if (swaggerType.type === 'boolean') {
        typespec.tsType = 'boolean';
    } else if (swaggerType.type === 'array') {
        typespec.tsType = 'array';
        typespec.elementType = convertType(swaggerType.items);
    } else /*if (swaggerType.type === 'object')*/ { //remaining types are created as objects
        if (swaggerType.minItems >= 0 && swaggerType.hasOwnProperty('title') && !swaggerType.$ref) {
            typespec.tsType = 'any';
        }
        else {
            typespec.tsType = 'object';
            typespec.properties = [];
            if (swaggerType.allOf) {
                _.forEach(swaggerType.allOf, function (ref) {
                    if(ref.$ref) {
                        let refSegments = ref.$ref.split('/');
                        let name = refSegments[refSegments.length - 1];
                        _.forEach(swagger.definitions, function (definition, definitionName) {
                            if (definitionName === name) {
                                var property = convertType(definition, swagger);
                                typespec.properties.push(...property.properties);
                            }
                        });
                    } else {
                        var property = convertType(ref);
                        typespec.properties.push(...property.properties);
                    }
                });
            }

            _.forEach(swaggerType.properties, function (propertyType, propertyName) {
                var property = convertType(propertyType);
                property.name = propertyName;
                typespec.properties.push(property);
            });
        }
    } /*else {
     // type unknown or unsupported... just map to 'any'...
     typespec.tsType = 'any';
     }*/

    // Since Mustache does not provide equality checks, we need to do the case distinction via explicit booleans
    typespec.isRef = typespec.tsType === 'ref';
    typespec.isObject = typespec.tsType === 'object';
    typespec.isArray = typespec.tsType === 'array';
    typespec.isAtomic = typespec.isAtomic || _.includes(['string', 'number', 'boolean', 'any'], typespec.tsType);

    return typespec;

}
Example #13
0
 create: function(type) {
   if (_.isString(type)) {
     return document.createElement(type);
   }
   throw new Error("dom.create: not implemented for non-string arguments");
 },
Example #14
0
Outgoing.prototype.reqHistoricalData = function (tickerId, contract, endDateTime, durationStr,
                                                 barSizeSetting, whatToShow, useRTH, formatDate) {
  var version = 5;

  if (this._controller._serverVersion < 16) {
    return this._controller.emitError('It does not support historical data backfill.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRADING_CLASS) {
    if (!_.isEmpty(contract.tradingClass) || contract.conId > 0) {
      return this._controller.emitError('It does not support conId and tradingClass parameters in reqHistroricalData.');
    }
  }

  var args = [C.OUTGOING.REQ_HISTORICAL_DATA, version, tickerId];

  // send contract fields
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.conId);
  }

  args.push(contract.symbol);
  args.push(contract.secType);
  args.push(contract.expiry);
  args.push(contract.strike);
  args.push(contract.right);
  args.push(contract.multiplier);
  args.push(contract.exchange);
  args.push(contract.primaryExch);
  args.push(contract.currency);
  args.push(contract.localSymbol);

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.tradingClass);
  }

  if (this._controller._serverVersion >= 31) {
    args.push(!!contract.includeExpired);
  }

  if (this._controller._serverVersion >= 20) {
    args.push(endDateTime);
    args.push(barSizeSetting);
  }

  args.push(durationStr);
  args.push(useRTH);
  args.push(whatToShow);

  if (this._controller._serverVersion > 16) {
    args.push(formatDate);
  }



  if (_.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(contract.comboLegs)) {
      args.push(0);
    } else {
      args.push(contract.comboLegs.length);

      contract.comboLegs.forEach(function (comboLeg) {
        args.push(comboLeg.conId);
        args.push(comboLeg.ratio);
        args.push(comboLeg.action);
        args.push(comboLeg.exchange);
      });
    }
  }

  this._send(args);
};
Example #15
0
     _setColumnType: function (schema, name, attr, options) {

      options = (typeof options !== 'undefined') ? options : {};

      // Set primary key options
      if (attr.primaryKey === 'hash') {

        _.merge(options, {hashKey: true});
      } else if (attr.primaryKey === 'range') {

        _.merge(options, {rangeKey: true});
      } else if (attr.index === 'secondary') {

        _.merge(options, {secondaryIndex: true});
      }

      // set columns
//          console.log("name:", name);
//          console.log("attr:", attr);
      var type = (_.isString(attr)) ? attr : attr.type;

      switch (type) {
        case "date":
        case "time":
        case "datetime":
//                  console.log("Set Date:", name);
          schema.Date(name, options);
          break;

        case "integer":
        case "float":
//                  console.log("Set Number:", name);
          schema.Number(name, options);
          break;

        case "boolean":
//                  console.log("Set Boolean:", name);
          schema.Boolean(name, options);
          break;

        case "array":  // not support
          schema.StringSet(name, options);
          break;

//              case "json":
//              case "string":
//              case "binary":
        case "string":

          if (attr.autoIncrement) {

            schema.UUID(name, options);
          } else {

            schema.String(name, options);
          }
          break;

        default:
//                  console.log("Set String", name);
          schema.String(name, options);
          break;
      }
    }
CriteriaProcessor.prototype.prepareCriterion = function prepareCriterion(key, value) {
  var self = this;
  var str;
  var comparator;
  var escapedDate = false;
  var bumpParamCount = true;

  // Check value for a date type
  if(_.isDate(value)) {
    value = value.getFullYear() + '-' +
      ('00' + (value.getMonth()+1)).slice(-2) + '-' +
      ('00' + value.getDate()).slice(-2) + ' ' +
      ('00' + value.getHours()).slice(-2) + ':' +
      ('00' + value.getMinutes()).slice(-2) + ':' +
      ('00' + value.getSeconds()).slice(-2);

    value = '"' + value + '"';
    escapedDate = true;
  }

  switch(key) {

    case '<':
    case 'lessThan':

      if(this.parameterized) {
        this.values.push(value);
        str = '< ' + '$' + this.paramCount;
      }
      else {
        if(_.isString(value) && !escapedDate) {
          value = '"' + utils.escapeString(value) + '"';
        }
        str = '< ' + value;
      }

      break;

    case '<=':
    case 'lessThanOrEqual':

      if(this.parameterized) {
        this.values.push(value);
        str = '<= ' + '$' + this.paramCount;
      }
      else {
        if(_.isString(value) && !escapedDate) {
          value = '"' + utils.escapeString(value) + '"';
        }
        str = '<= ' + value;
      }

      break;

    case '>':
    case 'greaterThan':

      if(this.parameterized) {
        this.values.push(value);
        str = '> ' + '$' + this.paramCount;
      }
      else {
        if(_.isString(value) && !escapedDate) {
          value = '"' + utils.escapeString(value) + '"';
        }
        str = '> ' + value;
      }

      break;

    case '>=':
    case 'greaterThanOrEqual':

      if(this.parameterized) {
        this.values.push(value);
        str = '>= ' + '$' + this.paramCount;
      }
      else {
        if(_.isString(value) && !escapedDate) {
          value = '"' + utils.escapeString(value) + '"';
        }
        str = '>= ' + value;
      }

      break;

    case '!':
    case 'not':
      if(value === null) {
        str = 'IS NOT NULL';
        bumpParamCount = false;
      }
      else {
        // For array values, do a "NOT IN"
        if (_.isArray(value)) {

          if(self.parameterized) {
            var params = [];

            this.values = this.values.concat(value);
            str = 'NOT IN (';

            _.each(value, function() {
              params.push('$' + self.paramCount++);
            });

            str += params.join(',') + ')';

            // Roll back one since we bump the count at the end
            this.paramCount--;
          }
          else {
            str = 'NOT IN (';
            _.each(value, function(val) {

              if(_.isString(val)) {
                val = '"' + utils.escapeString(val) + '"';
              }

              str += val + ',';
            });

            str = str.slice(0, -1) + ')';
          }
        }
        // Otherwise do a regular <>
        else {

          if(this.parameterized) {
            this.values.push(value);
            str = '<> ' + '$' + this.paramCount;
          }
          else {
            if(_.isString(value)) {
              value = '"' + utils.escapeString(value) + '"';
            }

            str = '<> ' + value;
          }
        }
      }

      break;

    case 'like':

      if(this.caseSensitive) {
        comparator = 'ILIKE';
      }
      else {
        comparator = 'LIKE';
      }

      // Override comparator with WL Next features
      if(hop(self.wlNext, 'caseSensitive') && self.wlNext.caseSensitive) {
        comparator = 'LIKE';
      }

      if(this.parameterized) {
        this.values.push(value);
        str = comparator + ' ' + '$' + this.paramCount;
      }
      else {
        // Note that wildcards are not escaped out of like criterion intentionally
        str = comparator + ' "' + utils.escapeString(value) + '"';
      }

      break;

    case 'contains':

      if(this.caseSensitive) {
        comparator = 'ILIKE';
      }
      else {
        comparator = 'LIKE';
      }

      // Override comparator with WL Next features
      if(hop(self.wlNext, 'caseSensitive') && self.wlNext.caseSensitive) {
        comparator = 'LIKE';
      }

      if(this.parameterized) {
        this.values.push('%' + value + '%');
        str = comparator + ' ' + '$' + this.paramCount;
      }
      else {
        str = comparator + ' "%' + utils.escapeString(value, true) + '%"';
      }

      break;

    case 'startsWith':

      if(this.caseSensitive) {
        comparator = 'ILIKE';
      }
      else {
        comparator = 'LIKE';
      }

      // Override comparator with WL Next features
      if(hop(self.wlNext, 'caseSensitive') && self.wlNext.caseSensitive) {
        comparator = 'LIKE';
      }

      if(this.parameterized) {
        this.values.push(value + '%');
        str = comparator + ' ' + '$' + this.paramCount;
      }
      else {
        str = comparator + ' "' + utils.escapeString(value, true) + '%"';
      }

      break;

    case 'endsWith':

      if(this.caseSensitive) {
        comparator = 'ILIKE';
      }
      else {
        comparator = 'LIKE';
      }

      // Override comparator with WL Next features
      if(hop(self.wlNext, 'caseSensitive') && self.wlNext.caseSensitive) {
        comparator = 'LIKE';
      }

      if(this.parameterized) {
        this.values.push('%' + value);
        str = comparator + ' ' + '$' + this.paramCount;
      }
      else {
        str = comparator + ' "%' + utils.escapeString(value, true) + '"';
      }

      break;

    default:
      var err = new Error('Unknown filtering operator: "' + key + "\". Should be 'startsWith', '>', 'contains' or similar");
      err.operator = key;
      throw err;
  }

  // Bump paramCount
  if(bumpParamCount) {
    this.paramCount++;
  }

  // Add str to query
  this.queryString += str;
};
Example #17
0
    find: function (connection, collectionName, options, cb) {
      //sails.log.silly("adaptor::find", collectionName);
      //sails.log.silly("::option", options);

      var collection = _collectionReferences[collectionName],
        model        = adapter._getModel(collectionName),
        query        = null,
        error;


      // Options object is normalized for you:
      //
      // options.where
      // options.limit
      // options.skip
      // options.

      // Filter, paginate, and sort records from the datastore.
      // You should end up w/ an array of objects as a result.
      // If no matches were found, this will be an empty array.

      if (options && 'where' in options && _.isObject(options.where)) {

        var wheres    = options.where,
            whereExt  = this._getSubQueryWhereConditions(options),
            indexing  = adapter._whichIndex(collectionName, ((whereExt) ? whereExt : wheres )),
            hash      = indexing.hash,
            range     = indexing.range,
            indexName = indexing.index,
            scanning  = false;

        if (indexing) {
          // console.log("USING INDEX")
          // console.log(indexing);
           query = model.query(options.where[hash])
          delete options.where[hash];

          if (indexName && indexName != 'primary') {
            query.usingIndex(indexName);
          }

          if (range) {

            error = adapter._applyQueryFilter(query, 'where', range, options.where[range]);
            if (error) return cb(error);

            delete options.where[range];
          }

        } else {
          scanning = true;
          query = model.scan();
        }

        var queryOp = scanning ? 'where' : 'filter';
        for (var key in options.where) {

          // Using startKey?
          if (key == 'startKey') {

            try {
              if (_.isString(options.where.startKey)){
                query.startKey(JSON.parse(options.where[key]));
              }else{
                query.startKey(options.where.startKey);
              }
            } catch (e) {

              return cb("Wrong start key format :" + e.message);
            }

          } else {

            var condition = (whereExt) ? whereExt : options.where[key];
            if (whereExt) {
              for (var subKey in condition) {
                error = adapter._applyQueryFilter(query, queryOp, subKey, condition[subKey]);
                if (error) return cb(error);
              }
              options.where = whereExt;
            } else {
              error = adapter._applyQueryFilter(query, queryOp, key, condition);
              if (error) return cb(error);
            }
          }
        }
      }

      query = adapter._searchCondition(query, options, model);
      this._findQuery(adapter, collection, query, false, cb);
    },
Example #18
0
function Probe (name) {

   this.name = _.isString(name) ? name : 'anonymous probe';

   this.tasks = new Tasks();
}
function toBool (s) {
  return _.isString(s) ? (s.toLowerCase() === 'true') : !!s;
}
Example #20
0
 logger.setLevel ( _.reduce ( module, function ( logLevel, mPart ) {
     return _.isString ( logLevel ) ? logLevel : ( _.isUndefined ( logLevel[mPart] ) ? 'ERROR' : logLevel[mPart] );
 }, config.logLevels ) );
Example #21
0
File: do.js Project: justsml/navit
  function screenshot(/*selector|boundingRect, type, path*/) {
    var self = this;
    var path, selector, boundingRect, type;

    if (arguments.length > 1) {
      if (_.isString(arguments[0]) || _.isFunction(arguments[0])) {
        selector = arguments[0];
      } else {
        boundingRect = arguments[0];
      }

      path = arguments.length === 3 ? arguments[2] : arguments[1];
      type = arguments.length === 3 ? arguments[1] : 'PNG';
    } else {
      path = arguments[0];
      type = 'PNG';
    }

    function saveScreenshot(callback) {
      self.__page__.render(_.isFunction(path) ? path() : path, _.isFunction(type) ? type() : type, callback);
    }

    this.__queue__.push(function screenshot_step(callback) {
      debug('do.screenshot()');

      self.__page__.get('clipRect', function (err, oldRect) {
        if (err) {
          callback(err);
          return;
        }

        if (selector) {
          var sel = _.isFunction(selector) ? selector() : selector;

          self.__page__.evaluate(function (selector) {
            var element = document.querySelector(selector);

            return element ? element.getBoundingClientRect() : null;
          }, sel, function (err, newRect) {
            if (err) {
              callback(err);
              return;
            }

            if (!newRect) {
              callback(new NavitError(format("screenshot('%s') failed - selector not found", sel)));
              return;
            }

            self.__page__.set('clipRect', newRect, function (err) {
              if (err) {
                callback(err);
                return;
              }

              saveScreenshot(function (err) {
                if (err) {
                  callback(err);
                  return;
                }

                self.__page__.set('clipRect', oldRect, callback);
              });
            });
          });
          return;
        }

        if (boundingRect) {
          var newRect = _.isArray(boundingRect) ? {
            top: boundingRect[0],
            left: boundingRect[1],
            width: boundingRect[2],
            height: boundingRect[3]
          } : boundingRect;

          self.__page__.set('clipRect', newRect, function (err) {
            if (err) {
              callback(err);
              return;
            }

            saveScreenshot(function (err) {
              if (err) {
                callback(err);
                return;
              }

              self.__page__.set('clipRect', oldRect, callback);
            });
          });

          return;
        }

        saveScreenshot(callback);
      });
    });

    return this;
  }
Example #22
0
var Connection = function(opts) {
  var self = this;

  opts = _.defaults(opts || {}, {
    clientId:      null,
    clientSecret:  null,
    redirectUri:   null,
    loginUri:      LOGIN_URI,
    testLoginUri:  TEST_LOGIN_URI,
    cacheMetadata: false,
    apiVersion:    _.last(API_VERSIONS),
    environment:   'production',
    mode:          'multi',
    gzip:          false,
    autoRefresh:   false,
    onRefresh:     undefined
  });

  // convert option values

  opts.apiVersion = opts.apiVersion.toString().toLowerCase().replace('v', '').replace('\.0', '');
  opts.environment = opts.environment.toLowerCase();
  opts.mode = opts.mode.toLowerCase();

  self = _.assign(this, opts);

  // validate options

  if(!_.isString(this.clientId)) throw new Error('invalid or missing clientId');
  if(!_.isString(this.clientSecret)) throw new Error('invalid or missing clientSecret');
  if(!_.isString(this.redirectUri)) throw new Error('invalid or missing redirectUri');
  if(!_.isString(this.loginUri)) throw new Error('invalid or missing loginUri');
  if(!_.isString(this.testLoginUri)) throw new Error('invalid or missing testLoginUri');
  if(!_.isBoolean(this.cacheMetadata)) throw new Error('cacheMetadata must be a boolean');
  if(!_.isBoolean(this.gzip)) throw new Error('gzip must be a boolean');
  if(!_.isString(this.environment) || _.indexOf(ENVS, this.environment) === -1) {
    throw new Error('invalid environment, only ' + ENVS.join(' and ') + ' are allowed');
  }
  if(!_.isString(this.mode) || _.indexOf(MODES, this.mode) === -1) {
    throw new Error('invalid mode, only ' + MODES.join(' and ') + ' are allowed');
  }
  if(this.onRefresh && !_.isFunction(this.onRefresh)) throw new Error('onRefresh must be a function');

  // setup cache

  if(this.cacheMetadata) {
    this._cache = {
      keyPrefixes: {},
      sObjects: {}
    }
  }

  // parse api version

  try {
    this.apiVersion = 'v' + parseInt(this.apiVersion, 10) + '.0';
  } catch (err) {
    throw new Error('invalid apiVersion number');
  }
  if(API_VERSIONS.indexOf(this.apiVersion) === -1) {
    throw new Error('api version ' + this.apiVersion + ' is not supported');
  }

  // load plugins

  if(opts.plugins && _.isArray(opts.plugins)) {
    opts.plugins.forEach(function(pname) {
      if(!plugins[pname]) throw new Error('plugin ' + pname + ' not found');
      // clone the object
      self[pname] = _.clone(plugins[pname]._fns);

      // now bind to the connection object
      _.forOwn(self[pname], function(fn, key) {
        self[pname][key] = _.bind(self[pname][key], self);
      });

    });
  }

}
Example #23
0
 morphTo: function(morphName) {
   if (!_.isString(morphName)) throw new Error('The `morphTo` name must be specified.');
   return this._relation('morphTo', null, {morphName: morphName, candidates: _.rest(arguments)}).init(this);
 },
Example #24
0
} 	= require('./model_utilities');

/**
 * @type { any } value [ value to validate ]
 * @type { object } options [ optional object with extra constraints]
 * @description Set of validation functions to be used by model class
 */
module.exports = {
	array(value/*, options */) {
		return exists(value) && _.isArray(value);
	},
	buffer(value /*, options */) {
		return exists(value) && _.isBuffer(value);
	},
	string(value/*, options */) {
		return exists(value) && _.isString(value);
	},
	boolean(value/*, options */) {
		return exists(value) && _.isBoolean(value);
	},
	ip(value/*, options */) {
		return exists(value) && validator.isIP(value);
	},
	url(value/*, options */) {
		return exists(value) && validator.isURL(value);
	},
	slug(value/*, options*/) {
		return exists(value) && _.isString(value) && !validator.isUUID(value);
	},
	uuid(value/*, options */) {
		return exists(value) && validator.isUUID(value);
Example #25
0
  Object.keys(obj).forEach(function(attr) {

    // Parse each item in an array
    if(Array.isArray(obj[attr])) {
      var replace = false;

      obj[attr].forEach(function(item, i) {

        // Check that the item is an object
        if(!_.isPlainObject(item)) return;

        // Don't recursively parse '$in' clauses
        if (attr === '$in') return;

        // Flag as replaceable
        replace = true;

        Object.keys(item).forEach(function(itemKey) {
          var val = item[itemKey];

          // If the value is a string we need to make it an object for the parser
          if(_.isString(item[itemKey])) {
            val = {};
            val[itemKey] = item[itemKey];
          }

          self.parseOptions(itemKey, val, item, itemKey);
        });
      });

      if(replace) {
        original[attr] = obj[attr];
      }

      return;
    }

    // Recursivly Parse unless value is a date or a $in array
    if(_.isPlainObject(obj[attr]) && !_.isDate(obj[attr])) {

      // Make sure the object isn't a '!' with a single '$in' key
      if((attr !== '!' && attr !== 'not') || Object.keys(obj[attr]).length > 1) {
        parent = attr;
        self.parseOptions(attr, obj[attr], original, parent);
        return;
      }

    }

    // Handle Sorting Order with binary or -1/1 values
    if(key === 'sort') {
      original[attr] = ([0, -1].indexOf(obj[attr]) > -1) ? -1 : 1;
    }

    // Handle `contains` by building up a case insensitive regex
    if(attr === 'contains') {
      val = obj[attr];
      delete original[parent];
      val = utils.caseInsensitive(val);
      original[parent] =  '.*' + val + '.*';
      original[parent] = new RegExp('^' + original[parent] + '$', 'i');
      return;
    }

    // Handle `like`
    if(attr === 'like' || parent === 'like') {
      if(_.isPlainObject(obj[attr])) {
        Object.keys(obj[attr]).forEach(function(_key) {
          original[_key] = original[parent][_key];

          if(_.isString(original[_key])) {
            val = utils.caseInsensitive(original[_key]);
            val = val.replace(/%/g, '.*');
            original[_key] = new RegExp('^' + val + '$', 'i');
          }
        });

        delete original[parent];
        return;
      }

      // Handle non-objects
      var _key;

      if(attr === 'like') {
        _key = parent;
        original[parent] = obj[attr];
        delete original[attr];
      }

      if(parent === 'like') {
        _key = attr;
        original[attr] = obj[attr];
        delete original[parent];
      }

      if(_.isString(original[_key])) {
        val = utils.caseInsensitive(original[_key]);
        val = val.replace(/%/g, '.*');
        original[_key] = new RegExp('^' + val + '$', 'i');
        return;
      }

      return;
    }

    // Handle `startsWith` by setting a case-insensitive regex
    if(attr === 'startsWith') {
      val = obj[attr];
      delete original[parent];
      val = utils.caseInsensitive(val);
      original[parent] =  val + '.*';
      original[parent] = new RegExp('^' + original[parent] + '$', 'i');
      return;
    }

    // Handle `endsWith` by setting a case-insensitive regex
    if(attr === 'endsWith') {
      val = obj[attr];
      delete original[parent];
      val = utils.caseInsensitive(val);
      original[parent] =  '.*' + val;
      original[parent] = new RegExp('^' + original[parent] + '$', 'i');
      return;
    }

    // Handle `lessThan` by transforiming to $lt
    if(attr === 'lessThan' || attr === '<') {
      val = obj[attr];
      delete original[parent][attr];
      original[parent]['$lt'] = val;
      return;
    }

    // Handle `lessThanOrEqual` by transforiming to $lte
    if(attr === 'lessThanOrEqual' || attr === '<=') {
      val = obj[attr];
      delete original[parent][attr];
      original[parent]['$lte'] = val;
      return;
    }

    // Handle `greaterThan` by transforiming to $gt
    if(attr === 'greaterThan' || attr === '>') {
      val = obj[attr];
      delete original[parent][attr];
      original[parent]['$gt'] = val;
      return;
    }

    // Handle `greaterThanOrEqual` by transforiming to $gte
    if(attr === 'greaterThanOrEqual' || attr === '>=') {
      val = obj[attr];
      delete original[parent][attr];
      original[parent]['$gte'] = val;
      return;
    }

    // Handle `not` by transforming to $ne or $nin
    if(attr.toLowerCase() === 'not' || attr === '!') {
      val = obj[attr];
      delete original[parent];

      // Check if the val is an object and contains an $in key
      if(_.isPlainObject(val)) {
        var keys = Object.keys(val);

        if(keys.length === 1 && keys[0] === '$in') {
          original[parent] = { '$nin': val['$in'] };
          return;
        }
      }

      original[parent] = { '$ne': val };
      return;
    }

    // Check for Mongo IDs
    if(utils.matchMongoId(obj[attr])) {
      return;
    }

    // Ignore special attributes
    if(['_bsontype', '_id', 'id'].indexOf(attr) >= 0) return;

    // Replace Percent Signs
    if(_.isString(obj[attr])) {
      val = utils.caseInsensitive(obj[attr]);
      val = val.replace(/%/g, '.*');
      original[attr] = new RegExp('^' + val + '$', 'i');
      return;
    }

  });
 helper.constructBody(function(err, res) {
     if(err) return done(err);
     assert(_.isString(res), 'Expected body to be a string');
     done(err);
 });
Example #27
0
 _.each(options.uniqueKeys, (columns, indexName) => {
   if (!_.isString(indexName)) {
     indexName = 'uniq_' + tableName + '_' + columns.fields.join('_');
   }
   values.attributes += ', CONSTRAINT ' + self.quoteIdentifier(indexName) + ' UNIQUE (' + _.map(columns.fields, self.quoteIdentifier).join(', ') + ')';
 });
Example #28
0
export function isFunction(distribution: Distribution): boolean{
  const {input} = distribution;
  return (_.isString(input) && (input !== '') && (input[0] === '='));
}
Example #29
0
  render() {
    var valueFor = (attr)=> { return _.get((this.props.value || {}), attr) }
    var classes = cx({
      'address-us': true,
      'form-group': true,
      'has-child-error': !_.isEmpty(this.errorsWithLabelNames()),
      [ this.props.className ]: _.isString(this.props.className)
    })

    return (
      <div className={classes}>
        <ObsLabel text={this.props.label} required={this.props.required} htmlFor={this.state.id} />
        <ObsHint  hint={this.props.hint} />
        <ObsCompoundLayout layout={"full"}>
          <ObsText id={this.state.id}
            value={valueFor(this.fields.street_1.attr)} errors={[]}
            required={this.props.required} formatter={Formatters.stringFormatter}
            placeholder={"Address"}
            className={this.classesForAttr(this.fields.street_1.attr, "address-line-1")}
            onChange={_.bind(this.onChange, this, this.fields.street_1.attr)}
            onBlur={_.bind(this.onBlur, this, this.fields.street_1.attr)}
            didMount={this.register} willUnmount={this.unregister}
            autoFocus={this.props.autoFocus} customValidator={this.props.streetCustomValidator}/>

          <ObsCompoundLayout layout={"inline"}>
            <div className="flex-grow-shrink">
              <ObsText
                value={valueFor(this.fields.city.attr)} errors={[]}
                required={this.props.required} formatter={Formatters.stringFormatter}
                placeholder={"City"}
                className={this.classesForAttr(this.fields.city.attr, "address-city")}
                onChange={_.bind(this.onChange, this, this.fields.city.attr)}
                onBlur={_.bind(this.onBlur, this, this.fields.city.attr)}
                didMount={this.register} willUnmount={this.unregister} customValidator={this.props.cityCustomValidator}/>
            </div>
            <div className="flex-static">
              <ObsText
                value={valueFor(this.fields.state.attr)} errors={[]}
                required={this.props.required} formatter={Formatters.stateFormatter}
                placeholder={"ST"}
                className={this.classesForAttr(this.fields.state.attr, "address-state state")}
                onChange={_.bind(this.onChange, this, this.fields.state.attr)}
                onBlur={_.bind(this.onBlur, this, this.fields.state.attr)}
                didMount={this.register} willUnmount={this.unregister} customValidator={this.props.stateCustomValidator}/>
            </div>
            <div className="flex-static">
              <ObsText
                value={valueFor(this.fields.zip.attr)} errors={[]}
                required={this.props.required} formatter={Formatters.zipcodeFormatter}
                placeholder={"Zip"}
                className={this.classesForAttr(this.fields.zip.attr, "address-zipcode zipcode")}
                onChange={_.bind(this.onChange, this, this.fields.zip.attr)}
                onBlur={_.bind(this.onBlur, this, this.fields.zip.attr)}
                didMount={this.register} willUnmount={this.unregister} customValidator={this.props.zipCustomValidator}/>
            </div>
          </ObsCompoundLayout>
        </ObsCompoundLayout>
        <ObsError errors={this.errorsWithLabelNames()} />
      </div>
    )
  }
Example #30
0
Outgoing.prototype.reqMktData = function (tickerId, contract, genericTickList, snapshot) {
  if (this._controller._serverVersion < C.MIN_SERVER_VER.SNAPSHOT_MKT_DATA && snapshot) {
    return this._controller.emitError('It does not support snapshot market data requests.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.UNDER_COMP) {
    return this._controller.emitError('It does not support delta-neutral orders.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.REQ_MKT_DATA_CONID) {
    return this._controller.emitError('It does not support conId parameter.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRADING_CLASS) {
    if (!_.isEmpty(contract.tradingClass)) {
      return this._controller.emitError('It does not support tradingClass parameter in reqMarketData.');
    }
  }

  var version = 10;

  var args = [C.OUTGOING.REQ_MKT_DATA, version, tickerId];

  // send contract fields
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.REQ_MKT_DATA_CONID) {
    args.push(contract.conId);
  }
  args.push(contract.symbol);
  args.push(contract.secType);
  args.push(contract.expiry);
  args.push(contract.strike);
  args.push(contract.right);

  if (this._controller._serverVersion >= 15) {
    args.push(contract.multiplier);
  }

  args.push(contract.exchange);

  if (this._controller._serverVersion >= 14) {
    args.push(contract.primaryExch);
  }

  args.push(contract.currency);

  if (this._controller._serverVersion >= 2) {
    args.push(contract.localSymbol);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.tradingClass);
  }

  if (this._controller._serverVersion >= 8 &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(contract.comboLegs)) {
      args.push(0);
    } else {
      args.push(contract.comboLegs.length);
      contract.comboLegs.forEach(function (comboLeg) {
        args.push(comboLeg.conId);
        args.push(comboLeg.ratio);
        args.push(comboLeg.action);
        args.push(comboLeg.exchange);
      });
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.UNDER_COMP) {
    if (_.isPlainObject(contract.underComp)) {
      args.push(true);
      args.push(contract.underComp.conId);
      args.push(contract.underComp.delta);
      args.push(contract.underComp.price);
    } else {
      args.push(false);
    }
  }

  if (this._controller._serverVersion >= 31) {
    /*
     * Note: Even though SHORTABLE tick type supported only
     *       starting server version 33 it would be relatively
     *       expensive to expose this restriction here.
     *
     *       Therefore we are relying on TWS doing validation.
     */
    args.push(genericTickList);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SNAPSHOT_MKT_DATA) {
    args.push(snapshot);
  }

  this._send(args);
};