text:
package swift.indigo;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import swift.api.CRDTIdentifier;
import swift.application.test.TestsUtil;
import swift.clocks.Timestamp;
import swift.indigo.proto.AcquireResourcesReply;
import swift.indigo.proto.AcquireResourcesReply.AcquireReply;
import swift.indigo.proto.AcquireResourcesRequest;
import swift.indigo.proto.ResourceCommittedRequest;
import swift.indigo.proto.TransferResourcesRequest;
import swift.utils.LogSiteFormatter;
import sys.net.api.Endpoint;
import sys.net.api.Envelope;
import sys.net.api.Service;
import sys.utils.Args;
import sys.utils.ConcurrentHashSet;
import sys.utils.Profiler;
import sys.utils.Threading;

public class ResourceManagerNode implements ReservationsProtocolHandler {
	protected static final long DEFAULT_QUEUE_PROCESSING_WAIT_TIME = 1;

	// private static final int DEFAULT_REQUEST_TRANSFER_RATIO = 3;

	private IndigoResourceManager manager;

	// Incoming requests
	private Queue<IndigoOperation> incomingRequestsQueue;

	private transient PriorityQueue<TransferResourcesRequest> transferRequestsQueue;

	private boolean active;

	private Service stub;

	private Map<Timestamp, AcquireResourcesReply> replies = new ConcurrentHashMap<Timestamp, AcquireResourcesReply>();

	private IndigoSequencerAndResourceManager sequencer;

	private ResourceManagerNode thisManager = this;

	private Set<IndigoOperation> waitingIndex;

	private HashMap<CRDTIdentifier, ResourceRequest<?>> pendingRequests;

	private ExecutorService workers;

	private static Profiler profiler;

	private static String profilerName = "ManagerProfile";

	private Logger logger;

	public ResourceManagerNode(IndigoSequencerAndResourceManager sequencer, Endpoint surrogate, final Map<String, Endpoint> endpoints) {

		// Outgoing transfers queue
		Queue<TransferResourcesRequest> outgoingMessages = new LinkedList<>();

		// Incoming transfer requests are ordered by priority: promotes
		// exclusive_lock operations
		// and messages with smaller requests (size of requests was not tested)
		this.transferRequestsQueue = new PriorityQueue<TransferResourcesRequest>();
		// Incoming messages are ordered by FIFO order
		this.incomingRequestsQueue = new ConcurrentLinkedQueue<IndigoOperation>();

		this.waitingIndex = new ConcurrentHashSet<IndigoOperation>();
		this.pendingRequests = new HashMap<CRDTIdentifier, ResourceRequest<?>>();

		this.workers = Executors.newCachedThreadPool();
		this.manager = new IndigoResourceManager(sequencer, surrogate, endpoints, outgoingMessages, pendingRequests);
		this.stub = sequencer.stub;

		this.sequencer = sequencer;
		this.active = true;

		initLogging();

		final TransferFirstMessageBalacing messageBalancing = new TransferFirstMessageBalacing(incomingRequestsQueue, transferRequestsQueue);
		// Incoming requests processor thread

		new Thread(() -> {
			while (active) {
				IndigoOperation request = messageBalancing.nextOp();
				if (request != null)
					workers.execute(() -> {
						request.deliverTo(thisManager);
					});
				else
					Threading.sleep(DEFAULT_QUEUE_PROCESSING_WAIT_TIME);
			}
		}).start();

		new Thread(() -> {
			while (active) {
				TransferResourcesRequest request;
				synchronized (outgoingMessages) {
					while (outgoingMessages.isEmpty())
						Threading.waitOn(outgoingMessages, 10 * DEFAULT_QUEUE_PROCESSING_WAIT_TIME);
					request = outgoingMessages.poll();
				}
				if (request != null) {
					Endpoint endpoint = endpoints.get(request.getDestination());
					stub.send(endpoint, request);
				}
			}
		}).start();

	}
	public void process(TransferResourcesRequest request) {
		if (logger.isLoggable(Level.INFO)) {
			logger.info("Processing TransferResourcesRequest: " + request);
		}
		TRANSFER_STATUS reply = manager.transferResources(request);
		if (reply.equals(TRANSFER_STATUS.SUCCESS) || reply.equals(TRANSFER_STATUS.ALREADY_SATISFIED)) {
			synchronized (pendingRequests) {
				for (ResourceRequest<?> req_i : request.getResources()) {
					pendingRequests.remove(req_i.getResourceId());
				}
			}
		}
		waitingIndex.remove(request);
		if (logger.isLoggable(Level.INFO)) {
			logger.info("Finished TransferResourcesRequest: " + request + " Reply: " + reply);
		}
	}

	public void process(ResourceCommittedRequest request) {
		if (logger.isLoggable(Level.INFO)) {
			logger.info("Processing ReleaseResourcesRequest " + request);
		}
		long opId = profiler.startOp(profilerName, "release");
		Timestamp ts = request.getClientTs();
		AcquireResourcesReply arr = replies.get(ts);
		if (arr != null && !arr.isReleased()) {
			if (arr.acquiredResources()) {
				manager.releaseResources(arr);
				arr.setReleased();
				waitingIndex.remove(request);
			}
		}
		profiler.endOp(profilerName, opId);
		if (logger.isLoggable(Level.INFO))
			logger.info("Finished ReleaseResourcesRequest" + request);

	}
	public void processWithReply(Envelope conn, AcquireResourcesRequest request) {
		if (logger.isLoggable(Level.INFO))
			logger.info("Processing AcquireResourcesRequest " + request);
		AcquireResourcesReply reply = null;
		long opId = profiler.startOp(profilerName, "acquire");
		reply = manager.acquireResources(request);
		if (reply.acquiredStatus().equals(AcquireReply.YES)) {
			replies.put(request.getClientTs(), reply);
		}
		waitingIndex.remove(request);
		profiler.endOp(profilerName, opId);
		conn.reply(reply);
		if (logger.isLoggable(Level.INFO))
			logger.info("Finished AcquireResourcesRequest " + request + " Reply: " + reply + " " + reply.getSnapshot());

	}
	/**
	 * Message handlers
	 */

	@Override
	public void onReceive(Envelope conn, AcquireResourcesRequest request) {
		request.setHandler(conn);
		AcquireResourcesReply reply = null;
		profiler.trackRequest(profilerName, request);
		if (request.getResources().size() == 0) {
			reply = new AcquireResourcesReply(AcquireReply.NO_RESOURCES, sequencer.clocks.currentClockCopy());
		} else {
			if (checkAcquireAlreadyProcessed(request) != null) {
				if (logger.isLoggable(Level.INFO))
					logger.info("Received an already processed message: " + request + " REPLY: " + replies.get(request.getClientTs()));
				reply = replies.get(request.getClientTs());
			} else {
				if (isDuplicate(request)) {
					if (logger.isLoggable(Level.INFO))
						logger.info("ignore duplicate request: " + request);
				} else {
					synchronized (incomingRequestsQueue) {
						incomingRequestsQueue.add(request);
					}
				}
			}
		}
		if (reply != null)
			conn.reply(reply);
	}
	@Override
	public void onReceive(Envelope conn, TransferResourcesRequest request) {
		if (!isDuplicate(request)) {
			synchronized (transferRequestsQueue) {
				transferRequestsQueue.add(request);
			}
		} else {
			logger.info("repeated message");
		}
	}

	@Override
	public void onReceive(Envelope conn, ResourceCommittedRequest request) {
		AcquireResourcesReply reply = replies.get(request.getClientTs());

		synchronized (pendingRequests) {
			for (CRDTIdentifier id : request.getUpdatedCRDTs()) {
				Map<String, SortedSet<ResourceRequest<?>>> updatedResources = new HashMap<>();
				if (pendingRequests.containsKey(id)) {
					ResourceRequest<?> pendingRequest = pendingRequests.get(id);
					SortedSet<ResourceRequest<?>> sitePendingRequests = updatedResources.get(pendingRequest.getRequesterId());
					if (sitePendingRequests == null) {
						sitePendingRequests = new TreeSet<>();
						updatedResources.put(pendingRequest.getRequesterId(), sitePendingRequests);
					}
					sitePendingRequests.add(pendingRequest);
				}
				synchronized (incomingRequestsQueue) {
					for (Entry<String, SortedSet<ResourceRequest<?>>> entry : updatedResources.entrySet()) {
						TransferResourcesRequest transfer = new TransferResourcesRequest(entry.getKey(), sequencer.siteId, manager.transferSeqNumber.incrementAndGet(), entry.getValue());
						incomingRequestsQueue.add(transfer);
					}
				}
			}
		}

		if (reply != null && !reply.isReleased()) {
			if (!isDuplicate(request)) {
				boolean hasLock = false;
				for (ResourceRequest<?> resource : reply.getResourcesRequest()) {
					if (resource instanceof LockReservation) {
						hasLock = true;
						break;
					}
				}
				if (hasLock)
					incomingRequestsQueue.add(request);
				else {
					reply.setReleased();
				}
			}
		}
	}

	/**
	 * Private methods
	 */

	// If messages is already enqueued for processing ignore new request
	private boolean isDuplicate(IndigoOperation request) {
		if (!waitingIndex.add(request))
			return true;
		else
			return false;
	}

	private AcquireResourcesReply checkAcquireAlreadyProcessed(AcquireResourcesRequest request) {
		AcquireResourcesReply reply = replies.get(request.getClientTs());

		if (reply != null && logger.isLoggable(Level.INFO))
			logger.info("Reply from cache: " + reply);

		if (reply != null)
			return reply;
		return null;
	}

	private void initLogging() {

		ConsoleHandler handler = new ConsoleHandler();
		handler.setFormatter(new LogSiteFormatter(sequencer.siteId));
		logger = Logger.getLogger(this.getClass().getName() + "." + sequencer.siteId);
		logger.setUseParentHandlers(false);
		logger.addHandler(handler);

		Logger logger = Logger.getLogger(profilerName);
		profiler = Profiler.getInstance();
		if (logger.isLoggable(Level.FINEST)) {
			FileHandler fileTxt;
			try {
				String resultsDir = Args.valueOf("-results_dir", ".");
				String siteId = Args.valueOf("-siteId", "GLOBAL");
				String suffix = Args.valueOf("-fileNameSuffix", "");
				fileTxt = new FileHandler(resultsDir + "/manager_profiler" + "_" + siteId + suffix + ".log");
				fileTxt.setFormatter(new java.util.logging.Formatter() {
					@Override
					public String format(LogRecord record) {
						return record.getMessage() + "\n";
					}
				});
				logger.addHandler(fileTxt);
				profiler.printMessage(profilerName, TestsUtil.dumpArgs());
			} catch (Exception e) {
				e.printStackTrace();
				System.exit(0);
			}
		}
		profiler.printHeaderWithCustomFields(profilerName);

	}

}

class SimpleMessageBalacing {

	enum OPType {
		TRANSFER, REQUEST
	}

	private AtomicInteger transfers;
	private AtomicInteger requests;
	private final int ratio;

	private Queue<IndigoOperation> requestQueue;
	private Queue<TransferResourcesRequest> transferQueue;

	public SimpleMessageBalacing(int requestTransferRatio, Queue<IndigoOperation> requestQueue, Queue<TransferResourcesRequest> transferQueue) {
		this.ratio = requestTransferRatio;
		this.requestQueue = requestQueue;
		this.transferQueue = transferQueue;
		this.requests = new AtomicInteger();
		this.transfers = new AtomicInteger();
	}

	private void registerOp(OPType op) {
		int count;
		switch (op) {
			case TRANSFER :
				count = transfers.incrementAndGet();
				transfers.set(0);
				break;
			case REQUEST :
				count = requests.incrementAndGet();
				if (count == ratio)
					requests.set(0);
				break;
		}
	}

	public IndigoOperation nextOp() {
		int nRequests, nTransfers;
		synchronized (this) {
			nRequests = requests.get();
			nTransfers = transfers.get();
		}
		if (requestQueue.size() > 0 && (nRequests - nTransfers <= ratio || transferQueue.size() == 0)) {
			registerOp(OPType.REQUEST);
			return requestQueue.remove();
		} else if (transferQueue.size() > 0) {
			registerOp(OPType.TRANSFER);
			synchronized (transferQueue) {
				return transferQueue.remove();
			}
		} else
			return null;
	}

	public String toString() {
		return "REQ: " + requestQueue + " TRANS: " + transferQueue;
	}
}

class TransferFirstMessageBalacing {

	enum OPType {
		TRANSFER, REQUEST
	}

	private Queue<IndigoOperation> requestQueue;
	private Queue<TransferResourcesRequest> transferQueue;

	public TransferFirstMessageBalacing(Queue<IndigoOperation> requestQueue, Queue<TransferResourcesRequest> transferQueue) {
		this.requestQueue = requestQueue;
		this.transferQueue = transferQueue;
	}

	public IndigoOperation nextOp() {
		IndigoOperation op = null;
		if (transferQueue.size() > 0) {
			synchronized (transferQueue) {
				op = transferQueue.remove();
			}
		} else if (requestQueue.size() > 0) {
			synchronized (requestQueue) {
				op = requestQueue.remove();
			}
		}
		return op;
	}

	public String toString() {
		return "REQ: " + requestQueue + " TRANS: " + transferQueue;
	}

}


text:
class PostRevision < ActiveRecord::Base
  belongs_to :post
  belongs_to :user

  serialize :modifications, Hash
end

redpajama_set_name: RedPajamaGithub


text:
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums.length == 0 || k == 0) return new int[] {};
        if (k == 1) return nums;

        int leftIndex = 0;
        int rightIndex = 0;

        int[] result = new int[nums.length - k + 1];

        Deque<Integer> deque = new ArrayDeque<>();

        while (rightIndex < nums.length) {
            if (rightIndex - leftIndex < k)  {
                offer(deque, nums, rightIndex);
                rightIndex++;
            } else {
                result[leftIndex] = nums[deque.getFirst()];

                if (leftIndex == deque.getFirst()) {
                    deque.removeFirst();
                }

                leftIndex++;
            }
        }

        result[leftIndex] = nums[deque.getFirst()];
        return result;
    }

    public void offer(Deque<Integer> deque, int[] nums, int index) {
        while (!deque.isEmpty() && nums[deque.getLast()] < nums[index]) {
            deque.removeLast();
        }

        deque.addLast(index);
    }
}


text:
/***
|''Name''|TiddlySpaceRevisionView|
|''Description''|Show tiddler revisions in a stack of cards view|
|''Author''|BenGillies|
|''Version''|0.2.0|
|''Status''|beta|
|''Source''|http://github.com/TiddlySpace/tiddlyspace|
|''CodeRepository''|http://github.com/TiddlySpace/tiddlyspace|
|''License''|[[BSD|http://www.opensource.org/licenses/bsd-license.php]]|
|''CoreVersion''|2.6.0|
|''Requires''|TiddlyWebAdaptor|
!Usage
The viewRevisions macro can be attached to any element, which should be passed
in as a parameter.

For example:

<<viewRevisions page:10 link:"<<view modified date>>">>

would show the revisions "stack of cards" view, 10 at a time, when the modified
date is clicked.
!Code
***/
//{{{
(function($) {

var me = config.macros.viewRevisions = {
	revisionTemplate: "RevisionTemplate",
	revSuffix: " [rev. #%0]", // text to append to each tiddler title
	defaultPageSize: 5, // default number of revisions to show
	defaultLinkText: "View Revisions", // when there's nothing else to use
	offsetTop: 30, // in px
	offsetLeft: 10, // in px
	shiftDownDelay: 50, // in ms
	visibleSlideAmount: 20, // amount of revisions to show on left hand edge after sliding
	zIndex: 100, // default z-index
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		params = paramString.parseParams(null, null, true)[0];
		var tiddlerElem = story.findContainingTiddler(place);

		var revButton;
		var pageSize = parseInt(params.page[0], 10) || me.defaultPageSize;
		var linkObj = params.link ? params.link[0] || me.defaultLinkText : false;
		if(linkObj) {
			revButton = $('')
				.appendTo(place);
			wikify(linkObj, revButton[0], null, tiddler);
		} else {
			revButton = place;
		}

		$(revButton).click(function() {
			if (!$(tiddlerElem).hasClass("revisions")) {
				me.showRevisions(tiddlerElem, tiddler, pageSize);
			} else {
				me.closeRevisions(tiddlerElem);
			}
		});
	},

	// initialisation for revision view
	showRevisions: function(tiddlerElem, tiddler, pageSize) {
		var context = {
			host: tiddler.fields["server.host"],
			workspace: tiddler.fields["server.workspace"]
		};
		$(tiddlerElem).addClass("revisions").attr("revName", tiddler.title);
		// ensure toolbar commands deactivate RevisionsView
		$("a", ".toolbar", tiddlerElem).each(function(index, btn) {
			var _onclick = btn.onclick;
			btn.onclick = function(e) {
				me.closeRevisions(tiddlerElem);
				_onclick.apply(this, arguments);
			};
		});
		// ensure default action deactivates RevisionsView
		var _ondblclick = tiddlerElem.ondblclick;
		tiddlerElem.ondblclick = function(e) {
			me.closeRevisions(tiddlerElem);
			_ondblclick.apply(this, arguments);
		};
		var type = tiddler.fields["server.type"];
		var adaptor = new config.adaptors[type]();
		var userParams = {
			tiddlerElem: tiddlerElem,
			pageSize: pageSize,
			title: tiddler.title
		};
		me.createCloak(tiddlerElem);
		adaptor.getTiddlerRevisionList(tiddler.title, null, context, userParams,
				function(context, userParams) {
					// strip the current revision
					context.revisions.shift();
					me.expandStack(context, userParams);
				});
	},

	// fetch the actual revision and put it in the tiddler div
	showRevision: function(place, revision, callback) {
		var context = {
			host: revision.fields["server.host"],
			workspace: revision.fields["server.workspace"]
		};
		var userParams = {
			revElem: place
		};
		var type = revision.fields["server.type"];
		var adaptor = new config.adaptors[type]();
		var revNo = revision.fields["server.page.revision"];
		adaptor.getTiddlerRevision(revision.title, revNo, context, userParams,
			function(context, userParams) {
				var tiddler = context.tiddler;
				tiddler.title += me.revSuffix
					.format([$(place).attr("revision")]);
				tiddler.fields.doNotSave = true;
				if (store.getTiddler(tiddler.title)) {
					store.deleteTiddler(tiddler.title);
				}
				store.addTiddler(tiddler);

				//now, populate the existing div
				var revElem = userParams.revElem;
				$(revElem).attr("id", story.tiddlerId(tiddler.title));
				$(revElem).attr("refresh", "tiddler");
				var getTemplate = function() {
					var themeName = config.options.txtTheme;
					if (themeName) {
						return store.getTiddlerSlice(themeName,
							me.revisionTemplate) || me.revisionTemplate ||
							"ViewTemplate";
					} else {
						return (store.getTiddler(me.revisionTemplate)) ?
							me.revisionTemplate : "ViewTemplate";
					}
				};
				var template = getTemplate();
				story.refreshTiddler(tiddler.title, template, true);
				callback(tiddler);
			});
	},

	createCloak: function(promoteElem) {
		var el = $(promoteElem);
		// cache styles for resetting later
		el.data({
			top: el.css("top"),
			left: el.css("left"),
			zIndex: el.css("z-index")
		});

		$('
').css("z-index", me.zIndex)
			.click(function() {
				me.closeRevisions(promoteElem);
			})
			.appendTo(document.body);

		el.css("z-index", me.zIndex + 1);
	},

	// clean up, removing all evidence of revision view
	closeRevisions: function(promoteElem) {
		var el = $(promoteElem);
		// revert the original tiddler back to its previous state
		el.removeAttr("revName").removeClass("revisions").css({
			top: el.data("top"),
			left: el.data("left"),
			zIndex: el.data("zIndex")
		});

		// remove any revisions still in the store
		var revisions = $(".revisions");
		revisions.each(function(index, revision) {
			var revAttributes = revision.attributes;
			if ((revAttributes.revname) &&
					(revAttributes.revision)) {
				var revName = revAttributes.revname.value;
				var revNo = revAttributes.revision.value;
				var title = revName + me.revSuffix.format([revNo]);

				if (store.getTiddler(title)) {
					store.deleteTiddler(title);
				}
			}
		});

		// delete the previous revisions
		revisions.remove();

		// remove the cloak
		$(".revisionCloak").remove();
	},

	// calback from getting list of revisions
	expandStack: function(context, userParams) {
		var pageSize = userParams.pageSize;

		var from = userParams.from || 0;
		var tiddlerElem = userParams.tiddlerElem;

		userParams.defaultHeight = $(tiddlerElem).height();
		userParams.defaultWidth = $(tiddlerElem).width();
		if (from < context.revisions.length) {
			me.displayNextRevision(tiddlerElem, userParams, context, from,
				from + pageSize - 1);
		}
	},

	// place the next div above and behind the previous one
	displayNextRevision: function(tiddlerElem, userParams, context, from, to) {
		var revision = context.revisions[from];
		var callback = function() {
			var revText = revBtn.getRevisionText(tiddlerElem, revision);
			tiddlerElem = me.createRevisionObject(tiddlerElem, context,
				userParams, revText);
			$(tiddlerElem)
				.attr("revision", (context.revisions.length - from));
			if ((from < to) && ((from + 1) < context.revisions.length)){
				me.displayNextRevision(tiddlerElem, userParams, context,
					from + 1, to);
			} else if ((context.revisions.length - 1) > to) {
				me.showMoreButton(tiddlerElem, context, userParams, to + 1);
			}
		};
		me.shiftVisibleDown(userParams.title, callback);
	},

	createRevisionObject: function(tiddlerElem, context, userParams, text) {
		var newPosition = me.calculatePosition(tiddlerElem, context);
		return $('
')
			.css({
				position: "absolute",
				top: newPosition.top,
				left: newPosition.left,
				"z-index": me.zIndex + 1,
				height: userParams.defaultHeight,
				width: userParams.defaultWidth
			})
			.attr("revName", userParams.title)
			.append(text)
			.insertBefore(tiddlerElem);
	},

	// move the already present revisions down by 1 to fit the next one in
	shiftVisibleDown: function(title, callback) {
		var revisions = $("[revName='%0'].revisions".format([title]));
		var revisionCount = revisions.length;

		$(revisions).animate({top: "+=" + me.offsetTop},
				me.shiftDownDelay, function() {
					revisionCount -= 1;
					if ((callback) && (!revisionCount)) {
						callback();
					}
				});
	},

	// where we put the new revision
	calculatePosition: function(elem, context) {
		var offset = $(elem).offset();
		var currentPosition = $(elem).position();
		var newPosition = {
			top: currentPosition.top - me.offsetTop
		};
		if ((context.restrictLeft) ||
				((offset.left - me.offsetLeft) <
				$("#contentWrapper").offset().left)) {
			newPosition.left = $(elem).position().left;
			context.restrictLeft = true;
		} else {
			newPosition.left = currentPosition.left - me.offsetLeft;
		}
		return newPosition;
	},

	// equivalent of displayNextRevision, but for the more button
	showMoreButton: function(tiddlerElem, context, userParams, moreIndex) {
		userParams.from = moreIndex + 1;
		me.shiftVisibleDown(userParams.title, function() {
			var btn = me.createRevisionObject(tiddlerElem, context, userParams,
				"");

			var more = createTiddlyButton(btn[0], "more...", "show more revisions",
				function() {
					if ($(".viewRevision").length) {
						return;
					}
					userParams.tiddlerElem = btn[0];
					$(btn).text("")
						.append(revBtn
							.getRevisionText(btn[0], context.revisions[moreIndex]))
						.attr("revision", context.revisions.length - moreIndex);
					me.expandStack(context, userParams);
				});
			$(more).css("float", "right");
		});
	},

	stripRevFromTitle: function(revisionTitle) {
		return revisionTitle.split(/ ?\[rev\. #[0-9]+\]$/)[0];
	},

	onClickRevision: function(revElem, revision, callback) {
		// don't do anything if we are still loading
		if ($(".revisions").hasClass("loading")) {
			return null;
		}

		var origTitle = me.stripRevFromTitle(revision.title);
		if ($(revElem).hasClass("viewRevision")) {
			$(".revisions").addClass("loading");
			me.slideIn(revElem, revision, origTitle, function() {
				store.deleteTiddler(revision.title);
				revision.title = origTitle;
				$(revElem).text("").append(revBtn.getRevisionText(revElem,
						revision))
					.removeAttr("tags").removeAttr("tiddler")
					.removeAttr("refresh").removeAttr("template")
					.removeAttr("id");
				$(".revisions").removeClass("loading");
				if (callback) {
					callback();
				}
			});
			$(revElem).removeAttr("prevPos").removeClass("viewRevision");
		} else {
			var viewRevision = function() {
				var prevPos = $(revElem).position().left;
				$(revElem).addClass("viewRevision").attr("prevPos", prevPos);
				$(".revisions").addClass("loading");
				me.showRevision(revElem, revision, function(rev) {
					me.slideOut(revElem, rev, origTitle, function() {
						$(".revisions").removeClass("loading");
					});
				});
			};
			// make sure another revision isn't already out
			if ($(".viewRevision").length) {
				var newRevElem = $(".viewRevision")[0];
				var newRevision = store.getTiddler($(newRevElem)
					.attr("tiddler"));
				me.onClickRevision(newRevElem, newRevision, viewRevision);
			} else {
				viewRevision();
			}
		}
	},

	slideOut: function(revElem, revision, title, callback) {
		var leftMostPos = $("[revName='%0'].revisions".format([title]))
			.offset().left;
		var width = $(revElem).width();
		var originalLeftPos = $(story.getTiddler(title))
			.position().left;

		var slideAmount = leftMostPos + width - me.visibleSlideAmount;
		$("[revName='%0'].revisions:not(.viewRevision)".format([title]))
			.animate({left: "-=" + slideAmount}, 1000);
		$(revElem)
			.attr("baseHeight", $(revElem).css("height"))
			.css("height", "auto")
			.animate({left: originalLeftPos}, 1000, callback);
	},

	slideIn: function(revElem, revision, title, callback) {
		var slideAmount = $(revElem).offset().left -
			$(story.getTiddler(title)).offset().left;
		var origRevPos = $(revElem).attr("prevPos");

		$("[revName='%0'].revisions:not(.viewRevision)".format([title]))
			.animate({left: "+=" + slideAmount}, 1000);
		$(revElem).animate({left: origRevPos}, 1000, function() {
			$(revElem)
				.css("height", $(revElem).attr("baseHeight"))
				.removeAttr("baseHeight");
			callback();
		});
	}
};

var revBtn;
config.macros.slideRevision = revBtn = {
	btnText: "created by %0 at %1 on %2",
	handler: function(place, macroName, params, wikifier, paramString, tiddler) {
		var btn = revBtn.getRevisionText(place, tiddler);
		$(place).append(btn);
	},

	getRevisionText: function(place, revision) {
		var text = revBtn.btnText.format([revision.modifier,
			revision.modified.formatString("0hh:0mm"),
			revision.modified.formatString("0DD MMM YYYY")]);
		var btn = $('')
			.text(text)
			.click(function() {
				var revElem = story.findContainingTiddler(this);
				me.onClickRevision(revElem, revision);
			});
		return btn;
	}
};

})(jQuery);
//}}}


text:
/*
 * src/energy.h
 *
 * Function to compute the energy of each pixel of an image.
 *
 * author: Hugues de Valon
 * mail: hugues.devalon@gmail.com
 * date: 29/07/2016
 */

#ifndef __ENERGY__
#define __ENERGY__

#include <stdint.h>

/*
 * Returns the calculated horizontal gradient of the image.
 * The energy array is allocaed and need to be freeed.
 * Returns NULL on error.
 */
uint8_t **gradienty(uint8_t **image, uint32_t lines, uint32_t columns);

#endif /* __ENERGY__ */


text:
<?php
namespace AppInterFace\Model\GoodsStock;
use AppInterFace\Model\GoodsStock\GoodsStockBaseModel;

class GoodsStockModel extends GoodsStockBaseModel{
    private $goodsId;
    private $intervalTime;
    protected $autoCheckFields = false;
    private $dbConfig ;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->intervalTime='+3 Month';
        $this->dbConfig ['LINE_TYPE']= 'trl_line_type';
        $this->dbConfig['LINE_STOCK'] = 'trl_line_stock';
        //查看从今天开始加3个月后的库存数量
    }

    public function response(){
        $intervalTime = $this->intervalTime;
        $config = $this->dbConfig;
        $goodsId = $this->getGoodsId();
        $where[$config['LINE_TYPE'].'.gid'] = array('eq',$goodsId);
        $where[$config['LINE_STOCK'].'.date_time'] = array(array('gt',time()),array('lt',strtotime($intervalTime)),'and');
        $where[$config['LINE_TYPE'].'.status'] = array('eq','1');
        $where[$config['LINE_STOCK'].'.status'] = array('eq','1');
        $field[] = $config['LINE_STOCK'].'.type';
        $field[] = $config['LINE_STOCK'].'.number';
        $field[] = $config['LINE_STOCK'].'.price';
        $field[] = $config['LINE_TYPE'].'.gid';
        $result = $this->table($config['LINE_TYPE'])->where($where)->join('__LINE_STOCK__ ON __LINE_TYPE__.id = __LINE_STOCK__.type')->fetchSql(false)->field($field)->select();
        return $result;
    }

    //获取最近三个月的库存信息
    public function setResponseTime(){

    }

    //设置商品的id
    public function setGoodsId($goodsId){

        $this->goodsId = $goodsId;

    }

    //获取商品的id
    private function getGoodsId(){
        $goodsId = $this->goodsId;
        if(empty($goodsId)){
            echo '商品id不能为空!';
            exit;
        }
        return $goodsId;
    }
}


text:
Returns analogous variations of the given color.
`returned[0]`: first analogous variation ( spinning given color by 30 degrees )
`returned[1]`: second analogous variation ( spinning given color by -30 degrees )

### Signature

`analogous( color )`

* `color`: color to perform analogous variations.

### Usage

```stylus
variations = analogous( #f00 )

.red-analog-one
    color variations[0]

.red-analog-two
    color variations[1]
```

### Result

```css
.red-analog-one {
  color: #ff8000;
}

.red-analog-two {
  color: #ff0080;
}
```


text:
AutoSeqGroup::AutoSeqGroup() {
        // Add Commands here:
        // e.g. AddSequential(new Command1());
        //      AddSequential(new Command2());
        // these will run in order.

        // To run multiple commands at the same time,
        // use AddParallel()
        // e.g. AddParallel(new Command1());
        //      AddSequential(new Command2());
        // Command1 and Command2 will run in parallel.

        // A command group will require all of the subsystems that each member
        // would req  uire.
        // e.g. if Command1 requires chassis, and Command2 requires arm,
        // a CommandGroup containing them would require both the chassis and the
        // arm.
	//AddSequential(new TiltToAngle(25.5));
	AddSequential(new TiltToPotAngle(2.598));

	AddSequential(new ToggleShooter());
	AddSequential(new ToggleShooter());

	AddSequential(new WaitCom());
	AddSequential(new SingleFire());
	AddSequential(new SingleFire());
	AddSequential(new SingleFire());
	AddSequential(new SingleFire());//4

	AddSequential(new KillShooter());

}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150713162423 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

//        $this->addSql("CREATE TABLE turno_unidad_educativa (id INT AUTO_INCREMENT NOT NULL, unidad_educativa_id INT DEFAULT NULL, turno_id INT DEFAULT NULL, INDEX IDX_167633EABF20CF2F (unidad_educativa_id), INDEX IDX_167633EA69C5211E (turno_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
        $this->addSql("CREATE TABLE secundariox_orientacion (secundariox_id INT NOT NULL, orientacion_id INT NOT NULL, INDEX IDX_98FC28242ED5694E (secundariox_id), INDEX IDX_98FC2824F73C956F (orientacion_id), PRIMARY KEY(secundariox_id, orientacion_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
//        $this->addSql("ALTER TABLE turno_unidad_educativa ADD CONSTRAINT FK_167633EABF20CF2F FOREIGN KEY (unidad_educativa_id) REFERENCES unidad_educativa (id)");
//        $this->addSql("ALTER TABLE turno_unidad_educativa ADD CONSTRAINT FK_167633EA69C5211E FOREIGN KEY (turno_id) REFERENCES turno (id)");
        $this->addSql("ALTER TABLE secundariox_orientacion ADD CONSTRAINT FK_98FC28242ED5694E FOREIGN KEY (secundariox_id) REFERENCES secundario_x (id)");
        $this->addSql("ALTER TABLE secundariox_orientacion ADD CONSTRAINT FK_98FC2824F73C956F FOREIGN KEY (orientacion_id) REFERENCES media_orientaciones (id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

//        $this->addSql("DROP TABLE turno_unidad_educativa");
        $this->addSql("DROP TABLE secundariox_orientacion");
    }
}


text:
package controllers

import es.weso.computex.entities._
import es.weso.computex.entities.Action._
import play.api.mvc.Action
import play.api.mvc.Controller
import es.weso.computex.PREFIXES

object Prefixes extends Controller {

  def sparql = Action {
    Ok(PREFIXES.prefixTemplateSparql)
  }

  def turtle = Action {
    Ok(PREFIXES.prefixTemplateTurtle)
  }

  def html = Action {
    Ok(PREFIXES.prefixTemplateHTML).as("text/html")
  }

  def json = Action {
    Ok(PREFIXES.prefixTemplateJSON).as("application/json")
  }
}


text: IdentityServer3.Admin Integration library for Asp.NET 5


text:
//
//  CustomTextField.m
//  Leisure
//
//  Created by 沈强 on 16/4/8.
//  Copyright © 2016年 SQ. All rights reserved.
//

#import "CustomTextField.h"

@interface CustomTextField ()
{
    int _a;
}

@end

static NSString * const SQPlacerholderColorKeyPath = @"_placeholderLabel.textColor";

@implementation CustomTextField

- (void)awakeFromNib {
    // 不成为第一响应者
    [self resignFirstResponder];

    // 设置光标颜色和文字颜色一致
    self.tintColor = self.textColor;
}

/**
 *  当前文本框聚焦时就会调用
 */
- (BOOL)becomeFirstResponder {
    // 修改placeholder(占位)文字颜色
    [self setValue:self.textColor forKeyPath:SQPlacerholderColorKeyPath];
    return [super becomeFirstResponder];
}

/**
 *  当前文本框失去焦点时就会调用
 */
- (BOOL)resignFirstResponder {
    // 修改placeholder(占位)文字颜色
    [self setValue:[UIColor grayColor] forKeyPath:SQPlacerholderColorKeyPath];
    return [super resignFirstResponder];
}

@end


text:
from app import MongoSplitter as MS
import logging
config = {
        "db_name": "test",
        "collection_name": "in",
        "split_size": 1, #MB
        "input_uri": "mongodb://localhost/test.in",
        "create_input_splits": False,
        "split_key": {'_id' : 1}, }

def test_single_split():
    splits = MS.calculate_splits(config)
    print splits
    assert splits

if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    test_single_split()


text:
using System;
using System.Collections;
using System.Windows.Input;
using Xamarin.Forms;

namespace XForms.Controls
{
	public class ListPicker : Picker
	{
		public static BindableProperty ConverterProperty =
				BindableProperty.Create<ListPicker, IValueConverter>(o => o.Converter,
					default(IValueConverter), BindingMode.TwoWay, null,
					null, null, null);

		public static BindableProperty ItemsSourceProperty =
				BindableProperty.Create<ListPicker, IEnumerable>(o => o.ItemsSource,
					default(IEnumerable), BindingMode.OneWay, null,
					new BindableProperty.BindingPropertyChangedDelegate<IEnumerable>(OnItemsSourceChanged), null, null);

		public static BindableProperty SelectedItemProperty =
				BindableProperty.Create<ListPicker, object>(o => o.SelectedItem,
					default(object), BindingMode.TwoWay, null,
					new BindableProperty.BindingPropertyChangedDelegate<object>(OnSelectedItemChanged), null, null);

		public static BindableProperty ItemSelectedCommandProperty =
				BindableProperty.Create<ListPicker, ICommand>(o => o.ItemSelectedCommand,
					default(ICommand), BindingMode.OneWay, null,
					null, null, null);

		public IValueConverter Converter
		{
			get { return (IValueConverter)GetValue(ConverterProperty); }
			set { SetValue(ConverterProperty, value); }
		}

		public IList ItemsSource
		{
			get { return (IList)GetValue(ItemsSourceProperty); }
			set { SetValue(ItemsSourceProperty, value); }
		}

		public object SelectedItem
		{
			get { return GetValue(SelectedItemProperty); }
			set { SetValue(SelectedItemProperty, value); }
		}

		public ICommand ItemSelectedCommand
		{
			get { return (ICommand)GetValue(ItemSelectedCommandProperty); }
			set { SetValue(ItemSelectedCommandProperty, value); }
		}

		public ListPicker()
		{
			SelectedIndexChanged += OnSelectedIndexChanged;

		}

		private static void OnItemsSourceChanged(BindableObject bindable, IEnumerable oldvalue, IEnumerable newvalue)
		{
			try
			{
				var picker = bindable as ListPicker;
				if (newvalue != null && picker != null)
				{
					picker.Items.Clear();
					foreach (var item in newvalue)
					{
						picker.Items.Add(picker.Convert(item, picker.Converter));
					}
				}
			}
			catch
			{
				//To solve navigation issues
			}
		}

		private string Convert(object input, IValueConverter converter)
		{
			return converter == null
				? input.ToString()
				: (string)converter.Convert(input, typeof(string), null, System.Globalization.CultureInfo.CurrentUICulture);
		}

		private void OnSelectedIndexChanged(object sender, EventArgs eventArgs)
		{
			if (SelectedIndex < 0 || SelectedIndex > Items.Count - 1)
			{
				SelectedItem = null;
			}
			else
			{
				SelectedItem = ItemsSource[SelectedIndex];

				ItemSelectedCommand?.Execute(SelectedItem);
			}
		}
		private static void OnSelectedItemChanged(BindableObject bindable, object oldvalue, object newvalue)
		{
			var picker = bindable as ListPicker;
			if (newvalue != null && picker != null)
			{
				picker.SelectedIndex = picker.ItemsSource.IndexOf(newvalue);
			}
		}
	}
}


text:
import React from 'react';
import { inject, observer } from 'mobx-react'

import { Alert, Col, Grid, Row } from 'react-bootstrap'

@inject('appStore')
@observer
export default class Menu extends React.Component {

  render = () => {
    const { message } = this.props.appStore

    return (
      <Row className="container-fluid">
        <Col xs={18} md={12}>
          {message && <Alert bsStyle={message.type}>{message.text}</Alert>}
        </Col>
      </Row>
    )
  }

}


text:
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { CreditCardValidators } from "ngx-validators";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-reactive-discover",
  templateUrl: "./reactive-form-discover.component.html",
})
export class ReactiveFormDiscoverComponent implements OnInit {
  form: FormGroup;
  creditcard = new FormControl("", Validators.compose([CreditCardValidators.discover]));
  constructor(protected _fb: FormBuilder) {}

  ngOnInit() {
    this.form = this._fb.group({
      creditcard: this.creditcard,
    });
  }
}


text:
/**
 * Firebase project management.
 *
 * @packageDocumentation
 */

import { App, getApp } from '../app';
import { FirebaseApp } from '../app/firebase-app';
import { ProjectManagement } from './project-management';

export { AppMetadata, AppPlatform } from './app-metadata';
export { ProjectManagement } from './project-management';
export { AndroidApp, AndroidAppMetadata, ShaCertificate } from './android-app';
export { IosApp, IosAppMetadata } from './ios-app';

/**
 * Gets the {@link ProjectManagement} service for the default app or a given app.
 *
 * `getProjectManagement()` can be called with no arguments to access the
 * default app's `ProjectManagement` service, or as `getProjectManagement(app)` to access
 * the `ProjectManagement` service associated with a specific app.
 *
 * @example
 * ```javascript
 * // Get the ProjectManagement service for the default app
 * const defaultProjectManagement = getProjectManagement();
 * ```
 *
 * @example
 * ```javascript
 * // Get the ProjectManagement service for a given app
 * const otherProjectManagement = getProjectManagement(otherApp);
 * ```
 *
 * @param app - Optional app whose `ProjectManagement` service
 *     to return. If not provided, the default `ProjectManagement` service will
 *     be returned. *
 * @returns The default `ProjectManagement` service if no app is provided or the
 *   `ProjectManagement` service associated with the provided app.
 */
export function getProjectManagement(app?: App): ProjectManagement {
  if (typeof app === 'undefined') {
    app = getApp();
  }

  const firebaseApp: FirebaseApp = app as FirebaseApp;
  return firebaseApp.getOrInitService('projectManagement', (app) => new ProjectManagement(app));
}


text:
package net.machinemuse.powersuits.powermodule.tool;

import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IBlockBreakingModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.event.entity.player.PlayerEvent.BreakSpeed;

import java.util.List;

public class PickaxeModule extends PowerModuleBase implements IBlockBreakingModule, IToggleableModule {
    public static final String MODULE_PICKAXE = "Pickaxe";
    public static final String PICKAXE_HARVEST_SPEED = "Pickaxe Harvest Speed";
    public static final String PICKAXE_ENERGY_CONSUMPTION = "Pickaxe Energy Consumption";
    public static final ItemStack ironPickaxe = new ItemStack(Items.iron_pickaxe);

    public PickaxeModule(List<IModularItem> validItems) {
        super(validItems);
        addInstallCost(new ItemStack(Items.iron_ingot, 3));
        addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 1));
        addBaseProperty(PICKAXE_ENERGY_CONSUMPTION, 50, "J");
        addBaseProperty(PICKAXE_HARVEST_SPEED, 8, "x");
        addTradeoffProperty("Overclock", PICKAXE_ENERGY_CONSUMPTION, 950);
        addTradeoffProperty("Overclock", PICKAXE_HARVEST_SPEED, 22);
        addPropertyLocalString(PICKAXE_ENERGY_CONSUMPTION, StatCollector.translateToLocal("module.pickaxe.energy"));
        addPropertyLocalString(PICKAXE_HARVEST_SPEED, StatCollector.translateToLocal("module.pickaxe.speed"));
    }

    @Override
    public String getCategory() {
        return MuseCommonStrings.CATEGORY_TOOL;
    }

    @Override
    public String getDataName() {
        return MODULE_PICKAXE;
    }

    @Override
    public String getLocalizedName() {
        return StatCollector.translateToLocal("module.pickaxe.name");
    }

    @Override
    public String getDescription() {
        return StatCollector.translateToLocal("module.pickaxe.desc");
    }

    @Override
    public String getTextureFile() {
        return "toolpick";
    }

    @Override
    public boolean canHarvestBlock(ItemStack stack, Block block, int meta, EntityPlayer player) {
        return harvestCheck(stack, block, meta, player);
    }

    @Override
    public boolean onBlockDestroyed(ItemStack stack, World world, Block block, int x, int y, int z, EntityPlayer player) {
        int meta = world.getBlockMetadata(x,y,z);
        if (canHarvestBlock(stack, block, meta, player)) {
            ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(stack, PICKAXE_ENERGY_CONSUMPTION));
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void handleBreakSpeed(BreakSpeed event) {
        event.newSpeed *= ModuleManager.computeModularProperty(event.entityPlayer.getCurrentEquippedItem(), PICKAXE_HARVEST_SPEED);
    }

    public static boolean harvestCheck(ItemStack stack, Block block, int meta, EntityPlayer player) {
        if (ForgeHooks.canToolHarvestBlock(block, meta, ironPickaxe)) {
            if (ElectricItemUtils.getPlayerEnergy(player) > ModuleManager.computeModularProperty(stack, PICKAXE_ENERGY_CONSUMPTION)) {
                return true;
            }
        }
        return false;
    }
}


text:
#pragma once
#include <aws/license-manager/LicenseManager_EXPORTS.h>
#include <aws/license-manager/LicenseManagerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/license-manager/model/ReportContext.h>
#include <aws/license-manager/model/ReportFrequency.h>
#include <aws/license-manager/model/ReportType.h>
#include <utility>

namespace Aws
{
namespace LicenseManager
{
namespace Model
{

  /**
   */
  class AWS_LICENSEMANAGER_API UpdateLicenseManagerReportGeneratorRequest : public LicenseManagerRequest
  {
  public:
    UpdateLicenseManagerReportGeneratorRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateLicenseManagerReportGenerator"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline const Aws::String& GetLicenseManagerReportGeneratorArn() const{ return m_licenseManagerReportGeneratorArn; }

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline bool LicenseManagerReportGeneratorArnHasBeenSet() const { return m_licenseManagerReportGeneratorArnHasBeenSet; }

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline void SetLicenseManagerReportGeneratorArn(const Aws::String& value) { m_licenseManagerReportGeneratorArnHasBeenSet = true; m_licenseManagerReportGeneratorArn = value; }

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline void SetLicenseManagerReportGeneratorArn(Aws::String&& value) { m_licenseManagerReportGeneratorArnHasBeenSet = true; m_licenseManagerReportGeneratorArn = std::move(value); }

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline void SetLicenseManagerReportGeneratorArn(const char* value) { m_licenseManagerReportGeneratorArnHasBeenSet = true; m_licenseManagerReportGeneratorArn.assign(value); }

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithLicenseManagerReportGeneratorArn(const Aws::String& value) { SetLicenseManagerReportGeneratorArn(value); return *this;}

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithLicenseManagerReportGeneratorArn(Aws::String&& value) { SetLicenseManagerReportGeneratorArn(std::move(value)); return *this;}

    /**
     *
Amazon Resource Number (ARN) of the report generator to update.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithLicenseManagerReportGeneratorArn(const char* value) { SetLicenseManagerReportGeneratorArn(value); return *this;}

    /**
     *
Name of the report generator.

     */
    inline const Aws::String& GetReportGeneratorName() const{ return m_reportGeneratorName; }

    /**
     *
Name of the report generator.

     */
    inline bool ReportGeneratorNameHasBeenSet() const { return m_reportGeneratorNameHasBeenSet; }

    /**
     *
Name of the report generator.

     */
    inline void SetReportGeneratorName(const Aws::String& value) { m_reportGeneratorNameHasBeenSet = true; m_reportGeneratorName = value; }

    /**
     *
Name of the report generator.

     */
    inline void SetReportGeneratorName(Aws::String&& value) { m_reportGeneratorNameHasBeenSet = true; m_reportGeneratorName = std::move(value); }

    /**
     *
Name of the report generator.

     */
    inline void SetReportGeneratorName(const char* value) { m_reportGeneratorNameHasBeenSet = true; m_reportGeneratorName.assign(value); }

    /**
     *
Name of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportGeneratorName(const Aws::String& value) { SetReportGeneratorName(value); return *this;}

    /**
     *
Name of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportGeneratorName(Aws::String&& value) { SetReportGeneratorName(std::move(value)); return *this;}

    /**
     *
Name of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportGeneratorName(const char* value) { SetReportGeneratorName(value); return *this;}

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline const Aws::Vector<ReportType>& GetType() const{ return m_type; }

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline void SetType(const Aws::Vector<ReportType>& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline void SetType(Aws::Vector<ReportType>&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithType(const Aws::Vector<ReportType>& value) { SetType(value); return *this;}

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithType(Aws::Vector<ReportType>&& value) { SetType(std::move(value)); return *this;}

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& AddType(const ReportType& value) { m_typeHasBeenSet = true; m_type.push_back(value); return *this; }

    /**
     *
Type of reports to generate. The following report types an be generated:

     *

License configuration report - Reports on the number and details of
     * consumed licenses for a license configuration.

Resource report
     * - Reports on the tracked licenses and resource consumption for a license
     * configuration.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& AddType(ReportType&& value) { m_typeHasBeenSet = true; m_type.push_back(std::move(value)); return *this; }

    /**
     *
?

     */
    inline const ReportContext& GetReportContext() const{ return m_reportContext; }

    /**
     *
?

     */
    inline bool ReportContextHasBeenSet() const { return m_reportContextHasBeenSet; }

    /**
     *
?

     */
    inline void SetReportContext(const ReportContext& value) { m_reportContextHasBeenSet = true; m_reportContext = value; }

    /**
     *
?

     */
    inline void SetReportContext(ReportContext&& value) { m_reportContextHasBeenSet = true; m_reportContext = std::move(value); }

    /**
     *
?

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportContext(const ReportContext& value) { SetReportContext(value); return *this;}

    /**
     *
?

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportContext(ReportContext&& value) { SetReportContext(std::move(value)); return *this;}

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline const ReportFrequency& GetReportFrequency() const{ return m_reportFrequency; }

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline bool ReportFrequencyHasBeenSet() const { return m_reportFrequencyHasBeenSet; }

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline void SetReportFrequency(const ReportFrequency& value) { m_reportFrequencyHasBeenSet = true; m_reportFrequency = value; }

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline void SetReportFrequency(ReportFrequency&& value) { m_reportFrequencyHasBeenSet = true; m_reportFrequency = std::move(value); }

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportFrequency(const ReportFrequency& value) { SetReportFrequency(value); return *this;}

    /**
     *
Frequency by which reports are generated. The following options are
     * avaiable:

??? What are the APi value options?

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithReportFrequency(ReportFrequency&& value) { SetReportFrequency(std::move(value)); return *this;}

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline const Aws::String& GetClientToken() const{ return m_clientToken; }

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; }

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}

    /**
     *
Unique, case-sensitive identifier that you provide to ensure the idempotency
     * of the request.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}

    /**
     *
Description of the report generator.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
Description of the report generator.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
Description of the report generator.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
Description of the report generator.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
Description of the report generator.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
Description of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
Description of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
Description of the report generator.

     */
    inline UpdateLicenseManagerReportGeneratorRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

  private:

    Aws::String m_licenseManagerReportGeneratorArn;
    bool m_licenseManagerReportGeneratorArnHasBeenSet;

    Aws::String m_reportGeneratorName;
    bool m_reportGeneratorNameHasBeenSet;

    Aws::Vector<ReportType> m_type;
    bool m_typeHasBeenSet;

    ReportContext m_reportContext;
    bool m_reportContextHasBeenSet;

    ReportFrequency m_reportFrequency;
    bool m_reportFrequencyHasBeenSet;

    Aws::String m_clientToken;
    bool m_clientTokenHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;
  };

} // namespace Model
} // namespace LicenseManager
} // namespace Aws


text:
namespace Pentacorn.Vision.Captures.DirectShow.Internals
{
    using System;
    using System.Runtime.InteropServices;

    ///
    /// The interface provides callback methods for the <see cref="ISampleGrabber.SetCallback"/> method.
    ///
    ///
    [ComImport,
    Guid("0579154A-2B53-4994-B0D0-E773148EFF85"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface ISampleGrabberCB
    {
        ///
        /// Callback method that receives a pointer to the media sample.
        ///
        ///
        /// <param name="sampleTime">Starting time of the sample, in seconds.</param>
        /// <param name="sample">Pointer to the sample's IMediaSample interface.</param>
        ///
        /// <returns>Return's HRESULT error code.</returns>
        ///
        [PreserveSig]
        int SampleCB(double sampleTime, IMediaSample sample);

        ///
        /// Callback method that receives a pointer to the sample bufferþ
        ///
        ///
        /// <param name="sampleTime">Starting time of the sample, in seconds.</param>
        /// <param name="buffer">Pointer to a buffer that contains the sample data.</param>
        /// <param name="bufferLen">Length of the buffer pointed to by buffer, in bytes</param>
        ///
        /// <returns>Return's HRESULT error code.</returns>
        ///
        [PreserveSig]
        int BufferCB(double sampleTime, IntPtr buffer, int bufferLen);
    }
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'my-heroes',
  templateUrl: 'app/heroes.component.html',
  styleUrls: ['app/heroes.component.css']
})
export class HeroesComponent implements OnInit, OnDestroy {

  addingHero:boolean;
  error: any;
  heroes: Hero[];
  selectedHero: Hero;
  constructor(
    private router: Router,
    private heroService: HeroService) {
  }
  ngOnInit() {
    this.getHeroes();
  }
  ngOnDestroy() {
    console.log('destroy');
  }
  getHeroes() {
    this.heroService
      .getHeroes()
      .then(heroes => this.heroes = heroes);

    /*var self = this;
    this.heroService.getHeroes()
      .then(function(heroes){
        self.heroes = heroes;
      });*/
  }
  onSelect(hero: Hero) {
    if (hero === this.selectedHero) {
      delete this.selectedHero;
    } else {
      this.selectedHero = hero;
    }
  }
  gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedHero.id]);
  }

  addHero(): void {
    this.addingHero = true;
    this.selectedHero = null;
  }

  close(savedHero: Hero): void {
    this.addingHero = false;
    if (savedHero) { this.getHeroes(); }
  }

  deleteHero(hero: Hero, event: any): void {
    event.stopPropagation();
    this.heroService
        .delete(hero)
        .then(res => {
          this.heroes = this.heroes.filter(h => h !== hero);
          if (this.selectedHero === hero) { this.selectedHero = null; }
        })
        .catch(error => this.error = error);
  }

}


text:
import test from 'ava'
import twif from './'

const username = 'Google'

test('should thrown exception without environment variables', t => {
    const consumerKeyError = t.throws(() => {
        twif(username)
    }, Error)

    t.is(consumerKeyError.message, 'Please, set the CONSUMER_KEY environment variable.');

    process.env.CONSUMER_KEY = 123;

    const consumerSecretError = t.throws(() => {
        twif(username)
    }, Error)

    t.is(consumerSecretError.message, 'Please, set the CONSUMER_SECRET environment variable.');

    process.env.CONSUMER_SECRET = 456;

    const accessTokenError = t.throws(() => {
        twif(username)
    }, Error)

    t.is(accessTokenError.message, 'Please, set the ACCESS_TOKEN environment variable.');

    process.env.ACCESS_TOKEN = 789;

    const accessTokenSecretError = t.throws(() => {
        twif(username)
    }, Error)

    t.is(accessTokenSecretError.message, 'Please, set the ACCESS_TOKEN_SECRET environment variable.');;
})


text:
using System;
using System.Windows;

namespace GitMind.RepositoryViews
{
	internal static class Converters
	{
		private static readonly int RowHeight = 17;
		private static readonly int ColumnSize = 20;
		public static readonly int HalfRow = RowHeight / 2;

		public static int ToRow(double y)
		{
			return (int)y / RowHeight;
		}

		public static int ToY(int row)
		{
			return row * RowHeight;
		}

		public static int ToColumn(double x)
		{
			return (int)((x + 3) / ColumnSize);
		}

		public static int ToX(int column)
		{
			return ColumnSize * column;
		}

		public static int ToTopRowIndex(Rect rectangle, int commitsCount)
		{
			int firstIndex = (int)Math.Floor(rectangle.Top / RowHeight);
			firstIndex = Math.Max(firstIndex, 0);
			firstIndex = Math.Min(firstIndex, commitsCount);
			return firstIndex;
		}

		public static int ToBottomRowIndex(Rect rectangle, int commitsCount)
		{
			int lastIndex = (int)Math.Ceiling(rectangle.Bottom / RowHeight);
			lastIndex = Math.Min(lastIndex, commitsCount);
			return lastIndex;
		}

		public static int ToRowExtent(int commitsCount)
		{
			return commitsCount * RowHeight;
		}
	}
}


text:
{% extends "layout.html" %}

{% block page_title %}
  Question page
{% endblock %}

{% block content %}

Continue to DigiD

      <form class="form" action="/multiple-brands/eu/dutch/registered" method="post">

You'll now verify your identity on Dutch Government's website.

          <input class="button" type="submit" value="Continue to DigiD">

      </form>

{% endblock %}


text:
require_relative '../base_page'

class UnibetFavGamesPage < BasePage

end


text:
layout: page
title: "Jennifer Kay"
comments: true
description: "blanks"
keywords: "Jennifer Kay,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: ATOC 1060, ATOC 4500, ATOC 5600, ATOC 6020

#### ATOC 1060: Our Changing Environment: El Nino, Ozone, and Climate

**Terms taught**: Fall 2014, Fall 2015, Spring 2017

**Instructor rating**: 5.06

**Standard deviation in instructor rating**: 0.15

**Average grade** (4.0 scale): 3.02

**Standard deviation in grades** (4.0 scale): 0.11

**Average workload** (raw): 2.0

**Standard deviation in workload** (raw): 0.16

#### ATOC 4500: Special Topics in Atmospheric and Oceanic Sciences

**Terms taught**: Fall 2016

**Instructor rating**: 5.88

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.59

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.71

**Standard deviation in workload** (raw): 0.0

#### ATOC 5600: Physics and Chemistry of Clouds and Aerosols

**Terms taught**: Spring 2014, Spring 2016

**Instructor rating**: 4.36

**Standard deviation in instructor rating**: 0.72

**Average grade** (4.0 scale): 3.68

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 3.63

**Standard deviation in workload** (raw): 0.13

#### ATOC 6020: Seminar in Atmospheric and Oceanic Sciences

**Terms taught**: Fall 2014, Fall 2015

**Instructor rating**: 5.76

**Standard deviation in instructor rating**: 0.13

**Average grade** (4.0 scale): 4.0

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 1.2

**Standard deviation in workload** (raw): 0.05


text:
package org.springframework.richclient.dialog;

import java.awt.image.BufferedImage;

import javax.swing.JLabel;
import javax.swing.JPanel;

import junit.framework.TestCase;

import org.springframework.richclient.core.DefaultMessage;

/**
 * Testcase for TitlePane
 *
 * @author Peter De Bruycker
 */
public class TitlePaneTests extends TestCase {

	public void testBlah() {
		TitlePane titlePane = new TitlePane();
		titlePane.setImage(new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB));
		titlePane.setTitle("new title");
		titlePane.setMessage(new DefaultMessage("test message", null));
		assertEquals("new title", titlePane.getTitle());

		// trigger control creation
		JPanel panel = (JPanel) titlePane.getControl();

		assertEquals("must have 3 components: title, icon and message", 3, panel.getComponentCount());

		JLabel titleLabel = (JLabel) panel.getComponent(0);
		assertEquals("new title", titleLabel.getText());

		JLabel iconLabel = (JLabel) panel.getComponent(1);
		assertNotNull(iconLabel.getIcon());

		JLabel messageLabel = (JLabel) panel.getComponent(2);
		assertEquals("test message", messageLabel.getText());

		// change title and message after control creation
		titlePane.setTitle("other title");
		titlePane.setMessage(new DefaultMessage("other message", null));

		assertEquals("other title", titleLabel.getText());
		assertEquals("other message", messageLabel.getText());
	}

}


text:
package com.amazon.ion.impl.lite;

import com.amazon.ion.ContainedValueException;
import com.amazon.ion.IonSexp;
import com.amazon.ion.IonType;
import com.amazon.ion.IonValue;
import com.amazon.ion.ValueVisitor;
import java.util.Collection;

final class IonSexpLite
    extends IonSequenceLite
    implements IonSexp
{
    private static final int HASH_SIGNATURE =
        IonType.SEXP.toString().hashCode();

    IonSexpLite(ContainerlessContext context, boolean isNull)
    {
        super(context, isNull);
    }

    IonSexpLite(IonSexpLite existing, IonContext context)
    {
        super(existing, context);
    }

    /**
     * Constructs a sexp value
     *
     * @param elements
     *   the initial set of child elements.  If null, then the new
     *   instance will have {@link #isNullValue()} == true.
     *
     * @throws ContainedValueException if any value in elements
     *  has {@link IonValue#getContainer()} != null.
     */
    IonSexpLite(ContainerlessContext context,
                Collection<? extends IonValue> elements)
        throws ContainedValueException
    {
        super(context, elements);
    }

    @Override
    IonSexpLite clone(IonContext parentContext)
    {
        return new IonSexpLite(this, parentContext);
    }

    @Override
    public IonSexpLite clone()
    {
        return clone(ContainerlessContext.wrap(getSystem()));
    }

    @Override
    public int hashCode(SymbolTableProvider symbolTableProvider) {
        return sequenceHashCode(HASH_SIGNATURE, symbolTableProvider);
    }

    @Override
    public IonType getType()
    {
        return IonType.SEXP;
    }

    @Override
    public void accept(ValueVisitor visitor) throws Exception
    {
        visitor.visit(this);
    }
}


text:
package ru.r2cloud.jradio.blocks;

import java.io.IOException;

import ru.r2cloud.jradio.ByteInput;
import ru.r2cloud.jradio.Context;

/**
 * operates over unpacked stream
 *
 */
public class NrziDecode implements ByteInput {

	private final ByteInput source;
	private int previous;

	public NrziDecode(ByteInput source) {
		if (source.getContext().getSoftBits()) {
			throw new IllegalArgumentException("expected hard bits");
		}
		this.source = source;
	}

	@Override
	public byte readByte() throws IOException {
		int inBit = (source.readByte() & 0xFF);
		int result = ~(inBit ^ previous) & 1;
		previous = inBit;
		return (byte) result;
	}

	@Override
	public void close() throws IOException {
		source.close();
	}

	@Override
	public Context getContext() {
		return source.getContext();
	}

}


text:
My personal collection of dotfiles. This repo serves as remote backup and also makes it possible to synchronize the files between different machines that I work on.

## Installation

Use the provided `Makefiles` to install all or some of the dotfiles on your machine:

    $ make

By default, this will copy all contents in the `dotfiles/` folder to the home directory (set by the `HOME` environment variable). This will not override any existing dotfiles, as a backup file is automatically generated before copying the contents.

The following targets are provided if you want to install specific dotfiles:

Target         | Description
-------------- | --------------------------------------------------------------
`all`          | Install all dotfiles (default)
`fish`         | Install [fish][] related dotfiles
`git`          | Install [Git][] related dotfiles
`vim`          | Install [VIm][] related dotfiles

[fish]: http://fishshell.com/
[Git]: https://git-scm.com/
[VIm]: http://www.vim.org/

For example, to install Git related dotfiles:

    $ make git


text:
<?php

/**
 * WebsiteConfigTranslation form.
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class WebsiteConfigTranslationForm extends BaseWebsiteConfigTranslationForm
{
  public function configure()
  {
  }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Data;
using EDEngineer.Localization;
using EDEngineer.Models;
using EDEngineer.Models.Operations;
using EDEngineer.Models.State;
using EDEngineer.Models.Utils;
using EDEngineer.Properties;
using EDEngineer.Utils;
using EDEngineer.Utils.System;
using EDEngineer.Views.Notifications;
using Newtonsoft.Json;
using NodaTime;

namespace EDEngineer.Views
{
    public class CommanderViewModel : INotifyPropertyChanged, IDisposable
    {
        public string CommanderName { get; }
        public State State { get; }
        public BlueprintFilters Filters { get; private set; }
        public ObservableCollection<Entry> HighlightedEntryData { get; } = new ObservableCollection<Entry>();

        public ShoppingListViewModel ShoppingList { get; private set; }

        private readonly JournalEntryConverter journalEntryConverter;
        public JsonSerializerSettings JsonSettings { get; }

        private readonly HashSet<Blueprint> favoritedBlueprints = new HashSet<Blueprint>();
        private Instant lastUpdate = Instant.MinValue;
        private readonly CommanderNotifications commanderNotifications;

        public Instant LastUpdate
        {
            get => lastUpdate;
            set
            {
                if (value == lastUpdate)
                    return;
                lastUpdate = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void LoadLogs(IEnumerable<string> events)
        {
            commanderNotifications?.UnsubscribeNotifications();
            State.Cargo.InitLoad();
            // Clear state:

            State.Cargo.Ingredients.ToList().ForEach(k => State.Cargo.IncrementCargo(k.Value.Data.Name, -1 * k.Value.Count));
            LastUpdate = Instant.MinValue;

            ApplyEventsToSate(events);
            commanderNotifications?.SubscribeNotifications();

            State.Cargo.Ingredients.RefreshSort();
            State.Cargo.CompleteLoad();
        }

        public CommanderViewModel(string commanderName, Action<CommanderViewModel> loadAction, Languages languages, List<EntryData> entryDatas, List<Equipment> equipments)
        {
            CommanderName = commanderName;

            var equipmentByName = equipments.ToDictionary(x => x.Code, StringComparer.OrdinalIgnoreCase);
            var converter = new ItemNameConverter(entryDatas, equipmentByName);

            State = new State(new StateCargo(entryDatas, equipments, languages, SettingsManager.Comparer));

            commanderNotifications = new CommanderNotifications(State);
            var blueprintConverter = new BlueprintConverter(State.Cargo.Ingredients);

            var blueprintsJson = Helpers.GetBlueprintsJson();
            var blueprints =
                JsonConvert.DeserializeObject<List<Blueprint>>(blueprintsJson, blueprintConverter)
                           .Where(b => b.Ingredients.Any())
                           .ToList();

            journalEntryConverter = new JournalEntryConverter(converter, State.Cargo.Ingredients, languages, blueprints);
            JsonSettings = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter> { journalEntryConverter },
                Error = (o, e) => e.ErrorContext.Handled = true
            };
            LoadBlueprints(languages, blueprints);
            languages.PropertyChanged += (o, e) => OnPropertyChanged(nameof(Filters));

            loadAction(this);

            State.BlueprintCrafted += (o, e) =>
                                      {
                                          TryRemoveFromShoppingListByIngredients(e.Category, e.TechnicalType,
                                              e.IngredientsConsumed);
                                          State.ApplyCraft(e);
                                      };
            ShoppingList.SynchronizeWithLogs = SettingsManager.SyncShoppingList;

            languages.PropertyChanged += (o, e) =>
                                         {
                                             OnPropertyChanged(nameof(ShoppingList));
                                             OnPropertyChanged(nameof(ShoppingListItem));
                                         };

            var datas = State.Cargo.Ingredients.Select(c => c.Value.Data);
            var ingredientUsed = State.Blueprints.SelectMany(blueprint => blueprint.Ingredients);
            var ingredientUsedNames = ingredientUsed.Select(ingredient => ingredient.Entry.Data.Name).Distinct();
            var unusedIngredients = datas.Where(data => !ingredientUsedNames.Contains(data.Name));

            foreach (var data in unusedIngredients)
            {
                data.Unused = true;
            }
        }

        public JournalEntry UserChange(Entry entry, int change)
        {
            var logEntry = new JournalEntry
            {
                JournalOperation = new ManualChangeOperation
                {
                    Count = change,
                    JournalEvent = JournalEvent.ManualUserChange,
                    Name = entry.Data.Name
                },
                Timestamp = SystemClock.Instance.GetCurrentInstant()
            };

            var json = JsonConvert.SerializeObject(logEntry, journalEntryConverter);

            logEntry.OriginalJson = json;

            MutateState(logEntry);

            return logEntry;
        }

        public void ApplyEventsToSate(IEnumerable<string> allLogs)
        {
            var entries = allLogs.Select(l => JsonConvert.DeserializeObject<JournalEntry>(l, JsonSettings))
                .Where(e => e?.Relevant == true);

            foreach (var entry in entries.Where(entry => entry.Timestamp >= LastUpdate).ToList())
            {
                MutateState(entry);
            }
        }

        private void MutateState(JournalEntry entry)
        {
            State.Operations.AddLast(entry);
            entry.JournalOperation.Mutate(State);
            LastUpdate = Instant.Max(LastUpdate, entry.Timestamp);
        }

        public ICollectionView FilterView(MainWindowViewModel parentViewModel, Kind kind, CollectionViewSource source)
        {
            source.Filter += (o, e) =>
            {
                var entry = ((KeyValuePair<string, Entry>)e.Item).Value;

                e.Accepted = ((entry.Data.Kind & kind) == entry.Data.Kind || entry.Data.Kind == Kind.Unknown) &&
                       (parentViewModel.MaterialSubkindFilter == null || entry.Data.Kind == Kind.Data || parentViewModel.MaterialSubkindFilter == entry.Data.Subkind) &&
                       (parentViewModel.ShowZeroes || entry.Count != 0) &&
                       (!parentViewModel.ShowOnlyForFavorites || favoritedBlueprints.Any(b => b.Ingredients.Any(i => i.Entry == entry)));
            };

            parentViewModel.PropertyChanged += (o, e) =>
            {
                if (e.PropertyName == nameof(parentViewModel.ShowZeroes) || e.PropertyName == nameof(parentViewModel.ShowOnlyForFavorites))
                {
                    source.View.Refresh();
                }
            };

            State.Blueprints.ForEach(b => b.PropertyChanged += (o, e) =>
            {
                if (parentViewModel.ShowOnlyForFavorites && e.PropertyName == "Favorite")
                {
                    Application.Current.Dispatcher.Invoke(source.View.Refresh);
                }
            });

            if (parentViewModel.IngredientsGrouped)
            {
                source.View.GroupDescriptions.Add(new PropertyGroupDescription("Value.Data.Group"));
            }

            return source.View;
        }

        private void LoadBlueprints(ILanguage languages, IEnumerable<Blueprint> blueprints)
        {
            State.Blueprints = new List<Blueprint>(blueprints);
            if (Settings.Default.Favorites == null)
            {
                Settings.Default.Favorites = new StringCollection();
            }

            if (Settings.Default.Ignored == null)
            {
                Settings.Default.Ignored = new StringCollection();
            }

            if (Settings.Default.ShoppingList == null)
            {
                Settings.Default.ShoppingList = new StringCollection();
            }

            if (Settings.Default.ShowAllGrades == null)
            {
                Settings.Default.ShowAllGrades = new StringCollection();
            }

            if (Settings.Default.CollapsedIngredientGroups == null)
            {
                Settings.Default.CollapsedIngredientGroups = new StringCollection();
            }

            foreach (var blueprint in State.Blueprints)
            {
                var text = $"{CommanderName}:{blueprint}";

                if (Settings.Default.Favorites.Contains(text))
                {
                    blueprint.Favorite = true;
                    favoritedBlueprints.Add(blueprint);

                    if (Settings.Default.Favorites.Contains($"{blueprint}"))
                    {
                        Settings.Default.Favorites.Remove($"{blueprint}");
                        Settings.Default.Save();
                    }
                }
                else if (Settings.Default.Favorites.Contains($"{blueprint}"))
                {
                    blueprint.Favorite = true;
                    favoritedBlueprints.Add(blueprint);
                    Settings.Default.Favorites.Remove($"{blueprint}");
                    Settings.Default.Favorites.Add(text);
                    Settings.Default.Save();
                }

                if (Settings.Default.Ignored.Contains(text))
                {
                    blueprint.Ignored = true;

                    if (Settings.Default.Ignored.Contains($"{blueprint}"))
                    {
                        Settings.Default.Ignored.Remove($"{blueprint}");
                        Settings.Default.Save();
                    }
                }
                else if (Settings.Default.Ignored.Contains($"{blueprint}"))
                {
                    blueprint.Ignored = true;
                    Settings.Default.Ignored.Remove($"{blueprint}");
                    Settings.Default.Ignored.Add(text);
                    Settings.Default.Save();
                }

                blueprint.ShoppingListCount = Settings.Default.ShoppingList.Cast<string>().Count(l => l == text);

                blueprint.PropertyChanged += (o, e) =>
                {
                    if (e.PropertyName == "Favorite")
                    {
                        if (blueprint.Favorite)
                        {
                            Settings.Default.Favorites.Add($"{CommanderName}:{blueprint}");
                            favoritedBlueprints.Add(blueprint);
                        }
                        else
                        {
                            Settings.Default.Favorites.Remove($"{CommanderName}:{blueprint}");
                            favoritedBlueprints.Remove(blueprint);
                        }

                        Settings.Default.Save();
                    }
                    else if (e.PropertyName == "Ignored")
                    {
                        if (blueprint.Ignored)
                        {
                            Settings.Default.Ignored.Add($"{CommanderName}:{blueprint}");
                        }
                        else
                        {
                            Settings.Default.Ignored.Remove($"{CommanderName}:{blueprint}");
                        }

                        Settings.Default.Save();
                    }
                    else if (e.PropertyName == "ShoppingListCount")
                    {
                        while (Settings.Default.ShoppingList.Contains(text))
                        {
                            Settings.Default.ShoppingList.Remove(text);
                        }

                        for (var i = 0; i < blueprint.ShoppingListCount; i++)
                        {
                            Settings.Default.ShoppingList.Add(text);
                        }

                        Settings.Default.Save();
                    }
                };
            }

            Filters = new BlueprintFilters(languages, State.Blueprints);

            ShoppingList = new ShoppingListViewModel(State.Cargo, State.Blueprints, languages);
        }

        public void TryRemoveFromShoppingListByIngredients(BlueprintCategory category, string technicalModuleName, List<BlueprintIngredient> blueprintIngredients)
        {
            if (!ShoppingList.SynchronizeWithLogs)
            {
                return;
            }

            var blueprints = ShoppingList
                .Composition
                .Select(x => x.Item1)
                .ToList();

            if (category == BlueprintCategory.Module)
            {
                var blueprint = blueprints.FirstOrDefault(b => b.Category == BlueprintCategory.Module &&
                                                               b.TechnicalType.IsIn(technicalModuleName) &&
                                                               b.HasSameIngredients(blueprintIngredients));
                if (blueprint == null)
                {
                    var experimentals = blueprints.Where(b => b.Category == BlueprintCategory.Experimental).ToList();
                    foreach (var experimental in experimentals)
                    {
                        foreach (var module in blueprints.Where(
                            b => b.Category == BlueprintCategory.Module && b.TechnicalType.IsIn(technicalModuleName)))
                        {
                            var mergedIngredients = experimental.Ingredients.Concat(module.Ingredients).ToList();
                            if (mergedIngredients.Count == blueprintIngredients.Count &&
                                mergedIngredients.All(blueprintIngredients.Contains))
                            {
                                ShoppingListChange(experimental, -1);
                                ShoppingListChange(module, -1);

                                return;
                            }
                        }
                    }

                    blueprint = blueprints.FirstOrDefault(b => b.HasSameIngredients(blueprintIngredients));
                }

                if (blueprint != null)
                {
                    ShoppingListChange(blueprint, -1);
                }
            }
            else
            {
                var blueprint = blueprints.FirstOrDefault(b =>
                {
                    if (b.Category != category)
                    {
                        return false;
                    }

                    switch (b.Category)
                    {
                        case BlueprintCategory.Synthesis:
                        case BlueprintCategory.Technology:
                            return b.HasSameIngredients(blueprintIngredients);
                        default:
                            return false;
                    }
                });

                if (blueprint != null)
                {
                    ShoppingListChange(blueprint, -1);
                }
            }
        }

        public void ShoppingListChange(Blueprint blueprint, int i)
        {
            if (i != 0 && blueprint.ShoppingListCount + i >= 0)
            {
                blueprint.ShoppingListCount += i;

                OnPropertyChanged(nameof(ShoppingList));
                OnPropertyChanged(nameof(ShoppingListItem));
            }
        }

        public void ImportShoppingList()
        {
            if (Helpers.TryRetrieveShoppingList(out var shoppingListItems))
            {
                var blueprints = State.Blueprints;

                if (shoppingListItems != null && shoppingListItems.Count > 0)
                {
                    // Configure the message box to be displayed
                    var messageBoxText = "Do you want to clear the shopping list before import?";
                    var caption = "Shopping List Import";
                    var button = MessageBoxButton.YesNoCancel;
                    var icon = MessageBoxImage.Warning;

                    // Display message box
                    var result = MessageBox.Show(messageBoxText, caption, button, icon);

                    // Process message box results
                    switch (result)
                    {
                        case MessageBoxResult.Yes:
                            ClearShoppingList();
                            break;
                        case MessageBoxResult.No:
                            // User pressed No, so just load into shopping list without clearing
                            break;
                        case MessageBoxResult.Cancel:
                            // User pressed Cancel button so skip out of Import
                            return;
                    }

                    LoadShoppingListItems(shoppingListItems, blueprints);
                    Settings.Default.Save();
                }

                RefreshShoppingList();

            }
        }

        private void LoadShoppingListItems(StringCollection shoppingListItems, List<Blueprint> blueprints)
        {
            var blueprintsByString = blueprints.ToDictionary(b => b.ToString(), b => b);
            foreach (var item in shoppingListItems)
            {
                if (item == null)
                {
                    continue;
                }

                var itemName = item.Split(':');

                if (blueprintsByString.TryGetValue(itemName[1], out var blueprint))
                {
                    ShoppingListChange(blueprint, 1);
                }
            }
        }

        public void ExportShoppingList()
        {
            try
            {
                Helpers.SaveShoppingList(CommanderName);
            }
            catch(Exception e)
            {
                MessageBox.Show("Shopping list could not be saved." + Environment.NewLine + Environment.NewLine + e, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void ClearShoppingList()
        {
            foreach (var tuple in ShoppingList.Composition.ToList())
            {
                ShoppingListChange(tuple.Item1, tuple.Item2 * -1);
            }
        }

        public int ShoppingListItem => 0;

        public override string ToString()
        {
            return $"CMDR {CommanderName}";
        }

        public void Dispose()
        {
            commanderNotifications?.Dispose();
        }

        public void ToggleHighlight(Entry entry)
        {
            entry.Highlighted = !entry.Highlighted;

            if (entry.Highlighted)
            {
                HighlightedEntryData.Add(entry);
            }
            else
            {
                HighlightedEntryData.Remove(entry);
            }

            Settings.Default.Save();
        }

        public void HighlightShoppingListIngredient(List<BlueprintIngredient> ingredients, Blueprint blueprint, bool highlighted)
        {
            if (ingredients == null)
            {
                return;
            }

            foreach (
                var ingredient in
                    blueprint.Ingredients.Join(ingredients,
                        ingredient => ingredient.Entry.Data.Name,
                        ingredient => ingredient.Entry.Data.Name,
                        (_, ingredient) => ingredient))
            {
                ingredient.ShoppingListHighlighted = highlighted;
            }

            blueprint.ShoppingListHighlighted = highlighted;
        }

        public void HighlightShoppingListBlueprint(List<Tuple<Blueprint, int>> blueprints, BlueprintIngredient ingredient, bool highlighted)
        {
            foreach (var blueprint in blueprints.Select(i => i.Item1).Where(b => b.Ingredients.Any(i => i.Entry.Data.Name == ingredient.Entry.Data.Name)))
            {
                blueprint.ShoppingListHighlighted = highlighted;
            }

            ingredient.ShoppingListHighlighted = highlighted;
        }

        public void RefreshShoppingList()
        {
            // relevant when live reloading a commander, because WPF didn't bind upon creating the object:
            OnPropertyChanged(nameof(ShoppingList));
            OnPropertyChanged(nameof(ShoppingListItem));
        }

        public void RefreshShoppingList( StringCollection shoppingList)
        {
            var blueprints = State.Blueprints;
            LoadShoppingListItems(shoppingList, blueprints);
            Settings.Default.Save();
        }

        public void ShowAllGradeChanges(ShoppingListBlock shoppingListBlock)
        {
            shoppingListBlock.ShowAllGrades = !shoppingListBlock.ShowAllGrades;
            if (shoppingListBlock.ShowAllGrades)
            {
                SettingsManager.AddToAllGrades(shoppingListBlock.Label);
            }
            else
            {
                SettingsManager.RemoveFromAllGrades(shoppingListBlock.Label);
            }

            OnPropertyChanged(nameof(ShoppingList));
            OnPropertyChanged(nameof(ShoppingListItem));
        }

        public void LoadAggregation(StateAggregation aggregation)
        {
            State.ApplyAggregation(aggregation);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Monogr. bot. , Warsaw 30: 99 (1969)

#### Original name
Cortinarius trivialis J.E. Lange, 1940

### Remarks
null


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.domain.AgentStatus;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ElasticAgentRuntimeInfoTest {

    @Test
    public void shouldUpdateSelfForAnIdleAgent() throws Exception {
        ElasticAgentRuntimeInfo agentRuntimeInfo = new ElasticAgentRuntimeInfo(new AgentIdentifier("localhost", "127.0.0.1", "uuid"), AgentRuntimeStatus.Idle, "/foo/one", null, "42", "go.cd.elastic-agent-plugin.docker");
        ElasticAgentRuntimeInfo newRuntimeInfo = new ElasticAgentRuntimeInfo(new AgentIdentifier("go02", "10.10.10.1", "uuid"), AgentStatus.Building.getRuntimeStatus(), "/foo/two", "cookie", "42", "go.cd.elastic-agent-plugin.docker");

        agentRuntimeInfo.updateSelf(newRuntimeInfo);

        assertThat(agentRuntimeInfo.getBuildingInfo(), is(newRuntimeInfo.getBuildingInfo()));
        assertThat(agentRuntimeInfo.getLocation(), is(newRuntimeInfo.getLocation()));
        assertThat(agentRuntimeInfo.getUsableSpace(), is(newRuntimeInfo.getUsableSpace()));
        assertThat(agentRuntimeInfo.getOperatingSystem(), is(newRuntimeInfo.getOperatingSystem()));
        assertThat(agentRuntimeInfo.getElasticAgentId(), is(newRuntimeInfo.getElasticAgentId()));
        assertThat(agentRuntimeInfo.getElasticPluginId(), is(newRuntimeInfo.getElasticPluginId()));
    }

    @Test
    public void shouldRefreshOperatingSystemOfAgent() throws Exception {
        AgentIdentifier identifier = new AgentIdentifier("local.in", "127.0.0.1", "uuid-1");
        AgentRuntimeInfo runtimeInfo = ElasticAgentRuntimeInfo.fromAgent(identifier, AgentRuntimeStatus.Idle, "/tmp/foo");
        String os = new SystemEnvironment().getOperatingSystemCompleteName();
        assertThat(runtimeInfo.getOperatingSystem(), is(os));
    }

    @Test
    public void shouldRefreshUsableSpaceOfAgent() throws Exception {
        AgentIdentifier identifier = new AgentIdentifier("local.in", "127.0.0.1", "uuid-1");
        String workingDirectory = FileUtils.getTempDirectory().getAbsolutePath();
        AgentRuntimeInfo runtimeInfo = ElasticAgentRuntimeInfo.fromAgent(identifier, AgentRuntimeStatus.Idle, workingDirectory);
        long space = ElasticAgentRuntimeInfo.usableSpace(workingDirectory);
        assertThat(runtimeInfo.getUsableSpace(), is(space));
    }
}


text:
import { getLocationHref } from '../../main';
import {
  createElementID,
} from '../../utils/common';
import filtersFactory from '../../utils/filters';

var registeredEffects = {};
var idPrefix = 'filter_result_';

function SVGEffects(elem) {
  var i;
  var source = 'SourceGraphic';
  var len = elem.data.ef ? elem.data.ef.length : 0;
  var filId = createElementID();
  var fil = filtersFactory.createFilter(filId, true);
  var count = 0;
  this.filters = [];
  var filterManager;
  for (i = 0; i < len; i += 1) {
    filterManager = null;
    var type = elem.data.ef[i].ty;
    if (registeredEffects[type]) {
      var Effect = registeredEffects[type].effect;
      filterManager = new Effect(fil, elem.effectsManager.effectElements[i], elem, idPrefix + count, source);
      source = idPrefix + count;
      if (registeredEffects[type].countsAsEffect) {
        count += 1;
      }
    }
    if (filterManager) {
      this.filters.push(filterManager);
    }
  }
  if (count) {
    elem.globalData.defs.appendChild(fil);
    elem.layerElement.setAttribute('filter', 'url(' + getLocationHref() + '#' + filId + ')');
  }
  if (this.filters.length) {
    elem.addRenderableComponent(this);
  }
}

SVGEffects.prototype.renderFrame = function (_isFirstFrame) {
  var i;
  var len = this.filters.length;
  for (i = 0; i < len; i += 1) {
    this.filters[i].renderFrame(_isFirstFrame);
  }
};

export function registerEffect(id, effect, countsAsEffect) {
  registeredEffects[id] = {
    effect,
    countsAsEffect,
  };
}

export default SVGEffects;


text:
from django.db import migrations

class Migration(migrations.Migration):

    replaces = [('pipeline', '0101_squashed2'), ('pipeline', '0102_relink_apps'), ('pipeline', '0103_drop_all')]

    initial = True

    dependencies = []

    operations = []