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

import com.intellij.lang.Language;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.GlobalUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.command.undo.UndoableAction;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CachedValueImpl;
import com.intellij.util.FileContentUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.containers.*;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.intellij.plugins.intelliLang.inject.InjectorUtils;
import org.intellij.plugins.intelliLang.inject.LanguageInjectionConfigBean;
import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport;
import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
import org.intellij.plugins.intelliLang.inject.config.InjectionPlace;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * Configuration that holds configured xml tag, attribute and method parameter
 * injection settings as well as the annotations to use for injection, pattern
 * validation and for substituting non-compile time constant expression.
 *
 * Making it a service may result in FileContentUtil.reparseFiles at a random loading moment which may cause
 * mysterious PSI validity losses
 */
public class Configuration extends SimpleModificationTracker implements PersistentStateComponent<Element>, ModificationTracker {
  static final Logger LOG = Logger.getInstance(Configuration.class.getName());
  private static final Condition<BaseInjection> LANGUAGE_INJECTION_CONDITION =
    o -> Language.findLanguageByID(o.getInjectedLanguageId()) != null;

  @State(name = Configuration.COMPONENT_NAME, defaultStateAsResource = true, storages = @Storage("IntelliLang.xml"))
  public static class App extends Configuration {
    private final List<BaseInjection> myDefaultInjections;
    private final AdvancedConfiguration myAdvancedConfiguration;

    App() {
      myDefaultInjections = loadDefaultInjections();
      myAdvancedConfiguration = new AdvancedConfiguration();
    }

    @Override
    public List<BaseInjection> getDefaultInjections() {
      return myDefaultInjections;
    }

    @Override
    public AdvancedConfiguration getAdvancedConfiguration() {
      return myAdvancedConfiguration;
    }

    @Override
    public void loadState(final Element element) {
      myAdvancedConfiguration.loadState(element);
      super.loadState(element);
    }

    @Override
    public Element getState() {
      final Element element = new Element(COMPONENT_NAME);
      myAdvancedConfiguration.writeState(element);
      return getState(element);
    }
  }

  @State(name = Configuration.COMPONENT_NAME, defaultStateAsResource = true, storages = @Storage("IntelliLang.xml"))
  public static class Prj extends Configuration {

    private final Configuration myParentConfiguration;

    Prj(final Configuration configuration) {
      myParentConfiguration = configuration;
    }

    @Override
    public AdvancedConfiguration getAdvancedConfiguration() {
      return myParentConfiguration.getAdvancedConfiguration();
    }

    @Override
    public List<BaseInjection> getDefaultInjections() {
      return myParentConfiguration.getDefaultInjections();
    }

    @Override
    protected Collection<BaseInjection> getAllInjections() {
      Collection<BaseInjection> injections = super.getAllInjections();
      injections.addAll(myParentConfiguration.getAllInjections());
      return injections;
    }

    @NotNull
    @Override
    public List<BaseInjection> getInjections(final String injectorId) {
      return ContainerUtil.concat(myParentConfiguration.getInjections(injectorId), getOwnInjections(injectorId));
    }

    public Configuration getParentConfiguration() {
      return myParentConfiguration;
    }

    public List<BaseInjection> getOwnInjections(final String injectorId) {
      return super.getInjections(injectorId);
    }

    @Override
    public long getModificationCount() {
      return super.getModificationCount() + myParentConfiguration.getModificationCount();
    }

    @Override
    public boolean replaceInjections(List<? extends BaseInjection> newInjections,
                                     List<? extends BaseInjection> originalInjections,
                                     boolean forceLevel) {
      if (!forceLevel && !originalInjections.isEmpty()) {
        if (myParentConfiguration.replaceInjections(Collections.emptyList(), originalInjections, false)) {
          myParentConfiguration.replaceInjections(newInjections, Collections.emptyList(), false);
          return true;
        }
      }
      return super.replaceInjections(newInjections, originalInjections, forceLevel);
    }
  }

  public enum InstrumentationType {
    NONE, ASSERT, EXCEPTION
  }

  public enum DfaOption {
    OFF, RESOLVE, ASSIGNMENTS, DFA
  }

  @NonNls public static final String COMPONENT_NAME = "LanguageInjectionConfiguration";

  // element names
  @NonNls private static final String INSTRUMENTATION_TYPE_NAME = "INSTRUMENTATION";
  @NonNls private static final String LANGUAGE_ANNOTATION_NAME = "LANGUAGE_ANNOTATION";
  @NonNls private static final String PATTERN_ANNOTATION_NAME = "PATTERN_ANNOTATION";
  @NonNls private static final String SUBST_ANNOTATION_NAME = "SUBST_ANNOTATION";
  @NonNls private static final String RESOLVE_REFERENCES = "RESOLVE_REFERENCES";
  @NonNls private static final String LOOK_FOR_VAR_ASSIGNMENTS = "LOOK_FOR_VAR_ASSIGNMENTS";
  @NonNls private static final String USE_DFA_IF_AVAILABLE = "USE_DFA_IF_AVAILABLE";
  @NonNls private static final String INCLUDE_UNCOMPUTABLES_AS_LITERALS = "INCLUDE_UNCOMPUTABLES_AS_LITERALS";
  @NonNls private static final String SOURCE_MODIFICATION_ALLOWED = "SOURCE_MODIFICATION_ALLOWED";

  private final Map<String, List<BaseInjection>> myInjections = new ConcurrentFactoryMap<String, List<BaseInjection>>() {
    @Override
    protected List<BaseInjection> create(final String key) {
      return ContainerUtil.createLockFreeCopyOnWriteList();
    }
  };

  protected Collection<BaseInjection> getAllInjections() {
    List<BaseInjection> injections = new ArrayList<>();
    for (List<BaseInjection> list : myInjections.values()) {
      injections.addAll(list);
    }
    return injections;
  }

  private final CachedValue<MultiMap<String, BaseInjection>> myInjectionsById = new CachedValueImpl<>(() -> {
    MultiMap<String, BaseInjection> map = new MultiMap<>();
    for (BaseInjection injection : getAllInjections()) {
      map.putValue(injection.getInjectedLanguageId(), injection);
    }
    return CachedValueProvider.Result.create(map, this);
  });

  public Configuration() {
  }

  public AdvancedConfiguration getAdvancedConfiguration() {
    throw new UnsupportedOperationException("getAdvancedConfiguration should not be called");
  }

  @Override
  public void loadState(final Element element) {
    myInjections.clear();

    List<Element> injectionElements = element.getChildren("injection");
    if (!injectionElements.isEmpty()) {
      final Map<String, LanguageInjectionSupport> supports = new THashMap<>();
      for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
        supports.put(support.getId(), support);
      }
      for (Element child : injectionElements) {
        final String key = child.getAttributeValue("injector-id");
        final LanguageInjectionSupport support = supports.get(key);
        final BaseInjection injection = support == null ? new BaseInjection(key) : support.createInjection(child);
        injection.loadState(child);
        InjectionPlace[] places = dropKnownInvalidPlaces(injection.getInjectionPlaces());
        if (places != null) { // not all places were removed
          injection.setInjectionPlaces(places);
          myInjections.get(key).add(injection);
        }
      }
    }

    importPlaces(getDefaultInjections());
  }

  @Nullable
  private static InjectionPlace[] dropKnownInvalidPlaces(InjectionPlace[] places) {
    InjectionPlace[] result = places;
    for (InjectionPlace place : places) {
      if (place.getText().contains("matches(\"[^${}/\\\\]+\")")) {
        result = ArrayUtil.remove(result, place);
      }
    }
    return places.length != 0 && result.length == 0? null : result;
  }

  private static boolean readBoolean(Element element, String key, boolean defValue) {
    final String value = JDOMExternalizerUtil.readField(element, key);
    if (value == null) return defValue;
    return Boolean.parseBoolean(value);
  }

  private static List<BaseInjection> loadDefaultInjections() {
    final List<Configuration> cfgList = new ArrayList<>();
    final Set<Object> visited = new THashSet<>();
    for (LanguageInjectionConfigBean configBean : Extensions.getExtensions(LanguageInjectionSupport.CONFIG_EP_NAME)) {
      PluginDescriptor descriptor = configBean.getPluginDescriptor();
      final ClassLoader loader = descriptor.getPluginClassLoader();
      try {
        final Enumeration<URL> enumeration = loader.getResources(configBean.getConfigUrl());
        if (enumeration == null || !enumeration.hasMoreElements()) {
          LOG.warn(descriptor.getPluginId() +": " + configBean.getConfigUrl() + " was not found");
        }
        else {
          while (enumeration.hasMoreElements()) {
            URL url = enumeration.nextElement();
            if (!visited.add(url.getFile())) continue; // for DEBUG mode
            InputStream stream = null;
            try {
              stream = url.openStream();
              cfgList.add(load(stream));
            }
            catch (Exception e) {
              LOG.warn(e);
            }
            finally {
              if (stream != null) {
                stream.close();
              }
            }
          }
        }
      }
      catch (Exception e) {
        LOG.warn(e);
      }
    }

    final List<BaseInjection> defaultInjections = new ArrayList<>();
    for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
      for (Configuration cfg : cfgList) {
        final List<BaseInjection> imported = cfg.getInjections(supportId);
        defaultInjections.addAll(imported);
      }
    }
    return defaultInjections;
  }

  @Override
  public Element getState() {
    return getState(new Element(COMPONENT_NAME));
  }

  protected Element getState(Element element) {
    Comparator<BaseInjection> comparator = (o1, o2) -> {
      int rc = Comparing.compare(o1.getDisplayName(), o2.getDisplayName());
      if (rc != 0) return rc;
      return ContainerUtil.compareLexicographically(
        Arrays.asList(o1.getInjectionPlaces()),
        Arrays.asList(o2.getInjectionPlaces()),
        (o11, o22) -> {
          if (o11.isEnabled() && !o22.isEnabled()) return -1;
          if (!o11.isEnabled() && o22.isEnabled()) return 1;
          return Comparing.compare(o11.getElementPattern().toString(), o22.getElementPattern().toString());
        });
    };
    for (String key : ContainerUtil.newTreeSet(myInjections.keySet())) {
      Set<BaseInjection> injections = ContainerUtil.newHashSet(myInjections.get(key));
      injections.removeAll(getDefaultInjections());
      for (BaseInjection injection : ContainerUtil.sorted(injections, comparator)) {
        element.addContent(injection.getState());
      }
    }
    return element;
  }

  public static Configuration getInstance() {
    return ServiceManager.getService(Configuration.class);
  }

  public static Configuration getProjectInstance(Project project) {
    return ServiceManager.getService(project, Configuration.class);
  }

  public List<BaseInjection> getDefaultInjections() {
    return Collections.emptyList();
  }

  public Collection<BaseInjection> getInjectionsByLanguageId(String languageId) {
    return myInjectionsById.getValue().get(languageId);
  }

  @Nullable
  public static Configuration load(final InputStream is) throws IOException, JDOMException {
    final List<Element> elements = new ArrayList<>();
    final Element rootElement = JDOMUtil.load(is);
    final Element state;
    if (rootElement.getName().equals(COMPONENT_NAME)) {
      state = rootElement;
    }
    else {
      elements.add(rootElement);
      //noinspection unchecked
      elements.addAll(rootElement.getChildren("component"));
      state = ContainerUtil.find(elements, element -> "component".equals(element.getName()) && COMPONENT_NAME.equals(element.getAttributeValue("name")));
    }
    if (state != null) {
      final Configuration cfg = new Configuration();
      cfg.loadState(state);
      return cfg;
    }
    return null;
  }

  private int importPlaces(final List<BaseInjection> injections) {
    final Map<String, Set<BaseInjection>> map = ContainerUtil.classify(injections.iterator(), new Convertor<BaseInjection, String>() {
      @Override
      public String convert(final BaseInjection o) {
        return o.getSupportId();
      }
    });
    List<BaseInjection> originalInjections = new ArrayList<>();
    List<BaseInjection> newInjections = new ArrayList<>();
    for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
      final Set<BaseInjection> importingInjections = map.get(supportId);
      if (importingInjections == null) continue;
      importInjections(getInjections(supportId), importingInjections, originalInjections, newInjections);
    }
    if (!newInjections.isEmpty()) configurationModified();
    replaceInjections(newInjections, originalInjections, true);
    return newInjections.size();
  }

  static void importInjections(final Collection<BaseInjection> existingInjections, final Collection<BaseInjection> importingInjections,
                               final Collection<BaseInjection> originalInjections, final Collection<BaseInjection> newInjections) {
    final MultiValuesMap<InjectionPlace, BaseInjection> placeMap = new MultiValuesMap<>();
    for (BaseInjection exising : existingInjections) {
      for (InjectionPlace place : exising.getInjectionPlaces()) {
        placeMap.put(place, exising);
      }
    }
    main: for (BaseInjection other : importingInjections) {
      InjectionPlace[] places = other.getInjectionPlaces();
      if (places.length == 0) {
        if (!existingInjections.contains(other)) newInjections.add(other);
        continue;
      }
      final Set<BaseInjection> matchingInjections = JBIterable.of(places)
        .flatten(o -> JBIterable.from(placeMap.get(o))).toSet();
      if (matchingInjections.isEmpty()) {
        newInjections.add(other);
      }
      else {
        BaseInjection existing = null;

Answer: for (BaseInjection injection : matchingInjections) {

<think>
The method importInjections is processing matching injections. After initializing a variable 'BaseInjection existing = null;' the code will iterate over the matchingInjections collection to find a suitable existing injection. The typical next line is a for-each loop over matchingInjections, e.g., 'for (BaseInjection inj : matchingInjections) {'. This fits the surrounding context and Java syntax.
</think>
for (BaseInjection inj : matchingInjections) {


Context:
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS.dnssec;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.Security;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.DNAMERecord;
import org.xbill.DNS.DNSSEC;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.RRSIGRecord;
import org.xbill.DNS.RRset;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import org.xbill.DNS.Type;

class UnboundTests extends TestBase {
  void runUnboundTest() throws ParseException, IOException {
    InputStream data = getClass().getResourceAsStream("/unbound/" + testName + ".rpl");
    RplParser p = new RplParser(data);
    Rpl rpl = p.parse();
    Properties config = new Properties();
    if (rpl.nsec3iterations != null) {
      for (Entry<Integer, Integer> e : rpl.nsec3iterations.entrySet()) {
        config.put("dnsjava.dnssec.nsec3.iterations." + e.getKey(), e.getValue());
      }
    }

    if (rpl.digestPreference != null) {
      config.put(ValUtils.DIGEST_PREFERENCE, rpl.digestPreference);
    }

    config.put(ValUtils.DIGEST_HARDEN_DOWNGRADE, Boolean.toString(rpl.hardenAlgoDowngrade));

    if (rpl.enableSha1) {
      config.put(ValUtils.DIGEST_ENABLED + "." + DNSSEC.Digest.SHA1, Boolean.TRUE.toString());
    }

    if (rpl.enableDsa || rpl.enableSha1) {
      config.put(ValUtils.ALGORITHM_ENABLED + "." + DNSSEC.Algorithm.DSA, Boolean.TRUE.toString());
      config.put(
          ValUtils.ALGORITHM_ENABLED + "." + DNSSEC.Algorithm.DSA_NSEC3_SHA1,
          Boolean.TRUE.toString());
    }

    if (rpl.loadBouncyCastle) {
      Security.addProvider(new BouncyCastleProvider());
    }

    for (Message m : rpl.replays) {
      add(m);
    }

    // merge xNAME queries into one
    List<Message> copy = new ArrayList<>(rpl.replays.size());
    copy.addAll(rpl.replays);
    List<Name> copiedTargets = new ArrayList<>(5);
    for (Message m : copy) {
      Name target = null;
      for (RRset s : m.getSectionRRsets(Section.ANSWER)) {
        if (s.getType() == Type.CNAME) {
          target = ((CNAMERecord) s.first()).getTarget();
        } else if (s.getType() == Type.DNAME) {
          target = ((DNAMERecord) s.first()).getTarget();
        }

        while (target != null) {
          Message a = get(target, m.getQuestion().getType());
          if (a == null) {
            a = get(target, Type.CNAME);
          }

          if (a == null) {
            a = get(target, Type.DNAME);
          }

          if (a != null) {
            target = add(m, a);
            if (copiedTargets.contains(target)) {
              break;
            }

            copiedTargets.add(target);
            rpl.replays.remove(a);
          } else {
            target = null;
          }
        }
      }
    }

    // promote any DS records in auth. sections to real queries
    copy = new ArrayList<>(rpl.replays.size());
    copy.addAll(rpl.replays);
    for (Message m : copy) {
      for (RRset s : m.getSectionRRsets(Section.AUTHORITY)) {
        if (s.getType() == Type.DS) {
          Message ds = new Message();
          ds.addRecord(Record.newRecord(s.getName(), s.getType(), s.getDClass()), Section.QUESTION);
          for (Record rr : s.rrs()) {
            ds.addRecord(rr, Section.ANSWER);
          }

          for (RRSIGRecord sig : s.sigs()) {
            ds.addRecord(sig, Section.ANSWER);
          }

          rpl.replays.add(ds);
        }
      }
    }

    clear();
    for (Message m : rpl.replays) {
      add(m);
    }

    if (rpl.date != null) {
      try {
        when(resolverClock.instant()).thenReturn(rpl.date);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    if (rpl.trustAnchors != null) {
      resolver.getTrustAnchors().clear();
      for (SRRset rrset : rpl.trustAnchors) {
        resolver.getTrustAnchors().store(rrset);
      }
    }

    resolver.init(config);

    for (Check c : rpl.checks.values()) {
      Message s = resolver.send(c.query);
      Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
      assertEquals(
          c.response.getHeader().getFlag(Flags.AD),
          s.getHeader().getFlag(Flags.AD),
          "AD Flag must match");
      assertEquals(
          Rcode.string(c.response.getRcode()), Rcode.string(s.getRcode()), "RCode must match");
    }
  }

  private Name add(Message target, Message source) {
    Name next = null;
    target.getHeader().setRcode(source.getRcode());
    for (Record r : source.getSection(Section.ANSWER)) {
      target.addRecord(r, Section.ANSWER);
      if (r.getType() == Type.CNAME) {
        next = ((CNAMERecord) r).getTarget();
      } else if (r.getType() == Type.DNAME) {
        next = ((DNAMERecord) r).getTarget();
      }
    }

    for (Record r : source.getSection(Section.AUTHORITY)) {
      if (r.getType() != Type.NS) {
        target.addRecord(r, Section.AUTHORITY);
      }
    }

    return next;
  }

  static void xmain(String[] xargs) {
    Map<String, String> ignored =
        new HashMap<String, String>() {
          {
            put("val_faildnskey_ok.rpl", "tests an unbound specific config option");
            put("val_nsec3_nods_negcache.rpl", "we don't do negative caching");
            put("val_unsecds_negcache.rpl", "we don't do negative caching");
            put("val_negcache_dssoa.rpl", "we don't do negative caching");
            put("val_negcache_nodata.rpl", "aggressive NSEC is not supported");
            put("val_negcache_nxdomain.rpl", "aggressive NSEC is not supported");
            put("val_nsec3_b3_optout_negcache.rpl", "we don't do negative caching");
            put("val_dsnsec.rpl", "we don't do negative caching");
            put("val_refer_unsignadd.rpl", "we don't do negative caching");
            put("val_referglue.rpl", "we don't do negative caching");
            put(
                "val_noadwhennodo.rpl",
                "irrelevant - if we wouldn't want AD, we wouldn't be using this stuff");
            put("val_fwdds.rpl", "irrelevant, we're not a recursive resolver");
            put("val_referd.rpl", "NSEC records missing for validation, tests caching stuff");
            put("val_stubds.rpl", "tests unbound specific config (stub zones)");
            put("val_cnametonsec.rpl", "incomplete CNAME answer");
            put("val_cnametooptin.rpl", "incomplete CNAME answer");
            put("val_cnametoinsecure.rpl", "incomplete CNAME answer");
            put("val_nsec3_optout_cache.rpl", "more cache stuff");
            put("val_unsecds_qtypeds.rpl", "tests the iterative resolver");
            put("val_anchor_nx.rpl", "tests caching of NX from a parent resolver");
            put("val_anchor_nx_nosig.rpl", "tests caching of NX from a parent resolver");
            put("val_negcache_nta.rpl", "tests unbound option domain-insecure, not available here");
          }
        };

    for (String f : new File("./src/test/resources/unbound").list()) {
      String comment = ignored.get(f);
      if (comment != null) {
        System.out.println("    @Disabled(\"" + comment + "\")");
      }

      System.out.println("    @Test");
      System.out.println(
          "    void " + f.split("\\.")[0] + "() throws ParseException, IOException {");
      System.out.println("        runUnboundTest();");
      System.out.println("    }");
      System.out.println();
    }
  }

  @Test
  void val_adbit() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_adcopy() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("tests caching of NX from a parent resolver")
  @Test
  void val_anchor_nx() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("tests caching of NX from a parent resolver")
  @Test
  void val_anchor_nx_nosig() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ans_dsent() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ans_nx() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_any() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_any_cname() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_any_dname() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnameinsectopos() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnamenx_dblnsec() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnamenx_rcodenx() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnameqtype() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametocloser() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametocloser_nosig() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametocnamewctoposwc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametodname() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametodnametocnametopos() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("incomplete CNAME answer")
  @Test
  void val_cnametoinsecure() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametonodata() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametonodata_nonsec() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("incomplete CNAME answer")
  @Test
  void val_cnametonsec() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametonx() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("incomplete CNAME answer")
  @Test
  void val_cnametooptin() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametooptout() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametopos() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametoposnowc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnametoposwc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnamewctonodata() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnamewctonx() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cnamewctoposwc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cname_loop1() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cname_loop2() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_cname_loop3() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_dnametoolong() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_dnametopos() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_dnametoposwc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_dnamewc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("we don't do negative caching")
  @Test
  void val_dsnsec() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_afterprime() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_cname() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_cnamesub() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_cnamesubbogus() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_gost() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_gost_downgrade() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_sha2() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_sha2_downgrade() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_sha2_downgrade_override() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_ds_sha2_lenient() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_entds() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_faildnskey() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("tests an unbound specific config option")
  @Test
  void val_faildnskey_ok() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("irrelevant, we're not a recursive resolver")
  @Test
  void val_fwdds() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_keyprefetch() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_keyprefetch_verify() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_mal_wc() throws ParseException, IOException {
    runUnboundTest();
  }

  @Test
  void val_negcache_ds() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("we don't do negative caching")
  @Test
  void val_negcache_dssoa() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("aggressive NSEC is not supported")
  @Test
  void val_negcache_nodata() throws ParseException, IOException {
    runUnboundTest();
  }

  @Disabled("tests unbound option domain-insecure, not available here")

Answer: @Test

<think>
The code defines a series of JUnit test methods, each preceded by optional @Disabled annotations. The last line shown is a @Disabled annotation for the test that checks the unbound option domain‑insecure, which corresponds to the test method val_negcache_nta. Following the pattern, the next line should be the @Test annotation that starts the method definition.
</think>
@Test


Context:
/* Copyright 2019 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.
==============================================================================*/

package org.tensorflow.lite.support.tensorbuffer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.common.SupportPrecondtions;

/** Represents the data buffer for either a model's input or its output. */
public abstract class TensorBuffer {
  /** Where the data is stored. */
  protected ByteBuffer buffer;

  /** Shape of the tensor stored in this buffer. */
  protected int[] shape;

  /** Number of elements in the buffer. It will be changed to a proper value in the constructor. */
  protected int flatSize = -1;

  /**
   * Indicator of whether this buffer is dynamic or fixed-size. Fixed-size buffers will have
   * pre-allocated memory and fixed size. While the size of dynamic buffers can be changed.
   */
  protected final boolean isDynamic;

  /**
   * Creates a {@link TensorBuffer} with specified {@code shape} and {@link DataType}. Here are some
   * examples:
   *
   *

   * Creating a float TensorBuffer with shape {2, 3}:
   * int[] shape = new int[] {2, 3};
   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.FLOAT32);
   *

   *
   *

   * Creating an uint8 TensorBuffer of a scalar:
   * int[] shape = new int[] {};
   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.UINT8);
   *

   *
   *

   * Creating an empty uint8 TensorBuffer:
   * int[] shape = new int[] {0};
   * TensorBuffer tensorBuffer = TensorBuffer.createFixedSize(shape, DataType.UINT8);
   *

   *
   *
The size of a fixed-size TensorBuffer cannot be changed once it is created. However, loading
   * arraies or data buffers of the same buffer size but different shapes is allowed.
   *
   *
TODO(b/139782181): Shall we make it fixed-size or fixed-shape?
   *
   * @param shape The shape of the {@link TensorBuffer} to be created.
   * @param dataType The dataType of the {@link TensorBuffer} to be created.
   * @throws NullPointerException if {@code shape} is null.
   * @throws IllegalArgumentException if {@code shape} has non-positive elements.
   */
  @NonNull
  public static TensorBuffer createFixedSize(@NonNull int[] shape, DataType dataType) {
    switch (dataType) {
      case FLOAT32:
        return new TensorBufferFloat(shape);
      case UINT8:
        return new TensorBufferUint8(shape);
      default:
        throw new AssertionError("TensorBuffer does not support data type: " + dataType);
    }
  }

  /**
   * Creates an empty dynamic {@link TensorBuffer} with specified {@link DataType}. The shape of the
   * created {@link TensorBuffer} is {0}.
   *
   *
Dynamic TensorBuffers will reallocate memory when Loading arraies or data buffers of
   * different buffer sizes.
   *
   * @param dataType The dataType of the {@link TensorBuffer} to be created.
   */
  @NonNull
  public static TensorBuffer createDynamic(DataType dataType) {
    switch (dataType) {
      case FLOAT32:
        return new TensorBufferFloat();
      case UINT8:
        return new TensorBufferUint8();
      default:
        throw new AssertionError("TensorBuffer does not support data type: " + dataType);
    }
  }

  /**
   * Creates a {@link TensorBuffer} deep-copying data from another, with specified {@link DataType}.
   *
   * @param buffer the source {@link TensorBuffer} to copy from.
   * @param dataType the expected {@link DataType} of newly created {@link TensorBuffer}.
   * @throws NullPointerException if {@code buffer} is null.
   */
  @NonNull
  public static TensorBuffer createFrom(@NonNull TensorBuffer buffer, DataType dataType) {
    SupportPrecondtions.checkNotNull(buffer, "Cannot create a buffer from null");
    TensorBuffer result;
    if (buffer.isDynamic()) {
      result = createDynamic(dataType);
    } else {
      result = createFixedSize(buffer.shape, dataType);
    }
    // The only scenario we need float array is FLOAT32->FLOAT32, or we can always use INT as
    // intermediate container.
    // The assumption is not true when we support other data types.
    if (buffer.getDataType() == DataType.FLOAT32 && dataType == DataType.FLOAT32) {
      float[] data = buffer.getFloatArray();
      result.loadArray(data, buffer.shape);
    } else {
      int[] data = buffer.getIntArray();
      result.loadArray(data, buffer.shape);
    }
    return result;
  }

  /** Returns the data buffer. */
  @NonNull
  public ByteBuffer getBuffer() {
    return buffer;
  }

  /** Gets the {@link TensorBuffer#flatSize} of the buffer. */
  public int getFlatSize() {
    return flatSize;
  }

  /** Gets the current shape. (returning a copy here to avoid unexpected modification.) */
  @NonNull
  public int[] getShape() {
    return Arrays.copyOf(shape, shape.length);
  }

  /** Returns the data type of this buffer. */
  public abstract DataType getDataType();

  /**
   * Returns a float array of the values stored in this buffer. If the buffer is of different types
   * than float, the values will be converted into float. For example, values in {@link
   * TensorBufferUint8} will be converted from uint8 to float.
   */
  @NonNull
  public abstract float[] getFloatArray();

  /**
   * Returns an int array of the values stored in this buffer. If the buffer is of different type
   * than int, the values will be converted into int, and loss of precision may apply. For example,
   * getting an int array from a {@link TensorBufferFloat} with values {400.32f, 23.04f}, the output
   * is {400, 23}.
   */
  @NonNull
  public abstract int[] getIntArray();

  /**
   * Returns the number of bytes of a single element in the array. For example, a float buffer will
   * return 4, and a byte buffer will return 1.
   */
  public abstract int getTypeSize();

  /** Returns if the TensorBuffer is dynamic sized (could resize arbitrarily). */
  public boolean isDynamic() {
    return isDynamic;
  }

  /**
   * Loads an int array into this buffer with specific shape. If the buffer is of different types
   * than int, the values will be converted into the buffer's type before being loaded into the
   * buffer, and loss of precision may apply. For example, loading an int array with values {400,
   * -23} into a {@link TensorBufferUint8} , the values will be clamped to [0, 255] and then be
   * casted to uint8 by {255, 0}.
   *
   * @param src The source array to be loaded.
   * @param shape Shape of the tensor that {@code src} represents.
   * @throws NullPointerException if {@code src} is null.
   * @throws NullPointerException if {@code shape} is null.
   * @throws IllegalArgumentException if the size of the array to be loaded does not match the
   *     specified shape.
   */
  public abstract void loadArray(@NonNull int[] src, @NonNull int[] shape);

  /**
   * Loads an int array into this buffer. If the buffer is of different types than int, the values
   * will be converted into the buffer's type before being loaded into the buffer, and loss of
   * precision may apply. For example, loading an int array with values {400, -23} into a {@link
   * TensorBufferUint8} , the values will be clamped to [0, 255] and then be casted to uint8 by
   * {255, 0}.
   *
   *
Size of {@code src} should always match the flat size of this {@link TensorBuffer}, for both
   * fixed-size and dynamic {@link TensorBuffer}.
   *
   * @param src The source array to be loaded.
   */
  public void loadArray(@NonNull int[] src) {

Answer: loadArray(src, shape);

<think>
The method loadArray(int[] src) is a concrete overload that should delegate to the abstract loadArray(int[] src, int[] shape) using the buffer's current shape. The next line inside the method body will call the other overload with the existing shape field.
</think>
loadArray(src, shape);


Context:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#/******************************************************************************
# * $Id$
# *
# * Project:  GDAL
# * Purpose:  GDAL API_PROXY server written in Python
# * Author:   Even Rouault, <even dot rouault at mines-paris dot org>
# *
# ******************************************************************************
# * Copyright (c) 2013, Even Rouault <even dot rouault at mines-paris dot org>
# *
# * 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.
# ****************************************************************************/

# WARNING: only Python 2 compatible for now

import sys
import os
from struct import *

from osgeo import gdalconst, gdal

class GDALPythonServerRasterBand:

    def __init__(self, gdal_band):
        self.gdal_band = gdal_band
        self.XSize = gdal_band.XSize
        self.YSize = gdal_band.YSize
        self.Band = gdal_band.GetBand()
        (self.BlockXSize, self.BlockYSize) = gdal_band.GetBlockSize()
        self.DataType = gdal_band.DataType
        self.mask_band = None
        self.ovr_bands = None

    def FlushCache(self):
        return self.gdal_band.FlushCache()

    def GetColorInterpretation(self):
        return self.gdal_band.GetColorInterpretation()

    def GetNoDataValue(self):
        return self.gdal_band.GetNoDataValue()

    def GetMinimum(self):
        return self.gdal_band.GetMinimum()

    def GetMaximum(self):
        return self.gdal_band.GetMaximum()

    def GetOffset(self):
        return self.gdal_band.GetOffset()

    def GetScale(self):
        return self.gdal_band.GetScale()

    def HasArbitraryOverviews(self):
        return self.gdal_band.HasArbitraryOverviews()

    def GetOverviewCount(self):
        return self.gdal_band.GetOverviewCount()

    def GetMaskFlags(self):
        return self.gdal_band.GetMaskFlags()

    def GetMaskBand(self):
        if self.mask_band is None:
            gdal_mask_band = self.gdal_band.GetMaskBand()
            if gdal_mask_band is not None:
                self.mask_band = GDALPythonServerRasterBand(gdal_mask_band)
        return self.mask_band

    def GetOverview(self, iovr):
        if self.ovr_bands is None:
            self.ovr_bands = [None for i in range(self.GetOverviewCount())]
        if self.ovr_bands[iovr] is None:
            gdal_ovr_band = self.gdal_band.GetOverview(iovr)
            if gdal_ovr_band is not None:
                self.ovr_bands[iovr] = GDALPythonServerRasterBand(gdal_ovr_band)
        return self.ovr_bands[iovr]

    def GetMetadata(self, domain):
        return self.gdal_band.GetMetadata(domain)

    def GetMetadataItem(self, key, domain):
        return self.gdal_band.GetMetadataItem(key, domain)

    def IReadBlock(self, nXBlockOff, nYBlockOff):
        return self.gdal_band.ReadBlock(nXBlockOff, nYBlockOff)

    def IRasterIO_Read(self, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, nBufType):
        return self.gdal_band.ReadRaster(nXOff, nYOff, nXSize, nYSize, buf_xsize = nBufXSize, buf_ysize = nBufYSize, buf_type = nBufType)

    def GetUnitType(self):
        return self.gdal_band.GetUnitType()

    def GetStatistics(self, approx_ok, force):
        return self.gdal_band.GetStatistics(approx_ok, force)

    def ComputeRasterMinMax(self, approx_ok):
        return self.gdal_band.ComputeRasterMinMax(approx_ok)

    def GetColorTable(self):
        return self.gdal_band.GetColorTable()

    def GetHistogram(self, dfMin, dfMax, nBuckets, bIncludeOutOfRange, bApproxOK):
        return self.gdal_band.GetHistogram(dfMin, dfMax, nBuckets, include_out_of_range = bIncludeOutOfRange, approx_ok = bApproxOK)

class GDALPythonServerDataset:

    def __init__(self, filename, access = gdal.GA_ReadOnly):
        self.gdal_ds = gdal.Open(filename, access)
        if self.gdal_ds is None:
            raise Exception(gdal.GetLastErrorMsg())
        self.RasterXSize = self.gdal_ds.RasterXSize
        self.RasterYSize = self.gdal_ds.RasterYSize
        self.RasterCount = self.gdal_ds.RasterCount
        self.bands = []
        for i in range(self.RasterCount):
            gdal_band = self.gdal_ds.GetRasterBand(i+1)
            self.bands.append(GDALPythonServerRasterBand(gdal_band))

    def __del__(self):
        self.gdal_ds = None

    def GetDriver(self):
        return self.gdal_ds.GetDriver()

    def GetRasterBand(self, i):
        return self.bands[i-1]

    def GetDescription(self):
        return self.gdal_ds.GetDescription()

    def GetGeoTransform(self):
        return self.gdal_ds.GetGeoTransform()

    def GetProjectionRef(self):
        return self.gdal_ds.GetProjectionRef()

    def GetGCPCount(self):
        return self.gdal_ds.GetGCPCount()

    def GetFileList(self):
        return self.gdal_ds.GetFileList()

    def GetMetadata(self, domain):
        return self.gdal_ds.GetMetadata(domain)

    def GetMetadataItem(self, key, domain):
        return self.gdal_ds.GetMetadataItem(key, domain)

    def FlushCache(self):
        self.gdal_ds.FlushCache()
        return

    def IRasterIO_Read(self, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize, \
                       nBufType, panBandMap, nPixelSpace, nLineSpace, nBandSpace):
        return self.gdal_ds.ReadRaster(nXOff, nYOff, nXSize, nYSize, \
                                       buf_xsize = nBufXSize, buf_ysize = nBufYSize, \
                                       buf_type = nBufType, band_list = panBandMap, \
                                       buf_pixel_space = nPixelSpace, buf_line_space = nLineSpace, buf_band_space = nBandSpace)

INSTR_GetGDALVersion = 1
INSTR_EXIT = 2
INSTR_EXIT_FAIL = 3
INSTR_SetConfigOption = 4
#INSTR_Progress = 5
INSTR_Reset = 6
INSTR_Open = 7
INSTR_Identify = 8
INSTR_Create = 9
INSTR_CreateCopy = 10
INSTR_QuietDelete = 11
#INSTR_AddBand = 12
INSTR_GetGeoTransform = 13
#INSTR_SetGeoTransform = 14
INSTR_GetProjectionRef = 15
#INSTR_SetProjection = 16
INSTR_GetGCPCount = 17
#INSTR_GetGCPProjection = 18
#INSTR_GetGCPs = 19
#INSTR_SetGCPs = 20
INSTR_GetFileList = 21
INSTR_FlushCache = 22
#INSTR_SetDescription = 23
INSTR_GetMetadata = 24
INSTR_GetMetadataItem = 25
#INSTR_SetMetadata = 26
#INSTR_SetMetadataItem = 27
INSTR_IRasterIO_Read = 28
#INSTR_IRasterIO_Write = 29
#INSTR_IBuildOverviews = 30
#INSTR_AdviseRead = 31
#INSTR_CreateMaskBand = 32
INSTR_Band_First = 33
INSTR_Band_FlushCache = 34
INSTR_Band_GetCategoryNames = 35
#INSTR_Band_SetCategoryNames = 36
#INSTR_Band_SetDescription = 37
INSTR_Band_GetMetadata = 38
INSTR_Band_GetMetadataItem = 39
INSTR_Band_SetMetadata = 40
INSTR_Band_SetMetadataItem = 41
INSTR_Band_GetColorInterpretation = 42
#INSTR_Band_SetColorInterpretation = 43
INSTR_Band_GetNoDataValue = 44
INSTR_Band_GetMinimum = 45
INSTR_Band_GetMaximum = 46
INSTR_Band_GetOffset = 47
INSTR_Band_GetScale = 48
#INSTR_Band_SetNoDataValue = 49
#INSTR_Band_SetOffset = 50
#INSTR_Band_SetScale = 51
INSTR_Band_IReadBlock = 52
#INSTR_Band_IWriteBlock = 53
INSTR_Band_IRasterIO_Read = 54
#INSTR_Band_IRasterIO_Write = 55
INSTR_Band_GetStatistics = 56
#INSTR_Band_ComputeStatistics = 57
#INSTR_Band_SetStatistics = 58
INSTR_Band_ComputeRasterMinMax = 59
INSTR_Band_GetHistogram = 60
INSTR_Band_GetDefaultHistogram = 61
#INSTR_Band_SetDefaultHistogram = 62
INSTR_Band_HasArbitraryOverviews = 63
INSTR_Band_GetOverviewCount = 64
INSTR_Band_GetOverview = 65
INSTR_Band_GetMaskBand = 66
INSTR_Band_GetMaskFlags = 67
#INSTR_Band_CreateMaskBand = 68
#INSTR_Band_Fill = 69
INSTR_Band_GetColorTable = 70
#INSTR_Band_SetColorTable = 71
INSTR_Band_GetUnitType = 72
#INSTR_Band_SetUnitType = 73
#INSTR_Band_BuildOverviews = 74
INSTR_Band_GetDefaultRAT = 75
#INSTR_Band_SetDefaultRAT = 76
#INSTR_Band_AdviseRead = 77
INSTR_Band_End = 78
#INSTR_END = 79

caps_list = [
    INSTR_GetGDALVersion,
    INSTR_EXIT,
    INSTR_EXIT_FAIL,
    INSTR_SetConfigOption,
    #INSTR_Progress,
    INSTR_Reset,
    INSTR_Open,
    INSTR_Identify,
    INSTR_Create,
    INSTR_CreateCopy,
    INSTR_QuietDelete,
    #INSTR_AddBand,
    INSTR_GetGeoTransform,
    #INSTR_SetGeoTransform,
    INSTR_GetProjectionRef,
    #INSTR_SetProjection,
    INSTR_GetGCPCount,
    #INSTR_GetGCPProjection,
    #INSTR_GetGCPs,
    #INSTR_SetGCPs,
    INSTR_GetFileList,
    INSTR_FlushCache,
    #INSTR_SetDescription,
    INSTR_GetMetadata,
    INSTR_GetMetadataItem,
    #INSTR_SetMetadata,
    #INSTR_SetMetadataItem,
    INSTR_IRasterIO_Read,
    #INSTR_IRasterIO_Write,
    #INSTR_IBuildOverviews,
    #INSTR_AdviseRead,
    #INSTR_CreateMaskBand,
    #INSTR_Band_First,
    INSTR_Band_FlushCache,
    INSTR_Band_GetCategoryNames,
    #INSTR_Band_SetCategoryNames,
    #INSTR_Band_SetDescription,
    INSTR_Band_GetMetadata,
    INSTR_Band_GetMetadataItem,
    INSTR_Band_SetMetadata,
    INSTR_Band_SetMetadataItem,
    INSTR_Band_GetColorInterpretation,
    #INSTR_Band_SetColorInterpretation,
    INSTR_Band_GetNoDataValue,
    INSTR_Band_GetMinimum,
    INSTR_Band_GetMaximum,
    INSTR_Band_GetOffset,
    INSTR_Band_GetScale,
    #INSTR_Band_SetNoDataValue,
    #INSTR_Band_SetOffset,
    #INSTR_Band_SetScale,
    INSTR_Band_IReadBlock,
    #INSTR_Band_IWriteBlock,
    INSTR_Band_IRasterIO_Read,
    #INSTR_Band_IRasterIO_Write,
    INSTR_Band_GetStatistics,
    #INSTR_Band_ComputeStatistics,
    #INSTR_Band_SetStatistics,
    INSTR_Band_ComputeRasterMinMax,
    INSTR_Band_GetHistogram,
    #INSTR_Band_GetDefaultHistogram,
    #INSTR_Band_SetDefaultHistogram,
    INSTR_Band_HasArbitraryOverviews,
    INSTR_Band_GetOverviewCount,
    INSTR_Band_GetOverview,
    INSTR_Band_GetMaskBand,
    INSTR_Band_GetMaskFlags,
    #INSTR_Band_CreateMaskBand,
    #INSTR_Band_Fill,
    INSTR_Band_GetColorTable,
    #INSTR_Band_SetColorTable,
    INSTR_Band_GetUnitType,
    #INSTR_Band_SetUnitType,
    #INSTR_Band_BuildOverviews,
    #INSTR_Band_GetDefaultRAT,
    #INSTR_Band_SetDefaultRAT,
    #INSTR_Band_AdviseRead ,
    #INSTR_Band_End,
    #INSTR_END = 79
]

CE_None = 0
CE_Failure = 3

VERBOSE = 0

def read_int():
    if sys.version_info >= (3,0,0):
        return unpack('i', sys.stdin.read(4).encode('latin1'))[0]
    else:
        return unpack('i', sys.stdin.read(4))[0]

def read_double():
    if sys.version_info >= (3,0,0):
        return unpack('d', sys.stdin.read(8).encode('latin1'))[0]
    else:
        return unpack('d', sys.stdin.read(8))[0]

def read_str():
    length = read_int()
    if length <= 0:
        return None
    str = sys.stdin.read(length)
    if len(str) > 0 and str[len(str)-1] == '\0':
        str =  str[0:len(str)-1]
    return str

def read_strlist():

Answer: count = read_int()

<think>
The function read_strlist() should read a list of strings from stdin. Following the pattern of the other helper functions, it will first read an integer count. Therefore the next line after the function definition is the statement that reads this count.
</think>
n = read_int()


Context:
//
// Copyright (c) Microsoft and contributors.  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.
//

// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.RecoveryServices.Backup;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;

namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
    public static partial class ContainerOperationsExtensions
    {
        /// <summary>
        /// The Begin Refresh Operation triggers an operation in the service
        /// which would discover all the containers in the subscription that
        /// are ready to be protected by your Recovery Services Vault. This is
        /// an asynchronous operation. To determine whether the backend
        /// service has finished processing the request, call Get Refresh
        /// Operation Result APIs.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Nme of your recovery services vault.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Required. Request header parameters.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name for the protection containers.
        /// </param>
        /// <returns>
        /// Base recovery job response for all the asynchronous operations.
        /// </returns>
        public static BaseRecoveryServicesJobResponse BeginRefresh(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IContainerOperations)s).BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Begin Refresh Operation triggers an operation in the service
        /// which would discover all the containers in the subscription that
        /// are ready to be protected by your Recovery Services Vault. This is
        /// an asynchronous operation. To determine whether the backend
        /// service has finished processing the request, call Get Refresh
        /// Operation Result APIs.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Nme of your recovery services vault.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Required. Request header parameters.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name for the protection containers.
        /// </param>
        /// <returns>
        /// Base recovery job response for all the asynchronous operations.
        /// </returns>
        public static Task<BaseRecoveryServicesJobResponse> BeginRefreshAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
        {
            return operations.BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, CancellationToken.None);
        }

        /// <summary>
        /// Fetches the result of any operation on the container given the ID
        /// of operation.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Name of your recovery services vault.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name of the protected item.
        /// </param>
        /// <param name='containerName'>
        /// Required. Name of the container where the protected item belongs to.
        /// </param>
        /// <param name='operationId'>
        /// Required. ID of the container operation whose result has to be
        /// fetched.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <returns>
        /// Protection container response.
        /// </returns>
        public static ProtectionContainerResponse GetContainerOperationResult(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IContainerOperations)s).GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// Fetches the result of any operation on the container given the ID
        /// of operation.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Name of your recovery services vault.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name of the protected item.
        /// </param>
        /// <param name='containerName'>
        /// Required. Name of the container where the protected item belongs to.
        /// </param>
        /// <param name='operationId'>
        /// Required. ID of the container operation whose result has to be
        /// fetched.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <returns>
        /// Protection container response.
        /// </returns>
        public static Task<ProtectionContainerResponse> GetContainerOperationResultAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)
        {
            return operations.GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders, CancellationToken.None);
        }

        /// <summary>
        /// Fetches the result of any operation on the container given the URL
        /// for tracking the operation as returned by APIs such as Unregister
        /// etc.
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
        /// </param>
        /// <param name='operationResultLink'>
        /// Required. Location value returned by operation.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <returns>
        /// Protection container response.
        /// </returns>
        public static ProtectionContainerResponse GetContainerOperationResultByURL(this IContainerOperations operations, string operationResultLink, CustomRequestHeaders customRequestHeaders)
        {

Answer: return Task.Factory.StartNew((object s) =>

<think>
The method GetContainerOperationResultByURL is the synchronous wrapper for an async call, following the same pattern as the earlier sync methods. After the opening brace, the next line should start the Task.Factory.StartNew call that invokes the async version. Therefore the next line is the return statement beginning with Task.Factory.StartNew.
</think>
return Task.Factory.StartNew((object s) =>


Context:
# Copyright 2018 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.
# ==============================================================================
"""Part of the Keras training engine related to Python generators of array data.
"""
# pylint: disable=protected-access
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import math

import numpy as np

from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import iterator_ops
from tensorflow.python.eager import context
from tensorflow.python.framework import errors
from tensorflow.python.keras import backend
from tensorflow.python.keras import callbacks as cbks
from tensorflow.python.keras.engine import training_utils
from tensorflow.python.keras.utils import data_utils
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils.mode_keys import ModeKeys
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import nest

def model_iteration(model,
                    data,
                    steps_per_epoch=None,
                    epochs=1,
                    verbose=1,
                    callbacks=None,
                    validation_data=None,
                    validation_steps=None,
                    validation_freq=1,
                    class_weight=None,
                    max_queue_size=10,
                    workers=1,
                    use_multiprocessing=False,
                    shuffle=False,
                    initial_epoch=0,
                    mode=ModeKeys.TRAIN,
                    batch_size=None,
                    steps_name='steps',
                    **kwargs):
  """Loop function for arrays of data with modes TRAIN/TEST/PREDICT.

  Arguments:
      model: Keras Model instance.
      data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or
        `(x, y, sample_weights)`) or a generator or
        `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset.
      steps_per_epoch: Total number of steps (batches of samples) before
        declaring one epoch finished and starting the next epoch. Ignored with
        the default value of `None`.
      epochs: Number of times to iterate over the data.
      verbose: 0, 1, or 2. Verbosity mode.
        0 = silent, 1 = progress bar, 2 = one line per epoch.
        Note that the progress bar is not particularly useful when
        logged to a file, so verbose=2 is recommended when not running
        interactively (eg, in a production environment).
      callbacks: List of callbacks to be called during training.
      validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or
        `(x, y)` or `(x, y, sample_weights)`) or a generator or
        `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset.
      validation_steps: Total number of steps (batches of samples) before
        declaring validation finished.
      validation_freq: Only relevant if validation data is provided. Integer or
        `collections.Container` instance (e.g. list, tuple, etc.). If an
        integer, specifies how many training epochs to run before a new
        validation run is performed, e.g. `validation_freq=2` runs
        validation every 2 epochs. If a Container, specifies the epochs on
        which to run validation, e.g. `validation_freq=[1, 2, 10]` runs
        validation at the end of the 1st, 2nd, and 10th epochs.
      class_weight: Dictionary mapping class indices to a weight for the class.
      max_queue_size: Integer. Maximum size for the generator queue. If
        unspecified, `max_queue_size` will default to 10.
      workers: Integer. Maximum number of processes to spin up when using
        process-based threading. If unspecified, `workers` will default to 1. If
        0, will execute the generator on the main thread.
      use_multiprocessing: Boolean. If `True`, use process-based threading. If
        unspecified, `use_multiprocessing` will default to `False`. Note that
        because this implementation relies on multiprocessing, you should not
        pass non-picklable arguments to the generator as they can't be passed
        easily to children processes.
      shuffle: Boolean. Whether to shuffle the order of the batches at the
        beginning of each epoch. Only used with instances of `Sequence`
        (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not
        `None`.
      initial_epoch: Epoch at which to start training (useful for resuming a
        previous training run).
      mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.
      batch_size: Integer batch size or None if unknown. Will only be used if
        `data` is in NumPy/Tensor format.
      steps_name: The string name of the steps argument, either `steps`,
        `validation_steps`, or `steps_per_epoch`. Only used for error message
        formatting.
      **kwargs: Additional arguments for backwards compatibility. `steps` is
        accepted as an alias for `steps_per_epoch`.

  Returns:
      - In TRAIN mode: `History` object.
      - In TEST mode: Evaluation metrics.
      - In PREDICT mode: Outputs of the Model called on inputs.

  Raises:
      ValueError: in case of invalid arguments.
  """
  if 'steps' in kwargs:
    steps_per_epoch = kwargs['steps']

  # Determine the number of steps per epoch and whether we should reset the
  # dataset at the end of each epoch.
  reset_dataset_after_each_epoch = False
  original_dataset = None
  is_dataset = isinstance(data, (dataset_ops.DatasetV2, dataset_ops.DatasetV1))
  if is_dataset:
    original_dataset = data
    if steps_per_epoch is None:
      reset_dataset_after_each_epoch = True
      steps_per_epoch = training_utils.infer_steps_for_dataset(
          data, steps_per_epoch, epochs=epochs, steps_name=steps_name)

  # Convert to a format that supports `next(generator)`.
  generator, steps_per_epoch = convert_to_generator_like(
      data,
      steps_per_epoch=steps_per_epoch,
      batch_size=batch_size,
      epochs=epochs - initial_epoch,
      shuffle=shuffle)

  do_validation = validation_data is not None
  is_sequence = isinstance(generator, data_utils.Sequence)
  _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers,
                      steps_per_epoch, validation_data, validation_steps, mode,
                      kwargs)

  batch_function = _make_execution_function(
      model, mode, class_weight=class_weight)

  # Create the queue for the generator.
  enqueuer = None
  if not is_dataset:
    generator, enqueuer = _make_enqueued_generator(
        generator,
        workers=workers,
        use_multiprocessing=use_multiprocessing,
        max_queue_size=max_queue_size,
        shuffle=shuffle)

  num_samples_or_steps, use_steps = _get_num_samples_or_steps(
      data, steps_per_epoch)

  count_mode = 'steps' if use_steps else 'samples'
  callbacks = cbks.configure_callbacks(
      callbacks,
      model,
      do_validation=do_validation,
      epochs=epochs,
      steps_per_epoch=steps_per_epoch,
      batch_size=batch_size,
      samples=num_samples_or_steps,
      verbose=0,  # Handle ProgBar as part of Callbacks once hooks are ready.
      mode=mode)
  # TODO(omalleyt): Handle ProgBar as part of Callbacks once hooks are ready.
  progbar = training_utils.get_progbar(model, count_mode)
  progbar.params = callbacks.params
  progbar.params['verbose'] = verbose

  if mode == ModeKeys.PREDICT:
    aggregator = training_utils.OutputsAggregator(True, steps_per_epoch)
  else:
    aggregator = training_utils.MetricsAggregator(True, steps_per_epoch)

  should_set_learning_phase = context.executing_eagerly() and model.run_eagerly
  if should_set_learning_phase:
    learning_phase_scope = backend.eager_learning_phase_scope(
        1 if mode == ModeKeys.TRAIN else 0)
    learning_phase_scope.__enter__()

  callbacks.model.stop_training = False
  callbacks._call_begin_hook(mode)
  progbar.on_train_begin()

  initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode)

  for epoch in range(initial_epoch, epochs):
    if callbacks.model.stop_training:
      break

    # Setup work for each epoch.
    model.reset_metrics()
    epoch_logs = {}
    if mode == ModeKeys.TRAIN:
      callbacks.on_epoch_begin(epoch, epoch_logs)
    progbar.on_epoch_begin(epoch, epoch_logs)

    if steps_per_epoch is None:
      # Loop over dataset until `OutOfRangeError` is raised.
      target_steps = np.inf
    else:
      # Loop over dataset for the specified number of steps.
      target_steps = steps_per_epoch

    step = 0
    while step < target_steps:
      batch_data = _get_next_batch(generator, mode)
      if batch_data is None:
        if is_dataset:
          # The dataset passed by the user ran out of batches.
          # Now we know the cardinality of the dataset.
          # If steps_per_epoch was specified, then running out of data is
          # unexpected, so we stop training and inform the user.
          if steps_per_epoch:
            callbacks.model.stop_training = True
            logging.warning(
                'Your dataset ran out of data; interrupting training. '
                'Make sure that your dataset can generate at least '
                '`%s * epochs` batches (in this case, %d batches). '
                'You may need to use the repeat() function when '
                'building your dataset.'
                % (steps_name, steps_per_epoch * epochs))
          elif step > 0:
            steps_per_epoch = step
            aggregator.num_samples_or_steps = steps_per_epoch
            if mode == ModeKeys.TRAIN:
              progbar.params['steps'] = steps_per_epoch
              progbar.progbar.target = steps_per_epoch
        else:
          # We ran out of batches while the user passed an iterator (legacy).
          callbacks.model.stop_training = True
          logging.warning(
              'Your dataset iterator ran out of data; '
              'interrupting training. Make sure that your iterator '
              'can generate at least `%s * epochs` '
              'batches (in this case, %d batches). You may need to'
              'use the repeat() function when building your '
              'dataset.' % (steps_name, steps_per_epoch * epochs))
        break

      # `batch_size` used for validation data if validation
      # data is NumPy/EagerTensors.
      batch_size = int(nest.flatten(batch_data)[0].shape[0])

      # Callbacks batch begin.
      batch_logs = {'batch': step, 'size': batch_size}
      callbacks._call_batch_hook(mode, 'begin', step, batch_logs)
      progbar.on_batch_begin(step, batch_logs)

      is_deferred = not model._is_compiled
      batch_outs = batch_function(*batch_data)
      if not isinstance(batch_outs, list):
        batch_outs = [batch_outs]

      if step == 0:
        aggregator.create(batch_outs)

        if is_deferred:
          # Set callbacks params. We do this here when model is compiled only
          # in the first iteration of this loop (deferred build scenario).
          cbks.set_callback_parameters(
              callbacks,
              model,
              do_validation=do_validation,
              batch_size=batch_size,
              epochs=epochs,
              steps_per_epoch=steps_per_epoch,
              samples=num_samples_or_steps,
              verbose=verbose,
              mode=mode)

          progbar.params = callbacks.params
          progbar.params['verbose'] = verbose

      # Aggregate results.
      aggregator.aggregate(batch_outs)

      # Callbacks batch end.
      batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode)
      callbacks._call_batch_hook(mode, 'end', step, batch_logs)
      progbar.on_batch_end(step, batch_logs)
      step += 1

      if callbacks.model.stop_training:
        break

    aggregator.finalize()
    results = aggregator.results
    epoch_logs = cbks.make_logs(model, epoch_logs, results, mode)
    if len(results) == 1:
      results = results[0]

    # Run the test loop every epoch during training.
    if (do_validation and
        training_utils.should_run_validation(validation_freq, epoch) and
        not callbacks.model.stop_training):
      val_results = model_iteration(
          model,
          validation_data,
          steps_per_epoch=validation_steps,
          batch_size=batch_size,
          class_weight=class_weight,
          workers=workers,

Answer: use_multiprocessing=use_multiprocessing,

<think>
The code is inside the training loop of model_iteration. After completing a training epoch, it runs validation by recursively calling model_iteration with validation_data. The call already includes model, validation_data, steps_per_epoch, batch_size, class_weight, and workers, ending with a trailing comma, indicating more arguments are needed. The next argument in the function signature is use_multiprocessing, which should be passed the same flag used for training. Therefore the next line adds `use_multiprocessing=use_multiprocessing,` to the call.
</think>
use_multiprocessing=use_multiprocessing,


Context:
# -*- coding: utf-8 -*-
"""
    werkzeug.serving
    ~~~~~~~~~~~~~~~~

    There are many ways to serve a WSGI application.  While you're developing
    it you usually don't want a full blown webserver like Apache but a simple
    standalone one.  From Python 2.5 onwards there is the `wsgiref`_ server in
    the standard library.  If you're using older versions of Python you can
    download the package from the cheeseshop.

    However there are some caveats. Sourcecode won't reload itself when
    changed and each time you kill the server using ``^C`` you get an
    `KeyboardInterrupt` error.  While the latter is easy to solve the first
    one can be a pain in the ass in some situations.

    The easiest way is creating a small ``start-myproject.py`` that runs the
    application::

        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        from myproject import make_app
        from werkzeug.serving import run_simple

        app = make_app(...)
        run_simple('localhost', 8080, app, use_reloader=True)

    You can also pass it a `extra_files` keyword argument with a list of
    additional files (like configuration files) you want to observe.

    For bigger applications you should consider using `werkzeug.script`
    instead of a simple start file.

    :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement

import os
import socket
import sys
import signal

from ._compat import PY2

try:
    import ssl
except ImportError:
    class _SslDummy(object):
        def __getattr__(self, name):
            raise RuntimeError('SSL support unavailable')
    ssl = _SslDummy()

def _get_openssl_crypto_module():
    try:
        from OpenSSL import crypto
    except ImportError:
        raise TypeError('Using ad-hoc certificates requires the pyOpenSSL '
                        'library.')
    else:
        return crypto

try:
    from SocketServer import ThreadingMixIn, ForkingMixIn
    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
except ImportError:
    from socketserver import ThreadingMixIn, ForkingMixIn
    from http.server import HTTPServer, BaseHTTPRequestHandler

import werkzeug
from werkzeug._internal import _log
from werkzeug._compat import reraise, wsgi_encoding_dance
from werkzeug.urls import url_parse, url_unquote
from werkzeug.exceptions import InternalServerError

LISTEN_QUEUE = 128
can_open_by_fd = hasattr(socket, 'fromfd')

class WSGIRequestHandler(BaseHTTPRequestHandler, object):

    """A request handler that implements WSGI dispatching."""

    @property
    def server_version(self):
        return 'Werkzeug/' + werkzeug.__version__

    def make_environ(self):
        request_url = url_parse(self.path)

        def shutdown_server():
            self.server.shutdown_signal = True

        url_scheme = self.server.ssl_context is None and 'http' or 'https'
        path_info = url_unquote(request_url.path)

        environ = {
            'wsgi.version':         (1, 0),
            'wsgi.url_scheme':      url_scheme,
            'wsgi.input':           self.rfile,
            'wsgi.errors':          sys.stderr,
            'wsgi.multithread':     self.server.multithread,
            'wsgi.multiprocess':    self.server.multiprocess,
            'wsgi.run_once':        False,
            'werkzeug.server.shutdown': shutdown_server,
            'SERVER_SOFTWARE':      self.server_version,
            'REQUEST_METHOD':       self.command,
            'SCRIPT_NAME':          '',
            'PATH_INFO':            wsgi_encoding_dance(path_info),
            'QUERY_STRING':         wsgi_encoding_dance(request_url.query),
            'CONTENT_TYPE':         self.headers.get('Content-Type', ''),
            'CONTENT_LENGTH':       self.headers.get('Content-Length', ''),
            'REMOTE_ADDR':          self.client_address[0],
            'REMOTE_PORT':          self.client_address[1],
            'SERVER_NAME':          self.server.server_address[0],
            'SERVER_PORT':          str(self.server.server_address[1]),
            'SERVER_PROTOCOL':      self.request_version
        }

        for key, value in self.headers.items():
            key = 'HTTP_' + key.upper().replace('-', '_')
            if key not in ('HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH'):
                environ[key] = value

        if request_url.netloc:
            environ['HTTP_HOST'] = request_url.netloc

        return environ

    def run_wsgi(self):
        if self.headers.get('Expect', '').lower().strip() == '100-continue':
            self.wfile.write(b'HTTP/1.1 100 Continue\r\n\r\n')

        self.environ = environ = self.make_environ()
        headers_set = []
        headers_sent = []

        def write(data):
            assert headers_set, 'write() before start_response'
            if not headers_sent:
                status, response_headers = headers_sent[:] = headers_set
                try:
                    code, msg = status.split(None, 1)
                except ValueError:
                    code, msg = status, ""
                self.send_response(int(code), msg)
                header_keys = set()
                for key, value in response_headers:
                    self.send_header(key, value)
                    key = key.lower()
                    header_keys.add(key)
                if 'content-length' not in header_keys:
                    self.close_connection = True
                    self.send_header('Connection', 'close')
                if 'server' not in header_keys:
                    self.send_header('Server', self.version_string())
                if 'date' not in header_keys:
                    self.send_header('Date', self.date_time_string())
                self.end_headers()

            assert isinstance(data, bytes), 'applications must write bytes'
            self.wfile.write(data)
            self.wfile.flush()

        def start_response(status, response_headers, exc_info=None):
            if exc_info:
                try:
                    if headers_sent:
                        reraise(*exc_info)
                finally:
                    exc_info = None
            elif headers_set:
                raise AssertionError('Headers already set')
            headers_set[:] = [status, response_headers]
            return write

        def execute(app):
            application_iter = app(environ, start_response)
            try:
                for data in application_iter:
                    write(data)
                if not headers_sent:
                    write(b'')
            finally:
                if hasattr(application_iter, 'close'):
                    application_iter.close()
                application_iter = None

        try:
            execute(self.server.app)
        except (socket.error, socket.timeout) as e:
            self.connection_dropped(e, environ)
        except Exception:
            if self.server.passthrough_errors:
                raise
            from werkzeug.debug.tbtools import get_current_traceback
            traceback = get_current_traceback(ignore_system_exceptions=True)
            try:
                # if we haven't yet sent the headers but they are set
                # we roll back to be able to set them again.
                if not headers_sent:
                    del headers_set[:]
                execute(InternalServerError())
            except Exception:
                pass
            self.server.log('error', 'Error on request:\n%s',
                            traceback.plaintext)

    def handle(self):
        """Handles a request ignoring dropped connections."""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (socket.error, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception:
            if self.server.ssl_context is None or not is_ssl_error():
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv

    def initiate_shutdown(self):
        """A horrible, horrible way to kill the server for Python 2.6 and
        later.  It's the best we can do.
        """
        # Windows does not provide SIGKILL, go with SIGTERM then.
        sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
        # reloader active
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            os.kill(os.getpid(), sig)
        # python 2.7
        self.server._BaseServer__shutdown_request = True
        # python 2.6
        self.server._BaseServer__serving = False

    def connection_dropped(self, error, environ=None):
        """Called if the connection was closed by the client.  By default
        nothing happens.
        """

    def handle_one_request(self):
        """Handle a single HTTP request."""
        self.raw_requestline = self.rfile.readline()
        if not self.raw_requestline:
            self.close_connection = 1
        elif self.parse_request():
            return self.run_wsgi()

    def send_response(self, code, message=None):
        """Send the response header and log the response code."""
        self.log_request(code)
        if message is None:
            message = code in self.responses and self.responses[code][0] or ''
        if self.request_version != 'HTTP/0.9':
            hdr = "%s %d %s\r\n" % (self.protocol_version, code, message)
            self.wfile.write(hdr.encode('ascii'))

    def version_string(self):
        return BaseHTTPRequestHandler.version_string(self).strip()

    def address_string(self):
        return self.environ['REMOTE_ADDR']

    def log_request(self, code='-', size='-'):
        self.log('info', '"%s" %s %s', self.requestline, code, size)

    def log_error(self, *args):
        self.log('error', *args)

    def log_message(self, format, *args):
        self.log('info', format, *args)

    def log(self, type, message, *args):
        _log(type, '%s - - [%s] %s\n' % (self.address_string(),
                                         self.log_date_time_string(),
                                         message % args))

#: backwards compatible name if someone is subclassing it
BaseRequestHandler = WSGIRequestHandler

def generate_adhoc_ssl_pair(cn=None):
    from random import random
    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = '*'

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = 'Dummy Certificate'

    issuer = cert.get_issuer()
    issuer.CN = 'Untrusted Authority'
    issuer.O = 'Self-Signed'

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 1024)
    cert.set_pubkey(pkey)
    cert.sign(pkey, 'md5')

    return cert, pkey

def make_ssl_devcert(base_path, host=None, cn=None):
    """Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    """
    from OpenSSL import crypto
    if host is not None:
        cn = '*.%s/CN=%s' % (host, host)
    cert, pkey = generate_adhoc_ssl_pair(cn=cn)

    cert_file = base_path + '.crt'
    pkey_file = base_path + '.key'

    with open(cert_file, 'wb') as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(pkey_file, 'wb') as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))

Answer: return cert_file, pkey_file

<think>
The function make_ssl_devcert creates a certificate and private key, writes them to files named <base_path>.crt and <base_path>.key. After writing, the typical behavior is to return the paths of the generated files so callers can use them. In Werkzeug's implementation, the function ends with 'return cert_file, pkey_file'. Therefore the next line should be that return statement.
</think>
return cert_file, pkey_file