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

/**
 * @fileoverview Tree-like drilldown components for HTML tables.
 *
 * This component supports expanding and collapsing groups of rows in
 * HTML tables.  The behavior is like typical Tree widgets, but tables
 * need special support to enable the tree behaviors.
 *
 * Any row or rows in an HTML table can be DrilldownRows.  The root
 * DrilldownRow nodes are always visible in the table, but the rest show
 * or hide as input events expand and collapse their ancestors.
 *
 * Programming them:  Top-level DrilldownRows are made by decorating
 * a TR element.  Children are made with addChild or addChildAt, and
 * are entered into the document by the render() method.
 *
 * A DrilldownRow can have any number of children.  If it has no children
 * it can be loaded, not loaded, or with a load in progress.
 * Top-level DrilldownRows are always displayed (though setting
 * style.display on a containing DOM node could make one be not
 * visible to the user).  A DrilldownRow can be expanded, or not.  A
 * DrilldownRow displays if all of its ancestors are expanded.
 *
 * Set up event handlers and style each row for the application in an
 * enterDocument method.
 *
 * Children normally render into the document lazily, at the first
 * moment when all ancestors are expanded.
 *
 * @see ../demos/drilldownrow.html
 */

// TODO(user): Build support for dynamically loading DrilldownRows,
// probably using automplete as an example to follow.

// TODO(user): Make DrilldownRows accessible through the keyboard.

// The render method is redefined in this class because when addChildAt renders
// the new child it assumes that the child's DOM node will be a child
// of the parent component's DOM node, but all DOM nodes of DrilldownRows
// in the same tree of DrilldownRows are siblings to each other.
//
// Arguments (or lack of arguments) to the render methods in Component
// all determine the place of the new DOM node in the DOM tree, but
// the place of a new DrilldownRow in the DOM needs to be determined by
// its position in the tree of DrilldownRows.

goog.provide('goog.ui.DrilldownRow');

goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.ui.Component');

/**
 * Builds a DrilldownRow component, which can overlay a tree
 * structure onto sections of an HTML table.
 *
 * @param {Object=} opt_properties This parameter can contain:
 *   contents:  if present, user data identifying
 *     the information loaded into the row and its children.
 *   loaded: initializes the isLoaded property, defaults to true.
 *   expanded: DrilldownRow expanded or not, default is true.
 *   html: String of HTML, relevant and required for DrilldownRows to be
 *     added as children.  Ignored when decorating an existing table row.
 *   decorator: Function that accepts one DrilldownRow argument, and
 *     should customize and style the row.  The default is to call
 *     goog.ui.DrilldownRow.decorator.
 * @constructor
 * @extends {goog.ui.Component}
 */
goog.ui.DrilldownRow = function(opt_properties) {
  goog.ui.Component.call(this);
  var properties = opt_properties || {};

  // Initialize instance variables.

  /**
   * String of HTML to initialize the DOM structure for the table row.
   * Should have the form '
Row contents here
'.
   * @type {string}
   * @private
   */
  this.html_ = properties.html;

  /**
   * Controls whether this component's children will show when it shows.
   * @type {boolean}
   * @private
   */
  this.expanded_ = typeof properties.expanded != 'undefined' ?
      properties.expanded : true;

  /**
   * Is this component loaded? States are true, false, and null for
   * 'loading in progress'.  For in-memory
   * trees of components, this is always true.
   * @type {boolean}
   * @private
   */
  this.loaded_ = typeof properties.loaded != 'undefined' ?
      properties.loaded : true;

  /**
   * If this component's DOM element is created from a string of
   * HTML, this is the function to call when it is entered into the DOM tree.
   * @type {Function} args are DrilldownRow and goog.events.EventHandler
   *   of the DrilldownRow.
   * @private
   */
  this.decoratorFn_ = properties.decorator || goog.ui.DrilldownRow.decorate;

  /**
   * Is the DrilldownRow to be displayed?  If it is rendered, this mirrors
   * the style.display of the DrilldownRow's row.
   * @type {boolean}
   * @private
   */
  this.displayed_ = true;
};
goog.inherits(goog.ui.DrilldownRow, goog.ui.Component);

/**
 * Example object with properties of the form accepted by the class
 * constructor.  These are educational and show the compiler that
 * these properties can be set so it doesn't emit warnings.
 */
goog.ui.DrilldownRow.sampleProperties = {
  'html': '
Sample	Sample
',
  'loaded': true,
  'decorator': function(selfObj, handler) {
    // When the mouse is hovering, add CSS class goog-drilldown-hover.
    goog.ui.DrilldownRow.decorate(selfObj);
    var row = selfObj.getElement();
    handler.listen(row, 'mouseover', function() {
      goog.dom.classes.add(row, goog.getCssName('goog-drilldown-hover'));
    });
    handler.listen(row, 'mouseout', function() {
      goog.dom.classes.remove(row, goog.getCssName('goog-drilldown-hover'));
    });
  }
};

//
// Implementations of Component methods.
//

/**
 * The base class method calls its superclass method and this
 * drilldown's 'decorator' method as defined in the constructor.
 */
goog.ui.DrilldownRow.prototype.enterDocument = function() {
  goog.ui.DrilldownRow.superClass_.enterDocument.call(this);
  this.decoratorFn_(this, this.getHandler());
};

/** @inheritDoc */
goog.ui.DrilldownRow.prototype.createDom = function() {
  this.setElementInternal(goog.ui.DrilldownRow.createRowNode_(
      this.html_, this.getDomHelper().getDocument()));
};

/**
 * A top-level DrilldownRow decorates a TR element.
 *
 * @param {Element} node The element to test for decorability.
 * @return {boolean} true iff the node is a TR.
 */
goog.ui.DrilldownRow.prototype.canDecorate = function(node) {
  return node.tagName == 'TR';
};

/**
 * Child drilldowns are rendered when needed.
 *
 * @param {goog.ui.DrilldownRow} child New child to be added.
 * @param {number} index position to be occupied by the child.
 * @param {boolean=} opt_render true to force immediate rendering.
 */
goog.ui.DrilldownRow.prototype.addChildAt = function(child, index, opt_render) {
  goog.ui.DrilldownRow.superClass_.addChildAt.call(this, child, index, false);
  child.setDisplayable_(this.isVisible_() && this.isExpanded());
  if (opt_render && !child.isInDocument()) {
    child.render();
  }
};

/** @inheritDoc */
goog.ui.DrilldownRow.prototype.removeChild = function(child) {
  goog.dom.removeNode(child.getElement());
  goog.ui.DrilldownRow.superClass_.removeChild.call(this, child);
};

/** @inheritDoc */
goog.ui.DrilldownRow.prototype.disposeInternal = function() {
  delete this.html_;
  this.children_ = null;
  goog.ui.DrilldownRow.superClass_.disposeInternal.call(this);
};

/**
 * Rendering of DrilldownRow's is on need, do not call this directly
 * from application code.
 *
 * Rendering a DrilldownRow places it according to its position in its
 * tree of DrilldownRows.  DrilldownRows cannot be placed any other
 * way so this method does not use any arguments.  This does not call
 * the base class method and does not modify any of this
 * DrilldownRow's children.
 */
goog.ui.DrilldownRow.prototype.render = function() {
  if (arguments.length) {
    throw Error('A DrilldownRow cannot be placed under a specific parent.');
  } else {
    var parent = this.getParent();
    if (!parent.isInDocument()) {
      throw Error('Cannot render child of un-rendered parent');
    }
    // The new child's TR node needs to go just after the last TR
    // of the part of the parent's subtree that is to the left
    // of this.  The subtree includes the parent.
    var previous = parent.previousRenderedChild_(this);
    var row;
    if (previous) {
      row = previous.lastRenderedLeaf_().getElement();
    } else {
      row = parent.getElement();
    }
    row = /** @type {Element} */ (row.nextSibling);
    // Render the child row component into the document.
    if (row) {
      this.renderBefore(row);
    } else {
      // Render at the end of the parent of this DrilldownRow's
      // DOM element.
      var tbody = /** @type {Element} */ (parent.getElement().parentNode);
      goog.ui.DrilldownRow.superClass_.render.call(this, tbody);
    }
  }
};

/**
 * Finds the numeric index of this child within its parent Component.
 * Throws an exception if it has no parent.
 *
 * @return {number} index of this within the children of the parent Component.
 */
goog.ui.DrilldownRow.prototype.findIndex = function() {
  var parent = this.getParent();
  if (!parent) {
    throw Error('Component has no parent');
  }
  for (var i = 0; i < parent.getChildCount(); i++) {
    if (parent.getChildAt(i) == this) {
      return i;
    }
  }
};

//
// Type-specific operations
//

/**
 * Returns the expanded state of the DrilldownRow.
 *
 * @return {boolean} true iff this is expanded.
 */
goog.ui.DrilldownRow.prototype.isExpanded = function() {
  return this.expanded_;
};

/**
 * Sets the expanded state of this DrilldownRow: makes all children
 * displayable or not displayable corresponding to the expanded state.
 *
 * @param {boolean} expanded whether this should be expanded or not.
 */
goog.ui.DrilldownRow.prototype.setExpanded = function(expanded) {
  if (expanded != this.expanded_) {
    this.expanded_ = expanded;
    goog.dom.classes.toggle(this.getElement(),
        goog.getCssName('goog-drilldown-expanded'));
    goog.dom.classes.toggle(this.getElement(),
        goog.getCssName('goog-drilldown-collapsed'));
    if (this.isVisible_()) {
      this.forEachChild(function(child) {
        child.setDisplayable_(expanded);
      });
    }
  }
};

/**
 * Returns this DrilldownRow's level in the tree.  Top level is 1.
 *
 * @return {number} depth of this DrilldownRow in its tree of drilldowns.
 */
goog.ui.DrilldownRow.prototype.getDepth = function() {
  for (var component = this, depth = 0;
       component instanceof goog.ui.DrilldownRow;
       component = component.getParent(), depth++) {}
  return depth;
};

/**
 * This static function is a default decorator that adds HTML at the
 * beginning of the first cell to display indentation and an expander
 * image; sets up a click handler on the toggler; initializes a class
 * for the row: either goog-drilldown-expanded or
 * goog-drilldown-collapsed, depending on the initial state of the
 * DrilldownRow; and sets up a click event handler on the toggler
 * element.
 *
 * This creates a DIV with class=toggle.  Your application can set up
 * CSS style rules something like this:
 *
 * tr.goog-drilldown-expanded .toggle {
 *   background-image: url('minus.png');
 * }
 *
 * tr.goog-drilldown-collapsed .toggle {
 *   background-image: url('plus.png');
 * }
 *
 * These background images show whether the DrilldownRow is expanded.
 *
 * @param {goog.ui.DrilldownRow} selfObj DrilldownRow to be decorated.
 */
goog.ui.DrilldownRow.decorate = function(selfObj) {
  var depth = selfObj.getDepth();
  var row = selfObj.getElement();
  if (!row.cells) {
    throw Error('No cells');
  }
  var cell = row.cells[0];
  var html = '

' +
      '

';
  var fragment = selfObj.getDomHelper().htmlToDocumentFragment(html);
  cell.insertBefore(fragment, cell.firstChild);
  goog.dom.classes.add(row, selfObj.isExpanded() ?
      goog.getCssName('goog-drilldown-expanded') :
      goog.getCssName('goog-drilldown-collapsed'));
  // Default mouse event handling:
  var toggler = fragment.getElementsByTagName('div')[0];
  var key = selfObj.getHandler().listen(toggler, 'click', function(event) {
    selfObj.setExpanded(!selfObj.isExpanded());
  });
};

//
// Private methods
//

/**
 * Turn display of a DrilldownRow on or off.  If the DrilldownRow has not
 * yet been rendered, this renders it.  This propagates the effect
 * of the change recursively as needed -- children displaying iff the
 * parent is displayed and expanded.
 *
 * @param {boolean} display state, true iff display is desired.
 * @private
 */
goog.ui.DrilldownRow.prototype.setDisplayable_ = function(display) {
  if (display && !this.isInDocument()) {
    this.render();
  }
  if (this.displayed_ == display) {
    return;
  }
  this.displayed_ = display;
  if (this.isInDocument()) {
    this.getElement().style.display = display ? '' : 'none';
  }
  var selfObj = this;
  this.forEachChild(function(child) {
    child.setDisplayable_(display && selfObj.expanded_);
  });
};

/**
 * True iff this and all its DrilldownRow parents are displayable.  The
 * value is an approximation to actual visibility, since it does not
 * look at whether DOM nodes containing the top-level component have
 * display: none, visibility: hidden or are otherwise not displayable.
 * So this visibility is relative to the top-level component.
 *
 * @return {boolean} visibility of this relative to its top-level drilldown.
 * @private
 */
goog.ui.DrilldownRow.prototype.isVisible_ = function() {
  for (var component = this;
       component instanceof goog.ui.DrilldownRow;
       component = component.getParent()) {
    if (!component.displayed_)
      return false;
  }
  return true;
};

/**
 * Create and return a TR element from HTML that looks like
 * "
 ...
".
 *
 * @param {string} html for one row.
 * @param {Document} doc object to hold the Element.
 * @return {Element} table row node created from the HTML.
 * @private
 */
goog.ui.DrilldownRow.createRowNode_ = function(html, doc) {
  // Note: this may be slow.
  var tableHtml = '
' + html + '
';
  var div = doc.createElement('div');
  div.innerHTML = tableHtml;
  return div.firstChild.rows[0];
};

/**
 * Get the recursively rightmost child that is in the document.
 *
 * @return {goog.ui.DrilldownRow} rightmost child currently entered in
 *     the document, potentially this DrilldownRow.  If this is in the
 *     document, result is non-null.
 * @private
 */
goog.ui.DrilldownRow.prototype.lastRenderedLeaf_ = function() {
  var leaf = null;
  for (var node = this;
       node && node.isInDocument();
       // Node will become undefined if parent has no children.
       node = node.getChildAt(node.getChildCount() - 1)) {
    leaf = node;
  }
  return /** @type {goog.ui.DrilldownRow} */ (leaf);
};

/**
 * Search this node's direct children for the last one that is in the
 * document and is before the given child.
 * @param {goog.ui.DrilldownRow} child The child to stop the search at.
 * @return {goog.ui.Component?} The last child component before the given child
 *     that is in the document.
 * @private
 */
goog.ui.DrilldownRow.prototype.previousRenderedChild_ = function(child) {
  for (var i = this.getChildCount() - 1; i >= 0; i--) {
    if (this.getChildAt(i) == child) {
      for (var j = i - 1; j >= 0; j--) {
        var prev = this.getChildAt(j);
        if (prev.isInDocument()) {
          return prev;
        }
      }
    }
  }
  return null;
};


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SimpleCell = void 0;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _jsxRuntime = require("../../lib/jsxRuntime");
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _classNames = require("../../lib/classNames");
var _getClassName = require("../../helpers/getClassName");
var _Tappable = require("../Tappable/Tappable");
var _icons = require("@vkontakte/icons");
var _platform = require("../../lib/platform");
var _usePlatform = require("../../hooks/usePlatform");
var _utils = require("../../lib/utils");
var _useAdaptivity2 = require("../../hooks/useAdaptivity");
var _withAdaptivity = require("../../hoc/withAdaptivity");
var _Subhead = require("../Typography/Subhead/Subhead");
var _Headline = require("../Typography/Headline/Headline");
var _Footnote = require("../Typography/Footnote/Footnote");
var _Caption = require("../Typography/Caption/Caption");
var _excluded = ["badge", "badgeBeforeTitle", "badgeAfterTitle", "badgeBeforeSubtitle", "badgeAfterSubtitle", "before", "indicator", "children", "after", "description", "expandable", "multiline", "sizeY", "subhead", "subtitle", "extraSubtitle"];
var SubtitleTypography = function SubtitleTypography(props) {
  var _useAdaptivity = (0, _useAdaptivity2.useAdaptivity)(),
    sizeY = _useAdaptivity.sizeY;
  if (sizeY === _withAdaptivity.SizeType.COMPACT) {
    return (0, _jsxRuntime.createScopedElement)(_Caption.Caption, (0, _extends2.default)({
      level: "2"
    }, props));
  }
  return (0, _jsxRuntime.createScopedElement)(_Footnote.Footnote, props);
};
var SimpleCellComponent = function SimpleCellComponent(_ref) {
  var badge = _ref.badge,
    badgeBeforeTitle = _ref.badgeBeforeTitle,
    _ref$badgeAfterTitle = _ref.badgeAfterTitle,
    badgeAfterTitle = _ref$badgeAfterTitle === void 0 ? badge : _ref$badgeAfterTitle,
    badgeBeforeSubtitle = _ref.badgeBeforeSubtitle,
    badgeAfterSubtitle = _ref.badgeAfterSubtitle,
    before = _ref.before,
    indicator = _ref.indicator,
    children = _ref.children,
    after = _ref.after,
    description = _ref.description,
    expandable = _ref.expandable,
    multiline = _ref.multiline,
    sizeY = _ref.sizeY,
    subhead = _ref.subhead,
    _ref$subtitle = _ref.subtitle,
    subtitle = _ref$subtitle === void 0 ? description : _ref$subtitle,
    extraSubtitle = _ref.extraSubtitle,
    restProps = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var platform = (0, _usePlatform.usePlatform)();
  var hasAfter = (0, _utils.hasReactNode)(after) || expandable && platform === _platform.IOS;
  return (0, _jsxRuntime.createScopedElement)(_Tappable.Tappable, (0, _extends2.default)({}, restProps, {
    vkuiClass: (0, _classNames.classNames)((0, _getClassName.getClassName)("SimpleCell", platform), expandable && "SimpleCell--exp", multiline && "SimpleCell--mult", "SimpleCell--sizeY-".concat(sizeY))
  }), before, (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "SimpleCell__main"
  }, subhead && (0, _jsxRuntime.createScopedElement)(_Subhead.Subhead, {
    Component: "span",
    vkuiClass: "SimpleCell__text SimpleCell__subhead"
  }, subhead), (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "SimpleCell__content"
  }, badgeBeforeTitle && (0, _jsxRuntime.createScopedElement)("span", {
    vkuiClass: "SimpleCell__badge"
  }, badgeBeforeTitle), (0, _jsxRuntime.createScopedElement)(_Headline.Headline, {
    Component: "span",
    vkuiClass: "SimpleCell__children",
    weight: "3"
  }, children), (0, _utils.hasReactNode)(badgeAfterTitle) && (0, _jsxRuntime.createScopedElement)("span", {
    vkuiClass: "SimpleCell__badge"
  }, badgeAfterTitle)), subtitle && (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "SimpleCell__content"
  }, badgeBeforeSubtitle && (0, _jsxRuntime.createScopedElement)("span", {
    vkuiClass: "SimpleCell__badge"
  }, badgeBeforeSubtitle), (0, _jsxRuntime.createScopedElement)(SubtitleTypography, {
    vkuiClass: "SimpleCell__text SimpleCell__subtitle"
  }, subtitle), badgeAfterSubtitle && (0, _jsxRuntime.createScopedElement)("span", {
    vkuiClass: "SimpleCell__badge"
  }, badgeAfterSubtitle)), extraSubtitle && (0, _jsxRuntime.createScopedElement)(SubtitleTypography, {
    vkuiClass: "SimpleCell__text SimpleCell__extraSubtitle"
  }, extraSubtitle)), (0, _utils.hasReactNode)(indicator) && (0, _jsxRuntime.createScopedElement)(_Headline.Headline, {
    Component: "span",
    weight: "3",
    vkuiClass: "SimpleCell__indicator"
  }, indicator), hasAfter && (0, _jsxRuntime.createScopedElement)("div", {
    vkuiClass: "SimpleCell__after"
  }, after, expandable && platform === _platform.IOS && (0, _jsxRuntime.createScopedElement)(_icons.Icon24Chevron, null)));
};

/**
 * @see https://vkcom.github.io/VKUI/#/SimpleCell
 */
var SimpleCell = (0, _withAdaptivity.withAdaptivity)(SimpleCellComponent, {
  sizeY: true
});
exports.SimpleCell = SimpleCell;
SimpleCell.displayName = "SimpleCell";
//# sourceMappingURL=SimpleCell.js.map

redpajama_set_name: RedPajamaGithub


text:
import * as React from "react";

import { XmldocNode } from ".";

import { PackageContext } from "../../util";
import { IXmldoc } from "../../structure";

interface XmldocSeeAlsoProps extends PackageContext {
    data?: IXmldoc;
}

export const XmldocSeeAlso: React.StatelessComponent<XmldocSeeAlsoProps> = (props) => {
    const { data } = props;
    if (!data || !data.s)
        return null;
    return (

See Also

            {data.s.map((x, i) => <XmldocNode {...props} data={x} key={i}/>)}

    );
}


text:
package org.apache.hawq.pxf.plugins.hdfs.utilities;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("RecordkeyAdapter")
@PrepareForTest({RecordkeyAdapter.class, LogFactory.class})
public class RecordkeyAdapterTest {
    Log LOG;
    RecordkeyAdapter recordkeyAdapter;

    /**
     * Test convertKeyValue for Integer type
     */
    @Test
    public void convertKeyValueInteger() {
        int key = 13;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new IntWritable(key));
    }

    /**
     * Test convertKeyValue for Boolean type
     */
    @Test
    public void convertKeyValueBoolean() {
        boolean key = true;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new BooleanWritable(key));
    }

    /**
     * Test convertKeyValue for Byte type
     */
    @Test
    public void convertKeyValueByte() {
        byte key = 1;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new ByteWritable(key));
    }

    /**
     * Test convertKeyValue for Double type
     */
    @Test
    public void convertKeyValueDouble() {
        double key = 2.3;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new DoubleWritable(key));
    }

    /**
     * Test convertKeyValue for Float type
     */
    @Test
    public void convertKeyValueFloat() {
        float key = (float) 2.3;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new FloatWritable(key));
    }

    /**
     * Test convertKeyValue for Long type
     */
    @Test
    public void convertKeyValueLong() {
        long key = 12345678901234567l;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new LongWritable(key));
    }

    /**
     * Test convertKeyValue for String type
     */
    @Test
    public void convertKeyValueString() {
        String key = "key";
        initRecordkeyAdapter();
        runConvertKeyValue(key, new Text(key));
    }

    /**
     * Test convertKeyValue for several calls of the same type
     */
    @Test
    public void convertKeyValueManyCalls() {
        Boolean key = true;
        mockLog();
        initRecordkeyAdapter();
        runConvertKeyValue(key, new BooleanWritable(key));
        verifyLog("converter initialized for type " + key.getClass() +
                " (key value: " + key + ")");

        for (int i = 0; i < 5; ++i) {
            key = (i % 2) == 0;
            runConvertKeyValue(key, new BooleanWritable(key));
        }
        verifyLogOnlyOnce();
    }

    /**
     * Test convertKeyValue for boolean type and then string type - negative
     * test
     */
    @Test
    public void convertKeyValueBadSecondValue() {
        boolean key = true;
        initRecordkeyAdapter();
        runConvertKeyValue(key, new BooleanWritable(key));
        String badKey = "bad";
        try {
            recordkeyAdapter.convertKeyValue(badKey);
            fail("conversion of string to boolean should fail");
        } catch (ClassCastException e) {
            assertEquals(e.getMessage(),
                    "java.lang.String cannot be cast to java.lang.Boolean");
        }
    }

    private void initRecordkeyAdapter() {
        recordkeyAdapter = new RecordkeyAdapter();
    }

    private void runConvertKeyValue(Object key, Writable expected) {
        Writable writable = recordkeyAdapter.convertKeyValue(key);
        assertEquals(writable, expected);
    }

    private void mockLog() {
        LOG = mock(Log.class);
        Whitebox.setInternalState(RecordkeyAdapter.class, LOG);
    }

    private void verifyLog(String msg) {
        Mockito.verify(LOG).debug(msg);
    }

    private void verifyLogOnlyOnce() {
        Mockito.verify(LOG, Mockito.times(1)).debug(Mockito.any());
    }
}


text:
package command

import (
	"strings"

	"github.com/mitchellh/cli"
)

type OperatorRaftCommand struct {
	BaseCommand
}

func (c *OperatorRaftCommand) Run(args []string) int {
	return cli.RunResultHelp
}

func (c *OperatorRaftCommand) Help() string {
	helpText := `
Usage: consul operator raft <subcommand> [options]

The Raft operator command is used to interact with Consul's Raft subsystem. The
command can be used to verify Raft peers or in rare cases to recover quorum by
removing invalid peers.

`

	return strings.TrimSpace(helpText)
}

func (c *OperatorRaftCommand) Synopsis() string {
	return "Provides cluster-level tools for Consul operators"
}


text:
get "/users/:id" do
  @user = current_user
  @posts = @user.posts
  # @answers = @posts.answers
  erb :"/users/show"
end


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

/**
 * @fileoverview Page object for the topic and story viewer page, for use
 * in Protractor tests.
 */

var waitFor = require('./waitFor.js');
var action = require('./action.js');

var SubTopicViewerPage = function() {
  var subTopicTileList = element.all(by.css('.protractor-test-subtopic-tile'));
  var conceptCardList = element.all(
    by.css('.protractor-test-concept-card-link'));
  var conceptCardExplanation = element(
    by.css('.protractor-test-concept-card-explanation'));

  this.get = async function(subTopicName) {
    await waitFor.pageToFullyLoad();
    var subTopicTile = element(by.cssContainingText(
      '.protractor-test-subtopic-tile', subTopicName));
    await waitFor.presenceOf(
      subTopicTile, 'Sub topic ' + subTopicName + ' card is not present,');
    await action.click(subTopicName, subTopicTile);
    await waitFor.pageToFullyLoad();
  };

  this.expectRevisionCardCountToBe = async function(count) {
    if (count === 0) {
      expect(await subTopicTileList.count()).toEqual(0);
    } else {
      await waitFor.visibilityOf(
        subTopicTileList.first(),
        'Revisions cards take too long to be visible.');
      expect(await subTopicTileList.count()).toEqual(count);
    }
  };

  this.expectConceptCardCountToBe = async function(count) {
    if (count === 0) {
      expect(await conceptCardList.count()).toEqual(0);
    } else {
      await waitFor.visibilityOf(
        conceptCardList.first(),
        'Concept cards take too long to be visible.');
      expect(await conceptCardList.count()).toEqual(count);
    }
  };

  this.getConceptCard = async function() {
    var conceptCardElement = conceptCardList.first();
    await action.click('Concept card link', conceptCardElement);
    await waitFor.pageToFullyLoad();
  };

  this.expectConceptCardInformationToBe = async function(description) {
    await waitFor.visibilityOf(
      conceptCardExplanation,
      'Concept card explanation takes too long to be visible.');
    var text = await conceptCardExplanation.getText();
    expect(text).toEqual(description);
  };
};

exports.SubTopicViewerPage = SubTopicViewerPage;


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

import org.junit.Test;

public class EscapeTest extends HtplTestCase {

	@Test
	public void testBaseEntities(){
		assertRender("

");
		assertRender("
<100>&"©
");
		assertRender("<input value=\"a>\"/>");
		assertRender("<input value=\"a<\"/>");
	}

	@Test
	public void testAttributeSpecialChars() {
		assertRender("a");
		assertRender("a");
		assertRender("<a href=\"javascript:alert('<');\">a");
	}

	@Test
	public void testHtmlAutoEscape() {
		context.setLocalVariable("a", "<");
		assertRender("<" ,"${a}");
		assertRender(" <" ," ${a}");
		assertRender(" <" ," ${a;escape:off}");
		assertRender(" <" ," $!{a}");
		assertRender(" <" ," ${a ; escape : off}");
		assertRender(" <" ," ${a;}");
		assertRender(" < ; " ," ${a + ' ; '}");
	}

	@Test
	public void testAttrAutoEscape() {
		context.setLocalVariable("sq", "\'");
		context.setLocalVariable("dq", "\"");
		context.setLocalVariable("amp","&");

		assertRender("
1
");
		assertRender("
1
","
1
");
		assertRender("
1
","
1
");
	}

	@Test
	public void testJavascriptAutoEscape() {
		context.setLocalVariable("sq", "\'");
		context.setLocalVariable("dq", "\"");

		assertRender("");
		assertRender("","");
		assertRender("","");
	}

	@Test
	public void testExpressionSpecialChars(){
		context.setLocalVariable("i", 1);
		context.setLocalVariable("j", 10);
		context.setLocalVariable("s", "str");

		assertRender("
str
","
${i > 0 && j > 0 ? s : 'nothing'}
");
		assertRender("
str
","
${i > 0 && j > 0 ? s : 'nothing'}
");

		assertRender("<input value=\"str\"/>","<input value=\"${i > 0 && j > 0 ? s : 'nothing'}\"/>");
		assertRender("<input value=\"str\"/>","<input value=\"${i > 0 && j > 0 ? s : 'nothing'}\"/>");
	}

}


text:
using System;

namespace Renci.SshNet.Common
{
    /// <summary>
    /// Provides data for <see cref="Renci.SshNet.ForwardedPort.RequestReceived"/> event.
    /// </summary>
    public class PortForwardEventArgs : EventArgs
    {
        /// <summary>
        /// Gets request originator host.
        /// </summary>
        public string OriginatorHost { get; private set; }

        /// <summary>
        /// Gets request originator port.
        /// </summary>
        public uint OriginatorPort { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PortForwardEventArgs"/> class.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="port">The port.</param>
        /// <exception cref="ArgumentNullException"><paramref name="host"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="port" /> is not within <see cref="F:System.Net.IPEndPoint.MinPort" /> and <see cref="F:System.Net.IPEndPoint.MaxPort" />.</exception>
        internal PortForwardEventArgs(string host, uint port)
        {
            if (host == null)
                throw new ArgumentNullException("host");
            port.ValidatePort("port");

            OriginatorHost = host;
            OriginatorPort = port;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 504 (1898)

#### Original name
Psathyra schulzeri Quél.

### Remarks
null


text:
Kinecting AR Drone
===========
Tutorial on how you can fly your **Parrot AR Drone** by using **Kinect for Windows**.

> Disclaimer – This application is not finished and needs additional work

## Prerequisites
- Parrot AR Drone
- Kinect for Windows
- Basic C# & WPF knowledge
- Kinect for Windows SDK v1.8 ([link](http://go.microsoft.com/fwlink/?LinkID=323588 "link"))
- Microsoft Speech Platform SDK v11 ([link](http://www.microsoft.com/en-us/download/details.aspx?id=27226 "link"))

## What you will learn

### Part I - Basic UI, Kinect camera & voice recognition ([Code](https://github.com/KinectingForWindows/GIK-KinectingARDrone/tree/Part_I))
In part I we will integrate our Kinect into the template by **visualizing the camera** and setting up our **speech recognition**.

- Integrate Kinect sensor in our application
- Visualize the Kinect-state
- Visualize the camera
- Add speech recognition

### Mayday, mayday! Ending the Kinecting AR Drone series. ([Code](https://github.com/KinectingForWindows/GIK-KinectingARDrone/tree/Final-Version))
> Disclaimer – This application is not finished and needs additional work

As you can read in my blog post ([link](http://www.kinectingforwindows.com/2014/08/07/mayday-mayday-ending-the-kinecting-ar-drone-series/)) I didn't had the time to finish this series but I'll open-source the code anyway.

#### Application Status
Currently you are able to enter your *battle station* as a *Commander* and take-off by using speech commands. In the meanwhile you can monitor the drone & Kinect cameras.

#### Drone Features
These are some of the features we use of the drone.

- Blinking of the LED
- Perform tricks
- Use camera
- Fly around

#### Kinect Features
This application is based on the following Kinect features

- Camera
- Skeletal Tracking
- Speech recognition

#### Flying Gestures
Here is the list of gestures that are being used to fly the drone -

- **Fly up** - Move both your hand above your head (25° Angle)
- **Fly down** - Move both your hand below your shoulder your head (25° Angle)
- **Move left** - Move left hand below your shoulders and right hand above your head(25° Angle)
- **Move right** - Move right hand below your shoulders and left hand above your head(25° Angle)
- **Move forward** - Lean forward
- **Move backwards** - Lean backward
- **Rotate left** - Rotate your arms counter clock wise with your spine as a center
- **Rotate right** - Rotate your arms clock wise with your spine as a center

The gestures are partially developed but not flying smoothly as I want it to be.

## Template ##
In this tutorial we will use a template to avoid spending too much time on the interface.
The template contains a basic WPF application where we will **visualize** our **Kinect** *(2)* & **drone** *(4)* cameras as well as the **state** of our **devices**. *(1-3)* In *sector 5* we will **log** some things like our recognized commands, etc.

You can download the template in the [Template-branch](https://github.com/KinectingForWindows/GIK-KinectingARDrone/tree/Template "Template-branch").

## Credits ##
This application uses the [AR.Drone](https://github.com/Ruslan-B/AR.Drone)-library from [Ruslan Balanukhin](https://twitter.com/rbalanukhin).


text:
FROM elasticsearch:5.6
ADD config/elasticsearch.yml /usr/share/elasticsearch/config/
USER root
RUN chown elasticsearch:elasticsearch config/elasticsearch.yml
RUN bin/elasticsearch-plugin install x-pack
USER elasticsearch


text:
'use strict';

var SearchResults = require('./SearchResults');
var React = require('react-native');
var {
  Component,
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  ActivityIndicatorIOS,
  Image,
} = React;

function urlForQueryAndPage(key, value, pageNumber) {
  var data = {
    country: 'uk',
    pretty: '1',
    encoding: 'json',
    listing_type: 'buy',
    action: 'search_listings',
    page: pageNumber
  };
  data[key] = value;

  var querystring = Object.keys(data)
    .map(key => key + '=' + encodeURIComponent(data[key]))
    .join('&');

  return 'http://api.nestoria.co.uk/api?' + querystring;
};

class SearchPage extends Component {
  constructor(props){
    super(props);
    this.state = {
      searchString: 'london',
      isLoading: false,
      message: ''
    };
  }
  render() {
    console.log('SearchPage.render');
    var spinner = this.state.isLoading ?
      (<ActivityIndicatorIOS
        hidden='true'
        size='large'/>) :
      (<View />);

    return (
      <View style={styles.container}>
        <Text style={styles.description}>
          Search for houses to buy!
        </Text>
        <Text style={styles.description}>
          Search by place-name, postcode or search near your location.
        </Text>
        <View style={styles.flowRight}>
          <TextInput
            style={styles.searchInput}
            value={this.state.searchString}
            onChange={this.onSearchTextChanged.bind(this)}
            placeholder='Search via name or postcode'/>
          <TouchableHighlight style={styles.button}
            underlayColor='#99d9f4'
            onPress={this.onSearchPressed.bind(this)}>
            <Text style={styles.buttonText}>Go</Text>
          </TouchableHighlight>
        </View>
        <TouchableHighlight style={styles.button}
          underlayColor='#99d9f4'
          onPress={this.onLocationPressed.bind(this)}>
          <Text style={styles.buttonText}>Location</Text>
        </TouchableHighlight>
        <Image source={require('image!house')} style={styles.image}/>
        {spinner}
        <Text style={styles.description}> {this.state.message}</Text>
      </View>
    );
  }

  onSearchTextChanged(event) {
    console.log('onSearchTextChanged');
    this.setState({searchString: event.nativeEvent.text});
    console.log(this.state.searchString);
  }

  onLocationPressed() {
    navigator.geolocation.getCurrentPosition(
      loaction => {
        var search = loaction.coords.latitude + ',' + loaction.coords.longitude;
        this.setState({searchString: search});
        var query = urlForQueryAndPage('centre_point', search, 1);
        this._executeQuery(query);
      },
      error => {
        this.setState({
          message: 'There was a problem with obtaining your location: ' + error
        });
      });
  }
  _executeQuery(query) {
    console.log(query);
    this.setState({isLoading: true});

    fetch(query)
      .then(response => response.json())
      .then(json => this._handleResponse(json.response))
      .catch(error =>
        this.setState({
          isLoading: false,
          message: 'Something bad happened' + error
        }));
  }

  _handleResponse(response) {
    this.setState({isLoading: false, message: ''});
    if (response.application_response_code.substr(0,1) === '1') {
      console.log('Properties found: ' + response.listings.length);
      this.props.navigator.push({
        title: 'Results',
        component: SearchResults,
        passProps: {listings: response.listings}
      });
    } else {
      this.setState({message: 'Location not recognized; please try again.'});
    }
  }

  onSearchPressed() {
    var query = urlForQueryAndPage('place_name', this.state.searchString, 1);
    this._executeQuery(query);
  }

}

var styles = StyleSheet.create({
  description: {
    marginBottom: 20,
    fontSize: 18,
    textAlign: 'center',
    color: '#656565'
  },
  container: {
    padding: 30,
    marginTop: 65,
    alignItems: 'center'
  },
  flowRight: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'stretch'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  searchInput: {
    height: 36,
    padding: 4,
    marginRight: 5,
    flex: 4,
    fontSize: 18,
    borderWidth: 1,
    borderColor: '#48BBEC',
    borderRadius: 8,
    color: '#48BBEC'
  },
  image: {
    width: 217,
    height: 138
  }
});

module.exports = SearchPage;


text:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <inttypes.h>
#include <string.h>
#include <sys/stat.h>

/****************************************
 Author: Joel Klein, Katie Stasaski, Lucas Chaufournier, Tim Wood
 with a little help from
 http://beej.us/guide/bgnet/
 ****************************************/

#define BACKLOG 10     // how many pending connections queue will hold

/* Struct for contents of http request */
typedef struct http_request {
    char* method;
    char* request;
    char* version;
} http_request;

/* Struct to contain information for an http response */
typedef struct http_response {
    char* version;
    char* response_code;
    char* host;
    char* content_type;
    int len;
    char* body;
} http_response;

http_response *http_response_alloc()
{
    http_response* response = malloc(sizeof(struct http_response));
    response->version = "HTTP/1.1";
    response->host = "host.name";
    printf("response object created\n");
    return response;
}

void http_response_free(http_response * response)
{
    free(response);
}

//char* response_creation()

int main(int argc, char ** argv)
{
    char* server_port = "1234";
    int sockfd, rc;
    int yes=1;
    struct addrinfo hints, *server;
    char message[256];
    char *requestmsgseg = NULL; /* Storage for current segment of the request message */
    char* resp = NULL; /* holds the response message returned from a request */
    int o, i;

    /* Command line args:
     -p port
     */
    while ((o = getopt (argc, argv, "p:")) != -1) {
        switch(o){
            case 'p':
                server_port = optarg;
                break;
            case '?':
                if(optopt == 'p') {
                    fprintf (stderr, "Option %c requires an argument.\n", optopt);
                }
                else {
                    fprintf (stderr, "Unknown argument: %c.\n", optopt);
                }
                break;
        }
    }

    printf("listening on port: %s\n", server_port);

    /* The hints struct is used to specify what kind of server info we are looking for */
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM; /* or SOCK_DGRAM */
    hints.ai_flags = AI_PASSIVE;

    /* getaddrinfo() gives us back a server address we can connect to.
     The first parameter is NULL since we want an address on this host.
     It actually gives us a linked list of addresses, but we'll just use the first.
     */
    if (rc = getaddrinfo(NULL, server_port, &hints, &server) != 0) {
        perror(gai_strerror(rc));
        exit(-1);
    }

    /* Now we can create the socket and bind it to the local IP and port */
    sockfd = socket(server->ai_family, server->ai_socktype, server->ai_protocol);
    if (sockfd == -1) {
        perror("ERROR opening socket");
        exit(-1);
    }
    /* Get rid of "Address already in use" error messages */
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
        perror("setsockopt");
        exit(-1);
    }
    rc = bind(sockfd, server->ai_addr, server->ai_addrlen);
    if (rc == -1) {
        perror("ERROR on connect");
        close(sockfd);
        exit(-1);
        // TODO: could use goto here for error cleanup
    }

    /* Time to listen for clients.*/
    listen(sockfd, BACKLOG);
    /* Loop forever accepting new connections. */
    while(1) {
        struct sockaddr_storage client_addr;
        socklen_t addr_size;
        int clientfd;
        int bytes_read;
        char * response_message = NULL; // container for the HTTP response message

        addr_size = sizeof client_addr;
        clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &addr_size);

        bytes_read = read(clientfd, message, sizeof message);
        if(bytes_read < 0) {
            perror("ERROR reading socket");
        }

        http_request *req = malloc(sizeof(struct http_request));
        /* Break up the request message into space delimited segments */
        requestmsgseg = strtok(message, " ");
        req->method = strdup(requestmsgseg);

        /*This is necessary to prevent not get requests from segfaulting server. #Lucas*/
        if(strcmp(req->method,"GET")!=0)
        {
            //printf("Not a get request");
            close(clientfd);
            free(req);
            continue;
        }

        requestmsgseg = strtok(NULL, " ");
        req->request = strdup(requestmsgseg);
        requestmsgseg = strtok(NULL, " ");
        req->version = strdup(requestmsgseg);
        /*Check for get request*/

        /* Test the request was recorded correctly */
        printf("Method: %s, Request: %s, Version: %s\n", req->method, req->request, req->version);

        /* File exists, return contents */
        if (access(++req->request, R_OK) != -1) {
            FILE * fp;
            struct stat st;
            int file_size, size;

            /* create the response object to contain response information */
            http_response* response = http_response_alloc();
            response->response_code = "200";

            /* open the file requested and move the information into the response object */
            fp = fopen(req->request, "r");
            stat(req->request, &st);
            size = st.st_size; // need to know the size of the object we are manipulating
            response->body = malloc(size);
            file_size = fread(response->body, 1, size, fp); //moves contents into response->body
            response->len = file_size;

            asprintf(&response_message, "%s %s\nHost: %s\nContent-Type: %s\nContent-Length: %d\n\n%s", response->version, response->response_code, response->host, response->content_type, response->len, response->body);
            rc = send(clientfd, response_message, strlen(response_message)+1, 0);
            if(rc <0) {
                perror("ERROR on send");
                exit(-1);
            }
            free(response);

            /* File does not exist, return 404 */
        } else {
            //file does not exist return 404
            printf("File does not exist\n");
            http_response * response = http_response_alloc();
            response->response_code = "404";
            response->body = "
ERROR 404: File Not Found
";
            response->len = strlen(response->body);

            asprintf(&response_message, "%s %s\nHost: %s\nContent-Type: %s\nContent-Length: %d\n\n%s", response->version, response->response_code, response->host, response->content_type, response->len, response->body);
            rc = send(clientfd, response_message, strlen(response_message)+1, 0);
            if(rc <0) {
                perror("ERROR on send");
                exit(-1);
            }
            free(response);
        }

        close(clientfd);
        free (req);
    }

out:
    freeaddrinfo(server);
    close(sockfd);

    printf("Done.\n");
    return 0;
}


text:
setopt shwordsplit
SHUNIT_PARENT=$0

source ../zit.zsh

setUp() {
  ZIT_MODULES_PATH="mocks"
}

test_loading_module() {
  local result="$(zit-load "module" "dummy.zsh";
                  echo "ZIT_MODULES_LOADED: ${ZIT_MODULES_LOADED}")"
  local expect="$(cat <<EOF
Hello World!
ZIT_MODULES_LOADED: mocks/module
EOF
  )"
  assertEquals "${expect}" "${result}"
}

test_loading_module_from_non_standard_directory() {
  local result="$(ZIT_MODULES_PATH="mocks/test" zit-load "module" "dummy.zsh";
                  echo "ZIT_MODULES_LOADED: ${ZIT_MODULES_LOADED}")"
  local expect="$(cat <<EOF
Hello World!
ZIT_MODULES_LOADED: mocks/test/module
EOF
  )"
  assertEquals "${expect}" "${result}"
}

test_loading_sh_module() {
  local result="$(emulate sh -c 'zit-load "module" "dummy.sh"')"
  assertEquals "Hello World!" "${result}"
}

test_loading_bash_module() {
  local result="$(emulate bash -c 'zit-load "module" "dummy.bash"')"
  assertEquals "Hello World!" "${result}"
}

test_loading_module_with_space() {
  local result="$(zit-load "another module" "dummy.zsh")"
  assertEquals "Another Hello World!" "${result}"
}

test_missing_param_module_dir() {
  local result="$(zit-load)"
  assertEquals "[zit] Missing argument: Module directory" "${result}"
}

test_missing_param_dot_zsh() {
  local result="$(zit-load "module")"
  assertEquals "[zit] Missing argument: .zsh file" "${result}"
}

source ./shunit2/src/shunit2


text:
import mock
from oslo_concurrency import processutils as putils

from cinder import context
from cinder import exception
from cinder.tests.unit.targets import targets_fixture as tf
from cinder import utils
from cinder.volume.targets import lio

class TestLioAdmDriver(tf.TargetDriverFixture):

    def setUp(self):
        super(TestLioAdmDriver, self).setUp()

        with mock.patch.object(lio.LioAdm, '_verify_rtstool'):
            self.target = lio.LioAdm(root_helper=utils.get_root_helper(),
                                     configuration=self.configuration)
        self.target.db = mock.MagicMock(
            volume_get=lambda x, y: {'provider_auth': 'IncomingUser foo bar'})

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_get_target(self, mexecute, mpersist_cfg, mlock_exec):
        mexecute.return_value = (self.test_vol, None)
        self.assertEqual(self.test_vol, self.target._get_target(self.test_vol))
        self.assertFalse(mpersist_cfg.called)
        expected_args = ('cinder-rtstool', 'get-targets')
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)

    def test_get_iscsi_target(self):
        ctxt = context.get_admin_context()
        expected = 0
        self.assertEqual(expected,
                         self.target._get_iscsi_target(ctxt,
                                                       self.testvol['id']))

    def test_get_target_and_lun(self):
        lun = 0
        iscsi_target = 0
        ctxt = context.get_admin_context()
        expected = (iscsi_target, lun)
        self.assertEqual(expected,
                         self.target._get_target_and_lun(ctxt, self.testvol))

    def test_get_target_chap_auth(self):
        ctxt = context.get_admin_context()
        self.assertEqual(('foo', 'bar'),
                         self.target._get_target_chap_auth(ctxt,
                                                           self.test_vol))

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    @mock.patch.object(lio.LioAdm, '_get_target')
    def test_create_iscsi_target(self, mget_target, mexecute, mpersist_cfg,
                                 mlock_exec):

        mget_target.return_value = 1
        # create_iscsi_target sends volume_name instead of volume_id on error
        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                self.test_vol,
                1,
                0,
                self.fake_volumes_dir))
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)
        mexecute.assert_called_once_with(
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            self.test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            run_as_root=True)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch.object(utils, 'execute')
    @mock.patch.object(lio.LioAdm, '_get_target', return_value=1)
    def test_create_iscsi_target_port_ip(self, mget_target, mexecute,
                                         mpersist_cfg, mlock_exec):
        ip = '10.0.0.15'
        port = 3261

        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                name=self.test_vol,
                tid=1,
                lun=0,
                path=self.fake_volumes_dir,
                **{'portals_port': port, 'portals_ips': [ip]}))

        expected_args = (
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            self.test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            '-p%s' % port,
            '-a' + ip)

        mlock_exec.assert_any_call(*expected_args, run_as_root=True)
        mexecute.assert_any_call(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch.object(utils, 'execute')
    @mock.patch.object(lio.LioAdm, '_get_target', return_value=1)
    def test_create_iscsi_target_port_ips(self, mget_target, mexecute,
                                          mpersist_cfg, mlock_exec):
        test_vol = 'iqn.2010-10.org.openstack:' + self.VOLUME_NAME
        ips = ['10.0.0.15', '127.0.0.1']
        port = 3261

        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                name=test_vol,
                tid=1,
                lun=0,
                path=self.fake_volumes_dir,
                **{'portals_port': port, 'portals_ips': ips}))

        expected_args = (
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            '-p%s' % port,
            '-a' + ','.join(ips))

        mlock_exec.assert_any_call(*expected_args, run_as_root=True)
        mexecute.assert_any_call(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute',
                side_effect=putils.ProcessExecutionError)
    @mock.patch.object(lio.LioAdm, '_get_target')
    def test_create_iscsi_target_already_exists(self, mget_target, mexecute,
                                                mpersist_cfg, mlock_exec):
        chap_auth = ('foo', 'bar')
        self.assertRaises(exception.ISCSITargetCreateFailed,
                          self.target.create_iscsi_target,
                          self.test_vol,
                          1,
                          0,
                          self.fake_volumes_dir,
                          chap_auth)
        self.assertFalse(mpersist_cfg.called)
        expected_args = ('cinder-rtstool', 'create', self.fake_volumes_dir,
                         self.test_vol, chap_auth[0], chap_auth[1], False)
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_remove_iscsi_target(self, mexecute, mpersist_cfg, mlock_exec):
        # Test the normal case
        self.target.remove_iscsi_target(0,
                                        0,
                                        self.testvol['id'],
                                        self.testvol['name'])
        expected_args = ('cinder-rtstool', 'delete',
                         self.iscsi_target_prefix + self.testvol['name'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

        # Test the failure case: putils.ProcessExecutionError
        mlock_exec.reset_mock()
        mpersist_cfg.reset_mock()
        mexecute.side_effect = putils.ProcessExecutionError
        self.assertRaises(exception.ISCSITargetRemoveFailed,
                          self.target.remove_iscsi_target,
                          0,
                          0,
                          self.testvol['id'],
                          self.testvol['name'])
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)

        # Ensure there have been no calls to persist configuration
        self.assertFalse(mpersist_cfg.called)

    @mock.patch.object(lio.LioAdm, '_get_target_chap_auth')
    @mock.patch.object(lio.LioAdm, 'create_iscsi_target')
    def test_ensure_export(self, _mock_create, mock_get_chap):

        ctxt = context.get_admin_context()
        mock_get_chap.return_value = ('foo', 'bar')
        self.target.ensure_export(ctxt,
                                  self.testvol,
                                  self.fake_volumes_dir)

        _mock_create.assert_called_once_with(
            self.iscsi_target_prefix + 'testvol',
            0, 0, self.fake_volumes_dir, ('foo', 'bar'),
            check_exit_code=False,
            old_name=None,
            portals_ips=[self.configuration.iscsi_ip_address],
            portals_port=self.configuration.iscsi_port)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    @mock.patch.object(lio.LioAdm, '_get_iscsi_properties')
    def test_initialize_connection(self, mock_get_iscsi, mock_execute,
                                   mpersist_cfg, mlock_exec):
        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id
        connector = {'initiator': 'fake_init'}

        # Test the normal case
        mock_get_iscsi.return_value = 'foo bar'
        expected_return = {'driver_volume_type': 'iscsi',
                           'data': 'foo bar'}
        self.assertEqual(expected_return,
                         self.target.initialize_connection(self.testvol,
                                                           connector))

        expected_args = ('cinder-rtstool', 'add-initiator', target_id,
                         self.expected_iscsi_properties['auth_username'],
                         '2FE0CQ8J196R', connector['initiator'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mock_execute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

        # Test the failure case: putils.ProcessExecutionError
        mlock_exec.reset_mock()
        mpersist_cfg.reset_mock()
        mock_execute.side_effect = putils.ProcessExecutionError
        self.assertRaises(exception.ISCSITargetAttachFailed,
                          self.target.initialize_connection,
                          self.testvol,
                          connector)

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)

        # Ensure there have been no calls to persist configuration
        self.assertFalse(mpersist_cfg.called)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_terminate_connection(self, mock_execute, mpersist_cfg,
                                  mlock_exec):

        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id

        connector = {'initiator': 'fake_init'}
        self.target.terminate_connection(self.testvol,
                                         connector)
        expected_args = ('cinder-rtstool', 'delete-initiator', target_id,
                         connector['initiator'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mock_execute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_terminate_connection_fail(self, mock_execute, mpersist_cfg,
                                       mlock_exec):

        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id
        mock_execute.side_effect = putils.ProcessExecutionError
        connector = {'initiator': 'fake_init'}
        self.assertRaises(exception.ISCSITargetDetachFailed,
                          self.target.terminate_connection,
                          self.testvol,
                          connector)
        mlock_exec.assert_called_once_with('cinder-rtstool',
                                           'delete-initiator', target_id,
                                           connector['initiator'],
                                           run_as_root=True)
        self.assertFalse(mpersist_cfg.called)

    def test_iscsi_protocol(self):
        self.assertEqual(self.target.iscsi_protocol, 'iscsi')

    @mock.patch.object(lio.LioAdm, '_get_target_and_lun', return_value=(1, 2))
    @mock.patch.object(lio.LioAdm, 'create_iscsi_target', return_value=3)
    @mock.patch.object(lio.LioAdm, '_get_target_chap_auth',
                       return_value=(mock.sentinel.user, mock.sentinel.pwd))
    def test_create_export(self, mock_chap, mock_create, mock_get_target):
        ctxt = context.get_admin_context()
        result = self.target.create_export(ctxt, self.testvol_2,
                                           self.fake_volumes_dir)

        loc = (u'%(ip)s:%(port)d,3 %(prefix)s%(name)s 2' %
               {'ip': self.configuration.iscsi_ip_address,
                'port': self.configuration.iscsi_port,
                'prefix': self.iscsi_target_prefix,
                'name': self.testvol_2['name']})

        expected_result = {
            'location': loc,
            'auth': 'CHAP %s %s' % (mock.sentinel.user, mock.sentinel.pwd),
        }

        self.assertEqual(expected_result, result)

        mock_create.assert_called_once_with(
            self.iscsi_target_prefix + self.testvol_2['name'],
            1,
            2,
            self.fake_volumes_dir,
            (mock.sentinel.user, mock.sentinel.pwd),
            portals_ips=[self.configuration.iscsi_ip_address],
            portals_port=self.configuration.iscsi_port)


text:
package org.smartdata.hdfs.action;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.junit.Assert;
import org.junit.Test;
import org.smartdata.hdfs.MiniClusterHarness;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class TestAppendFileAction extends MiniClusterHarness {
  private void appendFile(String src, long length) throws IOException {
    Map<String, String> args = new HashMap<>();
    args.put(AppendFileAction.FILE_PATH, src);
    args.put(AppendFileAction.LENGTH, "" + length);
    AppendFileAction appendFileAction = new AppendFileAction();
    appendFileAction.setDfsClient(dfsClient);
    appendFileAction.setContext(smartContext);
    appendFileAction.init(args);
    appendFileAction.setConf(smartContext.getConf());
    appendFileAction.run();
    Assert.assertTrue(appendFileAction.getExpectedAfterRun());
  }

  @Test
  public void testInit() throws IOException {
    Map<String, String> args = new HashMap<>();
    args.put(AppendFileAction.FILE_PATH, "/Test");
    args.put(AppendFileAction.LENGTH, "100000000000000");
    AppendFileAction appendFileAction = new AppendFileAction();
    appendFileAction.init(args);
    args.put(AppendFileAction.BUF_SIZE, "1024");
    appendFileAction.init(args);
  }

  @Test
  public void testAppendNonExistFile() throws UnsupportedEncodingException {
    Map<String, String> args = new HashMap<>();
    args.put(WriteFileAction.FILE_PATH, "/Test");
    AppendFileAction appendFileAction = new AppendFileAction();
    appendFileAction.init(args);
    appendFileAction.run();
    Assert.assertNotNull(appendFileAction.getActionStatus().getThrowable());
  }

  @Test
  public void testAppendFile() throws IOException {
    Path src = new Path("/srcFile");
    int size = 1024;
    int appendLength = 1024;
    DFSTestUtil.createFile(dfs, src, size, (short)3, 0xFEED);
    appendFile("/srcFile", 1024);
    FileStatus fileStatus = dfs.getFileStatus(src);
    Assert.assertEquals(size + appendLength, fileStatus.getLen());
  }
}


text:
Orchard Core is a redevelopment of [Orchard CMS](https://github.com/OrchardCMS/Orchard) on [ASP.NET Core](https://docs.microsoft.com/aspnet/core/).

Orchard Core consists of two different targets:

- **Orchard Core Framework**: An application framework for building **modular**, **multi-tenant** applications on ASP.NET Core.
- **Orchard Core CMS**: A Web Content Management System (CMS) built on top of the Orchard Core Framework.

It's important to note the differences between the framework and the CMS. Some developers who want to develop SaaS applications will only be interested in the modular framework. Others who want to build administrable websites will focus on the CMS and build modules to enhance their sites or the whole ecosystem.

[![Join the chat at https://gitter.im/OrchardCMS/OrchardCore](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/OrchardCMS/OrchardCore?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![BSD-3-Clause License](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](https://github.com/OrchardCMS/OrchardCore/blob/master/LICENSE)
[![Documentation](https://readthedocs.org/projects/orchardcore/badge/)](https://docs.orchardcore.net/)
[![Crowdin](https://badges.crowdin.net/orchard-core/localized.svg)](https://crowdin.com/project/orchard-core)

## Building Software as a Service (SaaS) solutions with the Orchard Core Framework

It's very important to understand the Orchard Core Framework is distributed independently from the CMS on nuget.org. We've made some sample applications on <https://github.com/OrchardCMS/OrchardCore.Samples> that will guide you on how to build **modular** and **multi-tenant** applications using just Orchard Core Framework without any of the CMS specific features.

One of our goals is to enable community-based ecosystems of hosted applications which can be extended with modules, like e-commerce systems, blog engines and more. The Orchard Core Framework enables a modular environment that allows different teams to work on separate parts of an application and make components reusable across projects.

## Building Website with Orchard Core CMS

Orchard Core CMS is a complete rewrite of Orchard CMS on ASP.NET Core. It's not just a port as we wanted to improve the performance drastically and align as close as possible to the development models of ASP.NET Core.

- **Performance**. This might the most obvious change when you start using Orchard Core CMS. It's extremely fast for a CMS. So fast that we haven't even cared about working on an output cache module. To give you an idea, without caching Orchard Core CMS is around 20 times faster than the previous version.

- **Portable**. You can now develop and deploy Orchard Core CMS on Windows, Linux and macOS. We also have Docker images ready for use.

- **Document database** abstraction. Orchard Core CMS still requires a relational database, and is compatible with SQL Server, MySQL, PostgreSQL and SQLite, but it's now using a document abstraction (YesSql) that provides a document database API to store and query documents. This is a much better approach for CMS systems and helps performance significantly.

- **NuGet Packages**. Modules and themes are now shared as NuGet packages. Creating a new website with Orchard Core CMS is actually as simple as referencing a single meta package from the NuGet gallery. It also means that updating to a newer version only involves updating the version number of this package.

- **Live preview**. When editing a content item, you can now see live how it will look like on your site, even before saving your content. And it also works for templates, where you can browse any page to inspect the impact of a change on templates as you type it.

- **Liquid templates support**. Editors can safely change the HTML templates with the Liquid template language. It was chosen as it's both very well documented (Jekyll, Shopify, …) and secure.

- **Custom queries**. We wanted to provide a way for developers to access all their data as simply as possible. We created a module that lets you create custom ad-hoc SQL and Lucene queries that can be re-used to display custom content, or exposed as API endpoints. You can use it to create efficient queries, or expose your data to SPA applications.

- **Deployment plans**. Deployment plans are scripts that can contain content and metadata to build a website. You can now include binary files, and even use them to deploy your sites remotely from a staging to a production environment for instance. They can also be part of NuGet Packages, allowing you to ship predefined websites.

- **Scalability**. Because Orchard Core is a multi-tenant system, you can host as many websites as you want with a single deployment. A typical cloud machine can then host thousands of sites in parallel, with database, content, theme and user isolation.

- **Workflows**. Create content approval workflows, react to webhooks, take actions when forms are submitted, and any other process you'd like to implement with a user friendly UI.

- **GraphQL**. We provide a very flexible GraphQL API, such that any authorized external application can reuse your content, like SPA applications or static site generators.

### Different website building strategies

Orchard Core CMS supports all major site building strategies:

- **Full CMS**. In this mode, the website uses a theme and templates to render your content, aiming for little to no custom development at all.

- **Decoupled CMS**. The site starts off blank, apart from the content management back-end. You create all the templates you need with Razor Pages or MVC actions and access your content via the content services. Ref: <https://www.youtube.com/watch?v=yWpz8p-oaKg>

- **Headless CMS**. The site only manages the content, and you create a separate application that will fetch the managed content using GraphQL or REST APIs. Ref: <https://www.youtube.com/watch?v=4o9zG17cfa0>

## Status

The latest released version of Orchard Core is `1.0.0-rc2`.
The release notes can be found on <https://github.com/OrchardCMS/OrchardCore/releases/tag/1.0.0-rc2>

The software is almost ready for final release. No feature development or enhancement of the software is undertaken; tightly scoped bug fixes are the only code you're allowed to write in this phase, and even then only for the most heinous and debilitating of bugs.

Here is a more detailed [roadmap](https://github.com/OrchardCMS/OrchardCore/wiki/Roadmap).

## Getting Started

- Clone the repository using the command `git clone https://github.com/OrchardCMS/OrchardCore.git` and checkout the `master` branch for the latest release, or the `dev` branch for the cutting-edge version.

- Watch the ASP.NET Community Standup video where Orchard Core was demonstrated: <https://www.youtube.com/watch?v=HeDjv3blBjQ&t=2246s&list=PL1rZQsJPBU2StolNg0aqvQswETPcYnNKL&index=24>

- Follow the samples on <https://github.com/OrchardCMS/OrchardCore.Samples> that will guide you on how to build **modular** and **multi-tenant** applications

- Follow the tutorial inside the [Training Demo Module](https://github.com/Lombiq/Orchard-Training-Demo-Module) to learn how to develop Orchard Core modules.

### Command line

- Install the latest version of the .NET Core SDK from this page <https://www.microsoft.com/net/download/core>
- Next, navigate to `D:\OrchardCore\src\OrchardCore.Cms.Web` or wherever your folder is on the commandline in Administrator mode.
- Call `dotnet run`.
- Then open the `http://localhost:5000` URL in your browser.

You can also read the [Code Generation Templates documentation](docs/getting-started/templates/README.md) to create new applications from predefined templates.

### Visual Studio

- Download Visual Studio 2019 (any edition) from <https://www.visualstudio.com/downloads/>.
- Open `OrchardCore.sln` and wait for Visual Studio to restore all Nuget packages.
- Ensure `OrchardCore.Cms.Web` is the startup project and run it.
- Optionally install the [Lombiq Orchard Visual Studio Extension](https://marketplace.visualstudio.com/items?itemName=LombiqVisualStudioExtension.LombiqOrchardVisualStudioExtension) to add some useful utilities to your Visual Studio such as an error log watcher or a dependency injector.

### Docker

- Run `docker run --name orchardcms orchardproject/orchardcore-cms-linux:latest`

Docker images and parameters can be found at <https://hub.docker.com/u/orchardproject/>


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

#include "client/crashpad_client.h"

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/futex.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <atomic>

#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "client/client_argv_handling.h"
#include "third_party/lss/lss.h"
#include "util/file/file_io.h"
#include "util/file/filesystem.h"
#include "util/linux/exception_handler_client.h"
#include "util/linux/exception_information.h"
#include "util/linux/scoped_pr_set_dumpable.h"
#include "util/linux/scoped_pr_set_ptracer.h"
#include "util/linux/socket.h"
#include "util/misc/address_sanitizer.h"
#include "util/misc/from_pointer_cast.h"
#include "util/posix/scoped_mmap.h"
#include "util/posix/signals.h"
#include "util/posix/spawn_subprocess.h"

namespace crashpad {

namespace {

std::string FormatArgumentInt(const std::string& name, int value) {
  return base::StringPrintf("--%s=%d", name.c_str(), value);
}

std::string FormatArgumentAddress(const std::string& name, const void* addr) {
  return base::StringPrintf("--%s=%p", name.c_str(), addr);
}

#if BUILDFLAG(IS_ANDROID)

std::vector<std::string> BuildAppProcessArgs(
    const std::string& class_name,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    int socket) {
#if defined(ARCH_CPU_64_BITS)
  static constexpr char kAppProcess[] = "/system/bin/app_process64";
#else
  static constexpr char kAppProcess[] = "/system/bin/app_process32";
#endif

  std::vector<std::string> argv;
  argv.push_back(kAppProcess);
  argv.push_back("/system/bin");
  argv.push_back("--application");
  argv.push_back(class_name);

  std::vector<std::string> handler_argv =
      BuildHandlerArgvStrings(base::FilePath(kAppProcess),
                              database,
                              metrics_dir,
                              url,
                              annotations,
                              arguments);

  if (socket != kInvalidFileHandle) {
    handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
  }

  argv.insert(argv.end(), handler_argv.begin(), handler_argv.end());
  return argv;
}

std::vector<std::string> BuildArgsToLaunchWithLinker(
    const std::string& handler_trampoline,
    const std::string& handler_library,
    bool is_64_bit,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    int socket) {
  std::vector<std::string> argv;
  if (is_64_bit) {
    argv.push_back("/system/bin/linker64");
  } else {
    argv.push_back("/system/bin/linker");
  }
  argv.push_back(handler_trampoline);
  argv.push_back(handler_library);

  std::vector<std::string> handler_argv = BuildHandlerArgvStrings(
      base::FilePath(), database, metrics_dir, url, annotations, arguments);

  if (socket != kInvalidFileHandle) {
    handler_argv.push_back(FormatArgumentInt("initial-client-fd", socket));
  }

  argv.insert(argv.end(), handler_argv.begin() + 1, handler_argv.end());
  return argv;
}

#endif  // BUILDFLAG(IS_ANDROID)

// A base class for Crashpad signal handler implementations.
class SignalHandler {
 public:
  SignalHandler(const SignalHandler&) = delete;
  SignalHandler& operator=(const SignalHandler&) = delete;

  // Returns the currently installed signal hander. May be `nullptr` if no
  // handler has been installed.
  static SignalHandler* Get() { return handler_; }

  // Disables any installed Crashpad signal handler. If a crash signal is
  // received, any previously installed (non-Crashpad) signal handler will be
  // restored and the signal reraised.
  static void Disable() {
    if (!handler_->disabled_.test_and_set()) {
      handler_->WakeThreads();
    }
  }

  void SetFirstChanceHandler(CrashpadClient::FirstChanceHandler handler) {
    first_chance_handler_ = handler;
  }

  // The base implementation for all signal handlers, suitable for calling
  // directly to simulate signal delivery.
  void HandleCrash(int signo, siginfo_t* siginfo, void* context) {
    exception_information_.siginfo_address =
        FromPointerCast<decltype(exception_information_.siginfo_address)>(
            siginfo);
    exception_information_.context_address =
        FromPointerCast<decltype(exception_information_.context_address)>(
            context);
    exception_information_.thread_id = sys_gettid();

    ScopedPrSetDumpable set_dumpable(false);
    HandleCrashImpl();
  }

 protected:
  SignalHandler() = default;
  ~SignalHandler() = default;

  bool Install(const std::set<int>* unhandled_signals) {
    bool signal_stack_initialized =
        CrashpadClient::InitializeSignalStackForThread();
    DCHECK(signal_stack_initialized);

    DCHECK(!handler_);
    handler_ = this;
    return Signals::InstallCrashHandlers(
        HandleOrReraiseSignal, SA_ONSTACK, &old_actions_, unhandled_signals);
  }

  const ExceptionInformation& GetExceptionInfo() {
    return exception_information_;
  }

  virtual void HandleCrashImpl() = 0;

 private:
  static constexpr int32_t kDumpNotDone = 0;
  static constexpr int32_t kDumpDone = 1;

  // The signal handler installed at OS-level.
  static void HandleOrReraiseSignal(int signo,
                                    siginfo_t* siginfo,
                                    void* context) {
    if (handler_->first_chance_handler_ &&
        handler_->first_chance_handler_(
            signo, siginfo, static_cast<ucontext_t*>(context))) {
      return;
    }

    // Only handle the first fatal signal observed. If another thread receives a
    // crash signal, it waits for the first dump to complete instead of
    // requesting another.
    if (!handler_->disabled_.test_and_set()) {
      handler_->HandleCrash(signo, siginfo, context);
      handler_->WakeThreads();
    } else {
      // Processes on Android normally have several chained signal handlers that
      // co-operate to report crashes. e.g. WebView will have this signal
      // handler installed, the app embedding WebView may have a signal handler
      // installed, and Bionic will have a signal handler. Each signal handler
      // runs in succession, possibly managed by libsigchain. This wait is
      // intended to avoid ill-effects from multiple signal handlers from
      // different layers (possibly all trying to use ptrace()) from running
      // simultaneously. It does not block forever so that in most conditions,
      // those signal handlers will still have a chance to run and ensures
      // process termination in case the first crashing thread crashes again in
      // its signal handler. Though less typical, this situation also occurs on
      // other Linuxes, e.g. to produce in-process stack traces for debug
      // builds.
      handler_->WaitForDumpDone();
    }

    Signals::RestoreHandlerAndReraiseSignalOnReturn(
        siginfo, handler_->old_actions_.ActionForSignal(signo));
  }

  void WaitForDumpDone() {
    kernel_timespec timeout;
    timeout.tv_sec = 5;
    timeout.tv_nsec = 0;
    sys_futex(&dump_done_futex_,
              FUTEX_WAIT_PRIVATE,
              kDumpNotDone,
              &timeout,
              nullptr,
              0);
  }

  void WakeThreads() {
    dump_done_futex_ = kDumpDone;
    sys_futex(
        &dump_done_futex_, FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
  }

  Signals::OldActions old_actions_ = {};
  ExceptionInformation exception_information_ = {};
  CrashpadClient::FirstChanceHandler first_chance_handler_ = nullptr;
  int32_t dump_done_futex_ = kDumpNotDone;
#if !defined(__cpp_lib_atomic_value_initialization) || \
    __cpp_lib_atomic_value_initialization < 201911L
  std::atomic_flag disabled_ = ATOMIC_FLAG_INIT;
#else
  std::atomic_flag disabled_;
#endif

  static SignalHandler* handler_;
};
SignalHandler* SignalHandler::handler_ = nullptr;

// Launches a single use handler to snapshot this process.
class LaunchAtCrashHandler : public SignalHandler {
 public:
  LaunchAtCrashHandler(const LaunchAtCrashHandler&) = delete;
  LaunchAtCrashHandler& operator=(const LaunchAtCrashHandler&) = delete;

  static LaunchAtCrashHandler* Get() {
    static LaunchAtCrashHandler* instance = new LaunchAtCrashHandler();
    return instance;
  }

  bool Initialize(std::vector<std::string>* argv_in,
                  const std::vector<std::string>* envp,
                  const std::set<int>* unhandled_signals) {
    argv_strings_.swap(*argv_in);

    if (envp) {
      envp_strings_ = *envp;
      StringVectorToCStringVector(envp_strings_, &envp_);
      set_envp_ = true;
    }

    argv_strings_.push_back(FormatArgumentAddress("trace-parent-with-exception",
                                                  &GetExceptionInfo()));

    StringVectorToCStringVector(argv_strings_, &argv_);
    return Install(unhandled_signals);
  }

  void HandleCrashImpl() override {
    ScopedPrSetPtracer set_ptracer(sys_getpid(), /* may_log= */ false);

    pid_t pid = fork();
    if (pid < 0) {
      return;
    }
    if (pid == 0) {
      if (set_envp_) {
        execve(argv_[0],
               const_cast<char* const*>(argv_.data()),
               const_cast<char* const*>(envp_.data()));
      } else {
        execv(argv_[0], const_cast<char* const*>(argv_.data()));
      }
      _exit(EXIT_FAILURE);
    }

    int status;
    waitpid(pid, &status, 0);
  }

 private:
  LaunchAtCrashHandler() = default;

  ~LaunchAtCrashHandler() = delete;

  std::vector<std::string> argv_strings_;
  std::vector<const char*> argv_;
  std::vector<std::string> envp_strings_;
  std::vector<const char*> envp_;
  bool set_envp_ = false;
};

class RequestCrashDumpHandler : public SignalHandler {
 public:
  RequestCrashDumpHandler(const RequestCrashDumpHandler&) = delete;
  RequestCrashDumpHandler& operator=(const RequestCrashDumpHandler&) = delete;

  static RequestCrashDumpHandler* Get() {
    static RequestCrashDumpHandler* instance = new RequestCrashDumpHandler();
    return instance;
  }

  // pid < 0 indicates the handler pid should be determined by communicating
  // over the socket.
  // pid == 0 indicates it is not necessary to set the handler as this process'
  // ptracer. e.g. if the handler has CAP_SYS_PTRACE or if this process is in a
  // user namespace and the handler's uid matches the uid of the process that
  // created the namespace.
  // pid > 0 directly indicates what the handler's pid is expected to be, so
  // retrieving this information from the handler is not necessary.
  bool Initialize(ScopedFileHandle sock,
                  pid_t pid,
                  const std::set<int>* unhandled_signals) {
    ExceptionHandlerClient client(sock.get(), true);
    if (pid < 0) {
      ucred creds;
      if (!client.GetHandlerCredentials(&creds)) {
        return false;
      }
      pid = creds.pid;
    }
    if (pid > 0) {
      pthread_atfork(nullptr, nullptr, SetPtracerAtFork);
      if (prctl(PR_SET_PTRACER, pid, 0, 0, 0) != 0) {
        PLOG(WARNING) << "prctl";
      }
    }
    sock_to_handler_.reset(sock.release());
    handler_pid_ = pid;
    return Install(unhandled_signals);
  }

  bool GetHandlerSocket(int* sock, pid_t* pid) {
    if (!sock_to_handler_.is_valid()) {
      return false;
    }
    if (sock) {
      *sock = sock_to_handler_.get();
    }
    if (pid) {
      *pid = handler_pid_;
    }
    return true;
  }

  void HandleCrashImpl() override {
    // Attempt to set the ptracer again, in case a crash occurs after a fork,
    // before SetPtracerAtFork() has been called. Ignore errors because the
    // system call may be disallowed if the sandbox is engaged.
    if (handler_pid_ > 0) {
      sys_prctl(PR_SET_PTRACER, handler_pid_, 0, 0, 0);
    }

    ExceptionHandlerProtocol::ClientInformation info = {};
    info.exception_information_address =
        FromPointerCast<VMAddress>(&GetExceptionInfo());
#if BUILDFLAG(IS_CHROMEOS_ASH)
    info.crash_loop_before_time = crash_loop_before_time_;
#endif

    ExceptionHandlerClient client(sock_to_handler_.get(), true);
    client.RequestCrashDump(info);
  }

#if BUILDFLAG(IS_CHROMEOS_ASH)
  void SetCrashLoopBefore(uint64_t crash_loop_before_time) {
    crash_loop_before_time_ = crash_loop_before_time;
  }
#endif

 private:
  RequestCrashDumpHandler() = default;

  ~RequestCrashDumpHandler() = delete;

  static void SetPtracerAtFork() {
    auto handler = RequestCrashDumpHandler::Get();
    if (handler->handler_pid_ > 0 &&
        prctl(PR_SET_PTRACER, handler->handler_pid_, 0, 0, 0) != 0) {
      PLOG(WARNING) << "prctl";
    }
  }

  ScopedFileHandle sock_to_handler_;
  pid_t handler_pid_ = -1;

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // An optional UNIX timestamp passed to us from Chrome.
  // This will pass to crashpad_handler and then to Chrome OS crash_reporter.
  // This should really be a time_t, but it's basically an opaque value (we
  // don't anything with it except pass it along).
  uint64_t crash_loop_before_time_ = 0;
#endif
};

}  // namespace

CrashpadClient::CrashpadClient() {}

CrashpadClient::~CrashpadClient() {}

bool CrashpadClient::StartHandler(
    const base::FilePath& handler,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    bool restartable,
    bool asynchronous_start,
    const std::vector<base::FilePath>& attachments) {
  DCHECK(!asynchronous_start);

  ScopedFileHandle client_sock, handler_sock;
  if (!UnixCredentialSocket::CreateCredentialSocketpair(&client_sock,
                                                        &handler_sock)) {
    return false;
  }

  std::vector<std::string> argv = BuildHandlerArgvStrings(
      handler, database, metrics_dir, url, annotations, arguments, attachments);

  argv.push_back(FormatArgumentInt("initial-client-fd", handler_sock.get()));
  argv.push_back("--shared-client-connection");
  if (!SpawnSubprocess(argv, nullptr, handler_sock.get(), false, nullptr)) {
    return false;
  }
  handler_sock.reset();

  pid_t handler_pid = -1;
  if (!IsRegularFile(base::FilePath("/proc/sys/kernel/yama/ptrace_scope"))) {
    handler_pid = 0;
  }

  auto signal_handler = RequestCrashDumpHandler::Get();
  return signal_handler->Initialize(
      std::move(client_sock), handler_pid, &unhandled_signals_);
}

#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// static
bool CrashpadClient::GetHandlerSocket(int* sock, pid_t* pid) {
  auto signal_handler = RequestCrashDumpHandler::Get();
  return signal_handler->GetHandlerSocket(sock, pid);
}

bool CrashpadClient::SetHandlerSocket(ScopedFileHandle sock, pid_t pid) {
  auto signal_handler = RequestCrashDumpHandler::Get();
  return signal_handler->Initialize(std::move(sock), pid, &unhandled_signals_);
}

// static
bool CrashpadClient::InitializeSignalStackForThread() {
  stack_t stack;
  if (sigaltstack(nullptr, &stack) != 0) {
    PLOG(ERROR) << "sigaltstack";
    return false;
  }

  DCHECK_EQ(stack.ss_flags & SS_ONSTACK, 0);

  const size_t page_size = getpagesize();
#if defined(ADDRESS_SANITIZER)
  const size_t kStackSize = 2 * ((SIGSTKSZ + page_size - 1) & ~(page_size - 1));
#else
  const size_t kStackSize = (SIGSTKSZ + page_size - 1) & ~(page_size - 1);
#endif  // ADDRESS_SANITIZER
  if (stack.ss_flags & SS_DISABLE || stack.ss_size < kStackSize) {
    const size_t kGuardPageSize = page_size;
    const size_t kStackAllocSize = kStackSize + 2 * kGuardPageSize;

    static void (*stack_destructor)(void*) = [](void* stack_mem) {
      const size_t page_size = getpagesize();
      const size_t kGuardPageSize = page_size;
#if defined(ADDRESS_SANITIZER)
      const size_t kStackSize =
          2 * ((SIGSTKSZ + page_size - 1) & ~(page_size - 1));
#else
      const size_t kStackSize = (SIGSTKSZ + page_size - 1) & ~(page_size - 1);
#endif  // ADDRESS_SANITIZER
      const size_t kStackAllocSize = kStackSize + 2 * kGuardPageSize;

      stack_t stack;
      stack.ss_flags = SS_DISABLE;
      if (sigaltstack(&stack, &stack) != 0) {
        PLOG(ERROR) << "sigaltstack";
      } else if (stack.ss_sp !=
                 static_cast<char*>(stack_mem) + kGuardPageSize) {
        PLOG_IF(ERROR, sigaltstack(&stack, nullptr) != 0) << "sigaltstack";
      }

      if (munmap(stack_mem, kStackAllocSize) != 0) {
        PLOG(ERROR) << "munmap";
      }
    };

    static pthread_key_t stack_key;
    static int key_error = []() {
      errno = pthread_key_create(&stack_key, stack_destructor);
      PLOG_IF(ERROR, errno) << "pthread_key_create";
      return errno;
    }();
    if (key_error) {
      return false;
    }

    auto old_stack = static_cast<char*>(pthread_getspecific(stack_key));
    if (old_stack) {
      stack.ss_sp = old_stack + kGuardPageSize;
    } else {
      ScopedMmap stack_mem;
      if (!stack_mem.ResetMmap(nullptr,
                               kStackAllocSize,
                               PROT_NONE,
                               MAP_PRIVATE | MAP_ANONYMOUS,
                               -1,
                               0)) {
        return false;
      }

      if (mprotect(stack_mem.addr_as<char*>() + kGuardPageSize,
                   kStackSize,
                   PROT_READ | PROT_WRITE) != 0) {
        PLOG(ERROR) << "mprotect";
        return false;
      }

      stack.ss_sp = stack_mem.addr_as<char*>() + kGuardPageSize;

      errno = pthread_setspecific(stack_key, stack_mem.release());
      PCHECK(errno == 0) << "pthread_setspecific";
    }

    stack.ss_size = kStackSize;
    stack.ss_flags =
        (stack.ss_flags & SS_DISABLE) ? 0 : stack.ss_flags & SS_AUTODISARM;
    if (sigaltstack(&stack, nullptr) != 0) {
      PLOG(ERROR) << "sigaltstack";
      return false;
    }
  }
  return true;
}
#endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) ||
        // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_ANDROID)

bool CrashpadClient::StartJavaHandlerAtCrash(
    const std::string& class_name,
    const std::vector<std::string>* env,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments) {
  std::vector<std::string> argv = BuildAppProcessArgs(class_name,
                                                      database,
                                                      metrics_dir,
                                                      url,
                                                      annotations,
                                                      arguments,
                                                      kInvalidFileHandle);

  auto signal_handler = LaunchAtCrashHandler::Get();
  return signal_handler->Initialize(&argv, env, &unhandled_signals_);
}

// static
bool CrashpadClient::StartJavaHandlerForClient(
    const std::string& class_name,
    const std::vector<std::string>* env,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    int socket) {
  std::vector<std::string> argv = BuildAppProcessArgs(
      class_name, database, metrics_dir, url, annotations, arguments, socket);
  return SpawnSubprocess(argv, env, socket, false, nullptr);
}

bool CrashpadClient::StartHandlerWithLinkerAtCrash(
    const std::string& handler_trampoline,
    const std::string& handler_library,
    bool is_64_bit,
    const std::vector<std::string>* env,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments) {
  std::vector<std::string> argv =
      BuildArgsToLaunchWithLinker(handler_trampoline,
                                  handler_library,
                                  is_64_bit,
                                  database,
                                  metrics_dir,
                                  url,
                                  annotations,
                                  arguments,
                                  kInvalidFileHandle);
  auto signal_handler = LaunchAtCrashHandler::Get();
  return signal_handler->Initialize(&argv, env, &unhandled_signals_);
}

// static
bool CrashpadClient::StartHandlerWithLinkerForClient(
    const std::string& handler_trampoline,
    const std::string& handler_library,
    bool is_64_bit,
    const std::vector<std::string>* env,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    int socket) {
  std::vector<std::string> argv =
      BuildArgsToLaunchWithLinker(handler_trampoline,
                                  handler_library,
                                  is_64_bit,
                                  database,
                                  metrics_dir,
                                  url,
                                  annotations,
                                  arguments,
                                  socket);
  return SpawnSubprocess(argv, env, socket, false, nullptr);
}

#endif

bool CrashpadClient::StartHandlerAtCrash(
    const base::FilePath& handler,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    const std::vector<base::FilePath>& attachments) {
  std::vector<std::string> argv = BuildHandlerArgvStrings(
      handler, database, metrics_dir, url, annotations, arguments, attachments);

  auto signal_handler = LaunchAtCrashHandler::Get();
  return signal_handler->Initialize(&argv, nullptr, &unhandled_signals_);
}

// static
bool CrashpadClient::StartHandlerForClient(
    const base::FilePath& handler,
    const base::FilePath& database,
    const base::FilePath& metrics_dir,
    const std::string& url,
    const std::map<std::string, std::string>& annotations,
    const std::vector<std::string>& arguments,
    int socket) {
  std::vector<std::string> argv = BuildHandlerArgvStrings(
      handler, database, metrics_dir, url, annotations, arguments);

  argv.push_back(FormatArgumentInt("initial-client-fd", socket));

  return SpawnSubprocess(argv, nullptr, socket, true, nullptr);
}

// static
void CrashpadClient::DumpWithoutCrash(NativeCPUContext* context) {
  if (!SignalHandler::Get()) {
    DLOG(ERROR) << "Crashpad isn't enabled";
    return;
  }

#if defined(ARCH_CPU_ARMEL)
  memset(context->uc_regspace, 0, sizeof(context->uc_regspace));
#elif defined(ARCH_CPU_ARM64)
  memset(context->uc_mcontext.__reserved,
         0,
         sizeof(context->uc_mcontext.__reserved));
#endif

  siginfo_t siginfo;
  siginfo.si_signo = Signals::kSimulatedSigno;
  siginfo.si_errno = 0;
  siginfo.si_code = 0;
  SignalHandler::Get()->HandleCrash(
      siginfo.si_signo, &siginfo, reinterpret_cast<void*>(context));
}

// static
void CrashpadClient::CrashWithoutDump(const std::string& message) {
  SignalHandler::Disable();
  LOG(FATAL) << message;
}

// static
void CrashpadClient::SetFirstChanceExceptionHandler(
    FirstChanceHandler handler) {
  DCHECK(SignalHandler::Get());
  SignalHandler::Get()->SetFirstChanceHandler(handler);
}

void CrashpadClient::SetUnhandledSignals(const std::set<int>& signals) {
  DCHECK(!SignalHandler::Get());
  unhandled_signals_ = signals;
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
// static
void CrashpadClient::SetCrashLoopBefore(uint64_t crash_loop_before_time) {
  auto request_crash_dump_handler = RequestCrashDumpHandler::Get();
  request_crash_dump_handler->SetCrashLoopBefore(crash_loop_before_time);
}
#endif

}  // namespace crashpad