/**
     * Resumes a transfer operation that is paused.
     * @example
     * ```js
     * // Before running the sample:
     * // - Enable the API at:
     * //   https://console.developers.google.com/apis/api/storagetransfer.googleapis.com
     * // - Login into gcloud by running:
     * //   `$ gcloud auth application-default login`
     * // - Install the npm module by running:
     * //   `$ npm install googleapis`
     *
     * const {google} = require('googleapis');
     * const storagetransfer = google.storagetransfer('v1');
     *
     * async function main() {
     *   const auth = new google.auth.GoogleAuth({
     *     // Scopes can be specified either as an array or as a single, space-delimited string.
     *     scopes: ['https://www.googleapis.com/auth/cloud-platform'],
     *   });
     *
     *   // Acquire an auth client, and bind it to all future calls
     *   const authClient = await auth.getClient();
     *   google.options({auth: authClient});
     *
     *   // Do the magic
     *   const res = await storagetransfer.transferOperations.resume({
     *     // Required. The name of the transfer operation.
     *     name: 'transferOperations/.*',
     *
     *     // Request body metadata
     *     requestBody: {
     *       // request body parameters
     *       // {}
     *     },
     *   });
     *   console.log(res.data);
     *
     *   // Example response
     *   // {}
     * }
     *
     * main().catch(e => {
     *   console.error(e);
     *   throw e;
     * });
     *
     * ```
     *
     * @param params - Parameters for request
     * @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
     * @param callback - Optional callback that handles the response.
     * @returns A promise if used with async/await, or void if used with a callback.
     */
resume(
      params: Params$Resource$Transferoperations$Resume,
      options: StreamMethodOptions
    ): GaxiosPromise<Readable>;


resume(
      params?: Params$Resource$Transferoperations$Resume,
      options?: MethodOptions
    ): GaxiosPromise<Schema$Empty>;


resume(
      params: Params$Resource$Transferoperations$Resume,
      options: StreamMethodOptions | BodyResponseCallback<Readable>,
      callback: BodyResponseCallback<Readable>
    ): void;


resume(
      params: Params$Resource$Transferoperations$Resume,
      options: MethodOptions | BodyResponseCallback<Schema$Empty>,
      callback: BodyResponseCallback<Schema$Empty>
    ): void;


resume(
      params: Params$Resource$Transferoperations$Resume,
      callback: BodyResponseCallback<Schema$Empty>
    ): void;


resume(callback: BodyResponseCallback<Schema$Empty>): void;


resume(
      paramsOrCallback?:
        | Params$Resource$Transferoperations$Resume
        | BodyResponseCallback<Schema$Empty>
        | BodyResponseCallback<Readable>,
      optionsOrCallback?:
        | MethodOptions
        | StreamMethodOptions
        | BodyResponseCallback<Schema$Empty>
        | BodyResponseCallback<Readable>,
      callback?:
        | BodyResponseCallback<Schema$Empty>
        | BodyResponseCallback<Readable>
    ): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> {
      let params = (paramsOrCallback ||
        {}) as Params$Resource$Transferoperations$Resume;
      let options = (optionsOrCallback || {}) as MethodOptions;

      if (typeof paramsOrCallback === 'function') {
        callback = paramsOrCallback;
        params = {} as Params$Resource$Transferoperations$Resume;
        options = {};
      }

      if (typeof optionsOrCallback === 'function') {
        callback = optionsOrCallback;
        options = {};
      }

      const rootUrl =
        options.rootUrl || 'https://storagetransfer.googleapis.com/';
      const parameters = {
        options: Object.assign(
          {
            url: (rootUrl + '/v1/{+name}:resume').replace(/([^:]\/)\/+/g, '$1'),
            method: 'POST',
          },
          options
        ),
        params,
        requiredParams: ['name'],
        pathParams: ['name'],
        context: this.context,
      };
      if (callback) {
        createAPIRequest<Schema$Empty>(
          parameters,
          callback as BodyResponseCallback<unknown>
        );
      } else {
        return createAPIRequest<Schema$Empty>(parameters);
      }
    }


/**
 * Compute role.
 * Latest API Version: 2020-12-01.
 */
/** @deprecated The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:databoxedge:getRole'. */
export function getRole(args: GetRoleArgs, opts?: pulumi.InvokeOptions): Promise<GetRoleResult> {
    pulumi.log.warn("getRole is deprecated: The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:databoxedge:getRole'.")
    if (!opts) {
        opts = {}
    }

    if (!opts.version) {
        opts.version = utilities.getVersion();
    }
    return pulumi.runtime.invoke("azure-native:databoxedge/latest:getRole", {
        "deviceName": args.deviceName,
        "name": args.name,
        "resourceGroupName": args.resourceGroupName,
    }, opts);
}


export interface GetRoleArgs {
    /**
     * The device name.
     */
    readonly deviceName: string;
    /**
     * The role name.
     */
    readonly name: string;
    /**
     * The resource group name.
     */
    readonly resourceGroupName: string;
}


/**
 * Compute role.
 */
export interface GetRoleResult {
    /**
     * The path ID that uniquely identifies the object.
     */
    readonly id: string;
    /**
     * Role type.
     */
    readonly kind: string;
    /**
     * The object name.
     */
    readonly name: string;
    /**
     * Role configured on ASE resource
     */
    readonly systemData: outputs.databoxedge.latest.SystemDataResponse;
    /**
     * The hierarchical type of the object.
     */
    readonly type: string;
}


(option, index) => {
      copy = this.getRowClone(row, index, rowIndex);
      copy.scopedVars = {};
      copy.scopedVars[variable.name] = option;

      for (i = 0; i < copy.panels.length; i++) {
        panel = copy.panels[i];
        panel.scopedVars = {};
        panel.scopedVars[variable.name] = option;
        panel.repeatIteration = this.iteration;
      }
    }


(option, index) => {
      var copy = this.getPanelClone(panel, row, index);
      copy.span = Math.max(12 / selected.length, panel.minSpan || 4);
      copy.scopedVars = copy.scopedVars || {};
      copy.scopedVars[variable.name] = option;
    }


export class DynamicDashboardSrv {
  iteration: number;
  dashboard: any;

  init(dashboard) {
    if (dashboard.snapshot) { return; }
    this.process(dashboard, {});
  }

  update(dashboard) {
    if (dashboard.snapshot) { return; }
    this.process(dashboard, {});
  }

  process(dashboard, options) {
    if (dashboard.templating.list.length === 0) { return; }

    this.dashboard = dashboard;
    this.iteration = (this.iteration || new Date().getTime()) + 1;

    var cleanUpOnly = options.cleanUpOnly;

    var i, j, row, panel;
    for (i = 0; i < this.dashboard.rows.length; i++) {
      row = this.dashboard.rows[i];
      // handle row repeats
      if (row.repeat) {
        if (!cleanUpOnly) {
          this.repeatRow(row, i);
        }
      } else if (row.repeatRowId && row.repeatIteration !== this.iteration) {
        // clean up old left overs
        this.dashboard.rows.splice(i, 1);
        i = i - 1;
        continue;
      }

      // repeat panels
      for (j = 0; j < row.panels.length; j++) {
        panel = row.panels[j];
        if (panel.repeat) {
          if (!cleanUpOnly) {
            this.repeatPanel(panel, row);
          }
        } else if (panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
          // clean up old left overs
          row.panels = _.without(row.panels, panel);
          j = j - 1;
        } else if (!_.isEmpty(panel.scopedVars) && panel.repeatIteration !== this.iteration) {
          panel.scopedVars = {};
        }
      }
    }
  }

  // returns a new row clone or reuses a clone from previous iteration
  getRowClone(sourceRow, repeatIndex, sourceRowIndex) {
    if (repeatIndex === 0) {
      return sourceRow;
    }

    var i, panel, row, copy;
    var sourceRowId = sourceRowIndex + 1;

    // look for row to reuse
    for (i = 0; i < this.dashboard.rows.length; i++) {
      row = this.dashboard.rows[i];
      if (row.repeatRowId === sourceRowId && row.repeatIteration !== this.iteration) {
        copy = row;
        break;
      }
    }

    if (!copy) {
      copy = angular.copy(sourceRow);
      this.dashboard.rows.splice(sourceRowIndex + repeatIndex, 0, copy);

      // set new panel ids
      for (i = 0; i < copy.panels.length; i++) {
        panel = copy.panels[i];
        panel.id = this.dashboard.getNextPanelId();
      }
    }

    copy.repeat = null;
    copy.repeatRowId = sourceRowId;
    copy.repeatIteration = this.iteration;
    return copy;
  }

  // returns a new row clone or reuses a clone from previous iteration
  repeatRow(row, rowIndex) {
    var variables = this.dashboard.templating.list;
    var variable = _.findWhere(variables, {name: row.repeat});
    if (!variable) {
      return;
    }

    var selected, copy, i, panel;
    if (variable.current.text === 'All') {
      selected = variable.options.slice(1, variable.options.length);
    } else {
      selected = _.filter(variable.options, {selected: true});
    }

    _.each(selected, (option, index) => {
      copy = this.getRowClone(row, index, rowIndex);
      copy.scopedVars = {};
      copy.scopedVars[variable.name] = option;

      for (i = 0; i < copy.panels.length; i++) {
        panel = copy.panels[i];
        panel.scopedVars = {};
        panel.scopedVars[variable.name] = option;
        panel.repeatIteration = this.iteration;
      }
    });
  }

  getPanelClone(sourcePanel, row, index) {
    // if first clone return source
    if (index === 0) {
      return sourcePanel;
    }

    var i, tmpId, panel, clone;

    // first try finding an existing clone to use
    for (i = 0; i < row.panels.length; i++) {
      panel = row.panels[i];
      if (panel.repeatIteration !== this.iteration && panel.repeatPanelId === sourcePanel.id) {
        clone = panel;
        break;
      }
    }

    if (!clone) {
      clone = { id: this.dashboard.getNextPanelId() };
      row.panels.push(clone);
    }

    // save id
    tmpId = clone.id;
    // copy properties from source
    angular.copy(sourcePanel, clone);
    // restore id
    clone.id = tmpId;
    clone.repeatIteration = this.iteration;
    clone.repeatPanelId = sourcePanel.id;
    clone.repeat = null;
    return clone;
  }

  repeatPanel(panel, row) {
    var variables = this.dashboard.templating.list;
    var variable = _.findWhere(variables, {name: panel.repeat});
    if (!variable) { return; }

    var selected;
    if (variable.current.text === 'All') {
      selected = variable.options.slice(1, variable.options.length);
    } else {
      selected = _.filter(variable.options, {selected: true});
    }

    _.each(selected, (option, index) => {
      var copy = this.getPanelClone(panel, row, index);
      copy.span = Math.max(12 / selected.length, panel.minSpan || 4);
      copy.scopedVars = copy.scopedVars || {};
      copy.scopedVars[variable.name] = option;
    });
  }
}


init(dashboard) {
    if (dashboard.snapshot) { return; }
    this.process(dashboard, {});
  }


update(dashboard) {
    if (dashboard.snapshot) { return; }
    this.process(dashboard, {});
  }


process(dashboard, options) {
    if (dashboard.templating.list.length === 0) { return; }

    this.dashboard = dashboard;
    this.iteration = (this.iteration || new Date().getTime()) + 1;

    var cleanUpOnly = options.cleanUpOnly;

    var i, j, row, panel;
    for (i = 0; i < this.dashboard.rows.length; i++) {
      row = this.dashboard.rows[i];
      // handle row repeats
      if (row.repeat) {
        if (!cleanUpOnly) {
          this.repeatRow(row, i);
        }
      } else if (row.repeatRowId && row.repeatIteration !== this.iteration) {
        // clean up old left overs
        this.dashboard.rows.splice(i, 1);
        i = i - 1;
        continue;
      }

      // repeat panels
      for (j = 0; j < row.panels.length; j++) {
        panel = row.panels[j];
        if (panel.repeat) {
          if (!cleanUpOnly) {
            this.repeatPanel(panel, row);
          }
        } else if (panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
          // clean up old left overs
          row.panels = _.without(row.panels, panel);
          j = j - 1;
        } else if (!_.isEmpty(panel.scopedVars) && panel.repeatIteration !== this.iteration) {
          panel.scopedVars = {};
        }
      }
    }
  }


// returns a new row clone or reuses a clone from previous iteration
getRowClone(sourceRow, repeatIndex, sourceRowIndex) {
    if (repeatIndex === 0) {
      return sourceRow;
    }

    var i, panel, row, copy;
    var sourceRowId = sourceRowIndex + 1;

    // look for row to reuse
    for (i = 0; i < this.dashboard.rows.length; i++) {
      row = this.dashboard.rows[i];
      if (row.repeatRowId === sourceRowId && row.repeatIteration !== this.iteration) {
        copy = row;
        break;
      }
    }

    if (!copy) {
      copy = angular.copy(sourceRow);
      this.dashboard.rows.splice(sourceRowIndex + repeatIndex, 0, copy);

      // set new panel ids
      for (i = 0; i < copy.panels.length; i++) {
        panel = copy.panels[i];
        panel.id = this.dashboard.getNextPanelId();
      }
    }

    copy.repeat = null;
    copy.repeatRowId = sourceRowId;
    copy.repeatIteration = this.iteration;
    return copy;
  }


// returns a new row clone or reuses a clone from previous iteration
repeatRow(row, rowIndex) {
    var variables = this.dashboard.templating.list;
    var variable = _.findWhere(variables, {name: row.repeat});
    if (!variable) {
      return;
    }

    var selected, copy, i, panel;
    if (variable.current.text === 'All') {
      selected = variable.options.slice(1, variable.options.length);
    } else {
      selected = _.filter(variable.options, {selected: true});
    }

    _.each(selected, (option, index) => {
      copy = this.getRowClone(row, index, rowIndex);
      copy.scopedVars = {};
      copy.scopedVars[variable.name] = option;

      for (i = 0; i < copy.panels.length; i++) {
        panel = copy.panels[i];
        panel.scopedVars = {};
        panel.scopedVars[variable.name] = option;
        panel.repeatIteration = this.iteration;
      }
    });
  }


getPanelClone(sourcePanel, row, index) {
    // if first clone return source
    if (index === 0) {
      return sourcePanel;
    }

    var i, tmpId, panel, clone;

    // first try finding an existing clone to use
    for (i = 0; i < row.panels.length; i++) {
      panel = row.panels[i];
      if (panel.repeatIteration !== this.iteration && panel.repeatPanelId === sourcePanel.id) {
        clone = panel;
        break;
      }
    }

    if (!clone) {
      clone = { id: this.dashboard.getNextPanelId() };
      row.panels.push(clone);
    }

    // save id
    tmpId = clone.id;
    // copy properties from source
    angular.copy(sourcePanel, clone);
    // restore id
    clone.id = tmpId;
    clone.repeatIteration = this.iteration;
    clone.repeatPanelId = sourcePanel.id;
    clone.repeat = null;
    return clone;
  }


repeatPanel(panel, row) {
    var variables = this.dashboard.templating.list;
    var variable = _.findWhere(variables, {name: panel.repeat});
    if (!variable) { return; }

    var selected;
    if (variable.current.text === 'All') {
      selected = variable.options.slice(1, variable.options.length);
    } else {
      selected = _.filter(variable.options, {selected: true});
    }

    _.each(selected, (option, index) => {
      var copy = this.getPanelClone(panel, row, index);
      copy.span = Math.max(12 / selected.length, panel.minSpan || 4);
      copy.scopedVars = copy.scopedVars || {};
      copy.scopedVars[variable.name] = option;
    });
  }


export default function webpackRollupLoader(this: webpack.loader.LoaderContext, source: string, sourceMap: RawSourceMap): void;


(paraobj) => {
            return this._validate(paraobj);
        }


<T>(c : T) : c is Exclude<T, null> => c !== null


(row) => callback(null, row)


(err) => callback(err)


// Parse the raw output of Amazon MTurk paraphrasing into easier to handle objects
//
// Input:
//  - one row per task submission
//    formatted as per MTurk results
//
// Output:
//  - one row per paraphrase, each with:
//    - id
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrase
export class ParaphrasingParser extends Stream.Transform {
    private _sentencesPerTask : number;
    private _paraphrasesPerSentence : number;
    private _contextual : boolean;

    private _id : number;

    constructor(options : ParaphrasingParserOptions) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._sentencesPerTask = options.sentencesPerTask;
        this._paraphrasesPerSentence = options.paraphrasesPerSentence;
        this._contextual = options.contextual;

        this._id = 0;
    }

    _transform(row : Record<string, string>, encoding : BufferEncoding, callback : () => void) {
        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            let context, context_utterance, assistant_action;
            if (this._contextual) {
                context = row[`Input.context${i+1}`];
                context_utterance = row[`Input.context_utterance${i+1}`];
                assistant_action = row[`Input.assistant_action${i+1}`];
            }

            for (let j = 0; j < this._paraphrasesPerSentence; j++) {
                const paraphrase = row[`Answer.Paraphrase${i+1}-${j+1}`];
                const id = (this._contextual ? 'C' : '') + this._id++;
                if (this._contextual) {
                    this.push({
                        id, synthetic_id, synthetic,
                        context, context_utterance, assistant_action,
                        target_code, paraphrase
                    });
                } else {
                    this.push({
                        id, synthetic_id, synthetic, target_code, paraphrase
                    });
                }
            }
        }
        callback();
    }

    _flush(callback : () => void) {
        process.nextTick(callback);
    }
}


// Accumulate all paraphrases of the same synthetic
//
// Input:
//  - one row per paraphrase, each with:
//    - id
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrase
//
// Output:
//  - one row per synthetic, each with:
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrases: array of { id, paraphrase }
export class ParaphrasingAccumulator extends Stream.Transform {
    private _totalParaphrasesPerSentence : number;
    private _synthetics : Map<string, ParsedParaphrase>;
    private _buffers : Map<string, Array<{ id : string; paraphrase : string }>>;

    constructor(totalParaphrasesPerSentence : number) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._totalParaphrasesPerSentence = totalParaphrasesPerSentence;

        this._synthetics = new Map;
        this._buffers = new Map;
    }

    _transform(row : ParsedParaphrase, encoding : BufferEncoding, callback : () => void) {
        const synthetic_id = row.synthetic_id;

        let buffer = this._buffers.get(synthetic_id);
        if (!buffer) {
            this._synthetics.set(synthetic_id, row);
            this._buffers.set(synthetic_id, buffer = []);
        }

        buffer.push({
            id: row.id,
            paraphrase: row.paraphrase
        });

        if (buffer.length >= this._totalParaphrasesPerSentence) {
            this.push({
                synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrases: buffer
            });
            this._buffers.delete(synthetic_id);
        }
        callback();
    }

    _flush(callback : () => void) {
        for (const [synthetic_id, buffer] of this._buffers) {
            const row = this._synthetics.get(synthetic_id)!;
            this.push({
                synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrases: buffer
            });
        }

        this._buffers.clear();
        this._synthetics.clear();
        callback();
    }
}


// Parse the raw output of Amazon MTurk validation into easier to handle objects
//
// Input:
//  - one row per task submission
//    formatted as per MTurk results
//
// Output:
//  - one row per paraphrase, each with:
//    - id
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrase
//    - vote
export class ValidationParser extends Stream.Transform {
    private _sentencesPerTask : number;
    private _targetSize : number;
    private _skipRejected : boolean;

    constructor(options : ValidationParserOptions) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._sentencesPerTask = options.sentencesPerTask;
        this._targetSize = options.targetSize;
        this._skipRejected = options.skipRejected;
    }

    _transform(row : Record<string, string>, encoding : BufferEncoding, callback : () => void) {
        if (this._skipRejected && row['Reject']) {
            callback();
            return;
        }

        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            // + 2 to account for same/different paraphrases (sanity checks)
            // mixed in with the real data
            for (let j = 0; j < this._targetSize + 2; j++) {
                const paraphrase = row[`Input.paraphrase${i+1}-${j+1}`];
                const id = row[`Input.id${i+1}-${j+1}`];
                if (id === '-same' || id === '-different')
                    continue;

                const vote = row[`Answer.${i+1}-${j+1}`];
                this.push({
                    id, synthetic_id, synthetic, target_code, paraphrase, vote
                });
            }
        }
        callback();
    }

    _flush(callback : () => void) {
        process.nextTick(callback);
    }
}


// Count all validation votes of the same paraphrase
//
// Input:
//  - one row per validation task, each with:
//    - id
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrase
//    - vote
//
// Output:
//  - one row per paraphrase, each with:
//    - id
//    - synthetic_id
//    - synthetic
//    - target_code
//    - paraphrase
//    - same_count
//    - diff_count
export class ValidationCounter extends Stream.Transform {
    private _targetNumVotes : number;
    private _buffer : Map<string, ValidationCount>;

    constructor(options : ValidationCounterOptions) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._targetNumVotes = options.targetNumVotes;
        this._buffer = new Map;
    }

    _transform(row : ParsedParaphrase & { vote : string }, encoding : BufferEncoding, callback : () => void) {
        const id = row.id;

        let count = this._buffer.get(id);
        if (!count) {
            this._buffer.set(id, count = {
                id,
                synthetic_id: row.synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrase: row.paraphrase,
                same_count: 0,
                diff_count: 0
            });
        }

        if (row.vote === 'same')
            count.same_count ++;
        else
            count.diff_count ++;

        if (count.same_count + count.diff_count >= this._targetNumVotes) {
            this.push(count);
            this._buffer.delete(id);
        }
        callback();
    }

    _flush(callback : () => void) {
        for (const count of this._buffer.values())
            this.push(count);

        this._buffer.clear();
        callback();
    }
}


export class ValidationRejecter extends Stream.Transform {
    private _sentencesPerTask : number;

    constructor(options : ValidationRejecterOptions) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._sentencesPerTask = options.sentencesPerTask;
    }

    _transform(row : Record<string, string>, encoding : BufferEncoding, callback : (err : Error|null, row : Record<string, string>) => void) {
        let incorrect = 0;
        for (let i = 0; i < this._sentencesPerTask; i++) {
            const indexSame = row[`Input.index_same${i+1}`];
            const indexDifferent = row[`Input.index_diff${i+1}`];
            const answerSame = row[`Answer.${i+1}-${indexSame}`];
            const answerDifferent = row[`Answer.${i+1}-${indexDifferent}`];
            if (answerSame !== 'same')
                incorrect++;
            if (answerDifferent !== 'different')
                incorrect++;
        }

        if (incorrect >= 2) {
            row['Approve'] = '';
            row['Reject'] = '2 or more mistakes in the sanity checks hidden among the questions.';
        } else {
            row['Approve'] = 'x';
            row['Reject'] = '';
        }

        callback(null, row);
    }

    _flush(callback : () => void) {
        process.nextTick(callback);
    }
}


export class ParaphrasingRejecter extends Stream.Transform {
    private _schemas : SchemaRetriever;
    private _langPack : I18n.LanguagePack;
    private _tokenizer : I18n.BaseTokenizer;

    private _locale : string;
    private _timezone : string;
    private _sentencesPerTask : number;
    private _paraphrasesPerSentence : number;
    private _contextual : boolean;

    private _counter : Statistics;
    private _id : number;

    constructor(schemaRetriever : SchemaRetriever,
                options : ParaphrasingRejecterOptions) {
        super({
            readableObjectMode: true,
            writableObjectMode: true
        });

        this._schemas = schemaRetriever;
        this._langPack = I18n.get(options.locale);
        this._tokenizer = this._langPack.getTokenizer();

        this._locale = options.locale;
        this._timezone = options.timezone;
        this._sentencesPerTask = options.sentencesPerTask;
        this._paraphrasesPerSentence = options.paraphrasesPerSentence;
        this._contextual = options.contextual;

        this._counter = {
            'good': 0,
            'no_idea': 0,
            'values': 0,
            'quoting': 0,
            'manual': 0
        };

        this._id = 0;
    }

    private async _validate(paraobj : ParsedParaphrase) {
        const paraphrase = new ParaphraseValidator(this._schemas, this._langPack, this._tokenizer, this._locale,
            this._timezone, paraobj, this._counter, false);

        try {
            await paraphrase.clean();
            if (paraphrase.isValid())
                return paraobj;
            else
                return null;
        } catch(e) {
            console.error(`Failed paraphrase ${paraobj.id} (${paraobj.synthetic_id}): ${e.message}`);
            return null;
        }
    }

    async _doTransform(row : Record<string, string>) : Promise<Record<string, string>> {
        const minibatch : ParsedParaphrase[] = [];

        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            let context, context_utterance, assistant_action;
            if (this._contextual) {
                context = row[`Input.context${i+1}`];
                context_utterance = row[`Input.context_utterance${i+1}`];
                assistant_action = row[`Input.assistant_action${i+1}`];
            }

            for (let j = 0; j < this._paraphrasesPerSentence; j++) {
                const paraphrase = row[`Answer.Paraphrase${i+1}-${j+1}`];
                const id = (this._contextual ? 'C' : '') + this._id++;

                let paraobj : ParsedParaphrase;
                if (this._contextual) {
                    paraobj = {
                        id, synthetic_id, synthetic,
                        context, context_utterance, assistant_action,
                        target_code, paraphrase
                    };
                } else {
                    paraobj = {
                        id, synthetic_id, synthetic, target_code, paraphrase
                    };
                }
                minibatch.push(paraobj);
            }
        }

        const validated = (await Promise.all(minibatch.map((paraobj) => {
            return this._validate(paraobj);
        }))).filter(<T>(c : T) : c is Exclude<T, null> => c !== null);

        if (validated.length < this._sentencesPerTask * this._paraphrasesPerSentence - 2) {
            row['Approve'] = '';
            row['Reject'] = `Failed to give reasonable result or failed to follow the instruction in at least 2 of ${this._sentencesPerTask * this._paraphrasesPerSentence} paraphrases`;
        } else {
            row['Approve'] = 'x';
            row['Reject'] = '';
        }
        return row;
    }

    _transform(row : Record<string, string>, encoding : BufferEncoding, callback : (err : Error|null, row ?: Record<string, string>) => void) {
        this._doTransform(row).then(
            (row) => callback(null, row),
            (err) => callback(err)
        );
    }

    _flush(callback : () => void) {
        process.nextTick(callback);
    }
}


export interface ParsedParaphrase {
    id : string;
    synthetic_id : string;
    synthetic : string;
    context ?: string;
    context_utterance ?: string;
    assistant_action ?: string;
    target_code : string;
    paraphrase : string;
}


interface ParaphrasingParserOptions {
    sentencesPerTask : number;
    paraphrasesPerSentence : number;
    contextual : boolean;
    skipRejected : boolean;
}


export interface AccumulatedParaphrases {
    synthetic_id : string;
    synthetic : string;
    target_code : string;
    paraphrases : Array<{ id : string; paraphrase : string }>;
}


interface ValidationParserOptions {
    sentencesPerTask : number;
    targetSize : number;
    skipRejected : boolean;
}


interface ValidationCounterOptions {
    targetNumVotes : number;
}


export interface ValidationCount {
    id : string;
    synthetic_id : string;
    synthetic : string;
    target_code : string;
    paraphrase : string;
    same_count : number;
    diff_count : number;
}


interface ValidationRejecterOptions {
    sentencesPerTask : number;
}


interface ParaphrasingRejecterOptions {
    locale : string;
    timezone : string;
    sentencesPerTask : number;
    paraphrasesPerSentence : number;
    contextual : boolean;
}


_transform(row : Record<string, string>, encoding : BufferEncoding, callback : () => void) {
        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            let context, context_utterance, assistant_action;
            if (this._contextual) {
                context = row[`Input.context${i+1}`];
                context_utterance = row[`Input.context_utterance${i+1}`];
                assistant_action = row[`Input.assistant_action${i+1}`];
            }

            for (let j = 0; j < this._paraphrasesPerSentence; j++) {
                const paraphrase = row[`Answer.Paraphrase${i+1}-${j+1}`];
                const id = (this._contextual ? 'C' : '') + this._id++;
                if (this._contextual) {
                    this.push({
                        id, synthetic_id, synthetic,
                        context, context_utterance, assistant_action,
                        target_code, paraphrase
                    });
                } else {
                    this.push({
                        id, synthetic_id, synthetic, target_code, paraphrase
                    });
                }
            }
        }
        callback();
    }


_flush(callback : () => void) {
        process.nextTick(callback);
    }


_transform(row : ParsedParaphrase, encoding : BufferEncoding, callback : () => void) {
        const synthetic_id = row.synthetic_id;

        let buffer = this._buffers.get(synthetic_id);
        if (!buffer) {
            this._synthetics.set(synthetic_id, row);
            this._buffers.set(synthetic_id, buffer = []);
        }

        buffer.push({
            id: row.id,
            paraphrase: row.paraphrase
        });

        if (buffer.length >= this._totalParaphrasesPerSentence) {
            this.push({
                synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrases: buffer
            });
            this._buffers.delete(synthetic_id);
        }
        callback();
    }


_flush(callback : () => void) {
        for (const [synthetic_id, buffer] of this._buffers) {
            const row = this._synthetics.get(synthetic_id)!;
            this.push({
                synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrases: buffer
            });
        }

        this._buffers.clear();
        this._synthetics.clear();
        callback();
    }


_transform(row : Record<string, string>, encoding : BufferEncoding, callback : () => void) {
        if (this._skipRejected && row['Reject']) {
            callback();
            return;
        }

        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            // + 2 to account for same/different paraphrases (sanity checks)
            // mixed in with the real data
            for (let j = 0; j < this._targetSize + 2; j++) {
                const paraphrase = row[`Input.paraphrase${i+1}-${j+1}`];
                const id = row[`Input.id${i+1}-${j+1}`];
                if (id === '-same' || id === '-different')
                    continue;

                const vote = row[`Answer.${i+1}-${j+1}`];
                this.push({
                    id, synthetic_id, synthetic, target_code, paraphrase, vote
                });
            }
        }
        callback();
    }


_transform(row : ParsedParaphrase & { vote : string }, encoding : BufferEncoding, callback : () => void) {
        const id = row.id;

        let count = this._buffer.get(id);
        if (!count) {
            this._buffer.set(id, count = {
                id,
                synthetic_id: row.synthetic_id,
                synthetic: row.synthetic,
                target_code: row.target_code,
                paraphrase: row.paraphrase,
                same_count: 0,
                diff_count: 0
            });
        }

        if (row.vote === 'same')
            count.same_count ++;
        else
            count.diff_count ++;

        if (count.same_count + count.diff_count >= this._targetNumVotes) {
            this.push(count);
            this._buffer.delete(id);
        }
        callback();
    }


_flush(callback : () => void) {
        for (const count of this._buffer.values())
            this.push(count);

        this._buffer.clear();
        callback();
    }


_transform(row : Record<string, string>, encoding : BufferEncoding, callback : (err : Error|null, row : Record<string, string>) => void) {
        let incorrect = 0;
        for (let i = 0; i < this._sentencesPerTask; i++) {
            const indexSame = row[`Input.index_same${i+1}`];
            const indexDifferent = row[`Input.index_diff${i+1}`];
            const answerSame = row[`Answer.${i+1}-${indexSame}`];
            const answerDifferent = row[`Answer.${i+1}-${indexDifferent}`];
            if (answerSame !== 'same')
                incorrect++;
            if (answerDifferent !== 'different')
                incorrect++;
        }

        if (incorrect >= 2) {
            row['Approve'] = '';
            row['Reject'] = '2 or more mistakes in the sanity checks hidden among the questions.';
        } else {
            row['Approve'] = 'x';
            row['Reject'] = '';
        }

        callback(null, row);
    }


private async _validate(paraobj : ParsedParaphrase) {
        const paraphrase = new ParaphraseValidator(this._schemas, this._langPack, this._tokenizer, this._locale,
            this._timezone, paraobj, this._counter, false);

        try {
            await paraphrase.clean();
            if (paraphrase.isValid())
                return paraobj;
            else
                return null;
        } catch(e) {
            console.error(`Failed paraphrase ${paraobj.id} (${paraobj.synthetic_id}): ${e.message}`);
            return null;
        }
    }


async _doTransform(row : Record<string, string>) : Promise<Record<string, string>> {
        const minibatch : ParsedParaphrase[] = [];

        for (let i = 0; i < this._sentencesPerTask; i++) {
            const target_code = row[`Input.thingtalk${i+1}`];
            const synthetic = row[`Input.sentence${i+1}`];
            const synthetic_id = row[`Input.id${i+1}`];

            let context, context_utterance, assistant_action;
            if (this._contextual) {
                context = row[`Input.context${i+1}`];
                context_utterance = row[`Input.context_utterance${i+1}`];
                assistant_action = row[`Input.assistant_action${i+1}`];
            }

            for (let j = 0; j < this._paraphrasesPerSentence; j++) {
                const paraphrase = row[`Answer.Paraphrase${i+1}-${j+1}`];
                const id = (this._contextual ? 'C' : '') + this._id++;

                let paraobj : ParsedParaphrase;
                if (this._contextual) {
                    paraobj = {
                        id, synthetic_id, synthetic,
                        context, context_utterance, assistant_action,
                        target_code, paraphrase
                    };
                } else {
                    paraobj = {
                        id, synthetic_id, synthetic, target_code, paraphrase
                    };
                }
                minibatch.push(paraobj);
            }
        }

        const validated = (await Promise.all(minibatch.map((paraobj) => {
            return this._validate(paraobj);
        }))).filter(<T>(c : T) : c is Exclude<T, null> => c !== null);

        if (validated.length < this._sentencesPerTask * this._paraphrasesPerSentence - 2) {
            row['Approve'] = '';
            row['Reject'] = `Failed to give reasonable result or failed to follow the instruction in at least 2 of ${this._sentencesPerTask * this._paraphrasesPerSentence} paraphrases`;
        } else {
            row['Approve'] = 'x';
            row['Reject'] = '';
        }
        return row;
    }


_transform(row : Record<string, string>, encoding : BufferEncoding, callback : (err : Error|null, row ?: Record<string, string>) => void) {
        this._doTransform(row).then(
            (row) => callback(null, row),
            (err) => callback(err)
        );
    }


export function createPlatformFactory(
    parentPlatformFactory: ((extraProviders?: StaticProvider[]) => PlatformRef) | null,
    name: string,
    providers: StaticProvider[] = []
): (extraProviders?: StaticProvider[]) =>
        PlatformRef {
    const desc = `Platform: ${name}`;
    const marker = new InjectionToken(desc);
    return (extraProviders: StaticProvider[] = []) => {
        let platform = getPlatform();
        if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
            if (parentPlatformFactory) {
                const allProviders = providers
                    .concat(extraProviders)
                    .concat({ provide: marker, useValue: true })
                parentPlatformFactory(allProviders);
            } else {
                const injectedProviders: StaticProvider[] =
                    providers
                        .concat(extraProviders)
                        .concat({ provide: marker, useValue: true });
                createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
            }
        }
        return assertPlatform(marker);
    };
}


export function assertPlatform(requiredToken: any): PlatformRef {
    const platform = getPlatform();
    if (!platform) {
        throw new Error('No platform exists!');
    }
    if (!platform.injector.get(requiredToken, null)) {
        throw new Error(
            'A platform with a different configuration has been created. Please destroy it first.');
    }
    return platform;
}


(extraProviders: StaticProvider[] = []) => {
        let platform = getPlatform();
        if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
            if (parentPlatformFactory) {
                const allProviders = providers
                    .concat(extraProviders)
                    .concat({ provide: marker, useValue: true })
                parentPlatformFactory(allProviders);
            } else {
                const injectedProviders: StaticProvider[] =
                    providers
                        .concat(extraProviders)
                        .concat({ provide: marker, useValue: true });
                createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
            }
        }
        return assertPlatform(marker);
    }


export interface ModalPopupProps extends IModalPropTypes {
  styles?: any
  children?: any
}


() => {
    it('should test some numbers', async () => {
        // Given
        const numbers = [
            {
                num: new BigNumber(0.1),
                decimals: 4,
                expectedDiff: '000',
                expectedNum: '0.1',
            },
            {
                num: new BigNumber(0.02),
                decimals: 4,
                expectedDiff: '00',
                expectedNum: '0.02',
            },
            {
                num: new BigNumber(4),
                decimals: 4,
                expectedDiff: '.0000',
                expectedNum: '4',
            },
            {
                num: new BigNumber(2478),
                decimals: 4,
                expectedDiff: '.0000',
                expectedNum: '2478',
            },
            {
                num: new BigNumber(10.1234),
                decimals: 4,
                expectedDiff: '',
                expectedNum: '10.1234',
            },
            {
                num: ZERO,
                decimals: 4,
                expectedDiff: '',
                expectedNum: '0.0000',
            },
            {
                num: new BigNumber(100.676767),
                decimals: 4,
                expectedDiff: '',
                expectedNum: '100.6768',
            },
            {
                num: ZERO,
                decimals: 4,
                expectedDiff: '',
                expectedNum: '0.0000',
            },
        ];

        for (const numberObject of numbers) {
            const { num, decimals } = numberObject;

            // When
            const result = padRightSplitted(num, decimals);

            // Then
            expect(result.num).toEqual(numberObject.expectedNum);
            expect(result.diff).toEqual(numberObject.expectedDiff);
        }
    });
}


async () => {
        // Given
        const numbers = [
            {
                num: new BigNumber(0.1),
                decimals: 4,
                expectedDiff: '000',
                expectedNum: '0.1',
            },
            {
                num: new BigNumber(0.02),
                decimals: 4,
                expectedDiff: '00',
                expectedNum: '0.02',
            },
            {
                num: new BigNumber(4),
                decimals: 4,
                expectedDiff: '.0000',
                expectedNum: '4',
            },
            {
                num: new BigNumber(2478),
                decimals: 4,
                expectedDiff: '.0000',
                expectedNum: '2478',
            },
            {
                num: new BigNumber(10.1234),
                decimals: 4,
                expectedDiff: '',
                expectedNum: '10.1234',
            },
            {
                num: ZERO,
                decimals: 4,
                expectedDiff: '',
                expectedNum: '0.0000',
            },
            {
                num: new BigNumber(100.676767),
                decimals: 4,
                expectedDiff: '',
                expectedNum: '100.6768',
            },
            {
                num: ZERO,
                decimals: 4,
                expectedDiff: '',
                expectedNum: '0.0000',
            },
        ];

        for (const numberObject of numbers) {
            const { num, decimals } = numberObject;

            // When
            const result = padRightSplitted(num, decimals);

            // Then
            expect(result.num).toEqual(numberObject.expectedNum);
            expect(result.diff).toEqual(numberObject.expectedDiff);
        }
    }


() => {
        return this.listAllPagingPage(options);
      }


() => {
        return this.listPagingPage(resourceGroupName, options);
      }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<void> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ) => {
      let currentRawResponse:
        | coreClient.FullOperationResponse
        | undefined = undefined;
      const providedCallback = args.options?.onResponse;
      const callback: coreClient.RawResponseCallback = (
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      };
      const updatedArgs = {
        ...args,
        options: {
          ...args.options,
          onResponse: callback
        }
      };
      const flatResponse = await directSendOperation(updatedArgs, spec);
      return {
        flatResponse,
        rawResponse: {
          statusCode: currentRawResponse!.status,
          body: currentRawResponse!.parsedBody,
          headers: currentRawResponse!.headers.toJSON()
        }
      };
    }


(
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<CustomIPPrefixesCreateOrUpdateResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


/**
   * Gets all the custom IP prefixes in a subscription.
   * @param options The options parameters.
   */
public listAll(
    options?: CustomIPPrefixesListAllOptionalParams
  ): PagedAsyncIterableIterator<CustomIpPrefix> {
    const iter = this.listAllPagingAll(options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: () => {
        return this.listAllPagingPage(options);
      }
    };
  }


next() {
        return iter.next();
      }


[Symbol.asyncIterator]() {
        return this;
      }


private async *listAllPagingPage(
    options?: CustomIPPrefixesListAllOptionalParams
  ): AsyncIterableIterator<CustomIpPrefix[]> {
    let result = await this._listAll(options);
    yield result.value || [];
    let continuationToken = result.nextLink;
    while (continuationToken) {
      result = await this._listAllNext(continuationToken, options);
      continuationToken = result.nextLink;
      yield result.value || [];
    }
  }


private async *listAllPagingAll(
    options?: CustomIPPrefixesListAllOptionalParams
  ): AsyncIterableIterator<CustomIpPrefix> {
    for await (const page of this.listAllPagingPage(options)) {
      yield* page;
    }
  }


/**
   * Gets all custom IP prefixes in a resource group.
   * @param resourceGroupName The name of the resource group.
   * @param options The options parameters.
   */
public list(
    resourceGroupName: string,
    options?: CustomIPPrefixesListOptionalParams
  ): PagedAsyncIterableIterator<CustomIpPrefix> {
    const iter = this.listPagingAll(resourceGroupName, options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: () => {
        return this.listPagingPage(resourceGroupName, options);
      }
    };
  }


private async *listPagingPage(
    resourceGroupName: string,
    options?: CustomIPPrefixesListOptionalParams
  ): AsyncIterableIterator<CustomIpPrefix[]> {
    let result = await this._list(resourceGroupName, options);
    yield result.value || [];
    let continuationToken = result.nextLink;
    while (continuationToken) {
      result = await this._listNext(
        resourceGroupName,
        continuationToken,
        options
      );
      continuationToken = result.nextLink;
      yield result.value || [];
    }
  }


private async *listPagingAll(
    resourceGroupName: string,
    options?: CustomIPPrefixesListOptionalParams
  ): AsyncIterableIterator<CustomIpPrefix> {
    for await (const page of this.listPagingPage(resourceGroupName, options)) {
      yield* page;
    }
  }


/**
   * Deletes the specified custom IP prefix.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the CustomIpPrefix.
   * @param options The options parameters.
   */
async beginDelete(
    resourceGroupName: string,
    customIpPrefixName: string,
    options?: CustomIPPrefixesDeleteOptionalParams
  ): Promise<PollerLike<PollOperationState<void>, void>> {
    const directSendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<void> => {
      return this.client.sendOperationRequest(args, spec);
    };
    const sendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ) => {
      let currentRawResponse:
        | coreClient.FullOperationResponse
        | undefined = undefined;
      const providedCallback = args.options?.onResponse;
      const callback: coreClient.RawResponseCallback = (
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      };
      const updatedArgs = {
        ...args,
        options: {
          ...args.options,
          onResponse: callback
        }
      };
      const flatResponse = await directSendOperation(updatedArgs, spec);
      return {
        flatResponse,
        rawResponse: {
          statusCode: currentRawResponse!.status,
          body: currentRawResponse!.parsedBody,
          headers: currentRawResponse!.headers.toJSON()
        }
      };
    };

    const lro = new CoreClientLro(
      sendOperation,
      { resourceGroupName, customIpPrefixName, options },
      deleteOperationSpec,
      "location"
    );
    return new LroEngine(lro, { intervalInMs: options?.updateIntervalInMs });
  }


/**
   * Deletes the specified custom IP prefix.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the CustomIpPrefix.
   * @param options The options parameters.
   */
async beginDeleteAndWait(
    resourceGroupName: string,
    customIpPrefixName: string,
    options?: CustomIPPrefixesDeleteOptionalParams
  ): Promise<void> {
    const poller = await this.beginDelete(
      resourceGroupName,
      customIpPrefixName,
      options
    );
    return poller.pollUntilDone();
  }


/**
   * Gets the specified custom IP prefix in a specified resource group.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the custom IP prefix.
   * @param options The options parameters.
   */
get(
    resourceGroupName: string,
    customIpPrefixName: string,
    options?: CustomIPPrefixesGetOptionalParams
  ): Promise<CustomIPPrefixesGetResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, customIpPrefixName, options },
      getOperationSpec
    );
  }


/**
   * Creates or updates a custom IP prefix.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the custom IP prefix.
   * @param parameters Parameters supplied to the create or update custom IP prefix operation.
   * @param options The options parameters.
   */
async beginCreateOrUpdate(
    resourceGroupName: string,
    customIpPrefixName: string,
    parameters: CustomIpPrefix,
    options?: CustomIPPrefixesCreateOrUpdateOptionalParams
  ): Promise<
    PollerLike<
      PollOperationState<CustomIPPrefixesCreateOrUpdateResponse>,
      CustomIPPrefixesCreateOrUpdateResponse
    >
  > {
    const directSendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<CustomIPPrefixesCreateOrUpdateResponse> => {
      return this.client.sendOperationRequest(args, spec);
    };
    const sendOperation = async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ) => {
      let currentRawResponse:
        | coreClient.FullOperationResponse
        | undefined = undefined;
      const providedCallback = args.options?.onResponse;
      const callback: coreClient.RawResponseCallback = (
        rawResponse: coreClient.FullOperationResponse,
        flatResponse: unknown
      ) => {
        currentRawResponse = rawResponse;
        providedCallback?.(rawResponse, flatResponse);
      };
      const updatedArgs = {
        ...args,
        options: {
          ...args.options,
          onResponse: callback
        }
      };
      const flatResponse = await directSendOperation(updatedArgs, spec);
      return {
        flatResponse,
        rawResponse: {
          statusCode: currentRawResponse!.status,
          body: currentRawResponse!.parsedBody,
          headers: currentRawResponse!.headers.toJSON()
        }
      };
    };

    const lro = new CoreClientLro(
      sendOperation,
      { resourceGroupName, customIpPrefixName, parameters, options },
      createOrUpdateOperationSpec,
      "location"
    );
    return new LroEngine(lro, { intervalInMs: options?.updateIntervalInMs });
  }


/**
   * Creates or updates a custom IP prefix.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the custom IP prefix.
   * @param parameters Parameters supplied to the create or update custom IP prefix operation.
   * @param options The options parameters.
   */
async beginCreateOrUpdateAndWait(
    resourceGroupName: string,
    customIpPrefixName: string,
    parameters: CustomIpPrefix,
    options?: CustomIPPrefixesCreateOrUpdateOptionalParams
  ): Promise<CustomIPPrefixesCreateOrUpdateResponse> {
    const poller = await this.beginCreateOrUpdate(
      resourceGroupName,
      customIpPrefixName,
      parameters,
      options
    );
    return poller.pollUntilDone();
  }


/**
   * Updates custom IP prefix tags.
   * @param resourceGroupName The name of the resource group.
   * @param customIpPrefixName The name of the custom IP prefix.
   * @param parameters Parameters supplied to update custom IP prefix tags.
   * @param options The options parameters.
   */
updateTags(
    resourceGroupName: string,
    customIpPrefixName: string,
    parameters: TagsObject,
    options?: CustomIPPrefixesUpdateTagsOptionalParams
  ): Promise<CustomIPPrefixesUpdateTagsResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, customIpPrefixName, parameters, options },
      updateTagsOperationSpec
    );
  }


/**
   * Gets all the custom IP prefixes in a subscription.
   * @param options The options parameters.
   */
private _listAll(
    options?: CustomIPPrefixesListAllOptionalParams
  ): Promise<CustomIPPrefixesListAllResponse> {
    return this.client.sendOperationRequest({ options }, listAllOperationSpec);
  }


/**
   * Gets all custom IP prefixes in a resource group.
   * @param resourceGroupName The name of the resource group.
   * @param options The options parameters.
   */
private _list(
    resourceGroupName: string,
    options?: CustomIPPrefixesListOptionalParams
  ): Promise<CustomIPPrefixesListResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, options },
      listOperationSpec
    );
  }


/**
   * ListAllNext
   * @param nextLink The nextLink from the previous successful call to the ListAll method.
   * @param options The options parameters.
   */
private _listAllNext(
    nextLink: string,
    options?: CustomIPPrefixesListAllNextOptionalParams
  ): Promise<CustomIPPrefixesListAllNextResponse> {
    return this.client.sendOperationRequest(
      { nextLink, options },
      listAllNextOperationSpec
    );
  }


/**
   * ListNext
   * @param resourceGroupName The name of the resource group.
   * @param nextLink The nextLink from the previous successful call to the List method.
   * @param options The options parameters.
   */
private _listNext(
    resourceGroupName: string,
    nextLink: string,
    options?: CustomIPPrefixesListNextOptionalParams
  ): Promise<CustomIPPrefixesListNextResponse> {
    return this.client.sendOperationRequest(
      { resourceGroupName, nextLink, options },
      listNextOperationSpec
    );
  }


async function execWithTransaction(
  fn: (transaction: Transaction) => Promise<void>,
  transaction?: Transaction,
) {
  if (transaction) {
    return fn(transaction);
  } else {
    await sequelize.transaction(fn);
  }
}


(req: Request, res: Response) => ({
    ...req,
    ...res,
    prisma,
  })


() => console.log(`Server is running on ${HOST}${PORT}`)


export function getCartoonParams(ctx: ThemeRegistryContext, structure: Structure) {
    const params = PD.clone(CartoonParams);
    let hasNucleotides = false;
    let hasGaps = false;
    structure.units.forEach(u => {
        if (!hasNucleotides && Unit.isAtomic(u) && u.nucleotideElements.length) hasNucleotides = true;
        if (!hasGaps && u.gapElements.length) hasGaps = true;
    });
    params.visuals.defaultValue = ['polymer-trace'];
    if (hasNucleotides) params.visuals.defaultValue.push('nucleotide-ring');
    if (hasGaps) params.visuals.defaultValue.push('polymer-gap');
    return params;
}


export function CartoonRepresentation(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, CartoonParams>): CartoonRepresentation {
    return Representation.createMulti('Cartoon', ctx, getParams, StructureRepresentationStateBuilder, CartoonVisuals as unknown as Representation.Def<Structure, CartoonParams>);
}


(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, PolymerTraceParams>) => UnitsRepresentation('Polymer trace mesh', ctx, getParams, PolymerTraceVisual)


(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, PolymerGapParams>) => UnitsRepresentation('Polymer gap cylinder', ctx, getParams, PolymerGapVisual)


(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, NucleotideBlockParams>) => UnitsRepresentation('Nucleotide block mesh', ctx, getParams, NucleotideBlockVisual)


(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, NucleotideRingParams>) => UnitsRepresentation('Nucleotide ring mesh', ctx, getParams, NucleotideRingVisual)


(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, PolymerDirectionParams>) => UnitsRepresentation('Polymer direction wedge', ctx, getParams, PolymerDirectionVisual)


u => {
        if (!hasNucleotides && Unit.isAtomic(u) && u.nucleotideElements.length) hasNucleotides = true;
        if (!hasGaps && u.gapElements.length) hasGaps = true;
    }


(structure: Structure) => structure.polymerResidueCount > 0


async (ctx: CustomProperty.Context, structure: Structure) => {
            await SecondaryStructureProvider.attach(ctx, structure, void 0, true);
            for (const m of structure.models) {
                await HelixOrientationProvider.attach(ctx, m, void 0, true);
            }
        }


(data) => {
            SecondaryStructureProvider.ref(data, false);
            for (const m of data.models) {
                HelixOrientationProvider.ref(m, false);
            }
        }


export type CartoonParams = typeof CartoonParams


export type CartoonRepresentation = StructureRepresentation<CartoonParams>


export interface ViewPropsAndroid {
    /**
     * Views that are only used to layout their children or otherwise don't draw anything
     * may be automatically removed from the native hierarchy as an optimization.
     * Set this property to false to disable this optimization and ensure that this View exists in the native view hierarchy.
     */
    collapsable?: boolean;

    /**
     * Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior.
     * The default (false) falls back to drawing the component and its children
     * with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value.
     * This default may be noticeable and undesired in the case where the View you are setting an opacity on
     * has multiple overlapping elements (e.g. multiple overlapping Views, or text and a background).
     *
     * Rendering offscreen to preserve correct alpha behavior is extremely expensive
     * and hard to debug for non-native developers, which is why it is not turned on by default.
     * If you do need to enable this property for an animation,
     * consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame).
     * If that property is enabled, this View will be rendered off-screen once,
     * saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU.
     */
    needsOffscreenAlphaCompositing?: boolean;

    /**
     * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU.
     *
     * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale:
     * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be
     * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation.
     */
    renderToHardwareTextureAndroid?: boolean;

    /**
     * (Android-only) Sets the elevation of a view, using Android's underlying elevation API.
     *
     * This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.
     */
    elevation?: number;
  }


@Component({
  selector: 'app-pages',
  templateUrl: './pages.component.html'
})
export class PagesComponent implements OnInit {
  constructor(public app: AppService, public wpx: WpxService) {}

  ngOnInit(): void {
    this.wpx.loadPages().subscribe(() => {});
  }
}


ngOnInit(): void {
    this.wpx.loadPages().subscribe(() => {});
  }


export default class Earn implements View {

    private container: DomNode;

    constructor() {
        Layout.current.content.append(this.container = el("#earn",
            el("h2", "Earn"),
            el("p", "Earn MaidCoin!"),
            new FarmList(),
        ));
    }

    public changeParams(params: ViewParams, uri: string): void { }

    public close(): void {
        this.container.delete();
    }
}


public changeParams(params: ViewParams, uri: string): void { }


public close(): void {
        this.container.delete();
    }


/**
 * PDU payload base TLV object class for responses.
 */
export abstract class ResponsePayload extends PduPayload {
  private status: IntegerTag;
  private errorMessage: StringTag | null = null;

  /**
   * PDU payload base TLV object class constructor.
   * @param tlvTag TLV object.
   */
  protected constructor(tlvTag: TlvTag) {
    super(tlvTag);
  }

  /**
   * Get payload status.
   * @returns Payload status.
   */
  public getStatus(): BigInteger {
    return this.status.getValue();
  }

  /**
   * Get error message.
   * @returns Error message.
   */
  public getErrorMessage(): string | null {
    return this.errorMessage !== null ? this.errorMessage.getValue() : null;
  }

  /**
   * Parse child element to correct object.
   * @param tlvTag TLV object.
   * @returns TLV object.
   */
  protected parseChild(tlvTag: TlvTag): TlvTag {
    switch (tlvTag.id) {
      case PDU_PAYLOAD_CONSTANTS.StatusTagType:
        return (this.status = new IntegerTag(tlvTag));
      case PDU_PAYLOAD_CONSTANTS.ErrorMessageTagType:
        return (this.errorMessage = new StringTag(tlvTag));
      default:
        return this.validateUnknownTlvTag(tlvTag);
    }
  }

  /**
   * Validate current TLV object format.
   */
  protected validate(): void {
    if (this.getCount(PDU_PAYLOAD_CONSTANTS.StatusTagType) !== 1) {
      throw new TlvError('Exactly one status code must exist in response payload.');
    }

    if (this.getCount(PDU_PAYLOAD_CONSTANTS.ErrorMessageTagType) > 1) {
      throw new TlvError('Only one error message is allowed in response payload.');
    }
  }
}


/**
   * Get payload status.
   * @returns Payload status.
   */
public getStatus(): BigInteger {
    return this.status.getValue();
  }


/**
   * Get error message.
   * @returns Error message.
   */
public getErrorMessage(): string | null {
    return this.errorMessage !== null ? this.errorMessage.getValue() : null;
  }


/**
   * Parse child element to correct object.
   * @param tlvTag TLV object.
   * @returns TLV object.
   */
protected parseChild(tlvTag: TlvTag): TlvTag {
    switch (tlvTag.id) {
      case PDU_PAYLOAD_CONSTANTS.StatusTagType:
        return (this.status = new IntegerTag(tlvTag));
      case PDU_PAYLOAD_CONSTANTS.ErrorMessageTagType:
        return (this.errorMessage = new StringTag(tlvTag));
      default:
        return this.validateUnknownTlvTag(tlvTag);
    }
  }


/**
   * Validate current TLV object format.
   */
protected validate(): void {
    if (this.getCount(PDU_PAYLOAD_CONSTANTS.StatusTagType) !== 1) {
      throw new TlvError('Exactly one status code must exist in response payload.');
    }

    if (this.getCount(PDU_PAYLOAD_CONSTANTS.ErrorMessageTagType) > 1) {
      throw new TlvError('Only one error message is allowed in response payload.');
    }
  }


export abstract class AbstractWorkerThread implements NamedServiceInterface, InjectorAwareInterface {

  protected injector: Injector;

  setInjector(injector: Injector): void {
    this.injector = injector;
  }

  abstract run(): Promise<void>;

  abstract getName(): string;
}


setInjector(injector: Injector): void {
    this.injector = injector;
  }


abstract run(): Promise<void>;


abstract getName(): string;


() => {
  it('renders', async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toHaveClass('st-lucide-icon');
  });

  it('renders one-word props', async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact stroke="blue"></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toEqualAttribute('stroke', 'blue');

    const svg = await page.find('icon-contact > svg');
    expect(svg).toEqualAttribute('stroke', 'blue');
  });

  it('renders dashed props', async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact stroke-width="2"></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toEqualAttribute('stroke-width', 2);

    const svg = await page.find('icon-contact > svg');
    expect(svg).toEqualAttribute('stroke-width', 2);
  });
}


async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toHaveClass('st-lucide-icon');
  }


async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact stroke="blue"></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toEqualAttribute('stroke', 'blue');

    const svg = await page.find('icon-contact > svg');
    expect(svg).toEqualAttribute('stroke', 'blue');
  }


async () => {
    const page = await newE2EPage();
    await page.setContent('<icon-contact stroke-width="2"></icon-contact>');

    const element = await page.find('icon-contact');
    expect(element).toHaveClass('hydrated');
    expect(element).toEqualAttribute('stroke-width', 2);

    const svg = await page.find('icon-contact > svg');
    expect(svg).toEqualAttribute('stroke-width', 2);
  }


() =>
    ({
      __esModule: true,
      ...jest.requireActual('@angular-devkit/schematics'),
      // For some reason TS (BUT only via ts-jest, not in VSCode) has an issue with this spread usage of requireActual(), so suppressing with any
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } as any)


() => {
  let appTree: UnitTestTree;

  beforeEach(() => {
    appTree = new UnitTestTree(Tree.empty());
    appTree.create('package.json', JSON.stringify({}));
    appTree.create(
      'angular.json',
      JSON.stringify({
        $schema: './node_modules/@angular/cli/lib/config/schema.json',
        version: 1,
        newProjectRoot: 'projects',
        projects: {},
      }),
    );
  });

  it('should pass all the given options directly to the @schematics/angular schematic', async () => {
    const spy = jest.spyOn(angularDevkitSchematics, 'externalSchematic');
    const options = {
      name: 'bar',
    };

    expect(spy).not.toHaveBeenCalled();

    await schematicRunner
      .runSchematicAsync('library', options, appTree)
      .toPromise();

    expect(spy).toHaveBeenCalledTimes(1);
    expect(spy).toHaveBeenCalledWith(
      '@schematics/angular',
      'library',
      expect.objectContaining(options),
    );
  });

  it('should change the lint target to use the @angular-eslint builder', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('application', { name: 'bar' }, appTree)
      .toPromise();

    expect(readJsonInTree(tree, 'angular.json').projects.bar.architect.lint)
      .toMatchInlineSnapshot(`
      Object {
        "builder": "@angular-eslint/builder:lint",
        "options": Object {
          "lintFilePatterns": Array [
            "projects/bar/**/*.ts",
            "projects/bar/**/*.html",
          ],
        },
      }
    `);
  });

  it('should add the ESLint config for the project and delete the TSLint config', async () => {
    const tree = await schematicRunner
      .runSchematicAsync(
        'application',
        { name: 'bar', prefix: 'something-else-custom' },
        appTree,
      )
      .toPromise();

    expect(tree.exists('projects/bar/tslint.json')).toBe(false);
    expect(tree.read('projects/bar/.eslintrc.json')?.toString())
      .toMatchInlineSnapshot(`
      "{
        \\"extends\\": \\"../../.eslintrc.json\\",
        \\"ignorePatterns\\": [
          \\"!**/*\\"
        ],
        \\"overrides\\": [
          {
            \\"files\\": [
              \\"*.ts\\"
            ],
            \\"parserOptions\\": {
              \\"project\\": [
                \\"projects/bar/tsconfig.app.json\\",
                \\"projects/bar/tsconfig.spec.json\\",
                \\"projects/bar/e2e/tsconfig.json\\"
              ],
              \\"createDefaultProgram\\": true
            },
            \\"rules\\": {
              \\"@angular-eslint/directive-selector\\": [
                \\"error\\",
                {
                  \\"type\\": \\"attribute\\",
                  \\"prefix\\": \\"something-else-custom\\",
                  \\"style\\": \\"camelCase\\"
                }
              ],
              \\"@angular-eslint/component-selector\\": [
                \\"error\\",
                {
                  \\"type\\": \\"element\\",
                  \\"prefix\\": \\"something-else-custom\\",
                  \\"style\\": \\"kebab-case\\"
                }
              ]
            }
          },
          {
            \\"files\\": [
              \\"*.html\\"
            ],
            \\"rules\\": {}
          }
        ]
      }
      "
    `);
  });
}


() => {
    appTree = new UnitTestTree(Tree.empty());
    appTree.create('package.json', JSON.stringify({}));
    appTree.create(
      'angular.json',
      JSON.stringify({
        $schema: './node_modules/@angular/cli/lib/config/schema.json',
        version: 1,
        newProjectRoot: 'projects',
        projects: {},
      }),
    );
  }


async () => {
    const spy = jest.spyOn(angularDevkitSchematics, 'externalSchematic');
    const options = {
      name: 'bar',
    };

    expect(spy).not.toHaveBeenCalled();

    await schematicRunner
      .runSchematicAsync('library', options, appTree)
      .toPromise();

    expect(spy).toHaveBeenCalledTimes(1);
    expect(spy).toHaveBeenCalledWith(
      '@schematics/angular',
      'library',
      expect.objectContaining(options),
    );
  }


async () => {
    const tree = await schematicRunner
      .runSchematicAsync('application', { name: 'bar' }, appTree)
      .toPromise();

    expect(readJsonInTree(tree, 'angular.json').projects.bar.architect.lint)
      .toMatchInlineSnapshot(`
      Object {
        "builder": "@angular-eslint/builder:lint",
        "options": Object {
          "lintFilePatterns": Array [
            "projects/bar/**/*.ts",
            "projects/bar/**/*.html",
          ],
        },
      }
    `);
  }


async () => {
    const tree = await schematicRunner
      .runSchematicAsync(
        'application',
        { name: 'bar', prefix: 'something-else-custom' },
        appTree,
      )
      .toPromise();

    expect(tree.exists('projects/bar/tslint.json')).toBe(false);
    expect(tree.read('projects/bar/.eslintrc.json')?.toString())
      .toMatchInlineSnapshot(`
      "{
        \\"extends\\": \\"../../.eslintrc.json\\",
        \\"ignorePatterns\\": [
          \\"!**/*\\"
        ],
        \\"overrides\\": [
          {
            \\"files\\": [
              \\"*.ts\\"
            ],
            \\"parserOptions\\": {
              \\"project\\": [
                \\"projects/bar/tsconfig.app.json\\",
                \\"projects/bar/tsconfig.spec.json\\",
                \\"projects/bar/e2e/tsconfig.json\\"
              ],
              \\"createDefaultProgram\\": true
            },
            \\"rules\\": {
              \\"@angular-eslint/directive-selector\\": [
                \\"error\\",
                {
                  \\"type\\": \\"attribute\\",
                  \\"prefix\\": \\"something-else-custom\\",
                  \\"style\\": \\"camelCase\\"
                }
              ],
              \\"@angular-eslint/component-selector\\": [
                \\"error\\",
                {
                  \\"type\\": \\"element\\",
                  \\"prefix\\": \\"something-else-custom\\",
                  \\"style\\": \\"kebab-case\\"
                }
              ]
            }
          },
          {
            \\"files\\": [
              \\"*.html\\"
            ],
            \\"rules\\": {}
          }
        ]
      }
      "
    `);
  }


() => {
  let component: NodeSettingsComponent;
  let fixture: ComponentFixture<NodeSettingsComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [NodeSettingsComponent],
      imports: [
        BrowserAnimationsModule,
        SharedModule,
        StoreModule.forRoot({ root: RootReducer, lnd: LNDReducer, cln: CLNReducer, ecl: ECLReducer })
      ],
      providers: [
        CommonService,
        { provide: LoggerService, useClass: mockLoggerService },
        { provide: DataService, useClass: mockDataService }
      ]
    }).
      compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NodeSettingsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  afterEach(() => {
    TestBed.resetTestingModule();
  });
}


() => {
    TestBed.configureTestingModule({
      declarations: [NodeSettingsComponent],
      imports: [
        BrowserAnimationsModule,
        SharedModule,
        StoreModule.forRoot({ root: RootReducer, lnd: LNDReducer, cln: CLNReducer, ecl: ECLReducer })
      ],
      providers: [
        CommonService,
        { provide: LoggerService, useClass: mockLoggerService },
        { provide: DataService, useClass: mockDataService }
      ]
    }).
      compileComponents();
  }


() => {
    fixture = TestBed.createComponent(NodeSettingsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


() => {
    TestBed.resetTestingModule();
  }


export interface ISyntaxVisitor {
        visitToken(token: ISyntaxToken): any;
        visitSourceUnit(node: SourceUnitSyntax): any;
        visitQualifiedName(node: QualifiedNameSyntax): any;
        visitObjectType(node: ObjectTypeSyntax): any;
        visitFunctionType(node: FunctionTypeSyntax): any;
        visitArrayType(node: ArrayTypeSyntax): any;
        visitConstructorType(node: ConstructorTypeSyntax): any;
        visitGenericType(node: GenericTypeSyntax): any;
        visitTypeQuery(node: TypeQuerySyntax): any;
        visitTupleType(node: TupleTypeSyntax): any;
        visitUnionType(node: UnionTypeSyntax): any;
        visitParenthesizedType(node: ParenthesizedTypeSyntax): any;
        visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): any;
        visitFunctionDeclaration(node: FunctionDeclarationSyntax): any;
        visitModuleDeclaration(node: ModuleDeclarationSyntax): any;
        visitClassDeclaration(node: ClassDeclarationSyntax): any;
        visitEnumDeclaration(node: EnumDeclarationSyntax): any;
        visitImportDeclaration(node: ImportDeclarationSyntax): any;
        visitExportAssignment(node: ExportAssignmentSyntax): any;
        visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): any;
        visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): any;
        visitConstructorDeclaration(node: ConstructorDeclarationSyntax): any;
        visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): any;
        visitGetAccessor(node: GetAccessorSyntax): any;
        visitSetAccessor(node: SetAccessorSyntax): any;
        visitPropertySignature(node: PropertySignatureSyntax): any;
        visitCallSignature(node: CallSignatureSyntax): any;
        visitConstructSignature(node: ConstructSignatureSyntax): any;
        visitIndexSignature(node: IndexSignatureSyntax): any;
        visitMethodSignature(node: MethodSignatureSyntax): any;
        visitBlock(node: BlockSyntax): any;
        visitIfStatement(node: IfStatementSyntax): any;
        visitVariableStatement(node: VariableStatementSyntax): any;
        visitExpressionStatement(node: ExpressionStatementSyntax): any;
        visitReturnStatement(node: ReturnStatementSyntax): any;
        visitSwitchStatement(node: SwitchStatementSyntax): any;
        visitBreakStatement(node: BreakStatementSyntax): any;
        visitContinueStatement(node: ContinueStatementSyntax): any;
        visitForStatement(node: ForStatementSyntax): any;
        visitForInStatement(node: ForInStatementSyntax): any;
        visitEmptyStatement(node: EmptyStatementSyntax): any;
        visitThrowStatement(node: ThrowStatementSyntax): any;
        visitWhileStatement(node: WhileStatementSyntax): any;
        visitTryStatement(node: TryStatementSyntax): any;
        visitLabeledStatement(node: LabeledStatementSyntax): any;
        visitDoStatement(node: DoStatementSyntax): any;
        visitDebuggerStatement(node: DebuggerStatementSyntax): any;
        visitWithStatement(node: WithStatementSyntax): any;
        visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): any;
        visitDeleteExpression(node: DeleteExpressionSyntax): any;
        visitTypeOfExpression(node: TypeOfExpressionSyntax): any;
        visitVoidExpression(node: VoidExpressionSyntax): any;
        visitConditionalExpression(node: ConditionalExpressionSyntax): any;
        visitBinaryExpression(node: BinaryExpressionSyntax): any;
        visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): any;
        visitMemberAccessExpression(node: MemberAccessExpressionSyntax): any;
        visitInvocationExpression(node: InvocationExpressionSyntax): any;
        visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): any;
        visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): any;
        visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): any;
        visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): any;
        visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): any;
        visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): any;
        visitCastExpression(node: CastExpressionSyntax): any;
        visitElementAccessExpression(node: ElementAccessExpressionSyntax): any;
        visitFunctionExpression(node: FunctionExpressionSyntax): any;
        visitOmittedExpression(node: OmittedExpressionSyntax): any;
        visitTemplateExpression(node: TemplateExpressionSyntax): any;
        visitTemplateAccessExpression(node: TemplateAccessExpressionSyntax): any;
        visitVariableDeclaration(node: VariableDeclarationSyntax): any;
        visitVariableDeclarator(node: VariableDeclaratorSyntax): any;
        visitArgumentList(node: ArgumentListSyntax): any;
        visitParameterList(node: ParameterListSyntax): any;
        visitTypeArgumentList(node: TypeArgumentListSyntax): any;
        visitTypeParameterList(node: TypeParameterListSyntax): any;
        visitHeritageClause(node: HeritageClauseSyntax): any;
        visitEqualsValueClause(node: EqualsValueClauseSyntax): any;
        visitCaseSwitchClause(node: CaseSwitchClauseSyntax): any;
        visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): any;
        visitElseClause(node: ElseClauseSyntax): any;
        visitCatchClause(node: CatchClauseSyntax): any;
        visitFinallyClause(node: FinallyClauseSyntax): any;
        visitTemplateClause(node: TemplateClauseSyntax): any;
        visitTypeParameter(node: TypeParameterSyntax): any;
        visitConstraint(node: ConstraintSyntax): any;
        visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): any;
        visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): any;
        visitParameter(node: ParameterSyntax): any;
        visitEnumElement(node: EnumElementSyntax): any;
        visitTypeAnnotation(node: TypeAnnotationSyntax): any;
        visitComputedPropertyName(node: ComputedPropertyNameSyntax): any;
        visitExternalModuleReference(node: ExternalModuleReferenceSyntax): any;
        visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): any;
    }


({ region, theme, pixelsPerMSec, style, children, ...others }: ClipRegionProps & {theme: Theme}) => {
    const r = region || [0, 0];
    const ppms = pixelsPerMSec || 0.01;
    const primary = theme.palette.primary[theme.palette.type];
    const bg = theme.palette.background.paper;
    const left = r[0] * ppms;
    const right = r[1] * ppms;
    const combinedStyle: React.CSSProperties = {
        position: 'absolute',
        top: 0,
        background: `linear-gradient(to right, ${bg} ${left}px, ${primary} ${left}px, ${primary} ${right}px, ${bg} ${right}px)`,
        mixBlendMode: 'darken',
        width: '100%',
        ...style
    };
    return (
        <div style={combinedStyle} {


export interface ClipRegionProps extends React.HTMLAttributes<{}>{
    region?: number[];
    pixelsPerMSec?: number;
}


() => {

    // tslint:disable-next-line:deprecation
    const transform = chainTransforms(...(takeHomeCommand.transform as Array<CodeTransform<TakeHomeCommandParameters>>));

    const parameters: TakeHomeCommandParameters & SeedDrivenGeneratorParameters = {
        screenName: "rod",
        source: {
            repoRef: GitHubRepoRef.from({ owner: "sourceowner", repo: "sourcerepo" }),
        },
        target: {
            repoRef: GitHubRepoRef.from({ owner: "targetowner", repo: "targetrepo" }),
            description: "thing",
            webhookUrl: "https://thing",
            visibility: "public",
            credentials: { token: "foo" },
        },
    };

    it("should not change name", async () => {
        const p = InMemoryProject.of({ path: "package.json", content: Package_Json });
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package.json");
        const json = JSON.parse(newPackage.getContentSync()) as PackageJson;
        assert.strictEqual(json.name, "@atomist/global-sdm");
        // assert.strictEqual(json.version, "1.0.1");
    });

    it("should remove dependency", async () => {
        const p = InMemoryProject.of(
            {
                path: "package.json", content: Package_Json,
            },
        );
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package.json").getContentSync();
        assert(!newPackage.includes("@atomist/sdm-pack-configuration"), newPackage);
    });

    it("should remove dependency from package-lock.json", async () => {
        const p = InMemoryProject.of({ path: "package-lock.json", content: Package_Json }, {
            path: "package-lock.json",
            content: PackageLockJson,
        });
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package-lock.json").getContentSync();
        assert(!newPackage.includes("@atomist/sdm-pack-global"), newPackage);
    });

    it("should remove import from machine.ts", async () => {
        const p = InMemoryProject.of({ path: "lib/machine.ts", content: machineTs });
        await transform(p, { parameters } as any, parameters);
        const newMachine = p.findFileSync("lib/machine.ts").getContentSync();
        assert(!newMachine.includes("import { globalConfiguration }"), newMachine);
        assert(newMachine.includes("import { editModes } from \"@atomist/automation-client\";\n"), newMachine);
    });

    it("should remove pack usage from machine.ts", async () => {
        const p = InMemoryProject.of({ path: "lib/machine.ts", content: machineTs });
        await transform(p, { parameters } as any, parameters);
        const newMachine = p.findFileSync("lib/machine.ts").getContentSync();
        assert(!newMachine.includes("sdm.addExtensionPacks(globalConfiguration())"), newMachine);
    });

    it("should update README", async () => {
        const p = InMemoryProject.of({ path: "README.md", content: readme });
        await transform(p, { parameters } as any, parameters);
        const newReadme = p.findFileSync("README.md").getContentSync();
        assert(!newReadme.includes(`# @atomist/global-sdm

Atomist Global SDM, which is capable of running on behalf of all users.

Also forms the basis of user SDMs.`), newReadme);
        assert(newReadme.includes(`# Based on @atomist/global-sdm

Your own SDM.`), newReadme);
    });

}


async () => {
        const p = InMemoryProject.of({ path: "package.json", content: Package_Json });
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package.json");
        const json = JSON.parse(newPackage.getContentSync()) as PackageJson;
        assert.strictEqual(json.name, "@atomist/global-sdm");
        // assert.strictEqual(json.version, "1.0.1");
    }


async () => {
        const p = InMemoryProject.of(
            {
                path: "package.json", content: Package_Json,
            },
        );
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package.json").getContentSync();
        assert(!newPackage.includes("@atomist/sdm-pack-configuration"), newPackage);
    }


async () => {
        const p = InMemoryProject.of({ path: "package-lock.json", content: Package_Json }, {
            path: "package-lock.json",
            content: PackageLockJson,
        });
        await transform(p, { parameters } as any, parameters);
        const newPackage = p.findFileSync("package-lock.json").getContentSync();
        assert(!newPackage.includes("@atomist/sdm-pack-global"), newPackage);
    }


async () => {
        const p = InMemoryProject.of({ path: "lib/machine.ts", content: machineTs });
        await transform(p, { parameters } as any, parameters);
        const newMachine = p.findFileSync("lib/machine.ts").getContentSync();
        assert(!newMachine.includes("import { globalConfiguration }"), newMachine);
        assert(newMachine.includes("import { editModes } from \"@atomist/automation-client\";\n"), newMachine);
    }


async () => {
        const p = InMemoryProject.of({ path: "lib/machine.ts", content: machineTs });
        await transform(p, { parameters } as any, parameters);
        const newMachine = p.findFileSync("lib/machine.ts").getContentSync();
        assert(!newMachine.includes("sdm.addExtensionPacks(globalConfiguration())"), newMachine);
    }


async () => {
        const p = InMemoryProject.of({ path: "README.md", content: readme });
        await transform(p, { parameters } as any, parameters);
        const newReadme = p.findFileSync("README.md").getContentSync();
        assert(!newReadme.includes(`# @atomist/global-sdm

Atomist Global SDM, which is capable of running on behalf of all users.

Also forms the basis of user SDMs.`), newReadme);
        assert(newReadme.includes(`# Based on @atomist/global-sdm

Your own SDM.`), newReadme);
    }


() => this.parent.hasNext()


() => value


() => new SkipIterator<T>(this.parent.clone(), this._amount)


/**
 * @class SkipIterator
 * Iterator that skips a given amount of items
 */
export class SkipIterator<T> implements BaseStreamIterator<T>{
    private _amount: number;

    public constructor(
        private parent: BaseStreamIterator<T>,
        private amount: number
    ){
        this._amount = this.amount;
    }

    public hasNext = () => this.parent.hasNext();

    public next(){
        while(this.amount >= 0){
            this.parent.next();
            this.amount -= 1;
        }

        const value = this.parent.next().value();
        if(this.amount === 0)
            this.amount -= 1;

        return {
            value: () => value
        };
    }

    public clone = () => new SkipIterator<T>(this.parent.clone(), this._amount);
}


public next(){
        while(this.amount >= 0){
            this.parent.next();
            this.amount -= 1;
        }

        const value = this.parent.next().value();
        if(this.amount === 0)
            this.amount -= 1;

        return {
            value: () => value
        };
    }


@Component({
    selector:'piece',
    template:`
             <div [style.width.px]="height" [style.height.px]="height" [ngClass]="[color,piece]" class="chessgroundpiece">
             </div>`,

})
export class pieceComponent{

  @Input() width: number;
  @Input() height: number;
  @Input() pieces: string = 'merida';
  @Input() piece:string ='';
  @Input() color: string = 'white';
  @Input() is3d: boolean = false;

  constructor(){

  }

}


e => {
			if (e.affectsConfiguration('terminal.integrated.showTabs')) {
				this._showTabs = this._terminalService.configHelper.config.showTabs;
				if (this._showTabs) {
					this._addTabTree();
					this._addSashListener();
				} else {
					this._splitView.removeView(this._tabTreeIndex);
					if (this._plusButton) {
						this._tabTreeContainer.removeChild(this._plusButton);
					}
					this._removeSashListener();
				}
			} else if (e.affectsConfiguration('terminal.integrated.tabsLocation')) {
				this._tabTreeIndex = this._terminalService.configHelper.config.tabsLocation === 'left' ? 0 : 1;
				this._terminalContainerIndex = this._terminalService.configHelper.config.tabsLocation === 'left' ? 1 : 0;
				if (this._showTabs) {
					this._splitView.swapViews(0, 1);
					this._splitView.resizeView(this._tabTreeIndex, DEFAULT_TABS_WIDGET_WIDTH);
				}
			}
		}


theme => this._updateTheme(theme)


() => this._terminalContainer!.classList.add(FIND_FOCUS_CLASS)


(p, c) => {
				return Math.max(p, ctx.measureText(c.title).width);
			}


() => this._handleOnDidSashReset()


() => this._handleOnDidSashChange()


width => this._terminalService.terminalTabs.forEach(tab => tab.layout(width, this._height || 0))


tab => tab.layout(width, this._height || 0)


() => Disposable.None


width => this._tabsWidget.layout(this._height ? this._height - 28 : 0, width)


e => {
				interval = window.setInterval(() => {
					this._refreshHasTextClass();
					this._rerenderTabs();
				}, 100);
			}


() => {
					this._refreshHasTextClass();
					this._rerenderTabs();
				}


e => {
				window.clearInterval(interval);
				interval = 0;
			}


async (event: MouseEvent) => {
			if (this._terminalService.terminalInstances.length === 0) {
				return;
			}

			if (event.which === 2 && isLinux) {
				// Drop selection and focus terminal on Linux to enable middle button paste when click
				// occurs on the selection itself.
				const terminal = this._terminalService.getActiveInstance();
				if (terminal) {
					terminal.focus();
				}
			} else if (event.which === 3) {
				const rightClickBehavior = this._terminalService.configHelper.config.rightClickBehavior;
				if (rightClickBehavior === 'copyPaste' || rightClickBehavior === 'paste') {
					const terminal = this._terminalService.getActiveInstance();
					if (!terminal) {
						return;
					}

					// copyPaste: Shift+right click should open context menu
					if (rightClickBehavior === 'copyPaste' && event.shiftKey) {
						this._openContextMenu(event);
						return;
					}

					if (rightClickBehavior === 'copyPaste' && terminal.hasSelection()) {
						await terminal.copySelection();
						terminal.clearSelection();
					} else {
						if (BrowserFeatures.clipboard.readText) {
							terminal.paste();
						} else {
							this._notificationService.info(`This browser doesn't support the clipboard.readText API needed to trigger a paste, try ${isMacintosh ? '⌘' : 'Ctrl'}+V instead.`);
						}
					}
					// Clear selection after all click event bubbling is finished on Mac to prevent
					// right-click selecting a word which is seemed cannot be disabled. There is a
					// flicker when pasting but this appears to give the best experience if the
					// setting is enabled.
					if (isMacintosh) {
						setTimeout(() => {
							terminal.clearSelection();
						}, 0);
					}
					this._cancelContextMenu = true;
				}
			}
		}


() => {
							terminal.clearSelection();
						}


(event: MouseEvent) => {
			if (!this._cancelContextMenu) {
				this._openContextMenu(event);
			}
			event.preventDefault();
			event.stopImmediatePropagation();
			this._cancelContextMenu = false;
		}


(event: KeyboardEvent) => {
			terminalContainer.classList.toggle('alt-active', !!event.altKey);
		}


(event: KeyboardEvent) => {
			if (event.keyCode === 27) {
				// Keep terminal open on escape
				event.stopPropagation();
			}
		}


async (e: DragEvent) => {
			if (e.target === this._parentElement || dom.isAncestor(e.target as HTMLElement, parentDomElement)) {
				if (!e.dataTransfer) {
					return;
				}

				// Check if files were dragged from the tree explorer
				let path: string | undefined;
				const resources = e.dataTransfer.getData(DataTransfers.RESOURCES);
				if (resources) {
					path = URI.parse(JSON.parse(resources)[0]).fsPath;
				} else if (e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) {
					// Check if the file was dragged from the filesystem
					path = URI.file(e.dataTransfer.files[0].path).fsPath;
				}

				if (!path) {
					return;
				}

				const terminal = this._terminalService.getActiveInstance();
				if (terminal) {
					const preparedPath = await this._terminalService.preparePathForTerminalAsync(path, terminal.shellLaunchConfig.executable, terminal.title, terminal.shellType);
					terminal.sendText(preparedPath, false);
					terminal.focus();
				}
			}
		}


() => actions


() => this._parentElement


() => actionsDisposable.dispose()


() => {
				// Only focus the terminal if the activeElement has not changed since focus() was called
				// TODO hack
				if (document.activeElement === activeElement) {
					this._focus();
				}
			}


private _getLastWidgetWidth(): number {
		const storedValue = this._storageService.get(TABS_WIDGET_WIDTH_KEY, StorageScope.WORKSPACE);
		if (!storedValue || !parseInt(storedValue)) {
			return DEFAULT_TABS_WIDGET_WIDTH;
		}
		return parseInt(storedValue);
	}