text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class uk_co_progger_alienFXLite_led_LEDController */

#ifndef _Included_uk_co_progger_alienFXLite_led_LEDController
#define _Included_uk_co_progger_alienFXLite_led_LEDController
#ifdef __cplusplus
extern "C" {
#endif
#undef uk_co_progger_alienFXLite_led_LEDController_ALLPOWERFULL_ALIENFX
#define uk_co_progger_alienFXLite_led_LEDController_ALLPOWERFULL_ALIENFX 1L
#undef uk_co_progger_alienFXLite_led_LEDController_AREA51_ALIENFX
#define uk_co_progger_alienFXLite_led_LEDController_AREA51_ALIENFX 2L
#undef uk_co_progger_alienFXLite_led_LEDController_NOT_FOUND
#define uk_co_progger_alienFXLite_led_LEDController_NOT_FOUND 0L
/*
 * Class:     uk_co_progger_alienFXLite_led_LEDController
 * Method:    initialize
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_uk_co_progger_alienFXLite_led_LEDController_initialize
  (JNIEnv *, jclass);

/*
 * Class:     uk_co_progger_alienFXLite_led_LEDController
 * Method:    write
 * Signature: ([B)I
 */
JNIEXPORT jint JNICALL Java_uk_co_progger_alienFXLite_led_LEDController_write
  (JNIEnv *, jclass, jbyteArray);

/*
 * Class:     uk_co_progger_alienFXLite_led_LEDController
 * Method:    read
 * Signature: ()[B
 */
JNIEXPORT jbyteArray JNICALL Java_uk_co_progger_alienFXLite_led_LEDController_read
  (JNIEnv *, jclass);

/*
 * Class:     uk_co_progger_alienFXLite_led_LEDController
 * Method:    destroy
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_uk_co_progger_alienFXLite_led_LEDController_destroy
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

redpajama_set_name: RedPajamaGithub


text:
title: Use BR to Back Up Cluster Data
summary: Learn how to back up data using BR commands
---

# Use BR to Back Up Cluster Data

This document describes how to back up TiDB cluster data in the following scenarios:

- [Back up TiDB cluster snapshots](#back-up-tidb-cluster-snapshots)
- [Back up a database](#back-up-a-database)
- [Back up a table](#back-up-a-table)
- [Back up multiple tables with table filter](#back-up-multiple-tables-with-table-filter)
- [Back up data to external storage](#back-up-data-to-external-storage)
- [Back up incremental data](#back-up-incremental-data)
- [Encrypt backup data](#encrypt-backup-data)

If you are not familiar with the backup and restore tools, it is recommended that you read the following documents to fully understand usage principles and methods of these tools:

- [BR Overview](/br/backup-and-restore-overview.md)
- [Use BR Command-line for Backup and Restoration](/br/use-br-command-line-tool.md)

If you need to back up a small amount of data (for example, less than 50 GB) and do not require high backup speed, you can use Dumpling to export data to implement backup. For detailed backup operations, see [Use Dumpling to back up full data](/backup-and-restore-using-dumpling-lightning.md#use-dumpling-to-back-up-full-data).

## Back up TiDB cluster snapshots

A snapshot of a TiDB cluster contains only the latest and transactionally consistent data at a specific time. You can back up the latest or specified snapshot data of a TiDB cluster by running the `br backup full` command. To get help on this command, run the `br backup full --help` command.

Example: Back up the snapshot generated at `2022-01-30 07:42:23` to the `2022-01-30/` directory in the `backup-data` bucket of Amazon S3.

{{< copyable "shell-regular" >}}

```shell
br backup full \
    --pd "${PDIP}:2379" \
    --backupts '2022-01-30 07:42:23' \
    --storage "s3://backup-data/2022-01-30/" \
    --ratelimit 128 \
    --log-file backupfull.log
```

In the preceding command:

- `--backupts`: The physical time of the snapshot. If data of this snapshot is processed by Garbage Collection (GC), the `br backup` command will exit with an error. If you leave this parameter unspecified, BR picks the snapshot corresponding to the backup start time.
- `--ratelimit`: The maximum speed **per TiKV** performing backup tasks (in MiB/s).
- `--log-file`: The target file for BR logging.

During backup, a progress bar is displayed in the terminal, as shown below. When the progress bar advances to 100%, the backup is complete.

```shell
br backup full \
    --pd "${PDIP}:2379" \
    --storage "s3://backup-data/2022-01-30/" \
    --ratelimit 128 \
    --log-file backupfull.log
Full Backup <---------/................................................> 17.12%.
```

After the backup is completed, BR compares the checksum of the backup data with the [admin checksum table](/sql-statements/sql-statement-admin-checksum-table.md) of the cluster to ensure data correctness and security.

## Back up a database or a table

BR supports backing up partial data of a specified database or table from a cluster snapshot or incremental data backup. This feature allows you to filter out unwanted data from snapshot backup and incremental data backup, and back up only business-critical data.

### Back up a database

To back up a database in a cluster, run the `br backup db` command. To get help on this command, run the `br backup db --help` command.

Example: Back up the `test` database to the `db-test/2022-01-30/` directory in the `backup-data` bucket of Amazon S3.

{{< copyable "shell-regular" >}}

```shell
br backup db \
    --pd "${PDIP}:2379" \
    --db test \
    --storage "s3://backup-data/db-test/2022-01-30/" \
    --ratelimit 128 \
    --log-file backuptable.log
```

In the preceding command, `--db` specifies the database name, and other parameters are the same as those in [Back up TiDB cluster snapshots](#back-up-tidb-cluster-snapshots).

### Back up a table

To back up a table in a cluster, run the `br backup table` command. To get help on this command, run the `br backup table --help` command.

Example: Back up `test.usertable` to the `table-db-usertable/2022-01-30/` directory in the `backup-data` bucket of Amazon S3.

{{< copyable "shell-regular" >}}

```shell
br backup table \
    --pd "${PDIP}:2379" \
    --db test \
    --table usertable \
    --storage "s3://backup-data/table-db-usertable/2022-01-30/" \
    --ratelimit 128 \
    --log-file backuptable.log
```

In the preceding command, `--db` and `--table` specify the database name and table name respectively, and other parameters are the same as those in [Back up TiDB cluster snapshots](#back-up-tidb-cluster-snapshots).

### Back up multiple tables with table filter

To back up multiple tables with more criteria, run the `br backup full` command and specify the [table filters](/table-filter.md) with `--filter` or `-f`.

Example: Back up `db*.tbl*` data of a table to the `table-filter/2022-01-30/` directory in the `backup-data` bucket of Amazon S3.

{{< copyable "shell-regular" >}}

```shell
br backup full \
    --pd "${PDIP}:2379" \
    --filter 'db*.tbl*' \
    --storage "s3://backup-data/table-filter/2022-01-30/" \
    --ratelimit 128 \
    --log-file backupfull.log
```

## Back up data to external storage

BR supports backing up data to Amazon S3, Google Cloud Storage (GCS), Azure Blob Storage, NFS, or other S3-compatible file storage services. For details, see the following documents:

- [Back up data on Amazon S3 using BR](/br/backup-storage-S3.md)
- [Back up data on Google Cloud Storage using BR](/br/backup-storage-gcs.md)
- [Back up data on Azure Blob Storage using BR](/br/backup-storage-azblob.md)

## Back up incremental data

> **Warning:**
>
> This is still an experimental feature. It is **NOT** recommended that you use it in the production environment.

Incremental data of a TiDB cluster is differentiated data between the snapshot of a starting point and that of an end point. Compared with snapshot data, incremental data is smaller and therefore it is a supplementary to snapshot backup, which reduces the volume of backup data.

To back up incremental data, run the `br backup` command with **the last backup timestamp** `--lastbackupts` specified. To get `--lastbackupts`, run the `validate` command. The following is an example:

{{< copyable "shell-regular" >}}

```shell
LAST_BACKUP_TS=`br validate decode --field="end-version" -s s3://backup-data/2022-01-30/ | tail -n1`
```

> **Note:**
>
> - You need to save the incremental backup data under a different path from the previous snapshot backup.
> - GC safepoint must be prior to `lastbackupts`. The defalt GC lifetime is 10 minutes in TiDB, which means that TiDB only backs up incremental data generated in the last 10 minutes. To back up earlier incremental data, you need to [adjust TiDB GC Lifetime setting](/system-variables.md#tidb_gc_life_time-new-in-v50).

{{< copyable "shell-regular" >}}

```shell
br backup full\
    --pd ${PDIP}:2379 \
    --ratelimit 128 \
    --storage "s3://backup-data/2022-01-30/incr" \
    --lastbackupts ${LAST_BACKUP_TS}
```

The preceding command backs up the incremental data between `(LAST_BACKUP_TS, current PD timestamp]` and the DDLs generated during this time period. When restoring incremental data, BR restores all DDLs first, and then restores data.

## Encrypt backup data

> **Warning:**
>
> This is still an experimental feature. It is **NOT** recommended that you use it in the production environment.

BR supports encrypting backup data at the backup end and at the storage end when backing up to Amazon S3. You can choose either encryption method as required.

### Encrypt backup data at the backup end

Since TiDB v5.3.0, you can encrypt backup data by configuring the following parameters:

- `--crypter.method`: Encryption algorithm, which can be `aes128-ctr`, `aes192-ctr`, or `aes256-ctr`. The default value is `plaintext`, indicating that data is not encrypted.
- `--crypter.key`: Encryption key in hexadecimal string format. It is a 128-bit (16 bytes) key for the algorithm `aes128-ctr`, 24-byte key for the algorithm `aes192-ctr`, and 32-byte key for the algorithm `aes256-ctr`.
- `--crypter.key-file`: The key file. You can directly pass in the file path where the key is stored as a parameter without passing in "crypter.key".

Example: Encrypt backup data at the backup end.

{{< copyable "shell-regular" >}}

```shell
br backup full\
    --pd ${PDIP}:2379 \
    --storage "s3://backup-data/2022-01-30/"  \
    --crypter.method aes128-ctr \
    --crypter.key 0123456789abcdef0123456789abcdef
```

> **Note:**
>
> - If the key is lost, the backup data cannot be restored to the cluster.
> - The encryption feature needs to be used on BR tools and TiDB clusters v5.3.0 or later versions. The encrypted backup data cannot be restored on clusters earlier than v5.3.0.

### Encrypt backup data when backing up to Amazon S3

BR supports server-side encryption (SSE) when backing up data to S3. In this scenario, you can use AWS KMS keys you have created to encrypt data. For details, see [BR S3 server-side encryption](/encryption-at-rest.md#br-s3-server-side-encryption).

## Backup performance and impact

The backup feature has some impact on cluster performance (transaction latency and QPS). However, you can mitigate the impact by adjusting the number of backup threads [`backup.num-threads`](/tikv-configuration-file.md#num-threads-1) or by adding more clusters.

To illustrate the impact of backup, this document lists the test conclusions of several snapshot backup tests:

- (5.3.0 and earlier) When the backup threads of BR on a TiKV node takes up 75% of the total CPU of the node, the QPS is reduced by 30% of the original QPS.
- (5.4.0 and later) When there are no more than `8` threads of BR on a TiKV node and the cluster's total CPU utilization does not exceed 80%, the impact of BR tasks on the cluster (write and read) is 20% at most.
- (5.4.0 and later) When there are no more than `8` threads of BR on a TiKV node and the cluster's total CPU utilization does not exceed 75%, the impact of BR tasks on the cluster (write and read) is 10% at most.
- (5.4.0 and later) When there are no more than `8` threads of BR on a TiKV node and the cluster's total CPU utilization does not exceed 60%, BR tasks has little impact on the cluster (write and read).

You can mitigate impact on cluster performance by reducing the number of backup threads. However, this might cause backup performance to deteriorate. Based on the preceding test results: (On a single TiKV node) the backup speed is proportional to the number of backup threads. When the number of threads is small, the backup speed is about 20 MB/thread. For example, a single node with 5 backup threads can deliver a backup speed of 100 MB/s.

> **Note:**
>
> The impact and speed of backup depends much on cluser configuration, deployment, and running services. The preceding test conclusions, based on simulation tests in many scenarios and verified in some customer sites, are worthy of reference. However, the exact impact and performance cap may vary depending on the scenarios. Therefore, you should always run the test and verify the test results.

 Since v5.3.0, BR introduces the auto tunning feature (enabled by default) to adjust the number of backup threads. It can maintain the CPU utilization of the cluster below 80% during backup tasks. For details, see [BR Auto-Tune](/br/br-auto-tune.md).


text:
package org.apache.hadoop.mapred.nativetask.handlers;

import java.io.Closeable;
import java.io.IOException;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.TaskAttemptID;
import org.apache.hadoop.mapred.nativetask.Command;
import org.apache.hadoop.mapred.nativetask.CommandDispatcher;
import org.apache.hadoop.mapred.nativetask.DataChannel;
import org.apache.hadoop.mapred.nativetask.ICombineHandler;
import org.apache.hadoop.mapred.nativetask.INativeHandler;
import org.apache.hadoop.mapred.nativetask.NativeBatchProcessor;
import org.apache.hadoop.mapred.nativetask.TaskContext;
import org.apache.hadoop.mapred.nativetask.util.NativeTaskOutput;
import org.apache.hadoop.mapred.nativetask.util.OutputUtil;
import org.apache.hadoop.mapred.nativetask.util.ReadWriteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Java Record Reader + Java Mapper + Native Collector
 */
@SuppressWarnings("unchecked")
@InterfaceAudience.Private
public class NativeCollectorOnlyHandler<K, V> implements CommandDispatcher, Closeable {

  public static final String NAME = "NativeTask.MCollectorOutputHandler";
  private static final Logger LOG =
      LoggerFactory.getLogger(NativeCollectorOnlyHandler.class);
  public static final Command GET_OUTPUT_PATH =
      new Command(100, "GET_OUTPUT_PATH");
  public static final Command GET_OUTPUT_INDEX_PATH =
      new Command(101, "GET_OUTPUT_INDEX_PATH");
  public static final Command GET_SPILL_PATH =
      new Command(102, "GET_SPILL_PATH");
  public static final Command GET_COMBINE_HANDLER =
      new Command(103, "GET_COMBINE_HANDLER");

  private NativeTaskOutput output;
  private int spillNumber = 0;
  private ICombineHandler combinerHandler = null;
  private final BufferPusher<K, V> kvPusher;
  private final INativeHandler nativeHandler;
  private boolean closed = false;

  public static <K, V> NativeCollectorOnlyHandler<K, V> create(TaskContext context)
    throws IOException {

    ICombineHandler combinerHandler = null;
    try {
      final TaskContext combineContext = context.copyOf();
      combineContext.setInputKeyClass(context.getOutputKeyClass());
      combineContext.setInputValueClass(context.getOutputValueClass());

      combinerHandler = CombinerHandler.create(combineContext);
    } catch (final ClassNotFoundException e) {
      throw new IOException(e);
    }

    if (null != combinerHandler) {
      LOG.info("[NativeCollectorOnlyHandler] combiner is not null");
    }

    final INativeHandler nativeHandler = NativeBatchProcessor.create(
      NAME, context.getConf(), DataChannel.OUT);
    final BufferPusher<K, V> kvPusher = new BufferPusher<K, V>(
        (Class<K>)context.getOutputKeyClass(),
        (Class<V>)context.getOutputValueClass(),
        nativeHandler);

    return new NativeCollectorOnlyHandler<K, V>(context, nativeHandler, kvPusher, combinerHandler);
  }

  protected NativeCollectorOnlyHandler(TaskContext context, INativeHandler nativeHandler,
      BufferPusher<K, V> kvPusher, ICombineHandler combiner) throws IOException {
    Configuration conf = context.getConf();
    TaskAttemptID id = context.getTaskAttemptId();
    if (null == id) {
      this.output = OutputUtil.createNativeTaskOutput(conf, "");
    } else {
      this.output = OutputUtil.createNativeTaskOutput(context.getConf(), context.getTaskAttemptId()
        .toString());
    }
    this.combinerHandler = combiner;
    this.kvPusher = kvPusher;
    this.nativeHandler = nativeHandler;
    nativeHandler.setCommandDispatcher(this);
  }

  public void collect(K key, V value, int partition) throws IOException {
    kvPusher.collect(key, value, partition);
  };

  public void flush() throws IOException {
  }

  @Override
  public void close() throws IOException {
    if (closed) {
      return;
    }

    if (null != kvPusher) {
      kvPusher.close();
    }

    if (null != combinerHandler) {
      combinerHandler.close();
    }

    if (null != nativeHandler) {
      nativeHandler.close();
    }
    closed = true;
  }

  @Override
  public ReadWriteBuffer onCall(Command command, ReadWriteBuffer parameter) throws IOException {
    Path p = null;
    if (null == command) {
      return null;
    }

    if (command.equals(GET_OUTPUT_PATH)) {
      p = output.getOutputFileForWrite(-1);
    } else if (command.equals(GET_OUTPUT_INDEX_PATH)) {
      p = output.getOutputIndexFileForWrite(-1);
    } else if (command.equals(GET_SPILL_PATH)) {
      p = output.getSpillFileForWrite(spillNumber++, -1);

    } else if (command.equals(GET_COMBINE_HANDLER)) {
      if (null == combinerHandler) {
        return null;
      }
      final ReadWriteBuffer result = new ReadWriteBuffer(8);

      result.writeLong(combinerHandler.getId());
      return result;
    } else {
      throw new IOException("Illegal command: " + command.toString());
    }
    if (p != null) {
      final ReadWriteBuffer result = new ReadWriteBuffer();
      result.writeString(p.toUri().getPath());
      return result;
    } else {
      throw new IOException("MapOutputFile can't allocate spill/output file");
    }
  }
}


text:
(function () {
  "use strict";

  //constructor
  function Board () {}

  //instance
  var board = new Board();

  //assign properties
  board.squares = document.getElementsByClassName("square");
  board.playButton = document.getElementById("play-button");
  board.progBar = document.getElementById("prog-bar");
  board.finalScoreHolder = document.getElementById("final-score-holder");
  board.currentCoordinateHolder = document.getElementById("current-coordinate-holder");
  board.chooseSide = document.getElementById("choose-side");
  board.coordinateArr = [];
  board.correctAnswers = 0;
  board.currentMove = null;
  board.sideVal = null;

  //push coordinates to array
  board.pushToArray = function () {
    for (var i = 0; i < this.squares.length; i += 1) {
      this.coordinateArr.push(this.squares[i].getAttribute("id"));
    }
  };
  //retrieve a random square's coordinates from arr
  board.getRandomCoordinates = function () {
    return this.coordinateArr[Math.floor(Math.random() * this.coordinateArr.length)];
  };
  //flip board
  board.switchSides = function () {
    this.coordinateArr.reverse();
    for (var i = 0; i < this.coordinateArr.length; i += 1) {
      this.squares[i].setAttribute("id", this.coordinateArr[i]);
    }
  };
  board.randomSide = function () {
    var sideGen = Math.random() >= 0.5 ? true : false;
    if (!sideGen) {
      board.switchSides();
    }
  };
  //push random coordinates to the 'coordinate queue'
  board.currentCoordinates = function () {
    this.currentMove = this.getRandomCoordinates();
    this.currentCoordinateHolder.innerHTML = "
" + this.currentMove + "
";
    return this.currentMove;
  };
  //add .progress-bar to activate timer
  board.startTimer = function () {
    this.progBar.className = "progress-bar";
  };
  board.nextMove = function (iDynamic) {
    var that = this;
    return function () {
      if (that.currentMove === that.squares[iDynamic].getAttribute("id")) {
        that.currentMove = that.currentCoordinates();
        that.correctAnswers += 1;
        that.currentCoordinateHolder.style.color = "#fbfbfb";
        return that.currentMove;
      } else if (that.currentMove !== that.squares[iDynamic].getAttribute("id")) {
          that.currentCoordinateHolder.style.color = "#ff0033";
      }
    };
  };
  board.startGame = function () {
    this.currentCoordinateHolder.style.color = "#fbfbfb";
    this.sideVal = this.chooseSide.options[this.chooseSide.selectedIndex].value;
    this.currentMove = this.currentCoordinates();
    this.startTimer();
    this.finalScoreHolder.innerHTML = "";
    this.playButton.setAttribute("disabled", true);
    this.chooseSide.setAttribute("disabled", true);
    if (this.sideVal === "random") {
      this.randomSide();
    } else if (this.sideVal === "black" && this.coordinateArr[0] === "a8") {
        this.switchSides();
    } else if (this.sideVal === "white" && this.coordinateArr[0] === "h1") {
        this.switchSides();
    }
  };
  board.endGame = function () {
    this.progBar.className = "complete";
    this.finalScoreHolder.innerHTML = "
" + this.correctAnswers + "
";
    this.currentCoordinateHolder.innerHTML = "";
    this.currentMove = "";
    this.playButton.disabled = false;
    this.chooseSide.disabled = false;
    this.correctAnswers = 0;
  };

  board.pushToArray();

  // add event listener to side picker
  board.chooseSide.addEventListener("change", function () {
    if (board.chooseSide.options[board.chooseSide.selectedIndex].value !== "random") {
      board.switchSides();
    }
  }, false);

  // add event listeners to squares & permit move
  for (var i = 0; i < board.squares.length; i += 1) {
    board.squares[i].addEventListener("click", board.nextMove.call(board, i), false);
  }
  // add event listener to play button
  board.playButton.addEventListener("click", board.startGame.bind(board), false);

  // add prefixed event listeners to progBar animation
  board.progBar.addEventListener("webkitAnimationEnd", board.endGame.bind(board), false);
  board.progBar.addEventListener("animationend", board.endGame.bind(board), false);
  board.progBar.addEventListener("oAnimationend", board.endGame.bind(board), false);
  board.progBar.addEventListener("MSAnimationEnd", board.endGame.bind(board), false);
})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Biatora laureri f. laureri

### Remarks
null


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

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.xml.sax.*;

import generic.jar.ResourceFile;
import ghidra.app.util.*;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.scalar.Scalar;
import ghidra.program.model.symbol.*;
import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.TaskMonitor;
import ghidra.util.xml.GenericXMLOutputter;
import ghidra.util.xml.XmlUtilities;
import ghidra.xml.*;
import util.CollectionUtils;

class LibrarySymbolTable {

	private static final SimpleDateFormat TIMESTAMP_FORMAT =
		new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");

	private static final int NONE = 0;
	private static final int LIBRARY = 1;
	private static final int EXPORTS = 2;
	private static final int ORDINAL = 3;

	private String tableName;
	private int size;
	private String path;
	private String date;
	private String version;
	private int tempPurge;
	private String fowardLibrary = null;
	private String fowardSymbol = null;
	private HashMap<String, LibraryExportedSymbol> symMap = new HashMap<>();
	private ArrayList<LibraryExportedSymbol> exportList = new ArrayList<>();
	private HashMap<Integer, LibraryExportedSymbol> ordMap = new HashMap<>();
	private Set<String> forwards = new HashSet<>();

	/**
	 * Construct an empty library symbol table
	 * @param tableName symbol table name (generally same as associated library name)
	 * @param size the architecture size of the DLL (e.g., 32 or 64).
	 */
	LibrarySymbolTable(String tableName, int size) {
		this.tableName = tableName.toLowerCase();
		this.size = size;
		this.version = "unknown";
		tempPurge = size <= 32 ? -1 : 0; // assume 0 purge for 64-bit
	}

	/**
	 * Construct library symbol table from an existing symbol exports file in XML format
	 * @param libraryFile existing symbol exports file
	 * @param size the architecture size of the DLL (e.g., 32 or 64).
	 * @throws IOException thrown if file IO error occurs
	 */
	LibrarySymbolTable(ResourceFile libraryFile, int size) throws IOException {
		read(libraryFile, size);
	}

	/**
	 * Construct a library symbol table based upon a specified library in the
	 * form of a {@link Program} object.
	 * @param library library program
	 * @param monitor task monitor
	 * @throws CancelledException thrown if task cancelled
	 */
	LibrarySymbolTable(Program library, TaskMonitor monitor) throws CancelledException {

		tableName = new File(library.getExecutablePath()).getName().toLowerCase();
		size = library.getLanguage().getLanguageDescription().getSize();

		LibraryHints hints = LibraryHints.getLibraryHints(tableName, size);

		SymbolTable symTab = library.getSymbolTable();

		// go through all the symbols looking for Ordinal_#
		//    get the number and name for the symbol
		SymbolIterator iter = symTab.getSymbolIterator(SymbolUtilities.ORDINAL_PREFIX + "*", true);
		while (iter.hasNext()) {
			monitor.checkCanceled();
			Symbol sym = iter.next();

			// Only consider ordinal exports, not ordinal imports
			if (!(sym.isGlobal() && sym.isExternalEntryPoint())) {
				continue;
			}

			int ordinal = SymbolUtilities.getOrdinalValue(sym.getName());
			if (ordinal == -1) {
				continue;
			}

			// The symbols at the given address should be in a list ordered like:
			// [realName1, ordinalName1, realName2, ordinalName2, ...]
			// where the realName elements are optional.  For example,
			// [ordinalName1, realName2, ordinalName2, ordinalName3, ...]
			// is also valid.  We want to find our ordinalName in the list and look at the
			// previous entry to find its corresponding realName.  If there is no previous
			// entry or the previous entry starts with Ordinal_, then we'll assume it's
			// a [NONAME] export and we'll just use the ordinalName as the realName.
			String ordinalName = sym.getName();
			String realName = ordinalName;
			Address symAddr = sym.getAddress();
			Symbol symbolsAt[] = symTab.getSymbols(symAddr);
			for (int i = 0; i < symbolsAt.length; i++) {
				if (symbolsAt[i].getName().equals(ordinalName)) {
					if (i > 0 &&
						!symbolsAt[i - 1].getName().startsWith(SymbolUtilities.ORDINAL_PREFIX)) {
						realName = symbolsAt[i - 1].getName();
					}
					break;
				}
			}

			fowardLibrary = null;
			fowardSymbol = null;
			tempPurge = -1;
			String comment = "";

			Attribute cmtAttr = hints.getAttributeHint(ordinal, realName, "COMMENT");
			if (cmtAttr != null) {
				comment = cmtAttr.getValue();
			}

			Function func = library.getFunctionManager().getFunctionAt(symAddr);
			if (func != null) {
				tempPurge = func.getStackPurgeSize();
			}
			if (tempPurge == -1 || tempPurge > 128 || tempPurge < -128) {
				Data data = library.getListing().getDefinedDataAt(symAddr);
				if (data != null) {
					Reference[] refs = library.getReferenceManager().getReferencesFrom(symAddr);
					if (refs != null && refs.length > 0 && refs[0].isExternalReference()) {
						ExternalReference exRef = (ExternalReference) refs[0];
						fowardLibrary = exRef.getLibraryName();
						fowardSymbol = exRef.getLabel();
					}
				}

				if (fowardLibrary == null || fowardLibrary.length() <= 0) {
					MemoryBlock block = library.getMemory().getBlock(symAddr);
					if (block != null && block.isExecute()) {
						pseudoDisassemble(library, symAddr);
					}
				}
			}

			boolean noReturn = false;
			Attribute noReturnHint = hints.getAttributeHint(ordinal, realName, "NO_RETURN");
			if (noReturnHint != null && "y".equals(noReturnHint.getValue())) {
				noReturn = true;
			}

			if (fowardLibrary != null && fowardLibrary.length() > 0) {
				forwards.add(fowardLibrary);
			}

			LibraryExportedSymbol expSym = new LibraryExportedSymbol(tableName, size, ordinal,
				realName, fowardLibrary, fowardSymbol, tempPurge, noReturn, comment);

			// add to export list in order
			exportList.add(expSym);
			ordMap.put(Integer.valueOf(ordinal), expSym);
			symMap.put(realName, expSym);
		}
	}

	String getCacheKey() {
		return LibrarySymbolTable.getCacheKey(tableName, size);
	}

	static String getCacheKey(String dllName, int size) {
		return LibraryLookupTable.stripPossibleExtensionFromFilename(dllName).toLowerCase() + ":" +
			size;
	}

	private void pseudoDisassemble(Program library, Address addr) {
		// Pseudo Disassemble to get the purge
		PseudoDisassembler pdis = new PseudoDisassembler(library);
		pdis.followSubFlows(addr, 4000, new PseudoFlowProcessor() {
			@Override
			public boolean followFlows(PseudoInstruction instr) {
				return true;
			}

			@Override
			public boolean process(PseudoInstruction instr) {
				if (instr == null) {
					return false;
				}
				FlowType ftype = instr.getFlowType();
				if (ftype.isTerminal()) {
					String mnemonicStr = instr.getMnemonicString().toLowerCase();
					if ("ret".equals(mnemonicStr) || "retf".equals(mnemonicStr)) {
						// x86 has a scalar operand to purge value from the stack
						tempPurge = 0;
						Scalar scalar = instr.getScalar(0);
						if (scalar != null) {
							tempPurge = (int) scalar.getSignedValue();
							fowardLibrary = null;
							fowardSymbol = null;
							return false;
						}
					}
				}
				if (ftype.isJump() && ftype.isComputed()) {
					Reference[] refs = instr.getReferencesFrom();
					if (refs.length > 0) {
						Data data = instr.getProgram().getListing().getDefinedDataAt(
							refs[0].getToAddress());
						if (data != null) {
							refs = instr.getProgram().getReferenceManager().getReferencesFrom(
								data.getMinAddress());
							if (refs != null && refs.length > 0 && refs[0].isExternalReference()) {
								ExternalReference exRef = (ExternalReference) refs[0];
								fowardLibrary = exRef.getLibraryName();
								fowardSymbol = exRef.getLabel();
							}
						}
					}
				}
				return true;
			}
		});
	}

	/**
	 * Parse a ordinal exports file produced by Microsoft DUMPBIN /EXPORTS <DLL>
	 * It is expected to start parsing lines following the table header containing the 'ordinal' header.
	 * Each ordinal mapping line is expected to have the format, starting with ordinal number and
	 * ending with symbol name:
	 *   <ordinal> <other-column-data> <name>
	 * The name column contains the symbol name followed by an optional demangled form.  If the name starts with
	 * [NONAME] this will be stripped.
	 * @param ordinalExportsFile file path to ordinal mapping file produced by DUMPBIN /EXPORTS
	 * @param addMissingOrdinals if true new entries will be created for ordinal mappings
	 * not already existing within this symbol table, otherwise only those which already
	 * exist will be updated with a name if specified by mapping file.
	 */
	public void applyOrdinalFile(ResourceFile ordinalExportsFile, boolean addMissingOrdinals) {
		try (BufferedReader in =
			new BufferedReader(new InputStreamReader(ordinalExportsFile.getInputStream()))) {

			int ordinalColumnEndIndex = -1;
			int nameColumnStartIndex = -1;

			int mode = NONE;
			String inString;
			while ((inString = in.readLine()) != null) {

				if (mode == NONE && inString.trim().startsWith("ordinal")) {
					// rely on column header labels to establish ordinal and name column start/end
					int ordinalColumnStartIndex = inString.indexOf("ordinal");
					if (ordinalColumnStartIndex < 0) {
						continue;
					}
					ordinalColumnEndIndex = ordinalColumnStartIndex + 7;

					nameColumnStartIndex = inString.indexOf("name");
					if (nameColumnStartIndex < 1) {
						Msg.error(this,
							"Failed to parse ordinal symbol file: " + ordinalExportsFile);
						break;
					}
					mode = ORDINAL;
					continue;
				}

				if (mode != ORDINAL) {
					continue;
				}

				inString = stripComment(inString);
				if (inString.length() < nameColumnStartIndex) {
					continue;
				}

				// parse ordinal from first token on line, if bad parse, then done
				String ordinalStr = inString.substring(0, ordinalColumnEndIndex).trim();
				int ordinal;
				try {
					ordinal = Integer.parseInt(ordinalStr);
				}
				catch (NumberFormatException exc) {
					// done parsing
					break;
				}

				String nameStr = inString.substring(nameColumnStartIndex).trim();
				if (nameStr.length() == 0) {
					break; // unexpected
				}

				// if [NONAME] present strip-off and use next field as name (i.e., mangled name)
				if (nameStr.startsWith("[NONAME]")) {
					nameStr = nameStr.substring(8).trim();
				}

				int index = nameStr.indexOf(' ');
				if (index > 0) {
					nameStr = nameStr.substring(0, index);
				}

				if (nameStr.length() == 0) {
					continue; // skip if no name
				}

				LibraryExportedSymbol sym = ordMap.get(Integer.valueOf(ordinal));
				if (sym != null) {
					symMap.remove(sym.getName());
					sym.setName(nameStr);
				}
				else if (addMissingOrdinals) {
					sym = new LibraryExportedSymbol(tableName, size, ordinal, nameStr, null, null,
						tempPurge, false, null);
					symMap.put(nameStr, sym);
					ordMap.put(ordinal, sym);
				}
			}
		}
		catch (FileNotFoundException e) {
			return;
		}
		catch (IOException e) {
			Msg.error(this, "Unexpected Exception: " + e.getMessage(), e);
		}
	}

	private String stripComment(String str) {
		int index = str.indexOf(';');
		return index < 0 ? str : str.substring(0, index);
	}

	List<String> getForwards() {
		return new ArrayList<>(forwards);
	}

	/**
	 * Returns the symbol for the specified ordinal.
	 *
	 * @param ordinal the ordinal value of the desired symbol
	 * @return the symbol for the specified ordinal, or null if one does not
	 *         exist.
	 */
	LibraryExportedSymbol getSymbol(int ordinal) {
		return ordMap.get(ordinal);
	}

	/**
	 * Returns the symbol for the specified name
	 *
	 * @param symbol the name of the desired symbol
	 * @return symbol map entry or null if not found
	 */
	LibraryExportedSymbol getSymbol(String symbol) {
		return symMap.get(symbol);
	}

	/**
	 * Returns a string describing the version of this library. For example,
	 * "5.100.2566".
	 *
	 * @return a string describing the version of this library
	 */
	String getVersion() {
		return version;
	}

	String getPath() {
		return path;
	}

	String getDate() {
		return date;
	}

	private void read(ResourceFile file, int size) throws IOException {
		this.size = size;
		symMap = new HashMap<>();
		exportList = new ArrayList<>();

		InputStream is = file.getInputStream();
		SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);

		try {
			Document doc = sax.build(is);

			Element root = doc.getRootElement();
			tableName = root.getAttributeValue("NAME");
			if (tableName == null) {
				throw new IOException("Missing NAME attribute: " + file);
			}
			tableName = tableName.toLowerCase();

			path = root.getAttributeValue("PATH");
			date = root.getAttributeValue("DATE");
			version = root.getAttributeValue("VERSION");

			List<Element> children = CollectionUtils.asList(root.getChildren(), Element.class);
			Iterator<Element> iter = children.iterator();
			while (iter.hasNext()) {
				Element export = iter.next();
				int ordinal = Integer.parseInt(export.getAttributeValue("ORDINAL"));
				String name = export.getAttributeValue("NAME");
				int purge = Integer.parseInt(export.getAttributeValue("PURGE"));
				String comment = export.getAttributeValue("COMMENT");
				String fowardLibName = export.getAttributeValue("FOWARDLIBRARY");
				String fowardSymName = export.getAttributeValue("FOWARDSYMBOL");

				String noReturnStr = export.getAttributeValue("NO_RETURN");
				boolean noReturn = noReturnStr != null && "y".equals(noReturnStr);

				if (fowardLibName != null && fowardLibName.length() > 0 &&
					!fowardLibName.equals(tableName)) {
					forwards.add(fowardLibName);
				}

				LibraryExportedSymbol sym = new LibraryExportedSymbol(tableName, size, ordinal,
					name, fowardLibName, fowardSymName, purge, noReturn, comment);

				exportList.add(sym);
				symMap.put(name, sym);
				ordMap.put(new Integer(ordinal), sym);
			}
		}
		catch (JDOMException e) {
			throw new IOException(e);
		}

		is.close();

		//// read in the formatted data
		//FileReader fr = new FileReader(file);
		//BufferedReader br = new BufferedReader(fr);
		//
		//try{
		//    Pattern p = Pattern.compile("(.*)\\t(.*)\\t(.*)\\t(.*)$");
		//
		//    String inline;
		//    while ((inline = br.readLine()) != null) {
		//        Matcher m = p.matcher(inline);
		//        if (m.matches()) {
		//            int ord = Integer.parseInt(m.group(1));
		//            String funcName = m.group(2);
		//            int purge = Integer.parseInt(m.group(3));
		//            String comment = m.group(4);
		//
		//            LibraryExportedSymbol sym = new LibraryExportedSymbol(tableName, ord, funcName, purge, comment);
		//            exportList.add(sym);
		//            symMap.put(funcName, sym);
		//            ordMap.put(new Integer(ord), sym);
		//        }
		//    }
		//}
		//finally {
		//    fr.close();
		//}
	}

	void write(File output, File input, String lversion) throws IOException {
		Element root = new Element("LIBRARY");

		root.setAttribute("NAME", tableName);
		root.setAttribute("PATH", input.getAbsolutePath());
		long lastModifiedSeconds = (input.lastModified() / 1000) * 1000; // file time in seconds
		root.setAttribute("DATE", TIMESTAMP_FORMAT.format(new Date(lastModifiedSeconds)));
		root.setAttribute("VERSION", lversion);

		Iterator<LibraryExportedSymbol> iter = exportList.iterator();
		while (iter.hasNext()) {
			LibraryExportedSymbol sym = iter.next();

			Element export = new Element("EXPORT");

			export.setAttribute("ORDINAL", sym.getOrdinal() + "");
			export.setAttribute("NAME", sym.getName() == null ? "" : sym.getName());
			export.setAttribute("PURGE", sym.getPurge() + "");
			export.setAttribute("COMMENT", sym.getComment() == null ? "" : sym.getComment());

			if (sym.hasNoReturn()) {
				export.setAttribute("NO_RETURN", "y");
			}

			if (sym.isFowardEntry()) {
				export.setAttribute("FOWARDLIBRARY",
					sym.getFowardLibraryName() == null ? "" : sym.getFowardLibraryName());
				export.setAttribute("FOWARDSYMBOL",
					sym.getFowardSymbolName() == null ? "" : sym.getFowardSymbolName());
			}
			root.addContent(export);
		}

		FileOutputStream fos = new FileOutputStream(output);
		try {
			Document doc = new Document(root);

			XMLOutputter xmlout = new GenericXMLOutputter();
			xmlout.output(doc, fos);
		}
		finally {
			fos.close();
		}

		//StringBuffer buffer = new StringBuffer();
		//Iterator iter = exportList.iterator();
		//while (iter.hasNext()) {
		//    LibraryExportedSymbol sym = (LibraryExportedSymbol) iter.next();
		//
		//    buffer.append(sym.getOrdinal());
		//    buffer.append("\t");
		//    buffer.append(sym.getName());
		//    buffer.append("\t");
		//    buffer.append(sym.getPurge());
		//    buffer.append("\t");
		//    buffer.append(sym.getComment());
		//    buffer.append("\n");
		//}
		//PrintWriter writer = new PrintWriter(new FileOutputStream(file));
		//try {
		//    writer.println(buffer.toString());
		//}
		//finally {
		//    writer.flush();
		//    writer.close();
		//}
	}

	void setVersion(String version) {
		this.version = version;
	}

	/**
	 * Check an existing exports file to verify that it corresponds to the
	 * specified libraryFile.
	 *
	 * @param exportsFile existing exports file
	 * @param libraryFile library file
	 * @return true if exports file corresponds to library file
	 * @throws ParseException if timestamp fails to parse
	 * @throws SAXException if exports file has XML failure
	 * @throws IOException if unable to read exports file
	 */
	static boolean hasFileAndPathAndTimeStampMatch(ResourceFile exportsFile, File libraryFile)
			throws ParseException, SAXException, IOException {
		if (exportsFile == null || !exportsFile.exists()) {
			return false;
		}
		// TODO: should consider checking version instead of last modified
		XmlPullParser parser = XmlPullParserFactory.create(exportsFile, ERROR_HANDLER, false);
		try {
			XmlElement start = parser.start("LIBRARY");
			String path = start.getAttribute("PATH");
			String dateString = start.getAttribute("DATE");
			Date date = TIMESTAMP_FORMAT.parse(dateString);
			long lastModifiedSeconds = (libraryFile.lastModified() / 1000) * 1000; // file time in seconds
			return date.equals(new Date(lastModifiedSeconds)) &&
				path.equalsIgnoreCase(libraryFile.getAbsolutePath());
		}
		finally {
			parser.dispose();
		}
	}

	private static final ErrorHandler ERROR_HANDLER = new ErrorHandler() {
		@Override
		public void error(SAXParseException exception) throws SAXException {
			Msg.warn(LibraryLookupTable.class, "error", exception);
		}

		@Override
		public void fatalError(SAXParseException exception) throws SAXException {
			Msg.warn(LibraryLookupTable.class, "fatal error", exception);
		}

		@Override
		public void warning(SAXParseException exception) throws SAXException {
			Msg.warn(LibraryLookupTable.class, "warning", exception);
		}
	};
}


text:
package org.elasticsearch.common.geo;

import org.apache.lucene.util.Bits;
import org.apache.lucene.util.SloppyMath;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.GeoPointValues;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.NumericDoubleValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
import org.elasticsearch.index.fielddata.SortingNumericDoubleValues;

import java.io.IOException;
import java.util.Locale;

/**
 * Geo distance calculation.
 */
public enum GeoDistance implements Writeable {
    /**
     * Calculates distance as points on a plane. Faster, but less accurate than {@link #ARC}.
     */
    PLANE {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double px = targetLongitude - sourceLongitude;
            double py = targetLatitude - sourceLatitude;
            return Math.sqrt(px * px + py * py) * unit.getDistancePerDegree();
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new PlaneFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },

    /**
     * Calculates distance factor.
     */
    FACTOR {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double longitudeDifference = targetLongitude - sourceLongitude;
            double a = Math.toRadians(90D - sourceLatitude);
            double c = Math.toRadians(90D - targetLatitude);
            return (Math.cos(a) * Math.cos(c)) + (Math.sin(a) * Math.sin(c) * Math.cos(Math.toRadians(longitudeDifference)));
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return Math.cos(distance / unit.getEarthRadius());
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new FactorFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },
    /**
     * Calculates distance as points on a globe.
     */
    ARC {
        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            double result = SloppyMath.haversinMeters(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude);
            return unit.fromMeters(result);
        }

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new ArcFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    },
    /**
     * Calculates distance as points on a globe in a sloppy way. Close to the pole areas the accuracy
     * of this function decreases.
     */
    @Deprecated
    SLOPPY_ARC {

        @Override
        public double normalize(double distance, DistanceUnit unit) {
            return distance;
        }

        @Override
        public double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit) {
            return unit.fromMeters(SloppyMath.haversinMeters(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude));
        }

        @Override
        public FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            return new SloppyArcFixedSourceDistance(sourceLatitude, sourceLongitude, unit);
        }
    };

    public static GeoDistance readFromStream(StreamInput in) throws IOException {
        int ord = in.readVInt();
        if (ord < 0 || ord >= values().length) {
            throw new IOException("Unknown GeoDistance ordinal [" + ord + "]");
        }
        return GeoDistance.values()[ord];
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeVInt(this.ordinal());
    }

    /**
     * Default {@link GeoDistance} function. This method should be used, If no specific function has been selected.
     * This is an alias for SLOPPY_ARC
     */
    public static final GeoDistance DEFAULT = SLOPPY_ARC;

    public abstract double normalize(double distance, DistanceUnit unit);

    public abstract double calculate(double sourceLatitude, double sourceLongitude, double targetLatitude, double targetLongitude, DistanceUnit unit);

    public abstract FixedSourceDistance fixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit);

    private static final double MIN_LAT = Math.toRadians(-90d);  // -PI/2
    private static final double MAX_LAT = Math.toRadians(90d);   //  PI/2
    private static final double MIN_LON = Math.toRadians(-180d); // -PI
    private static final double MAX_LON = Math.toRadians(180d);  //  PI

    public static DistanceBoundingCheck distanceBoundingCheck(double sourceLatitude, double sourceLongitude, double distance, DistanceUnit unit) {
        // angular distance in radians on a great circle
        // assume worst-case: use the minor axis
        double radDist = unit.toMeters(distance) / GeoUtils.EARTH_SEMI_MINOR_AXIS;

        double radLat = Math.toRadians(sourceLatitude);
        double radLon = Math.toRadians(sourceLongitude);

        double minLat = radLat - radDist;
        double maxLat = radLat + radDist;

        double minLon, maxLon;
        if (minLat > MIN_LAT && maxLat < MAX_LAT) {
            double deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));
            minLon = radLon - deltaLon;
            if (minLon < MIN_LON) minLon += 2d * Math.PI;
            maxLon = radLon + deltaLon;
            if (maxLon > MAX_LON) maxLon -= 2d * Math.PI;
        } else {
            // a pole is within the distance
            minLat = Math.max(minLat, MIN_LAT);
            maxLat = Math.min(maxLat, MAX_LAT);
            minLon = MIN_LON;
            maxLon = MAX_LON;
        }

        GeoPoint topLeft = new GeoPoint(Math.toDegrees(maxLat), Math.toDegrees(minLon));
        GeoPoint bottomRight = new GeoPoint(Math.toDegrees(minLat), Math.toDegrees(maxLon));
        if (minLon > maxLon) {
            return new Meridian180DistanceBoundingCheck(topLeft, bottomRight);
        }
        return new SimpleDistanceBoundingCheck(topLeft, bottomRight);
    }

    /**
     * Get a {@link GeoDistance} according to a given name. Valid values are
     *
     *

     *
plane for GeoDistance.PLANE

     *
sloppy_arc for GeoDistance.SLOPPY_ARC

     *
factor for GeoDistance.FACTOR

     *
arc for GeoDistance.ARC

     *

     *
     * @param name name of the {@link GeoDistance}
     * @return a {@link GeoDistance}
     */
    public static GeoDistance fromString(String name) {
        name = name.toLowerCase(Locale.ROOT);
        if ("plane".equals(name)) {
            return PLANE;
        } else if ("arc".equals(name)) {
            return ARC;
        } else if ("sloppy_arc".equals(name)) {
            return SLOPPY_ARC;
        } else if ("factor".equals(name)) {
            return FACTOR;
        }
        throw new IllegalArgumentException("No geo distance for [" + name + "]");
    }

    public static interface FixedSourceDistance {

        double calculate(double targetLatitude, double targetLongitude);
    }

    public static interface DistanceBoundingCheck {

        boolean isWithin(double targetLatitude, double targetLongitude);

        GeoPoint topLeft();

        GeoPoint bottomRight();
    }

    public static final AlwaysDistanceBoundingCheck ALWAYS_INSTANCE = new AlwaysDistanceBoundingCheck();

    private static class AlwaysDistanceBoundingCheck implements DistanceBoundingCheck {
        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return true;
        }

        @Override
        public GeoPoint topLeft() {
            return null;
        }

        @Override
        public GeoPoint bottomRight() {
            return null;
        }
    }

    public static class Meridian180DistanceBoundingCheck implements DistanceBoundingCheck {

        private final GeoPoint topLeft;
        private final GeoPoint bottomRight;

        public Meridian180DistanceBoundingCheck(GeoPoint topLeft, GeoPoint bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }

        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return (targetLatitude >= bottomRight.lat() && targetLatitude <= topLeft.lat()) &&
                    (targetLongitude >= topLeft.lon() || targetLongitude <= bottomRight.lon());
        }

        @Override
        public GeoPoint topLeft() {
            return topLeft;
        }

        @Override
        public GeoPoint bottomRight() {
            return bottomRight;
        }
    }

    public static class SimpleDistanceBoundingCheck implements DistanceBoundingCheck {
        private final GeoPoint topLeft;
        private final GeoPoint bottomRight;

        public SimpleDistanceBoundingCheck(GeoPoint topLeft, GeoPoint bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }

        @Override
        public boolean isWithin(double targetLatitude, double targetLongitude) {
            return (targetLatitude >= bottomRight.lat() && targetLatitude <= topLeft.lat()) &&
                    (targetLongitude >= topLeft.lon() && targetLongitude <= bottomRight.lon());
        }

        @Override
        public GeoPoint topLeft() {
            return topLeft;
        }

        @Override
        public GeoPoint bottomRight() {
            return bottomRight;
        }
    }

    public static class PlaneFixedSourceDistance implements FixedSourceDistance {

        private final double sourceLatitude;
        private final double sourceLongitude;
        private final double distancePerDegree;

        public PlaneFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLatitude = sourceLatitude;
            this.sourceLongitude = sourceLongitude;
            this.distancePerDegree = unit.getDistancePerDegree();
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            double px = targetLongitude - sourceLongitude;
            double py = targetLatitude - sourceLatitude;
            return Math.sqrt(px * px + py * py) * distancePerDegree;
        }
    }

    public static class FactorFixedSourceDistance implements FixedSourceDistance {

        private final double sourceLongitude;

        private final double a;
        private final double sinA;
        private final double cosA;

        public FactorFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLongitude = sourceLongitude;
            this.a = Math.toRadians(90D - sourceLatitude);
            this.sinA = Math.sin(a);
            this.cosA = Math.cos(a);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            double longitudeDifference = targetLongitude - sourceLongitude;
            double c = Math.toRadians(90D - targetLatitude);
            return (cosA * Math.cos(c)) + (sinA * Math.sin(c) * Math.cos(Math.toRadians(longitudeDifference)));
        }
    }

    /**
     * Basic implementation of {@link FixedSourceDistance}. This class keeps the basic parameters for a distance
     * functions based on a fixed source. Namely latitude, longitude and unit.
     */
    public static abstract class FixedSourceDistanceBase implements FixedSourceDistance {
        protected final double sourceLatitude;
        protected final double sourceLongitude;
        protected final DistanceUnit unit;

        public FixedSourceDistanceBase(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            this.sourceLatitude = sourceLatitude;
            this.sourceLongitude = sourceLongitude;
            this.unit = unit;
        }
    }

    public static class ArcFixedSourceDistance extends FixedSourceDistanceBase {

        public ArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            super(sourceLatitude, sourceLongitude, unit);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            return ARC.calculate(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, unit);
        }

    }

    public static class SloppyArcFixedSourceDistance extends FixedSourceDistanceBase {

        public SloppyArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
            super(sourceLatitude, sourceLongitude, unit);
        }

        @Override
        public double calculate(double targetLatitude, double targetLongitude) {
            return SLOPPY_ARC.calculate(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, unit);
        }
    }

    /**
     * Return a {@link SortedNumericDoubleValues} instance that returns the distances to a list of geo-points for each document.
     */
    public static SortedNumericDoubleValues distanceValues(final MultiGeoPointValues geoPointValues, final FixedSourceDistance... distances) {
        final GeoPointValues singleValues = FieldData.unwrapSingleton(geoPointValues);
        if (singleValues != null && distances.length == 1) {
            final Bits docsWithField = FieldData.unwrapSingletonBits(geoPointValues);
            return FieldData.singleton(new NumericDoubleValues() {

                @Override
                public double get(int docID) {
                    if (docsWithField != null && !docsWithField.get(docID)) {
                        return 0d;
                    }
                    final GeoPoint point = singleValues.get(docID);
                    return distances[0].calculate(point.lat(), point.lon());
                }

            }, docsWithField);
        } else {
            return new SortingNumericDoubleValues() {

                @Override
                public void setDocument(int doc) {
                    geoPointValues.setDocument(doc);
                    resize(geoPointValues.count() * distances.length);
                    int valueCounter = 0;
                    for (FixedSourceDistance distance : distances) {
                        for (int i = 0; i < geoPointValues.count(); ++i) {
                            final GeoPoint point = geoPointValues.valueAt(i);
                            values[valueCounter] = distance.calculate(point.lat(), point.lon());
                            valueCounter++;
                        }
                    }
                    sort();
                }
            };
        }
    }
}


text:
1. Advice: use multiple cloud, -> no vendor lock-in!
2. Solution: use Kubernetes & Spinnaker & Istio

## Spinnaker
Spinnaker = from netflix, multi-cloud CD platform, maintains pipelines
1. knows deployment strategies
    1. blue/green (switch a load-balancer)
    2. rolling
    3. canary (score 2 deployments)
2. can trigger pipelines (after code change)

## Istio
Istio = defines service mesh incl.
1. routing
2. security(mutual-tls,policies,rate-limiting)
3. telemetry(distributed-tracing)
4. resilience(retries, healthcheck, circuit-breaker)

### Istio components:
1. Proxy in the pod (=envoy)
2. Pilot: maintains the routing rules, configures the Envoy proxies
3. Mixer: collects telemetry data and exposes this data to other services (Prometheus, InfluxDB, ...), envorces quota & policy
4. Citadel: does security: mutual encryption, like a Certificate Authority (CA), distributes certificates

## Envoy
1. Envoy is a proxy
2. Configured with Aggregated Discovery Services (ADS)
3. part of Istio

## With this architecture:
1. you can orchestrate several GCP Clusters

## Cloud Market:

## Cluster building blocks:

## CI/CD on GCP

## Spinnaker UI
1. "mdservice" is the app name
2. in the middle: 2 clusters, with namespace 'default' (the green boxes are the pods)

## Commands in this Setup:
1. cmd: glcoud container builds submit ...
2. Spinnaker pipeline triggered

### Spinnaker pipeline:
1. Spinnaker pipeline with 2 roads
2. does tests automatically
3. prod deployment has to be started manually

## Use kubectl on GCP with Spinnaker
By changing the route rule you can manually route traffic to the new deployment

## Manual Prod Deployment launch:


text:
use strict;
use warnings;
use File::Basename;
use lib dirname($0);

use Getopt::Long qw(:config no_ignore_case bundling);
use LWP::UserAgent;
use JSON;

my $username;
my $password;
my $url;
my $session_id;
my $help;
my $trackname;

$| = 1;

parse_options();

sub parse_options {
    GetOptions(
           "username|u=s"       => \$username,
           "password|p=s"       => \$password,
           "url|U=s"            => \$url,
           "track|t=s"            => \$trackname,
           "help|h"             => \$help);
    print_usage() if $help;
    die "Missing required parameter: username\n" if !$username;
    die "Missing required parameter: password\n" if !$password;
    die "Missing required parameter: url\n" if !$url;
    die "Missing required parameter: track\n" if !$trackname;
    $url = "http://$url" if $url !~ m%http://%;
}

sub print_usage {
    my $progname = basename($0);
    die << "END";
usage: $progname
    --url|-U <URL to Apollo instance>
    --username|-u <username>
    --password|-p <password>
    --track|-t <trackname>
    [--prefix|-P <trackname>]

    U: URL to Apollo instance
    u: username to access Apollo
    p: password to access Apollo
    t: trackname to delete tracks on
END
}

print $trackname."\n";
my $track=$trackname;

print $track."\n";
my $login_result=`curl -b cookies.txt -c cookies.txt -H "Content-Type:application/json" -d "{'username': '$username', 'password': '$password'}" "$url/Login?operation=login" 2> /dev/null`;

my $features_to_delete=`curl -b cookies.txt -c cookies.txt --data '{ "track": "$track", "operation": "get_features" }' $url/AnnotationEditorService 2> /dev/null`;

my $result=decode_json $features_to_delete;

my @features;
if($result->{features}) {
    foreach my $feature (@{$result->{features}}) {
        my %uniquename=("uniquename"=>$feature->{uniquename});
        push (@features, \%uniquename);
    }
}
my $str=encode_json \@features;

my $output=`curl -b cookies.txt -c cookies.txt --data '{ "track": "$track", "operation": "delete_feature","features": $str }' $url/AnnotationEditorService 2> /dev/null`;
if($output eq '{"features":[]}') {
    print "Success\n";
}
else {
    print "Error: $output";
}


text:
"use strict";

const ImageReducer = require("../lib/ImageReducer");
const ImageData    = require("../lib/ImageData");
const test         = require("ava");
const pify         = require("pify");
const fs           = require("fs");
const fsP          = pify(fs);

test("Reduce JPEG with JpegOptim", async t => {
    const fixture = await fsP.readFile(`${__dirname}/fixture/fixture.jpg`);
    const reducer = new ImageReducer({jpegOptimizer: "jpegoptim"});
    const image = new ImageData("fixture/fixture.jpg", "fixture", fixture);

    const reduced = await reducer.exec(image);
    t.true(reduced.data.length > 0);
    t.true(reduced.data.length < fixture.length);
});

test("Reduce JPEG with JpegOptim and quality", async t => {
    const fixture = await fsP.readFile(`${__dirname}/fixture/fixture.jpg`);
    const reducer = new ImageReducer({quality: 90, jpegOptimizer: "jpegoptim"});
    const image = new ImageData("fixture/fixture.jpg", "fixture", fixture);

    const reduced = await reducer.exec(image);
    t.true(reduced.data.length > 0);
    t.true(reduced.data.length < fixture.length);
});


text:
/*-------------------------------------------------------------------------
 *
 * cdboid.c
 *
 */
#include "postgres.h"

#include <assert.h>
#include <ctype.h>
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "cdboid.h"

/*
 * cdb_get_oid takes 0 arguments
 * and returns an int4
 */
PG_FUNCTION_INFO_V1(cdb_get_oid);
Datum
cdb_get_oid(PG_FUNCTION_ARGS)
{
	int result;

	if ( SPI_OK_CONNECT != SPI_connect() )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_connect failed in cdb_eget_oid" )));
	}

	if ( SPI_OK_UTILITY != SPI_execute( "CREATE TEMPORARY TABLE pgdump_oid (dummy integer) WITH OIDS", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in cdb_get_oid" )));
	}

	if ( SPI_OK_INSERT != SPI_execute( "insert into pgdump_oid values(0)", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed to insert a row into pgdump_oid in cdb_get_oid" )));
	}

	if ( SPI_OK_SELECT != SPI_execute( "select oid from pgdump_oid", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in cdb_get_oid" )));
	}

	if ( SPI_processed == 0 )
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("No rows in pgdump_oid in cdb_get_oid" )));

	TupleDesc tupdesc = SPI_tuptable->tupdesc;
	result = atoi( SPI_getvalue( SPI_tuptable->vals[0], tupdesc, 1));

	if ( SPI_OK_UTILITY != SPI_execute( "DROP TABLE pgdump_oid", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in cdb_get_oid" )));
	}

	SPI_finish();

	PG_RETURN_INT32(result);
}

/*
 * cdb_set_oid takes 1 argument (the new oid max value)
 * and returns a boolean
 */
PG_FUNCTION_INFO_V1(cdb_set_oid);
Datum
cdb_set_oid(PG_FUNCTION_ARGS)
{
	int32 maxoid = PG_GETARG_INT32(0);
	char *tempFileName = tempnam( NULL, "TMPCP" );

/*	elog(NOTICE, "tempFileName = %s", tempFileName ); */

	StringInfoData buffer;
	initStringInfo( &buffer );

	appendStringInfo( &buffer, "%u\t0\n\\.\n", maxoid );

	FILE *fptr = fopen(tempFileName, "w");
	if ( strlen(buffer.data) != fwrite( buffer.data, 1, strlen(buffer.data), fptr) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in in temp file write in cdb_set_oid" )));

	}

	fclose(fptr);
	pfree(buffer.data);
	buffer.data = NULL;

	if ( SPI_OK_CONNECT != SPI_connect() )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_connect failed in cdb_set_oid" )));
	}

	if ( SPI_OK_UTILITY != SPI_execute( "CREATE TEMPORARY TABLE pgdump_oid (dummy integer) WITH OIDS", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in cdb_set_oid" )));
	}

	initStringInfo( &buffer );

	appendStringInfo( &buffer, "COPY pgdump_oid WITH OIDS FROM '%s'", tempFileName );

	if ( SPI_OK_UTILITY != SPI_execute( buffer.data, false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in copy command in cdb_set_oid" )));
	}

	remove( tempFileName );

	pfree(buffer.data);

	if ( SPI_OK_UTILITY != SPI_execute( "DROP TABLE pgdump_oid", false, 0 ) )
	{
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
				errmsg("SPI_execute failed in cdb_set_oid" )));
	}

	SPI_finish();

	PG_RETURN_BOOL(true);
}


text:
[![Build Status](https://travis-ci.org/marteinn/django-csvexport.svg?branch=master)](https://travis-ci.org/marteinn/django-csvexport)
[![PyPI version](https://badge.fury.io/py/django-csvexport.svg)](http://badge.fury.io/py/django-csvexport)

# Django-CSVExport

This is a django extension that simplifies model to csv conversions.

## Requirements
- Python 2.7 / 3.3+
- Django 1.8+

## Example:

### Simple usage:

Generate csv string from a model:

```python
from csvexport.exports import ModelCSVExporter

records = Record.objects.all()
exp = ModelExporter(queryset=records)
f = exp.to_string()
```

### With specified fields

Same as the previous example, but only expose certain fields:

```python
from csvexport.exports import ModelCSVExporter

class RecordExporter(ModelCSVExporter):
    class Meta:
        fields = ["album", "slug"]
        exclude = ["id"]

records = Record.objects.all()
exp = RecordExporter(queryset=records)
f = exp.to_string()
```

### Generating a csv from a view:

This is a example how you could generate a downloadable csv by requesting a view, using the `render_to_csv` helper.

**urls.py**

```python
url(r'^csv/$', 'app.views.gen_csv'),
```

**views.py**

```python
def gen_csv(request):
    from csvexport.exporters import ModelExporter
    from csvexport.utils import render_to_csv
    records = Record.objects.all()
    exp = ModelExporter(queryset=records)
    return render_to_csv(exp)
```

### With custom hydration

It is also possible to create a custom csv object:

```python
class RecordExporter(ModelExporter):
    class Meta:
        fields = ["artist", "title", "release_year", "format", "quality",
                  "record_label", "comment", "venue", "url"]

    def hydrate_entry(self, entry):
        venue_name = ""

        if entry.venue:
            venue_name = entry.venue.name

        return {
            "artist": entry.album.artist.name,
            "title": entry.album.name,
            "release_year": entry.album.release_year,
            "format": entry.format,
            "quality": entry.quality,
            "record_label": entry.record_label,
            "comment": entry.comment,
            "venue": venue_name,
        }

records = Record.objects.all()
exp = RecordExporter(queryset=records)
f = exp.to_string()

```

## Installation

django-csvexport can easily be installed through pip.

    $ pip install django-csvexport

## Tests

This library include tests, just run `python runtests.py`.

You can also run separate test cases: `runtests.py tests.ViewTestCase`

## Contributing

Want to contribute? Awesome. Just send a pull request.

## License

Django-CSVExport is released under the [MIT License](http://www.opensource.org/licenses/MIT).


text:
This is a class that simply wraps the functionality of the builtin `struct` datatype, but adds a number of useful features. The most notable feature, is that a `structobj` is a handle class and is therefore passed *by reference* to other functions. This allows you to essentially modify the structure *in-place*.

    S = structobj('Parameter1', 'value');
    addParameter(S);

    function addParameter(structure)
        % Simple function that adds a parameter without returned value
        structure.NewParameter = 'differentValue';
    end

Now when we display `S`, we see that it has been modified despite not being returned from the `addParameter` function.

    S =

        Parameter1: 'value'
        NewParameter: 'differentValue'

### Object Creation
You can create a `structobj` in a number of different ways

#### Standard Structure Inputs ####

The typical inputs can be passed to the `structobj` constructor

**Scalar Structure**

    S = structobj('a', 1, 'b', 2)

    S =

        a: 1
        b: 2

**Array of Structures**

    S = structobj('a', {1, 2}, 'b', {3, 4})

    S =

    1x2 struct array with fields:

        a
        b

**Dot Assignment**

    S = structobj();
    S.Program = 'structobj';

#### Existing struct

If you already have a structure (or array of structures) containing all of your data, you can simply pass that structure directly to the constructor.

    S = structobj(existingStructure);

Keep in mind that since the built-in `struct` datatype isn't passed by reference, any changes made to `S` *will not* be reflected in `existingStructure`.

### Additional Features

#### Events for data change

When the underlying data is changed, an event (`Updated`) is fired. You can register any callback to listen to this event using `addlistener`.

    S = structobj();

    listener = addlistener(S, 'Updated', @(s,e)disp('Updated!'))

    S.Name = 'Jonathan';

    Updated!

This is very useful if you use a `structobj` as a way to store data that underlies a GUI. This way, if any changes are made to the underlying data, you can have a listener that updates the necessary plots.

    S = structobj('x', [1,2,3], 'y', [1,2,3]);
    hplot = plot(S.x, S.y);
    listener = addlistener(S, 'Updated', @(s,e)set(hplot, 'XData', S.x, 'YData', S.y));

#### Conversion back to `struct`

If for some reason you need a *real* `struct` representation of your `structobj` object, you can cast it to a `struct`.

    realStruct = struct(S);

Again, remember that `realStruct` can no longer be passed by reference and any changes made to `realStruct` will not exist within `S`.

#### Update with another `struct` or `structobj`

If you want to add many fields to a `structobj` at once (whether they exist already or not), you can use the `update` method

    toUpdate = structobj('a', 1);
    updateWith = structobj('b', 2);

    update(toUpdate, updateWith)

    toUpdate =

        a: 1
        b: 2

    update(toUpdate, struct('c', 3))

    toUpdate =

        a: 1
        b: 2
        c: 3

#### Shallow copy of data

If you need a copy of the `structobj` that is *also* a `structobj` but *isn't* linked to the original data, you can create a shallow copy.

    S = structobj('a', 2);
    S2 = copy(S);

    disp(S2.a)

        2

    S2.a = 1;

    disp(S.a)

        2

    disp(S2.a)

        1

### Other Supported Functionality

* **Dynamic field references**

        fieldname = 'a';
        value = S.(fieldname);

* **Concatenation**

        S = [structobj('a', 1), structobj('a', 2)];
        S = [S; S]
        S = horzcat(S, S);
        S = vertcat(S, S);

* **Tab completion**

        S = structobj('parameter', 'value');
        >> S.<tab>

* **Field ordering**

        S = structobj('b', 1, 'a', 2);

        S =

          b: 1
          a: 2

        orderfields(S)

        S =

          a: 2
          b: 1

* **Field alteration methods**

        S = structobj();
        setfield(S, 'fieldname', 'value');
        tf = isfield(S, 'fieldname')
        value = getfield(S, 'fieldname');
        rmfield(S, 'fieldname');

* **Saving/Loading from file**

        S = structobj('field1', 'value1');
        save('data.mat', 'S');
        values = load('data.mat');

        values.S =

            field1: 'value1'

### Testing

A suite of unit tests is distributed with this software and can be run using the following command

    results = structobj.test()

### Bug Reporting

Any issues or bugs should be reported to this project's [Github issue page][3]

### Attribution

Copyright (c) <2016> [Jonathan Suever][1].
All rights reserved.

This software is licensed under the [three-clause BSD license][2].

[1]: https://github.com/suever
[2]: https://github.com/suever/structobj/blob/master/LICENSE
[3]: https://github.com/suever/structobj/issue


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

using System.Collections;
using System.Collections.Generic;

namespace VBF.Compilers.Scanners
{
    public class LexemeRange : IReadOnlyList<Lexeme>
    {
        private readonly int m_length;
        private readonly IReadOnlyList<Lexeme> m_lexemeList;
        private readonly int m_startIndex;

        public LexemeRange(IReadOnlyList<Lexeme> lexemeList, int startIndex, int length)
        {
            CodeContract.RequiresArgumentNotNull(lexemeList, "lexemeList");
            CodeContract.RequiresArgumentInRange(startIndex >= 0 && startIndex <= lexemeList.Count,
                "startIndex", "startIndex must be greater or equal to 0 and less than the count of lexemeList");
            CodeContract.RequiresArgumentInRange(length >= 0 && startIndex + length <= lexemeList.Count,
                "length", "lengh is invalid");

            m_lexemeList = lexemeList;
            m_startIndex = startIndex;
            m_length = length;
        }

        public Lexeme this[int index]
        {
            get
            {
                CodeContract.RequiresArgumentInRange(index >= 0 && index < m_length,
                    "index", "index must be greater than or equal to 0 and less than the length of the range");
                return m_lexemeList[index + m_startIndex];
            }
        }

        public int Count
        {
            get { return m_length; }
        }

        public IEnumerator<Lexeme> GetEnumerator()
        {
            for (int i = m_startIndex; i < m_startIndex + m_length; i++)
            {
                yield return m_lexemeList[i];
            }
        }

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


text:
package nl.futureedge.sonar.plugin.issueresolver.ws;

import java.util.List;

import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.text.JsonWriter;
import org.sonarqube.ws.Issues.Component;
import org.sonarqube.ws.Issues.Issue;

import nl.futureedge.sonar.plugin.issueresolver.helper.IssueHelper;
import nl.futureedge.sonar.plugin.issueresolver.helper.SearchHelper;
import nl.futureedge.sonar.plugin.issueresolver.issues.IssueData;
import nl.futureedge.sonar.plugin.issueresolver.issues.IssueKey;

/**
 * Export action.
 */
public class ExportAction implements IssueResolverWsAction {

	public static final String ACTION = "export";
	public static final String PARAM_PROJECT_KEY = "projectKey";

	private static final Logger LOGGER = Loggers.get(ExportAction.class);

	@Override
	public void define(final NewController controller) {
		LOGGER.debug("Defining export action ...");
		final NewAction action = controller.createAction(ACTION)
				.setDescription("Export resolved issues with the status false positive or won't fix.")
				.setResponseExample(getClass().getResource("/response-examples/export.json")).setHandler(this)
				.setPost(false);

		action.createParam(PARAM_PROJECT_KEY).setDescription("Project to export issues for")
				.setExampleValue("my-project").setRequired(true);
		LOGGER.debug("Export action defined");
	}

	@Override
	public void handle(final Request request, final Response response) {
		LOGGER.debug("Handle issueresolver export request");
		response.setHeader("Content-Disposition", "attachment; filename=\"resolved-issues.json\"");

		final JsonWriter responseWriter = response.newJsonWriter();
		writeStart(responseWriter);

		IssueHelper.forEachIssue(request.localConnector(),
				SearchHelper.findIssuesForExport(request.mandatoryParam(PARAM_PROJECT_KEY)), (searchIssuesResponse,
						issue) -> writeIssue(responseWriter, issue, searchIssuesResponse.getComponentsList()));

		writeEnd(responseWriter);
		responseWriter.close();
		LOGGER.debug("Issueresolver export request done");
	}

	private void writeStart(final JsonWriter writer) {
		writer.beginObject();
		writer.prop("version", 1);
		writer.name("issues");
		writer.beginArray();
	}

	private void writeIssue(final JsonWriter writer, final Issue issue, List<Component> components) {
		writer.beginObject();

		final IssueKey key = IssueKey.fromIssue(issue, components);
		key.write(writer);

		final IssueData data = IssueData.fromIssue(issue);
		data.write(writer);

		writer.endObject();
	}

	private void writeEnd(final JsonWriter writer) {
		writer.endArray();
		writer.endObject();
		writer.close();
	}

}


text:
package daemon

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"os"
	"os/signal"
	"time"

	log "github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/Sirupsen/logrus"
	"github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/codegangsta/cli"
	"github.com/socketplane/socketplane/datastore"
)

type Daemon struct {
	Configuration   *Configuration
	Connections     map[string]*Connection
	cC              chan *ConnectionContext
	bindChan        chan *ClusterContext
	clusterListener string
	serialChan      chan bool
	bootstrapNode   bool
}

func NewDaemon() *Daemon {
	return &Daemon{
		&Configuration{},
		map[string]*Connection{},
		make(chan *ConnectionContext),
		make(chan *ClusterContext),
		"",
		make(chan bool),
		false,
	}
}

const (
	ClusterBind = iota
	ClusterJoin
	ClusterLeave
)

type ClusterContext struct {
	Param  string
	Action int
}

func (d *Daemon) Run(ctx *cli.Context) {
	if ctx.Bool("debug") {
		log.SetLevel(log.DebugLevel)
	}
	d.bootstrapNode = ctx.Bool("bootstrap")

	if err := os.Mkdir("/var/run/netns", 0777); err != nil {
		fmt.Println("mkdir /var/run/netns failed", err)
	}

	go ServeAPI(d)
	go func() {
		var bindInterface string
		if ctx.String("iface") != "auto" {
			bindInterface = ctx.String("iface")
		} else {
			intf := d.identifyInterfaceToBind()
			if intf != nil {
				bindInterface = intf.Name
			}
		}
		if bindInterface != "" {
			log.Printf("Binding to %s", bindInterface)
			d.clusterListener = bindInterface
		} else {
			log.Errorf("Unable to identify any Interface to Bind to. Going with Defaults")
		}
		datastore.Init(bindInterface, d.bootstrapNode)
		Bonjour(bindInterface)
		if !d.bootstrapNode {
			d.serialChan <- true
		}
	}()

	go ClusterRPCHandler(d)

	go func() {
		if !d.bootstrapNode {
			log.Printf("Non-Bootstrap node waiting on peer discovery")
			<-d.serialChan
			log.Printf("Non-Bootstrap node admitted into cluster")
		}
		err := CreateBridge()
		if err != nil {
			log.Error(err.Error)
		}
		d.populateConnections()
		_, err = CreateDefaultNetwork()
		if err != nil {
			log.Error(err.Error)
		}
	}()

	go ConnectionRPCHandler(d)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			os.Exit(0)
		}
	}()
	select {}
}

func (d *Daemon) ConfigureClusterListenerPort(listen string) error {
	iface, err := net.InterfaceByName(listen)
	if err != nil {
		log.Debugf("Could not find interface %s", listen)
		return err
	}
	if iface.Flags&net.FlagUp == 0 {
		log.Debugf("%s is down", listen)
		return errors.New("Interface is down")
	}
	log.Debugf("Requesting to bind to %s", listen)
	context := &ClusterContext{listen, ClusterBind}
	d.bindChan <- context
	return nil
}

func (d *Daemon) JoinCluster(address string) error {
	if addr := net.ParseIP(address); addr == nil {
		return errors.New("Invalid IP address")
	}
	log.Debugf("Requesting to join cluster %s", address)
	context := &ClusterContext{address, ClusterJoin}
	d.bindChan <- context
	return nil
}

func ClusterRPCHandler(d *Daemon) {
	for {
		context := <-d.bindChan
		switch context.Action {
		case ClusterBind:
			bindInterface := context.Param
			err := clusterBindRPC(d, bindInterface)
			if err != nil {
				break
			}
		case ClusterJoin:
			joinAddress := context.Param
			err := clusterJoinRPC(d, joinAddress)
			if err != nil {
				break
			}
		case ClusterLeave:
			if err := datastore.Leave(); err != nil {
				log.Errorf("Error leaving cluster. %s", err.Error())
				break
			}
		}
	}
}

func clusterBindRPC(d *Daemon, bindInterface string) error {
	if bindInterface == d.clusterListener {
		log.Debug("Bind Interface is the same as currently bound interface")
		return errors.New("Bind Interface is the same as currently bound interface")
	}
	once := true
	if d.clusterListener != "" {
		log.Debug("Cluster is already bound on another interface. Leaving...")
		once = false
		datastore.Leave()
		time.Sleep(time.Second * 5)
	}
	log.Debugf("Setting new cluster listener to %s", bindInterface)
	d.clusterListener = bindInterface
	datastore.Init(d.clusterListener, d.bootstrapNode)

	if !d.bootstrapNode && once {
		d.serialChan <- true
	}
	return nil
}

func clusterJoinRPC(d *Daemon, joinAddress string) error {
	bindInterface, err := GetIfaceForRoute(joinAddress)
	if err != nil {
		return err
	}
	if d.clusterListener != bindInterface {
		log.Debug("Cluster is already bound on another interface. Leaving...")
		datastore.Leave()
		time.Sleep(time.Second * 10)
		log.Debugf("Setting new cluster listener to %s", bindInterface)
		d.bootstrapNode = false
		d.clusterListener = bindInterface
		datastore.Init(d.clusterListener, d.bootstrapNode)
	}
	if err = datastore.Join(joinAddress); err != nil {
		log.Errorf("Could not join cluster %s. %s", joinAddress, err.Error())
	}
	return nil
}

func (d *Daemon) identifyInterfaceToBind() *net.Interface {
	// If the user isnt binding an interface using --iface option and let the daemon to
	// identify the interface, the daemon will try its best to identify the best interface
	// for the job.
	// In a few auto-install / zerotouch config scenarios, eligible interfaces may
	// be identified after the socketplane daemon is up and running.

	for {
		var intf *net.Interface
		if d.clusterListener != "" {
			intf, _ = net.InterfaceByName(d.clusterListener)
		} else {
			intf = InterfaceToBind()
		}
		if intf != nil {
			return intf
		}
		time.Sleep(time.Second * 5)
		log.Infof("Identifying interface to bind ... Use --iface option for static binding")
	}
	return nil
}

func (d *Daemon) populateConnections() {
	for key, val := range ContextCache {
		connection := &Connection{}
		err := json.Unmarshal([]byte(val), connection)
		if err == nil {
			d.Connections[key] = connection
		}
	}
}


text:
package org.intellij.lang.regexp.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.psi.StringEscapesTokenTypes;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import org.intellij.lang.regexp.RegExpTT;
import org.intellij.lang.regexp.psi.RegExpChar;
import org.intellij.lang.regexp.psi.RegExpElementVisitor;

public class RegExpCharImpl extends RegExpElementImpl implements RegExpChar {
    private static final TokenSet OCT_CHARS = TokenSet.create(RegExpTT.OCT_CHAR, RegExpTT.BAD_OCT_VALUE);
    private static final TokenSet HEX_CHARS = TokenSet.create(RegExpTT.HEX_CHAR, RegExpTT.BAD_HEX_VALUE);
    private static final TokenSet UNICODE_CHARS = TokenSet.create(RegExpTT.UNICODE_CHAR, StringEscapesTokenTypes.INVALID_UNICODE_ESCAPE_TOKEN);

    public RegExpCharImpl(ASTNode astNode) {
        super(astNode);
    }

    @Override
    @NotNull
    public Type getType() {
        final ASTNode child = getNode().getFirstChildNode();
        assert child != null;
        final IElementType t = child.getElementType();
        if (OCT_CHARS.contains(t)) {
            return Type.OCT;
        } else if (HEX_CHARS.contains(t)) {
            return Type.HEX;
        } else if (UNICODE_CHARS.contains(t)) {
            return Type.UNICODE;
        } else if (t == TokenType.ERROR_ELEMENT) {
            return Type.INVALID;
        } else {
            return Type.CHAR;
        }
    }

    @Override
    @Nullable
    public Character getValue() {
      final String s = getUnescapedText();
      if (s.equals("\\") && getType() == Type.CHAR) return '\\';
      return unescapeChar(s);
    }

    @Nullable
    private static Character unescapeChar(String s) {
        final int length = s.length();
        assert length > 0;

        boolean escaped = false;
        for (int idx = 0; idx < length; idx++) {
            final char ch = s.charAt(idx);
            if (!escaped) {
                if (ch == '\\') {
                    escaped = true;
                } else {
                    return ch;
                }
            } else {
                switch (ch) {
                    case 'n':
                        return '\n';
                    case 'r':
                        return '\r';
                    case 't':
                        return '\t';
                    case 'a':
                        return '\u0007';
                    case 'e':
                        return '\u001b';
                    case 'f':
                        return '\f';
                    case 'b':
                        return '\b';
                    case 'c':
                        return (char)(ch ^ 64);
                    case 'x':
                      if (length <= idx + 1) return null;
                      if (s.charAt(idx + 1) == '{') {
                        final char c = s.charAt(length - 1);
                        return (c != '}') ? null : parseNumber(s, idx + 2, 16);
                      }
                      if (length == 3) {
                          return parseNumber(s, idx + 1, 16);
                      }
                      return length == 4 ? parseNumber(s, idx + 1, 16) : null;
                    case 'u':
                        if (length <= idx + 1) return null;
                        if (length > idx + 1 && s.charAt(idx + 1) == '{') {
                            final char c = s.charAt(length - 1);
                            return (c != '}') ? null : parseNumber(s, idx + 2, 16);
                        }
                        if (length != 6) {
                            return ch;
                        }
                        return parseNumber(s, idx + 1, 16);
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                        return parseNumber(s, idx, 8);
                    default:
                        return ch;
                }
            }
        }

        return null;
    }

    private static Character parseNumber(String s, int offset, int radix) {
        int sum = 0;
        int i = offset;
        for (; i < s.length(); i++) {
            final int digit = Character.digit(s.charAt(i), radix);
            if (digit < 0) { // '}' encountered
                break;
            }
            sum = sum * radix + digit;
            if (sum > Character.MAX_CODE_POINT) {
                return null;
            }
        }
        if (i - offset <= 0) return null; // no digits found
        return (char)sum;
    }

    @Override
    public void accept(RegExpElementVisitor visitor) {
        visitor.visitRegExpChar(this);
    }
}


text:
PJHOME=/Users/feiyu/workspace/SparkPlayground/Scala/
SPARKHOME=/Users/feiyu/workspace/sparkOrg/spark-1.3.0-bin-hadoop2.4/
DATADIR=/Users/feiyu/workspace/SparkPlayground/Scala/src/main/resources/graphx/
cd $PJHOME

${SPARKHOME}bin/spark-submit --driver-memory 2g --class com.feiyu.pagerank.PageRankWiki target/scala-2.11/scala_2.11-1.0.jar ${DATADIR}graphx-wiki-vertices.txt ${DATADIR}graphx-wiki-edges.txt


text:
__author__ = 'zhijieliu'

import GlobalConfig

text_hospital_department_info = "[" + GlobalConfig.GLOBAL_INFO_HOSPITAL_NAME + "]-[" + GlobalConfig.GLOBAL_INFO_DEPARTMENT_NAME + "]"

text_welcome = """
欢迎使用本系统
"""
print(text_welcome)

#保存本次信息
GlobalConfig.saveConfigInfoToFile()


text:
package org.gradle.api.internal;

import org.gradle.api.NamedDomainObjectFactory;
import org.gradle.internal.reflect.Instantiator;

public class ReflectiveNamedDomainObjectFactory<T> implements NamedDomainObjectFactory<T> {
    private final Class<? extends T> type;
    private final Object[] extraArgs;
    private final Instantiator instantiator;

    public ReflectiveNamedDomainObjectFactory(Class<? extends T> type, Instantiator instantiator, Object... extraArgs) {
        this.type = type;
        this.instantiator = instantiator;
        this.extraArgs = extraArgs;
    }

    @Override
    public T create(String name) {
        return instantiator.newInstance(type, combineInstantiationArgs(name));
    }

    protected Object[] combineInstantiationArgs(String name) {
        Object[] combinedArgs;
        if (extraArgs.length == 0) {
            Object[] nameArg = {name};
            combinedArgs = nameArg;
        } else {
            combinedArgs = new Object[extraArgs.length + 1];
            combinedArgs[0] = name;
            int i = 1;
            for (Object e : extraArgs) {
                combinedArgs[i++] = e;
            }
        }

        return combinedArgs;
    }
}


text:
//// [tests/cases/conformance/es6/moduleExportsSystem/decoratedDefaultExportsGetExportedSystem.ts] ////

//// [a.ts]
var decorator: ClassDecorator;

@decorator
export default class Foo {}

//// [b.ts]
var decorator: ClassDecorator;

@decorator
export default class {}

//// [a.js]
System.register([], function (exports_1, context_1) {
    "use strict";
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var decorator, Foo;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [],
        execute: function () {
            Foo = /** @class */ (() => {
                let Foo = class Foo {
                };
                Foo = __decorate([
                    decorator
                ], Foo);
                return Foo;
            })();
            exports_1("default", Foo);
        }
    };
});
//// [b.js]
System.register([], function (exports_1, context_1) {
    "use strict";
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var decorator, default_1;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [],
        execute: function () {
            default_1 = /** @class */ (() => {
                let default_1 = class {
                };
                default_1 = __decorate([
                    decorator
                ], default_1);
                return default_1;
            })();
            exports_1("default", default_1);
        }
    };
});


text:
package country

import (
	"testing"
)

const (
	TestAlpha2  = "CA"
	TestAlpha3  = "CAN"
	TestCountry = "Canada"
	TestNumeric = "124"
)

func TestGetCountryNameFromAlpha2(t *testing.T) {
	country, err := GetCountryNameFromAlpha2(TestAlpha2)
	if err != nil {
		t.Fatalf("No Country found for '%s'", TestAlpha2)
	}
	if country != TestCountry {
		t.Fatalf("Country should be '%s' got '%s' for '%s'", TestCountry, country, TestAlpha2)
	}
}

func TestGetCountryNameFromAlpha3(t *testing.T) {
	country, err := GetCountryNameFromAlpha3(TestAlpha3)
	if err != nil {
		t.Fatalf("No Country found for '%s'", TestAlpha3)
	}
	if country != TestCountry {
		t.Fatalf("Country should be '%s' got '%s' for '%s'", TestCountry, country, TestAlpha3)
	}
}

func TestGetCountryNameFromNumeric(t *testing.T) {
	country, err := GetCountryNameFromNumeric(TestNumeric)
	if err != nil {
		t.Fatalf("No Country found for '%s'", TestNumeric)
	}
	if country != TestCountry {
		t.Fatalf("Country should be '%s' got '%s' for '%s'", TestCountry, country, TestNumeric)
	}
}

func TestGetAlpha2FromAlpha3(t *testing.T) {
	alpha2, err := GetAlpha2FromAlpha3(TestAlpha3)
	if err != nil {
		t.Fatalf("No Alpha2 found for '%s'", TestAlpha3)
	}
	if alpha2 != TestAlpha2 {
		t.Fatalf("Alpha2 should be '%s' got '%s' for '%s'", TestAlpha2, alpha2, TestAlpha3)
	}
}

func TestGetAlpha2FromNumeric(t *testing.T) {
	alpha2, err := GetAlpha2FromNumeric(TestNumeric)
	if err != nil {
		t.Fatalf("No Alpha2 found for '%s'", TestNumeric)
	}
	if alpha2 != TestAlpha2 {
		t.Fatalf("Alpha2 should be '%s' got '%s' for '%s'", TestAlpha2, alpha2, TestNumeric)
	}
}

func TestGetAlpha3FromAlpha2(t *testing.T) {
	alpha3, err := GetAlpha3FromAlpha2(TestAlpha2)
	if err != nil {
		t.Fatalf("No Alpha3 found for '%s'", TestAlpha2)
	}
	if alpha3 != TestAlpha3 {
		t.Fatalf("Alpha3 should be '%s' got '%s' for '%s'", TestAlpha3, alpha3, TestAlpha2)
	}
}

func TestGetAlpha3FromNumeric(t *testing.T) {
	alpha3, err := GetAlpha3FromNumeric(TestNumeric)
	if err != nil {
		t.Fatalf("No Alpha3 found for '%s'", TestNumeric)
	}
	if alpha3 != TestAlpha3 {
		t.Fatalf("Alpha3 should be '%s' got '%s' for '%s'", TestAlpha3, alpha3, TestNumeric)
	}
}

func TestGetNumericFromAlpha2(t *testing.T) {
	numeric, err := GetNumericFromAlpha2(TestAlpha2)
	if err != nil {
		t.Fatalf("No numeric found for '%s'", TestAlpha2)
	}
	if numeric != TestNumeric {
		t.Fatalf("Numeric should be '%s' got '%s' for '%s'", TestNumeric, numeric, TestAlpha2)
	}
}

func TestGetNumericFromAlpha3(t *testing.T) {
	numeric, err := GetNumericFromAlpha3(TestAlpha3)
	if err != nil {
		t.Fatalf("No numeric found for '%s'", TestAlpha3)
	}
	if numeric != TestNumeric {
		t.Fatalf("Numeric should be '%s' got '%s' for '%s'", TestNumeric, numeric, TestAlpha3)
	}
}


text:
package config

import (
	"bytes"
	"unicode"
)

// Like strings.Fields but ignores spaces inside areas surrounded
// by the specified quote character.
// To specify a single quote use backslash to escape it: '\''
func SplitQuotedFields(in string, quote rune) []string {
	type stateEnum int
	const (
		inSpace stateEnum = iota
		inField
		inQuote
		inQuoteEscaped
	)
	state := inSpace
	r := []string{}
	var buf bytes.Buffer

	for _, ch := range in {
		switch state {
		case inSpace:
			if ch == quote {
				state = inQuote
			} else if !unicode.IsSpace(ch) {
				buf.WriteRune(ch)
				state = inField
			}

		case inField:
			if ch == quote {
				state = inQuote
			} else if unicode.IsSpace(ch) {
				r = append(r, buf.String())
				buf.Reset()
			} else {
				buf.WriteRune(ch)
			}

		case inQuote:
			if ch == quote {
				state = inField
			} else if ch == '\\' {
				state = inQuoteEscaped
			} else {
				buf.WriteRune(ch)
			}

		case inQuoteEscaped:
			buf.WriteRune(ch)
			state = inQuote
		}
	}

	if buf.Len() != 0 {
		r = append(r, buf.String())
	}

	return r
}