text:
import matplotlib
import matplotlib.ticker
import warnings
# the other imports are inside functions!!!1

def import_matplotlib_pyplot(interactive=True):
    if interactive:
        matplotlib.use('qt4agg')
    import matplotlib.pyplot as plt
    return plt

def format_list(values, divisor=1000):
    powers = ['', 'K', 'M', 'G', 'T', 'P']
    div_values = values.copy()
    power = powers[0]
    while max(div_values) >= divisor:
        div_values = [x / divisor for x in div_values]
        power = powers[powers.index(power) + 1]
    decimal_positions = 1 if max(div_values) < 10 else 0
    return map("{{:.{}f}}".format(decimal_positions).format, div_values), power

class TogglableLegend:

    def __init__(self, fig):
        self.fig = fig
        self.connection_id = fig.canvas.mpl_connect('pick_event', self.__onpick)
        self.__lines_legend = {}

    def add(self, legend_line, original_lines):
        if legend_line not in self.__lines_legend:
            self.__lines_legend[legend_line] = []
        self.__lines_legend[legend_line].extend(original_lines)
        legend_line.set_picker(5)  # 5 pts tolerance

    def __set_visibility(self, legline, visibility=None):
        origlines = self.__lines_legend[legline]
        if visibility == None:
            # toggle
            visibility = not origlines[0].get_visible()
        for origline in origlines:
            origline.set_visible(visibility)
        # Change the alpha on the line in the legend so we can see what lines
        # have been toggled
        if visibility:
            legline.set_alpha(1.0)
        else:
            legline.set_alpha(0.4)

    def __onpick(self, event):
        # on the pick event, find the orig line corresponding to the
        # legend proxy line, and toggle the visibility
        legline = event.artist
        if event.mouseevent.button == 1:
            self.__set_visibility(legline)
        elif event.mouseevent.button == 3:
            for ll in self.__lines_legend.keys():
                visibility = (ll == legline) if not event.mouseevent.dblclick else True
                self.__set_visibility(ll, visibility)
        self.fig.canvas.draw()

class YAx:
    name = None
    unit = None

    @classmethod
    def get_instance(cls, attr_name, is_relative):
        ylimits = None
        if ':' in attr_name:
            attr_name, str_ylimits = attr_name.split(':', 1)
            try:
                ylimits = tuple(map(float, str_ylimits.split(',', 1)))
            except ValueError:
                pass
        if attr_name == 'throughput':
            instance = ThroughputAx(is_relative)
        elif attr_name == 'cpu':
            instance = CpuAx(is_relative)
        elif attr_name == 'packetput':
            instance = PacketputAx(is_relative)
        instance.ylimits = ylimits
        return instance

    def __init__(self, is_relative):
        self.is_relative = is_relative

    def get_value(self, r):
        raise ValueError('Must be implemented in subclass')

    def format_ax(self, ax):
        ax.grid(True)
        if self.ylimits is not None:
            ax.set_ylim(self.ylimits)
        if self.name is not None:
            ylabel = self.name
            if self.is_relative:
                ylabel += ' (% gain relative to ref)'
            elif self.unit is not None:
                ylabel += ' ({})'.format(self.unit)
            ax.set_ylabel(ylabel)

class ThroughputAx(YAx):
    name = 'throughput'
    unit = 'b/s'

    def get_value(self, r):
        try:
            return r['iperf_result']['throughput']
        except TypeError:
            return None

    def format_ax(self, ax):
        super().format_ax(ax)
        if not self.is_relative:
            ax.yaxis.set_major_formatter(PrefixFormatter())

class CpuAx(YAx):
    name = 'cpu utilization'
    unit = '%'

    def get_value(self, r):
        try:
            return (100 - r['iostat_cpu']['idle'][0], r['iostat_cpu']['idle'][1])  # 100 - idle
        except TypeError:
            return None

    def format_ax(self, ax):
        super().format_ax(ax)
        if not self.is_relative:
            ax.axis([None, None, 0, 102])

class PacketputAx(YAx):
    name = 'throughput'
    unit = 'pps'

    def get_value(self, r):
        try:
            return r['iperf_result']['packetput']
        except TypeError:
            return None

    def format_ax(self, ax):
        super().format_ax(ax)
        if not self.is_relative:
            ax.yaxis.set_major_formatter(PrefixFormatter())

class PrefixFormatter(matplotlib.ticker.Formatter):
    __powers = ['', 'K', 'M', 'G', 'T', 'P']
    __divisor = 1000
    __cache = {}

    def __call__(self, x, pos=None):  # pos=None when trying to display the value on the statusbar (you're hovering the plot with the pointer)
        if pos is None:
            return x
        locs_tuple = tuple(self.locs)
        if locs_tuple not in self.__cache:
            div_values = self.locs.copy()
            div_xmax = self.locs[-1]
            power_index = 0
            while div_xmax >= self.__divisor and power_index < len(self.__powers):
                div_values = [x / self.__divisor for x in div_values]
                div_xmax = div_values[-1]
                power_index += 1
            power = self.__powers[power_index]
            decimals = [str(int(n))[-(power_index * 3):] for n in self.locs]
            decimal_lengths = [len(n.replace('0', '')) for n in decimals]
            decimal_positions = max(decimal_lengths)
            self.__cache[locs_tuple] = tuple(map("{{:.{}f}}{}".format(decimal_positions, power).format, div_values))
        return self.__cache[locs_tuple][pos]

def dynamic(collection, export=None):
    columns, rows, rows_grouped = collection.analyze()
    y_axes = collection.y_axes
    window_title = collection.__class__.__name__

    if collection.is_relative():
        window_title += ' relative to: ' + ' '.join(['{}={}'.format(k, v) for k, v in collection.reference.items()])

    if len(rows_grouped) == 0 or len(y_axes) == 0:
        raise ValueError('Nothing to plot')
    for i, y_ax in enumerate(y_axes):
        if isinstance(y_ax, str):
            y_axes[i] = YAx.get_instance(y_ax, collection.is_relative())
    # import
    from collections import OrderedDict
    plt = import_matplotlib_pyplot(interactive=(export is None))

    fig, all_axes = plt.subplots(len(rows_grouped), len(y_axes), sharex=(export is None))
    fig.canvas.set_window_title(window_title)
    if len(rows_grouped) == 1:
        all_axes = (all_axes,)
    togglable_legend = TogglableLegend(fig)
    row_id = 0
    for axes_row in all_axes:
        if len(y_axes) == 1:
            axes_row = (axes_row,)
        while row_id not in rows_grouped:
            row_id += 1
        lines = []
        for label, rowdetails in rows_grouped[row_id].items():
            row = rowdetails['row']
            row_element = None  # used for the style_fn

            # fill the data structures
            x_values = [[] for i in range(len(y_axes))]
            plot_values = [[] for i in range(len(y_axes))]
            plot_errors = [[] for i in range(len(y_axes))]
            for col_index, col_name in enumerate(columns):
                r = row[col_index]
                if r is None:
                    # warnings.warn("Missing value on serie '{}' for x value {}".format(label, col_name), RuntimeWarning)
                    continue
                row_element = r
                for y_ax_index, y_ax in enumerate(y_axes):
                    value_error = y_ax.get_value(r)
                    if value_error is None:
                        warnings.warn("Missing value on serie '{}' for y_ax '{}'".format(label, y_ax.__class__.__name__), RuntimeWarning)
                        continue
                    if not isinstance(value_error, tuple):
                        value_error = (value_error, 0)
                    if collection.is_relative():
                        ref_r = collection.get_reference_row(r)
                        if ref_r is None:
                            # warnings.warn("Missing reference value on serie '{}' for x value {}".format(label, col_name), RuntimeWarning)
                            continue
                        ref_value_error = y_ax.get_value(ref_r)
                        if not isinstance(ref_value_error, tuple):
                            ref_value_error = (ref_value_error, 0)
                        plot_values[y_ax_index].append((value_error[0] - ref_value_error[0]) * 100 / ref_value_error[0])
                        plot_errors[y_ax_index].append((value_error[1] + ref_value_error[1]) * 100 / ref_value_error[0])
                    else:
                        plot_values[y_ax_index].append(value_error[0])
                        plot_errors[y_ax_index].append(value_error[1])
                    x_values[y_ax_index].append(col_name)

            # draw plot
            basestyle = {'linestyle': '-', 'markersize': 7}
            if export:
                basestyle['linewidth'] = 2
            kwargs = basestyle.copy()
            kwargs.update(collection.plot_style_fn(row_element, row_id))
            series_lines = []
            for y_ax_index, mpl_ax in enumerate(axes_row):
                if not len(x_values[y_ax_index]):
                    continue
                y_ax = y_axes[y_ax_index]
                if not collection.plot_hook_enabled or collection.plot_hook(mpl_ax, row_id, y_ax, x_values[y_ax_index], plot_values[y_ax_index], plot_errors[y_ax_index], kwargs):
                    line, two, three = mpl_ax.errorbar(x_values[y_ax_index], plot_values[y_ax_index], yerr=plot_errors[y_ax_index], label=label, **kwargs)
                    series_lines.extend((line,) + two + three)
                mpl_ax.set_xlabel(collection.x_title)
                if collection.x_limits is not None:
                    mpl_ax.set_xlim(collection.x_limits)
                y_ax.format_ax(mpl_ax)
                if mpl_ax.get_xlim()[1] > 10000:
                    mpl_ax.xaxis.set_major_formatter(PrefixFormatter())
            lines.append(series_lines)

        if export:
            legend = mpl_ax.legend(loc=collection.plot_legend_loc, fontsize='x-small')
        else:
            legend = mpl_ax.legend(bbox_to_anchor=(1, 1), loc=2, fontsize='x-small')
        if legend is not None:  # it may happen, if we have no series on that axis :/
            for legline, origlines in zip(legend.get_texts(), lines):
                togglable_legend.add(legline, origlines)
        row_id += 1

    if export is not None:
        fig.set_size_inches(len(y_axes) * 6.5 * collection.plot_size_factors[0], len(rows_grouped) * 3.2 * collection.plot_size_factors[1])
        fig.savefig(export, bbox_inches='tight')
    else:
        plt.subplots_adjust(left=0.05, right=0.82, top=0.95, bottom=0.1)
        plt.show()


text:
using System;
using System.Diagnostics;
using System.IO;
using BuildAProject.BuildManagement.BuildManagers;
using BuildAProject.Console.Configuration;
using BuildAProject.Console.IOC;
using BuildAProject.Console.Logging;

namespace BuildAProject.Console
{
  static class Program
  {
    static void Main(string[] args)
    {
      var stopWatch = new Stopwatch();
      stopWatch.Start();

      var container = Bootstrap.CreateContainer();

      var configuration = container.GetInstance<ConsoleConfiguration>();
      if (!configuration.Parse(args))
        return;

      var buildPath = Path.Combine(Environment.CurrentDirectory, configuration.BuildPath);

      var buildManager = container.GetInstance<IProjectBuildManager>();
      buildManager.Build(buildPath);

      var consoleLog = container.GetInstance<ILog>();

      var unhandledTasksErrorMessage = UnhandledBuildTasksLogger.GetErrorMessage();
      if (unhandledTasksErrorMessage != null)
        consoleLog.Error(unhandledTasksErrorMessage, 3);

      stopWatch.Stop();
      consoleLog.Information("Build complete", 1);
      consoleLog.Information(String.Format("Time building solutions: {0} ms", stopWatch.ElapsedMilliseconds), 1);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.elkm1api.messages.types;

import com.elkm1api.messages.Message;

/**
 * <quote>
 *
 * </quote>
 *
 * @author cdhesse
 *
 */
public class ReplyPLCStatusReport extends Message {

	public ReplyPLCStatusReport(String cmd, String fullCommand) {
		super(cmd, fullCommand);
	}

	public String toString() {
		return "";
	}
}


text:
package callete.api.services.impl.network.model;

/**
 * Pojo for ftl rendering.
 */
public class HostAPDRepresentation {
  private String ssid;
  private String password;

  public HostAPDRepresentation(String ssid, String password) {
    this.ssid = ssid;
    this.password = password;
  }

  public String getSsid() {
    return ssid;
  }

  public String getPassword() {
    return password;
  }
}


text:
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from cms.toolbar.items import BaseItem

@toolbar_pool.register
class PrivateLessonsToolbar(CMSToolbar):
    ''' Adds private events links to the Staff toolbar and category links to the related items toolbar '''

    def populate(self):
        staff_menu = self.toolbar.get_or_create_menu('core-staffmember', _('Staff'))
        position = staff_menu.find_first(BaseItem, name=_('Your Stats')) or 0

        staff_menu.add_link_item(
            _('Schedule a Private Lesson'), url=reverse('bookPrivateLesson'),
            position=position + 1
        )

        if (
            self.request.user.has_perm('private_lessons.edit_own_availability') or
            self.request.user.has_perm('private_lessons.edit_others_availability')
        ):
            staff_menu.add_link_item(
                _('Private Lesson Availability'),
                url=reverse('instructorAvailability'), position=position + 1
            )


text:
import mutations from './mutations';
import queries from './queries';
import types from './types';

export mutations from './mutations';
export types from './types';
export queries from './queries';

export default {
  types,
  mutations,
  queries
};


text:
/*
import React from 'react'
import * as Sb from '../../../stories/storybook'
import * as Types from '../../../constants/types/fs'
import * as Constants from '../../../constants/fs'
import * as Container from '../../../util/container'
import {isMobile} from '../../../constants/platform'
import {Box} from '../../../common-adapters'
import {WrapRow} from './rows'
import ConnectedStillRow from './still-container'
import TlfTypeRow from './tlf-type'
import TlfRow from './tlf'
import StillRow from './still'
import EditingRow from './editing'
import PlaceholderRow from './placeholder'
import * as RowTypes from './types'
import {commonProvider} from '../../common/index.stories'
import {topBarProvider} from '../../top-bar/index.stories'
import {asRows as topBarAsRow} from '../../top-bar'

export const rowsProvider = {
  ConnectedRows: (o: any) => ({
    destinationPickerIndex: o.destinationPickerIndex,
    emptyMode: 'not-empty',
    items: [
      ...(o.headerRows || []),
      ...topBarAsRow(o.path),
      {
        key: 'me',
        name: 'me',
        path: Types.stringToPath('/keybase/private/me'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,abc',
        name: 'me,abc',
        path: Types.stringToPath('/keybase/private/me,empty'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,abc,def',
        name: 'me,abc,def',
        path: Types.stringToPath('/keybase/private/me,abc,def'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,abc,def,ghi',
        name: 'me,abc,def,ghi',
        path: Types.stringToPath('/keybase/private/me,abc,def,ghi'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,def',
        name: 'me,def',
        path: Types.stringToPath('/keybase/private/me,def'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,def,ghi',
        name: 'me,def,ghi',
        path: Types.stringToPath('/keybase/private/me,def,ghi'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,ghi',
        name: 'me,ghi',
        path: Types.stringToPath('/keybase/private/me,ghi'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: 'me,abc,ghi',
        name: 'me,abc,ghi',
        path: Types.stringToPath('/keybase/private/me,abc,ghi'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '1',
        name: '1',
        path: Types.stringToPath('/keybase/private/meatball/1'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '2',
        name: '2',
        path: Types.stringToPath('/keybase/private/meatball/2'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '3',
        name: '3',
        path: Types.stringToPath('/keybase/private/meatball/3'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '4',
        name: '4',
        path: Types.stringToPath('/keybase/private/meatball/4'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '5',
        name: '5',
        path: Types.stringToPath('/keybase/private/meatball/5'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '6',
        name: '6',
        path: Types.stringToPath('/keybase/private/meatball/dir/6'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '7',
        name: '7',
        path: Types.stringToPath('/keybase/private/meatball/dir/7'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '8',
        name: '8',
        path: Types.stringToPath('/keybase/private/meatball/dir/8'),
        rowType: RowTypes.RowType.Still,
      },
      {
        key: '9',
        name: '9',
        path: Types.stringToPath('/keybase/private/meatball/dir/9'),
        rowType: RowTypes.RowType.Still,
      },
      ...(!isMobile && typeof o.destinationPickerIndex === 'number'
        ? [
            {key: 'empty:0', rowType: RowTypes.RowType.Empty},
            {key: 'empty:1', rowType: RowTypes.RowType.Empty},
          ]
        : []),
    ],
  }),
  ConnectedTlfTypeRow: ({destinationPickerIndex, name}) => ({
    destinationPickerIndex,
    name,
    path: Types.stringToPath(`/keybase/${name}`),
  }),
  LoadFilesWhenNeeded: ({path}: any) => ({
    loadFavorites: Sb.action('loadFavorites'),
    loadFolderListWithRefreshTag: Sb.action('loadFolderListWithRefreshTag'),
    loadFolderListWithoutRefreshTag: Sb.action('loadFolderListWithoutRefreshTag'),
    path,
    syncingFoldersProgress: Constants.emptySyncingFoldersProgress,
  }),
  SortBar: () => ({
    folderIsPending: true,
    sortSetting: Types.SortSetting.NameAsc,
    sortSettingToAction: Sb.action('sortSettingToAction'),
  }),
  Still: ({path, destinationPickerIndex}: {destinationPickerIndex?: number; path: Types.Path}) => {
    const pathStr = Types.pathToString(path)
    return {
      destinationPickerIndex,
      isEmpty: pathStr.includes('empty'),
      name: Types.getPathName(path),
      path,
      type: Types.PathType.Folder,
    }
  },
}

const store = Container.produce(Sb.createStoreWithCommon(), draftState => {
  draftState.fs.edits.set('edit-new-folder', {
    name: 'New Folder',
    originalName: 'New Folder',
    parentPath: Types.stringToPath('/keybae/private/meatball'),
    type: Types.EditType.NewFolder,
  })
  draftState.fs.edits.set('edit-new-folder-saving', {
    name: 'New Folder 2',
    originalName: 'New Folder 2',
    parentPath: Types.stringToPath('/keybae/private/meatball'),
    type: Types.EditType.NewFolder,
  })
  draftState.fs.edits.set('edit-rename', {
    name: 'original file name',
    originalName: 'original file name',
    parentPath: Types.stringToPath('/keybae/private/meatball'),
    type: Types.EditType.Rename,
  })
  draftState.fs.edits.set('edit-rename-failed', {
    error: 'this is an error message',
    name: 'original file name',
    originalName: 'original file name',
    parentPath: Types.stringToPath('/keybae/private/meatball'),
    type: Types.EditType.Rename,
  })
})

const provider = Sb.createPropProviderWithCommon({
  ...commonProvider,
  ...topBarProvider,
  ...rowsProvider,
})

const load = () => {
  Sb.storiesOf('Files', module)
    .addDecorator(Sb.scrollViewDecorator)
    .addDecorator(story => <Sb.MockStore store={store}>{story()}</Sb.MockStore>)
    .add('Rows - Editing', () => (
      <>
        <WrapRow key="2">
          <EditingRow editID="edit-new-folder" />
        </WrapRow>
        <WrapRow key="3">
          <EditingRow editID="edit-new-folder-saving" />
        </WrapRow>
        <WrapRow key="4">
          <EditingRow editID="edit-rename" />
        </WrapRow>
        <WrapRow key="5">
          <EditingRow editID="edit-rename-failed" />
        </WrapRow>
      </>
    ))
  Sb.storiesOf('Files', module)
    .addDecorator(provider)
    .addDecorator(Sb.scrollViewDecorator)
    .add('Rows', () => (
      <Box>
        <WrapRow key="1">
          <ConnectedStillRow path={Types.stringToPath('/keybase/private/meatball/a')} />
        </WrapRow>
        <WrapRow key="6">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath('/keybase/team/kbkbfstest/foo')}
            type={Types.PathType.Folder}
            writingToJournal={true}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="7">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath('/keybase/team/kbkbfstest/dir/foo')}
            type={Types.PathType.File}
            writingToJournal={true}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="8">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath('/keybase/team/kbkbfstest/dir/foo')}
            type={Types.PathType.File}
            writingToJournal={true}
            uploading={true}
          />
        </WrapRow>
        <WrapRow key="9">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath(
              '/keybase/team/kbkbfstest/dir/foo-obnoxiously-long-aslkdjhfalskjdhfaklsjdfhalksdjfhasdf-asdflkasjdfhlaksdjfh-asdhflaksjdhfaskd.mpeg4'
            )}
            type={Types.PathType.File}
            writingToJournal={false}
            uploading={true}
          />
        </WrapRow>
        <WrapRow key="10">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath('/keybase/team/kbkbfstest/dir/foo')}
            type={Types.PathType.File}
            writingToJournal={false}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="11">
          <StillRow
            isEmpty={false}
            path={Types.stringToPath('/keybase/team/kbkbfstest/dir/foo')}
            type={Types.PathType.File}
            writingToJournal={false}
            uploading={false}
            dismissUploadError={Sb.action('dismissUploadError')}
          />
        </WrapRow>
        <WrapRow key="download-normal">
          <StillRow
            path={Types.stringToPath('/keybase/private/foo/dir/bar')}
            type={Types.PathType.File}
            intentIfDownloading={Types.DownloadIntent.None}
            onOpen={Sb.action('onOpen')}
            isEmpty={false}
            writingToJournal={false}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="download-save">
          <StillRow
            path={Types.stringToPath('/keybase/private/foo/dir/bar')}
            type={Types.PathType.File}
            intentIfDownloading={Types.DownloadIntent.CameraRoll}
            onOpen={Sb.action('onOpen')}
            isEmpty={false}
            writingToJournal={false}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="download-share">
          <StillRow
            path={Types.stringToPath('/keybase/private/foo/dir/bar')}
            type={Types.PathType.File}
            intentIfDownloading={Types.DownloadIntent.Share}
            onOpen={Sb.action('onOpen')}
            isEmpty={false}
            writingToJournal={false}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="13">
          <PlaceholderRow type={Types.PathType.Folder} />
        </WrapRow>
        <WrapRow key="14">
          <PlaceholderRow type={Types.PathType.File} />
        </WrapRow>
        <WrapRow key="15">
          <ConnectedStillRow path={Types.stringToPath('/keybase/private/meatball/empty')} />
        </WrapRow>
        <WrapRow key="16">
          <StillRow
            path={Types.stringToPath('/keybase/private/foo/bar/baz')}
            type={Types.PathType.File}
            onOpen={Sb.action('onOpen')}
            isEmpty={false}
            writingToJournal={false}
            uploading={false}
          />
        </WrapRow>
        <WrapRow key="17">
          <TlfTypeRow path={Types.stringToPath('/keybase/private')} onOpen={Sb.action('onOpen')} />
        </WrapRow>
        <WrapRow key="18">
          <TlfTypeRow path={Types.stringToPath('/keybase/private')} onOpen={Sb.action('onOpen')} />
        </WrapRow>
        <WrapRow key="19">
          <TlfRow
            disabled={false}
            path={Types.stringToPath('/keybase/private/alice,bob,charlie')}
            isIgnored={false}
            onOpen={Sb.action('onOpen')}
            usernames={['bob', 'charlie']}
          />
        </WrapRow>
        <WrapRow key="20">
          <TlfRow
            disabled={false}
            path={Types.stringToPath('/keybase/private/alice,bob,charlie')}
            isIgnored={false}
            onOpen={Sb.action('onOpen')}
            usernames={['bob', 'charlie']}
          />
        </WrapRow>
        <WrapRow key="21">
          <TlfRow
            disabled={false}
            path={Types.stringToPath('/keybase/private/alice,bob,charlie,david,eve,felicity,george')}
            isIgnored={false}
            onOpen={Sb.action('onOpen')}
            usernames={['bob', 'charlie', 'david', 'eve', 'felicity', 'george']}
          />
        </WrapRow>
        <WrapRow key="22">
          <TlfRow
            disabled={true}
            path={Types.stringToPath('/keybase/private/alice,bob,charlie,david,eve,felicity,george')}
            isIgnored={false}
            onOpen={Sb.action('onOpen')}
            usernames={['bob', 'charlie', 'david', 'eve', 'felicity', 'george']}
          />
        </WrapRow>
      </Box>
    ))
}

export default load
*/

export default {}


text:
"use strict";

function Cone(gl , program , h_slices , v_slices)
{
    this.gl = gl;
    this.program = program;
    this.h_slices = h_slices;
    this.v_slices = v_slices;
}

Cone.prototype = new Shape();

Cone.prototype.create_shapes = function()
{
    var nodes = [];
    var horizontals = this.h_slices || 2;
    var horizontal_slice = 2 / horizontals;
    var verticals = this.v_slices || 24;
    var vertical_slice = 2 * Math.PI / verticals;

    for(var lattitude = 0; lattitude <= horizontals ; lattitude++)
    {
	var width = lattitude * horizontal_slice;
	var pos = 1 - width;
	width /= 2;
	for(var longitude = 0; longitude <= verticals ; longitude++)
	{
	    var theta = longitude * vertical_slice;
	    var x = Math.cos(theta) * width;
	    var y = pos ;
	    var z = Math.sin(theta) * width;
	    nodes.push(x);
	    nodes.push(y);
	    nodes.push(z);
	}
    }

    this.shapes.push(nodes);
    nodes = [];

    var pos = Math.PI / 2;
    var angle = (2 * Math.PI) / verticals;

    nodes.push(0.0);
    nodes.push(-1.0);
    nodes.push(0.0);

    for(var i = 0 ; i < (verticals * 3) ; i+=3)
    {
	nodes.push(Math.cos(pos));
	nodes.push(-1.0);
	nodes.push(Math.sin(pos));
	pos -= angle;
    }

    nodes.push(Math.cos(pos));
    nodes.push(-1.0);
    nodes.push(Math.sin(pos));

    this.shapes.push(nodes);
}

Cone.prototype.create_indices = function()
{
    var indices = [];
    var horizontals = this.h_slices || 2;
    var verticals = this.v_slices || 24;
    for(var lattitude = 0; lattitude < horizontals ; lattitude++)
    {
	for(var longitude = 0; longitude < verticals ; longitude++)
	{
	    var first = (lattitude * (verticals + 1)) + longitude;
	    var second = first + verticals + 1;
	    indices.push(first);
	    indices.push(second);
	    indices.push(first + 1);
	    indices.push(second);
	    indices.push(second + 1);
	    indices.push(first + 1);
	}
    }
    this.shape_indices.push(indices);

    indices = [];
    for(var i = 0 ; i < verticals ; i++)
    {
	indices.push(0);
	indices.push(i + 1);
	indices.push(i + 2);
    }
    this.shape_indices.push(indices);
}

Cone.prototype.name = function()
{
    return "Cone";
}


text:
abcpettraining
==============


text:
namespace DeJong.Networking.Core.Channels
{
    using Messages;
    using Receiver;
    using Sender;
    using System.Net;
    using Utilities.Core;
    using Utilities.Logging;

#if !DEBUG
    [System.Diagnostics.DebuggerStepThrough]
#endif
    internal sealed class ReceiverController
    {
        public int Size { get; private set; }

        private IPEndPoint remote;
        private EndPoint ep;
        private ReceiverChannelBase[] channels;
        private SenderController sendController;
        private ReadableBuffer readHelper;
        private PeerConfig config;
        private RawSocket socket;

        public ReceiverChannelBase this[int index]
        {
            get
            {
                LoggedException.RaiseIf(index >= Size || index < 0, nameof(ReceiverController), "index ot of range");
                return channels[index];
            }
        }

        public ReceiverController(RawSocket socket, IPEndPoint ep, PeerConfig config, SenderController sender)
        {
            remote = ep;
            this.ep = remote;
            this.config = config;
            this.socket = socket;
            channels = new ReceiverChannelBase[15];
            sendController = sender;
            readHelper = new ReadableBuffer(socket.ReceiveBuffer);

            channels[Size++] = new LibReceiverChannel(socket, ep, config) { ID = 0 };
        }

        public void AddUnreliable(int id)
        {
            CheckNewChannel(id);
            channels[Size++] = new UnreliableReceiverChannel(socket, remote, config) { ID = id };
        }

        public void AddOrdered(int id, OrderChannelBehaviour behaviour)
        {
            CheckNewChannel(id);
            channels[Size++] = new OrderedReceiverChannel(socket, remote, config, behaviour) { ID = id };
        }

        public void AddReliable(int id)
        {
            CheckNewChannel(id);
            channels[Size++] = new ReliableReceiverChannel(socket, remote, config, sendController.LibSender) { ID = id };
        }

        public void AddReliableOrdered(int id, OrderChannelBehaviour behaviour)
        {
            CheckNewChannel(id);
            channels[Size++] = new ReliableOrderedReceiverChannel(socket, remote, config, sendController.LibSender, behaviour) { ID = id };
        }

        public void Heartbeat()
        {
            for (int i = 0; i < Size; i++)
            {
                channels[i].Heartbeat();
            }
        }

        public void ReceivedPacket(RawSocket sender, PacketReceiveEventArgs e)
        {
            readHelper.PositionBits = 0;
            LibHeader header = new LibHeader(readHelper);
            IncommingMsg msg = this[header.Channel].CreateMessage(header);

            for (int i = 0; i < Size; i++)
            {
                ReceiverChannelBase cur = channels[i];

                if (cur.ID == msg.Header.Channel)
                {
                    cur.EnqueueMessage(msg);
                    return;
                }
            }

            Log.Warning(nameof(ReceiverController), $"Message received on unknown channel({msg.Header.Channel}), message dropped");
        }

        public override string ToString()
        {
            return $"Receiver controller with {Size} channels";
        }

        private void CheckNewChannel(int id)
        {
            LoggedException.RaiseIf(id <= 0 || id > 14, nameof(ReceiverController), "Id must be between zero and 15");
            LoggedException.RaiseIf(Size > 15, nameof(ReceiverController), "Maximum of 15 channels reached");
        }
    }
}


text:
#ifndef _Pineapple_Camera_Orthographic
#define _Pineapple_Camera_Orthographic

#include "Pineapple/Camera.hpp"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

class OrthographicCamera: public Camera {
    public:
        /**
         * Initialize a  new orthogrpahic camera.
         */
        OrthographicCamera(float left = -1.f, float right = 1.f, float top = 1.f, float bottom = -1.f);

        /**
         * Initialize a new orthographic camera.
         */
        OrthographicCamera(int width = 320, int height = 320, float near = 0.1f, float far = 0.1f, float left = -1.f,
                float right = 1.f, float top = 1.f, float bottom = -1.f);

        /** Orthographic view bounds */
        glm::vec4 bounds;

        /**
         * Compute the orthographic projection matrix to transform into normalized space.
         *
         * @return     4x4 projection matrix
         */
        glm::mat4 computeProjectionMatrix();

        /**
         * Compute a ray in the direction of projection based on normalized screen coordinates.
         *
         * @param nx    Normalized x coordinate
         * @param ny    Normalized y coordinate
         */
        Ray getRay(float, float);
};

#endif


text:
'use strict'

// this is dinner
app.directive('four', function(){

	return {
		restrict: 'E',
		templateUrl: 'js/directives/four/four.html'

	}
})


text:
API
===

.. module:: gsignals

.. autoclass:: Signal
   :members:

.. autoclass:: SignalManager
   :members:


text:
.class Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;
.super Landroid/os/AsyncTask;
.source "AlwaysOnHotwordDetector.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/service/voice/AlwaysOnHotwordDetector;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "RefreshAvailabiltyTask"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/os/AsyncTask",
        "<",
        "Ljava/lang/Void;",
        "Ljava/lang/Void;",
        "Ljava/lang/Void;",
        ">;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

# direct methods
.method constructor <init>(Landroid/service/voice/AlwaysOnHotwordDetector;)V
    .registers 2
    .param p1, "this$0"    # Landroid/service/voice/AlwaysOnHotwordDetector;

    .prologue
    .line 682
    iput-object p1, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-direct {p0}, Landroid/os/AsyncTask;-><init>()V

    return-void
.end method

.method private internalGetInitialAvailability()I
    .registers 6

    .prologue
    const/4 v4, -0x3

    .line 715
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get4(Landroid/service/voice/AlwaysOnHotwordDetector;)Ljava/lang/Object;

    move-result-object v3

    monitor-enter v3

    .line 717
    :try_start_8
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get0(Landroid/service/voice/AlwaysOnHotwordDetector;)I
    :try_end_d
    .catchall {:try_start_8 .. :try_end_d} :catchall_28

    move-result v2

    if-ne v2, v4, :cond_12

    monitor-exit v3

    .line 718
    return v4

    :cond_12
    monitor-exit v3

    .line 722
    const/4 v0, 0x0

    .line 725
    .local v0, "dspModuleProperties":Landroid/hardware/soundtrigger/SoundTrigger$ModuleProperties;
    :try_start_14
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get5(Landroid/service/voice/AlwaysOnHotwordDetector;)Lcom/android/internal/app/IVoiceInteractionManagerService;

    move-result-object v2

    iget-object v3, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v3}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get6(Landroid/service/voice/AlwaysOnHotwordDetector;)Landroid/service/voice/IVoiceInteractionService;

    move-result-object v3

    invoke-interface {v2, v3}, Lcom/android/internal/app/IVoiceInteractionManagerService;->getDspModuleProperties(Landroid/service/voice/IVoiceInteractionService;)Landroid/hardware/soundtrigger/SoundTrigger$ModuleProperties;
    :try_end_23
    .catch Landroid/os/RemoteException; {:try_start_14 .. :try_end_23} :catch_2b

    move-result-object v0

    .line 730
    .end local v0    # "dspModuleProperties":Landroid/hardware/soundtrigger/SoundTrigger$ModuleProperties;
    :goto_24
    if-nez v0, :cond_36

    .line 731
    const/4 v2, -0x2

    return v2

    .line 715
    :catchall_28
    move-exception v2

    monitor-exit v3

    throw v2

    .line 726
    .restart local v0    # "dspModuleProperties":Landroid/hardware/soundtrigger/SoundTrigger$ModuleProperties;
    :catch_2b
    move-exception v1

    .line 727
    .local v1, "e":Landroid/os/RemoteException;
    const-string/jumbo v2, "AlwaysOnHotwordDetector"

    const-string/jumbo v3, "RemoteException in getDspProperties!"

    invoke-static {v2, v3, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_24

    .line 734
    .end local v0    # "dspModuleProperties":Landroid/hardware/soundtrigger/SoundTrigger$ModuleProperties;
    .end local v1    # "e":Landroid/os/RemoteException;
    :cond_36
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get2(Landroid/service/voice/AlwaysOnHotwordDetector;)Landroid/hardware/soundtrigger/KeyphraseMetadata;

    move-result-object v2

    if-nez v2, :cond_40

    .line 735
    const/4 v2, -0x1

    return v2

    .line 737
    :cond_40
    const/4 v2, 0x0

    return v2
.end method

.method private internalGetIsEnrolled(ILjava/util/Locale;)Z
    .registers 7
    .param p1, "keyphraseId"    # I
    .param p2, "locale"    # Ljava/util/Locale;

    .prologue
    .line 745
    :try_start_0
    iget-object v1, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v1}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get5(Landroid/service/voice/AlwaysOnHotwordDetector;)Lcom/android/internal/app/IVoiceInteractionManagerService;

    move-result-object v1

    .line 746
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get6(Landroid/service/voice/AlwaysOnHotwordDetector;)Landroid/service/voice/IVoiceInteractionService;

    move-result-object v2

    invoke-virtual {p2}, Ljava/util/Locale;->toLanguageTag()Ljava/lang/String;

    move-result-object v3

    .line 745
    invoke-interface {v1, v2, p1, v3}, Lcom/android/internal/app/IVoiceInteractionManagerService;->isEnrolledForKeyphrase(Landroid/service/voice/IVoiceInteractionService;ILjava/lang/String;)Z
    :try_end_13
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_13} :catch_15

    move-result v1

    return v1

    .line 747
    :catch_15
    move-exception v0

    .line 748
    .local v0, "e":Landroid/os/RemoteException;
    const-string/jumbo v1, "AlwaysOnHotwordDetector"

    const-string/jumbo v2, "RemoteException in listRegisteredKeyphraseSoundModels!"

    invoke-static {v1, v2, v0}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 750
    const/4 v1, 0x0

    return v1
.end method

# virtual methods
.method public bridge synthetic doInBackground([Ljava/lang/Object;)Ljava/lang/Object;
    .registers 3
    .param p1, "params"    # [Ljava/lang/Object;

    .prologue
    .line 685
    check-cast p1, [Ljava/lang/Void;

    .end local p1    # "params":[Ljava/lang/Object;
    invoke-virtual {p0, p1}, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->doInBackground([Ljava/lang/Void;)Ljava/lang/Void;

    move-result-object v0

    return-object v0
.end method

.method public varargs doInBackground([Ljava/lang/Void;)Ljava/lang/Void;
    .registers 6
    .param p1, "params"    # [Ljava/lang/Void;

    .prologue
    .line 686
    invoke-direct {p0}, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->internalGetInitialAvailability()I

    move-result v0

    .line 687
    .local v0, "availability":I
    const/4 v1, 0x0

    .line 689
    .local v1, "enrolled":Z
    if-eqz v0, :cond_a

    .line 690
    const/4 v2, 0x1

    if-ne v0, v2, :cond_33

    .line 692
    :cond_a
    :goto_a
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get2(Landroid/service/voice/AlwaysOnHotwordDetector;)Landroid/hardware/soundtrigger/KeyphraseMetadata;

    move-result-object v2

    iget v2, v2, Landroid/hardware/soundtrigger/KeyphraseMetadata;->id:I

    iget-object v3, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v3}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get3(Landroid/service/voice/AlwaysOnHotwordDetector;)Ljava/util/Locale;

    move-result-object v3

    invoke-direct {p0, v2, v3}, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->internalGetIsEnrolled(ILjava/util/Locale;)Z

    move-result v1

    .line 693
    .local v1, "enrolled":Z
    if-nez v1, :cond_37

    .line 694
    const/4 v0, 0x1

    .line 700
    .end local v1    # "enrolled":Z
    :cond_1f
    :goto_1f
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-get4(Landroid/service/voice/AlwaysOnHotwordDetector;)Ljava/lang/Object;

    move-result-object v3

    monitor-enter v3

    .line 705
    :try_start_26
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2, v0}, Landroid/service/voice/AlwaysOnHotwordDetector;->-set0(Landroid/service/voice/AlwaysOnHotwordDetector;I)I

    .line 706
    iget-object v2, p0, Landroid/service/voice/AlwaysOnHotwordDetector$RefreshAvailabiltyTask;->this$0:Landroid/service/voice/AlwaysOnHotwordDetector;

    invoke-static {v2}, Landroid/service/voice/AlwaysOnHotwordDetector;->-wrap0(Landroid/service/voice/AlwaysOnHotwordDetector;)V
    :try_end_30
    .catchall {:try_start_26 .. :try_end_30} :catchall_39

    monitor-exit v3

    .line 708
    const/4 v2, 0x0

    return-object v2

    .line 691
    .local v1, "enrolled":Z
    :cond_33
    const/4 v2, 0x2

    if-ne v0, v2, :cond_1f

    goto :goto_a

    .line 696
    .local v1, "enrolled":Z
    :cond_37
    const/4 v0, 0x2

    goto :goto_1f

    .line 700
    .end local v1    # "enrolled":Z
    :catchall_39
    move-exception v2

    monitor-exit v3

    throw v2
.end method


text:
.. image:: http://vmlaker.github.io/mpipe/_static/logo.png
  :alt: MPipe Logo
  :align: right
  :target: http://vmlaker.github.io/mpipe

.. image:: https://travis-ci.org/vmlaker/mpipe.png?branch=master
  :alt: Build Result Image
  :target: https://travis-ci.org/vmlaker/mpipe

A tiny Python module that lets you
easily write multi-stage, multiprocess pipeline algorithms.
For the full description, including user guide and examples,
visit `the documentation page <http://vmlaker.github.io/mpipe>`_.


text:
<?php

/**
 * Exception thrown when a field name is used that has not been defined
 * through the document definition.
 *
 * @package Search
 * @version //autogentag//
 */
class ezcSearchFieldNotDefinedException extends ezcSearchException
{
    /**
     * Constructs an ezcSearchFieldNotDefinedException for document type $type
     * and field $field.
     *
     * @param string $type
     * @param string $field
     */
    public function __construct( $type, $field )
    {
        $message = "The document type '$type' does not define the field '$field'.";
        parent::__construct( $message );
    }
}
?>


text:
var EventEmitter = require('./events');
var util = require('util');

module.exports = function() {
  var RealServicePrototype = function() {
    EventEmitter.call(this);
  };
  util.inherits(RealServicePrototype, EventEmitter);

  RealServicePrototype.prototype.loadBundle = function() {
  };

  RealServicePrototype.prototype.runRemoteCommand = function() {
    return 'the id';
  };

  var realService = new RealServicePrototype();

  var Statwolf = function() {};

  var setter = function(currentKey) {
    Statwolf.prototype[currentKey] = function() {
      return realService[currentKey].apply(realService, arguments);
    };
  };
  for(var key in realService) {
    setter(key);
  }

  Statwolf.getRealService = function() {
    return realService;
  };

  return Statwolf;
};


text:
class CJS_EventContext;

#define IDS_STRING_JSALERT 25613
#define IDS_STRING_JSPARAMERROR 25614
#define IDS_STRING_JSAFNUMBER_KEYSTROKE 25615
#define IDS_STRING_JSPARAM_TOOLONG 25617
#define IDS_STRING_JSPARSEDATE 25618
#define IDS_STRING_JSRANGE1 25619
#define IDS_STRING_JSRANGE2 25620
#define IDS_STRING_JSRANGE3 25621
#define IDS_STRING_JSNOTSUPPORT 25627
#define IDS_STRING_JSBUSY 25628
#define IDS_STRING_JSEVENT 25629
#define IDS_STRING_RUN 25630
#define IDS_STRING_JSPRINT1 25632
#define IDS_STRING_JSPRINT2 25633
#define IDS_STRING_JSNOGLOBAL 25635
#define IDS_STRING_JSREADONLY 25636
#define IDS_STRING_JSTYPEERROR 25637
#define IDS_STRING_JSVALUEERROR 25638
#define IDS_STRING_JSNOPERMISSION 25639
#define IDS_STRING_JSBADOBJECT 25640

CFX_WideString JSGetStringFromID(uint32_t id);
CFX_WideString JSFormatErrorString(const char* class_name,
                                   const char* property_name,
                                   const CFX_WideString& details);

#endif  // FPDFSDK_JAVASCRIPT_RESOURCE_H_


text:
/**
* Course.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {
  attributes: {
    // Primitives
    id: {
   type: 'integer',
   autoIncrement: true,
   primaryKey: true,
   unique: true
    },
    title: { // 'CSCI 201'
      type: 'string'
    },
    professor: {
      model: 'professor'
    },
    term: {
      model: 'term'
    },
    // Associations
    quizzes: {
      collection: 'quiz',
      via: 'course'
    },
    sections: {
      collection: 'section',
      via: 'course'
    },

    // Methods
  }
};


text:
package org.apache.hyracks.api.result;

import java.io.Serializable;

public class ResultSetId implements Serializable {
    private static final long serialVersionUID = 1L;

    private final long id;

    public ResultSetId(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    @Override
    public int hashCode() {
        return (int) id;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof ResultSetId)) {
            return false;
        }
        return ((ResultSetId) o).id == id;
    }

    @Override
    public String toString() {
        return "RSID:" + id;
    }
}


text:
/** FRONTOFFICE GENERIC VIEW ***************************************************************************************************************************/
body                    { background-color: #202020;  }
html, body              { overflow: hidden; } /* remove page scrollbar */

/** HEADER MENU BAR ************************************************************************************************************************************/
/* picture container */
#pic_container          { margin: 0; padding: 0; margin-left: 2px;}

*                       { margin: 0; padding: 0; }
div.headerbar           { width: 100%; height: 26px; margin: 0; z-index: 99; position: relative; background-color: #202020;}  /* menu background color*/

ul.navbar li            { list-style: none; text-align: center; }
ul.navbar ul            { display: none; }
ul.navbar a             { font-family: Arial; -webkit-font-stretch: normal; -moz-font-stretch: normal; -ms-font-stretch: normal; -o-font-stretch: normal; font-stretch: normal; }

ul.navbar               { position: relative; }

/* MENU LEVEL 0 */
ul.navbar > li 	        { height: auto; float: left; padding-right: 20px; padding-left: 10px; }
ul.navbar li > a        { color: darkgray; font-weight: bold; font-size: 11px; padding-top: 6px;  padding-bottom: 6px; text-decoration: none;  display: block; }
ul.navbar li:hover      { position: relative; }
ul.navbar li a:hover    { color: white; font-weight: bold; }

/* MENU LEVEL 1 */
ul.navbar ul            { display: none; top: 100%; left: 0; position: absolute; }
ul.navbar li:hover > ul { display: block; }
ul.navbar ul li         { width:180px; background-color: #D0D0D0; /* sub-menu background color*/
                            opacity:0.96;
                            filter:alpha(opacity=90); /* For IE8 and earlier */
                        }

ul.navbar ul li a       { color: black; font-size:10px; display: inline-block; width:180px; }
ul.navbar ul li a:hover { color: black; font-weight: bold; background-color: #F8F8F8; border: 1px solid black;
                            -webkit-transition: background-color 400ms;
                            -moz-transition: background-color 400ms;
                            -ms-transition: background-color 400ms;
                            -o-transition: background-color 400ms;
                            transition: background-color 400ms;
                        }

/* MENU LEVEL 2 */
ul.navbar ul ul         { left: 100%; top: 0; }
/*******************************************************************************************************************************************************/

/** LOGIN BOX ******************************************************************************************************************************************/
div.loginbox {
    text-align:right; padding: 2px; position: relative; float:right; width: 250px; background-color: #202020; -ms-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }

/* menu background color*/

div.loginbox span           { font-family: Arial; font-size:11px; color:white; }
div.loginbox > span         { color:darkgray; font-weight:bold; border-left: 1px solid gray; padding-left: 4px; padding-right: 4px; }
div.loginbox > span:hover   { color: white; }
div.loginbox div            { display:none; float: right; position:relative; }

input.spanbutton            { color:darkgray; font:bold 11px Arial; border: 0; padding-left: 4px; padding-right: 4px; background-color: transparent;}
input.spanbutton:hover      { color: white; }

input.logintextbox          { width:90px; font: normal 10px Arial; border: 1px solid black; background-color: white; color: black; -ms-border-radius:4px; border-radius:4px; }

input.loginbutton           { width: 35px; font: normal 10px Arial; border: 1px solid white; background-color: #202020; color: white; -ms-border-radius:4px; border-radius:4px; margin-left: 4px; }

/** PAGE FRAME ******************************************************************************************************************************************/
iframe                      { width: 100%; border: 0; }


text:
Simple plugin for Sublime Text to show the number of open files in the status bar.

## Installation

You may either install using Package Control (which gains you automatic updates and a simpler install), or manually using `git`.

### Package Control (Recommended)

1. Install [Sublime Package Control](http://wbond.net/sublime_packages/package_control/installation).
2. Run `Package Control: Install Package` from the Command Palette
3. Find and install the `Show Open Files` plugin

### Manual

1. CD into your Sublime Text Packages directory;
	* Windows: `%APPDATA%\Sublime Text 3\Packages\`
	* OS X: `~/Library/Application Support/Sublime Text 3/Packages/`
	* Linux: `~/.config/sublime-text-3/Packages/`
	* Portable Installation: `Sublime Text 3/Data/Packages/`
2. `git clone https://github.com/grapegravity/ShowOpenFiles.git`

_**Note**: For Sublime Text 2 users, substitute the `3` in the above directory names with `2`._

## Usage

The number of files open in the current window will be displayed in the status bar. This is updated whenever a view is opened or closed. There are no settings to configure.


text:
const {Keymap, Plugin} = require("../edit")

// ;; Input rules are regular expressions describing a piece of text
// that, when typed, causes something to happen. This might be
// changing two dashes into an emdash, wrapping a paragraph starting
// with `"> "` into a blockquote, or something entirely different.
class InputRule {
  // :: (RegExp, ?string, union<string, (pm: ProseMirror, match: [string], pos: number)>)
  // Create an input rule. The rule applies when the user typed
  // something and the text directly in front of the cursor matches
  // `match`, which should probably end with `$`. You can optionally
  // provide a filter, which should be a single character that always
  // appears at the end of the match, and will be used to only apply
  // the rule when there's an actual chance of it succeeding.
  //
  // The `handler` can be a string, in which case the matched text
  // will simply be replaced by that string, or a function, which will
  // be called with the match array produced by
  // [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  // and should produce the effect of the rule.
  constructor(match, filter, handler) {
    this.filter = filter
    this.match = match
    this.handler = handler
  }
}
exports.InputRule = InputRule

// ;; Manages the set of active input rules for an editor. Created
// with the `inputRules` plugin.
class InputRules {
  constructor(pm, options) {
    this.pm = pm
    this.rules = []
    this.cancelVersion = null

    pm.on.selectionChange.add(this.onSelChange = () => this.cancelVersion = null)
    pm.on.textInput.add(this.onTextInput = this.onTextInput.bind(this))
    pm.addKeymap(new Keymap({Backspace: pm => this.backspace(pm)}, {name: "inputRules"}), 20)

    options.rules.forEach(rule => this.addRule(rule))
  }

  detach() {
    this.pm.on.selectionChange.remove(this.onSelChange)
    this.pm.on.textInput.remove(this.onTextInput)
    this.pm.removeKeymap("inputRules")
  }

  // :: (InputRule)
  // Add the given input rule to the editor.
  addRule(rule) {
    this.rules.push(rule)
  }

  // :: (InputRule) → bool
  // Remove the given input rule from the editor. Returns false if the
  // rule wasn't found.
  removeRule(rule) {
    let found = this.rules.indexOf(rule)
    if (found > -1) {
      this.rules.splice(found, 1)
      return true
    }
    return false
  }

  onTextInput(text) {
    let $pos = this.pm.selection.$head
    if (!$pos) return

    let textBefore, isCode
    let lastCh = text[text.length - 1]

    for (let i = 0; i < this.rules.length; i++) {
      let rule = this.rules[i], match
      if (rule.filter && rule.filter != lastCh) continue
      if (textBefore == null) {
        ;({textBefore, isCode} = getContext($pos))
        if (isCode) return
      }
      if (match = rule.match.exec(textBefore)) {
        let startVersion = this.pm.history && this.pm.history.getVersion()
        if (typeof rule.handler == "string") {
          let start = $pos.pos - (match[1] || match[0]).length
          let marks = this.pm.doc.marksAt($pos.pos)
          this.pm.tr.delete(start, $pos.pos)
                    .insert(start, this.pm.schema.text(rule.handler, marks))
                    .apply()
        } else {
          rule.handler(this.pm, match, $pos.pos)
        }
        this.cancelVersion = startVersion
        return
      }
    }
  }

  backspace() {
    if (this.cancelVersion && this.pm.history) {
      this.pm.history.backToVersion(this.cancelVersion)
      this.cancelVersion = null
    } else {
      return false
    }
  }
}

function getContext($pos) {
  let parent = $pos.parent, isCode = parent.type.isCode
  let textBefore = ""
  for (let i = 0, rem = $pos.parentOffset; rem > 0; i++) {
    let child = parent.child(i)
    if (child.isText) textBefore += child.text.slice(0, rem)
    else textBefore += "\ufffc"
    rem -= child.nodeSize
    if (rem <= 0 && child.marks.some(st => st.type.isCode)) isCode = true
  }
  return {textBefore, isCode}
}

// :: Plugin
// A plugin for adding input rules to an editor. A common pattern of
// use is to call `inputRules.ensure(editor).addRule(...)` to get an
// instance of the plugin state and add a rule to it.
//
// Takes a single option, `rules`, which may be an array of
// `InputRules` objects to initially add.
const inputRules = new Plugin(InputRules, {
  rules: []
})
exports.inputRules = inputRules


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />
<title></title>

Revamp of Automatic VirtualBox Testing

Introduction

This is the design document for a revamped automatic testing framework.
The revamp aims at replacing the current tinderbox based testing by a new
system that is written from scratch.

The old system is not easy to work with and was never meant to be used for
managing tests, after all it just a simple a build manager tailored for
contiguous building.  Modifying the existing tinderbox system to do what
we want would require fundamental changes that would render it useless as
a build manager, it would therefore end up as a fork.  The amount of work
required would probably be about the same as writing a new system from
scratch.  Other considerations, such as the license of the tinderbox
system (MPL) and language it is realized in (Perl), are also in favor of
doing it from scratch.

The language envisioned for the new automatic testing framework is Python.  This
is for several reasons:

The VirtualBox API has Python bindings.

Python is used quite a bit inside Sun (dunno about Oracle).

Works relatively well with Apache for the server side bits.

It is more difficult to produce write-only code in Python (alias the
we-don't-like-perl argument).

You don't need to compile stuff.

Note that the author of this document has no special training as a test
engineer and may therefore be using the wrong terms here and there.  The
primary focus is to express what we need to do in order to improve
testing.

This document is written in reStructuredText (rst) which just happens to
be used by Python, the primary language for this revamp.  For more
information on reStructuredText: http://docutils.sourceforge.net/rst.html

Definitions / Glossary

sub-test driver

A set of test cases that can be used by more than one test driver.  Could
also be called a test unit, in the pascal sense of unit, if it wasn't so
easily confused with 'unit test'.

test

This is somewhat ambiguous and this document try avoid using it where
possible.  When used it normally refers to doing testing by executing one or
more testcases.

test case

A set of inputs, test programs and expected results. It validates system
requirements and generates a pass or failed status.  A basic unit of testing.
Note that we use the term in a rather broad sense.

test driver

A program/script used to execute a test.  Also known as a test harness.
Generally abbreviated 'td'.  It can have sub-test drivers.

test manager

Software managing the automatic testing.  This is a web application that runs
on a dedicated server (tindertux).

test set

The output of testing activity.  Logs, results, ++.  Our usage of this should
probably be renamed to 'test run'.

test group

A collection of related test cases.

testbox

A computer that does testing.

testbox script

Script executing orders from the test manager on a testbox.  Started
automatically upon bootup.

testing

todo

TODO: Check that we've got all this right and make them more exact

where possible.

See also http://encyclopedia2.thefreedictionary.com/testing%20types
and http://www.aptest.com/glossary.html .

Objectives

A scalable test manager (>200 testboxes).

Optimize the web user interface (WUI) for typical workflows and analysis.

Efficient and flexibile test configuration.

Import test result from other test systems (logo testing, VDI, ++).

Easy to add lots of new testscripts.

Run tests locally without a manager.

Revamp a bit at the time.

The Testbox Side

Each testbox has a unique name corresponding to its DNS zone entry.  When booted
a testbox script is started automatically.  This script will query the test
manager for orders and execute them.  The core order downloads and executes a
test driver with parameters (configuration) from the server.  The test driver
does all the necessary work for executing the test.  In a typical VirtualBox
test this means picking a build, installing it, configuring VMs, running the
test VMs, collecting the results, submitting them to the server, and finally
cleaning up afterwards.

The testbox environment which the test drivers are executed in will have a
number of environment variables for determining location of the source images
and other test data, scratch space, test set id, server URL, and so on and so
forth.

On startup, the testbox script will look for crash dumps and similar on
systems where this is possible.  If any sign of a crash is found, it will
put any dumps and reports in the upload directory and inform the test
manager before reporting for duty.  In order to generate the proper file
names and report the crash in the right test set as well as prevent
reporting crashes unrelated to automatic testing, the testbox script will
keep information (test set id, ++) in a separate scratch directory
(${TESTBOX_PATH_SCRATCH}/../testbox) and make sure it is synced to the
disk (both files and directories).

After checking for crashes, the testbox script will clean up any previous test
which might be around.  This involves first invoking the test script in cleanup
mode and the wiping the scratch space.

When reporting for duty the script will submit information about the host: OS
name, OS version, OS bitness, CPU vendor, total number of cores, VT-x support,
AMD-V support, amount of memory, amount of scratch space, and anything else that
can be found useful for scheduling tests or filtering test configurations.

Testbox Script Orders

The orders are kept in a queue on the server and the testbox script will fetch
them one by one.  Orders that cannot be executed at the moment will be masked in
the query from the testbox.

Execute Test Driver

Downloads and executes the a specified test driver with the given
configuration (arguments).  Only one test driver can be executed at a time.
The server can specify more than one ZIP file to be downloaded and unpacked
before executing the test driver.  The testbox script may cache these zip
files using http time stamping.

Abort Test Driver

Aborts the current test driver.  This will drop a hint to the driver and give
it 60 seconds to shut down the normal way.  If that fails, the testbox script
will kill the driver processes (SIGKILL or equivalent), invoke the
testdriver in cleanup mode, and finally wipe the scratch area.  Should either
of the last two steps fail in some way, the testbox will be rebooted.

Idle

Ask again in X seconds, where X is specified by the server.

Reboot

Reboot the testbox.  If a test driver is current running, an attempt at
aborting it (Abort Test Driver) will be made first.

Update

Updates the testbox script.  The order includes a server relative path to the
new testbox script.  This can only be executed when no test driver is
currently being executed.

Testbox Environment: Variables

COMSPEC

This will be set to C:WindowsSystem32cmd.exe on Windows.

PATH

This will contain the kBuild binary directory for the host platform.

SHELL

This will be set to point to kmk_ash(.exe) on all platforms.

TESTBOX_NAME

The testbox name.
This is not required by the local reporter.

TESTBOX_PATH_BUILDS

The absolute path to where the build repository can be found.  This should be
a read only mount when possible.

TESTBOX_PATH_RESOURCES

The absolute path to where static test resources like ISOs and VDIs can be
found.  The test drivers knows the layout of this.  This should be a read only
mount when possible.

TESTBOX_PATH_SCRATCH

The absolute path to the scratch space.  This is the current directory when
starting the test driver.  It will be wiped automatically after executing the
test.
(Envisioned as ${TESTBOX_PATH_SCRIPTS}/../scratch and that
${TESTBOX_PATH_SCRATCH}/ will be automatically wiped by the testbox script.)

TESTBOX_PATH_SCRIPTS

The absolute path to the test driver and the other files that was unzipped
together with it.  This is also where the test-driver-abort file will be put.
(Envisioned as ${TESTBOX_PATH_SCRATCH}/../driver, see above.)

TESTBOX_PATH_UPLOAD

The absolute path to the upload directory for the testbox.  This is for
putting VOBs, PNGs, core dumps, crash dumps, and such on.  The files should be
bzipped or zipped if they aren't compress already.  The names should contain
the testbox and test set ID.

TESTBOX_REPORTER

The name of the test reporter back end.  If not present, it will default to
the local reporter.

TESTBOX_TEST_SET_ID

The test set ID if we're running.
This is not required by the local reporter.

TESTBOX_MANAGER_URL

The URL to the test manager.
This is not required by the local reporter.

TESTBOX_XYZ

There will probably be some more of these.

Testbox Environment: Core Utilities

The testbox will not provide the typical unix /bin and /usr/bin utilities.  In
other words, cygwin will not be used on Windows!

The testbox will provide the unixy utilties that ships with kBuild and possibly
some additional ones from tools/./bin in the VirtualBox tree (wget, unzip,
zip, and so on).  The test drivers will avoid invoking any of these utilites
directly and instead rely on generic utility methods in the test driver
framework.  That way we can more easily reimplement the functionality of the
core utilites and drop the dependency on them.  It also allows us to quickly
work around platform specific oddities and bugs.

Test Drivers

The test drivers are programs that will do the actual testing.  In addition to
run under the testbox script, they can be executed in the VirtualBox development
environment.  This is important for bug analysis and for simplifying local
testing by the developers before commiting changes.  It also means the test
drivers can be developed locally in the VirtualBox development environment.

The main difference between executing a driver under the testbox script and
running it manually is that there is no test manager in the latter case.  The
test result reporter will not talk to the server, but report things to a local
log file and/or standard out/err.  When invoked manually, all the necessary
arguments will need to be specified by hand of course - it should be possible
to extract them from a test set as well.

For the early implementation stages, an implementation of the reporter interface
that talks to the tinderbox base test manager will be needed.  This will be
dropped later on when a new test manager is ready.

As hinted at in other sections, there will be a common framework
(libraries/packages/classes) for taking care of the tedious bits that every
test driver needs to do.  Sharing code is essential to easing test driver
development as well as reducing their complexity.  The framework will contain:

A generic way of submitting output.  This will be a generic interface with
multiple implementation, the TESTBOX_REPORTER environment variable
will decide which of them to use.  The interface will have very specific
methods to allow the reporter to do a best possible job in reporting the
results to the test manager.

Helpers for typical tasks, like:

Copying files.

Deleting files, directory trees and scratch space.

Unzipping files.

Creating ISOs

And such things.

Helpers for installing and uninstalling VirtualBox.

Helpers for defining VMs. (The VBox API where available.)

Helpers for controlling VMs. (The VBox API where available.)

The VirtualBox bits will be separate from the more generic ones, simply because
this is cleaner it will allow us to reuse the system for testing other products.

The framework will be packaged in a zip file other than the test driver so we
don't waste time and space downloading the same common code.

The test driver will poll for the file
${TESTBOX_PATH_SCRIPTS}/test-driver-abort and abort all testing when it sees it.

The test driver can be invoked in three modes: execute, help and cleanup.  The
default is execute mode, the help shows an configuration summary and the cleanup
is for cleaning up after a reboot or aborted run.  The latter is done by the
testbox script on startup and after abort - the driver is expected to clean up
by itself after a normal run.

The Server Side

The server side will be implemented using a webserver (apache), a database
(postgres) and cgi scripts (Python).  In addition a cron job (Python) running
once a minute will generate static html for frequently used pages and maybe
execute some other tasks for driving the testing forwards.  The order queries
from the testbox script is the primary driving force in the system.  The total
makes up the test manager.

The test manager can be split up into three rough parts:

Configuration (of tests, testgroups and testboxes).

Execution     (of tests, collecting and organizing the output).

Analysis      (of test output, mostly about presentation).

Test Manager: Requirements

List of requirements:

Two level testing - L1 quick smoke tests and L2 longer tests performed on
builds passing L1.  (Klaus (IIRC) ment this could be realized using
test dependency.)

Black listing builds (by revision or similar) known to be bad.

Distinguish between build types so we can do a portion of the testing with
strict builds.

Easy to re-configure build source for testing different branch or for
testing a release candidate. (Directory based is fine.)

Useful to be able to partition testboxes (run specific builds on some
boxes, let an engineer have a few boxes for a while).

Interation with ILOM/...: reset systems.

Be able to suspend testing on selected testboxes when doing maintance
(where automatically resuming testing on reboot is undesired) or similar
activity.

Abort testing on seleced testboxes.

Scheduling of tests requiring more than one testbox.

Scheduling of tests that cannot be executing concurrently on several
machines because of some global resource like an iSCSI target.

Jump the scheduling queue.  Scheduling of specified test the next time a
testbox is available (optionally specifying which testbox to schedule it
on).

Configure tests with variable configuration to get better coverage. Two modes:

TM generates the permutations based on one or more sets of test script arguments.

Each configuration permuation is specified manually.

Test specification needs to be flexible (select tests, disable test, test
scheduling (run certain tests nightly), ... ).

Test scheduling by hour+weekday and by priority.

Test dependencies (test A depends on test B being successful).

Historize all configuration data, in particular test configs (permutations
included) and testboxes.

Test sets has at a minimum a build reference, a testbox reference and a
primary log associated with it.

Test sets stores further result as a recursive collection of:

hierachical subtest name (slash sep)

test parameters / config

bool fail/succ

attributes (typed?)

test time

e.g. throughput

subresults

log

screenshots, video,...

The test sets database structure needs to designed such that data mining
can be done in an efficient manner.

Presentation/analysis: graphs!, categorize bugs, columns reorganizing
grouped by test (hierarchical), overviews, result for last day.

Test Manager: Configuration

Testboxes

Configuration of testboxes doesn't involve much work normally.  A testbox
is added manually to the test manager by entering the DNS entry and/or IP
address (the test manager resolves the missing one when necessary) as well as
the system UUID (when obtainable - should be displayed by the testbox script
installer).  Queries from unregistered testboxes will be declined as a kind of
security measure, the incident should be logged in the webserver log if
possible.   In later dealings with the client the System UUID will be the key
identifier.  It's permittable for the IP address to change when the testbox
isn't online, but not while testing (just imagine live migration tests and
network tests).  Ideally, the testboxes should not change IP address.

The testbox edit function must allow changing the name and system UUID.

One further idea for the testbox configuration is indicating what they are
capable of to filter out tests and test configurations that won't work on that
testbox.  To examplify this take the ACP2 installation test.  If the test
manager does not make sure the testbox have VT-x or AMD-v capabilities, the test
is surely going to fail.  Other testbox capabilities would be total number of
CPU cores, memory size, scratch space.  These testbox capabilities should be
collected automatically on bootup by the testbox script together with OS name,
OS version and OS bitness.

A final thought, instead of outright declining all requests from new testboxes,
we could record the unregistered testboxes with ip, UUID, name, os info and
capabilities but mark them as inactive.  The test operator can then activate
them on an activation page or edit the testbox or something.

Testcases

We use the term testcase for a test.

Testgroups

Testcases are organized into groups.  A testcase can be member of more than one
group.  The testcase gets a priority assigned to it in connection with the
group membership.

Testgroups are picked up by a testbox partition (aka scheduling group) and a
prioirty, scheduling time restriction and dependencies on other test groups are
associated with the assignment.  A testgroup can be used by several testbox
partitions.

(This used to be called 'testsuites' but was renamed to avoid confusion with
the VBox Test Suite.)

Scheduling

The initial scheduler will be modelled after what we're doing already on in the
tinderbox driven testing.  It's best described as a best effort continuous
integration scheduler.  Meaning, it will always use the latest build suitable
for a testcase.  It will schedule on a testcase level, using the combined
priority of the testcase in the test group and the test group with the testbox
partition, trying to spread the test case argument varation out accordingly
over the whole scheduilng queue.  Which argument variation to start with, is
not undefined (random would be best).

Later, we may add other schedulers as needed.

The Test Manager Database

First a general warning:

The guys working on this design are not database experts, web
programming experts or similar, rather we are low level guys
who's main job is x86 & AMD64 virtualization.  So, please don't
be too hard on us. :-)

A logical table layout can be found in TestManagerDatabaseMap.png (created by
Oracle SQL Data Modeler, stored in TestManagerDatabase.dmd).  The physical
database layout can be found in TestManagerDatabaseInit.pgsql postgreSQL
script.  The script is commented.

Data History

We need to somehow track configuration changes over time.  We also need to
be able to query the exact configuration a test set was run with so we can
understand and make better use of the results.

There are different techniques for archiving this, one is tuple-versioning
( http://en.wikipedia.org/wiki/Tuple-versioning ), another is log trigger
( http://en.wikipedia.org/wiki/Log_trigger ).  We use tuple-versioning in
this database, with 'effective' as start date field name and 'expire' as
the end (exclusive).

Tuple-versioning has a shortcomming wrt to keys, both primary and foreign.
The primary key of a table employing tuple-versioning is really
'id' + 'valid_period', where the latter is expressed using two fields
([effective...expire-1]).  Only, how do you tell the database engine that
it should not allow overlapping valid_periods?  Useful suggestions are
welcomed. :-)

Foreign key references to a table using tuple-versioning is running into
trouble because of the time axsis and that to our knowledge foreign keys
must reference exactly one row in the other table.  When time is involved
what we wish to tell the database is that at any given time, there actually
is exactly one row we want to match in the other table, only we've no idea
how to express this.  So, many foreign keys are not expressed in SQL of this
database.

In some cases, we extend the tuple-versioning with a generation ID so that
normal foreign key referencing can be used.  We only use this for recording
(references in testset) and scheduling (schedqueue), as using it more widely
would force updates (gen_id changes) to propagate into all related tables.

See also:

http://en.wikipedia.org/wiki/Slowly_changing_dimension

http://en.wikipedia.org/wiki/Change_data_capture

http://en.wikipedia.org/wiki/Temporal_database

Test Manager: Execution

Test Manager: Scenarios

#1 - Testbox Signs On (At Bootup)

The testbox supplies a number of inputs when reporting for duty:

IP address.

System UUID.

OS name.

OS version.

CPU architecture.

CPU count (= threads).

CPU VT-x/AMD-V capability.

CPU nested paging capability.

Chipset I/O MMU capability.

Memory size.

Scratch size space (for testing).

Testbox Script revision.

Results:

ACK or NACK.

Testbox ID and name on ACK.

After receiving a ACK the testbox will ask for work to do, i.e. continue with
scenario #2.  In the NACK case, it will sleep for 60 seconds and try again.

Actions:

Validate the testbox by looking the UUID up in the TestBoxes table.
If not found, NACK the request.  SQL:

SELECT  idTestBox, sName
FROM    TestBoxes
WHERE   uuidSystem = :sUuid
  AND   tsExpire = 'infinity'::timestamp;

Check if any of the information by testbox script has changed.  The two
sizes are normalized first, memory size rounded to nearest 4 MB and scratch
space is rounded down to nearest 64 MB.  If anything changed, insert a new
row in the testbox table and historize the current one, i.e. set
OLD.tsExpire to NEW.tsEffective and get a new value for NEW.idGenTestBox.

Check with TestBoxStatuses:

If there is an row for the testbox in it already clean up change it
to 'idle' state and deal with any open testset like described in
scenario #9.

If there is no row, add one with 'idle' state.

ACK the request and pass back the idTestBox.

Note! Testbox.enabled is not checked here, that is only relevant when it asks

for a new task (scenario #2 and #5).

Note! Should the testbox script detect changes in any of the inputs, it should

redo the sign in.

Note! In scenario #8, the box will not sign on until it has done the reboot and

cleanup reporting!

#2 - Testbox Asks For Work To Do

Inputs:

The testbox is supplying its IP indirectly.

The testbox should supply its UUID and ID directly.

Results:

IDLE, WAIT, EXEC, REBOOT, UPGRADE, UPGRADE-AND-REBOOT, SPECIAL or DEAD.

Actions:

Validate the ID and IP by selecting the currently valid testbox row:

SELECT  idGenTestBox, fEnabled, idSchedGroup, enmPendingCmd
FROM    TestBoxes
WHERE   id = :id
  AND   uuidSystem = :sUuid
  AND   ip = :ip
  AND   tsExpire = 'infinity'::timestamp;

If NOT found return DEAD to the testbox client (it will go back to sign on
mode and retry every 60 seconds or so - see scenario #1).

Note! The WUI will do all necessary clean-ups when deleting a testbox, so

contrary to the initial plans, we don't need to do anything more for
the DEAD status.

Check with TestBoxStatuses (maybe joined with query from 1).

If enmState is 'gang-gathering': Goto scenario #6 on timeout or pending
'abort' or 'reboot' command.  Otherwise, tell the testbox to WAIT [done].

If enmState is 'gang-testing': The gang has been gathered and execution
has been triggered.  Goto 5.

If enmState is not 'idle', change it to 'idle'.

If idTestSet is not NULL, CALL scenario #9 to it up.

If there is a pending abort command, remove it.

If there is a pending command and the old state doesn't indicate that it was
being executed, GOTO scenario #3.

Note! There should be a TestBoxStatuses row after executing scenario #1,

however should none be found for some funky reason, returning DEAD
will fix the problem (see above)

If the testbox was marked as disabled, respond with an IDLE command to the
testbox [done]. (Note! Must do this after TestBoxStatuses maintainance from
point 2, or abandond tests won't be cleaned up after a testbox is disabled.)

Consider testcases in the scheduling queue, pick the first one which the
testbox can execute.  There is a concurrency issue here, so we put and
exclusive lock on the SchedQueues table while considering its content.

The cursor we open looks something like this:

SELECT  idItem, idGenTestCaseArgs,
        idTestSetGangLeader, cMissingGangMembers
FROM    SchedQueues
WHERE   idSchedGroup = :idSchedGroup
   AND  (   bmHourlySchedule is NULL
         OR get_bit(bmHourlySchedule, :iHourOfWeek) = 1 ) --< does this work?
ORDER BY ASC idItem;

If there no rows are returned (this can happen because no testgroups are
associated with this scheduling group, the scheduling group is disabled,
or because the queue is being regenerated), we will tell the testbox to
IDLE [done].

For each returned row we will:

Check testcase/group dependencies.

Select a build (and default testsuite) satisfying the dependencies.

Check the testcase requirements with that build in mind.

If idTestSetGangLeader is NULL, try allocate the necessary resources.

If it didn't check out, fetch the next row and redo from (a).

Tentatively create a new test set row.

If not gang scheduling:

Next state: 'testing'

ElIf we're the last gang participant:

Set idTestSetGangLeader to NULL.

Set cMissingGangMembers to 0.

Next state: 'gang-testing'

ElIf we're the first gang member:

Set cMissingGangMembers to TestCaseArgs.cGangMembers - 1.

Set idTestSetGangLeader to our idTestSet.

Next state: 'gang-gathering'

Else:

Decrement cMissingGangMembers.

Next state: 'gang-gathering'

If we're not gang scheduling OR cMissingGangMembers is 0:

Move the scheduler queue entry to the end of the queue.

Update our TestBoxStatuses row with the new state and test set.
COMMIT;

If state is 'testing' or 'gang-testing':

EXEC reponse.

The EXEC response for a gang scheduled testcase includes a number of
extra arguments so that the script knows the position of the testbox
it is running on and of the other members.  This means the that the
TestSet.iGangMemberNo is passed using --gang-member-no and the IP
addresses of the all gang members using --gang-ipv4-<memb-no> <ip>.

Else (state is 'gang-gathering'):

WAIT

#3 - Pending Command When Testbox Asks For Work

This is a subfunction of scenario #2 and #5.

As seen in scenario #2, the testbox will send 'abort' commands to /dev/null
when it finds one when not executing a test.  This includes when it reports
that the test has completed (no need to abort a completed test, wasting lot
of effort when standing at the finish line).

The other commands, though, are passed back to the testbox.  The testbox
script will respond with an ACK or NACK as it sees fit.  If NACKed, the
pending command will be removed (pending_cmd set to none) and that's it.
If ACKed, the state of the testbox will change to that appropriate for the
command and the pending_cmd set to none.  Should the testbox script fail to
respond, the command will be repeated the next time it asks for work.

#4 - Testbox Uploads Results During Test

TODO

#5 - Testbox Completes Test and Asks For Work

This is very similar to scenario #2

TODO

#6 - Gang Gathering Timeout

This is a subfunction of scenario #2.

When gathering a gang of testboxes for a testcase, we do not want to wait
forever and have testboxes doing nothing for hours while waiting for partners.
So, the gathering has a reasonable timeout (imagine something like 20-30 mins).

Also, we need some way of dealing with 'abort' and 'reboot' commands being
issued while waiting.  The easy way out is pretent it's a time out.

When changing the status to 'gang-timeout' we have to be careful.  First of all,
we need to exclusively lock the SchedQueues and TestBoxStatuses (in that order)
and re-query our status.  If it changed redo the checks in scenario #2 point 2.

If we still want to timeout/abort, change the state from 'gang-gathering' to
'gang-gathering-timedout' on all the gang members that has gathered so far.
Then reset the scheduling queue record and move it to the end of the queue.

When acting on 'gang-timeout' the TM will fail the testset in a manner similar
to scenario #9.  No need to repeat that.

#7 - Gang Cleanup

When a testbox completes a gang scheduled test, we will have to serialize
resource cleanup (both globally and on testboxes) as they stop.  More details
can be found in the documentation of 'gang-cleanup'.

So, the transition from 'gang-testing' is always to 'gang-cleanup'.  When we
can safely leave 'gang-cleanup' is decided by the query:

SELECT  COUNT(*)
FROM    TestBoxStatuses,
        TestSets
WHERE   TestSets.idTestSetGangLeader = :idTestSetGangLeader
    AND TestSets.idTestBox = TestBoxStatuses.idTestBox
    AND TestBoxStatuses.enmState = 'gang-running'::TestBoxState_T;

As long as there are testboxes still running, we stay in the 'gang-cleanup'
state.  Once there are none, we continue closing the testset and such.

#8 - Testbox Reports A Crash During Test Execution

TODO

#9 - Cleaning Up Abandond Testcase

This is a subfunction of scenario #1 and #2.  The actions taken are the same in
both situations.  The precondition for taking this path is that the row in the
testboxstatus table is refering to a testset (i.e. testset_id is not NULL).

Actions:

If the testset is incomplete, we need to completed:

Add a message to the root TestResults row, creating one if necesary,
that explains that the test was abandond.  This is done
by inserting/finding the string into/in TestResultStrTab and adding
a row to TestResultMsgs with idStrMsg set to that string id and
enmLevel set to 'failure'.

Mark the testset as failed.

Free any global resources referenced by the test set.  This is done by
deleting all rows in GlobalResourceStatuses matching the testbox id.

Set the idTestSet to NULL in the TestBoxStatuses row.

#10 - Cleaning Up a Disabled/Dead TestBox

The UI needs to be able to clean up the remains of a testbox which for some
reason is out of action.  Normal cleaning up of abandond testcases requires
that the testbox signs on or asks for work, but if the testbox is dead or
in some way indisposed, it won't be doing any of that.  So, the testbox
sheriff needs to have a way of cleaning up after it.

It's basically a manual scenario #9 but with some safe guards, like checking
that the box hasn't been active for the last 1-2 mins (max idle/wait time * 2).

Note! When disabling a box that still executing the testbox script, this

cleanup isn't necessary as it will happen automatically.   Also, it's
probably desirable that the testbox finishes what ever it is doing first
before going dormant.

Test Manager: Analysis

One of the testbox sheriff's tasks is to try figure out the reason why something
failed.  The test manager will provide facilities for doing so from very early
in it's implementation.

We need to work out some useful status reports for the early implementation.
Later there will be more advanced analysis tools, where for instance we can
create graphs from selected test result values or test execution times.

Implementation Plan

This has changed for various reasons.  The current plan is to implement the
infrastructure (TM & testbox script) first and do a small deployment with the
2-5 test drivers in the Testsuite as basis.  Once the bugs are worked out, we
will convert the rest of the tests and start adding new ones.

We just need to finally get this done, no point in doing it piecemeal by now!

Test Manager Implementation Sub-Tasks

The implementation of the test manager and adjusting/completing of the testbox
script and the test drivers are tasks which can be done by more than one
person.  Splitting up the TM implementation into smaller tasks should allow
parallel development of different tasks and get us working code sooner.

Milestone #1

The goal is to getting the fundamental testmanager engine implemented, debugged
and working.  With the exception of testboxes, the configuration will be done
via SQL inserts.

Tasks in somewhat prioritized order:

Kick off test manager.  It will live in testmanager/.  Salvage as much as
possible from att/testserv.  Create basic source and file layout.

Adjust the testbox script, part one.  There currently is a testbox script
in att/testbox, this shall be moved up into testboxscript/.  The script
needs to be adjusted according to the specification layed down earlier
in this document.  Installers or installation scripts for all relevant
host OSes are required.  Left for part two is result reporting beyond the
primary log.  This task must be 100% feature complete, on all host OSes,
there is no room for FIXME, XXX or @todo here.

Implement the schedule queue generator.

Implement the testbox dispatcher in TM.  Support all the testbox script
responses implemented above, including upgrading the testbox script.

Implement simple testbox management page.

Implement some basic activity and result reports so that we can see
what's going on.

Create a testmanager / testbox test setup.  This lives in selftest/.

Set up something that runs, no fiddly bits. Debug till it works.

Create a setup that tests testgroup dependencies, i.e. real tests
depending on smoke tests.

Create a setup that exercises testcase dependency.

Create a setup that exercises global resource allocation.

Create a setup that exercises gang scheduling.

Check that all features work.

Milestone #2

The goal is getting to VBox testing.

Tasks in somewhat prioritized order:

Implement full result reporting in the testbox script and testbox driver.
A testbox script specific reporter needs to be implemented for the
testdriver framework.  The testbox script needs to forward the results to
the test manager, or alternatively the testdriver report can talk
directly to the TM.

Implement the test manager side of the test result reporting.

Extend the selftest with some setup that report all kinds of test
results.

Implement script/whatever feeding builds to the test manager from the
tinderboxes.

The toplevel test driver is a VBox thing that must be derived from the
base TestDriver class or maybe the VBox one.  It should move from
toptestdriver to testdriver and be renamed to vboxtltd or smth.

Create a vbox testdriver that boots the t-xppro VM once and that's it.

Create a selftest setup which tests booting t-xppro taking builds from
the tinderbox.

Milestone #3

The goal for this milestone is configuration and converting current testscases,
the result will be the a minimal test deployment (4-5 new testboxes).

Tasks in somewhat prioritized order:

Implement testcase configuration.

Implement testgroup configuration.

Implement build source configuration.

Implement scheduling group configuration.

Implement global resource configuration.

Re-visit the testbox configuration.

Black listing of builds.

Implement simple failure analysis and reporting.

Implement the initial smoke tests modelled on the current smoke tests.

Implement installation tests for Windows guests.

Implement installation tests for Linux guests.

Implement installation tests for Solaris guest.

Implement installation tests for OS/2 guest.

Set up a small test deployment.

Further work

After milestone #3 has been reached and issues found by the other team members
have been addressed, we will probably go for full deployment.

Beyond this point we will need to improve reporting and analysis.  There may be
configuration aspects needing reporting as well.

Once deployed, a golden rule will be that all new features shall have test
coverage.  Preferrably, implemented by someone else and prior to the feature
implementation.

Discussion Logs

2009-07-21,22,23 Various Discussions with Michal and/or Klaus

Scheduling of tests requiring more than one testbox.

Scheduling of tests that cannot be executing concurrently on several machines
because of some global resource like an iSCSI target.

Manually create the test config permutations instead of having the test
manager create all possible ones and wasting time.

Distinguish between built types so we can run smoke tests on strick builds as
well as release ones.

2009-07-20 Brief Discussion with Michal

Installer for the testbox script to make bringing up a new testbox even
smoother.

2009-07-16 Raw Input

test set. recursive collection of:

hierachical subtest name (slash sep)

test parameters / config

bool fail/succ

attributes (typed?)

test time

e.g. throughput

subresults

log

screenshots,....

client package (zip) dl from server (maybe client caching)

thoughts on bits to do at once.

We really need the basic bits ASAP.

client -> support for test driver

server -> controls configs

cleanup on both sides

2009-07-15 Raw Input

testing should start automatically

switching to branch too tedious

useful to be able to partition testboxes (run specific builds on some boxes, let an engineer have a few boxes for a while).

test specification needs to be more flexible (select tests, disable test, test scheduling (run certain tests nightly), ... )

testcase dependencies (blacklisting builds, run smoketests on box A before long tests on box B, ...)

more testing flexibility, more test than just install/moke. For instance unit tests, benchmarks, ...

presentation/analysis: graphs!, categorize bugs, columns reorganizing grouped by test (hierarchical), overviews, result for last day.

testcase specificion, variables (e.g. I/O-APIC, SMP, HWVIRT, SATA...) as sub-tests

interation with ILOM/...: reset systems

Changes needs LDAP authentication

historize all configuration  w/ name

ability to run testcase locally (provided the VDI/ISO/whatever extra requirements can be met).

<colgroup><col class="label" /><col /></colgroup>

[1]	no such footnote

<col class="field-name" />
<col class="field-body" />

Status:	$Id: AutomaticTestingRevamp.html $

Copyright:	Copyright (C) 2010-2015 Oracle Corporation.