text:
var ISOFile = function (stream) {
	/* DataStream object (extended with multiple underlying buffers) used to parse boxes */
	this.stream = stream;
	/* Array of all boxes (in order) found in the file */
	this.boxes = [];
	/* Array of all mdats */
	this.mdats = [];
	/* Array of all moofs */
	this.moofs = [];
	/* Boolean indicating if the file is compatible with progressive parsing (moov first) */
	this.isProgressive = false;
	/* Index of the last moof box received */
	this.lastMoofIndex = 0;
	/* position in the current buffer of the beginning of the last box parsed */
	this.lastBoxStartPosition = 0;
	/* indicator if the parsing is stuck in the middle of an mdat box */
	this.parsingMdat = null;
	/* Boolean used to fire moov start event only once */
	this.moovStartFound = false;
	/* size of the buffers allocated for samples */
	this.samplesDataSize = 0;
	/* next file position that the parser needs:
	    - 0 until the first buffer (i.e. fileStart ===0) has been received
	    - otherwise, the next box start until the moov box has been parsed
	    - otherwise, the position of the next sample to fetch
	 */
	this.nextParsePosition = 0;
}

ISOFile.prototype.mergeNextBuffer = function() {
	var next_buffer;
	if (this.stream.bufferIndex+1 < this.stream.nextBuffers.length) {
		next_buffer = this.stream.nextBuffers[this.stream.bufferIndex+1];
		if (next_buffer.fileStart === this.stream.buffer.fileStart + this.stream.buffer.byteLength) {
			var oldLength = this.stream.buffer.byteLength;
			var oldUsedBytes = this.stream.buffer.usedBytes;
			var oldFileStart = this.stream.buffer.fileStart;
			this.stream.nextBuffers[this.stream.bufferIndex] = ArrayBuffer.concat(this.stream.buffer, next_buffer);
			this.stream.buffer = this.stream.nextBuffers[this.stream.bufferIndex];
			this.stream.nextBuffers.splice(this.stream.bufferIndex+1, 1);
			this.stream.buffer.usedBytes = oldUsedBytes; /* TODO: should it be += ? */
			this.stream.buffer.fileStart = oldFileStart;
			Log.d("ISOFile", "Concatenating buffer for box parsing (length: "+oldLength+"->"+this.stream.buffer.byteLength+")");
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

ISOFile.prototype.parse = function() {
	var found;
	var ret;
	var box;

	Log.d("ISOFile","Starting parsing with buffer #"+this.stream.bufferIndex+" (fileStart: "+this.stream.buffer.fileStart+" - Length: "+this.stream.buffer.byteLength+") from position "+this.lastBoxStartPosition+
		" ("+(this.stream.buffer.fileStart+this.lastBoxStartPosition)+" in the file)");

	/* Reposition at the start position of the previous box not entirely parsed */
	this.stream.seek(this.lastBoxStartPosition);

	while (true) {

		if (this.parsingMdat !== null) {
			/* we are in the parsing of an incomplete mdat box */
			box = this.parsingMdat;

			found = this.reposition(false, box.fileStart + box.hdr_size + box.size);
			if (found) {
				Log.d("ISOFile", "Found 'mdat' end in buffer #"+this.stream.bufferIndex);
				/* the end of the mdat has been found */
				this.parsingMdat = null;
				/* we can parse more in this buffer */
				continue;
			} else {
				/* we don't have the end of this mdat yet,
				   indicate that the next byte to fetch is the end of the buffers we have so far,
				   return and wait for more buffer to come */
				this.nextParsePosition = this.findEndContiguousBuf(this.stream.bufferIndex);
				return;
			}
		} else {
			/* not parsing an 'mdat' box
			/* remember the position of the box start in case we need to roll back (if the box is incomplete) */
			this.lastBoxStartPosition = this.stream.position;
			ret = BoxParser.parseOneBox(this.stream);
			if (ret.code === BoxParser.ERR_NOT_ENOUGH_DATA) {
				/* we did not have enough bytes in the current buffer to parse the entire box */
				if (ret.type === "mdat") {
					/* we had enough bytes to get its type and size and it's an 'mdat' */

					/* special handling for mdat boxes, since we don't actually need to parse it linearly
					   we create the box */
					box = new BoxParser[ret.type+"Box"](ret.size-ret.hdr_size);
					this.parsingMdat = box;
					this.mdats.push(box);
					box.fileStart = this.stream.buffer.fileStart + this.stream.position;
					box.hdr_size = ret.hdr_size;
					this.stream.buffer.usedBytes += ret.hdr_size;

					/* let's see if we have the end of the box in the other buffers */
					found = this.reposition(false, box.fileStart + box.hdr_size + box.size);
					if (found) {
						/* found the end of the box */
						this.parsingMdat = null;
						/* let's see if we can parse more in this buffer */
						continue;
					} else {
						/* 'mdat' end not found in the existing buffers */
						/* determine the next position in the file to start parsing from */
						if (!this.moovStartFound) {
							/* moov not find yet,
							   the file probably has 'mdat' at the beginning, and 'moov' at the end,
							   indicate that the downloader should not try to download those bytes now */
							this.nextParsePosition = box.fileStart + box.size + box.hdr_size;
						} else {
							/* we have the start of the moov box,
							   the next bytes should try to complete the current 'mdat' */
							this.nextParsePosition = this.findEndContiguousBuf(this.stream.bufferIndex);
						}
						/* not much we can do, wait for more buffers to arrive */
						return;
					}
				} else {
					/* box is incomplete, we may not even know its type */
					if (ret.type === "moov") {
						/* the incomplete box is a 'moov' box */
						this.moovStartFound = true;
						if (this.mdats.length === 0) {
							this.isProgressive = true;
						}
					}
					/* either it's not an mdat box (and we need to parse it, we cannot skip it)
					   (TODO: we could skip 'free' boxes ...)
  					   or we did not have enough data to parse the type and size of the box,
					   we try to concatenate the current buffer with the next buffer to restart parsing */
					merged = this.mergeNextBuffer();
					if (merged) {
						/* The next buffer was contiguous, the merging succeeded,
						   we can now continue parsing,
						   the next best position to parse is at the end of this new buffer */
						this.nextParsePosition = this.stream.buffer.fileStart + this.stream.buffer.byteLength;
						continue;
					} else {
						/* we cannot concatenate existing buffers because they are not contiguous or because there is no additional buffer */
						/* The next best position to parse is still at the end of this old buffer */
						if (!ret.type) {
							/* There were not enough bytes in the buffer to parse the box type and length,
							   the next fetch should retrieve those missing bytes, i.e. the next bytes after this buffer */
							this.nextParsePosition = this.stream.buffer.fileStart + this.stream.buffer.byteLength;
						} else {
							/* we had enough bytes to parse size and type of the incomplete box
							   if we haven't found yet the moov box, skip this one and try the next one
							   if we have found the moov box, let's continue linear parsing */
							if (this.moovStartFound) {
								this.nextParsePosition = this.stream.buffer.fileStart + this.stream.buffer.byteLength;
							} else {
								this.nextParsePosition = this.stream.buffer.fileStart + this.stream.position + ret.size;
							}
						}
						return;
					}
				}
			} else {
				/* the box is entirely parsed */
				box = ret.box;
				/* store the box in the 'boxes' array to preserve box order (for file rewrite if needed)  */
				this.boxes.push(box);
				/* but also store box in a property for more direct access */
				switch (box.type) {
					case "mdat":
						this.mdats.push(box);
						/* remember the position in the file of this box for comparison with sample offsets */
						box.fileStart = this.stream.buffer.fileStart + box.start;
						break;
					case "moof":
						this.moofs.push(box);
						break;
					case "moov":
						this.moovStartFound = true;
						if (this.mdats.length === 0) {
							this.isProgressive = true;
						}
						/* no break */
						/* falls through */
					default:
						if (this[box.type] !== undefined) {
							Log.w("ISOFile", "Duplicate Box of type: "+box.type+", overriding previous occurrence");
						}
						this[box.type] = box;
						break;
				}
				if (box.type === "mdat") {
					/* for an mdat box, only its header is considered used, other bytes will be used when sample data is requested */
					this.stream.buffer.usedBytes += box.hdr_size;
				} else {
					/* for all other boxes, the entire box data is considered used */
					this.stream.buffer.usedBytes += ret.size;
				}
			}
		}
	}
}

/* Searches for the buffer containing the given file position:
  - if found, repositions the parsing from there and returns true
  - if not found, does not change anything and returns false */
ISOFile.prototype.reposition = function(fromStart, filePosition) {
	var index;
	index = this.findPosition(fromStart, filePosition);
	if (index !== -1) {
		this.stream.buffer = this.stream.nextBuffers[index];
		this.stream.bufferIndex = index;
		this.stream.position = filePosition - this.stream.buffer.fileStart;
		Log.d("ISOFile", "Repositioning parser at buffer position: "+this.stream.position);
		return true;
	} else {
		return false;
	}
}

/* Searches for the buffer containing the given file position
   Returns the index of the buffer (-1 if not found) */
ISOFile.prototype.findPosition = function(fromStart, filePosition) {
	var i;
	var buffer = null;
	var index = -1;

	/* find the buffer with the largest position smaller than the given position */
	if (fromStart === true) {
	   /* the reposition can be in the past, we need to check from the beginning of the list of buffers */
		i = 0;
	} else {
		i = this.stream.bufferIndex;
	}

	while (i < this.stream.nextBuffers.length) {
		buffer = this.stream.nextBuffers[i];
		if (buffer.fileStart <= filePosition) {
			index = i;
		} else {
			break;
		}
		i++;
	}

	if (index !== -1) {
		buffer = this.stream.nextBuffers[index];
		if (buffer.fileStart + buffer.byteLength >= filePosition) {
			Log.d("ISOFile", "Found position in existing buffer #"+index);
			return index;
		} else {
			return -1;
		}
	} else {
		return -1;
	}
}

ISOFile.prototype.findEndContiguousBuf = function(index) {
	var i;
	var currentBuf;
	var nextBuf;
	currentBuf = this.stream.nextBuffers[index];
	/* find the end of the contiguous range of data */
	if (this.stream.nextBuffers.length > index+1) {
		for (i = index+1; i < this.stream.nextBuffers.length; i++) {
			nextBuf = this.stream.nextBuffers[i];
			if (nextBuf.fileStart === currentBuf.fileStart + currentBuf.byteLength) {
				currentBuf = nextBuf;
			} else {
				break;
			}
		}
	}
	/* return the position of last byte in the file that we have */
	return currentBuf.fileStart + currentBuf.byteLength;
}

/* Rewrite the entire file */
ISOFile.prototype.write = function(outstream) {
	for (var i=0; i<this.boxes.length; i++) {
		this.boxes[i].write(outstream);
	}
}

/* Modify the file and create the initialization segment */
ISOFile.prototype.writeInitializationSegment = function(outstream) {
	var i;
	var index;
	var mehd;
	var trex;
	var box;
	Log.d("ISOFile", "Generating initialization segment");
	/* write the ftyp box as is in the input, may need to be fixed for DASH brands ?*/
	this.ftyp.write(outstream);

	/* The input file may be fragmented and have an mvex box, we just retrieve the duration and delele that box  */
	if (this.moov.mvex) {
		this.initial_duration = this.moov.mvex.mehd.fragment_duration;
		/* find this mvex box in the array of boxes and remove it */
		index = -1;
		for (i = 0; i < this.moov.boxes.length; i++) {
			box = this.moov.boxes[i];
			if (box === this.moov.mvex) {
				index = i;
			}
		}
		if (index > -1) {
			this.moov.boxes.splice(index, 1);
		}
		this.moov.mvex = null;
	}
	/* we can now create the new mvex box */
	this.moov.mvex = new BoxParser.mvexBox();
	this.moov.boxes.push(this.moov.mvex);
	this.moov.mvex.mehd = new BoxParser.mehdBox();
	this.moov.mvex.boxes.push(this.moov.mvex.mehd);
	this.moov.mvex.mehd.fragment_duration = this.initial_duration; // restore the same duration
	for (i = 0; i < this.moov.traks.length; i++) {
		if (this.moov.traks[i].ignore) continue;
		trex = new BoxParser.trexBox();
		this.moov.mvex.boxes.push(trex);
		trex.track_id = this.moov.traks[i].tkhd.track_id;
		trex.default_sample_description_index = 1;
		trex.default_sample_duration = (this.moov.traks[i].samples.length>0 ? this.moov.traks[i].samples[0].duration: 0);
		trex.default_sample_size = 0;
		trex.default_sample_flags = 1<<16;
	}
	this.moov.write(outstream);
}

/* Resets all sample tables */
ISOFile.prototype.resetTables = function () {
	var i;
	var trak, stco, stsc, stsz, stts, ctts, stss;
	this.initial_duration = this.moov.mvhd.duration;
	this.moov.mvhd.duration = 0;
	for (i = 0; i < this.moov.traks.length; i++) {
		trak = this.moov.traks[i];
		trak.tkhd.duration = 0;
		trak.mdia.mdhd.duration = 0;
		stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;
		stco.chunk_offsets = [];
		stsc = trak.mdia.minf.stbl.stsc;
		stsc.first_chunk = [];
		stsc.samples_per_chunk = [];
		stsc.sample_description_index = [];
		stsz = trak.mdia.minf.stbl.stsz;
		stsz.sample_sizes = [];
		stts = trak.mdia.minf.stbl.stts;
		stts.sample_counts = [];
		stts.sample_deltas = [];
		ctts = trak.mdia.minf.stbl.ctts;
		if (ctts) {
			ctts.sample_counts = [];
			ctts.sample_offsets = [];
		}
		stss = trak.mdia.minf.stbl.stss;
		var k = trak.mdia.minf.stbl.boxes.indexOf(stss);
		if (k != -1) trak.mdia.minf.stbl.boxes[k] = null;
	}
}

/* Build initial sample list from  sample tables */
ISOFile.prototype.buildSampleLists = function() {
	var i, j, k;
	var trak, stco, stsc, stsz, stts, ctts, stss, stsd, subs;
	var chunk_run_index, chunk_index, last_chunk_in_run, offset_in_chunk, last_sample_in_chunk;
	var last_sample_in_stts_run, stts_run_index, last_sample_in_ctts_run, ctts_run_index, last_stss_index, last_subs_index;
	for (i = 0; i < this.moov.traks.length; i++) {
		trak = this.moov.traks[i];
		trak.samples = [];
		stco = trak.mdia.minf.stbl.stco || trak.mdia.minf.stbl.co64;
		stsc = trak.mdia.minf.stbl.stsc;
		stsz = trak.mdia.minf.stbl.stsz;
		stts = trak.mdia.minf.stbl.stts;
		ctts = trak.mdia.minf.stbl.ctts;
		stss = trak.mdia.minf.stbl.stss;
		stsd = trak.mdia.minf.stbl.stsd;
		subs = trak.mdia.minf.stbl.subs;

		last_sample_in_stts_run = -1;
		stts_run_index = -1;
		last_sample_in_ctts_run = -1;
		ctts_run_index = -1;
		last_stss_index = 0;
		subs_entry_index = 0;
		last_subs_sample_index = 0;
		/* we build the samples one by one and compute their properties */
		for (j = 0; j < stsz.sample_sizes.length; j++) {
			var sample = {};
			sample.number = j;
			sample.track_id = trak.tkhd.track_id;
			sample.timescale = trak.mdia.mdhd.timescale;
			trak.samples[j] = sample;
			/* size can be known directly */
			sample.size = stsz.sample_sizes[j];

			/* computing chunk-based properties (offset, sample description index)*/
			if (j === 0) {
				chunk_index = 1; /* the first sample is in the first chunk (chunk indexes are 1-based) */
				chunk_run_index = 0; /* the first chunk is the first entry in the first_chunk table */
				sample.chunk_index = chunk_index;
				sample.chunk_run_index = chunk_run_index;
				last_sample_in_chunk = stsc.samples_per_chunk[chunk_run_index];
				offset_in_chunk = 0;

				/* Is there another entry in the first_chunk table ? */
				if (chunk_run_index + 1 < stsc.first_chunk.length) {
					/* The last chunk in the run is the chunk before the next first chunk */
					last_chunk_in_run = stsc.first_chunk[chunk_run_index+1]-1;
				} else {
					/* There is only one entry in the table, it is valid for all future chunks*/
					last_chunk_in_run = Infinity;
				}
			} else {
				if (j < last_sample_in_chunk) {
					/* the sample is still in the current chunk */
					sample.chunk_index = chunk_index;
					sample.chunk_run_index = chunk_run_index;
				} else {
					/* the sample is in the next chunk */
					chunk_index++;
					sample.chunk_index = chunk_index;
					/* reset the accumulated offset in the chunk */
					offset_in_chunk = 0;
					if (chunk_index <= last_chunk_in_run) {
						/* stay in the same entry of the first_chunk table */
						/* chunk_run_index unmodified */
					} else {
						chunk_run_index++;
						/* Is there another entry in the first_chunk table ? */
						if (chunk_run_index + 1 < stsc.first_chunk.length) {
							/* The last chunk in the run is the chunk before the next first chunk */
							last_chunk_in_run = stsc.first_chunk[chunk_run_index+1]-1;
						} else {
							/* There is only one entry in the table, it is valid for all future chunks*/
							last_chunk_in_run = Infinity;
						}

					}
					sample.chunk_run_index = chunk_run_index;
					last_sample_in_chunk += stsc.samples_per_chunk[chunk_run_index];
				}
			}

			sample.description = stsd.entries[stsc.sample_description_index[sample.chunk_run_index]-1];
			sample.offset = stco.chunk_offsets[sample.chunk_index-1] + offset_in_chunk; /* chunk indexes are 1-based */
			offset_in_chunk += sample.size;

			/* setting dts, cts, duration and rap flags */
			if (j > last_sample_in_stts_run) {
				stts_run_index++;
				if (last_sample_in_stts_run < 0) {
					last_sample_in_stts_run = 0;
				}
				last_sample_in_stts_run += stts.sample_counts[stts_run_index];
			}
			if (j > 0) {
				trak.samples[j-1].duration = stts.sample_deltas[stts_run_index];
				sample.dts = trak.samples[j-1].dts + trak.samples[j-1].duration;
			} else {
				sample.dts = 0;
			}
			if (ctts) {
				if (j > last_sample_in_ctts_run) {
					ctts_run_index++;
					if (last_sample_in_ctts_run < 0) {
						last_sample_in_ctts_run = 0;
					}
					last_sample_in_ctts_run += ctts.sample_counts[ctts_run_index];
				}
				sample.cts = trak.samples[j].dts + ctts.sample_offsets[ctts_run_index];
			} else {
				sample.cts = sample.dts;
			}
			if (stss) {
				if (j == stss.sample_numbers[last_stss_index] - 1) { // sample numbers are 1-based
					sample.is_rap = true;
					last_stss_index++;
				} else {
					sample.is_rap = false;
				}
			} else {
				sample.is_rap = true;
			}
			if (subs) {
				if (subs.samples[subs_entry_index].sample_delta + last_subs_sample_index == j) {
					sample.subsamples = subs.samples[subs_entry_index].subsamples;
					last_subs_sample_index += subs.samples[subs_entry_index].sample_delta;
				}
			}
		}
		if (j>0) trak.samples[j-1].duration = trak.mdia.mdhd.duration - trak.samples[j-1].dts;
	}
}

/* Update sample list when new 'moof' boxes are received */
ISOFile.prototype.updateSampleLists = function() {
	var i, j, k;
	var default_sample_description_index, default_sample_duration, default_sample_size, default_sample_flags;
	var last_run_position;
	var box, moof, traf, trak, trex;
	var sample;

	/* if the input file is fragmented and fetched in multiple downloads, we need to update the list of samples */
	while (this.lastMoofIndex < this.moofs.length) {
		box = this.moofs[this.lastMoofIndex];
		this.lastMoofIndex++;
		if (box.type == "moof") {
			moof = box;
			for (i = 0; i < moof.trafs.length; i++) {
				traf = moof.trafs[i];
				trak = this.getTrackById(traf.tfhd.track_id);
				trex = this.getTrexById(traf.tfhd.track_id);
				if (traf.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DESC) {
					default_sample_description_index = traf.tfhd.default_sample_description_index;
				} else {
					default_sample_description_index = trex.default_sample_description_index;
				}
				if (traf.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_DUR) {
					default_sample_duration = traf.tfhd.default_sample_duration;
				} else {
					default_sample_duration = trex.default_sample_duration;
				}
				if (traf.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_SIZE) {
					default_sample_size = traf.tfhd.default_sample_size;
				} else {
					default_sample_size = trex.default_sample_size;
				}
				if (traf.tfhd.flags & BoxParser.TFHD_FLAG_SAMPLE_FLAGS) {
					default_sample_flags = traf.tfhd.default_sample_flags;
				} else {
					default_sample_flags = trex.default_sample_flags;
				}
				for (j = 0; j < traf.truns.length; j++) {
					var trun = traf.truns[j];
					for (k = 0; k < trun.sample_count; k++) {
						sample = {};
						traf.first_sample_index = trak.samples.length;
						trak.samples.push(sample);
						sample.track_id = trak.tkhd.track_id;
						sample.timescale = trak.mdia.mdhd.timescale;
						sample.description = trak.mdia.minf.stbl.stsd.entries[default_sample_description_index-1];
						sample.size = default_sample_size;
						if (trun.flags & BoxParser.TRUN_FLAGS_SIZE) {
							sample.size = trun.sample_size[k];
						}
						sample.duration = default_sample_duration;
						if (trun.flags & BoxParser.TRUN_FLAGS_DURATION) {
							sample.duration = trun.sample_duration[k];
						}
						if (trak.first_traf_merged || k > 0) {
							sample.dts = trak.samples[trak.samples.length-2].dts+trak.samples[trak.samples.length-2].duration;
						} else {
							if (traf.tfdt) {
								sample.dts = traf.tfdt.baseMediaDecodeTime;
							} else {
								sample.dts = 0;
							}
							trak.first_traf_merged = true;
						}
						sample.cts = sample.dts;
						if (trun.flags & BoxParser.TRUN_FLAGS_CTS_OFFSET) {
							sample.cts = sample.dts + trun.sample_composition_time_offset[k];
						}
						sample_flags = default_sample_flags;
						if (trun.flags & BoxParser.TRUN_FLAGS_FLAGS) {
							sample_flags = trun.sample_flags[k];
						} else if (k === 0 && (trun.flags & BoxParser.TRUN_FLAGS_FIRST_FLAG)) {
							sample_flags = trun.first_sample_flags;
						}
						sample.is_rap = ((sample_flags >> 16 & 0x1) ? false : true);
						var bdop = (traf.tfhd.flags & BoxParser.TFHD_FLAG_BASE_DATA_OFFSET) ? true : false;
						var dbim = (traf.tfhd.flags & BoxParser.TFHD_FLAG_DEFAULT_BASE_IS_MOOF) ? true : false;
						var dop = (trun.flags & BoxParser.TRUN_FLAGS_DATA_OFFSET) ? true : false;
						var bdo = 0;
						if (!bdop) {
							if (!dbim) {
								if (j === 0) { // the first track in the movie fragment
									bdo = moof.fileStart; // the position of the first byte of the enclosing Movie Fragment Box
								} else {
									bdo = last_run_position; // end of the data defined by the preceding *track* (irrespective of the track id) fragment in the moof
								}
							} else {
								bdo = moof.fileStart;
							}
						} else {
							bdo = traf.tfhd.base_data_offset;
						}
						if (j === 0 && k === 0) {
							if (dop) {
								sample.offset = bdo + trun.data_offset; // If the data-offset is present, it is relative to the base-data-offset established in the track fragment header
							} else {
								sample.offset = bdo; // the data for this run starts the base-data-offset defined by the track fragment header
							}
						} else {
							sample.offset = last_run_position; // this run starts immediately after the data of the previous run
						}
						last_run_position = sample.offset + sample.size;
					}
				}
				if (traf.subs) {
					var sample_index = traf.first_sample_index;
					for (j = 0; j < traf.subs.samples.length; j++) {
						sample_index += traf.subs.samples[j].sample_delta;
						sample = trak.samples[sample_index-1];
						sample.subsamples = traf.subs.samples[j].subsamples;
					}
				}
			}
		}
	}
}

/* Builds the MIME Type 'codecs' sub-parameters for the whole file */
ISOFile.prototype.getCodecs = function() {
	var i;
	var codecs = "";
	for (i = 0; i < this.moov.traks.length; i++) {
		var trak = this.moov.traks[i];
		if (i>0) {
			codecs+=",";
		}
		codecs += trak.mdia.minf.stbl.stsd.entries[0].getCodec();
	}
	return codecs;
}

/* Helper function */
ISOFile.prototype.getTrexById = function(id) {
	var i;
	if (!this.moov || !this.moov.mvex) return null;
	for (i = 0; i < this.moov.mvex.trexs.length; i++) {
		var trex = this.moov.mvex.trexs[i];
		if (trex.track_id == id) return trex;
	}
	return null;
}

/* Helper function */
ISOFile.prototype.getTrackById = function(id) {
	for (var j = 0; j < this.moov.traks.length; j++) {
		var trak = this.moov.traks[j];
		if (trak.tkhd.track_id == id) return trak;
	}
	return null;
}

/* Try to get sample data for a given sample:
   returns null if not found
   returns the same sample if already requested
 */
ISOFile.prototype.getSample = function(trak, sampleNum) {
	var buffer;
	var i;
	var sample = trak.samples[sampleNum];

	if (!this.moov) {
		return null;
	}

	if (!sample.data) {
		/* Not yet fetched */
		sample.data = new Uint8Array(sample.size);
		sample.alreadyRead = 0;
		this.samplesDataSize += sample.size;
		Log.d("ISOFile", "Allocating sample #"+sampleNum+" on track #"+trak.tkhd.track_id+" of size "+sample.size+" (total: "+this.samplesDataSize+")");
	} else if (sample.alreadyRead == sample.size) {
		/* Already fetched entirely */
		return sample;
	}

	/* The sample has only been partially fetched, we need to check in all mdat boxes (e.g. if the input file is fragmented)
	   and in all mdat buffers (if the input file was not fetched in a single download) */
	for (i = 0; i < this.stream.nextBuffers.length; i++) {
		buffer = this.stream.nextBuffers[i];

		if (sample.offset + sample.alreadyRead >= buffer.fileStart &&
		    sample.offset + sample.alreadyRead <  buffer.fileStart + buffer.byteLength) {
			/* The sample starts in this buffer */

			var lengthAfterStart = buffer.byteLength - (sample.offset + sample.alreadyRead - buffer.fileStart);
			if (sample.size - sample.alreadyRead <= lengthAfterStart) {
				/* the (rest of the) sample is entirely contained in this buffer */

				Log.d("ISOFile","Getting sample #"+sampleNum+" data (alreadyRead: "+sample.alreadyRead+" offset: "+
					(sample.offset+sample.alreadyRead - buffer.fileStart)+" size: "+(sample.size - sample.alreadyRead)+")");

				DataStream.memcpy(sample.data.buffer, sample.alreadyRead,
				                  buffer, sample.offset+sample.alreadyRead - buffer.fileStart, sample.size - sample.alreadyRead);
				sample.alreadyRead = sample.size;

				/* update the number of bytes used in this buffer and check if it needs to be removed */
				buffer.usedBytes += sample.size - sample.alreadyRead;
				if (buffer.usedBytes === buffer.byteLength) {
					this.stream.nextBuffers.splice(i, 1);
					i--;
					/* TODO: check if the DataStream buffer needs to be updated */
				}

				return sample;
			} else {
				/* the sample does not end in this buffer */

				Log.d("ISOFile","Getting sample data (alreadyRead: "+sample.alreadyRead+" offset: "+
					(sample.offset+sample.alreadyRead - buffer.fileStart)+" size: "+lengthAfterStart+")");

				DataStream.memcpy(sample.data.buffer, sample.alreadyRead,
				                  buffer, sample.offset+sample.alreadyRead - buffer.fileStart, lengthAfterStart);
				sample.alreadyRead += lengthAfterStart;

				/* update the number of bytes used in this buffer and check if it needs to be removed */
				buffer.usedBytes += lengthAfterStart;
				if (buffer.usedBytes === buffer.byteLength) {
					this.stream.nextBuffers.splice(i, 1);
					i--;
					/* TODO: check if the DataStream buffer needs to be updated */
				}
			}
		}
	}
	return null;
}

/* Release the memory used to store the data of the sample */
ISOFile.prototype.releaseSample = function(trak, sampleNum) {
	var sample = trak.samples[sampleNum];
	sample.data = null;
	this.samplesDataSize -= sample.size;
	return sample.size;
}


text:
class AddTreatiseIdToQuestion < ActiveRecord::Migration[4.2]
  def change
    add_column :questions, :treatise_id, :integer
  end
end

redpajama_set_name: RedPajamaGithub


text:
package eu.dnetlib.iis.wf.report;

import eu.dnetlib.iis.common.AbstractOozieWorkflowTestCase;
import org.junit.jupiter.api.Test;

/**
 * @author madryk
 */
public class ReportWorkflowTest extends AbstractOozieWorkflowTestCase {

    //------------------------ TESTS --------------------------

    @Test
    public void testReportWorkflow() throws Exception {

        testWorkflow("eu/dnetlib/iis/wf/report/builder/test");

    }
}


text:
package org.apereo.cas.config;

import org.apereo.cas.audit.AuditActionResolvers;
import org.apereo.cas.audit.AuditPrincipalIdProvider;
import org.apereo.cas.audit.AuditResourceResolvers;
import org.apereo.cas.audit.AuditTrailConstants;
import org.apereo.cas.audit.AuditTrailRecordResolutionPlanConfigurer;
import org.apereo.cas.audit.AuditableExecution;
import org.apereo.cas.authentication.audit.SurrogateAuditPrincipalIdProvider;
import org.apereo.cas.authentication.audit.SurrogateAuthenticationEligibilityAuditableExecution;
import org.apereo.cas.authentication.audit.SurrogateEligibilitySelectionAuditResourceResolver;
import org.apereo.cas.authentication.audit.SurrogateEligibilityVerificationAuditResourceResolver;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.features.CasFeatureModule;
import org.apereo.cas.util.spring.boot.ConditionalOnFeatureEnabled;

import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apereo.inspektr.audit.spi.AuditResourceResolver;
import org.apereo.inspektr.audit.spi.support.DefaultAuditActionResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;

/**
 * This is {@link SurrogateAuthenticationAuditConfiguration}.
 *
 * @author Dmitriy Kopylenko
 * @since 5.3.0
 */
@ConditionalOnFeatureEnabled(feature = CasFeatureModule.FeatureCatalog.SurrogateAuthentication)
@AutoConfiguration
public class SurrogateAuthenticationAuditConfiguration {

    @Configuration(value = "SurrogateAuthenticationAuditPrincipalConfiguration", proxyBeanMethods = false)
    @EnableConfigurationProperties(CasConfigurationProperties.class)
    public static class SurrogateAuthenticationAuditPrincipalConfiguration {
        @Bean
        @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
        @ConditionalOnMissingBean(name = "surrogateAuditPrincipalIdProvider")
        public AuditPrincipalIdProvider surrogateAuditPrincipalIdProvider() {
            return new SurrogateAuditPrincipalIdProvider();
        }

    }

    @Configuration(value = "SurrogateAuthenticationAuditExecutionConfiguration", proxyBeanMethods = false)
    @EnableConfigurationProperties(CasConfigurationProperties.class)
    public static class SurrogateAuthenticationAuditExecutionConfiguration {
        @Bean
        @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
        @ConditionalOnMissingBean(name = "surrogateEligibilityAuditableExecution")
        public AuditableExecution surrogateEligibilityAuditableExecution() {
            return new SurrogateAuthenticationEligibilityAuditableExecution();
        }
    }

    @Configuration(value = "SurrogateAuthenticationAuditResourcesConfiguration", proxyBeanMethods = false)
    @EnableConfigurationProperties(CasConfigurationProperties.class)
    public static class SurrogateAuthenticationAuditResourcesConfiguration {
        @Bean
        @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
        @ConditionalOnMissingBean(name = "surrogateEligibilityVerificationAuditResourceResolver")
        public AuditResourceResolver surrogateEligibilityVerificationAuditResourceResolver() {
            return new SurrogateEligibilityVerificationAuditResourceResolver();
        }

        @Bean
        @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
        @ConditionalOnMissingBean(name = "surrogateEligibilitySelectionAuditResourceResolver")
        public AuditResourceResolver surrogateEligibilitySelectionAuditResourceResolver() {
            return new SurrogateEligibilitySelectionAuditResourceResolver();
        }

    }

    @Configuration(value = "SurrogateAuthenticationAuditPlanConfiguration", proxyBeanMethods = false)
    @EnableConfigurationProperties(CasConfigurationProperties.class)
    public static class SurrogateAuthenticationAuditPlanConfiguration {
        @Bean
        @RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
        @ConditionalOnMissingBean(name = "surrogateAuditTrailRecordResolutionPlanConfigurer")
        public AuditTrailRecordResolutionPlanConfigurer surrogateAuditTrailRecordResolutionPlanConfigurer(
            @Qualifier("surrogateEligibilityVerificationAuditResourceResolver")
            final AuditResourceResolver surrogateEligibilityVerificationAuditResourceResolver,
            @Qualifier("surrogateEligibilitySelectionAuditResourceResolver")
            final AuditResourceResolver surrogateEligibilitySelectionAuditResourceResolver) {
            return plan -> {
                val actionResolver = new DefaultAuditActionResolver(AuditTrailConstants.AUDIT_ACTION_POSTFIX_TRIGGERED, StringUtils.EMPTY);
                plan.registerAuditActionResolver(AuditActionResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_VERIFICATION_ACTION_RESOLVER, actionResolver);
                plan.registerAuditActionResolver(AuditActionResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_SELECTION_ACTION_RESOLVER, actionResolver);

                plan.registerAuditResourceResolver(AuditResourceResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_VERIFICATION_RESOURCE_RESOLVER,
                    surrogateEligibilityVerificationAuditResourceResolver);
                plan.registerAuditResourceResolver(AuditResourceResolvers.SURROGATE_AUTHENTICATION_ELIGIBILITY_SELECTION_RESOURCE_RESOLVER,
                    surrogateEligibilitySelectionAuditResourceResolver);
            };
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springboot</groupId>
    <artifactId>springboot-freemarker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-freemarker :: Spring Boot 集成 FreeMarker 案例</name>

    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
    </properties>

    <dependencies>
        <!-- Spring Boot Freemarker 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>


text:
testRec* simpleCalTest(int testNum);
testRec* medCalTest(int testNum);
testRec* largeCalTest(int testNum);
testRec* invFileTest(int testNum);
testRec* invCalTest(int testNum);
testRec* invEvtTest(int testNum);
testRec* printCalTest(int testNum);
testRec* deleteCalTest(int testNum);
testRec* printErrTest(int testNum);
testRec* invAlmTest(int testNum);


text:
Micro Python documentation and references
=========================================

.. toctree::

   quickref.rst
   general.rst
   tutorial/index.rst
   library/index.rst
   hardware/index.rst
   license.rst
   contents.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
#include "src/cpp/client/secure_credentials.h"

#include <grpc/impl/codegen/slice.h>
#include <grpc/slice.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpcpp/channel.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/grpc_library.h>
#include <grpcpp/support/channel_arguments.h>

#include "src/core/lib/gpr/env.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/json/json.h"
#include "src/core/lib/security/transport/auth_filters.h"
#include "src/core/lib/security/util/json_util.h"
#include "src/cpp/client/create_channel_internal.h"
#include "src/cpp/common/secure_auth_context.h"

namespace grpc_impl {

static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
SecureChannelCredentials::SecureChannelCredentials(
    grpc_channel_credentials* c_creds)
    : c_creds_(c_creds) {
  g_gli_initializer.summon();
}

std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl(
    const grpc::string& target, const ChannelArguments& args) {
  return CreateChannelWithInterceptors(
      target, args,
      std::vector<std::unique_ptr<
          grpc::experimental::ClientInterceptorFactoryInterface>>());
}

std::shared_ptr<Channel>
SecureChannelCredentials::CreateChannelWithInterceptors(
    const grpc::string& target, const ChannelArguments& args,
    std::vector<
        std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
        interceptor_creators) {
  grpc_channel_args channel_args;
  args.SetChannelArgs(&channel_args);
  return ::grpc::CreateChannelInternal(
      args.GetSslTargetNameOverride(),
      grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args,
                                 nullptr),
      std::move(interceptor_creators));
}

SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds)
    : c_creds_(c_creds) {
  g_gli_initializer.summon();
}

bool SecureCallCredentials::ApplyToCall(grpc_call* call) {
  return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK;
}

namespace {
std::shared_ptr<ChannelCredentials> WrapChannelCredentials(
    grpc_channel_credentials* creds) {
  return creds == nullptr ? nullptr
                          : std::shared_ptr<ChannelCredentials>(
                                new SecureChannelCredentials(creds));
}

std::shared_ptr<CallCredentials> WrapCallCredentials(
    grpc_call_credentials* creds) {
  return creds == nullptr ? nullptr
                          : std::shared_ptr<CallCredentials>(
                                new SecureCallCredentials(creds));
}
}  // namespace

std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapChannelCredentials(grpc_google_default_credentials_create());
}

// Builds SSL Credentials given SSL specific options
std::shared_ptr<ChannelCredentials> SslCredentials(
    const SslCredentialsOptions& options) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  grpc_ssl_pem_key_cert_pair pem_key_cert_pair = {
      options.pem_private_key.c_str(), options.pem_cert_chain.c_str()};

  grpc_channel_credentials* c_creds = grpc_ssl_credentials_create(
      options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(),
      options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr,
      nullptr);
  return WrapChannelCredentials(c_creds);
}

namespace experimental {

namespace {

void ClearStsCredentialsOptions(StsCredentialsOptions* options) {
  if (options == nullptr) return;
  options->token_exchange_service_uri.clear();
  options->resource.clear();
  options->audience.clear();
  options->scope.clear();
  options->requested_token_type.clear();
  options->subject_token_path.clear();
  options->subject_token_type.clear();
  options->actor_token_path.clear();
  options->actor_token_type.clear();
}

}  // namespace

// Builds STS credentials options from JSON.
grpc::Status StsCredentialsOptionsFromJson(const grpc::string& json_string,
                                           StsCredentialsOptions* options) {
  struct GrpcJsonDeleter {
    void operator()(grpc_json* json) { grpc_json_destroy(json); }
  };
  if (options == nullptr) {
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                        "options cannot be nullptr.");
  }
  ClearStsCredentialsOptions(options);
  std::vector<char> scratchpad(json_string.c_str(),
                               json_string.c_str() + json_string.size() + 1);
  std::unique_ptr<grpc_json, GrpcJsonDeleter> json(
      grpc_json_parse_string(&scratchpad[0]));
  if (json == nullptr) {
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Invalid json.");
  }

  // Required fields.
  const char* value = grpc_json_get_string_property(
      json.get(), "token_exchange_service_uri", nullptr);
  if (value == nullptr) {
    ClearStsCredentialsOptions(options);
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                        "token_exchange_service_uri must be specified.");
  }
  options->token_exchange_service_uri.assign(value);
  value =
      grpc_json_get_string_property(json.get(), "subject_token_path", nullptr);
  if (value == nullptr) {
    ClearStsCredentialsOptions(options);
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                        "subject_token_path must be specified.");
  }
  options->subject_token_path.assign(value);
  value =
      grpc_json_get_string_property(json.get(), "subject_token_type", nullptr);
  if (value == nullptr) {
    ClearStsCredentialsOptions(options);
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                        "subject_token_type must be specified.");
  }
  options->subject_token_type.assign(value);

  // Optional fields.
  value = grpc_json_get_string_property(json.get(), "resource", nullptr);
  if (value != nullptr) options->resource.assign(value);
  value = grpc_json_get_string_property(json.get(), "audience", nullptr);
  if (value != nullptr) options->audience.assign(value);
  value = grpc_json_get_string_property(json.get(), "scope", nullptr);
  if (value != nullptr) options->scope.assign(value);
  value = grpc_json_get_string_property(json.get(), "requested_token_type",
                                        nullptr);
  if (value != nullptr) options->requested_token_type.assign(value);
  value =
      grpc_json_get_string_property(json.get(), "actor_token_path", nullptr);
  if (value != nullptr) options->actor_token_path.assign(value);
  value =
      grpc_json_get_string_property(json.get(), "actor_token_type", nullptr);
  if (value != nullptr) options->actor_token_type.assign(value);

  return grpc::Status();
}

// Builds STS credentials Options from the $STS_CREDENTIALS env var.
grpc::Status StsCredentialsOptionsFromEnv(StsCredentialsOptions* options) {
  if (options == nullptr) {
    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                        "options cannot be nullptr.");
  }
  ClearStsCredentialsOptions(options);
  grpc_slice json_string = grpc_empty_slice();
  char* sts_creds_path = gpr_getenv("STS_CREDENTIALS");
  grpc_error* error = GRPC_ERROR_NONE;
  grpc::Status status;
  auto cleanup = [&json_string, &sts_creds_path, &error, &status]() {
    grpc_slice_unref_internal(json_string);
    gpr_free(sts_creds_path);
    GRPC_ERROR_UNREF(error);
    return status;
  };

  if (sts_creds_path == nullptr) {
    status = grpc::Status(grpc::StatusCode::NOT_FOUND,
                          "STS_CREDENTIALS environment variable not set.");
    return cleanup();
  }
  error = grpc_load_file(sts_creds_path, 1, &json_string);
  if (error != GRPC_ERROR_NONE) {
    status =
        grpc::Status(grpc::StatusCode::NOT_FOUND, grpc_error_string(error));
    return cleanup();
  }
  status = StsCredentialsOptionsFromJson(
      reinterpret_cast<const char*>(GRPC_SLICE_START_PTR(json_string)),
      options);
  return cleanup();
}

// C++ to Core STS Credentials options.
grpc_sts_credentials_options StsCredentialsCppToCoreOptions(
    const StsCredentialsOptions& options) {
  grpc_sts_credentials_options opts;
  memset(&opts, 0, sizeof(opts));
  opts.token_exchange_service_uri = options.token_exchange_service_uri.c_str();
  opts.resource = options.resource.c_str();
  opts.audience = options.audience.c_str();
  opts.scope = options.scope.c_str();
  opts.requested_token_type = options.requested_token_type.c_str();
  opts.subject_token_path = options.subject_token_path.c_str();
  opts.subject_token_type = options.subject_token_type.c_str();
  opts.actor_token_path = options.actor_token_path.c_str();
  opts.actor_token_type = options.actor_token_type.c_str();
  return opts;
}

// Builds STS credentials.
std::shared_ptr<CallCredentials> StsCredentials(
    const StsCredentialsOptions& options) {
  auto opts = StsCredentialsCppToCoreOptions(options);
  return WrapCallCredentials(grpc_sts_credentials_create(&opts, nullptr));
}

// Builds ALTS Credentials given ALTS specific options
std::shared_ptr<ChannelCredentials> AltsCredentials(
    const AltsCredentialsOptions& options) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  grpc_alts_credentials_options* c_options =
      grpc_alts_credentials_client_options_create();
  for (auto service_account = options.target_service_accounts.begin();
       service_account != options.target_service_accounts.end();
       service_account++) {
    grpc_alts_credentials_client_options_add_target_service_account(
        c_options, service_account->c_str());
  }
  grpc_channel_credentials* c_creds = grpc_alts_credentials_create(c_options);
  grpc_alts_credentials_options_destroy(c_options);
  return WrapChannelCredentials(c_creds);
}

// Builds Local Credentials
std::shared_ptr<ChannelCredentials> LocalCredentials(
    grpc_local_connect_type type) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapChannelCredentials(grpc_local_credentials_create(type));
}

}  // namespace experimental

// Builds credentials for use when running in GCE
std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapCallCredentials(
      grpc_google_compute_engine_credentials_create(nullptr));
}

// Builds JWT credentials.
std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials(
    const grpc::string& json_key, long token_lifetime_seconds) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  if (token_lifetime_seconds <= 0) {
    gpr_log(GPR_ERROR,
            "Trying to create JWTCredentials with non-positive lifetime");
    return WrapCallCredentials(nullptr);
  }
  gpr_timespec lifetime =
      gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN);
  return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create(
      json_key.c_str(), lifetime, nullptr));
}

// Builds refresh token credentials.
std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials(
    const grpc::string& json_refresh_token) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapCallCredentials(grpc_google_refresh_token_credentials_create(
      json_refresh_token.c_str(), nullptr));
}

// Builds access token credentials.
std::shared_ptr<CallCredentials> AccessTokenCredentials(
    const grpc::string& access_token) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapCallCredentials(
      grpc_access_token_credentials_create(access_token.c_str(), nullptr));
}

// Builds IAM credentials.
std::shared_ptr<CallCredentials> GoogleIAMCredentials(
    const grpc::string& authorization_token,
    const grpc::string& authority_selector) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  return WrapCallCredentials(grpc_google_iam_credentials_create(
      authorization_token.c_str(), authority_selector.c_str(), nullptr));
}

// Combines one channel credentials and one call credentials into a channel
// composite credentials.
std::shared_ptr<ChannelCredentials> CompositeChannelCredentials(
    const std::shared_ptr<ChannelCredentials>& channel_creds,
    const std::shared_ptr<CallCredentials>& call_creds) {
  // Note that we are not saving shared_ptrs to the two credentials passed in
  // here. This is OK because the underlying C objects (i.e., channel_creds and
  // call_creds) into grpc_composite_credentials_create will see their refcounts
  // incremented.
  SecureChannelCredentials* s_channel_creds =
      channel_creds->AsSecureCredentials();
  SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials();
  if (s_channel_creds && s_call_creds) {
    return WrapChannelCredentials(grpc_composite_channel_credentials_create(
        s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(), nullptr));
  }
  return nullptr;
}

std::shared_ptr<CallCredentials> CompositeCallCredentials(
    const std::shared_ptr<CallCredentials>& creds1,
    const std::shared_ptr<CallCredentials>& creds2) {
  SecureCallCredentials* s_creds1 = creds1->AsSecureCredentials();
  SecureCallCredentials* s_creds2 = creds2->AsSecureCredentials();
  if (s_creds1 != nullptr && s_creds2 != nullptr) {
    return WrapCallCredentials(grpc_composite_call_credentials_create(
        s_creds1->GetRawCreds(), s_creds2->GetRawCreds(), nullptr));
  }
  return nullptr;
}

std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin(
    std::unique_ptr<MetadataCredentialsPlugin> plugin) {
  grpc::GrpcLibraryCodegen init;  // To call grpc_init().
  const char* type = plugin->GetType();
  grpc::MetadataCredentialsPluginWrapper* wrapper =
      new grpc::MetadataCredentialsPluginWrapper(std::move(plugin));
  grpc_metadata_credentials_plugin c_plugin = {
      grpc::MetadataCredentialsPluginWrapper::GetMetadata,
      grpc::MetadataCredentialsPluginWrapper::Destroy, wrapper, type};
  return WrapCallCredentials(
      grpc_metadata_credentials_create_from_plugin(c_plugin, nullptr));
}

}  // namespace grpc_impl

namespace grpc {
namespace {
void DeleteWrapper(void* wrapper, grpc_error* ignored) {
  MetadataCredentialsPluginWrapper* w =
      static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
  delete w;
}
}  // namespace

void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) {
  if (wrapper == nullptr) return;
  grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
  grpc_core::ExecCtx exec_ctx;
  GRPC_CLOSURE_RUN(GRPC_CLOSURE_CREATE(DeleteWrapper, wrapper,
                                       grpc_core::Executor::Scheduler(
                                           grpc_core::ExecutorJobType::SHORT)),
                   GRPC_ERROR_NONE);
}

int MetadataCredentialsPluginWrapper::GetMetadata(
    void* wrapper, grpc_auth_metadata_context context,
    grpc_credentials_plugin_metadata_cb cb, void* user_data,
    grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
    size_t* num_creds_md, grpc_status_code* status,
    const char** error_details) {
  GPR_ASSERT(wrapper);
  MetadataCredentialsPluginWrapper* w =
      static_cast<MetadataCredentialsPluginWrapper*>(wrapper);
  if (!w->plugin_) {
    *num_creds_md = 0;
    *status = GRPC_STATUS_OK;
    *error_details = nullptr;
    return 1;
  }
  if (w->plugin_->IsBlocking()) {
    // The internals of context may be destroyed if GetMetadata is cancelled.
    // Make a copy for InvokePlugin.
    grpc_auth_metadata_context context_copy = grpc_auth_metadata_context();
    grpc_auth_metadata_context_copy(&context, &context_copy);
    // Asynchronous return.
    w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable {
      w->MetadataCredentialsPluginWrapper::InvokePlugin(
          context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr);
      grpc_auth_metadata_context_reset(&context_copy);
    });
    return 0;
  } else {
    // Synchronous return.
    w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status,
                    error_details);
    return 1;
  }
}

namespace {

void UnrefMetadata(const std::vector<grpc_metadata>& md) {
  for (auto it = md.begin(); it != md.end(); ++it) {
    grpc_slice_unref(it->key);
    grpc_slice_unref(it->value);
  }
}

}  // namespace

void MetadataCredentialsPluginWrapper::InvokePlugin(
    grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb,
    void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md,
    grpc_status_code* status_code, const char** error_details) {
  std::multimap<grpc::string, grpc::string> metadata;

  // const_cast is safe since the SecureAuthContext only inc/dec the refcount
  // and the object is passed as a const ref to plugin_->GetMetadata.
  SecureAuthContext cpp_channel_auth_context(
      const_cast<grpc_auth_context*>(context.channel_auth_context));

  Status status = plugin_->GetMetadata(context.service_url, context.method_name,
                                       cpp_channel_auth_context, &metadata);
  std::vector<grpc_metadata> md;
  for (auto it = metadata.begin(); it != metadata.end(); ++it) {
    grpc_metadata md_entry;
    md_entry.key = SliceFromCopiedString(it->first);
    md_entry.value = SliceFromCopiedString(it->second);
    md_entry.flags = 0;
    md.push_back(md_entry);
  }
  if (creds_md != nullptr) {
    // Synchronous return.
    if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) {
      *num_creds_md = 0;
      *status_code = GRPC_STATUS_INTERNAL;
      *error_details = gpr_strdup(
          "blocking plugin credentials returned too many metadata keys");
      UnrefMetadata(md);
    } else {
      for (const auto& elem : md) {
        creds_md[*num_creds_md].key = elem.key;
        creds_md[*num_creds_md].value = elem.value;
        creds_md[*num_creds_md].flags = elem.flags;
        ++(*num_creds_md);
      }
      *status_code = static_cast<grpc_status_code>(status.error_code());
      *error_details =
          status.ok() ? nullptr : gpr_strdup(status.error_message().c_str());
    }
  } else {
    // Asynchronous return.
    cb(user_data, md.empty() ? nullptr : &md[0], md.size(),
       static_cast<grpc_status_code>(status.error_code()),
       status.error_message().c_str());
    UnrefMetadata(md);
  }
}

MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper(
    std::unique_ptr<MetadataCredentialsPlugin> plugin)
    : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {}

}  // namespace grpc


text:
namespace arangodb {

class ClusterInfo;

namespace velocypack {
class Builder;
}

class LogicalCollection;

namespace cluster {

class ShardDistributionReporter {
 public:
  ShardDistributionReporter(ClusterInfo* ci, network::Sender sender);

  ~ShardDistributionReporter();

  /// @brief helper function to create an instance of the ShardDistributionReporter
  static std::shared_ptr<ShardDistributionReporter> instance(application_features::ApplicationServer&);

  /// @brief fetch distribution for a single collections in db
  void getCollectionDistributionForDatabase(std::string const& dbName,
                                            std::string const& colName,
                                            arangodb::velocypack::Builder& result);

  /// @brief fetch distributions for all collections in db
  void getDistributionForDatabase(std::string const& dbName,
                                  arangodb::velocypack::Builder& result);

 private:
  /// @brief internal helper function to fetch distributions
  void getCollectionDistribution(
      std::string const& dbName,
      std::vector<std::shared_ptr<LogicalCollection>> const& cols,
      arangodb::velocypack::Builder& result,
      bool progress);

  bool testAllShardsInSync(std::string const& dbName, LogicalCollection const* col,
                           std::unordered_map<std::string, std::vector<std::string>> const* allShards);

  void helperDistributionForDatabase(
      std::string const& dbName, arangodb::velocypack::Builder& result,
      std::queue<std::shared_ptr<LogicalCollection>>& todoSyncStateCheck, double endtime,
      std::unordered_map<std::string, std::string>& aliases, bool progress);

 private:
  ClusterInfo* _ci;
  network::Sender _send;
};
}  // namespace cluster
}  // namespace arangodb


text:
<?php
/**
 * Created by PhpStorm
 * Date: 08/01/2017
 * Time: 22:09
 * Author: Daniel Simangunsong
 *
 * Calm seas, never make skill full sailors
 */

namespace Webarq\Manager\HTML\Table\Driver;

use DB;
use Illuminate\Pagination\LengthAwarePaginator;

class PaginatorManager extends DriverAbstractManager
{
    /**
     * @var \Illuminate\Database\Query\Builder
     */
    protected $builder;

    /**
     * @var null|number
     */
    protected $limit;

    /**
     * @var LengthAwarePaginator
     */
    protected $get;

    /**
     * Create builder instance
     *
     * @param string $table
     * @param array $columns
     * @param int|number $limit
     */
    public function __construct($table, $columns = [], $limit = 2)
    {
        $this->builder = DB::table($table)->select($columns);

        $this->limit = $limit;
    }

    /**
     * @inheritdoc
     */
    public function sampling()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function getRows()
    {
        $this->get = $this->builder->paginate($this->limit);

        if ($this->get->count()) {
            $data = $this->get->toArray();
            foreach ($data['data'] as &$item) {
                $item = (array) $item;
            }

            return $data['data'];
        }

        return [];
    }

    /**
     * @param null|string $view
     * @return string
     */
    public function paginator($view = null)
    {
        if ($this->get instanceof LengthAwarePaginator) {
            return $this->get->render($view);
        }
    }
}


text:
package org.sikuli.script;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

class FinderTestImage {

   File file;
   BufferedImage image;
   BufferedImage getImage() throws IOException{
      if (image == null){
         image = ImageIO.read(file);
      }
      return image;
   }

   String getScreenImageFilename(){
      return file.getAbsolutePath();
   }

   public String toString(){
      return file.getParentFile().getName();
   }

   final static String ROOT = "test-res/cv";

   private ArrayList<FinderTestTarget> testTargets = new  ArrayList<FinderTestTarget>();
   ArrayList<FinderTestTarget> getTestTargets(){
      return testTargets;
   }

   FinderTestTarget getTestTarget(int index) {
      return testTargets.get(index);
   }

   public FinderTestImage(String name){
      File rootDir = new File(ROOT);

      File testcaseDir = new File(rootDir, name);

      file = new File(testcaseDir, "screen.png");
      File[] targetFiles = testcaseDir.listFiles(new FilenameFilter(){
         public boolean accept(File dir, String name) {
            return name.startsWith("target");
         }
      });

      for (File targetFile : targetFiles){
         FinderTestTarget testTarget = new FinderTestTarget(this,targetFile);
         testTargets.add(testTarget);
      }

   }

   static FinderTestImage createFromDirectory(String name){
      return new FinderTestImage(name);
   }

}


text:
# Video Tutorials

I'm in the midst of an install and walk-through on Timber, here are the screencasts thus far:

### 1. Install Timber

#### Option 1: Via GitHub (for developers)

##### 1) Navigate to your WordPress plugins directory
	$ cd ~/Sites/mywordpress/wp-content/plugins

##### 2) Use git to grab the repo
	$ git clone git@github.com:jarednova/timber.git

##### 3) Use [Composer](https://getcomposer.org/doc/00-intro.md) to download the dependencies (Twig, etc.)
	$ cd timber
	$ composer install

#### Option 2: Via Composer (for developers)

##### 1) Navigate to your WordPress plugins directory
    $ cd ~/Sites/mywordpress/wp-content/plugins

##### 2) Use [Composer](https://getcomposer.org/doc/00-intro.md) to create project and download the dependencies (Twig, etc.)
    $ composer create-project --no-dev jarednova/timber ./timber

#### Option 3: Via WordPress plugins directory (for non-developers)

##### If you'd prefer one-click installation, you should use the [WordPress.org](http://wordpress.org/plugins/timber-library/) version.

* * *

Now just activate in your WordPress admin screen. Inside of the timber directory there's a timber-starter-theme. To use this move it into your `themes` directory (probably want to rename it too) and select it.

* * *

### 2. Including a Twig template and sending data
[![Installing Timber](http://img.youtube.com/vi/SlMonnwVi5M/0.jpg)](http://www.youtube.com/watch?v=SlMonnwVi5M)

In which we use an existing WordPress template and implement a very simple Timber usage.

Here's the relevant code:

```php
<?php
/* index.php */
$context = array();
$context['headline'] = 'Welcome to my new Timber Blog!';
Timber::render('welcome.twig', $context);
```

```twig
{# welcome.twig #}
<section class="welcome-block">
	<div class="inner">
		<h3>{{headline}}</h3>
		<p>This will be a superb blog, I will inform you every day</p>
	</div>
</section>
```
* * *
### 3. Connecting Twig to your WordPress Admin
[![Connecting Timber](http://img.youtube.com/vi/C7HtYkaG2DQ/0.jpg)](http://www.youtube.com/watch?v=C7HtYkaG2DQ)

```php
<?php
$context = array();
$context['welcome'] = Timber::get_post(56);
Timber::render('welcome.twig', $context);
```

```twig
<section class="welcome-block">
	<div class="inner">
		<h3>{{welcome.post_title}}</h3>
		<p>{{welcome.get_content}}</p>
		<p>Follow me on <a href="https://twitter.com/{{welcome.twitter_handle}}" target="_blank">Twitter!</a></p>
	</div>
</section>
```
* * *
### 4. Converting HTML to Twig Templates
[![Connecting HTML Templates](http://img.youtube.com/vi/BxazrNBLK-0/0.jpg)](http://www.youtube.com/watch?v=BxazrNBLK-0)

```php
<?php
$context['posts'] = Timber::get_posts();
Timber::render('home-main.twig', $context);
```

```twig
{# home-main.twig #}
{% for post in posts %}
    {% include "tz-post.twig" %}
{% endfor %}
```

* * *

### 5. Using Custom Post Types with Timber + Twig

[![Using Custom Post Types with Timber](http://img.youtube.com/vi/19T0MStDLSQ/0.jpg)](http://www.youtube.com/watch?v=19T0MStDLSQ)

```twig
{# home-main.twig #}
{% for post in posts %}
	{# you can send includes an array, in order of precedence #}
	{% include ["tz-"~post.post_type~".twig", "tz-post.twig"] %}
{% endfor %}
```

```twig
{# tz-recipe.twig #}
<article id="post-{{post.ID}}" class="post-{{post.ID}} {{post.post_type}} type-{{post.post_type}} status-publish hentry">
	{% if post.get_thumbnail %}
		<img src="{{post.get_thumbnail.get_src|resize(600, 300)}}" />
	{% endif %}
	<h2>{{post.post_title}}</h2>
	<div class="post-body">
		{{post.get_content}}
	</div>
</article>
```
* * *
### 6. Extending Templates
_Todo: Record Screencast showing this_

This is a **really** important concept for DRY. I'll show how to create a base template that can power your site:

##### Create a `base.twig` file:

```twig
{# base.twig #}
{% include "html-header.twig" %}
{% block head %}
	<!-- This is where you'll put template-specific stuff that needs to go in the head tags like custom meta tags, etc. -->
{% endblock %}
</head>
<body class="{{body_class}}">
{% block content %}
	<!-- The template's main content will go here. -->
{% endblock %}
{% include "footer.twig" %}
{{wp_footer}}
</body>
</html>
```

##### You can use this in a custom `single.twig` file:

```twig
{# single.twig #}
{% extends "base.twig" %}
{% block head %}
	<meta property="og:title" value="{{post.title}}" />
{% endblock %}
{% block content %}
	<div class="main">
		<h1>{{post.title}}</h1>
		<p>{{post.get_content}}</p>
	</div>
{% endblock %}
```


text:
/**
 * Creates a new, empty double pane controller.
 * @constructor
 * @class
 * This class manages the two-pane view. The top pane contains a list view of
 * items, and the bottom pane contains the selected item content.
 *
 * @author Parag Shah
 *
 * @param {DwtControl}					container					the containing shell
 * @param {ZmApp}						mailApp						the containing application
 * @param {constant}					type						type of controller
 * @param {string}						sessionId					the session id
 * @param {ZmSearchResultsController}	searchResultsController		containing controller
 *
 * @extends		ZmMailListController
 */
ZmDoublePaneController = function(container, mailApp, type, sessionId, searchResultsController) {

	if (arguments.length == 0) { return; }

	ZmMailListController.apply(this, arguments);

	if (this.supportsDnD()) {
		this._dragSrc = new DwtDragSource(Dwt.DND_DROP_MOVE);
		this._dragSrc.addDragListener(this._dragListener.bind(this));
	}

	this._listSelectionShortcutDelayAction = new AjxTimedAction(this, this._listSelectionTimedAction);
	this._listeners[ZmOperation.KEEP_READING] = this._keepReadingListener.bind(this);
};

ZmDoublePaneController.prototype = new ZmMailListController;
ZmDoublePaneController.prototype.constructor = ZmDoublePaneController;

ZmDoublePaneController.prototype.isZmDoublePaneController = true;
ZmDoublePaneController.prototype.toString = function() { return "ZmDoublePaneController"; };

ZmDoublePaneController.LIST_SELECTION_SHORTCUT_DELAY = 300;

ZmDoublePaneController.RP_IDS = [ZmSetting.RP_BOTTOM, ZmSetting.RP_RIGHT, ZmSetting.RP_OFF];

ZmDoublePaneController.DEFAULT_TAB_TEXT = ZmMsg.conversation;

/**
 * Displays the given list of mail items in a two-pane view where one pane shows the list
 * and the other shows the currently selected mail item (msg or conv). This method takes
 * care of displaying the list. Displaying an item is typically handled via selection.
 *
 * @param {ZmSearchResults}	results		the current search results
 * @param {ZmMailList}		mailList	list of mail items
 * @param {AjxCallback}		callback	the client callback
 * @param {Boolean}			markRead	if true, mark msg read
 *
 */
ZmDoublePaneController.prototype.show =
function(results, mailList, callback, markRead) {

	ZmMailListController.prototype.show.call(this, results);

	var mlv = this._listView[this._currentViewId];

	// if search was run as a result of a <refresh> block rather than by the user, preserve
	// what's in the reading pane as long as it's still in the list of results
	var s = results && results.search;
	var refreshSelItem = (s && s.isRefresh && mlv && mlv.hasItem(s.selectedItem) && s.selectedItem);
	if (this._doublePaneView) {
		if (!refreshSelItem) {
			this._doublePaneView._itemView.reset();
		}
	}
	this.setList(mailList);
	this._setup(this._currentViewId);
	mlv = this._listView[this._currentViewId]; //might have been created in the _setup call
	mlv.reset(); //called to reset the groups (in case "group by" is used, to clear possible previous items in it - bug 77154

	this._displayResults(this._currentViewId, null, refreshSelItem);

	if (refreshSelItem) {
		mlv.setSelection(refreshSelItem, true);
	}
	else {
		var dpv = this._doublePaneView;
		var readingPaneOn = this.isReadingPaneOn();
		if (dpv.isReadingPaneVisible() != readingPaneOn) {
			dpv.setReadingPane();
		}
		// clear the item view, unless it's showing something selected
		if (!this._itemViewCurrent()) {
			dpv.clearItem();
		}
	}

	if (callback) {
		callback.run();
	}
};

// returns true if the item shown in the reading pane is selected in the list view
ZmDoublePaneController.prototype._itemViewCurrent =
function() {

	var dpv = this._doublePaneView;
	var mlv = dpv._mailListView;
	mlv._restoreState();
	var item = dpv.getItem();
	if (item) {
		var sel = mlv.getSelection();
		for (var i = 0, len = sel.length; i < len; i++) {
			var listItem = sel[i];
			if (listItem.id == item.id) {
				return true;
			}
		}
	}
	return false;
};

ZmDoublePaneController.prototype.switchView =
function(view, force) {
	if (view == ZmSetting.RP_OFF ||	view == ZmSetting.RP_BOTTOM || view == ZmSetting.RP_RIGHT) {
		this._mailListView._colHeaderActionMenu = null;
		var oldView = this._getReadingPanePref();
		if (view != oldView) {
			this._setReadingPanePref(view);
			this._doublePaneView.setReadingPane();
		}
	} else {
		ZmMailListController.prototype.switchView.apply(this, arguments);
	}
	this._resetNavToolBarButtons();
};

/**
 * Clears the conversation view, which actually just clears the message view.
 */
ZmDoublePaneController.prototype.reset =
function() {
	if (this._doublePaneView) {
		this._doublePaneView.reset();
	}
	var lv = this._listView[this._currentViewId];
	if (lv) {
		lv._itemToSelect = lv._selectedItem = null;
	}
};

ZmDoublePaneController.prototype._handleResponseSwitchView =
function(item) {
	this._doublePaneView.setItem(item);
};

// called after a delete has occurred.
// Return value indicates whether view was popped as a result of a delete
ZmDoublePaneController.prototype.handleDelete =
function() {
	return false;
};

ZmDoublePaneController.prototype.handleKeyAction =
function(actionCode, ev) {

	DBG.println(AjxDebug.DBG3, "ZmDoublePaneController.handleKeyAction");
	var lv = this._listView[this._currentViewId];

	switch (actionCode) {

		case DwtKeyMap.SELECT_NEXT:
		case DwtKeyMap.SELECT_PREV:
			if (lv) {
				return lv.handleKeyAction(actionCode, ev);
			}
			break;

		default:
			return ZmMailListController.prototype.handleKeyAction.apply(this, arguments);
	}
	return true;
};

// Private and protected methods

ZmDoublePaneController.prototype._createDoublePaneView =
function() {
	// overload me
};

// Creates the conv view, which is not a standard list view (it's a two-pane
// sort of thing).
ZmDoublePaneController.prototype._initialize =
function(view) {
	// set up double pane view (which creates the MLV and MV)
	if (!this._doublePaneView){
		var dpv = this._doublePaneView = this._createDoublePaneView();
		this._mailListView = dpv.getMailListView();
		dpv.addInviteReplyListener(this._inviteReplyListener);
		dpv.addShareListener(this._shareListener);
		dpv.addSubscribeListener(this._subscribeListener);
	}

	ZmMailListController.prototype._initialize.call(this, view);
};

ZmDoublePaneController.prototype._initializeNavToolBar =
function(view) {
	var toolbar = this._toolbar[view];
	this._itemCountText[ZmSetting.RP_BOTTOM] = toolbar.getButton(ZmOperation.TEXT);
	if (AjxEnv.isFirefox) {
		this._itemCountText[ZmSetting.RP_BOTTOM].setScrollStyle(Dwt.CLIP);
	}
};

ZmDoublePaneController.prototype._getRightSideToolBarOps =
function() {
	var list = [];
	if (appCtxt.isChildWindow) {
		return list;
	}
	list.push(ZmOperation.KEEP_READING);
	list.push(ZmOperation.VIEW_MENU);
	return list;
};

ZmDoublePaneController.prototype._getActionMenuOps =
function() {
	var list = this._flagOps();
	list.push(ZmOperation.SEP);
	list = list.concat(this._msgOps());
    list.push(ZmOperation.REDIRECT);
    list.push(ZmOperation.EDIT_AS_NEW);		// bug #28717
	list.push(ZmOperation.SEP);
	list = list.concat(this._standardActionMenuOps());
	if (!appCtxt.isChildWindow && appCtxt.get(ZmSetting.DETACH_MAILVIEW_ENABLED)) {
		list.push(ZmOperation.SEP, ZmOperation.DETACH);
	}
	list.push(ZmOperation.SHOW_ORIG);
	if (this.getCurrentViewType() == ZmId.VIEW_TRAD) {
		list.push(ZmOperation.SHOW_CONV);
	}
	if (appCtxt.get(ZmSetting.FILTERS_ENABLED)) {
		list.push(ZmOperation.ADD_FILTER_RULE);
	}
    if(appCtxt.get(ZmSetting.CALENDAR_ENABLED)) {
        list.push(ZmOperation.CREATE_APPT);
    }
    if(appCtxt.get(ZmSetting.TASKS_ENABLED)) {
        list.push(ZmOperation.CREATE_TASK);
    }
    //list.push(ZmOperation.QUICK_COMMANDS);
	return list;
};

// Returns the already-created message list view.
ZmDoublePaneController.prototype._createNewView =
function() {
	if (this._mailListView && this._dragSrc) {
		this._mailListView.setDragSource(this._dragSrc);
	}
	return this._mailListView;
};

/**
 * Returns the double-pane view.
 *
 * @return {ZmDoublePaneView}	double-pane view
 */
ZmDoublePaneController.prototype.getCurrentView =
function() {
	return this._doublePaneView;
};
ZmDoublePaneController.prototype.getReferenceView = ZmDoublePaneController.prototype.getCurrentView;

/**
 * Returns the item view.
 *
 * @return {ZmMailItemView}	item view
 */
ZmDoublePaneController.prototype.getItemView =
function() {
	return this._doublePaneView && this._doublePaneView._itemView;
};

ZmDoublePaneController.prototype._getTagMenuMsg =
function(num) {
	return AjxMessageFormat.format(ZmMsg.tagMessages, num);
};

ZmDoublePaneController.prototype._getMoveDialogTitle =
function(num) {
	return AjxMessageFormat.format(ZmMsg.moveMessages, num);
};

// Add reading pane to focus ring
ZmDoublePaneController.prototype._initializeTabGroup =
function(view) {
	if (this._tabGroups[view]) { return; }

	ZmListController.prototype._initializeTabGroup.apply(this, arguments);
	if (!AjxEnv.isIE) {
		this._tabGroups[view].addMember(this.getCurrentView().getItemView());
	}
};

ZmDoublePaneController.prototype._setViewContents =
function(view) {
	this._doublePaneView.setList(this._list);
};

ZmDoublePaneController.prototype._displayItem =
function(item) {

	if (!item._loaded) { return; }

	// cancel timed mark read action on previous msg
	if (appCtxt.markReadActionId > 0) {
		AjxTimedAction.cancelAction(appCtxt.markReadActionId);
		appCtxt.markReadActionId = -1;
	}

	this._doublePaneView.setItem(item);
	this._handleMarkRead(item);
	this._curItem = item;
};
ZmDoublePaneController.prototype._displayMsg = ZmDoublePaneController.prototype._displayItem;

ZmDoublePaneController.prototype._markReadAction =
function(msg) {
	this._doMarkRead([msg], true);
};

ZmDoublePaneController.prototype._preHideCallback =
function() {
	// cancel timed mark read action on view change
	if (appCtxt.markReadActionId > 0) {
		AjxTimedAction.cancelAction(appCtxt.markReadActionId);
		appCtxt.markReadActionId = -1;
	}
	return ZmController.prototype._preHideCallback.call(this);
};

// Adds a "Reading Pane" checked menu item to a view menu
ZmDoublePaneController.prototype._setupReadingPaneMenuItems =
function(view, menu, checked) {

	if (menu.getItemCount() > 0) {
		new DwtMenuItem({parent:menu, style:DwtMenuItem.SEPARATOR_STYLE});
	}

	var miParams = {text:ZmMsg.readingPaneAtBottom, style:DwtMenuItem.RADIO_STYLE, radioGroupId:"RP"};
	var ids = ZmDoublePaneController.RP_IDS;
	var pref = this._getReadingPanePref();
	for (var i = 0; i < ids.length; i++) {
		var id = ids[i];
		if (!menu._menuItems[id]) {
			miParams.text = ZmMailListController.READING_PANE_TEXT[id];
			miParams.image = ZmMailListController.READING_PANE_ICON[id];
			var mi = menu.createMenuItem(id, miParams);
			mi.setData(ZmOperation.MENUITEM_ID, id);
			mi.addSelectionListener(this._listeners[ZmOperation.VIEW]);
			if (id == pref) {
				mi.setChecked(true, true);
			}
		}
	}
};

ZmDoublePaneController.prototype._displayResults =
function(view, newTab, refreshSelItem) {

	var elements = this.getViewElements(view, this._doublePaneView);

	if (!refreshSelItem) {
		this._doublePaneView.setReadingPane();
	}

	var tabId = newTab && Dwt.getNextId();
	this._setView({ view:		view,
					noPush:		this.isSearchResults,
					viewType:	this._currentViewType,
					elements:	elements,
					hide:		this._elementsToHide,
					tabParams:	newTab && this._getTabParams(tabId, this._tabCallback.bind(this)),
					isAppView:	this._isTopLevelView()});
	if (this.isSearchResults) {
		// if we are switching views, make sure app view mgr is up to date on search view's components
		appCtxt.getAppViewMgr().setViewComponents(this.searchResultsController.getCurrentViewId(), elements, true);
	}
	this._resetNavToolBarButtons(view);

	if (newTab) {
		var buttonText = (this._conv && this._conv.subject) ? this._conv.subject.substr(0, ZmAppViewMgr.TAB_BUTTON_MAX_TEXT) : ZmDoublePaneController.DEFAULT_TAB_TEXT;
		var avm = appCtxt.getAppViewMgr();
		avm.setTabTitle(view, buttonText);
	}

	// always allow derived classes to reset size after loading
	var sz = this._doublePaneView.getSize();
	this._doublePaneView._resetSize(sz.x, sz.y);
};

ZmDoublePaneController.prototype._getTabParams =
function(tabId, tabCallback) {
	return {
		id:				tabId,
		image:			"ConvView",
		textPrecedence:	85,
		tooltip:		ZmDoublePaneController.DEFAULT_TAB_TEXT,
		tabCallback:	tabCallback
	};
};

/**
 * Loads and displays the given message. If the message was unread, it gets marked as
 * read, and the conversation may be marked as read as well. Note that we request no
 * busy overlay during the SOAP call - that's so that a subsequent click within the
 * double-click threshold can be processed. Otherwise, it's very difficult to generate
 * a double click because the first click triggers a SOAP request and the ensuing busy
 * overlay blocks the receipt of the second click.
 *
 * @param msg	[ZmMailMsg]		msg to load
 *
 * @private
 */
ZmDoublePaneController.prototype._doGetMsg =
function(msg) {
	if (!msg) { return; }
	if (msg.id == this._pendingMsg) { return; }

	msg._loadPending = true;
	this._pendingMsg = msg.id;
	var respCallback = new AjxCallback(this, this._handleResponseDoGetMsg, msg);
	msg.load({callback:respCallback, noBusyOverlay:true});
};

ZmDoublePaneController.prototype._handleResponseDoGetMsg =
function(msg) {
	if (this._pendingMsg && (msg.id != this._pendingMsg)) { return; }
	msg._loadPending = false;
	this._pendingMsg = null;
	this._doublePaneView.setItem(msg);
};

ZmDoublePaneController.prototype._resetOperations =
function(parent, num) {
	ZmMailListController.prototype._resetOperations.call(this, parent, num);
	var isDraft = this.isDraftsFolder();
	if (num == 1) {
		var item = this._mailListView.getSelection()[0];
		if (item) {
			isDraft = item.isDraft;
		}
		parent.enable(ZmOperation.SHOW_ORIG, true);
		if (appCtxt.get(ZmSetting.FILTERS_ENABLED)) {
			var isSyncFailuresFolder = this.isSyncFailuresFolder();
			parent.enable(ZmOperation.ADD_FILTER_RULE, !isSyncFailuresFolder);
		}
	}

	parent.enable(ZmOperation.DETACH, (appCtxt.get(ZmSetting.DETACH_MAILVIEW_ENABLED) && num == 1 && !isDraft));
	parent.enable(ZmOperation.TEXT, true);
	parent.enable(ZmOperation.KEEP_READING, this._keepReading(true));
};

ZmDoublePaneController.prototype._resetOperation =
function(parent, op, num) {
	if (op == ZmOperation.KEEP_READING) {
		parent.enable(ZmOperation.KEEP_READING, this._keepReading(true));
	}
};

// top level view means this view is allowed to get shown when user clicks on
// app icon in app toolbar - overload to not allow this.
ZmDoublePaneController.prototype._isTopLevelView =
function() {
	var sessionId = this.getSessionId();
	return (!sessionId || (sessionId == ZmApp.MAIN_SESSION));
};

// All items in the list view are gone - show "No Results" and clear reading pane
ZmDoublePaneController.prototype._handleEmptyList =
function(listView) {
	this.reset();
	ZmMailListController.prototype._handleEmptyList.apply(this, arguments);
};

// List listeners

// Clicking on a message in the message list loads and displays it.
ZmDoublePaneController.prototype._listSelectionListener =
function(ev) {

	var handled = ZmMailListController.prototype._listSelectionListener.call(this, ev);

	var currView = this._listView[this._currentViewId];

	if (!handled && ev.detail == DwtListView.ITEM_DBL_CLICKED) {
		var item = ev.item;
		if (!item) { return; }

		var cs = appCtxt.isOffline && appCtxt.getCurrentSearch();
		if (cs && cs.isMultiAccount()) {
			appCtxt.accountList.setActiveAccount(item.getAccount());
		}

		var div = this._mailListView.getTargetItemDiv(ev);
		this._mailListView._itemSelected(div, ev);

		if (appCtxt.get(ZmSetting.SHOW_SELECTION_CHECKBOX)) {
			this._mailListView.setSelectionHdrCbox(false);
		}

		var respCallback = new AjxCallback(this, this._handleResponseListSelectionListener, item);
		var folder = appCtxt.getById(item.getFolderId());
		if (item.isDraft && folder && folder.id == ZmFolder.ID_DRAFTS && (!folder || !folder.isReadOnly())) {
			this._doAction({ev:ev, action:ZmOperation.DRAFT});
			return true;
		} else if (appCtxt.get(ZmSetting.OPEN_MAIL_IN_NEW_WIN)) {
			this._detachListener(null, respCallback);
			return true;
		} else {
			return false;
		}
	} else if (!handled) {
		if (this.isReadingPaneOn()) {
			// Give the user a chance to zip around the list view via shortcuts without having to
			// wait for each successively selected msg to load, by waiting briefly for more list
			// selection shortcut actions. An event will have the 'kbNavEvent' property set if it's
			// the result of a shortcut.
			if (ev.kbNavEvent && ZmDoublePaneController.LIST_SELECTION_SHORTCUT_DELAY) {
				if (this._listSelectionShortcutDelayActionId) {
					AjxTimedAction.cancelAction(this._listSelectionShortcutDelayActionId);
				}
				this._listSelectionShortcutDelayActionId = AjxTimedAction.scheduleAction(this._listSelectionShortcutDelayAction,
																						 ZmDoublePaneController.LIST_SELECTION_SHORTCUT_DELAY);
			} else {
				this._setSelectedItem();
			}
			return true;
		} else {
			var msg = currView.getSelection()[0];
			if (msg) {
				this._doublePaneView.resetMsg(msg);
			}
		}
	}
	return handled;
	DBG.timePt("***** CONV: msg selection");
};

ZmDoublePaneController.prototype._handleResponseListSelectionListener =
function(item) {
	if (item.type == ZmItem.MSG && item._loaded && item.isUnread &&
		(appCtxt.get(ZmSetting.MARK_MSG_READ) == ZmSetting.MARK_READ_NOW)) {

		this._list.markRead([item], true);
	}
	// make sure correct msg is displayed in msg pane when user returns
	this._setSelectedItem();
};

ZmDoublePaneController.prototype._listSelectionTimedAction =
function() {
	if (this._listSelectionShortcutDelayActionId) {
		AjxTimedAction.cancelAction(this._listSelectionShortcutDelayActionId);
	}
	this._setSelectedItem();
};

/**
 * Handles selection of a row by loading the item.
 *
 * @param {hash}	params		params for loading the item
 *
 * @private
 */
ZmDoublePaneController.prototype._setSelectedItem =
function(params) {
	var selCnt = this._listView[this._currentViewId].getSelectionCount();
	if (selCnt == 1) {
		var respCallback = this._handleResponseSetSelectedItem.bind(this);
		this._getLoadedMsg(params, respCallback);
	}
};

ZmDoublePaneController.prototype._handleResponseSetSelectedItem =
function(msg) {

	if (msg) {
		// bug 41196
		if (appCtxt.isOffline) {
			// clear the new-mail badge every time user reads a msg regardless
			// of number of unread messages across all accounts
			this._app.clearNewMailBadge();

			// offline mode, reset new mail notifier if user reads a msg from that account
			var acct = msg.getAccount();

			// bug: 46873 - set active account when user clicks on item w/in cross-account search
			var cs = appCtxt.getCurrentSearch();
			if (cs && cs.isMultiAccount()) {
				var active = acct || appCtxt.accountList.defaultAccount
				appCtxt.accountList.setActiveAccount(active);
			}

			if (acct && acct.inNewMailMode) {
				acct.inNewMailMode = false;
				var allContainers = appCtxt.getOverviewController()._overviewContainer;
				for (var i in allContainers) {
					allContainers[i].updateAccountInfo(acct, true, true);
				}
			}
		}

		// make sure list view has this msg
		var lv = this._listView[this._currentViewId];
		var id = (lv.type == ZmItem.CONV && msg.type == ZmItem.MSG) ? msg.cid : msg.id;
		if (lv.hasItem(id)) {
			this._displayMsg(msg);
		}
	}
};

ZmDoublePaneController.prototype._listActionListener =
function(ev) {
	ZmMailListController.prototype._listActionListener.call(this, ev);

	if (!this.isReadingPaneOn()) {
		// reset current message
		var msg = this._listView[this._currentViewId].getSelection()[0];
		if (msg) {
			this._doublePaneView.resetMsg(msg);
		}
	}
};

ZmDoublePaneController.prototype._doDelete =
function(items, hardDelete, attrs, confirmDelete) {
	this._listView[this._currentViewId]._itemToSelect = this._getNextItemToSelect();
	ZmMailListController.prototype._doDelete.apply(this, arguments);
};

ZmDoublePaneController.prototype._doMove =
function(items, destinationFolder, attrs, isShiftKey) {

	// if user moves a non-selected item via DnD, don't change selection
	var dndUnselectedItem = false;
	if (items && items.length == 1) {
		var lv = this.getListView();
		var selection = lv && lv.getSelection();
		if (selection && selection.length) {
			dndUnselectedItem = true;
			var id = items[0].id;
			// AjxUtil.intersection doesn't work with objects, so check IDs
			for (var i = 0; i < selection.length; i++) {
				if (selection[i].id == id) {
					dndUnselectedItem = false;
				}
			}
		}
	}
	if (!dndUnselectedItem) {
		this._listView[this._currentViewId]._itemToSelect = this._getNextItemToSelect();
	}
	ZmMailListController.prototype._doMove.apply(this, arguments);
};

ZmDoublePaneController.prototype._keepReadingListener =
function(ev) {
	this.handleKeyAction(ZmKeyMap.KEEP_READING, ev);
};

ZmDoublePaneController.prototype._keepReading = function(ev) {};

// Set enabled state of the KEEP_READING button
ZmDoublePaneController.prototype._checkKeepReading =
function() {
	// done on timer so item view has had change to lay out and resize
	setTimeout(this._resetOperation.bind(this, this._toolbar[this._currentViewId], ZmOperation.KEEP_READING), 250);
};

ZmDoublePaneController.prototype._dragListener =
function(ev) {
	ZmListController.prototype._dragListener.call(this, ev);
	if (ev.action == DwtDragEvent.DRAG_END) {
		this._resetOperations(this._toolbar[this._currentViewId], this._doublePaneView.getSelection().length);
	}
};

ZmDoublePaneController.prototype._draftSaved =
function(msg, resp) {
	if (resp) {
		if (!msg) {
			msg = new ZmMailMsg();
		}
		msg._loadFromDom(resp);
	}
	appCtxt.cacheSet(msg.id, msg);
	this._redrawDraftItemRows(msg);
	var displayedMsg = this._doublePaneView.getMsg();
	if (displayedMsg && displayedMsg.id == msg.id) {
		this._doublePaneView.reset();
		this._doublePaneView.setItem(msg, null, true);
	}
};

ZmDoublePaneController.prototype._redrawDraftItemRows =
function(msg) {
	this._listView[this._currentViewId].redrawItem(msg);
	this._listView[this._currentViewId].setSelection(msg, true);
};

ZmDoublePaneController.prototype.selectFirstItem =
function() {
	this._doublePaneView._selectFirstItem();
};

ZmDoublePaneController.prototype._getDefaultFocusItem =
function() {
	return this.getListView();
};

/**
 * Returns the item that should be selected after a move/delete. Finds
 * the first non-selected item after the first selected item.
 *
 * @param	{hash}		omit		hash of item IDs to exclude from being next selected item
 */
ZmDoublePaneController.prototype._getNextItemToSelect =
function(omit) {

	omit = omit || {};
	var listView = this._listView[this._currentViewId];
	var numSelected = listView.getSelectionCount();
	if (numSelected) {
		var selection = listView.getSelection();
		var selIds = {};
		for (var i = 0; i < selection.length; i++) {
			selIds[selection[i].id] = true;
		}
		var setting = appCtxt.get(ZmSetting.SELECT_AFTER_DELETE);
		var goingUp = (setting == ZmSetting.DELETE_SELECT_PREV || (setting == ZmSetting.DELETE_SELECT_ADAPT &&
						(this.lastListAction == DwtKeyMap.SELECT_PREV || this.lastListAction == ZmKeyMap.PREV_UNREAD)));
		if (goingUp && (numSelected == 1)) {
			var idx = listView._getRowIndex(selection[selection.length - 1]);
			var childNodes = listView._parentEl.childNodes;
			for (var i = idx - 1; i >= 0; i--) {
				var item = listView.getItemFromElement(childNodes[i]);
				if (item && !selIds[item.id] && !omit[item.id] && !(item.cid && (selIds[item.cid] || omit[item.cid]))) {
					return item;
				}
			}
			return ZmMailListView.FIRST_ITEM;
		} else {
			var idx = listView._getRowIndex(selection[0]);
			var childNodes = listView._parentEl.childNodes;
			for (var i = idx + 1; i < childNodes.length; i++) {
				var item = listView.getItemFromElement(childNodes[i]);
				if (item && !selIds[item.id] && !omit[item.id] && !(item.cid && (selIds[item.cid] || omit[item.cid]))) {
					return item;
				}
			}
			return ZmMailListView.LAST_ITEM;
		}
	}
	return ZmMailListView.FIRST_ITEM;
};

ZmDoublePaneController.prototype._setItemCountText =
function(text) {

	text = text || this._getItemCountText();

	var rpr = (this._getReadingPanePref() == ZmSetting.RP_RIGHT);
	if (this._itemCountText[ZmSetting.RP_RIGHT]) {
		this._itemCountText[ZmSetting.RP_RIGHT].setText(rpr ? text : "");
	}
	if (this._itemCountText[ZmSetting.RP_BOTTOM]) {
		this._itemCountText[ZmSetting.RP_BOTTOM].setText(rpr ? "" : text);
	}
};

ZmDoublePaneController.prototype._postShowCallback =
function() {

	ZmMailListController.prototype._postShowCallback.apply(this, arguments);
	var dpv = this._doublePaneView;
	if (dpv && dpv.isStale && dpv._staleHandler) {
		dpv._staleHandler();
	}
};


text:
namespace bench
{
namespace tests
{

template <typename Derived> // CRTP
class test_template : public test_loop
{
public:
    class test_class : public bench::test_class
    {
    public:
        test_class()
        {
            name = Derived::name();
            description = Derived::description();
            size_dependent = Derived::size_dependent();
        }

        std::unique_ptr<test_loop> create_loop(test_config config) const override
        {
            return utils::make_unique<Derived>(config);
        }

        probe_collection create_probes(test_config config) const override
        {
            return Derived::create_probes(config);
        }
    };

    static probe_collection create_probes(test_config config)
    {
        return {};
    }

    test_template(test_config config)
        : _config(config), _prepared_iterations(static_cast<std::uint32_t>(config.iterations))
    {
    }

    void setup() override {}

    void run() override
    {
        if (_prepared_iterations > 0)
            run_n_iterations(_prepared_iterations);
        else
            run_iteration_until(clock::now() + _config.duration);
    }

    void cleanup() override {}

protected:
    template <typename Function>
    void cleanup_each(Function function)
    {
        for (auto i = 0u; i < test_loop::iterations(); i++)
        {
            function(i);
        }
    }

    template <typename Function>
    void setup_each(Function function)
    {
        if (_prepared_iterations != 0)
        {
            for (auto iteration = 0u; iteration < _prepared_iterations; ++iteration)
            {
                function(iteration);
            }
        }
        else
        {
            clock::time_point timeout = clock::now() + _config.duration;
            while (clock::now() < timeout)
            {
                function(_prepared_iterations++);
            }
        }
    }

private:
    void run_iteration_until(clock::time_point timeout)
    {
        while (clock::now() < timeout)
        {
            static_cast<Derived *>(this)->run_iteration(iterations());
            test_loop::add_iteration();
        }
    }

    void run_n_iterations(std::uint32_t count)
    {
        while (iterations() < count)
        {
            static_cast<Derived *>(this)->run_iteration(iterations());
            test_loop::add_iteration();
        }
    }

    test_config _config;
    std::uint32_t _prepared_iterations;
};

} // namespace tests
} // namespace bench


text:
<?php

error_reporting(E_STRICT | E_ALL);

// You can set the include path to src directory or reference
// DfpUser.php directly via require_once.
// $path = '/path/to/dfp_api_php_lib/src';
$path = dirname(__FILE__) . '/../../../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php';
require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php';

try {
  // Get DfpUser from credentials in "../auth.ini"
  // relative to the DfpUser.php file's directory.
  $user = new DfpUser();

  // Log SOAP XML request and response.
  $user->LogDefaults();

  // Get the LabelService.
  $labelService = $user->GetService('LabelService', 'v201403');

  // Create a statement to only select labels that are active.
  $filterStatement = new Statement(
      "WHERE isActive = true LIMIT 500");

  // Get labels by statement.
  $page = $labelService->getLabelsByStatement($filterStatement);

  if (isset($page->results)) {
    $labels = $page->results;

    // Update each local label object's description.
    foreach ($labels as $label) {
      $label->description = 'Last updated on ' . date('Ymd');
    }

    // Update the labels on the server.
    $labels = $labelService->updateLabels($labels);

    // Display results.
    if (isset($labels)) {
      foreach ($labels as $label) {
        printf("A label with ID '%s', name '%s', and description '%s' was "
            . "updated.\n", $label->id, $label->name, $label->description);
      }
    } else {
      print "No labels updated.\n";
    }
  } else {
    print "No labels found to update.\n";
  }
} catch (OAuth2Exception $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (ValidationException $e) {
  ExampleUtils::CheckForOAuth2Errors($e);
} catch (Exception $e) {
  print $e->getMessage() . "\n";
}


text:
package com.cpwr.gdo.simulator.web.security;

import org.apache.click.ActionListener;
import org.apache.click.Control;
import org.apache.click.control.Form;
import org.apache.click.control.HiddenField;
import org.apache.click.control.PasswordField;
import org.apache.click.control.Submit;
import org.apache.click.control.TextField;
import org.apache.click.extras.control.EmailField;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.cpwr.gdo.simulator.model.security.User;
import com.cpwr.gdo.simulator.service.AuthDetailsService;
import com.cpwr.gdo.simulator.web.page.BorderPage;
import com.cpwr.gdo.simulator.web.security.secure.SecurePage;

/**
 * Provides an Spring Security (ACEGI) enabled account creation page.
 */
@Component
public class CreateAccount extends BorderPage {

    private static final long serialVersionUID = 1L;

    private static final String EMAIL_PROPERTY = "email";
    private static final String FULLNAME_PROPERTY = "fullname";
    private static final String PASSWORD_PROPERTY = "password";
    private static final String USERNAME_PROPERTY = "username";

    private Form form = new Form("form");
    private TextField fullNameField = new TextField(FULLNAME_PROPERTY, "Full Name", true);
    private EmailField emailField = new EmailField(EMAIL_PROPERTY);
    private TextField userNameField = new TextField(USERNAME_PROPERTY, true);
    private PasswordField passwordField = new PasswordField("password", true);
    private PasswordField passwordAgainField = new PasswordField("passwordAgain", "Password again", true);
    private HiddenField redirectField = new HiddenField("redirect", String.class);

    @Autowired
    @Qualifier(value = "authenticationManager")
    private AuthenticationManager authenticationManager;

    @Autowired
    @Qualifier(value = "authService")
    private AuthDetailsService userService;

    // Constructor ------------------------------------------------------------

    public CreateAccount() {
        addControl(form);

        form.setDefaultFieldSize(30);

        form.add(fullNameField);
        form.add(emailField);
        form.add(userNameField);
        form.add(passwordField);
        form.add(passwordAgainField);

        Submit submit = new Submit("create");
        submit.setActionListener(new ActionListener() {
            private static final long serialVersionUID = 1L;

            public boolean onAction(Control source) {
                return onCreate();
            }
        });
        form.add(submit);

        form.add(redirectField);
    }

    // Event Handlers ---------------------------------------------------------

    @Override
    public void onInit() {
        super.onInit();

        if (getContext().isGet()) {
            redirectField.setValue(getContext().getRequestParameter("redirect"));
        }
    }

    @Override
    public String getHelpPageLink() {
        return "";
    }

    public boolean onCreate() {
        if (form.isValid()) {

            String fullName = fullNameField.getValue();
            String email = emailField.getValue();
            String username = userNameField.getValue();
            String password1 = passwordField.getValue();
            String password2 = passwordAgainField.getValue();

            if (!password1.equals(password2)) {
                passwordField.setError("Password and password again do not match");
                return true;
            }

            User user = null;

            try {
                user = (User) userService.loadUserByUsername(username);
            } catch (UsernameNotFoundException unfe) {

            }
            ;

            if (user != null) {
                userNameField.setError(getMessage("usernameExistsError"));
                return true;
            }

            // new user
            user = userService.createUser(fullName, email, username, password1);

            Authentication token = new UsernamePasswordAuthenticationToken(username, password1);
            Authentication result = authenticationManager.authenticate(token);
            SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication(result);
            SecurityContextHolder.setContext(securityContext);

            String path = redirectField.getValue();

            if (StringUtils.isNotBlank(path)) {
                setRedirect(path);
            } else {
                setRedirect(SecurePage.class);
            }
        }

        return true;
    }

}


text:
<?php
/**
 * This view is used by console/controllers/MigrateController.php
 * The following variables are available in this view:
 */
/* @var $className string the new migration class name without namespace */
/* @var $namespace string the new migration class namespace */

echo "<?php\n";
if (!empty($namespace)) {
    echo "\nnamespace {$namespace};\n";
}
?>

use yii\db\Migration;

class <?= $className ?> extends Migration
{
    public function safeUp()
    {

    }

    public function safeDown()
    {
        echo "<?= $className ?> cannot be reverted.\n";

        return false;
    }

    /*
    // Use up()/down() to run migration code without a transaction.
    public function up()
    {

    }

    public function down()
    {
        echo "<?= $className ?> cannot be reverted.\n";

        return false;
    }
    */
}