text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.

package com.microsoft.alm.plugin.idea.git.ui.pullrequest;

import com.intellij.openapi.util.Pair;
import com.microsoft.alm.common.utils.UrlHelper;
import com.microsoft.alm.plugin.context.ServerContext;
import com.microsoft.alm.plugin.context.rest.GitPullRequestEx;
import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle;
import com.microsoft.alm.sourcecontrol.webapi.GitHttpClient;
import com.microsoft.alm.sourcecontrol.webapi.model.GitPullRequest;
import com.microsoft.alm.sourcecontrol.webapi.model.GitPullRequestSearchCriteria;
import com.microsoft.alm.sourcecontrol.webapi.model.PullRequestStatus;
import com.microsoft.visualstudio.services.webapi.model.ResourceRef;
import git4idea.GitCommit;
import git4idea.GitRemoteBranch;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * Helper utility class for pull request related methods
 */
public class PullRequestHelper {

    private static final Logger logger = LoggerFactory.getLogger(PullRequestHelper.class);

    public enum PRCreateStatus {
        UNKNOWN,
        FAILED,
        SUCCESS,
        DUPLICATE
    }

    public static final String PR_EXISTS_EXCEPTION_NAME = "GitPullRequestExistsException";
    public static final String PR_EXISTS_EXCEPTION_CODE = "TF401179";

    private static final String WEB_ACCESS_PR_FORMAT = "%s/pullrequest/%d";
    private static final String TF_REF_FORMATTER = "refs/heads/%s";

    /**
     * Create a default title for pull request
     *

     * If there is only one commit, use its subject; otherwise use a standard template
     * "Merge source to target".
     *

     * Default titles will be less than 120 chars.
     *
     * @return default title
     */
    public String createDefaultTitle(final List<GitCommit> commits, final String sourceBranchName,
                                     final String targetBranchName) {

        if (commits == null || commits.isEmpty()) {
            return StringUtils.EMPTY;
        }

        if (commits.size() == 1) {
            // if we only have one commit, use it's title as the title of pull request
            final GitCommit commit = commits.get(0);
            final String commitMessage = commit.getSubject();

            //WebAcess use 80 (because it's common code for many things, and 80 is such a magic number),
            //but IMHO 80 is too short for title, set it to 120
            final int titleLength = 120;
            if (commitMessage.length() < titleLength) {
                return commitMessage;
            } else {
                // break at last whitespace right before length 120
                final String shortCommitMessage = commitMessage.substring(0, titleLength);
                return StringUtils.substringBeforeLast(shortCommitMessage, "\\s+");
            }
        }

        // Standard title "merging source branch to target branch"
        return TfPluginBundle.message(TfPluginBundle.KEY_CREATE_PR_DEFAULT_TITLE, sourceBranchName, targetBranchName);
    }

    /**
     * Create a default description for pull request
     *

     * If there is only one commit, use its message; otherwise use a standard template
     * "-Subject" for every commit
     *
     * @return default Description
     */
    public String createDefaultDescription(final List<GitCommit> commits) {
        if (commits == null || commits.isEmpty()) {
            return StringUtils.EMPTY;
        }

        if (commits.size() == 1) {
            final GitCommit commit = commits.get(0);
            if (commit.getFullMessage().length() > CreatePullRequestModel.MAX_SIZE_DESCRIPTION) {
                return commit.getFullMessage().substring(0, CreatePullRequestModel.MAX_SIZE_DESCRIPTION - 5) + "...";
            }

            return commit.getFullMessage();
        }

        final StringBuilder descBuilder = new StringBuilder();
        final String lineSeparator = System.getProperty("line.separator");

        // WebAccess limit, at most we look at the last 10 commits
        final int descCommitsLimit = 10;
        for (int i = 0; i < descCommitsLimit && i < commits.size(); ++i) {
            final GitCommit commit = commits.get(i);
            descBuilder.append("-").append(commit.getSubject()).append(lineSeparator);
        }

        // there is a chance there are more than 10 commits
        if (commits.size() > descCommitsLimit) {
            descBuilder.append("...");
        }

        // oh well, if it's longer than 4000 chars, we probably won't care about the last few words
        // we will lose our "..." and may break off in the middle of a word
        return descBuilder.length() < CreatePullRequestModel.MAX_SIZE_DESCRIPTION
                ? descBuilder.toString() : descBuilder.substring(0, CreatePullRequestModel.MAX_SIZE_DESCRIPTION - 10);
    }

    /**
     * A html document points to the webaccess PR link
     *
     * @param repositoryRemoteUrl git repo url
     * @param id                  pull request id
     * @return html document with link to specified pull request
     */
    public String getHtmlMsg(final String repositoryRemoteUrl, final int id) {
        String url = UrlHelper.removeUserInfo(repositoryRemoteUrl);
        final String text = TfPluginBundle.message(TfPluginBundle.KEY_CREATE_PR_CREATED_MESSAGE, String.valueOf(id));
        final String webAccessUrl = String.format(WEB_ACCESS_PR_FORMAT, url, id);
        return String.format(UrlHelper.SHORT_HTTP_LINK_FORMATTER, webAccessUrl, text);
    }

    public GitPullRequestEx generateGitPullRequest(@NotNull final String title,
                                                   @NotNull final String description,
                                                   @NotNull final String branchNameOnRemoteServer,
                                                   @NotNull final GitRemoteBranch targetBranch,
                                                   @NotNull final Set<Integer> workItems,
                                                   @NotNull final ServerContext context) {
        final GitPullRequestEx pullRequest = new GitPullRequestEx();
        pullRequest.setTitle(title);
        pullRequest.setDescription(description);
        pullRequest.setSourceRefName(getVSORefName(branchNameOnRemoteServer));
        pullRequest.setTargetRefName(getVSORefName(targetBranch.getNameForRemoteOperations()));

        // add work items that are to be associated to the request
        try {
            if (!workItems.isEmpty()) {
                final ResourceRef[] workItemRefs = new ResourceRef[workItems.size()];
                int count = 0;
                for (final int workItemId : workItems) {
                    final ResourceRef ref = new ResourceRef();
                    ref.setId(String.valueOf(workItemId));
                    ref.setUrl(UrlHelper.getWorkItemRefURI(context.getTeamProjectURI(), String.valueOf(workItemId)).toString());
                    workItemRefs[count] = ref;
                    count++;
                }

                pullRequest.setWorkItemRefs(workItemRefs);
            }
        } catch (Exception e) {
            logger.warn("Error while adding work items to pull request", e);
        }

        return pullRequest;
    }

    /**
     * Parse the exception we got when generating pull request
     *

     * if we have a duplicate pr on server, try locate its id and generate a link to it
     *
     * @return status and string message as a pair
     */
    public Pair<PRCreateStatus, String> parseException(final Throwable t, final String sourceBranch,
                                                       final GitRemoteBranch targetBranch, final ServerContext context,
                                                       final GitHttpClient gitClient) {
        if (t == null) {
            // if there is no throwale, why are we here?
            return Pair.create(PRCreateStatus.UNKNOWN, StringUtils.EMPTY);
        }

        if ((StringUtils.contains(t.getMessage(), PR_EXISTS_EXCEPTION_NAME)) || (StringUtils.contains(t.getMessage(), PR_EXISTS_EXCEPTION_CODE))) {
            try {
                // look for the existing PR
                final UUID repoId = context.getGitRepository().getId();
                final GitPullRequestSearchCriteria searchCriteria = new GitPullRequestSearchCriteria();
                searchCriteria.setRepositoryId(repoId);
                searchCriteria.setStatus(PullRequestStatus.ACTIVE);
                searchCriteria.setSourceRefName(getVSORefName(sourceBranch));
                searchCriteria.setTargetRefName(getVSORefName(targetBranch.getNameForRemoteOperations()));
                List<GitPullRequest> pullRequests = gitClient.getPullRequests(repoId, searchCriteria, null, 0, 1);

                if (pullRequests != null && pullRequests.size() > 0) {
                    final String repositoryRemoteUrl = context.getGitRepository().getRemoteUrl();
                    final String notifyMsgInHtml = getHtmlMsg(repositoryRemoteUrl, pullRequests.get(0).getPullRequestId());

                    return Pair.create(PRCreateStatus.DUPLICATE, notifyMsgInHtml);
                }
            } catch (Throwable innerT) {
                logger.error("Failed to retrieve existing pull request", innerT);

                // since we are making server calls, it's possible this call will fail, in that case, just return
                // the original exception, never let any exception bubble up to intellij
                return Pair.create(PRCreateStatus.FAILED, t.getMessage());
            }
        }

        return Pair.create(PRCreateStatus.FAILED, t.getMessage());
    }

    private String getVSORefName(final String name) {
        return String.format(TF_REF_FORMATTER, name);
    }
}


text:
package net.wendal.nutzwx.service;

public interface ResourceService {

	boolean put(String openid, String key, String str);

	String get(String openid, String key);

	<T> T getAsJsonObjet(String openid, String key, Class<T> klass);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * Simple database connection script
 *
 * PDO class.
 */
//define("PDO_USER", "root");
//define("PDO_PASS", "root");

class GenericPDO {

	  private $db;

	  public function __construct($dsn) {
	    try {
	      $this->db = new PDO($dsn, PDO_USER, PDO_PASS, array( PDO::ATTR_PERSISTENT => true ));
	    } catch (PDOException $e) {
	      die('Connection failed: ' . $e->getMessage());
	    }
	  }

	  function __destruct() {
	    $this->db = NULL;
	  }

	  private function handleException($e) {
	    echo "Database error: " . $e->getMessage();
	    exit;
	  }

	public function getEntries($limit) {
	    $result = array();
	    try {
	      $sql = "SELECT * FROM entries WHERE moderate=0";
	      //if ($conditions) $sql .= "AND ".$conditions;
	      if ($limit && $limit > 0) $sql .= " LIMIT ".intval($limit);
	      $stmt = $this->db->prepare($sql);
	      $stmt->execute();
	      while ($row = $stmt->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_NEXT)) {
		      $result[] = $row;
		    }
		    $stmt = null;
	      return json_encode($result);
	    } catch (PDOException $e) {
	      $this->handleException($e);
	    }
    }

   public function getEntry($id) {
	    $result = array();
	    try {
	      $sql = "SELECT * FROM entries";
	      //if ($conditions) $sql .= "AND ".$conditions;
	      if ($id > 0){
		      $sql .= " WHERE id=".intval($id);
	      } else {
		      throw PDOException('Need an ID');
	      }
	      $stmt = $this->db->prepare($sql);
	      $stmt->execute();
	      while ($row = $stmt->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_NEXT)) {
		      $result[] = $row;
		    }
		    $stmt = null;
	      return json_encode($result);
	    } catch (PDOException $e) {
	      $this->handleException($e);
	    }
    }

	//TODO: add code to prevent sql injection.
	public function executeSQL2($sql){
		$return_data = array();
		try {
			//PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);
			 $stmt = $this->dbh->prepare($sql);
			 $stmt->execute();
			 //$return_data = $stmt->fetch(PDO::FETCH_OBJ);
			 //while ($row = $sth->fetch (PDO::FETCH_BOTH)){}
			 //while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
			 while ($row = $stmt->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_NEXT)) {
		      $return_data[] = $row;
		    }
		    $stmt = null;

	    } catch (PDOException $e) {
	        $return_data = "Error!: " . $e->getMessage() . "<br/>";
	        die();
	    }

	    return json_encode($return_data);
    }

}
?>


text:
Get the last matching element for the locator.

###Example

```html
<ul class="items">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>
```

```javascript
var list = element.all(by.css('.items li'));
expect(list.last().getText()).toBe('Third');
```

###Returns

Type | Description
--- | ---
[webdriver.WebElement](#webdriverwebelement) | the last matching element


text:
package replicant;

import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ChannelAddressTest
  extends AbstractReplicantTest
{
  @Test
  public void construct()
  {
    final ChannelAddress address = new ChannelAddress( 2, 4, 1 );

    assertEquals( address.getSystemId(), 2 );
    assertEquals( address.getChannelId(), 4 );
    assertEquals( address.getId(), (Integer) 1 );
  }

  @Test
  public void parseWithSubChannel()
  {
    final ChannelAddress address = ChannelAddress.parse( 2, "4.1" );

    assertEquals( address.getSystemId(), 2 );
    assertEquals( address.getChannelId(), 4 );
    assertEquals( address.getId(), (Integer) 1 );
  }

  @Test
  public void parse()
  {
    final ChannelAddress address = ChannelAddress.parse( 4, "77" );

    assertEquals( address.getSystemId(), 4 );
    assertEquals( address.getChannelId(), 77 );
    assertEquals( address.getId(), null );
  }

  @Test
  public void getCacheKey()
  {
    final ChannelAddress address = new ChannelAddress( 2, 4, 1 );
    assertEquals( address.getCacheKey(), "RC-2.4.1" );
  }

  @SuppressWarnings( "EqualsWithItself" )
  @Test
  public void testEquals()
  {
    final ChannelAddress address = new ChannelAddress( 1, 2, 1 );
    final ChannelAddress address2 = new ChannelAddress( 1, 2, 2 );
    final ChannelAddress address3 = new ChannelAddress( 1, 1 );

    assertTrue( address.equals( address ) );
    assertFalse( address.equals( new Object() ) );
    assertFalse( address.equals( address2 ) );
    assertFalse( address.equals( address3 ) );
  }

  @Test
  public void toStringTest()
  {
    final ChannelAddress address = new ChannelAddress( 1, 2, 1 );
    assertEquals( address.toString(), "1.2.1" );
  }

  @Test
  public void toStringTest_NamingDisabled()
  {
    ReplicantTestUtil.disableNames();
    final ChannelAddress address =
      new ChannelAddress( ValueUtil.randomInt(), ValueUtil.randomInt(), ValueUtil.randomInt() );
    assertEquals( address.toString(), "replicant.ChannelAddress@" + Integer.toHexString( address.hashCode() ) );
  }

  @Test
  public void getName_NamingDisabled()
  {
    ReplicantTestUtil.disableNames();
    assertEquals( new ChannelAddress( 1, 3, 5 ).getName(), "1.3.5" );
  }

  @Test
  public void asChannelDescriptor()
  {
    assertEquals( new ChannelAddress( 1, 3, 5 ).asChannelDescriptor(), "3.5" );
  }

  @SuppressWarnings( "EqualsWithItself" )
  @Test
  public void compareTo()
  {
    final ChannelAddress address1 = new ChannelAddress( 1, 1 );
    final ChannelAddress address2 = new ChannelAddress( 1, 2, 1 );

    assertEquals( address1.compareTo( address1 ), 0 );
    assertEquals( address1.compareTo( address2 ), -1 );
    assertEquals( address2.compareTo( address1 ), 1 );
    assertEquals( address2.compareTo( address2 ), 0 );
  }
}


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CodeCracker.CSharp.Usage
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CallExtensionMethodAsExtensionCodeFixProvider)), Shared]
    public class CallExtensionMethodAsExtensionCodeFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(DiagnosticId.CallExtensionMethodAsExtension.ToDiagnosticId());

        public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            context.RegisterCodeFix(CodeAction.Create(
                "Use extension method as an extension",
                cancellationToken => CallAsExtensionAsync(context.Document, diagnostic, cancellationToken), nameof(CallExtensionMethodAsExtensionCodeFixProvider)),
                diagnostic);
            return Task.FromResult(0);
        }

        private static async Task<Document> CallAsExtensionAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var staticInvocationExpression = root
                .FindToken(diagnosticSpan.Start)
                .Parent.AncestorsAndSelf()
                .OfType<InvocationExpressionSyntax>()
                .First();

            var childNodes = staticInvocationExpression.ChildNodes();
            var parameterExpressions = GetParameterExpressions(childNodes);

            var firstArgument = parameterExpressions.FirstOrDefault();
            var callerMethod = childNodes.OfType<MemberAccessExpressionSyntax>().FirstOrDefault();

            root = ReplaceStaticCallWithExtionMethodCall(
                        root,
                        staticInvocationExpression,
                        firstArgument,
                        callerMethod.Name,
                        CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1))
                   ).WithAdditionalAnnotations(Formatter.Annotation);

            var semanticModel = await document.GetSemanticModelAsync();
            root = ImportNeededNamespace(root, semanticModel, callerMethod).WithAdditionalAnnotations(Formatter.Annotation);
            var newDocument = document.WithSyntaxRoot(root);

            return newDocument;
        }

        public static IEnumerable<ExpressionSyntax> GetParameterExpressions(IEnumerable<SyntaxNode> childNodes) =>
            childNodes.OfType<ArgumentListSyntax>().SelectMany(s => s.Arguments).Select(s => s.Expression);

        public static ArgumentListSyntax CreateArgumentListSyntaxFrom(IEnumerable<ExpressionSyntax> expressions) =>
            SyntaxFactory.ArgumentList().AddArguments(expressions.Select(s => SyntaxFactory.Argument(s)).ToArray());

        private static CompilationUnitSyntax ReplaceStaticCallWithExtionMethodCall(CompilationUnitSyntax root, InvocationExpressionSyntax staticInvocationExpression, ExpressionSyntax sourceExpression, SimpleNameSyntax methodName, ArgumentListSyntax argumentList)
        {
            var extensionInvocationExpression = CreateInvocationExpression(sourceExpression, methodName, argumentList)
                .WithLeadingTrivia(staticInvocationExpression.GetLeadingTrivia());
            return root.ReplaceNode(staticInvocationExpression, extensionInvocationExpression);
        }

        public static InvocationExpressionSyntax CreateInvocationExpression(ExpressionSyntax sourceExpression, SimpleNameSyntax methodName, ArgumentListSyntax argumentList) =>
            SyntaxFactory.InvocationExpression(
                SyntaxFactory.MemberAccessExpression(
                SyntaxKind.SimpleMemberAccessExpression,
                sourceExpression,
                methodName),
                argumentList);

        private static CompilationUnitSyntax ImportNeededNamespace(CompilationUnitSyntax root, SemanticModel semanticModel, MemberAccessExpressionSyntax callerMethod)
        {
            var symbolInfo = semanticModel.GetSymbolInfo(callerMethod.Name);
            var methodSymbol = symbolInfo.Symbol as IMethodSymbol;
            if (methodSymbol == null) return root;
            var namespaceDisplayString = methodSymbol.ContainingNamespace.ToDisplayString();
            var hasNamespaceImported = root
                .DescendantNodes()
                .OfType<UsingDirectiveSyntax>()
                .Select(s => s.Name.ToString())
                .Any(n => n == namespaceDisplayString);
            if (!hasNamespaceImported)
            {
                var namespaceQualifiedName = methodSymbol.ContainingNamespace.ToNameSyntax();
                root = root.AddUsings(SyntaxFactory.UsingDirective(namespaceQualifiedName));
            }
            return root;
        }
    }
}


text:
sudo launchctl unload -w /Library/LaunchDaemons/com.xsnmp.xsnmp-agentx.plist
sudo launchctl unload -w /System/Library/LaunchDaemons/org.net-snmp.snmpd.plist
sudo rm -rf /Library/Xsnmp
sudo rm -rf /Library/PreferencePanes/Xsnmp.prefPane
sudo rm /Library/Preferences/com.xsnmp.xsnmp.plist
sudo cp /etc/snmp/snmpd.conf.default /etc/snmp/snmpd.conf


text:
	<TITLE>3rd Party ROBOTC Drivers</TITLE>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

    3rd Party ROBOTC Drivers

            [Home] [Download] [Submit a bug/suggestion]  [ROBOTC Forums] [Blog] [Support this project]

hitechnic-colour-v1-test1.c

#pragma config(Sensor, S1,     HTCS,                sensorI2CCustom)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

/*
 * $Id: hitechnic-colour-v1-test1.c 133 2013-03-10 15:15:38Z xander $
 */

/**
 * hitechnic-colour-v1.h provides an API for the HiTechnic Color Sensor.  This program
 * demonstrates how to use that API.
 *
 * Changelog:
 * - 0.1: Initial release
 * - 0.2: Changed the intro and info displayed
 * - 0.3: More comments
 * - 0.4: Removed common.h from includes
 *
 * Credits:
 * - Big thanks to HiTechnic for providing me with the hardware necessary to write and test this.
 *
 * License: You may use this code as you wish, provided you give credit where it's due.
 *
 * THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 3.59 AND HIGHER.

 * Xander Soldaat (xander_at_botbench.com)
 * 20 February 2011
 * version 0.4
 */

#include "drivers/hitechnic-colour-v1.h"

task main () {
  int red = 0;
  int green = 0;
  int blue = 0;
  int _color = 0;
  string _tmp;

  nxtDisplayCenteredTextLine(0, "HiTechnic");
  nxtDisplayCenteredBigTextLine(1, "COLOUR");
  nxtDisplayCenteredTextLine(3, "Test 1");
  nxtDisplayCenteredTextLine(5, "Connect sensor");
  nxtDisplayCenteredTextLine(6, "to S1");
  wait1Msec(2000);

  eraseDisplay();
  while (true) {
    // Read the currently detected colour from the sensor
    _color = HTCSreadColor(HTCS);

    // If colour == -1, it implies an error has occurred
    if (_color < 0) {
      nxtDisplayTextLine(4, "ERROR!!");
      wait1Msec(2000);
      StopAllTasks();
    }

    // Read the RGB values of the currently colour from the sensor
    // A return value of false implies an error has occurred
    if (!HTCSreadRGB(HTCS, red, green, blue)) {
      nxtDisplayTextLine(4, "ERROR!!");
      wait1Msec(2000);
      StopAllTasks();
    }

    nxtDisplayCenteredTextLine(0, "Color: %d", _color);
    nxtDisplayCenteredBigTextLine(1, "R  G  B");

    nxtEraseRect(0,10, 99, 41);
    nxtFillRect( 0, 10, 30, 10 + (red+1)/8);
    nxtFillRect(35, 10, 65, 10 + (green+1)/8);
    nxtFillRect(70, 10, 99, 10 + (blue+1)/8);
    StringFormat(_tmp, " %3d   %3d", red, green);
    nxtDisplayTextLine(7, "%s   %3d", _tmp, blue);

    wait1Msec(100);
  }
}

/*
 * $Id: hitechnic-colour-v1-test1.c 133 2013-03-10 15:15:38Z xander $
 */

<address class="footer">Generated on Wed Mar 13 2013 19:56:42 for ROBOTC Drivers by

 1.7.2 </address>


text:
package org.apache.camel.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.processor.OnCompletionProcessor;
import org.apache.camel.processor.UnitOfWorkProcessor;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.util.concurrent.ExecutorServiceHelper;

/**
 * Represents an XML <onCompletion/> element
 *
 * @version
 */
@XmlRootElement(name = "onCompletion")
@XmlAccessorType(XmlAccessType.FIELD)
public class OnCompletionDefinition extends ProcessorDefinition<OnCompletionDefinition> implements ExecutorServiceAwareDefinition<OnCompletionDefinition> {
    @XmlAttribute
    private Boolean onCompleteOnly;
    @XmlAttribute
    private Boolean onFailureOnly;
    @XmlElement(name = "onWhen")
    private WhenDefinition onWhen;
    @XmlAttribute
    private String executorServiceRef;
    @XmlAttribute(name = "useOriginalMessage")
    private Boolean useOriginalMessagePolicy;
    @XmlElementRef
    private List<ProcessorDefinition> outputs = new ArrayList<ProcessorDefinition>();
    @XmlTransient
    private ExecutorService executorService;

    public OnCompletionDefinition() {
    }

    @Override
    public String toString() {
        return "onCompletion[" + getOutputs() + "]";
    }

    @Override
    public String getShortName() {
        return "onCompletion";
    }

    @Override
    public String getLabel() {
        return "onCompletion";
    }

    @Override
    public boolean isAbstract() {
        return true;
    }

    @Override
    public Processor createProcessor(RouteContext routeContext) throws Exception {
        if (isOnCompleteOnly() && isOnFailureOnly()) {
            throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
        }

        Processor childProcessor = this.createChildProcessor(routeContext, true);

        // wrap the on completion route in a unit of work processor
        childProcessor = new UnitOfWorkProcessor(routeContext, childProcessor);

        Predicate when = null;
        if (onWhen != null) {
            when = onWhen.getExpression().createPredicate(routeContext);
        }

        executorService = ExecutorServiceHelper.getConfiguredExecutorService(routeContext, "OnCompletion", this);
        if (executorService == null) {
            executorService = routeContext.getCamelContext().getExecutorServiceStrategy().newDefaultThreadPool(this, "OnCompletion");
        }
        // should be false by default
        boolean original = getUseOriginalMessagePolicy() != null ? getUseOriginalMessagePolicy() : false;
        OnCompletionProcessor answer = new OnCompletionProcessor(routeContext.getCamelContext(), childProcessor,
                executorService, isOnCompleteOnly(), isOnFailureOnly(), when, original);
        return answer;
    }

    /**
     * Removes all existing {@link org.apache.camel.model.OnCompletionDefinition} from the definition.
     *

     * This is used to let route scoped <tt>onCompletion</tt> overrule any global <tt>onCompletion</tt>.
     * Hence we remove all existing as they are global.
     *
     * @param definition the parent definition that is the route
     */
    @SuppressWarnings("unchecked")
    public void removeAllOnCompletionDefinition(ProcessorDefinition definition) {
        for (Iterator<ProcessorDefinition> it = definition.getOutputs().iterator(); it.hasNext();) {
            ProcessorDefinition out = it.next();
            if (out instanceof OnCompletionDefinition) {
                it.remove();
            }
        }
    }

    @Override
    public ProcessorDefinition end() {
        // pop parent block, as we added our self as block to parent when synchronized was defined in the route
        getParent().popBlock();
        return super.end();
    }

    /**
     * Will only synchronize when the {@link org.apache.camel.Exchange} completed successfully (no errors).
     *
     * @return the builder
     */
    public OnCompletionDefinition onCompleteOnly() {
        if (isOnFailureOnly()) {
            throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
        }
        // must define return type as OutputDefinition and not this type to avoid end user being able
        // to invoke onFailureOnly/onCompleteOnly more than once
        setOnCompleteOnly(Boolean.TRUE);
        setOnFailureOnly(Boolean.FALSE);
        return this;
    }

    /**
     * Will only synchronize when the {@link org.apache.camel.Exchange} ended with failure (exception or FAULT message).
     *
     * @return the builder
     */
    public OnCompletionDefinition onFailureOnly() {
        if (isOnCompleteOnly()) {
            throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
        }
        // must define return type as OutputDefinition and not this type to avoid end user being able
        // to invoke onFailureOnly/onCompleteOnly more than once
        setOnCompleteOnly(Boolean.FALSE);
        setOnFailureOnly(Boolean.TRUE);
        return this;
    }

    /**
     * Sets an additional predicate that should be true before the onCompletion is triggered.
     *

     * To be used for fine grained controlling whether a completion callback should be invoked or not
     *
     * @param predicate predicate that determines true or false
     * @return the builder
     */
    public OnCompletionDefinition onWhen(Predicate predicate) {
        setOnWhen(new WhenDefinition(predicate));
        return this;
    }

    /**
     * Will use the original input body when an {@link org.apache.camel.Exchange} for this on completion.
     *

     * By default this feature is off.
     *
     * @return the builder
     */
    public OnCompletionDefinition useOriginalBody() {
        setUseOriginalMessagePolicy(Boolean.TRUE);
        return this;
    }

    public OnCompletionDefinition executorService(ExecutorService executorService) {
        setExecutorService(executorService);
        return this;
    }

    public OnCompletionDefinition executorServiceRef(String executorServiceRef) {
        setExecutorServiceRef(executorServiceRef);
        return this;
    }

    public List<ProcessorDefinition> getOutputs() {
        return outputs;
    }

    public void setOutputs(List<ProcessorDefinition> outputs) {
        this.outputs = outputs;
    }

    public boolean isOutputSupported() {
        return true;
    }

    public Boolean getOnCompleteOnly() {
        return onCompleteOnly;
    }

    public void setOnCompleteOnly(Boolean onCompleteOnly) {
        this.onCompleteOnly = onCompleteOnly;
    }

    public boolean isOnCompleteOnly() {
        return onCompleteOnly != null && onCompleteOnly;
    }

    public Boolean getOnFailureOnly() {
        return onFailureOnly;
    }

    public void setOnFailureOnly(Boolean onFailureOnly) {
        this.onFailureOnly = onFailureOnly;
    }

    public boolean isOnFailureOnly() {
        return onFailureOnly != null && onFailureOnly;
    }

    public WhenDefinition getOnWhen() {
        return onWhen;
    }

    public void setOnWhen(WhenDefinition onWhen) {
        this.onWhen = onWhen;
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public String getExecutorServiceRef() {
        return executorServiceRef;
    }

    public void setExecutorServiceRef(String executorServiceRef) {
        this.executorServiceRef = executorServiceRef;
    }

    public Boolean getUseOriginalMessagePolicy() {
        return useOriginalMessagePolicy != null;
    }

    public void setUseOriginalMessagePolicy(Boolean useOriginalMessagePolicy) {
        this.useOriginalMessagePolicy = useOriginalMessagePolicy;
    }

}


text:
layout: posts_by_tag
tag: atom
permalink: /tags/atom/
---


text:
copyright:
  years: 2015, 2016

---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}

# Python
{: #python_runtime}
*Ultimo aggiornamento: 10 giugno 2016*
{: .last-updated}

Il runtime Python su {{site.data.keyword.Bluemix}} si avvale del python_buildpack.
Il python_buildpack fornisce un ambiente di runtime completo per le applicazioni Python.
{: shortdesc}

Il python_buildpack verrà utilizzato se la directory root della tua applicazione contiene un file requirements.txt o un file setup.py.

## Applicazione starter
{: #starter_application}

{{site.data.keyword.Bluemix}} fornisce un'applicazione starter Python.  L'applicazione starter Python è una semplice applicazione Python che fornisce un template che puoi utilizzare per la tua applicazione. Puoi fare delle prove con l'applicazione starter, apportare modifiche ed eseguirne il push
all'ambiente {{site.data.keyword.Bluemix}}.  Consulta [Utilizzo di applicazioni starter](../../cfapps/starter_app_usage.html) per informazioni sull'utilizzo dell'applicazione starter.

## Versioni di runtime
{: #runtime_versions}

Puoi specificare la versione di Python che deve essere utilizzata dalla tua applicazione impostando python-versionnumber nel file runtime.txt nella root della tua applicazione. Ad esempio:

```
python-3.4.3
```
{: codeblock}

Quando non viene specificata una versione, viene scelta per impostazione predefinita la versione 2.7.10.

### Versioni disponibili:
{: #available_versions}

Le seguenti versioni Python sono disponibili nel [pacchetto
di build Python](https://github.com/cloudfoundry/python-buildpack/releases/tag/v1.5.1) attualmente
installato in {{site.data.keyword.Bluemix}}:

* 2.7.9
* 2.7.10
* 3.3.5
* 3.3.6
* 3.4.2
* 3.4.3
* 3.5.0

Se la tua applicazione richiede una versione di Python che non è elencata, puoi utilizzare
il [pacchetto di build Python](https://github.com/cloudfoundry/python-buildpack) esterno
per distribuire l'applicazione.

# rellinks
{: #rellinks}
## general
{: #general}
* [Pacchetto di build Cloud Foundry per Python](https://github.com/cloudfoundry/python-buildpack)


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/type/postal_address.proto

package com.google.type;

public final class PostalAddressProto {
  private PostalAddressProto() {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
  }

  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_type_PostalAddress_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_type_PostalAddress_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
    return descriptor;
  }

  private static com.google.protobuf.Descriptors.FileDescriptor descriptor;

  static {
    java.lang.String[] descriptorData = {
      "\n google/type/postal_address.proto\022\013goog"
          + "le.type\"\375\001\n\rPostalAddress\022\020\n\010revision\030\001 "
          + "\001(\005\022\023\n\013region_code\030\002 \001(\t\022\025\n\rlanguage_cod"
          + "e\030\003 \001(\t\022\023\n\013postal_code\030\004 \001(\t\022\024\n\014sorting_"
          + "code\030\005 \001(\t\022\033\n\023administrative_area\030\006 \001(\t\022"
          + "\020\n\010locality\030\007 \001(\t\022\023\n\013sublocality\030\010 \001(\t\022\025"
          + "\n\raddress_lines\030\t \003(\t\022\022\n\nrecipients\030\n \003("
          + "\t\022\024\n\014organization\030\013 \001(\tBx\n\017com.google.ty"
          + "peB\022PostalAddressProtoP\001ZFgoogle.golang."
          + "org/genproto/googleapis/type/postaladdre"
          + "ss;postaladdress\370\001\001\242\002\003GTPb\006proto3"
    };
    descriptor =
        com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
            descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {});
    internal_static_google_type_PostalAddress_descriptor = getDescriptor().getMessageTypes().get(0);
    internal_static_google_type_PostalAddress_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_type_PostalAddress_descriptor,
            new java.lang.String[] {
              "Revision",
              "RegionCode",
              "LanguageCode",
              "PostalCode",
              "SortingCode",
              "AdministrativeArea",
              "Locality",
              "Sublocality",
              "AddressLines",
              "Recipients",
              "Organization",
            });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
//
// In these tests, we mock React-Bootstrap, so we can only check it has the right components
//

/*global jest, describe, it, expect */
'use strict';

jest.dontMock('../DropdownInput');
var React = require('react/addons');
var DropdownInput = require('../DropdownInput');
var ReactBootstrap = require('react-bootstrap');
var TestUtils = React.addons.TestUtils;

describe('DropdownInput', function() {

  var names = ['Aab', 'abcd', 'Cde', 'Def', 'Deb', 'Eabc'];
  var menuClassName = 'jest-test';
  var id = 'test-id';
  var element = (<DropdownInput id={id} options={names} menuClassName={menuClassName}/>);
  var result;

  beforeEach(function() {
    var shallowRenderer = TestUtils.createRenderer();
    shallowRenderer.render(element);
    result = shallowRenderer.getRenderOutput();
  });

  it('contains the right components', function() {
    // there should be one Input component and one DropdownMenu component
    // for now, assume in that order - TODO: generalize
    var child0 = result.props.children[0];
    var child1 = result.props.children[1];
    expect(child0.type).toEqual(ReactBootstrap.Input);
    expect(child1.type).toEqual(ReactBootstrap.DropdownMenu);
    // also check the dropdown menu has been passed the right class name
    expect(child1.props.className).toEqual(menuClassName);
  });

  it('contains the right menu items', function() {
    var child1 = result.props.children[1];
    var child1props = child1.props.children[0]; // not very general
    expect(child1props[0].props.children).toContain(names[0]);
  });

});


text:
#include "third_party/blink/renderer/core/html/html_image_element.h"

#include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_image_bitmap_options.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/media_query_matcher.h"
#include "third_party/blink/renderer/core/css/media_values_dynamic.h"
#include "third_party/blink/renderer/core/css/parser/sizes_attribute_parser.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/attribution_src_loader.h"
#include "third_party/blink/renderer/core/frame/deprecation/deprecation.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/cross_origin_attribute.h"
#include "third_party/blink/renderer/core/html/forms/form_associated.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/html_dimension.h"
#include "third_party/blink/renderer/core/html/html_image_fallback_helper.h"
#include "third_party/blink/renderer/core/html/html_picture_element.h"
#include "third_party/blink/renderer/core/html/html_source_element.h"
#include "third_party/blink/renderer/core/html/loading_attribute.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/parser/html_srcset_parser.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/layout/layout_object_factory.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/media_type_names.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/paint_timing.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/style/content_data.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"

namespace blink {

class HTMLImageElement::ViewportChangeListener final
    : public MediaQueryListListener {
 public:
  explicit ViewportChangeListener(HTMLImageElement* element)
      : element_(element) {}

  void NotifyMediaQueryChanged() override {
    if (element_)
      element_->NotifyViewportChanged();
  }

  void Trace(Visitor* visitor) const override {
    visitor->Trace(element_);
    MediaQueryListListener::Trace(visitor);
  }

 private:
  Member<HTMLImageElement> element_;
};

HTMLImageElement::HTMLImageElement(Document& document,
                                   const CreateElementFlags flags)
    : HTMLImageElement(document, flags.IsCreatedByParser()) {}

HTMLImageElement::HTMLImageElement(Document& document, bool created_by_parser)
    : HTMLElement(html_names::kImgTag, document),
      image_loader_(MakeGarbageCollected<HTMLImageLoader>(this)),
      image_device_pixel_ratio_(1.0f),
      source_(nullptr),
      layout_disposition_(LayoutDisposition::kPrimaryContent),
      form_was_set_by_parser_(false),
      element_created_by_parser_(created_by_parser),
      is_fallback_image_(false),
      is_default_overridden_intrinsic_size_(
          !document.IsImageDocument() && GetExecutionContext() &&
          !GetExecutionContext()->IsFeatureEnabled(
              mojom::blink::DocumentPolicyFeature::kUnsizedMedia)),
      is_legacy_format_or_unoptimized_image_(false),
      is_ad_related_(false),
      is_lcp_element_(false),
      is_changed_shortly_after_mouseover_(false),
      has_sizes_attribute_(false),
      is_lazy_loaded_(false),
      referrer_policy_(network::mojom::ReferrerPolicy::kDefault) {
  SetHasCustomStyleCallbacks();
}

HTMLImageElement::~HTMLImageElement() = default;

void HTMLImageElement::Trace(Visitor* visitor) const {
  visitor->Trace(image_loader_);
  visitor->Trace(listener_);
  visitor->Trace(form_);
  visitor->Trace(source_);
  HTMLElement::Trace(visitor);
}

void HTMLImageElement::NotifyViewportChanged() {
  // Re-selecting the source URL in order to pick a more fitting resource
  // And update the image's intrinsic dimensions when the viewport changes.
  // Picking of a better fitting resource is UA dependant, not spec required.
  SelectSourceURL(ImageLoader::kUpdateSizeChanged);
}

HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document) {
  HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
  image->element_created_by_parser_ = false;
  return image;
}

HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
                                                           unsigned width) {
  HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
  image->setWidth(width);
  image->element_created_by_parser_ = false;
  return image;
}

HTMLImageElement* HTMLImageElement::CreateForJSConstructor(Document& document,
                                                           unsigned width,
                                                           unsigned height) {
  HTMLImageElement* image = MakeGarbageCollected<HTMLImageElement>(document);
  image->setWidth(width);
  image->setHeight(height);
  image->element_created_by_parser_ = false;
  return image;
}

bool HTMLImageElement::IsPresentationAttribute(
    const QualifiedName& name) const {
  if (name == html_names::kWidthAttr || name == html_names::kHeightAttr ||
      name == html_names::kBorderAttr || name == html_names::kVspaceAttr ||
      name == html_names::kHspaceAttr || name == html_names::kAlignAttr ||
      name == html_names::kValignAttr)
    return true;
  return HTMLElement::IsPresentationAttribute(name);
}

void HTMLImageElement::CollectStyleForPresentationAttribute(
    const QualifiedName& name,
    const AtomicString& value,
    MutableCSSPropertyValueSet* style) {
  if (name == html_names::kWidthAttr) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kWidth, value);
    if (FastHasAttribute(html_names::kHeightAttr)) {
      const AtomicString& height = FastGetAttribute(html_names::kHeightAttr);
      ApplyAspectRatioToStyle(value, height, style);
    }
  } else if (name == html_names::kHeightAttr) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kHeight, value);
    if (FastHasAttribute(html_names::kWidthAttr)) {
      const AtomicString& width = FastGetAttribute(html_names::kWidthAttr);
      ApplyAspectRatioToStyle(width, value, style);
    }
  } else if (name == html_names::kBorderAttr) {
    ApplyBorderAttributeToStyle(value, style);
  } else if (name == html_names::kVspaceAttr) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kMarginTop, value);
    AddHTMLLengthToStyle(style, CSSPropertyID::kMarginBottom, value);
  } else if (name == html_names::kHspaceAttr) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kMarginLeft, value);
    AddHTMLLengthToStyle(style, CSSPropertyID::kMarginRight, value);
  } else if (name == html_names::kAlignAttr) {
    ApplyAlignmentAttributeToStyle(value, style);
  } else if (name == html_names::kValignAttr) {
    AddPropertyToPresentationAttributeStyle(
        style, CSSPropertyID::kVerticalAlign, value);
  } else {
    HTMLElement::CollectStyleForPresentationAttribute(name, value, style);
  }
}

void HTMLImageElement::CollectExtraStyleForPresentationAttribute(
    MutableCSSPropertyValueSet* style) {
  if (!source_)
    return;

  const AtomicString& width = source_->FastGetAttribute(html_names::kWidthAttr);
  const AtomicString& height =
      source_->FastGetAttribute(html_names::kHeightAttr);
  if (!width && !height)
    return;

  if (width) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kWidth, width);
  } else {
    AddPropertyToPresentationAttributeStyle(style, CSSPropertyID::kWidth,
                                            CSSValueID::kAuto);
  }

  if (height) {
    AddHTMLLengthToStyle(style, CSSPropertyID::kHeight, height);
  } else {
    AddPropertyToPresentationAttributeStyle(style, CSSPropertyID::kHeight,
                                            CSSValueID::kAuto);
  }

  if (width && height) {
    ApplyAspectRatioToStyle(width, height, style);
  } else {
    AddPropertyToPresentationAttributeStyle(style, CSSPropertyID::kAspectRatio,
                                            CSSValueID::kAuto);
  }
}

const AtomicString HTMLImageElement::ImageSourceURL() const {
  return best_fit_image_url_.IsNull() ? FastGetAttribute(html_names::kSrcAttr)
                                      : best_fit_image_url_;
}

HTMLFormElement* HTMLImageElement::formOwner() const {
  return form_.Get();
}

void HTMLImageElement::FormRemovedFromTree(const Node& form_root) {
  DCHECK(form_);
  if (NodeTraversal::HighestAncestorOrSelf(*this) != form_root)
    ResetFormOwner();
}

void HTMLImageElement::ResetFormOwner() {
  form_was_set_by_parser_ = false;
  HTMLFormElement* nearest_form = FindFormAncestor();
  if (form_) {
    if (nearest_form == form_.Get())
      return;
    form_->Disassociate(*this);
  }
  if (nearest_form) {
    form_ = nearest_form;
    form_->Associate(*this);
  } else {
    form_ = nullptr;
  }
}

void HTMLImageElement::SetBestFitURLAndDPRFromImageCandidate(
    const ImageCandidate& candidate) {
  best_fit_image_url_ = candidate.Url();
  float candidate_density = candidate.Density();
  float old_image_device_pixel_ratio = image_device_pixel_ratio_;
  if (candidate_density >= 0)
    image_device_pixel_ratio_ = 1.0 / candidate_density;

  bool intrinsic_sizing_viewport_dependant = false;
  if (candidate.GetResourceWidth() > 0) {
    intrinsic_sizing_viewport_dependant = true;
    UseCounter::Count(GetDocument(), WebFeature::kSrcsetWDescriptor);
  } else if (!candidate.SrcOrigin()) {
    UseCounter::Count(GetDocument(), WebFeature::kSrcsetXDescriptor);
  }
  if (auto* layout_image = DynamicTo<LayoutImage>(GetLayoutObject())) {
    layout_image->SetImageDevicePixelRatio(image_device_pixel_ratio_);

    if (old_image_device_pixel_ratio != image_device_pixel_ratio_)
      layout_image->IntrinsicSizeChanged();
  }

  if (intrinsic_sizing_viewport_dependant) {
    if (!listener_)
      listener_ = MakeGarbageCollected<ViewportChangeListener>(this);

    GetDocument().GetMediaQueryMatcher().AddViewportListener(listener_);
    // If we have a listener, that means a viewport dependent image
  } else if (listener_) {
    GetDocument().GetMediaQueryMatcher().RemoveViewportListener(listener_);
  }
}

void HTMLImageElement::ParseAttribute(
    const AttributeModificationParams& params) {
  const QualifiedName& name = params.name;
  if (name == html_names::kAltAttr || name == html_names::kTitleAttr) {
    if (UserAgentShadowRoot()) {
      Element* text = UserAgentShadowRoot()->getElementById("alttext");
      String alt_text_content = AltText();
      if (text && text->textContent() != alt_text_content)
        text->setTextContent(alt_text_content);
    }
  } else if (name == html_names::kSrcAttr || name == html_names::kSrcsetAttr ||
             name == html_names::kSizesAttr) {
    SelectSourceURL(ImageLoader::kUpdateIgnorePreviousError);
  } else if (name == html_names::kUsemapAttr) {
    SetIsLink(!params.new_value.IsNull());
  } else if (name == html_names::kReferrerpolicyAttr) {
    network::mojom::ReferrerPolicy old_referrer_policy = referrer_policy_;
    referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
    if (!params.new_value.IsNull()) {
      UseCounter::Count(GetDocument(),
                        WebFeature::kHTMLImageElementReferrerPolicyAttribute);

      SecurityPolicy::ReferrerPolicyFromString(
          params.new_value, kSupportReferrerPolicyLegacyKeywords,
          &referrer_policy_);
    }

    if (referrer_policy_ != old_referrer_policy) {
      GetImageLoader().UpdateFromElement(
          ImageLoader::kUpdateIgnorePreviousError, referrer_policy_);
    }
  } else if (name == html_names::kDecodingAttr) {
    UseCounter::Count(GetDocument(), WebFeature::kImageDecodingAttribute);
    decoding_mode_ = ParseImageDecodingMode(params.new_value);
  } else if (name == html_names::kLoadingAttr) {
    LoadingAttributeValue loading = GetLoadingAttributeValue(params.new_value);
    if (loading == LoadingAttributeValue::kEager ||
        (loading == LoadingAttributeValue::kAuto)) {
      GetImageLoader().LoadDeferredImage(referrer_policy_);
    } else {
      is_lazy_loaded_ = true;
    }
  } else if (name == html_names::kFetchpriorityAttr &&
             RuntimeEnabledFeatures::PriorityHintsEnabled(
                 GetExecutionContext())) {
    // We only need to keep track of usage here, as the communication of the
    // |fetchPriority| attribute to the loading pipeline takes place in
    // ImageLoader.
    UseCounter::Count(GetDocument(), WebFeature::kPriorityHints);
  } else if (name == html_names::kCrossoriginAttr) {
    // As per an image's relevant mutations [1], we must queue a new loading
    // microtask when the `crossorigin` attribute state has changed. Note that
    // the attribute value can change without the attribute state changing [2].
    //
    // [1]:
    // https://html.spec.whatwg.org/multipage/images.html#relevant-mutations
    // [2]: https://github.com/whatwg/html/issues/4533#issuecomment-483417499
    CrossOriginAttributeValue new_crossorigin_state =
        GetCrossOriginAttributeValue(params.new_value);
    CrossOriginAttributeValue old_crossorigin_state =
        GetCrossOriginAttributeValue(params.old_value);

    if (new_crossorigin_state != old_crossorigin_state) {
      // Update the current state so we can detect future state changes.
      GetImageLoader().UpdateFromElement(
          ImageLoader::kUpdateIgnorePreviousError, referrer_policy_);
    }
  } else if (name == html_names::kAttributionsrcAttr) {
    LocalDOMWindow* window = GetDocument().domWindow();
    if (!params.new_value.IsEmpty() && window && window->GetFrame()) {
      window->GetFrame()->GetAttributionSrcLoader()->Register(
          GetDocument().CompleteURL(params.new_value), this);
    }
  } else {
    HTMLElement::ParseAttribute(params);
  }
  if (has_sizes_attribute_ && is_lazy_loaded_ && listener_) {
    UseCounter::Count(
        GetDocument(),
        WebFeature::kViewportDependentLazyLoadedImageWithSizesAttribute);
  }
}

String HTMLImageElement::AltText() const {
  // lets figure out the alt text.. magic stuff
  // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
  // also heavily discussed by Hixie on bugzilla
  const AtomicString& alt = FastGetAttribute(html_names::kAltAttr);
  if (!alt.IsNull())
    return alt;
  // fall back to title attribute
  return FastGetAttribute(html_names::kTitleAttr);
}

void HTMLImageElement::InvalidateAttributeMapping() {
  EnsureUniqueElementData().SetPresentationAttributeStyleIsDirty(true);
  SetNeedsStyleRecalc(kLocalStyleChange,
                      StyleChangeReasonForTracing::Create(
                          style_change_reason::kPictureSourceChanged));
}

bool HTMLImageElement::SupportedImageType(
    const String& type,
    const HashSet<String>* disabled_image_types) {
  String trimmed_type = ContentType(type).GetType();
  // An empty type attribute is implicitly supported.
  if (trimmed_type.IsEmpty())
    return true;
  if (disabled_image_types && disabled_image_types->Contains(trimmed_type)) {
    return false;
  }
  return MIMETypeRegistry::IsSupportedImagePrefixedMIMEType(trimmed_type);
}

// http://picture.responsiveimages.org/#update-source-set
ImageCandidate HTMLImageElement::FindBestFitImageFromPictureParent() {
  DCHECK(IsMainThread());
  source_ = nullptr;
  auto* picture_parent = DynamicTo<HTMLPictureElement>(parentNode());
  if (!picture_parent)
    return ImageCandidate();
  HashSet<String> disabled_image_types;
  probe::GetDisabledImageTypes(GetExecutionContext(), &disabled_image_types);
  for (Node* child = picture_parent->firstChild(); child;
       child = child->nextSibling()) {
    if (child == this)
      return ImageCandidate();

    auto* source = DynamicTo<HTMLSourceElement>(child);
    if (!source)
      continue;

    if (!source->FastGetAttribute(html_names::kSrcAttr).IsNull()) {
      Deprecation::CountDeprecation(GetExecutionContext(),
                                    WebFeature::kPictureSourceSrc);
    }
    String srcset = source->FastGetAttribute(html_names::kSrcsetAttr);
    if (srcset.IsEmpty())
      continue;
    String type = source->FastGetAttribute(html_names::kTypeAttr);
    if (!SupportedImageType(type, &disabled_image_types))
      continue;

    if (!source->MediaQueryMatches())
      continue;

    ImageCandidate candidate = BestFitSourceForSrcsetAttribute(
        GetDocument().DevicePixelRatio(), SourceSize(*source),
        source->FastGetAttribute(html_names::kSrcsetAttr), &GetDocument());
    if (candidate.IsEmpty())
      continue;
    source_ = source;
    return candidate;
  }
  return ImageCandidate();
}

LayoutObject* HTMLImageElement::CreateLayoutObject(const ComputedStyle& style,
                                                   LegacyLayout legacy) {
  const ContentData* content_data = style.GetContentData();
  if (content_data && content_data->IsImage()) {
    const StyleImage* content_image =
        To<ImageContentData>(content_data)->GetImage();
    bool error_occurred = content_image && content_image->CachedImage() &&
                          content_image->CachedImage()->ErrorOccurred();
    if (!error_occurred)
      return LayoutObject::CreateObject(this, style, legacy);
  }

  switch (layout_disposition_) {
    case LayoutDisposition::kFallbackContent:
      return LayoutObjectFactory::CreateBlockFlow(*this, style, legacy);
    case LayoutDisposition::kPrimaryContent: {
      LayoutImage* image = MakeGarbageCollected<LayoutImage>(this);
      image->SetImageResource(MakeGarbageCollected<LayoutImageResource>());
      image->SetImageDevicePixelRatio(image_device_pixel_ratio_);
      return image;
    }
    case LayoutDisposition::kCollapsed:  // Falls through.
    default:
      NOTREACHED();
      return nullptr;
  }
}

void HTMLImageElement::AttachLayoutTree(AttachContext& context) {
  HTMLElement::AttachLayoutTree(context);
  if (auto* layout_image = DynamicTo<LayoutImage>(GetLayoutObject())) {
    LayoutImageResource* layout_image_resource = layout_image->ImageResource();
    if (is_fallback_image_)
      layout_image_resource->UseBrokenImage();

    if (layout_image_resource->HasImage())
      return;

    if (!GetImageLoader().GetContent() && !layout_image_resource->CachedImage())
      return;
    layout_image_resource->SetImageResource(GetImageLoader().GetContent());
  }
}

Node::InsertionNotificationRequest HTMLImageElement::InsertedInto(
    ContainerNode& insertion_point) {
  if (!form_was_set_by_parser_ ||
      NodeTraversal::HighestAncestorOrSelf(insertion_point) !=
          NodeTraversal::HighestAncestorOrSelf(*form_.Get()))
    ResetFormOwner();
  if (listener_)
    GetDocument().GetMediaQueryMatcher().AddViewportListener(listener_);
  bool was_added_to_picture_parent = false;
  if (auto* picture_parent = DynamicTo<HTMLPictureElement>(parentNode())) {
    picture_parent->AddListenerToSourceChildren();
    was_added_to_picture_parent = picture_parent == insertion_point;
  }

  bool image_was_modified = false;
  if (GetDocument().IsActive() && was_added_to_picture_parent) {
    ImageCandidate candidate = FindBestFitImageFromPictureParent();
    if (!candidate.IsEmpty()) {
      InvalidateAttributeMapping();
      SetBestFitURLAndDPRFromImageCandidate(candidate);
      image_was_modified = true;
    }
  }

  if (image_was_modified || GetImageLoader().ShouldUpdateOnInsertedInto(
                                insertion_point, referrer_policy_)) {
    GetImageLoader().UpdateFromElement(ImageLoader::kUpdateNormal,
                                       referrer_policy_);
  }
  return HTMLElement::InsertedInto(insertion_point);
}

void HTMLImageElement::RemovedFrom(ContainerNode& insertion_point) {
  InvalidateAttributeMapping();
  if (!form_ || NodeTraversal::HighestAncestorOrSelf(*form_.Get()) !=
                    NodeTraversal::HighestAncestorOrSelf(*this))
    ResetFormOwner();
  if (listener_) {
    GetDocument().GetMediaQueryMatcher().RemoveViewportListener(listener_);
    if (auto* picture_parent = DynamicTo<HTMLPictureElement>(parentNode()))
      picture_parent->RemoveListenerFromSourceChildren();
  }
  HTMLElement::RemovedFrom(insertion_point);
}

unsigned HTMLImageElement::width() {
  if (InActiveDocument()) {
    GetDocument().UpdateStyleAndLayoutForNode(
        this, DocumentUpdateReason::kJavaScript);
  }

  if (!GetLayoutObject()) {
    // check the attribute first for an explicit pixel value
    // TODO(cbiesinger): The attribute could be a float or percentage value...
    unsigned width = 0;
    if (ParseHTMLNonNegativeInteger(FastGetAttribute(html_names::kWidthAttr),
                                    width))
      return width;

    // if the image is available, use its width
    if (ImageResourceContent* image_content = GetImageLoader().GetContent()) {
      return image_content->IntrinsicSize(kRespectImageOrientation).width();
    }
  }

  return LayoutBoxWidth();
}

unsigned HTMLImageElement::height() {
  if (InActiveDocument()) {
    GetDocument().UpdateStyleAndLayoutForNode(
        this, DocumentUpdateReason::kJavaScript);
  }

  if (!GetLayoutObject()) {
    // check the attribute first for an explicit pixel value
    // TODO(cbiesinger): The attribute could be a float or percentage value...
    unsigned height = 0;
    if (ParseHTMLNonNegativeInteger(FastGetAttribute(html_names::kHeightAttr),
                                    height))
      return height;

    // if the image is available, use its height
    if (ImageResourceContent* image_content = GetImageLoader().GetContent()) {
      return image_content->IntrinsicSize(kRespectImageOrientation).height();
    }
  }

  return LayoutBoxHeight();
}

LayoutSize HTMLImageElement::DensityCorrectedIntrinsicDimensions() const {
  if (IsDefaultIntrinsicSize()) {
    return LayoutSize(LayoutReplaced::kDefaultWidth,
                      LayoutReplaced::kDefaultHeight);
  }
  ImageResourceContent* image_content = GetImageLoader().GetContent();
  if (!image_content || !image_content->HasImage())
    return LayoutSize();

  float pixel_density = image_device_pixel_ratio_;
  if (image_content->HasDevicePixelRatioHeaderValue() &&
      image_content->DevicePixelRatioHeaderValue() > 0)
    pixel_density = 1 / image_content->DevicePixelRatioHeaderValue();

  RespectImageOrientationEnum respect_image_orientation =
      LayoutObject::ShouldRespectImageOrientation(GetLayoutObject());

  LayoutSize natural_size(
      image_content->IntrinsicSize(respect_image_orientation));
  natural_size.Scale(pixel_density);
  return natural_size;
}

unsigned HTMLImageElement::naturalWidth() const {
  return DensityCorrectedIntrinsicDimensions().Width().ToUnsigned();
}

unsigned HTMLImageElement::naturalHeight() const {
  return DensityCorrectedIntrinsicDimensions().Height().ToUnsigned();
}

unsigned HTMLImageElement::LayoutBoxWidth() const {
  LayoutBox* box = GetLayoutBox();
  return box ? AdjustForAbsoluteZoom::AdjustLayoutUnit(box->ContentWidth(),
                                                       *box)
                   .Round()
             : 0;
}

unsigned HTMLImageElement::LayoutBoxHeight() const {
  LayoutBox* box = GetLayoutBox();
  return box ? AdjustForAbsoluteZoom::AdjustLayoutUnit(box->ContentHeight(),
                                                       *box)
                   .Round()
             : 0;
}

const String& HTMLImageElement::currentSrc() const {
  // http://www.whatwg.org/specs/web-apps/current-work/multipage/edits.html#dom-img-currentsrc
  // The currentSrc IDL attribute must return the img element's current
  // request's current URL.

  // Return the picked URL string in case of load error.
  if (GetImageLoader().HadError())
    return best_fit_image_url_;
  // Initially, the pending request turns into current request when it is
  // either available or broken. Check for the resource being in error or
  // having an image to determine these states.
  ImageResourceContent* image_content = GetImageLoader().GetContent();
  if (!image_content ||
      (!image_content->ErrorOccurred() && !image_content->HasImage()))
    return g_empty_atom;

  return image_content->Url().GetString();
}

bool HTMLImageElement::IsURLAttribute(const Attribute& attribute) const {
  return attribute.GetName() == html_names::kSrcAttr ||
         attribute.GetName() == html_names::kLowsrcAttr ||
         attribute.GetName() == html_names::kLongdescAttr ||
         (attribute.GetName() == html_names::kUsemapAttr &&
          attribute.Value()[0] != '#') ||
         HTMLElement::IsURLAttribute(attribute);
}

bool HTMLImageElement::HasLegalLinkAttribute(const QualifiedName& name) const {
  return name == html_names::kSrcAttr ||
         HTMLElement::HasLegalLinkAttribute(name);
}

const QualifiedName& HTMLImageElement::SubResourceAttributeName() const {
  return html_names::kSrcAttr;
}

bool HTMLImageElement::draggable() const {
  // Image elements are draggable by default.
  return !EqualIgnoringASCIICase(FastGetAttribute(html_names::kDraggableAttr),
                                 "false");
}

void HTMLImageElement::setHeight(unsigned value) {
  SetUnsignedIntegralAttribute(html_names::kHeightAttr, value);
}

void HTMLImageElement::setWidth(unsigned value) {
  SetUnsignedIntegralAttribute(html_names::kWidthAttr, value);
}

int HTMLImageElement::x() const {
  GetDocument().UpdateStyleAndLayoutForNode(this,
                                            DocumentUpdateReason::kJavaScript);
  LayoutObject* r = GetLayoutObject();
  if (!r)
    return 0;

  // FIXME: This doesn't work correctly with transforms.
  PhysicalOffset abs_pos =
      r->LocalToAbsolutePoint(PhysicalOffset(), kIgnoreTransforms);
  return abs_pos.left.ToInt();
}

int HTMLImageElement::y() const {
  GetDocument().UpdateStyleAndLayoutForNode(this,
                                            DocumentUpdateReason::kJavaScript);
  LayoutObject* r = GetLayoutObject();
  if (!r)
    return 0;

  // FIXME: This doesn't work correctly with transforms.
  PhysicalOffset abs_pos =
      r->LocalToAbsolutePoint(PhysicalOffset(), kIgnoreTransforms);
  return abs_pos.top.ToInt();
}

ScriptPromise HTMLImageElement::decode(ScriptState* script_state,
                                       ExceptionState& exception_state) {
  return GetImageLoader().Decode(script_state, exception_state);
}

bool HTMLImageElement::complete() const {
  return GetImageLoader().ImageComplete();
}

void HTMLImageElement::DidMoveToNewDocument(Document& old_document) {
  GetImageLoader().ElementDidMoveToNewDocument();
  HTMLElement::DidMoveToNewDocument(old_document);
  SelectSourceURL(ImageLoader::kUpdateIgnorePreviousError);
}

bool HTMLImageElement::IsServerMap() const {
  if (!FastHasAttribute(html_names::kIsmapAttr))
    return false;

  const AtomicString& usemap = FastGetAttribute(html_names::kUsemapAttr);

  // If the usemap attribute starts with '#', it refers to a map element in
  // the document.
  if (usemap[0] == '#')
    return false;

  return GetDocument()
      .CompleteURL(StripLeadingAndTrailingHTMLSpaces(usemap))
      .IsEmpty();
}

Image* HTMLImageElement::ImageContents() {
  if (!GetImageLoader().ImageComplete() || !GetImageLoader().GetContent())
    return nullptr;

  return GetImageLoader().GetContent()->GetImage();
}

bool HTMLImageElement::IsInteractiveContent() const {
  return FastHasAttribute(html_names::kUsemapAttr);
}

gfx::SizeF HTMLImageElement::DefaultDestinationSize(
    const gfx::SizeF& default_object_size,
    const RespectImageOrientationEnum respect_orientation) const {
  ImageResourceContent* image_content = CachedImage();
  if (!image_content || !image_content->HasImage())
    return gfx::SizeF();

  Image* image = image_content->GetImage();
  if (auto* svg_image = DynamicTo<SVGImage>(image))
    return svg_image->ConcreteObjectSize(default_object_size);

  LayoutSize size(image->Size(respect_orientation));
  if (GetLayoutObject() && GetLayoutObject()->IsLayoutImage() &&
      image->HasIntrinsicSize())
    size.Scale(To<LayoutImage>(GetLayoutObject())->ImageDevicePixelRatio());
  return gfx::SizeF(size);
}

static bool SourceSizeValue(const Element* element,
                            Document& current_document,
                            float& source_size) {
  String sizes = element->FastGetAttribute(html_names::kSizesAttr);
  bool exists = !sizes.IsNull();
  if (exists)
    UseCounter::Count(current_document, WebFeature::kSizes);
  source_size =
      SizesAttributeParser(MediaValuesDynamic::Create(current_document), sizes,
                           current_document.GetExecutionContext())
          .length();
  return exists;
}

FetchParameters::ResourceWidth HTMLImageElement::GetResourceWidth() const {
  FetchParameters::ResourceWidth resource_width;
  Element* element = source_.Get();
  resource_width.is_set = SourceSizeValue(element ? element : this,
                                          GetDocument(), resource_width.width);
  return resource_width;
}

float HTMLImageElement::SourceSize(Element& element) {
  float value;
  // We only care if the sizes attribute exist here for use counter purposes..
  has_sizes_attribute_ = SourceSizeValue(&element, GetDocument(), value);
  return value;
}

void HTMLImageElement::ForceReload() const {
  GetImageLoader().UpdateFromElement(ImageLoader::kUpdateForcedReload,
                                     referrer_policy_);
}

void HTMLImageElement::SelectSourceURL(
    ImageLoader::UpdateFromElementBehavior behavior) {
  if (!GetDocument().IsActive())
    return;

  is_changed_shortly_after_mouseover_ =
      PaintTiming::From(GetDocument()).IsLCPMouseoverDispatchedRecently();
  HTMLSourceElement* old_source = source_;
  ImageCandidate candidate = FindBestFitImageFromPictureParent();
  if (candidate.IsEmpty()) {
    candidate = BestFitSourceForImageAttributes(
        GetDocument().DevicePixelRatio(), SourceSize(*this),
        FastGetAttribute(html_names::kSrcAttr),
        FastGetAttribute(html_names::kSrcsetAttr), &GetDocument());
  }
  if (old_source != source_)
    InvalidateAttributeMapping();
  AtomicString old_url = best_fit_image_url_;
  SetBestFitURLAndDPRFromImageCandidate(candidate);

  // Step 5 in
  // https://html.spec.whatwg.org/multipage/images.html#reacting-to-environment-changes
  // Deliberately not compliant and avoiding checking image density, to avoid
  // spurious downloads. See https://github.com/whatwg/html/issues/4646
  if (behavior != HTMLImageLoader::kUpdateSizeChanged ||
      best_fit_image_url_ != old_url) {
    GetImageLoader().UpdateFromElement(behavior, referrer_policy_);
  }

  if (GetImageLoader().ImageIsPotentiallyAvailable())
    EnsurePrimaryContent();
  else
    EnsureCollapsedOrFallbackContent();
}

void HTMLImageElement::StartLoadingImageDocument(
    ImageResourceContent* image_content) {
  // This element is being used to load an image in an ImageDocument. The
  // provided ImageResource is owned/managed by the ImageDocumentParser. Set it
  // on our ImageLoader and then update the 'src' attribute to reflect the URL
  // of the image. This latter step will also initiate the load from the
  // ImageLoader's PoV.
  GetImageLoader().SetImageDocumentContent(image_content);
  setAttribute(html_names::kSrcAttr, AtomicString(image_content->Url()));
}

void HTMLImageElement::DidAddUserAgentShadowRoot(ShadowRoot&) {
  HTMLImageFallbackHelper::CreateAltTextShadowTree(*this);
}

void HTMLImageElement::EnsureFallbackForGeneratedContent() {
  // The special casing for generated content in CreateLayoutObject breaks the
  // invariant that the layout object attached to this element will always be
  // appropriate for |layout_disposition_|. Force recreate it.
  // TODO(engedy): Remove this hack. See: https://crbug.com/671953.
  SetLayoutDisposition(LayoutDisposition::kFallbackContent,
                       true /* force_reattach */);
}

void HTMLImageElement::EnsureCollapsedOrFallbackContent() {
  if (is_fallback_image_)
    return;

  ImageResourceContent* image_content = GetImageLoader().GetContent();
  absl::optional<ResourceError> error =
      image_content ? image_content->GetResourceError() : absl::nullopt;
  SetLayoutDisposition(error && error->ShouldCollapseInitiator()
                           ? LayoutDisposition::kCollapsed
                           : LayoutDisposition::kFallbackContent);
}

void HTMLImageElement::EnsurePrimaryContent() {
  SetLayoutDisposition(LayoutDisposition::kPrimaryContent);
}

bool HTMLImageElement::IsCollapsed() const {
  return layout_disposition_ == LayoutDisposition::kCollapsed;
}

void HTMLImageElement::SetLayoutDisposition(
    LayoutDisposition layout_disposition,
    bool force_reattach) {
  if (layout_disposition_ == layout_disposition && !force_reattach)
    return;

  DCHECK(!GetDocument().InStyleRecalc());

  layout_disposition_ = layout_disposition;

  if (layout_disposition_ == LayoutDisposition::kFallbackContent) {
    EventDispatchForbiddenScope::AllowUserAgentEvents allow_events;
    EnsureUserAgentShadowRoot();
  }

  // ComputedStyle depends on layout_disposition_. Trigger recalc.
  SetNeedsStyleRecalc(
      kLocalStyleChange,
      StyleChangeReasonForTracing::Create(style_change_reason::kUseFallback));
  // LayoutObject type depends on layout_disposition_. Trigger re-attach.
  SetForceReattachLayoutTree();
}

scoped_refptr<ComputedStyle> HTMLImageElement::CustomStyleForLayoutObject(
    const StyleRecalcContext& style_recalc_context) {
  switch (layout_disposition_) {
    case LayoutDisposition::kPrimaryContent:  // Fall through.
    case LayoutDisposition::kCollapsed:
      return OriginalStyleForLayoutObject(style_recalc_context);
    case LayoutDisposition::kFallbackContent: {
      scoped_refptr<ComputedStyle> style =
          OriginalStyleForLayoutObject(style_recalc_context);
      HTMLImageFallbackHelper::CustomStyleForAltText(*this, *style);
      return style;
    }
    default:
      NOTREACHED();
      return nullptr;
  }
}

void HTMLImageElement::AssociateWith(HTMLFormElement* form) {
  if (form && form->isConnected()) {
    form_ = form;
    form_was_set_by_parser_ = true;
    form_->Associate(*this);
    form_->DidAssociateByParser();
  }
}

// Minimum height or width of the image to start lazyloading.
constexpr int kMinDimensionToLazyLoad = 10;

HTMLImageElement::LazyLoadDimensionType
HTMLImageElement::GetAttributeLazyLoadDimensionType(
    const String& attribute_value) {
  HTMLDimension dimension;
  if (ParseDimensionValue(attribute_value, dimension) &&
      dimension.IsAbsolute()) {
    return dimension.Value() <= kMinDimensionToLazyLoad
               ? LazyLoadDimensionType::kAbsoluteSmall
               : LazyLoadDimensionType::kAbsoluteNotSmall;
  }
  return LazyLoadDimensionType::kNotAbsolute;
}

HTMLImageElement::LazyLoadDimensionType
HTMLImageElement::GetInlineStyleDimensionsType(
    const CSSPropertyValueSet* property_set) {
  if (!property_set)
    return LazyLoadDimensionType::kNotAbsolute;
  const CSSValue* height =
      property_set->GetPropertyCSSValue(CSSPropertyID::kHeight);
  const CSSValue* width =
      property_set->GetPropertyCSSValue(CSSPropertyID::kWidth);
  const auto* width_prim = DynamicTo<CSSPrimitiveValue>(width);
  const auto* height_prim = DynamicTo<CSSPrimitiveValue>(height);
  if (!width_prim || !height_prim || !width_prim->IsPx() ||
      !height_prim->IsPx()) {
    return LazyLoadDimensionType::kNotAbsolute;
  }
  return (height_prim->GetDoubleValue() <= kMinDimensionToLazyLoad) &&
                 (width_prim->GetDoubleValue() <= kMinDimensionToLazyLoad)
             ? LazyLoadDimensionType::kAbsoluteSmall
             : LazyLoadDimensionType::kAbsoluteNotSmall;
}

}  // namespace blink


text:
    /* Graph JavaScript framework, version 0.0.1
     * (c) 2006 Aslak Hellesoy <aslak.hellesoy@gmail.com>
     * (c) 2006 Dave Hoover <dave.hoover@gmail.com>
     *
     * Ported from Graph::Layouter::Spring in
     * http://search.cpan.org/~pasky/Graph-Layderer-0.02/
     * The algorithm is based on a spring-style layouter of a Java-based social
     * network tracker PieSpy written by Paul Mutton E<lt>paul@jibble.orgE<gt>.
     *
     * Graph is freely distributable under the terms of an MIT-style license.
     * For details, see the Graph web site: http://dev.buildpatternd.com/trac
     *
    /*--------------------------------------------------------------------------*/

    var Graph = Class.create();
    Graph.prototype = {
    initialize: function() {
    this.nodeSet = {};
    this.nodes = [];
    this.edges = [];
    },

    addNode: function(value) {
    if(typeof value == 'string') {
    // Create a new div
    var key = value;
    var element = document.createElement('div');
    element.innerHTML = value;
    // THIS DOESN'T WORK!! NEED AN OTHER CONTAINER.
    document.appendChild(element);
    } else {
    // Assuming it's a DOM node *with* and id.
    var key = value.id;
    var element = value;
    }

    var node = this.nodeSet[key];
    if(node == undefined) {
    node = new Graph.Node(element);
    this.nodeSet[key] = node;
    this.nodes.push(node);
    }
    return node;
    },

    // Uniqueness must be ensured by caller
    addEdge: function(source, target) {
    var s = this.addNode(source);
    var t = this.addNode(target);
    var edge = {source: s, target: t};
    this.edges.push(edge);
    }
    };

    Graph.Node = Class.create();
    Graph.Node.prototype = {
    initialize: function(value) {
    this.value = value;
    }
    };

    Graph.Renderer = {};
    Graph.Renderer.Basic = Class.create();
    Graph.Renderer.Basic.prototype = {
    initialize: function(element, graph) {
    this.element = element;
    this.graph = graph;

    this.ctx = element.getContext("2d");
    this.radius = 20;
    this.arrowAngle = Math.PI/10;

    this.factorX = (element.width - 2 * this.radius) / (graph.layoutMaxX - graph.layoutMinX);
    this.factorY = (element.height - 2 * this.radius) / (graph.layoutMaxY - graph.layoutMinY);
    },

    translate: function(point) {
    return [
    (point[0] - this.graph.layoutMinX) * this.factorX + this.radius,
    (point[1] - this.graph.layoutMinY) * this.factorY + this.radius
    ];
    },

    rotate: function(point, length, angle) {
    var dx = length * Math.cos(angle);
    var dy = length * Math.sin(angle);
    return [point[0]+dx, point[1]+dy];
    },

    draw: function() {
    for (var i = 0; i < this.graph.nodes.length; i++) {
    this.drawNode(this.graph.nodes[i]);
    }
    for (var i = 0; i < this.graph.edges.length; i++) {
    this.drawEdge(this.graph.edges[i]);
    }
    },

    drawNode: function(node) {
    var point = this.translate([node.layoutPosX, node.layoutPosY]);

    node.value.style.position = 'absolute';
    node.value.style.top = point[1] + 'px';
    node.value.style.left = point[0] + 'px';

    this.ctx.strokeStyle = 'black'
    this.ctx.beginPath();
    this.ctx.arc(point[0], point[1], this.radius, 0, Math.PI*2, true);
    this.ctx.closePath();
    this.ctx.stroke();
    },

    drawEdge: function(edge) {
    var source = this.translate([edge.source.layoutPosX, edge.source.layoutPosY]);
    var target = this.translate([edge.target.layoutPosX, edge.target.layoutPosY]);

    var tan = (target[1] - source[1]) / (target[0] - source[0]);
    var theta = Math.atan(tan);
    if(source[0] <= target[0]) {theta = Math.PI+theta}
    source = this.rotate(source, -this.radius, theta);
    target = this.rotate(target, this.radius, theta);

    // draw the edge
    this.ctx.strokeStyle = 'grey';
    this.ctx.fillStyle = 'grey';
    this.ctx.lineWidth = 1.0;
    this.ctx.beginPath();
    this.ctx.moveTo(source[0], source[1]);
    this.ctx.lineTo(target[0], target[1]);
    this.ctx.stroke();

    this.drawArrowHead(20, this.arrowAngle, theta, source[0], source[1], target[0], target[1]);
    },

    drawArrowHead: function(length, alpha, theta, startx, starty, endx, endy) {
    var top = this.rotate([endx, endy], length, theta + alpha);
    var bottom = this.rotate([endx, endy], length, theta - alpha);
    this.ctx.beginPath();
    this.ctx.moveTo(endx, endy);
    this.ctx.lineTo(top[0], top[1]);
    this.ctx.lineTo(bottom[0], bottom[1]);
    this.ctx.fill();
    }
    };

    Graph.Layout = {};
    Graph.Layout.Spring = Class.create();
    Graph.Layout.Spring.prototype = {
    initialize: function(graph) {
    this.graph = graph;
    this.iterations = 500;
    this.maxRepulsiveForceDistance = 6;
    this.k = 2;
    this.c = 0.01;
    this.maxVertexMovement = 0.5;
    },

    layout: function() {
    this.layoutPrepare();
    for (var i = 0; i < this.iterations; i++) {
    this.layoutIteration();
    }
    this.layoutCalcBounds();
    },

    layoutPrepare: function() {
    for (var i = 0; i < this.graph.nodes.length; i++) {
    var node = this.graph.nodes[i];
    node.layoutPosX = 0;
    node.layoutPosY = 0;
    node.layoutForceX = 0;
    node.layoutForceY = 0;
    }
    },

    layoutCalcBounds: function() {
    var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity;

    for (var i = 0; i < this.graph.nodes.length; i++) {
    var x = this.graph.nodes[i].layoutPosX;
    var y = this.graph.nodes[i].layoutPosY;

    if(x > maxx) maxx = x;
    if(x < minx) minx = x;
    if(y > maxy) maxy = y;
    if(y < miny) miny = y;
    }

    this.graph.layoutMinX = minx;
    this.graph.layoutMaxX = maxx;
    this.graph.layoutMinY = miny;
    this.graph.layoutMaxY = maxy;
    },

    layoutIteration: function() {
    // Forces on nodes due to node-node repulsions
    for (var i = 0; i < this.graph.nodes.length; i++) {
    var node1 = this.graph.nodes[i];
    for (var j = i + 1; j < this.graph.nodes.length; j++) {
    var node2 = this.graph.nodes[j];
    this.layoutRepulsive(node1, node2);
    }
    }
    // Forces on nodes due to edge attractions
    for (var i = 0; i < this.graph.edges.length; i++) {
    var edge = this.graph.edges[i];
    this.layoutAttractive(edge);
    }

    // Move by the given force
    for (var i = 0; i < this.graph.nodes.length; i++) {
    var node = this.graph.nodes[i];
    var xmove = this.c * node.layoutForceX;
    var ymove = this.c * node.layoutForceY;

    var max = this.maxVertexMovement;
    if(xmove > max) xmove = max;
    if(xmove < -max) xmove = -max;
    if(ymove > max) ymove = max;
    if(ymove < -max) ymove = -max;

    node.layoutPosX += xmove;
    node.layoutPosY += ymove;
    node.layoutForceX = 0;
    node.layoutForceY = 0;
    }
    },

    layoutRepulsive: function(node1, node2) {
    var dx = node2.layoutPosX - node1.layoutPosX;
    var dy = node2.layoutPosY - node1.layoutPosY;
    var d2 = dx * dx + dy * dy;
    if(d2 < 0.01) {
    dx = 0.1 * Math.random() + 0.1;
    dy = 0.1 * Math.random() + 0.1;
    var d2 = dx * dx + dy * dy;
    }
    var d = Math.sqrt(d2);
    if(d < this.maxRepulsiveForceDistance) {
    var repulsiveForce = this.k * this.k / d;
    node2.layoutForceX += repulsiveForce * dx / d;
    node2.layoutForceY += repulsiveForce * dy / d;
    node1.layoutForceX -= repulsiveForce * dx / d;
    node1.layoutForceY -= repulsiveForce * dy / d;
    }
    },

    layoutAttractive: function(edge) {
    var node1 = edge.source;
    var node2 = edge.target;

    var dx = node2.layoutPosX - node1.layoutPosX;
    var dy = node2.layoutPosY - node1.layoutPosY;
    var d2 = dx * dx + dy * dy;
    if(d2 < 0.01) {
    dx = 0.1 * Math.random() + 0.1;
    dy = 0.1 * Math.random() + 0.1;
    var d2 = dx * dx + dy * dy;
    }
    var d = Math.sqrt(d2);
    if(d > this.maxRepulsiveForceDistance) {
    d = this.maxRepulsiveForceDistance;
    d2 = d * d;
    }
    var attractiveForce = (d2 - this.k * this.k) / this.k;
    if(edge.weight == undefined || edge.weight < 1) edge.weight = 1;
    attractiveForce *= Math.log(edge.weight) * 0.5 + 1;

    node2.layoutForceX -= attractiveForce * dx / d;
    node2.layoutForceY -= attractiveForce * dy / d;
    node1.layoutForceX += attractiveForce * dx / d;
    node1.layoutForceY += attractiveForce * dy / d;
    }
    };


text:
/* !kawai! */

#ifndef GCC_TIMEVAR_H
#define GCC_TIMEVAR_H

struct timevar_time_def {
	int dummy;
};

typedef enum {
  TIMEVAR_LAST
} timevar_id_t;

#define init_timevar()			/* none */
#define timevar_push(timevar)	/* none */
#define timevar_pop(timevar)	/* none */
#define timevar_start(timevar)	/* none */
#define timevar_stop(timevar)	/* none */
#define timevar_get(timevar, elapsed)	/* none */
#define	timevar_print(fp) 		/* none */
#if (!defined(get_run_time))
	#define get_run_time()			0L
#endif
#define	print_time(str, total)	/* none */

#endif


text:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
fieldset {
 height: 20px;
 background-color: green;
 border: none;
 margin: 0;
 padding: 0;
}
#top {
 margin-bottom: 10px;
}
#middle {
 margin: 20px 0;
}
#bottom {
 margin-top: 10px;
}
</style>
</head>
<body>
<fieldset id="top"></fieldset>
<fieldset id="middle"></fieldset>
<fieldset id="bottom"></fieldset>
</body>
</html>


text:
require 'rbbt/resource/path'
module TSV

  def self.stream_column(file, column)
    header = TSV.parse_header(file)
    pos = header.fields.index(column) + 1
    sep2 = header.options[:sep2] || "|"
    case header.type.to_s
    when nil, "double"
      TSV.traverse file, :type => :array, :into => :stream do |line|
        next if line =~ /^#/
        line.split("\t")[pos].gsub(sep2, "\n")
      end
    when "single"
      TSV.traverse file, :type => :array, :into => :stream do |line|
        next if line =~ /^#/
        line.split("\t")[1]
      end
    when "flat"
      TSV.traverse file, :type => :array, :into => :stream do |line|
        next if line =~ /^#/
        line.split("\t")[1..-1] * "\n"
      end
    when 'list'
      TSV.traverse file, :type => :array, :into => :stream do |line|
        next if line =~ /^#/
        line.split("\t")[pos]
      end
    end
  end

  def self.guess_id(identifier_file, values, options = {})
    field_matches = TSV.field_match_counts(identifier_file, values, options)
    field_matches.sort_by{|field, count| count.to_i}.last
  end

  def self.field_match_counts(file, values, options = {})
    options = Misc.add_defaults options, :persist_prefix => "Field_Matches"
    persist_options = Misc.pull_keys options, :persist

    filename = TSV === file ? file.filename : file
    path = Persist.persist filename, :string, persist_options.merge(:no_load => true) do
      tsv = TSV === file ? file : TSV.open(file, options)

      text = ""
      fields = nil
      tsv.tap{|e| e.unnamed =  true; fields = e.fields}.through do |gene, names|
        names.zip(fields).each do |list, format|
          list = [list] unless Array === list
          list.delete_if do |name| name.empty? end
          next if list.empty?
          text << list.collect{|name| [name, format] * "\t"} * "\n" << "\n"
        end
        text << [gene, tsv.key_field] * "\t" << "\n"
      end
      text
    end

    TmpFile.with_file(values.uniq * "\n", false) do |value_file|
      cmd = "cat '#{ path }' | sed 's/\\t/\\tHEADERNOMATCH/' | grep -w -F -f '#{ value_file }' | sed 's/HEADERNOMATCH//' |sort -u|cut -f 2  |sort|uniq -c|sed 's/^ *//;s/ /\t/'"
      begin
        TSV.open(CMD.cmd(cmd), :key_field => 1, :fields => [0], :type => :single, :cast => :to_i)
      rescue
        Log.exception $!
        TSV.setup({}, :type => :single, :cast => :to_i)
      end
    end
  end

  def self.get_filename(file)
    case
    when (defined? Step and Step === file)
      file.path
    when Path === file
      file
    when (String === file and (Open.exists? file or Open.remote? file))
      file
    when String === file
      "String-#{Misc.digest file}"
    when file.respond_to?(:filename)
      file.filename
    when file.respond_to?(:gets)
      nil
    else
      raise "Cannot get filename from: #{file.inspect}"
    end
  end

  def self.abort_stream(file, exception = nil)
    return if file.nil?
    if defined? Step and Step === file
      if exception
        file.exception exception
      else
        if not (file.aborted? or file.done?)
          file.abort
        end
      end
    elsif Hash === file or Array === file
      return
    else
      stream = get_stream(file)
      stream.abort(exception) if stream.respond_to? :abort
      AbortedStream.setup(stream, exception) unless stream.respond_to?(:exception) && stream.exception
    end
  end

  def self.get_stream(file, open_options = {})
    case file
    when Zlib::GzipReader
      file
    when (defined? Bgzf and Bgzf)
      file
    when TSV
      file.dumper_stream
    when TSV::Dumper
      file.stream
    when TSV::Parser
      file.stream
    when Path
      file.open(open_options)
    when (defined? Tempfile and Tempfile)
      begin
        pos = file.pos
        file.rewind if file.respond_to?(:rewind) and pos != 0
      rescue Exception
      end
      file
    when IO, StringIO, File
      begin
        pos = file.pos
        file.rewind if file.respond_to?(:rewind) and pos != 0
      rescue
      end
      file
    when String
      if Open.remote?(file) || Open.ssh?(file) || Open.exist?(file)
        Open.open(file, open_options)
      else
        StringIO.new file
      end
    when (defined? Step and Step)
      if file.respond_to?(:base_url)
        if file.result and IO === file.result
          file.result
        else
          file.join
          get_stream(file.path, open_options.merge(:nocache => true))
        end
      else
        file.grace

        stream = file.get_stream
        if stream && ! stream.closed?
          stream
        else
          file.join
          raise "Aborted stream from Step #{file.path}" if file.aborted?
          raise "Exception in stream from Step #{file.path}: #{file.messages.last}" if file.error?
          get_stream(file.path, open_options)
        end
      end
    when Array
      Misc.open_pipe do |sin|
        file.each do |l|
          sin.puts l
        end
      end
    when Set
      get_stream(file.to_a, open_options)
    else
      raise "Cannot get stream from: #{file.inspect}"
    end
  end

  def self.identify_field(key_field, fields, field)
    case field
    when nil
      :key
    when Symbol
      field == :key ? field : identify_field(key_field, fields, field.to_s)
    when Integer
      field
    when (fields.nil? and String)
      raise "No field information available and specified field not numeric: #{ field }" unless field =~ /^\d+$/
      identify_field(key_field, fields, field.to_i)
    when String
      return :key if key_field == field
      pos = fields.index field
      return pos if pos
      return identify_field(key_field, fields, field.to_i) if field =~ /^\d+$/
      raise "Field '#{ field }' was not found. Options: (#{key_field || "NO_KEY_FIELD"}), #{(fields || ["NO_FIELDS"]) * ", "}" if pos.nil?
    else
      raise "Field '#{ field }' was not found. Options: (#{key_field || "NO_KEY_FIELD"}), #{(fields || ["NO_FIELDS"]) * ", "}"
    end
  end

  def self.header_lines(key_field, fields, entry_hash = nil)
    if Hash === entry_hash
      sep = entry_hash[:sep] ? entry_hash[:sep] : "\t"
      preamble = entry_hash[:preamble]
      header_hash = entry_hash[:header_hash]
    end

    header_hash = "#" if header_hash.nil?

    preamble = "#: " << Misc.hash2string(entry_hash.merge(:key_field => nil, :fields => nil)) << "\n" if preamble.nil? and entry_hash and entry_hash.values.compact.any?

    str = ""
    str << preamble.strip << "\n" if preamble and not preamble.empty?
    if fields
      if fields.empty?
        str << header_hash << (key_field || "ID").to_s << "\n"
      else
        str << header_hash << (key_field || "ID").to_s << sep << (fields * sep) << "\n"
      end
    end

    str
  end

  def identify_field(field)
    TSV.identify_field(key_field, fields, field)
  end

  def rename_field(field, new)
    self.fields = self.fields.collect{|f| f == field ? new : f }
    self
  end

  def unzip_replicates
    raise "Can only unzip replicates in :double TSVs" unless type == :double

    new = {}
    self.with_unnamed do
      through do |k,vs|
        Misc.zip_fields(vs).each_with_index do |v,i|
          new[k + "(#{i})"] = v
        end
      end
    end

    self.annotate(new)
    new.type = :list

    new
  end

  def to_list(&block)
    new = {}
    case type
    when :double
      if block_given?
        through do |k,v|
          if block.arity == 1
            new[k] = v.collect{|e| yield e}
          else
            new[k] = yield k, v
          end
        end
      else
        through do |k,v|
          new[k] = v.collect{|e| e.first}
        end
      end
    when :flat
      through do |k,v|
        new[k] = [v.first]
      end
    when :single
      through do |k,v|
        new[k] = [v]
      end
    when :list
      return self
    end
    self.annotate(new)
    new.type = :list
    new
  end

  def to_double
    new = {}
    case type
    when :double
      return self
    when :flat
      through do |k,v|
        new[k] = v.nil? ? [] : [v]
      end
    when :single
      through do |k,v|
        new[k] = v.nil? ? [[]] : [[v]]
      end
    when :list
      if block_given?
        through do |k,v|
          if v.nil?
            new[k] = nil
          else
            new[k] = v.collect{|e| yield e}
          end
        end
      else
        through do |k,v|
          if v.nil?
            new[k] = nil
          else
            new[k] = v.collect{|e| [e]}
          end
        end
      end
    end
    self.annotate(new)
    new.type = :double
    new
  end

  def to_flat(field = nil)
    new = {}
    case type
    when :double
      if field.nil?
        through do |k,v| new[k] = v.first end
      elsif field == :all
        through do |k,v| new[k] = v.flatten.compact end
      else
        pos = identify_field field
        through do |k,v| new[k] = v[pos] end
      end
    when :flat
      return self
    when :single
      through do |k,v|
        new[k] = [v]
      end
    when :list
      through do |k,v|
        new[k] = [v.first]
      end
    end
    self.annotate(new)
    if new.fields
      case field
      when nil
        new.fields = new.fields[0..0]
      when :all
        new.fields = [new.fields * "+"]
      else
        new.fields = [field]
      end
    end
    new.type = :flat
    new
  end

  def to_single
    new = {}

    if block_given?
      through do |k,v|
        new[k] = yield v
      end
    else
      case type
      when :double
        through do |k,v|
          new[k] = v.first.first
        end
      when :flat
        through do |k,v|
          new[k] = v.first
        end
      when :single
        return self
      when :list
        through do |k,v|
          new[k] = v.nil? ? nil : v.first
        end
      end
    end

    self.annotate(new)
    new.type = :single
    new.fields = [new.fields.first] if new.fields.length > 1
    new
  end

  def to_onehot(boolean = false)
    all_values = values.flatten.uniq.collect{|v| v.to_s}.sort
    index = TSV.setup({}, :key_field => key_field, :fields => all_values, :type => :list)
    index.cast = :to_i unless boolean
    through do |key,values|
      v = all_values.collect{|_v| values.include?(_v)}
      v = v.collect{|_v| _v ? 1 : 0 } unless boolean
      index[key] = v
    end
    index
  end
end


text:
import * as au from "../aurelia";
import { ConfigBuilder } from "../config-builder";
export declare class MdButton {
    private element;
    private configBuilder;
    constructor(element: Element, configBuilder: ConfigBuilder);
    attributeManager: au.AttributeManager;
    disabled: boolean;
    disabledChanged(): void;
    flat: boolean;
    flatChanged(): void;
    floating: boolean;
    large: boolean;
    small: boolean;
    pulse: boolean;
    pulseChanged(): void;
    attached(): void;
    detached(): void;
}


text:
<?php
require_once 'Pager.php';
?>


text:
using CourseExercises.Classes;
using System;

namespace CourseExercises
{
  public partial class InteractiveMenu
  {
    private void PromptMainMenu()
    {
      Console.Clear();

      ConsoleHelper.WriteMenuWithOptions(
        "Main Menu",
        new[]
        {
          "For exercises with vectors, type 'vector'",
          "For exercises with matrixes, type 'matrix'",
          "To exit, type 'exit'"
        });
    }

    private void ReadAndHandleMainMenuOption()
    {
      while (true)
      {
        Console.Write("Please enter your option: ");

        string input = Console.ReadLine();

        if (string.Equals(input, "vector", StringComparison.OrdinalIgnoreCase))
        {
          this.PromptVectorMenu();
          this.ReadAndHandleVectorMenuOption();
        }

        if (string.Equals(input, "matrix", StringComparison.OrdinalIgnoreCase))
        {
          this.PromptMatrixMenu();
          this.ReadAndHandleMatrixMenuOption();
        }

        if (string.Equals(input, "exit", StringComparison.OrdinalIgnoreCase))
        {
          break;
        }
      }
    }
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace SecurityWebSite.Controllers;

public class AuthorizedActionsController : ControllerBase
{
    [AllowAnonymous]
    public IActionResult ActionWithoutAllowAnonymous() => Ok();

    public IActionResult ActionWithoutAuthAttribute() => Ok();

    [Authorize("RequireClaimB")]
    public IActionResult ActionWithAuthAttribute() => Ok();
}