text:
package com.github.sarxos.webcam.ds.buildin;

import java.awt.Dimension;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.ComponentSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.bridj.Pointer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.sarxos.webcam.WebcamDevice;
import com.github.sarxos.webcam.WebcamDevice.BufferAccess;
import com.github.sarxos.webcam.WebcamException;
import com.github.sarxos.webcam.WebcamExceptionHandler;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.WebcamTask;
import com.github.sarxos.webcam.ds.buildin.natives.Device;
import com.github.sarxos.webcam.ds.buildin.natives.DeviceList;
import com.github.sarxos.webcam.ds.buildin.natives.OpenIMAJGrabber;

public class WebcamDefaultDevice implements WebcamDevice, BufferAccess, Runnable, WebcamDevice.FPSSource {

	/**
	 * Logger.
	 */
	private static final Logger LOG = LoggerFactory.getLogger(WebcamDefaultDevice.class);

	/**
	 * Artificial view sizes. I'm really not sure if will fit into other webcams
	 * but hope that OpenIMAJ can handle this.
	 */
	private final static Dimension[] DIMENSIONS = new Dimension[] {
		WebcamResolution.QQVGA.getSize(),
		WebcamResolution.QVGA.getSize(),
		WebcamResolution.VGA.getSize(),
	};

	private class NextFrameTask extends WebcamTask {

		private final AtomicInteger result = new AtomicInteger(0);

		public NextFrameTask(WebcamDevice device) {
			super(device);
		}

		public int nextFrame() {
			try {
				process();
			} catch (InterruptedException e) {
				LOG.debug("Image buffer request interrupted", e);
			}
			return result.get();
		}

		@Override
		protected void handle() {

			WebcamDefaultDevice device = (WebcamDefaultDevice) getDevice();
			if (!device.isOpen()) {
				return;
			}

			grabber.setTimeout(timeout);
			result.set(grabber.nextFrame());
			fresh.set(true);
		}
	}

	/**
	 * RGB offsets.
	 */
	private static final int[] BAND_OFFSETS = new int[] { 0, 1, 2 };

	/**
	 * Number of bytes in each pixel.
	 */
	private static final int[] BITS = { 8, 8, 8 };

	/**
	 * Image offset.
	 */
	private static final int[] OFFSET = new int[] { 0 };

	/**
	 * Data type used in image.
	 */
	private static final int DATA_TYPE = DataBuffer.TYPE_BYTE;

	/**
	 * Image color space.
	 */
	private static final ColorSpace COLOR_SPACE = ColorSpace.getInstance(ColorSpace.CS_sRGB);

	/**
	 * Maximum image acquisition time (in milliseconds).
	 */
	private int timeout = 5000;

	private OpenIMAJGrabber grabber = null;
	private Device device = null;
	private Dimension size = null;
	private ComponentSampleModel smodel = null;
	private ColorModel cmodel = null;
	private boolean failOnSizeMismatch = false;

	private final AtomicBoolean disposed = new AtomicBoolean(false);
	private final AtomicBoolean open = new AtomicBoolean(false);

	/**
	 * Is the last image fresh one.
	 */
	private final AtomicBoolean fresh = new AtomicBoolean(false);

	private Thread refresher = null;

	private String name = null;
	private String id = null;
	private String fullname = null;

	private long t1 = -1;
	private long t2 = -1;

	/**
	 * Current FPS.
	 */
	private volatile double fps = 0;

	protected WebcamDefaultDevice(Device device) {
		this.device = device;
		this.name = device.getNameStr();
		this.id = device.getIdentifierStr();
		this.fullname = String.format("%s %s", this.name, this.id);
	}

	@Override
	public String getName() {
		return fullname;
	}

	public String getDeviceName() {
		return name;
	}

	public String getDeviceId() {
		return id;
	}

	public Device getDeviceRef() {
		return device;
	}

	@Override
	public Dimension[] getResolutions() {
		return DIMENSIONS;
	}

	@Override
	public Dimension getResolution() {
		if (size == null) {
			size = getResolutions()[0];
		}
		return size;
	}

	@Override
	public void setResolution(Dimension size) {

		if (size == null) {
			throw new IllegalArgumentException("Size cannot be null");
		}

		if (open.get()) {
			throw new IllegalStateException("Cannot change resolution when webcam is open, please close it first");
		}

		this.size = size;
	}

	@Override
	public ByteBuffer getImageBytes() {

		if (disposed.get()) {
			LOG.debug("Webcam is disposed, image will be null");
			return null;
		}
		if (!open.get()) {
			LOG.debug("Webcam is closed, image will be null");
			return null;
		}

		// if image is not fresh, update it

		if (fresh.compareAndSet(false, true)) {
			updateFrameBuffer();
		}

		// get image buffer

		LOG.trace("Webcam grabber get image pointer");

		Pointer<Byte> image = grabber.getImage();
		fresh.set(false);

		if (image == null) {
			LOG.warn("Null array pointer found instead of image");
			return null;
		}

		int length = size.width * size.height * 3;

		LOG.trace("Webcam device get buffer, read {} bytes", length);

		return image.getByteBuffer(length);
	}

	@Override
	public void getImageBytes(ByteBuffer target) {

		if (disposed.get()) {
			LOG.debug("Webcam is disposed, image will be null");
			return;
		}
		if (!open.get()) {
			LOG.debug("Webcam is closed, image will be null");
			return;
		}

		int minSize = size.width * size.height * 3;
		int curSize = target.remaining();

		if (minSize < curSize) {
			throw new IllegalArgumentException(String.format("Not enough remaining space in target buffer (%d necessary vs %d remaining)", minSize, curSize));
		}

		// if image is not fresh, update it

		if (fresh.compareAndSet(false, true)) {
			updateFrameBuffer();
		}

		// get image buffer

		LOG.trace("Webcam grabber get image pointer");

		Pointer<Byte> image = grabber.getImage();
		fresh.set(false);

		if (image == null) {
			LOG.warn("Null array pointer found instead of image");
			return;
		}

		LOG.trace("Webcam device read buffer {} bytes", minSize);

		image = image.validBytes(minSize);
		image.getBytes(target);

	}

	@Override
	public BufferedImage getImage() {

		ByteBuffer buffer = getImageBytes();

		if (buffer == null) {
			LOG.error("Images bytes buffer is null!");
			return null;
		}

		byte[] bytes = new byte[size.width * size.height * 3];
		byte[][] data = new byte[][] { bytes };

		buffer.get(bytes);

		DataBufferByte dbuf = new DataBufferByte(data, bytes.length, OFFSET);
		WritableRaster raster = Raster.createWritableRaster(smodel, dbuf, null);

		BufferedImage bi = new BufferedImage(cmodel, raster, false, null);
		bi.flush();

		return bi;
	}

	@Override
	public void open() {

		if (disposed.get()) {
			return;
		}

		LOG.debug("Opening webcam device {}", getName());

		if (size == null) {
			size = getResolutions()[0];
		}
		if (size == null) {
			throw new RuntimeException("The resolution size cannot be null");
		}

		LOG.debug("Webcam device {} starting session, size {}", device.getIdentifierStr(), size);

		grabber = new OpenIMAJGrabber();

		// NOTE!

		// Following the note from OpenIMAJ code - it seams like there is some
		// issue on 32-bit systems which prevents grabber to find devices.
		// According to the mentioned note this for loop shall fix the problem.

		DeviceList list = grabber.getVideoDevices().get();
		for (Device d : list.asArrayList()) {
			d.getNameStr();
			d.getIdentifierStr();
		}

		boolean started = grabber.startSession(size.width, size.height, 50, Pointer.pointerTo(device));
		if (!started) {
			throw new WebcamException("Cannot start native grabber!");
		}

		LOG.debug("Webcam device session started");

		Dimension size2 = new Dimension(grabber.getWidth(), grabber.getHeight());

		int w1 = size.width;
		int w2 = size2.width;
		int h1 = size.height;
		int h2 = size2.height;

		if (w1 != w2 || h1 != h2) {

			if (failOnSizeMismatch) {
				throw new WebcamException(String.format("Different size obtained vs requested - [%dx%d] vs [%dx%d]", w1, h1, w2, h2));
			}

			Object[] args = new Object[] { w1, h1, w2, h2, w2, h2 };
			LOG.warn("Different size obtained vs requested - [{}x{}] vs [{}x{}]. Setting correct one. New size is [{}x{}]", args);

			size = new Dimension(w2, h2);
		}

		smodel = new ComponentSampleModel(DATA_TYPE, size.width, size.height, 3, size.width * 3, BAND_OFFSETS);
		cmodel = new ComponentColorModel(COLOR_SPACE, BITS, false, false, Transparency.OPAQUE, DATA_TYPE);

		LOG.debug("Initialize buffer");

		int i = 0;
		do {

			grabber.nextFrame();

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				LOG.error("Nasty interrupted exception", e);
			}

		} while (++i < 3);

		LOG.debug("Webcam device {} is now open", this);

		open.set(true);

		refresher = new Thread(this, String.format("frames-refresher-[%s]", id));
		refresher.setUncaughtExceptionHandler(WebcamExceptionHandler.getInstance());
		refresher.setDaemon(true);
		refresher.start();
	}

	@Override
	public void close() {

		if (!open.compareAndSet(true, false)) {
			return;
		}

		LOG.debug("Closing webcam device");

		grabber.stopSession();
	}

	@Override
	public void dispose() {

		if (!disposed.compareAndSet(false, true)) {
			return;
		}

		LOG.debug("Disposing webcam device {}", getName());

		close();
	}

	/**
	 * Determines if device should fail when requested image size is different
	 * than actually received.
	 *
	 * @param fail the fail on size mismatch flag, true or false
	 */
	public void setFailOnSizeMismatch(boolean fail) {
		this.failOnSizeMismatch = fail;
	}

	@Override
	public boolean isOpen() {
		return open.get();
	}

	/**
	 * Get timeout for image acquisition.
	 *
	 * @return Value in milliseconds
	 */
	public int getTimeout() {
		return timeout;
	}

	/**
	 * Set timeout for image acquisition.
	 *
	 * @param timeout the timeout value in milliseconds
	 */
	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	/**
	 * Update underlying memory buffer and fetch new frame.
	 */
	private void updateFrameBuffer() {

		LOG.trace("Next frame");

		if (t1 == -1 || t2 == -1) {
			t1 = System.currentTimeMillis();
			t2 = System.currentTimeMillis();
		}

		int result = new NextFrameTask(this).nextFrame();

		t1 = t2;
		t2 = System.currentTimeMillis();

		fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5;

		if (result == -1) {
			LOG.error("Timeout when requesting image!");
		} else if (result < -1) {
			LOG.error("Error requesting new frame!");
		}
	}

	@Override
	public void run() {

		do {

			if (Thread.interrupted()) {
				LOG.debug("Refresher has been interrupted");
				return;
			}

			if (!open.get()) {
				LOG.debug("Cancelling refresher");
				return;
			}

			updateFrameBuffer();

		} while (open.get());
	}

	@Override
	public double getFPS() {
		return fps;
	}
}


text:
/**
 * slides lateral panel
 */

cdb.admin.SlidesPanel = cdb.core.View.extend({

  className: 'slides_panel',

  template_name: 'table/views/slides/panel',

  initialize: function() {

    this.template = this.getTemplate(this.template_name);

    this.slides = this.options.slides;
    this.toggleElement = this.options.toggle;

    this.model = new cdb.core.Model({
      visible: false
    });

    this.model.bind("change:visible", this._onChangeVisible, this);

    if (!this.slides) {
      throw new Error("slides is undefined");
    }

    this._bindSlides();

  },

  _bindSlides: function() {

    this.add_related_model(this.slides);

    this.slides.bind('reset' , function() {
      this.slides.each(this._add.bind(this));
    }, this);

    this.slides.bind('remove', function() {
      this._reInitScrollpane();
    }, this);

    this.slides.bind('add', this._add, this);

  } ,

  _addAddButton: function(slide) {

    this.addSlideButton = new cdb.admin.SlideViewAdd({
      model: new cdb.core.Model()
    });

    this.addSlideButton.bind("click", function() {
      this.addSlideButton.model.set("loading", true);
      this.slides.create();
    }, this);

    this.addView(this.addSlideButton);
    this.$el.find(".scrollpane").append(this.addSlideButton.render().el);

  },

  _reInitScrollpane: function() {
    var self = this;
    setTimeout(function() {
      this.$('.scrollpane').data('jsp') && this.$('.scrollpane').data('jsp').reinitialise();
      this.$('.scrollpane.jspScrollable').css("overflow", "");
    }, 500);
  },

  _add: function(slide) {
    var v = new cdb.admin.SlideView({
      user: this.options.user,
      model: slide
    });
    // remove fake
    if (this._fakeSlide) {
      this._fakeSlide.clean();
      this._fakeSlide = null;
    }

    this._addSlideView(v);
  },

  _addSlideView: function(slideView) {
    this.addView(slideView);
    this.$el.find(".scrollpane .slides").append(slideView.render().el);

    slideView.show();
    this._reInitScrollpane();
  },

  _onChangeVisible: function() {

    var visible = this.model.get("visible")
    visible ? this._show() : this._hide();

    this.trigger("onChangeVisible", visible, this);

  },

  toggle: function() {

    var visible = !this.model.get("visible");
    this.model.set("visible", visible);

    return visible;

  },

  show: function() {
    this.model.set("visible", true);
  },

  hide: function() {
    this.model.set("visible", false);
  },

  _hide: function() {
    this.toggleElement.find("h5").html("Create");
    this.toggleElement.removeClass("active");
    this.$el.removeClass("active");
    cdb.god.trigger("closeDialogs");
  },

  _show: function() {
    this.toggleElement.find("h5").html("Hide");
    this.toggleElement.addClass("active");
    this.$el.addClass("active");
  },

  _initScrollPane: function() {

    var $scrollpane = this.$el.find(".scrollpane");
    var height      = this.$el.height();

    setTimeout(function() {
      $scrollpane.css("max-height", height - 60);
      $scrollpane.jScrollPane();
      $scrollpane.css("overflow", "");
    }, 500)

  },

  _initSortable: function() {

    var self = this;

    this.$el.find(".slides").sortable({
      axis: "y",
      update : function (event, ui) {

        var current_id = ui.item.attr("id");
        var next_id = ui.item.next() ? ui.item.next().attr("id") : null;
        //var prev_id = ui.item.prev() ? ui.item.prev().attr("id") : null;

        var slide = self.slides.get(current_id);
        slide.setNext(next_id);
        //self.trigger("on_sortable", { current: current_id, next: next_id }, self);;
      }
    });

  },

  _renderFake: function() {
    this._fakeSlide = new cdb.admin.SlideViewFake();
    this._addSlideView(this._fakeSlide);
  },

  render: function() {

    this.clearSubViews();

    this.$el.append(this.template());

    this._renderFake();

    this.slides.each(this._add.bind(this));

    this._addAddButton();
    this._initScrollPane();
    this._initSortable();

    this.slides.bind("add", function() {
      this.addSlideButton.model.set("loading", false);
    }, this);

    return this;

  }

});

/**
 * view for the fake slide. When there are no slides the UI shows one (the master one) but it's not
 * an actual slide in the server.
 */

cdb.admin.SlideViewFake = cdb.core.View.extend({

  tagName: "a",

  className: 'slide_view fake',

  template_name: 'table/views/slides/slide',

  initialize: function () {
    this.template = this.getTemplate(this.template_name);
  },

  show: function() {
    this.$el.addClass('animated bounceIn active');
  },

  render: function() {
    this.$el.attr("href", "#");
    this.$el.append(this.template({ count: 1, transition: false }));
    return this;
  }

});

/**
 * view for a single slide
 */
cdb.admin.SlideView = cdb.core.View.extend({

  tagName: "a",

  className: 'slide_view',

  template_name: 'table/views/slides/slide',

  events: {
    'click':        '_onClick',
    'click .count': '_onClick',
    'click .info':  '_onClickInfo',
    'click .close': '_onClickClose'
  },

  initialize: function () {

    this._setupModel();
    this.template = this.getTemplate(this.template_name);

  },

  _setupDropdown: function() {

    this.dropdown = new cdb.admin.TransitionDropdown({
      target: this.$el.find('.js-change-transition-method'),
      template_base: "table/views/slides/transition_dropdown",
      horizontal_position: "left",
      tick: "top",
      vertical_offset: 58,
      horizontal_offset: -145,
      vis: this.model.visualization
    });

    this.addView(this.dropdown);

    cdb.god.bind("closeDialogs", this._onHideDropdown, this);

    this.$el.append(this.dropdown.render().el);

  },

  _onHideDropdown: function() {

    this.dropdown.hide();
    this.$el.css("z-index", 1);

  },

  _setupModel: function() {

    this.model.bind('change:active', this._onChangeActive, this);
    this.model.visualization.bind('change:transition_options', this._onChangeTransitionOptions, this);
    this.model.bind('remove',        this._onDestroy, this);

    this.model.collection.bind('add remove reset change:next_id', this._onChangeCount, this);
    this.add_related_model(this.model.collection);

  },

  _onClick: function(e) {
    this.killEvent(e);
    this.model.collection.setActive(this.model);
  },

  _onClickInfo: function(e) {
    this.killEvent(e);
    this.$el.css("z-index", 100)
  },

  _onClickClose: function(e) {
    this.killEvent(e);

    var delete_confirmation = cdb.editor.ViewFactory.createDialogByTemplate('common/dialogs/confirm_delete_slide');
    delete_confirmation.ok = this.model.destroy.bind(this.model);
    delete_confirmation.appendToBody();
  },

  _onDestroy: function() {
    var self = this;

    this.hide(function() {
      self.clean();
    });

  },

  _onChangeCount: function() {
    this.$el.find(".count").html(this.model.collection.indexOf(this.model) + 1);
  },

  _onChangeTransitionOptions: function() {

    var transition_method = this._getTransitionMethod();

    this.$el.find(".js-change-transition-method").html(transition_method);

  },

  _onChangeActive: function() {

    if (this.model.isActive()) {
      this.$el.addClass("active");
    } else {
      this.$el.removeClass("active");
    }
    cdb.god.trigger("closeDialogs");

  },

  hide: function(callback) {

    this.$el
    .removeClass('animated bounceIn')
    .addClass('animated bounceOut');

    if (callback) {
      setTimeout(function() {
        callback();
      }, 500)
    }

  },

  _getTransitionMethod: function() {

    var transition = this.model.visualization.get("transition_options");
    var transition_method = "on click";

    if (transition && transition.transition_trigger === "time") {
      transition_method = (transition.time !== 1) ? transition.time + " seconds" : "1 second";
    }

    return transition_method;

  },

  show: function() {
    this.$el.addClass('animated bounceIn');
  },

  render: function() {

    this.$el.attr("href", "#");

    // TODO: remove count && get the value from the model
    var attributes = _.extend(this.model.attributes, { count: 1, transition: true, transition_method: this._getTransitionMethod() });

    this.$el.append(this.template(attributes));

    this._onChangeActive();
    this._onChangeCount();

    this._setupDropdown();

    this.$el.attr("id", this.model.get("id"))

    return this;

  }

});

cdb.admin.SlideViewAdd = cdb.admin.SlideView.extend({

  className: 'slide_view add',

  template_name: 'table/views/slides/add_slide',

  _setupModel: function() {
    this.model.bind('change:loading', this._onChangeLoading, this);
  },

  _onChangeLoading: function(e) {

    if (this.model.get("loading")) {
      this.$el.addClass("loading");
    } else {
      this.$el.removeClass("loading");
    }

  },

  _onClick: function(e) {

    e.preventDefault();
    e.stopPropagation();

    this.trigger("click", this);

  },

  render: function() {

    this.$el.attr("href", "#");

    var attributes = this.options;

    this.$el.append(this.template(attributes));

    return this;

  }

});

redpajama_set_name: RedPajamaGithub


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

    angular
        .module('app')
        .factory('search_factory', searchFactory);

    function searchFactory($http, $log) {
        return {
            status: 'idle',
            filters: [],
            query: '',
            search_type: 'q',
            result: null,
            facets: null,

            pp: [
                {value: 15, label: 'Show 15'},
                {value: 30, label: 'Show 30'},
                {value: 60, label: 'Show 60'},
                {value: 100, label: 'Show 100'}
            ],

            search_types: [
                {value: 'q', label: 'All Fields'},
                {value: 'title', label: 'Title'},
                {value: 'description', label: 'Description'},
                {value: 'identifier', label: 'Identifier'},
                {value: 'related_people', label: 'Related People'},
                {value: 'related_organisations', label: 'Related Organisations'}
            ],

            vocab_choices: [
                {value: 'anzsrc-for', label: 'ANZSRC FOR'},
                {value: 'anzsrc-for-2020', label: 'ANZSRC FOR 2020'},
                {value: 'anzsrc-seo', label: 'ANZSRC SEO'},
                {value: 'anzsrc-seo-2020', label: 'ANZSRC SEO 2020'},
                {value: 'anzsrc', label: 'ANZSRC'},
                {value: 'keywords', label: 'Keywords'},
                {value: 'scot', label: 'School of Online Thesaurus'},
                {value: 'pont', label: 'Powerhouse Museum Object Name Thesaurus'},
                {value: 'psychit', label: 'Thesaurus of Psychological Index Terms'},
                {value: 'apt', label: 'Australian Pictorial Thesaurus'},
                {value: 'lcsh', label: 'LCSH'},
                {value: 'gcmd', label: 'Global Change Master Directory Keywords'},
                {value: 'iso639-3', label: 'iso639-3 Language'}
            ],

            search_types_activities: [
                {value: 'q', label: 'All Fields'},
                {value: 'title', label: 'Title'},
                {value: 'description', label: 'Description'},
                {value: 'identifier', label: 'Identifier'},
                {value: 'institution', label: 'Institution'},
                {value: 'researcher', label: 'Researcher'}
            ],

            available_search_type: [
                'q', 'title', 'identifier', 'related_people', 'related_organisations', 'description'
            ],

            class_choices: [
                {value: 'collection', label: 'Data'},
                {value: 'party', label: 'People and Organisation'},
                {value: 'service', label: 'Services and Tools'},
                {value: 'activity', label: 'Grants and Projects'}
            ],

            default_filters: {
                'rows': 15,
                'sort': 'list_title_sort asc',
                'class': 'collection'
            },

            sort: [
                {value: 'score desc', label: 'Relevance'},
                {value: 'list_title_sort asc', label: 'Title A-Z'},
                {value: 'list_title_sort desc', label: 'Title Z-A'},
                {value: 'record_created_timestamp desc', label: 'Date Added  '}
            ],

            activity_sort: [
                {value: 'score desc', label: 'Relevance'},
                {value: 'list_title_sort asc', label: 'Title A-Z'},
                {value: 'list_title_sort desc', label: 'Title Z-A'},
                {value: 'earliest_year asc', label: 'Commencement '},
                {value: 'earliest_year desc', label: 'Commencement '},
                {value: 'latest_year asc', label: 'Completion '},
                {value: 'latest_year desc', label: 'Completion '},
                {value: 'funding_amount asc', label: 'Funding Amount '},
                {value: 'funding_amount desc', label: 'Funding Amount '}
            ],

            advanced_fields: [
                {'name': 'terms', 'display': 'Search Terms', 'active': true},
                {'name': 'collection_type', 'display': 'Type'},
                {'name': 'subject', 'display': 'Subject'},
                {'name': 'group', 'display': 'Data Provider'},
                {'name': 'access_rights', 'display': 'Access'},
                {'name': 'access_methods_ss', 'display': 'Access Method'},
                {'name': 'license_class', 'display': 'Licence'},
                {'name': 'temporal', 'display': 'Time Period'},
                {'name': 'spatial', 'display': 'Location'},
                {'name': 'review', 'display': 'Review'},
                {'name': 'help', 'display': ' Help'}
            ],

            advanced_fields_party: [
                {'name': 'terms', 'display': 'Search Terms', 'active': true},
                {'name': 'type', 'display': 'Type'},
                {'name': 'subject', 'display': 'Subject'},
                {'name': 'group', 'display': 'Data Provider'},
                {'name': 'review', 'display': 'Review'},
                {'name': 'help', 'display': ' Help'}
            ],

            advanced_fields_service: [
                {'name': 'terms', 'display': 'Search Terms', 'active': true},
                {'name': 'type', 'display': 'Type'},
                {'name': 'subject', 'display': 'Subject'},
                {'name': 'group', 'display': 'Data Provider'},
                {'name': 'spatial', 'display': 'Location'},
                {'name': 'review', 'display': 'Review'},
                {'name': 'help', 'display': ' Help'}
            ],

            advanced_fields_activity: [
                {'name': 'terms', 'display': 'Search Terms', 'active': true},
                {'name': 'type', 'display': 'Type'},
                {'name': 'activity_status', 'display': 'Status'},
                {'name': 'subject', 'display': 'Subject'},
                {'name': 'administering_institution', 'display': 'Managing Institution'},
                {'name': 'date_range', 'display': 'Date Range'},
                {'name': 'funders', 'display': 'Funder'},
                {'name': 'funding_scheme', 'display': 'Funding Scheme'},
                {'name': 'funding_amount', 'display': 'Funding Amount'},
                {'name': 'review', 'display': 'Review'},
                {'name': 'help', 'display': ' Help'}
            ],

            collection_facet_order: ['collection_type','group', 'access_rights', 'access_methods_ss','license_class','type'],
            activity_facet_order: ['type', 'activity_status', 'funding_scheme', 'administering_institution', 'funders'],

            ingest: function (hash) {
                this.filters = this.filters_from_hash(hash);
                if (this.filters.q) this.query = this.filters.q;
                var that = this;

                if (that.filters['class'] != 'activity') {
                    angular.forEach(this.search_types, function (x) {
                        var term = x.value;
                        if (that.filters.hasOwnProperty(term)) {
                            that.query = that.filters[term];
                            that.search_type = term;
                        }
                    });
                } else {
                    angular.forEach(this.search_types_activities, function (x) {
                        var term = x.value;
                        if (that.filters.hasOwnProperty(term)) {
                            that.query = that.filters[term];
                            that.search_type = term;
                        }
                    });
                }

                return this.filters;
            },

            reset: function () {
                var prev_class = this.filters['class'];
                this.filters = {q: '', 'class': prev_class};
                this.search_type = 'q';
                this.query = '';
            },

            update: function (which, what) {
                this[which] = what;
            },

            update_class: function (what) {
                this.default_filters['class'] = what;
            },

            search: function (filters) {
                filters = this.cleanFilters(filters);
                // $log.debug('search filters', filters);
                return $http.post(base_url + 'registry_object/filter', {'filters': filters}).then(function (response) {
                    if (response.data.response && response.data.responseHeader.status == 0) {
                        return response.data;
                    } else {
                        $log.debug(response);
                        return false;
                    }
                });
            },

            cleanFilters: function (filters) {
                angular.forEach(filters, function (value, index) {
                    if (value == '') delete filters[index];
                });
                return filters;
            },

            search_no_record: function (filters) {
                return $http.post(base_url + 'registry_object/filter/true', {'filters': filters}).then(function (response) {
                    return response.data;
                });
            },

            construct_facets: function (result, sclass) {
                var facets = [];

                //other facet fields
                if (result.error)  console.log(result);
                angular.forEach(result.facet_counts.facet_fields, function (item, index) {
                    facets[index] = [];
                    for (var i = 0; i < result.facet_counts.facet_fields[index].length; i += 2) {
                        var fa = {
                            name: result.facet_counts.facet_fields[index][i],
                            value: result.facet_counts.facet_fields[index][i + 1]
                        };
                        facets[index].push(fa);
                    }
                });

                facets['collection_type'] =[];
                angular.forEach(result.facet_counts.facet_queries, function (item, index) {
                    if(item > 0) {
                        var fa = {
                            name: index,
                            value: item
                        };
                        facets['collection_type'].push(fa);
                    }
                });

                var order = this.collection_facet_order;

                if (this.filters['class'] == 'activity') {
                    order = this.activity_facet_order;
                }

                if (sclass == 'collection') {
                    order = this.collection_facet_order;
                } else if (sclass == 'activity') {
                    order = this.activity_facet_order;
                }

                var orderedfacets = [];
                angular.forEach(order, function (item) {
                    // orderedfacets[item] = facets[item]
                    orderedfacets.push({
                        name: item,
                        value: facets[item]
                    });
                });
                return orderedfacets;
            },

            temporal_range: function (result) {
                var range = [];
                var earliest_year = false;
                var latest_year = false;

                // $log.debug(result.facet_counts.facet_fields.earliest_year);

                var earliest_array = result.facet_counts.facet_fields.earliest_year;
                var latest_array = result.facet_counts.facet_fields.latest_year;

                var i;
                for (i = 0; i < earliest_array.length - 1; i += 2) {
                    if (earliest_year && parseInt(earliest_array[i]) < earliest_year) {
                        earliest_year = parseInt(earliest_array[i]);
                    } else if (!earliest_year || earliest_year == '') {
                        earliest_year = parseInt(earliest_array[i]);
                    }
                }

                for (i = 0; i < latest_array.length - 1; i += 2) {
                    if (latest_year && parseInt(latest_array[i]) > latest_year) {
                        latest_year = parseInt(latest_array[i]);
                    } else if (!latest_year) {
                        latest_year = parseInt(latest_array[i]);
                    }
                }

                if (earliest_year && latest_year) {
                    // $log.debug(earliest_year, latest_year);
                    for (i = parseInt(earliest_year); i < parseInt(latest_year) + 1; i++) {
                        range.push(i);
                    }
                }

                return range;
            },

            filters_from_hash: function (hash) {

                var xp = hash.split('/');
                var filters = {};
                $.each(xp, function () {
                    var t = this.split('=');
                    var term = t[0];
                    var value = t[1];
                    if (term == 'rows' || term == 'year_from' || term == 'year_to' && value.trim() != '') value = parseInt(value);
                    if (term == 'funding_from' || term == 'funding_to') {
                        value = decodeURIComponent(value);
                        value = Number(value.replace(/[^0-9\.-]+/g, ""));
                    }

                    if (term == 'subject_value_resolved') {
                        value = decodeURIComponent(value);
                    }

                    if (term && value && term != '' && value != '') {

                        if (filters[term]) {
                            if (typeof filters[term] == 'string') {
                                var old = filters[term];
                                filters[term] = [];
                                filters[term].push(old);
                                filters[term].push(decodeURIComponent(value));
                            } else if (typeof filters[term] == 'object') {
                                filters[term].push(decodeURIComponent(value));
                            }
                        } else {
                            filters[term] = decodeURIComponent(value);
                        }
                    }
                });

                angular.forEach(this.default_filters, function (content, type) {
                    if (!filters[type]) filters[type] = content;
                });

                //auto switch to activity search in grants
                if (location.href.indexOf('grants') > -1) {
                    filters['class'] = 'activity';

                }

                if (filters['class'] == 'activity' && location.href.indexOf('search') > -1) {
                    $('#banner-image').css('background-image', "url('" + base_url + "assets/core/images/activity_banner.jpg')");
                } else if (location.href.indexOf('search') > -1) {
                    $('#banner-image').css('background-image', "url('" + base_url + "assets/core/images/collection_banner.jpg')");
                }

                return filters;
            },

            filters_to_hash: function (filters) {
                var hash = '';
                $.each(filters, function (i, k) {
                    if (typeof k != 'object') {
                        hash += i + '=' + encodeURIComponent(k) + '/';
                    } else if (typeof k == 'object') {
                        $.each(k, function () {
                            hash += i + '=' + encodeURIComponent(this) + '/';
                        });
                    }
                });
                return hash;
            },

            get_matching_records: function (id) {
                return $http
                    .get(api_url + '/registry/object/' + id + '/identifiermatch')
                    .then(function (response) {
                        return response.data;
                    });
            }
        }
    }
})();


text:
#ifndef DATE_H
#define DATE_H

	// #define OPERATOR_OVERLOAD_OUTSIDE_CLASS

	class Date
	{
	private:
		int yr;
		int mo;
		int da;
		static int dys[];
	public:										// Usage :
		Date(int y=0, int m=0, int d=0);		// object()  or  object or object(y, m, d)
		Date(const Date& dt);					// object1(object2)
		~Date(void);
		void display(void) const;

		#if !defined (OPERATOR_OVERLOAD_OUTSIDE_CLASS)
			/* Overloaded various operator functions
			 */
			Date operator+(int n) const;		// object1 +  n
			Date operator-(int n);				// object1 -  n
			Date operator+=(int n);				// object1 += n
			Date operator-=(int n);				// object1 -= n
			Date operator=(const Date& dt);		// object1 = object2
			int operator==(Date& dt) const;		// object1 == object2
			int operator<(Date& dt)  const;		// object1 <  object2
			int operator<=(Date& dt) const;		// object1 <= object2
			int operator!=(Date& dt) const;		// object1 != object2

			Date operator++();					// ++object
			Date operator++(int);				// object++
			Date operator--();					// --object
			Date operator--(int);				// object--
		#else
			friend Date operator+(int n, Date& dt);
			friend Date operator+(Date& dt, int n);
		#endif	/* OPERATOR_OVERLOAD_OUTSIDE_CLASS */
	};

	#if !defined (OPERATOR_OVERLOAD_OUTSIDE_CLASS)
		/* Overloaded operator:
		 * int + Date
		 */
		Date operator+(int n, Date& dt);		// n + object1
		Date operator+=(int n, Date& dt);		// object1 = n + object2
	#else
		Date operator+(int n, Date& dt);
		Date operator+(Date& dt, int n);
	#endif	/* OPERATOR_OVERLOAD_OUTSIDE_CLASS */

	class DatePtr
	{
	private:
		Date *dp;
	public:
		DatePtr(Date *d = 0);
		~DatePtr(void);

		Date* operator->();
	};

#endif	/*  DATE_H  */


text:
<?php namespace Scriptotek\Ncip;
/*
 * (c) Dan Michael O. Heggø (2013)
 *
 * Basic Ncip library. This class currently only implements
 * a small subset of the NCIP services.
 */

class CheckInRequest extends Request implements RequestInterface {

	public $agencyId;
	public $itemId;

	/**
	 * Create a new Ncip checkin request
	 *
	 * @param  string  $agencyId
	 * @param  string  $itemId
	 * @return void
	 */
	public function __construct($agencyId, $itemId)
	{
		$this->agencyId = $agencyId;
		$this->itemId = $itemId;
	}

	/**
	 * Return XML representation of the request
	 *
	 * @return string
	 */
	public function xml()
	{
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
			<ns1:NCIPMessage xmlns:ns1="http://www.niso.org/2008/ncip" ns1:version="http://www.niso.org/schemas/ncip/v2_01/ncip_v2_01.xsd">
				<ns1:CheckInItem>
					<ns1:ItemId>
					   <ns1:AgencyId>' . $this->agencyId . '</ns1:AgencyId>
					   <ns1:ItemIdentifierValue>' . $this->itemId . '</ns1:ItemIdentifierValue>
					</ns1:ItemId>
				</ns1:CheckInItem>
			</ns1:NCIPMessage>';
	}

}


text:
[![Build Status](https://travis-ci.org/andersonlucasg3/Swift.Binary.svg?branch=master)](https://travis-ci.org/andersonlucasg3/Swift.Binary)

# Swift.Binary
Binary auto-parsing for **Swift** **3.2** and **4**.

## Examples
For using the Encoder and Decoder classes you just need to declare your swift classes where all the properties are `@objc dynamic` and the class **MUST** extend from `NSObject`.
Other thing is that `Obj-c` representable objects may be optional, but non `obj-c` representable objects **MUST** be defined non optional.
But the `@objc dynamic` diretive will obligate you to define it right.

## Writing example:
Example of the implementation for converting objects to data.
```swift
import Swift_Binary // very important

class Employee: NSObject {
    @objc fileprivate(set) dynamic var name: String?
    @objc fileprivate(set) dynamic var age: Int = 0
}

class Boss: Employee {
    @objc fileprivate(set) dynamic var employees: [Employee]?
}

let employee1: Employee = Employee()
employee1.name = "John Apple Juice"
employee1.age = 35

let boss: Boss = Boss()
boss.name = "Steve James Apple Orange Juice"
boss.age = 65
boss.employees?.append(employee1)

let encoder = Encoder()
let binaryData: Data = try! encoder.encode(boss)
```

## Parsing example:
Example of the implementation for converting data to objects.
Obs: Using the same classes from above.
```swift
let binaryData: Data = // binary NSData

let decoder = Decoder()
let boss: Boss = try! decoder.decode(binaryData)

assert(boss.name == "Steve James Apple Orange Juice")
assert(boss.age == 65)
assert(boss.employees![0].name == "John Apple Juice")
assert(boss.employees![0].age == 35)
```

Any doubts, post an issue or create a pull request. Pull requests are welcome.
Thanks.


text:
namespace mediapipe {
namespace api2 {

// Concatenate several input packets of ListType with a repeated field of
// ItemType into a single output packet of ListType following stream index
// order.
template <typename ItemType, typename ListType>
class ConcatenateListsCalculator : public Node {
 public:
  static constexpr typename Input<ListType>::Multiple kIn{""};
  static constexpr Output<ListType> kOut{""};

  MEDIAPIPE_NODE_CONTRACT(kIn, kOut);

  static absl::Status UpdateContract(CalculatorContract* cc) {
    RET_CHECK_GE(kIn(cc).Count(), 1);
    return absl::OkStatus();
  }

  absl::Status Open(CalculatorContext* cc) override {
    only_emit_if_all_present_ =
        cc->Options<::mediapipe::ConcatenateVectorCalculatorOptions>()
            .only_emit_if_all_present();
    return absl::OkStatus();
  }

  absl::Status Process(CalculatorContext* cc) override {
    if (only_emit_if_all_present_) {
      for (const auto& input : kIn(cc)) {
        if (input.IsEmpty()) return absl::OkStatus();
      }
    }

    ListType output;
    for (const auto& input : kIn(cc)) {
      if (input.IsEmpty()) continue;
      const ListType& list = *input;
      for (int j = 0; j < ListSize(list); ++j) {
        *AddItem(output) = GetItem(list, j);
      }
    }
    kOut(cc).Send(std::move(output));
    return absl::OkStatus();
  }

 protected:
  virtual int ListSize(const ListType& list) const = 0;
  virtual const ItemType GetItem(const ListType& list, int idx) const = 0;
  virtual ItemType* AddItem(ListType& list) const = 0;

 private:
  bool only_emit_if_all_present_;
};

// TODO: Move calculators to separate *.cc files

class ConcatenateNormalizedLandmarkListCalculator
    : public ConcatenateListsCalculator<NormalizedLandmark,
                                        NormalizedLandmarkList> {
 protected:
  int ListSize(const NormalizedLandmarkList& list) const override {
    return list.landmark_size();
  }
  const NormalizedLandmark GetItem(const NormalizedLandmarkList& list,
                                   int idx) const override {
    return list.landmark(idx);
  }
  NormalizedLandmark* AddItem(NormalizedLandmarkList& list) const override {
    return list.add_landmark();
  }
};
MEDIAPIPE_REGISTER_NODE(ConcatenateNormalizedLandmarkListCalculator);

class ConcatenateLandmarkListCalculator
    : public ConcatenateListsCalculator<Landmark, LandmarkList> {
 protected:
  int ListSize(const LandmarkList& list) const override {
    return list.landmark_size();
  }
  const Landmark GetItem(const LandmarkList& list, int idx) const override {
    return list.landmark(idx);
  }
  Landmark* AddItem(LandmarkList& list) const override {
    return list.add_landmark();
  }
};
MEDIAPIPE_REGISTER_NODE(ConcatenateLandmarkListCalculator);

class ConcatenateClassificationListCalculator
    : public ConcatenateListsCalculator<Classification, ClassificationList> {
 protected:
  int ListSize(const ClassificationList& list) const override {
    return list.classification_size();
  }
  const Classification GetItem(const ClassificationList& list,
                               int idx) const override {
    return list.classification(idx);
  }
  Classification* AddItem(ClassificationList& list) const override {
    return list.add_classification();
  }
};
MEDIAPIPE_REGISTER_NODE(ConcatenateClassificationListCalculator);

}  // namespace api2
}  // namespace mediapipe

// NOLINTNEXTLINE
#endif  // MEDIAPIPE_CALCULATORS_CORE_CONCATENATE_PROTO_LIST_CALCULATOR_H_


text:
module ag.grid {

    // Implemented by Column and ColumnGroup. Allows the groups to contain a list of this type for it's children.
    // See the note at the top of Column class.
    export interface ColumnGroupChild {
        getActualWidth(): number;
        getMinimumWidth(): number;
        getDefinition(): AbstractColDef;
        getColumnGroupShow(): string;
    }
}


text:
static const uint64_t apiTypeReset = 0;
static const uint64_t apiTypeErase = 1;
static const uint64_t apiTypeWrite = 2;
static const uint64_t apiTypeRead = 3;
static const uint64_t apiTypeHash = 4;
static const uint64_t apiTypeFileMkfs = 5;
static const uint64_t apiTypeFileList = 6;
static const uint64_t apiTypeFileOpen = 7;
static const uint64_t apiTypeFileUnlink = 8;
static const uint64_t apiTypeFileAddress = 9;
static const uint64_t apiTypeFileExpand = 10;
static const uint64_t apiTypeFileWrite = 11;
static const uint64_t apiTypeFileRead = 12;

#define fdi_storage_instrument_count 1
fdi_storage_instrument_t fdi_storage_instruments[fdi_storage_instrument_count];

uint32_t fdi_storage_instrument_get_count(void) {
    return fdi_storage_instrument_count;
}

fdi_storage_instrument_t *fdi_storage_instrument_get_at(uint32_t index) {
    return &fdi_storage_instruments[index];
}

fdi_storage_instrument_t *fdi_storage_instrument_get(uint64_t identifier) {
    for (int i = 0; i < fdi_storage_instrument_count; ++i) {
        fdi_storage_instrument_t *instrument = &fdi_storage_instruments[i];
        if (instrument->super.identifier == identifier) {
            return instrument;
        }
    }
    return 0;
}

void fdi_storage_instrument_reset(fdi_storage_instrument_t *instrument __attribute__((unused))) {
    // nothing to do...
}

void fdi_storage_instrument_api_reset(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary __attribute__((unused))) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    fdi_storage_instrument_reset(instrument);
}

void fdi_storage_instrument_api_erase(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    uint32_t address = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t length = (uint32_t)fd_binary_get_varuint(binary);

#ifdef FD_INSTRUMENT_ALL_IN_ONE
    uint32_t end = address + length;
    while (address < end) {
        fdi_s25fl116k_enable_write();
        fdi_s25fl116k_erase_sector(address);
        address += fdi_s25fl116k_sector_size;
        fdi_s25fl116k_wait_while_busy();
    }
#else
    fd_sdcard_erase(address, length);
#endif
}

void fdi_storage_instrument_api_write(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    uint32_t address = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t length = (uint32_t)fd_binary_get_varuint(binary);

#ifdef FD_INSTRUMENT_ALL_IN_ONE
    uint32_t offset = 0;
    while (offset < length) {
        uint32_t sublength = length - offset;
        uint32_t lower_address = address + offset;
        uint32_t lower_page = lower_address >> 8;
        uint32_t upper_page = (lower_address + sublength - 1) >> 8;
        if (upper_page != lower_page) {
            sublength = ((lower_page + 1) << 8) - lower_address;
        }
        fdi_s25fl116k_enable_write();
        fdi_s25fl116k_write_page(lower_address, &binary->buffer[binary->get_index], sublength);
        fdi_s25fl116k_wait_while_busy();
        binary->get_index += sublength;
        offset += sublength;
    }
#else
    fd_sdcard_write(address, &binary->buffer[binary->get_index], length);
#endif
}

void fdi_storage_instrument_read(
    fdi_storage_instrument_t *instrument,
    uint32_t address, uint32_t length, uint32_t sublength, uint32_t substride,
    uint8_t *buffer, uint32_t size
) {
    fd_log_assert(length <= size);
    if (length > size) {
        length = size;
    }
    if (sublength == 0) {
        sublength = length;
    }

    uint32_t total = 0;
    while (total < length) {
#ifdef FD_INSTRUMENT_ALL_IN_ONE
        fdi_s25fl116k_read(address, &buffer[total], sublength);
#else
        fd_sdcard_read(address, &buffer[total], sublength);
#endif
        total += sublength;
        address += substride;
    }
}

void fdi_storage_instrument_api_read(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    uint32_t address = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t length = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t sublength = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t substride = (uint32_t)fd_binary_get_varuint(binary);
    uint8_t buffer[4096];
    fdi_storage_instrument_read(instrument, address, length, sublength, substride, buffer, sizeof(buffer));

    if (!fdi_api_send(instrument->super.identifier, apiTypeRead, buffer, length)) {
        fd_log_assert_fail("can't send");
    }
}

void fdi_storage_instrument_api_hash(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    uint32_t address = (uint32_t)fd_binary_get_varuint(binary);
    uint32_t length = (uint32_t)fd_binary_get_varuint(binary);

    uint8_t hash[FD_SHA_HASH_SIZE];
#ifdef FD_INSTRUMENT_ALL_IN_ONE
    fd_sha1(fdi_s25fl116k_read, address, length, hash);
#else
    fd_sha1(fd_sdcard_read, address, length, hash);
#endif

    if (!fdi_api_send(instrument->super.identifier, apiTypeHash, hash, FD_SHA_HASH_SIZE)) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_mkfs(fdi_storage_instrument_t *instrument) {
    f_mount(0, "", 1);
    uint8_t mkfs_buffer[4096];
    FRESULT result = f_mkfs("", 0, mkfs_buffer, sizeof(mkfs_buffer));
    if (result == FR_OK) {
        result = f_mount(&instrument->fs, "", 1);
    }
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_mkfs(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    bool result = fdi_storage_instrument_file_mkfs(instrument);
    uint8_t buffer[] = { result ? 1 : 0 };
    if (!fdi_api_send(instrument->super.identifier, apiTypeFileMkfs, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

void fdi_storage_instrument_api_file_list(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    uint8_t buffer[4096];
    fd_binary_t response;
    fd_binary_initialize(&response, buffer, sizeof(buffer));
    uint8_t count = 0;
    fd_binary_put_uint8(&response, count);
    DIR dir;
    FRESULT result = f_opendir(&dir, "/");
    if (result == FR_OK) {
        while (true) {
            FILINFO info;
            result = f_readdir(&dir, &info);
            if ((result != FR_OK) || (info.fname[0] == 0)) {
                break;
            }
            if ((info.fattrib & AM_DIR) == 0) {
                fd_binary_put_string(&response, info.fname);
                fd_binary_put_uint32(&response, info.fsize);
                fd_binary_put_uint32(&response, info.fdate);
                fd_binary_put_uint32(&response, info.ftime);
                ++count;
            }
        }
        f_closedir(&dir);
    }
    buffer[0] = count;
    if (!fdi_api_send(instrument->super.identifier, apiTypeFileList, buffer, response.put_index)) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_open(fdi_storage_instrument_t *instrument, const char *name, uint8_t mode) {
    FIL file;
    FRESULT result = f_open(&file, name, mode);
    if (result == FR_OK) {
        f_close(&file);
    }
    return result == FR_OK;
}

static void fdi_storage_instrument_get_name(fd_binary_t *binary, char *name, size_t size) {
    fd_binary_string_t string = fd_binary_get_string(binary);
    if (string.length > (size - 1)) {
        string.length = size - 1;
    }
    memcpy(name, string.data, string.length);
    name[string.length] = '\0';
}

void fdi_storage_instrument_api_file_open(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    uint8_t mode = (uint8_t)fd_binary_get_varuint(binary);
    bool result = fdi_storage_instrument_file_open(instrument, name, mode);
    uint8_t buffer[] = { result ? 1 : 0 };

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileOpen, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_unlink(fdi_storage_instrument_t *instrument, const char *name) {
    FRESULT result = f_unlink(name);
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_unlink(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    bool result = fdi_storage_instrument_file_unlink(instrument, name);
    uint8_t buffer[] = { result ? 1 : 0 };

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileUnlink, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_address(fdi_storage_instrument_t *instrument, const char *name, uint32_t *address) {
    FIL file;
    FRESULT result = f_open(&file, name, FA_READ | FA_OPEN_EXISTING);
    if (result == FR_OK) {
        *address = 512 * (file.obj.fs->database + file.obj.fs->csize * (file.obj.sclust - 2));
    }
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_address(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    uint32_t address = 0;
    bool result = fdi_storage_instrument_file_address(instrument, name, &address);
    uint8_t buffer[] = { result ? 1 : 0, address, address >> 8, address >> 16, address >> 24 };

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileAddress, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_expand(fdi_storage_instrument_t *instrument, const char *name, uint32_t size) {
    FIL file;
    FRESULT result = f_open(&file, name, FA_WRITE | FA_OPEN_EXISTING);
    if (result == FR_OK) {
        result = f_expand(&file, size, 1);
        f_close(&file);
    }
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_expand(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    uint32_t size = fd_binary_get_uint32(binary);
    bool result = fdi_storage_instrument_file_expand(instrument, name, size);
    uint8_t buffer[] = { result ? 1 : 0 };

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileExpand, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_write(fdi_storage_instrument_t *instrument, const char *name, uint32_t offset, const uint8_t *data, uint32_t length) {
    FIL file;
    FRESULT result = f_open(&file, name, FA_WRITE | FA_OPEN_EXISTING);
    if (result == FR_OK) {
        result = f_lseek(&file, offset);
        if (result == FR_OK) {
            uint32_t actual = 0;
            result = f_write(&file, data, length, &actual);
            if (result == FR_OK) {
                if (actual != length) {
                    result = FR_INVALID_PARAMETER;
                }
            }
        }
        f_close(&file);
    }
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_write(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    uint32_t offset = fd_binary_get_uint32(binary);
    uint32_t length = fd_binary_get_uint32(binary);
    uint8_t *data = &binary->buffer[binary->get_index];
    bool result = fdi_storage_instrument_file_write(instrument, name, offset, data, length);
    uint8_t buffer[] = { result ? 1 : 0 };

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileWrite, buffer, sizeof(buffer))) {
        fd_log_assert_fail("can't send");
    }
}

bool fdi_storage_instrument_file_read(fdi_storage_instrument_t *instrument, const char *name, uint32_t offset, uint8_t *data, uint32_t length) {
    FIL file;
    FRESULT result = f_open(&file, name, FA_READ | FA_OPEN_EXISTING);
    if (result == FR_OK) {
        result = f_lseek(&file, offset);
        if (result == FR_OK) {
            uint32_t actual = 0;
            result = f_read(&file, data, length, &actual);
            if (result == FR_OK) {
                if (actual != length) {
                    result = FR_INVALID_PARAMETER;
                }
            }
        }
        f_close(&file);
    }
    return result == FR_OK;
}

void fdi_storage_instrument_api_file_read(uint64_t identifier, uint64_t type __attribute__((unused)), fd_binary_t *binary) {
    fdi_storage_instrument_t *instrument = fdi_storage_instrument_get(identifier);
    if (instrument == 0) {
        return;
    }

    char name[12 + 1];
    fdi_storage_instrument_get_name(binary, name, sizeof(name));
    uint32_t offset = fd_binary_get_uint32(binary);
    uint32_t length = fd_binary_get_uint32(binary);
    uint8_t data[1 + 4 + 4096];
    data[1] = length;
    data[2] = length >> 8;
    data[3] = length >> 16;
    data[4] = length >> 24;
    bool result = fdi_storage_instrument_file_read(instrument, name, offset, &data[1 + 4], length);
    data[0] = result ? 1 : 0;

    if (!fdi_api_send(instrument->super.identifier, apiTypeFileRead, data, 1 + 4 + length)) {
        fd_log_assert_fail("can't send");
    }
}

void fdi_storage_instrument_initialize(void) {
    fdi_storage_instrument_t *instrument = &fdi_storage_instruments[0];
    instrument->super.category = "Storage";
    instrument->super.reset = fdi_storage_instrument_api_reset;
    fdi_instrument_register(&instrument->super);
    fdi_api_register(instrument->super.identifier, apiTypeReset, fdi_storage_instrument_api_reset);
    fdi_api_register(instrument->super.identifier, apiTypeErase, fdi_storage_instrument_api_erase);
    fdi_api_register(instrument->super.identifier, apiTypeWrite, fdi_storage_instrument_api_write);
    fdi_api_register(instrument->super.identifier, apiTypeRead, fdi_storage_instrument_api_read);
    fdi_api_register(instrument->super.identifier, apiTypeHash, fdi_storage_instrument_api_hash);
    fdi_api_register(instrument->super.identifier, apiTypeFileMkfs, fdi_storage_instrument_api_file_mkfs);
    fdi_api_register(instrument->super.identifier, apiTypeFileList, fdi_storage_instrument_api_file_list);
    fdi_api_register(instrument->super.identifier, apiTypeFileOpen, fdi_storage_instrument_api_file_open);
    fdi_api_register(instrument->super.identifier, apiTypeFileUnlink, fdi_storage_instrument_api_file_unlink);
    fdi_api_register(instrument->super.identifier, apiTypeFileAddress, fdi_storage_instrument_api_file_address);
    fdi_api_register(instrument->super.identifier, apiTypeFileExpand, fdi_storage_instrument_api_file_expand);
    fdi_api_register(instrument->super.identifier, apiTypeFileWrite, fdi_storage_instrument_api_file_write);
    fdi_api_register(instrument->super.identifier, apiTypeFileRead, fdi_storage_instrument_api_file_read);
    FRESULT result = f_mount(&instrument->fs, "", 1);
    fd_log_assert(result == FR_OK);
}


text:
package repo

import (
	"fmt"
	"net/http"
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/models/db"
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/unit"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/markup/markdown"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/upload"
	"code.gitea.io/gitea/modules/util"
	"code.gitea.io/gitea/modules/web"
	"code.gitea.io/gitea/services/forms"
	releaseservice "code.gitea.io/gitea/services/release"
)

const (
	tplReleases   base.TplName = "repo/release/list"
	tplReleaseNew base.TplName = "repo/release/new"
)

// calReleaseNumCommitsBehind calculates given release has how many commits behind release target.
func calReleaseNumCommitsBehind(repoCtx *context.Repository, release *repo_model.Release, countCache map[string]int64) error {
	// Fast return if release target is same as default branch.
	if repoCtx.BranchName == release.Target {
		release.NumCommitsBehind = repoCtx.CommitsCount - release.NumCommits
		return nil
	}

	// Get count if not exists
	if _, ok := countCache[release.Target]; !ok {
		if repoCtx.GitRepo.IsBranchExist(release.Target) {
			commit, err := repoCtx.GitRepo.GetBranchCommit(release.Target)
			if err != nil {
				return fmt.Errorf("GetBranchCommit: %w", err)
			}
			countCache[release.Target], err = commit.CommitsCount()
			if err != nil {
				return fmt.Errorf("CommitsCount: %w", err)
			}
		} else {
			// Use NumCommits of the newest release on that target
			countCache[release.Target] = release.NumCommits
		}
	}
	release.NumCommitsBehind = countCache[release.Target] - release.NumCommits
	return nil
}

// Releases render releases list page
func Releases(ctx *context.Context) {
	releasesOrTags(ctx, false)
}

// TagsList render tags list page
func TagsList(ctx *context.Context) {
	releasesOrTags(ctx, true)
}

func releasesOrTags(ctx *context.Context, isTagList bool) {
	ctx.Data["PageIsReleaseList"] = true
	ctx.Data["DefaultBranch"] = ctx.Repo.Repository.DefaultBranch
	ctx.Data["IsViewBranch"] = false
	ctx.Data["IsViewTag"] = true
	// Disable the showCreateNewBranch form in the dropdown on this page.
	ctx.Data["CanCreateBranch"] = false
	ctx.Data["HideBranchesInDropdown"] = true

	if isTagList {
		ctx.Data["Title"] = ctx.Tr("repo.release.tags")
		ctx.Data["PageIsTagList"] = true
	} else {
		ctx.Data["Title"] = ctx.Tr("repo.release.releases")
		ctx.Data["PageIsTagList"] = false
	}

	listOptions := db.ListOptions{
		Page:     ctx.FormInt("page"),
		PageSize: ctx.FormInt("limit"),
	}
	if listOptions.PageSize == 0 {
		listOptions.PageSize = setting.Repository.Release.DefaultPagingNum
	}
	if listOptions.PageSize > setting.API.MaxResponseItems {
		listOptions.PageSize = setting.API.MaxResponseItems
	}

	// TODO(20073) tags are used for compare feature which needs all tags
	// filtering is done on the client-side atm
	tagListStart, tagListEnd := 0, 0
	if isTagList {
		tagListStart, tagListEnd = listOptions.GetStartEnd()
	}

	tags, err := ctx.Repo.GitRepo.GetTags(tagListStart, tagListEnd)
	if err != nil {
		ctx.ServerError("GetTags", err)
		return
	}
	ctx.Data["Tags"] = tags

	writeAccess := ctx.Repo.CanWrite(unit.TypeReleases)
	ctx.Data["CanCreateRelease"] = writeAccess && !ctx.Repo.Repository.IsArchived

	opts := repo_model.FindReleasesOptions{
		ListOptions: listOptions,
	}
	if isTagList {
		// for the tags list page, show all releases with real tags (having real commit-id),
		// the drafts should also be included because a real tag might be used as a draft.
		opts.IncludeDrafts = true
		opts.IncludeTags = true
		opts.HasSha1 = util.OptionalBoolTrue
	} else {
		// only show draft releases for users who can write, read-only users shouldn't see draft releases.
		opts.IncludeDrafts = writeAccess
	}

	releases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts)
	if err != nil {
		ctx.ServerError("GetReleasesByRepoID", err)
		return
	}

	count, err := repo_model.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, opts)
	if err != nil {
		ctx.ServerError("GetReleaseCountByRepoID", err)
		return
	}

	if err = repo_model.GetReleaseAttachments(ctx, releases...); err != nil {
		ctx.ServerError("GetReleaseAttachments", err)
		return
	}

	// Temporary cache commits count of used branches to speed up.
	countCache := make(map[string]int64)
	cacheUsers := make(map[int64]*user_model.User)
	if ctx.Doer != nil {
		cacheUsers[ctx.Doer.ID] = ctx.Doer
	}
	var ok bool

	for _, r := range releases {
		if r.Publisher, ok = cacheUsers[r.PublisherID]; !ok {
			r.Publisher, err = user_model.GetUserByID(r.PublisherID)
			if err != nil {
				if user_model.IsErrUserNotExist(err) {
					r.Publisher = user_model.NewGhostUser()
				} else {
					ctx.ServerError("GetUserByID", err)
					return
				}
			}
			cacheUsers[r.PublisherID] = r.Publisher
		}

		r.Note, err = markdown.RenderString(&markup.RenderContext{
			URLPrefix: ctx.Repo.RepoLink,
			Metas:     ctx.Repo.Repository.ComposeMetas(),
			GitRepo:   ctx.Repo.GitRepo,
			Ctx:       ctx,
		}, r.Note)
		if err != nil {
			ctx.ServerError("RenderString", err)
			return
		}

		if r.IsDraft {
			continue
		}

		if err := calReleaseNumCommitsBehind(ctx.Repo, r, countCache); err != nil {
			ctx.ServerError("calReleaseNumCommitsBehind", err)
			return
		}
	}

	ctx.Data["Releases"] = releases
	ctx.Data["ReleasesNum"] = len(releases)

	pager := context.NewPagination(int(count), opts.PageSize, opts.Page, 5)
	pager.SetDefaultParams(ctx)
	ctx.Data["Page"] = pager

	ctx.HTML(http.StatusOK, tplReleases)
}

// SingleRelease renders a single release's page
func SingleRelease(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.release.releases")
	ctx.Data["PageIsReleaseList"] = true

	writeAccess := ctx.Repo.CanWrite(unit.TypeReleases)
	ctx.Data["CanCreateRelease"] = writeAccess && !ctx.Repo.Repository.IsArchived

	release, err := repo_model.GetRelease(ctx.Repo.Repository.ID, ctx.Params("*"))
	if err != nil {
		if repo_model.IsErrReleaseNotExist(err) {
			ctx.NotFound("GetRelease", err)
			return
		}
		ctx.ServerError("GetReleasesByRepoID", err)
		return
	}

	err = repo_model.GetReleaseAttachments(ctx, release)
	if err != nil {
		ctx.ServerError("GetReleaseAttachments", err)
		return
	}

	release.Publisher, err = user_model.GetUserByID(release.PublisherID)
	if err != nil {
		if user_model.IsErrUserNotExist(err) {
			release.Publisher = user_model.NewGhostUser()
		} else {
			ctx.ServerError("GetUserByID", err)
			return
		}
	}
	if !release.IsDraft {
		if err := calReleaseNumCommitsBehind(ctx.Repo, release, make(map[string]int64)); err != nil {
			ctx.ServerError("calReleaseNumCommitsBehind", err)
			return
		}
	}
	release.Note, err = markdown.RenderString(&markup.RenderContext{
		URLPrefix: ctx.Repo.RepoLink,
		Metas:     ctx.Repo.Repository.ComposeMetas(),
		GitRepo:   ctx.Repo.GitRepo,
		Ctx:       ctx,
	}, release.Note)
	if err != nil {
		ctx.ServerError("RenderString", err)
		return
	}

	ctx.Data["Releases"] = []*repo_model.Release{release}
	ctx.HTML(http.StatusOK, tplReleases)
}

// LatestRelease redirects to the latest release
func LatestRelease(ctx *context.Context) {
	release, err := repo_model.GetLatestReleaseByRepoID(ctx.Repo.Repository.ID)
	if err != nil {
		if repo_model.IsErrReleaseNotExist(err) {
			ctx.NotFound("LatestRelease", err)
			return
		}
		ctx.ServerError("GetLatestReleaseByRepoID", err)
		return
	}

	if err := release.LoadAttributes(ctx); err != nil {
		ctx.ServerError("LoadAttributes", err)
		return
	}

	ctx.Redirect(release.HTMLURL())
}

// NewRelease render creating or edit release page
func NewRelease(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.release.new_release")
	ctx.Data["PageIsReleaseList"] = true
	ctx.Data["RequireTribute"] = true
	ctx.Data["tag_target"] = ctx.Repo.Repository.DefaultBranch
	if tagName := ctx.FormString("tag"); len(tagName) > 0 {
		rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
		if err != nil && !repo_model.IsErrReleaseNotExist(err) {
			ctx.ServerError("GetRelease", err)
			return
		}

		if rel != nil {
			rel.Repo = ctx.Repo.Repository
			if err := rel.LoadAttributes(ctx); err != nil {
				ctx.ServerError("LoadAttributes", err)
				return
			}

			ctx.Data["tag_name"] = rel.TagName
			if rel.Target != "" {
				ctx.Data["tag_target"] = rel.Target
			}
			ctx.Data["title"] = rel.Title
			ctx.Data["content"] = rel.Note
			ctx.Data["attachments"] = rel.Attachments
		}
	}
	ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
	upload.AddUploadContext(ctx, "release")
	ctx.HTML(http.StatusOK, tplReleaseNew)
}

// NewReleasePost response for creating a release
func NewReleasePost(ctx *context.Context) {
	form := web.GetForm(ctx).(*forms.NewReleaseForm)
	ctx.Data["Title"] = ctx.Tr("repo.release.new_release")
	ctx.Data["PageIsReleaseList"] = true
	ctx.Data["RequireTribute"] = true

	if ctx.HasError() {
		ctx.HTML(http.StatusOK, tplReleaseNew)
		return
	}

	if !ctx.Repo.GitRepo.IsBranchExist(form.Target) {
		ctx.RenderWithErr(ctx.Tr("form.target_branch_not_exist"), tplReleaseNew, &form)
		return
	}

	var attachmentUUIDs []string
	if setting.Attachment.Enabled {
		attachmentUUIDs = form.Files
	}

	rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, form.TagName)
	if err != nil {
		if !repo_model.IsErrReleaseNotExist(err) {
			ctx.ServerError("GetRelease", err)
			return
		}

		msg := ""
		if len(form.Title) > 0 && form.AddTagMsg {
			msg = form.Title + "\n\n" + form.Content
		}

		if len(form.TagOnly) > 0 {
			if err = releaseservice.CreateNewTag(ctx, ctx.Doer, ctx.Repo.Repository, form.Target, form.TagName, msg); err != nil {
				if models.IsErrTagAlreadyExists(err) {
					e := err.(models.ErrTagAlreadyExists)
					ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName))
					ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
					return
				}

				if models.IsErrInvalidTagName(err) {
					ctx.Flash.Error(ctx.Tr("repo.release.tag_name_invalid"))
					ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
					return
				}

				if models.IsErrProtectedTagName(err) {
					ctx.Flash.Error(ctx.Tr("repo.release.tag_name_protected"))
					ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
					return
				}

				ctx.ServerError("releaseservice.CreateNewTag", err)
				return
			}

			ctx.Flash.Success(ctx.Tr("repo.tag.create_success", form.TagName))
			ctx.Redirect(ctx.Repo.RepoLink + "/src/tag/" + util.PathEscapeSegments(form.TagName))
			return
		}

		rel = &repo_model.Release{
			RepoID:       ctx.Repo.Repository.ID,
			Repo:         ctx.Repo.Repository,
			PublisherID:  ctx.Doer.ID,
			Publisher:    ctx.Doer,
			Title:        form.Title,
			TagName:      form.TagName,
			Target:       form.Target,
			Note:         form.Content,
			IsDraft:      len(form.Draft) > 0,
			IsPrerelease: form.Prerelease,
			IsTag:        false,
		}

		if err = releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, attachmentUUIDs, msg); err != nil {
			ctx.Data["Err_TagName"] = true
			switch {
			case repo_model.IsErrReleaseAlreadyExist(err):
				ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), tplReleaseNew, &form)
			case models.IsErrInvalidTagName(err):
				ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_invalid"), tplReleaseNew, &form)
			case models.IsErrProtectedTagName(err):
				ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_protected"), tplReleaseNew, &form)
			default:
				ctx.ServerError("CreateRelease", err)
			}
			return
		}
	} else {
		if !rel.IsTag {
			ctx.Data["Err_TagName"] = true
			ctx.RenderWithErr(ctx.Tr("repo.release.tag_name_already_exist"), tplReleaseNew, &form)
			return
		}

		rel.Title = form.Title
		rel.Note = form.Content
		rel.Target = form.Target
		rel.IsDraft = len(form.Draft) > 0
		rel.IsPrerelease = form.Prerelease
		rel.PublisherID = ctx.Doer.ID
		rel.IsTag = false

		if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo, rel, attachmentUUIDs, nil, nil); err != nil {
			ctx.Data["Err_TagName"] = true
			ctx.ServerError("UpdateRelease", err)
			return
		}
	}
	log.Trace("Release created: %s/%s:%s", ctx.Doer.LowerName, ctx.Repo.Repository.Name, form.TagName)

	ctx.Redirect(ctx.Repo.RepoLink + "/releases")
}

// EditRelease render release edit page
func EditRelease(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.release.edit_release")
	ctx.Data["PageIsReleaseList"] = true
	ctx.Data["PageIsEditRelease"] = true
	ctx.Data["RequireTribute"] = true
	ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
	upload.AddUploadContext(ctx, "release")

	tagName := ctx.Params("*")
	rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
	if err != nil {
		if repo_model.IsErrReleaseNotExist(err) {
			ctx.NotFound("GetRelease", err)
		} else {
			ctx.ServerError("GetRelease", err)
		}
		return
	}
	ctx.Data["ID"] = rel.ID
	ctx.Data["tag_name"] = rel.TagName
	ctx.Data["tag_target"] = rel.Target
	ctx.Data["title"] = rel.Title
	ctx.Data["content"] = rel.Note
	ctx.Data["prerelease"] = rel.IsPrerelease
	ctx.Data["IsDraft"] = rel.IsDraft

	rel.Repo = ctx.Repo.Repository
	if err := rel.LoadAttributes(ctx); err != nil {
		ctx.ServerError("LoadAttributes", err)
		return
	}
	ctx.Data["attachments"] = rel.Attachments

	ctx.HTML(http.StatusOK, tplReleaseNew)
}

// EditReleasePost response for edit release
func EditReleasePost(ctx *context.Context) {
	form := web.GetForm(ctx).(*forms.EditReleaseForm)
	ctx.Data["Title"] = ctx.Tr("repo.release.edit_release")
	ctx.Data["PageIsReleaseList"] = true
	ctx.Data["PageIsEditRelease"] = true
	ctx.Data["RequireTribute"] = true

	tagName := ctx.Params("*")
	rel, err := repo_model.GetRelease(ctx.Repo.Repository.ID, tagName)
	if err != nil {
		if repo_model.IsErrReleaseNotExist(err) {
			ctx.NotFound("GetRelease", err)
		} else {
			ctx.ServerError("GetRelease", err)
		}
		return
	}
	if rel.IsTag {
		ctx.NotFound("GetRelease", err)
		return
	}
	ctx.Data["tag_name"] = rel.TagName
	ctx.Data["tag_target"] = rel.Target
	ctx.Data["title"] = rel.Title
	ctx.Data["content"] = rel.Note
	ctx.Data["prerelease"] = rel.IsPrerelease

	if ctx.HasError() {
		ctx.HTML(http.StatusOK, tplReleaseNew)
		return
	}

	const delPrefix = "attachment-del-"
	const editPrefix = "attachment-edit-"
	var addAttachmentUUIDs, delAttachmentUUIDs []string
	editAttachments := make(map[string]string) // uuid -> new name
	if setting.Attachment.Enabled {
		addAttachmentUUIDs = form.Files
		for k, v := range ctx.Req.Form {
			if strings.HasPrefix(k, delPrefix) && v[0] == "true" {
				delAttachmentUUIDs = append(delAttachmentUUIDs, k[len(delPrefix):])
			} else if strings.HasPrefix(k, editPrefix) {
				editAttachments[k[len(editPrefix):]] = v[0]
			}
		}
	}

	rel.Title = form.Title
	rel.Note = form.Content
	rel.IsDraft = len(form.Draft) > 0
	rel.IsPrerelease = form.Prerelease
	if err = releaseservice.UpdateRelease(ctx.Doer, ctx.Repo.GitRepo,
		rel, addAttachmentUUIDs, delAttachmentUUIDs, editAttachments); err != nil {
		ctx.ServerError("UpdateRelease", err)
		return
	}
	ctx.Redirect(ctx.Repo.RepoLink + "/releases")
}

// DeleteRelease deletes a release
func DeleteRelease(ctx *context.Context) {
	deleteReleaseOrTag(ctx, false)
}

// DeleteTag deletes a tag
func DeleteTag(ctx *context.Context) {
	deleteReleaseOrTag(ctx, true)
}

func deleteReleaseOrTag(ctx *context.Context, isDelTag bool) {
	if err := releaseservice.DeleteReleaseByID(ctx, ctx.FormInt64("id"), ctx.Doer, isDelTag); err != nil {
		if models.IsErrProtectedTagName(err) {
			ctx.Flash.Error(ctx.Tr("repo.release.tag_name_protected"))
		} else {
			ctx.Flash.Error("DeleteReleaseByID: " + err.Error())
		}
	} else {
		if isDelTag {
			ctx.Flash.Success(ctx.Tr("repo.release.deletion_tag_success"))
		} else {
			ctx.Flash.Success(ctx.Tr("repo.release.deletion_success"))
		}
	}

	if isDelTag {
		ctx.JSON(http.StatusOK, map[string]interface{}{
			"redirect": ctx.Repo.RepoLink + "/tags",
		})
		return
	}

	ctx.JSON(http.StatusOK, map[string]interface{}{
		"redirect": ctx.Repo.RepoLink + "/releases",
	})
}


text:
<?php

// Theme info
return [
    'name' => 'Flatly',
    'identifier' => 'flatly',
    'folder_name' => 'flatly',
    'description' => 'Bootstrap-based free template of Bootswatch, modified for the Everest CMS.',
    'version' => '1.0.0-beta',
    'for' => [],
    'author' => 'Thomas Park and Everest CMS contributors',
    'copyright' => '2012-2018 Thomas Park',
    'license' => 'GPLv3',
    'type' => 'frontend',
    'block_handling' => 'sequential', // grouped | sequential
    'blocks' => [
        ['content', 'Content Default'],
        ['content-primary', 'Content Primary'],
    ],
    'navigations' => [
        ['footer', 'Footer'],
    ],
];


text:
<?php

namespace Bundle\DoctrineUserBundle\Validator\Doctrine\ODM\MongoDB;

use Symfony\Component\Validator\Constraint;

class Unique extends Constraint
{

    public $message = 'The value for "%property%" already exists.';
    public $property;

    public function defaultOption()
    {
        return 'property';
    }

    public function requiredOptions()
    {
        return array('property');
    }

}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>
#ifdef CONFIG_NET_ICMPv6_PING

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <semaphore.h>
#include <debug.h>

#include <net/if.h>

#include <nuttx/clock.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/ip.h>
#include <nuttx/net/icmpv6.h>
#include <nuttx/net/netstats.h>

#include "netdev/netdev.h"
#include "devif/devif.h"
#include "utils/utils.h"
#include "icmpv6/icmpv6.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

#define ETHBUF    ((struct eth_hdr_s *)&dev->d_buf[0])
#define ICMPv6BUF ((struct icmpv6_iphdr_s *)&dev->d_buf[NET_LL_HDRLEN(dev)])
#define ICMPv6ECHOREQ \
  ((struct icmpv6_echo_request_s *)&dev->d_buf[NET_LL_HDRLEN(dev) + IPv6_HDRLEN])
#define ICMPv6ECHOREPLY \
  ((struct icmpv6_echo_reply_s *)&dev->d_buf[NET_LL_HDRLEN(dev) + IPv6_HDRLEN])

/****************************************************************************
 * Private Data
 ****************************************************************************/

/****************************************************************************
 * Private Types
 ****************************************************************************/

struct icmpv6_ping_s
{
  FAR struct devif_callback_s *png_cb; /* Reference to callback instance */

  sem_t          png_sem;     /* Use to manage the wait for the response */
  uint32_t       png_time;    /* Start time for determining timeouts */
  uint32_t       png_ticks;   /* System clock ticks to wait */
  int            png_result;  /* 0: success; <0:negated errno on fail */
  net_ipv6addr_t png_addr;    /* The peer to be ping'ed */
  uint16_t       png_id;      /* Used to match requests with replies */
  uint16_t       png_seqno;   /* IN: seqno to send; OUT: seqno recieved */
  uint16_t       png_datlen;  /* The length of data to send in the ECHO request */
  bool           png_sent;    /* true... the PING request has been sent */
};

/****************************************************************************
 * Public Variables
 ****************************************************************************/

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Function: ping_timeout
 *
 * Description:
 *   Check for send timeout.
 *
 * Parameters:
 *   pstate - Ping state structure
 *
 * Returned Value:
 *   TRUE:timeout FALSE:no timeout
 *
 * Assumptions:
 *   Running at the interrupt level
 *
 ****************************************************************************/

static inline int ping_timeout(FAR struct icmpv6_ping_s *pstate)
{
  uint32_t elapsed =  clock_systimer() - pstate->png_time;
  if (elapsed >= pstate->png_ticks)
    {
      return TRUE;
    }

  return FALSE;
}

/****************************************************************************
 * Name: icmpv6_echo_request
 *
 * Description:
 *   Format an ICMPv6 Echo Request message.. This version
 *   is for a standalone solicitation.  If formats:
 *
 *   - The Ethernet header
 *   - The IPv6 header
 *   - The ICMPv6 Echo Request Message
 *
 * Parameters:
 *   dev    - Reference to an Ethernet device driver structure
 *   pstate - Ping state structure
 *
 * Return:
 *   None
 *
 ****************************************************************************/

static void icmpv6_echo_request(FAR struct net_driver_s *dev,
                                FAR struct icmpv6_ping_s *pstate)
{
  FAR struct icmpv6_iphdr_s *icmp;
  FAR struct icmpv6_echo_request_s *req;
  uint16_t reqlen;
  int i;

  nllvdbg("Send ECHO request: seqno=%d\n", pstate->png_seqno);

  /* Set up the IPv6 header (most is probably already in place) */

  icmp          = ICMPv6BUF;
  icmp->vtc     = 0x60;                    /* Version/traffic class (MS) */
  icmp->tcf     = 0;                       /* Traffic class (LS)/Flow label (MS) */
  icmp->flow    = 0;                       /* Flow label (LS) */

  /* Length excludes the IPv6 header */

  reqlen        = SIZEOF_ICMPV6_ECHO_REQUEST_S(pstate->png_datlen);
  icmp->len[0]  = (reqlen >> 8);
  icmp->len[1]  = (reqlen & 0xff);

  icmp->proto   = IP_PROTO_ICMP6;          /* Next header */
  icmp->ttl     = IP_TTL;                  /* Hop limit */

  /* Set the multicast destination IP address */

  net_ipv6addr_copy(icmp->destipaddr,  pstate->png_addr);

  /* Add out IPv6 address as the source address */

  net_ipv6addr_copy(icmp->srcipaddr, dev->d_ipv6addr);

  /* Set up the ICMPv6 Echo Request message */

  req           = ICMPv6ECHOREQ;
  req->type     = ICMPv6_ECHO_REQUEST; /* Message type */
  req->code     = 0;                   /* Message qualifier */
  req->id       = htons(pstate->png_id);
  req->seqno    = htons(pstate->png_seqno);

  /* Add some easily verifiable data */

  for (i = 0; i < pstate->png_datlen; i++)
    {
      req->data[i] = i;
    }

  /* Calculate the checksum over both the ICMP header and payload */

  icmp->chksum  = 0;
  icmp->chksum  = ~icmpv6_chksum(dev);

  /* Set the size to the size of the IPv6 header and the payload size */

  IFF_SET_IPv6(dev->d_flags);

  dev->d_sndlen = reqlen;
  dev->d_len    = reqlen + IPv6_HDRLEN;

  nllvdbg("Outgoing ICMPv6 Echo Request length: %d (%d)\n",
          dev->d_len, (icmp->len[0] << 8) | icmp->len[1]);

#ifdef CONFIG_NET_STATISTICS
  g_netstats.icmpv6.sent++;
  g_netstats.ipv6.sent++;
#endif
}

/****************************************************************************
 * Function: ping_interrupt
 *
 * Description:
 *   This function is called from the interrupt level to perform the actual
 *   ECHO request and/or ECHO reply actions when polled by the lower, device
 *   interfacing layer.
 *
 * Parameters:
 *   dev        The structure of the network driver that caused the interrupt
 *   conn       The received packet, cast to void *
 *   pvpriv     An instance of struct icmpv6_ping_s cast to void*
 *   flags      Set of events describing why the callback was invoked
 *
 * Returned Value:
 *   Modified value of the input flags
 *
 * Assumptions:
 *   Running at the interrupt level
 *
 ****************************************************************************/

static uint16_t ping_interrupt(FAR struct net_driver_s *dev, FAR void *conn,
                               FAR void *pvpriv, uint16_t flags)
{
  FAR struct icmpv6_ping_s *pstate = (struct icmpv6_ping_s *)pvpriv;

  nllvdbg("flags: %04x\n", flags);

  if (pstate)
    {
      /* Check if this is a ICMPv6 ECHO reply.  If so, return the sequence
       * number to the caller.  NOTE: We may not even have sent the
       * requested ECHO request; this could have been the delayed ECHO
       * response from a previous ping.
       */

      if ((flags & ICMPv6_ECHOREPLY) != 0 && conn != NULL)
        {
          FAR struct icmpv6_echo_reply_s *reply = ICMPv6ECHOREPLY;

          nllvdbg("ECHO reply: id=%d seqno=%d\n",
                  ntohs(reply->id), ntohs(reply->seqno));

          if (ntohs(reply->id) == pstate->png_id)
            {
              /* Consume the ECHOREPLY */

              flags     &= ~ICMPv6_ECHOREPLY;
              dev->d_len = 0;

              /* Return the result to the caller */

              pstate->png_result = OK;
              pstate->png_seqno  = ntohs(reply->seqno);
              goto end_wait;
            }
        }

      /* Check:
       *   If the outgoing packet is available (it may have been claimed
       *   by a sendto interrupt serving a different thread)
       * -OR-
       *   If the output buffer currently contains unprocessed incoming
       *   data.
       * -OR-
       *   If we have already sent the ECHO request
       *
       * In the first two cases, we will just have to wait for the next
       * polling cycle.
       */

      if (dev->d_sndlen <= 0 &&             /* Packet available */
          (flags & ICMPv6_NEWDATA) == 0 &&  /* No incoming data */
          !pstate->png_sent)                /* Request not sent */
        {
          /* Send the ECHO request now. */

          icmpv6_echo_request(dev, pstate);
          pstate->png_sent = true;
          return flags;
        }

      /* Check if the selected timeout has elapsed */

      if (ping_timeout(pstate))
        {
          int failcode;

          /* Check if this device is on the same network as the destination
           * device.
           */

          if (!net_ipv6addr_maskcmp(pstate->png_addr, dev->d_ipv6addr,
                                    dev->d_ipv6netmask))
            {
              /* Destination address was not on the local network served by
               * this device.  If a timeout occurs, then the most likely
               * reason is that the destination address is not reachable.
               */

              nlldbg("Not reachable\n");
              failcode = -ENETUNREACH;
            }
          else
            {
              nlldbg("Ping timeout\n");
              failcode = -ETIMEDOUT;
            }

          /* Report the failure */

          pstate->png_result = failcode;
          goto end_wait;
        }

      /* Continue waiting */
    }

  return flags;

end_wait:
  nllvdbg("Resuming\n");

  /* Do not allow any further callbacks */

  pstate->png_cb->flags   = 0;
  pstate->png_cb->priv    = NULL;
  pstate->png_cb->event   = NULL;

  /* Wake up the waiting thread */

  sem_post(&pstate->png_sem);
  return flags;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: imcpv6_ping
 *
 * Description:
 *   Send a ECHO request and wait for the ECHO response
 *
 * Parameters:
 *   addr  - The IP address of the peer to send the ICMPv6 ECHO request to
 *           in network order.
 *   id    - The ID to use in the ICMPv6 ECHO request.  This number should be
 *           unique; only ECHO responses with this matching ID will be
 *           processed (host order)
 *   seqno - The sequence number used in the ICMPv6 ECHO request.  NOT used
 *           to match responses (host order)
 *   dsecs - Wait up to this many deci-seconds for the ECHO response to be
 *           returned (host order).
 *
 * Return:
 *   seqno of received ICMPv6 ECHO with matching ID (may be different
 *   from the seqno argument (may be a delayed response from an earlier
 *   ping with the same ID). Or a negated errno on any failure.
 *
 * Assumptions:
 *   Called from the user level with interrupts enabled.
 *
 ****************************************************************************/

int icmpv6_ping(net_ipv6addr_t addr, uint16_t id, uint16_t seqno,
                uint16_t datalen, int dsecs)
{
  struct icmpv6_ping_s state;
  net_lock_t save;

#ifdef CONFIG_NET_ICMPv6_NEIGHBOR
  int ret;

  /* Make sure that the IP address mapping is in the Neighbor Table */

  ret = icmpv6_neighbor(addr);
  if (ret < 0)
    {
      ndbg("ERROR: Not reachable\n");
      return -ENETUNREACH;
    }
#endif /* CONFIG_NET_ICMPv6_NEIGHBOR */

  /* Initialize the state structure */

  sem_init(&state.png_sem, 0, 0);
  state.png_ticks  = DSEC2TICK(dsecs);     /* System ticks to wait */
  state.png_result = -ENOMEM;              /* Assume allocation failure */
  state.png_id     = id;                   /* The ID to use in the ECHO request */
  state.png_seqno  = seqno;                /* The seqno to use in the ECHO request */
  state.png_datlen = datalen;              /* The length of data to send in the ECHO request */
  state.png_sent   = false;                /* ECHO request not yet sent */

  net_ipv6addr_copy(state.png_addr, addr); /* Address of the peer to be ping'ed */

  save             = net_lock();
  state.png_time   = clock_systimer();

  /* Set up the callback */

  state.png_cb = icmpv6_callback_alloc();
  if (state.png_cb)
    {
      state.png_cb->flags   = (ICMPv6_POLL | ICMPv6_ECHOREPLY);
      state.png_cb->priv    = (void*)&state;
      state.png_cb->event   = ping_interrupt;
      state.png_result      = -EINTR; /* Assume sem-wait interrupted by signal */

      /* Notify the device driver of the availability of TX data */

#ifdef CONFIG_NETDEV_MULTINIC
      netdev_ipv6_txnotify(g_ipv6_allzeroaddr, state.png_addr);
#else
      netdev_ipv6_txnotify(state.png_addr);
#endif

      /* Wait for either the full round trip transfer to complete or
       * for timeout to occur. (1) net_lockedwait will also terminate if a
       * signal is received, (2) interrupts may be disabled!  They will
       * be re-enabled while the task sleeps and automatically
       * re-enabled when the task restarts.
       */

      nllvdbg("Start time: 0x%08x seqno: %d\n", state.png_time, seqno);
      net_lockedwait(&state.png_sem);

      icmpv6_callback_free(state.png_cb);
    }

  net_unlock(save);

  /* Return the negated error number in the event of a failure, or the
   * sequence number of the ECHO reply on success.
   */

  if (!state.png_result)
    {
      nllvdbg("Return seqno=%d\n", state.png_seqno);
      return (int)state.png_seqno;
    }
  else
    {
      nlldbg("Return error=%d\n", -state.png_result);
      return state.png_result;
    }
}

#endif /* CONFIG_NET_ICMPv6_PING */