text:
google.charts.load('current', {packages: ['corechart', 'gauge', 'default', 'format', 'ui', 'table']});

function humanize(num, size, units) {
  var unit;
  for (unit = units.pop(); units.length && num >= size; unit = units.pop()) {
    num /= size;
  }
  return [num, unit];
}

// Following the IEC naming convention
function humanizeIEC(num) {
  var ret = humanize(num, 1024, ['TiB', 'GiB', 'MiB', 'KiB', 'B']);
  return ret[0].toFixed(2) + ' ' + ret[1];
}
// Following the Metric naming convention

function humanizeMetric(num) {
  var ret = humanize(num, 1000, ['TB', 'GB', 'MB', 'KB', 'Bytes']);
  return ret[0].toFixed(2) + ' ' + ret[1];
}

// Draw a table.
function drawTable(
    seriesTitles, titleTypes, data, elementId, numPages, sortIndex) {
  var dataTable = new google.visualization.DataTable();
  for (var i = 0; i < seriesTitles.length; i++) {
    dataTable.addColumn(titleTypes[i], seriesTitles[i]);
  }
  dataTable.addRows(data);
  if (!(elementId in window.charts)) {
    window.charts[elementId] =
        new google.visualization.Table(document.getElementById(elementId));
  }

  var cssClassNames = {
    'headerRow': '',
    'tableRow': 'table-row',
    'oddTableRow': 'table-row'
  };
  var opts = {
    alternatingRowStyle: true,
    page: 'enable',
    pageSize: numPages,
    allowHtml: true,
    sortColumn: sortIndex,
    sortAscending: false,
    cssClassNames: cssClassNames
  };
  window.charts[elementId].draw(dataTable, opts);
}

// Draw a line chart.
function drawLineChart(seriesTitles, data, elementId, unit) {
  var min = Infinity;
  var max = -Infinity;
  for (var i = 0; i < data.length; i++) {
    // Convert the first column to a Date.
    if (data[i] != null) {
      data[i][0] = new Date(data[i][0]);
    }

    // Find min, max.
    for (var j = 1; j < data[i].length; j++) {
      var val = data[i][j];
      if (val < min) {
        min = val;
      }
      if (val > max) {
        max = val;
      }
    }
  }

  // We don't want to show any values less than 0 so cap the min value at that.
  // At the same time, show 10% of the graph below the min value if we can.
  var minWindow = min - (max - min) / 10;
  if (minWindow < 0) {
    minWindow = 0;
  }

  // Add the definition of each column and the necessary data.
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('datetime', seriesTitles[0]);
  for (var i = 1; i < seriesTitles.length; i++) {
    dataTable.addColumn('number', seriesTitles[i]);
  }
  dataTable.addRows(data);

  // Create and draw the visualization.
  if (!(elementId in window.charts)) {
    window.charts[elementId] =
        new google.visualization.LineChart(document.getElementById(elementId));
  }

  // TODO(vmarmol): Look into changing the view window to get a smoother
  // animation.
  var opts = {
    curveType: 'function',
    height: 300,
    legend: {position: 'none'},
    focusTarget: 'category',
    vAxis: {
      title: unit,
      viewWindow: {
        min: minWindow,
      }
    },
    legend: {
      position: 'bottom'
    }
  };
  // If the whole data series has the same value, try to center it in the chart.
  if (min == max) {
    opts.vAxis.viewWindow.max = 1.1 * max;
    opts.vAxis.viewWindow.min = 0.9 * max;
  }

  window.charts[elementId].draw(dataTable, opts);
}

// Gets the length of the interval in nanoseconds.
function getInterval(current, previous) {
  var cur = new Date(current);
  var prev = new Date(previous);

  // ms -> ns.
  return (cur.getTime() - prev.getTime()) * 1000000;
}

// Checks if the specified stats include the specified resource.
function hasResource(stats, resource) {
  return stats.stats.length > 0 && stats.stats[0][resource];
}

// Checks if all containers in provided list include the specified resource.
function hasResourceForAll(containerInfos, resource) {
  if (containerInfos.length === 0) {
    return false;
  }
  for (var i = 0; i < containerInfos.length; i++) {
    if (!hasResource(containerInfos[i], resource)) {
      return false;
    }
  }
  return true;
}

// Draw a set of gauges. Data is comprised of an array of arrays with two
// elements:
// a string label and a numeric value for the gauge.
function drawGauges(elementId, gauges) {
  gauges.unshift(['Label', 'Value']);

  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable(gauges);

  // Create and draw the visualization.
  var options = {
    height: 100,
    redFrom: 90,
    redTo: 100,
    yellowFrom: 75,
    yellowTo: 90,
    minorTicks: 5,
    animation: {duration: 900, easing: 'linear'}
  };
  var chart =
      new google.visualization.Gauge(document.getElementById(elementId));
  chart.draw(data, options);
}

// Get the machine info.
function getMachineInfo(rootDir, callback) {
  $.getJSON(rootDir + 'api/v1.0/machine', function(data) { callback(data); });
}

// Get ps info.
function getProcessInfo(rootDir, containerName, callback) {
  $.getJSON(rootDir + 'api/v2.0/ps' + containerName)
      .done(function(data) { callback(data); })
      .fail(function(jqhxr, textStatus, error) { callback([]); });
}

// Get the container stats for the specified container.
function getStats(rootDir, containerName, callback) {
  // Request 60s of container history and no samples.
  var request = JSON.stringify({
    // Update main.statsRequestedByUI while updating "num_stats" here.
    'num_stats': 60,
    'num_samples': 0
  });

  $.when(
       $.post(rootDir + 'api/v1.0/containers' + containerName, request),
       $.post(rootDir + 'api/v1.1/subcontainers' + containerName, request))
      .done(function(containersResp, subcontainersResp) {
        callback(containersResp[0], subcontainersResp[0]);
      });
}

// Draw the graph for CPU usage.
function drawCpuTotalUsage(elementId, machineInfo, stats) {
  if (stats.spec.has_cpu && !hasResource(stats, 'cpu')) {
    return;
  }

  var titles = ['Time', 'Total'];
  var data = [];
  for (var i = 1; i < stats.stats.length; i++) {
    var cur = stats.stats[i];
    var prev = stats.stats[i - 1];
    var intervalNs = getInterval(cur.timestamp, prev.timestamp);

    var elements = [];
    elements.push(cur.timestamp);
    elements.push((cur.cpu.usage.total - prev.cpu.usage.total) / intervalNs);
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Cores');
}

// Draw the graph for CPU load.
function drawCpuLoad(elementId, machineInfo, stats) {
  var titles = ['Time', 'Average'];
  var data = [];
  for (var i = 1; i < stats.stats.length; i++) {
    var cur = stats.stats[i];

    var elements = [];
    elements.push(cur.timestamp);
    elements.push(cur.cpu.load_average / 1000);
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Runnable threads');
}

// Draw the graph for per-core CPU usage.
function drawCpuPerCoreUsage(elementId, machineInfo, stats) {
  if (stats.spec.has_cpu && !hasResource(stats, 'cpu')) {
    return;
  }

  // Add a title for each core.
  var titles = ['Time'];
  for (var i = 0; i < machineInfo.num_cores; i++) {
    titles.push('Core ' + i);
  }
  var data = [];
  for (var i = 1; i < stats.stats.length; i++) {
    var cur = stats.stats[i];
    var prev = stats.stats[i - 1];
    var intervalNs = getInterval(cur.timestamp, prev.timestamp);

    if (cur.cpu.usage.per_cpu_usage == undefined) {
        return;
    }

    var elements = [];
    elements.push(cur.timestamp);
    for (var j = 0; j < machineInfo.num_cores; j++) {
      elements.push(
          (cur.cpu.usage.per_cpu_usage[j] - prev.cpu.usage.per_cpu_usage[j]) /
          intervalNs);
    }
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Cores');
}

// Draw the graph for CPU usage breakdown.
function drawCpuUsageBreakdown(elementId, machineInfo, containerInfo) {
  if (containerInfo.spec.has_cpu && !hasResource(containerInfo, 'cpu')) {
    return;
  }

  var titles = ['Time', 'User', 'Kernel'];
  var data = [];
  for (var i = 1; i < containerInfo.stats.length; i++) {
    var cur = containerInfo.stats[i];
    var prev = containerInfo.stats[i - 1];
    var intervalNs = getInterval(cur.timestamp, prev.timestamp);

    var elements = [];
    elements.push(cur.timestamp);
    elements.push((cur.cpu.usage.user - prev.cpu.usage.user) / intervalNs);
    elements.push(
        (cur.cpu.usage.system - prev.cpu.usage.system) / intervalNs);
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Cores');
}

// Return chart titles and data from an array of subcontainerInfos, using the
// passed dataFn to return the individual data points.
function getSubcontainerChartData(subcontainerInfos, dataFn) {
  var titles = ['Time'];
  var data = [];
  for (var i = 0; i < subcontainerInfos.length; i++) {
    titles.push(subcontainerInfos[i].name);
    for (var j = 1; j < subcontainerInfos[i].stats.length; j++) {
      var cur = subcontainerInfos[i].stats[j];
      var prev = subcontainerInfos[i].stats[j - 1];

      // Generate a sparse array with timestamp at index zero and data point at
      // index i+1, to be used as a DataTable row.
      var elements = [cur.timestamp];
      subcontainerInfos.forEach(function() {
        elements.push(null);
      });
      elements[i+1] = dataFn(cur, prev);
      data.push(elements);
    }
  }
  return {
    titles: titles,
    data: data,
  }
}

// Draw the graph for per-subcontainer CPU usage.
function drawCpuPerSubcontainerUsage(elementId, subcontainerInfos) {
  if (!hasResourceForAll(subcontainerInfos, 'cpu')) {
    return;
  }

  var chartData = getSubcontainerChartData(subcontainerInfos,
      function(cur, prev) {
    var intervalNs = getInterval(cur.timestamp, prev.timestamp);
    return (cur.cpu.usage.total - prev.cpu.usage.total) / intervalNs;
  });
  drawLineChart(chartData.titles, chartData.data, elementId, 'Cores');
}

// Draw the graph for per-subcontainer memory usage.
function drawMemoryPerSubcontainerUsage(elementId, subcontainerInfos) {
  if (!hasResourceForAll(subcontainerInfos, 'memory')) {
    return;
  }

  var chartData = getSubcontainerChartData(subcontainerInfos,
      function(cur, prev) {
    return cur.memory.usage / oneMegabyte;
  });
  drawLineChart(chartData.titles, chartData.data, elementId, 'Megabytes');
}

// Draw the gauges for overall resource usage.
function drawOverallUsage(elementId, machineInfo, containerInfo) {
  var cur = containerInfo.stats[containerInfo.stats.length - 1];
  var gauges = [];

  var cpuUsage = 0;
  if (containerInfo.spec.has_cpu && containerInfo.stats.length >= 2) {
    var prev = containerInfo.stats[containerInfo.stats.length - 2];
    var rawUsage = cur.cpu.usage.total - prev.cpu.usage.total;
    var intervalNs = getInterval(cur.timestamp, prev.timestamp);

    // Convert to millicores and take the percentage
    cpuUsage =
        Math.round(((rawUsage / intervalNs) / machineInfo.num_cores) * 100);
    if (cpuUsage > 100) {
      cpuUsage = 100;
    }
    gauges.push(['CPU', cpuUsage]);
  }

  var memoryUsage = 0;
  if (containerInfo.spec.has_memory) {
    // Saturate to the machine size.
    var limit = containerInfo.spec.memory.limit;
    if (limit > machineInfo.memory_capacity) {
      limit = machineInfo.memory_capacity;
    }

    memoryUsage = Math.round((cur.memory.usage / limit) * 100);
    gauges.push(['Memory', memoryUsage]);
  }

  var numGauges = gauges.length;
  if (cur.filesystem) {
    for (var i = 0; i < cur.filesystem.length; i++) {
      var data = cur.filesystem[i];
      var totalUsage = Math.floor((data.usage * 100.0) / data.capacity);
      var els = window.cadvisor.fsUsage.elements[data.device];

      // Update the gauges in the right order.
      gauges[numGauges + els.index] = ['FS #' + (els.index + 1), totalUsage];
    }

    // Limit the number of filesystem gauges displayed to 5.
    // 'Filesystem details' section still shows information for all filesystems.
    var max_gauges = numGauges + 5;
    if (gauges.length > max_gauges) {
      gauges = gauges.slice(0, max_gauges);
    }
  }

  drawGauges(elementId, gauges);
}

var oneMegabyte = 1024 * 1024;
var oneGigabyte = 1024 * oneMegabyte;

function drawMemoryUsage(elementId, machineInfo, containerInfo) {
  if (containerInfo.spec.has_memory && !hasResource(containerInfo, 'memory')) {
    return;
  }

  var titles = ['Time', 'Total', 'Hot'];
  var data = [];
  for (var i = 0; i < containerInfo.stats.length; i++) {
    var cur = containerInfo.stats[i];

    var elements = [];
    elements.push(cur.timestamp);
    elements.push(cur.memory.usage / oneMegabyte);
    elements.push(cur.memory.working_set / oneMegabyte);
    data.push(elements);
  }

  // Get the memory limit, saturate to the machine size.
  var memory_limit = machineInfo.memory_capacity;
  if (containerInfo.spec.memory.limit &&
      (containerInfo.spec.memory.limit < memory_limit)) {
    memory_limit = containerInfo.spec.memory.limit;
  }

  // Updating the progress bar.
  var cur = containerInfo.stats[containerInfo.stats.length - 1];
  var hotMemory = Math.floor((cur.memory.working_set * 100.0) / memory_limit);
  var totalMemory = Math.floor((cur.memory.usage * 100.0) / memory_limit);
  var coldMemory = totalMemory - hotMemory;
  $('#progress-hot-memory').width(hotMemory + '%');
  $('#progress-cold-memory').width(coldMemory + '%');
  $('#memory-text')
      .text(
          humanizeIEC(cur.memory.usage) + ' / ' + humanizeIEC(memory_limit) +
          ' (' + totalMemory + '%)');

  drawLineChart(titles, data, elementId, 'Megabytes');
}

// Get the index of the interface with the specified name.
function getNetworkInterfaceIndex(interfaceName, interfaces) {
  for (var i = 0; i < interfaces.length; i++) {
    if (interfaces[i].name == interfaceName) {
      return i;
    }
  }
  return -1;
}

// Draw the graph for network tx/rx bytes.
function drawNetworkBytes(elementId, machineInfo, stats) {
  if (stats.spec.has_network && !hasResource(stats, 'network')) {
    return;
  }

  // Get interface index.
  var interfaceIndex = -1;
  if (stats.stats.length > 0) {
    interfaceIndex = getNetworkInterfaceIndex(
        window.cadvisor.network.interface, stats.stats[0].network.interfaces);
  }
  if (interfaceIndex < 0) {
    console.log(
        'Unable to find interface"', interfaceName, '" in ',
        stats.stats.network);
    return;
  }

  var titles = ['Time', 'Tx bytes', 'Rx bytes'];
  var data = [];
  for (var i = 1; i < stats.stats.length; i++) {
    var cur = stats.stats[i];
    var prev = stats.stats[i - 1];
    var intervalInSec = getInterval(cur.timestamp, prev.timestamp) / 1000000000;

    var elements = [];
    elements.push(cur.timestamp);
    elements.push(
        (cur.network.interfaces[interfaceIndex].tx_bytes -
         prev.network.interfaces[interfaceIndex].tx_bytes) /
        intervalInSec);
    elements.push(
        (cur.network.interfaces[interfaceIndex].rx_bytes -
         prev.network.interfaces[interfaceIndex].rx_bytes) /
        intervalInSec);
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Bytes per second');
}

// Draw the graph for network errors
function drawNetworkErrors(elementId, machineInfo, stats) {
  if (stats.spec.has_network && !hasResource(stats, 'network')) {
    return;
  }

  // Get interface index.
  var interfaceIndex = -1;
  if (stats.stats.length > 0) {
    interfaceIndex = getNetworkInterfaceIndex(
        window.cadvisor.network.interface, stats.stats[0].network.interfaces);
  }
  if (interfaceIndex < 0) {
    console.log(
        'Unable to find interface"', interfaceName, '" in ',
        stats.stats.network);
    return;
  }

  var titles = ['Time', 'Tx', 'Rx'];
  var data = [];
  for (var i = 1; i < stats.stats.length; i++) {
    var cur = stats.stats[i];
    var prev = stats.stats[i - 1];
    var intervalInSec = getInterval(cur.timestamp, prev.timestamp) / 1000000000;

    var elements = [];
    elements.push(cur.timestamp);
    elements.push(
        (cur.network.interfaces[interfaceIndex].tx_errors -
         prev.network.interfaces[interfaceIndex].tx_errors) /
        intervalInSec);
    elements.push(
        (cur.network.interfaces[interfaceIndex].rx_errors -
         prev.network.interfaces[interfaceIndex].rx_errors) /
        intervalInSec);
    data.push(elements);
  }
  drawLineChart(titles, data, elementId, 'Errors per second');
}

// Update the filesystem usage values.
function drawFileSystemUsage(machineInfo, stats) {
  var cur = stats.stats[stats.stats.length - 1];
  if (!cur.filesystem) {
    return;
  }

  var el = $('<div>');
  for (var i = 0; i < cur.filesystem.length; i++) {
    var data = cur.filesystem[i];
    var totalUsage = Math.floor((data.usage * 100.0) / data.capacity);

    // Update DOM elements.
    var els = window.cadvisor.fsUsage.elements[data.device];
    els.progressElement.width(totalUsage + '%');
    els.textElement.text(
        humanizeMetric(data.usage) + ' / ' + humanizeMetric(data.capacity) +
        ' (' + totalUsage + '%)');
  }
}

function drawImages(images) {
  if (images == null || images.length == 0) {
    return;
  }
  window.charts = {};
  var titles = ['Repository', 'Tags', 'ID', 'Virtual Size', 'Creation Time'];
  var titleTypes = ['string', 'string', 'string', 'number', 'number'];
  var sortIndex = 0;
  var data = [];
  for (var i = 0; i < images.length; i++) {
    var elements = [];
    var tags = [];
    var repos = images[i].repo_tags[0].split(':');
    repos.splice(-1, 1);
    for (var j = 0; j < images[i].repo_tags.length; j++) {
      var splits = images[i].repo_tags[j].split(':');
      if (splits.length > 1) {
        tags.push(splits[splits.length - 1]);
      }
    }
    elements.push(repos.join(':'));
    elements.push(tags.join(', '));
    elements.push(images[i].id.substr(0, 24));
    elements.push(
        {v: images[i].virtual_size, f: humanizeIEC(images[i].virtual_size)});
    var d = new Date(images[i].created * 1000);
    elements.push({v: images[i].created, f: d.toLocaleString()});
    data.push(elements);
  }
  drawTable(titles, titleTypes, data, 'docker-images', 30, sortIndex);
}

function drawProcesses(isRoot, rootDir, processInfo) {
  if (processInfo.length == 0) {
    $('#processes-top').text('No processes found');
    return;
  }
  var titles = [
    'User', 'PID', 'PPID', 'Start Time', 'CPU %', 'MEM %', 'RSS',
    'Virtual Size', 'Status', 'Running Time', 'Command', 'PSR'
  ];
  var titleTypes = [
    'string', 'number', 'number', 'string', 'number', 'number', 'number',
    'number', 'string', 'string', 'string', 'number'
  ];
  var sortIndex = 4;
  if (isRoot) {
    titles.push('Container');
    titleTypes.push('string');
  }
  var data = [];
  for (var i = 0; i < processInfo.length; i++) {
    var elements = [];
    elements.push(processInfo[i].user);
    elements.push(processInfo[i].pid);
    elements.push(processInfo[i].parent_pid);
    elements.push(processInfo[i].start_time);
    elements.push({
      v: processInfo[i].percent_cpu,
      f: processInfo[i].percent_cpu.toFixed(2)
    });
    elements.push({
      v: processInfo[i].percent_mem,
      f: processInfo[i].percent_mem.toFixed(2)
    });
    elements.push({v: processInfo[i].rss, f: humanizeIEC(processInfo[i].rss)});
    elements.push({
      v: processInfo[i].virtual_size,
      f: humanizeIEC(processInfo[i].virtual_size)
    });
    elements.push(processInfo[i].status);
    elements.push(processInfo[i].running_time);
    elements.push(processInfo[i].cmd);
    elements.push(processInfo[i].psr);
    if (isRoot) {
      var cgroup = processInfo[i].cgroup_path;
      // Use the raw cgroup link as it works for all containers.
      var cgroupLink = '<a href="' + rootDir + 'containers/' + cgroup + '">' +
          cgroup.substr(0, 30) + ' </a>';
      elements.push({v: cgroup, f: cgroupLink});
    }
    data.push(elements);
  }
  drawTable(titles, titleTypes, data, 'processes-top', 25, sortIndex);
}

// Draw the filesystem usage nodes.
function startFileSystemUsage(elementId, machineInfo, stats) {
  window.cadvisor.fsUsage = {};

  // A map of device name to DOM elements.
  window.cadvisor.fsUsage.elements = {};

  var cur = stats.stats[stats.stats.length - 1];
  var el = $('<div>');
  if (!cur.filesystem) {
    return;
  }
  for (var i = 0; i < cur.filesystem.length; i++) {
    var data = cur.filesystem[i];
    el.append(
        $('<div>')
            .addClass('row col-sm-12')
            .append($('<h4>').text('FS #' + (i + 1) + ': ' + data.device)));

    var progressElement =
        $('<div>').addClass('progress-bar progress-bar-danger');
    el.append(
        $('<div>')
            .addClass('col-sm-9')
            .append($('<div>').addClass('progress').append(progressElement)));

    var textElement = $('<div>').addClass('col-sm-3');
    el.append(textElement);

    window.cadvisor.fsUsage.elements[data.device] = {
      'progressElement': progressElement,
      'textElement': textElement,
      'index': i,
    };
  }
  $('#' + elementId).empty().append(el);

  drawFileSystemUsage(machineInfo, stats);
}

// Expects an array of closures to call. After each execution the JS runtime is
// given control back before continuing.
// This function returns asynchronously
function stepExecute(steps) {
  // No steps, stop.
  if (steps.length == 0) {
    return;
  }

  // Get a step and execute it.
  var step = steps.shift();
  step();

  // Schedule the next step.
  setTimeout(function() { stepExecute(steps); }, 0);
}

// Draw all the charts on the page.
function drawCharts(machineInfo, containerInfo, subcontainers) {
  var steps = [];

  if (containerInfo.spec.has_cpu || containerInfo.spec.has_memory) {
    steps.push(function() {
      drawOverallUsage('usage-gauge', machineInfo, containerInfo);
    });
  }

  // CPU.
  if (containerInfo.spec.has_cpu) {
    steps.push(function() {
      drawCpuTotalUsage('cpu-total-usage-chart', machineInfo, containerInfo);
    });
    // TODO(rjnagal): Re-enable CPU Load after understanding resource usage.
    // steps.push(function() {
    // 	drawCpuLoad("cpu-load-chart", machineInfo, containerInfo);
    // });
    steps.push(function() {
      drawCpuPerCoreUsage(
          'cpu-per-core-usage-chart', machineInfo, containerInfo);
    });
    steps.push(function() {
      drawCpuUsageBreakdown(
          'cpu-usage-breakdown-chart', machineInfo, containerInfo);
    });
  }

  // Memory.
  if (containerInfo.spec.has_memory) {
    steps.push(function() {
      drawMemoryUsage('memory-usage-chart', machineInfo, containerInfo);
    });
  }

  // Network.
  if (containerInfo.spec.has_network) {
    steps.push(function() {
      drawNetworkBytes('network-bytes-chart', machineInfo, containerInfo);
    });
    steps.push(function() {
      drawNetworkErrors('network-errors-chart', machineInfo, containerInfo);
    });
  }

  // Filesystem.
  if (containerInfo.spec.has_filesystem) {
    steps.push(function() { drawFileSystemUsage(machineInfo, containerInfo); });
  }

  // Custom Metrics
  if (containerInfo.spec.has_custom_metrics) {
    steps.push(function() {
      getCustomMetrics(
          window.cadvisor.rootDir, window.cadvisor.containerName,
          function(metricsInfo) {
            drawCustomMetrics(
              'custom-metrics-chart', containerInfo, metricsInfo);
          });
    });
  }

  // Subcontainers.
  var subcontainerInfos = filterSubcontainers(containerInfo, subcontainers);
  if (subcontainerInfos.length > 0) {
    if (hasResourceForAll(subcontainerInfos, 'cpu')) {
      steps.push(function() {
        var displayCount = $('#cpu-per-subcontainer-display-count').val();
        drawCpuPerSubcontainerUsage(
            'cpu-per-subcontainer-usage-chart',
            sliceByCpu(subcontainerInfos, displayCount));
      });
    }

    if (hasResourceForAll(subcontainerInfos, 'memory')) {
      steps.push(function() {
        var displayCount = $('#memory-per-subcontainer-display-count').val();
        drawMemoryPerSubcontainerUsage(
            'memory-per-subcontainer-usage-chart',
            sliceByMemory(subcontainerInfos, displayCount));
      });
    }
  }

  stepExecute(steps);
}

// Return an slice of subcontainers sorted by CPU, with at most 'count' entries.
function sliceByCpu(subcontainerInfos, count) {
  subcontainerInfos.sort(function(a, b) {
    if (a.averages.cpu > b.averages.cpu) {
      return -1;
    } else if (a.averages.cpu < b.averages.cpu) {
      return 1;
    } else {
      return compareByName(a, b);
    }
  });
  return subcontainerInfos.slice(0, Math.min(subcontainerInfos.length, count))
      .sort(compareByName);
}

// Return an slice of subcontainers sorted by memory, with at most 'count'
// entries.
function sliceByMemory(subcontainerInfos, count) {
  subcontainerInfos.sort(function(a, b) {
    if (a.averages.memory > b.averages.memory) {
      return -1;
    } else if (a.averages.memory < b.averages.memory) {
      return 1;
    } else {
      return compareByName(a, b);
    }
  });
  return subcontainerInfos.slice(0, Math.min(subcontainerInfos.length, count))
      .sort(compareByName);
}

// Return sort comparitor based on subcontroller name.
function compareByName(subA, subB) {
  if (subA.name > subB.name) {
    return 1;
  } else if (subA.name < subB.name) {
    return -1;
  } else {
    return 0;
  }
}

// Return a map of the averages of the subcontainer stats.
function getSubcontainerAverages(subcontainer) {
  var cpuSum = 0;
  var memorySum = 0;
  subcontainer.stats.forEach(function(stat) {
    cpuSum += stat.cpu.usage.total;
    memorySum += stat.memory.usage / oneMegabyte;
  });
  return {
    cpu: cpuSum / subcontainer.stats.length,
    memory: memorySum / subcontainer.stats.length,
  }
}

// Return a list of immediate subcontainers, including metric averages.
function filterSubcontainers(containerInfo, subcontainers) {
  if (!containerInfo.subcontainers ||
      containerInfo.subcontainers.length === 0 ||
      !subcontainers) {
    return [];
  }

  var subcontainerNames = {};
  containerInfo.subcontainers.forEach(function(subcontainer) {
    subcontainerNames[subcontainer.name] = subcontainer.name;
  });

  var subcontainerInfos = [];
  subcontainers.forEach(function(subcontainer) {
    if (subcontainerNames[subcontainer.name] !== undefined) {
      subcontainer.averages = getSubcontainerAverages(subcontainer);
      subcontainerInfos.push(subcontainer);
    }
  });

  return subcontainerInfos;
}

function setNetwork(interfaceName) {
  $('#network-selection-text')
      .empty()
      .append($('<span>').text('Interface: '))
      .append($('<b>').text(interfaceName));
  window.cadvisor.network.interface = interfaceName;

  // Draw the new stats.
  refreshStats();
}

// Creates the network selection dropdown.
function startNetwork(selectionElement, containerInfo) {
  if (!hasResource(containerInfo, 'network') ||
      containerInfo.stats.length == 0 ||
      !containerInfo.stats[0].network.interfaces ||
      containerInfo.stats[0].network.interfaces.length == 0) {
    return;
  }

  window.cadvisor.network = {};
  window.cadvisor.network.interface = '';

  // Add all interfaces to the dropdown.
  var el = $('#' + selectionElement);
  for (var i = 0; i < containerInfo.stats[0].network.interfaces.length; i++) {
    var interfaceName = containerInfo.stats[0].network.interfaces[i].name;
    el.append($('<li>')
                  .attr('role', 'presentation')
                  .append($('<a>')
                              .attr('role', 'menuitem')
                              .attr('tabindex', -1)
                              .click(setNetwork.bind(null, interfaceName))
                              .text(interfaceName)));
  }
  setNetwork(containerInfo.stats[0].network.interfaces[0].name);
}

// Refresh the stats on the page.
function refreshStats() {
  var machineInfo = window.cadvisor.machineInfo;
  getStats(
      window.cadvisor.rootDir, window.cadvisor.containerName,
      function(containerInfo, subcontainers) {
        if (window.cadvisor.firstRun) {
          window.cadvisor.firstRun = false;

          if (containerInfo.spec.has_filesystem) {
            startFileSystemUsage(
                'filesystem-usage', machineInfo, containerInfo);
          }
          if (containerInfo.spec.has_network) {
            startNetwork('network-selection', containerInfo);
          }
          if (containerInfo.spec.has_custom_metrics) {
            startCustomMetrics('custom-metrics-chart', containerInfo);
          }
        }
        drawCharts(machineInfo, containerInfo, subcontainers);
      });
}

function addAllLabels(containerInfo, metricsInfo) {
  if (metricsInfo.length == 0) {
    return;
  }
  var metricSpec = containerInfo.spec.custom_metrics;
  for (var containerName in metricsInfo) {
    var container = metricsInfo[containerName];
    for (i = 0; i < metricSpec.length; i++) {
      metricName = metricSpec[i].name;
      metricLabelVal = container[metricName];
      firstLabel = true;
      for (var label in metricLabelVal) {
        if (label == '') {
          $('#button-' + metricName).hide();
        }

        $('#' + metricName + '_labels')
            .append(
                $('<li>')
                    .attr('role', 'presentation')
                    .append($('<a>')
                                .attr('role', 'menuitem')
                                .click(setLabel.bind(null, metricName, label))
                                .text(label)));
        if (firstLabel) {
          firstLabel = false;
          setLabel(metricName, label);
        }
      }
    }
  }
}

function getMetricIndex(metricName) {
  for (i = 0; i < window.cadvisor.metricLabelPair.length; ++i) {
    if (window.cadvisor.metricLabelPair[i][0] == metricName) { return i; }
  }
  return -1;
}

function setLabel(metric, label) {
  $('#' + metric + '-selection-text')
      .empty()
      .append($('<span>').text('Label: '))
      .append($('<b>').text(label));

  index = getMetricIndex(metric);
  if (index == -1) {
    window.cadvisor.metricLabelPair.push([metric, label]);
  } else {
    window.cadvisor.metricLabelPair[index][1] = label;
  }

  refreshStats();
}

function getSelectedLabel(metricName) {
  index = getMetricIndex(metricName);
  if (index == -1) { return ''; }
  return window.cadvisor.metricLabelPair[index][1];
}

function startCustomMetrics(elementId, containerInfo) {
  var metricSpec = containerInfo.spec.custom_metrics;
  var metricStats = containerInfo.stats.custom_metrics;
  var el = $('<div>');

  if (metricSpec.length < window.cadvisor.maxCustomMetrics) {
    window.cadvisor.maxCustomMetrics = metricSpec.length;
    for (i = 0; i < window.cadvisor.maxCustomMetrics; i++) {
      metricName = metricSpec[i].name;
      var divText =
          '<div class=\'dropdown\'> <button class=\'btn btn-default' +
          ' dropdown-toggle\' type=\'button\' id=\'button-' + metricName;
      divText +=
          '\' data-toggle=\'dropdown\' aria-haspopup=\'true\'' +
          ' aria-expanded=\'false\'>';
      divText += '<span id=\'' + metricName +
          '-selection-text\'></span> <span class=\'caret\'></span> </button>';
      divText += '<ul id=\'' + metricName +
          '_labels\' class=\'dropdown-menu\' role=\'menu\'' +
          ' aria-labelledby=\'button-' + metricName + '\'> </ul> </div>';
      divText += '<div id=\'' + elementId + '-' + metricName + '\'> </div>';
      el.append($(divText));
    }
  }
  el.append($('</div>'));

  $('#' + elementId).append(el);
}

function getCustomMetrics(rootDir, containerName, callback) {
  $.getJSON(rootDir + 'api/v2.0/appmetrics/' + containerName)
      .done(function(data) { callback(data); })
      .fail(function(jqhxr, textStatus, error) { callback([]); });
}

function drawCustomMetrics(elementId, containerInfo, metricsInfo) {
  if (metricsInfo.length == 0) {
    return;
  }
  var metricSpec = containerInfo.spec.custom_metrics;
  for (var containerName in metricsInfo) {
    var container = metricsInfo[containerName];
    for (i = 0; i < window.cadvisor.maxCustomMetrics; i++) {
      metricName = metricSpec[i].name;
      metricUnits = metricSpec[i].units;
      var titles = ['Time', metricName];
      metricLabelVal = container[metricName];
      if (window.cadvisor.firstCustomCollection) {
        window.cadvisor.firstCustomCollection = false;
        addAllLabels(containerInfo, metricsInfo);
      }
      var data = [];
      selectedLabel = getSelectedLabel(metricName);
      metricVal = metricLabelVal[selectedLabel];
      for (var index in metricVal) {
        metric = metricVal[index];
        var elements = [];
        for (var attribute in metric) {
          value = metric[attribute];
          elements.push(value);
        }
        if (elements.length < 2) {
          elements.push(0);
        }
        data.push(elements);
      }
      drawLineChart(titles, data, elementId + '-' + metricName, metricUnits);
    }
  }
}

// Executed when the page finishes loading.
function startPage(containerName, hasCpu, hasMemory, rootDir, isRoot) {
  // Don't fetch data if we don't have any resource.
  if (!hasCpu && !hasMemory) {
    return;
  }

  window.charts = {};
  window.cadvisor = {};
  window.cadvisor.firstRun = true;
  window.cadvisor.rootDir = rootDir;
  window.cadvisor.containerName = containerName;

  window.cadvisor.firstCustomCollection = true;
  window.cadvisor.metricLabelPair = [];
  window.cadvisor.maxCustomMetrics = 10;

  // Draw process information at start and refresh every 60s.
  getProcessInfo(rootDir, containerName, function(processInfo) {
    drawProcesses(isRoot, rootDir, processInfo);
  });
  setInterval(function() {
    getProcessInfo(rootDir, containerName, function(processInfo) {
      drawProcesses(isRoot, rootDir, processInfo);
    });
  }, 60000);

  // Get machine info, then get the stats every 1s.
  getMachineInfo(rootDir, function(machineInfo) {
    window.cadvisor.machineInfo = machineInfo;
    setInterval(function() { refreshStats(); }, 1000);
  });
}


text:
const helmet = require('helmet');
const contentSecurityPolicy = require('./contentSecurityPolicy');

function config(app) {
  app.use(helmet({
    contentSecurityPolicy,
    frameguard: { action: 'deny' },
    hsts: { includeSubDomains: false },
  }));
}

module.exports = config;

redpajama_set_name: RedPajamaGithub


text:
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

GitHubOrg=$1
GitHubUser=$2
GitHubToken=$3
LastPage=$4

rm -rf "$SCRIPT_DIR/github_teamIdNamePairs.txt"

for i in $(seq 1 $LastPage); do
    curl --silent --user "$GitHubUser:$GitHubToken" "https://api.github.com/orgs/$GitHubOrg/teams?per_page=100&page=$i" | ./jq -c '.[] | {id,name}' >> "$SCRIPT_DIR/github_teamIdNamePairs.txt"
done

cat github_teamIdNamePairs.txt | ./jq -r '.name' | sed 's@\(.*\)@\1,\1@' | sort > "$SCRIPT_DIR/github_teamList.txt"


text:
using Haven;
using SharpHaven.UI.Widgets;

namespace SharpHaven.UI.Remote
{
	public class ServerBufflist : ServerWidget
	{
		private Bufflist widget;

		public ServerBufflist(ushort id, ServerWidget parent) : base(id, parent)
		{
		}

		public override Widget Widget
		{
			get { return widget; }
		}

		public static ServerWidget Create(ushort id, ServerWidget parent)
		{
			return new ServerBufflist(id, parent);
		}

		protected override void OnInit(Point2D position, object[] args)
		{
			widget = new Bufflist(Parent.Widget, Parent.Session);
			widget.Move(position);
		}
	}
}


text:
package org.multibit.action;

import org.multibit.controller.MultiBitController;
import org.multibit.model.DataProvider;

/**
 * an action to go back to the home page
 * (typically used in an OK button on a messagebox)
 *
 * @author jim
 *
 */
public class OkBackToParentAction implements Action {

    private MultiBitController controller;

    public OkBackToParentAction(MultiBitController controller) {
        this.controller = controller;
    }

    public void execute(DataProvider dataProvider) {
        // no changes required to model

        controller.setActionForwardToParent();
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladonia rangiformis var. aberrans Abbayes

### Remarks
null


text:
static git_repository *repo;
static git_strarray ref_list;

static void ensure_no_refname_starts_with_a_forward_slash(const char *path)
{
	size_t i;

	cl_git_pass(git_repository_open(&repo, path));
	cl_git_pass(git_reference_list(&ref_list, repo, GIT_REF_LISTALL));

	cl_assert(ref_list.count > 0);

	for (i = 0; i < ref_list.count; i++)
		cl_assert(git__prefixcmp(ref_list.strings[i], "/") != 0);

	git_strarray_free(&ref_list);
	git_repository_free(repo);
}

void test_refs_listall__from_repository_opened_through_workdir_path(void)
{
	cl_fixture_sandbox("status");
	cl_git_pass(p_rename("status/.gitted", "status/.git"));

	ensure_no_refname_starts_with_a_forward_slash("status");

	cl_fixture_cleanup("status");
}

void test_refs_listall__from_repository_opened_through_gitdir_path(void)
{
	ensure_no_refname_starts_with_a_forward_slash(cl_fixture("testrepo.git"));
}


text:
'use strict';

app.controller('MainCtrl', function ($scope, $location, CarResource, socket, notifier) {
    $scope.startYearFrom = 1920;
    $scope.startYearTo = $scope.startYearFrom;
    $scope.yearsFrom = generateYearsArray($scope.startYearFrom);
    $scope.filteredCars = CarResource.queryBased
        .query({ page: 1, sortBy: "published", desc: true }, function () {
            $scope.filteredCars.forEach(function (item) {
                if (!item.photoUrl) {
                    item.photoUrl = "img/no_photo.png";
                }
            });

            if ($scope.filteredCars.length === 10) {
                $scope.filteredCars.pop();
            }
        });

    function generateYearsArray(until) {
        var arr = [],
            currentYear = new Date().getFullYear();

        for (currentYear; currentYear >= until; currentYear -= 1) {
            arr.push(currentYear);
        }

        return arr;
    }

    $scope.updateToYears = function () {
        $scope.yearsTo = generateYearsArray($scope.ad.yearFrom);
    };

    $scope.search = function (ad) {
        $location.path("/cars").search(ad);
    };

    socket.on('make added', function (make) {
        notifier.success(make.name + " make has been added!");
    });

    socket.on('model added', function (model) {
        notifier.success("Model " + model.name + " has been added successfully!");
    });

    socket.on('category added', function (category) {
        notifier.success(category.name + " category has been added!");
    });
});


text:
package dao

import (
	"context"
	"net/http"
	"net/url"
	"strconv"

	"go-common/app/interface/main/space/model"
	favmdl "go-common/app/service/main/favorite/model"
	"go-common/library/ecode"
	"go-common/library/log"
	"go-common/library/net/metadata"
)

const (
	_favFolderURI  = "/x/internal/v2/fav/folder"
	_favArchiveURI = "/x/internal/v2/fav/video"
	_favAlbumURI   = "/userext/v1/Fav/getMyFav"
	_favMovieURI   = "/follow/api/list/mine"
	_samplePage    = "1"
	_samplePs      = "1"
)

// FavFolder favorite folder list.
func (d *Dao) FavFolder(c context.Context, mid, vmid int64) (res []*favmdl.VideoFolder, err error) {
	var (
		params = url.Values{}
		ip     = metadata.String(c, metadata.RemoteIP)
	)
	params.Set("mid", strconv.FormatInt(mid, 10))
	params.Set("vmid", strconv.FormatInt(vmid, 10))
	var rs struct {
		Code int                   `json:"code"`
		Data []*favmdl.VideoFolder `json:"data"`
	}
	if err = d.httpR.Get(c, d.favFolderURL, ip, params, &rs); err != nil {
		log.Error("d.http.Get(%s,%d) error(%v)", d.favFolderURL, mid, err)
		return
	}
	if rs.Code != ecode.OK.Code() {
		log.Error("d.http.Get(%s,%d) code(%d)", d.favFolderURL, mid, rs.Code)
		err = ecode.Int(rs.Code)
		return
	}
	res = rs.Data
	return
}

// LiveFavCount get live(vc or album) favorite count.
func (d *Dao) LiveFavCount(c context.Context, mid int64, favType int) (count int, err error) {
	var (
		req *http.Request
		rs  struct {
			Code int `json:"code"`
			Data struct {
				PageInfo struct {
					Page      int `json:"page"`
					PageSize  int `json:"page_size"`
					TotalPage int `json:"total_page"`
					Count     int `json:"count"`
				} `json:"pageinfo"`
			} `json:"data"`
		}
		ip = metadata.String(c, metadata.RemoteIP)
	)
	params := url.Values{}
	params.Set("biz_type", strconv.Itoa(favType))
	if req, err = d.httpR.NewRequest("GET", d.favAlbumURL, ip, params); err != nil {
		log.Error("d.httpR.NewRequest %s error(%v)", d.favAlbumURL, err)
		return
	}
	req.Header.Set("X-BILILIVE-UID", strconv.FormatInt(mid, 10))
	if err = d.httpR.Do(c, req, &rs); err != nil {
		log.Error("d.httpR.Get(%s,%d) error(%v)", d.favAlbumURL, mid, err)
		return
	}
	if rs.Code != ecode.OK.Code() {
		log.Error("d.httpR.Get(%s,%d) code(%d)", d.favAlbumURL, mid, rs.Code)
		err = ecode.Int(rs.Code)
		return
	}
	count = rs.Data.PageInfo.Count
	return
}

// MovieFavCount get movie fav count
func (d *Dao) MovieFavCount(c context.Context, mid int64, favType int) (count int, err error) {
	var (
		params = url.Values{}
		ip     = metadata.String(c, metadata.RemoteIP)
	)
	params.Set("season_type", strconv.Itoa(favType))
	params.Set("mid", strconv.FormatInt(mid, 10))
	params.Set("page", _samplePage)
	params.Set("pagesize", _samplePs)
	params.Set("build", _build)
	params.Set("platform", _platform)
	var (
		rs struct {
			Code  int    `json:"code"`
			Count string `json:"count"`
		}
	)
	if err = d.httpR.Get(c, d.favMovieURL, ip, params, &rs); err != nil {
		log.Error("d.httpR.Get(%s,%d) error(%v)", d.favMovieURL, mid, err)
		return
	}
	if rs.Code != ecode.OK.Code() {
		log.Error("d.httpR.Get(%s,%d) code(%d)", d.favMovieURL, mid, rs.Code)
		err = ecode.Int(rs.Code)
		return
	}
	count, _ = strconv.Atoi(rs.Count)
	return
}

// FavArchive fav archive.
func (d *Dao) FavArchive(c context.Context, mid int64, arg *model.FavArcArg) (res *favmdl.SearchArchive, err error) {
	var (
		params = url.Values{}
		ip     = metadata.String(c, metadata.RemoteIP)
	)
	if mid > 0 {
		params.Set("mid", strconv.FormatInt(mid, 10))
	}
	params.Set("vmid", strconv.FormatInt(arg.Vmid, 10))
	params.Set("fid", strconv.FormatInt(arg.Fid, 10))
	if arg.Tid > 0 {
		params.Set("tid", strconv.FormatInt(arg.Tid, 10))
	}
	if arg.Keyword != "" {
		params.Set("keyword", arg.Keyword)
	}
	if arg.Order != "" {
		params.Set("order", arg.Order)
	}
	params.Set("pn", strconv.Itoa(arg.Pn))
	params.Set("ps", strconv.Itoa(arg.Ps))
	var rs struct {
		Code int                   `json:"code"`
		Data *favmdl.SearchArchive `json:"data"`
	}
	if err = d.httpR.Get(c, d.favArcURL, ip, params, &rs); err != nil {
		log.Error("d.http.Get(%s,%d) error(%v)", d.favArcURL, mid, err)
		return
	}
	if rs.Code != ecode.OK.Code() {
		log.Error("d.http.Get(%s,%d) code(%d)", d.favArcURL, mid, rs.Code)
		err = ecode.Int(rs.Code)
		return
	}
	res = rs.Data
	return
}


text:
<!doctype html>

		<title>SilverStripe CMS / Framework Installation</title>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">

		<link rel="stylesheet" type="text/css" href="<?php echo FRAMEWORK_NAME; ?>/dev/install/css/install.css">
		<link rel="shortcut icon" href="favicon.ico">

SilverStripe

CMS / Framework Installation <?php if($silverstripe_version) echo "Version $silverstripe_version"; ?>

Thanks for choosing to use SilverStripe! Please follow the instructions below and you should be up in running in no time.

								If you get stuck, head over to the installation forum, or check out our list of suggested web hosts known to work with SilverStripe.

						<form action="install.php" method="post">
							<?php if(isset($hasErrorOtherThanDatabase)) { ?>

									You aren't currently able to install the software.  Please see below for details.

									If you are having problems meeting the requirements, see the server requirements.

								<?php if (isset($phpIniLocation)) { ?>

Your php.ini file is located at <?php echo $phpIniLocation; ?>

								<?php } ?>
							<?php } else { ?>
								<?php if($alreadyInstalled) { ?>

Note: SilverStripe is already installed here.

										If you wish to reinstall SilverStripe, please delete the mysite/_config.php file first.

								<?php } else if($req->hasWarnings()) { ?>

There are some issues that we recommend you look at before installing, however, you are still able to install the software.

Please see below for details. If you are having problems meeting the requirements, see the server requirements.

								<?php } else if(!$dbReq->hasErrors() && !$adminReq->hasErrors()) { ?>

You're ready to install! Please confirm the configuration options below. Install SilverStripe

								<?php } ?>

								<?php if($dbReq->hasErrors()) { ?>

The database details don't appear to be correct. Please review and correct before installing.

								<?php } ?>

								<?php if($adminReq->hasErrors()) { ?>

Please enter an email address and password for the default administrator account before installing.

								<?php } ?>
							<?php } ?>

Requirements Step 1 of 5

							<?php $req->showTable(); ?>
							<?php $dbReq->showTable(); ?>

								Read more about our server requirements.

								<input type="submit" class="action" value="Re-check requirements">

Database Configuration Step 2 of 5

								<?php $dbReq->showTable("Database Configuration"); ?>

									SilverStripe stores its content in a relational SQL database. Please provide the username and password to connect to the server here.
									If this account has permission to create databases, then we will create the database for you; otherwise, you must give the name of a
									database that already exists.

									Other databases:

									Databases in the list that are greyed out cannot currently be used. Click on them for more information and possible remedies.

											<?php
											foreach($databaseClasses as $class => $details) {
												$checked = ($databaseConfig['type'] == $class || $type == $class) ? ' checked="checked"' : '';
												$disabled = $help = '';
												if($usingEnv) {
													// All are disabled by default when environment is used
													$disabled = 'disabled="disabled"';
													// If SS_DATABASE_CLASS is specified, check the database in the list
													if(defined('SS_DATABASE_CLASS') && SS_DATABASE_CLASS == $class) {
														$checked = ' checked="checked"';
													}
												} else {
													$disabled = !$details['supported'] || !$details['hasModule'] ? 'notavailable="true"' : '';
													if ($disabled) {
														if (!$details['supported'] && !$details['hasModule']) {
															$help = 'PHP does not have the required extension, and SilverStripe does not have the correct module installed';
															$helpText = '
'.$details['missingExtensionText'].'
';
															$helpText .= '
'.$details['missingModuleText'].'
';
														} else if ($details['supported'] && !$details['hasModule']) {
															$help = 'PHP has the required extension, but SilverStripe is missing the module';
															$helpText = '
'.$details['missingModuleText'].'
';
														} else if (!$details['supported'] && $details['hasModule']) {
															$help = 'SilverStripe has the module installed, but PHP is missing the required extension';
															$helpText = '
'.$details['missingExtensionText'].'
';
														}
														$help .= "
$helpText
";
													}
												}
												echo "
";
												echo "<input id=\"$class\" class=\"databaseClass\" type=\"radio\" name=\"db[type]\" value=\"$class\"$checked $disabled>";
												echo "{$details['title']}";
												if ($help) {
													echo '

'.$help.'

';
												}

												// generate db-specific config fields
												echo '
';
												if(isset($details['fields'])) foreach($details['fields'] as $fieldName => $fieldSpec) {
													$fieldTitle = $fieldSpec['title'];
													$fieldType = ($fieldName == 'password') ? 'password' : 'text';

													// values
													$defaultValue = (isset($fieldSpec['default'])) ? $fieldSpec['default'] : null;
													if($usingEnv && isset($fieldSpec['envVar']) && defined($fieldSpec['envVar'])) {
														$value = constant($fieldSpec['envVar']);
													} else {
														$value = (isset($databaseConfig[$fieldName])) ? $databaseConfig[$fieldName] : $defaultValue;
													}

													// attributes
													$attrs = array(
														'id' => "db_{$class}_{$fieldName}",
														'class' => 'text',
														'type' => $fieldType,
														'name' => "db[$class][$fieldName]",
														'value' => $value,
													);
													if($usingEnv && isset($fieldSpec['envVar']) && defined($fieldSpec['envVar'])) {
														$attrs['disabled'] = 'disabled';
													}
													if(isset($fieldSpec['envVar'])) {
														$attrs['class'] .= ' configured-by-env';
													}
													$attrHTML = '';
													foreach($attrs as $attrName => $attrValue) $attrHTML .= "$attrName=\"$attrValue\" ";
													if(isset($fieldSpec['attributes'])) $attrs = array_merge($attrs, $fieldSpec['attributes']);

													// html
													echo "
";
													echo "$fieldTitle:";
													echo "";
													echo "<input $attrHTML>";
													echo "";
													echo "
";
												}
												echo '
';

												echo "
";
											}
											?>

										<?php if($envFileExists) { ?>

											<input id="use_environment" type="checkbox" name="useEnv" <?php if($usingEnv) echo "checked=\"checked\"" ?>>
											Use _ss_environment file for configuration (?)

										<?php } ?>

										<input type="submit" class="action" value="Re-check requirements">

CMS Admin Account Step 3 of 5

We will set up the first administrator account for you automatically. You can change these details later in the "Security" section within the CMS.

										Email:

											<input type="text" class="text configured-by-env" name="admin[username]" id="admin_username" value="<?php echo $adminConfig['username']; ?>" <?php if($usingEnv && defined('SS_DEFAULT_ADMIN_USERNAME')) echo 'disabled="disabled"' ?>>

										Password:

											<input type="password" class="text configured-by-env" name="admin[password]" id="admin_password" value="<?php echo $adminConfig['password']; ?>" <?php if($usingEnv && defined('SS_DEFAULT_ADMIN_PASSWORD')) echo 'disabled="disabled"' ?>>

										"Default language" determines the default locale settings
										(for dates, currencies, etc.), as well as the default language
										of the CMS interface. This can be changed for each user.

										Warning: The CMS interface may be missing translations in certain locales.

										Default language:

											<select name="locale" id="locale">
												<?php
												$selectedLocale = isset($_POST['locale']) ? $_POST['locale'] : $defaultLocale;
												foreach($locales as $code => $title) {
													$selected = $code == $selectedLocale ? ' selected="selected"' : '';
													echo "<option$selected value=\"$code\">{$title}</option>\n";
												}
												?>
											</select>

Theme selection Step 4 of 5

You can change the theme or download another from the SilverStripe website after installation.

<input type="radio" name="template" value="simple" id="Simple" <?php if(!isset($_POST['template']) || $_POST['template'] == 'simple') {?>checked="checked"<?php }?>>Simple - our default theme ready to use, or begin the tutorial.

<input type="radio" name="template" value="tutorial" id="EmptyTemplate" <?php if(isset($_POST['template']) && $_POST['template'] == 'tutorial') {?>checked="checked"<?php }?>>Empty template

Confirm Install Step 5 of 5

							<?php if(isset($hasErrorOtherThanDatabase)) { ?>

									You aren't currently able to install the software.  Please see above for details.

									If you are having problems meeting the requirements, see the server requirements page.

							<?php } else { ?>

									<input type="checkbox" id="stats" name="stats" checked="checked">
										Send information about my webserver to silverstripe.org

											(anonymous version information, used for statistical purposes)

									<?php if($alreadyInstalled) { ?>
										<input id="install_button" type="submit" disabled="disabled" class="action" name="go" value="Install SilverStripe">
									<?php } else { ?>
										<input id="install_button" type="submit" class="action" name="go" value="Install SilverStripe">
									<?php } ?>

										<img src="<?php echo FRAMEWORK_NAME; ?>/images/network-save.gif" alt="Saving">
										(this will take a minute or so)

							<?php } ?>
						</form>

SilverStripe Open Source CMS / Framework | Copyright © <?php echo date('Y'); ?> SilverStripe Limited


text:
The Concise Binary Object Representation (CBOR) is a data format
whose design goals include the possibility of extremely small code
size, fairly small message size, and extensibility without the need
for version negotiation.  These design goals make it different from
earlier binary serializations such as ASN.1 and MessagePack.

[CBOR RFC 7049](http://tools.ietf.org/html/rfc7049)

[![Build Status](https://travis-ci.org/naphaso/cbor-java.png?branch=master)](https://travis-ci.org/naphaso/cbor-java)

## Current status

Currently the project is under initial development.

## To do

* Object mapping of CBOR objects.
* Test coverage.
* Benchmark in comparsion with [jvm-serializers](https://github.com/eishay/jvm-serializers/wiki).

## License

This software is distributed under [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).


text:
package com.edi.thoth.service.mongodb;

import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;

import com.edi.thoth.domain.ThothOrder;

@Component
public interface ThothOrderRepository extends MongoRepository<ThothOrder, ObjectId>
{

}


text:
#ifndef USERSESSIONLOGIN_H
#define USERSESSIONLOGIN_H

#include <QObject>
#include <QUrlQuery>
#include "qtnicolivelib.h"
#include "httpgetter.h"
#include "strabstractor.h"

namespace nicolive {

//! ニコ動にログインしてユーザセッションを取得します

class QTNICOLIVELIBSHARED_EXPORT UserSessionLogin : public HttpGetter
{
  Q_OBJECT
public:
  //! コンストラクタ
  explicit UserSessionLogin(QObject *parent = 0);

  //! リクエストを発行します。
  /*!
   * 取得後、Signalの got() または error() をemitします。
   */
  void get(const QString& mailAddress, const QString& password);
private:
  void gotReply(QNetworkReply* reply) override;
signals:
  //! エラーになった場合にエミットされるシグナルです。
  /*! 参考: get() */
  void error();

  //! 取得成功した場合にエミットされるシグナルです。
  /*! 参考: get() */
  void got(QString userSession);
};

}

#endif // USERSESSIONLOGIN_H


text:
//package depauw.edu.myro.android.sandbox;
//
//import com.google.zxing.NotFoundException;
//import com.google.zxing.ReaderException;
//
//import android.app.Activity;
//import android.graphics.Bitmap;
//import android.os.Bundle;
//import android.os.Handler;
//import android.text.method.ScrollingMovementMethod;
//import android.util.Log;
//import android.view.View;
//import android.view.View.OnClickListener;
//import android.widget.Button;
//import android.widget.ImageView;
//import android.widget.TextView;
//import android.widget.Toast;
//import depauw.edu.myro.original.MyroQRReader;
//import depauw.edu.myro.original.MyroUtils;
//
//public class Camera_QR extends Activity {
//
//	private Sandbox appState;
//	private TextView console;
//	private Button bool;
//	private ImageView camera_image_bitmap;
//    private String lastResult = "";
//    private Bitmap newBm;
//    MyroQRReader qrReader;
//
//    private boolean takePictures = false;
//	 Handler mHandler;
//
//	@Override
//	public void onCreate(Bundle savedInstanceState){
//		super.onCreate(savedInstanceState);
//		setContentView(R.layout.camera_qr_main);
//
//		appState = (Sandbox) getApplicationContext();
//
//		console = (TextView) findViewById(R.id.camera_console);
//
//		//the initial clear, used later as a testing tool
//		console.setText("");
//
//		// this line below allows the textview to be scrollable
//		console.setMovementMethod(new ScrollingMovementMethod());
//
//		camera_image_bitmap = (ImageView) findViewById(R.id.camera_qr_image_bitmap);
//
//		bool = (Button) findViewById(R.id.camera_bool);
//		bool.setText("Enable");
//		bool.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {
//
//				if(takePictures == true){
//					//how to cancel it all
//					bool.setText("Enable Camera");
//					takePictures = false;
//				}
//				else{
//					//start taking pictures repeatedly
//					bool.setText("Disable Camera");
//					takePictures = true;
//
//					if(appState.getScribbler().isConnected())
//					{
//
//						newBm = appState.getScribbler().takePicture();
//						camera_image_bitmap.setImageBitmap(newBm);
//						try {
//							Toast.makeText(getApplicationContext(), qrReader.decode(newBm), Toast.LENGTH_LONG).show();
//						} catch (ReaderException e) {
//							Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
//						}
//
//						consoleCheck("Picture Taken");
//					}
//					else{
//						consoleCheck("Not connected");
//					}
//				}
//			}
//	    });
//	}
//
//	private String scan()
//    {
//		String results = "";
//        while(results.equals(""))
//        {
//
//            Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
//            // gotta get closer to that image
//        	//appState.getScribbler().forward(0.5);
//			//appState.getScribbler().stop();
//        }
//        return results;
//    }
//
//	private void qrTest(String QRresults)
//    {
//        if (QRresults.contains(";"))
//        {
//
//            String[] parts = QRresults.split(";");
//
//            for(int i = 0; i < parts.length; i++)
//            {
//                lastResult = parts[i];
//                if(parts[i].contains("stop"))
//                {
//                	consoleCheck("stop");
//                    appState.getScribbler().stop();
//                    break;
//                }
//                else if(parts[i].contains("forward"))
//                {
//                    String test = parts[i].substring(7, parts[i].length());
//                    String command1 = test.substring(1, test.indexOf(','));
//                    String command2 = test.substring(test.indexOf(',')+2, test.length()-1);
//                    double value1 = Double.parseDouble(command1);
//                    double value2 = Double.parseDouble(command2);
//
//                    //debugging
//                    Log.d("Camera_QR_Forward", "Forward");
//                    Log.d("Camera_QR_Forward", "value1 " + value1);
//                    Log.d("Camera_QR_Forward", "value2 " + value2);
//
//                    //console
//                    consoleCheck("Forward");
//                    consoleCheck(command1);
//                    consoleCheck(command2);
//
//                    //performing the action
//                    appState.getScribbler().forward(value1);
//                    double numSeconds = Double.valueOf(value2);
//    				assert numSeconds >= 0.0 : "numSeconds not >= 0.0";
//    				MyroUtils.sleep(numSeconds);
//    				appState.getScribbler().stop();
//
//                }
//                else if(parts[i].contains("backward"))
//                {
//                    String test = parts[i].substring(9, parts[i].length());
//                    String command1 = test.substring(1, test.indexOf(','));
//                    String command2 = test.substring(test.indexOf(',')+2, test.length()-1);
//                    double value1 = Double.parseDouble(command1);
//                    double value2 = Double.parseDouble(command2);
//
//                    // debugging
//                    Log.d("Camera_QR_Backward", "backward");
//                    Log.d("Camera_QR_Backward", "value1 " + value1);
//                    Log.d("Camera_QR_Backward", "value2 " + value2);
//
//                    // console
//                    consoleCheck("Backward");
//                    consoleCheck(command1);
//                    consoleCheck(command2);
//
//                    // performing the action
//                    appState.getScribbler().backward(value1);
//    				double numSeconds = Double.valueOf(value2);
//    				assert numSeconds >= 0.0 : "numSeconds not >= 0.0";
//    				MyroUtils.sleep(numSeconds);
//    				appState.getScribbler().stop();
//                }
//                else if(parts[i].contains("turnRight"))
//                {
//                    String test = parts[i].substring(9, parts[i].length());
//                    String command1 = test.substring(1, test.indexOf(','));
//                    String command2 = test.substring(test.indexOf(',')+2, test.length()-1);
//                    double value1 = Double.parseDouble(command1);
//                    double value2 = Double.parseDouble(command2);
//
//                    // debugging
//                    Log.d("Camera_QR_turnRight", "backward");
//                    Log.d("Camera_QR_turnRight", "value1 " + value1);
//                    Log.d("Camera_QR_turnRight", "value2 " + value2);
//
//                    // console
//                    consoleCheck("Turn Right");
//                    consoleCheck(command1);
//                    consoleCheck(command2);
//
//                    // performing the action
//                    appState.getScribbler().turnRight(value1);
//                    double numSeconds = Double.valueOf(value2);
//    				assert numSeconds >= 0.0 : "numSeconds not >= 0.0";
//    				MyroUtils.sleep(numSeconds);
//    				appState.getScribbler().stop();
//                }
//                else if(parts[i].contains("turnLeft"))
//                {
//                    String test = parts[i].substring(8, parts[i].length());
//                    String command1 = test.substring(1, test.indexOf(','));
//                    String command2 = test.substring(test.indexOf(',')+2, test.length()-1);
//                    double value1 = Double.parseDouble(command1);
//                    double value2 = Double.parseDouble(command2);
//
//                    // debugging
//                    Log.d("Camera_QR_turnLeft", "backward");
//                    Log.d("Camera_QR_turnLeft", "value1 " + value1);
//                    Log.d("Camera_QR_turnLeft", "value2 " + value2);
//
//                    // console
//                    consoleCheck("Turn Right");
//                    consoleCheck(command1);
//                    consoleCheck(command2);
//
//                    // performing the action
//                    appState.getScribbler().turnLeft(value1);
//                    double numSeconds = Double.valueOf(value2);
//    				assert numSeconds >= 0.0 : "numSeconds not >= 0.0";
//    				MyroUtils.sleep(numSeconds);
//    				appState.getScribbler().stop();
//                }
//                else
//                {
//                    // Don't know what just happened
//                	appState.getScribbler().stop();
//                	Log.d("Camera_QR_Error", "I don't understand the QR code. It says: " + parts.toString());
//                	consoleCheck("Camera_QR_Error, I don't understand the QR code. It says: " + parts.toString());
//                }
//            }
//            if(!lastResult.contains("stop"))
//            {
//                scan();
//            }
//        }
//    }
//
//	/**
//	 * simply checks to see if the TextView is empty or not.
//	 *
//	 * If it is empty, then the message is printed.
//	 *
//	 * If its not empty, then the text is copied over to a new string with the new message on a new line
//	 *
//	 * @param String message
//	 */
//	private void consoleCheck(String message)
//	{
//		if(console.getText().equals("")){
//			console.setText(message);
//		}
//		else{
//			String original = console.getText().toString();
//			console.setText(original + "\n" + message);
//		}
//	}
//}


text:
#region License

#endregion

using System;
using System.Runtime.Serialization;

namespace Common.Logging
{
    /// <summary>
    /// The exception that is thrown when a configuration system error has occurred with Common.Logging
    /// </summary>
    /// <author>Mark Pollack</author>
    [Serializable]
    public class ConfigurationException : ApplicationException
    {
        #region Constructor (s) / Destructor

        /// <summary>Creates a new instance of the ObjectsException class.</summary>
        public ConfigurationException()
        {
        }

        /// <summary>
        /// Creates a new instance of the ConfigurationException class. with the specified message.
        /// </summary>
        /// <param name="message">
        /// A message about the exception.
        /// </param>
        public ConfigurationException(string message) : base(message)
        {
        }

        /// <summary>
        /// Creates a new instance of the ConfigurationException class with the specified message
        /// and root cause.
        /// </summary>
        /// <param name="message">
        /// A message about the exception.
        /// </param>
        /// <param name="rootCause">
        /// The root exception that is being wrapped.
        /// </param>
        public ConfigurationException(string message, Exception rootCause)
            : base(message, rootCause)
        {
        }

        /// <summary>
        /// Creates a new instance of the ConfigurationException class.
        /// </summary>
        /// <param name="info">
        /// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
        /// that holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="System.Runtime.Serialization.StreamingContext"/>
        /// that contains contextual information about the source or destination.
        /// </param>
        protected ConfigurationException(
            SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        #endregion
    }
}


text:
package com.wantedtech.common.xpresso.web.service;

import java.io.IOException;
import java.net.*;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Service provider class for HttpServer.
 * Sub-classes of HttpServerProvider provide an implementation of {@link HttpServer} and
 * associated classes. Applications do not normally use this class.
 * See {@link #provider()} for how providers are found and loaded.
 */
public abstract class HttpServerProvider {

    /**
     * creates a HttpServer from this provider
     * @param addr the address to bind to. May be null
     * @param backlog the socket backlog. A value of zero means the systems default
     */
    public abstract HttpServer createHttpServer (InetSocketAddress addr, int backlog) throws IOException;

    private static final Object lock = new Object();
    private static HttpServerProvider provider = null;

    /**
     * Initializes a new instance of this class.

     *
     * @throws  SecurityException
     *          If a security manager has been installed and it denies
     *          {@link RuntimePermission}<tt>("httpServerProvider")</tt>
     */
    protected HttpServerProvider() {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null)
            sm.checkPermission(new RuntimePermission("httpServerProvider"));
    }

    /**
     * Returns the system wide default HttpServerProvider for this invocation of
     * the Java virtual machine.
     *
     *
 The first invocation of this method locates the default provider
     * object as follows:

     *
     *

     *
     *

 If the system property
     *   <tt>com.sun.net.httpserver.HttpServerProvider</tt> is defined then it is
     *   taken to be the fully-qualified name of a concrete provider class.
     *   The class is loaded and instantiated; if this process fails then an
     *   unspecified unchecked error or exception is thrown.

     *
     *

 If a provider class has been installed in a jar file that is
     *   visible to the system class loader, and that jar file contains a
     *   provider-configuration file named
     *   <tt>com.sun.net.httpserver.HttpServerProvider</tt> in the resource
     *   directory <tt>META-INF/services</tt>, then the first class name
     *   specified in that file is taken.  The class is loaded and
     *   instantiated; if this process fails then an unspecified unchecked error or exception is
     *   thrown.

     *
     *

 Finally, if no provider has been specified by any of the above
     *   means then the system-default provider class is instantiated and the
     *   result is returned.

     *
     *

     *
     *
 Subsequent invocations of this method return the provider that was
     * returned by the first invocation.

     *
     * @return  The system-wide default HttpServerProvider
     */
    public static HttpServerProvider provider () {
        synchronized (lock) {
            if (provider != null)
                return provider;
            return (HttpServerProvider)AccessController
                .doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            provider = new DefaultHttpServerProvider();
                            return provider;
                        }
                    });
        }
    }

}


text:
class AttackScore
  OFFENSIVE_TRICK_MULTIPLIER = 100
  BASE_SCORES = {
    Card.suits[:spades]   =>  40,
    Card.suits[:clubs]    =>  60,
    Card.suits[:diamonds] =>  80,
    Card.suits[:hearts]   => 100,
    Card.suits[:no_suit]  => 120
  }

  def initialize(attempted_number_of_tricks:, attempted_suit:, number_of_tricks_won:)
    @attempted_number_of_tricks = attempted_number_of_tricks
    @number_of_tricks_won = number_of_tricks_won
    @attempted_suit = attempted_suit
  end

  def score
    @number_of_tricks_won >= @attempted_number_of_tricks ? score_for_attack : -score_for_attack
  end

  private

  def score_for_attack
    BASE_SCORES[Card.suits[@attempted_suit]] +
      ((@attempted_number_of_tricks - Bid::MIN_TRICKS) * OFFENSIVE_TRICK_MULTIPLIER)
  end
end


text:
package net.java.sip.communicator.slick.netaddr;

import junit.framework.*;

/**
 *
 * @author Emil Ivov
 */
public class TestAddressPool
    extends TestCase
{
    public TestAddressPool()
    {
        super();
    }

    public TestAddressPool(String name)
    {
        super(name);
    }
}


text:
.. title: Testez le prototype de la nouvelle apparence de Wikipedia
.. category: articles-fr
.. slug: testez-le-prototype-de-la-nouvelle-apparence-de-wikipedia
.. date: 2009-06-20 16:27:51
.. tags: Wikimedia
.. keywords: Ingénierie, Wikimedia, Wikipedia
.. image: /images/2009-06-20_Vector_frwp.png

La |usability initiative|_ est un projet de la *Wikimedia Foundation* ayant pour objectif d'améliorer l'ergonomie de Wikipedia, souvent jugée trop complexe et trop chargée pour les débutants. Je ne peux qu'être d'accord ; j'avais d'ailleurs abordé le sujet il y a presque deux ans, à la conférence Wikimania de Taipei, lors de ma présentation sur l'identité visuelle des projets Wikimedia [#]_.

.. |usability initiative| replace:: *Wikipedia Usability Initiative*

.. _usability initiative: http://usability.wikimedia.org

Naoko Komura, chef du projet *Usability initiative*, a annoncé au début du mois [#]_ la mise en ligne d'un `prototype <http://usability.wikimedia.org/wiki/Prototype>`__ des améliorations sur lesquelles l'équipe travaille actuellement ; l'objectif est de voir comment la nouvelle apparence s'intègre au contenu existant des Wikipedia dans différentes langues. Ces prototypes consistent en des copies de Wikipedia en anglais, allemand, japonais, arabe et serbe utilisant la nouvelle apparence.

Wikipedia en français n'est pas dans la liste, mais il est cependant possible d'en avoir un aperçu en utilisant `une astuce technique <http://fr.wikipedia.org/w/index.php?title=Wikip%C3%A9dia:Accueil_principal&useskin=vector>`__.

Les principaux changements consistent en une réduction de l'encombrement visuel ; il y a encore du travail à faire, mais l'équipe est sur la bonne voie. L'activation complète de cette nouvelle apparence n'est pas encore prévue ; il n'est même pas certain que ce prototype sera au final la solution choisie.

Si vous souhaitez donner votre retour sur le prototype, vous pouvez déposer vos commentaires sur http://usability.wikimedia.org/wiki/Talk:Prototype.

.. [#] |wm2007|_. Guillaume Paumier and Elisabeth Bauer, Wikimania 2007, Taipei, Taiwan.

.. |wm2007| replace:: *Strengthening and unifying the visual identity of Wikimedia projects: a step towards maturity*

.. _wm2007: http://wikimania2007.wikimedia.org/wiki/Proceedings:GP1

.. [#] |brewing|_. Naoko Komura, Wikimedia blog, 2 juin 2009.

.. |brewing| replace:: *Brewing ideas for the Wikipedia usability initiative*

.. _brewing: http://blog.wikimedia.org/2009/06/02/brewing-ideas-for-the-wikipedia-usability-initiative/


text:
package com.bupt.poirot.data.kafakaDataStream;

import java.util.Arrays;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

public class ConsumerDemo {

	public static void main(String[] args) {
		System.out.println("begin consumer");
		connectionKafka();
		System.out.println("finish consumer");
	}

	@SuppressWarnings("resource")
	public static void connectionKafka() {

		Properties props = new Properties();
		props.put("bootstrap.servers", "10.109.253.74:9092");
//		props.put("bootstrap.servers", "localhost:9092");
		props.put("group.id", "testConsumer");
		props.put("enable.auto.commit", "true");
		props.put("auto.commit.interval.ms", "1000");
		props.put("session.timeout.ms", "10000");
		props.put("max.poll.records", "3");
		props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
		props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
		consumer.subscribe(Arrays.asList("traffic-data"));
		while (true) {
			ConsumerRecords<String, String> records = consumer.poll(1);
//			try {
//				Thread.sleep(200);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			for (ConsumerRecord<String, String> record : records) {
				System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value());
				System.out.println();
			}
		}
	}
}


text:
@class NSArray, UILabel, WFActivityBarGraphWeekView;

@interface WFHistoryCalendarScrollerWeekCell : WFHistoryCalendarScrollerCell
{
    NSArray *_dateLabels;
    UILabel *_monthLabel;
    UILabel *_secondMonthLabel;
    NSArray *_weekdayLabels;
    WFActivityBarGraphWeekView *_barGraphView;
}

@property(nonatomic) __weak WFActivityBarGraphWeekView *barGraphView; // @synthesize barGraphView=_barGraphView;
@property(retain, nonatomic) NSArray *weekdayLabels; // @synthesize weekdayLabels=_weekdayLabels;
@property(nonatomic) __weak UILabel *secondMonthLabel; // @synthesize secondMonthLabel=_secondMonthLabel;
@property(nonatomic) __weak UILabel *monthLabel; // @synthesize monthLabel=_monthLabel;
@property(retain, nonatomic) NSArray *dateLabels; // @synthesize dateLabels=_dateLabels;
- (void).cxx_destruct;
- (void)setEndDate:(double)arg1;
- (void)setStartDate:(double)arg1;
- (void)awakeFromNib;

@end


text:
IF(NOT DEFINED CMAKE_INSTALL_PREFIX)
  SET(CMAKE_INSTALL_PREFIX "/usr/local")
ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)
STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  IF(BUILD_TYPE)
    STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  ELSE(BUILD_TYPE)
    SET(CMAKE_INSTALL_CONFIG_NAME "Release")
  ENDIF(BUILD_TYPE)
  MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)

# Set the component getting installed.
IF(NOT CMAKE_INSTALL_COMPONENT)
  IF(COMPONENT)
    MESSAGE(STATUS "Install component: \"${COMPONENT}\"")
    SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  ELSE(COMPONENT)
    SET(CMAKE_INSTALL_COMPONENT)
  ENDIF(COMPONENT)
ENDIF(NOT CMAKE_INSTALL_COMPONENT)

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE SHARED_LIBRARY FILES
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/librabbitmq.1.0.1.dylib"
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/librabbitmq.1.dylib"
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/librabbitmq.dylib"
    )
  FOREACH(file
      "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.1.0.1.dylib"
      "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.1.dylib"
      "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.dylib"
      )
    IF(EXISTS "${file}" AND
       NOT IS_SYMLINK "${file}")
      EXECUTE_PROCESS(COMMAND "/usr/bin/install_name_tool"
        -id "librabbitmq.1.dylib"
        "${file}")
      IF(CMAKE_INSTALL_DO_STRIP)
        EXECUTE_PROCESS(COMMAND "/usr/bin/strip" "${file}")
      ENDIF(CMAKE_INSTALL_DO_STRIP)
    ENDIF()
  ENDFOREACH()
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/lib" TYPE STATIC_LIBRARY FILES "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/librabbitmq.a")
  IF(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.a" AND
     NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.a")
    EXECUTE_PROCESS(COMMAND "/usr/bin/ranlib" "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/lib/librabbitmq.a")
  ENDIF()
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")

IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
  FILE(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/include" TYPE FILE FILES
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/amqp.h"
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/amqp_framing.h"
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/amqp_tcp_socket.h"
    "/Users/janmachacek/Talks/springone2gx2013/native/rabbitmq-c/librabbitmq/amqp_ssl_socket.h"
    )
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")


text:
<?php

namespace Antares\Contracts\Foundation\Command\Account;

use Antares\Contracts\Foundation\Listener\Account\ProfileCreator as Listener;

interface ProfileCreator
{

    /**
     * View registration page.
     */
    public function create();

    /**
     * Create a new user.
     */
    public function store(Listener $listener, array $input);
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('delibere', '0024_auto_20170613_0948'),
    ]

    operations = [
        migrations.AddField(
            model_name='delibera',
            name='pubblicata',
            field=models.BooleanField(default=False, help_text='Se la delibera \xe8 visibile e ricercabile'),
        ),
        migrations.AlterField(
            model_name='delibera',
            name='amministrazioni',
            field=models.ManyToManyField(blank=True, null=True, related_name='delibere', to='delibere.Amministrazione'),
        ),
        migrations.AlterField(
            model_name='delibera',
            name='normative',
            field=models.ManyToManyField(blank=True, null=True, related_name='delibere', to='delibere.Normativa'),
        ),
        migrations.AlterField(
            model_name='delibera',
            name='settori',
            field=models.ManyToManyField(blank=True, null=True, related_name='delibere', to='delibere.Settore'),
        ),
        migrations.AlterField(
            model_name='settore',
            name='display_order',
            field=models.PositiveIntegerField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name='settore',
            name='ss_id',
            field=models.IntegerField(blank=True, null=True, unique=True),
        ),
        migrations.AlterField(
            model_name='settore',
            name='sss_id',
            field=models.IntegerField(blank=True, null=True, unique=True),
        ),
    ]


text:
package com.dreamfighter.android.webadapter.entity;

import android.graphics.Bitmap;

public class BaseEntity {
	protected Long 	 id;
	protected String name;
	protected Bitmap image;
	protected String imageUrl;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Bitmap getImage() {
		return image;
	}
	public void setImage(Bitmap image) {
		this.image = image;
	}
	public String getImageUrl() {
		return imageUrl;
	}
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}

}


text:
var gulp = require('gulp');
var gutil = require("gulp-util");
var fs = require("fs");
var expect = require('chai').expect;
var requireFile = require('../');

function buildTestFile(fileName) {
  return new gutil.File({
    base: "test/fixtures/",
    path: "test/fixtures/" + fileName,
    contents: fs.readFileSync("test/fixtures/" + fileName)
  });
}

function testByFile(fileName, done, opts) {
  opts = opts || {};
  opts.makeSourceMaps = true;
  var file = buildTestFile(fileName);

  testRequireFile = requireFile(opts);
  testRequireFile.on("data", function (newFile) {
    expect(newFile).to.exist;
    expect(newFile.contents).to.exist;
    expect(newFile.sourceMap).to.exist;

    var expectedString = String(fs.readFileSync("test/expected/" + fileName), "utf8");
    expect(String(newFile.contents)).to.equal(expectedString);
    var expectedMap = String(fs.readFileSync("test/expected/maps/" + fileName.split(".")[0] + ".map"), "utf8");
    expect(JSON.stringify(newFile.sourceMap)).to.equal(expectedMap);
    done();
  });
  testRequireFile.write(file);
}

describe('gulp-require-file', function(){
  describe('requireFile()', function(){
    it("should not require the same file multiple times", function (done) {
      testByFile('app.js', done);
    });

    it("should require a directory of source files", function (done) {
      testByFile('app_directory.js', done);
    });

    it("should require a tree of source files", function (done) {
      testByFile('app_tree.js', done);
    });

    it("should process a nested structure of source files", function (done) {
      testByFile('app_recursive.js', done);
    });

    it("should ignore files based on glob pattern", function (done) {
      testByFile('app_ignore.js', done, {globOptions: {ignore: '**/b.js'}});
    });
  })
});


text:
package org.jf.dexlib2.iface.instruction.formats;

import org.jf.dexlib2.iface.instruction.*;

public interface Instruction51l extends OneRegisterInstruction, WideLiteralInstruction {
}


text:
package net.sourceforge.jeval.function.math;

import net.sourceforge.jeval.Evaluator;
import net.sourceforge.jeval.function.Function;
import net.sourceforge.jeval.function.FunctionConstants;
import net.sourceforge.jeval.function.FunctionException;
import net.sourceforge.jeval.function.FunctionResult;

/**
 * This class is a function that executes within Evaluator. The function returns
 * trigonometric tangent of an angle. See the Math.tan(double) method in the JDK
 * for a complete description of how this function works.
 */
public class Tan implements Function {
	/**
	 * Returns the name of the function - "tan".
	 *
	 * @return The name of this function class.
	 */
	public String getName() {
		return "tan";
	}

	/**
	 * Executes the function for the specified argument. This method is called
	 * internally by Evaluator.
	 *
	 * @param evaluator
	 *            An instance of Evaluator.
	 * @param arguments
	 *            A string argument that will be converted to a double value and
	 *            evaluated.
	 *
	 * @return A trigonometric tangent of an angle.
	 *
	 * @exception FunctionException
	 *                Thrown if the argument(s) are not valid for this function.
	 */
	public FunctionResult execute(Evaluator evaluator, String arguments)
			throws FunctionException {
		Double result = null;
		Double number = null;

		try {
			number = new Double(arguments);
		} catch (Exception e) {
			throw new FunctionException("Invalid argument.", e);
		}

		result = new Double(Math.tan(number.doubleValue()));

		return new FunctionResult(result.toString(),
				FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
	}
}


text:
from .linked_service import LinkedService

class WebLinkedService(LinkedService):
    """Web linked service.

    :param additional_properties: Unmatched properties from the message are
     deserialized this collection
    :type additional_properties: dict[str, object]
    :param connect_via: The integration runtime reference.
    :type connect_via:
     ~azure.mgmt.datafactory.models.IntegrationRuntimeReference
    :param description: Linked service description.
    :type description: str
    :param type: Constant filled by server.
    :type type: str
    :param type_properties: Web linked service properties.
    :type type_properties:
     ~azure.mgmt.datafactory.models.WebLinkedServiceTypeProperties
    """

    _validation = {
        'type': {'required': True},
        'type_properties': {'required': True},
    }

    _attribute_map = {
        'additional_properties': {'key': '', 'type': '{object}'},
        'connect_via': {'key': 'connectVia', 'type': 'IntegrationRuntimeReference'},
        'description': {'key': 'description', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'type_properties': {'key': 'typeProperties', 'type': 'WebLinkedServiceTypeProperties'},
    }

    def __init__(self, type_properties, additional_properties=None, connect_via=None, description=None):
        super(WebLinkedService, self).__init__(additional_properties=additional_properties, connect_via=connect_via, description=description)
        self.type_properties = type_properties
        self.type = 'Web'


text:
@implementation HLShowRefreshCountTool

+ (void)showText:(NSString *)text inNavc:(UINavigationController *)navc; {
    UILabel *label = [[UILabel alloc] init];
    label.alpha = 0.0;
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:10];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    [navc.view insertSubview:label belowSubview:navc.navigationBar];

    NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:navc.navigationBar attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    NSLayoutConstraint *centerX = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:navc.navigationBar attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:[UIScreen mainScreen].bounds.size.width];
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:20];
    [navc.view addConstraints:@[bottom, centerX, width, height]];
    [UIView animateWithDuration:1 animations:^{
        label.alpha = 1.0;
        label.transform = CGAffineTransformMakeTranslation(0, 20);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            label.alpha = 0.0;
            label.transform =CGAffineTransformMakeTranslation(0, 0);
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

@end


text:
using HFEA.Connector.Contracts.Clients;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HFEA.Connector.Contracts.ClientFactories
{
    public interface IPatchClientFactory
    {
        IApiPatchClient GetClientApi(Enum apiType);
    }
}


text:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Day1 {

    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);
		/* Declare second integer, double, and String variables. */
        int i1;
        double d1;
        String s1;
        /* Read and save an integer, double, and String to your variables.*/
        // Note: If you have trouble reading the entire String, please go back and review the Tutorial closely.
        i1 = scan.nextInt();
		d1 = scan.nextDouble();
		scan.nextLine();//It seems nextInt doesnt' consume the '\n' character and hence '\n' becomes the input for nextLine.
		s1 = scan.nextLine();//To solve this the above nexLine methid is included.
		System.out.println(s1);
        /* Print the sum of both integer variables on a new line. */
        System.out.println(i + i1);
        /* Print the sum of the double variables on a new line. */
		System.out.println(d + d1);
        /* Concatenate and print the String variables on a new line;
        	the 's' variable above should be printed first. */
		System.out.println(s1);
		System.out.println(s + s1);
	    scan.close();
    }
}


text:
namespace dropkick.DeploymentModel
{
    using System;
    using System.Diagnostics;

    [DebuggerDisplay("[{Status}:{Message}")]
    public class DeploymentItem
    {
        public DeploymentItem(DeploymentItemStatus status, string message)
        {
            Status = status;
            Message = message;
        }

        public DeploymentItem(DeploymentItemStatus status, string message, Exception exception)
        {
            Status = status;
            Message = message;
            Exception = exception;
        }

        public DeploymentItemStatus Status { get; private set; }
        public string Message { get; private set; }
        public Exception Exception { get; private set; }
    }
}


text:
Angular Panels
================

Pure [AngularJS](http://www.angularjs.org) based Drag and Drop.
[![ScreenShot](https://rawgit.com/eu81273/angular.dragndrop/gh-pages/images/preview.png)](http://eu81273.github.io/angular.dragndrop/)

## Demo

[http://eu81273.github.io/angular.dragndrop/](http://eu81273.github.io/angular.dragndrop/)

## Installation

Copy the script and css into your project and add a script and link tag to your page.

```html
<script type="text/javascript" src="angular.dragndrop.js"></script>
<link rel="stylesheet" type="text/css" href="angular.dragndrop.css">
```

And add dragndrop container tag to your application.

```html
<div data-dragndrop="true"></div>

```

Add a dependency to your application module and configure panel settings.

```javascript
var app = angular.module('myApp', ['angular.dragndrop']);

app.config(['dragndropProvider', function (dragndropProvider) {

	dragndropProvider
		.add({
			id: "testmenu",
			position: "right",
			size: "700px",
			templateUrl: "../resources/template/testmenu.html",
			controller: "testmenuCtrl"
		})
		.add({
			id: "testpanel",
			position: "right",
			size: "80%",
			templateUrl: "../resources/template/testpanel.html",
			controller: "testpanelCtrl",
			closeCallbackFunction: "testpanelClose"
		});
}]);

```

attributes are..

- id : panel's unique id.
- position : the side panel slides from top/right/bottom/left.
- size : panel's height or width. unit(px,em,%..) is required.
- templateUrl : panel template url.
- controller : panel's controller name.
- openCallbackFunction : panel open callback.
- closeCallbackFunction : panel close callback.

## Open panel

Opening panel also very simple. Inject dragndrop service to your app then call the service method like below.

```javascript
var app = angular.module('myApp', ['angular.dragndrop']);

app.config(['dragndropProvider', function (dragndropProvider) {

	dragndropProvider
		.add({
			id: "testmenu",
			position: "right",
			size: "700px",
			templateUrl: "../resources/template/testmenu.html",
			controller: "testmenuCtrl"
		});
}]);

app.controller('defaultController', function($scope, dragndrop) {

	//open testmenu panel
	dragndrop.open("testmenu");
});

app.controller('testmenuCtrl', function($scope) {

	//left panel controller

});

```

## Browser Compatibility

IE10+, Chrome, Safari

## Changelogs

#### version 1.0.0
- first release

## License

The MIT License.

Copyright ⓒ 2015 AHN JAE-HA.

See [LICENSE](https://github.com/eu81273/angular.dragndrop/blob/master/LICENSE)


text:
<TITLE>Review for Wild Wild West (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Wild Wild West (1999)

reviewed by
David Sunga

WILD WILD WEST (1999)

Rating: 2.0 stars (out of 4.0)
********************************
Key to rating system:
2.0 stars - Debatable
2.5 stars - Some people may like it
3.0 stars - I liked it
3.5 stars - I am biased in favor of the movie
4.0 stars - I felt the movie's impact personally or it stood out
*********************************
A Movie Review by David Sunga

Directed by: Barry Sonnenfeld

Written by: Written by S.S. Wilson, Brent Maddock, Jeffrey Price and Peter
S. Seaman

Starring: Will Smith, Kevin Kline, Salma Hayek, and Kenneth Branagh

Synopsis:
Will Smith plays James West and Kevin Kline is Artemus Gordon in this 1999
movie based on the 1965-70 television adventure/spy series about two 1860s
cowboy secret agents.

West attends a party and soon finds himself in trouble. "Sorry I made the
mistake of drumming on a white woman's breasts," says West. Meanwhile
Gordon falls for a saloon girl named Rita (Salma Hayek) whose father has
been kidnapped. "She's a breath of fresh ass, I mean a breast of fresh
air," the love-smitten Gordon remarks. The kidnapper, a scientist named Dr.
Arliss Loveless (Kenneth Branagh), is wheelchair-bound, a condition which
gives West ample comedic ammunition for emasculation and shortness jokes.
As West, Gordon and Rita give chase Loveless plots to dismantle America and
give most of it to European colonialist rulers.

Opinion:
These days I often hear the WILD WILD WEST song played on MTV. It sounds
like an old Stevie Wonder tune with all the same chords but they changed
the words and now it's WILD WILD WEST. The song makes a pretty catchy
advertisement for the movie.

WILD WILD WEST (1999) shows how agents West and Gordon first meet and
become partners. Usually in cop buddy movies new partners develop a close
bond after some initial friction. Unfortunately, in WILD WILD WEST
chemistry between West and Gordon never seems to develop. James West has
initial misgivings about technology and develops a bond with it, but he
doesn't seem to like Gordon any more or any less by the end of the movie.
West is a Civil War Era African American and Gordon is a white stranger,
but the whole relationship aspect seems unexplored.

On the other hand, it's supposed to be escapist fantasy. WILD WILD WEST is
the kind of movie where they spend a fortune on special effects but blunder
on the details. A bad guy gets electrocuted with a big wrench. I didn't see
any batteries or wires. West plucks a flattened bullet from the INSIDE of
his bulletproof vest rather than the OUTSIDE. Huh? Loveless captures Rita
and threatens to use her for his pleasure, but Loveless has already had the
lower half of his body chopped off. And so on.

Given a choice between hearing the MTV song or watching the movie, I take
the song.

Reviewed by David Sunga
July 5, 1999

Copyright © 1999 by David Sunga
This review and others like it can be found at
THE CRITIC ZOO: http://www.criticzoo.com
email: zookeeper@criticzoo.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews