text:
package org.apache.hadoop.fs.s3a.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.transfer.model.CopyResult;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.s3a.RenameFailedException;
import org.apache.hadoop.fs.s3a.Retries;
import org.apache.hadoop.fs.s3a.S3AFileStatus;
import org.apache.hadoop.fs.s3a.S3ALocatedFileStatus;
import org.apache.hadoop.fs.s3a.S3AReadOpContext;
import org.apache.hadoop.fs.s3a.S3ObjectAttributes;
import org.apache.hadoop.fs.s3a.Tristate;
import org.apache.hadoop.fs.s3a.s3guard.MetadataStore;
import org.apache.hadoop.fs.s3a.s3guard.RenameTracker;
import org.apache.hadoop.util.DurationInfo;
import org.apache.hadoop.util.OperationDuration;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.hadoop.fs.s3a.Constants.FS_S3A_BLOCK_SIZE;
import static org.apache.hadoop.fs.s3a.S3AUtils.objectRepresentsDirectory;
import static org.apache.hadoop.fs.s3a.impl.CallableSupplier.submit;
import static org.apache.hadoop.fs.s3a.impl.CallableSupplier.waitForCompletion;
import static org.apache.hadoop.fs.s3a.impl.InternalConstants.DEFAULT_BLOCKSIZE;
import static org.apache.hadoop.fs.s3a.impl.InternalConstants.RENAME_PARALLEL_LIMIT;

/**
 * A parallelized rename operation which updates the metastore in the
 * process, through whichever {@link RenameTracker} the store provides.
 *

 * The parallel execution is in groups of size
 * {@link InternalConstants#RENAME_PARALLEL_LIMIT}; it is only
 * after one group completes that the next group is initiated.
 *

 * Once enough files have been copied that they meet the
 * {@link InternalConstants#MAX_ENTRIES_TO_DELETE} threshold, a delete
 * is initiated.
 * If it succeeds, the rename continues with the next group of files.
 *

 * The RenameTracker has the task of keeping the metastore up to date
 * as the rename proceeds.
 *

 * Directory Markers which have child entries are never copied; only those
 * which represent empty directories are copied in the rename.
 * The {@link DirMarkerTracker} tracks which markers must be copied, and
 * which can simply be deleted from the source.
 * As a result: rename always purges all non-leaf directory markers from
 * the copied tree. This is to ensure that even if a directory tree
 * is copied from an authoritative path to a non-authoritative one
 * there is never any contamination of the non-auth path with markers.
 *

 * The rename operation implements the classic HDFS rename policy of
 * rename(file, dir) renames the file under the directory.
 *

 *
 * There is no validation of input and output paths.
 * Callers are required to themselves verify that destination is not under
 * the source, above the source, the source itself, etc, etc.
 */
public class RenameOperation extends ExecutingStoreOperation<Long> {

  private static final Logger LOG = LoggerFactory.getLogger(
      RenameOperation.class);

  private final Path sourcePath;

  private final String sourceKey;

  private final S3AFileStatus sourceStatus;

  private final Path destPath;

  private final String destKey;

  private final S3AFileStatus destStatus;

  /**
   * Callbacks into the filesystem.
   */
  private final OperationCallbacks callbacks;

  /**
   * Counter of bytes copied.
   */

  private final AtomicLong bytesCopied = new AtomicLong();

  /**
   * Page size for bulk deletes.
   */
  private final int pageSize;

  /**
   * Rename tracker.
   */
  private RenameTracker renameTracker;

  /**
   * List of active copies.
   */
  private final List<CompletableFuture<Path>> activeCopies =
      new ArrayList<>(RENAME_PARALLEL_LIMIT);

  /**
   * list of keys to delete on the next (bulk) delete call.
   */
  private final List<DeleteObjectsRequest.KeyVersion> keysToDelete =
      new ArrayList<>();

  /**
   * List of paths to delete, which will be passed to the rename
   * tracker after the deletion succeeds.
   */
  private final List<Path> pathsToDelete = new ArrayList<>();

  private final long blocksize;

  /**
   * Initiate the rename.
   *
   * @param storeContext store context
   * @param sourcePath source path
   * @param sourceKey key of source
   * @param sourceStatus pre-fetched source status
   * @param destPath destination path.
   * @param destKey destination key
   * @param destStatus destination status.
   * @param callbacks callback provider
   * @param pageSize size of delete requests
   */
  public RenameOperation(
      final StoreContext storeContext,
      final Path sourcePath,
      final String sourceKey,
      final S3AFileStatus sourceStatus,
      final Path destPath,
      final String destKey,
      final S3AFileStatus destStatus,
      final OperationCallbacks callbacks,
      final int pageSize) {
    super(storeContext);
    this.sourcePath = sourcePath;
    this.sourceKey = sourceKey;
    this.sourceStatus = sourceStatus;
    this.destPath = destPath;
    this.destKey = destKey;
    this.destStatus = destStatus;
    this.callbacks = callbacks;
    blocksize = storeContext.getConfiguration()
        .getLongBytes(FS_S3A_BLOCK_SIZE, DEFAULT_BLOCKSIZE);
    this.pageSize = pageSize;
  }

  /**
   * Wait for the active copies to complete then reset the list.
   * @param reason for messages
   * @throws IOException if one of the called futures raised an IOE.
   * @throws RuntimeException if one of the futures raised one.
   */
  @Retries.OnceTranslated
  private void completeActiveCopies(String reason) throws IOException {
    LOG.debug("Waiting for {} active copies to complete: {}",
        activeCopies.size(), reason);
    waitForCompletion(activeCopies);
    activeCopies.clear();
  }

  /**
   * Queue an object for deletion.
   *

   * This object will be deleted when the next page of objects to delete
   * is posted to S3. Therefore, the COPY must have finished
   * before that deletion operation takes place.
   * This is managed by:
   *

   *

   *     The delete operation only being executed once all active
   *     copies have completed.
   *

   *

   *     Only queuing objects here whose copy operation has
   *     been submitted and so is in that thread pool.
   *

   *

   * This method must only be called from the primary thread.
   * @param path path to the object
   * @param key key of the object.
   * @param version object version.
   */
  private void queueToDelete(Path path, String key, String version) {
    LOG.debug("Queueing to delete {}", path);
    pathsToDelete.add(path);
    keysToDelete.add(new DeleteObjectsRequest.KeyVersion(key, version));
  }

  /**
   * Queue a list of markers for deletion.
   *

   * no-op if the list is empty.
   *

   * See {@link #queueToDelete(Path, String, String)} for
   * details on safe use of this method.
   *
   * @param markersToDelete markers
   */
  private void queueToDelete(
      List<DirMarkerTracker.Marker> markersToDelete) {
    markersToDelete.forEach(m ->
        queueToDelete(m));
  }

  /**
   * Queue a single marker for deletion.
   *

   * See {@link #queueToDelete(Path, String, String)} for
   * details on safe use of this method.
   *
   * @param marker markers
   */
  private void queueToDelete(final DirMarkerTracker.Marker marker) {
    queueToDelete(marker.getPath(), marker.getKey(),
        marker.getStatus().getVersionId());
  }

  /**
   * Block waiting for ay active copies to finish
   * then delete all queued keys + paths to delete.
   * @param reason reason for logs
   * @throws IOException failure.
   */
  @Retries.RetryTranslated
  private void completeActiveCopiesAndDeleteSources(String reason)
      throws IOException {
    completeActiveCopies(reason);
    removeSourceObjects(
        keysToDelete,
        pathsToDelete);
    // now reset the lists.
    keysToDelete.clear();
    pathsToDelete.clear();
  }

  @Retries.RetryMixed
  public Long execute() throws IOException {
    executeOnlyOnce();
    final StoreContext storeContext = getStoreContext();
    final MetadataStore metadataStore = checkNotNull(
        storeContext.getMetadataStore(),
        "No metadata store in context");

    // Validation completed: time to begin the operation.
    // The store-specific rename tracker is used to keep the store
    // to date with the in-progress operation.
    // for the null store, these are all no-ops.
    renameTracker = metadataStore.initiateRenameOperation(
        storeContext,
        sourcePath, sourceStatus, destPath);

    // The path to whichever file or directory is created by the
    // rename. When deleting markers all parents of
    // this path will need their markers pruned.
    Path destCreated = destPath;

    // Ok! Time to start
    try {
      if (sourceStatus.isFile()) {
        // rename the file. The destination path will be different
        // from that passed in if the destination is a directory;
        // the final value is needed to completely delete parent markers
        // when they are not being retained.
        destCreated = renameFileToDest();
      } else {
        recursiveDirectoryRename();
      }
    } catch (AmazonClientException | IOException ex) {
      // rename failed.
      // block for all ongoing copies to complete, successfully or not
      try {
        completeActiveCopies("failure handling");
      } catch (IOException e) {
        // a failure to update the metastore after a rename failure is what
        // we'd see on a network problem, expired credentials and other
        // unrecoverable errors.
        // Downgrading to warn because an exception is already
        // about to be thrown.
        LOG.warn("While completing all active copies", e);
      }
      // notify the rename tracker of the failure
      throw renameTracker.renameFailed(ex);
    }

    // At this point the rename has completed successfully in the S3 store.
    // Tell the metastore this fact and let it complete its changes
    renameTracker.completeRename();

    callbacks.finishRename(sourcePath, destCreated);
    return bytesCopied.get();
  }

  /**
   * The source is a file: rename it to the destination, which
   * will be under the current destination path if that is a directory.
   * @return the path of the object created.
   * @throws IOException failure
   */
  protected Path renameFileToDest() throws IOException {
    final StoreContext storeContext = getStoreContext();
    // the source is a file.
    Path copyDestinationPath = destPath;
    String copyDestinationKey = destKey;
    S3ObjectAttributes sourceAttributes =
        callbacks.createObjectAttributes(sourceStatus);
    S3AReadOpContext readContext = callbacks.createReadContext(sourceStatus);
    if (destStatus != null && destStatus.isDirectory()) {
      // destination is a directory: build the final destination underneath
      String newDestKey = maybeAddTrailingSlash(destKey);
      String filename = sourceKey.substring(
          storeContext.pathToKey(sourcePath.getParent()).length() + 1);
      newDestKey = newDestKey + filename;
      copyDestinationKey = newDestKey;
      copyDestinationPath = storeContext.keyToPath(newDestKey);
    }
    // destination either does not exist or is a file to overwrite.
    LOG.debug("rename: renaming file {} to {}", sourcePath,
        copyDestinationPath);
    copySourceAndUpdateTracker(
        sourcePath,
        sourceKey,
        sourceAttributes,
        readContext,
        copyDestinationPath,
        copyDestinationKey,
        false);
    bytesCopied.addAndGet(sourceStatus.getLen());
    // delete the source
    callbacks.deleteObjectAtPath(sourcePath, sourceKey, true, null);
    // and update the tracker
    renameTracker.sourceObjectsDeleted(Lists.newArrayList(sourcePath));
    return copyDestinationPath;
  }

  /**
   * Execute a full recursive rename.
   * There is a special handling of directly markers here -only leaf markers
   * are copied. This reduces incompatibility "regions" across versions.
Are   * @throws IOException failure
   */
  protected void recursiveDirectoryRename() throws IOException {
    final StoreContext storeContext = getStoreContext();

    LOG.debug("rename: renaming directory {} to {}", sourcePath, destPath);

    // This is a directory-to-directory copy
    String dstKey = maybeAddTrailingSlash(destKey);
    String srcKey = maybeAddTrailingSlash(sourceKey);

    // Verify dest is not a child of the source directory
    if (dstKey.startsWith(srcKey)) {
      throw new RenameFailedException(srcKey, dstKey,
          "cannot rename a directory to a subdirectory of itself ");
    }

    if (destStatus != null
        && destStatus.isEmptyDirectory() == Tristate.TRUE) {
      // delete unnecessary fake directory at the destination.
      // this MUST be done before anything else so that
      // rollback code doesn't get confused and insert a tombstone
      // marker.
      LOG.debug("Deleting fake directory marker at destination {}",
          destStatus.getPath());
      // Although the dir marker policy doesn't always need to do this,
      // it's simplest just to be consistent here.
      callbacks.deleteObjectAtPath(destStatus.getPath(), dstKey, false, null);
    }

    Path parentPath = storeContext.keyToPath(srcKey);

    // Track directory markers so that we know which leaf directories need to be
    // recreated
    DirMarkerTracker dirMarkerTracker = new DirMarkerTracker(parentPath,
        false);

    final RemoteIterator<S3ALocatedFileStatus> iterator =
        callbacks.listFilesAndEmptyDirectories(parentPath,
            sourceStatus,
            true,
            true);
    while (iterator.hasNext()) {
      // get the next entry in the listing.
      S3ALocatedFileStatus child = iterator.next();
      // convert it to an S3 key.
      String k = storeContext.pathToKey(child.getPath());
      // possibly adding a "/" if it represents directory and it does
      // not have a trailing slash already.
      String key = (child.isDirectory() && !k.endsWith("/"))
          ? k + "/"
          : k;
      // the source object to copy as a path.
      Path childSourcePath = storeContext.keyToPath(key);

      List<DirMarkerTracker.Marker> markersToDelete;

      boolean isMarker = key.endsWith("/");
      if (isMarker) {
        // add the marker to the tracker.
        // it will not be deleted _yet_ but it may find a list of parent
        // markers which may now be deleted.
        markersToDelete = dirMarkerTracker.markerFound(
            childSourcePath, key, child);
      } else {
        // it is a file.
        // note that it has been found -this may find a list of parent
        // markers which may now be deleted.
        markersToDelete = dirMarkerTracker.fileFound(
            childSourcePath, key, child);
        // the destination key is that of the key under the source tree,
        // remapped under the new destination path.
        String newDestKey =
            dstKey + key.substring(srcKey.length());
        Path childDestPath = storeContext.keyToPath(newDestKey);

        // mark the source file for deletion on a successful copy.
        queueToDelete(childSourcePath, key, child.getVersionId());
          // now begin the single copy
        CompletableFuture<Path> copy = initiateCopy(child, key,
            childSourcePath, newDestKey, childDestPath);
        activeCopies.add(copy);
        bytesCopied.addAndGet(sourceStatus.getLen());
      }
      // add any markers to delete to the operation so they get cleaned
      // incrementally
      queueToDelete(markersToDelete);
      // and trigger any end of loop operations
      endOfLoopActions();
    } // end of iteration through the list

    // finally process remaining directory markers
    copyEmptyDirectoryMarkers(srcKey, dstKey, dirMarkerTracker);

    // await the final set of copies and their deletion
    // This will notify the renameTracker that these objects
    // have been deleted.
    completeActiveCopiesAndDeleteSources("final copy and delete");

    // We moved all the children, now move the top-level dir
    // Empty directory should have been added as the object summary
    renameTracker.moveSourceDirectory();
  }

  /**
   * Operations to perform at the end of every loop iteration.
   *

   * This may block the thread waiting for copies to complete
   * and/or delete a page of data.
   */
  private void endOfLoopActions() throws IOException {
    if (keysToDelete.size() == pageSize) {
      // finish ongoing copies then delete all queued keys.
      completeActiveCopiesAndDeleteSources("paged delete");
    } else {
      if (activeCopies.size() == RENAME_PARALLEL_LIMIT) {
        // the limit of active copies has been reached;
        // wait for completion or errors to surface.
        LOG.debug("Waiting for active copies to complete");
        completeActiveCopies("batch threshold reached");
      }
    }
  }

  /**
   * Process all directory markers at the end of the rename.
   * All leaf markers are queued to be copied in the store;
   * this updates the metastore tracker as it does so.
   *

   * Why not simply create new markers? All the metadata
   * gets copied too, so if there was anything relevant then
   * it would be preserved.
   *

   * At the same time: markers aren't valued much and may
   * be deleted without any safety checks -so if there was relevant
   * data it is at risk of destruction at any point.
   * If there are lots of empty directory rename operations taking place,
   * the decision to copy the source may need revisiting.
   * Be advised though: the costs of the copy not withstanding,
   * it is a lot easier to have one single type of scheduled copy operation
   * than have copy and touch calls being scheduled.
   *

   * The duration returned is the time to initiate all copy/delete operations,
   * including any blocking waits for active copies and paged deletes
   * to execute. There may still be outstanding operations
   * queued by this method -the duration may be an underestimate
   * of the time this operation actually takes.
   *
   * @param srcKey source key with trailing /
   * @param dstKey dest key with trailing /
   * @param dirMarkerTracker tracker of markers
   * @return how long it took.
   */
  private OperationDuration copyEmptyDirectoryMarkers(
      final String srcKey,
      final String dstKey,
      final DirMarkerTracker dirMarkerTracker) throws IOException {
    // directory marker work.
    LOG.debug("Copying markers from {}", dirMarkerTracker);
    final StoreContext storeContext = getStoreContext();
    Map<Path, DirMarkerTracker.Marker> leafMarkers =
        dirMarkerTracker.getLeafMarkers();
    Map<Path, DirMarkerTracker.Marker> surplus =
        dirMarkerTracker.getSurplusMarkers();
    // for all leaf markers: copy the original
    DurationInfo duration = new DurationInfo(LOG, false,
        "copying %d leaf markers with %d surplus not copied",
        leafMarkers.size(), surplus.size());
    for (DirMarkerTracker.Marker entry: leafMarkers.values()) {
      Path source = entry.getPath();
      String key = entry.getKey();
      String newDestKey =
          dstKey + key.substring(srcKey.length());
      Path childDestPath = storeContext.keyToPath(newDestKey);
      LOG.debug("copying dir marker from {} to {}", key, newDestKey);

      activeCopies.add(
          initiateCopy(
              entry.getStatus(),
              key,
              source,
              newDestKey,
              childDestPath));
      queueToDelete(entry);
      // end of loop
      endOfLoopActions();
    }
    duration.close();
    return duration;
  }

  /**
   * Initiate a copy operation in the executor.
   * @param source status of the source object.
   * @param key source key
   * @param childSourcePath source as a path.
   * @param newDestKey destination key
   * @param childDestPath destination path.
   * @return the future.
   */
  protected CompletableFuture<Path> initiateCopy(
      final S3ALocatedFileStatus source,
      final String key,
      final Path childSourcePath,
      final String newDestKey,
      final Path childDestPath) {
    S3ObjectAttributes sourceAttributes =
        callbacks.createObjectAttributes(
            source.getPath(),
            source.getETag(),
            source.getVersionId(),
            source.getLen());
    // queue the copy operation for execution in the thread pool
    return submit(getStoreContext().getExecutor(), () ->
        copySourceAndUpdateTracker(
            childSourcePath,
            key,
            sourceAttributes,
            callbacks.createReadContext(source),
            childDestPath,
            newDestKey,
            true));
  }

  /**
   * This invoked to copy a file or directory marker then update the
   * rename operation on success.
   * It may be called in its own thread.
   * @param sourceFile source path of the copy; may have a trailing / on it.
   * @param srcKey source key
   * @param srcAttributes status of the source object
   * @param destination destination as a qualified path.
   * @param destinationKey destination key
   * @param addAncestors should ancestors be added to the metastore?
   * @return the destination path.
   * @throws IOException failure
   */
  @Retries.RetryTranslated
  private Path copySourceAndUpdateTracker(
      final Path sourceFile,
      final String srcKey,
      final S3ObjectAttributes srcAttributes,
      final S3AReadOpContext readContext,
      final Path destination,
      final String destinationKey,
      final boolean addAncestors) throws IOException {
    long len = srcAttributes.getLen();
    CopyResult copyResult;
    try (DurationInfo ignored = new DurationInfo(LOG, false,
        "Copy file from %s to %s (length=%d)", srcKey, destinationKey, len)) {
      copyResult = callbacks.copyFile(srcKey, destinationKey,
          srcAttributes, readContext);
    }
    if (objectRepresentsDirectory(srcKey, len)) {
      renameTracker.directoryMarkerCopied(
          sourceFile,
          destination,
          addAncestors);
    } else {
      S3ObjectAttributes destAttributes = new S3ObjectAttributes(
          destination,
          copyResult,
          srcAttributes.getServerSideEncryptionAlgorithm(),
          srcAttributes.getServerSideEncryptionKey(),
          len);
      renameTracker.fileCopied(
          sourceFile,
          srcAttributes,
          destAttributes,
          destination,
          blocksize,
          addAncestors);
    }
    return destination;
  }

  /**
   * Remove source objects and update the metastore by way of
   * the rename tracker.
   * @param keys list of keys to delete
   * @param paths list of paths matching the keys to delete 1:1.
   * @throws IOException failure
   */
  @Retries.RetryTranslated
  private void removeSourceObjects(
      final List<DeleteObjectsRequest.KeyVersion> keys,
      final List<Path> paths)
      throws IOException {
    List<Path> undeletedObjects = new ArrayList<>();
    try {
      // remove the keys

      // list what is being deleted for the interest of anyone
      // who is trying to debug why objects are no longer there.
      if (LOG.isDebugEnabled()) {
        LOG.debug("Initiating delete operation for {} objects", keys.size());
        for (DeleteObjectsRequest.KeyVersion key : keys) {
          LOG.debug(" {} {}", key.getKey(),
              key.getVersion() != null ? key.getVersion() : "");
        }
      }
      // this will update the metastore on a failure, but on
      // a successful operation leaves the store as is.
      callbacks.removeKeys(
          keys,
          false,
          undeletedObjects,
          renameTracker.getOperationState(),
          true);
      // and clear the list.
    } catch (AmazonClientException | IOException e) {
      // Failed.
      // Notify the rename tracker.
      // removeKeys will have already purged the metastore of
      // all keys it has known to delete; this is just a final
      // bit of housekeeping and a chance to tune exception
      // reporting.
      // The returned IOE is rethrown.
      throw renameTracker.deleteFailed(e, paths, undeletedObjects);
    }
    renameTracker.sourceObjectsDeleted(paths);
  }

  /**
   * Turns a path (relative or otherwise) into an S3 key, adding a trailing
   * "/" if the path is not the root and does not already have a "/"
   * at the end.
   *
   * @param key s3 key or ""
   * @return the with a trailing "/", or, if it is the root key, "",
   */
  private String maybeAddTrailingSlash(String key) {
    if (!key.isEmpty() && !key.endsWith("/")) {
      return key + '/';
    } else {
      return key;
    }
  }

}


text:
package com.stulsoft.pjava.basics.stream;

import com.stulsoft.pjava.utils.BenchmarkMaster;
import com.stulsoft.pjava.utils.BenchmarkResult;

import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.OptionalInt;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * Playing with reduce for range (stream).
 *

 * Using without parallel and with parallel.
 *

 * Conclusion: if we want to use reduce with parallel the function in reduce should be associative.
 * For instance {@code (v1,v2)->v1 + v2} is good function (associative) and {@code (v1,v2)->v1 - v2} is bad function (non-associative)
 *
 * @author Yuriy Stul.
 */
public class RangeEx01 {
    private static final int N = 100000;

    /**
     * Without parallel
     */
    private static AbstractMap.SimpleEntry<String, Integer> test1() {
        int result = 0;
        OptionalInt resultOptional = IntStream.range(0, N).reduce((v1, v2) -> v1 - v2);
        if (resultOptional.isPresent()) {
            result = resultOptional.getAsInt();
        }
        return new AbstractMap.SimpleEntry<>("Without parallel", result);
    }

    /**
     * With parallel
     */
    private static AbstractMap.SimpleEntry<String, Integer> test2() {
        int result = 0;
        OptionalInt resultOptional = IntStream.range(0, N).parallel().reduce((v1, v2) -> v1 - v2);
        if (resultOptional.isPresent()) {
            result = resultOptional.getAsInt();
        }
        return new AbstractMap.SimpleEntry<>("With parallel", result);
    }

    /**
     * With parallel and sum instead reduce
     */
    private static AbstractMap.SimpleEntry<String, Integer> test3() {
        int result = -IntStream.range(0, N).parallel().sum();
        return new AbstractMap.SimpleEntry<>("With parallel and sum instead reduce", result);
    }

    /**
     * With parallel and AtomicInteger
     */
    private static AbstractMap.SimpleEntry<String, Integer> test4() {
        final AtomicInteger counter = new AtomicInteger();
        IntStream.range(0, N).parallel()
                .forEach(i -> counter.addAndGet(-i));
        return new AbstractMap.SimpleEntry<>("With parallel and AtomicInteger", counter.intValue());
    }

    /**
     * Without parallel and sum instead reduce
     */
    private static AbstractMap.SimpleEntry<String, Integer> test5() {
        int result = -IntStream.range(0, N).sum();
        return new AbstractMap.SimpleEntry<>("Without parallel and sum instead reduce", result);
    }

    /**
     * With parallel and minus sum
     */
    private static AbstractMap.SimpleEntry<String, Integer> test6() {
        int result = 0;
        OptionalInt resultOptional = IntStream.range(0, N).parallel().reduce(Integer::sum);
        if (resultOptional.isPresent()) {
            result = -resultOptional.getAsInt();
        }
        return new AbstractMap.SimpleEntry<>("With parallel and minus sum", result);
    }

    public static void main(String[] args) {
        System.out.println("==>main");
        Collection<BenchmarkResult> results =
                BenchmarkMaster.sortBenchmarkResultsByDurationAscending(BenchmarkMaster.execute(Arrays.asList(
                        RangeEx01::test1,
                        RangeEx01::test2,
                        RangeEx01::test3,
                        RangeEx01::test4,
                        RangeEx01::test5,
                        RangeEx01::test6), 50));

        System.out.println("\nCorrect results:");
        System.out.println("===============");
        results.stream().filter(r -> Integer.parseInt(r.getValue().toString()) != 0)
                .forEach(r -> System.out.format("%s, %s, %dms\n", r.getText(), r.getValue().toString(), r.getDuration()));

        System.out.println("\nWrong results:");
        System.out.println("==============");
        results.stream().filter(r -> Integer.parseInt(r.getValue().toString()) == 0)
                .forEach(r -> System.out.format("%s, %s, %dms\n", r.getText(), r.getValue().toString(), r.getDuration()));

        System.out.println("<==main");
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_dark_black" >#ff333333</color>
    <color name="text_dark_silver" >#ff888888</color>
    <color name="text_silver" >#ffaaaaaa</color>

    <color name="bg_dark_black" >#ff333333</color>
    <color name="bg_shadow_black" >#ff888888</color>
    <color name="bg_holo_white" >#ffeeeeee</color>
</resources>


text:
title: Ruby Sass Has Reached End-Of-Life
author: Natalie Weizenbaum
date: 2019-04-03 16:15 PST
---

One year has passed since we announced [the deprecation of Ruby
Sass](/blog/ruby-sass-is-deprecated), and it has now officially reached its
end-of-life. We will release one final version of the Ruby Sass gem that will
print a warning indicating that it's no longer receiving updates, and then
archive [the GitHub repository](https://github.com/sass/ruby-sass).

![A woman saying "Goodbye, my friend"](/assets/img/blog/020-goodbye.gif)

We will then merge the [sass/language](https://github.com/sass/language) repo
into the [sass/sass](https://github.com/sass/sass) repo. This means that
**anyone still depending on Ruby Sass from `github.com/sass/sass` will break.**
Going forward, the sass/sass repo will be the location for working on the
language specs, and will not contain any code. The sass/language repo will just
include links pointing to sass/sass.

### Migrating Away

If you haven't migrated away from Ruby Sass yet, now is the time. The best way
to do that depends on how you use Ruby Sass today.

If you use Ruby Sass as a command-line tool, the easiest way to migrate is to
[install Dart Sass](/install) as a command-line tool. It supports a similar
interface to Ruby Sass, and you can run `sass --help` for a full explanation of
its capabilities.

If you use Ruby Sass as a plugin for a Ruby web app, particularly if you define
your own Sass functions in Ruby, the
[`sassc`](https://github.com/sass/sassc-ruby) gem provides access to
[LibSass](/libsass) from Ruby with a very similar API to Ruby Sass. In most
cases, you can just replace the `Sass` module with the `SassC` module and your
code will continue to work.

If you're using Rails, we particularly recommend using the
[`sassc-rails`](https://github.com/sass/sassc-rails) gem, which wraps up the
`sassc` gem and integrates it smoothly into the asset pipeline. Most of the time
you won't even need to change any of your code.

### Farewell, Ruby Sass!

On a personal note, I started writing Ruby Sass in 2006 when I was just a
college kid coding in between homework assignments. I've worked on it (with
varying degrees of focus) continuously for the last 13 years, and I expect it'll
take me a long time to match that record with any other codebase. I'm glad to
see the language [moving forward](/blog/announcing-dart-sass), but at the same
time I'll miss Ruby Sass terribly.

I also want to take this opportunity to thank our users, especially those in the
Ruby community in which Sass was born, for appreciating the language we created
and evangelizing it so widely. Sass has an incredible userbase, and I've been so
proud to see how large and diverse it's grown over the years. Let's keep it up
as we move into a new era of Sass!


text:
namespace FMStudio.Lib.Test
{
    //
    public static class AssemblyInitializer
    {
        //[AssemblyInitialize]
        //public static void AssemblyInitialize(TestContext context)
        //{
        //    Database.Cleanup();
        //}

        //[AssemblyCleanup]
        //public static void AssemblyCleanup()
        //{
        //    Database.Cleanup();
        //}
    }
}


text:
package net.bytebuddy.test;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.build.EntryPoint;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.inline.MethodNameTransformer;

public class IllegalEntryPoint implements EntryPoint {

    @Override
    public ByteBuddy getByteBuddy() {
        throw new RuntimeException();
    }

    @Override
    public DynamicType.Builder<?> transform(TypeDescription typeDescription,
                                            ByteBuddy byteBuddy,
                                            ClassFileLocator classFileLocator,
                                            MethodNameTransformer methodNameTransformer) {
        throw new RuntimeException();
    }
}


text:
package com.haxademic.demo.draw.text;

import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.data.constants.PTextAlign;
import com.haxademic.core.draw.text.FontCacher;
import com.haxademic.core.draw.text.StrokeText;
import com.haxademic.core.media.DemoAssets;
import com.haxademic.core.render.FrameLoop;
import com.haxademic.core.ui.UI;

import processing.core.PFont;

public class Demo_StrokeText
extends PAppletHax {
	public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected String thickness = "thickness";
	protected String resolution = "resolution";

	protected void firstFrame() {
		UI.addTitle("Stroke text config");
		UI.addSlider(thickness, 1, 0, 20, 0.1f, false);
		UI.addSlider(resolution, 12, 4, 36, 1, false);
		UI.active(true);
	}

	protected void drawApp() {
		p.background(0);

		// set font
		PFont font = FontCacher.getFont(DemoAssets.fontInterPath, 90);
		FontCacher.setFontOnContext(p.g, font, p.color(255), 1.4f, PTextAlign.LEFT, PTextAlign.TOP);

		// draw text
		StrokeText.draw(p.g, "Hello", 300, 100, p.color(0, 255, 0), p.color(0), UI.value(thickness), UI.valueInt(resolution));

		// draw text that wraps
		font = FontCacher.getFont(DemoAssets.fontInterPath, 20);
		FontCacher.setFontOnContext(p.g, font, p.color(255), 1.4f, PTextAlign.LEFT, PTextAlign.TOP);
		StrokeText.draw(p.g, "Hello this will wrap if we have enough text", 300, 300, 150 + FrameLoop.osc(0.02f, 0, 150), 1000, p.color(0, 255, 255), p.color(0), UI.value(thickness)/2f, UI.valueInt(resolution));
	}

}


text:
<?php
namespace Lemon\ReportBundle\Report\Query;

use Twig_Environment;
use Twig_Error_Syntax;
use Lemon\ReportBundle\Report\Query\Renderer\Exception as RendererException;

class Renderer
{
    protected $report;
    protected $query;
    protected $twig;

    public function render($report, $values = array())
    {
        $this->report = $report;

        try {
            $template = $this->twig->createTemplate($this->report->getQuery());
            $this->query = $template->render(
                array_merge($this->report->getParameterArray(), $values)
            );

            return $this->query;
        } catch (Twig_Error_Syntax $e) {
            throw new RendererException($e->getMessage());
        }
    }

    public function getQuery()
    {
        return $this->query;
    }

    public function getParameters()
    {
        return $this->report->getParameters();
    }

    public function setTwig(Twig_Environment $twig)
    {
        $this->twig = $twig;
    }
}


text:
#include "outcome.h"

// ReRap Version 0.9
// Copyright 2011 Matthew Mikolay.
//
// This file is part of ReRap.
//
// ReRap 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 3 of the License, or
// (at your option) any later version.
//
// ReRap 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 ReRap.  If not, see <http://www.gnu.org/licenses/>.

/*** Constructor ***/
Outcome::Outcome()
{
	setStatus(S_SUCCESS);
	setObject(0);
}

/*** Constructor ***/
Outcome::Outcome(unsigned char pStatus)
{
	setStatus(pStatus);
	setObject(0);
}

/*** Set the status of this outcome ***/
void Outcome::setStatus(unsigned char pStatus)
{
	status = pStatus;
}

/*** Get the status of this outcome ***/
unsigned char Outcome::getStatus()
{
	return status;
}

/*** Set the object ***/
void Outcome::setObject(Object* pObj)
{
	obj = pObj;
}

/*** Get the object ***/
Object* Outcome::getObject()
{
	return obj;
}

/*** Destructor ***/
Outcome::~Outcome()
{
}


text:
use std::io;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};

fn main() {
    // Create client
    let (client, _status) =
        jack::Client::new("rust_jack_trans", jack::ClientOptions::NO_START_SERVER).unwrap();

    let transport = client.transport();
    let stop = Arc::new(AtomicBool::new(false));

    let show = {
        let stop = stop.clone();
        std::thread::spawn(move || {
            let mut state_last: Option<jack::TransportStatePosition> = None;
            while !stop.load(Ordering::Relaxed) {
                std::thread::sleep(std::time::Duration::from_millis(10));
                if let Ok(state) = transport.query() {
                    //print if state has changed
                    if state_last
                        .as_ref()
                        .map_or_else(|| true, |l| l.state != state.state)
                    {
                        println!("{:?}", state.state);
                    };
                    //print if bbt structure changes (ignoring tick and bar_start_tick)
                    if let Some(mut bbt) = state.pos.bbt() {
                        let print = if let Some(last) = &state_last {
                            if let Some(mut last) = last.pos.bbt() {
                                //zero out some details so we can just compare directly
                                bbt.tick = 0;
                                bbt.bar_start_tick = 0.0;
                                last.tick = 0;
                                last.bar_start_tick = 0.0;
                                bbt != last
                            } else {
                                true
                            }
                        } else {
                            true
                        };
                        if print {
                            println!(
                                "bar {} beat {} bpm {} sig: {}/{} tpb {}",
                                bbt.bar,
                                bbt.beat,
                                bbt.bpm,
                                bbt.sig_num,
                                bbt.sig_denom,
                                bbt.ticks_per_beat
                            );
                        }
                    }
                    state_last = Some(state);
                } else {
                    eprint!("couldn't get state");
                    break;
                }
            }
        })
    };

    // Wait for user input to quit
    println!("Press enter/return to quit...");
    let mut user_input = String::new();
    io::stdin().read_line(&mut user_input).ok();
    stop.store(true, Ordering::Relaxed);
    show.join().expect("failed to join");
}


text:
namespace Cauldron
{
    /// <summary>
    /// Describes the UWP device families
    /// </summary>
    public static class DeviceFamilies
    {
        /// <summary>
        /// Constant string for the Windows desktop device family
        /// </summary>
        public const string DeviceFamily_WindowsDesktop = "Windows.Desktop";

        /// <summary>
        /// Constant string for the Windows desktop IoT family
        /// </summary>
        public const string DeviceFamily_WindowsIoT = "Windows.IoT";

        /// <summary>
        /// Constant string for the Windows desktop mobile family
        /// </summary>
        public const string DeviceFamily_WindowsMobile = "Windows.Mobile";

        /// <summary>
        /// Constant string for the Windows desktop xbox family
        /// </summary>
        public const string DeviceFamily_WindowsXbox = "Windows.Xbox";
    }
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

Managed Object Types	Data Object Types	All Properties	All Methods

Enum -
						VirtualMachineTargetInfoConfigurationTag

Enum Description

         Describes how widely the endpoint is availabe in a cluster. Note that these
  fields are not neccessarily mutual-exclusive.

Enum Constants

Name	Description

clusterWide
      Indicates that this is available for all hosts in the cluster.

compliant
      Indicates that this device is part of the cluster compliant
  specification.

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <simpleType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="VirtualMachineTargetInfoConfigurationTag">
            <restriction base="xsd:string">
               <enumeration value="compliant"/>
               <enumeration value="clusterWide"/>
            </restriction>
         </simpleType></textarea>

Top of page

Managed Object Types	Data Object Types	All Properties	All Methods


text:
package com.makemyandroidapp.funtimes;

import android.util.Log;

/*******************
 *
 * @author Tim
 *
 * I sometimes use a static class like this to help make logging easier.
 * The advantage is I can be sure I only have one log tag for my whole activity
 * and I can easily switch off all of the logging (if I want to) when I am ready to
 * deploy the application.
 *******************/
public class Util {
	public static String logTag = "FunTimes";
	public static boolean debugging = true;

	public static void Log(String s){
		if(debugging){
			Log.i(logTag, s);
		}

	}
}


text:
"""File parsers for Nets AvtaleGiro and OCR Giro files."""

from typing import List

from netsgiro.constants import *
from netsgiro.enums import *
from netsgiro.objects import *
from netsgiro.utils import *

from netsgiro import constants, enums, objects, utils  # isort: skip

__version__ = '1.3.0'

__all__: List[str] = constants.__all__ + enums.__all__ + objects.__all__ + utils.__all__


text:
function CountedLockableContainer() { this.initialize.apply(this, arguments); };

(function(Parent) {

    'use strict';

    var _MSG_MAX_COUNT_REACHED =
            'The maximum amount of tolerable key mismatches are reached';

    function _addKeyMismatchCount() { this._keyMismatchCount++; };

    function _hasReachedMaxKeyMismatchCount() {
        return this.keyMismatchCount() >= this._MAX_KEY_MISMATCH_COUNT;
    };

    CountedLockableContainer.prototype = Object.create(Parent);
    CountedLockableContainer.prototype.constructor = CountedLockableContainer;

    CountedLockableContainer.prototype.initialize =
            function(key, maxKeyMismatchCount) {
        Parent.initialize.call(this, key);
        this._MAX_KEY_MISMATCH_COUNT = maxKeyMismatchCount;
    };

    CountedLockableContainer.prototype.tryUnlock = function(key, errback) {
        if (_hasReachedMaxKeyMismatchCount.call(this)) {
            return errback(_MSG_MAX_COUNT_REACHED);
        }
        this._tryUnlock(key, errback);
    };

    CountedLockableContainer.prototype.keyMismatchCount = function() {
        return this._keyMismatchCount;
    };

    CountedLockableContainer.prototype._initCaches = function() {
        Parent._initCaches.call(this);
        this._resetKeyMismatchCount();
    };

    CountedLockableContainer.prototype._tryUnlock = function(key, errback) {
        if (!this._isCorrectKey(key)) _addKeyMismatchCount.call(this);
        Parent.tryUnlock.call(this, key, errback);
        if (!_hasReachedMaxKeyMismatchCount.call(this)) return;
        errback(_MSG_MAX_COUNT_REACHED);
    };

    CountedLockableContainer.prototype._resetKeyMismatchCount = function() {
        this._keyMismatchCount = 0;
    };

    CountedLockableContainerUnitTest(CountedLockableContainer.prototype);

})(LockableContainer.prototype);


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of landing_page
 *
 * @author janim
 */
class Landing_page extends CI_Controller{
    public function __construct() {
        parent::__construct();
    }

    public function index(){
        session_start();
        if($_SESSION){
            $this->load->view('index');
        } else {
            $this->load->view('login');
        }
    }
    public function login_post(){
        if($this->input->post()){
            session_start();
            $user = $this->input->post('user');
            $pass = $this->input->post('pwd');
            $this->load->library('encryption');
            $this->load->model('usuario_model');
            $coded = $this->encryption->encrypt($pass);
            $var = $this->usuario_model->verificar_u($user,$coded);
            if($var != NULL){
                $_SESSION['nombre'] = $var->nombre;
                $_SESSION['categoria'] = $var->categoria;
                redirect('./index.php');
            } else {
                session_destroy();
                redirect('./index.php');
            }
        } else {
            echo 'hola';
        }
    }

    public function radio_player_post(){
        session_start();
        if($_SESSION){
            $data = array();
            $this->load->model('audio_model');
            $data['lAudio'] = $this->audio_model->listado_audios();
            $this->load->view('musicaRadioPlayer',$data);
        } else {
            $this->load->view('login');
        }
    }

    public function logout(){
        session_start();
        if($_SESSION){
            session_destroy();
            redirect('./index.php');
        }
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lloydia 6: 33 (1943)

#### Original name
Lambertella hicoriae Whetzel, 1943

### Remarks
null


text:
int main()
{
    {
        std::vector<MoveOnly, test_allocator<MoveOnly> > l(test_allocator<MoveOnly>(5));
        std::vector<MoveOnly, test_allocator<MoveOnly> > lo(test_allocator<MoveOnly>(5));
        for (int i = 1; i <= 3; ++i)
        {
            l.push_back(i);
            lo.push_back(i);
        }
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        std::vector<MoveOnly, test_allocator<MoveOnly> > l2(test_allocator<MoveOnly>(5));
        l2 = std::move(l);
        assert(l2 == lo);
        assert(l.empty());
        assert(l2.get_allocator() == lo.get_allocator());
        assert(is_contiguous_container_asan_correct(l2));
    }
    {
        std::vector<MoveOnly, test_allocator<MoveOnly> > l(test_allocator<MoveOnly>(5));
        std::vector<MoveOnly, test_allocator<MoveOnly> > lo(test_allocator<MoveOnly>(5));
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        for (int i = 1; i <= 3; ++i)
        {
            l.push_back(i);
            lo.push_back(i);
        }
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        std::vector<MoveOnly, test_allocator<MoveOnly> > l2(test_allocator<MoveOnly>(6));
        l2 = std::move(l);
        assert(l2 == lo);
        assert(!l.empty());
        assert(l2.get_allocator() == test_allocator<MoveOnly>(6));
        assert(is_contiguous_container_asan_correct(l2));
    }
    {
        std::vector<MoveOnly, other_allocator<MoveOnly> > l(other_allocator<MoveOnly>(5));
        std::vector<MoveOnly, other_allocator<MoveOnly> > lo(other_allocator<MoveOnly>(5));
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        for (int i = 1; i <= 3; ++i)
        {
            l.push_back(i);
            lo.push_back(i);
        }
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        std::vector<MoveOnly, other_allocator<MoveOnly> > l2(other_allocator<MoveOnly>(6));
        l2 = std::move(l);
        assert(l2 == lo);
        assert(l.empty());
        assert(l2.get_allocator() == lo.get_allocator());
        assert(is_contiguous_container_asan_correct(l2));
    }
    {
        std::vector<MoveOnly, min_allocator<MoveOnly> > l(min_allocator<MoveOnly>{});
        std::vector<MoveOnly, min_allocator<MoveOnly> > lo(min_allocator<MoveOnly>{});
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        for (int i = 1; i <= 3; ++i)
        {
            l.push_back(i);
            lo.push_back(i);
        }
        assert(is_contiguous_container_asan_correct(l));
        assert(is_contiguous_container_asan_correct(lo));
        std::vector<MoveOnly, min_allocator<MoveOnly> > l2(min_allocator<MoveOnly>{});
        l2 = std::move(l);
        assert(l2 == lo);
        assert(l.empty());
        assert(l2.get_allocator() == lo.get_allocator());
        assert(is_contiguous_container_asan_correct(l2));
    }
}


text:
App.Entity.Order = (function() {

	var orderId = 1;

	function Order( order ) {
		this.orderId = orderId++;

		this.customerId = order.customerId;
		this.shipmentDestination = order.shipmentDestination;
		this.paymentInformation = order.paymentInformation;
		this.customerContactInfo = order.customerContactInfo;
		this.shipmentMechanism = order.shipmentMechanism;
	}

	Order.validate = function( order ) {
		if (order === undefined) {
			throw new Error('no order passed');
		}

		// some existence checking here
		// you should do real validation!
		return order.customerId
			&& order.shipmentDestination
			&& order.paymentInformation
			&& order.customerContactInfo
			&& order.shipmentMechanism;
	};

	return Order;

})();


text:
#include "BiosSnp16.h"

/**
  PXE
  START UNDI
  Op-Code: PXENV_START_UNDI (0000h)
  Input: Far pointer to a PXENV_START_UNDI_T parameter structure that has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This service is used to pass the BIOS parameter registers to the UNDI driver. The UNDI driver is
  responsible for saving the information it needs to communicate with the hardware.
  This service is also responsible for hooking the Int 1Ah service routine
  Note: This API service must be called only once during UNDI Option ROM boot.
  The UNDI driver is responsible for saving this information and using it every time
  PXENV_UNDI_STARTUP is called.
  Service cannot be used in protected mode.
  typedef struct  {
      PXENV_STATUS Status;
      UINT16 AX;
      UINT16 BX;
      UINT16 DX;
      UINT16 DI;
      UINT16 ES;
  } PXENV_START_UNDI_T;
  Set before calling API service
  AX, BX, DX, DI, ES: BIOS initialization parameter registers. These
  fields should contain the same information passed to the option ROM
  initialization routine by the Host System BIOS. Information about the
  contents of these registers can be found in the [PnP], [PCI] and
  [BBS] specifications.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeStartUndi (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_START_UNDI_T      *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_START_UNDI_T),
          PXENV_START_UNDI
          );
}

/**
  PXE
  UNDI STARTUP
  Op-Code: PXENV_UNDI_STARTUP (0001h)
  Input: Far pointer to a PXENV_UNDI_STARTUP_T parameter structure that has been initialized by the
  caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This API is responsible for initializing the contents of the UNDI code & data segment for proper
  operation. Information from the !PXE structure and the first PXENV_START_UNDI API call is used
  to complete this initialization. The rest of the UNDI APIs will not be available until this call has
  been completed.
  Note: PXENV_UNDI_STARTUP must not be called again without first calling
  PXENV_UNDI_SHUTDOWN.
  PXENV_UNDI_STARTUP and PXENV_UNDI_SHUTDOWN are no longer responsible for
  chaining interrupt 1Ah. This must be done by the PXENV_START_UNDI and
  PXENV_STOP_UNDI API calls.
  This service cannot be used in protected mode.
  typedef struct
  {
      PXENV_STATUS Status;
  } PXENV_UNDI_STARTUP_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiStartup (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_STARTUP_T    *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_STARTUP_T),
          PXENV_UNDI_STARTUP
          );
}

/**
  PXE
  UNDI CLEANUP
  Op-Code: PXENV_UNDI_CLEANUP (0002h)
  Input: Far pointer to a PXENV_UNDI_CLEANUP_T parameter structure.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field
  in the parameter structure must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This call will prepare the network adapter driver to be unloaded from memory. This call must be
  made just before unloading the Universal NIC Driver. The rest of the API will not be available
  after this call executes.
  This service cannot be used in protected mode.
  typedef struct {
      PXENX_STATUS Status;
  } PXENV_UNDI_CLEANUP_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiCleanup (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_CLEANUP_T    *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_CLEANUP_T),
          PXENV_UNDI_CLEANUP
          );
}

/**
  PXE
  UNDI INITIALIZE
  Op-Code: PXENV_UNDI_INITIALIZE (0003h)
  Input: Far pointer to a PXENV_UNDI_INITIALIZE_T parameter structure that has been initialized by the
  caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call resets the adapter and programs it with default parameters. The default parameters used
  are those supplied to the most recent UNDI_STARTUP call. This routine does not enable the
  receive and transmit units of the network adapter to readily receive or transmit packets. The
  application must call PXENV_UNDI_OPEN to logically connect the network adapter to the network.
  This call must be made by an application to establish an interface to the network adapter driver.
  Note: When the PXE code makes this call to initialize the network adapter, it passes a NULL pointer for
  the Protocol field in the parameter structure.
  typedef struct {
    PXENV_STATUS Status;
    ADDR32 ProtocolIni;
    UINT8 reserved[8];
  } PXENV_UNDI_INITIALIZE_T;
  Set before calling API service
  ProtocolIni: Physical address of a memory copy of the driver
  module from the protocol.ini file obtained from the protocol manager
  driver (refer to the NDIS 2.0 specification). This parameter is
  supported for the universal NDIS driver to pass the information
  contained in the protocol.ini file to the NIC driver for any specific
  configuration of the NIC. (Note that the module identification in the
  protocol.ini file was done by NDIS.) This value can be NULL for any
  other application interfacing to the universal NIC driver
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiInitialize (
  IN     EFI_SIMPLE_NETWORK_DEV   *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_INITIALIZE_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_INITIALIZE_T),
          PXENV_UNDI_INITIALIZE
          );
}

/**
  Wrapper routine for reset adapter.

  PXE
  UNDI RESET ADAPTER
  Op-Code: PXENV_UNDI_RESET_ADAPTER (0004h)
  Input: Far pointer to a PXENV_UNDI_RESET_ADAPTER_t parameter structure that has been initialized
  by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call resets and reinitializes the network adapter with the same set of parameters supplied to
  Initialize Routine. Unlike Initialize, this call opens the adapter that is, it connects logically to the
  network. This routine cannot be used to replace Initialize or Shutdown calls.
  typedef struct {
    PXENV_STATUS Status;
    PXENV_UNDI_MCAST_ADDRESS_t    R_Mcast_Buf;
  } PXENV_UNDI_RESET_T;

  #define MAXNUM_MCADDR 8

  typedef struct {
    UINT16 MCastAddrCount;
    MAC_ADDR McastAddr[MAXNUM_MCADDR];
  } PXENV_UNDI_MCAST_ADDRESS_t;

  Set before calling API service
  R_Mcast_Buf: This is a structure of MCastAddrCount and
  McastAddr.
  MCastAddrCount: Number of multicast MAC addresses in the
  buffer.
  McastAddr: List of up to MAXNUM_MCADDR multicast MAC
  addresses.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance.
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.
  @param  RxFilter             Filter setting mask value for PXE recive .

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiResetNic (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_RESET_T      *PxeUndiTable,
  IN     UINT16                  RxFilter
  )
{
  PXENV_UNDI_OPEN_T   Open;
  PXENV_UNDI_CLOSE_T  Close;
  UINTN               Status;

  Status = MakePxeCall (
            SimpleNetworkDevice,
            PxeUndiTable,
            sizeof (PXENV_UNDI_RESET_T),
            PXENV_UNDI_RESET_NIC
            );
  if (!EFI_ERROR(Status)) {
    return Status;
  }

  Close.Status = PXENV_STATUS_SUCCESS;

  Status = MakePxeCall (
            SimpleNetworkDevice,
            &Close,
            sizeof (Close),
            PXENV_UNDI_CLOSE
            );
  if (EFI_ERROR(Status)) {
    return EFI_DEVICE_ERROR;
  }

  Status = MakePxeCall (
            SimpleNetworkDevice,
            PxeUndiTable,
            sizeof (PXENV_UNDI_RESET_T),
            PXENV_UNDI_RESET_NIC
            );
  if (EFI_ERROR(Status)) {
    return EFI_DEVICE_ERROR;
  }

  Open.Status       = PXENV_STATUS_SUCCESS;
  Open.OpenFlag     = 0;
  Open.PktFilter    = RxFilter;
  CopyMem (
    &Open.McastBuffer,
    &PxeUndiTable->R_Mcast_Buf,
    sizeof (PXENV_UNDI_MCAST_ADDR_T)
    );

  Status = MakePxeCall (
            SimpleNetworkDevice,
            &Open,
            sizeof (Open),
            PXENV_UNDI_OPEN
            );
  if (EFI_ERROR(Status)) {
    return EFI_DEVICE_ERROR;
  }

  return EFI_SUCCESS;
}

/**
  PXE
  UNDI SHUTDOWN
  Op-Code: PXENV_UNDI_SHUTDOWN (0005h)
  Input: Far pointer to a PXENV_UNDI_SHUTDOWN_T parameter.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call resets the network adapter and leaves it in a safe state for another driver to program it.
  Note: The contents of the PXENV_UNDI_STARTUP parameter structure need to be saved by the
  Universal NIC Driver in case PXENV_UNDI_INITIALIZE is called again.
  typedef struct
  {
    PXENV_STATUS Status;
  } PXENV_UNDI_SHUTDOWN_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiShutdown (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_SHUTDOWN_T   *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_SHUTDOWN_T),
          PXENV_UNDI_SHUTDOWN
          );
}

/**
  PXE
  UNDI OPEN
  Op-Code: PXENV_UNDI_OPEN (0006h)
  Input: Far pointer to a PXENV_UNDI_OPEN_T parameter structure that has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call activates the adapter network connection and sets the adapter ready to accept packets
  for transmit and receive.
  typedef struct {
    PXENV_STATUS Status;
    UINT16 OpenFlag;
    UINT16 PktFilter;
      #define FLTR_DIRECTED 0x0001
      #define FLTR_BRDCST 0x0002
      #define FLTR_PRMSCS 0x0004
      #define FLTR_SRC_RTG 0x0008
    PXENV_UNDI_MCAST_ADDRESS_t R_Mcast_Buf;
  } PXENV_UNDI_OPEN_T;
  Set before calling API service
  OpenFlag: This is an adapter specific input parameter. This is
  supported for the universal NDIS 2.0 driver to pass in the open flags
  provided by the protocol driver. (See the NDIS 2.0 specification.)
  This can be zero.
  PktFilter: Filter for receiving packets. This can be one, or more, of
  the FLTR_xxx constants. Multiple values are arithmetically or-ed
  together.
  directed packets are packets that may come to your MAC address
  or the multicast MAC address.
  R_Mcast_Buf: See definition in UNDI RESET ADAPTER (0004h).
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiOpen (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_OPEN_T       *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_OPEN_T),
          PXENV_UNDI_OPEN
          );
}

/**
  PXE
  UNDI CLOSE
  Op-Code: PXENV_UNDI_CLOSE (0007h)
  Input: Far pointer to a PXENV_UNDI_CLOSE_T parameter.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call disconnects the network adapter from the network. Packets cannot be transmitted or
  received until the network adapter is open again.
  typedef struct {
    PXENV_STATUS Status;
  } PXENV_UNDI_CLOSE_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiClose (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_CLOSE_T      *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_CLOSE_T),
          PXENV_UNDI_CLOSE
          );
}

/**
  PXE
  UNDI TRANSMIT PACKET
  Op-Code: PXENV_UNDI_TRANSMIT (0008h)
  Input: Far pointer to a PXENV_UNDI_TRANSMIT_T parameter structure that
  has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX.
  The status code must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This call transmits a buffer to the network. The media header
  for the packet can be filled by the calling protocol, but it might not be.
  The network adapter driver will fill it if required by the values in the
  parameter block. The packet is buffered for transmission provided there is
  an available buffer, and the function returns PXENV_EXIT_SUCCESS. If no
  buffer is available the function returns PXENV_EXIT_FAILURE with a status
  code of PXE_UNDI_STATUS__OUT OF_RESOURCE. The number of buffers is
  implementation-dependent. An interrupt is generated on completion of the
  transmission of one or more packets. A call to PXENV_UNDI_TRANSMIT is
  permitted in the context of a transmit complete interrupt.

  typedef struct {
    PXENV_STATUS Status;
    UINT8 Protocol;
      #define P_UNKNOWN 0
      #define P_IP 1
      #define P_ARP 2
      #define P_RARP 3
    UINT8 XmitFlag;
      #define XMT_DESTADDR 0x0000
      #define XMT_BROADCAST 0x0001
    SEGOFF16 DestAddr;
    SEGOFF16 TBD;
    UINT32 Reserved[2];
  } t_PXENV_UNDI_TRANSMIT;

  #define MAX_DATA_BLKS 8

  typedef struct {
    UINT16 ImmedLength;
    SEGOFF16 Xmit;
    UINT16 DataBlkCount;
    struct DataBlk {
      UINT8 TDPtrType;
      UINT8 TDRsvdByte;
      UINT16 TDDataLen;
      SEGOFF16 TDDataPtr;
    } DataBlock[MAX_DATA_BLKS];
  } PXENV_UNDI_TBD_T

  Set before calling API service
  Protocol: This is the protocol of the upper layer that is calling UNDI
  TRANSMIT call. If the upper layer has filled the media header, this
  field must be P_UNKNOWN.
  XmitFlag: If this flag is XMT_DESTADDR, the NIC driver expects a
  pointer to the destination media address in the field DestAddr. If
  XMT_BROADCAST, the NIC driver fills the broadcast address for the
  destination.
  TBD: Segment:Offset address of the transmit buffer descriptor.
  ImmedLength: Length of the immediate transmit buffer: Xmit.
  Xmit: Segment:Offset of the immediate transmit buffer.
  DataBlkCount: Number of blocks in this transmit buffer.
  TDPtrType:
  0 => 32-bit physical address in TDDataPtr (not supported in this
  version of PXE)
  1 => segment:offset in TDDataPtr which can be a real mode or 16-bit
  protected mode pointer
  TDRsvdByte: Reserved must be zero.
  TDDatalen: Data block length in bytes.
  TDDataPtr: Segment:Offset of the transmit block.
  DataBlock: Array of transmit data blocks.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiTransmit (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_TRANSMIT_T   *PxeUndiTable
  )
{
  EFI_STATUS  Status;

  Status = MakePxeCall (
            SimpleNetworkDevice,
            PxeUndiTable,
            sizeof (PXENV_UNDI_TRANSMIT_T),
            PXENV_UNDI_TRANSMIT
            );
  if (Status == EFI_SUCCESS) {
    return EFI_SUCCESS;
  }

  switch (PxeUndiTable->Status) {
  case PXENV_STATUS_OUT_OF_RESOURCES:
    return EFI_NOT_READY;

  default:
    return EFI_DEVICE_ERROR;
  }
}

/**
  PXE
  UNDI SET STATION ADDRESS
  Op-Code: PXENV_UNDI_SET_STATION_ADDRESS (000Ah)
  Input: Far pointer to a PXENV_UNDI_SET_STATION_ADDRESS_t parameter structure that has been
  initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call sets the MAC address to be the input value and is called before opening the network
  adapter. Later, the open call uses this variable as a temporary MAC address to program the
  adapter individual address registers.
  typedef struct {
    PXENV_STATUS Status;
    MAC_ADDR StationAddress;
  } PXENV_UNDI_SET_STATION_ADDR_T;
  Set before calling API service
  StationAddress: Temporary MAC address to be used for
  transmit and receive.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiSetStationAddr (
  IN     EFI_SIMPLE_NETWORK_DEV         *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_SET_STATION_ADDR_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_SET_STATION_ADDR_T),
          PXENV_UNDI_SET_STATION_ADDR
          );
}

/**
  PXE
  UNDI SET PACKET FILTER
  Op-Code: PXENV_UNDI_SET_PACKET_FILTER (000Bh)
  Input: Far pointer to a PXENV_UNDI_SET_PACKET_FILTER_T parameter structure that has been
  initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call resets the adapter's receive unit to accept a new filter, different from the one provided with
  the open call.
  typedef struct {
    PXENV_STATUS Status;
    UINT8 filter;
  } PXENV_UNDI_SET_PACKET_FILTER_T;
  Set before calling API service
  Filter: See the receive filter values in the UNDI OPEN
  (0006h) API description.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/

/**
  PXE
  UNDI GET INFORMATION
  Op-Code: PXENV_UNDI_GET_INFORMATION (000Ch)
  Input: Far pointer to a PXENV_UNDI_GET_INFORMATION_T parameter structure that has been
  initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This call copies the network adapter variables, including the MAC address, into the input buffer.
  Note: The PermNodeAddress field must be valid after PXENV_START_UNDI and
  PXENV_UNDI_STARTUP have been issued. All other fields must be valid after
  PXENV_START_UNDI, PXENV_UNDI_STARTUP and PXENV_UNDI_INITIALIZE have been
  called.
  typedef struct {
    PXENV_STATUS Status;
    UINT16 BaseIo;
    UINT16 IntNumber;
    UINT16 MaxTranUnit;
    UINT16 HwType;
      #define ETHER_TYPE 1
      #define EXP_ETHER_TYPE 2
      #define IEEE_TYPE 6
      #define ARCNET_TYPE 7
    UINT16 HwAddrLen;
    MAC_ADDR CurrentNodeAddress;
    MAC_ADDR PermNodeAddress;
    SEGSEL ROMAddress;
    UINT16 RxBufCt;
    UINT16 TxBufCt;
  } PXENV_UNDI_GET_INFORMATION_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  BaseIO: Adapter base I/O address.
  IntNumber: Adapter IRQ number.
  MaxTranUnit: Adapter maximum transmit unit.
  HWType: Type of protocol at the hardware level.
  HWAddrLen: Length of the hardware address.
  CurrentNodeAddress: Current hardware address.
  PermNodeAddress: Permanent hardware address.
  ROMAddress: Real mode ROM segment address.
  RxBufCnt: Receive queue length.
  TxBufCnt: Transmit queue length.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiGetInformation (
  IN     EFI_SIMPLE_NETWORK_DEV        *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_GET_INFORMATION_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_GET_INFORMATION_T),
          PXENV_UNDI_GET_INFORMATION
          );
}

/**
  PXE
  UNDI GET STATISTICS
  Op-Code: PXENV_UNDI_GET_STATISTICS (000Dh)
  Input: Far pointer to a PXENV_UNDI_GET_STATISTICS_T parameter structure that has been initialized
  by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call reads statistical information from the network adapter, and returns.
  typedef struct {
    PXENV_STATUS Status;
    UINT32 XmtGoodFrames;
    UINT32 RcvGoodFrames;
    UINT32 RcvCRCErrors;
    UINT32 RcvResourceErrors;
  } PXENV_UNDI_GET_STATISTICS_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  XmtGoodFrames: Number of successful transmissions.
  RcvGoodFrames: Number of good frames received.
  RcvCRCErrors: Number of frames received with CRC
  error.
  RcvResourceErrors: Number of frames discarded
  because receive queue was full.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiGetStatistics (
  IN     EFI_SIMPLE_NETWORK_DEV       *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_GET_STATISTICS_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_GET_STATISTICS_T),
          PXENV_UNDI_GET_STATISTICS
          );
}

/**
  PXE
  UNDI CLEAR STATISTICS
  Op-Code: PXENV_UNDI_CLEAR_STATISTICS (000Eh)
  Input: Far pointer to a PXENV_UNDI_CLEAR_STATISTICS_T parameter.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This call clears the statistical information from the network adapter.
  typedef struct {
    PXENV_STATUS Status;
  } PXENV_UNDI_CLEAR_STATISTICS_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiClearStatistics (
  IN     EFI_SIMPLE_NETWORK_DEV         *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_CLEAR_STATISTICS_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_CLEAR_STATISTICS_T),
          PXENV_UNDI_CLEAR_STATISTICS
          );
}

/**
  PXE
  UNDI INITIATE DIAGS
  Op-Code: PXENV_UNDI_INITIATE_DIAGS (000Fh)
  Input: Far pointer to a PXENV_UNDI_INITIATE_DIAGS_T parameter.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the
  PXENV_STATUS_xxx constants.
  Description: This call can be used to initiate the run-time diagnostics. It causes the network adapter to run
  hardware diagnostics and to update its status information.
  typedef struct {
    PXENV_STATUS Status;
  } PXENV_UNDI_INITIATE_DIAGS_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/

/**
  PXE
  UNDI FORCE INTERRUPT
  Op-Code: PXENV_UNDI_FORCE_INTERRUPT (0010h)
  Input: Far pointer to a PXENV_UNDI_FORCE_INTERRUPT_T parameter structure that has been
  initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call forces the network adapter to generate an interrupt. When a receive interrupt occurs, the
  network adapter driver usually queues the packet and calls the application's callback receive
  routine with a pointer to the packet received. Then, the callback routine either can copy the packet
  to its buffer or can decide to delay the copy to a later time. If the packet is not immediately copied,
  the network adapter driver does not remove it from the input queue. When the application wants to
  copy the packet, it can call the PXENV_UNDI_FORCE_INTERRUPT routine to simulate the receive
  interrupt.
  typedef struct {
    PXENV_STATUS Status;
  } PXENV_UNDI_FORCE_INTERRUPT_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/

/**
  PXE
  UNDI GET MULTICAST ADDRESS
  Op-Code: PXENV_UNDI_GET_MCAST_ADDRESS (0011h)
  Input: Far pointer to a PXENV_GET_MCAST_ADDRESS_t parameter structure that has been initialized
  by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This call converts the given IP multicast address to a hardware multicast address.
  typedef struct  {
    PXENV_STATUS Status;
    IP4 InetAddr;
    MAC_ADDR MediaAddr;
  } PXENV_UNDI_GET_MCAST_ADDR_T;
  Set before calling API service
  InetAddr: IP multicast address.
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  MediaAddr: MAC multicast address.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiGetMcastAddr (
  IN     EFI_SIMPLE_NETWORK_DEV       *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_GET_MCAST_ADDR_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_GET_MCAST_ADDR_T),
          PXENV_UNDI_GET_MCAST_ADDR
          );
}

/**
  PXE
  UNDI GET NIC TYPE
  Op-Code: PXENV_UNDI_GET_NIC_TYPE (0012h)
  Input: Far pointer to a PXENV_UNDI_GET_NIC_TYPE parameter structure that has been initialized by
  the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants. If the PXENV_EXIT_SUCCESS is returned the parameter structure must contain the
  NIC information.
  Description: This call, if successful, provides the NIC-specific information necessary to identify the network
  adapter that is used to boot the system.
  Note: The application first gets the DHCPDISCOVER packet using GET_CACHED_INFO and checks if
  the UNDI is supported before making this call. If the UNDI is not supported, the NIC-specific
  information can be obtained from the DHCPDISCOVER packet itself.
  PXENV_START_UNDI, PXENV_UNDI_STARTUP and PXENV_UNDI_INITIALIZE must be called
  before the information provided is valid.
  typedef {
    PXENV_STATUS Status;
    UINT8 NicType;
      #define PCI_NIC 2
      #define PnP_NIC 3
      #define CardBus_NIC 4
    Union {
      Struct {
        UINT16 Vendor_ID;
        UINT16 Dev_ID;
        UINT8 Base_Class;
        UINT8 Sub_Class;
        UINT8 Prog_Intf;
        UINT8 Rev;
        UINT16 BusDevFunc;
        UINT16 SubVendor_ID;
        UINT16 SubDevice_ID;
      } pci, cardbus;
      struct {
        UINT32 EISA_Dev_ID;
        UINT8 Base_Class;
        UINT8 Sub_Class;
        UINT8 Prog_Intf;
        UINT16 CardSelNum;
      } pnp;
    } info;
  } PXENV_UNDI_GET_NIC_TYPE_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  NICType: Type of NIC information stored in the parameter
  structure.
  Info: Information about the fields in this union can be found
  in the [PnP] and [PCI] specifications

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiGetNicType (
  IN     EFI_SIMPLE_NETWORK_DEV     *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_GET_NIC_TYPE_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_GET_NIC_TYPE_T),
          PXENV_UNDI_GET_NIC_TYPE
          );
}

/**
  PXE
  UNDI GET IFACE INFO
  Op-Code: PXENV_UNDI_GET_IFACE_INFO (0013h)
  Input: Far pointer to a PXENV_UNDI_GET_IFACE_INFO_t parameter structure that has been initialized
  by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants. If the PXENV_EXIT_SUCCESS is returned, the parameter structure must contain the
  interface specific information.
  Description: This call, if successful, provides the network interface specific information such as the interface
  type at the link layer (Ethernet, Tokenring) and the link speed. This information can be used in the
  universal drivers such as NDIS or Miniport to communicate to the upper protocol modules.
  Note: UNDI follows the NDIS2 specification in giving this information. It is the responsibility of the
  universal driver to translate/convert this information into a format that is required in its specification
  or to suit the expectation of the upper level protocol modules.
  PXENV_START_UNDI, PXENV_UNDI_STARTUP and PXENV_UNDI_INITIALIZE must be called
  before the information provided is valid.
  typedef struct {
    PXENV_STATUS Status
    UINT8 IfaceType[16];
    UINT32 LinkSpeed;
    UINT32 ServiceFlags;
    UINT32 Reserved[4];
  } PXENV_UNDI_GET_NDIS_INFO_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  IfaceType: Name of MAC type in ASCIIZ format. This is
  used by the universal NDIS driver to specify its driver type
  to the protocol driver.
  LinkSpeed: Defined in the NDIS 2.0 specification.
  ServiceFlags: Defined in the NDIS 2.0 specification.
  Reserved: Must be zero.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiGetNdisInfo (
  IN     EFI_SIMPLE_NETWORK_DEV      *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_GET_NDIS_INFO_T  *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_GET_NDIS_INFO_T),
          PXENV_UNDI_GET_NDIS_INFO
          );
}

/**
  PXE
  UNDI ISR
  Op-Code: PXENV_UNDI_ISR (0014h)
  Input: Far pointer to a PXENV_UNDI_ISR_T parameter structure that has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This API function will be called at different levels of processing the interrupt. The FuncFlag field in
  the parameter block indicates the operation to be performed for the call. This field is filled with the
  status of that operation on return.
  Note: Interrupt Service Routine Operation:
  In this design the UNDI does not hook the interrupt for the Network Interface. Instead, the
  application or the protocol driver hooks the interrupt and calls UNDI with the PXENV_UNDI_ISR
  API call for interrupt verification (PXENV_UNDI_ISR_IN_START) and processing
  (PXENV_UNDI_ISR_IN_PROCESS and PXENV_UNDI_ISR_GET_NEXT).
  When the Network Interface HW generates an interrupt the protocol driver interrupt service
  routine (ISR) gets control and takes care of the interrupt processing at the PIC level. The ISR then
  calls the UNDI using the PXENV_UNDI_ISR API with the value PXENV_UNDI_ISR_IN_START for
  the FuncFlag parameter. At this time UNDI must disable the interrupts at the Network Interface
  level and read any status values required to further process the interrupt. UNDI must return as
  quickly as possible with one of the two values, PXENV_UNDI_ISR_OUT_OURS or
  PXENV_UNDI_ISR_OUT_NOT_OURS, for the parameter FuncFlag depending on whether the
  interrupt was generated by this particular Network Interface or not.
  If the value returned in FuncFlag is PXENV_UNDI_ISR_OUT_NOT_OURS, then the interrupt was
  not generated by our NIC, and interrupt processing is complete.
  If the value returned in FuncFlag is PXENV_UNDI_ISR_OUT_OURS, the protocol driver must start
  a handler thread and send an end-of-interrupt (EOI) command to the PIC. Interrupt processing is
  now complete.
  The protocol driver strategy routine will call UNDI using this same API with FuncFlag equal to
  PXENV_UNDI_ISR_IN_PROCESS. At this time UNDI must find the cause of this interrupt and
  return the status in the FuncFlag. It first checks if there is a frame received and if so it returns the
  first buffer pointer of that frame in the parameter block.
  The protocol driver calls UNDI repeatedly with the FuncFlag equal to
  PXENV_UNDI_ISR_IN_GET_NEXT to get all the buffers in a frame and also all the received
  frames in the queue. On this call, UNDI must remember the previous buffer given to the protoco,l
  remove it from the receive queue and recycle it. In case of a multi-buffered frame, if the previous
  buffer is not the last buffer in the frame it must return the next buffer in the frame in the parameter
  block. Otherwise it must return the first buffer in the next frame.
  If there is no received frame pending to be processed, UNDI processes the transmit completes and
  if there is no other interrupt status to be processed, UNDI re-enables the interrupt at the
  NETWORK INTERFACE level and returns PXENV_UNDI_ISR_OUT_DONE in the FuncFlag.
  IMPORTANT: It is possible for the protocol driver to be interrupted again while in the
  strategy routine when the UNDI re-enables interrupts.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiIsr (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_UNDI_ISR_T        *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_UNDI_ISR_T),
          PXENV_UNDI_ISR
          );
}

/**
  PXE
  STOP UNDI
  Op-Code: PXENV_STOP_UNDI (0015h)
  Input: Far pointer to a PXENV_STOP_UNDI_T parameter structure that has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This routine is responsible for unhooking the Int 1Ah service routine.
  Note: This API service must be called only once at the end of UNDI Option ROM boot. One of the valid
  status codes is PXENV_STATUS_KEEP. If this status is returned, UNDI must not be removed from
  base memory. Also, UNDI must not be removed from base memory if BC is not removed from base
  memory.
  Service cannot be used in protected mode.
  typedef struct {
    PXENV_STATUS Status;
  } PXENV_STOP_UNDI_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/
EFI_STATUS
PxeUndiStop (
  IN     EFI_SIMPLE_NETWORK_DEV  *SimpleNetworkDevice,
  IN OUT PXENV_STOP_UNDI_T       *PxeUndiTable
  )
{
  return MakePxeCall (
          SimpleNetworkDevice,
          PxeUndiTable,
          sizeof (PXENV_STOP_UNDI_T),
          PXENV_STOP_UNDI
          );
}

/**
  PXE
  UNDI GET STATE
  Op-Code: PXENV_UNDI_GET_STATE (0015h)
  Input: Far pointer to a PXENV_UNDI_GET_STATE_T parameter.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants. The UNDI_STATE field in the parameter structure must be set to one of the valid state
  constants
  Description: This call can be used to obtain state of the UNDI engine in order to avoid issuing adverse call
  sequences
  typedef struct {
    #define PXE_UNDI_GET_STATE_STARTED 1
    #define PXE_UNDI_GET_STATE_INITIALIZED 2
    #define PXE_UNDI_GET_STATE_OPENED 3
    PXENV_STATUS Status;
    UINT8 UNDIstate;
  } PXENV_UNDI_GET_STATE_T;
  Set before calling API service
  N/A
  Returned from API service
  Status: See the PXENV_STATUS_xxx constants.
  State: See definitions of the state constants.
  Note. UNDI implementation is responsible for maintaining
  internal state machine.
  UNDI ISR
  Op-Code: PXENV_UNDI_ISR (0014h)
  Input: Far pointer to a t_PXENV_UNDI_ISR parameter structure that has been initialized by the caller.
  Output: PXENV_EXIT_SUCCESS or PXENV_EXIT_FAILURE must be returned in AX. The status field in
  the parameter structure must be set to one of the values represented by the PXENV_STATUS_xxx
  constants.
  Description: This API function will be called at different levels of processing the interrupt. The FuncFlag field in
  the parameter block indicates the operation to be performed for the call. This field is filled with the
  status of that operation on return.

  @param  SimpleNetworkDevice   Device instance
  @param  PxeUndiTable          Point to structure which hold parameter and return value
                                for option ROM call.

  @return Return value of PXE option ROM far call.
**/


text:
Showdown Boilerplate
========================================================================

Showdown Boilerplate is a template for private servers of [Pokémon Showdown][1]. Pokémon Showdown is created [Zarel][2].

What is a boilerplate? Boilerplate is any text that is or can be reused in new contexts or applications without being greatly changed from the original.

This repository contains the files needed to set up your own Pokémon Showdown server with all the amazing stuff that Pokémon Showdown private servers like Frost and Pandora has. This also includes [Pokemon-Showdown-Addons][3] created by [kota][4].

For more information on Pokémon Showdown, setting up your own server, or viewing the credits, go visit the main [Pokémon Showdown repository][1].

  [1]: https://github.com/Zarel/Pokemon-Showdown
  [2]: https://github.com/Zarel
  [3]: https://github.com/kotarou3/Pokemon-Showdown-Addons
  [4]: https://github.com/kotarou3

Features
------------------------------------------------------------------------

* Single Process Hack for improve performance.
* Up-to-date with [Pokemon Showdown][1]'s latest features.
* Money (bucks) system for winning tournaments.
* Polls for voting
* Profile command to check to see when the user's last online, their money, etc.
* A bunch of useful commands like /away, /hide, /poof, etc.

_More coming soon_

Configuration
------------------------------------------------------------------------

### Setting up files

Create __about.csv__, __elo.csv__, __money.csv__, __lastSeen.csv__, and __tourWins.csv__ files in __config__ folder.

### Modifying core

* For profile, you can change the color property. (_Line 69_) and also change the custom avatar url to your own server. (_Line 74 & Line 80_)
* For shop, you can add, remove, or change items in the shop.
In the array, each index means [Command, Description, Cost]. (_Lines 244 - 252_)
* For tournaments, you can change the amount of users it takes for the winner to win money in tournaments/frontend.js.
If you decrease the amount of users require, also decrease the amount divided by the tourSize. For example, if you changed
it from 8 to 4. You would change the amount divided by the tourSize from 10 to 5. (_Lines 597-598_)

License
------------------------------------------------------------------------

Pokémon Showdown's server is distributed under the terms of the [MIT License][5].

  [5]: https://github.com/Zarel/Pokemon-Showdown/blob/master/LICENSE