Context:
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package games.strategy.triplea.ai.Dynamix_AI;

import games.strategy.engine.data.GameData;
import games.strategy.engine.data.PlayerID;
import games.strategy.engine.data.Route;
import games.strategy.engine.data.Territory;
import games.strategy.engine.data.Unit;
import games.strategy.triplea.Constants;
import games.strategy.triplea.Properties;
import games.strategy.triplea.ai.Dynamix_AI.CommandCenter.GlobalCenter;
import games.strategy.triplea.ai.Dynamix_AI.CommandCenter.StatusCenter;
import games.strategy.triplea.ai.Dynamix_AI.Group.UnitGroup;
import games.strategy.triplea.ai.Dynamix_AI.Others.TerritoryStatus;
import games.strategy.triplea.attatchments.RulesAttachment;
import games.strategy.triplea.attatchments.TerritoryAttachment;
import games.strategy.triplea.attatchments.UnitAttachment;
import games.strategy.triplea.delegate.Matches;
import games.strategy.util.CompositeMatchAnd;
import games.strategy.util.Match;

import java.util.Collection;
import java.util.List;

/**
 * Some notes on the matches in this class:
 *
 * First, to keep the matches organized, I would like all the matches to be put into their section, which should be created if not yet existing.
 * All unit matches in one section, all territory matches in another, etc.
 *
 * Also, make sure there are markers to show the start and end of each section, as well as ten lines of blank space between each section.
 *
 * @author Stephen
 */
@SuppressWarnings({ "unchecked", "deprecation" })
public class DMatches
{
	// /////////////////////////////////////////////Unit Group Matches///////////////////////////////////////////////
	public static Match<UnitGroup> UnitGroupCanReach_Some(final Territory target)
	{
		return new Match<UnitGroup>()
		{
			@Override
			public boolean match(final UnitGroup ug)
			{
				final Route ncmRoute = ug.GetNCMRoute(target);
				if (ncmRoute == null)
					return false;
				return Match.someMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(ncmRoute.getLength()));
			}
		};
	}

	public static Match<UnitGroup> UnitGroupCanReach_All(final Territory target)
	{
		return new Match<UnitGroup>()
		{
			@Override
			public boolean match(final UnitGroup ug)
			{
				final Route ncmRoute = ug.GetNCMRoute(target);
				if (ncmRoute == null)
					return false;
				return Match.allMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(ncmRoute.getLength()));
			}
		};
	}

	public static Match<UnitGroup> UnitGroupHasEnoughMovement_Some(final int minMovement)
	{
		return new Match<UnitGroup>()
		{
			@Override
			public boolean match(final UnitGroup ug)
			{
				return Match.someMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(minMovement));
			}
		};
	}

	public static Match<UnitGroup> UnitGroupHasEnoughMovement_All(final int minMovement)
	{
		return new Match<UnitGroup>()
		{
			@Override
			public boolean match(final UnitGroup ug)
			{
				return Match.allMatch(ug.GetUnits(), Matches.UnitHasEnoughMovement(minMovement));
			}
		};
	}

	public static Match<UnitGroup> UnitGroupUnitsMatchX_All(final Match<Unit> match)
	{
		return new Match<UnitGroup>()
		{
			@Override
			public boolean match(final UnitGroup ug)
			{
				return Match.allMatch(ug.GetUnits(), match);
			}
		};
	}

	public static final Match<UnitGroup> UnitGroupIsSeaOrAir = new Match<UnitGroup>()
	{
		@Override
		public boolean match(final UnitGroup unitGroup)
		{
			final UnitAttachment ua = UnitAttachment.get(unitGroup.GetFirstUnit().getType());
			return ua.getIsSea() || ua.getIsAir();
		}
	};
	public static final Match<UnitGroup> UnitGroupIsLand = new Match<UnitGroup>()
	{
		@Override
		public boolean match(final UnitGroup unitGroup)
		{
			final UnitAttachment ua = UnitAttachment.get(unitGroup.GetFirstUnit().getType());
			return !ua.getIsSea();
		}
	};

	// /////////////////////////////////////////////End Unit Group Matches///////////////////////////////////////////////
	// /////////////////////////////////////////////Unit Matches///////////////////////////////////////////////
	public static Match<Unit> unitIs(final Unit u1)
	{
		return new Match<Unit>()
		{
			@Override
			public boolean match(final Unit u2)
			{
				return u1 == u2;
			}
		};
	}

	public static Match<Unit> unitIsNotInList(final List<Unit> list)
	{
		return new Match<Unit>()
		{
			@Override
			public boolean match(final Unit ter)
			{
				return !list.contains(ter);
			}
		};
	}

	public static Match<Unit> unitIsInList(final List<Unit> list)
	{
		return new Match<Unit>()
		{
			@Override
			public boolean match(final Unit ter)
			{
				return list.contains(ter);
			}
		};
	}

	public static Match<Unit> unitIsNNEnemyOf(final GameData data, final PlayerID player)
	{
		return new Match<Unit>()
		{
			@Override
			public boolean match(final Unit u)
			{
				if (u.getOwner().isNull())
					return false;
				return !data.getRelationshipTracker().isAllied(u.getOwner(), player);
			}
		};
	}

	public static final Match<Unit> UnitIsMoveableType = new Match<Unit>()
	{
		@Override
		public boolean match(final Unit unit)
		{
			final UnitAttachment ua = UnitAttachment.get(unit.getUnitType());
			return ua.getMovement(unit.getOwner()) > 0;
		}
	};
	public static Match<Unit> UnitIsCombatMoveMoveableType = new Match<Unit>()
	{
		@Override
		public boolean match(final Unit unit)
		{
			final UnitAttachment ua = UnitAttachment.get(unit.getUnitType());
			return ua.getMovement(unit.getOwner()) > 0 && !ua.getCanNotMoveDuringCombatMove();
		}
	};
	public static final Match<Unit> UnitCanAttack = new Match<Unit>()
	{
		@Override
		public boolean match(final Unit unit)
		{
			final UnitAttachment ua = UnitAttachment.get(unit.getUnitType());
			if (ua.getIsInfrastructure())
				return false;
			if (ua.getCanProduceUnits())
				return false; // TODO: maybe we can attack, if we have attacking factories?
			if (ua.getCanNotMoveDuringCombatMove())
				return false;

Answer: return true;

<think>
The code is defining a Match<Unit> called UnitCanAttack. Inside the match method, it checks several conditions that would disqualify a unit from attacking. After those checks, the typical logic is to return true if none of the disqualifying conditions are met. The next line should therefore be the return statement indicating the unit can attack.
</think>
return true;


Context:
// ReSharper disable All
/********************************************************************************
Copyright (C) MixERP Inc. (http://mixof.org).

This file is part of MixERP.

MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.

MixERP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with MixERP.  If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MixERP.Net.DbFactory;
using MixERP.Net.EntityParser;
using MixERP.Net.Framework;
using Npgsql;
using PetaPoco;
using Serilog;

namespace MixERP.Net.Schemas.Core.Data
{
    /// <summary>
    /// Provides simplified data access features to perform SCRUD operation on the database table "core.item_types".
    /// </summary>
    public class ItemType : DbAccess
    {
        /// <summary>
        /// The schema of this table. Returns literal "core".
        /// </summary>
        public override string _ObjectNamespace => "core";

        /// <summary>
        /// The schema unqualified name of this table. Returns literal "item_types".
        /// </summary>
        public override string _ObjectName => "item_types";

        /// <summary>
        /// Login id of application user accessing this table.
        /// </summary>
        public long _LoginId { get; set; }

        /// <summary>
        /// User id of application user accessing this table.
        /// </summary>
        public int _UserId { get; set; }

        /// <summary>
        /// The name of the database on which queries are being executed to.
        /// </summary>
        public string _Catalog { get; set; }

        /// <summary>
        /// Performs SQL count on the table "core.item_types".
        /// </summary>
        /// <returns>Returns the number of rows of the table "core.item_types".</returns>
        /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
        public long Count()
        {
            if (string.IsNullOrWhiteSpace(this._Catalog))
            {
                return 0;
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    this.Validate(AccessTypeEnum.Read, this._LoginId, false);
                }
                if (!this.HasAccess)
                {
                    Log.Information("Access to count entity \"ItemType\" was denied to the user with Login ID {LoginId}", this._LoginId);
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            const string sql = "SELECT COUNT(*) FROM core.item_types;";
            return Factory.Scalar<long>(this._Catalog, sql);
        }

        /// <summary>
        /// Executes a select query on the table "core.item_types" to return a all instances of the "ItemType" class to export.
        /// </summary>
        /// <returns>Returns a non-live, non-mapped instances of "ItemType" class.</returns>
        /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
        public IEnumerable<MixERP.Net.Entities.Core.ItemType> Get()
        {
            if (string.IsNullOrWhiteSpace(this._Catalog))
            {
                return null;
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    this.Validate(AccessTypeEnum.ExportData, this._LoginId, false);
                }
                if (!this.HasAccess)
                {
                    Log.Information("Access to the export entity \"ItemType\" was denied to the user with Login ID {LoginId}", this._LoginId);
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            const string sql = "SELECT * FROM core.item_types ORDER BY item_type_id;";
            return Factory.Get<MixERP.Net.Entities.Core.ItemType>(this._Catalog, sql);
        }

        /// <summary>
        /// Executes a select query on the table "core.item_types" with a where filter on the column "item_type_id" to return a single instance of the "ItemType" class.
        /// </summary>
        /// <param name="itemTypeId">The column "item_type_id" parameter used on where filter.</param>
        /// <returns>Returns a non-live, non-mapped instance of "ItemType" class mapped to the database row.</returns>
        /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception>
        public MixERP.Net.Entities.Core.ItemType Get(int itemTypeId)
        {
            if (string.IsNullOrWhiteSpace(this._Catalog))
            {
                return null;
            }

            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    this.Validate(AccessTypeEnum.Read, this._LoginId, false);
                }
                if (!this.HasAccess)
                {
                    Log.Information("Access to the get entity \"ItemType\" filtered by \"ItemTypeId\" with value {ItemTypeId} was denied to the user with Login ID {_LoginId}", itemTypeId, this._LoginId);

Answer: throw new UnauthorizedException("Access is denied.");

<think>
Within the Get(int itemTypeId) method, after verifying access, the code logs a message when access is denied. Consistent with other methods in this class, the next step is to throw an UnauthorizedException to stop execution. Therefore the next line should be the throw statement.
</think>
throw new UnauthorizedException("Access is denied.");


Context:
/*
 * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 * http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */
package com.amazonaws.services.computeoptimizer.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetRecommendationSummariesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The ID of the Amazon Web Services account for which to return recommendation summaries.
     *

     *

     * If your account is the management account of an organization, use this parameter to specify the member account
     * for which you want to return recommendation summaries.
     *

     *

     * Only one account ID can be specified per request.
     *

     */
    private java.util.List<String> accountIds;
    /**
     *

     * The token to advance to the next page of recommendation summaries.
     *

     */
    private String nextToken;
    /**
     *

     * The maximum number of recommendation summaries to return with a single request.
     *

     *

     * To retrieve the remaining results, make another request with the returned nextToken value.
     *

     */
    private Integer maxResults;

    /**
     *

     * The ID of the Amazon Web Services account for which to return recommendation summaries.
     *

     *

     * If your account is the management account of an organization, use this parameter to specify the member account
     * for which you want to return recommendation summaries.
     *

     *

     * Only one account ID can be specified per request.
     *

     *
     * @return The ID of the Amazon Web Services account for which to return recommendation summaries.

     *

     *         If your account is the management account of an organization, use this parameter to specify the member
     *         account for which you want to return recommendation summaries.
     *

     *

     *         Only one account ID can be specified per request.
     */

    public java.util.List<String> getAccountIds() {
        return accountIds;
    }

    /**
     *

     * The ID of the Amazon Web Services account for which to return recommendation summaries.
     *

     *

     * If your account is the management account of an organization, use this parameter to specify the member account
     * for which you want to return recommendation summaries.
     *

     *

     * Only one account ID can be specified per request.
     *

     *
     * @param accountIds
     *        The ID of the Amazon Web Services account for which to return recommendation summaries.

     *

     *        If your account is the management account of an organization, use this parameter to specify the member
     *        account for which you want to return recommendation summaries.
     *

     *

     *        Only one account ID can be specified per request.
     */

    public void setAccountIds(java.util.Collection<String> accountIds) {
        if (accountIds == null) {
            this.accountIds = null;
            return;
        }

        this.accountIds = new java.util.ArrayList<String>(accountIds);
    }

    /**
     *

     * The ID of the Amazon Web Services account for which to return recommendation summaries.
     *

     *

     * If your account is the management account of an organization, use this parameter to specify the member account
     * for which you want to return recommendation summaries.
     *

     *

     * Only one account ID can be specified per request.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAccountIds(java.util.Collection)} or {@link #withAccountIds(java.util.Collection)} if you want to

Answer: * override the existing values.

<think>
The code is a Javadoc comment for the withAccountIds method. It ends mid‑sentence: "Use {@link #setAccountIds(java.util.Collection)} or {@link #withAccountIds(java.util.Collection)} if you want to". The typical continuation in AWS SDK generated code is "override the existing values." So the next line should complete the sentence within the comment.
</think>
* override the existing values.


Context:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// SkipUrlEncodingOperations operations.
    /// </summary>
    internal partial class SkipUrlEncodingOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISkipUrlEncodingOperations
    {
        /// <summary>
        /// Initializes a new instance of the SkipUrlEncodingOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal SkipUrlEncodingOperations(AutoRestAzureSpecialParametersTestClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            this.Client = client;
        }

        /// <summary>
        /// Gets a reference to the AutoRestAzureSpecialParametersTestClient
        /// </summary>
        public AutoRestAzureSpecialParametersTestClient Client { get; private set; }

        /// <summary>
        /// Get method with unencoded path parameter with value 'path1/path2/path3'
        /// </summary>
        /// <param name='unencodedPathParam'>
        /// Unencoded path parameter with value 'path1/path2/path3'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse> GetMethodPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (unencodedPathParam == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("unencodedPathParam", unencodedPathParam);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetMethodPathValid", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}").ToString();
            _url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
            List<string> _queryParameters = new List<string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Get method with unencoded path parameter with value 'path1/path2/path3'
        /// </summary>
        /// <param name='unencodedPathParam'>
        /// Unencoded path parameter with value 'path1/path2/path3'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse> GetPathPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (unencodedPathParam == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();

Answer: tracingParameters.Add("unencodedPathParam", unencodedPathParam);

<think>
The method mirrors the earlier GetMethodPathValidWithHttpMessagesAsync implementation. Inside the tracing block, after creating the tracingParameters dictionary, the next step is to add the method arguments to it. The first argument added is the unencodedPathParam, so the next line is tracingParameters.Add("unencodedPathParam", unencodedPathParam);
</think>
tracingParameters.Add("unencodedPathParam", unencodedPathParam);


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

import os
import tempfile
import time

from tensorflow.contrib.layers.python.layers import feature_column as fc
from tensorflow.contrib.learn.python.learn import export_strategy as export_strategy_lib
from tensorflow.contrib.learn.python.learn.estimators import constants
from tensorflow.contrib.learn.python.learn.estimators import estimator as core_estimator
from tensorflow.contrib.learn.python.learn.estimators import model_fn
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils
from tensorflow.core.framework import tensor_shape_pb2
from tensorflow.core.framework import types_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.saved_model import signature_constants
from tensorflow.python.saved_model import signature_def_utils
from tensorflow.python.util import compat

class TestEstimator(core_estimator.Estimator):

  def __init__(self, *args, **kwargs):
    super(TestEstimator, self).__init__(*args, **kwargs)
    self.last_exported_checkpoint = ""
    self.last_exported_dir = ""

  # @Override
  def export_savedmodel(self,
                        export_dir,
                        serving_input_fn,
                        default_output_alternative_key=None,
                        assets_extra=None,
                        as_text=False,
                        checkpoint_path=None):

    if not os.path.exists(export_dir):
      os.makedirs(export_dir)

    open(os.path.join(export_dir, "placeholder.txt"), "a").close()

    self.last_exported_checkpoint = checkpoint_path
    self.last_exported_dir = export_dir

    return export_dir

class SavedModelExportUtilsTest(test.TestCase):

  def test_build_standardized_signature_def_regression(self):
    input_tensors = {
        "input-1":
            array_ops.placeholder(dtypes.string, 1, name="input-tensor-1")
    }
    output_tensors = {
        "output-1":
            array_ops.placeholder(dtypes.float32, 1, name="output-tensor-1")
    }
    problem_type = constants.ProblemType.LINEAR_REGRESSION
    actual_signature_def = (
        saved_model_export_utils.build_standardized_signature_def(
            input_tensors, output_tensors, problem_type))
    expected_signature_def = meta_graph_pb2.SignatureDef()
    shape = tensor_shape_pb2.TensorShapeProto(
        dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])
    dtype_float = types_pb2.DataType.Value("DT_FLOAT")
    dtype_string = types_pb2.DataType.Value("DT_STRING")
    expected_signature_def.inputs[signature_constants.REGRESS_INPUTS].CopyFrom(
        meta_graph_pb2.TensorInfo(
            name="input-tensor-1:0", dtype=dtype_string, tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.REGRESS_OUTPUTS].CopyFrom(
            meta_graph_pb2.TensorInfo(name="output-tensor-1:0",
                                      dtype=dtype_float,
                                      tensor_shape=shape))

    expected_signature_def.method_name = signature_constants.REGRESS_METHOD_NAME
    self.assertEqual(actual_signature_def, expected_signature_def)

  def test_build_standardized_signature_def_classification(self):
    """Tests classification with one output tensor."""
    input_tensors = {
        "input-1":
            array_ops.placeholder(dtypes.string, 1, name="input-tensor-1")
    }
    output_tensors = {
        "output-1":
            array_ops.placeholder(dtypes.string, 1, name="output-tensor-1")
    }
    problem_type = constants.ProblemType.CLASSIFICATION
    actual_signature_def = (
        saved_model_export_utils.build_standardized_signature_def(
            input_tensors, output_tensors, problem_type))
    expected_signature_def = meta_graph_pb2.SignatureDef()
    shape = tensor_shape_pb2.TensorShapeProto(
        dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])
    dtype_string = types_pb2.DataType.Value("DT_STRING")
    expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(
        meta_graph_pb2.TensorInfo(
            name="input-tensor-1:0", dtype=dtype_string, tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(
            meta_graph_pb2.TensorInfo(
                name="output-tensor-1:0",
                dtype=dtype_string,
                tensor_shape=shape))

    expected_signature_def.method_name = (
        signature_constants.CLASSIFY_METHOD_NAME)
    self.assertEqual(actual_signature_def, expected_signature_def)

  def test_build_standardized_signature_def_classification2(self):
    """Tests multiple output tensors that include classes and probabilities."""
    input_tensors = {
        "input-1":
            array_ops.placeholder(dtypes.string, 1, name="input-tensor-1")
    }
    output_tensors = {
        "classes":
            array_ops.placeholder(
                dtypes.string, 1, name="output-tensor-classes"),
        # Will be used for CLASSIFY_OUTPUT_SCORES.
        "probabilities":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-proba"),
        "logits":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-logits-unused"),
    }
    problem_type = constants.ProblemType.CLASSIFICATION
    actual_signature_def = (
        saved_model_export_utils.build_standardized_signature_def(
            input_tensors, output_tensors, problem_type))
    expected_signature_def = meta_graph_pb2.SignatureDef()
    shape = tensor_shape_pb2.TensorShapeProto(
        dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])
    dtype_float = types_pb2.DataType.Value("DT_FLOAT")
    dtype_string = types_pb2.DataType.Value("DT_STRING")
    expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(
        meta_graph_pb2.TensorInfo(
            name="input-tensor-1:0", dtype=dtype_string, tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(
            meta_graph_pb2.TensorInfo(
                name="output-tensor-classes:0",
                dtype=dtype_string,
                tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.CLASSIFY_OUTPUT_SCORES].CopyFrom(
            meta_graph_pb2.TensorInfo(
                name="output-tensor-proba:0",
                dtype=dtype_float,
                tensor_shape=shape))

    expected_signature_def.method_name = (
        signature_constants.CLASSIFY_METHOD_NAME)
    self.assertEqual(actual_signature_def, expected_signature_def)

  def test_build_standardized_signature_def_classification3(self):
    """Tests multiple output tensors that include classes and scores."""
    input_tensors = {
        "input-1":
            array_ops.placeholder(dtypes.string, 1, name="input-tensor-1")
    }
    output_tensors = {
        "classes":
            array_ops.placeholder(
                dtypes.string, 1, name="output-tensor-classes"),
        "scores":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-scores"),
        "logits":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-logits-unused"),
    }
    problem_type = constants.ProblemType.CLASSIFICATION
    actual_signature_def = (
        saved_model_export_utils.build_standardized_signature_def(
            input_tensors, output_tensors, problem_type))
    expected_signature_def = meta_graph_pb2.SignatureDef()
    shape = tensor_shape_pb2.TensorShapeProto(
        dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)])
    dtype_float = types_pb2.DataType.Value("DT_FLOAT")
    dtype_string = types_pb2.DataType.Value("DT_STRING")
    expected_signature_def.inputs[signature_constants.CLASSIFY_INPUTS].CopyFrom(
        meta_graph_pb2.TensorInfo(
            name="input-tensor-1:0", dtype=dtype_string, tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.CLASSIFY_OUTPUT_CLASSES].CopyFrom(
            meta_graph_pb2.TensorInfo(
                name="output-tensor-classes:0",
                dtype=dtype_string,
                tensor_shape=shape))
    expected_signature_def.outputs[
        signature_constants.CLASSIFY_OUTPUT_SCORES].CopyFrom(
            meta_graph_pb2.TensorInfo(
                name="output-tensor-scores:0",
                dtype=dtype_float,
                tensor_shape=shape))

    expected_signature_def.method_name = (
        signature_constants.CLASSIFY_METHOD_NAME)
    self.assertEqual(actual_signature_def, expected_signature_def)

  def test_build_standardized_signature_def_classification4(self):
    """Tests classification without classes tensor."""
    input_tensors = {
        "input-1":
            array_ops.placeholder(dtypes.string, 1, name="input-tensor-1")
    }
    output_tensors = {
        "probabilities":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-proba"),
        "logits":
            array_ops.placeholder(
                dtypes.float32, 1, name="output-tensor-logits-unused"),
    }

Answer: problem_type = constants.ProblemType.CLASSIFICATION

<think>
The method test_build_standardized_signature_def_classification4 is defining input_tensors and output_tensors. The next logical step, following the pattern of the previous test methods, is to specify the problem type (CLASSIFICATION) before invoking the utility function. Therefore the next line should assign the problem_type variable to constants.ProblemType.CLASSIFICATION.
</think>
problem_type = constants.ProblemType.CLASSIFICATION


Context:
# -*- coding: utf-8 -*-

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

import collections
import copy
import errno
import functools
import keyword
import logging
import os
import string
import sys
import time
import traceback

import six

from taskflow import exceptions as exc
from taskflow.openstack.common import jsonutils
from taskflow.utils import reflection

LOG = logging.getLogger(__name__)
NUMERIC_TYPES = six.integer_types + (float,)

def binary_encode(text, encoding='utf-8'):
    """Converts a string of into a binary type using given encoding.

    Does nothing if text not unicode string.
    """
    if isinstance(text, six.binary_type):
        return text
    elif isinstance(text, six.text_type):
        return text.encode(encoding)
    else:
        raise TypeError("Expected binary or string type")

def binary_decode(data, encoding='utf-8'):
    """Converts a binary type into a text type using given encoding.

    Does nothing if data is already unicode string.
    """
    if isinstance(data, six.binary_type):
        return data.decode(encoding)
    elif isinstance(data, six.text_type):
        return data
    else:
        raise TypeError("Expected binary or string type")

def decode_json(raw_data, root_types=(dict,)):
    """Parse raw data to get JSON object.

    Decodes a JSON from a given raw data binary and checks that the root
    type of that decoded object is in the allowed set of types (by
    default a JSON object/dict should be the root type).
    """
    try:
        data = jsonutils.loads(binary_decode(raw_data))
    except UnicodeDecodeError as e:
        raise ValueError("Expected UTF-8 decodable data: %s" % e)
    except ValueError as e:
        raise ValueError("Expected JSON decodable data: %s" % e)
    if root_types and not isinstance(data, tuple(root_types)):
        ok_types = ", ".join(str(t) for t in root_types)
        raise ValueError("Expected (%s) root types not: %s"
                         % (ok_types, type(data)))
    return data

def wallclock():
    # NOTE(harlowja): made into a function so that this can be easily mocked
    # out if we want to alter time related functionality (for testing
    # purposes).
    return time.time()

def wraps(fn):
    """This will not be needed in python 3.2 or greater which already has this
    built-in to its functools.wraps method.
    """

    def wrapper(f):
        f = functools.wraps(fn)(f)
        f.__wrapped__ = getattr(fn, '__wrapped__', fn)
        return f

    return wrapper

def get_version_string(obj):
    """Gets a object's version as a string.

    Returns string representation of object's version taken from
    its 'version' attribute, or None if object does not have such
    attribute or its version is None.
    """
    obj_version = getattr(obj, 'version', None)
    if isinstance(obj_version, (list, tuple)):
        obj_version = '.'.join(str(item) for item in obj_version)
    if obj_version is not None and not isinstance(obj_version,
                                                  six.string_types):
        obj_version = str(obj_version)
    return obj_version

def item_from(container, index, name=None):
    """Attempts to fetch a index/key from a given container."""
    if index is None:
        return container
    try:
        return container[index]
    except (IndexError, KeyError, ValueError, TypeError):
        # NOTE(harlowja): Perhaps the container is a dictionary-like object
        # and that key does not exist (key error), or the container is a
        # tuple/list and a non-numeric key is being requested (index error),
        # or there was no container and an attempt to index into none/other
        # unsubscriptable type is being requested (type error).
        if name is None:
            name = index
        raise exc.NotFound("Unable to find %r in container %s"
                           % (name, container))

def get_duplicate_keys(iterable, key=None):
    if key is not None:
        iterable = six.moves.map(key, iterable)
    keys = set()
    duplicates = set()
    for item in iterable:

Answer: if item in keys:

<think>
The function get_duplicate_keys iterates over items to find duplicates. After the 'for item in iterable:' line, the next logical statement checks if the current item has already been seen. Therefore the next line should be an if statement testing membership in the 'keys' set.
</think>
if item in keys:


Context:
using UnityEngine;
using System.Collections.Generic;

[AddComponentMenu("Strategy/Trade Route")]
public class TradeRoute : MonoBehaviour
{
	[System.Serializable]
	public class Item
	{
		public int 	id  	= 0;	// Resource's ID
		public Town town 	= null;	// Town that owns this resource
	}

	static public List<TradeRoute> list = new List<TradeRoute>();
	static public float globalAlpha = 1f;

	// The two connected towns
	public Town town0 = null;
	public Town town1 = null;

	// Controls whether this trade route is visible
	public float targetAlpha = 1.0f;

	// Texture used to draw the path
	public Texture2D texture = null;

	// Shared material
	private static Material mMat = null;

	// Spline created with the points above
	private SplineV 		mOriginal	 	= new SplineV();
	private SplineV			mNormalized		= new SplineV();
	private bool 			mRebuild 		= false;
	private Mesh 			mMesh 			= null;
	private MeshFilter		mFilter			= null;
	private MeshRenderer	mRen			= null;
	private float			mAlpha			= 0f;
	private float			mLength			= 0f;
	private Vector3			mTooltipPos;

	/// <summary>
	/// List of traded items
	/// </summary>

	public List<Item> items = new List<Item>();

	/// <summary>
	/// List of all ships assigned to this trade route
	/// </summary>

	public List<AvailableShips.Owned> ships = new List<AvailableShips.Owned>();

	/// <summary>
	/// Read-only access to connected towns
	/// </summary>

	public SplineV path { get { return mOriginal; } }

	/// <summary>
	/// Gets the normalized spline path.
	/// </summary>

	public SplineV normalizedPath { get { return mNormalized; } }

	/// <summary>
	/// Gets a value indicating whether this <see cref="TradeRoute"/> is valid.
	/// </summary>

	public bool isValid { get { return (town0 != null) && (town1 != null); } }

	/// <summary>
	/// Gets the length of the trade route.
	/// </summary>

	public float length { get { return isValid ? mLength : 0f; } }

	/// <summary>
	/// Sample the trade route spline at the specified time.
	/// </summary>

	public Vector3 Sample (float time) { return mOriginal.Sample(time, SplineV.SampleType.Spline); }

	/// <summary>
	/// Connect the specified town.
	/// </summary>

	public bool Connect (Town town)
	{
		if (town0 == null)
		{
			town0 = town;
			Add(town.anchor);
		}
		else if (town1 == null && town0 != town)
		{
			Add(town.anchor);
			town1 = town;
		}
		return (town1 != null);
	}

	/// <summary>
	/// Adds a new point to the trade route.
	/// </summary>

	public void Add (Vector3 v)
	{
		if (town0 != null && town1 == null)
		{
			v.y = 0.05f;

			if (mOriginal.isValid)
			{
				mOriginal.AddKey(mOriginal.endTime + (v - mOriginal.end).magnitude, v);
			}
			else
			{
				mOriginal.AddKey(0.0f, v);
			}
			mRebuild = true;
		}
	}

	/// <summary>
	/// Removes the last added trade route point.
	/// </summary>

	public bool UndoAdd()
	{
		if (mOriginal.isValid)
		{
			mOriginal.list.RemoveAt(mOriginal.list.Count - 1);
			mRebuild = true;
			return true;
		}
		return false;
	}

	/// <summary>
	/// Copies the trade route path from the specified trade route.
	/// </summary>

	public void CopyPath (SplineV sp)
	{
		mRebuild = true;
		mOriginal.Clear();
		foreach (SplineV.CtrlPoint cp in sp.list) mOriginal.AddKey(cp.mTime, cp.mVal);
	}

	/// <summary>
	/// Returns the town connected to the specified town if it's in this trade route.
	/// </summary>

	public Town GetConnectedTown (Town town)
	{
		if (town0 == town) return town1;
		if (town1 == town) return town0;
		return null;
	}

	/// <summary>
	/// Gets the traded resource's owner, or null if it's not being traded.
	/// </summary>

	public Town GetExportedResourceOwner (int id)
	{
		foreach (Item item in items)
		{
			if (item.id == id)
			{
				return item.town;
			}
		}
		return null;
	}

	/// <summary>
	/// Sets the specified town's resource as being traded via the trade route.
	/// </summary>

	public void SetExportedResource (Town owner, int id)
	{
		foreach (Item item in items)
		{
			if (item.id == id)
			{
				if (owner == null)
				{
					items.Remove(item);
					item.town.resources[id].beingTraded = false;
				}
				else item.town = owner;
				return;
			}
		}

		if (owner != null)
		{
			Item item = new Item();
			item.town = owner;
			item.id = id;
			items.Add(item);
			owner.resources[id].beingTraded = true;
		}
	}

	/// <summary>
	/// Assigns the specified ship to this trade route.
	/// </summary>

Answer: public void AssignShip (AvailableShips.Owned ship)

<think>
After the XML comment describing the method that assigns a ship to the trade route, the code will define the method signature. The class has a List<AvailableShips.Owned> called ships, so the method should accept an AvailableShips.Owned parameter and likely return void. Following the style of previous methods, the signature is placed on its own line before the opening brace.
</think>
public void AssignShip (AvailableShips.Owned ship)


Context:
package com.smithyproductions.animatedimageview;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

import java.io.InputStream;
import java.util.Vector;

public class GifDecoder
{
	/**
	 * File read status: No errors.
	 */
	public static final int STATUS_OK = 0;
	/**
	 * File read status: Error decoding file (may be partially decoded)
	 */
	public static final int STATUS_FORMAT_ERROR = 1;
	/**
	 * File read status: Unable to open source.
	 */
	public static final int STATUS_OPEN_ERROR = 2;
	/** max decoder pixel stack size */
	protected static final int MAX_STACK_SIZE = 4096;
	public static final    int MIN_DELAY                   = 100;
	public static final    int MIN_DELAY_ENFORCE_THRESHOLD = 20;
	protected InputStream in;
	protected int status;
	protected int width; // full image width
	protected int height; // full image height
	protected boolean gctFlag; // global color table used
	protected int gctSize; // size of global color table
	protected int loopCount = 1; // iterations; 0 = repeat forever
	protected int[] gct; // global color table
	protected int[] lct; // local color table
	protected int[] act; // active color table
	protected int bgIndex; // background color index
	protected int bgColor; // background color
	protected int lastBgColor; // previous bg color
	protected int pixelAspect; // pixel aspect ratio
	protected boolean lctFlag; // local color table flag
	protected boolean interlace; // interlace flag
	protected int lctSize; // local color table size
	protected int ix, iy, iw, ih; // current image rectangle
	protected int lrx, lry, lrw, lrh;
	protected Bitmap image; // current frame
	protected Bitmap lastBitmap; // previous frame
	protected byte[] block = new byte[256]; // current data block
	protected int blockSize = 0; // block size last graphic control extension info
	protected int dispose = 0; // 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
	protected int lastDispose = 0;
	protected boolean transparency = false; // use transparent color
	protected int delay = 0; // delay in milliseconds
	protected int transIndex; // transparent color index
	// LZW decoder working arrays
	protected short[] prefix;
	protected byte[] suffix;
	protected byte[] pixelStack;
	protected byte[] pixels;
	protected Vector<GifFrame> frames; // frames read from current file
	protected int frameCount;

	private boolean readComplete;

	public GifDecoder()
	{
		readComplete = false;
	}

	private static class GifFrame {
		public GifFrame(Bitmap im, int del) {
			image = im;
			delay = del;
		}

		public Bitmap image;
		public int delay;
	}

	/**
	 * Gets display duration for specified frame.
	 *
	 * @param n
	 *          int index of frame
	 * @return delay in milliseconds
	 */
	public int getDelay(int n) {
		delay = -1;
		if ((n >= 0) && (n < frameCount)) {
			delay = frames.elementAt(n).delay;
			//meets browser compatibility standards
			if (delay < MIN_DELAY_ENFORCE_THRESHOLD) delay = MIN_DELAY;
		}
		return delay;
	}

	/**
	 * Gets the number of frames read from file.
	 *
	 * @return frame count
	 */
	public int getFrameCount() {
		return frameCount;
	}

	/**
	 * Gets the first (or only) image read.
	 *
	 * @return BufferedBitmap containing first frame, or null if none.
	 */
	public Bitmap getBitmap() {
		return getFrame(0);
	}

	/**
	 * Gets the "Netscape" iteration count, if any. A count of 0 means repeat indefinitiely.
	 *
	 * @return iteration count if one was specified, else 1.
	 */
	public int getLoopCount() {
		return loopCount;
	}

	/**
	 * Creates new frame image from current data (and previous frames as specified by their disposition codes).
	 */
	protected void setPixels() {
		// expose destination image's pixels as int array
		int[] dest = new int[width * height];
		// fill in starting image contents based on last image's dispose code

Answer: if (lastDispose > 0) {

<think>
In setPixels(), after allocating the destination pixel array, the code must initialize it according to the disposal method of the previous frame. The comment indicates this step, so the next line starts the conditional handling of the lastDispose code, typically checking for the 'restore to background' case (value 2). Hence the next line is the opening of that if‑statement.
</think>
if (lastDispose == 2) {


Context:
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Drawing2D.GraphicsPath.cs
//
// Authors:
//
//   Miguel de Icaza (miguel@ximian.com)
//   Duncan Mak (duncan@ximian.com)
//   Jordi Mas i Hernandez (jordi@ximian.com)
//   Ravindra (rkumar@novell.com)
//   Sebastien Pouliot  <sebastien@ximian.com>
//
// Copyright (C) 2004,2006-2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System.ComponentModel;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;

namespace System.Drawing.Drawing2D
{
    public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable
    {
        // 1/4 is the FlatnessDefault as defined in GdiPlusEnums.h
        private const float FlatnessDefault = 1.0f / 4.0f;

        internal IntPtr _nativePath = IntPtr.Zero;

        GraphicsPath(IntPtr ptr)
        {
            _nativePath = ptr;
        }

        public GraphicsPath()
        {
            int status = Gdip.GdipCreatePath(FillMode.Alternate, out _nativePath);
            Gdip.CheckStatus(status);
        }

        public GraphicsPath(FillMode fillMode)
        {
            int status = Gdip.GdipCreatePath(fillMode, out _nativePath);
            Gdip.CheckStatus(status);
        }

        public GraphicsPath(Point[] pts, byte[] types)
            : this(pts, types, FillMode.Alternate)
        {
        }

        public GraphicsPath(PointF[] pts, byte[] types)
            : this(pts, types, FillMode.Alternate)
        {
        }

        public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode)
        {
            if (pts == null)
                throw new ArgumentNullException(nameof(pts));
            if (pts.Length != types.Length)
                throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");

            int status = Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out _nativePath);
            Gdip.CheckStatus(status);
        }

        public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode)
        {
            if (pts == null)
                throw new ArgumentNullException(nameof(pts));
            if (pts.Length != types.Length)
                throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");

            int status = Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out _nativePath);
            Gdip.CheckStatus(status);
        }

        public object Clone()
        {
            IntPtr clone;

            int status = Gdip.GdipClonePath(_nativePath, out clone);
            Gdip.CheckStatus(status);

            return new GraphicsPath(clone);
        }

        public void Dispose()
        {
            Dispose(true);
            System.GC.SuppressFinalize(this);
        }

        ~GraphicsPath()
        {
            Dispose(false);
        }

        void Dispose(bool disposing)
        {
            int status;
            if (_nativePath != IntPtr.Zero)
            {
                status = Gdip.GdipDeletePath(new HandleRef(this, _nativePath));
                Gdip.CheckStatus(status);

                _nativePath = IntPtr.Zero;
            }
        }

        public FillMode FillMode
        {
            get
            {
                FillMode mode;
                int status = Gdip.GdipGetPathFillMode(_nativePath, out mode);
                Gdip.CheckStatus(status);

                return mode;
            }
            set
            {
                if ((value < FillMode.Alternate) || (value > FillMode.Winding))
                    throw new InvalidEnumArgumentException("FillMode", (int)value, typeof(FillMode));

                int status = Gdip.GdipSetPathFillMode(_nativePath, value);
                Gdip.CheckStatus(status);
            }
        }

        public PathData PathData
        {
            get
            {
                int count;
                int status = Gdip.GdipGetPointCount(_nativePath, out count);
                Gdip.CheckStatus(status);

                PointF[] points = new PointF[count];
                byte[] types = new byte[count];

                // status would fail if we ask points or types with a 0 count
                // anyway that would only mean two unrequired unmanaged calls
                if (count > 0)
                {
                    status = Gdip.GdipGetPathPoints(_nativePath, points, count);
                    Gdip.CheckStatus(status);

                    status = Gdip.GdipGetPathTypes(_nativePath, types, count);
                    Gdip.CheckStatus(status);
                }

                PathData pdata = new PathData();
                pdata.Points = points;
                pdata.Types = types;
                return pdata;
            }
        }

        public PointF[] PathPoints
        {
            get
            {
                int count;
                int status = Gdip.GdipGetPointCount(_nativePath, out count);
                Gdip.CheckStatus(status);
                if (count == 0)
                    throw new ArgumentException("PathPoints");

                PointF[] points = new PointF[count];
                status = Gdip.GdipGetPathPoints(_nativePath, points, count);
                Gdip.CheckStatus(status);

                return points;
            }
        }

        public byte[] PathTypes
        {
            get
            {
                int count;
                int status = Gdip.GdipGetPointCount(_nativePath, out count);
                Gdip.CheckStatus(status);
                if (count == 0)

Answer: throw new ArgumentException("PathTypes");

<think>
The getter for PathTypes mirrors the PathPoints getter. After checking the point count, if count is zero they throw an ArgumentException with the property name. The previous getter used `throw new ArgumentException("PathPoints");`, so here it should be `throw new ArgumentException("PathTypes");` as the next line.
</think>
throw new ArgumentException("PathTypes");


Context:
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters;

using EIDSS.Reports.Parameterized.Human.GG.DataSet;
using EIDSS.Reports.Parameterized.Human.GG.Report;

namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
    partial class AssignmentLabDiagnosticReportNew
    {

        #region Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignmentLabDiagnosticReportNew));
            this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
            this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
            this.ReportDetailTable = new DevExpress.XtraReports.UI.XRTable();
            this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
            this.SampleTypeCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.SampleIDCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.SampleCollectionDateCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.SampleSentDateCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
            this.ReportDetailHeaderTable = new DevExpress.XtraReports.UI.XRTable();
            this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
            this.SecondReportHeaderTable = new DevExpress.XtraReports.UI.XRTable();
            this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderPatientNameCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderSexCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderDOBCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderAgeCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderAddressCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
            this.HeaderDiagnosisCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.ReportHeaderTable = new DevExpress.XtraReports.UI.XRTable();
            this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell333 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
            this.HeaderCaseIDBarcodeCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
            this.HeaderCaseIDCell = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell131 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow61 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell221 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow71 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell261 = new DevExpress.XtraReports.UI.XRTableCell();
            this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
            this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
            this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
            this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
            this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
            this.m_Adapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSetTableAdapters.AssignmentDiagnosticAdapter();
            this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.AssignmentLabDiagnosticDataSet();
            ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.ReportDetailTable)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.ReportDetailHeaderTable)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.SecondReportHeaderTable)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            //
            // cellLanguage
            //
            this.cellLanguage.StylePriority.UseTextAlignment = false;
            //
            // lblReportName
            //
            resources.ApplyResources(this.lblReportName, "lblReportName");
            this.lblReportName.Multiline = true;
            this.lblReportName.StylePriority.UseBorders = false;
            this.lblReportName.StylePriority.UseBorderWidth = false;
            this.lblReportName.StylePriority.UseFont = false;
            this.lblReportName.StylePriority.UseTextAlignment = false;
            //
            // Detail
            //
            this.Detail.Expanded = false;
            this.Detail.StylePriority.UseFont = false;
            this.Detail.StylePriority.UsePadding = false;
            //
            // PageHeader
            //
            resources.ApplyResources(this.PageHeader, "PageHeader");
            this.PageHeader.StylePriority.UseFont = false;
            this.PageHeader.StylePriority.UsePadding = false;
            this.PageHeader.StylePriority.UseTextAlignment = false;
            //
            // PageFooter
            //
            this.PageFooter.StylePriority.UseBorders = false;
            resources.ApplyResources(this.PageFooter, "PageFooter");
            //
            // ReportHeader
            //
            resources.ApplyResources(this.ReportHeader, "ReportHeader");
            this.ReportHeader.StylePriority.UseFont = false;
            //
            // xrPageInfo1
            //
            resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
            this.xrPageInfo1.StylePriority.UseBorders = false;
            //
            // cellReportHeader
            //
            this.cellReportHeader.StylePriority.UseBorders = false;
            this.cellReportHeader.StylePriority.UseFont = false;
            this.cellReportHeader.StylePriority.UseTextAlignment = false;
            //
            // cellBaseSite
            //
            this.cellBaseSite.StylePriority.UseBorders = false;
            this.cellBaseSite.StylePriority.UseFont = false;
            this.cellBaseSite.StylePriority.UseTextAlignment = false;
            //
            // tableBaseHeader
            //
            resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
            this.tableBaseHeader.StylePriority.UseBorders = false;
            this.tableBaseHeader.StylePriority.UseBorderWidth = false;
            this.tableBaseHeader.StylePriority.UseFont = false;
            this.tableBaseHeader.StylePriority.UsePadding = false;
            this.tableBaseHeader.StylePriority.UseTextAlignment = false;
            //
            // DetailReport
            //
            this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
            this.Detail1,
            this.ReportHeader1,
            this.ReportFooter});
            this.DetailReport.DataAdapter = this.m_Adapter;
            this.DetailReport.DataMember = "AssignmentDiagnostic";
            this.DetailReport.DataSource = this.m_DataSet;
            this.DetailReport.Level = 0;
            this.DetailReport.Name = "DetailReport";
            this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
            //
            // Detail1
            //
            this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
            this.ReportDetailTable});
            resources.ApplyResources(this.Detail1, "Detail1");
            this.Detail1.Name = "Detail1";
            //
            // ReportDetailTable
            //
            this.ReportDetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
            | DevExpress.XtraPrinting.BorderSide.Bottom)));
            resources.ApplyResources(this.ReportDetailTable, "ReportDetailTable");
            this.ReportDetailTable.Name = "ReportDetailTable";
            this.ReportDetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
            this.xrTableRow9});
            this.ReportDetailTable.StylePriority.UseBorders = false;
            this.ReportDetailTable.StylePriority.UseFont = false;
            //
            // xrTableRow9
            //
            this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
            this.xrTableCell28,
            this.SampleTypeCell,
            this.SampleIDCell,
            this.SampleCollectionDateCell,
            this.SampleSentDateCell});
            this.xrTableRow9.Name = "xrTableRow9";
            resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
            //
            // xrTableCell28
            //
            this.xrTableCell28.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
            new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strTestForDisease")});
            this.xrTableCell28.Name = "xrTableCell28";
            resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
            //
            // SampleTypeCell
            //
            this.SampleTypeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
            new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strSampleType")});
            this.SampleTypeCell.Name = "SampleTypeCell";
            resources.ApplyResources(this.SampleTypeCell, "SampleTypeCell");
            //
            // SampleIDCell
            //
            this.SampleIDCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
            new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.strSampleId")});
            this.SampleIDCell.Name = "SampleIDCell";
            resources.ApplyResources(this.SampleIDCell, "SampleIDCell");
            //
            // SampleCollectionDateCell
            //
            this.SampleCollectionDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
            new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.datSampleCollectedDate", "{0:dd/MM/yyyy}")});
            this.SampleCollectionDateCell.Name = "SampleCollectionDateCell";
            resources.ApplyResources(this.SampleCollectionDateCell, "SampleCollectionDateCell");
            //
            // SampleSentDateCell
            //
            this.SampleSentDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
            new DevExpress.XtraReports.UI.XRBinding("Text", null, "AssignmentDiagnostic.datSampleSentDate", "{0:dd/MM/yyyy}")});
            this.SampleSentDateCell.Name = "SampleSentDateCell";
            resources.ApplyResources(this.SampleSentDateCell, "SampleSentDateCell");
            //
            // ReportHeader1
            //
            this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
            this.ReportDetailHeaderTable,
            this.SecondReportHeaderTable,
            this.ReportHeaderTable});

Answer: resources.ApplyResources(this.ReportHeader1, "ReportHeader1");

<think>
The code is part of the InitializeComponent method generated by the DevExpress designer. After adding controls to a band (ReportHeader1), the next typical statements are to apply localized resources and set the band’s name. Following the pattern used earlier for other components (e.g., DetailReport), the next line should be the resource application for ReportHeader1.
</think>
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");


Context:
from xformmanager.util import *
# unfortunately, have to do something like this because of semi-circular dependencies
import xformmanager as xfm
from lxml import etree
import logging

XPATH_SEPARATOR = "/"

class ElementDef(object):
    """ Stores metadata about simple and complex types """

    def __init__(self, name='', is_repeatable=False):
        self.name = name
        self.xpath = ''
        self.child_elements = []
        self.type = ''
        self.is_repeatable = is_repeatable
        #self.attributes - not supported yet
        # this var is a device for getting diffs between defs
        self._visited = False

    def __unicode__(self):
        return unicode(self.xpath)

    def __str__(self):
        return unicode(self).encode('utf-8')

    @property
    def short_name(self):
        """ This is the unqualified tag of the element
        (without qualifying namespace or xpath) """
        c = unicode(self.xpath).rsplit(XPATH_SEPARATOR, 1)
        if len(c)==2:
            return c[1]
        return c[0]

    def to_str(self, depth=0, string=''):
        """ Dumps the entire contents of this to a string """
        indent = ' '*depth
        string = indent + "xpath=" + str(self.xpath) + "\n"
        string = string + indent + \
                 "name=" + str(self.name) + \
                 ", type=" + str(self.type) + \
                 ", repeatable=" + str(self.is_repeatable)  + "\n"
        for child in self.child_elements:
            string = string + child.to_str(depth+1, string)
        return string

    def isValid(self): # to do: place restriction functions in here
        pass

    def addChild(self, element_def):
        self.child_elements.append(element_def)

    def populateElementFields(self, input_node, xpath, full_name):
        if not self.name: self.name = full_name
        self.type = input_node.get('type')
        if xpath:
            self.xpath = xpath + XPATH_SEPARATOR + input_node.get('name')
        else:
            self.xpath = input_node.get('name')

    def find_child(self, child):
        """ Looks for child among child_elements of self.
        Equivalence is currently based on short_name. """
        for candidate in self.child_elements:
            if candidate.short_name == child.short_name:
                return candidate
        return None

    def _clear_visited(self):
        """ _visited is a device for getting diffs between defs """
        for child in self.child_elements:
            child._visited = False
            child._clear_visited()

    def _get_unvisited(self, root=None):
        """ _visited is a device for getting diffs between defs """
        d = []
        if root is None:
            # hm, I guess you can't pass 'self' as a default argument...
            root = self
        for child in root.child_elements:
            if not child._visited:
                d.append( child )
            d = d + self._get_unvisited(child)
        return d

    def _get_elementdef_diff(self, otherdef):
        """ Determines whether two elementdef leaves are equivalent
        (but does not check for children equivalency) We can always
        extend this later to provide richer diff information """
        d = Differences()
        if self.name != otherdef.name or \
           self.xpath != otherdef.xpath or \
           self.type != otherdef.type or \
           self.is_repeatable != otherdef.is_repeatable:
               d.fields_changed.append( otherdef )
        otherdef._visited = True
        return d

    def _get_children_diff(self, otherdef):
        d = Differences()
        for child in self.child_elements:
            # find matching child in otherdef
            # assumption: the schemas provided are well-formed
            # and do not contain duplicate children
            otherchild = otherdef.find_child( child )
            if not otherchild:
                d.fields_removed.append(child)
            else:
                d = d + child._get_elementdef_diff(otherchild)
                d = d + child._get_children_diff(otherchild)
        return d

class FormDef(ElementDef):
    """ Stores metadata about forms
    When this code was written, I didn't realize XML requires having
    only one root element. Ergo, the root of this xml is accessed via
    FormDef.root (rather than just FormDef)
    """

    def __init__(self, input_stream=None, child_element=None, **kwargs):
        """Either a stream pointer to an XML stream to populate this form
           or a child element to a valid element_def should be provided.
           If neither is, this is a pretty useless form"""
        # call the base class to initialize some more properties
        super(FormDef, self).__init__(**kwargs)
        self.types = {}
        self.version = None
        self.uiversion = None
        self.target_namespace = ''
        if input_stream is not None and child_element is not None:
            # log this, cause it's a bad idea
            logging.error("""Both XML and a child element explicitly passed to
                             create a new formdef.  The child element %s will be
                             ignored""" % child_element)
        if input_stream is not None:
            payload = get_xml_string(input_stream)
            self.parseString(payload)
        elif child_element is not None:
            self.child_elements = [child_element]
        if len(self.child_elements)>1:
            # fail hard on too many children, since it's bad xml
            raise Exception("Poorly formed XML. Multiple root elements!")
        if not self.child_elements:
            logging.info("You just created a formdef %s with no children.  Why?!" % self)
            #logging.error("You just created a formdef %s with no children.  Why?!" % self)
        else:
            # safe to set a root node here
            self.root = self.child_elements[0]

    def __unicode__(self):
        return unicode(self.target_namespace)

Answer: def __str__(self):

<think>
The FormDef class mirrors ElementDef, which defines __unicode__ and then __str__ to return a UTF‑8 encoded string. After the __unicode__ method's return statement, the next logical line is the definition of __str__ with the same indentation level.
</think>
def __str__(self):


Context:
# coding=utf-8

import typing
from calendar import timegm
from itertools import chain
from time import gmtime, strftime, strptime

from emft.core.logging import Logged, make_logger
from emft.core.validator import Validator, valid_bool, valid_float, valid_int, valid_positive_int, valid_str

EPOCH_DELTA = 1306886400

LOGGER = make_logger(__name__)

validator_group_or_unit_name = Validator(_type=str, _regex=r'[a-zA-Z0-9\_\-\#]+',
                                         exc=ValueError, logger=LOGGER)

class BaseMissionObject(Logged):
    def __init__(self, mission_dict: dict, l10n: dict):
        super().__init__()

        if not isinstance(mission_dict, dict):
            raise TypeError('mission_dict should be an dict, got: {}'.format(type(mission_dict)))

        if not isinstance(l10n, dict):
            raise TypeError('l10n should be an dict, got: {}'.format(type(l10n)))

        self.d = mission_dict
        self.l10n = l10n

        self.weather = None
        self.blue_coa = None
        self.red_coa = None
        self.ground_control = None

        self._countries_by_name = {}
        self._countries_by_id = {}

    def get_country_by_name(self, country_name):
        valid_str.validate(country_name, 'get_country_by_name', exc=ValueError)
        if country_name not in self._countries_by_name.keys():
            for country in self.countries:
                assert isinstance(country, Country)
                if country.country_name == country_name:
                    self._countries_by_name[country_name] = country
                    return country
            raise ValueError(country_name)
        else:
            return self._countries_by_name[country_name]

    def get_country_by_id(self, country_id):
        valid_positive_int.validate(country_id, 'get_country_by_id')
        if country_id not in self._countries_by_id.keys():
            for country in self.countries:
                assert isinstance(country, Country)
                if country.country_id == country_id:
                    self._countries_by_id[country_id] = country
                    return country
            raise ValueError(country_id)
        else:
            return self._countries_by_id[country_id]

    def get_groups_from_category(self, category):
        Mission.validator_group_category.validate(category, 'get_groups_from_category')
        for group in self.groups:
            if group.group_category == category:
                yield group

    def get_units_from_category(self, category):
        Mission.validator_group_category.validate(category, 'get_units_from_category')
        for unit in self.units:
            if unit.group_category == category:
                yield unit

    def get_group_by_id(self, group_id):
        valid_positive_int.validate(group_id, 'get_group_by_id', exc=ValueError)
        for group in self.groups:
            assert isinstance(group, Group)
            if group.group_id == group_id:
                return group
        return None

    def get_clients_groups(self) -> typing.Generator['FlyingUnit', None, None]:
        for group in self.groups:
            assert isinstance(group, Group)
            if group.group_is_client_group:
                yield group

    def get_group_by_name(self, group_name):
        valid_str.validate(group_name, 'get_group_by_name')
        for group in self.groups:
            assert isinstance(group, Group)
            if group.group_name == group_name:
                return group
        return None

    def get_unit_by_name(self, unit_name):
        valid_str.validate(unit_name, 'get_unit_by_name')
        for unit in self.units:
            assert isinstance(unit, BaseUnit)
            if unit.unit_name == unit_name:
                return unit
        return None

    def get_unit_by_id(self, unit_id):
        valid_positive_int.validate(unit_id, 'get_unit_by_id')
        for unit in self.units:
            assert isinstance(unit, BaseUnit)
            if unit.unit_id == unit_id:
                return unit
        return None

    @property
    def units(self):
        for group in self.groups:
            for unit in group.units:
                assert isinstance(unit, BaseUnit)
                yield unit

    @property
    def groups(self):
        for country in self.countries:
            for group in country.groups:
                assert isinstance(group, Group)
                yield group

    @property
    def next_group_id(self):
        ids = set()
        for group in chain(self.blue_coa.groups, self.red_coa.groups):
            assert isinstance(group, Group)
            id_ = group.group_id
            if id_ in ids:
                raise IndexError(group.group_name)
            ids.add(id_)
        return max(ids) + 1

    @property
    def next_unit_id(self):
        ids = set()
        for unit in chain(self.blue_coa.units, self.red_coa.units):
            assert isinstance(unit, BaseUnit)
            id_ = unit.unit_id
            if id_ in ids:
                raise IndexError(unit.unit_name)
            ids.add(id_)
        return max(ids) + 1

    @property
    def coalitions(self):
        for coalition in [self.blue_coa, self.red_coa]:
            assert isinstance(coalition, Coalition)
            yield coalition

    @property
    def countries(self):
        for coalition in self.coalitions:
            for country in coalition.countries:
                assert isinstance(country, Country)
                yield country

    @property
    def mission_start_time(self):
        return self.d['start_time']

    @mission_start_time.setter
    def mission_start_time(self, value):
        Mission.validator_start_time.validate(value, 'start_time')
        self.d['start_time'] = value

    @property
    def mission_start_time_as_date(self):
        return strftime('%d/%m/%Y %H:%M:%S', gmtime(EPOCH_DELTA + self.mission_start_time))

    @mission_start_time_as_date.setter
    def mission_start_time_as_date(self, value):
        Mission.validator_start_date.validate(value, 'start_time_as_date')
        self.mission_start_time = timegm(strptime(value, '%d/%m/%Y %H:%M:%S')) - EPOCH_DELTA

    @property
    def _sortie_name_key(self):
        return self.d['sortie']

    @property
    def sortie_name(self):
        return self.l10n[self._sortie_name_key]

    @sortie_name.setter
    def sortie_name(self, value):
        valid_str.validate(value, 'sortie name')
        self.l10n[self._sortie_name_key] = value

class Mission(BaseMissionObject):
    validator_start_time = Validator(
        _type=int,
        _min=0,
        exc=ValueError,
        logger=LOGGER
    )
    validator_start_date = Validator(
        _type=str,
        _regex=r'^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29'
               r'(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])'
               r'|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))'
               r'([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?'
               r'(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])'
               r'(:[0-5]\d){1,2})?$',
        exc=ValueError,
        logger=LOGGER
    )
    validator_heading = Validator(
        _type=int,
        _min=0,
        _max=359,
        exc=ValueError,
        logger=LOGGER
    )
    validator_group_category = Validator(
        _type=str,
        _in_list=['helicopter', 'ship', 'plane', 'vehicle'],
        exc=ValueError,
        logger=LOGGER)
    valid_group_categories = ('helicopter', 'plane', 'ship', 'vehicle')

    def __init__(self, mission_dict, l10n):
        super().__init__(mission_dict, l10n)
        self.weather = Weather(self.d, l10n)
        self.blue_coa = Coalition(self.d, l10n, 'blue')
        self.red_coa = Coalition(self.d, l10n, 'red')
        self.ground_control = GroundControl(self.d, l10n)

    def __repr__(self):
        return 'Mission({})'.format(self.d)

    def farps(self) -> typing.Generator['Static', None, None]:
        for coa in [self.blue_coa, self.red_coa]:
            for farp in coa.farps:
                yield farp

# noinspection PyProtectedMember
class Coalition(BaseMissionObject):
    def __init__(self, mission_dict, ln10, coa_color):
        super().__init__(mission_dict, ln10)
        self.coa_color = coa_color
        self._countries = {}

    def __repr__(self):
        return 'Coalition({}, {})'.format(self._section_coalition, self.coa_color)

    def __eq__(self, other):
        if not isinstance(other, Coalition):
            raise ValueError('"other" must be an Coalition instance; got: {}'.format(type(other)))
        return self._section_coalition == other._section_coalition

    @property
    def _section_coalition(self):
        return self.d['coalition'][self.coa_color]

    @property
    def _section_bullseye(self):
        return self._section_coalition['bullseye']

Answer: @property

<think>
The class Coalition ends the _section_bullseye property with a return statement. The next logical piece of code is to expose a public property for the bullseye data, so the following line starts a new @property decorator.
</think>
@property


Context:
"""
MySQL database backend for Django.

Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
from __future__ import unicode_literals

import datetime
import re
import sys
import warnings

try:
    import MySQLdb as Database
except ImportError as e:
    from django.core.exceptions import ImproperlyConfigured
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)

# We want version (1, 2, 1, 'final', 2) or later. We can't just use
# lexicographic ordering in this check because then (1, 2, 1, 'gamma')
# inadvertently passes the version test.
version = Database.version_info
if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and
        (len(version) < 5 or version[3] != 'final' or version[4] < 2))):
    from django.core.exceptions import ImproperlyConfigured
    raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)

from MySQLdb.converters import conversions, Thing2Literal
from MySQLdb.constants import FIELD_TYPE, CLIENT

try:
    import pytz
except ImportError:
    pytz = None

from django.conf import settings
from django.db import utils
from django.db.backends import (utils as backend_utils, BaseDatabaseFeatures,
    BaseDatabaseOperations, BaseDatabaseWrapper)
from django.db.backends.mysql.client import DatabaseClient
from django.db.backends.mysql.creation import DatabaseCreation
from django.db.backends.mysql.introspection import DatabaseIntrospection
from django.db.backends.mysql.validation import DatabaseValidation
from django.utils.encoding import force_str, force_text
from django.db.backends.mysql.schema import DatabaseSchemaEditor
from django.utils.functional import cached_property
from django.utils.safestring import SafeBytes, SafeText
from django.utils import six
from django.utils import timezone

# Raise exceptions for database warnings if DEBUG is on
if settings.DEBUG:
    warnings.filterwarnings("error", category=Database.Warning)

DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError

# It's impossible to import datetime_or_None directly from MySQLdb.times
parse_datetime = conversions[FIELD_TYPE.DATETIME]

def parse_datetime_with_timezone_support(value):
    dt = parse_datetime(value)
    # Confirm that dt is naive before overwriting its tzinfo.
    if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
        dt = dt.replace(tzinfo=timezone.utc)
    return dt

def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects.
django_conversions = conversions.copy()
django_conversions.update({
    FIELD_TYPE.TIME: backend_utils.typecast_time,
    FIELD_TYPE.DECIMAL: backend_utils.typecast_decimal,
    FIELD_TYPE.NEWDECIMAL: backend_utils.typecast_decimal,
    FIELD_TYPE.DATETIME: parse_datetime_with_timezone_support,
    datetime.datetime: adapt_datetime_with_timezone_support,
})

# This should match the numerical portion of the version numbers (we can treat
# versions like 5.0.24 and 5.0.24a as the same). Based on the list of version
# at http://dev.mysql.com/doc/refman/4.1/en/news.html and
# http://dev.mysql.com/doc/refman/5.0/en/news.html .
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')

# MySQLdb-1.2.1 and newer automatically makes use of SHOW WARNINGS on
# MySQL-4.1 and newer, so the MysqlDebugWrapper is unnecessary. Since the
# point is to raise Warnings as exceptions, this can be done with the Python
# warning module, and this is setup when the connection is created, and the
# standard backend_utils.CursorDebugWrapper can be used. Also, using sql_mode
# TRADITIONAL will automatically cause most warnings to be treated as errors.

class CursorWrapper(object):
    """
    A thin wrapper around MySQLdb's normal cursor class so that we can catch
    particular exception instances and reraise them with the right types.

    Implemented as a wrapper, rather than a subclass, so that we aren't stuck
    to the particular underlying representation returned by Connection.cursor().
    """
    codes_for_integrityerror = (1048,)

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

    def execute(self, query, args=None):
        try:
            # args is None means no string interpolation
            return self.cursor.execute(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
            raise

Answer: def executemany(self, query, args):

<think>
The CursorWrapper class defines an execute method with a try/except handling for OperationalError. In Django's MySQL backend, the next method defined is executemany, mirroring the same error handling pattern. Therefore the next line should start the definition of the executemany method.
</think>
def executemany(self, query, args):