Beispiel #1
0
 {this.props.metadata.faqs.map(({question, answer}) =>
   <div key={hash(question)} className="accordion-group panel">
     <div className="accordion-heading accordionize"> <a className="accordion-toggle active" data-toggle="collapse" data-parent="#accordionArea" href={`#${hash(question)}`}>{question}<i className="fa fa-angle-down" /> </a> </div>
     <div id={hash(question)} className="accordion-body in collapse">
       <div className="accordion-inner">{answer}</div>
     </div>
   </div>
Beispiel #2
0
	preOmitFunc: function(payload) {
		console.log('pre');
		if (cache[hash(payload)]) {
			console.log('cached');
			// console.log(cache[hash(payload)]);
			return cache[hash(payload)];
		}
	},
 hashValue(value: any): string {
   if (!value) return value;
   const type = typeof value;
   switch (type) {
     case 'object':
       if (Array.isArray(value)) return value.map(v => hash(v));
       return hash(value);
     default:
       return hash(value);
   }
 }
Beispiel #4
0
export const getCommits = options => {

    const key = hash(options);

    return new Promise((resolve, reject) => {

        redis.get(key, (error, response) => {

            if (response) {
                return void resolve(JSON.parse(response));
            }

            github.repos.getCommits(options, (error, response) => {

                redis.set(key, JSON.stringify(response));
                redis.expire(key, config.cacheExpiration);

                if (error) {
                    const response = JSON.parse(error.message);
                    const prettyError = new PrettyError();
                    console.log(prettyError.render(new Error(response.message)));
                    reject();
                    return;
                }

                resolve(response);

            });

        });

    });

};
function getHash(collectionName, paths, vals) {
  var queryObject = { collection: collectionName };
  _.times(paths.length, function(i) {
    queryObject['vals.' + paths[i]] = vals[i];
  });
  return hash(queryObject);
}
Beispiel #6
0
  self.ensureTemplateExists = (client, name, template) => {
    const toHash = {
      name:     name,
      template: template
    };

    const templateKey = hash(toHash);

    if (templatesFound[templateKey]) {
      log.debug(`template '${name}' previously found`);
      return Promise.resolve('previously found');
    }

    return client.indices.existsTemplate({name: name}).then((response) => {
      if (!response) {
        log.info(`template '${name}' does not exist. creating ..`);

        return client.indices.putTemplate({
          name: name,
          body: template
        }).then(() => {
          log.info(`template '${name}' successfully created`);
          templatesFound[templateKey] = true;
          return Promise.resolve('created');
        });
      }

      log.debug(`template '${name}' exists`);
      return Promise.resolve('exists');
    });
  };
  _.each(optionList, function (option) {
    var optionKey = option
    var fieldOptions = {}

    // if option is an object, set the key and set the field options
    if (_.isObject(option)) {
      optionKey = option.key
      fieldOptions = option
      delete fieldOptions.key
    }

    // hash the field options and use as value field key
    var fieldHash = 'value' + type + '_' + hash(fieldOptions)

    // push option key to all options array
    allOptions.push({ value: optionKey, label: optionKey })

    // add option key to field map, mapping field to value field
    fieldMap[optionKey] = fieldHash

    // if field doesn't already exist in all fields array, create it, adding custom options
    if (!allFields[fieldHash])
      allFields[fieldHash] = _.extend({ type: Types[type], label: 'Value', dependsOn: {key: []} }, fieldOptions)

    // push the field to the value field dependencies
    allFields[fieldHash].dependsOn.key.push(optionKey)
  })
Beispiel #8
0
 hashNode(node) {
   const _node = clone(node)
   _node.id = undefined
   _node.namespace = undefined
   _node.parent = undefined
   return objectHash(_node)
 }
Beispiel #9
0
export async function createProductHash(product, collections) {
  const variants = await collections.Products.find({ ancestors: product._id, type: "variant" }).toArray();

  const productForHashing = {};
  productFieldsThatNeedPublishing.forEach((field) => {
    productForHashing[field] = product[field];
  });
  customPublishedProductFields.forEach((field) => {
    productForHashing[field] = product[field];
  });

  // Track changes to all related media, too
  productForHashing.media = await getCatalogProductMedia(product._id, collections);

  // Track changes to all variants, too
  productForHashing.variants = variants.map((variant) => {
    const variantForHashing = {};
    variantFieldsThatNeedPublishing.forEach((field) => {
      variantForHashing[field] = variant[field];
    });
    customPublishedProductVariantFields.forEach((field) => {
      variantForHashing[field] = variant[field];
    });
    return variantForHashing;
  });

  return hash(productForHashing);
}
Beispiel #10
0
function compareHashObject({
    obj,
    clone
}) {
    // equal
    const hash1 = hashObj(JSON.stringify(obj));
    const hash2 = hashObj(JSON.stringify(clone));
    assert.equal(hash1, hash2);

    // not equal
    const hash3 = hashObj(JSON.stringify(obj));
    const hash4 = hashObj(JSON.stringify(checkObj));
    assert.notEqual(hash3, hash4);

    return;
}
Beispiel #11
0
ReverseProxy.buildRoute = function (route) {
  if (!_.isString(route) && !_.isObject(route)) {
    return null;
  }

  if (_.isObject(route) && route.hasOwnProperty('urls') && route.hasOwnProperty('path')) {
    // default route type matched.
    return route;
  }

  var cacheKey = _.isString(route) ? route : hash(route);
  var entry = routeCache.get(cacheKey);
  if (entry) {
    return entry;
  }

  var routeObject = { rr: 0, isResolved: true };
  if (_.isString(route)) {
    routeObject.urls = [ReverseProxy.buildTarget(route)];
    routeObject.path = '/';
  } else {
    if (!route.hasOwnProperty('url')) {
      return null;
    }

    routeObject.urls = (_.isArray(route.url) ? route.url : [route.url]).map(function (url) {
      return ReverseProxy.buildTarget(url, route.opts || {});
    });

    routeObject.path = route.path || '/';
  }
  routeCache.set(cacheKey, routeObject);
  return routeObject;
};
Beispiel #12
0
Queue.prototype.getKeyFromArgs = function Queue$getKeyByArgs (input) {
  return hashing(input, {
    unorderedArrays: true,
    //algorithm: 'md5',
    encoding: 'base64'
  });
};
Beispiel #13
0
  self.ensureIndexExists = (client, index) => {
    const toHash = {
      index: index
    };

    const aliasKey = hash(toHash);

    if (indicesFound[aliasKey]) {
      log.debug(`index '${index}' previously found`);
      return Promise.resolve('previously found');
    }

    return client.indices.exists({index: index}).then((response) => {
      if (!response) {
        log.info(`index '${index}' does not exist. creating ..`);

        return client.indices.create({index: index}).then(() => {
          log.info(`index '${index}' successfully created`);
          indicesFound[aliasKey] = true;
          return Promise.resolve('created');
        });
      }

      log.debug(`index '${index}' exists`);
      return Promise.resolve('exists');
    });
  };
Beispiel #14
0
var hashNode = function (n) {
  var node = clone(n);
  node.id = undefined;
  node.namespace = undefined;
  node.parent = undefined;
  return objectHash(node);
};
Beispiel #15
0
  self.ensureAliasExists = (client, alias, index) => {
    const toHash = {
      alias: alias,
      index: index
    };

    const aliasKey = hash(toHash);

    if (aliasesFound[aliasKey]) {
      log.debug(`alias '${alias}' previously found`);
      return Promise.resolve('previously found');
    }

    return client.indices.existsAlias({
      name:  alias,
      index: index
    }).then((response) => {
      if (!response) {
        log.info(`alias '${alias}' does not exist. creating ..`);

        return client.indices.putAlias({
          name:  alias,
          index: index
        }).then(() => {
          log.info(`alias '${alias}' successfully created`);
          aliasesFound[aliasKey] = true;
          return Promise.resolve('created');
        });
      }

      log.debug(`alias '${alias}' exists`);
      return Promise.resolve('exists');
    });
  };
Beispiel #16
0
    _buildLib(){
        const libsObj = this.libsObj
        if(!libsObj){
            return;
        }

        const vals = Object.keys(libsObj).map(function (key) {
            return libsObj[key];
        });
        var result = UglifyJS.minify(vals,this.options.uglify_lib_options)

        var libDistPath = this._replaceHolder('[dist_path]/[project_name]/')

        mkdirp.sync(libDistPath);

        fs.writeFileSync(libDistPath+'lib.js',result.code);

        const libHash = objHash(this.libsObj);

        const options = this.options;

        this.libAssets = {
            'lib':{
                js:`${options.cdn_path}/${options.project_name}/lib.js?v=${libHash}`
            }
        }
    }
Beispiel #17
0
 indexDocs = function (i) {
   if (i < batch.length) {
     //verify document format
     if (Object.prototype.toString.call(batch[i]) != '[object Object]') {
       searchIndexLogger.error('malformed document: check document formatting at batch index ' + i);
       return callback(true);
     }
     var docID = '';
     if (batch[i]['id'])
       docID = batch[i]['id'];
     else
       docID = Date.now() + '-' + Math.random()*10000000000000000 + '-' + hash(batch[i]);
     deleter.deleteDoc(docID, indexes, indexesMultiply, function(msgg) {
       indexDoc(indexes, docID, batch[i], filters, function(msg) {
         searchIndexLogger.info(msg.status);
         tf[docID] = msg.tfValues;
         indexDocs(++i);
       });
     });
   }
   else {
     searchIndexLogger.info('starting calibration');
     calibrater.incrementallyCalibrate(indexesMultiply, reduceTF(tf), function(msg) {
       searchIndexLogger.info(msg);
       searchIndexLogger.info('indexed batch: ' + batchName);
       callback(false);
     });
   }
 };
Beispiel #18
0
export function mangle (node) {
  if (node.settings && node.settings.isGeneric) {
    return hash(_.merge({}, node.inputPorts, node.outputPorts))
  } else {
    return ''
  }
}
Beispiel #19
0
export function typeName (type) {
  if (typeof (type) === 'object') {
    return 'type_' + hash(type)
  } else {
    return type
  }
}
export function *ensureEntityIndexTask(action) {
	const { collectionName, filter } = action.payload;
	const indexHash = hash({ collectionName, filter });
	const apiContext = yield select(getApiContext);
	const ApiService = yield select(getApiService);
	const authContext = yield select(getAuthContext);
	// const { collectionName, filter } = yield select(getEntityIndexSelector(indexHash));
	yield put(attemptFetchEntityIndex(indexHash));
	try {
		const normalizedFilter = normalizeFilter(filter);
		const result = yield call(
			ApiService.getEntityIndex,
			collectionName,
			normalizedFilter,
			apiContext,
			authContext
		);
		apiServiceResultTypeInvariant(result, EntityIndexResult);
		const entitySchemas = yield select(getEntitySchemas);
		const normalized = normalize(result.data, collectionName, entitySchemas);
		const nowTime = moment().format();
		yield put(receiveEntities(normalized.entities, nowTime));
		yield put(receiveEntityIndex(indexHash, normalized.result, result.existingCount, nowTime));
	} catch (e) {
		apiServiceResultTypeInvariant(e, Error);
		yield put(fetchEntityIndexFailure(indexHash, e));
	}
}
Beispiel #21
0
ListItem.prototype.getHash = function () {
    var self = this;
    var objectToHash = {};
    _.map(this.valuesToHash, function (value) {
        objectToHash[value] = self.values[value];
    });
    return hash(this.values);
}
  fn: function(inputs, exits) {

    var hashFn = require('object-hash');

    var hash = hashFn(inputs.dictionary);
    return exits.success(hash);

  },
Beispiel #23
0
const hash = value =>
	objectHash(
		value,
		{
			algorithm: 'md5',
			unorderedObjects: true
		}
	);
Beispiel #24
0
 saveAction(action) {
     const streamId = action.reduxLive.streamId;
     const streamIdKey = hash(streamId);
     this._actions[streamIdKey][action.reduxLive.sequenceNumber] = action;
     this._eventEmitter.emit(NEW_ACTION_EVENT + streamIdKey, action);
     this._eventEmitter.emit(NEW_ACTION_EVENT, action);
     return Promise.resolve();
 }
Beispiel #25
0
    async getSnapshot(streamId) {
        const snapshotKey = hash(streamId);
        const snapshots = await this.snapshotCollection.find({_id: snapshotKey}).toArray();
        if (snapshots.length === 0) {
            throw new Error(util.format('No state for stream ID %j', streamId));
        }

        return censorDocument(snapshots[0])
    }
Beispiel #26
0
    getSnapshot(streamId) {
        const streamIdKey = hash(streamId);
        const snapshot = this._snapshots[streamIdKey];
        if (!snapshot) {
            return Promise.reject(`No state for stream ID ${streamId}`);
        }

        return Promise.resolve(snapshot);
    }
Beispiel #27
0
const hash = ctx => {
  const {
    headers: { 'user-agent': userAgent },
    url,
  } = ctx.request

  // Hash the storage key by the url, and the userAgent
  return objectHash({ url, userAgent })
}
Beispiel #28
0
	getStateHash(state) {
		return objectHash(
			state,
			{
				algorithm: 'md5',
				unorderedObjects: true
			}
		);
	}
Beispiel #29
0
    async saveSnapshot(snapshot) {
        const {streamId, sequenceNumber} = snapshot.reduxLive;

        const snapshotKey = hash(streamId);
        var snapshotToSave = {...snapshot, _id: snapshotKey};
        await this.snapshotCollection.updateOne(
            {_id: snapshotKey, 'reduxLive.sequenceNumber': sequenceNumber - 1},
            snapshotToSave);
    }
Beispiel #30
0
/**
 * @private emitResponse
 *
 * sends data back to the client through socket
 *
 * @param  {object} resource that was requested
 * @param  {error|null} error
 * @param  {object} response
 * @param  {string} body
 */
function emitResponse (resource, error, response, body) {
  var timeDiff = Date.now()  - resource.startTs;
  var responseHash;

  if(error) {
    log.debug('[ERROR]: (id: ' + resource.id + ', url: ' + resource.url + ')');
    log.trace('[ERROR]: (id: ' + resource.id + ', url: ' + resource.url + ') body : (' + error.toString() + ')');

    if (this.polledResources[resource.id]) {
      responseHash = hash(error || {});
      if (this.polledResources[resource.id].response === responseHash.toString()) {
        return;
      } else {
        this.polledResources[resource.id].response = responseHash.toString();
      }
    }

    this.connection.write(JSON.stringify({
      resource: resource,
      error: error,
      warning: error.toString()
    }, stripResource));

  } else {
    log.debug('[SUCCESS]: (id: ' + resource.id + ', url: ' + resource.url + ')');
    log.trace('[' + timeDiff + 'ms] Success (' + resource.id + ',' + resource.url + ') body : (' + JSON.stringify(body) + ')');

    if (this.polledResources[resource.id]) {
      responseHash = hash(body || {});
      if (this.polledResources[resource.id].response === responseHash.toString()){
        // No need to send this to the client as nothing changed.
        return;
      } else {
        this.polledResources[resource.id].response = responseHash;
      }
    }
    log.debug('[RESPONSE]: (id: ' + resource.id + ', url: ' + resource.url + ')' );
    this.connection.write(JSON.stringify({
      resource: resource,
      statusCode: response.statusCode,
      response: body
    }, stripResource));
  }
}