Пример #1
0
function common(facade, settings){
  var cid = hash(facade.userId() || facade.anonymousId());
  var campaign = facade.proxy('context.campaign') || {};
  var options = facade.options('Google Analytics');
  var app = facade.proxy('context.app') || {};
  var tid = settings.serversideTrackingId;
  var traits = facade.traits();

  if (options && is.string(options.clientId)) cid = options.clientId;

  var form = metrics(traits, settings);
  form.cid = cid;
  form.tid = tid;
  form.v = 1;

  // campaign
  if (campaign.name) form.cn = fmt('(%s)', campaign.name);
  if (campaign.source) form.cs = fmt('(%s)', campaign.source);
  if (campaign.medium) form.cm = campaign.medium;
  if (campaign.content) form.cc = campaign.content;

  // app
  if (app.name) form.an = app.name;
  if (app.version) form.av = app.version;

  if (settings.sendUserId && facade.userId()) form.uid = facade.userId();
  if (facade.userAgent()) form.ua = facade.userAgent();
  if (facade.ip()) form.uip = facade.ip();

  return form;
}
Пример #2
0
function formatCompany (company) {
  if (is.string(company)) company = { name : company };
  if (company.created) company.created_at = unixTime(company.created);
  if (!company.id && !company.name) return company;
  company.id = company.id || hash(company.name);
  return company;
}
Пример #3
0
exports.genHash = function(string) {
	//console.warn("GENHASH: ", string);
	// TODO: hash function here
	string = hash(string);

	return string;
}
Пример #4
0
export function stringToColor(string, colorConstraints){
    const config = configManager.getConfig();
    let mode = config.CDCMode;
    let CDC = config.CDCRange;
    const c1 = colorConstraints[0];
    const c2 = colorConstraints[1];
    const alpha = colorConstraints[2];
    if(colorConstraints[3] !== undefined){
        if(typeof colorConstraints[3] === "string"){
            mode = colorConstraints[3];
        }
        else{
            CDC = colorConstraints[3];
        }
    }
    if(colorConstraints[4] !== undefined){
        CDC = colorConstraints[4];
    }
    const CDCRange = CDC[1] - CDC[0];
    const CDCStart = CDC[0];
    const d = Math.round(stringHash(string) % CDCRange) + CDCStart;
    let color;
    if(mode === "hue"){
        color = colorSpace.hsl.rgb([d, c1, c2]).map(num => parseInt(num));
    }
    else if(mode === "saturation"){
        color = colorSpace.hsl.rgb([c1, d, c2]).map(num => parseInt(num));
    }
    else if(mode === "lightness"){
        color = colorSpace.hsl.rgb([c1, c2, d]).map(num => parseInt(num));
    }
    color.push(alpha);
    return "rgba(" + color.join(",") + ")";
}
Пример #5
0
  isItemValid(code, hash) {
    if (typeof code !== 'string') { return false; }

    return (
      stringHash(code) === hash
    );
  }
Пример #6
0
/*
  Custom `generateScopedName` function for `postcss-modules-scope`.
  Short names consisting of source hash and line number.
*/
function generateShortName (name, filename, css) {
  // first occurrence of the name
  // TODO: better match with regex
  var i = css.indexOf('.' + name);
  var numLines = css.substr(0, i).split(/[\r\n]/).length;

  var hash = stringHash(css).toString(36).substr(0, 5);
  return '_' + name + '_' + hash + '_' + numLines;
}
Пример #7
0
function formatCompany (company) {
  if (is.string(company)) company = { name : company };
  var created = dot(company, 'created') || dot(company, 'createdAt');
  if (created) company.created_at = time(created);
  if (!company.id && !company.name) return company;
  company.id = company.id || hash(company.name);
  dot.del(company, 'created');
  delete company.createdAt;
  return company;
}
Object.keys(expressions).sort().forEach(function(expression) {
    var minified = expression.replace(/\s+/g, "");
    var expansion = expand(expression);

    result[minified] = {
        source: expression,
        expansion: expansion,
        hash: stringHash(minified),
        ast: parse(expansion)
    };
});
StorageHandler.prototype.getSummoner = function(summName, region) {
  var self = this;
  var saveName = hash(region + "-" + summName);
  return new Promise(function(resolve, reject){
    self.storage.getAsync("summ:"+saveName).then(function(data){
      resolve(JSON.parse(data));
    }).catch(function(err){
      reject(err);
    });
  });
}
function getOrGenerateDevId(facade, payload) {
  var devId = facade.proxy('context.device.id');

  if (devId && devId.length > 0) {
    return devId;
  }

  var phone = facade.proxy('traits.phone') || facade.proxy('context.traits.phone');
  if (facade.userId()) {
    devId = "nodev-segment-user-id-" + hash(facade.userId());
  } else if (facade.username()) {
    devId = "nodev-segment-" + hash(facade.username());
  } else if (facade.email()) {
    devId = "nodev-segment-" + hash(facade.email());
  } else if (phone) {
    devId = "nodev-segment-" + hash(phone);
  }

  return devId;
}
 return guests.map(guest => GuestUsers.upsert({
   meetingId,
   intId: guest.intId,
 }, {
   approved: false,
   denied: false,
   ...guest,
   meetingId,
   loginTime: new Date().getTime(),
   color: COLOR_LIST[stringHash(guest.intId) % COLOR_LIST.length],
 }, cb));
Пример #12
0
 getVendorsBundleName: function (packages) {
   if (!packages || Object.keys(packages).length === 0) {
     return null;
   }
   var packagesList = Object.keys(packages).map(function (key) {
     return key + ':' + packages[key];
   }).sort(function (a, b) {
     if (a < b) return -1;
     if (a > b) return 1;
     return 0;
   });
   return String(hash(JSON.stringify(packagesList)));
 },
Пример #13
0
			return Promise.all(imports).then(function () {
				if (fromPath && cache) {
					cache[fromPath] = cache[fromPath] || {};

					cache[fromPath].mtime = getModified(fromPath);

					if (imports.length) {
						var output        = css.toResult().css;
						var cacheFilename = path.resolve(opts.cachedir, hash(output) + '.css');

						cache[fromPath].cache = cacheFilename;

						return fs.writeFile(cacheFilename, output);
					}
				}
			});
Пример #14
0
/**
 * Builds a cookie for segment.io using a combination of:
 *
 * http://www.tutkiun.com/2011/04/a-google-analytics-cookie-explained.html
 * http://www.vdgraaf.info/wp-content/uploads/image-url-explained.txt
 * https://github.com/jgallen23/node-ga
 */
function buildCookie (message, settings) {

  /**
   * UTMA: Cookie indicating visitor information
   *
   * ex. 1.579990553.1301242771.1302852082.1302867721.40
   *
   * 1         : Domain hash, unique for each domain, can be set to '1'
   * 579990553 : Unique identifier for the user
   * 1301242771: Timestamp of time you first visited the site
   * 1302852082: Timestamp for the previous visit
   * 1302867721: Timestamp for the current visit
   * 40        : Number of sessions started
   */

  var domainHash = 1
    , userId     = hash(message.userId() || message.sessionId())
    , visits     = 1
    , now        = unixTime(new Date());

  var utma = [domainHash, userId, now, now, now, visits].join('.');

  /*
   * UTMZ: Traffic Sources cookie
   *
   * ex. 126210440.1302625640.30.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=page%20load%20javascript
   *
   * 126210440 :  Domain Hash
   * 1302625640 :   Timestamp when cookie was set
   * 30 : Session number
   * 3 : Campaign number
   * utmcsr=google : Campaign source
   * utmccn=(organic):  Campaign name
   * utmcmd=organic :  Campaign medium [Organic, referral, cpc and email]
   * utmctr=page%20load%20javascript : last keyword used to enter in site.
   */

  var utmz = [
    domainHash,
    now,
    1,
    1,
    'utmcsr=(none)|utmccn=(none)|utmcmd=(none)|utmcr=(none)'
  ].join('.');

  return util.format('__utma=%s; __utmz=%s;', utma, utmz);
}
Пример #15
0
GA.prototype._common = function(track, settings){
  var cid = hash(track.userId() || track.sessionId());
  var options = track.options(this.name);
  var tid = settings.serversideTrackingId;

  if (options && is.string(options.clientId)) {
    cid = options.clientId;
  }

  var form = {
    v: 1,
    cid: cid,
    tid: tid
  };

  if (track.ip()) form.uip = track.ip();
  if (track.userAgent()) form.ua = track.userAgent();
  return form;
}
Пример #16
0
/**
 * insert imported content at the right place
 *
 * @param {Object} atRule
 * @param {Object} parsedAtImport
 * @param {Object} options
 * @param {String} resolvedFilename
 * @param {Function} cb
 */
function readImportedContent(atRule, parsedAtImport, options, resolvedFilename, cb, importedFiles, ignoredAtRules, media, hashFiles) {
  // add directory containing the @imported file in the paths
  // to allow local import from this file
  var dirname = path.dirname(resolvedFilename)
  if (options.path.indexOf(dirname) === -1) {
    options.path = options.path.slice()
    options.path.unshift(dirname)
  }

  options.from = resolvedFilename
  var fileContent = readFile(resolvedFilename, options.encoding, options.transform || function(value) { return value })

  if (fileContent.trim() === "") {
    console.log(helpers.message(resolvedFilename + " is empty", atRule.source))
    detach(atRule)
    return
  }

  // skip files wich only contain @import rules
  var newFileContent = fileContent.replace(/@import (.*);/,"")
  if (newFileContent.trim() !== "") {
    var fileContentHash = hash(fileContent)

    // skip files already imported at the same scope and same hash
    if (hashFiles[fileContentHash] && hashFiles[fileContentHash][media]) {
      detach(atRule)
      return
    }

    // save hash files to skip them next time
    if (!hashFiles[fileContentHash]) {
      hashFiles[fileContentHash] = {}
    }
    hashFiles[fileContentHash][media] = true
  }

  var newStyles = postcss.parse(fileContent, options)

  // recursion: import @import from imported file
  parseStyles(newStyles, options, cb, importedFiles, ignoredAtRules, parsedAtImport.media, hashFiles)

  cb(atRule, parsedAtImport, newStyles, resolvedFilename)
}
Пример #17
0
exports.findByHashtag = function(hashtag, offset, count, userId, channel) {
  var deferred = Q.defer();
  var score = stringHash(hashtag);
  var default_offset = 0;
  var default_count = 10;

  offset = (offset === undefined) ? default_offset : offset;
  count = (count === undefined) ? default_count : count;

  var tweetHashChannel = config.store.tweetHash + ':' + channel;
  var hashtagZsetChannel = config.store.hashtagZset + ':' + channel;
  var args1 = [ hashtagZsetChannel, score, score, 'LIMIT', offset, count ];

  redis.zrangebyscore(args1, function (err, response) {
    var result = [];
    if(err) {
      deferred.reject(err);
    } else {
      if (response.length === 0) {
        // No result
        deferred.resolve([]);
      } else {
        //console.log('Result', response);
        async.forEach(response, function (tweetId, callback) {
          redis.hget(tweetHashChannel, tweetId, function (err, reply) {
            // console.log(">>",reply);
            result.push({ id: tweetId, content: reply});
            callback();
          });
        }, function (err) {
          if(err) {
            deferred.reject(err);
            return;
          }
          deferred.resolve(result);
        });
      }
    }
  });

  return deferred.promise;
};
Пример #18
0
 getChalkFuncByHash: function(id) {
   var stringHash = require('string-hash');
   var hash_number_id = stringHash(id);
   return this.getNextChalkFunc(hash_number_id);
 },
Пример #19
0
export default function addUser(meetingId, user) {
  check(meetingId, String);

  check(user, {
    intId: String,
    extId: String,
    name: String,
    role: String,
    guest: Boolean,
    authed: Boolean,
    waitingForAcceptance: Match.Maybe(Boolean),
    guestStatus: String,
    emoji: String,
    presenter: Boolean,
    locked: Boolean,
    avatar: String,
    clientType: String,
  });

  const userId = user.intId;
  check(userId, String);

  const selector = {
    meetingId,
    userId,
  };

  const USER_CONFIG = Meteor.settings.public.user;
  const ROLE_PRESENTER = USER_CONFIG.role_presenter;
  const ROLE_MODERATOR = USER_CONFIG.role_moderator;
  const ROLE_VIEWER = USER_CONFIG.role_viewer;
  const APP_CONFIG = Meteor.settings.public.app;
  const ALLOW_HTML5_MODERATOR = APP_CONFIG.allowHTML5Moderator;

  const Meeting = Meetings.findOne({ meetingId });
  // override moderator status of html5 client users, depending on a system flag
  const dummyUser = Users.findOne(selector);
  let userRole = user.role;

  if (
    dummyUser
    && dummyUser.clientType === 'HTML5'
    && userRole === ROLE_MODERATOR
    && !ALLOW_HTML5_MODERATOR
  ) {
    userRole = ROLE_VIEWER;
  }

  /* While the akka-apps dont generate a color we just pick one
    from a list based on the userId */
  const color = COLOR_LIST[stringHash(user.intId) % COLOR_LIST.length];

  const modifier = {
    $set: Object.assign(
      {
        meetingId,
        connectionStatus: 'online',
        roles: [ROLE_VIEWER.toLowerCase()],
        sortName: user.name.trim().toLowerCase(),
        color,
        breakoutProps: {
          isBreakoutUser: Meeting.meetingProp.isBreakout,
          parentId: Meeting.breakoutProps.parentId,
        },
        effectiveConnectionType: null,
        inactivityCheck: false,
        responseDelay: 0,
        loggedOut: false,
      },
      flat(user),
    ),
  };

  // Only add an empty VoiceUser if there isn't one already. We want to avoid overwriting good data
  if (!VoiceUsers.findOne({ meetingId, intId: userId })) {
    addVoiceUser(meetingId, {
      voiceUserId: '',
      intId: userId,
      callerName: user.name,
      callerNum: '',
      muted: false,
      talking: false,
      callingWith: '',
      listenOnly: false,
      voiceConf: '',
      joined: false,
    });
  }

  const cb = (err, numChanged) => {
    if (err) {
      return Logger.error(`Adding user to collection: ${err}`);
    }

    if (user.presenter) {
      changeRole(ROLE_PRESENTER, true, userId, meetingId);
    }

    if (userRole === ROLE_MODERATOR) {
      changeRole(ROLE_MODERATOR, true, userId, meetingId);
    }

    const { insertedId } = numChanged;
    if (insertedId) {
      return Logger.info(`Added user id=${userId} meeting=${meetingId}`);
    }

    return Logger.info(`Upserted user id=${userId} meeting=${meetingId}`);
  };

  return Users.upsert(selector, modifier, cb);
}
Пример #20
0
function process_args () {

  args.pwd ? println('dir:', cwd) : null;

  if (ARGS_DEBUG)
    console.log('args:', args)
  // help requested
  if (args.help) {
    println()
    println('To set an iTerm2 tab\'s color, badge, or title:')
    println()
    println('tabset --all|-a <string>')
    println('       --color|-c <named-color>')
    println('                  | <rgb()>')
    println('                  | <hex-color>')
    println('                  | random')
    println('                  | RANDOM')
    println('       --pick|-p')
    println('       --hash|-h <string>')
    println('       --badge|-b <string>')
    println('       --title|-t <string>')
    println('       --pwd')
    println('       --mode  0 | 1 | 2')
    println('       --init')
    println('       --add <name> <colorspec>')
    println('       --add <name> --pick|-p')
    println('       --del <name>')
    println('       --list')
    println('       --colors')
    println('       --help')
    println('       --verbose|-V')
    println()
  }


  const nFreeArgs = _.size(args._)
  // no real args given, so improvise
  var noSpecificArgs = (_.size(args) === (argopt['boolean'].length + 1 + 1));
      // always expect _ and booleans (e.g. pwd and verbose)
      // they do not count at "specific" arguments
  dprintln('noSpecificArgs:', jsonify(noSpecificArgs))
  if (!nFreeArgs && noSpecificArgs) {
    args.all = settingString(null, 'all')
    if (!args.all) {
      args.all = cwd
    }
    dprintln('set args.all to', args.all)
  }

  if (args.colors) {
    var colorNames = _.keys(colors).sort()
    println(wrap('named colors: ' + colorNames.join(', ')))
  }

  // combo set everthing
  if (nFreeArgs === 1) {
    args.all = settingString(args._[0], 'all')
  } else if (nFreeArgs > 1) {
    args.all = args._.join(' ')
  }
  if (ARGS_DEBUG) {
    console.log('nFreeArgs:', nFreeArgs)
    console.log('setting args.all to:' , args.all)
  }

  if (args.all) {
    setBadge(args.all)
    setTabTitle(args.all, definedOr(args.mode, 1))
    var col = decodeColorSpec(args.all)
    if (!col) {
      var colorNames = _.keys(colors).sort()
      var index = stringHash(args.all) % colorNames.length
      var hashColor = colorNames[index]
      col = colors[hashColor]
    }
    showChoice('picked color:', hashColor)
    setTabColor(col, definedOr(args.mode, 1))
  }

  if (args.badge) {
    var badge = settingString(args.badge, 'badge')
    setBadge(badge)
  }

  if (args.title) {
    var title = settingString(args.title, 'title')
    setTabTitle(title, definedOr(args.mode, 1))
  }

  if (args.hash && !args.color) {
    args.color = true
  }

  if (args.add) {
    if (!_.isString(args.add)) {
      errorExit('must give name to add')
    }
    if (args.pick) {
      colorpick({ targetApp: 'iTerm2'},
                function (res) {
                  addColor(args.add, rgbstr(res.rgb))
                  println('added:', args.add)
                })
    } else if (_.size(args._) === 1) {
      addColor(args.add, args._[0])
      println('added:', args.add)
    } else {
      errorExit('add what color?')
    }
  } else if (args.pick) {
    colorpick({ targetApp: 'iTerm2'},
              function (res) {
                println('picked:', rgbstr(res.rgb))
                setTabColor(res.rgb)
              })
  }

  if (args.del) {
    if (!_.isString(args.del)) {
      errorExit('must give name to delete')
    }
    delColor(args.del)
    println('deleted:', args.del)
  }

  if (args.list) {
    listColors()
  }

  if (args.color) {
    setTabColor(decodeColor(args.color))
  }

  if (args.init) {
    initConfigFile()
  }
}
Пример #21
0
/**
 * A high-level color decoder that handles the complex,
 * UI-entangled cases such as random colors, hashed colors,
 * partial string search, and defaults. By delegation to
 * decodeColorSpec(), also handles the simpler cases of
 * exactly named colors and rgb() or hex CSS color definitions.
 */
function decodeColor (name) {
  if (_.isArray(name)) {  // predecoded!
    return name
  }
  if (name === null) {    // not in use
    return name
  }

  var colorNames = _.keys(colors).sort()

  if (!_.isString(name)) {
    // --color invoked, but no color specified

    // might be a hashed color request
    if (args.hash) {
      var index = stringHash(args.hash) % colorNames.length
      var hashColor = colorNames[index]
      showChoice('hashed color:', hashColor)
      return colors[hashColor]
    }

    // nope, no hash; so pick something at random
    name = 'random'
  }

  // random named color
  if (name === 'random') {
    var randColor = _.sample(colorNames)
    showChoice('random color:', randColor)
    return colors[randColor]
  }

  // RANDOM color - not just a random named color
  if (name === 'RANDOM') {
    var rcolor = [_.random(255), _.random(255), _.random(255) ]
    showChoice('RANDOM color:', rgbstr(rcolor))
    return rcolor
  }

  // try a low level spec
  name = name.toLowerCase()
  var defn = decodeColorSpec(name)
  if (defn) {
    return defn
  }

  // finally, a string containment search
  if (colorNames) {
    var possibles = colorNames.filter(s => {
      return s.indexOf(name) >= 0
    })
    if (possibles.length === 1) {
      showChoice('guessing:', possibles[0])
      return colors[possibles[0]]
    }  else if (possibles.length > 1) {
      println(wrap('possibly: ' + possibles.join(', ')))
      var rcolor = _.sample(possibles)
      showChoice('randomly picked:', rcolor)
      return colors[rcolor]
    }
  }

  // nothing worked, use default color
  showChoice('using default:', defaultColorSpec)
  println('because no color', jsonify(name), 'known')
  println('use --colors option to list color names')
  return colors['default']
}
StorageHandler.prototype.addSummoner = function(summName, region, data) {
  var saveName = hash(region + "-" + summName);
  this.storage.set("summ:"+saveName, JSON.stringify(data));
}
StorageHandler.prototype.addTeam = function(teamName, region, data) {
  var saveName = hash(region + "-" + teamName);
  this.storage.set("team:"+saveName, JSON.stringify(data));
}
Пример #24
0
 getVendorsBundleName: function (packages) {
   if (Object.keys(packages).length === 0) {
     return null;
   }
   return String(hash(JSON.stringify(packages)));
 },
Пример #25
0
 function (hashtag, callback) {
   console.log("Found hashtag ", hashtag);
   args.push(stringHash(hashtag));
   args.push(tweet.id_str);
   callback();
 },
Пример #26
0
app.post('/student/submit', function(req, res, next){
  console.log('post form:', req.body.studentSample.length);

  // FIRST CHECK OUR HASH if we pre-ran this sample
  var studentSample = req.body.studentSample;
  var sampleHash = hash(studentSample);
  console.log('input sample hash:', sampleHash);
  app.tradeoffdb.get(sampleHash, function(err, data){
    // err will be 404 for no previous run
    if (err && err.statusCode === 404) {
      console.log('no previous run found, running analysis...', studentSample.length);
      app.persInsights.profile({text: studentSample}, function(err, studentPersonality){
        if (err) {
          next(err);
          return;
        }
        console.log('got a student profile');
        console.log('finding matches...');
        // TODO matching algorithm here against all schools
        finder.findSchools(schooldocs, studentPersonality, function(err, matches){
          if (err) {
            next(err);
            return;
          }

          // do some munging on the student top5 compared to schools
          // prepare the tradeoff setup
          finder.tradeoff(matches, function(err, finalMatchData){
            // now returns an object with matches that had enough data to tradeoff analyze...
            // changed to return a cache to the tradeoff result run a separate cloudant db
            if (err) {
              next(err);
              return;
            }
            var tradeoffId = finalMatchData.tradeoffId;

            var results = {
              sampleId: sampleHash, // our future DB id
              isCached: false, // this will get saved - just override when reading
              matches: finalMatchData.matches, // JUST WHAT IS USED IN TRADEOFF PLZ
              tradeoff: '/tradeoff/' + tradeoffId,
              studentPersonality: persUtils.matches(studentPersonality)
            };

            // let's cache? what should we cache really just what we are sending?
            // need fast for demos, just save and forget
            // // FORCE STRING FOR CLOUDANT ID
            app.tradeoffdb.insert(results, sampleHash + '', function(err, ok){
              console.log('cached an analysis run:', err, ok);
            });
            res.json(results); // done sending JSON back
          }); // end tradeoff run
        }); // end school matcher
      }); // end personality profile run

    } else if (data) {
      // we got a cached run!
      console.log('found a cached');
      data.isCached = true;
      res.json(data);
    } else {
      console.log('no cached run and no data, fubar');
      if (err) {
        next(err);
        return;
      }
    }
  });
});
Пример #27
0
function createJoiModel(schema, defaults) {

    // Check if schema is a Joi schema
    if (!schema.isJoi && !(schema._type === 'object')) {
        throw new Error('Schema passed to joi-model2 must be a Joi schema.');
    }

    // Check if default object is valid itself
    if (defaults) {
        const validation = Joi.validate(schema, defaults);
        if (validation.error) {
            throw new Error('JoiModel default values do not validate against given schema \n' + validation.error);
        }
    }

    // Create a shadow object that
    const shadowObj = _.cloneDeep(defaults || {});

    // TODO make real random UUIDs
    const modelUUID = '12345';
    let JoiModel = {
        _UUID:      modelUUID,
        _shadowObj: shadowObj,
        _data:       {}
    };

    // Create an object to store cached values
    validatedValues[ modelUUID ] = {};

    const childrenSchemas = schema._inner.children;

    for (let childSchema of childrenSchemas) {

        const key = childSchema.key;

        Object.defineProperty(JoiModel, key, {
            enumerable: true,
            get() {
                return this._data[ key ];
            },
            set(val) {
                const _this = this;
                const hash = hashAString(JSON.stringify(val));

                // If this value has already been validated for this key before, then just set the value
                if (validatedValues[ modelUUID ][ hash ]) {
                    return _this._data[ key ] = val;
                }

                // Do the validation against the shadow object
                const oldVal = _this._data[ key ];
                _this._shadowObj[ key ] = val;
                const validation = Joi.validate(_this._shadowObj, schema);
                if (validation.error) {
                    _this._shadowObj[ key ] = oldVal;
                    throw new Error('Attempted to change a property to an invalid value: \n' + validation.error);
                }
                else {
                    // Cache the validated value
                    validatedValues[ modelUUID ][ hash ] = true;
                    return _this._data[ key ] = val;

                }
            }
        });
    }

    JoiModel.toJSON = function() {
        return this._shadowObj;
    };

    JoiModel.toString = function() {
        return this._shadowObj + '';
    };

    JoiModel.inspect = function() {
        return this._shadowObj;
    };

    // Stops the addition of new properties
    Object.preventExtensions(JoiModel);

    return JoiModel;
}
Пример #28
0
  function visitVariableDeclaration(path, opts, filename) {
    if (
      t.isVariableDeclaration(path.node) &&
      path.node.declarations.length === 1 &&
      path.node.declarations[0].init
    ) {
      const {input, tag, match} = getInputAndTag(path.get('declarations')[0].get('init'));
      if (!match) {
        return;
      }

      const processor = postcss([
        modules({
          getJSON(cssFileName, json) {
            aliases[path.node.declarations[0].id.name] = json;
          },
          generateScopedName(name, filename, css) {
            filename = resolve(filename);
            if (opts.optimised) {
              const key = stringHash(filename).toString(36) + '_' + stringHash(name).toString(36);
              let id;
              let cache = compressedClassesCache;
              if (opts.cache) {
                try {
                  cache = JSON.parse(readFileSync(opts.cache, 'utf8'));
                } catch (ex) {
                  if (ex.code === 'ENOENT') cache = {maxID: 0};
                  else throw ex;
                }
              }
              if (key in cache) {
                id = cache[key];
              } else {
                id = cache.maxID++;
                cache[key] = id;
              }
              if (opts.cache) {
                writeFileSync(opts.cache, JSON.stringify(cache, null, '  '));
              }
              return '_' + (opts.optimised === true ? id : opts.optimised + '_' + id);
            }
            const i = css.indexOf('.' + name);
            const numLines = css.substr(0, i).split(/[\r\n]/).length;
            const hash = stringHash(css).toString(36);

            return `_${ name }_${ hash }_${ numLines }`;
          },
        }),
      ].concat(postPlugins()),
      );

      const transformedCSS = processor.process(input, {
        from: filename,
        to: filename,
      }).css;

      if (opts.extractCSS) {
        cssSources[opts.extractCSS][filename] += transformedCSS;
        path.remove();
      } else {
        path.replaceWith(
          t.expressionStatement(
            t.callExpression(
              tag,
              [
                t.stringLiteral(transformedCSS),
              ],
            ),
          ),
        );
      }
    }
  }
Пример #29
0
 var djb2 = function (ip) { return hash_djb2(ip) % CONCURRENCY; };
Пример #30
0
 computeStringHash: function(str) {
   var md5 = crypto.createHash('md5').update(str || "").digest("hex");
   return Math.abs(hasher(md5));
 },