text:
/*
 * Chartkick.js
 * Create beautiful JavaScript charts with minimal code
 * https://github.com/ankane/chartkick.js
 * v2.1.0
 * MIT License
 */

/*jslint browser: true, indent: 2, plusplus: true, vars: true */

(function (window) {
  'use strict';

  var config = window.Chartkick || {};
  var Chartkick, ISO8601_PATTERN, DECIMAL_SEPARATOR, adapters = [];
  var DATE_PATTERN = /^(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)$/i;
  var GoogleChartsAdapter, HighchartsAdapter, ChartjsAdapter;

  // helpers

  function isArray(variable) {
    return Object.prototype.toString.call(variable) === "[object Array]";
  }

  function isFunction(variable) {
    return variable instanceof Function;
  }

  function isPlainObject(variable) {
    return !isFunction(variable) && variable instanceof Object;
  }

  // https://github.com/madrobby/zepto/blob/master/src/zepto.js
  function extend(target, source) {
    var key;
    for (key in source) {
      if (isPlainObject(source[key]) || isArray(source[key])) {
        if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
          target[key] = {};
        }
        if (isArray(source[key]) && !isArray(target[key])) {
          target[key] = [];
        }
        extend(target[key], source[key]);
      } else if (source[key] !== undefined) {
        target[key] = source[key];
      }
    }
  }

  function merge(obj1, obj2) {
    var target = {};
    extend(target, obj1);
    extend(target, obj2);
    return target;
  }

  // https://github.com/Do/iso8601.js
  ISO8601_PATTERN = /(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)?(:)?(\d\d)?([\.,]\d+)?($|Z|([\+\-])(\d\d)(:)?(\d\d)?)/i;
  DECIMAL_SEPARATOR = String(1.5).charAt(1);

  function parseISO8601(input) {
    var day, hour, matches, milliseconds, minutes, month, offset, result, seconds, type, year;
    type = Object.prototype.toString.call(input);
    if (type === "[object Date]") {
      return input;
    }
    if (type !== "[object String]") {
      return;
    }
    matches = input.match(ISO8601_PATTERN);
    if (matches) {
      year = parseInt(matches[1], 10);
      month = parseInt(matches[3], 10) - 1;
      day = parseInt(matches[5], 10);
      hour = parseInt(matches[7], 10);
      minutes = matches[9] ? parseInt(matches[9], 10) : 0;
      seconds = matches[11] ? parseInt(matches[11], 10) : 0;
      milliseconds = matches[12] ? parseFloat(DECIMAL_SEPARATOR + matches[12].slice(1)) * 1000 : 0;
      result = Date.UTC(year, month, day, hour, minutes, seconds, milliseconds);
      if (matches[13] && matches[14]) {
        offset = matches[15] * 60;
        if (matches[17]) {
          offset += parseInt(matches[17], 10);
        }
        offset *= matches[14] === "-" ? -1 : 1;
        result -= offset * 60 * 1000;
      }
      return new Date(result);
    }
  }
  // end iso8601.js

  function negativeValues(series) {
    var i, j, data;
    for (i = 0; i < series.length; i++) {
      data = series[i].data;
      for (j = 0; j < data.length; j++) {
        if (data[j][1] < 0) {
          return true;
        }
      }
    }
    return false;
  }

  function jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle) {
    return function (series, opts, chartOptions) {
      var options = merge({}, defaultOptions);
      options = merge(options, chartOptions || {});

      // hide legend
      // this is *not* an external option!
      if (opts.hideLegend) {
        hideLegend(options);
      }

      // min
      if ("min" in opts) {
        setMin(options, opts.min);
      } else if (!negativeValues(series)) {
        setMin(options, 0);
      }

      // max
      if (opts.max) {
        setMax(options, opts.max);
      }

      if ("stacked" in opts) {
        setStacked(options, opts.stacked);
      }

      if (opts.colors) {
        options.colors = opts.colors;
      }

      if (opts.xtitle) {
        setXtitle(options, opts.xtitle);
      }

      if (opts.ytitle) {
        setYtitle(options, opts.ytitle);
      }

      // merge library last
      options = merge(options, opts.library || {});

      return options;
    };
  }

  function setText(element, text) {
    if (document.body.innerText) {
      element.innerText = text;
    } else {
      element.textContent = text;
    }
  }

  function chartError(element, message) {
    setText(element, "Error Loading Chart: " + message);
    element.style.color = "#ff0000";
  }

  function getJSON(element, url, success) {
    ajaxCall(url, success, function (jqXHR, textStatus, errorThrown) {
      var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message;
      chartError(element, message);
    });
  }

  function ajaxCall(url, success, error) {
    var $ = window.jQuery || window.Zepto || window.$;

    if ($) {
      $.ajax({
        dataType: "json",
        url: url,
        success: success,
        error: error
      });
    } else {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.onload = function () {
        if (xhr.status === 200) {
          success(JSON.parse(xhr.responseText), xhr.statusText, xhr);
        } else {
          error(xhr, "error", xhr.statusText);
        }
      };
      xhr.send();
    }
  }

  function errorCatcher(chart, callback) {
    try {
      callback(chart);
    } catch (err) {
      chartError(chart.element, err.message);
      throw err;
    }
  }

  function fetchDataSource(chart, callback) {
    if (typeof chart.dataSource === "string") {
      getJSON(chart.element, chart.dataSource, function (data, textStatus, jqXHR) {
        chart.data = data;
        errorCatcher(chart, callback);
      });
    } else {
      chart.data = chart.dataSource;
      errorCatcher(chart, callback);
    }
  }

  // type conversions

  function toStr(n) {
    return "" + n;
  }

  function toFloat(n) {
    return parseFloat(n);
  }

  function toDate(n) {
    var matches, year, month, day;
    if (typeof n !== "object") {
      if (typeof n === "number") {
        n = new Date(n * 1000); // ms
      } else if ((matches = n.match(DATE_PATTERN))) {
        year = parseInt(matches[1], 10);
        month = parseInt(matches[3], 10) - 1;
        day = parseInt(matches[5], 10);
        return new Date(year, month, day);
      } else { // str
        // try our best to get the str into iso8601
        // TODO be smarter about this
        var str = n.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
        n = parseISO8601(str) || new Date(n);
      }
    }
    return n;
  }

  function toArr(n) {
    if (!isArray(n)) {
      var arr = [], i;
      for (i in n) {
        if (n.hasOwnProperty(i)) {
          arr.push([i, n[i]]);
        }
      }
      n = arr;
    }
    return n;
  }

  function sortByTime(a, b) {
    return a[0].getTime() - b[0].getTime();
  }

  function sortByNumber(a, b) {
    return a - b;
  }

  function loadAdapters() {
    if (!HighchartsAdapter && "Highcharts" in window) {
      HighchartsAdapter = new function () {
        var Highcharts = window.Highcharts;

        this.name = "highcharts";

        var defaultOptions = {
          chart: {},
          xAxis: {
            title: {
              text: null
            },
            labels: {
              style: {
                fontSize: "12px"
              }
            }
          },
          yAxis: {
            title: {
              text: null
            },
            labels: {
              style: {
                fontSize: "12px"
              }
            }
          },
          title: {
            text: null
          },
          credits: {
            enabled: false
          },
          legend: {
            borderWidth: 0
          },
          tooltip: {
            style: {
              fontSize: "12px"
            }
          },
          plotOptions: {
            areaspline: {},
            series: {
              marker: {}
            }
          }
        };

        var hideLegend = function (options) {
          options.legend.enabled = false;
        };

        var setMin = function (options, min) {
          options.yAxis.min = min;
        };

        var setMax = function (options, max) {
          options.yAxis.max = max;
        };

        var setStacked = function (options, stacked) {
          options.plotOptions.series.stacking = stacked ? "normal" : null;
        };

        var setXtitle = function (options, title) {
          options.xAxis.title.text = title;
        };

        var setYtitle = function (options, title) {
          options.yAxis.title.text = title;
        };

        var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);

        this.renderLineChart = function (chart, chartType) {
          chartType = chartType || "spline";
          var chartOptions = {};
          if (chartType === "areaspline") {
            chartOptions = {
              plotOptions: {
                areaspline: {
                  stacking: "normal"
                },
                series: {
                  marker: {
                    enabled: false
                  }
                }
              }
            };
          }
          var options = jsOptions(chart.data, chart.options, chartOptions), data, i, j;
          options.xAxis.type = chart.options.discrete ? "category" : "datetime";
          if (!options.chart.type) {
            options.chart.type = chartType;
          }
          options.chart.renderTo = chart.element.id;

          var series = chart.data;
          for (i = 0; i < series.length; i++) {
            data = series[i].data;
            if (!chart.options.discrete) {
              for (j = 0; j < data.length; j++) {
                data[j][0] = data[j][0].getTime();
              }
            }
            series[i].marker = {symbol: "circle"};
          }
          options.series = series;
          new Highcharts.Chart(options);
        };

        this.renderScatterChart = function (chart) {
          var chartOptions = {};
          var options = jsOptions(chart.data, chart.options, chartOptions);
          options.chart.type = "scatter";
          options.chart.renderTo = chart.element.id;
          options.series = chart.data;
          new Highcharts.Chart(options);
        };

        this.renderPieChart = function (chart) {
          var chartOptions = {};
          if (chart.options.colors) {
            chartOptions.colors = chart.options.colors;
          }
          var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});
          options.chart.renderTo = chart.element.id;
          options.series = [{
            type: "pie",
            name: chart.options.label || "Value",
            data: chart.data
          }];
          new Highcharts.Chart(options);
        };

        this.renderColumnChart = function (chart, chartType) {
          chartType = chartType || "column";
          var series = chart.data;
          var options = jsOptions(series, chart.options), i, j, s, d, rows = [];
          options.chart.type = chartType;
          options.chart.renderTo = chart.element.id;

          for (i = 0; i < series.length; i++) {
            s = series[i];

            for (j = 0; j < s.data.length; j++) {
              d = s.data[j];
              if (!rows[d[0]]) {
                rows[d[0]] = new Array(series.length);
              }
              rows[d[0]][i] = d[1];
            }
          }

          var categories = [];
          for (i in rows) {
            if (rows.hasOwnProperty(i)) {
              categories.push(i);
            }
          }
          options.xAxis.categories = categories;

          var newSeries = [];
          for (i = 0; i < series.length; i++) {
            d = [];
            for (j = 0; j < categories.length; j++) {
              d.push(rows[categories[j]][i] || 0);
            }

            newSeries.push({
              name: series[i].name,
              data: d
            });
          }
          options.series = newSeries;

          new Highcharts.Chart(options);
        };

        var self = this;

        this.renderBarChart = function (chart) {
          self.renderColumnChart(chart, "bar");
        };

        this.renderAreaChart = function (chart) {
          self.renderLineChart(chart, "areaspline");
        };
      };
      adapters.push(HighchartsAdapter);
    }
    if (!GoogleChartsAdapter && window.google && (window.google.setOnLoadCallback || window.google.charts)) {
      GoogleChartsAdapter = new function () {
        var google = window.google;

        this.name = "google";

        var loaded = {};
        var callbacks = [];

        var runCallbacks = function () {
          var cb, call;
          for (var i = 0; i < callbacks.length; i++) {
            cb = callbacks[i];
            call = google.visualization && ((cb.pack === "corechart" && google.visualization.LineChart) || (cb.pack === "timeline" && google.visualization.Timeline));
            if (call) {
              cb.callback();
              callbacks.splice(i, 1);
              i--;
            }
          }
        };

        var waitForLoaded = function (pack, callback) {
          if (!callback) {
            callback = pack;
            pack = "corechart";
          }

          callbacks.push({pack: pack, callback: callback});

          if (loaded[pack]) {
            runCallbacks();
          } else {
            loaded[pack] = true;

            // https://groups.google.com/forum/#!topic/google-visualization-api/fMKJcyA2yyI
            var loadOptions = {
              packages: [pack],
              callback: runCallbacks
            };
            if (config.language) {
              loadOptions.language = config.language;
            }

            if (window.google.setOnLoadCallback) {
              google.load("visualization", "1", loadOptions);
            } else {
              google.charts.load("current", loadOptions);
            }
          }
        };

        // Set chart options
        var defaultOptions = {
          chartArea: {},
          fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
          pointSize: 6,
          legend: {
            textStyle: {
              fontSize: 12,
              color: "#444"
            },
            alignment: "center",
            position: "right"
          },
          curveType: "function",
          hAxis: {
            textStyle: {
              color: "#666",
              fontSize: 12
            },
            titleTextStyle: {},
            gridlines: {
              color: "transparent"
            },
            baselineColor: "#ccc",
            viewWindow: {}
          },
          vAxis: {
            textStyle: {
              color: "#666",
              fontSize: 12
            },
            titleTextStyle: {},
            baselineColor: "#ccc",
            viewWindow: {}
          },
          tooltip: {
            textStyle: {
              color: "#666",
              fontSize: 12
            }
          }
        };

        var hideLegend = function (options) {
          options.legend.position = "none";
        };

        var setMin = function (options, min) {
          options.vAxis.viewWindow.min = min;
        };

        var setMax = function (options, max) {
          options.vAxis.viewWindow.max = max;
        };

        var setBarMin = function (options, min) {
          options.hAxis.viewWindow.min = min;
        };

        var setBarMax = function (options, max) {
          options.hAxis.viewWindow.max = max;
        };

        var setStacked = function (options, stacked) {
          options.isStacked = !!stacked;
        };

        var setXtitle = function (options, title) {
          options.hAxis.title = title;
          options.hAxis.titleTextStyle.italic = false;
        };

        var setYtitle = function (options, title) {
          options.vAxis.title = title;
          options.vAxis.titleTextStyle.italic = false;
        };

        var jsOptions = jsOptionsFunc(defaultOptions, hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);

        // cant use object as key
        var createDataTable = function (series, columnType) {
          var i, j, s, d, key, rows = [];
          for (i = 0; i < series.length; i++) {
            s = series[i];

            for (j = 0; j < s.data.length; j++) {
              d = s.data[j];
              key = (columnType === "datetime") ? d[0].getTime() : d[0];
              if (!rows[key]) {
                rows[key] = new Array(series.length);
              }
              rows[key][i] = toFloat(d[1]);
            }
          }

          var rows2 = [];
          var day = true;
          var value;
          for (i in rows) {
            if (rows.hasOwnProperty(i)) {
              if (columnType === "datetime") {
                value = new Date(toFloat(i));
                day = day && isDay(value);
              } else if (columnType === "number") {
                value = toFloat(i);
              } else {
                value = i;
              }
              rows2.push([value].concat(rows[i]));
            }
          }
          if (columnType === "datetime") {
            rows2.sort(sortByTime);
          }

          // create datatable
          var data = new google.visualization.DataTable();
          columnType = columnType === "datetime" && day ? "date" : columnType;
          data.addColumn(columnType, "");
          for (i = 0; i < series.length; i++) {
            data.addColumn("number", series[i].name);
          }
          data.addRows(rows2);

          return data;
        };

        var resize = function (callback) {
          if (window.attachEvent) {
            window.attachEvent("onresize", callback);
          } else if (window.addEventListener) {
            window.addEventListener("resize", callback, true);
          }
          callback();
        };

        this.renderLineChart = function (chart) {
          waitForLoaded(function () {
            var options = jsOptions(chart.data, chart.options);
            var data = createDataTable(chart.data, chart.options.discrete ? "string" : "datetime");
            chart.chart = new google.visualization.LineChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderPieChart = function (chart) {
          waitForLoaded(function () {
            var chartOptions = {
              chartArea: {
                top: "10%",
                height: "80%"
              }
            };
            if (chart.options.colors) {
              chartOptions.colors = chart.options.colors;
            }
            var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});

            var data = new google.visualization.DataTable();
            data.addColumn("string", "");
            data.addColumn("number", "Value");
            data.addRows(chart.data);

            chart.chart = new google.visualization.PieChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderColumnChart = function (chart) {
          waitForLoaded(function () {
            var options = jsOptions(chart.data, chart.options);
            var data = createDataTable(chart.data, "string");
            chart.chart = new google.visualization.ColumnChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderBarChart = function (chart) {
          waitForLoaded(function () {
            var chartOptions = {
              hAxis: {
                gridlines: {
                  color: "#ccc"
                }
              }
            };
            var options = jsOptionsFunc(defaultOptions, hideLegend, setBarMin, setBarMax, setStacked, setXtitle, setYtitle)(chart.data, chart.options, chartOptions);
            var data = createDataTable(chart.data, "string");
            chart.chart = new google.visualization.BarChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderAreaChart = function (chart) {
          waitForLoaded(function () {
            var chartOptions = {
              isStacked: true,
              pointSize: 0,
              areaOpacity: 0.5
            };
            var options = jsOptions(chart.data, chart.options, chartOptions);
            var data = createDataTable(chart.data, chart.options.discrete ? "string" : "datetime");
            chart.chart = new google.visualization.AreaChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderGeoChart = function (chart) {
          waitForLoaded(function () {
            var chartOptions = {
              legend: "none",
              colorAxis: {
                colors: chart.options.colors || ["#f6c7b6", "#ce502d"]
              }
            };
            var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});

            var data = new google.visualization.DataTable();
            data.addColumn("string", "");
            data.addColumn("number", chart.options.label || "Value");
            data.addRows(chart.data);

            chart.chart = new google.visualization.GeoChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderScatterChart = function (chart) {
          waitForLoaded(function () {
            var chartOptions = {};
            var options = jsOptions(chart.data, chart.options, chartOptions);
            var data = createDataTable(chart.data, "number");

            chart.chart = new google.visualization.ScatterChart(chart.element);
            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };

        this.renderTimeline = function (chart) {
          waitForLoaded("timeline", function () {
            var chartOptions = {
              legend: "none"
            };

            if (chart.options.colors) {
              chartOptions.colors = chart.options.colors;
            }
            var options = merge(merge(defaultOptions, chartOptions), chart.options.library || {});

            var data = new google.visualization.DataTable();
            data.addColumn({type: "string", id: "Name"});
            data.addColumn({type: "date", id: "Start"});
            data.addColumn({type: "date", id: "End"});
            data.addRows(chart.data);

            chart.element.style.lineHeight = "normal";
            chart.chart = new google.visualization.Timeline(chart.element);

            resize(function () {
              chart.chart.draw(data, options);
            });
          });
        };
      };

      adapters.push(GoogleChartsAdapter);
    }
    if (!ChartjsAdapter && "Chart" in window) {
      ChartjsAdapter = new function () {
        var Chart = window.Chart;

        this.name = "chartjs";

        var baseOptions = {
          maintainAspectRatio: false,
          animation: false
        };

        var defaultOptions = {
          scales: {
            yAxes: [
              {
                ticks: {
                  maxTicksLimit: 4
                },
                scaleLabel: {
                  fontSize: 16,
                  // fontStyle: "bold",
                  fontColor: "#333"
                }
              }
            ],
            xAxes: [
              {
                gridLines: {
                  drawOnChartArea: false
                },
                scaleLabel: {
                  fontSize: 16,
                  // fontStyle: "bold",
                  fontColor: "#333"
                },
                time: {},
                ticks: {}
              }
            ]
          },
          legend: {}
        };

        // http://there4.io/2012/05/02/google-chart-color-list/
        var defaultColors = [
          "#3366CC", "#DC3912", "#FF9900", "#109618", "#990099", "#3B3EAC", "#0099C6",
          "#DD4477", "#66AA00", "#B82E2E", "#316395", "#994499", "#22AA99", "#AAAA11",
          "#6633CC", "#E67300", "#8B0707", "#329262", "#5574A6", "#3B3EAC"
        ];

        var hideLegend = function (options) {
          options.legend.display = false;
        };

        var setMin = function (options, min) {
          if (min !== null) {
            options.scales.yAxes[0].ticks.min = min;
          }
        };

        var setMax = function (options, max) {
          options.scales.yAxes[0].ticks.max = max;
        };

        var setBarMin = function (options, min) {
          if (min !== null) {
            options.scales.xAxes[0].ticks.min = min;
          }
        };

        var setBarMax = function (options, max) {
          options.scales.xAxes[0].ticks.max = max;
        };

        var setStacked = function (options, stacked) {
          options.scales.xAxes[0].stacked = !!stacked;
          options.scales.yAxes[0].stacked = !!stacked;
        };

        var setXtitle = function (options, title) {
          options.scales.xAxes[0].scaleLabel.display = true;
          options.scales.xAxes[0].scaleLabel.labelString = title;
        };

        var setYtitle = function (options, title) {
          options.scales.yAxes[0].scaleLabel.display = true;
          options.scales.yAxes[0].scaleLabel.labelString = title;
        };

        var drawChart = function(chart, type, data, options) {
          chart.element.innerHTML = "<canvas></canvas>";
          var ctx = chart.element.getElementsByTagName("CANVAS")[0];

          chart.chart = new Chart(ctx, {
            type: type,
            data: data,
            options: options
          });
        };

        // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
        var addOpacity = function(hex, opacity) {
          var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
          return result ? "rgba(" + parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16) + ", " + opacity + ")" : hex;
        };

        var setLabelSize = function (chart, data, options) {
          var maxLabelSize = Math.ceil(chart.element.offsetWidth / 4.0 / data.labels.length);
          if (maxLabelSize > 25) {
            maxLabelSize = 25;
          }
          options.scales.xAxes[0].ticks.callback = function (value) {
            value = toStr(value);
            if (value.length > maxLabelSize) {
              return value.substring(0, maxLabelSize - 2) + "...";
            } else {
              return value;
            }
          };
        };

        var jsOptions = jsOptionsFunc(merge(baseOptions, defaultOptions), hideLegend, setMin, setMax, setStacked, setXtitle, setYtitle);

        var createDataTable = function (chart, options, chartType) {
          var datasets = [];
          var labels = [];

          var colors = chart.options.colors || defaultColors;

          var day = true;
          var week = true;
          var dayOfWeek;
          var month = true;
          var year = true;
          var hour = true;
          var minute = true;
          var detectType = (chartType === "line" || chartType === "area") && !chart.options.discrete;

          var series = chart.data;

          var sortedLabels = [];

          var i, j, s, d, key, rows = [];
          for (i = 0; i < series.length; i++) {
            s = series[i];

            for (j = 0; j < s.data.length; j++) {
              d = s.data[j];
              key = detectType ? d[0].getTime() : d[0];
              if (!rows[key]) {
                rows[key] = new Array(series.length);
              }
              rows[key][i] = toFloat(d[1]);
              if (sortedLabels.indexOf(key) === -1) {
                sortedLabels.push(key);
              }
            }
          }

          if (detectType) {
            sortedLabels.sort(sortByNumber);
          }

          var rows2 = [];
          for (j = 0; j < series.length; j++) {
            rows2.push([]);
          }

          var value;
          var k;
          for (k = 0; k < sortedLabels.length; k++) {
            i = sortedLabels[k];
            if (detectType) {
              value = new Date(toFloat(i));
              // TODO make this efficient
              day = day && isDay(value);
              if (!dayOfWeek) {
                dayOfWeek = value.getDay();
              }
              week = week && isWeek(value, dayOfWeek);
              month = month && isMonth(value);
              year = year && isYear(value);
              hour = hour && isHour(value);
              minute = minute && isMinute(value);
            } else {
              value = i;
            }
            labels.push(value);
            for (j = 0; j < series.length; j++) {
              rows2[j].push(rows[i][j]);
            }
          }

          for (i = 0; i < series.length; i++) {
            s = series[i];

            var backgroundColor = chartType !== "line" ? addOpacity(colors[i], 0.5) : colors[i];

            var dataset = {
              label: s.name,
              data: rows2[i],
              fill: chartType === "area",
              borderColor: colors[i],
              backgroundColor: backgroundColor,
              pointBackgroundColor: colors[i],
              borderWidth: 2
            };

            datasets.push(merge(dataset, s.library || {}));
          }

          if (detectType && labels.length > 0) {
            var minTime = labels[0].getTime();
            var maxTime = labels[0].getTime();
            for (i = 1; i < labels.length; i++) {
              value = labels[i].getTime();
              if (value < minTime) {
                minTime = value;
              }
              if (value > maxTime) {
                maxTime = value;
              }
            }

            var timeDiff = (maxTime - minTime) / (86400 * 1000.0);

            if (!options.scales.xAxes[0].time.unit) {
              var step;
              if (year || timeDiff > 365 * 10) {
                options.scales.xAxes[0].time.unit = "year";
                step = 365;
              } else if (month || timeDiff > 30 * 10) {
                options.scales.xAxes[0].time.unit = "month";
                step = 30;
              } else if (day || timeDiff > 10) {
                options.scales.xAxes[0].time.unit = "day";
                step = 1;
              } else if (hour) {
                options.scales.xAxes[0].time.unit = "hour";
                step = 1 / 24.0;
              } else if (minute) {
                options.scales.xAxes[0].time.displayFormats = {minute: "h:mm a"};
                options.scales.xAxes[0].time.unit = "minute";
                step = 1 / 24.0 / 60.0;
              }

              if (step && timeDiff > 0) {
                var unitStepSize = Math.ceil(timeDiff / step / (chart.element.offsetWidth / 100.0));
                if (week && step === 1) {
                  unitStepSize = Math.ceil(unitStepSize / 7.0) * 7;
                }
                options.scales.xAxes[0].time.unitStepSize = unitStepSize;
              }
            }

            if (!options.scales.xAxes[0].time.tooltipFormat) {
              if (day) {
                options.scales.xAxes[0].time.tooltipFormat = "ll";
              } else if (hour) {
                options.scales.xAxes[0].time.tooltipFormat = "MMM D, h a";
              } else if (minute) {
                options.scales.xAxes[0].time.tooltipFormat = "h:mm a";
              }
            }
          }

          var data = {
            labels: labels,
            datasets: datasets
          };

          return data;
        };

        this.renderLineChart = function (chart, chartType) {
          var areaOptions = {};
          if (chartType === "area") {
            // TODO fix area stacked
            // areaOptions.stacked = true;
          }
          // fix for https://github.com/chartjs/Chart.js/issues/2441
          if (!chart.options.max && allZeros(chart.data)) {
            chart.options.max = 1;
          }

          var options = jsOptions(chart.data, merge(areaOptions, chart.options));

          var data = createDataTable(chart, options, chartType || "line");

          options.scales.xAxes[0].type = chart.options.discrete ? "category" : "time";

          drawChart(chart, "line", data, options);
        };

        this.renderPieChart = function (chart) {
          var options = merge(baseOptions, chart.options.library || {});

          var labels = [];
          var values = [];
          for (var i = 0; i < chart.data.length; i++) {
            var point = chart.data[i];
            labels.push(point[0]);
            values.push(point[1]);
          }

          var data = {
            labels: labels,
            datasets: [
              {
                data: values,
                backgroundColor: chart.options.colors || defaultColors
              }
            ]
          };

          drawChart(chart, "pie", data, options);
        };

        this.renderColumnChart = function (chart, chartType) {
          var options;
          if (chartType === "bar") {
            options = jsOptionsFunc(merge(baseOptions, defaultOptions), hideLegend, setBarMin, setBarMax, setStacked, setXtitle, setYtitle)(chart.data, chart.options);
          } else {
            options = jsOptions(chart.data, chart.options);
          }
          var data = createDataTable(chart, options, "column");
          setLabelSize(chart, data, options);
          drawChart(chart, (chartType === "bar" ? "horizontalBar" : "bar"), data, options);
        };

        var self = this;

        this.renderAreaChart = function (chart) {
          self.renderLineChart(chart, "area");
        };

        this.renderBarChart = function (chart) {
          self.renderColumnChart(chart, "bar");
        };

        this.renderScatterChart = function (chart) {
          var options = jsOptions(chart.data, chart.options);

          var colors = chart.options.colors || defaultColors;

          var datasets = [];
          var series = chart.data;
          for (var i = 0; i < series.length; i++) {
            var s = series[i];
            var d = [];
            for (var j = 0; j < s.data.length; j++) {
              d.push({
                x: toFloat(s.data[j][0]),
                y: toFloat(s.data[j][1])
              });
            }

            datasets.push({
              label: s.name,
              showLine: false,
              data: d,
              borderColor: colors[i],
              backgroundColor: colors[i],
              pointBackgroundColor: colors[i]
            })
          }

          var data = {datasets: datasets};

          options.scales.xAxes[0].type = "linear";
          options.scales.xAxes[0].position = "bottom";

          drawChart(chart, "line", data, options);
        };
      };

      adapters.unshift(ChartjsAdapter);
    }
  }

  // TODO remove chartType if cross-browser way
  // to get the name of the chart class
  function renderChart(chartType, chart) {
    var i, adapter, fnName, adapterName;
    fnName = "render" + chartType;
    adapterName = chart.options.adapter;

    loadAdapters();

    for (i = 0; i < adapters.length; i++) {
      adapter = adapters[i];
      if ((!adapterName || adapterName === adapter.name) && isFunction(adapter[fnName])) {
        return adapter[fnName](chart);
      }
    }
    throw new Error("No adapter found");
  }

  // process data

  var toFormattedKey = function (key, keyType) {
    if (keyType === "number") {
      key = toFloat(key);
    } else if (keyType === "datetime") {
      key = toDate(key);
    } else {
      key = toStr(key);
    }
    return key;
  };

  var formatSeriesData = function (data, keyType) {
    var r = [], key, j;
    for (j = 0; j < data.length; j++) {
      key = toFormattedKey(data[j][0], keyType);
      r.push([key, toFloat(data[j][1])]);
    }
    if (keyType === "datetime") {
      r.sort(sortByTime);
    }
    return r;
  };

  function isMinute(d) {
    return d.getMilliseconds() === 0 && d.getSeconds() === 0;
  }

  function isHour(d) {
    return isMinute(d) && d.getMinutes() === 0;
  }

  function isDay(d) {
    return isHour(d) && d.getHours() === 0;
  }

  function isWeek(d, dayOfWeek) {
    return isDay(d) && d.getDay() === dayOfWeek;
  }

  function isMonth(d) {
    return isDay(d) && d.getDate() === 1;
  }

  function isYear(d) {
    return isMonth(d) && d.getMonth() === 0;
  }

  function isDate(obj) {
    return !isNaN(toDate(obj)) && toStr(obj).length >= 6;
  }

  function allZeros(data) {
    var i, j, d;
    for (i = 0; i < data.length; i++) {
      d = data[i].data;
      for (j = 0; j < d.length; j++) {
        if (d[j][1] != 0) {
          return false;
        }
      }
    }
    return true;
  }

  function detectDiscrete(series) {
    var i, j, data;
    for (i = 0; i < series.length; i++) {
      data = toArr(series[i].data);
      for (j = 0; j < data.length; j++) {
        if (!isDate(data[j][0])) {
          return true;
        }
      }
    }
    return false;
  }

  function processSeries(series, opts, keyType) {
    var i;

    // see if one series or multiple
    if (!isArray(series) || typeof series[0] !== "object" || isArray(series[0])) {
      series = [{name: opts.label || "Value", data: series}];
      opts.hideLegend = true;
    } else {
      opts.hideLegend = false;
    }
    if ((opts.discrete === null || opts.discrete === undefined)) {
      opts.discrete = detectDiscrete(series);
    }
    if (opts.discrete) {
      keyType = "string";
    }

    // right format
    for (i = 0; i < series.length; i++) {
      series[i].data = formatSeriesData(toArr(series[i].data), keyType);
    }

    return series;
  }

  function processSimple(data) {
    var perfectData = toArr(data), i;
    for (i = 0; i < perfectData.length; i++) {
      perfectData[i] = [toStr(perfectData[i][0]), toFloat(perfectData[i][1])];
    }
    return perfectData;
  }

  function processTime(data)
  {
    var i;
    for (i = 0; i < data.length; i++) {
      data[i][1] = toDate(data[i][1]);
      data[i][2] = toDate(data[i][2]);
    }
    return data;
  }

  function processLineData(chart) {
    chart.data = processSeries(chart.data, chart.options, "datetime");
    renderChart("LineChart", chart);
  }

  function processColumnData(chart) {
    chart.data = processSeries(chart.data, chart.options, "string");
    renderChart("ColumnChart", chart);
  }

  function processPieData(chart) {
    chart.data = processSimple(chart.data);
    renderChart("PieChart", chart);
  }

  function processBarData(chart) {
    chart.data = processSeries(chart.data, chart.options, "string");
    renderChart("BarChart", chart);
  }

  function processAreaData(chart) {
    chart.data = processSeries(chart.data, chart.options, "datetime");
    renderChart("AreaChart", chart);
  }

  function processGeoData(chart) {
    chart.data = processSimple(chart.data);
    renderChart("GeoChart", chart);
  }

  function processScatterData(chart) {
    chart.data = processSeries(chart.data, chart.options, "number");
    renderChart("ScatterChart", chart);
  }

  function processTimelineData(chart) {
    chart.data = processTime(chart.data);
    renderChart("Timeline", chart);
  }

  function setElement(chart, element, dataSource, opts, callback) {
    var elementId;
    if (typeof element === "string") {
      elementId = element;
      element = document.getElementById(element);
      if (!element) {
        throw new Error("No element with id " + elementId);
      }
    }
    chart.element = element;
    chart.options = opts || {};
    chart.dataSource = dataSource;
    chart.getElement = function () {
      return element;
    };
    chart.getData = function () {
      return chart.data;
    };
    chart.getOptions = function () {
      return opts || {};
    };
    chart.getChartObject = function () {
      return chart.chart;
    };
    Chartkick.charts[element.id] = chart;
    fetchDataSource(chart, callback);
  }

  // define classes

  Chartkick = {
    LineChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processLineData);
    },
    PieChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processPieData);
    },
    ColumnChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processColumnData);
    },
    BarChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processBarData);
    },
    AreaChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processAreaData);
    },
    GeoChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processGeoData);
    },
    ScatterChart: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processScatterData);
    },
    Timeline: function (element, dataSource, opts) {
      setElement(this, element, dataSource, opts, processTimelineData);
    },
    charts: {},
    configure: function (options) {
      for (var key in options) {
        if (options.hasOwnProperty(key)) {
          config[key] = options[key];
        }
      }
    }
  };

  if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = Chartkick;
  } else {
    window.Chartkick = Chartkick;
  }
}(window));

redpajama_set_name: RedPajamaGithub


text:
#requires -modules BuildHelpers
#requires -modules @{ ModuleName = "Pester"; ModuleVersion = "4.4.0" }

Describe "Remove-JiraGroupMember" -Tag 'Unit' {

BeforeAll {
        Remove-Item -Path Env:\BH*
        $projectRoot = (Resolve-Path "$PSScriptRoot/../..").Path
        if ($projectRoot -like "*Release") {
            $projectRoot = (Resolve-Path "$projectRoot/..").Path
        }

        Import-Module BuildHelpers
        Set-BuildEnvironment -BuildOutput '$ProjectPath/Release' -Path $projectRoot -ErrorAction SilentlyContinue

        $env:BHManifestToTest = $env:BHPSModuleManifest
        $script:isBuild = $PSScriptRoot -like "$env:BHBuildOutput*"
        if ($script:isBuild) {
            $Pattern = [regex]::Escape($env:BHProjectPath)

            $env:BHBuildModuleManifest = $env:BHPSModuleManifest -replace $Pattern, $env:BHBuildOutput
            $env:BHManifestToTest = $env:BHBuildModuleManifest
        }

        Import-Module "$env:BHProjectPath/Tools/BuildTools.psm1"

        Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue
        Import-Module $env:BHManifestToTest
    }
    AfterAll {
        Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue
        Remove-Module BuildHelpers -ErrorAction SilentlyContinue
        Remove-Item -Path Env:\BH*
    }

    InModuleScope JiraPS {

        . "$PSScriptRoot/../Shared.ps1"

        #region Definitions
        $jiraServer = 'http://jiraserver.example.com'

        $testGroupName = 'testGroup'
        $testUsername1 = 'testUsername1'
        $testUsername2 = 'testUsername2'
        #endregion Definitions

        #region Mocks
        Mock Get-JiraConfigServer -ModuleName JiraPS {
            Write-Output $jiraServer
        }

        Mock Get-JiraGroup -ModuleName JiraPS {
            [PSCustomObject]@{
                PSTypeName = "JiraPS.Group"
                Name       = $testGroupName
                Size       = 2
            }
        }

        Mock Get-JiraUser -ModuleName JiraPS {
            if ($InputObject) {
                $obj = [PSCustomObject]@{
                    PSTypeName = "JiraPS.User"
                    Name       = "$InputObject"
                }
            }
            else {
                $obj = [PSCustomObject]@{
                    PSTypeName = "JiraPS.User"
                    Name       = "$UserName"
                }
            }
            $obj | Add-Member -MemberType ScriptMethod -Name "ToString" -Force -Value {
                Write-Output "$($this.Name)"
            }
            $obj
        }

        Mock Get-JiraGroupMember -ModuleName JiraPS {
            [PSCustomObject]@{
                PSTypeName = "JiraPS.Group"
                Name       = $testUsername1
            }
        }

        Mock Invoke-JiraMethod -ModuleName JiraPS {
            ShowMockInfo 'Invoke-JiraMethod' 'Method', 'Uri'
        }
        #endregion Mocks

        #############
        # Tests
        #############
        Context "Sanity checking" {
            $command = Get-Command -Name Remove-JiraGroupMember

            defParam $command 'Group'
            defParam $command 'User'
            defParam $command 'Credential'
            defParam $command 'PassThru'
            defParam $command 'Force'
        }

        Context "Behavior testing" {
            It "Tests to see if a provided user is currently a member of the provided JIRA group before attempting to remove them" {
                { Remove-JiraGroupMember -Group $testGroupName -User $testUsername1 -Force } | Should Not Throw

                Assert-MockCalled -CommandName Get-JiraGroup -ModuleName "JiraPS" -Exactly -Times 1 -Scope It
            }

            It "Removes a user from a JIRA group if the user is a member" {
                { Remove-JiraGroupMember -Group $testGroupName -User $testUsername1 -Force } | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq 'Delete' -and
                        $URI -like "$jiraServer/rest/api/*/group/user?groupname=$testGroupName&username=$testUsername1"
                    }
                    Exactly         = $true
                    Times           = 1
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }

            It "Removes multiple users to a JIRA group if they are passed to the -User parameter" {
                # Override our previous mock so we have two group members
                Mock Get-JiraGroupMember -ModuleName JiraPS {
                    @(
                        [PSCustomObject] @{
                            'Name' = $testUsername1
                        },
                        [PSCustomObject] @{
                            'Name' = $testUsername2
                        }
                    )
                }

                # Should use the REST method twice, since at present, you can only delete one group member per API call
                { Remove-JiraGroupMember -Group $testGroupName -User $testUsername1, $testUsername2 -Force } | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq 'Delete' -and
                        $URI -like "$jiraServer/rest/api/*/group/user?groupname=$testGroupName&username=*"
                    }
                    Exactly         = $true
                    Times           = 2
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }
        }

        Context "Input testing" {
            It "Accepts a group name as a String to the -Group parameter" {
                { Remove-JiraGroupMember -Group $testGroupName -User $testUsername1 -Force } | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq "Delete" -and
                        $URI -like "*/rest/api/*/group/user*" -and
                        $URI -match "groupname=$testGroupName" -and
                        $URI -match "username=$testUsername1"
                    }
                    Exactly         = $true
                    Times           = 1
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }

            It "Accepts a JiraPS.Group object to the -Group parameter" {
                {
                    $group = Get-JiraGroup -GroupName $testGroupName
                    Remove-JiraGroupMember -Group $group -User $testUsername1 -Force
                } | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq "Delete" -and
                        $URI -like "*/rest/api/*/group/user*" -and
                        $URI -match "groupname=$testGroupName" -and
                        $URI -match "username=$testUsername1"
                    }
                    Exactly         = $true
                    Times           = 1
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }

            It "Accepts pipeline input from Get-JiraGroup" {
                { Get-JiraGroup -GroupName $testGroupName | Remove-JiraGroupMember -User $testUsername1 -Force} | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq "Delete" -and
                        $URI -like "*/rest/api/*/group/user*" -and
                        $URI -match "groupname=$testGroupName" -and
                        $URI -match "username=$testUsername1"
                    }
                    Exactly         = $true
                    Times           = 1
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }

            It "Accepts a JiraPS.User as input for -User parameter" {
                {
                    $user = Get-JiraUser -UserName $testUsername1
                    Remove-JiraGroupMember -Group $testGroupName -User $user -Force
                } | Should Not Throw

                $assertMockCalledSplat = @{
                    CommandName     = 'Invoke-JiraMethod'
                    ModuleName      = "JiraPS"
                    ParameterFilter = {
                        $Method -eq "Delete" -and
                        $URI -like "*/rest/api/*/group/user*" -and
                        $URI -match "groupname=$testGroupName" -and
                        $URI -match "username=$testUsername1"
                    }
                    Exactly         = $true
                    Times           = 1
                    Scope           = 'It'
                }
                Assert-MockCalled @assertMockCalledSplat
            }
        }
    }
}


text:
#ifndef BGFX_PLATFORM_H_HEADER_GUARD
#define BGFX_PLATFORM_H_HEADER_GUARD

// NOTICE:
// This header file contains platform specific interfaces. It is only
// necessary to use this header in conjunction with creating windows.

#include <bx/platform.h>
#include <bgfx/bgfx.h>

namespace bgfx
{
	/// Render frame enum.
	///
	/// @attention C99 equivalent is `bgfx_render_frame_t`.
	///
	struct RenderFrame
	{
		enum Enum
		{
			NoContext,
			Render,
			Exiting,

			Count
		};
	};

	/// Render frame.
	///
	/// @returns Current renderer state. See: `bgfx::RenderFrame`.
	///
	/// @warning This call should be only used on platforms that don't
	///   allow creating separate rendering thread. If it is called before
	///   to bgfx::init, render thread won't be created by bgfx::init call.
	RenderFrame::Enum renderFrame();

	/// Platform data.
	///
	/// @attention C99 equivalent is `bgfx_platform_data_t`.
	///
	struct PlatformData
	{
		void* ndt;          //!< Native display type.
		void* nwh;          //!< Native window handle.
		void* context;      //!< GL context, or D3D device.
		void* backBuffer;   //!< GL backbuffer, or D3D render target view.
		void* backBufferDS; //!< Backbuffer depth/stencil.
	};

	/// Set platform data.
	///
	/// @warning Must be called before `bgfx::init`.
	///
	/// @attention C99 equivalent is `bgfx_set_platform_data`.
	///
	void setPlatformData(const PlatformData& _data);

	/// Internal data.
	///
	/// @attention C99 equivalent is `bgfx_internal_data_t`.
	///
	struct InternalData
	{
		const struct Caps* caps; //!< Renderer capabilities.
		void* context;           //!< GL context, or D3D device.
	};

	/// Get internal data for interop.
	///
	/// @attention It's expected you understand some bgfx internals before you
	///   use this call.
	///
	/// @warning Must be called only on render thread.
	///
	/// @attention C99 equivalent is `bgfx_get_internal_data`.
	///
	const InternalData* getInternalData();

	/// Override internal texture with externally created texture. Previously
	/// created internal texture will released.
	///
	/// @attention It's expected you understand some bgfx internals before you
	///   use this call.
	///
	/// @param[in] _handle Texture handle.
	/// @param[in] _ptr Native API pointer to texture.
	///
	/// @returns Native API pointer to texture. If result is 0, texture is not created yet from the
	///   main thread.
	///
	/// @warning Must be called only on render thread.
	///
	/// @attention C99 equivalent is `bgfx_override_internal_texture_ptr`.
	///
	uintptr_t overrideInternal(TextureHandle _handle, uintptr_t _ptr);

	/// Override internal texture by creating new texture. Previously created
	/// internal texture will released.
	///
	/// @attention It's expected you understand some bgfx internals before you
	///   use this call.
	///
	/// @param[in] _handle Texture handle.
	/// @param[in] _width Width.
	/// @param[in] _height Height.
	/// @param[in] _numMips Number of mip-maps.
	/// @param[in] _format Texture format. See: `TextureFormat::Enum`.
	/// @param[in] _flags Default texture sampling mode is linear, and wrap mode
	///   is repeat.
	///   - `BGFX_TEXTURE_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap
	///     mode.
	///   - `BGFX_TEXTURE_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic
	///     sampling.
	///
	/// @returns Native API pointer to texture. If result is 0, texture is not created yet from the
	///   main thread.
	///
	/// @warning Must be called only on render thread.
	///
	/// @attention C99 equivalent is `bgfx_override_internal_texture`.
	///
	uintptr_t overrideInternal(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, TextureFormat::Enum _format, uint32_t _flags = BGFX_TEXTURE_NONE);

} // namespace bgfx

#if BX_PLATFORM_ANDROID
#	include <android/native_window.h>

namespace bgfx
{
	///
	inline void androidSetWindow(::ANativeWindow* _window)
	{
		PlatformData pd;
		pd.ndt          = NULL;
		pd.nwh          = _window;
		pd.context      = NULL;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#elif BX_PLATFORM_IOS
namespace bgfx
{
	///
	inline void iosSetEaglLayer(void* _window)
	{
		PlatformData pd;
		pd.ndt          = NULL;
		pd.nwh          = _window;
		pd.context      = NULL;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#elif BX_PLATFORM_BSD || BX_PLATFORM_LINUX || BX_PLATFORM_RPI

namespace bgfx
{
	///
	inline void x11SetDisplayWindow(void* _display, uint32_t _window, void* _glx = NULL)
	{
		PlatformData pd;
		pd.ndt          = _display;
		pd.nwh          = (void*)(uintptr_t)_window;
		pd.context      = _glx;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#elif BX_PLATFORM_NACL
#	include <ppapi/c/ppb_graphics_3d.h>
#	include <ppapi/c/ppb_instance.h>

namespace bgfx
{
	typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);

	///
	bool naclSetInterfaces(::PP_Instance, const ::PPB_Instance*, const ::PPB_Graphics3D*, PostSwapBuffersFn);

} // namespace bgfx

#elif BX_PLATFORM_OSX
namespace bgfx
{
	///
	inline void osxSetNSWindow(void* _window, void* _nsgl = NULL)
	{
		PlatformData pd;
		pd.ndt          = NULL;
		pd.nwh          = _window;
		pd.context      = _nsgl;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#elif BX_PLATFORM_WINDOWS
#	include <windows.h>

namespace bgfx
{
	///
	inline void winSetHwnd(::HWND _window)
	{
		PlatformData pd;
		pd.ndt          = NULL;
		pd.nwh          = _window;
		pd.context      = NULL;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#elif BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT
#   include <Unknwn.h>

namespace bgfx
{
	///
	inline void winrtSetWindow(::IUnknown* _window)
	{
		PlatformData pd;
		pd.ndt          = NULL;
		pd.nwh          = _window;
		pd.context      = NULL;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#endif // BX_PLATFORM_

#if defined(_SDL_syswm_h)
// If SDL_syswm.h is included before bgfxplatform.h we can enable SDL window
// interop convenience code.

namespace bgfx
{
	///
	inline bool sdlSetWindow(SDL_Window* _window)
	{
		SDL_SysWMinfo wmi;
		SDL_VERSION(&wmi.version);
		if (!SDL_GetWindowWMInfo(_window, &wmi) )
		{
			return false;
		}

		PlatformData pd;
#	if BX_PLATFORM_LINUX || BX_PLATFORM_BSD
		pd.ndt          = wmi.info.x11.display;
		pd.nwh          = (void*)(uintptr_t)wmi.info.x11.window;
#	elif BX_PLATFORM_OSX
		pd.ndt          = NULL;
		pd.nwh          = wmi.info.cocoa.window;
#	elif BX_PLATFORM_WINDOWS
		pd.ndt          = NULL;
		pd.nwh          = wmi.info.win.window;
#	elif BX_PLATFORM_STEAMLINK
		pd.ndt          = wmi.info.vivante.display;
		pd.nwh          = wmi.info.vivante.window;
#	endif // BX_PLATFORM_
		pd.context      = NULL;
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);

		return true;
	}

} // namespace bgfx

#elif defined(_glfw3_h_)
// If GLFW/glfw3.h is included before bgfxplatform.h we can enable GLFW3
// window interop convenience code.

#	if BX_PLATFORM_LINUX || BX_PLATFORM_BSD
#		define GLFW_EXPOSE_NATIVE_X11
#		define GLFW_EXPOSE_NATIVE_GLX
#	elif BX_PLATFORM_OSX
#		define GLFW_EXPOSE_NATIVE_COCOA
#		define GLFW_EXPOSE_NATIVE_NSGL
#	elif BX_PLATFORM_WINDOWS
#		define GLFW_EXPOSE_NATIVE_WIN32
#		define GLFW_EXPOSE_NATIVE_WGL
#	endif //
#	include <GLFW/glfw3native.h>

namespace bgfx
{
	inline void glfwSetWindow(GLFWwindow* _window)
	{
		PlatformData pd;
#	if BX_PLATFORM_LINUX || BX_PLATFORM_BSD
		pd.ndt          = glfwGetX11Display();
		pd.nwh          = (void*)(uintptr_t)glfwGetGLXWindow(_window);
		pd.context      = glfwGetGLXContext(_window);
#	elif BX_PLATFORM_OSX
		pd.ndt          = NULL;
		pd.nwh          = glfwGetCocoaWindow(_window);
		pd.context      = glfwGetNSGLContext(_window);
#	elif BX_PLATFORM_WINDOWS
		pd.ndt          = NULL;
		pd.nwh          = glfwGetWin32Window(_window);
		pd.context      = NULL;
#	endif // BX_PLATFORM_WINDOWS
		pd.backBuffer   = NULL;
		pd.backBufferDS = NULL;
		setPlatformData(pd);
	}

} // namespace bgfx

#endif // defined(_SDL_H)

#endif // BGFX_PLATFORM_H_HEADER_GUARD


text:
import fetch from 'node-fetch';
import { sites } from './sites';

import { Image, ImageData } from './Image';

const VERSION = 2;

interface SearchRequest {
	tags?: string[];
	exclude?: string[];
	limit?: number;
	random?: boolean;
}

interface Sites {
	[key: string]: {
		aliases: string[];
		nsfw: boolean;
		endpoint: string;
		random: boolean;
	};
}

function resolveSite(resolvable: string): string | null {
	if (typeof resolvable !== 'string') return null;
	resolvable = resolvable.toLowerCase();
	for (const site of Object.keys(sites)) {
		if (site === resolvable || (sites as Sites)[site].aliases.includes(resolvable)) return site;
	}
	return null;
}

function shuffle<T>(array: T): T {
	if (!Array.isArray(array)) throw new TypeError(`Expected an Array, got ${typeof array} instead.`);
	for (let i = array.length - 1; i > 0; i--) {
		const j = Math.floor(Math.random() * (i + 1));
		const tmp = array[i] as unknown;
		array[i] = array[j] as unknown;
		array[j] = tmp;
	}
	return array;
}

export async function search(
	site: string,
	{ tags = [], exclude = [], limit = 1, random = false }: SearchRequest = {
		tags: [],
		exclude: [],
		limit: 1,
		random: false,
	},
): Promise<Image[]> {
	if (!Array.isArray(tags)) throw new Error('Tags have to be an array.');
	if (typeof limit !== 'number' && !Number.isNaN(limit)) throw new Error('Limit has to be a number.');
	const s = resolveSite(site);
	if (!s) throw new Error('This site is not supported.');
	const { endpoint, random: rand } = (sites as Sites)[s];
	let rngLimit = 0;
	if (random) {
		if (rand) tags.push('order:random');
		else rngLimit = 100;
	}

	const userAgent = `Kaori, a npm module for boorus. v${VERSION} (https://github.com/iCrawl/kaori/)`;
	const options = { headers: { 'User-Agent': userAgent } };

	try {
		const res = await fetch(
			`https://${s}${endpoint}tags=${tags.join('+')}&limit=${rngLimit ? rngLimit : limit}`,
			options,
		);
		const res2 = res.clone();
		const text = await res2.text();
		if (!text) throw new Error('Encountered empty response');
		const json = (await res.json()) as ImageData[];
		let images: Image[] = json.map((image) => new Image(image, s));
		if (rngLimit) {
			images = shuffle(images).slice(0, limit);
		}
		if (exclude.length) {
			const left = images.filter((image) => image.tags.every((tag) => !exclude.includes(tag)));
			return left;
		}
		return images;
	} catch (error) {
		throw error;
	}
}


text:
'use strict';

const table = require('./table');

function formatSoapPorts(ports) {
    const header = [
        {value: 'Port'},
        {value: 'Active'},
        {value: 'Shadow'},
        {value: 'URL', align: 'left'},
    ];
    const rows = ports
        .map(s => [s['port'], s['active'], s['shadowPort'], s['url']]);

    return table.renderTable(header, rows, {compact: false});
}

function formatRestPorts(ports) {
    const header = [
        {value: 'Port'},
        {value: 'Active'},
        {value: 'ID'},
        {value: 'URL', align: 'left'},
    ];
    const rows = ports
        .map(s => [s['port'], s['active'], s['id'], s['url']]);

    return table.renderTable(header, rows, {compact: false});
}

/** @type OutputFormatters */
module.exports = {

    responseFormatter: response => {

        let result = `Category: ${response['category'] || '?'}`;
        if(response['soapInfo'] && response['soapInfo'].length > 0) {
            result += '\n\nSOAP Ports:';
            result += formatSoapPorts(response['soapInfo']);
        }
        if(response['restInfo'] && response['restInfo'].length > 0) {
            result += '\n\nREST Ports:';
            result += formatRestPorts(response['restInfo']);
        }

        return result;
    }
};


text:
int main()
{
  Tree<int> myTree;

  myTree.insertNode(8);
  myTree.insertNode(3);
  myTree.insertNode(1);
  myTree.insertNode(6);
  myTree.insertNode(4);
  myTree.insertNode(7);
  myTree.insertNode(10);
  myTree.insertNode(14);
  myTree.insertNode(13);

  myTree.inOrderTraversal();
  myTree.preOrderTraversal();
  myTree.postOrderTraversal();
}


text:
'''Inverse kinematics for 3dof legs.'''

import math

from ..tf.tf import Point3D

class Configuration(object):
    coxa_min_deg = None
    coxa_idle_deg = None
    coxa_max_deg = None
    coxa_length_mm = None
    coxa_sign = 1
    coxa_ident = None

    femur_min_deg = None
    femur_idle_deg = None
    femur_max_deg = None
    femur_length_mm = None
    femur_sign = 1
    femur_ident = None

    tibia_min_deg = None
    tibia_idle_deg = None
    tibia_max_deg = None
    tibia_length_mm = None
    tibia_sign = 1
    tibia_ident = None

    servo_speed_dps = 360.0

    @staticmethod
    def get_attributes():
        return [key for key, value in Configuration.__dict__.iteritems()
                if (not key.startswith('__') and
                    not callable(value) and
                    not isinstance(value, staticmethod))]

    def write_settings(self, config, group_name):
        config.add_section(group_name)

        for x in Configuration.get_attributes():
            config.set(group_name, x, getattr(self, x))

    @staticmethod
    def read_settings(config, group_name):
        result = Configuration()
        for x in Configuration.get_attributes():
            if config.has_option(group_name, x):
                if x.endswith('sign') or x.endswith('ident'):
                    value = config.getint(group_name, x)
                else:
                    value = config.getfloat(group_name, x)
                setattr(result, x, value)
        return result

class JointAngles(object):
    config = None
    coxa_deg = None # positive is rotating clockwise viewed from top
    femur_deg = None # positive is rotating upward
    tibia_deg = None # positive is rotating upward

    def command_dict(self):
        '''Return a dictionary mapping servo identifiers to commands
        in degrees.  This is the same format as the servo_controller
        module uses.'''
        return { self.config.coxa_ident : self.coxa_deg,
                 self.config.femur_ident : self.femur_deg,
                 self.config.tibia_ident : self.tibia_deg }

def lizard_3dof_ik(point_mm, config):
    '''Given a target end position in 3D coordinate space, return the
    required joint angles for a 3 degree of freedom lizard style
    leg.

    +y is away from the shoulder
    +x is clockwise from shoulder
    +z is up

    If no solution is possible, return None.
    '''
    # Solve for the coxa first, as it has only a single solution.
    coxa_deg = (config.coxa_sign *
                math.degrees(math.atan2(point_mm.x, point_mm.y)) +
                config.coxa_idle_deg)

    if (coxa_deg < config.coxa_min_deg or
        coxa_deg > config.coxa_max_deg):
        return None

    # x-coordinate of femur/tibia pair after rotating to 0 coxa
    true_x = (math.sqrt(point_mm.x ** 2 + point_mm.y ** 2) -
              config.coxa_length_mm)
    im = math.sqrt(point_mm.z ** 2 + true_x ** 2)

    # The new femur/tibia pair makes a triangle where the 3rd side is
    # the hypotenuse of the right triangle composed of z and im, lets
    # call it c.
    #
    #           --\  femur
    #           |\ --\
    #           | \   --\
    #           |  --    |
    #          z|  im\   | tibia
    #           |     --\|
    #           ----------
    #            true_x
    #
    # im = math.sqrt(z ** 2 + true_x ** 2)
    #
    # Then, we can use the law of cosines to find the angle opposite
    # im, which is the angle between the femur and tibia.
    #
    # im ** 2 = a ** 2 + b ** 2 + 2 * a * b * cos(C)
    #
    # Solving for C yields:
    #
    #  C = acos((im ** 2 - a ** 2 - b ** 2) / (2 * a * b))

    tibia_cos = ((im ** 2 -
                  config.tibia_length_mm ** 2 -
                  config.femur_length_mm ** 2) /
                 (2 * config.tibia_length_mm * config.femur_length_mm))
    if tibia_cos < -1.0 or tibia_cos > 1.0:
        return None

    # For our purposes, a 0 tibia angle should equate to a right angle
    # with the femur, so subtract off 90 degrees.
    tibia_deg = (config.tibia_sign *
                 math.degrees(0.5 * math.pi - math.acos(tibia_cos)) +
                 config.tibia_idle_deg)

    if (tibia_deg < config.tibia_min_deg or
        tibia_deg > config.tibia_max_deg):
        return None

    # To solve for the femur angle, we first get the angle opposite
    # true_x, then the angle opposite the tibia.
    true_x_deg = math.degrees(math.atan2(true_x, -point_mm.z))

    # Then the angle opposite the tibia is also found the via the law
    # of cosines.
    #
    #  tibia ** 2 = femur ** 2 + im ** 2 + 2 * femur * im * cos(femur_im)
    #
    #  femur_im = acos ( (tibia ** 2 - im ** 2 - femur ** 2) /
    #                    (2 * femur * im) )

    femur_im_cos = -(config.tibia_length_mm ** 2 -
                     config.femur_length_mm ** 2 -
                     im ** 2) / (2 * config.femur_length_mm * im)
    if femur_im_cos < -1.0 or femur_im_cos > 1.0:
        return None

    femur_im_deg = math.degrees(math.acos(femur_im_cos))

    femur_deg = (config.femur_sign * ((femur_im_deg + true_x_deg) - 90.0) +
                 config.femur_idle_deg)

    if (femur_deg < config.femur_min_deg or
        femur_deg > config.femur_max_deg):
        return None

    result = JointAngles()
    result.config = config
    result.coxa_deg = coxa_deg
    result.femur_deg = femur_deg
    result.tibia_deg = tibia_deg

    return result

class LizardIk(object):
    def __init__(self, config):
        self.config = config

    def do_ik(self, point_mm):
        return lizard_3dof_ik(point_mm, self.config)

    def worst_case_speed_mm_s(self, point_mm, direction_mm=None):
        '''Return the worst case linear velocity the end effector can
        achieve in the given orientation.'''
        step = 0.01
        nominal = self.do_ik(point_mm)

        if nominal is None:
            return None

        servo_step = step * self.config.servo_speed_dps
        result = None

        def update(result, advanced_servo_deg, nominal_servo_deg):
            if advanced_servo_deg == nominal_servo_deg:
                return

            this_speed = (servo_step /
                          abs(advanced_servo_deg - nominal_servo_deg))

            if result is None or this_speed < result:
                result = this_speed

            return result

        if direction_mm:
            normalized = direction_mm.scaled(1.0 / direction_mm.length())
            consider = [normalized.scaled(step)]
        else:
            consider = [Point3D(*val) for val in
                        (step, 0., 0.), (0., step, 0.), (0., 0., step)]

        for advance in consider:
            advanced = self.do_ik(point_mm + advance)

            if advanced is None:
                return None

            result = update(result, advanced.coxa_deg, nominal.coxa_deg)
            result = update(result, advanced.femur_deg, nominal.femur_deg)
            result = update(result, advanced.tibia_deg, nominal.tibia_deg)

        return result

    def servo_speed_dps(self):
        return self.config.servo_speed_dps

    def largest_change_deg(self, result1, result2):
        return max(abs(result1.coxa_deg - result2.coxa_deg),
                   abs(result1.femur_deg - result2.femur_deg),
                   abs(result1.tibia_deg - result2.tibia_deg))


text:
<!DOCTYPE html>

<link rel="import" href="/base/base.html">
<link rel="import" href="/model/card.html">

<script>

mm.exportTo('mm.m', function() {

  function CardStack() {
    this.cards_ = [];
  }

  CardStack.prototype = {
    get size() {
      return this.cards_.length;
    },

    get topColor() {
      return this.size == 0 ? undefined : this.cards_[this.size - 1].color;
    },

    get topCard() {
      return this.size == 0 ? undefined : this.cards_[this.size - 1];
    },

    get cards() {
      return this.cards_.slice(0);
    },

    push: function(card) {
      this.cards_.push(card);
    },

    pop: function() {
      return this.cards_.pop();
    },

    remove: function(index) {
      return this.cards_.splice(index);
    },

    clear: function() {
      this.cards_ = [];
    },

    format: function(prefix) {
      if (this.cards_.length === 0)
        return prefix + 'Empty\n';
      output = '';
      this.cards_.forEach(function(card) {
        output += card.format(prefix) + '\n';
      });
      return output;
    },

    computeScore: function() {
      var idToInfo = {};
      this.cards_.forEach(function (card) {
        var info = idToInfo[card.treasureId] || { count: 0, multi: false };
        if (info.count > 0)
          info.multi = true;
        info.count += card.treasureCount;
        idToInfo[card.treasureId] = info;
      });
      var score = 0;
      Object.keys(idToInfo).forEach(function (key) {
        var info = idToInfo[key];
        score += info.count;
        if (info.multi)
          score += info.count;
      });
      return score;
    },

    isCursed: function() {
      return this.numCursed() > 0;
    },

    numCursed: function() {
      var badSum = 0;
      this.cards_.forEach(function (card) {
        switch (card.symbol) {
          case Card.SYMBOL_NONE:
            return;
          case Card.SYMBOL_AMULET:
            badSum -= 1;
          case Card.SYMBOL_MUMMY:
          case Card.SYMBOL_WEREWOLF:
          case Card.SYMBOL_MONSTER:
            badSum += 1;
        }
      });
      return badSum;
    },

    hasSymbol: function(symbol) {
      return this.cards_.some(function (card) {
        return card.symbol === symbol;
      });
    },

    shuffle: function() {
      for(var j, x, i = this.cards_.length; i;) {
        j = Math.floor(Math.random() * i);
        x = this.cards_[--i];
        this.cards_[i] = this.cards_[j];
        this.cards_[j] = x;
      }
    },

    distribute: function(stacks) {
      var i = 0;
      this.cards_.forEach(function(card){
        stacks[i].push(card);
        i = (i + 1) % stacks.length;
      });
    },

    colors: function() {
      var result = [];
      this.cards_.forEach(function(card){
        result.push(card.color);
      });
      return result;
    }
  };

  return {
    CardStack: CardStack
  };
});

</script>


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: AT2.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="AT2" comment="To specify Bill of Lading quantity, weight, commodity classification and other details.">
  <Field name="LadingQuantity1" type="long" required="y" min="1" max="7" comment="Number of units (pieces) of the lading commodity"/>
  <Field name="PackagingFormCode1" required="y" min="3" max="3" validation="T211" comment="Code for packaging form of the lading quantity"/>
  <Field name="WeightQualifier" min="1" max="2" validation="T187" comment="Code defining the type of weight"/>
  <Field name="WeightUnitCode" min="1" max="1" validation="T188" comment="Code specifying the weight unit"/>
  <Field name="Weight" type="double" min="1" max="10" comment="Numeric value of weight"/>
  <Field name="LadingQuantity2" type="long" required="y" min="1" max="7" comment="Number of units (pieces) of the lading commodity"/>
  <Field name="PackagingFormCode2" required="y" min="3" max="3" validation="T211" comment="Code for packaging form of the lading quantity"/>
  <Field name="YesNoConditionOrResponseCode1" required="y" min="1" max="1" validation="T1073" comment="Code indicating a Yes or No condition or response"/>
  <Field name="CommodityCode" required="y" min="1" max="30" comment="Code describing a commodity or group of commodities"/>
  <Field name="FreightClassCode" required="y" min="2" max="5" comment="Code indicating generalized classification that applies to one or more items in the shipment, i.e., class 70, 77.5, etc."/>
  <Field name="YesNoConditionOrResponseCode2" required="y" min="1" max="1" validation="T1073" comment="Code indicating a Yes or No condition or response"/>
  <Field name="LadingValue" type="double" required="y" min="2" max="9" comment="Value of shipment for export, expressed in the standard monetary denomination for the currency specified"/>
</Segment>


text:
<!doctype HTML>

		<title>Icons Preview!</title>

	<link href="icons.fallback.css" rel="stylesheet">

.icon-test:


text:
A NodeJS module that splits a file into parts while preserving lines.

Install with `npm install split-by-line`

##Example
Split by line splits a file into a specified number of files but preserves the lines of the file.

```Javascript
const splitByLine = require('split-by-line');

splitByLine('file.txt', {
	number: 3
}, function(err, files) {
	// files is an array with the resulting filenames
	console.log(files);
	// Prints:
	// ['file.txt.part0', 'file.txt.part1', 'file.txt.part2']
});
```

## Api
`splitByLine(inputFile, [opts], callback)`

- the first parameter is the file that gets split
- the second parameter are optional options
- the callback will be called with `err` and `files`, where files is an array containing the file names of the created files

*Currently it is not guaranteed that the lines stay in order*

### Options
```Javascript
options = {
	number: 2, // The number of files that are created (1000 is maximum)
	keepEmpty: true, // If the number of files is bigger than the number of lines, decide whether to keep the remaining empty files or not
	outputDir: path.dirname(inputFile), // The folder in which the files are stored
	minLines: 1 // The minimum number of lines one file should have.
}
```


text:
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/ban-types */
import cx from "classnames"
import React, { ReactElement, ReactNode } from "react"
import styled from "styled-components"
import { colors } from "../GlobalStyle"
import { Meta } from "../../utils/Meta"

const GridTable = styled.table`
    border-collapse: collapse;
    table-layout: fixed;
    border-spacing: 0;

    > thead {
        > tr {
            border-bottom: 1px solid ${colors.__bg2};
            > th {
                padding: 4px 8px;
                white-space: nowrap;
                cursor: default;
                font-weight: normal;
                text-align: left;
                vertical-align: top;
                box-sizing: border-box;
                &:hover {
                    background-color: ${colors.__bg2};
                }
                &.sorted {
                    &.asc {
                        background-color: ${colors.__bg2};
                    }
                    &.desc {
                        background-color: ${colors.__bg3};
                    }
                }
            }
        }
    }

    > tfoot {
        > tr {
            > th {
                padding: 4px 8px;
                white-space: nowrap;
                cursor: pointer;
                font-weight: bold;
                > button {
                    width: 100%;
                    min-height: 100%;
                    border: none;
                    background-color: inherit;
                    padding: 4px;
                }
            }
            &:hover {
                outline: 1px solid #ccc;
            }
        }
    }
`
const GridDiv = styled.div`
    > .Pager {
        display: inline-block;
        margin: 0 5px;
        > .Pages > .Page {
            display: inline-block;
            width: 20px;
            line-height: 20px;
        }
        > .PagerInfo {
            display: inline-block;
            margin: 0 5px;
        }

        > .NextPage {
            visibility: hidden;
        }
        > .PrevPage {
            visibility: hidden;
        }
    }

    > .Search {
        display: inline-block;
    }
`
export interface ColumnsConfig<T, K extends {}> {
    keys: Meta<K, string>
    getters?: Partial<Meta<K, (item: T, index: number) => unknown>>
    visibleColumns?: (keyof K)[]
}

export interface GridProps<T, K extends {}> {
    className?: string
    items: T[]
    headers?: Partial<Meta<K, () => ReactElement>>
    children?: Partial<Meta<K, (item: T, index: number) => ReactNode>>
    head?: boolean
    body?: boolean
    columns: ColumnsConfig<T, K>

    GetRowClass?: (item: T) => string
    onItemClick?: (e: React.MouseEvent, item: T) => void
    onItemMouseDown?: (e: React.MouseEvent, item: T) => void
    onItemDoubleClick?: (e: React.MouseEvent, item: T) => void

    getHeaderClass?: (column: keyof K) => string
    getCellClass?: (column: keyof K, item: T) => string
    orderBy?: (column: keyof K) => void
    classNames?: Partial<Meta<K, string>>
    titles?: Partial<Meta<K, string>>
}

export function Grid<T, K extends {}>({
    columns,
    GetRowClass,
    onItemClick,
    onItemMouseDown,
    onItemDoubleClick,
    items,
    orderBy,
    body = true,
    children,
    headers,
    classNames,
    titles,
    head,
    className,
    getHeaderClass,
    getCellClass,
}: GridProps<T, K>) {
    const { keys, visibleColumns, getters } = columns
    const cells = children

    return (
        <GridDiv className={className}>
            <GridTable>
                {head && (

                            {visibleColumns?.map(
                                column =>
                                    headers?.[column]?.() ?? (
                                         orderBy?.(column)}
                                        >
                                            {headers?.[column]?.() ?? titles?.[column] ?? keys[column]}

                                    )
                            )}

                )}
                {body && (

                        {items?.map((item, itemIndex) => (

 onItemMouseDown?.(e, item)}
                                onClick={e => onItemClick?.(e, item)}
                                onDoubleClick={e => onItemDoubleClick?.(e, item)}
                            >
                                {visibleColumns?.map(column => (

                                        {cells?.[column]?.(item, itemIndex) ?? {getters?.[column] as any}}

                                ))}

                        ))}

                )}
            </GridTable>
        </GridDiv>
    )
}


text:
$(document).ready(function() {
    var converter = Markdown.getSanitizingConverter();

    converter.hooks.chain("preConversion", function (text) {
        return text.replace(/===cut===/g, '');
    });

    var editor = new Markdown.Editor(converter);

    editor.run();

    $("#wmd-button-row").append(
        '
short/full text separator
');

    jQuery.fn.extend({
        insertAtCaret: function(myValue){
            return this.each(function(i) {
                if (document.selection) {
                    this.focus();
                    var sel = document.selection.createRange();
                    sel.text = myValue;
                    this.focus();
                }
                else if (this.selectionStart || this.selectionStart == '0') {
                    var startPos = this.selectionStart;
                    var endPos = this.selectionEnd;
                    var scrollTop = this.scrollTop;
                    this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
                    this.focus();
                    this.selectionStart = startPos + myValue.length;
                    this.selectionEnd = startPos + myValue.length;
                    this.scrollTop = scrollTop;
                } else {
                    this.value += myValue;
                    this.focus();
                }
            });
        }
    });

    $('#insertSeparator').click(function(){
        var $textarea = $('#wmd-input');
        $textarea.insertAtCaret('===cut===');
    });

    $("#postForm").validate({
        rules: {
            title: {
                required: true,
                minlength: 3
            },
            tags: {
                required: true
            },
            text: {
                required: true,
                minlength: 50
            }
        }
    });

    $(window).bind('beforeunload', function(){
        if ($.trim($('#wmd-input').val()) != '')
            return 'You have not submitted your post.';
    });

    $(document).on("submit", "form", function(event){
        $(window).off('beforeunload');
    });
});


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"strconv"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
)

// OpenpitrixGroupDetailUserSet users in group
// swagger:model openpitrixGroupDetailUserSet
type OpenpitrixGroupDetailUserSet []*OpenpitrixUser

// Validate validates this openpitrix group detail user set
func (m OpenpitrixGroupDetailUserSet) Validate(formats strfmt.Registry) error {
	var res []error

	for i := 0; i < len(m); i++ {

		if swag.IsZero(m[i]) { // not required
			continue
		}

		if m[i] != nil {

			if err := m[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName(strconv.Itoa(i))
				}
				return err
			}
		}

	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
//
//  ========================================================================
//  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.security.jaspi.callback;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;

import org.eclipse.jetty.util.security.Credential;

/**
 * CredentialValidationCallback
 *
 * Store a jetty Credential for a user so that it can be
 * validated by jaspi
 */
public class CredentialValidationCallback implements Callback
{
    private Credential _credential;
    private boolean _result;
    private Subject _subject;
    private String _userName;

    public CredentialValidationCallback (Subject subject, String userName, Credential credential)
    {
        _subject = subject;
        _userName = userName;
        _credential = credential;
    }

    public Credential getCredential ()
    {
        return _credential;
    }

    public void clearCredential ()
    {
        _credential = null;
    }

    public boolean getResult()
    {
        return _result;
    }

    public javax.security.auth.Subject getSubject()
    {
        return _subject;
    }

    public java.lang.String getUsername()
    {
        return _userName;
    }

    public void setResult(boolean result)
    {
        _result = result;
    }

}


text:
import pyglet
from pyglet.gl import *

def screenshot(name='screenshot'):
    """
    Take a screenshot

    Parameters:
    name : string : Default 'screenshot'.  Name of the saved image.  Will
        always save as .png
    """
    # Get the 'the back-left color buffer'
    pyglet.image.get_buffer_manager().get_color_buffer().save('%s.png' % name)

def getPixelValue(x, y):
    """
    Return the RGBA 0-255 color value of the pixel at the x,y position.
    """
    # BufferManager, ColorBufferImage
    color_buffer = pyglet.image.get_buffer_manager().get_color_buffer()
    # AbstractImage, ImageData, sequece of bytes
    pix = color_buffer.get_region(
        x, y, 1, 1).get_image_data().get_data(
        "RGBA", 4)
    return pix[0], pix[1], pix[2], pix[3]

def drawPoint(x, y, color):
    """
    Based on the (r,g,b) color passed in, draw a point at the given x,y coord.
    """
    pyglet.graphics.draw(1, GL_POINTS,
                         ('v2i', (x, y)),
                         ('c3B', (color[0], color[1], color[2])))

def getSmoothConfig():
    """
    Sets up a configuration that allows of smoothing\antialiasing.
    The return of this is passed to the config parameter of the created window.
    """
    try:
        # Try and create a window config with multisampling (antialiasing)
        config = Config(sample_buffers=1, samples=4,
                        depth_size=16, double_buffer=True)
    except pyglet.window.NoSuchConfigException:
        print "Smooth contex could not be aquiried."
        config = None
    return config

def printEvents(window):
    """
    Debug tool that will print the events to the console.

    window is an instance of a Window object receiving the events.
    """
    window.push_handlers(pyglet.window.event.WindowEventLogger())

def playMusic(music):
    """
    Simple wrapper to play a music (mp3) file.

    music : music file relative to application.
    """
    music = pyglet.resource.media(music)
    music.play()

def setBackgroundColor(color):
    """
    Color is a list of four values, [r,g,b,a], each from 0 -> 1
    """
    pyglet.gl.glClearColor(*color)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
  <title>JBoss A-MQ Console</title>

          Red Hat®
          JBoss® A-MQ

        Support

Page not found!

Useful Links

Documentation

      © 2013 Red Hat, Inc. and/or its affiliates. All rights reserved.


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Seefeld, Austria</formatted_address>
  <address_component>
   <long_name>Seefeld</long_name>
   <short_name>Seefeld</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Seefeld in Tirol</long_name>
   <short_name>Gemeinde Seefeld in Tirol</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Innsbruck-Land District</long_name>
   <short_name>Innsbruck-Land District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Tyrol</long_name>
   <short_name>Tyrol</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>47.3300017</lat>
    <lng>11.1877742</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>47.3193200</lat>
     <lng>11.1636999</lng>
    </southwest>
    <northeast>
     <lat>47.3698400</lat>
     <lng>11.2571600</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>47.3193200</lat>
     <lng>11.1636999</lng>
    </southwest>
    <northeast>
     <lat>47.3698400</lat>
     <lng>11.2571600</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJORw1LwYRnUcR_DELmK6v64A</place_id>
 </result>
</GeocodeResponse>


text:
package com.kiuwan.client.examples;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.kiuwan.client.KiuwanClientException;
import com.kiuwan.client.KiuwanRestApiClient;
import com.kiuwan.client.model.management.applications.ApplicationBean;
import com.kiuwan.client.model.management.applications.PortfolioBean;

public class CreateApplications {

	public static void main(String[] args) throws KiuwanClientException {
		if(args.length != 2)
	    {
	        System.out.println("You need to pass 2 parameters: username password");
	        return;
	    }

		String username = args[0];
		String password = args[1];

		PortfolioBean portfolioBean = new PortfolioBean();
		portfolioBean.setPortfolioName("MyPortfolio");
		portfolioBean.setPortfolioValue("LightweightApplications");

		Collection<PortfolioBean> portfolios = new ArrayList<PortfolioBean>();
		portfolios.add(portfolioBean);

		Map<String, Double> targets = new HashMap<String, Double>();
		targets.put(ApplicationBean.TARGET_EFFICIENCY, 1.0);
		targets.put(ApplicationBean.TARGET_MAINTAINABILITY, 2.0);
		targets.put(ApplicationBean.TARGET_PORTABILITY, 3.0);
		targets.put(ApplicationBean.TARGET_RELIABILITY, 4.0);
		targets.put(ApplicationBean.TARGET_SECURITY, 5.0);

		ApplicationBean application = new ApplicationBean();
		application.setName("MyFirstApplication");
		application.setModel("CQM");
		application.setDescription("This is my first application created in Kiuwan.");
		application.setPortfolios(portfolios);
		application.setBusinessValue(ApplicationBean.BUSINESS_VALUE_LOW);
		application.setTargets(targets);

		KiuwanRestApiClient client = new KiuwanRestApiClient(username, password);
		String result = client.createApplications(Collections.singletonList(application));

		System.out.println(result);
	}

}


text:
package testPullUpGen.test31.expectedresult;

public interface B extends I2, I<String> {

}