<commit_before>/* eslint-disable no-console */
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

/*
plugins: `
  firstRelease: Date
  buildDate: Date
  categories: {
    id: String!
  }
  dependencies: {
    name: String
    title: String
    optional: Boolean
    version: String
    implied: Boolean
  }
  maintainers: {
    id: String
    name: String
    email: String
  }
  excerpt: String
  gav: String
  labels: {
    id: String!
  }
  name: String
  previousTimestamp: Date
  previousVersion: String
  releaseTimestamp: Date
  requiredCore: String
  scm: {
    issues: String
    link: String
    inLatestRelease: String
    sinceLatestRelease: String
    pullRequest: String
  }
  sha1: String
  // stats:
  title: String
  url: String
  version: String
  // securityWarnings:
  wiki: {
    content: String
    url: String
  }
`
*/

const requestGET = ({ url, reporter }) => {
  const activity = reporter.activityTimer(`Fetching '${url}'`);
  activity.start();

  return axios
    .get(url)
    .then((results) => {
      activity.end();

      if (results.status !== 200) {
        throw results.data;
      }
      return results.data;
    });
};

const getPluginSiteVersion = () => {
  const file = path.join(__dirname, '../../GIT_COMMIT');
  try {
    return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').substring(0, 7) : 'TBD';
  } catch (err) {
    console.error(`Problem accessing ${file}`, err);
  }
};

const fetchPluginData = async ({ createNode, reporter }) => {
  const sectionActivity = reporter.activityTimer('fetch plugins info');
  sectionActivity.start();
  let page = 1;
  const promises = [];
  while (1) {
    const url = `https://plugins.jenkins.io/api/plugins/?limit=100&page=${page}`;
    const pluginsContainer = await requestGET({ url, reporter });

    for (const plugin of pluginsContainer.plugins) {
      const promise = (
        process.env.SLOW_MODE
          ? requestGET({ reporter, url: `https://plugins.jenkins.io/api/plugin/${plugin.name}` })
          : Promise.resolve(plugin)
      );
      promises.push(promise.then(pluginData => {
        pluginData.wiki = pluginData.wiki || {};
        pluginData.wiki.content = pluginData.wiki.content || '';
        return createNode({
          ...pluginData,
          id: pluginData.name.trim(),
          parent: null,
          children: [],
          internal: {
            type: 'JenkinsPlugin',
            contentDigest: crypto.createHash('md5').update(`plugin${pluginData.name.trim()}`).digest('hex')
          }
        });
      }));
    }
    page = pluginsContainer.page + 1;
    if (pluginsContainer.page > pluginsContainer.pages) {
      break;
    }
  }
  await Promise.all(promises);
  sectionActivity.end();
};

const fetchCategoryData = async ({ createNode, reporter }) => {
  const sectionActivity = reporter.activityTimer('fetch categories info');
  sectionActivity.start();
  let page = 1;
  while (1) {
    const url = `https://plugins.jenkins.io/api/categories/?limit=100&page=${page}`;
    const categoriesContainer = await requestGET({ url, reporter });

    for (const category of categoriesContainer.categories) {
      createNode({
        ...category,
        id: category.id.trim(),
        parent: null,
        children: [],
        internal: {
          type: 'JenkinsPluginCategory',
          contentDigest: crypto
            .createHash('md5')
            .update(`category${category.name}`)
            .digest('hex')
        }
      });
    }
    page = categoriesContainer.page + 1;
    if (!page || categoriesContainer.page > categoriesContainer.pages) {
      break;
    }
  }
  sectionActivity.end();
};

const fetchLabelData = async ({ createNode, reporter }) => {
  const sectionActivity = reporter.activityTimer('fetch labels info');
  sectionActivity.start();
  let page = 1;
  while (1) {
    const url = `https://plugins.jenkins.io/api/labels/?limit=100&page=${page}`;
    const labelsContainer = await requestGET({ url, reporter });

    for (const label of labelsContainer.labels) {
      createNode({
        ...label,
        id: label.id.trim(),
        parent: null,
        children: [],
        internal: {
          type: 'JenkinsPluginLabel',
          contentDigest: crypto
            .createHash('md5')
            .update(`label${label.name}`)
            .digest('hex')
        }
      });
    }
    page = labelsContainer.page + 1;
    if (!page || labelsContainer.page > labelsContainer.pages) {
      break;
    }
  }
  sectionActivity.end();
};

const fetchSiteInfo = async ({ createNode, reporter }) => {
  const sectionActivity = reporter.activityTimer('fetch plugin api info');
  sectionActivity.start();
  do {
    const url = 'https://plugins.jenkins.io/api/info';
    const info = await requestGET({ url, reporter });

    createNode({
      api: {
        ...info
      },
      website: {
        commit: getPluginSiteVersion()
      },
      id: 'pluginSiteInfo',
      parent: null,
      children: [],
      internal: {
        type: 'JenkinsPluginSiteInfo',
        contentDigest: crypto.createHash('md5').update('pluginSiteInfo').digest('hex')
      }
    });
  } while (0);
  sectionActivity.end();
};

exports.sourceNodes = async (
  { actions, reporter },
  { /* options */ } // eslint-disable-line no-empty-pattern
) => {
  const { createNode } = actions;

  try {
    await fetchSiteInfo({ createNode, reporter });
    await fetchPluginData({ createNode, reporter });
    await fetchCategoryData({ createNode, reporter });
    await fetchLabelData({ createNode, reporter });
  } catch (err) {
    reporter.panic(
      `gatsby-source-jenkinsplugin: Failed to parse API call -  ${err}`
    );
  }
};
<commit_msg>Eslint fixes to the gatsby source<commit_after>/* eslint-disable no-console */
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

/*
plugins: `
  firstRelease: Date
  buildDate: Date
  categories: {
    id: String!
  }
  dependencies: {
    name: String
    title: String
    optional: Boolean
    version: String
    implied: Boolean
  }
  maintainers: {
    id: String
    name: String
    email: String
  }
  excerpt: String
  gav: String
  labels: {
    id: String!
  }
  name: String
  previousTimestamp: Date
  previousVersion: String
  releaseTimestamp: Date
  requiredCore: String
  scm: {
    issues: String
    link: String
    inLatestRelease: String
    sinceLatestRelease: String
    pullRequest: String
  }
  sha1: String
  // stats:
  title: String
  url: String
  version: String
  // securityWarnings:
  wiki: {
    content: String
    url: String
  }
`
*/

const requestGET = ({url, reporter}) => {
    const activity = reporter.activityTimer(`Fetching '${url}'`);
    activity.start();

    return axios
        .get(url)
        .then((results) => {
            activity.end();

            if (results.status !== 200) {
                throw results.data;
            }
            return results.data;
        });
};

const getPluginSiteVersion = () => {
    const file = path.join(__dirname, '../../GIT_COMMIT');
    try {
        return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').substring(0, 7) : 'TBD';
    } catch (err) {
        console.error(`Problem accessing ${file}`, err);
    }
};

const fetchPluginData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugins info');
    sectionActivity.start();
    let page = 1;
    const promises = [];
    while (1) {
        const url = `https://plugins.jenkins.io/api/plugins/?limit=100&page=${page}`;
        const pluginsContainer = await requestGET({url, reporter});

        for (const plugin of pluginsContainer.plugins) {
            const promise = (
                process.env.SLOW_MODE
                    ? requestGET({reporter, url: `https://plugins.jenkins.io/api/plugin/${plugin.name}`})
                    : Promise.resolve(plugin)
            );
            promises.push(promise.then(pluginData => {
                pluginData.wiki = pluginData.wiki || {};
                pluginData.wiki.content = pluginData.wiki.content || '';
                return createNode({
                    ...pluginData,
                    id: pluginData.name.trim(),
                    parent: null,
                    children: [],
                    internal: {
                        type: 'JenkinsPlugin',
                        contentDigest: crypto.createHash('md5').update(`plugin${pluginData.name.trim()}`).digest('hex')
                    }
                });
            }));
        }
        page = pluginsContainer.page + 1;
        if (pluginsContainer.page > pluginsContainer.pages) {
            break;
        }
    }
    await Promise.all(promises);
    sectionActivity.end();
};

const fetchCategoryData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch categories info');
    sectionActivity.start();
    let page = 1;
    while (1) {
        const url = `https://plugins.jenkins.io/api/categories/?limit=100&page=${page}`;
        const categoriesContainer = await requestGET({url, reporter});

        for (const category of categoriesContainer.categories) {
            createNode({
                ...category,
                id: category.id.trim(),
                parent: null,
                children: [],
                internal: {
                    type: 'JenkinsPluginCategory',
                    contentDigest: crypto
                        .createHash('md5')
                        .update(`category${category.name}`)
                        .digest('hex')
                }
            });
        }
        page = categoriesContainer.page + 1;
        if (!page || categoriesContainer.page > categoriesContainer.pages) {
            break;
        }
    }
    sectionActivity.end();
};

const fetchLabelData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch labels info');
    sectionActivity.start();
    let page = 1;
    while (1) {
        const url = `https://plugins.jenkins.io/api/labels/?limit=100&page=${page}`;
        const labelsContainer = await requestGET({url, reporter});

        for (const label of labelsContainer.labels) {
            createNode({
                ...label,
                id: label.id.trim(),
                parent: null,
                children: [],
                internal: {
                    type: 'JenkinsPluginLabel',
                    contentDigest: crypto
                        .createHash('md5')
                        .update(`label${label.name}`)
                        .digest('hex')
                }
            });
        }
        page = labelsContainer.page + 1;
        if (!page || labelsContainer.page > labelsContainer.pages) {
            break;
        }
    }
    sectionActivity.end();
};

const fetchSiteInfo = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugin api info');
    sectionActivity.start();
    do {
        const url = 'https://plugins.jenkins.io/api/info';
        const info = await requestGET({url, reporter});

        createNode({
            api: {
                ...info
            },
            website: {
                commit: getPluginSiteVersion()
            },
            id: 'pluginSiteInfo',
            parent: null,
            children: [],
            internal: {
                type: 'JenkinsPluginSiteInfo',
                contentDigest: crypto.createHash('md5').update('pluginSiteInfo').digest('hex')
            }
        });
    } while (0);
    sectionActivity.end();
};

exports.sourceNodes = async (
    {actions, reporter},
    { /* options */ } // eslint-disable-line no-empty-pattern
) => {
    const {createNode} = actions;

    try {
        await fetchSiteInfo({createNode, reporter});
        await fetchPluginData({createNode, reporter});
        await fetchCategoryData({createNode, reporter});
        await fetchLabelData({createNode, reporter});
    } catch (err) {
        reporter.panic(
            `gatsby-source-jenkinsplugin: Failed to parse API call -  ${err}`
        );
    }
};
<|endoftext|>


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

// 1.0 style test script not using the `casperjs test` subcommand
var casper = require('casper').create();
var host = casper.cli.args[0];

casper.start(host + '/', function (response) {
    console.log('Starting ' + host + '/');
    this.test.assertEquals(response.status, 302);
});

casper.thenOpen(host + '/Books', function (response) {
    this.test.assertEquals(response.status, 200);
});

casper.assertExists({ type: 'xpath', path: "//a[text()='Login']" });

casper.thenClick('#add-book', function () {
    console.log('Clicked Add book.  New location is ' + this.getCurrentUrl());
    this.test.assertExists({ type: 'xpath', path: '//input[@type="file"]' },
    'The Form element "image" exists for uploading book cover images .');
    this.fill('form#book-form', {
        'Book.Title': 'test.js',
        'Book.Author': 'test.js',
        'Book.PublishedDate': '2000-01-01',
        'Book.Description': 'Automatically added by test.js'
    }, false);
    console.log('Filled form.');
});

casper.thenClick('button', function () {
    console.log('Submitted.  New location is ' + this.getCurrentUrl());
    this.test.assertEquals(this.fetchText('.book-description'),
        'Automatically added by test.js');
});

casper.thenClick('button', function (response) {
    console.log('Deleted new book.  New location is ' + this.getCurrentUrl());
    this.test.assertEquals(response.status, 200);
});

casper.run(function () {
    this.test.done();
    this.test.renderResults(true);
});
<commit_msg>Fix 6-auth/test.js.<commit_after>// Copyright(c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// 1.0 style test script not using the `casperjs test` subcommand
var casper = require('casper').create();
var host = casper.cli.args[0];

casper.start(host + '/', function (response) {
    console.log('Starting ' + host + '/');
    this.test.assertEquals(response.status, 302);
});

casper.thenOpen(host + '/Books', function (response) {
    this.test.assertEquals(response.status, 200);
    this.test.assertExists({ type: 'xpath', path: "//a[text()='Login']" });
});

casper.thenClick('#add-book', function () {
    console.log('Clicked Add book.  New location is ' + this.getCurrentUrl());
    this.test.assertExists({ type: 'xpath', path: '//input[@type="file"]' },
    'The Form element "image" exists for uploading book cover images .');
    this.fill('form#book-form', {
        'Book.Title': 'test.js',
        'Book.Author': 'test.js',
        'Book.PublishedDate': '2000-01-01',
        'Book.Description': 'Automatically added by test.js'
    }, false);
    console.log('Filled form.');
});

casper.thenClick('button', function () {
    console.log('Submitted.  New location is ' + this.getCurrentUrl());
    this.test.assertEquals(this.fetchText('.book-description'),
        'Automatically added by test.js');
});

casper.thenClick('button', function (response) {
    console.log('Deleted new book.  New location is ' + this.getCurrentUrl());
    this.test.assertEquals(response.status, 200);
});

casper.run(function () {
    this.test.done();
    this.test.renderResults(true);
});
<|endoftext|>


<commit_before>define([
	'plugins/wrappup-toggle',
	'plugins/iscroll-pagination',
	'plugins/permanent-link',
	'plugins/user-comments',
	'plugins/twitter-widgets',
	'css!theme/liveblog'
], function(){
	return {
		//enviroments: [ 'mobile', 'desktop', 'quirks' ],
		plugins: [ 'wrappup-toggle',
					'scroll-pagination',
					'permanent-link',
					'user-comments' ]
	}
});<commit_msg>Iscroll<commit_after>define([
	'plugins/wrappup-toggle',
	'plugins/scroll-pagination',
	'plugins/permanent-link',
	'plugins/user-comments',
	'plugins/twitter-widgets',
	'css!theme/liveblog'
], function(){
	return {
		//enviroments: [ 'mobile', 'desktop', 'quirks' ],
		plugins: [ 'wrappup-toggle',
					'scroll-pagination',
					'permanent-link',
					'user-comments' ]
	}
});<|endoftext|>


<commit_before>Flotr.addType('funnel', {
    options: {
        show: false,
        lineWidth: 2,
        fill: true,
        fillColor: null,
        fillOpacity: 0.5,
        fontColor: "#B2B2B2",
        explode: 5,
        marginX: 450,
        marginY: 20,
        leftMargin: 160,
        colors: ['#ACD39C', '#BE9DE2', '#6598DA', '#ECC87E', '#A4A2F6', '#6487BF', '#65BC87', '#8985C2', '#ECB574', '#84A377'],
        nozzleSteps: [],
        tickFormatter: function(label, value) {
            return label + ': ' + value;
        },
        nozzleFormatter: function(label, value) {
            return label + ': ' + value;
        }
    },

    stack: [],
    stacked: false,
    shiftLabels: false,
    originData: [],

    in_array: function(what, where) {
        for(var i=0; i<where.length; i++) {
            if(what == where[i]) {
                return true;
            }
        }

        return false;
    },

    plot: function (options) {
        var
            self = this,
            marginWidth = options.marginX ? options.width - options.marginX : options.width,
            marginHeight = options.marginY || options.explode ? options.height - options.marginY * 2 - options.explode : options.height,
            extraHeight = options.extraHeight || 0,
            data = options.data,
            context = options.context,
            summ = 0,
            reSumm = 0,
            i = 0;

        Flotr._.each(data, function (funnel, label) {
            if (!self.in_array(label, options.nozzleSteps)) {
                summ += funnel;
            }
        });
        Flotr._.each(data, function (funnel, iterator) {
            if (funnel == 0 && !self.in_array(iterator, options.nozzleSteps)) {
                reSumm += summ / 100 * 2;
                data[iterator] = summ / 100 * 2;
                self.shiftLabels = true;
            } else if (self.in_array(iterator, options.nozzleSteps)) {
                reSumm += summ / 100 * 10;
                data[iterator] = summ / 100 * 10;
                self.shiftLabels = true;
            } else {
                reSumm += funnel;
            }
        });
        summ = reSumm;

        context.lineJoin = 'round';
        context.translate(0.5, 0.5);
        context.beginPath();
        context.moveTo(options.leftMargin || 0, options.marginY);

        self.stack[0] = {};
        self.stack[0].x1 = options.leftMargin || 0;
        self.stack[0].y1 = options.marginY;

        var segmentData = {
            'prevStepWidth': marginWidth,
            'prevStepWidthDelta': 0,
            'prevStepHeight': marginHeight + extraHeight,
            'funnelSumm': options.marginY
        };

        Flotr._.each(data, function (funnel, iterator) {
            if (self.in_array(iterator, options.nozzleSteps)) {
                var isNozzleStep = true;
            } else {
                var isNozzleStep = false;
            }
            var funnelSize = marginHeight / summ * funnel;
            if (options.explode > 0 /*&& Object.keys(data).length > i+1*/) {
                funnelSize -= options.explode;
            }

            segmentData = self.calculateSegment(options, funnelSize, i, marginWidth, segmentData, true, isNozzleStep);
            if (options.explode > 0 && Object.keys(data).length != i+1) {
                segmentData = self.calculateSegment(options, options.explode, i, marginWidth, segmentData, false, isNozzleStep);
            }
            i++;
        });
    },

    hit: function (options) {
        var
            self   = this,
            args   = options.args,
            mouse  = args[0],
            x      = mouse.relX,
            y      = mouse.relY;

            for (var i in self.stack) {
                var belongSide = true;
                /**
                 *  left/right rectangle side case
                 *  detect mouse is in figure
                 *
                 *  (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0)
                 *  (x2 - x0) * (y3 - y2) - (x3 - x2) * (y2 - y0)
                 *  (x3 - x0) * (y1 - y3) - (x1 - x3) * (y3 - y0)
                 */

                if (
                    x >= self.stack[i].x1 && x <= self.stack[i].x4 &&
                    y >= self.stack[i].y1 && y <= self.stack[i].y4
                ){
                    var
                        s1 = (self.stack[i].x1 - x) * (self.stack[i].y4 - self.stack[i].y1) - (self.stack[i].x1 - self.stack[i].x1) * (self.stack[i].y1 - y),
                        s2 = (self.stack[i].x1 - x) * (self.stack[i].y4 - self.stack[i].y4) - (self.stack[i].x4 - self.stack[i].x1) * (self.stack[i].y4 - y),
                        s3 = (self.stack[i].x4 - x) * (self.stack[i].y1 - self.stack[i].y4) - (self.stack[i].x1 - self.stack[i].x4) * (self.stack[i].y4 - y);
                    if (s1 == 0 || s2 == 0 || s3 == 0 || (s1 > 0 && s2 > 0 && s3 > 0) || (s1 < 0 && s2 < 0 && s3 < 0)){
                        belongSide = false;
                    }
                }

                // right rectangle side case
                if (
                    x >= self.stack[i].x3 && x <= self.stack[i].x2 &&
                    y >= self.stack[i].y2 && y <= self.stack[i].y3
                ){
                    var
                        s1 = (self.stack[i].x3 - x) * (self.stack[i].y2 - self.stack[i].y3) - (self.stack[i].x2 - self.stack[i].x3) * (self.stack[i].y3 - y),
                        s2 = (self.stack[i].x2 - x) * (self.stack[i].y3 - self.stack[i].y2) - (self.stack[i].x2 - self.stack[i].x2) * (self.stack[i].y2 - y),
                        s3 = (self.stack[i].x2 - x) * (self.stack[i].y3 - self.stack[i].y3) - (self.stack[i].x3 - self.stack[i].x2) * (self.stack[i].y3 - y);
                    if (s1 == 0 || s2 == 0 || s3 == 0 || (s1 > 0 && s2 > 0 && s3 > 0) || (s1 < 0 && s2 < 0 && s3 < 0)){
                        belongSide = false;
                    }
                }

                // full rectangle case
                if (
                    y >= self.stack[i].y1 && y <= self.stack[i].y3
                    && x >= self.stack[i].x1 && x <= self.stack[i].x2
                    && belongSide != false
                ) {
                    if (self.stacked === i) return;

                    self.stacked = i;
                    self.clearHit(options);
                    self.drawHit(options, i);

                    //self.drawTooltip('Test', x+10 , y);
                    return;
                }
            }

            self.stacked = false;
            self.clearHit(options);
    },

    drawTooltip: function (content, x, y, options){
    },

    drawHit: function (options, i) {
        var self = this, context = options.context;
        context.save();
        context.lineJoin    = 'round';
        context.strokeStyle = '#FF3F19';
        context.lineWidth   = options.lineWidth;
        context.beginPath();
        context.moveTo(self.stack[i].x1 + options.lineWidth * 2, self.stack[i].y1);
        context.lineTo(self.stack[i].x2 + options.lineWidth * 2, self.stack[i].y2);
        context.lineTo(self.stack[i].x3 + options.lineWidth * 2, self.stack[i].y3);
        context.lineTo(self.stack[i].x4 + options.lineWidth * 2, self.stack[i].y4);
        context.closePath();
        context.stroke();
        context.restore();
    },

    clearHit: function (options) {
        var
            self = this,
            context = options.context;

        context.save();
        for (var i in self.stack) {
            context.clearRect(
                self.stack[i].x1 - options.lineWidth * 2,
                self.stack[i].y1 - options.lineWidth,
                self.stack[i].x2 - self.stack[i].x1 + options.lineWidth * 5,
                self.stack[i].y4 - self.stack[i].y1 + options.lineWidth * 5
            );
        }
        context.restore();
    },

    draw: function (options) {
        var context = options.context;

        context.save();
        context.lineJoin = 'miter';
        context.lineWidth = options.lineWidth;

        this.originData = _.clone(options.data);

        this.plot(options);

        context.restore();
    },

    calculateSegment: function(options, funnel, iterator, marginWidth, segmentData, renderable, isNozzleStep) {
        var
            context = options.context,
            prevStepWidth      = segmentData.prevStepWidth,
            prevStepWidthDelta = segmentData.prevStepWidthDelta,
            prevStepHeight     = segmentData.prevStepHeight,
            funnelSumm         = segmentData.funnelSumm;

        context.lineWidth = options.lineWidth;
        context.strokeStyle = options.colors[iterator];
        context.fillStyle = Flotr.Color.parse(options.colors[iterator]).alpha(options.fillOpacity).toString();

        /**
         * Each segment calculate
         *
         *    D    D0            A                 D1
         *     ------------------------------------  AB  - funnel segment size (height) OR height of previous segment -> "prevStepHeight"
         *     \   |            |                /   AP  - full height (with margins) -> "marginHeight"
         *      \  |            |               /    DD1 - full width (OR full width of previous segment) "prevStepWidth"
         *       \ |            |              /     DD0 - "prevStepWidthDelta"
         *        \|            |             /
         *         \            | B          /       On any calculation step we should know BC
         *        C -------------------------          to correctly render segment of funnel
         *           \          |          /
         *            \         |         /
         *             \        |        /
         *              \       |       /
         *               \      |      /
         *                \     |     /
         *                 \    |    /
         *                  \   |   /
         *                   \  |  /
         *                    \ | /
         *                     \|/
         *                      | P
         */

        var
            self = this,
            AD = Math.ceil(prevStepWidth / 2),
            BC = Math.ceil((AD * (prevStepHeight - funnel)) / prevStepHeight);

        if (renderable) {
            this.stack[iterator].x2 = prevStepWidth + prevStepWidthDelta + (options.leftMargin || 0);
            this.stack[iterator].y2 = funnelSumm;

            if (isNozzleStep) {
                var x3 = this.stack[iterator].x2;
                var x4 = Math.ceil(marginWidth / 2 - AD) + (options.leftMargin || 0);
            } else {
                var x3 = Math.round(marginWidth / 2 + BC) + (options.leftMargin || 0);
                var x4 = Math.round(marginWidth / 2 - BC) + (options.leftMargin || 0);
            }

            this.stack[iterator].x3 = x3;
            this.stack[iterator].x4 = x4;

            this.stack[iterator].y3 =
            this.stack[iterator].y4 = (funnelSumm + funnel);

            context.lineTo(this.stack[iterator].x2, this.stack[iterator].y2); // lineTo x2y2
            context.lineTo(this.stack[iterator].x3, this.stack[iterator].y3); // lineTo x3y3
            if (this.stack[iterator].x3 != this.stack[iterator].x4) {
                context.lineTo(this.stack[iterator].x4, this.stack[iterator].y4); // lineTo x4y4
            }

            context.closePath();
            context.stroke();
            context.fill();

            self.renderLabel(context, options, Object.keys(options.data)[iterator], funnelSumm, iterator, isNozzleStep);
        }

        funnelSumm += funnel;

        context.beginPath();
        if (isNozzleStep) {
            var nextX = Math.ceil(marginWidth / 2 - AD) + (options.leftMargin || 0);
        } else {
            var nextX = Math.ceil(marginWidth / 2 - BC) + (options.leftMargin || 0);
        }
        context.moveTo(nextX , funnelSumm);

        self.stack[iterator + 1] = {};
        self.stack[iterator + 1].x1 = nextX;
        self.stack[iterator + 1].y1 = funnelSumm;

        return {
            'prevStepWidth'     : isNozzleStep ? AD * 2 : BC * 2,
            'prevStepWidthDelta': isNozzleStep ? marginWidth / 2 - AD: marginWidth / 2 - BC,
            'prevStepHeight'    : prevStepHeight - funnel,
            'funnelSumm'        : funnelSumm
        };
    },

    renderLabel: function(context, options, label, startY, iterator, isNozzleStep) {
        var distX = (options.width - options.marginX) / 2,
            count = Object.keys(options.data).length,
            distY = (iterator == 0)
                ? options.marginY
                : this.shiftLabels
                    ? (options.height - options.marginY * 2) / (count + 1) * iterator
                    : startY,
            style = {
                size : options.fontSize * 1.2,
                color : options.fontColor,
                weight : 1.5
            };
        options.htmlText   = true;
        style.textAlign    = 'left';
        style.textBaseline = 'top';
        style.wordWrap     = 'break-word';

        var html = [],
            divStyle =
                'position:absolute;' +
                style.textBaseline + ':' + (distY - style.size)  + 'px;' +
                style.textAlign + ':' + (distX + (options.marginX + options.width)/3 + 10) + 'px;',
            labelString = isNozzleStep
                ? options.nozzleFormatter(label, this.originData[label])
                : options.tickFormatter(label, this.originData[label]);

        html.push('
', labelString, '
');

        var div = Flotr.DOM.node('

');
        Flotr.DOM.insert(div, html.join(''));
        Flotr.DOM.insert(options.element, div);

        // label line
        context.beginPath();
        context.lineWidth = 1;
        context.strokeStyle = options.fontColor;
        context.moveTo(this.stack[iterator].x2, this.stack[iterator].y2);
        context.lineTo(distX + (options.marginX + options.width)/3, distY);
        context.stroke();
    }
});
<commit_msg>CRM-732: Funnel charts with nozzle<commit_after>Flotr.addType('funnel', {
    options: {
        show: false,
        lineWidth: 2,
        fill: true,
        fillColor: null,
        fillOpacity: 0.5,
        fontColor: "#B2B2B2",
        explode: 5,
        marginX: 450,
        marginY: 20,
        leftMargin: 160,
        colors: ['#ACD39C', '#BE9DE2', '#6598DA', '#ECC87E', '#A4A2F6', '#6487BF', '#65BC87', '#8985C2', '#ECB574', '#84A377'],
        nozzleSteps: [],
        tickFormatter: function(label, value) {
            return label + ': ' + value;
        },
        nozzleFormatter: function(label, value) {
            return label + ': ' + value;
        }
    },
    stack: [],
    stacked: false,
    shiftLabels: false,
    originData: [],

    plot: function (options) {
        var
            self = this,
            marginWidth = options.marginX ? options.width - options.marginX : options.width,
            marginHeight = options.marginY || options.explode ? options.height - options.marginY * 2 - options.explode : options.height,
            extraHeight = options.extraHeight || 0,
            data = options.data,
            context = options.context,
            summ = 0,
            reSumm = 0,
            i = 0;

        Flotr._.each(data, function (funnel, label) {
            if (options.nozzleSteps.indexOf(label) === -1) {
                summ += funnel;
            }
        });

        Flotr._.each(data, function (funnel, iterator) {
            if (funnel == 0 && options.nozzleSteps.indexOf(iterator) === -1) {
                reSumm += summ / 100 * 2;
                data[iterator] = summ / 100 * 2;
                self.shiftLabels = true;
            } else if (options.nozzleSteps.indexOf(iterator) !== -1) {
                reSumm += summ / 100 * 10;
                data[iterator] = summ / 100 * 10;
                self.shiftLabels = true;
            } else {
                reSumm += funnel;
            }
        });
        summ = reSumm;

        context.lineJoin = 'round';
        context.translate(0.5, 0.5);
        context.beginPath();
        context.moveTo(options.leftMargin || 0, options.marginY);

        self.stack[0]    = {};
        self.stack[0].x1 = options.leftMargin || 0;
        self.stack[0].y1 = options.marginY;

        var segmentData = {
            'prevStepWidth': marginWidth,
            'prevStepWidthDelta': 0,
            'prevStepHeight': marginHeight + extraHeight,
            'funnelSumm': options.marginY
        };

        Flotr._.each(data, function (funnel) {
            var funnelSize = marginHeight / summ * funnel;
            if (options.explode > 0) {
                funnelSize -= options.explode;
            }

            segmentData = self.calculateSegment(options, funnelSize, i, marginWidth, segmentData, true);
            if (options.explode > 0 && Object.keys(data).length != i+1) {
                segmentData = self.calculateSegment(options, options.explode, i, marginWidth, segmentData, false);
            }
            i++;
        });
    },

    hit: function (options) {
        var
            self   = this,
            args   = options.args,
            mouse  = args[0],
            x      = mouse.relX,
            y      = mouse.relY;

            for (var i in self.stack) {
                var
                    belongSide = true,
                    seg        = self.stack[i]; //Current funnel's segment

                /**
                 *  left/right rectangle side case
                 *  detect mouse is in figure
                 *
                 *  (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0)
                 *  (x2 - x0) * (y3 - y2) - (x3 - x2) * (y2 - y0)
                 *  (x3 - x0) * (y1 - y3) - (x1 - x3) * (y3 - y0)
                 */

                if (x >= seg.x1 && x <= seg.x4 && y >= seg.y1 && y <= seg.y4) {
                    var
                        s1 = (seg.x1 - x) * (seg.y4 - seg.y1) - (seg.x1 - seg.x1) * (seg.y1 - y),
                        s2 = (seg.x1 - x) * (seg.y4 - seg.y4) - (seg.x4 - seg.x1) * (seg.y4 - y),
                        s3 = (seg.x4 - x) * (seg.y1 - seg.y4) - (seg.x1 - seg.x4) * (seg.y4 - y);
                    if (s1 == 0 || s2 == 0 || s3 == 0 || (s1 > 0 && s2 > 0 && s3 > 0) || (s1 < 0 && s2 < 0 && s3 < 0)){
                        belongSide = false;
                    }
                }

                // right rectangle side case
                if (x >= seg.x3 && x <= seg.x2 && y >= seg.y2 && y <= seg.y3) {
                    var
                        s1 = (seg.x3 - x) * (seg.y2 - seg.y3) - (seg.x2 - seg.x3) * (seg.y3 - y),
                        s2 = (seg.x2 - x) * (seg.y3 - seg.y2) - (seg.x2 - seg.x2) * (seg.y2 - y),
                        s3 = (seg.x2 - x) * (seg.y3 - seg.y3) - (seg.x3 - seg.x2) * (seg.y3 - y);
                    if (s1 == 0 || s2 == 0 || s3 == 0 || (s1 > 0 && s2 > 0 && s3 > 0) || (s1 < 0 && s2 < 0 && s3 < 0)){
                        belongSide = false;
                    }
                }

                // full rectangle case
                if (y >= seg.y1 && y <= seg.y3 && x >= seg.x1 && x <= seg.x2 && belongSide != false) {
                    if (self.stacked === i) return;

                    self.stacked = i;
                    self.clearHit(options);
                    self.drawHit(options, i);

                    return;
                }
            }

            self.stacked = false;
            self.clearHit(options);
    },

    drawHit: function (options, i) {
        var self = this, context = options.context;
        context.save();
        context.lineJoin    = 'round';
        context.strokeStyle = '#FF3F19';
        context.lineWidth   = options.lineWidth;
        context.beginPath();
        context.moveTo(self.stack[i].x1 + options.lineWidth * 2, self.stack[i].y1);
        context.lineTo(self.stack[i].x2 + options.lineWidth * 2, self.stack[i].y2);
        context.lineTo(self.stack[i].x3 + options.lineWidth * 2, self.stack[i].y3);
        context.lineTo(self.stack[i].x4 + options.lineWidth * 2, self.stack[i].y4);
        context.closePath();
        context.stroke();
        context.restore();
    },

    clearHit: function (options) {
        var
            self = this,
            context = options.context;

        context.save();
        for (var i in self.stack) {
            context.clearRect(
                self.stack[i].x1 - options.lineWidth * 2,
                self.stack[i].y1 - options.lineWidth,
                self.stack[i].x2 - self.stack[i].x1 + options.lineWidth * 5,
                self.stack[i].y4 - self.stack[i].y1 + options.lineWidth * 5
            );
        }
        context.restore();
    },

    draw: function (options) {
        var context = options.context;

        context.save();
        context.lineJoin = 'miter';
        context.lineWidth = options.lineWidth;

        this.originData = _.clone(options.data);

        this.plot(options);

        context.restore();
    },

    calculateSegment: function(options, funnel, iterator, marginWidth, segmentData, renderable) {
        var
            context = options.context,
            prevStepWidth      = segmentData.prevStepWidth,
            prevStepWidthDelta = segmentData.prevStepWidthDelta,
            prevStepHeight     = segmentData.prevStepHeight,
            funnelSumm         = segmentData.funnelSumm,
            isNozzleStep       = true,
            label              = Object.keys(options.data)[iterator];

        if (options.nozzleSteps.indexOf(label) === -1) {
            isNozzleStep = false;
        }

        context.lineWidth   = options.lineWidth;
        context.strokeStyle = options.colors[iterator];
        context.fillStyle   = Flotr.Color.parse(options.colors[iterator]).alpha(options.fillOpacity).toString();

        /**
         * Each segment calculate
         *
         *    D    D0            A                 D1
         *     ------------------------------------  AB  - funnel segment size (height) OR height of previous segment -> "prevStepHeight"
         *     \   |            |                /   AP  - full height (with margins) -> "marginHeight"
         *      \  |            |               /    DD1 - full width (OR full width of previous segment) "prevStepWidth"
         *       \ |            |              /     DD0 - "prevStepWidthDelta"
         *        \|            |             /
         *         \            | B          /       On any calculation step we should know BC
         *        C -------------------------          to correctly render segment of funnel
         *           \          |          /
         *            \         |         /
         *             \        |        /
         *              \       |       /
         *               \      |      /
         *                \     |     /
         *                 \    |    /
         *                  \   |   /
         *                   \  |  /
         *                    \ | /
         *                     \|/
         *                      | P
         */

        var
            self = this,
            AD = Math.ceil(prevStepWidth / 2),
            BC = Math.ceil((AD * (prevStepHeight - funnel)) / prevStepHeight);

        if (renderable) {
            this.stack[iterator].x2 = prevStepWidth + prevStepWidthDelta + (options.leftMargin || 0);
            this.stack[iterator].y2 = funnelSumm;

            var x3 = Math.round(marginWidth / 2 + BC) + (options.leftMargin || 0);
            var x4 = Math.round(marginWidth / 2 - BC) + (options.leftMargin || 0);

            if (isNozzleStep) {
                x3 = this.stack[iterator].x2;
                x4 = Math.ceil(marginWidth / 2 - AD) + (options.leftMargin || 0);
            }

            this.stack[iterator].x3 = x3;
            this.stack[iterator].x4 = x4;

            this.stack[iterator].y3 =
            this.stack[iterator].y4 = (funnelSumm + funnel);

            context.lineTo(this.stack[iterator].x2, this.stack[iterator].y2); // lineTo x2y2
            context.lineTo(this.stack[iterator].x3, this.stack[iterator].y3); // lineTo x3y3
            if (this.stack[iterator].x3 != this.stack[iterator].x4) {
                context.lineTo(this.stack[iterator].x4, this.stack[iterator].y4); // lineTo x4y4
            }

            context.closePath();
            context.stroke();
            context.fill();

            self.renderLabel(context, options, label, funnelSumm, iterator, isNozzleStep);
        }

        funnelSumm += funnel;

        context.beginPath();

        var nextX = Math.ceil(marginWidth / 2 - BC) + (options.leftMargin || 0);
        if (isNozzleStep) {
            nextX = Math.ceil(marginWidth / 2 - AD) + (options.leftMargin || 0);
        }

        context.moveTo(nextX , funnelSumm);

        self.stack[iterator + 1] = {};
        self.stack[iterator + 1].x1 = nextX;
        self.stack[iterator + 1].y1 = funnelSumm;

        return {
            'prevStepWidth'     : isNozzleStep ? AD * 2 : BC * 2,
            'prevStepWidthDelta': isNozzleStep ? marginWidth / 2 - AD: marginWidth / 2 - BC,
            'prevStepHeight'    : prevStepHeight - funnel,
            'funnelSumm'        : funnelSumm
        };
    },

    renderLabel: function(context, options, label, startY, iterator, isNozzleStep) {
        var distX = (options.width - options.marginX) / 2,
            count = Object.keys(options.data).length,
            distY = (iterator == 0)
                ? options.marginY
                : this.shiftLabels
                    ? (options.height - options.marginY * 2) / (count + 1) * iterator
                    : startY,
            style = {
                size : options.fontSize * 1.2,
                color : options.fontColor,
                weight : 1.5
            };
        options.htmlText   = true;
        style.textAlign    = 'left';
        style.textBaseline = 'top';
        style.wordWrap     = 'break-word';

        var html = [],
            divStyle =
                'position:absolute;' +
                style.textBaseline + ':' + (distY - style.size)  + 'px;' +
                style.textAlign + ':' + (distX + (options.marginX + options.width)/3 + 10) + 'px;',
            labelString = isNozzleStep
                ? options.nozzleFormatter(label, this.originData[label])
                : options.tickFormatter(label, this.originData[label]);

        html.push('
', labelString, '
');

        var div = Flotr.DOM.node('

');
        Flotr.DOM.insert(div, html.join(''));
        Flotr.DOM.insert(options.element, div);

        // label line
        context.beginPath();
        context.lineWidth = 1;
        context.strokeStyle = options.fontColor;
        context.moveTo(this.stack[iterator].x2, this.stack[iterator].y2);
        context.lineTo(distX + (options.marginX + options.width)/3, distY);
        context.stroke();
    }
});
<|endoftext|>


<commit_before>    /**
     *
     * @param {bigint} id_group l'Id du groupe dont on veut importer
     * @param {array} urls les adress qui mène aux actions d'importation
     * @returns {undefined}
     */
       function importerMembres(id_group,urls){
            $("#progress").show();
           var actionActive=false;
           var nombreMembre;
           var nomGroupe;
           if (typeof(FB) !=='undefined' && FB !== null ) {
           FB.api(id_group+'?fields=members.fields(id),name&&access_token='+$.cookie('accessToken'),
           function(reponse){
               if (!reponse || reponse.error) {
            console.log("Message d'erreur "+response.error.message);
                }else{
               nomGroupe=reponse.name;
               nombreMembre=reponse.members.data.length;
      $('
',{
       html: '
 Vous allez recuperer les membres du groupe :   '+nomGroupe+'      vers votre base de données. Ce groupe contient '+
             nombreMembre+' membres . Le nombre d\'administrateur vous le saurez une fois les membres seront tous importés ',

          }).dialog({
      height: 350,
      width : 550,
      title:" Importation de membre de groupe",
      modal: true,
      close:function(){
         if(actionActive) $("#progress").show();
      },
      show: {
        effect: "clip",
        duration: 400
      },
      hide:{
          effect:"clip",
          duration: 600,

      },
      buttons: {
        " Démarer l'importation ": function() {
         var actionActive=true;

        },
        " Annuler ": function() {
          $( this ).dialog( "close" );

        }
      },open: function( event, ui ) {
          $("#progress").hide();
      }
    });
                }
           });}
      }

<commit_msg>Nouvelle version des fichies js<commit_after>    /**
     *
     * @param {bigint} id_group l'Id du groupe dont on veut importer
     * @param {array} urls les adress qui mène aux actions d'importation
     * @returns {undefined}
     */
       function importerMembres(id_group,urls){
            $("#progress").show();
           var actionActive=false;
           var nombreMembre;
           var nomGroupe;
           if (typeof(FB) !=='undefined' && FB !== null ) {
           FB.api(id_group+'?fields=members.fields(id),name&&access_token='+$.cookie('accessToken'),
           function(reponse){
               if (!reponse || reponse.error) {
            console.log("Message d'erreur "+response.error.message);
                }else{
               nomGroupe=reponse.name;
               nombreMembre=reponse.members.data.length;
      $("
",{
       html: '
 Vous allez recuperer les membres du groupe :   '+nomGroupe+' vers votre base de données. Ce groupe contient '+
             nombreMembre+' membres . Le nombre d\'administrateur vous le saurez une fois les membres seront tous importés ',

          }).dialog({
      height: 350,
      width : 550,
      title:" Importation de membre de groupe",
      modal: true,
      close:function(){
         if(actionActive) $("#progress").show();
      },
      show: {
        effect: "clip",
        duration: 400
      },
      hide:{
          effect:"clip",
          duration: 600,

      },
      buttons: {
        " Démarer l'importation ": function() {
         var actionActive=true;

        },
        " Annuler ": function() {
          $( this ).dialog( "close" );

        }
      },open: function( event, ui ) {
          $("#progress").hide();
      }
    });
                }
           });}
      }

<|endoftext|>


<commit_before>'use strict';

const http = require('http');
const { Counter, Histogram, register } = require('prom-client');
const { Transform } = require('stream');
const DEV_ENVS = ['test', 'development'];

const requestCounter = new Counter({
    name: 'sql_api_requests_total',
    help: 'SQL API requests total'
});

const requestOkCounter = new Counter({
    name: 'sql_api_requests_ok_total',
    help: 'SQL API requests ok total'
});

const requestErrorCounter = new Counter({
    name: 'sql_api_requests_errors_total',
    help: 'SQL API requests errors total'
});

const responseTimeHistogram = new Histogram({
    name: 'sql_api_response_time_total',
    help: 'SQL API response time total'
});

const userRequestCounter = new Counter({
    name: 'sql_api_requests',
    help: 'SQL API requests per user',
    labelNames: ['user', 'http_code']
});

const userRequestOkCounter = new Counter({
    name: 'sql_api_requests_ok',
    help: 'SQL API requests per user with success HTTP code',
    labelNames: ['user', 'http_code']
});

const userRequestErrorCounter = new Counter({
    name: 'sql_api_requests_errors',
    help: 'SQL API requests per user with error HTTP code',
    labelNames: ['user', 'http_code']
});

const userResponseTimeHistogram = new Histogram({
    name: 'sql_api_response_time',
    help: 'SQL API response time total',
    labelNames: ['user']
});

module.exports = function metricsCollector () {
    return new Transform({
        transform (chunk, enc, callback) {
            let entry;

            try {
                entry = JSON.parse(chunk);
                const { level, time } = entry;

                if (level === undefined && time === undefined) {
                    throw new Error('Entry log is not valid');
                }
            } catch (e) {
                if (DEV_ENVS.includes(process.env.NODE_ENV)) {
                    this.push(chunk);
                }
                return callback();
            }

            const { request, response, stats } = entry;

            if (request === undefined || response === undefined || stats === undefined) {
                this.push(chunk);
                return callback();
            }

            const { statusCode, headers } = response;
            const { 'carto-user': user } = headers;

            requestCounter.inc();

            if (statusCode !== undefined && user !== undefined) {
                userRequestCounter.labels(user, `${statusCode}`).inc();
            }

            if (statusCode >= 200 && statusCode < 400) {
                requestOkCounter.inc();
                if (user !== undefined) {
                    userRequestOkCounter.labels(user, `${statusCode}`).inc();
                }
            } else if (statusCode >= 400) {
                requestErrorCounter.inc();
                if (user !== undefined) {
                    userRequestErrorCounter.labels(user, `${statusCode}`).inc();
                }
            }

            const { response: responseTime } = stats;

            if (Number.isFinite(responseTime)) {
                responseTimeHistogram.observe(responseTime);
                userResponseTimeHistogram.labels(user).observe(responseTime);
            }

            this.push(chunk);
            callback();
        }
    });
};

const port = process.env.PORT || 9145;

http
    .createServer((req, res) => {
        res.writeHead(200, { 'Content-Type': register.contentType });
        res.end(register.metrics());
    })
    .listen(port)
    .unref();
<commit_msg>Use the right port for sql-api prometheus metrics<commit_after>'use strict';

const http = require('http');
const { Counter, Histogram, register } = require('prom-client');
const { Transform } = require('stream');
const DEV_ENVS = ['test', 'development'];

const requestCounter = new Counter({
    name: 'sql_api_requests_total',
    help: 'SQL API requests total'
});

const requestOkCounter = new Counter({
    name: 'sql_api_requests_ok_total',
    help: 'SQL API requests ok total'
});

const requestErrorCounter = new Counter({
    name: 'sql_api_requests_errors_total',
    help: 'SQL API requests errors total'
});

const responseTimeHistogram = new Histogram({
    name: 'sql_api_response_time_total',
    help: 'SQL API response time total'
});

const userRequestCounter = new Counter({
    name: 'sql_api_requests',
    help: 'SQL API requests per user',
    labelNames: ['user', 'http_code']
});

const userRequestOkCounter = new Counter({
    name: 'sql_api_requests_ok',
    help: 'SQL API requests per user with success HTTP code',
    labelNames: ['user', 'http_code']
});

const userRequestErrorCounter = new Counter({
    name: 'sql_api_requests_errors',
    help: 'SQL API requests per user with error HTTP code',
    labelNames: ['user', 'http_code']
});

const userResponseTimeHistogram = new Histogram({
    name: 'sql_api_response_time',
    help: 'SQL API response time total',
    labelNames: ['user']
});

module.exports = function metricsCollector () {
    return new Transform({
        transform (chunk, enc, callback) {
            let entry;

            try {
                entry = JSON.parse(chunk);
                const { level, time } = entry;

                if (level === undefined && time === undefined) {
                    throw new Error('Entry log is not valid');
                }
            } catch (e) {
                if (DEV_ENVS.includes(process.env.NODE_ENV)) {
                    this.push(chunk);
                }
                return callback();
            }

            const { request, response, stats } = entry;

            if (request === undefined || response === undefined || stats === undefined) {
                this.push(chunk);
                return callback();
            }

            const { statusCode, headers } = response;
            const { 'carto-user': user } = headers;

            requestCounter.inc();

            if (statusCode !== undefined && user !== undefined) {
                userRequestCounter.labels(user, `${statusCode}`).inc();
            }

            if (statusCode >= 200 && statusCode < 400) {
                requestOkCounter.inc();
                if (user !== undefined) {
                    userRequestOkCounter.labels(user, `${statusCode}`).inc();
                }
            } else if (statusCode >= 400) {
                requestErrorCounter.inc();
                if (user !== undefined) {
                    userRequestErrorCounter.labels(user, `${statusCode}`).inc();
                }
            }

            const { response: responseTime } = stats;

            if (Number.isFinite(responseTime)) {
                responseTimeHistogram.observe(responseTime);
                userResponseTimeHistogram.labels(user).observe(responseTime);
            }

            this.push(chunk);
            callback();
        }
    });
};

const port = process.env.PORT || 9144;

http
    .createServer((req, res) => {
        res.writeHead(200, { 'Content-Type': register.contentType });
        res.end(register.metrics());
    })
    .listen(port)
    .unref();
<|endoftext|>


<commit_before>/* PRs that need attention */
const moment = require("moment");

module.exports = function(options, callback) {
    if (!options.db.pull_request) {
        return callback({
            message: "There are no PRs to count",
            stack: "skipping"
        });
    }

    /* Work out how many PRs are open now */
    options.db.pull_request.find({state: "open"}, {created_at:1, comments: 1, html_url: 1, title: 1}).toArray().then(openNowPR => {
        /* give each PR a score:
           each day old it is is one point
           each comment it has is five points
         */
        let scores = openNowPR.map(pr => {
            let cre = moment(pr.created_at);
            let days = moment().diff(cre, "days");
            let score = pr.comments * 5 + days;
            return {pr: pr, score: score, created_moment: cre}
        })
        scores.sort((b,a) => a.score - b.score);

        let result = {
            title: "Open PRs sorted by urgency score (descending)",
            list: scores.map(pr => {
                return {html: '' + pr.pr.title + ''};
            })
        }
        options.templates.list(result, callback);
    }).catch(e => { callback(e); });;
}<commit_msg>Add a divider between all PRs and those after a certain date<commit_after>/* PRs that need attention */
const moment = require("moment");

module.exports = function(options, callback) {
    if (!options.db.pull_request) {
        return callback({
            message: "There are no PRs to count",
            stack: "skipping"
        });
    }

    /* Work out how many PRs are open now */
    options.db.pull_request.find({state: "open"}, {created_at:1, comments: 1, html_url: 1, title: 1}).toArray().then(openNowPR => {
        /* give each PR a score:
           each day old it is is one point
           each comment it has is five points
         */
        let scores = openNowPR.map(pr => {
            let cre = moment(pr.created_at);
            let days = moment().diff(cre, "days");
            let score = pr.comments * 5 + days;
            return {pr: pr, score: score, created_moment: cre}
        })
        scores.sort((b,a) => a.score - b.score);

        if (options.config.hoursToRespond) {
            let htr = moment().subtract(options.config.hoursToRespond, "hours");
            too_new = scores.filter((s) => { return s.created_moment >= htr; });
            scores = scores.filter((s) => { return s.created_moment < htr; });
        }

        let result = {
            title: "Open PRs sorted by urgency score (descending)",
            list: scores.map(pr => {
                return {html: '' + pr.pr.title + ''};
            })
        }

        if (options.config.hoursToRespond) {
            result.list.append({html: '
'});
            result.list.append({html: 'New PRs'});
            result.list = result.list.concat(too_new.map(pr => {
                return {html: '' + pr.pr.title + ''};
            }))
        }

        options.templates.list(result, callback);
    }).catch(e => { callback(e); });;
}<|endoftext|>


<commit_before>/* global docma, dust, hljs, $ */
/* eslint camelcase:0 */

(function () {
    'use strict';

    // ---------------------------
    // HELPER METHODS
    // ---------------------------

    function _getSymbolBadge(symbol) {
        if (!symbol) return '';

        function html(cls, title, str) {
            return '
'
                + '
' + str + '
'
                + '

'
                + '
';
        }

        if (docma.utils.isClass(symbol)) return html('diamond bg-green', 'Class', 'C');
        if (docma.utils.isNamespace(symbol)) return html('diamond bg-red', 'Namespace', 'N');
        if (docma.utils.isModule(symbol)) return html('diamond bg-pink', 'Module', 'M');
        if (docma.utils.isEnum(symbol)) return html('square bg-purple', 'Enum', 'E');
        if (docma.utils.isGlobal(symbol)) {
            if (docma.utils.isMethod(symbol)) return html('diamond bg-accent', 'Global Function', 'G');
            return html('diamond bg-red', 'Global Object', 'G');
        }
        if (docma.utils.isInner(symbol)) {
            if (docma.utils.isMethod(symbol)) return html('circle bg-gray-dark', 'Inner Method', 'M');
            return html('circle bg-gray-dark', 'Inner', 'I');
        }
        if (docma.utils.isStaticProperty(symbol)) return html('square bg-orange', 'Static Property', 'P');
        if (docma.utils.isInstanceProperty(symbol)) return html('circle bg-yellow', 'Instance Property', 'P');
        if (docma.utils.isStaticMethod(symbol)) return html('square bg-accent', 'Static Method', 'M');
        if (docma.utils.isInstanceMethod(symbol)) return html('circle bg-cyan', 'Instance Method', 'M');
        return '';
    }

    function _colorOperators(str) {
        return str.replace(/[.#~:]/g, '$&');
    }

    function _indentGetMenuItem(id, badge, symbolName, keywords) {
        var ops = /[.#~:]/,
            levels = symbolName.split(ops),
            last = levels[levels.length - 1],
            marginLeft = (levels.length - 1) * 20;
        last = symbolName.slice(-(last.length + 1)); // with operator
        return ''
            + ''
            + badge + '' + _colorOperators(last) + ''
            + ''
            + '';
    }

    // ---------------------------
    // CUSTOM DUST FILTERS
    // ---------------------------

    docma
        .addFilter('$color_ops', function (name) {
            return _colorOperators(name);
        })
        .addFilter('$dot_prop', function (name) {
            var re = /(.*)([.#~:]\w+)/g,
                match = re.exec(name);
            if (!match) {
                return '' + name + '';
            }
            return '' + _colorOperators(match[1]) + '' + _colorOperators(match[2]);
        })
        .addFilter('$author', function (symbol) {
            var authors = Array.isArray(symbol) ? symbol : (symbol.author || []);
            return authors.join(', ');
        })
        .addFilter('$type', function (symbol) {
            if (docma.utils.isConstructor(symbol)) return '';
            if (symbol.kind === 'function') {
                var returnTypes = docma.utils.getReturnTypes(symbol);
                return returnTypes ? returnTypes : '';
            }
            var types = docma.utils.getTypes(symbol);
            return types ? types : '';
        })
        .addFilter('$type_sep', function (symbol) {
            if (docma.utils.isConstructor(symbol)) return '';
            if (symbol.kind === 'function') return '⇒';
            if (symbol.kind === 'class') return ':';
            if (!symbol.type && !symbol.returns) return '';
            return ':';
        })
        .addFilter('$param_desc', function (param) {
            var str = !param.optional
                ? 'Required '
                : '';
            str += param.description;
            return docma.utils.parse(str);
        })
        .addFilter('$longname', function (symbol) {
            if (typeof symbol === 'string') return symbol;
            var nw = docma.utils.isConstructor(symbol) ? 'new ' : '';
            return nw + symbol.$longname; // docma.utils.getFullName(symbol);
        })
        .addFilter('$longname_params', function (symbol) {
            var isCon = docma.utils.isConstructor(symbol),
                longName = _colorOperators(symbol.$longname); // docma.utils.getFullName(symbol);
            if (symbol.kind === 'function' || isCon) {
                var defVal,
                    defValHtml = '',
                    nw = isCon ? 'new ' : '',
                    name = nw + longName + '(';
                if (Array.isArray(symbol.params)) {
                    var params = symbol.params.reduce(function (memo, param) {
                        // ignore params such as options.<property>
                        if (param.name.indexOf('.') === -1) {
                            defVal = param.hasOwnProperty('defaultvalue') ? String(param.defaultvalue) : 'undefined';
                            defValHtml = param.optional
                                ? '=' + defVal + ''
                                : '';
                            memo.push(param.name + defValHtml);
                        }
                        return memo;
                    }, []).join(', ');
                    name += params;
                }
                return name + ')';
            }
            return longName;
        })
        .addFilter('$extends', function (symbol) {
            var ext = Array.isArray(symbol) ? symbol : symbol.augments;
            return docma.utils.listType(ext);
        })
        .addFilter('$returns', function (symbol) {
            var returns = Array.isArray(symbol) ? symbol : symbol.returns;
            return docma.utils.listTypeDesc(returns);
        })
        .addFilter('$exceptions', function (symbol) {
            var exceptions = Array.isArray(symbol) ? symbol : symbol.exceptions;
            return docma.utils.listTypeDesc(exceptions);
        })
        // non-standard JSDoc directives are stored in `.tags` property of a
        // symbol. We also add other properties such as .access (if not public),
        // `.readonly` or `.kind=namespace` as tags.
        .addFilter('$tags', function (symbol) {
            var open = '',
                open2 = '',
                open3 = '',
                open4 = '',
                open5 = '',
                open6 = '',
                close = '',
                tagBoxes = [];

            if (docma.utils.isDeprecated(symbol)) {
                tagBoxes.push(open6 + 'deprecated' + close);
            }
            if (docma.utils.isGlobal(symbol) && !docma.utils.isConstructor(symbol)) {
                tagBoxes.push(open + 'global' + close);
            }
            if (docma.utils.isStatic(symbol)) {
                tagBoxes.push(open5 + 'static' + close);
            }
            if (docma.utils.isPublic(symbol) === false) {
                tagBoxes.push(open4 + symbol.access + close);
            }
            if (docma.utils.isNamespace(symbol)) {
                tagBoxes.push(open + 'namespace' + close);
            }
            if (docma.utils.isReadOnly(symbol)) {
                tagBoxes.push(open3 + 'readonly' + close);
            }

            var tags = Array.isArray(symbol) ? symbol : symbol.tags || [],
                tagTitles = tags.map(function (tag) {
                    return open2 + tag.originalTitle + close;
                });
            tagBoxes = tagBoxes.concat(tagTitles);
            if (tagBoxes.length) return '  ' + tagBoxes.join(' ');
            return '';
        })
        .addFilter('$menuitem', function (symbolName) {
            var docs = docma.documentation,
                symbol = docma.utils.getSymbolByName(docs, symbolName);
            if (!symbol) return symbolName;
            var id = dust.filters.$id(symbol),
                keywords = docma.utils.getKeywords(symbol),
                badge = docma.template.options.badges
                    ? _getSymbolBadge(symbol)
                    : '• ';

            if (docma.template.options.outline === 'tree') {
                return _indentGetMenuItem(id, badge, symbolName, keywords);
            }
            // docma.template.options.outline === 'flat'
            var name = '' + dust.filters.$dot_prop(symbolName) + '';
            return '' + badge + name + '';

        });

    // ---------------------------
    // INITIALIZATION
    // ---------------------------

    // http://highlightjs.readthedocs.org/en/latest/api.html#configure-options
    hljs.configure({
        tabReplace: '    ',
        useBR: false
    });

    var menuItems, btnClean, txtSearch;

    function filterMenuItems() {
        var search = txtSearch.val().trim().toLowerCase();
        if (search === '') {
            menuItems.show();
            btnClean.hide();
            return;
        }
        btnClean.show();
        var keywords;
        menuItems.each(function () {
            keywords = $(this).attr('data-keywords');
            if (keywords.indexOf(search) < 0) {
                $(this).hide();
            } else {
                $(this).show();
            }
        });
    }

    // for sidebar items
    var minFontSize = 10,
        maxFontSize = 14;
    function setFontSize($el) {
        var f = maxFontSize;
        while ($el.width() > 215 && f >= minFontSize) {
            f--;
            $el.css('font-size', f + 'px');
        }
    }

    if (!docma.template.options.title) {
        docma.template.options.title = docma.app.title || 'Documentation';
    }

    docma.on('render', function (currentRoute) {

        $('[data-toggle="tooltip"]').tooltip({
            container: 'body',
            placement: 'bottom'
        });

        if (!docma.template.options.navbar) {
            // remove the gap created for navbar
            $('body, html').css('padding', 0);
            // remove sidbar top spacing
            $('#sidebar-wrapper').css('margin-top', 0);
            // since navbar is disabled, also remove the spacing set for
            // preventing navbar overlap with bookmark'ed symbol title.
            $('.symbol-container').css({
                'padding-top': 0,
                'margin-top': 0
            });
        }

        if (docma.currentRoute && docma.currentRoute.type === 'api') {
            if (docma.template.options.search) {
                menuItems = $('ul.sidebar-nav .sidebar-item');
                btnClean = $('.sidebar-search-clean');
                txtSearch = $('#txt-search');

                btnClean.hide();
                txtSearch.on('keyup', filterMenuItems);
                txtSearch.on('change', filterMenuItems);

                btnClean.on('click', function () {
                    txtSearch.val('').focus();
                    menuItems.show();
                    btnClean.hide();
                });
            } else {
                $('.sidebar-nav').css('top', '65px');
            }

            // Adjust font-size of each sidebar item's label so that they are
            // not cropped.
            $('.sidebar-nav .item-label').each(function () {
                setFontSize($(this));
            });
        }

        var pageContentRow = $('#page-content-wrapper').find('.row').first();
        if (docma.template.options.sidebar) {
            if (docma.template.options.collapsed) {
                $('#wrapper').addClass('toggled');
            }
            $('.sidebar-toggle').click(function (event) {
                event.preventDefault();
                $('#wrapper').toggleClass('toggled');
                // add some extra spacing if navbar is disabled; to prevent top
                // left toggle button to overlap with content.
                if (!docma.template.options.navbar) {
                    var marginLeft = $('#wrapper').hasClass('toggled')
                        ? '+=30px' : '-=30px';
                    // pageContentRow.css('margin-left', marginLeft);
                    pageContentRow.animate({
                        'margin-left': marginLeft
                    }, 300);
                }
            });
        } else {
            // collapse the sidebar since it's disabled
            $('#wrapper').addClass('toggled');
        }

        var brandMargin = 50,
            brandHPadding = 15;
        // For the JSDoc API documentation, our template partials already have
        // styles. So we'll style only some type of elements in other HTML
        // content.
        if (!docma.currentRoute || docma.currentRoute.type !== 'api') {
            // We'll add the template's modified bootstrap table classes
            $('table').addClass('table table-striped table-bordered');

            // code blocks in markdown files (e.g. ```js) are converted into
            // <code class="lang-js">. we'll add classes for hljs for proper
            // highlighting. e.g. for javascript, hljs requires class="js". So
            // this will be class="lang-js js".

            // this seems unnecessary. somehow, hljs detects it.
            // $("code[class^='lang-']").each(function () {
            //     var cls = $(this).attr('class'),
            //         m = cls.match(/lang\-([^ ]+)/)[1];
            //     if (m) $(this).addClass(m);
            // });

            // also adjust navbar-brand margin
            brandMargin = 0;
            brandHPadding = 0;
        }
        $('.navbar-brand').css({
            'margin-left': brandMargin + 'px',
            'padding-left': brandHPadding + 'px',
            'padding-right': brandHPadding + 'px'
        });

        // Syntax-Highlight code examples
        var examples = $('#docma-main pre > code');
        examples.each(function (i, block) {
            hljs.highlightBlock(block);
        });

    });

})();
<commit_msg>minor<commit_after>/* global docma, dust, hljs, $ */
/* eslint camelcase:0, no-nested-ternary:0, max-depth:0, no-var:0, prefer-template:0, prefer-arrow-callback:0, prefer-spread:0, object-shorthand:0 */

(function () {
    'use strict';

    // ---------------------------
    // HELPER METHODS
    // ---------------------------

    function _getSymbolBadge(symbol) {
        if (!symbol) return '';

        function html(cls, title, str) {
            return '<div class="item-badge" title="' + title + '">'
                + '<div class="badge-label">' + str + '</div>'
                + '<div class="badge-shape ' + cls + '"></div>'
                + '</div>';
        }

        if (docma.utils.isClass(symbol)) return html('diamond bg-green', 'Class', 'C');
        if (docma.utils.isNamespace(symbol)) return html('diamond bg-red', 'Namespace', 'N');
        if (docma.utils.isModule(symbol)) return html('diamond bg-pink', 'Module', 'M');
        if (docma.utils.isEnum(symbol)) return html('square bg-purple', 'Enum', 'E');
        if (docma.utils.isGlobal(symbol)) {
            if (docma.utils.isMethod(symbol)) return html('diamond bg-accent', 'Global Function', 'G');
            return html('diamond bg-red', 'Global Object', 'G');
        }
        if (docma.utils.isInner(symbol)) {
            if (docma.utils.isMethod(symbol)) return html('circle bg-gray-dark', 'Inner Method', 'M');
            return html('circle bg-gray-dark', 'Inner', 'I');
        }
        if (docma.utils.isStaticProperty(symbol)) return html('square bg-orange', 'Static Property', 'P');
        if (docma.utils.isInstanceProperty(symbol)) return html('circle bg-yellow', 'Instance Property', 'P');
        if (docma.utils.isStaticMethod(symbol)) return html('square bg-accent', 'Static Method', 'M');
        if (docma.utils.isInstanceMethod(symbol)) return html('circle bg-cyan', 'Instance Method', 'M');
        return '';
    }

    function _colorOperators(str) {
        return str.replace(/[.#~:]/g, '<span class="color-blue">$&</span>');
    }

    function _indentGetMenuItem(id, badge, symbolName, keywords) {
        var ops = /[.#~:]/,
            levels = symbolName.split(ops),
            last = levels[levels.length - 1],
            marginLeft = (levels.length - 1) * 20;
        last = symbolName.slice(-(last.length + 1)); // with operator
        return '<a href="#' + id + '" class="sidebar-item" data-keywords="' + keywords + '">'
            + '<span class="inline-block" style="margin-left:' + marginLeft + 'px">'
            + badge + '<span class="item-label">' + _colorOperators(last) + '</span>'
            + '</span>'
            + '</a>';
    }

    // ---------------------------
    // CUSTOM DUST FILTERS
    // ---------------------------

    docma
        .addFilter('$color_ops', function (name) {
            return _colorOperators(name);
        })
        .addFilter('$dot_prop', function (name) {
            var re = /(.*)([.#~:]\w+)/g,
                match = re.exec(name);
            if (!match) {
                return '<b>' + name + '</b>';
            }
            return '<span class="color-gray">' + _colorOperators(match[1]) + '</span>' + _colorOperators(match[2]);
        })
        .addFilter('$author', function (symbol) {
            var authors = Array.isArray(symbol) ? symbol : (symbol.author || []);
            return authors.join(', ');
        })
        .addFilter('$type', function (symbol) {
            if (docma.utils.isConstructor(symbol)) return '';
            if (symbol.kind === 'function') {
                var returnTypes = docma.utils.getReturnTypes(symbol);
                return returnTypes ? returnTypes : '';
            }
            var types = docma.utils.getTypes(symbol);
            return types ? types : '';
        })
        .addFilter('$type_sep', function (symbol) {
            if (docma.utils.isConstructor(symbol)) return '';
            if (symbol.kind === 'function') return '⇒';
            if (symbol.kind === 'class') return ':';
            if (!symbol.type && !symbol.returns) return '';
            return ':';
        })
        .addFilter('$param_desc', function (param) {
            var str = !param.optional
                ? '<span class="boxed bg-red">Required</span> '
                : '';
            str += param.description;
            return docma.utils.parse(str);
        })
        .addFilter('$longname', function (symbol) {
            if (typeof symbol === 'string') return symbol;
            var nw = docma.utils.isConstructor(symbol) ? 'new ' : '';
            return nw + symbol.$longname; // docma.utils.getFullName(symbol);
        })
        .addFilter('$longname_params', function (symbol) {
            var isCon = docma.utils.isConstructor(symbol),
                longName = _colorOperators(symbol.$longname); // docma.utils.getFullName(symbol);
            if (symbol.kind === 'function' || isCon) {
                var defVal,
                    defValHtml = '',
                    nw = isCon ? 'new ' : '',
                    name = nw + longName + '(';
                if (Array.isArray(symbol.params)) {
                    var params = symbol.params.reduce(function (memo, param) {
                        // ignore params such as options.<property>
                        if (param.name.indexOf('.') === -1) {
                            defVal = param.hasOwnProperty('defaultvalue') ? String(param.defaultvalue) : 'undefined';
                            defValHtml = param.optional
                                ? '<span class="def-val">=' + defVal + '</span>'
                                : '';
                            memo.push(param.name + defValHtml);
                        }
                        return memo;
                    }, []).join(', ');
                    name += params;
                }
                return name + ')';
            }
            return longName;
        })
        .addFilter('$extends', function (symbol) {
            var ext = Array.isArray(symbol) ? symbol : symbol.augments;
            return docma.utils.listType(ext);
        })
        .addFilter('$returns', function (symbol) {
            var returns = Array.isArray(symbol) ? symbol : symbol.returns;
            return docma.utils.listTypeDesc(returns);
        })
        .addFilter('$exceptions', function (symbol) {
            var exceptions = Array.isArray(symbol) ? symbol : symbol.exceptions;
            return docma.utils.listTypeDesc(exceptions);
        })
        // non-standard JSDoc directives are stored in `.tags` property of a
        // symbol. We also add other properties such as .access (if not public),
        // `.readonly` or `.kind=namespace` as tags.
        .addFilter('$tags', function (symbol) {
            var open = '<span class="boxed vertical-middle bg-ice opacity-full">',
                open2 = '<span class="boxed vertical-middle bg-ice-mid opacity-full">',
                open3 = '<span class="boxed vertical-middle">',
                open4 = '<span class="boxed vertical-middle bg-ice-dark opacity-full">',
                open5 = '<span class="boxed vertical-middle bg-blue opacity-full">',
                open6 = '<span class="boxed vertical-middle bg-warning color-brown opacity-full">',
                close = '</span>',
                tagBoxes = [];

            if (docma.utils.isDeprecated(symbol)) {
                tagBoxes.push(open6 + 'deprecated' + close);
            }
            if (docma.utils.isGlobal(symbol) && !docma.utils.isConstructor(symbol)) {
                tagBoxes.push(open + 'global' + close);
            }
            if (docma.utils.isStatic(symbol)) {
                tagBoxes.push(open5 + 'static' + close);
            }
            if (docma.utils.isPublic(symbol) === false) {
                tagBoxes.push(open4 + symbol.access + close);
            }
            if (docma.utils.isNamespace(symbol)) {
                tagBoxes.push(open + 'namespace' + close);
            }
            if (docma.utils.isReadOnly(symbol)) {
                tagBoxes.push(open3 + 'readonly' + close);
            }

            var tags = Array.isArray(symbol) ? symbol : symbol.tags || [],
                tagTitles = tags.map(function (tag) {
                    return open2 + tag.originalTitle + close;
                });
            tagBoxes = tagBoxes.concat(tagTitles);
            if (tagBoxes.length) return '  ' + tagBoxes.join(' ');
            return '';
        })
        .addFilter('$menuitem', function (symbolName) {
            var docs = docma.documentation,
                symbol = docma.utils.getSymbolByName(docs, symbolName);
            if (!symbol) return symbolName;
            var id = dust.filters.$id(symbol),
                keywords = docma.utils.getKeywords(symbol),
                badge = docma.template.options.badges
                    ? _getSymbolBadge(symbol)
                    : '• ';

            if (docma.template.options.outline === 'tree') {
                return _indentGetMenuItem(id, badge, symbolName, keywords);
            }
            // docma.template.options.outline === 'flat'
            var name = '<span class="item-label">' + dust.filters.$dot_prop(symbolName) + '</span>';
            return '<a href="#' + id + '" class="sidebar-item" data-keywords="' + keywords + '">' + badge + name + '</a>';

        });

    // ---------------------------
    // INITIALIZATION
    // ---------------------------

    // http://highlightjs.readthedocs.org/en/latest/api.html#configure-options
    hljs.configure({
        tabReplace: '    ',
        useBR: false
    });

    var menuItems, btnClean, txtSearch;

    function filterMenuItems() {
        var search = txtSearch.val().trim().toLowerCase();
        if (search === '') {
            menuItems.show();
            btnClean.hide();
            return;
        }
        btnClean.show();
        var keywords;
        menuItems.each(function () {
            keywords = $(this).attr('data-keywords');
            if (keywords.indexOf(search) < 0) {
                $(this).hide();
            } else {
                $(this).show();
            }
        });
    }

    // for sidebar items
    var minFontSize = 10,
        maxFontSize = 14;
    function setFontSize($el) {
        var f = maxFontSize;
        while ($el.width() > 215 && f >= minFontSize) {
            f--;
            $el.css('font-size', f + 'px');
        }
    }

    if (!docma.template.options.title) {
        docma.template.options.title = docma.app.title || 'Documentation';
    }

    docma.on('render', function (currentRoute) {

        $('[data-toggle="tooltip"]').tooltip({
            container: 'body',
            placement: 'bottom'
        });

        if (!docma.template.options.navbar) {
            // remove the gap created for navbar
            $('body, html').css('padding', 0);
            // remove sidbar top spacing
            $('#sidebar-wrapper').css('margin-top', 0);
            // since navbar is disabled, also remove the spacing set for
            // preventing navbar overlap with bookmark'ed symbol title.
            $('.symbol-container').css({
                'padding-top': 0,
                'margin-top': 0
            });
        }

        if (docma.currentRoute && docma.currentRoute.type === 'api') {
            if (docma.template.options.search) {
                menuItems = $('ul.sidebar-nav .sidebar-item');
                btnClean = $('.sidebar-search-clean');
                txtSearch = $('#txt-search');

                btnClean.hide();
                txtSearch.on('keyup', filterMenuItems);
                txtSearch.on('change', filterMenuItems);

                btnClean.on('click', function () {
                    txtSearch.val('').focus();
                    menuItems.show();
                    btnClean.hide();
                });
            } else {
                $('.sidebar-nav').css('top', '65px');
            }

            // Adjust font-size of each sidebar item's label so that they are
            // not cropped.
            $('.sidebar-nav .item-label').each(function () {
                setFontSize($(this));
            });
        }

        var pageContentRow = $('#page-content-wrapper').find('.row').first();
        if (docma.template.options.sidebar) {
            if (docma.template.options.collapsed) {
                $('#wrapper').addClass('toggled');
            }
            $('.sidebar-toggle').click(function (event) {
                event.preventDefault();
                $('#wrapper').toggleClass('toggled');
                // add some extra spacing if navbar is disabled; to prevent top
                // left toggle button to overlap with content.
                if (!docma.template.options.navbar) {
                    var marginLeft = $('#wrapper').hasClass('toggled')
                        ? '+=30px' : '-=30px';
                    // pageContentRow.css('margin-left', marginLeft);
                    pageContentRow.animate({
                        'margin-left': marginLeft
                    }, 300);
                }
            });
        } else {
            // collapse the sidebar since it's disabled
            $('#wrapper').addClass('toggled');
        }

        var brandMargin = 50,
            brandHPadding = 15;
        // For the JSDoc API documentation, our template partials already have
        // styles. So we'll style only some type of elements in other HTML
        // content.
        if (!docma.currentRoute || docma.currentRoute.type !== 'api') {
            // We'll add the template's modified bootstrap table classes
            $('table').addClass('table table-striped table-bordered');

            // code blocks in markdown files (e.g. ```js) are converted into
            // . we'll add classes for hljs for proper
            // highlighting. e.g. for javascript, hljs requires class="js". So
            // this will be class="lang-js js".

            // this seems unnecessary. somehow, hljs detects it.
            // $("code[class^='lang-']").each(function () {
            //     var cls = $(this).attr('class'),
            //         m = cls.match(/lang\-([^ ]+)/)[1];
            //     if (m) $(this).addClass(m);
            // });

            // also adjust navbar-brand margin
            brandMargin = 0;
            brandHPadding = 0;
        }
        $('.navbar-brand').css({
            'margin-left': brandMargin + 'px',
            'padding-left': brandHPadding + 'px',
            'padding-right': brandHPadding + 'px'
        });

        // Syntax-Highlight code examples
        var examples = $('#docma-main pre > code');
        examples.each(function (i, block) {
            hljs.highlightBlock(block);
        });

    });

})();
<|endoftext|>


<commit_before>'use strict';
const _ = require('lodash');
const path = require('path');
const bulk = require('bulk-require');
const lib_p = bulk(path.normalize(__dirname+'/..'), ['parsers/**/*.js', '**/*.js']);
const cheerio = require('cheerio');
const parsers = lib_p.parsers;

module.exports = function(elem) {
    // console.log(elem.name);
    let parser, txt_cnt;
    // looking for a static parser by name? Then return it
    if (_.isString(elem)) {
        return parsers[elem] || null;
    }

    if (elem.name) {
        if (parsers[elem.name]) {
            // return appropriate parser function
            parser = parsers[elem.name];
            if (elem.name === 'blockquote' && elem.attribs.class && (elem.attribs.class.indexOf('twitter-tweet') > -1 || elem.attribs.class.indexOf('instagram-media') > -1)) {
            	parser = parsers['oembed'];
            }
            // iframe inside p or div
            if(elem.name === 'p' || elem.name === 'div'){
                let $ = cheerio.load(elem);
                let $elem = $(elem);
                if($elem.children().length ){ // video embeds, youtube vimeo

                    if ($elem.children().get(0).tagName === 'iframe'){
                        parser = parsers['oembed'];
                    }

                } else{
                    // console.log('output text node');
                    // console.log('output text node: '+$(elem).contents());
                    // find out if there are other types of content like external embed
                    txt_cnt =  $(elem).text();
                    if(txt_cnt){

                        if(txt_cnt.match(/^(\[external_embed\s)(.+)(\s*\])$/i)){
                            // console.log(txt_cnt);
                            parser = parsers['externalEmbed'];
                        }
                    }
                }

            }

        } else {

            if (elem.name.match(/^h\d$/)) {
                parser = parsers['header'];
            } else if (elem.name.match(/^(o|u)l$/)) {
                parser = parsers['list'];
            } else if(elem.name.match(/div/) && elem.attribs.class && (elem.attribs.class.indexOf('posttv-video-embed') > -1 )) {
                parser = parsers['oembed'];
            } else {
                parser = parsers['rawhtml'];
            }
        }
        return parser;
    }
    return null;

};
<commit_msg>add default rawhtml parser<commit_after>'use strict';
const _ = require('lodash');
const path = require('path');
const bulk = require('bulk-require');
const lib_p = bulk(path.normalize(__dirname + '/..'), ['parsers/**/*.js', '**/*.js']);
const cheerio = require('cheerio');
const parsers = lib_p.parsers;

module.exports = function(elem) {
    // console.log(elem.name);
    let parser = parsers['rawhtml'], // default
        txt_cnt;
    // looking for a static parser by name? Then return it
    if (_.isString(elem)) {
        // return parsers[elem] || null;
        parser = parsers[elem];
    }

    if (elem.name) {
        if (parsers[elem.name]) {
            // return appropriate parser function
            parser = parsers[elem.name];
            if (elem.name === 'blockquote' && elem.attribs.class && (elem.attribs.class.indexOf('twitter-tweet') > -1 || elem.attribs.class.indexOf('instagram-media') > -1)) {
                parser = parsers['oembed'];
            }
            // iframe inside p or div
            if (elem.name === 'p' || elem.name === 'div') {
                let $ = cheerio.load(elem);
                let $elem = $(elem);
                if ($elem.children().length) { // video embeds, youtube vimeo

                    if ($elem.children().get(0).tagName === 'iframe') {
                        parser = parsers['oembed'];
                    }

                } else {
                    // console.log('output text node');
                    // console.log('output text node: '+$(elem).contents());
                    // find out if there are other types of content like external embed
                    txt_cnt = $(elem).text();
                    if (txt_cnt) {

                        if (txt_cnt.match(/^(\[external_embed\s)(.+)(\s*\])$/i)) {
                            // console.log(txt_cnt);
                            parser = parsers['externalEmbed'];
                        }
                    }
                }

            }

        } else {

            if (elem.name.match(/^h\d$/)) {
                parser = parsers['header'];
            } else if (elem.name.match(/^(o|u)l$/)) {
                parser = parsers['list'];
            } else if (elem.name.match(/div/) && elem.attribs.class && (elem.attribs.class.indexOf('posttv-video-embed') > -1)) {
                parser = parsers['oembed'];
            } else if (elem.name.match(/div/) && elem.attribs.class && (elem.attribs.class.indexOf('external-game-embed') > -1)) {
                parser = parsers['oembed'];
            } else {
                parser = parsers['rawhtml'];
            }
        }

    }
    return parser;

};
<|endoftext|>


<commit_before>// Dependencies
var assert = require('assert');
var gutil = require('gulp-util');
var through2 = require('through2');

var cssSpriteSmith = require('css-spritesmith');

// Default options
var defautlOptions = cssSpriteSmith.defautlOptions;

function gulpCssSprite(options) {
    options = options || {};
    for(var k in defautlOptions) {
        if(options[k] === undefined) {
            options[k] = defautlOptions[k];
        }
    }

    assert(options.imagepath, 'An `imagepath` parameter was not provided');
    assert(options.spritedest, 'An `spritedest` parameter was not provided');

    function onData(file, encoding, cb) {
        var self = this;
        var filepath = file.path;

        if(!filepath) {
            return cb();
        }

        options.cssfile = filepath;

        cssSpriteSmith(options, function(err, data) {
            if(err) {
                return cb(err);
            }

            if(data.cssData === null) {
                return cb();
            }

            var cssFile = new gutil.File({
                contents: new Buffer(data.cssData),
                path: filepath
            });
            self.push(cssFile);

            // sprite file
            var spriteData = data.spriteData;
            var spriteFile = new gutil.File({
                contents: new Buffer(spriteData.image, 'binary'),
                path: spriteData.imagePath
            });
            self.push(spriteFile);

            var retinaSpriteData = data.retinaSpriteData;
            if(retinaSpriteData) {
                var retinaSpriteFile = new gutil.File({
                    contents: new Buffer(retinaSpriteData.image, 'binary'),
                    path: retinaSpriteData.imagePath
                });
                self.push(retinaSpriteFile);
            }

            cb();
        });
    }

    var retStream = through2.obj(onData);

    return retStream;
}

module.exports = gulpCssSprite;
<commit_msg>bug fix: not surpport gulp.src(glob,{base:'***'})<commit_after>// Dependencies
var assert = require('assert');
var gutil = require('gulp-util');
var through2 = require('through2');

var cssSpriteSmith = require('css-spritesmith');

// Default options
var defautlOptions = cssSpriteSmith.defautlOptions;

function gulpCssSprite(options) {
    options = options || {};
    for(var k in defautlOptions) {
        if(options[k] === undefined) {
            options[k] = defautlOptions[k];
        }
    }

    assert(options.imagepath, 'An `imagepath` parameter was not provided');
    assert(options.spritedest, 'An `spritedest` parameter was not provided');

    function onData(file, encoding, cb) {
        var self = this;
        var filepath = file.path;

        if(!filepath) {
            return cb();
        }

        options.cssfile = filepath;

        cssSpriteSmith(options, function(err, data) {
            if(err) {
                return cb(err);
            }

            if(data.cssData === null) {
                return cb();
            }

            var cssFile = new gutil.File({
                contents: new Buffer(data.cssData),
                path: filepath
            });
            self.push(cssFile);

            // sprite file
            var spriteData = data.spriteData;
            var spriteFile = new gutil.File({
                contents: new Buffer(spriteData.image, 'binary'),
                path: spriteData.imagePath,
                base:file.base
            });
            self.push(spriteFile);

            var retinaSpriteData = data.retinaSpriteData;
            if(retinaSpriteData) {
                var retinaSpriteFile = new gutil.File({
                    contents: new Buffer(retinaSpriteData.image, 'binary'),
                    path: retinaSpriteData.imagePath
                });
                self.push(retinaSpriteFile);
            }

            cb();
        });
    }

    var retStream = through2.obj(onData);

    return retStream;
}

module.exports = gulpCssSprite;
<|endoftext|>


<commit_before>goog.require("goog.inherits");
goog.require("goog.base");

(function(){

	/**
	 * An implementation of Animatable
	 * @constructor
	 * @implements Animatable
	 * @extends ClientMoveable
	 */
	var ClientAnimatable = function(obj, transform, constraint){

		//call parent constructor here
		goog.base(this ,obj, transform, constraint);

		/**
		 * List of KeyframeAnimations
		 * @private
		 * @type {Array.<KeyframeAnimation>}
		 */
		this.availableAnimations = {};
		/**
		 * Map of active KeyframeAnimations
		 * Note: This works since the IDs are only numbers.
		 * Those numbers are turned into strings  and those are used as keys.
		 * @private
		 * @type {number}
		 */
		this.activeAnimations = {};
		/**
		 * Counter of IDs for active animations
		 * Attention: this might turn to infinity
		 * @private
		 * @type {number}
		 */
		this.idCounter = 0;
	};

	//inheritence is done here
	goog.inherits(ClientAnimatable, XMOT.ClientMoveable);

    var a = ClientAnimatable.prototype;

    /** @inheritDoc */
    a.addAnimation = function(animation){
		this.availableAnimations[animation.name] = animation;
    };

    /** @inheritDoc */
    a.startAnimation = function(name, opt){
		var toStart = this.availableAnimations[name];
		var id = this.idCounter;
		this.idCounter++;
		this.activeAnimations[id] = toStart;
		toStart.start(this, opt);
		return id;
    };

    /** @inheritDoc */
    a.stopAnimation = function(id){
		var toStop = this.activeAnimations[id];
		//TODO: this stops every(!) animation not just the one with id
		if(toStop) this.stop();
		return this;
    };

    //export
	XMOT.ClientAnimatable = ClientAnimatable;

}());<commit_msg>Cosmetic change<commit_after>goog.require("goog.inherits");
goog.require("goog.base");

(function(){

	/**
	 * An implementation of Animatable
	 * @constructor
	 * @implements Animatable
	 * @extends ClientMoveable
	 */
	var ClientAnimatable = function(obj, transform, constraint){

		//call parent constructor here
		goog.base(this, obj, transform, constraint);

		/**
		 * List of KeyframeAnimations
		 * @private
		 * @type {Array.<KeyframeAnimation>}
		 */
		this.availableAnimations = {};
		/**
		 * Map of active KeyframeAnimations
		 * Note: This works since the IDs are only numbers.
		 * Those numbers are turned into strings  and those are used as keys.
		 * @private
		 * @type {number}
		 */
		this.activeAnimations = {};
		/**
		 * Counter of IDs for active animations
		 * Attention: this might turn to infinity
		 * @private
		 * @type {number}
		 */
		this.idCounter = 0;
	};

	//inheritence is done here
	goog.inherits(ClientAnimatable, XMOT.ClientMoveable);

    var a = ClientAnimatable.prototype;

    /** @inheritDoc */
    a.addAnimation = function(animation){
		this.availableAnimations[animation.name] = animation;
    };

    /** @inheritDoc */
    a.startAnimation = function(name, opt){
		var toStart = this.availableAnimations[name];
		var id = this.idCounter;
		this.idCounter++;
		this.activeAnimations[id] = toStart;
		toStart.start(this, opt);
		return id;
    };

    /** @inheritDoc */
    a.stopAnimation = function(id){
		var toStop = this.activeAnimations[id];
		//TODO: this stops every(!) animation not just the one with id
		if(toStop) this.stop();
		return this;
    };

    //export
	XMOT.ClientAnimatable = ClientAnimatable;

}());<|endoftext|>