text:
namespace atheris {

namespace {

std::function<void(py::bytes data)>& test_one_input_global =
    *new std::function<void(py::bytes data)>([](py::bytes data) -> void {
      std::cerr << "You must call Setup() before Fuzz()." << std::endl;
      _exit(-1);
    });
std::function<py::bytes(py::bytes data, size_t max_size, unsigned int seed)>
    custom_mutator_global;
bool use_custom_mutator = false;

std::function<py::bytes(py::bytes data1, py::bytes data2, size_t max_out_size,
                        unsigned int seed)>
    custom_crossover_global;
bool use_custom_crossover = false;

std::vector<std::string>& args_global = *new std::vector<std::string>();

enum internal_libfuzzer_mode {
  INTERNAL_LIBFUZZER_AUTO = 0,
  INTERNAL_LIBFUZZER_ENABLE = 1,
  INTERNAL_LIBFUZZER_DISABLE = 2
};

internal_libfuzzer_mode internal_libfuzzer = INTERNAL_LIBFUZZER_AUTO;
bool setup_called = false;

}  // namespace

// These versions of _trace_branch, _trace_cmp, and _reserve_counter are called
// before fuzzing has begun.

NO_SANITIZE
void prefuzz_trace_branch(uint64_t idx) {
  // We don't care about tracing before fuzzing starts, do nothing.
}

NO_SANITIZE
py::handle prefuzz_trace_cmp(py::handle left, py::handle right, int opid,
                             uint64_t idx, bool left_is_const) {
  // We don't care about tracing before fuzzing starts, but _trace_cmp actually
  // *replaces* the comparison, so just do a compare.
  PyObject* ret = PyObject_RichCompare(left.ptr(), right.ptr(), opid);

  if (ret == nullptr) {
    throw py::error_already_set();
  } else {
    return ret;
  }
}

NO_SANITIZE
void prefuzz_trace_regex_match(std::string pattern_match, py::handle object) {}

NO_SANITIZE
std::vector<std::string> Setup(
    const std::vector<std::string>& args,
    const std::function<void(py::bytes data)>& test_one_input,
    py::kwargs kwargs) {
  if (setup_called) {
    std::cerr << Colorize(STDERR_FILENO,
                          "Setup() must not be called more than once.")
              << std::endl;
    exit(1);
  }
  setup_called = true;

  args_global = args;
  test_one_input_global = test_one_input;

  // Strip libFuzzer arguments (single dash).
  std::vector<std::string> ret;
  for (const std::string& arg : args) {
    if (arg.size() > 1 && arg[0] == '-' && arg[1] != '-') {
      continue;
    }
    ret.push_back(arg);
  }

  if (kwargs.contains("internal_libfuzzer")) {
    bool use_internal = kwargs["internal_libfuzzer"].cast<bool>();
    if (use_internal) {
      internal_libfuzzer = INTERNAL_LIBFUZZER_ENABLE;
    } else {
      internal_libfuzzer = INTERNAL_LIBFUZZER_DISABLE;
    }
  }

  if (kwargs.contains("custom_mutator") &&
      !kwargs["custom_mutator"].is_none()) {
    use_custom_mutator = true;
    custom_mutator_global =
        kwargs["custom_mutator"]
            .cast<std::function<py::bytes(py::bytes data, size_t max_size,
                                          unsigned int seed)>>();
  }
  if (kwargs.contains("custom_crossover") &&
      !kwargs["custom_crossover"].is_none()) {
    use_custom_crossover = true;
    custom_crossover_global =
        kwargs["custom_crossover"]
            .cast<std::function<py::bytes(py::bytes data1, py::bytes data2,
                                          size_t max_out_size,
                                          unsigned int seed)>>();
  }
  return ret;
}

// Checks if libfuzzer is already present.
NO_SANITIZE
bool libfuzzer_is_loaded() {
  void* self_lib = dlopen(nullptr, RTLD_LAZY);
  if (!self_lib) return false;

  void* sym = dlsym(self_lib, "LLVMFuzzerRunDriver");

  dlclose(self_lib);
  return sym;
}

NO_SANITIZE
py::module LoadCoreModule() {
  if (internal_libfuzzer == INTERNAL_LIBFUZZER_AUTO) {
    // Automatically determine whether we have libfuzzer loaded
    if (libfuzzer_is_loaded()) {
      internal_libfuzzer = INTERNAL_LIBFUZZER_DISABLE;  // Don't use our own
    } else {
      internal_libfuzzer = INTERNAL_LIBFUZZER_ENABLE;  // Use our own
    }
  }

  if (internal_libfuzzer == INTERNAL_LIBFUZZER_ENABLE) {
    std::cerr << "INFO: Using built-in libfuzzer" << std::endl;
    return py::module::import("atheris.core_with_libfuzzer");
  } else {
    std::cerr << "INFO: Using preloaded libfuzzer" << std::endl;
    return py::module::import("atheris.core_without_libfuzzer");
  }
}

NO_SANITIZE
py::module LoadExternalFunctionsModule(const std::string& module_name) {
  // Changing dlopenflags so external functions like LLVMFuzzerCustomMutator are
  // in the global scope.
  py::module sys = py::module::import("sys");
  py::int_ flags = sys.attr("getdlopenflags")();
  sys.attr("setdlopenflags")(py::cast<int>(flags) | RTLD_GLOBAL);
  py::module module = py::module::import(module_name.data());
  sys.attr("setdlopenflags")(flags);
  return module;
}

NO_SANITIZE
py::bytes Mutate(py::bytes data, size_t max_size) {
  std::cerr << Colorize(STDERR_FILENO,
                        "Fuzz() must be called before Mutate() can be called.")
            << std::endl;
  exit(-1);
}

int pending_counters = 0;
int ReservePendingCounter() { return ++pending_counters; }

NO_SANITIZE
void Fuzz() {
  if (!setup_called) {
    std::cerr << Colorize(STDERR_FILENO,
                          "Setup() must be called before Fuzz() can be called.")
              << std::endl;
    exit(1);
  }

  py::module atheris =
      (py::module)py::module::import("sys").attr("modules")["atheris"];

  std::string atheris_prefix = "atheris.";

  if (use_custom_mutator) {
    py::module custom_mutator =
        LoadExternalFunctionsModule(atheris_prefix + "custom_mutator");
    custom_mutator.attr("_set_custom_mutator")(custom_mutator_global);
  }
  if (use_custom_crossover) {
    py::module custom_crossover =
        LoadExternalFunctionsModule(atheris_prefix + "custom_crossover");
    custom_crossover.attr("_set_custom_crossover")(custom_crossover_global);
  }
  py::module core = LoadCoreModule();

  // Reserve all pending counters
  int res_ctrs = core.attr("_reserve_counters")(pending_counters).cast<int>();
  if (res_ctrs != 0) {
    std::cerr << Colorize(
                     STDERR_FILENO,
                     "Atheris internal error: expected 0 counters previously "
                     "reserved when reserving preregistered batch; got " +
                         std::to_string(res_ctrs))
              << std::endl;
    _exit(1);
  }
  pending_counters = 0;

  atheris.attr("Mutate") = core.attr("Mutate");
  atheris.attr("_trace_cmp") = core.attr("_trace_cmp");
  atheris.attr("_trace_regex_match") = core.attr("_trace_regex_match");
  atheris.attr("_trace_branch") = core.attr("_trace_branch");
  atheris.attr("_reserve_counter") = core.attr("_reserve_counter");

  core.attr("start_fuzzing")(args_global, test_one_input_global);
}

PYBIND11_MODULE(native, m) {
  m.def("Setup", &Setup);
  m.def("Fuzz", &Fuzz);
  m.def("Mutate", &Mutate);
  m.def("_trace_branch", &prefuzz_trace_branch);
  m.def("_trace_cmp", &prefuzz_trace_cmp, py::return_value_policy::move);
  m.def("_reserve_counter", &ReservePendingCounter);
  m.def("_trace_regex_match", &prefuzz_trace_regex_match);
  m.def("libfuzzer_is_loaded", &libfuzzer_is_loaded);

  py::class_<FuzzedDataProvider>(m, "FuzzedDataProvider")
      .def(py::init<py::bytes>())
      .def("ConsumeUnicode", &FuzzedDataProvider::ConsumeUnicode,
           py::arg("count"))
      .def("ConsumeUnicodeNoSurrogates",
           &FuzzedDataProvider::ConsumeUnicodeNoSurrogates)
      .def("ConsumeBytes", &FuzzedDataProvider::ConsumeBytes)
      .def("ConsumeString", &FuzzedDataProvider::ConsumeString)
      .def("ConsumeInt", &FuzzedDataProvider::ConsumeInt)
      .def("ConsumeUInt", &FuzzedDataProvider::ConsumeUInt)
      .def("ConsumeIntInRange", &FuzzedDataProvider::ConsumeIntInRange)
      .def("ConsumeIntList", &FuzzedDataProvider::ConsumeIntList)
      .def("ConsumeIntListInRange", &FuzzedDataProvider::ConsumeIntListInRange)
      .def("ConsumeFloat", &FuzzedDataProvider::ConsumeFloat)
      .def("ConsumeRegularFloat", &FuzzedDataProvider::ConsumeRegularFloat)
      .def("ConsumeProbability", &FuzzedDataProvider::ConsumeProbability)
      .def("ConsumeFloatInRange", &FuzzedDataProvider::ConsumeFloatInRange)
      .def("ConsumeFloatList", &FuzzedDataProvider::ConsumeFloatList)
      .def("ConsumeRegularFloatList",
           &FuzzedDataProvider::ConsumeRegularFloatList)
      .def("ConsumeProbabilityList",
           &FuzzedDataProvider::ConsumeProbabilityList)
      .def("ConsumeFloatListInRange",
           &FuzzedDataProvider::ConsumeFloatListInRange)
      .def("PickValueInList", &FuzzedDataProvider::PickValueInList)
      .def("ConsumeBool", &FuzzedDataProvider::ConsumeBool)
      .def("remaining_bytes", &FuzzedDataProvider::remaining_bytes)
      .def("buffer", &FuzzedDataProvider::buffer);
  m.attr("ALL_REMAINING") = std::numeric_limits<size_t>::max();
}

}  // namespace atheris


text:
/**
 * @author Yevgeny Kazakov, Jun 2, 2011
 */
package org.semanticweb.elk.util.hashing;

import java.util.Iterator;
import java.util.List;

/**
 * Class used to generate strong hash codes for newly created objects, and for
 * combining multiple hash codes into new ones in various ways.
 *
 * @author Yevgeny Kazakov
 * @author Markus Kroetzsch
 * @author Frantisek Simancik
 *
 */
public class HashGenerator {

	/**
	 * The counter incremented with each generated hash code which will be used
	 * for generating a hash code by generateNextHashCode().
	 */
	private static int counter = 0;

	/**
	 * Generate a new "hash code" integer. Consecutive calls to this method
	 * create a sequence of integers with near-uniform distribution. These codes
	 * may be used as hash codes for objects that are managed in such a way that
	 * no two objects of different content can occur. Different hash codes then
	 * guarantee that the objects are not equal, even if the hash code does is
	 * not based on the hashed object at all. Obviously, hash codes of this form
	 * are not stable over multiple runs of the program, and can therefore not
	 * be used for comparing objects across runs (e.g. in testing). However,
	 * they can be useful in hash-based data structures.
	 *
	 * @return the generated hash code
	 */
	public static int generateNextHashCode() {
		// we use a strategy from the java.util.HashMap
		int h = ++counter;
		h ^= (h >>> 20) ^ (h >>> 12);
		return h ^ (h >>> 7) ^ (h >>> 4);
	}

	/**
	 * Compute the combined hash code of several objects using their
	 * {@link #hashCode()} functions. The combined hash code depends on the
	 * order in which the objects are listed.
	 *
	 * The current implementation is based on the Jenkins One-at-a-Time hash,
	 * see http://www.burtleburtle.net/bob/hash/doobs.html and also
	 * http://en.wikipedia.org/wiki/Jenkins_hash_function.
	 *
	 * @param objects
	 *            the list of objects for which to compute the combined hash
	 *            code
	 * @return the combined hash code
	 */
	public static int combinedHashCode(Object... objects) {
		int result = 0;
		for (Object obj : objects) {
			int h = obj.hashCode();
			result += h;
			result += (h << 10);
			result ^= (h >> 6);
		}
		result += (result << 3);
		result ^= (result >> 11);
		result += (result << 15);

		return result;
	}

	/**
	 * Compute the combined hash code of several objects using their
	 * {@link #hashCode()} functions. The combined hash code depends on the
	 * order in which the objects are listed.
	 *
	 * The current implementation is based on the Jenkins One-at-a-Time hash,
	 * see http://www.burtleburtle.net/bob/hash/doobs.html and also
	 * http://en.wikipedia.org/wiki/Jenkins_hash_function.
	 *
	 * @param objects
	 *            the list of objects for which to compute the combined hash
	 *            code
	 * @return the combined hash code
	 */
	public static int combinedHashCode(Iterable<?> objects) {
		int result = 0;
		for (Object obj : objects) {
			int h = obj.hashCode();
			result += h;
			result += (h << 10);
			result ^= (h >> 6);
		}
		result += (result << 3);
		result ^= (result >> 11);
		result += (result << 15);

		return result;
	}

	/**
	 * Combine many hash codes with an associative commutative hash function.
	 * Associativity ensures that the result of this functions can be further
	 * combined with other hash codes for getting the same result as if all hash
	 * codes had been combined in one step.
	 *
	 * If finalize is false, then the method as such represents an associative
	 * commutative hash, i.e. the return value can be combined with other
	 * set-based hash codes in any order without making a difference. If
	 * finalize is true, then the method combines its arguments with a
	 * commutative hash, but shuffles the overall result. The method as such
	 * then is neither an associative nor a commutative operation. This mode of
	 * operation should be used whenever no further elements are to be added to
	 * the set of hashes.
	 *
	 * @param finalize
	 * @param hashes
	 * @return the combined hash code
	 */
	public static int combineMultisetHash(boolean finalize, int... hashes) {
		int hash = 0;
		for (int h : hashes) {
			hash = hash + h;
		}
		if (finalize) {
			hash = combineListHash(hash);
		}
		return hash;
	}

	/**
	 * Combine the hash codes of a collection of objects with an associative
	 * commutative hash function. Associativity ensures that the result of this
	 * functions can be further combined with other hash codes for getting the
	 * same result as if all hash codes had been combined in one step.
	 *
	 * If finalize is false, then the method as such represents an associative
	 * commutative hash, i.e. the return value can be combined with other
	 * set-based hash codes in any order without making a difference. If
	 * finalize is true, then the method combines its arguments with a
	 * commutative hash, but shuffles the overall result. The method as such
	 * then is neither an associative nor a commutative operation. This mode of
	 * operation should be used whenever no further elements are to be added to
	 * the set of hashes.
	 *
	 * @param finalize
	 * @param hashObjects
	 * @param hasher
	 * @return the combined hash code
	 */
	public static <T> int combineMultisetHash(boolean finalize,
			Iterable<? extends T> hashObjects, Hasher<T> hasher) {
		return combineMultisetHash(finalize, hashObjects.iterator(), hasher);
	}

	/**
	 * Combine the hash codes of a collection of objects with an associative
	 * commutative hash function. Associativity ensures that the result of this
	 * functions can be further combined with other hash codes for getting the
	 * same result as if all hash codes had been combined in one step.
	 *
	 * If finalize is false, then the method as such represents an associative
	 * commutative hash, i.e. the return value can be combined with other
	 * set-based hash codes in any order without making a difference. If
	 * finalize is true, then the method combines its arguments with a
	 * commutative hash, but shuffles the overall result. The method as such
	 * then is neither an associative nor a commutative operation. This mode of
	 * operation should be used whenever no further elements are to be added to
	 * the set of hashes.
	 *
	 * @param <T>
	 *
	 * @param finalize
	 * @param hashObjectIterator
	 * @param hasher
	 * @return the combined hash code
	 */
	public static <T> int combineMultisetHash(boolean finalize,
			Iterator<? extends T> hashObjectIterator, Hasher<T> hasher) {
		int hash = 0;
		while (hashObjectIterator.hasNext()) {
			hash += hasher.hash(hashObjectIterator.next());
		}
		if (finalize) {
			hash = combineListHash(hash);
		}
		return hash;
	}

	/**
	 * Combine many hash codes into one in a way that depends on their order.
	 *
	 * The current implementation is based on the Jenkins One-at-a-Time hash,
	 * see http://www.burtleburtle.net/bob/hash/doobs.html and also
	 * http://en.wikipedia.org/wiki/Jenkins_hash_function.
	 *
	 * @param hashes
	 * @return the combined hash code
	 */
	public static int combineListHash(int... hashes) {
		int hash = 0;
		for (int h : hashes) {
			hash += h;
			hash += (hash << 10);
			hash ^= (hash >> 6);
		}
		hash += (hash << 3);
		hash ^= (hash >> 11);
		hash += (hash << 15);

		return hash;
	}

	/**
	 * Combine the hash codes of a collection of objects into one in a way that
	 * depends on their order.
	 *
	 * The current implementation is based on the Jenkins One-at-a-Time hash,
	 * see http://www.burtleburtle.net/bob/hash/doobs.html and also
	 * http://en.wikipedia.org/wiki/Jenkins_hash_function.
	 *
	 * @param hashObjects
	 * @param hasher
	 * @return the combined hash code
	 */
	public static <T> int combineListHash(List<? extends T> hashObjects,
			Hasher<T> hasher) {
		return combineListHash(hashObjects.iterator(), hasher);
	}

	/**
	 * Combine the hash codes of a collection of objects into one in a way that
	 * depends on their order.
	 *
	 * The current implementation is based on the Jenkins One-at-a-Time hash,
	 * see http://www.burtleburtle.net/bob/hash/doobs.html and also
	 * http://en.wikipedia.org/wiki/Jenkins_hash_function.
	 *
	 * @param hashObjectIterator
	 * @param hasher
	 * @return the combined hash code
	 */
	public static <T> int combineListHash(
			Iterator<? extends T> hashObjectIterator, Hasher<T> hasher) {
		int hash = 0;
		while (hashObjectIterator.hasNext()) {
			hash += hasher.hash(hashObjectIterator.next());
			hash += (hash << 10);
			hash ^= (hash >> 6);
		}
		hash += (hash << 3);
		hash ^= (hash >> 11);
		hash += (hash << 15);
		return hash;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package cz.lkpanenka.model;

import java.util.Comparator;

import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Subclass;

/**
 * Reprezentace clena klubu
 *
 * @author jiri stepan
 *
 */

@Subclass(index=true)
public class Member extends Person {

	@Index  String email;
	@Index  String login; //secondary login information

	 String password;

	@Index String sessionCookie; //cookie pro session
	@Index String rememberCookie; //cookie pro zapamatovani

	 String phone;
	 String phone2;

	 String address;

	@Index  String membershipStatus; //MEMBER, CHILD

	String[] roles; //MANAGER,ADMIN

	//---------------------------
	public Member(){
	}

	public Member(String email, String password, String name, String surname){
		this.email = email;
		this.password = password;
		this.name = name;
		this.surname = surname;
	}

	 public static class Comparators {
	        public static Comparator<Member> EMAIL = new Comparator<Member>() {
	            @Override
	            public int compare(Member o1, Member o2) {
	                return o1.email.compareTo(o2.email);
	            }
	        };
	 }

	//---------------------------
	public String getEmail() {
		return getNull(email);
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return getNull(password);
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return getNull(phone);
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getPhone2() {
		return getNull(phone2);
	}

	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}

	public String getAddress() {
		return getNull(address);
	}

	public void setAddress(String address) {
		this.address = getNull(address);
	}

	public String getMembershipStatus() {
		return getNull(membershipStatus);
	}

	public void setMembershipStatus(String membershipStatus) {
		this.membershipStatus = membershipStatus;
	}

	public String[] getRoles() {
		return roles;
	}

	public void setRole(String[] role) {
		this.roles = role;
	}

	/** hack kvuli pridavani. zkontroluje, zda id nema hodnotu String null */
	public void fixId() {
		if ((id!=null) && (id.equals("null"))){
			this.setId(null);
		}
	}
}


text:
namespace MailMessaging.Plain.IntegrationTest.Contracts
{
    public delegate void ConnectionReceivedEventHandler(object sender, ConnectionReceivedEventHandlerArgs args);
}


text:
#include <stdint.h>
#include <string.h>

#include "py/runtime.h"
#include "py/mperrno.h"
#include "extmod/vfs_fat.h"

#include "systick.h"
#include "led.h"
#include "storage.h"
#include "irq.h"

#if MICROPY_HW_ENABLE_STORAGE

#define STORAGE_SYSTICK_MASK    (0x1ff) // 512ms
#define STORAGE_IDLE_TICK(tick) (((tick) & ~(SYSTICK_DISPATCH_NUM_SLOTS - 1) & STORAGE_SYSTICK_MASK) == 0)

#if defined(MICROPY_HW_BDEV2_IOCTL)
#define FLASH_PART2_START_BLOCK (FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0))
#endif

static bool storage_is_initialised = false;

static void storage_systick_callback(uint32_t ticks_ms);

void storage_init(void) {
    if (!storage_is_initialised) {
        storage_is_initialised = true;

        systick_enable_dispatch(SYSTICK_DISPATCH_STORAGE, storage_systick_callback);

        MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_INIT, 0);

        #if defined(MICROPY_HW_BDEV2_IOCTL)
        MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_INIT, 0);
        #endif

        // Enable the flash IRQ, which is used to also call our storage IRQ handler
        // It must go at the same priority as USB (see comment in irq.h).
        NVIC_SetPriority(FLASH_IRQn, IRQ_PRI_FLASH);
        HAL_NVIC_EnableIRQ(FLASH_IRQn);
    }
}

uint32_t storage_get_block_size(void) {
    return FLASH_BLOCK_SIZE;
}

uint32_t storage_get_block_count(void) {
    #if defined(MICROPY_HW_BDEV2_IOCTL)
    return FLASH_PART2_START_BLOCK + MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0);
    #else
    return FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0);
    #endif
}

static void storage_systick_callback(uint32_t ticks_ms) {
    if (STORAGE_IDLE_TICK(ticks_ms)) {
        // Trigger a FLASH IRQ to execute at a lower priority
        NVIC->STIR = FLASH_IRQn;
    }
}

void FLASH_IRQHandler(void) {
    IRQ_ENTER(FLASH_IRQn);
    MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_IRQ_HANDLER, 0);
    #if defined(MICROPY_HW_BDEV2_IOCTL)
    MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_IRQ_HANDLER, 0);
    #endif
    IRQ_EXIT(FLASH_IRQn);
}

void storage_flush(void) {
    MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_SYNC, 0);
    #if defined(MICROPY_HW_BDEV2_IOCTL)
    MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_SYNC, 0);
    #endif
}

static void build_partition(uint8_t *buf, int boot, int type, uint32_t start_block, uint32_t num_blocks) {
    buf[0] = boot;

    if (num_blocks == 0) {
        buf[1] = 0;
        buf[2] = 0;
        buf[3] = 0;
    } else {
        buf[1] = 0xff;
        buf[2] = 0xff;
        buf[3] = 0xff;
    }

    buf[4] = type;

    if (num_blocks == 0) {
        buf[5] = 0;
        buf[6] = 0;
        buf[7] = 0;
    } else {
        buf[5] = 0xff;
        buf[6] = 0xff;
        buf[7] = 0xff;
    }

    buf[8] = start_block;
    buf[9] = start_block >> 8;
    buf[10] = start_block >> 16;
    buf[11] = start_block >> 24;

    buf[12] = num_blocks;
    buf[13] = num_blocks >> 8;
    buf[14] = num_blocks >> 16;
    buf[15] = num_blocks >> 24;
}

bool storage_read_block(uint8_t *dest, uint32_t block) {
    // printf("RD %u\n", block);
    if (block == 0) {
        // fake the MBR so we can decide on our own partition table

        for (int i = 0; i < 446; i++) {
            dest[i] = 0;
        }

        build_partition(dest + 446, 0, 0x01 /* FAT12 */, FLASH_PART1_START_BLOCK, MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0));
        #if defined(MICROPY_HW_BDEV2_IOCTL)
        build_partition(dest + 462, 0, 0x01 /* FAT12 */, FLASH_PART2_START_BLOCK, MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0));
        #else
        build_partition(dest + 462, 0, 0, 0, 0);
        #endif
        build_partition(dest + 478, 0, 0, 0, 0);
        build_partition(dest + 494, 0, 0, 0, 0);

        dest[510] = 0x55;
        dest[511] = 0xaa;

        return true;

    #if defined(MICROPY_HW_BDEV_READBLOCK)
    } else if (FLASH_PART1_START_BLOCK <= block && block < FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV_READBLOCK(dest, block - FLASH_PART1_START_BLOCK);
    #endif
    } else {
        return false;
    }
}

bool storage_write_block(const uint8_t *src, uint32_t block) {
    // printf("WR %u\n", block);
    if (block == 0) {
        // can't write MBR, but pretend we did
        return true;
    #if defined(MICROPY_HW_BDEV_WRITEBLOCK)
    } else if (FLASH_PART1_START_BLOCK <= block && block < FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV_WRITEBLOCK(src, block - FLASH_PART1_START_BLOCK);
    #endif
    } else {
        return false;
    }
}

int storage_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) {
    #if defined(MICROPY_HW_BDEV_READBLOCKS)
    if (FLASH_PART1_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV_READBLOCKS(dest, block_num - FLASH_PART1_START_BLOCK, num_blocks);
    }
    #endif

    #if defined(MICROPY_HW_BDEV2_READBLOCKS)
    if (FLASH_PART2_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART2_START_BLOCK + MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV2_READBLOCKS(dest, block_num - FLASH_PART2_START_BLOCK, num_blocks);
    }
    #endif

    for (size_t i = 0; i < num_blocks; i++) {
        if (!storage_read_block(dest + i * FLASH_BLOCK_SIZE, block_num + i)) {
            return -MP_EIO; // error
        }
    }
    return 0; // success
}

int storage_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) {
    #if defined(MICROPY_HW_BDEV_WRITEBLOCKS)
    if (FLASH_PART1_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART1_START_BLOCK + MICROPY_HW_BDEV_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV_WRITEBLOCKS(src, block_num - FLASH_PART1_START_BLOCK, num_blocks);
    }
    #endif

    #if defined(MICROPY_HW_BDEV2_WRITEBLOCKS)
    if (FLASH_PART2_START_BLOCK <= block_num && block_num + num_blocks <= FLASH_PART2_START_BLOCK + MICROPY_HW_BDEV2_IOCTL(BDEV_IOCTL_NUM_BLOCKS, 0)) {
        return MICROPY_HW_BDEV2_WRITEBLOCKS(src, block_num - FLASH_PART2_START_BLOCK, num_blocks);
    }
    #endif

    for (size_t i = 0; i < num_blocks; i++) {
        if (!storage_write_block(src + i * FLASH_BLOCK_SIZE, block_num + i)) {
            return -MP_EIO; // error
        }
    }
    return 0; // success
}

/******************************************************************************/
// MicroPython bindings
//
// Expose the flash as an object with the block protocol.

#ifdef MICROPY_HW_BDEV_SPIFLASH_EXTENDED
// Board defined an external SPI flash for use with extended block protocol
#define SPIFLASH (MICROPY_HW_BDEV_SPIFLASH_EXTENDED)
#define PYB_FLASH_NATIVE_BLOCK_SIZE (MP_SPIFLASH_ERASE_BLOCK_SIZE)
#define MICROPY_HW_BDEV_READBLOCKS_EXT(dest, bl, off, len) (spi_bdev_readblocks_raw(SPIFLASH, (dest), (bl), (off), (len)))
#define MICROPY_HW_BDEV_WRITEBLOCKS_EXT(dest, bl, off, len) (spi_bdev_writeblocks_raw(SPIFLASH, (dest), (bl), (off), (len)))

#elif (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2) && MICROPY_HW_ENABLE_INTERNAL_FLASH_STORAGE
// Board uses littlefs and internal flash, so enable extended block protocol on internal flash
#define PYB_FLASH_NATIVE_BLOCK_SIZE (FLASH_BLOCK_SIZE)
#define MICROPY_HW_BDEV_READBLOCKS_EXT(dest, bl, off, len) (flash_bdev_readblocks_ext((dest), (bl), (off), (len)))
#define MICROPY_HW_BDEV_WRITEBLOCKS_EXT(dest, bl, off, len) (flash_bdev_writeblocks_ext((dest), (bl), (off), (len)))
#endif

#ifndef PYB_FLASH_NATIVE_BLOCK_SIZE
#define PYB_FLASH_NATIVE_BLOCK_SIZE (FLASH_BLOCK_SIZE)
#endif

typedef struct _pyb_flash_obj_t {
    mp_obj_base_t base;
    uint32_t start; // in bytes
    uint32_t len; // in bytes
    #if defined(SPIFLASH)
    bool use_native_block_size;
    #endif
} pyb_flash_obj_t;

// This Flash object represents the entire available flash, with emulated partition table at start
const pyb_flash_obj_t pyb_flash_obj = {
    { &pyb_flash_type },
    -(FLASH_PART1_START_BLOCK * FLASH_BLOCK_SIZE), // to offset FLASH_PART1_START_BLOCK
    0, // actual size handled in ioctl, MP_BLOCKDEV_IOCTL_BLOCK_COUNT case
};

STATIC void pyb_flash_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_flash_obj_t *self = MP_OBJ_TO_PTR(self_in);
    if (self == &pyb_flash_obj) {
        mp_printf(print, "Flash()");
    } else {
        mp_printf(print, "Flash(start=%u, len=%u)", self->start, self->len);
    }
}

STATIC mp_obj_t pyb_flash_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
    // Parse arguments
    enum { ARG_start, ARG_len };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_start, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
        { MP_QSTR_len,   MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
    };
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    if (args[ARG_start].u_int == -1 && args[ARG_len].u_int == -1) {
        // Default singleton object that accesses entire flash, including virtual partition table
        return MP_OBJ_FROM_PTR(&pyb_flash_obj);
    }

    pyb_flash_obj_t *self = m_new_obj(pyb_flash_obj_t);
    self->base.type = &pyb_flash_type;
    #if defined(SPIFLASH)
    self->use_native_block_size = false;
    #endif

    uint32_t bl_len = (storage_get_block_count() - FLASH_PART1_START_BLOCK) * FLASH_BLOCK_SIZE;

    mp_int_t start = args[ARG_start].u_int;
    if (start == -1) {
        start = 0;
    } else if (!(0 <= start && start < bl_len && start % PYB_FLASH_NATIVE_BLOCK_SIZE == 0)) {
        mp_raise_ValueError(NULL);
    }

    mp_int_t len = args[ARG_len].u_int;
    if (len == -1) {
        len = bl_len - start;
    } else if (!(0 < len && start + len <= bl_len && len % PYB_FLASH_NATIVE_BLOCK_SIZE == 0)) {
        mp_raise_ValueError(NULL);
    }

    self->start = start;
    self->len = len;

    return MP_OBJ_FROM_PTR(self);
}

STATIC mp_obj_t pyb_flash_readblocks(size_t n_args, const mp_obj_t *args) {
    pyb_flash_obj_t *self = MP_OBJ_TO_PTR(args[0]);
    uint32_t block_num = mp_obj_get_int(args[1]);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE);
    mp_uint_t ret = -MP_EIO;
    if (n_args == 3) {
        // Cast self->start to signed in case it's pyb_flash_obj with negative start
        block_num += FLASH_PART1_START_BLOCK + (int32_t)self->start / FLASH_BLOCK_SIZE;
        ret = storage_read_blocks(bufinfo.buf, block_num, bufinfo.len / FLASH_BLOCK_SIZE);
    }
    #if defined(MICROPY_HW_BDEV_READBLOCKS_EXT)
    else if (self != &pyb_flash_obj) {
        // Extended block read on a sub-section of the flash storage
        uint32_t offset = mp_obj_get_int(args[3]);
        block_num += self->start / PYB_FLASH_NATIVE_BLOCK_SIZE;
        ret = MICROPY_HW_BDEV_READBLOCKS_EXT(bufinfo.buf, block_num, offset, bufinfo.len);
    }
    #endif
    return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_flash_readblocks_obj, 3, 4, pyb_flash_readblocks);

STATIC mp_obj_t pyb_flash_writeblocks(size_t n_args, const mp_obj_t *args) {
    pyb_flash_obj_t *self = MP_OBJ_TO_PTR(args[0]);
    uint32_t block_num = mp_obj_get_int(args[1]);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
    mp_uint_t ret = -MP_EIO;
    if (n_args == 3) {
        // Cast self->start to signed in case it's pyb_flash_obj with negative start
        block_num += FLASH_PART1_START_BLOCK + (int32_t)self->start / FLASH_BLOCK_SIZE;
        ret = storage_write_blocks(bufinfo.buf, block_num, bufinfo.len / FLASH_BLOCK_SIZE);
    }
    #if defined(MICROPY_HW_BDEV_WRITEBLOCKS_EXT)
    else if (self != &pyb_flash_obj) {
        // Extended block write on a sub-section of the flash storage
        uint32_t offset = mp_obj_get_int(args[3]);
        block_num += self->start / PYB_FLASH_NATIVE_BLOCK_SIZE;
        ret = MICROPY_HW_BDEV_WRITEBLOCKS_EXT(bufinfo.buf, block_num, offset, bufinfo.len);
    }
    #endif
    return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_flash_writeblocks_obj, 3, 4, pyb_flash_writeblocks);

STATIC mp_obj_t pyb_flash_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t arg_in) {
    pyb_flash_obj_t *self = MP_OBJ_TO_PTR(self_in);
    mp_int_t cmd = mp_obj_get_int(cmd_in);
    switch (cmd) {
        case MP_BLOCKDEV_IOCTL_INIT: {
            mp_int_t ret = 0;
            storage_init();
            if (mp_obj_get_int(arg_in) == 1) {
                // Will be using extended block protocol
                if (self == &pyb_flash_obj) {
                    ret = -1;
                #if defined(SPIFLASH)
                } else {
                    // Switch to use native block size of SPI flash
                    self->use_native_block_size = true;
                #endif
                }
            }
            return MP_OBJ_NEW_SMALL_INT(ret);
        }
        case MP_BLOCKDEV_IOCTL_DEINIT:
            storage_flush();
            return MP_OBJ_NEW_SMALL_INT(0);                                             // TODO properly
        case MP_BLOCKDEV_IOCTL_SYNC:
            storage_flush();
            return MP_OBJ_NEW_SMALL_INT(0);

        case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: {
            mp_int_t n;
            if (self == &pyb_flash_obj) {
                // Get true size
                n = storage_get_block_count();
            #if defined(SPIFLASH)
            } else if (self->use_native_block_size) {
                n = self->len / PYB_FLASH_NATIVE_BLOCK_SIZE;
            #endif
            } else {
                n = self->len / FLASH_BLOCK_SIZE;
            }
            return MP_OBJ_NEW_SMALL_INT(n);
        }

        case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: {
            mp_int_t n = FLASH_BLOCK_SIZE;
            #if defined(SPIFLASH)
            if (self->use_native_block_size) {
                n = PYB_FLASH_NATIVE_BLOCK_SIZE;
            }
            #endif
            return MP_OBJ_NEW_SMALL_INT(n);
        }

        case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: {
            int ret = 0;
            #if defined(SPIFLASH)
            if (self->use_native_block_size) {
                mp_int_t block_num = self->start / PYB_FLASH_NATIVE_BLOCK_SIZE + mp_obj_get_int(arg_in);
                ret = spi_bdev_ioctl(SPIFLASH, BDEV_IOCTL_BLOCK_ERASE, block_num);
            }
            #endif
            return MP_OBJ_NEW_SMALL_INT(ret);
        }

        default:
            return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl);

STATIC const mp_rom_map_elem_t pyb_flash_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&pyb_flash_readblocks_obj) },
    { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&pyb_flash_writeblocks_obj) },
    { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&pyb_flash_ioctl_obj) },
};

STATIC MP_DEFINE_CONST_DICT(pyb_flash_locals_dict, pyb_flash_locals_dict_table);

const mp_obj_type_t pyb_flash_type = {
    { &mp_type_type },
    .name = MP_QSTR_Flash,
    .print = pyb_flash_print,
    .make_new = pyb_flash_make_new,
    .locals_dict = (mp_obj_dict_t *)&pyb_flash_locals_dict,
};

void pyb_flash_init_vfs(fs_user_mount_t *vfs) {
    vfs->base.type = &mp_fat_vfs_type;
    vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_NATIVE | MP_BLOCKDEV_FLAG_HAVE_IOCTL;
    vfs->fatfs.drv = vfs;
    #if MICROPY_FATFS_MULTI_PARTITION
    vfs->fatfs.part = 1; // flash filesystem lives on first partition
    #endif
    vfs->blockdev.readblocks[0] = MP_OBJ_FROM_PTR(&pyb_flash_readblocks_obj);
    vfs->blockdev.readblocks[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj);
    vfs->blockdev.readblocks[2] = MP_OBJ_FROM_PTR(storage_read_blocks); // native version
    vfs->blockdev.writeblocks[0] = MP_OBJ_FROM_PTR(&pyb_flash_writeblocks_obj);
    vfs->blockdev.writeblocks[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj);
    vfs->blockdev.writeblocks[2] = MP_OBJ_FROM_PTR(storage_write_blocks); // native version
    vfs->blockdev.u.ioctl[0] = MP_OBJ_FROM_PTR(&pyb_flash_ioctl_obj);
    vfs->blockdev.u.ioctl[1] = MP_OBJ_FROM_PTR(&pyb_flash_obj);
}

#endif


text:
<?php

namespace Omnipay\Alipay\Responses;

use Omnipay\Alipay\Requests\AopTradeCreateRequest;

class AopTradeCreateResponse extends AbstractAopResponse
{
    protected $key = 'alipay_trade_create_response';

    /**
     * @var AopTradeCreateRequest
     */
    protected $request;

    public function getTradeNo()
    {
        return $this->getAlipayResponse('trade_no');
    }

    public function getOutTradeNo()
    {
        return $this->getAlipayResponse('out_trade_no');
    }
}


text:
[![NPM Version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![Dependency Status][david-image]][david-url]
[![devDependency Status][david-dev-image]][david-dev-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]

> **Beta**. *This is a Beta release of the Stackdriver Trace agent for Node.js. These libraries might be changed in backward-incompatible ways and are not subject to any SLA or deprecation policy.*

This module provides Stackdriver Trace support for Node.js applications. [Stackdriver Trace](https://cloud.google.com/cloud-trace/) is a feature of [Google Cloud Platform](https://cloud.google.com/) that collects latency data (traces) from your applications and displays it in near real-time in the [Google Cloud Console][cloud-console].

![Stackdriver Trace Overview](doc/images/cloud-trace-overview-page.png)

## Prerequisites

1. Your application will need to be using Node.js version 4.0 or greater.
1. You will need a project in the [Google Developers Console][cloud-console]. Your application can run anywhere, but the trace data is associated with a particular project.
1. [Enable the Trace API](https://console.cloud.google.com/flows/enableapi?apiid=cloudtrace) for your project.
1. At this point, code using untranspiled async/await is not supported by this module. See [this section](#how-does-automatic-tracing-work).

## Installation

1. Install with [`npm`](https://www.npmjs.com) or add to your [`package.json`](https://docs.npmjs.com/files/package.json#dependencies).

    ```sh
    # Install through npm while saving to the local 'package.json'
    npm install --save @google-cloud/trace-agent
    ```

2. Set the GCLOUD_PROJECT environment variable. You can find your Project ID in the [Google Cloud Developers Console][cloud-console], or by running the command `gcloud projects list`. You can ensure this environment variable is set at startup time by placing it in your startup script in `package.json`:

    ```json
    "scripts": {
      "start": "GCLOUD_PROJECT=<YOUR_PROJECT_ID> node server.js",
    },
    ```

3. Include and start the library *as the very first action in your application*:

    ```js
    var agent = require('@google-cloud/trace-agent').start();
    ```

  If you use `--require` in your start up command, make sure that the trace agent is --required first.

4. If you are running your application locally, or on a machine where you are using the [Google Cloud SDK][gcloud-sdk], make sure to log in with the application default credentials:
    ```sh
    gcloud beta auth application-default login
    ```

If you are running somewhere other than the Google Cloud Platform, see [running elsewhere](#running-elsewhere).

## Configuration

See [the default configuration](config.js) for a list of possible configuration options. These options can be passed to the agent through the object argument to the start command shown above:

```js
require('@google-cloud/trace-agent').start({samplingRate: 500});
```

Alternatively, you can provide configuration through a config file. This can be useful if you want to load our module using `--require` on the command line instead of editing your main script. You can start by copying the default config file and modifying it to suit your needs. The `GCLOUD_TRACE_CONFIG` environment variable should point to your configuration file.

```bash
export GCLOUD_TRACE_CONFIG=./path/to/your/trace/configuration.js
```

## Running on Google Cloud Platform

There are three different services that can host Node.js applications within Google Cloud Platform.

### Google App Engine flexible environment

If you are using [Google App Engine flexible environment](https://cloud.google.com/appengine/docs/flexible/), you do not have to do any additional configuration.

### Google Compute Engine

For __Google Compute Engine instances__, you need to explicitly enable the `https://www.googleapis.com/auth/trace.append` access scope for each instance. When creating a new instance through the Google Cloud Platform Console, you can do this under __Identity and API access__: Use the Compute Engine default service account, select the __Set access for each API__ access scopes option, and ensure that the __Stackdriver Trace__ access is set to _Write Only_.

To enable to scope on existing GCE instances, you can follow the instructions for using a service account under [running elsewhere](#running-elsewhere).

### Google Container Engine

As with Compute Engine, Container Engine nodes need to be created with the `https://www.googleapis.com/auth/trace.append` scope, which is configurable during cluster creation:
* If the cluster is being created with the `gcloud` CLI, pass the scope to the command with the `--scopes` command (multiple scopes can be [delimited with a comma](https://cloud.google.com/sdk/gcloud/reference/container/clusters/create)):

  ```sh
  gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/trace.append
  ```

* If the cluster is being created through the Cloud Console UI, ensure that the "Stackdriver Trace" project access is set to "Write Only" (this is the default).

Alternatively, you can also follow the instructions for using a service account under [running elsewhere](#running-elsewhere). It's recommended that you store the service account credentials as [Kubernetes Secret](http://kubernetes.io/v1.1/docs/user-guide/secrets.html).

## Running elsewhere

If your application is running outside of Google Cloud Platform, such as locally, on-premise, or on another cloud provider, you can still use Stackdriver Trace.

1. You will need to specify your project ID when starting the trace agent.

    ```sh
    GCLOUD_PROJECT=particular-future-12345 node myapp.js
    ```

2. You need to provide service account credentials to your application. The recommended way is via [Application Default Credentials][app-default-credentials].

  1. [Create a new JSON service account key][service-account].
  2. Copy the key somewhere your application can access it. Be sure not to expose the key publicly.
  3. Set the environment variable `GOOGLE_APPLICATION_CREDENTIALS` to the full path to the key. The trace agent will automatically look for this environment variable.

If you are running your application on a development machine or test environment where you are using the [`gcloud` command line tools][gcloud-sdk], and are logged using `gcloud beta auth application-default login`, you already have sufficient credentials, and a service account key is not required.

Alternatively, you may set the `keyFilename` or `credentials` configuration field to the full path or contents to the key file, respectively. Setting either of these fields will override either setting `GOOGLE_APPLICATION_CREDENTIALS` or logging in using `gcloud`. (See the [default configuration](config.js) for more details.)

## Viewing your traces

Run your application and start sending some requests towards your application. In about 30 seconds or so, you should see trace data gathered in the [STACKDRIVER -> Traces -> Trace List](https://console.cloud.google.com/traces/overview) in the console:

![Trace List](doc/images/tracelist.png?raw=true)

This is the trace list that shows a sampling of the incoming requests your application is receiving. You can click on a URI to drill down into the details. This will show you the RPCs made by your application and their associated latency:

![Trace View](doc/images/traceview.png?raw=true)

## What gets traced

The trace agent can do automatic tracing of the following web frameworks:
* [express](https://www.npmjs.com/package/express) (version 4)
* [gRPC](https://www.npmjs.com/package/grpc)* server (version 1)
* [hapi](https://www.npmjs.com/package/hapi) (versions 8 - 16)
* [koa](https://www.npmjs.com/package/koa) (version 1)
* [restify](https://www.npmjs.com/package/restify) (versions 3 - 4)

The agent will also automatic trace of the following kinds of RPCs:
* Outbound HTTP requests through the `http` and `https` core modules
* [gRPC](https://www.npmjs.com/package/grpc)* client (version 1)
* [MongoDB-core](https://www.npmjs.com/package/mongodb-core) (version 1)
* [Mongoose](https://www.npmjs.com/package/mongoose) (version 4)
* [Redis](https://www.npmjs.com/package/redis) (versions 0.12 - 2)
* [MySQL](https://www.npmjs.com/package/mysql) (version ^2.9)

*Note: The latest versions of gRPC (versions 1.1 and up) have dropped support for Node.js <4.0. We do not support tracing gRPC on unsupported versions of Node.js.

You can use the [Custom Tracing API](#custom-tracing-api) to trace other processes in your application.

We are working on expanding the types of frameworks and services we can do automatic tracing for. We are also interested in hearing your feedback on what other frameworks, or versions, you would like to see supported. This would help us prioritize support going forward. If you want support for a particular framework or RPC, please file a bug or +1 an existing bug.

## Advanced trace configuration

The trace agent can be configured by passing a configurations object to the agent `start` method. This configuration option accepts all values in the [default configuration](config.js).

One configuration option of note is `enhancedDatabaseReporting`. Setting this option to `true` will cause database operations for redis and MongoDB to record query summaries and results as labels on reported trace spans.

### Trace batching and sampling

The aggregation of trace spans before publishing can be configured using the `flushDelaySeconds` and `bufferSize` [options](config.js). The spans recorded for each incoming requests are placed in a buffer after the request has completed. Spans will be published to the UI in batch when the spans from `bufferSize` requests have been queued in the buffer or after `flushDelaySeconds` have passed since the last publish, whichever comes first.

The trace configuration additionally exposes the `samplingRate` option which sets an upper bound on the number of traced requests captured per second. Some Google Cloud environments may override this sampling policy.

### Tracing Additional Modules

In addition to the modules listed [above](#what-gets-traced), the trace agent can be configured to trace additional modules through the use of *plugins*. To load an additional plugin, specify it in the agent's configuration:

```js
  require('@google-cloud/trace-agent').start({
    plugins: {
      // You may use a package name or absolute path to the file.
      'my-module': '@google-cloud/trace-agent-plugin-my-module',
      'another-module': path.join(__dirname, 'path/to/my-custom-plugins/plugin-another-module.js')
    }
  });
```

This list of plugins will be merged with the list of built-in plugins, which will be loaded by the plugin loader. Each plugin is only loaded when the module that it patches is loaded; in other words, there is no computational overhead for listing plugins for unused modules.

To create a plugin for a module, please see the [Plugin Developer Guide](doc/plugin-guide.md).

## Custom Tracing API

The custom tracing API can be used to add custom spans to trace. A *span* is a particular unit of work within a trace, such as an RPC request. Spans may be nested; the outermost span is called a *root span*, even if there are no nested child spans. Root spans typically correspond to incoming requests, while *child spans* typically correspond to outgoing requests, or other work that is triggered in response to incoming requests.

For any of the web frameworks for which we provide [built-in plugins](#what-gets-traced), a root span is automatically started whenever an incoming request is received (in other words, all middleware already runs within a root span). If you wish to record a span outside of any of these frameworks, any traced code must run within a root span that you create yourself.

### Accessing the API

Calling the `start` function returns an instance of `TraceApi`, which provides an interface for tracing:

```js
  var traceApi = require('@google-cloud/trace-agent').start();
```

It can also be retrieved by subsequent calls to `get` elsewhere:

```js
  // after start() is called
  var traceApi = require('@google-cloud/trace-agent').get();
```

A `TraceApi` object is guaranteed to be returned by both of these calls, even if the agent is disabled.

A fully detailed overview of the `TraceApi` object is available [here](doc/trace-api.md).

## How does automatic tracing work?

The Trace Agent automatically patches well-known modules to insert calls to functions that start, label, and end spans to measure latency of RPCs (such as mysql, redis, etc.) and incoming requests (such as express, hapi, etc.). As each RPC is typically performed on behalf of an incoming request, we must make sure that this association is accurately reflected in span data. To provide a uniform, generalized way of keeping track of which RPC belongs to which incoming request, we rely on the [continuation-local-storage][] module to keep track of the "trace context" across asynchronous boundaries.

This method, which relies on [async-listener][] to preserve continuations over asynchronous boundaries, works great in most cases. However, it does have some limitations that can prevent us from being able to properly propagate trace context:

* It is possible to use JavaScript code that does its own queuing of callback functions – effectively merging asynchronous execution contexts. For example, one may write a http request buffering library that queues requests and then performs them in a batch in one shot. In such a case, when all the callbacks fire, they will execute in the context which flushed the queue instead of the context which added the callbacks to the queue. This problem is called the pooling problem or the [user-space queuing problem][queueing-problem], and is a fundamental limitation of JavaScript. If your application uses such code, you will notice that RPCs from many requests are showing up under a single trace, or that certain portions of your outbound RPCs do not get traced. In such cases we try to work around the problem through monkey patching, or by working with the library authors to fix the code to properly propagate context. However, finding problematic code is not always trivial.
* Presently, it is not possible for [async-listener][] to keep track of async transitions in ES7 async/await functions that are available with Node 7.6+. If your application uses untranspiled async functions, we will not be properly track RPCs. We do expect to be able to track native async/await functions in the once [async-listener][] has support for the new [async-hooks][] API.

## Contributing changes

* See [CONTRIBUTING.md](CONTRIBUTING.md)

## Licensing

* See [LICENSE](LICENSE)

[app-default-credentials]: https://developers.google.com/identity/protocols/application-default-credentials
[async-hooks]: https://nodejs.org/api/async_hooks.html
[async-listener]: https://www.npmjs.com/package/async-listener
[cloud-console]: https://console.cloud.google.com
[continuation-local-storage]: https://www.npmjs.com/package/continuation-local-storage
[coveralls-image]: https://coveralls.io/repos/GoogleCloudPlatform/cloud-trace-nodejs/badge.svg?branch=master&service=github
[coveralls-url]: https://coveralls.io/github/GoogleCloudPlatform/cloud-trace-nodejs?branch=master
[david-dev-image]: https://david-dm.org/GoogleCloudPlatform/cloud-trace-nodejs/dev-status.svg
[david-dev-url]: https://david-dm.org/GoogleCloudPlatform/cloud-trace-nodejs?type=dev
[david-image]: https://david-dm.org/GoogleCloudPlatform/cloud-trace-nodejs.svg
[david-url]: https://david-dm.org/GoogleCloudPlatform/cloud-trace-nodejs
[gcloud-sdk]: https://cloud.google.com/sdk/gcloud/
[npm-image]: https://badge.fury.io/js/%40google-cloud%2Ftrace-agent.svg
[npm-url]: https://npmjs.org/package/@google-cloud/trace-agent
[queueing-problem]: https://github.com/groundwater/nodejs-symposiums/tree/master/2016-02-26-Errors/Round1/UserModeQueuing
[service-account]: https://console.developers.google.com/apis/credentials/serviceaccountkey
[snyk-image]: https://snyk.io/test/github/GoogleCloudPlatform/cloud-trace-nodejs/badge.svg
[snyk-url]: https://snyk.io/test/github/GoogleCloudPlatform/cloud-trace-nodejs
[travis-image]: https://travis-ci.org/GoogleCloudPlatform/cloud-trace-nodejs.svg?branch=master
[travis-url]: https://travis-ci.org/GoogleCloudPlatform/cloud-trace-nodejs


text:
package jdwp

import "fmt"

func dbg(msg string, args ...interface{}) {
	const enabled = false
	if enabled {
		fmt.Println(fmt.Sprintf(msg, args...))
	}
}


text:
package org.boon.json.serializers.impl;

import org.boon.Boon;
import org.boon.Exceptions;
import org.boon.Maps;
import org.boon.Str;
import org.boon.cache.SimpleCache;
import org.boon.core.TypeType;
import org.boon.core.reflection.FastStringUtils;
import org.boon.core.reflection.Invoker;
import org.boon.core.reflection.Reflection;
import org.boon.core.reflection.fields.FieldAccess;
import org.boon.json.serializers.JsonSerializerInternal;
import org.boon.primitive.CharBuf;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static org.boon.Boon.sputs;
import static org.boon.Exceptions.die;
import static org.boon.Exceptions.handle;

/**
 *
 * This is a simple fast serializer.
 * It excludes default values, i.e., int v by default is 0.
 * It excludes nulls and empties as well.
 */
public class JsonSimpleSerializerImpl implements JsonSerializerInternal {
    private final Map <Class<?>,  Map<String, FieldAccess>> fieldMap = new ConcurrentHashMap<>( );
    private final String view;
    private final boolean encodeStrings;

    private final boolean serializeAsSupport;

    private final CharBuf builder;

    private int level;

    private boolean asciiOnly;

    public JsonSimpleSerializerImpl() {

        this.view = null;
        this.encodeStrings = true;
        serializeAsSupport = true;
        builder = CharBuf.create( 4000 );

    }

    public JsonSimpleSerializerImpl(boolean encodeStrings) {

        this.view = null;
        this.encodeStrings = encodeStrings;

        serializeAsSupport = true;
        builder = CharBuf.create( 4000 );

    }

    public JsonSimpleSerializerImpl(String view, boolean encodeStrings,
                                    boolean serializeAsSupport, boolean asciiOnly) {

        this.encodeStrings = encodeStrings;
        this.serializeAsSupport = serializeAsSupport;
        this.view = view;
        builder = CharBuf.create( 4000 );
        this.asciiOnly = asciiOnly;

    }

    SimpleCache<String, String> stringCache;
    CharBuf encodedJsonChars;

    public final void serializeString( String str, CharBuf builder ) {

          if (encodeStrings) {

              if (stringCache == null) {
                  stringCache = new SimpleCache<>(1000);
                  encodedJsonChars = CharBuf.create(str.length());

              }

              String encodedString = stringCache.get(str);
              if (encodedString == null) {

                  encodedJsonChars.asJsonString(str, asciiOnly);
                  encodedString = encodedJsonChars.toStringAndRecycle();
                  stringCache.put(str, encodedString);
              }

              builder.add(encodedString);

          } else {
              builder.addQuoted(str);
          }

    }

    public CharBuf serialize( Object obj ) {
        level=0;

        builder.readForRecycle ();
        try {
            serializeObject( obj, builder );
        } catch ( Exception ex ) {
            return handle(CharBuf.class, "unable to serializeObject", ex);
        }
        return builder;
    }

    @Override
    public void serialize(CharBuf builder, Object obj) {
        level = 0;

        try {
            serializeObject( obj, builder );
        } catch ( Exception ex ) {
             handle("unable to serializeObject", ex);
        }
    }

    public final boolean serializeField ( Object parent, FieldAccess fieldAccess, CharBuf builder ) {

        final String fieldName = fieldAccess.name();
        final TypeType typeEnum = fieldAccess.typeEnum ();

        //try {

            if ( view!=null ){
                if (!fieldAccess.isViewActive( view ) ) {
                    return false;
                }
            }

            switch ( typeEnum ) {

                case INT:
                    int value = fieldAccess.getInt ( parent );
                    if (value !=0) {
                        serializeFieldName ( fieldName, builder );
                        builder.addInt ( value  );
                        return true;
                    }
                    return false;
                case BOOLEAN:
                    boolean bvalue = fieldAccess.getBoolean ( parent );
                    if ( bvalue ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addBoolean ( bvalue  );
                        return true;
                    }
                    return false;

                case BYTE:
                    byte byvalue = fieldAccess.getByte ( parent );
                    if ( byvalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addByte ( byvalue  );
                        return true;
                    }
                    return false;
                case LONG:
                    long lvalue = fieldAccess.getLong ( parent );
                    if ( lvalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addLong ( lvalue  );
                        return true;
                    }
                    return false;

                case DOUBLE:
                    double dvalue = fieldAccess.getDouble ( parent );
                    if ( dvalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addDouble ( dvalue  );
                        return true;
                    }
                    return false;
                case FLOAT:
                    float fvalue = fieldAccess.getFloat ( parent );
                    if ( fvalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addFloat ( fvalue  );
                        return true;
                    }
                    return false;
                case SHORT:
                    short svalue = fieldAccess.getShort( parent );
                    if ( svalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addShort ( svalue  );
                        return true;
                    }
                    return false;
                case CHAR:
                    char cvalue = fieldAccess.getChar( parent );
                    if ( cvalue != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addQuoted( "" + cvalue  );
                        return true;
                    }
                    return false;

            }

            Object value = fieldAccess.getObject ( parent );

            if ( value == null ) {
                return false;
            }

            /* Avoid back reference and infinite loops. */
            if ( value == parent ) {
                return false;
            }

            switch ( typeEnum )  {
                case BIG_DECIMAL:
                    serializeFieldName ( fieldName, builder );
                    builder.addBigDecimal ( (BigDecimal) value );
                    return true;
                case NUMBER:
                    Number nvalue = (Number) fieldAccess.getObject(parent);
                    if ( nvalue.intValue() != 0 ) {
                        serializeFieldName ( fieldName, builder );
                        builder.addString(nvalue.toString());
                        return true;
                    }
                    return false;
                case BIG_INT:
                    serializeFieldName ( fieldName, builder );
                    builder.addBigInteger((BigInteger) value);
                    return true;
                case DATE:
                    serializeFieldName ( fieldName, builder );
                    serializeDate((Date) value, builder);
                    return true;
                case STRING:
                    serializeFieldName ( fieldName, builder );
                    serializeString((String) value, builder);
                    return true;
                case CLASS:
                    serializeFieldName ( fieldName, builder );
                    builder.addQuoted ( (( Class ) value).getName());
                    return true;

                case CHAR_SEQUENCE:
                    serializeFieldName ( fieldName, builder );
                    serializeString ( value.toString (), builder );
                    return true;
                case INTEGER_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addInt ( ( Integer ) value );
                    return true;
                case LONG_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addLong ( ( Long ) value );
                    return true;
                case FLOAT_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addFloat ( ( Float ) value );
                    return true;
                case DOUBLE_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addDouble ( ( Double ) value );
                    return true;
                case SHORT_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addShort ( ( Short ) value );
                    return true;
                case BYTE_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addByte ( ( Byte ) value );
                    return true;
                case CHAR_WRAPPER:
                    serializeFieldName ( fieldName, builder );
                    builder.addQuoted ( (( Character ) value).toString() );
                    return true;
                case ENUM:
                    serializeFieldName ( fieldName, builder );
                    builder.addQuoted ( value.toString () );
                    return true;
                case COLLECTION:
                case LIST:
                case SET:
                    Collection collection = (Collection) value;
                    if ( collection.size () > 0) {
                        serializeFieldName ( fieldName, builder );
                        this.serializeCollection ( collection, builder );
                        return true;
                    }
                    return false;
                case MAP:
                    Map map = (Map) value;
                    if ( map.size () > 0) {
                        serializeFieldName ( fieldName, builder );
                        this.serializeMap ( map, builder );
                        return true;
                    }
                    return false;

                case ARRAY:
                case ARRAY_INT:
                case ARRAY_BYTE:
                case ARRAY_SHORT:
                case ARRAY_FLOAT:
                case ARRAY_DOUBLE:
                case ARRAY_LONG:
                case ARRAY_STRING:
                case ARRAY_OBJECT:
                    if (value.getClass().isArray()) {
                        if ( Array.getLength (value) > 0) {
                            serializeFieldName ( fieldName, builder );
                            this.serializeArray ( fieldAccess.componentType(), value, builder );
                            return true;
                        }
                    }
                    return false;

                case INTERFACE:
                case ABSTRACT:
                    serializeFieldName ( fieldName, builder );
                    serializeSubtypeInstance ( value, builder );
                    return true;

                case OBJECT:
                    serializeFieldName ( fieldName, builder );
                    final TypeType instanceType = TypeType.getInstanceType(value);
                    if (instanceType== TypeType.INSTANCE) {
                        serializeSubtypeInstance(value, builder);
                    } else {
                        serializeObject(value, builder);
                    }
                    return true;

                case INSTANCE:
                    serializeFieldName ( fieldName, builder );
                    serializeInstance ( value, builder );
                    return true;

                case SYSTEM:
                    return false;

                case TIME_ZONE:

                    serializeFieldName ( fieldName, builder );
                    TimeZone zone = (TimeZone) value;

                    builder.addQuoted ( zone.getID() );
                    return true;

                case CURRENCY:
                    serializeFieldName ( fieldName, builder );
                    serializeCurrency ( (Currency) value, builder );
                    return true;

                default:
                    serializeFieldName ( fieldName, builder );
                    serializeUnknown(value, builder);
                    return true;
            }

//        } catch (Exception ex) {
//            return handle(Boolean.class, ex, "Unable to serialize field", fieldName, "from parent object", parent,
//                    "type enum", typeEnum);
//        }

    }

    public final void serializeDate ( Date date, CharBuf builder ) {
        builder.addLong(date.getTime ());
    }

    public final void serializeCurrency ( Currency currency, CharBuf builder ) {
        builder.addChar ( '"' );
        builder.addString(currency.getCurrencyCode());
        builder.addChar ( '"' );
    }

    public final void serializeObject( Object obj, CharBuf builder )  {

        TypeType type = TypeType.getInstanceType(obj);

        switch ( type ) {

            case NULL:
                return;
            case INT:
                builder.addInt ( int.class.cast ( obj ) );
                return;
            case BOOLEAN:
                builder.addBoolean ( boolean.class.cast ( obj ) );
                return;
            case BYTE:
                builder.addByte ( byte.class.cast ( obj ) );
                return;
            case LONG:
                builder.addLong ( long.class.cast ( obj ) );
                return;
            case DOUBLE:
                builder.addDouble ( double.class.cast ( obj ) );
                return;
            case FLOAT:
                builder.addFloat ( float.class.cast ( obj ) );
                return;
            case SHORT:
                builder.addShort ( short.class.cast ( obj ) );
                return;
            case CHAR:
                builder.addChar ( char.class.cast ( obj ) );
                return;
            case BIG_DECIMAL:
                builder.addBigDecimal ( ( BigDecimal ) obj );
                return;
            case BIG_INT:
                builder.addBigInteger ( ( BigInteger ) obj );
                return;
            case DATE:
                serializeDate ( ( Date ) obj, builder );
                return;
            case CLASS:
                builder.addQuoted ( (( Class ) obj).getName() );
                return;

            case STRING:
                serializeString ( ( String ) obj, builder );
                return;
            case CHAR_SEQUENCE:
                serializeString ( obj.toString(), builder );
                return;
            case BOOLEAN_WRAPPER:
                builder.addBoolean ( ( Boolean ) obj );
                return;
            case INTEGER_WRAPPER:
                builder.addInt ( (Integer) obj);
                return;
            case LONG_WRAPPER:
                builder.addLong ( (Long) obj);
                return;
            case FLOAT_WRAPPER:
                builder.addFloat ( (Float) obj);
                return;
            case DOUBLE_WRAPPER:
                builder.addDouble ( (Double) obj);
                return;
            case SHORT_WRAPPER:
                builder.addShort ( (Short) obj);
                return;
            case BYTE_WRAPPER:
                builder.addByte ( (Byte) obj);
                return;
            case CHAR_WRAPPER:
                builder.addChar ( (Character) obj);
                return;
            case ENUM:
                builder.addQuoted ( obj.toString () );
                return;

            case TIME_ZONE:
                TimeZone zone = (TimeZone) obj;

                builder.addQuoted ( zone.getID() );
                return;

            case COLLECTION:
            case LIST:
            case SET:
                this.serializeCollection ( (Collection) obj, builder );
                return;
            case MAP:
                this.serializeMap ( ( Map ) obj, builder );
                return;

            case ARRAY:
            case ARRAY_INT:
            case ARRAY_BYTE:
            case ARRAY_SHORT:
            case ARRAY_FLOAT:
            case ARRAY_DOUBLE:
            case ARRAY_LONG:
            case ARRAY_STRING:
            case ARRAY_OBJECT:
                this.serializeArray ( obj, builder );
                return;
            case ABSTRACT:
            case INTERFACE:
                serializeSubtypeInstance ( obj, builder );
                return;

            case INSTANCE:
                serializeInstance ( obj, builder );
                return;
            case CURRENCY:
                serializeCurrency ( ( Currency ) obj, builder );
                return;
            default:

                    this.serializeUnknown(obj, builder);

        }

    }

    public void serializeUnknown ( Object obj, CharBuf builder ) {
        //try {
            builder.addQuoted ( obj.toString () );
        //} catch (Exception ex) {
           //unknown so... TODO log
           //
        //}
    }

    public final void serializeInstance ( Object instance, CharBuf builder )  {

        try {

            level++;

            if (level > 100) {
                die("Detected circular dependency", builder.toString());
            }

            if (serializeAsSupport && Reflection.respondsTo(instance, "serializeAs")) {
                serializeObject(Invoker.invoke(instance, "serializeAs"), builder);
                return;
            }

            final Collection<FieldAccess> fields = getFields(instance.getClass()).values();

            builder.addChar( '{' );

            int index = 0;
            for ( FieldAccess fieldAccess : fields ) {
                 if (serializeField ( instance, fieldAccess, builder ) ) {
                     builder.add(',');
                     index++;
                 }
            }
            if ( index > 0 ) {
                builder.removeLastChar();
            }
            builder.addChar( '}' );

        } catch (Exception ex) {
            Exceptions.handle(ex, "serialize instance", instance,
                    "class name of instance", Boon.className(instance),
                    "obj", instance);
        } finally {
            level--;
        }

    }

    @Override
    public void serializeInstance(Object obj, CharBuf builder, boolean includeTypeInfo) {

        this.serializeInstance(obj, builder);

    }

    public Map<String, FieldAccess> getFields( Class<? extends Object> aClass ) {
            Map<String, FieldAccess> map = fieldMap.get( aClass );
            if (map == null) {
                map = doGetFields ( aClass );
                fieldMap.put ( aClass, map );
            }
            return map;

   }

    private final Map<String, FieldAccess> doGetFields ( Class<? extends Object> aClass ) {
        Map<String, FieldAccess> fields =  Maps.copy ( Reflection.getPropertyFieldAccessMapFieldFirstForSerializer ( aClass ) );

        List<FieldAccess> removeFields = new ArrayList<>();

        for (FieldAccess field : fields.values()) {
            if (field.isWriteOnly ())  {
                removeFields.add(field);
            }
        }

        for (FieldAccess fieldAccess : removeFields) {
            fields.remove(fieldAccess.name());
        }
        return fields;
    }

    private static final char [] EMPTY_MAP_CHARS = {'{', '}'};

    public final void serializeMap( Map<Object, Object> smap, CharBuf builder )  {

        Map map = smap;
        if ( map.size () == 0 ) {
            builder.addChars ( EMPTY_MAP_CHARS );
            return;
        }

        builder.addChar( '{' );

        int index=0;
        final Set<Map.Entry> entrySet = map.entrySet();
        for ( Map.Entry entry : entrySet ) {
            if (entry.getValue ()!=null ) {
                serializeFieldName ( Str.toString(entry.getKey()), builder );
                serializeObject( entry.getValue(), builder );
                builder.addChar ( ',' );
                index++;
            }
        }
        if (index>0)
        builder.removeLastChar ();
        builder.addChar( '}' );

    }

    public final void serializeArray ( TypeType componentType, Object objectArray, CharBuf builder ) {

        switch (componentType) {
            case STRING: //optimization
                String[] array = (String[]) objectArray;
                final int length = array.length;

                builder.addChar( '[' );
                for ( int index = 0; index < length; index++ ) {
                        serializeString( array[index], builder );
                        builder.addChar ( ',' );
                }
                builder.removeLastChar ();
                builder.addChar( ']' );
                break;
            default:
                serializeArray(objectArray, builder);
        }
    }
    @Override
    public final void serializeArray ( Object array, CharBuf builder ) {

        if ( Array.getLength (array) == 0 ) {
            builder.addChars ( EMPTY_LIST_CHARS );
            return;
        }

        builder.addChar( '[' );
        final int length = Array.getLength( array );
        for ( int index = 0; index < length; index++ ) {
            serializeObject( Array.get( array, index ), builder );
            builder.addChar ( ',' );
        }
        builder.removeLastChar ();
        builder.addChar( ']' );

    }

    private void serializeFieldName ( String name, CharBuf builder ) {
            builder.addJsonFieldName ( FastStringUtils.toCharArray ( name ) );
    }

    private static final char [] EMPTY_LIST_CHARS = {'[', ']'};

    public final void serializeCollection( Collection<?> collection, CharBuf builder )  {

        if ( collection.size () == 0 ) {
             builder.addChars ( EMPTY_LIST_CHARS );
             return;
        }

        builder.addChar( '[' );
        for ( Object o : collection ) {
            if (o == null) {
                builder.addNull();
            } else {
                serializeObject(o, builder);
            }
            builder.addChar ( ',' );

        }
        builder.removeLastChar ();
        builder.addChar( ']' );

    }

    @Override
    public void serializeSubtypeInstance( Object instance, CharBuf builder ) {

        level++;

        if (level > 100) {
            die("Detected circular dependency", builder.toString());
        }

        final Map<String, FieldAccess> fieldAccessors = getFields(instance.getClass ());
        final Collection<FieldAccess> values = fieldAccessors.values ();

        builder.addString( "{\"class\":" );
        builder.addQuoted ( instance.getClass ().getName () );

        int index = 0;
        int length = values.size();

        if ( length > 0 ) {
            builder.addChar( ',' );

            for ( FieldAccess fieldAccess : values ) {
                if (serializeField ( instance, fieldAccess, builder ) ) {
                    builder.addChar ( ',' );
                    index++;
                }
            }
            if ( index > 0 ) {
                builder.removeLastChar();
            }
            builder.addChar( '}' );

        }

        level--;
    }

}


text:
package com.github.frankfarrell.snowball.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

/**
 * Created by Frank on 14/02/2016.
 */

/**
 * Representation of a work order that is enqueued
 */
public class QueuedWorkOrder extends WorkOrder{

    private final Long positionInQueue;
    private final Long durationInQueue; //In seconds
    private final WorkOrderClass workOrderClass;

    private Double rank;

    public QueuedWorkOrder(long id, OffsetDateTime timeStamp, long durationInQueue, long positionInQueue, WorkOrderClass workOrderClass) {
        super(id, timeStamp);
        this.durationInQueue = durationInQueue;
        this.positionInQueue = positionInQueue;
        this.workOrderClass = workOrderClass;
    }

    public long getDurationInQueue() {
        return durationInQueue;
    }

    public long getPositionInQueue() {
        return positionInQueue;
    }

    public WorkOrderClass getWorkOrderClass() {
        return workOrderClass;
    }

    @JsonIgnore
    public Double getRank() {
        return rank;
    }

    public void setRank(Double rank) {
        this.rank = rank;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        QueuedWorkOrder that = (QueuedWorkOrder) o;

        if (!positionInQueue.equals(that.positionInQueue)) return false;
        if (!durationInQueue.equals(that.durationInQueue)) return false;
        return workOrderClass == that.workOrderClass;

    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + positionInQueue.hashCode();
        result = 31 * result + durationInQueue.hashCode();
        result = 31 * result + workOrderClass.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "QueuedWorkOrder{" +
                "id="+ getId() +
                "timeStamp+"+getTimeStamp().toString()+
                "positionInQueue=" + positionInQueue +
                ", durationInQueue=" + durationInQueue +
                ", workOrderClass=" + workOrderClass +
                ", rank=" + rank +
                '}';
    }
}


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package minipython.node;

public abstract class PMoreListArguments extends Node
{
}