text:
#include <stdio.h>
#include <time.h>

// sg3 utils
#include "sg_lib.h"
#include "sg_pt.h"

// ltfs
#include "libltfs/ltfs.h"
#include "libltfs/ltfs_internal.h"
#include "libltfs/config_file.h"
#include "libltfs/plugin.h"
#include "libltfs/tape.h"

#include "LTFS.h"
#include "SCSI.h"

// SCSI defines
#define DEFAULT_TIMEOUT 60
#define MIN_SCSI_CDBSZ 6
#define MAX_SCSI_CDBSZ 256
#define MAX_SCSI_DXLEN (64 * 1024)

// Debug defines
//#define DEBUG

// disable the following define to speedup tool
// simulation of bad blocks will not work in this case
#define SIMULATE_BAD_BLOCKS

#include "debug.h"

// global variables
unsigned long g_block_size = 0;
unsigned long bad_blocks = 0;
int g_stop_verification = 0;
struct bad_block *bad_blocks_head = NULL;
struct bad_block *bad_blocks_tail = NULL;

/*
 * Signal handler to gracefully terminate the application
 */
void sig_handler(int signo) {
	g_stop_verification = 1;
	log_info_f("Stopping verification process...\n");
}

/*
 * Add a bad block to the linked list
 * Returns 0 on success, -1 otherwise
 */
int add_bad_block(tape_block_t pos) {
	struct bad_block *block = malloc(sizeof(struct bad_block));
	if (!block) {
		log_err("Out of memory!\n");
		return -1;
	}
	// add block to linked list
	block->next = NULL;
	block->pos = pos;
	block->file_list = NULL;
	bad_blocks_tail->next = block;
	bad_blocks_tail = block;

	bad_blocks++;

	return 0;
}

/*
 * Print all bad blocks
 */
void dump_bad_blocks() {
	struct bad_block *ptr = bad_blocks_head;
	while (ptr) {
		struct bad_block *current = ptr;
		ptr = ptr->next;
		if (current->pos != -1) {
			log_info("Bad block %lu\n", current->pos);
		}
	}
	fflush(stderr);
}

/*
 * Free linked list of bad blocks and file names
 */
void delete_bad_block_list() {
	struct bad_block *ptr = bad_blocks_head;
	while (ptr) {
		struct bad_block *current = ptr;
		struct filename *file = current->file_list;
		ptr = ptr->next;
		while (file) {
			struct filename *current_file = file;
			file = file->next;
			free(current_file->file);
			free(current_file);
		}
		free(current);
	}
}

/*
 * Dump all *possibly* corrupted files
 * Files are written to stderr and to a file if file_name is given
 */
void dump_corrupt_files(char *file_name) {
	struct bad_block *ptr = bad_blocks_head;

	// try to open file if file name is given
	FILE *f = NULL;
	if (file_name) {
		f = fopen(file_name, "w");
	}

	// loop through linked list
	while (ptr) {
		struct bad_block *current = ptr;
		struct filename *file_list = current->file_list;
		ptr = ptr->next;
		while (file_list) {
			struct filename *current_file = file_list;
			file_list = file_list->next;
			log_info("Block %ld, file %s\n", current->pos, current_file->file);
			// write file names to log file
			if (f) {
				fprintf(f, "%s\n", current_file->file);
			}
		}
	}
	fflush(stderr);

	// cleanup
	if (f) {
		fclose(f);
	}
}

/*
 * Use VERIFY6 SCSI CDBs to check from current tape position
 * Verify will ignore ILI, FM and will terminate on EOD or EOP
 *
 * Set bad_block_simluation a value > 0 to simulate a bad block
 * each bad_block_simluation number of blocks
 *
 * Set quick_check to a value > 0 to enable a quick check that
 * ends at quick_check blocks
 */
int verify_data(char* devname, int bad_block_simluation, int quick_check) {
	int ret = 0, i;
	int sg_fd = -1, sense_length = 0, cdb_length = 0, scsi_status = 0;
	unsigned long blocks_verified = 0, mb_verified = 0;
	struct sg_pt_base *ptvp = NULL;
	unsigned char cdb[MAX_SCSI_CDBSZ];
	unsigned char sense_buffer[32];
	time_t start, end;
	char *p;
	struct sg_scsi_sense_hdr ssh;

	// try to open SCSI device
	sg_fd = scsi_pt_open_device(devname, 1, 0);
	if (sg_fd < 0) {
		log_err("Failed to open device %s: %s\n", devname,
				safe_strerror(-sg_fd));
		ret = SG_LIB_FILE_ERROR;
		goto done;
	}

	// create SCSI object
	ptvp = construct_scsi_pt_obj();
	if (!ptvp) {
		log_err("construct_scsi_pt_obj failed\n");
		ret = SG_LIB_CAT_OTHER;
		goto done;
	}

	start = time(NULL);
	memset(sense_buffer, 0, sizeof(sense_buffer));

	// create CDB with correct block size
	p = (char*) &g_block_size;
	cdb[0] = 0x13;
	cdb[1] = 0x00;
	cdb[2] = p[2];	// block size MSB
	cdb[3] = p[1];
	cdb[4] = p[0];	// block size LSB
	cdb[5] = 0x00;
	cdb_length = 6;

	log_info("VERIFY6 CDB: ");
	for (i = 0; i < cdb_length; i++) {
		fprintf(stderr, "%02x ", cdb[i]);
	}
	fprintf(stderr, "\n");
	fflush(stderr);

	// loop until EOD/EOP or error detected
	while (!g_stop_verification) {
#ifdef SIMULATE_BAD_BLOCKS
		if(bad_block_simluation > 0) {
			// simulate a bad block
			if ((blocks_verified % bad_block_simluation) == 0) {
				struct tc_position pos;
				int s = readPositionLong(sg_fd, ptvp, &pos);
				if (s) {
					log_err_f("Error getting block position\n");
					break;
				}
				if (add_bad_block(pos.block)) {
					break;
				}
			}
		}
		// stop verification if quick check is enabled
		if (quick_check > 0) {
			if (blocks_verified >= quick_check) {
				ret = 0;
				break;
			}
		}
#endif
		// execute SCSI command
		ret = executeSCSICommand(sg_fd, ptvp, cdb, cdb_length, DEFAULT_TIMEOUT,
				&scsi_status, sense_buffer, sizeof(sense_buffer),
				&sense_length);

		// check for any other SG errors
		if (ret == SG_LIB_CAT_OTHER) {
			dump_scsi_info(scsi_status, sense_buffer, sense_length);
			break;
		}

		// parse SCSI result (some scenarios, e.g. ILI, FM, EOD are expected to happen
		if (scsi_status == SAM_STAT_GOOD) {
			; // nothing to do
		} else if (scsi_status == SAM_STAT_CHECK_CONDITION) {
			// no sense information present?
			if (ret == SG_LIB_CAT_NO_SENSE || ret == SG_LIB_CAT_RECOVERED) {
				// ILI is OK
				if (sense_buffer[2] & 0x20) {
					log_debug("Detected ILI at block %lu\n",
							blocks_verified);
				}
				// FM is also OK
				else if (sense_buffer[2] & 0x80) {
					log_info_f("Detected FM at block %lu\n", blocks_verified);
				} else {
					dump_scsi_info(scsi_status, sense_buffer, sense_length);
					break;
				}
			} else if (ret == SG_LIB_CAT_MEDIUM_HARD) {
				// check for EOD
				if (sg_scsi_normalize_sense(sense_buffer, sense_length, &ssh)) {
					dump_scsi_info(scsi_status, sense_buffer, sense_length);
					// EOD is 0x00/0x05, EOP is 0x00/0x02
					if (ssh.asc == 0x00
							&& (ssh.ascq == 0x02 || ssh.ascq == 0x05)) {
						log_info_f("EOP/EOD detected!\n");
						ret = 0;
						break;
					} else {
						// all other errors are treated as bad blocks up to now
						struct tc_position pos;
						int s = readPositionLong(sg_fd, ptvp, &pos);
						if (s) {
							log_err_f("Error getting block position\n");
							break;
						}
						if (add_bad_block(pos.block)) {
							break;
						}
					}
				} else {
					// this should not happen
					log_err_f("sg_scsi_normalize_sense failed\n");
					dump_scsi_info(scsi_status, sense_buffer, sense_length);
					break;
				}
			} else {
				// no medium or hardware error
				dump_scsi_info(scsi_status, sense_buffer, sense_length);
				break;
			}

			// reset sense buffer to not trigger additional warnings
			memset(sense_buffer, 0, sizeof(sense_buffer));
		} else {
			// all other status info are handled here (except GOOD, CHECK_CONDITION)
			dump_scsi_info(scsi_status, sense_buffer, sense_length);
			break;
		}
		blocks_verified++;
	}
	// interrupted by signal?
	if (g_stop_verification) {
		log_info("Not all blocks have been verified!\n");
		ret = 0;
	}
	end = time(NULL);

	log_info("Blocks verified: %lu\n", blocks_verified);
	log_info("Duration: %d seconds\n", (int) (end - start));
	// assume each block is filled up to 65% with data
	mb_verified = (blocks_verified * g_block_size / 1048576ul * 65ul / 100ul );
	if (((int)end - (int)start) > 0) {
		log_info("Blocks per second: %lu\n", blocks_verified / (end -start));
	}
	log_info("Approximate MB verified: %lu\n", mb_verified);
	if (((int)end - (int)start) > 0) {
		log_info("Approximate speed: %.2f MB/s\n",
			(double) ((double) mb_verified / (double) (end - start)));
	}
	log_info_f("\n");

done:
	if (ptvp)
		destruct_scsi_pt_obj(ptvp);
	if (sg_fd >= 0)
		scsi_pt_close_device(sg_fd);

	return ret;
}

/*
 * Print usage
 */
void printUsage(char* s) {
	fprintf(stderr, "\nUsage: %s -f <path to tape drive> [ -s <path to sg device -b <bad blocks> -q <quick check> -l <path to log file>]\n\n", s);
	fprintf(stderr, "Example: %s -f /dev/nst0\n", s);
	fprintf(stderr, "Example: %s -f /dev/IBMtape0 -g /dev/sg8\n", s);
	fprintf(stderr, "Set -b 10000 to simulate a bad block every 10000 blocks\n");
	fprintf(stderr, "Set -q 100000 to end verification after the first 100000 blocks\n");
	fprintf(stderr, "Set -l /tmp/verify.log to write possibly corrupted files to /tmp/verify.log\n");
	fprintf(stderr, "The drive must be loaded with a tape\n");
	fprintf(stderr, "before running this tool!\n\n");
}

/*
 * Entry point
 */
int main(int argc, char* argv[]) {
	int ret = 0, i;
	struct bad_block *bad_block_list = NULL;
	time_t start, end;
	int bad_block_simluation = 0;
	int quick_check = 0;
	char *device_name = NULL;
	char *sg_name = NULL;
	char *log_file = NULL;

	// check arguments
	while ((i = getopt(argc, argv, "b:q:f:g:l:")) != -1) {
		switch (i) {
		case 'b':
			bad_block_simluation = strtol(optarg, NULL, 10);
			break;
		case 'f':
			device_name = optarg;
			break;
		case 'g':
			sg_name = optarg;
			break;
		case 'l':
			log_file = optarg;
			break;
		case 'q':
			quick_check = strtol(optarg, NULL, 10);
			break;
		case '?':
			if (optopt == 'q' || optopt == 'b' || optopt == 'f' || optopt == 'g' || optopt == 'l')
				fprintf(stderr, "Option -%c requires an argument.\n", optopt);
			else if (isprint(optopt))
				fprintf(stderr, "Unknown option `-%c'.\n", optopt);
			else
				fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
			printUsage(argv[0]);
			return -1;
		default:
			printUsage(argv[0]);
			return -1;
		}
	}

	// device name must be given
	if(!device_name) {
		printUsage(argv[0]);
		return -1;
	}

#ifndef SIMULATE_BAD_BLOCKS
	log_warn("*********************************\n");
	log_warn("Warning: Simulation of bad blocks\n");
	log_warn("is disabled by compile option!\n");
	log_warn_f("*********************************\n");
#endif

	// for informational purpose
	start = time(NULL);

	/* **********************************************************
	 * Use LTFS library functionality to get block size of tape *
	 ************************************************************/
	// get LTFS block size
	log_info_f("Getting block size of loaded cartridge...\n");
	ret = get_ltfs_blocksize(device_name, &g_block_size);
	if (ret) {
		log_err("Failed to mount LTFS volume!\n");
		return 1;
	}

	log_info_f("LTFS block size: %lu (0x%lx)\n", g_block_size,
			g_block_size);

	/* ******************************************
	 * Use VERIFY6 CDBs to check data partition *
	 ********************************************/
	// initialize list of bad blocks
	bad_block_list = malloc(sizeof(struct bad_block));
	if (!bad_block_list) {
		log_err("Out of memory!\n");
		return -1;
	}
	bad_block_list->next = NULL;
	bad_block_list->pos = -1;
	bad_blocks_head = bad_block_list;
	bad_blocks_tail = bad_block_list;

	/*
	 * Install signal handler to gracefully stop verification
	 * Signal handler has to be installed at this point because
	 * the LTFS library will install its own signal handlers and
	 * removes them again
	 */
	if (signal(SIGINT, sig_handler) == SIG_ERR) {
		log_err("Unable to register signal handler!\n");
	}

	// verify data partition
	log_info_f("Verifying data on tape using VERIFY6 commands...\n");
	if (sg_name != NULL)
		ret = verify_data(sg_name, bad_block_simluation, quick_check);
	else
		ret = verify_data(device_name, bad_block_simluation, quick_check);

	// do not do any additional steps if no bad blocks found
	if (bad_blocks) {
		// print all bad blocks
		dump_bad_blocks();

		// get file names from bad blocks
		log_info_f("Retrieving file names for bad blocks on tape...\n");
		get_ltfs_files(device_name, bad_block_list);

		// print all corrupt files
		dump_corrupt_files(log_file);
	} else {
		log_info_f("No bad blocks found on tape!\n");
	}

	// cleanup
	delete_bad_block_list();

	// for informational purpose
	end = time(NULL);

	log_info("Complete verification took %d seconds\n", (int) (end - start));

	return ret;
}


text:
package org.apache.olingo.client.core.uri;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.olingo.client.api.Configuration;
import org.apache.olingo.client.api.uri.QueryOption;
import org.apache.olingo.client.api.uri.SegmentType;
import org.apache.olingo.client.api.uri.URIBuilder;
import org.apache.olingo.client.api.uri.URIFilter;
import org.apache.olingo.client.api.uri.URISearch;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.core.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class URIBuilderImpl implements URIBuilder {

  /**
   * Constructor.
   *
   * @param serviceRoot absolute URL (schema, host and port included) representing the location of the root of the data
   * service.
   */
  public URIBuilderImpl(final Configuration configuration, final String serviceRoot) {
    this.configuration = configuration;

    segments.add(new Segment(SegmentType.SERVICEROOT, serviceRoot));
  }

  protected static class Segment {

    private final SegmentType type;

    private final String value;

    public Segment(final SegmentType type, final String value) {
      this.type = type;
      this.value = value;
    }

    public SegmentType getType() {
      return type;
    }

    public String getValue() {
      return value;
    }
  }

  /**
   * Logger.
   */
  protected static final Logger LOG = LoggerFactory.getLogger(URIBuilderImpl.class);

  private final Configuration configuration;

  protected final List<Segment> segments = new ArrayList<Segment>();

  /**
   * Insertion-order map of query options.
   */
  protected final Map<String, String> queryOptions = new LinkedHashMap<String, String>();

  /**
   * Insertion-order map of parameter aliases.
   */
  protected final Map<String, String> parameters = new LinkedHashMap<String, String>();

  @Override
  public URIBuilder addQueryOption(final QueryOption option, final String value) {
    return addQueryOption(option.toString(), value, false);
  }

  @Override
  public URIBuilder replaceQueryOption(final QueryOption option, final String value) {
    return addQueryOption(option.toString(), value, true);
  }

  @Override
  public URIBuilder addQueryOption(final String option, final String value, final boolean replace) {
    final StringBuilder builder = new StringBuilder();
    if (!replace && queryOptions.containsKey(option)) {
      builder.append(queryOptions.get(option)).append(',');
    }
    builder.append(value);
    queryOptions.put(option, builder.toString());
    return this;
  }

  @Override
  public URIBuilder addParameterAlias(final String alias, final String exp) {
    parameters.put(alias, exp);
    return this;
  }

  @Override
  public URIBuilder appendEntitySetSegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.ENTITYSET, segmentValue));
    return this;
  }

  @Override
  public URIBuilder appendKeySegment(final Object val) {
    final String segValue = URIUtils.escape(val);

    segments.add(configuration.isKeyAsSegment()
        ? new Segment(SegmentType.KEY_AS_SEGMENT, segValue)
        : new Segment(SegmentType.KEY, "(" + segValue + ")"));

    return this;
  }

  @Override
  public URIBuilder appendKeySegment(final Map<String, Object> segmentValues) {
    if (!configuration.isKeyAsSegment()) {
      final String key = buildMultiKeySegment(segmentValues, true, ',');
      if (StringUtils.isEmpty(key)) {
        segments.add(new Segment(SegmentType.KEY, noKeysWrapper()));
      } else {
        segments.add(new Segment(SegmentType.KEY, key));
      }
    }

    return this;
  }

  @Override
  public URIBuilder appendPropertySegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.PROPERTY, segmentValue));
    return this;

  }

  @Override
  public URIBuilder appendNavigationSegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.NAVIGATION, segmentValue));
    return this;
  }

  @Override
  public URIBuilder appendDerivedEntityTypeSegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.DERIVED_ENTITY_TYPE, segmentValue));
    return this;
  }

  @Override
  public URIBuilder appendValueSegment() {
    segments.add(new Segment(SegmentType.VALUE, SegmentType.VALUE.getValue()));
    return this;
  }

  @Override
  public URIBuilder appendCountSegment() {
    segments.add(new Segment(SegmentType.COUNT, SegmentType.COUNT.getValue()));
    return this;
  }

  @Override
  public URIBuilder appendActionCallSegment(final String action) {
    segments.add(new Segment(
        segments.size() == 1 ? SegmentType.UNBOUND_ACTION : SegmentType.BOUND_ACTION, action));
    return this;
  }

  @Override
  public URIBuilder appendOperationCallSegment(final String operation) {
    segments.add(new Segment(
        segments.size() == 1 ? SegmentType.UNBOUND_OPERATION : SegmentType.BOUND_OPERATION, operation));
    return this;
  }

  @Override
  public URIBuilder appendMetadataSegment() {
    segments.add(new Segment(SegmentType.METADATA, SegmentType.METADATA.getValue()));
    return this;
  }

  @Override
  public URIBuilder appendBatchSegment() {
    segments.add(new Segment(SegmentType.BATCH, SegmentType.BATCH.getValue()));
    return this;
  }

  @Override
  public URIBuilder count() {
    segments.add(new Segment(SegmentType.ROOT_QUERY_OPTION, "$" + QueryOption.COUNT.toString()));
    return this;
  }

  @Override
  public URIBuilder expand(final String... expandItems) {
    return addQueryOption(QueryOption.EXPAND, StringUtils.join(expandItems, ","));
  }

  @Override
  public URIBuilder format(final String format) {
    return replaceQueryOption(QueryOption.FORMAT, format);
  }

  @Override
  public URIBuilder filter(final URIFilter filter) {
    URIBuilder result;
    try {
      // decode in order to support @ in parameter aliases
      result = filter(URLDecoder.decode(filter.build(), Constants.UTF8));
    } catch (UnsupportedEncodingException e) {
      result = filter(filter.build());
    }
    return result;
  }

  @Override
  public URIBuilder filter(final String filter) {
    return replaceQueryOption(QueryOption.FILTER, filter);
  }

  @Override
  public URIBuilder select(final String... selectItems) {
    return addQueryOption(QueryOption.SELECT, StringUtils.join(selectItems, ","));
  }

  @Override
  public URIBuilder orderBy(final String order) {
    return replaceQueryOption(QueryOption.ORDERBY, order);
  }

  @Override
  public URIBuilder top(final int top) {
    return replaceQueryOption(QueryOption.TOP, String.valueOf(top));
  }

  @Override
  public URIBuilder skip(final int skip) {
    return replaceQueryOption(QueryOption.SKIP, String.valueOf(skip));
  }

  @Override
  public URIBuilder skipToken(final String skipToken) {
    return replaceQueryOption(QueryOption.SKIPTOKEN, skipToken);
  }

  @Override
  public URI build() {
    final StringBuilder segmentsBuilder = new StringBuilder();

    for (Segment seg : segments) {
      if (segmentsBuilder.length() > 0 && seg.getType() != SegmentType.KEY) {
        switch (seg.getType()) {
        case BOUND_OPERATION:
          segmentsBuilder.append(getBoundOperationSeparator());
          break;
        case BOUND_ACTION:
          segmentsBuilder.append(getBoundOperationSeparator());
          break;
        default:
          if (segmentsBuilder.length() > 0 && segmentsBuilder.charAt(segmentsBuilder.length() - 1) != '/') {
            segmentsBuilder.append('/');
          }
        }
      }

      if (seg.getType() == SegmentType.ENTITY) {
        segmentsBuilder.append(seg.getType().getValue());
      } else {
        segmentsBuilder.append(seg.getValue());
      }
      if (seg.getType() == SegmentType.BOUND_OPERATION || seg.getType() == SegmentType.UNBOUND_OPERATION) {
        segmentsBuilder.append(getOperationInvokeMarker());
      }
    }

    try {
      if ((queryOptions.size() + parameters.size()) > 0) {
        segmentsBuilder.append("?");
        List<NameValuePair> list1 = new LinkedList<NameValuePair>();
        for (Map.Entry<String, String> option : queryOptions.entrySet()) {
          list1.add(new BasicNameValuePair("$" + option.getKey(), option.getValue()));
        }
        for (Map.Entry<String, String> parameter : parameters.entrySet()) {
          list1.add(new BasicNameValuePair("@" + parameter.getKey(), parameter.getValue()));
        }

        // don't use UriBuilder.build():
        // it will try to call URLEncodedUtils.format(Iterable<>,Charset) method,
        // which works in desktop java application, however, throws NoSuchMethodError in android OS,
        // so here manually construct the URL by its overload URLEncodedUtils.format(List<>,String).
        final String queryStr = encodeQueryParameter(list1);
        segmentsBuilder.append(queryStr);
      }

      return URI.create(segmentsBuilder.toString());
    } catch (IllegalArgumentException e) {
      throw new IllegalArgumentException("Could not build valid URI", e);
    }
  }

  private String encodeQueryParameter(List<NameValuePair> list) {
    final StringBuilder builder = new StringBuilder();

    for (NameValuePair pair : list) {
      if (builder.length() > 0) {
        builder.append("&");
      }

      builder.append(Encoder.encode(pair.getName()));
      builder.append("=");
      builder.append(Encoder.encode(pair.getValue()));
    }

    return builder.toString();
  }

  @Override
  public String toString() {
    return build().toASCIIString();
  }

  protected String buildMultiKeySegment(final Map<String, Object> segmentValues, final boolean escape,
      final char sperator) {
    if (segmentValues == null || segmentValues.isEmpty()) {
      return StringUtils.EMPTY;
    } else {
      final StringBuilder keyBuilder = new StringBuilder().append('(');
      for (Map.Entry<String, Object> entry : segmentValues.entrySet()) {
        keyBuilder.append(entry.getKey()).append('=').append(
            escape ? URIUtils.escape(entry.getValue()) : entry.getValue());
        keyBuilder.append(sperator);
      }
      keyBuilder.deleteCharAt(keyBuilder.length() - 1).append(')');

      return keyBuilder.toString();
    }
  }

  @Override
  public URIBuilder appendKeySegment(final EdmEnumType enumType, final String memberName) {
    return appendKeySegment(enumType.toUriLiteral(memberName));
  }

  @Override
  public URIBuilder appendKeySegment(final Map<String, Pair<EdmEnumType, String>> enumValues,
      final Map<String, Object> segmentValues) {

    final Map<String, Object> values = new LinkedHashMap<String, Object>();
    for (Map.Entry<String, Pair<EdmEnumType, String>> entry : enumValues.entrySet()) {
      values.put(entry.getKey(), entry.getValue().getKey().toUriLiteral(entry.getValue().getValue()));
    }
    values.putAll(segmentValues);

    return appendKeySegment(values);
  }

  protected String noKeysWrapper() {
    return "()";
  }

  protected char getBoundOperationSeparator() {
    return '/';
  }

  protected String getOperationInvokeMarker() {
    return "()";
  }

  @Override
  public URIBuilder appendSingletonSegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.SINGLETON, segmentValue));
    return this;
  }

  @Override
  public URIBuilder appendEntityIdSegment(final String segmentValue) {
    segments.add(new Segment(SegmentType.ENTITY, null));
    return addQueryOption(QueryOption.ID, segmentValue);
  }

  @Override
  public URIBuilder appendRefSegment() {
    segments.add(new Segment(SegmentType.REF, SegmentType.REF.getValue()));
    return this;
  }

  @Override
  public URIBuilder appendCrossjoinSegment(final String... segmentValues) {
    final StringBuilder segValue = new StringBuilder(SegmentType.CROSS_JOIN.getValue()).
        append('(').append(StringUtils.join(segmentValues, ",")).append(')');
    segments.add(new Segment(SegmentType.CROSS_JOIN, segValue.toString()));
    return this;
  }

  @Override
  public URIBuilder appendAllSegment() {
    segments.add(new Segment(SegmentType.ALL, SegmentType.ALL.getValue()));
    return this;
  }

  @Override
  public URIBuilder id(final String idValue) {
    return addQueryOption(QueryOption.ID, idValue);
  }

  @Override
  public URIBuilder search(final URISearch search) {
    return search(search.build());
  }

  @Override
  public URIBuilder search(final String expression) {
    return addQueryOption(QueryOption.SEARCH, expression);
  }

  @Override
  public URIBuilder count(final boolean value) {
    return addQueryOption(QueryOption.COUNT, Boolean.toString(value));
  }

  @Override
  public URIBuilder expandWithOptions(final String expandItem, final Map<QueryOption, Object> options) {
    return expandWithOptions(expandItem, false, false, options);
  }

  @Override
  public URIBuilder expandWithOptions(String expandItem, boolean pathRef,
      boolean pathCount, Map<QueryOption, Object> options) {
    final Map<String, Object> _options = new LinkedHashMap<String, Object>();
    for (Map.Entry<QueryOption, Object> entry : options.entrySet()) {
      _options.put("$" + entry.getKey().toString(), entry.getValue());
    }
    String path = pathRef?"/$ref":pathCount?"/$count":StringUtils.EMPTY;
    return expand(expandItem + buildMultiKeySegment(_options, false, ';')+path);
  }

  @Override
  public URIBuilder expandWithSelect(final String expandItem, final String... selectItems) {
    return expand(expandItem + "($select=" + StringUtils.join(selectItems, ",") + ")");
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Top-Level API | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Top-Level API | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/docs/top-level-api-ja-JP.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://facebook.github.io/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

          React

Docs

Support

Download

Blog

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Quick Start

            Getting Started

            Tutorial

            Thinking in React

Community Resources

            Conferences

            Videos

            Complementary Tools

            Examples

Guides

            Why React?

            Displaying Data

                    JSX in Depth

                    JSX Spread Attributes

                    JSX Gotchas

            Interactivity and Dynamic UIs

            Multiple Components

            Reusable Components

            Transferring Props

            Forms

            Working With the Browser

                    Refs to Components

            Tooling Integration

                    Language Tooling

                    Package Management

                    Server-side Environments

            Add-Ons

                    Animation

                    Two-Way Binding Helpers

                    Test Utilities

                    Cloning Elements

                    Keyed Fragments

                    Immutability Helpers

                    PureRenderMixin

                    Performance Tools

                    Shallow Compare

            Advanced Performance

            Context

Reference

            Top-Level API

            Component API

            Component Specs and Lifecycle

            Supported Tags and Attributes

            Event System

            DOM Differences

            Special Non-DOM Attributes

            Reconciliation

            Web Components

            React (Virtual) DOM Terminology

Tips

            Introduction

            Inline Styles

            If-Else in JSX

            Self-Closing Tag

            Maximum Number of JSX Root Nodes

            Shorthand for Specifying Pixel Values in style props

            Type of the Children props

            Value of null for Controlled Input

            componentWillReceiveProps Not Triggered After Mounting

            Props in getInitialState Is an Anti-Pattern

            DOM Event Listeners in a Component

            Load Initial Data via AJAX

            False in JSX

            Communicate Between Components

            Expose Component Functions

            this.props.children undefined

            Use React with Other Libraries

            Dangerously Set innerHTML

Contributing

            Design Principles

    Edit on GitHub

      Top-Level API

React #

React はReactのライブラリに対するエントリーポイントです。事前にビルドされたパッケージを使用する場合は、グローバルで使用可能です。CommonJSのモジュールを使用する場合は、 require() できます。

React.Component #

class Component

これは、ES6のクラスを使用して定義されている場合の、Reactコンポーネントに対する基底クラスです。ReactでES6のクラスを使用する方法については、再利用可能なコンポーネントをご覧ください。基底クラスからどのメソッドが実際に提供されるかについては、コンポーネントAPIをご覧ください。

React.createClass #

ReactClass createClass(object specification)

与えられた仕様に基づいてコンポーネントクラスを作成します。コンポーネントは ある単一の 子要素を返す render メソッドを実行します。その子要素は勝手に深い子要素の構造を保持しています。コンポーネントが標準的なプロトタイプのクラスと異なっている部分は、newを呼ぶ必要がないということです。それらは内部で(newを行う)インスタンスを構築する便利なラッパーです。

specificationオブジェクトについての情報は、コンポーネントのスペックとライフサイクルをご覧ください。

React.createElement #

ReactElement createElement(
  string/ReactClass type,
  [object props],
  [children ...]
)

与えられた型の ReactElement を作成し、返します。type引数はhtmlタグ名(例えば、'div'、'span'など)の文字列にもReactClass(React.createClass によって作成される)にもなり得ます。

React.cloneElement #

ReactElement cloneElement(
  ReactElement element,
  [object props],
  [children ...]
)

element をスターティングポイントとして使用する新しい ReactElement をクローンして返します。
結果として生まれる要素はオリジナルの要素のpropsと新しいpropsを暗にマージしたものを保持しています。新しい子要素は現存する子要素を置き換えます。 React.addons.cloneWithProps と異なり、オリジナルの要素から得られた key と ref は保存されます。(cloneWithProps とは異なり)propsをマージする際に特別な動きは行いません。詳細については、v0.13 RC2 blog記事をご覧ください。

React.createFactory #

factoryFunction createFactory(
  string/ReactClass type
)

与えられた型のReactElementsを生成する関数を返します。 React.createElement と同様に、type引数はhtmlタグ名(例えば、'div'、'span'など)の文字列にもReactClass にもなり得ます。

React.render #

ReactComponent render(
  ReactElement element,
  DOMElement container,
  [function callback]
)

与えられた container によってReactElementをDOMにレンダリングし、コンポーネントへの参照を返します。

もしReactElementが事前に container にレンダリングされていた場合は、更新を行い、DOMが最新のReactのコンポーネントを表すように変化させます。

オプションのコールバックが与えられた場合は、コンポーネントがレンダリングされたり、更新された後に実行されます。

注意:
React.render() は渡されたコンテナーノードの内容を制御します。内部に存在するDOM要素は最初に呼ばれた際に置き換えられます。その後に呼ばれた場合は、ReactのDOMの差分アルゴリズムを使用して、効率的に更新されます。

React.render() はコンテナーノードの変更は行いません(コンテナの子要素のみ変更を行います)。今後、存在する子要素を上書きすることなく、存在するDOMノードにコンポーネントを挿入することが可能になるでしょう。

React.unmountComponentAtNode #

boolean unmountComponentAtNode(DOMElement container)

マウントされたReactのコンポーネントをDOMから削除し、そのイベントハンドラとstateをクリーンアップします。コンテナにコンポーネントがマウントされていない場合は、この関数を呼んでも何も行われません。コンポーネントがアンマウントされた場合は true を返し、アンマウントするコンポーネントが存在しない場合は false を返します。

React.renderToString #

string renderToString(ReactElement element)

ReactElementを最初にHTMLにレンダリングします。これはサーバでのみ使用されるべきです。ReactはHTML文字列を返します。このメソッドを、サーバでHTMLを生成し、最初のリクエストに対してマークアップを送るのに使用することができます。そうすることで、ページロードが速くなり、サーチエンジンはSEOの目的でページをクロールします。

既にサーバでレンダリングされたマークアップを保持しているノードで React.render() を呼んだ場合は、Reactはそれを保護し、イベントハンドラを加えます。そうすることで、最初のローディングのパフォーマンスがとても良くなります。

React.renderToStaticMarkup #

string renderToStaticMarkup(ReactElement element)

renderToString に似ていますが、Reactが内部で使用する data-react-id のような外部のDOM属性を作成しません。Reactを、単純な静的なページを生成するために使用したい場合は有用です。外部の属性を取り除くことでメモリを節約することができます。

React.isValidElement #

boolean isValidElement(* object)

オブジェクトがReactElementであるかどうか調査します。

React.findDOMNode #

DOMElement findDOMNode(ReactComponent component)

このコンポーネントがDOMにマウントされた場合は、対応するネイティブブラウザのDOM要素を返します。このメソッドはDOMの外の値を読み込む場合に有用です。例えば、formフィールドの値やDOMの測定を行う場合があります。 render が null や false を返した場合は、 findDOMNode は null を返します。

React.DOM #

React.DOM はDOMコンポーネントのための React.createElement の周りの便利なラッパーを提供します。JSXを使用しない場合にのみ使用すべきです。例えば、 React.DOM.div(null, 'Hello World!') のように。

React.PropTypes #

React.PropTypes はコンポーネントに与えられたpropsをバリデーションするためにコンポーネントの propTypes と使用できる型を含んでいます。 propTypes についての更なる情報は、再利用可能なコンポーネントをご覧ください。

React.Children #

React.Children は this.props.children の不透明なデータ構造を扱うユーティリティを提供します。

React.Children.map #

object React.Children.map(object children, function fn [, object thisArg])

全ての children を含む子要素に対して、 fn を実行します。 this は thisArg にセットされます。 children がネストしたオブジェクトや配列だった場合は、実行されません。 fn はコンテナのオブジェクトから渡されません。子要素が null か undefined だった場合は、空のオブジェクトではなく null か undefined を返します。

React.Children.forEach #

React.Children.forEach(object children, function fn [, object thisArg])

React.Children.map() に似ていますが、オブジェクトを返しはしません。

React.Children.count #

number React.Children.count(object children)

children の中のコンポーネントの合計数を返します。 map や forEach に渡されるコールバックが実行される数と等しくなります。

React.Children.only #

object React.Children.only(object children)

children の単一の子要素を返します。それ以外の場合は例外をスローします。

        Next →

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.


text:
<?php

$dbh = mysql_connect('sql.mit.edu', 'landa', 'redacted');
if (!$dbh)
   die('Could not connect: ' . mysql_error() . '<br />');

mysql_select_db("landa+feedback") or die("No database selected.");

?>


text:
/*
* Class Name: Constantes
* Name:       Daniel Arevalo
* Date:       25/03/2016
* Version:    1.0
 */
package co.edu.uniandes.ecos.tarea6.util;

/**
 * Clase utilitaria de constantes
 *
 * @author Daniel
 */
public class Constantes {

    public static final Double NUMBER_OF_SEGMENTS = 10D;
    public static final Double ERROR = 0.00001;
}


text:
#import "UIKey+UIPrivate.h"
#import <AppKit/NSEvent.h>

@implementation UIKey
@synthesize keyCode=_keyCode, characters=_characters, charactersWithModifiers=_charactersWithModifiers, repeat=_repeat;

- (id)initWithNSEvent:(NSEvent *)event
{
    if ((self=[super init])) {
        _keyCode = [event keyCode];
        _characters = [[event charactersIgnoringModifiers] copy];
        _charactersWithModifiers = [[event characters] copy];
        _repeat = [event isARepeat];
        _modifierFlags = [event modifierFlags];
    }
    return self;
}

- (void)dealloc
{
    [_characters release];
    [_charactersWithModifiers release];
    [super dealloc];
}

- (UIKeyType)type
{
    if ([_characters length] > 0) {
        switch ([_characters characterAtIndex:0]) {
            case NSUpArrowFunctionKey:			return UIKeyTypeUpArrow;
            case NSDownArrowFunctionKey:		return UIKeyTypeDownArrow;
            case NSLeftArrowFunctionKey:		return UIKeyTypeLeftArrow;
            case NSRightArrowFunctionKey:		return UIKeyTypeRightArrow;
            case NSEndFunctionKey:				return UIKeyTypeEnd;
            case NSPageUpFunctionKey:			return UIKeyTypePageUp;
            case NSPageDownFunctionKey:			return UIKeyTypePageDown;
            case NSDeleteFunctionKey:			return UIKeyTypeDelete;
            case NSInsertFunctionKey:			return UIKeyTypeInsert;
            case NSHomeFunctionKey:				return UIKeyTypeHome;
            case 0x000D:						return UIKeyTypeReturn;
            case 0x0003:						return UIKeyTypeEnter;
        }
    }

    return UIKeyTypeCharacter;
}

- (BOOL)isCapslockEnabled
{
    return (_modifierFlags & NSAlphaShiftKeyMask) == NSAlphaShiftKeyMask;
}

- (BOOL)isShiftKeyPressed
{
    return (_modifierFlags & NSShiftKeyMask) == NSShiftKeyMask;
}

- (BOOL)isControlKeyPressed
{
    return (_modifierFlags & NSControlKeyMask) == NSControlKeyMask;
}

- (BOOL)isOptionKeyPressed
{
    return (_modifierFlags & NSAlternateKeyMask) == NSAlternateKeyMask;
}

- (BOOL)isCommandKeyPressed
{
    return (_modifierFlags & NSCommandKeyMask) == NSCommandKeyMask;
}

@end


text:
'use strict';

describe('Directives: whatsNew', function () {

  require('./whatsNew.directive.html');

  beforeEach(
    window.module(
      require('./whatsNew.directive'),
      require('angular-ui-bootstrap')
    )
  );

  beforeEach(window.inject(function ($rootScope, $compile, whatsNewReader, viewStateCache, $q, $filter, $uibModal) {
    this.scope = $rootScope.$new();
    this.compile = $compile;
    this.whatsNewReader = whatsNewReader;
    this.viewStateCache = viewStateCache;
    this.$filter = $filter;
    this.$q = $q;
    this.$uibModal = $uibModal;
  }));

  function createWhatsNew(compile, scope) {
    var domNode;

    domNode = compile('<whats-new></whats-new>')(scope);
    scope.$digest();

    // ng-if creates a sibling if used on the root element in the directive
    // so grab the sibling with .next()
    return domNode.next();
  }

  function hasUnread(domNode) {
    return domNode.find('a.unread').size() === 1;
  }

  describe('with content', function() {

    beforeEach(function() {
      var lastUpdated = new Date().getTime();
      var expectedDate = this.$filter('timestamp')(lastUpdated);

      spyOn(this.whatsNewReader, 'getWhatsNewContents').and.returnValue(this.$q.when({
        contents: 'stuff',
        lastUpdated: lastUpdated,
      }));

      this.lastUpdated = lastUpdated;
      this.expectedDate = expectedDate;
    });

    it('should show updated label when view state has not been cached', function() {
      var domNode;

      domNode = createWhatsNew(this.compile, this.scope);

      expect(hasUnread(domNode)).toBe(true);
    });

    it('should show updated label when view state has different lastUpdated value than file', function() {
      var domNode;

      this.viewStateCache.whatsNew = {
        get: function() {
          return {
            updateLastViewed: 'something else',
          };
        }
      };

      domNode = createWhatsNew(this.compile, this.scope);

      expect(hasUnread(domNode)).toBe(true);
    });

    it('should NOT show updated label when view state has same lastUpdated value as file', function() {
      var lastUpdated, domNode;

      lastUpdated = this.lastUpdated;
      this.viewStateCache.whatsNew = {
        get: function() {
          return {
            updateLastViewed: lastUpdated,
          };
        }
      };

      domNode = createWhatsNew(this.compile, this.scope);

      expect(hasUnread(domNode)).toBe(false);
    });

    it('should open modal when clicked, update and cache view state, then hide timestamp label', function() {
      var writtenToCache, domNode;

      writtenToCache = null;
      this.viewStateCache.whatsNew = {
        get: function() {
          return {
            updateLastViewed: null,
          };
        },
        put: function(id, val) {
          writtenToCache = val;
        }
      };
      spyOn(this.$uibModal, 'open').and.returnValue({});

      domNode = createWhatsNew(this.compile, this.scope);

      expect(hasUnread(domNode)).toBe(true);
      domNode.find('a').click();
      this.scope.$digest();

      expect(this.$uibModal.open).toHaveBeenCalled();
      expect(writtenToCache).not.toBeNull();
      expect(writtenToCache.updateLastViewed).toBe(this.lastUpdated);

      this.scope.$digest();
      expect(hasUnread(domNode)).toBe(false);
    });
  });

  describe('no content', function() {
    it('should not render the <ul>', function() {
      var domNode;

      spyOn(this.whatsNewReader, 'getWhatsNewContents').and.returnValue(this.$q.when(null));

      domNode = createWhatsNew(this.compile, this.scope);

      expect(domNode.find('ul').size()).toBe(0);
    });

  });

});


text:
struct bmd_animation {
  uint16_t num_frames;
  bool offset;
  struct vec3f *offsets;
};

struct bmd_bone {
  bool empty;
  char name[32];
  int16_t parent;
  struct mat4f *transformations;
  struct vec3f *translations;
  struct vec3f *rotations;
};

struct bmd_position {
  uint32_t bone;
  struct vec3f position;
};

struct bmd_normal {
  uint32_t bone;
  struct vec3f normal;
  uint32_t unk0;
};

struct bmd_triangle {
  uint16_t unk0;
  uint16_t positions[3];
  uint16_t unk1;
  uint16_t normals[3];
  uint16_t unk2;
  uint16_t texture_coords[3];
  uint16_t unk3[20];
};

struct bmd_object {
  uint16_t num_positions;
  uint16_t num_normals;
  uint16_t num_texture_coords;
  uint16_t num_triangles;
  uint16_t id;
  char texture[32];
  struct bmd_position *positions;
  struct bmd_normal *normals;
  struct vec2f *texture_coords;
  struct bmd_triangle *triangles;
};

struct bmd_mesh {
  char filename[32];
  uint16_t num_objects;
  uint16_t num_bones;
  uint16_t num_animations;
  struct bmd_object *objects;
  struct bmd_animation *animations;
  struct bmd_bone *bones;
};

struct bmd_entity {
  struct bmd_mesh mesh;
  struct texture *textures;
  struct renderable *renderables;
};

bool bmd_mesh_load(struct bmd_mesh *mesh, const char *path);
void bmd_mesh_delete(struct bmd_mesh *mesh);
bool bmd_load(struct bmd_entity *entity, const char *mesh_path, const char *texture_folder);
void bmd_delete(struct bmd_entity *entity);
bool bmd_render(struct bmd_entity *entity, struct shader *shader, struct camera *camera, struct transformation *transformation, struct buffer *lights);

#endif


text:
package com.hackbridge.viral;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExactRandomEdgeSelector extends EdgeSelector {

    private boolean DEBUG = false;

    private List<ArrayList<Double>> state; // 2D state array, modify only through setArrayDistance
    private List<Double> distanceSums;  // Internal calculation: sum of a row of stat0e
    private double distanceTotal = 0;  // Total distances (= 2 * value of all bidirectional edges)
    private Map<Long, Integer> nodeToMatrixPos;  // Map from node ID to row index in state matrix
    private int nodeCtr = 0;  // Counts the number of nodes: equivalent to the next available row index in the state matrix
    private int arrayCapacity = 512;

    public ExactRandomEdgeSelector(Map<Long, Node> nodes, NetworkParameters parameters) {
        super(nodes, parameters);
        state = new ArrayList<ArrayList<Double>>();
        nodeToMatrixPos = new HashMap<Long, Integer>();
        distanceSums = new ArrayList<Double>();
        for (int i = 0; i < arrayCapacity; ++i) {
            ArrayList<Double> new_array = new ArrayList<Double>();
            distanceSums.add(0.0);
            for (int j = 0; j < arrayCapacity; ++j) {
                new_array.add(0.0);
            }
            state.add(new_array);
        }
    }

    @Override
    public void addNode(Node node) {
        nodeToMatrixPos.put(node.getID(), nodeCtr);
        posToNode.put(nodeCtr, node);

        if (nodeCtr >= arrayCapacity) {
            increaseStateArrayCapacity();
        }

        nodeCtr++;
    }

    /**
     * Recompute the distances from the node's neighbouring nodes.
     *
     * @param nodeID
     */
    @Override
    public void updateDistances(long nodeID) {
        Node thisNode = nodes.get(nodeID);
        if (thisNode == null) {
            Logger.logError(3, "Failed to recompute distances. Node id " + nodeID + " does not " +
                    "exist.");
            return;
        }

        int matrixPos = nodeToMatrixPos.get(nodeID);

        for (int i = 0; i < nodeCtr; ++i) {
            if (i == matrixPos) {
                continue;
            }
            Node node = posToNode.get(i);
            if (!node.isActive()) {
                continue;
            }
            double distance =
                    parameters.getExponentialMultiplier() * Math.exp(
                            -parameters.getLambdaFactor() * thisNode.getDistanceFrom(node));

            /*
            debugPrint("Actual distance: " + thisNode.getDistanceFrom(node) + ", Exponentiated: " +
                    distance);
            */
            setArrayDistance(matrixPos, i, distance);
        }

        if (DEBUG) {
            outputArray();
        }
    }

    @Override
    public void reset() {
        arrayCapacity = 512;
        state.clear();
        distanceSums.clear();
        distanceTotal = 0;

        for (int i = 0; i < arrayCapacity; ++i) {
            ArrayList<Double> newRow = new ArrayList<Double>();
            distanceSums.add(0.0);
            for (int j = 0; j < arrayCapacity; ++j) {
                newRow.add(0.0);
            }
            state.add(newRow);
        }
    }

    /**
     * Selects an edge at random with probability directly and exactly
     * proportional to its distance.
     *
     * @return
     */
    public Edge selectRandomEdge() {
        if (distanceTotal <= 0 || nodeCtr <= 0) {
            return null;
        }

        // Pick an edge based on a random number and the accumulative normalized edge distances.
        double rand = Math.random();

        // Tracks the accumulate distance at the current row/column in the state matrix.
        double totalDistSoFar = 0.0;
        int i = 0, j = 0;

        // Add row distances.
        while (totalDistSoFar + distanceSums.get(i) <= rand * distanceTotal && i < nodeCtr) {
            totalDistSoFar += distanceSums.get(i);
            i++;
        }

        // Look at column distances.
        while (totalDistSoFar + state.get(i).get(j) <= rand * distanceTotal && j < nodeCtr) {
            totalDistSoFar += state.get(i).get(j);
            j++;
        }

        if (DEBUG) {
            System.out.format("Ack edge. Rand: %.5f total: %.5f Nodes: %d %d\n",
                    rand * distanceTotal, totalDistSoFar, i, j);
            outputNodes();
            System.out.format("Edge %d <-> %d activated.\n", i, j);
        }

        if (i == j) {
            return null;
        }

        Node ni = posToNode.get(i);
        Node nj = posToNode.get(j);

        if (ni == null || nj == null) {
            Logger.logError(3, "Tried to active null nodes " + i + " " + j);
            return null;
        }
        return new Edge(ni, nj);
    }

    public Map<Long, Integer> getNodeToMatrixPos() {
        return nodeToMatrixPos;
    }

    public List<ArrayList<Double>> getState() {
        return state;
    }

    private void increaseStateArrayCapacity() {
        int new_capacity = arrayCapacity * 2;
        for (int i = 0; i < arrayCapacity; ++i) {
            for (int j = arrayCapacity; j < new_capacity; ++j) {
                state.get(i).add(0.0);
            }
        }

        for (int i = arrayCapacity; i < new_capacity; ++i) {
            ArrayList<Double> new_array = new ArrayList<Double>();
            distanceSums.add(0.0);
            for (int j = 0; j < new_capacity; ++j) {
                new_array.add(0.0);
            }
            state.add(new_array);
        }
        arrayCapacity = new_capacity;
    }

    /**
     * Sets the distance between nodes i and j to dist. Note that i and j refer to internal
     * indices of the state matrix and do not necessarily correspond to the node's identifiers.
     * <p>
     * The state matrix should only be modified through this method.
     *
     * @param i
     * @param j
     * @param dist
     */
    private void setArrayDistance(int i, int j, double dist) {
        try {
            distanceSums.set(i, distanceSums.get(i) + dist - state.get(i).get(j));
            distanceTotal += dist - state.get(i).get(j);
            state.get(i).set(j, dist);

            distanceSums.set(j, distanceSums.get(j) + dist - state.get(j).get(i));
            distanceTotal += dist - state.get(j).get(i);
            state.get(j).set(i, dist);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }

    /**
     * Output the current distance array, including inactive nodes.
     */
    private void outputArray() {
        Logger.log(3, "===============\nOutputting current stage");
        for (int i = 0; i < nodeCtr; ++i) {
            String line = "";
            for (int j = 0; j < nodeCtr; ++j) {
                line += String.format("%.5f\t", state.get(i).get(j));
            }

            line += "\t | \t RowDistance: " + String.format("%.5f", distanceSums.get(i));
            Logger.log(3, line);
        }
        Logger.log(3, String.format("Total distance: %.5f", distanceTotal));
        Logger.log(3, "====================");
    }

    private void outputNodes() {
        for (int i = 0; i < nodeCtr; ++i) {
            System.out.println(posToNode.get(i));
        }
    }
}


text:
package com.pinterest.jbender.events.recording;

import com.pinterest.jbender.events.TimingEvent;
import org.HdrHistogram.Histogram;

/**
 * Records the duration of each TimingEvent in an HdrHistogram and keeps track of the total number
 * of errors and the start and end time of the load test.
 */
public class HdrHistogramRecorder implements Recorder {
  private final long scale;
  private boolean started;

  // The histogram used to record durations
  public final Histogram histogram;

  // The number of errors seen by this recorder so far.
  public long errorCount;

  // The start time of the first TimingEvent seen by this recorder. This is an estimate of the
  // start time of the load test, and not exact.
  public long startNanos;

  // The end time of the latest TimingEvent seen by this recorder.
  public long endNanos;

  /**
   * Constructor.
   *
   * @param h the HdrHistogram object into which values are written.
   * @param scale the value by which to divide the durationNanos field of each TimingEvent before
   *              recording it in the histogram. For example, to record milliseconds you would set
   *              the scale to 1,000,000, for microseconds you would use 1,000, and so on.
   */
  public HdrHistogramRecorder(final Histogram h, long scale) {
    this.histogram = h;
    this.scale = scale;
    this.errorCount = 0;
    this.startNanos = System.nanoTime();
    this.endNanos = System.nanoTime();
    this.started = false;
  }

  @Override
  public void record(final TimingEvent e) {
    if (!started) {
      started = true;
      startNanos = System.nanoTime() - e.durationNanos;
    }

    if (!e.isSuccess) {
      errorCount++;
    }

    histogram.recordValue(e.durationNanos / scale);

    endNanos = System.nanoTime();
  }
}