text:
package com.sunny.grokkingalgorithms.ctci.c4.misc;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by sundas on 4/15/2018.
 */
public class RightSideViewOfATree {

  /*
  Right side view of a tree

                      20
                    /    \
                  8       22
                /   \      \
              5      3      25
                    / \
                  10    14
   */

  /**
   *
   * @param root
   */
  public static void printRightSideViewOfATree(BinaryTreeNode root){
    Queue<BinaryTreeNode> queue = new LinkedList<>();
    queue.add(root);
    BinaryTreeNode levelMarker = new BinaryTreeNode();
    queue.add(levelMarker);
    while(!queue.isEmpty()){
      BinaryTreeNode node = queue.poll();
      if(node == levelMarker){
        if(!queue.isEmpty()){
          queue.add(levelMarker);
        }
      }
      else{
        if(queue.peek() == levelMarker){
          System.out.println(node.data);
        }
        if(node.left != null){
          queue.add(node.left);
        }
        if(node.right != null){
          queue.add(node.right);
        }
      }
    }
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode twenty = new BinaryTreeNode();
    twenty.data = 20;
    BinaryTreeNode eight = new BinaryTreeNode();
    eight.data = 8;
    twenty.left = eight;
    BinaryTreeNode twentytwo = new BinaryTreeNode();
    twentytwo.data = 22;
    twenty.right = twentytwo;
    BinaryTreeNode five = new BinaryTreeNode();
    five.data = 5;
    eight.left = five;
    BinaryTreeNode three = new BinaryTreeNode();
    three.data = 3;
    eight.right = three;
    BinaryTreeNode ten = new BinaryTreeNode();
    ten.data = 10;
    three.left = ten;
    BinaryTreeNode fourteen = new BinaryTreeNode();
    fourteen.data = 14;
    three.right = fourteen;
    BinaryTreeNode four = new BinaryTreeNode();
    four.data = 4;
    //twentytwo.left = four;
    BinaryTreeNode twentyfive = new BinaryTreeNode();
    twentyfive.data = 25;
    twentytwo.right = twentyfive;
    TreeUtils.performBfsLevelMarker(twenty);
    System.out.println("right view");
    printRightSideViewOfATree(twenty);
  }

}


text:
<?hh
namespace Titon\Debug\Dumper;

use Titon\Debug\Exception\FatalErrorException;
use Titon\Test\TestCase;

/**
 * @property \Titon\Debug\Dumper\HtmlDumper $object
 */
class HtmlDumperTest extends TestCase {

    protected function setUp(): void {
        parent::setUp();

        $this->object = new HtmlDumper();
    }

    public function testBacktrace(): void {
        $this->assertRegExp('/^
/', trim($this->object->backtrace()));
    }

    public function testDebug(): void {
        $this->assertRegExp('/^
/', $this->object->debug(1));
    }

    public function testDump(): void {
        $this->assertRegExp('/^
/', $this->object->dump(1));
    }

    public function testInspect(): void {
        $this->assertRegExp('/^
/', $this->object->inspect(new FatalErrorException('Systems critical!')));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.mauriciotogneri.tensiontunnel2.entities.behaviors;

import com.mauriciotogneri.mandy.input.Input;
import com.mauriciotogneri.mandy.screen.Camera;
import com.mauriciotogneri.tensiontunnel2.types.IntermittentState;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;

public class IntermittentBehavior implements EnemyBehavior
{
    private final Vec2 positionOn;
    private final Vec2 positionOff;
    private final float timeOn;
    private final float timeOff;
    private final IntermittentState state;

    private float currentTime;
    private IntermittentState currentState;

    public IntermittentBehavior(Vec2 positionOn, float timeOn, Vec2 positionOff, float timeOff, IntermittentState state)
    {
        this.positionOn = positionOn;
        this.positionOff = positionOff;
        this.timeOn = timeOn;
        this.timeOff = timeOff;
        this.state = state;
    }

    @Override
    public void onUpdate(Body body, float delta, Input input, Camera camera)
    {
        currentTime += delta;

        if ((currentState == IntermittentState.ON) && (currentTime >= timeOn))
        {
            currentTime -= timeOn;
            currentState = IntermittentState.OFF;
            updatePosition(body);
        }
        else if ((currentState == IntermittentState.OFF) && (currentTime >= timeOff))
        {
            currentTime -= timeOff;
            currentState = IntermittentState.ON;
            updatePosition(body);
        }
    }

    private void updatePosition(Body body)
    {
        switch (currentState)
        {
            case ON:
                body.setTransform(positionOn, body.getAngle());
                break;

            case OFF:
                body.setTransform(positionOff, body.getAngle());
                break;
        }
    }

    @Override
    public void onStart(Body body)
    {
    }

    @Override
    public void onStop(Body body)
    {
    }

    @Override
    public void onReset(Body body)
    {
        currentState = state;
        currentTime = 0;

        updatePosition(body);
    }
}


text:
package oguth

import (
	"encoding/json"
	"net/http"
	"net/url"
)

type ErrorCode string

var (
	ErrorGrantTypeMissing = &Error{
		Error:            ErrorCodeInvalidRequest,
		ErrorDescription: "Required parameter is missing: grant_type",
	}
	ErrorResponseTypeMissing = &Error{
		Error:            ErrorCodeInvalidRequest,
		ErrorDescription: "Required parameter is missing: response_type",
	}
	ErrorClientIdMissing = &Error{
		Error:            ErrorCodeInvalidRequest,
		ErrorDescription: "Required parameter is missing: client_id",
	}
	ErrorUnavailableScope = &Error{
		Error:            ErrorCodeInvalidScope,
		ErrorDescription: "Unknown scope(s) have been included in the request",
	}
	ErrorUnsupportedGrantType = &Error{
		Error:            ErrorCodeUnsupportedGrantType,
		ErrorDescription: "This grant type is not supported",
	}
	ErrorUnsupportedResponseType = &Error{
		Error:            ErrorCodeUnsupportedResponseType,
		ErrorDescription: "The authorization server does not support obtaining an authorization code using this method",
	}
	ErrorClientNotFound = &Error{
		Error:            ErrorCodeInvalidRequest,
		ErrorDescription: "The OAuth client was not found.",
	}
	ErrorRefreshTokenInvalid = &Error{
		Error:            ErrorCodeInvalidRequest,
		ErrorDescription: "The refresh token is invalid.",
	}
)

const (
	ErrorCodeInvalidRequest          ErrorCode = "invalid_request"
	ErrorCodeUnauthorizedClient                = "unauthorized_client"
	ErrorCodeUnsupportedGrantType              = "unsupported_grant_type"
	ErrorCodeUnsupportedResponseType           = "unsupported_response_type"
	ErrorCodeAccessDenied                      = "access_denied"
	ErrorCodeInvalidScope                      = "invalid_scope"
	ErrorCodeServerError                       = "server_error"
	ErrorCodeTemporarilyUnavailable            = "temporarily_unavailable"
)

type Error struct {
	Error            ErrorCode `json:"error"`
	ErrorDescription string    `json:"error_description"`
	ErrorUri         string    `json:"error_uri"`
	State            string    `json:"state"`
}

func NewError(code ErrorCode) *Error {
	return &Error{
		Error: code,
	}
}

func (e *Error) ToValues() url.Values {
	v := url.Values{
		"error":             {string(e.Error)},
		"error_description": {e.ErrorDescription},
		"error_uri":         {e.ErrorUri},
	}
	if e.State != "" {
		v.Set("state", e.State)
	}
	return v
}

func (e *Error) Write(w http.ResponseWriter) {
	body, _ := json.Marshal(&e)
	w.Write(body)
}


text:
from activitystreams.models.activity import Activity

from dino import environ
from dino.config import SessionKeys

__author__ = 'Oscar Eriksson <oscar.eriks@gmail.com>'

class BaseValidator(object):
    def validate_request(self, activity: Activity) -> (bool, str):
        if not hasattr(activity.actor, 'id') or activity.actor.id is None:
            return False, 'no ID on actor'

        session_user_id = environ.env.session.get('user_id', 'NOT_FOUND_IN_SESSION')
        if str(activity.actor.id).strip() != str(session_user_id).strip():
            error_msg = "user_id in session '%s' doesn't match user_id in request '%s'"
            return False, error_msg % (session_user_id, activity.actor.id)

        return True, None

    def validate_login(self, user_id: str, token: str) -> (bool, str):
        """
        checks whether required data was received and that it validates with community (not tampered with)

        :param user_id: the id of the user
        :param token: the token of the user to verify
        :return: tuple(Boolean, String): (is_valid, error_message)
        """
        is_valid, error_msg, session = environ.env.auth.authenticate_and_populate_session(user_id, token)
        if not is_valid:
            return False, error_msg, None

        is_valid, error_msg = self.validate_session(session)
        return is_valid, error_msg, session

    def validate_session(self, session: dict) -> (bool, str):
        """
        validate that all required parameters were send from the client side

        :param session: the session dict to validate
        :return: tuple(Boolean, String): (is_valid, error_message)
        """
        for session_key in SessionKeys:
            key = session_key.value

            if key not in SessionKeys.requires_session_keys.value:
                continue

            if key not in session:
                return False, '"%s" is a required parameter' % key

            val = session[key]
            if val is None or val == '':
                return False, '"%s" is a required parameter' % key
        return True, None


text:
import $ from "jquery";

import render_add_alert_word from "../templates/settings/add_alert_word.hbs";
import render_alert_word_settings_item from "../templates/settings/alert_word_settings_item.hbs";

import * as alert_words from "./alert_words";
import * as channel from "./channel";
import * as dialog_widget from "./dialog_widget";
import {$t, $t_html} from "./i18n";
import * as ListWidget from "./list_widget";
import * as ui_report from "./ui_report";

export let loaded = false;

export function rerender_alert_words_ui() {
    if (!loaded) {
        return;
    }

    const words = alert_words.get_word_list();
    words.sort();
    const $word_list = $("#alert-words-table");

    ListWidget.create($word_list, words, {
        name: "alert-words-list",
        modifier(alert_word) {
            return render_alert_word_settings_item({alert_word});
        },
        $parent_container: $("#alert-word-settings"),
        $simplebar_container: $("#alert-word-settings .progressive-table-wrapper"),
    });
}

function update_alert_word_status(status_text, is_error) {
    const $alert_word_status = $("#alert_word_status");
    if (is_error) {
        $alert_word_status.removeClass("alert-success").addClass("alert-danger");
    } else {
        $alert_word_status.removeClass("alert-danger").addClass("alert-success");
    }
    $alert_word_status.find(".alert_word_status_text").text(status_text);
    $alert_word_status.show();
}

function add_alert_word(e) {
    e.preventDefault();
    e.stopPropagation();

    const alert_word = $("#add-alert-word-name").val().trim();

    if (alert_words.has_alert_word(alert_word)) {
        ui_report.client_error(
            $t({defaultMessage: "Alert word already exists!"}),
            $("#dialog_error"),
        );
        dialog_widget.hide_dialog_spinner();
        return;
    }

    const words_to_be_added = [alert_word];

    const data = {alert_words: JSON.stringify(words_to_be_added)};
    dialog_widget.submit_api_request(channel.post, "/json/users/me/alert_words", data);
}

function remove_alert_word(alert_word) {
    const words_to_be_removed = [alert_word];
    channel.del({
        url: "/json/users/me/alert_words",
        data: {alert_words: JSON.stringify(words_to_be_removed)},
        success() {
            update_alert_word_status(
                $t(
                    {defaultMessage: `Alert word "{alert_word}" removed successfully!`},
                    {alert_word},
                ),
                false,
            );
        },
        error() {
            update_alert_word_status($t({defaultMessage: "Error removing alert word!"}), true);
        },
    });
}

export function show_add_alert_word_modal() {
    const html_body = render_add_alert_word();

    function add_alert_word_post_render() {
        const $add_user_group_input_element = $("#add-alert-word-name");
        const $add_user_group_submit_button = $("#add-alert-word .dialog_submit_button");
        $add_user_group_submit_button.prop("disabled", true);

        $add_user_group_input_element.on("input", () => {
            $add_user_group_submit_button.prop(
                "disabled",
                $add_user_group_input_element.val().trim() === "",
            );
        });
    }

    dialog_widget.launch({
        html_heading: $t_html({defaultMessage: "Add a new alert word"}),
        html_body,
        html_submit_button: $t_html({defaultMessage: "Add"}),
        help_link: "/help/pm-mention-alert-notifications#alert-words",
        form_id: "add-alert-word-form",
        id: "add-alert-word",
        loading_spinner: true,
        on_click: add_alert_word,
        on_shown: () => $("#add-alert-word-name").trigger("focus"),
        post_render: add_alert_word_post_render,
    });
}

export function set_up_alert_words() {
    // The settings page must be rendered before this function gets called.
    loaded = true;
    rerender_alert_words_ui();

    $("#open-add-alert-word-modal").on("click", () => {
        show_add_alert_word_modal();
    });

    $("#alert-words-table").on("click", ".remove-alert-word", (event) => {
        const word = $(event.currentTarget).parents("tr").find(".value").text().trim();
        remove_alert_word(word);
    });

    $("#alert-word-settings").on("click", ".close-alert-word-status", (event) => {
        event.preventDefault();
        const $alert = $(event.currentTarget).parents(".alert");
        $alert.hide();
    });
}

export function reset() {
    loaded = false;
}


text:
namespace {

string16 MacAsString16(const uint8 mac_as_int[6]) {
  // mac_as_int is big-endian. Write in byte chunks.
  // Format is XX-XX-XX-XX-XX-XX.
  static const wchar_t* const kMacFormatString =
      L"%02x-%02x-%02x-%02x-%02x-%02x";
  return WideToUTF16(StringPrintf(kMacFormatString,
                                  mac_as_int[0], mac_as_int[1],
                                  mac_as_int[2], mac_as_int[3],
                                  mac_as_int[4], mac_as_int[5]));
}

void FetchGatewayIps(std::set<IPAddr>* gateway_ips) {
  ULONG out_buf_len = 0;
  if (GetAdaptersInfo(NULL, &out_buf_len) != ERROR_BUFFER_OVERFLOW)
    return;
  scoped_ptr_malloc<IP_ADAPTER_INFO> adapter_list(
      static_cast<IP_ADAPTER_INFO*>(malloc(out_buf_len)));
  if (adapter_list == NULL)
    return;
  if (GetAdaptersInfo(adapter_list.get(), &out_buf_len) == NO_ERROR) {
    for (const IP_ADAPTER_INFO* adapter = adapter_list.get(); adapter != NULL;
         adapter = adapter->Next) {
      if (adapter->Type == IF_TYPE_ETHERNET_CSMACD) {
        // If we have multiple gateways with conflicting IPs we'll disregard
        // the duplicates.
        for (const IP_ADDR_STRING* gw = &adapter->GatewayList;
             gw != NULL; gw = gw->Next)
          gateway_ips->insert(inet_addr(gw->IpAddress.String));
      }
    }
  }
}

// Sends an ARP request to determine the MAC address of the destination.
bool GetMacFromIp(IPAddr dest_ip, ULONG* mac_addr, size_t mac_addr_size) {
  memset(mac_addr, 0xff, mac_addr_size);
  DWORD arp_result = 0;
  ULONG phys_addr_len = 6;
  IPAddr src_ip = 0;
  arp_result = SendARP(dest_ip, src_ip, mac_addr, &phys_addr_len);
  return arp_result == NO_ERROR && phys_addr_len == 6;
}

} // namespace

class WinGatewayApi : public GatewayDataProviderCommon::GatewayApiInterface {
 public:
  WinGatewayApi();
  virtual ~WinGatewayApi();

  // GatewayApiInterface
  virtual bool GetRouterData(GatewayData::RouterDataSet* data);
};

GatewayDataProviderCommon::GatewayApiInterface*
WinGatewayDataProvider::NewGatewayApi() {
  return new WinGatewayApi();
}

WinGatewayApi::WinGatewayApi() {
}

WinGatewayApi::~WinGatewayApi() {
}

bool WinGatewayApi::GetRouterData(GatewayData::RouterDataSet* data) {
  std::set<IPAddr> gateway_ips;
  FetchGatewayIps(&gateway_ips);
  if (gateway_ips.empty())
    return false;
  const size_t kMacAddrLength = 2;
  for (std::set<IPAddr>::const_iterator gateway_it =
       gateway_ips.begin(); gateway_it != gateway_ips.end(); ++gateway_it) {
    IPAddr adapter_gateway_ip = *gateway_it;
    ULONG mac_addr[kMacAddrLength];
    if (GetMacFromIp(adapter_gateway_ip, mac_addr, sizeof(mac_addr))) {
      RouterData router;
      uint8* phys_addr = reinterpret_cast<uint8*>(&mac_addr);
      router.mac_address = MacAsString16(phys_addr);
      data->insert(router);
    }
  }
  return true;
}

WinGatewayDataProvider::WinGatewayDataProvider() {
}

WinGatewayDataProvider::~WinGatewayDataProvider() {
}

template<>
GatewayDataProviderImplBase* GatewayDataProvider::DefaultFactoryFunction() {
  if (!CommandLine::ForCurrentProcess()
      ->HasSwitch(switches::kExperimentalLocationFeatures))
    return new EmptyDeviceDataProvider<GatewayData>();
  return new WinGatewayDataProvider();
}


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace MonoGame.Extended.Collections
{
    /// <summary>
    ///     Represents a collection of objects which elements are instantiated ahead of time and re-used by clearing their
    ///     state.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the pool.</typeparam>
    /// <remarks>
    ///     <para>
    ///         Requesting a free element from the <see cref="Pool{T}" /> is a O(1) operation. Returning a used element back to
    ///         the <see cref="Pool{T}" /> is an O(1) operation for the oldest or newest elements or O(n) otherwise, where n is
    ///         the <see cref="Count" />.
    ///     </para>
    /// </remarks>
    /// <example>
    ///     The following example demonstrates how to request and return a simple object from and to a
    ///     <see cref="Pool{T}" />.
    ///     <code>
    /// <![CDATA[
    /// // Create the pool
    /// var pool = new Pool<MyPoolable>();
    /// ...
    /// // Get an object from the pool
    /// var myPoolableInstance = pool.Request();
    /// ...
    /// // Return the object back to the pool
    /// myPoolableInstance.Return();
    /// ...
    /// private class MyPoolable : IPoolable
    /// {
    ///     // The return delegate responsible for invoking the internal method in the pool class
    ///     private ReturnToPoolDelegate _returnFunction;
    ///
    ///     // Called by the Pool when this object is requested for use
    ///     public void Initialize(ReturnToPoolDelegate returnFunction)
    ///     {
    ///         // Copy the reference of the delegate instance so we can use it later
    ///         _returnFunction = returnFunction;
    ///
    ///         // You could also reset the state of the object instance here instead of when returned
    ///         // Reset()
    ///     }
    ///
    ///     // Helper method for this instance that should reset the state in preperation for the next time it is requested
    ///     public void Reset()
    ///     {
    ///         // TODO: Reset the state of your object here
    ///     }
    ///
    ///     // Called by you or the Pool when this object is to be returned
    ///     public void Return()
    ///     {
    ///         // Check if we already used the return delegate
    ///         if (_returnFunction == null)
    ///         {
    ///             // We already used the return delegate; exit this method early
    ///             return;
    ///         }
    ///
    ///         // Call the reset helper method before we return this instance back to the pool
    ///         Reset();
    ///
    ///         // We didn't use the return delegate yet; use it now
    ///         _returnFunction.Invoke(this);
    ///         // Set the delegate instance reference to null so we know we can't use it again
    ///         _returnFunction = null;
    ///     }
    /// }
    /// ]]>
    /// </code>
    /// </example>
    public class Pool<T> : ICollection<T>
        where T : class, IPoolable
    {
        // since we are constraining T to classes, these two deqeues are just really two object reference arrays
        // on a 32-bit machine, a reference is 4 bytes
        // on a 64-bit machine, a reference is 8 bytes
        private readonly Deque<T> _freeItems;
        private readonly Func<int, T> _instantiationFunction;
        private readonly Deque<T> _usedItems;

        /// <summary>
        ///     Initializes a new instance of the <see cref="Pool{T}" /> class that has a specified capacity and an element
        ///     instantiating delegate.
        /// </summary>
        /// <param name="capacity">The number of elements that the new <see cref="Pool{T}" /> can store.</param>
        /// <param name="instantiationFunction">The delegate responsible for instantiating elements.</param>
        public Pool(int capacity, Func<int, T> instantiationFunction)
        {
            if (instantiationFunction == null)
                throw new ArgumentNullException(nameof(instantiationFunction));

            _instantiationFunction = instantiationFunction;
            _freeItems = new Deque<T>(capacity);
            _usedItems = new Deque<T>(capacity);
            for (var i = 0; i < capacity; i++)
            {
                var poolable = CreateObject(i);
                _freeItems.AddToBack(poolable);
            }
        }

        /// <summary>
        ///     Gets or sets the total number of elements the internal data structure can hold.
        /// </summary>
        /// <returns>The number of elements that the <see cref="Pool{T}" /> can contain.</returns>
        /// <remarks>
        ///     Once set, <see cref="Capacity" /> can not be changed.
        /// </remarks>
        public int Capacity => _usedItems.Count;

        /// <summary>
        ///     Gets the number of elements contained in the <see cref="Pool{T}" />.
        /// </summary>
        /// <returns>The number of elements contained in the <see cref="Pool{T}" />.</returns>
        public int Count => _usedItems.Count;

        bool ICollection<T>.IsReadOnly => true;

        public IEnumerator<T> GetEnumerator()
        {
            return _usedItems.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _usedItems.GetEnumerator();
        }

        void ICollection<T>.Add(T item)
        {
            throw new NotSupportedException();
        }

        bool ICollection<T>.Remove(T item)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        ///     Returns all in use elements back to the <see cref="Pool{T}" />.
        /// </summary>
        /// <remarks>
        ///     <para><see cref="Count" /> is set to 0.</para>
        ///     <para><see cref="Capacity" /> remains unchanged.</para>
        ///     <para>
        ///         The order which elements are returned is the same as the order they were requested using
        ///         <see cref="Request" />.
        ///     </para>
        ///     <para>This method is an O(n) operation where n is <see cref="Count" />.</para>
        /// </remarks>
        public void Clear()
        {
            while (_usedItems.Count > 0)
            {
                T item;
                _usedItems.GetFront(out item);
                item.Return();
            }
        }

        bool ICollection<T>.Contains(T item)
        {
            return _usedItems.Contains(item);
        }

        void ICollection<T>.CopyTo(T[] array, int arrayIndex)
        {
            _usedItems.CopyTo(array, arrayIndex);
        }

        private T CreateObject(int index)
        {
            var newObject = _instantiationFunction(index);
            if (newObject == null)
                throw new NullReferenceException($"The created pooled object of type '{typeof(T).Name}' is null.");
            return newObject;
        }

        /// <summary>
        ///     Get a free element from the <see cref="Pool{T}" />.
        /// </summary>
        /// <param name="killExistingObjectIfFull">
        ///     <c>true</c> to forcibly kill an existing, in use, element in the <see cref="Pool{T}" /> if <see cref="Count" /> is
        ///     equal to <see cref="Capacity" />; otherwise, <c>false</c>.
        /// </param>
        /// <returns>A free <see cref="T" /> element from the <see cref="Pool{T}" />.</returns>
        /// <remarks>
        ///     <para>This method is an O(1) operation.</para>
        /// </remarks>
        public T Request(bool killExistingObjectIfFull = false)
        {
            while (true)
            {
                T poolable;

                if (_freeItems.RemoveFromFront(out poolable))
                {
                    poolable.Initialize(Return);
                    _usedItems.AddToBack(poolable);
                    return poolable;
                }

                if (!killExistingObjectIfFull)
                    return null;
                if (!_usedItems.GetFront(out poolable))
                    return null;

                poolable.Return();
                killExistingObjectIfFull = false;
            }
        }

        private void Return(IPoolable poolable)
        {
            var poolable1 = (T) poolable;
            _freeItems.AddToBack(poolable1);
            _usedItems.Remove(poolable1);
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CsvFile.cs" company="QuantityTypes">
//   Copyright (c) 2014 QuantityTypes contributors
// </copyright>
//
//   Represents a comma separated file that supports units and reflection of the rows.
//
// --------------------------------------------------------------------------------------------------------------------

namespace QuantityTypes.Csv
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;

#if NET45
    using System.ComponentModel;
#endif

    ///
    /// Represents a comma separated file that supports units and reflection of the rows.
    ///
    /// <remarks>
    /// See Comma-separated values.
    /// </remarks>
    public class CsvFile
    {
        ///
        /// The quantity type
        ///
        internal static readonly Type QuantityType = typeof(IQuantity);

        ///
        /// Prevents a default instance of the <see cref="CsvFile" /> class from being created.
        ///
        private CsvFile()
        {
            this.Columns = new List<CsvColumn>();
            this.Rows = new List<CsvRow>();
        }

        ///
        /// Gets the columns.
        ///
        /// <value>The columns.</value>
        public List<CsvColumn> Columns { get; private set; }

        ///
        /// Gets the rows.
        ///
        /// <value>The rows.</value>
        public List<CsvRow> Rows { get; private set; }

        ///
        /// Loads the specified items into a <see cref="CsvFile" />.
        ///
        /// <typeparam name="T">The type of the items</typeparam>
        /// <param name="items">The items.</param>
        /// <param name="unitProvider">The unit provider.</param>
        /// <returns>A <see cref="CsvFile" />.</returns>
        public static CsvFile Load<T>(IEnumerable<T> items, IUnitProvider unitProvider = null)
        {
            var type = typeof(T);
            var properties = type.GetTypeInfo().DeclaredProperties.OrderBy(CsvColumnAttribute.GetColumn).ToList();

            var file = new CsvFile();
            foreach (var p in properties)
            {
                file.Columns.Add(new CsvColumn(p.Name, string.Empty, p.PropertyType, unitProvider));
            }

            foreach (var item in items)
            {
                var csvRow = new CsvRow(file);
                for (int i = 0; i < properties.Count; i++)
                {
                    csvRow.Values[i] = properties[i].GetValue(item, null);
                }

                file.Rows.Add(csvRow);
            }

            return file;
        }

        ///
        /// Loads from the specified stream.
        ///
        /// <param name="s">The stream.</param>
        /// <param name="cultureInfo">The culture info.</param>
        /// <returns>
        /// A <see cref="CsvFile" />.
        /// </returns>
        public static CsvFile Load(Stream s, CultureInfo cultureInfo = null)
        {
            return Load(new StreamReader(s), cultureInfo);
        }

        ///
        /// Loads from the specified stream reader.
        ///
        /// <param name="s">The stream reader.</param>
        /// <param name="cultureInfo">The culture info.</param>
        /// <returns>
        /// A <see cref="CsvFile" />.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">s;The stream reader must be specified.</exception>
        /// <exception cref="System.InvalidOperationException">Invalid header.</exception>
        /// <exception cref="System.FormatException">Wrong number of columns on line  + lineNumber</exception>
        public static CsvFile Load(StreamReader s, CultureInfo cultureInfo = null)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s", "The stream reader must be specified.");
            }

            if (cultureInfo == null)
            {
                cultureInfo = CultureInfo.InvariantCulture;
            }

            var separator = cultureInfo.TextInfo.ListSeparator;

            var headerLine = s.ReadLine();
            if (headerLine == null)
            {
                throw new InvalidOperationException("Invalid header.");
            }

            var headers = SplitLine(headerLine, separator[0]);
            int n = headers.Length;

            // Create a string collection for each column
            var items = new ValueList[n];
            for (int i = 0; i < n; i++)
            {
                items[i] = new ValueList();
            }

            // Read all rows
            int lineNumber = 1;
            while (!s.EndOfStream)
            {
                lineNumber++;
                var line = s.ReadLine();
                if (line == null)
                {
                    continue;
                }

                var fields = SplitLine(line, separator[0]);
                if (fields.Length != n)
                {
                    throw new FormatException("Wrong number of columns on line " + lineNumber);
                }

                for (int i = 0; i < n; i++)
                {
                    items[i].Add(fields[i]);
                }
            }

            var file = new CsvFile();

            // Determine the type of each column from the data
            for (int i = 0; i < n; i++)
            {
                string name, unit;
                SplitHeader(headers[i], out name, out unit);

                file.Columns.Add(new CsvColumn(name, unit, items[i].GetSmallestCommonType(cultureInfo)));
            }

            // Parse the values (and box them)
            for (int j = 0; j < items[0].Count; j++)
            {
                var item = new CsvRow(file);
                for (int i = 0; i < file.Columns.Count; i++)
                {
                    item.Values[i] = file.Columns[i].Convert(items[i][j], cultureInfo);
                }

                file.Rows.Add(item);
            }

            return file;
        }

        ///
        /// Gets the (underlying) quantity type or null if the type is not a quantity type.
        ///
        /// <param name="type">The type.</param>
        /// <returns>The quantity type, or null.</returns>
        public static Type GetQuantityType(Type type)
        {
            type = Nullable.GetUnderlyingType(type) ?? type;
            return QuantityType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) ? type : null;
        }

        ///
        /// Saves the csv file to the specified <see cref="Stream"/>.
        ///
        /// <param name="stream">The output <see cref="Stream"/>.</param>
        /// <param name="cultureInfo">The output culture.</param>
        /// <param name="unitProvider">The unit provider.</param>
        public void Save(Stream stream, CultureInfo cultureInfo = null, IUnitProvider unitProvider = null)
        {
            var writer = new StreamWriter(stream);
            this.Save(writer, cultureInfo, unitProvider);
            writer.Flush();
        }

        ///
        /// Saves the csv file to the specified <see cref="StreamWriter"/>.
        ///
        /// <param name="streamWriter">The output <see cref="StreamWriter"/>.</param>
        /// <param name="cultureInfo">The output culture.</param>
        /// <param name="unitProvider">The unit provider.</param>
        public void Save(StreamWriter streamWriter, CultureInfo cultureInfo = null, IUnitProvider unitProvider = null)
        {
            if (unitProvider == null)
            {
                unitProvider = UnitProvider.Default;
            }

            if (cultureInfo == null)
            {
                cultureInfo = unitProvider.Culture ?? CultureInfo.InvariantCulture;
            }

            var separator = cultureInfo.TextInfo.ListSeparator;

            for (int i = 0; i < this.Columns.Count; i++)
            {
                if (i > 0)
                {
                    streamWriter.Write(separator);
                }

                streamWriter.Write(this.Columns[i]);
            }

            var displayUnit =
                this.Columns.Select(
                    c =>
                        {
                            var qt = GetQuantityType(c.Type);
                            string symbol;
                            return qt != null ? unitProvider.GetDisplayUnit(qt, out symbol) : null;
                        }).ToList();

            streamWriter.WriteLine();

            for (int j = 0; j < this.Rows.Count; j++)
            {
                if (j > 0)
                {
                    streamWriter.WriteLine();
                }

                for (int i = 0; i < this.Columns.Count; i++)
                {
                    if (i > 0)
                    {
                        streamWriter.Write(separator);
                    }

                    var value = this.Rows[j].Values[i];
                    if (Csv.IsUndefined(value))
                    {
                        continue;
                    }

                    var q = value as IQuantity;
                    streamWriter.Write(
                        q != null
                            ? string.Format(cultureInfo, "{0}", q.ConvertTo(displayUnit[i]))
                            : string.Format(cultureInfo, "{0}", value));
                }
            }
        }

        ///
        /// Splits a line by the specified separator.
        ///
        /// <param name="line">
        /// The line.
        /// </param>
        /// <param name="separator">
        /// The separator.
        /// </param>
        /// <returns>
        /// An array of strings.
        /// </returns>
        internal static string[] SplitLine(string line, char separator)
        {
            return line.Split(separator);
        }

        ///
        /// Splits a header string in property name and unit.
        ///
        /// <param name="header">
        /// The header.
        /// </param>
        /// <param name="name">
        /// The property name.
        /// </param>
        /// <param name="unit">
        /// The unit.
        /// </param>
        internal static void SplitHeader(string header, out string name, out string unit)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header", "The header should be specified.");
            }

            var m = Regex.Match(header, @"^(.*?)\s*(\[(.*)\])?$");
            if (m.Success)
            {
                name = m.Groups[1].Value;
                unit = m.Groups[3].Value;
            }
            else
            {
                name = header;
                unit = string.Empty;
            }
        }

        ///
        /// Represents a column in the <see cref="CsvFile"/>.
        ///
        public class CsvColumn
        {
            ///
            /// Initializes a new instance of the <see cref="CsvColumn" /> class.
            ///
            /// <param name="name">The name.</param>
            /// <param name="unit">The unit.</param>
            /// <param name="type">The type.</param>
            /// <param name="unitProvider">The unit provider.</param>
            public CsvColumn(string name, string unit, Type type, IUnitProvider unitProvider = null)
            {
                this.Name = name;
                this.Type = type;
                var qt = GetQuantityType(type);
                this.Unit = qt != null ? (unitProvider ?? UnitProvider.Default).GetDisplayUnit(qt) : unit;
            }

            ///
            /// Gets the unit.
            ///
            /// <value>
            /// The unit.
            /// </value>
            public string Unit { get; private set; }

            ///
            /// Gets the type.
            ///
            /// <value>
            /// The type.
            /// </value>
            public Type Type { get; private set; }

            ///
            /// Gets or sets the name.
            ///
            /// <value>
            /// The name.
            /// </value>
            public string Name { get; set; }

            ///
            /// Returns a <see cref="System.String" /> that represents this instance.
            ///
            /// <returns>
            /// A <see cref="System.String" /> that represents this instance.
            /// </returns>
            public override string ToString()
            {
                if (string.IsNullOrEmpty(this.Unit))
                {
                    return this.Name;
                }

                return string.Format("{0} [{1}]", this.Name, this.Unit);
            }

            ///
            /// Converts the specified string to the type specified in this column.
            ///
            /// <param name="input">
            /// The input string.
            /// </param>
            /// <param name="provider">
            /// The provider.
            /// </param>
            /// <returns>
            /// The converted value.
            /// </returns>
            public object Convert(string input, IFormatProvider provider)
            {
                if (this.Type == typeof(int))
                {
                    return int.Parse(input, provider);
                }

                if (this.Type == typeof(double))
                {
                    return double.Parse(input, provider);
                }

                return input;
            }
        }

#if NET45
        ///
        /// Provides a property descriptor for an object in the <see cref="CsvRow" />.
        ///
        public class CsvPropertyDescriptor : PropertyDescriptor
        {
            ///
            /// The column
            ///
            private readonly CsvColumn column;

            ///
            /// The index
            ///
            private readonly int index;

            ///
            /// Initializes a new instance of the <see cref="CsvPropertyDescriptor"/> class.
            ///
            /// <param name="column">
            /// The column.
            /// </param>
            /// <param name="index">
            /// The index.
            /// </param>
            public CsvPropertyDescriptor(CsvColumn column, int index)
                : base(column.Name, null)
            {
                this.column = column;
                this.index = index;
            }

            ///
            /// When overridden in a derived class, gets the type of the component this property is bound to.
            ///
            /// <value> </value>
            /// <returns> A <see cref="T:System.Type" /> that represents the type of component this property is bound to. When the <see
            /// cref="M:System.ComponentModel.PropertyDescriptor.GetValue(System.Object)" /> or <see
            /// cref="M:System.ComponentModel.PropertyDescriptor.SetValue(System.Object,System.Object)" /> methods are invoked, the object specified might be an instance of this type. </returns>
            public override Type ComponentType
            {
                get
                {
                    return typeof(CsvRow);
                }
            }

            ///
            /// When overridden in a derived class, gets a value indicating whether this property is read-only.
            ///
            /// <value> </value>
            /// <returns> true if the property is read-only; otherwise, false. </returns>
            public override bool IsReadOnly
            {
                get
                {
                    return false;
                }
            }

            ///
            /// When overridden in a derived class, gets the type of the property.
            ///
            /// <value> </value>
            /// <returns> A <see cref="T:System.Type" /> that represents the type of the property. </returns>
            public override Type PropertyType
            {
                get
                {
                    return this.column.Type;
                }
            }

            ///
            /// When overridden in a derived class, returns whether resetting an object changes its value.
            ///
            /// <param name="component">
            /// The component to test for reset capability.
            /// </param>
            /// <returns>
            /// true if resetting the component changes its value; otherwise, false.
            /// </returns>
            public override bool CanResetValue(object component)
            {
                return false;
            }

            ///
            /// When overridden in a derived class, gets the current value of the property on a component.
            ///
            /// <param name="component">
            /// The component with the property for which to retrieve the value.
            /// </param>
            /// <returns>
            /// The value of a property for a given component.
            /// </returns>
            public override object GetValue(object component)
            {
                return ((CsvRow)component).Values[this.index];
            }

            ///
            /// When overridden in a derived class, resets the value for this property of the component to the default value.
            ///
            /// <param name="component">
            /// The component with the property value that is to be reset to the default value.
            /// </param>
            public override void ResetValue(object component)
            {
            }

            ///
            /// When overridden in a derived class, sets the value of the component to a different value.
            ///
            /// <param name="component">
            /// The component with the property value that is to be set.
            /// </param>
            /// <param name="value">
            /// The new value.
            /// </param>
            public override void SetValue(object component, object value)
            {
                ((CsvRow)component).Values[this.index] = value;
            }

            ///
            /// When overridden in a derived class, determines a value indicating whether the value of this property needs to be persisted.
            ///
            /// <param name="component">
            /// The component with the property to be examined for persistence.
            /// </param>
            /// <returns>
            /// true if the property should be persisted; otherwise, false.
            /// </returns>
            public override bool ShouldSerializeValue(object component)
            {
                return false;
            }
        }

        ///
        /// Provides a custom TypeDescriptionProvider for <see cref="CsvRow" />.
        ///
        public class CsvTypeDescriptionProvider : TypeDescriptionProvider
        {
            ///
            /// Gets a custom type descriptor for the given type and object.
            ///
            /// <param name="objectType">
            /// The type of object for which to retrieve the type descriptor.
            /// </param>
            /// <param name="instance">
            /// An instance of the type. Can be null if no instance was passed to the <see cref="T:System.ComponentModel.TypeDescriptor"/> .
            /// </param>
            /// <returns>
            /// An <see cref="T:System.ComponentModel.ICustomTypeDescriptor"/> that can provide metadata for the type.
            /// </returns>
            public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
            {
                return instance == null ? base.GetTypeDescriptor(objectType, null) : new CsvRowTypeDescriptor(instance);
            }
        }

        ///
        /// Provides a custom type descriptor for the <see cref="CsvRow" />.
        ///
        public class CsvRowTypeDescriptor : CustomTypeDescriptor
        {
            ///
            /// The row.
            ///
            private readonly CsvRow row;

            ///
            /// Initializes a new instance of the <see cref="CsvRowTypeDescriptor"/> class.
            ///
            /// <param name="instance">
            /// The instance.
            /// </param>
            public CsvRowTypeDescriptor(object instance)
            {
                this.row = (CsvRow)instance;
            }

            ///
            /// Gets the properties of the <see cref="CsvRow"/>.
            ///
            /// <returns> The property descriptor collection. </returns>
            public override PropertyDescriptorCollection GetProperties()
            {
                var result = new List<PropertyDescriptor>(this.row.File.Columns.Count);
                for (int i = 0; i < this.row.File.Columns.Count; i++)
                {
                    result.Add(new CsvPropertyDescriptor(this.row.File.Columns[i], i));
                }

                return new PropertyDescriptorCollection(result.ToArray());
            }
        }
#endif

        ///
        /// Represents a row in the <see cref="CsvFile"/>.
        ///
#if NET45
        [TypeDescriptionProvider(typeof(CsvTypeDescriptionProvider))]
#endif
        public class CsvRow
        {
            ///
            /// Initializes a new instance of the <see cref="CsvRow"/> class.
            ///
            /// <param name="file">
            /// The file.
            /// </param>
            public CsvRow(CsvFile file)
            {
                this.File = file;
                this.Values = new object[file.Columns.Count];
            }

            ///
            /// Gets the file.
            ///
            /// <value>The file.</value>
            public CsvFile File { get; private set; }

            ///
            /// Gets the values.
            ///
            /// <value>The values.</value>
            /// <remarks>
            /// The indices corresponds to the columns in the parent <see cref="CsvFile"/>.
            /// </remarks>
            public object[] Values { get; private set; }
        }

        ///
        /// Represents a list of values.
        ///
        private class ValueList : List<string>
        {
            ///
            /// Gets the smallest common type (<see cref="int"/>, <see cref="double"/> or <see cref="string"/>).
            ///
            /// <param name="provider">
            /// The format provider.
            /// </param>
            /// <returns>
            /// The smallest type (<see cref="int"/>, <see cref="double"/> or <see cref="string"/>) of the list.
            /// </returns>
            public Type GetSmallestCommonType(IFormatProvider provider)
            {
                Type type = null;
                foreach (var item in this)
                {
                    int i;
                    if (int.TryParse(item, NumberStyles.Integer, provider, out i))
                    {
                        if (type == null || type == typeof(int))
                        {
                            type = typeof(int);
                            continue;
                        }
                    }

                    double d;
                    if (double.TryParse(item, NumberStyles.Any, provider, out d))
                    {
                        if (type == null || type == typeof(int) || type == typeof(double))
                        {
                            type = typeof(double);
                            continue;
                        }
                    }

                    type = typeof(string);
                }

                return type;
            }
        }
    }
}


text:
<?

/**
 * @package    ab
 * @subpackage transcode
 * @version    $Id$
 * @author     Rasmus Andersson
 */
class TCDummySyntaxHighlighter extends TCSyntaxHighlighter {

	/**
	 * @param  string
	 * @param  string
	 * @param  string
	 * @return string
	 */
	public function convertString($code, $ext = '', $output = 'html') {
		return ($output == 'html') ? htmlentities($code) : $code;
	}

	/**
	 * @param  string
	 * @param  string
	 * @param  string
	 * @return string
	 */
	public function convertFile($path, $output = 'html') {
		return ($output == 'html') ? htmlentities(file_get_contents($path)) : file_get_contents($path);
	}
}
?>


text:
package com.google.android.accessibility.utils.parsetree;

class ParseTreeIntegerConstantNode extends ParseTreeNode {
  private final int mValue;
  private final int mEnumType;

  ParseTreeIntegerConstantNode(int value) {
    mValue = value;
    mEnumType = -1;
  }

  ParseTreeIntegerConstantNode(int value, int enumType) {
    mValue = value;
    mEnumType = enumType;
  }

  @Override
  public int getType() {
    if (mEnumType != -1) {
      return ParseTree.VARIABLE_ENUM;
    } else {
      return ParseTree.VARIABLE_INTEGER;
    }
  }

  @Override
  public int getEnumType() {
    if (mEnumType == -1) {
      return super.getEnumType();
    } else {
      return mEnumType;
    }
  }

  @Override
  public boolean canCoerceTo(@ParseTree.VariableType int type) {
    if (mEnumType != -1 && type == ParseTree.VARIABLE_ENUM) {
      return true;
    }
    return type == ParseTree.VARIABLE_BOOL
        || type == ParseTree.VARIABLE_INTEGER
        || type == ParseTree.VARIABLE_NUMBER
        || type == ParseTree.VARIABLE_STRING;
  }

  @Override
  public boolean resolveToBoolean(ParseTree.VariableDelegate delegate, String logIndent) {
    return mValue != 0;
  }

  @Override
  public int resolveToInteger(ParseTree.VariableDelegate delegate, String logIndent) {
    return mValue;
  }

  @Override
  public double resolveToNumber(ParseTree.VariableDelegate delegate, String logIndent) {
    return mValue;
  }

  @Override
  public CharSequence resolveToString(ParseTree.VariableDelegate delegate, String logIndent) {
    return Integer.toString(mValue);
  }
}


text:
package org.tolweb.tapestry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.StringUtils;
import org.tolweb.treegrow.page.PageContributor;

/**
 * Models the author name sequence component of a page citation.
 *
 * The format is bibliographic.  If Andrew Lenards, Lisa Antkow,
 * and Simon Josep were the authors of a page then the author
 * citation would be:
 *
 *    Lenards, Andrew, Lisa Antkow, and Simon Josep.
 *
 * If the contributors collection is empty, the author defaults
 * to being "Tree of Life Web Project."
 *
 * @author lenards
 *
 */
public class AuthorCitation implements PageCitationComponent {
	public static final String DEFAULT_AUTHOR = "Tree of Life Web Project.";

	private List<String> authorNames;

	/**
	 * Constructs an instance given the author contributors
	 * @param contributors
	 */
	public AuthorCitation(Collection<PageContributor> contributors) {
		authorNames = new ArrayList<String>();
		initializeAuthorNames(contributors, authorNames);
	}

	/**
	 * Returns a formatted list, in bibliographic style, of the author's names.
	 */
	public String getCitationString() {
		if (!authorNames.isEmpty()) {
			String names = StringUtils.returnCommaAndJoinedString(authorNames);
			return addPeriod(names.trim());
		}
		return DEFAULT_AUTHOR;
	}

	/**
	 * Returns a formatted version of the argument if it is not null nor empty.
	 * @param names the argument to format
	 * @return a formatted version of the argument
	 */
	private String addPeriod(String names) {
		if (StringUtils.notEmpty(names) && !names.endsWith(".")) {
			return names + ".";
		}
		return names;
	}

	/**
	 * Initializes the internal author names collection given the values from the
	 * contributors collection.
	 * @param contributors the data used to seed the internal collection.
	 * @param names the internal collection which is being seeded.
	 */
	private void initializeAuthorNames(Collection<PageContributor> contributors, List<String> names) {
		int index = 0;
		for(Iterator<PageContributor> itr = contributors.iterator(); itr.hasNext(); index++) {
			PageContributor pageContributor = (PageContributor)itr.next();
			Contributor actualContributor = pageContributor.getContributor();

			// we only want to add names if they're credited as authors for the page
			if(pageContributor.isAuthor()) {
				// if it's the very first author, add them as "LastName, FirstName" format
				if (authorNames.isEmpty()) {
					authorNames.add(getLastNameFirstName(actualContributor));
				} else {
					authorNames.add(actualContributor.getDisplayName());
				}
			}
		}
	}

	/**
	 * Returns a formatted version of the contributor's name in the
	 * format: LastName, FirstName.
	 * @param contr the contributor to format
	 * @return a formatted version of the contributor's name
	 */
	private String getLastNameFirstName(Contributor contr) {
		return contr.getLastName() + ", " + contr.getFirstName();
	}
}


text:
"""Tests for the analysis tool object."""

import argparse
import unittest

from plaso.cli import analysis_tool
from plaso.lib import errors

from tests.cli import test_lib

class StorageMediaToolTest(test_lib.CLIToolTestCase):
  """Tests for the analysis tool object."""

  _EXPECTED_OUTPUT_STORAGE_FILE_OPTIONS = u'\n'.join([
      u'usage: analysis_tool_test.py [STORAGE_FILE]',
      u'',
      u'Test argument parser.',
      u'',
      u'positional arguments:',
      u'  STORAGE_FILE  The path of the storage file.',
      u''])

  def testAddStorageFileOptions(self):
    """Tests the AddStorageFileOptions function."""
    argument_parser = argparse.ArgumentParser(
        prog=u'analysis_tool_test.py',
        description=u'Test argument parser.',
        add_help=False)

    test_tool = analysis_tool.AnalysisTool()
    test_tool.AddStorageFileOptions(argument_parser)

    output = argument_parser.format_help()
    self.assertEqual(output, self._EXPECTED_OUTPUT_STORAGE_FILE_OPTIONS)

  def testParseOptions(self):
    """Tests the ParseOptions function."""
    test_tool = analysis_tool.AnalysisTool()

    options = test_lib.TestOptions()

    with self.assertRaises(errors.BadConfigOption):
      test_tool.ParseOptions(options)

    options.storage_file = self._GetTestFilePath([u'psort_test.out'])

    test_tool.ParseOptions(options)

    # TODO: improve this test.

if __name__ == '__main__':
  unittest.main()


text:
"""scons.Node.Python

Python nodes.

"""

#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "src/engine/SCons/Node/Python.py  2009/09/04 16:33:07 david"

import SCons.Node

class ValueNodeInfo(SCons.Node.NodeInfoBase):
    current_version_id = 1

    field_list = ['csig']

    def str_to_node(self, s):
        return Value(s)

class ValueBuildInfo(SCons.Node.BuildInfoBase):
    current_version_id = 1

class Value(SCons.Node.Node):
    """A class for Python variables, typically passed on the command line
    or generated by a script, but not from a file or some other source.
    """

    NodeInfo = ValueNodeInfo
    BuildInfo = ValueBuildInfo

    def __init__(self, value, built_value=None):
        SCons.Node.Node.__init__(self)
        self.value = value
        if built_value is not None:
            self.built_value = built_value

    def str_for_display(self):
        return repr(self.value)

    def __str__(self):
        return str(self.value)

    def make_ready(self):
        self.get_csig()

    def build(self, **kw):
        if not hasattr(self, 'built_value'):
            apply (SCons.Node.Node.build, (self,), kw)

    is_up_to_date = SCons.Node.Node.children_are_up_to_date

    def is_under(self, dir):
        # Make Value nodes get built regardless of
        # what directory scons was run from. Value nodes
        # are outside the filesystem:
        return 1

    def write(self, built_value):
        """Set the value of the node."""
        self.built_value = built_value

    def read(self):
        """Return the value. If necessary, the value is built."""
        self.build()
        if not hasattr(self, 'built_value'):
            self.built_value = self.value
        return self.built_value

    def get_text_contents(self):
        """By the assumption that the node.built_value is a
        deterministic product of the sources, the contents of a Value
        are the concatenation of all the contents of its sources.  As
        the value need not be built when get_contents() is called, we
        cannot use the actual node.built_value."""
        ###TODO: something reasonable about universal newlines
        contents = str(self.value)
        for kid in self.children(None):
            contents = contents + kid.get_contents()
        return contents

    get_contents = get_text_contents    ###TODO should return 'bytes' value

    def changed_since_last_build(self, target, prev_ni):
        cur_csig = self.get_csig()
        try:
            return cur_csig != prev_ni.csig
        except AttributeError:
            return 1

    def get_csig(self, calc=None):
        """Because we're a Python value node and don't have a real
        timestamp, we get to ignore the calculator and just use the
        value contents."""
        try:
            return self.ninfo.csig
        except AttributeError:
            pass
        contents = self.get_contents()
        self.get_ninfo().csig = contents
        return contents

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
layout: default
description: Description of the oasisctl create apikey command
title: Oasisctl Create Apikey
---
# Oasisctl Create Apikey

Create a new API key

## Synopsis

Create a new API key

```
oasisctl create apikey [flags]
```

## Options

```
  -h, --help                     help for apikey
  -o, --organization-id string   If set, the newly created API key will grant access to this organization only
      --readonly                 If set, the newly created API key will grant readonly access only
```

## Options inherited from parent commands

```
      --endpoint string   API endpoint of the ArangoDB Oasis (default "api.cloud.arangodb.com")
      --format string     Output format (table|json) (default "table")
      --token string      Token used to authenticate at ArangoDB Oasis
```

## See also

* [oasisctl create](oasisctl-create.html)	 - Create resources


text:
<?php

  class Error extends Base {

    /**
     * Render the error404 view
     */
    public static function throw404(){
      if(Base::config('environment') == 'development'){
        $s = new LazySloth("The current path did not match any routes.");
        die($s->__toString());
      } else {
        View::render('error404');
      }
    }

    /**
     * The shutdown method will be the actual php error handler
     * for the framework that kicks in whenever some php-side
     * stuff is going wrong to give the user a feedback.
     * @param LazySloth $s - The exception object
     */
    public static function shutdown($s){
      if(Base::config('environment') == 'development'){
        die($s->__toString());
      } else {
        die("An internal error occured, please contact an administrator.");
      }
    }

  }

?>


text:
class Multi
  def initialize(wiederholungen)
    @anzahl = wiederholungen
  end

  def malfolge_ausgeben(a)
    #i = 1  #Start der Multiplikationsfolge
    (1..@anzahl).each do |i|
      puts "#{a} * #{i} = #{a*i}"   #interpolation sinnvoll, da übersichtlicher
    end
  end
end


text:
package postgres

// Code generated by xo. DO NOT EDIT.

import (
	"database/sql"
	"time"

	"github.com/google/uuid"
)

// ABitOfEverything represents a row from 'public.a_bit_of_everything'.
type ABitOfEverything struct {
	AEnum                     AEnum           `json:"a_enum"`                       // a_enum
	AEnumNullable             NullAEnum       `json:"a_enum_nullable"`              // a_enum_nullable
	ABigint                   int64           `json:"a_bigint"`                     // a_bigint
	ABigintNullable           sql.NullInt64   `json:"a_bigint_nullable"`            // a_bigint_nullable
	ABigserial                int64           `json:"a_bigserial"`                  // a_bigserial
	ABigserialNullable        int64           `json:"a_bigserial_nullable"`         // a_bigserial_nullable
	ABit                      uint8           `json:"a_bit"`                        // a_bit
	ABitNullable              *uint8          `json:"a_bit_nullable"`               // a_bit_nullable
	ABitVarying               []byte          `json:"a_bit_varying"`                // a_bit_varying
	ABitVaryingNullable       []byte          `json:"a_bit_varying_nullable"`       // a_bit_varying_nullable
	ABool                     bool            `json:"a_bool"`                       // a_bool
	ABoolNullable             sql.NullBool    `json:"a_bool_nullable"`              // a_bool_nullable
	ABoolean                  bool            `json:"a_boolean"`                    // a_boolean
	ABooleanNullable          sql.NullBool    `json:"a_boolean_nullable"`           // a_boolean_nullable
	ABpchar                   string          `json:"a_bpchar"`                     // a_bpchar
	ABpcharNullable           sql.NullString  `json:"a_bpchar_nullable"`            // a_bpchar_nullable
	ABytea                    []byte          `json:"a_bytea"`                      // a_bytea
	AByteaNullable            []byte          `json:"a_bytea_nullable"`             // a_bytea_nullable
	AChar                     string          `json:"a_char"`                       // a_char
	ACharNullable             sql.NullString  `json:"a_char_nullable"`              // a_char_nullable
	ACharacter                string          `json:"a_character"`                  // a_character
	ACharacterNullable        sql.NullString  `json:"a_character_nullable"`         // a_character_nullable
	ACharacterVarying         string          `json:"a_character_varying"`          // a_character_varying
	ACharacterVaryingNullable sql.NullString  `json:"a_character_varying_nullable"` // a_character_varying_nullable
	ADate                     time.Time       `json:"a_date"`                       // a_date
	ADateNullable             sql.NullTime    `json:"a_date_nullable"`              // a_date_nullable
	ADecimal                  float64         `json:"a_decimal"`                    // a_decimal
	ADecimalNullable          sql.NullFloat64 `json:"a_decimal_nullable"`           // a_decimal_nullable
	ADoublePrecision          float64         `json:"a_double_precision"`           // a_double_precision
	ADoublePrecisionNullable  sql.NullFloat64 `json:"a_double_precision_nullable"`  // a_double_precision_nullable
	AInet                     string          `json:"a_inet"`                       // a_inet
	AInetNullable             sql.NullString  `json:"a_inet_nullable"`              // a_inet_nullable
	AInt                      int             `json:"a_int"`                        // a_int
	AIntNullable              sql.NullInt64   `json:"a_int_nullable"`               // a_int_nullable
	AInteger                  int             `json:"a_integer"`                    // a_integer
	AIntegerNullable          sql.NullInt64   `json:"a_integer_nullable"`           // a_integer_nullable
	AInterval                 []byte          `json:"a_interval"`                   // a_interval
	AIntervalNullable         []byte          `json:"a_interval_nullable"`          // a_interval_nullable
	AJSON                     []byte          `json:"a_json"`                       // a_json
	AJSONNullable             []byte          `json:"a_json_nullable"`              // a_json_nullable
	AJsonb                    []byte          `json:"a_jsonb"`                      // a_jsonb
	AJsonbNullable            []byte          `json:"a_jsonb_nullable"`             // a_jsonb_nullable
	AMoney                    string          `json:"a_money"`                      // a_money
	AMoneyNullable            sql.NullString  `json:"a_money_nullable"`             // a_money_nullable
	ANumeric                  float64         `json:"a_numeric"`                    // a_numeric
	ANumericNullable          sql.NullFloat64 `json:"a_numeric_nullable"`           // a_numeric_nullable
	AReal                     float32         `json:"a_real"`                       // a_real
	ARealNullable             sql.NullFloat64 `json:"a_real_nullable"`              // a_real_nullable
	ASerial                   int             `json:"a_serial"`                     // a_serial
	ASerialNullable           int             `json:"a_serial_nullable"`            // a_serial_nullable
	ASmallint                 int16           `json:"a_smallint"`                   // a_smallint
	ASmallintNullable         sql.NullInt64   `json:"a_smallint_nullable"`          // a_smallint_nullable
	ASmallserial              int16           `json:"a_smallserial"`                // a_smallserial
	ASmallserialNullable      int16           `json:"a_smallserial_nullable"`       // a_smallserial_nullable
	AText                     string          `json:"a_text"`                       // a_text
	ATextNullable             sql.NullString  `json:"a_text_nullable"`              // a_text_nullable
	ATime                     time.Time       `json:"a_time"`                       // a_time
	ATimeNullable             sql.NullTime    `json:"a_time_nullable"`              // a_time_nullable
	ATimestamp                time.Time       `json:"a_timestamp"`                  // a_timestamp
	ATimestampNullable        sql.NullTime    `json:"a_timestamp_nullable"`         // a_timestamp_nullable
	ATimestamptz              time.Time       `json:"a_timestamptz"`                // a_timestamptz
	ATimestamptzNullable      sql.NullTime    `json:"a_timestamptz_nullable"`       // a_timestamptz_nullable
	ATimetz                   time.Time       `json:"a_timetz"`                     // a_timetz
	ATimetzNullable           sql.NullTime    `json:"a_timetz_nullable"`            // a_timetz_nullable
	AUUID                     uuid.UUID       `json:"a_uuid"`                       // a_uuid
	AUUIDNullable             uuid.NullUUID   `json:"a_uuid_nullable"`              // a_uuid_nullable
	AVarchar                  string          `json:"a_varchar"`                    // a_varchar
	AVarcharNullable          sql.NullString  `json:"a_varchar_nullable"`           // a_varchar_nullable
	AXML                      []byte          `json:"a_xml"`                        // a_xml
	AXMLNullable              []byte          `json:"a_xml_nullable"`               // a_xml_nullable
}


text:
<!DOCTYPE HTML>

		<title>USC - SPORTS</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="description" content="" />
		<meta name="keywords" content="" />

			<link rel="stylesheet" href="css/skel.css" />
			<link rel="stylesheet" href="css/style.css" />
			<link rel="stylesheet" href="css/style-wide.css" />

USC Sports Database

Home

Coach Account Registration

				<form action="#">

Hitting Hand

												<select name="HittingHand" id="category">
													<option value="1">Right</option>
													<option value="2">Left</option>
												</select>

Position

												<select name="Position" id="category">
													<option value="1">Setter</option>
													<option value="2">Libero</option>
													<option value="3">Open Hitter</option>
													<option value="3">Middle Hitter</option>
													<option value="3">Opposite Hitter</option>
												</select>

									<input type="checkbox" id="human" name="human">
									I am a human and not a robot

<input type="Submit" value="Sign Up"/>

				</form>

© University of San Carlos: Sports Club Management System

All rights reserved.


text:
#ifndef OVR_Tracing_h
#define OVR_Tracing_h

//-----------------------------------------------------------------------------------
// ***** OVR_ENABLE_ETW_TRACING definition (XXX default to on for windows builds?)
//

#ifdef OVR_OS_WIN32
#define OVR_ENABLE_ETW_TRACING
#endif

//-----------------------------------------------------------------------------------
// ***** Trace* definitions
//

#ifdef OVR_ENABLE_ETW_TRACING

#define TracingIsEnabled() (OVR_SDK_LibOVREnableBits[0] != 0)

#ifdef TRACE_STATE_CAPTURE_FUNC
// hook in our own state capture callback to record the state of all opened HMDs (supress unused
// parameter warnings with void() casts)
#define MCGEN_PRIVATE_ENABLE_CALLBACK_V2(                                                         \
    SourceId, ControlCode, Level, MatchAnyKeyword, MatchAllKeywords, FilterData, CallbackContext) \
  (void(SourceId),                                                                                \
   void(Level),                                                                                \
   void(MatchAnyKeyword),                                                                         \
   void(MatchAllKeywords),                                                                        \
   void(FilterData),                                                                              \
   void(CallbackContext),                                                                         \
   (((ControlCode) == EVENT_CONTROL_CODE_CAPTURE_STATE) ? (TRACE_STATE_CAPTURE_FUNC) : 0))
#endif

#if !defined(_In_reads_)
// get VS2010 working
#define _In_reads_(x)
#endif

#include "LibOVREvents.h"

// Register/Unregister the OVR_SDK_LibOVR provider with ETW
// (MCGEN_PRIVATE_ENABLE_CALLBACK_V2 hooks in our state capture)
#define TraceInit()                                                       \
  do {                                                                    \
    ULONG status = EventRegisterOVR_SDK_LibOVR();                         \
    if (ERROR_SUCCESS != status) {                                        \
      LogError("[LibOVR] Failed to register ETW provider (%ul)", status); \
    }                                                                     \
  } while (0)
#define TraceFini() EventUnregisterOVR_SDK_LibOVR()

// Trace function call and return for perf, and waypoints for debug
#define TraceCall(frameIndex) EventWriteCall(__FUNCTIONW__, __LINE__, (frameIndex))
#define TraceReturn(frameIndex) EventWriteReturn(__FUNCTIONW__, __LINE__, (frameIndex))
#define TraceWaypoint(frameIndex) EventWriteWaypoint(__FUNCTIONW__, __LINE__, (frameIndex))

// DistortionRenderer events
#define TraceDistortionBegin(id, frameIndex) EventWriteDistortionBegin((id), (frameIndex))
#define TraceDistortionWaitGPU(id, frameIndex) EventWriteDistortionWaitGPU((id), (frameIndex))
#define TraceDistortionPresent(id, frameIndex) EventWriteDistortionPresent((id), (frameIndex))
#define TraceDistortionEnd(id, frameIndex) EventWriteDistortionEnd((id), (frameIndex))
#define TraceDistortionEndToEndTiming(elapsedMs) EventWriteDistortionEndToEndTiming((elapsedMs))

// Tracking Camera events
#define _TraceCameraFrameData(fn, camIdx, img) \
  fn((camIdx),                                 \
     (uint32_t)(img).FrameNumber,              \
     (img).HmdFrameNumber,                     \
     (img).ArrivalTime,                        \
     (img).CaptureTime)
#define TraceCameraFrameReceived(img) _TraceCameraFrameData(EventWriteCameraFrameReceived, 0, (img))
#define TraceCameraBeginProcessing(camIdx, img) \
  _TraceCameraFrameData(EventWriteCameraBeginProcessing, (camIdx), (img))
#define TraceCameraEndProcessing(camIdx, img) \
  _TraceCameraFrameData(EventWriteCameraEndProcessing, (camIdx), (img))
#define TraceCameraFrameRequest(requestNumber, frameCount, lastFrameNumber) \
  EventWriteCameraFrameRequest(requestNumber, frameCount, lastFrameNumber)
#define TraceCameraSkippedFrames(camIdx, skippedFrameCount) \
  EventWriteCameraSkippedFrames(camIdx, skippedFrameCount)

// Trace the interesting parts of an ovrHmdDesc structure
#define TraceHmdDesc(desc)          \
  EventWriteHmdDesc(                \
      (desc).Type,                  \
      (desc).VendorId,              \
      (desc).ProductId,             \
      (desc).SerialNumber,          \
      (desc).FirmwareMajor,         \
      (desc).FirmwareMinor,         \
      (desc).AvailableHmdCaps,      \
      (desc).AvailableTrackingCaps, \
      (desc).Resolution.w,          \
      (desc).Resolution.h)
#define TraceHmdDisplay(dpy)             \
  EventWriteHmdDisplay(                  \
      (0),                               \
      (dpy).DeviceTypeGuess,             \
      (dpy).DisplayID.ToCStr(),          \
      (dpy).ModelName.ToCStr(),          \
      (dpy).EdidSerialNumber.ToCStr(),   \
      (dpy).LogicalResolutionInPixels.w, \
      (dpy).LogicalResolutionInPixels.h, \
      (dpy).NativeResolutionInPixels.w,  \
      (dpy).NativeResolutionInPixels.h,  \
      0,                                 \
      0,                                 \
      (dpy).DeviceNumber,                \
      (dpy).Rotation,                    \
      (dpy).ApplicationExclusive)

// Trace part of a JSON string (events have a 64k limit)
#define TraceJSONChunk(Name, TotalChunks, ChunkSequence, TotalSize, ChunkSize, ChunkOffset, Chunk) \
  EventWriteJSONChunk(Name, TotalChunks, ChunkSequence, TotalSize, ChunkSize, ChunkOffset, Chunk)

// Trace messages from the public ovr_Trace API and our internal logger
#define TraceLogDebug(message) EventWriteLogDebugMessage(message)
#define TraceLogInfo(message) EventWriteLogInfoMessage(message)
#define TraceLogError(message) EventWriteLogErrorMessage(message)

// Trace an ovrTrackingState
#define TraceTrackingState(ts)              \
  EventWriteHmdTrackingState(               \
      (ts).HeadPose.TimeInSeconds,          \
      &(ts).HeadPose.ThePose.Orientation.x, \
      &(ts).HeadPose.ThePose.Position.x,    \
      &(ts).HeadPose.AngularVelocity.x,     \
      &(ts).HeadPose.LinearVelocity.x,      \
      0,                                    \
      0,                                    \
      (ts).StatusFlags)

#define TraceCameraBlobs(camIdx, frame)            \
  if (EventEnabledCameraBlobs()) {                 \
    const int max_blobs = 80;                      \
    int count = (frame).Blobs.GetSizeI();          \
    double x[max_blobs];                           \
    double y[max_blobs];                           \
    int size[max_blobs];                           \
    if (count > max_blobs)                         \
      count = max_blobs;                           \
    for (int i = 0; i < count; ++i) {              \
      x[i] = (frame).Blobs[i].DistortedPosition.x; \
      y[i] = (frame).Blobs[i].DistortedPosition.y; \
      size[i] = (frame).Blobs[i].BlobSize;         \
    }                                              \
    EventWriteCameraBlobs(                         \
        camIdx,                                    \
        (uint32_t)(frame).Frame->FrameNumber,      \
        (frame).Frame->ArrivalTime,                \
        (frame).Frame->Width,                      \
        (frame).Frame->Height,                     \
        count,                                     \
        x,                                         \
        y,                                         \
        size);                                     \
  } else                                           \
    ((void)0)

#define TracePosePrediction(                                                           \
    OriginalPose, PredictedPose, PredictionTimeDeltaSeconds, CurrentTimeInSeconds, id) \
  EventWritePosePrediction(                                                            \
      &(OriginalPose).Translation.x,                                                   \
      &(OriginalPose).Rotation.x,                                                      \
      &(PredictedPose).Translation.x,                                                  \
      &(PredictedPose).Rotation.x,                                                     \
      (PredictionTimeDeltaSeconds),                                                    \
      (CurrentTimeInSeconds),                                                          \
      (id))

// Trace PoseLatching CPU pinned memory write
#define TracePoseLatchCPUWrite( \
    Sequence,                   \
    Layer,                      \
    MotionSensorTime,           \
    PredictedScanlineFirst,     \
    PredictedScanlineLast,      \
    TimeToScanlineFirst,        \
    TimeToScanlineLast,         \
    StartPosition,              \
    EndPosition,                \
    StartQuat,                  \
    EndQuat)                    \
  EventWritePoseLatchCPUWrite(  \
      Sequence,                 \
      Layer,                    \
      MotionSensorTime,         \
      PredictedScanlineFirst,   \
      PredictedScanlineLast,    \
      TimeToScanlineFirst,      \
      TimeToScanlineLast,       \
      StartPosition,            \
      EndPosition,              \
      StartQuat,                \
      EndQuat)

// Trace PoseLatching GPU latch
#define TracePoseLatchGPULatchReadback( \
    Sequence,                           \
    Layer,                              \
    MotionSensorTime,                   \
    PredictedScanlineFirst,             \
    PredictedScanlineLast,              \
    TimeToScanlineFirst,                \
    TimeToScanlineLast)                 \
  EventWritePoseLatchGPULatchReadback(  \
      Sequence,                         \
      Layer,                            \
      MotionSensorTime,                 \
      PredictedScanlineFirst,           \
      PredictedScanlineLast,            \
      TimeToScanlineFirst,              \
      TimeToScanlineLast)

#define TraceVSync(VSyncTime, FrameIndex, TWGpuEndTime) \
  EventWriteVSync(VSyncTime, FrameIndex, TWGpuEndTime)

#define TraceAppCompositorFocus(Pid) EventWriteAppCompositorFocus(Pid)
#define TraceAppConnect(Pid) EventWriteAppConnect(Pid)
#define TraceAppDisconnect(Pid) EventWriteAppDisconnect(Pid)
#define TraceAppNoOp(Pid) EventWriteAppNoOp(Pid)

#define TraceLatencyTiming(LatencyTiming)   \
  EventWriteLatencyTiming(                  \
      LatencyTiming.LatencyRenderCpuBegin,  \
      LatencyTiming.LatencyRenderCpuEnd,    \
      LatencyTiming.LatencyRenderIMU,       \
      LatencyTiming.LatencyTimewarpCpu,     \
      LatencyTiming.LatencyTimewarpLatched, \
      LatencyTiming.LatencyTimewarpGpuEnd,  \
      LatencyTiming.LatencyPostPresent,     \
      LatencyTiming.ErrorRender,            \
      LatencyTiming.ErrorTimewarp)

#define TraceEndFrameAppTiming(AppTiming, RenderCount) \
  EventWriteEndFrameAppTiming(                         \
      AppTiming.AppFrameIndex,                         \
      AppTiming.AppRenderIMUTime,                      \
      AppTiming.AppVisibleMidpointTime,                \
      AppTiming.AppGpuRenderDuration,                  \
      AppTiming.AppBeginRenderingTime,                 \
      AppTiming.AppEndRenderingTime,                   \
      AppTiming.QueueAheadSeconds,                     \
      RenderCount)
#define TraceEndFrameOrigAppTiming(AppTiming, RenderCount) \
  EventWriteEndFrameOrigAppTiming(                         \
      AppTiming.AppFrameIndex,                             \
      AppTiming.AppRenderIMUTime,                          \
      AppTiming.AppVisibleMidpointTime,                    \
      AppTiming.AppGpuRenderDuration,                      \
      AppTiming.AppBeginRenderingTime,                     \
      AppTiming.AppEndRenderingTime,                       \
      AppTiming.QueueAheadSeconds,                         \
      RenderCount)

// XXX for future reference this could have been done with events with different opcodes and
// identical templates
#define VirtualDisplayPacketTrace_Begin 0
#define VirtualDisplayPacketTrace_End 1
#define VirtualDisplayPacketTrace_Queue 2
#define VirtualDisplayPacketTrace_QueueRelease 3
#define VirtualDisplayPacketTrace_Result 5

#define TraceVirtualDisplayPacket(PacketType, Stage, SubmittingProcessID, ActiveProcessID) \
  EventWriteVirtualDisplayPacketTrace(PacketType, Stage, SubmittingProcessID, ActiveProcessID)
#define TraceClientFrameMissed(FrameIndex, ProcessID) \
  EventWriteClientFrameMissed(FrameIndex, ProcessID)
#define TraceCompositionBegin(ExpectedCPUStartTimeInSeconds, ActualCPUStartTimeInSeconds) \
  EventWriteCompositionBegin(ExpectedCPUStartTimeInSeconds, ActualCPUStartTimeInSeconds)
#define TraceCompositionEnd() EventWriteCompositionEnd()
#define TraceCompositionEndSpinWait() EventWriteCompositionEndSpinWait()
#define TraceCompositionFlushingToGPU() EventWriteCompositionFlushingToGPU()
#define TraceRenderPacket(Stage, ClientPID) EventWriteRenderPacketTrace(Stage, ClientPID)
#define TraceHardwareInfo(data) \
  EventWriteHardwareInfo(       \
      data.RequestedBits,       \
      data.CollectedBits,       \
      data.ImuTemp,             \
      data.StmTemp,             \
      data.NrfTemp,             \
      data.VBusVoltage,         \
      data.IAD,                 \
      data.Proximity,           \
      data.PanelOnTime,         \
      data.UseRolling,          \
      data.HighBrightness,      \
      data.DP,                  \
      data.SelfRefresh,         \
      data.Persistence,         \
      data.LightingOffset,      \
      data.PixelSettle,         \
      data.TotalRows)

#define TraceCompositionMissedCompositorFrame() EventWriteCompositionMissedCompositorFrame()
#define TraceCompositionGPUStartTime(Seconds) EventWriteCompositionGPUStartTime(Seconds)

#define TraceNotificationEnd(                                                        \
    AppFrameIndex, CpuBeginToGpuEndSeconds, CpuBeginSeconds, GpuEndSeconds, SleepMs) \
  EventWriteNotificationEnd(                                                         \
      AppFrameIndex, CpuBeginToGpuEndSeconds, CpuBeginSeconds, GpuEndSeconds, SleepMs)
#define TraceNotificationBegin( \
    AppFrameIndex,              \
    CpuBeginToGpuEndSeconds,    \
    CompositeTimeSeconds,       \
    VSyncTimeSeconds,           \
    CompositeDeltaSeconds,      \
    VSyncDeltaSeconds)          \
  EventWriteNotificationBegin(  \
      AppFrameIndex,            \
      CpuBeginToGpuEndSeconds,  \
      CompositeTimeSeconds,     \
      VSyncTimeSeconds,         \
      CompositeDeltaSeconds,    \
      VSyncDeltaSeconds)
#define TraceNotificationCompSubmit(IsEnabled, IsDisabled, FrameIndex) \
  EventWriteNotificationCompSubmit(IsEnabled, IsDisabled, FrameIndex)

#define TraceMotionEstimationCostStats(Count, Average, Log2Histogram) \
  EventWriteMotionEstimationCostStats(Count, Average, Log2Histogram)

#else // OVR_ENABLE_ETW_TRACING

// Eventually other platforms could support their form of performance tracing
#define TracingIsEnabled() (false)
#define TraceInit() ((void)0)
#define TraceFini() ((void)0)
#define TraceCall(frameIndex) ((void)0)
#define TraceReturn(frameIndex) ((void)0)
#define TraceWaypoint(frameIndex) ((void)0)
#define TraceDistortionBegin(id, frameIndex) ((void)0)
#define TraceDistortionWaitGPU(id, frameIndex) ((void)0)
#define TraceDistortionPresent(id, frameIndex) ((void)0)
#define TraceDistortionEnd(id, frameIndex) ((void)0)
#define TraceDistortionEndToEndTiming(elapsedMs) ((void)0)
#define TraceCameraFrameReceived(cfd) ((void)0)
#define TraceCameraBeginProcessing(camIdx, img) ((void)0)
#define TraceCameraFrameRequest(requestNumber, frameCount, lastFrameNumber) ((void)0)
#define TraceCameraEndProcessing(camIdx, img) ((void)0)
#define TraceCameraSkippedFrames(camIdx, skippedFrameCount) ((void)0)
#define TraceHmdDesc(desc) ((void)0)
#define TraceHmdDisplay(dpy) ((void)0)
#define TraceJSONChunk(Name, TotalChunks, ChunkSequence, TotalSize, ChunkSize, ChunkOffset, Chunk) \
  ((void)0)
#define TraceLogDebug(message) ((void)0)
#define TraceLogInfo(message) ((void)0)
#define TraceLogError(message) ((void)0)
#define TraceTrackingState(ts) ((void)0)
#define TraceCameraBlobs(camIdx, frame) ((void)0)
#define TracePoseLatchCPUWrite( \
    Sequence,                   \
    Layer,                      \
    MotionSensorTime,           \
    PredictedScanlineFirst,     \
    PredictedScanlineLast,      \
    TimeToScanlineFirst,        \
    TimeToScanlineLast,         \
    StartPosition,              \
    EndPosition,                \
    StartQuat,                  \
    EndQuat)                    \
  ((void)0)
#define TracePoseLatchGPULatchReadback( \
    Sequence,                           \
    Layer,                              \
    MotionSensorTime,                   \
    PredictedScanlineFirst,             \
    PredictedScanlineLast,              \
    TimeToScanlineFirst,                \
    TimeToScanlineLast)                 \
  ((void)0)
#define TraceVSync(VSyncTime, FrameIndex, TWGpuEndTime) ((void)0)
#define TracePosePrediction(                                                           \
    OriginalPose, PredictedPose, PredictionTimeDeltaSeconds, CurrentTimeInSeconds, id) \
  ((void)0)
#define TraceAppCompositorFocus(Pid) ((void)0)
#define TraceAppConnect(Pid) ((void)0)
#define TraceAppDisconnect(Pid) ((void)0)
#define TraceAppNoOp(Pid) ((void)0)
#define TraceLatencyTiming(LatencyTiming) ((void)0)
#define TraceEndFrameAppTiming(AppTiming, RenderCount) ((void)0)
#define TraceEndFrameOrigAppTiming(AppTiming, RenderCount) ((void)0)
#define TraceVirtualDisplayPacket(PacketType, Stage, SubmittingProcessID, ActiveProcessID) ((void)0)
#define TraceClientFrameMissed(FrameIndex, ProcessID) ((void)0)
#define TraceCompositionBegin(ExpectedCPUStartTimeInSeconds, ActualCPUStartTimeInSeconds) ((void)0)
#define TraceCompositionEnd() ((void)0)
#define TraceCompositionEndSpinWait() ((void)0)
#define TraceCompositionFlushingToGPU() ((void)0)
#define TraceRenderPacket(Stage, ClientPID) ((void)0)
#define TraceHardwareInfo(data) ((void)0)
#define TraceCompositionMissedCompositorFrame() ((void)0)
#define TraceCompositionGPUStartTime(Seconds) ((void)0)
#define TraceNotificationEnd(                                                        \
    AppFrameIndex, CpuBeginToGpuEndSeconds, CpuBeginSeconds, GpuEndSeconds, SleepMs) \
  ((void)0)
#define TraceNotificationBegin( \
    AppFrameIndex,              \
    CpuBeginToGpuEndSeconds,    \
    CompositeTimeSeconds,       \
    VSyncTimeSeconds,           \
    CompositeDeltaSeconds,      \
    VSyncDeltaSeconds)          \
  ((void)0)
#define TraceNotificationCompSubmit(IsEnabled, IsDisabled, FrameIndex) ((void)0)
#define TraceMotionEstimationCostStats(Count, Average, Log2Histogram) ((void)0)

#endif // OVR_ENABLE_ETW_TRACING

#endif // OVR_Tracing_h


text:
namespace content {

GpuChannelManager::GpuChannelManager(
    MessageRouter* router,
    GpuWatchdog* watchdog,
    base::SingleThreadTaskRunner* io_task_runner,
    base::WaitableEvent* shutdown_event,
    IPC::SyncChannel* channel,
    IPC::AttachmentBroker* broker,
    gpu::SyncPointManager* sync_point_manager,
    GpuMemoryBufferFactory* gpu_memory_buffer_factory)
    : io_task_runner_(io_task_runner),
      shutdown_event_(shutdown_event),
      router_(router),
      gpu_memory_manager_(
          this,
          GpuMemoryManager::kDefaultMaxSurfacesWithFrontbufferSoftLimit),
      watchdog_(watchdog),
      sync_point_manager_(sync_point_manager),
      gpu_memory_buffer_factory_(gpu_memory_buffer_factory),
      channel_(channel),
      relinquish_resources_pending_(false),
      attachment_broker_(broker),
      weak_factory_(this) {
  DCHECK(router_);
  DCHECK(io_task_runner);
  DCHECK(shutdown_event);
}

GpuChannelManager::~GpuChannelManager() {
  gpu_channels_.clear();
  if (default_offscreen_surface_.get()) {
    default_offscreen_surface_->Destroy();
    default_offscreen_surface_ = NULL;
  }
}

gpu::gles2::ProgramCache* GpuChannelManager::program_cache() {
  if (!program_cache_.get() &&
      (gfx::g_driver_gl.ext.b_GL_ARB_get_program_binary ||
       gfx::g_driver_gl.ext.b_GL_OES_get_program_binary) &&
      !base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableGpuProgramCache)) {
    program_cache_.reset(new gpu::gles2::MemoryProgramCache());
  }
  return program_cache_.get();
}

gpu::gles2::ShaderTranslatorCache*
GpuChannelManager::shader_translator_cache() {
  if (!shader_translator_cache_.get())
    shader_translator_cache_ = new gpu::gles2::ShaderTranslatorCache;
  return shader_translator_cache_.get();
}

void GpuChannelManager::RemoveChannel(int client_id) {
  Send(new GpuHostMsg_DestroyChannel(client_id));
  gpu_channels_.erase(client_id);
  CheckRelinquishGpuResources();
}

int GpuChannelManager::GenerateRouteID() {
  static int last_id = 0;
  return ++last_id;
}

void GpuChannelManager::AddRoute(int32 routing_id, IPC::Listener* listener) {
  router_->AddRoute(routing_id, listener);
}

void GpuChannelManager::RemoveRoute(int32 routing_id) {
  router_->RemoveRoute(routing_id);
}

GpuChannel* GpuChannelManager::LookupChannel(int32 client_id) {
  GpuChannelMap::const_iterator iter = gpu_channels_.find(client_id);
  if (iter == gpu_channels_.end())
    return NULL;
  else
    return iter->second;
}

bool GpuChannelManager::OnMessageReceived(const IPC::Message& msg) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(GpuChannelManager, msg)
    IPC_MESSAGE_HANDLER(GpuMsg_EstablishChannel, OnEstablishChannel)
    IPC_MESSAGE_HANDLER(GpuMsg_CloseChannel, OnCloseChannel)
    IPC_MESSAGE_HANDLER(GpuMsg_CreateViewCommandBuffer,
                        OnCreateViewCommandBuffer)
    IPC_MESSAGE_HANDLER(GpuMsg_DestroyGpuMemoryBuffer, OnDestroyGpuMemoryBuffer)
    IPC_MESSAGE_HANDLER(GpuMsg_LoadedShader, OnLoadedShader)
    IPC_MESSAGE_HANDLER(GpuMsg_RelinquishResources, OnRelinquishResources)
    IPC_MESSAGE_HANDLER(GpuMsg_UpdateValueState, OnUpdateValueState)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

bool GpuChannelManager::Send(IPC::Message* msg) { return router_->Send(msg); }

void GpuChannelManager::OnEstablishChannel(int client_id,
                                           bool share_context,
                                           bool allow_future_sync_points) {
  IPC::ChannelHandle channel_handle;

  gfx::GLShareGroup* share_group = NULL;
  gpu::gles2::MailboxManager* mailbox_manager = NULL;
  if (share_context) {
    if (!share_group_.get()) {
      share_group_ = new gfx::GLShareGroup;
      DCHECK(!mailbox_manager_.get());
      mailbox_manager_ = gpu::gles2::MailboxManager::Create();
    }
    share_group = share_group_.get();
    mailbox_manager = mailbox_manager_.get();
  }

  scoped_ptr<GpuChannel> channel(new GpuChannel(this,
                                                watchdog_,
                                                share_group,
                                                mailbox_manager,
                                                client_id,
                                                false,
                                                allow_future_sync_points));
  channel->Init(io_task_runner_.get(), shutdown_event_, attachment_broker_);
  channel_handle.name = channel->GetChannelName();

#if defined(OS_POSIX)
  // On POSIX, pass the renderer-side FD. Also mark it as auto-close so
  // that it gets closed after it has been sent.
  base::ScopedFD renderer_fd = channel->TakeRendererFileDescriptor();
  DCHECK(renderer_fd.is_valid());
  channel_handle.socket = base::FileDescriptor(renderer_fd.Pass());
#endif

  gpu_channels_.set(client_id, channel.Pass());

  Send(new GpuHostMsg_ChannelEstablished(channel_handle));
}

void GpuChannelManager::OnCloseChannel(
    const IPC::ChannelHandle& channel_handle) {
  for (GpuChannelMap::iterator iter = gpu_channels_.begin();
       iter != gpu_channels_.end(); ++iter) {
    if (iter->second->GetChannelName() == channel_handle.name) {
      gpu_channels_.erase(iter);
      CheckRelinquishGpuResources();
      return;
    }
  }
}

void GpuChannelManager::OnCreateViewCommandBuffer(
    const gfx::GLSurfaceHandle& window,
    int32 surface_id,
    int32 client_id,
    const GPUCreateCommandBufferConfig& init_params,
    int32 route_id) {
  DCHECK(surface_id);
  CreateCommandBufferResult result = CREATE_COMMAND_BUFFER_FAILED;

  GpuChannelMap::const_iterator iter = gpu_channels_.find(client_id);
  if (iter != gpu_channels_.end()) {
    result = iter->second->CreateViewCommandBuffer(
        window, surface_id, init_params, route_id);
  }

  Send(new GpuHostMsg_CommandBufferCreated(result));
}

void GpuChannelManager::DestroyGpuMemoryBuffer(
    gfx::GpuMemoryBufferId id,
    int client_id) {
  io_task_runner_->PostTask(
      FROM_HERE, base::Bind(&GpuChannelManager::DestroyGpuMemoryBufferOnIO,
                            base::Unretained(this), id, client_id));
}

void GpuChannelManager::DestroyGpuMemoryBufferOnIO(
    gfx::GpuMemoryBufferId id,
    int client_id) {
  gpu_memory_buffer_factory_->DestroyGpuMemoryBuffer(id, client_id);
}

void GpuChannelManager::OnDestroyGpuMemoryBuffer(
    gfx::GpuMemoryBufferId id,
    int client_id,
    int32 sync_point) {
  if (!sync_point) {
    DestroyGpuMemoryBuffer(id, client_id);
  } else {
    sync_point_manager()->AddSyncPointCallback(
        sync_point,
        base::Bind(&GpuChannelManager::DestroyGpuMemoryBuffer,
                   base::Unretained(this),
                   id,
                   client_id));
  }
}

void GpuChannelManager::OnUpdateValueState(
    int client_id, unsigned int target, const gpu::ValueState& state) {
  // Only pass updated state to the channel corresponding to the
  // render_widget_host where the event originated.
  GpuChannelMap::const_iterator iter = gpu_channels_.find(client_id);
  if (iter != gpu_channels_.end()) {
    iter->second->HandleUpdateValueState(target, state);
  }
}

void GpuChannelManager::OnLoadedShader(std::string program_proto) {
  if (program_cache())
    program_cache()->LoadProgram(program_proto);
}

bool GpuChannelManager::HandleMessagesScheduled() {
  for (GpuChannelMap::iterator iter = gpu_channels_.begin();
       iter != gpu_channels_.end(); ++iter) {
    if (iter->second->handle_messages_scheduled())
      return true;
  }
  return false;
}

uint64 GpuChannelManager::MessagesProcessed() {
  uint64 messages_processed = 0;

  for (GpuChannelMap::iterator iter = gpu_channels_.begin();
       iter != gpu_channels_.end(); ++iter) {
    messages_processed += iter->second->messages_processed();
  }
  return messages_processed;
}

void GpuChannelManager::LoseAllContexts() {
  for (GpuChannelMap::iterator iter = gpu_channels_.begin();
       iter != gpu_channels_.end(); ++iter) {
    iter->second->MarkAllContextsLost();
  }
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&GpuChannelManager::OnLoseAllContexts,
                            weak_factory_.GetWeakPtr()));
}

void GpuChannelManager::OnLoseAllContexts() {
  gpu_channels_.clear();
  CheckRelinquishGpuResources();
}

gfx::GLSurface* GpuChannelManager::GetDefaultOffscreenSurface() {
  if (!default_offscreen_surface_.get()) {
    default_offscreen_surface_ =
        gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size());
  }
  return default_offscreen_surface_.get();
}

void GpuChannelManager::OnRelinquishResources() {
  relinquish_resources_pending_ = true;
  CheckRelinquishGpuResources();
}

void GpuChannelManager::CheckRelinquishGpuResources() {
  if (relinquish_resources_pending_ && gpu_channels_.size() <= 1) {
    relinquish_resources_pending_ = false;
    if (default_offscreen_surface_.get()) {
      default_offscreen_surface_->DestroyAndTerminateDisplay();
      default_offscreen_surface_ = NULL;
    }
#if defined(USE_OZONE)
    ui::OzonePlatform::GetInstance()
        ->GetGpuPlatformSupport()
        ->RelinquishGpuResources(
            base::Bind(&GpuChannelManager::OnResourcesRelinquished,
                       weak_factory_.GetWeakPtr()));
#else
    OnResourcesRelinquished();
#endif
  }
}

void GpuChannelManager::OnResourcesRelinquished() {
  Send(new GpuHostMsg_ResourcesRelinquished());
}

}  // namespace content


text:
@interface TextFieldTableViewCell : JRTFormTextFieldTableViewCell
- (void)setInitialLabelText:(NSString *)text;
@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Triblidium cucurbitaria Rehm

### Remarks
null