https://github.com/scarney81/pg-hstore
188215
function sanitizeInput(input) {
  // http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html [4.1.2.1-4.1.2.2]
  // single quotes (') must be replaced with double single quotes ('')
  input = input.replace(/'/g, "''")
  // backslashes (\) must be replaced with double backslashes (\\)
  input = input.replace(/\\/g, '\\\\')
  // double quotes (") must be replaced with escaped quotes (\\")
  input = input.replace(/"/g, '\\"')
  return input
}
264727
function getOrderIndependentHash(object, orderIndependent, pathCache, valueCache) {
    orderIndependent = getFunctionOption(orderIndependent);
    pathCache = pathCache || [];
    valueCache = valueCache || [];

    var accum = 0;
    var accumList = [];
    var type = realTypeOf(object);
    var i;

    if (type === 'array' || type === 'object') {
      if ((i = valueCache.indexOf(object)) !== -1) {
        return hashThisString(pathCache.slice(i).join(','));
      }
    }

    if (type === 'array') {
      var arrayString;
      if (orderIndependent(pathCache)) {
        for (i = 0; i < object.length; ++i) {
          accum += getOrderIndependentHash(object[i], orderIndependent, pathCache.concat(0), valueCache.concat([object]));
        }
        arrayString = '[type: array, hash: ' + accum + ']';
      } else {
        for (i = 0; i < object.length; ++i) {
          accumList.push(getOrderIndependentHash(object[i], orderIndependent, pathCache.concat(i), valueCache.concat([object])));
        }
        arrayString = '[type: array, hash: ' + accumList.join(', ') + ']';
      }
      return hashThisString(arrayString);
    }

    if (type === 'object') {
      var keyValueString;
      var objectString;
      var key;
      if (orderIndependent(pathCache) !== false) {
        for (key in object) {
          if (object.hasOwnProperty(key)) {
            keyValueString = 'key: ' + key + ', value hash: ' + getOrderIndependentHash(object[key], orderIndependent, pathCache.concat(key), valueCache.concat(object));
            accum += hashThisString(keyValueString);
          }
        }
        objectString = '[type: object, hash: ' + accum + ']';
      } else {
        for (key in object) {
          if (object.hasOwnProperty(key)) {
            keyValueString = 'key: ' + key + ', value hash: ' + getOrderIndependentHash(object[key], orderIndependent, pathCache.concat(key), valueCache.concat(object));
            accumList.push(hashThisString(keyValueString));
          }
        }
        objectString = '[type: object, hash: ' + accumList.join(', ') + ']';
      }
      return hashThisString(objectString);
    }

    // Non object, non array...should be good?
    var stringToHash = '[ type: ' + type + ' ; value: ' + object + ']';
    return hashThisString(stringToHash);
  }
64786
function it_converts_and_normalizes_rows_to_pg($normalizer, $converter)
    {
        $this->setType('decimal', $converter, $normalizer);
        $this->setCompositeType('real', [
            'pi'  => 'decimal',
            'phi' => 'decimal'
        ]);

        $this
            ->toPg(
                [
                    'pi'  => (object) [
                        'value' => 3.14159265359
                    ],
                    'phi' => (object) [
                        'value' => 1.66180339887
                    ]
                ],
                'real'
            )
            ->shouldBeLike(new Row(
                [
                    'pi'  => new Value('3.14159265359', new Type('decimal')),
                    'phi' => new Value('1.66180339887', new Type('decimal'))
                ],
                new Type('real')
            ))
        ;
    }
229284
def sshfp_data(key_t, hash_t, pub):
    '''
    
    '''
    key_t = RFC.validate(key_t, RFC.SSHFP_ALGO, 'in')
    hash_t = RFC.validate(hash_t, RFC.SSHFP_HASH)

    hasher = hashlib.new(hash_t)
    hasher.update(
        base64.b64decode(pub)
    )
    ssh_fp = hasher.hexdigest()

    return _rec2data(key_t, hash_t, ssh_fp)
87493
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/trees/#get-a-tree-recursively
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/trees/:ref_or_sha?recursive
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refOrSha = req.params.ref_or_sha;
    const recursive = typeof req.query.recursive !== 'undefined' && req.query.recursive !== '';
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    async function dirEntryToJson({
      oid: sha, type, path, mode,
    }) {
      return {
        path,
        mode,
        type,
        sha,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
      };
    }

    async function fileEntryToJson({
      oid: sha, type, path, mode,
    }) {
      const { object: content } = await getObject(repPath, sha);

      return {
        path,
        mode,
        type,
        sha,
        size: content.length,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/blobs/${sha}`,
      };
    }

    async function collectTreeEntries(tree, result, treePath, deep) {
      const entries = tree.entries.map(({
        oid, type, mode, path,
      }) => {
        return {
          oid, type, mode, path: joinPaths(treePath, path),
        };
      });
      result.push(...entries);
      if (deep) {
        const treeEntries = entries.filter(entry => entry.type === 'tree');
        for (let i = 0; i < treeEntries.length; i += 1) {
          const { oid, path } = treeEntries[i];
          /* eslint-disable no-await-in-loop */
          const { object: subTree } = await getObject(repPath, oid);
          await collectTreeEntries(subTree, result, path, deep);
        }
      }
      return result;
    }

    async function treeEntriesToJson(tree, deep) {
      const result = [];
      await collectTreeEntries(tree, result, '', deep);
      return Promise.all(result.map(async (entry) => {
        /* eslint arrow-body-style: "off" */
        return entry.type === 'blob'
          ? fileEntryToJson(entry) : dirEntryToJson(entry);
      }));
    }

    resolveTree(repPath, refOrSha)
      .then(async ({ oid: sha, object: tree }) => {
        res.json({
          sha,
          url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
          tree: await treeEntriesToJson(tree, recursive),
          truncated: false,
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail' || err.code === 'ResolveRefError') {
          options.logger.debug(`[treeHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/trees/#get-a-tree',
          });
        } else {
          options.logger.debug(`[treeHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
914
function sinterstore(destination /* key-1, key-N, req*/) {
  var args = slice.call(arguments, 1)
    , req = typeof args[args.length - 1] === 'object'
      ? args[args.length - 1] : null;
  var list = this.sinter.apply(this, args);
  if(list.length) {
    this.setKey(
      destination, new Set(list), undefined, undefined, undefined, req);
  }
  return list.length;
}
617068
function giveStore(ecModel) {
    var store = ecModel[ATTR];
    if (!store) {
        store = ecModel[ATTR] = [{}];
    }
    return store;
}
176736
function(arr, seg, poly, pDist, coef) 
{
    var dta = vcross(seg.tn, seg.ta);
    var dtb = vcross(seg.tn, seg.tb);
    var n = vmult(seg.tn, coef);
    
    var verts = poly.tVerts;
    for(var i=0; i<verts.length; i+=2){
        var vx = verts[i];
        var vy = verts[i+1];
        if(vdot2(vx, vy, n.x, n.y) < vdot(seg.tn, seg.ta)*coef + seg.r){
            var dt = vcross2(seg.tn.x, seg.tn.y, vx, vy);
            if(dta >= dt && dt >= dtb){
                arr.push(new Contact(new Vect(vx, vy), n, pDist, hashPair(poly.hashid, i)));
            }
        }
    }
}
176341
function checksum(src, algorithm='sha256', outputFormat='hex'){
    return new Promise(async function(resolve, reject){
        // hash engine
        const hash = _crypto.createHash(algorithm);

        // events
        hash.on('readable', function(){
            // get hashsum
            const sum = hash.read();

            // data available ?
            if (!sum){
                return;
            }

            // hex, base64 or buffer
            switch (outputFormat){
                case 'base64':
                    resolve(sum.toString('base64'));
                    break;
                case 'raw':
                case 'buffer':
                    resolve(sum);
                    break;
                default:
                    resolve(sum.toString('hex'));
                    break;
            }
        });
        hash.on('error', function(e){
            reject(e);
        })

        try{
            // open file input stream
            const input = await _fInputStream(src);

             // stream hashing
            input.pipe(hash);
        }catch(e){
            reject(e);
        }
    });
}
172550
function (value, length, pad) {
        return _gpfToBaseANY(_gpfB64, value, {
            length: length,
            pad: pad
        });
    }
1306793
function rstr_hmac(key, data) {
        var bkey, ipad, opad, hash, i;

        key = (utf8) ? utf8Encode(key) : key;
        data = (utf8) ? utf8Encode(data) : data;
        bkey = rstr2binl(key);
        if (bkey.length > 16) {
          bkey = binl(bkey, key.length * 8);
        }

        ipad = Array(16), opad = Array(16);
        for (i = 0; i < 16; i += 1) {
          ipad[i] = bkey[i] ^ 0x36363636;
          opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }
        hash = binl(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
        return binl2rstr(binl(opad.concat(hash), 512 + 128));
      }
731007
function resolveAddresses(provider, value, paramType) {
    if (Array.isArray(paramType)) {
        var promises_1 = [];
        paramType.forEach(function (paramType, index) {
            var v = null;
            if (Array.isArray(value)) {
                v = value[index];
            }
            else {
                v = value[paramType.name];
            }
            promises_1.push(resolveAddresses(provider, v, paramType));
        });
        return Promise.all(promises_1);
    }
    if (paramType.type === 'address') {
        return provider.resolveName(value);
    }
    if (paramType.type === 'tuple') {
        return resolveAddresses(provider, value, paramType.components);
    }
    // Strips one level of array indexing off the end to recuse into
    var isArrayMatch = paramType.type.match(/(.*)(\[[0-9]*\]$)/);
    if (isArrayMatch) {
        if (!Array.isArray(value)) {
            throw new Error('invalid value for array');
        }
        var promises = [];
        var subParamType = {
            components: paramType.components,
            type: isArrayMatch[1],
        };
        value.forEach(function (v) {
            promises.push(resolveAddresses(provider, v, subParamType));
        });
        return Promise.all(promises);
    }
    return Promise.resolve(value);
}
586168
function(data, keysize) {
      var input, mode;
      if (keysize == null) {
        keysize = 512;
      }
      data = this.toHex(data);
      mode = "SHA-" + keysize;
      input = new jsSHA(data, "HEX");
      return input.getHash(mode, "HEX");
    }
206850
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Commits requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/commits/?path=:path&sha=:sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.query.sha || 'master';
    let fpath = req.query.path || '';

    // TODO: support filtering (author, since, until)
    // const { author, since, until } = req.query;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    if (typeof fpath !== 'string') {
      res.status(400).send('Bad request');
      return;
    }
    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    const NOT_IMPL = 'not implemented';

    function email2avatarUrl(email) {
      const hash = crypto.createHash('md5').update(email).digest('hex');
      return `https://s.gravatar.com/avatar/${hash}`;
    }

    commitLog(repPath, sha, fpath)
      .then((commits) => {
        const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
        const result = [];
        commits.forEach((commit) => {
          const parents = [];
          commit.parent.forEach(oid => parents.push({
            sha: oid,
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${oid}`,
          }));
          result.push({
            sha: commit.oid,
            node_id: NOT_IMPL,
            commit: {
              author: {
                name: commit.author.name,
                email: commit.author.email,
                date: new Date(commit.author.timestamp * 1000).toISOString(),
              },
              committer: {
                name: commit.committer.name,
                email: commit.committer.email,
                date: new Date(commit.committer.timestamp * 1000).toISOString(),
              },
              message: commit.message,
              tree: {
                sha: commit.tree,
                url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${commit.tree}`,
              },
              url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/commits/${commit.oid}`,
              comment_count: 0,
              verification: {
                verified: false,
                reason: NOT_IMPL,
                signature: NOT_IMPL,
                payload: NOT_IMPL,
              },
            },
            // TODO
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${commit.oid}`,
            comments_url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}/comments`,
            author: {
              avatar_url: email2avatarUrl(commit.author.email),
              gravatar_id: '',
              // TODO
            },
            committer: {
              avatar_url: email2avatarUrl(commit.committer.email),
              gravatar_id: '',
              // TODO
            },
            parents,
          });
        });
        res.json(result);
      })
      .catch((err) => {
        options.logger.debug(`[commitHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
        // github seems to swallow errors and just return an empty array...
        // res.json([]);
      });
  };
}
1134930
function deterministicGenerateK(curve, hash, d, checkSig, nonce) {
    enforceType("Buffer", hash);
    enforceType(BigInteger, d);

    if (nonce) {
        hash = sha256(Buffer.concat([hash, Buffer.alloc(nonce)]));
    }

    // sanity check
    assert.equal(hash.length, 32, "Hash must be 256 bit");

    var x = d.toBuffer(32);
    var k = Buffer.alloc(32);
    var v = Buffer.alloc(32);

    // Step B
    v.fill(1);

    // Step C
    k.fill(0);

    // Step D
    k = HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k);

    // Step E
    v = HmacSHA256(v, k);

    // Step F
    k = HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k);

    // Step G
    v = HmacSHA256(v, k);

    // Step H1/H2a, ignored as tlen === qlen (256 bit)
    // Step H2b
    v = HmacSHA256(v, k);

    var T = BigInteger.fromBuffer(v);

    // Step H3, repeat until T is within the interval [1, n - 1]
    while (T.signum() <= 0 || T.compareTo(curve.n) >= 0 || !checkSig(T)) {
        k = HmacSHA256(Buffer.concat([v, new Buffer([0])]), k);
        v = HmacSHA256(v, k);

        // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
        // Step H2b again
        v = HmacSHA256(v, k);

        T = BigInteger.fromBuffer(v);
    }

    return T;
}
251488
function headerReduce(headers, format) {
    var minmtime = new Date('Sun, 23 Feb 2014 18:00:00 UTC');
    var composed = {};

    composed['Cache-Control'] = 'max-age=3600';

    switch (format) {
    case 'vector.pbf':
        composed['Content-Type'] = 'application/x-protobuf';
        composed['Content-Encoding'] = 'deflate';
        break;
    case 'jpeg':
        composed['Content-Type'] = 'image/jpeg';
        break;
    case 'png':
        composed['Content-Type'] = 'image/png';
        break;
    }

    var times = headers.reduce(function(memo, h) {
        if (!h) return memo;
        for (var k in h) if (k.toLowerCase() === 'last-modified') {
            memo.push(new Date(h[k]));
            return memo;
        }
        return memo;
    }, []);
    if (!times.length) {
        times.push(new Date());
    } else {
        times.push(minmtime);
    }
    composed['Last-Modified'] = (new Date(Math.max.apply(Math, times))).toUTCString();

    var etag = headers.reduce(function(memo, h) {
        if (!h) return memo;
        for (var k in h) if (k.toLowerCase() === 'etag') {
            memo.push(h[k]);
            return memo;
        }
        return memo;
    }, []);
    if (!etag.length) {
        composed['ETag'] = '"' + crypto.createHash('md5').update(composed['Last-Modified']).digest('hex') + '"';
    } else {
        composed['ETag'] = etag.length === 1 ? etag[0] : '"' + crypto.createHash('md5').update(etag.join(',')).digest('hex') + '"';
    }

    return composed;
}
94268
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/blobs/#get-a-blob
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/blobs/:file_sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.params.file_sha;
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

    const repPath = resolveRepositoryPath(options, owner, repoName);

    if (sha.match(/[0-9a-f]/g).length !== 40) {
      // invalid sha format
      res.status(422).json({
        message: 'The sha parameter must be exactly 40 characters and contain only [0-9a-f].',
        documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
      });
      return;
    }
    getObject(repPath, sha)
      .then(({ object: content }) => {
        res.json({
          sha,
          size: content.length,
          url: `${req.protocol}://${host}${req.path}`,
          content: `${content.toString('base64')}\n`,
          encoding: 'base64',
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail') {
          options.logger.debug(`[blobHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/blobs/#get-a-blob',
          });
        } else {
          options.logger.debug(`[blobHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}