text:
import _ from 'underscore';
import moment from 'moment';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { ReactiveDict } from 'meteor/reactive-dict';
import { ReactiveVar } from 'meteor/reactive-var';
import { Random } from 'meteor/random';
import { Blaze } from 'meteor/blaze';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Session } from 'meteor/session';
import { Template } from 'meteor/templating';

import { t, roomTypes, getUserPreference, handleError } from '../../../../utils/client';
import { WebRTC } from '../../../../webrtc/client';
import { ChatMessage, RoomRoles, Users, Subscriptions, Rooms } from '../../../../models';
import {
	fireGlobalEvent,
	RoomHistoryManager,
	RoomManager,
	readMessage,
	Layout,
} from '../../../../ui-utils/client';
import { messageContext } from '../../../../ui-utils/client/lib/messageContext';
import { messageArgs } from '../../../../ui-utils/client/lib/messageArgs';
import { settings } from '../../../../settings';
import { callbacks } from '../../../../callbacks';
import { hasAllPermission, hasRole } from '../../../../authorization';
import { ChatMessages } from '../../lib/chatMessages';
import { fileUpload } from '../../lib/fileUpload';
import './room.html';
import { getCommonRoomEvents } from './lib/getCommonRoomEvents';
import { RoomManager as NewRoomManager } from '../../../../../client/lib/RoomManager';

export const chatMessages = {};

const userCanDrop = (_id) => !roomTypes.readOnly(_id, Users.findOne({ _id: Meteor.userId() }, { fields: { username: 1 } }));

export const openProfileTab = (e, tabBar, username) => {
	e.stopPropagation();

	if (Layout.isEmbedded()) {
		fireGlobalEvent('click-user-card-message', { username });
		e.preventDefault();
		return;
	}

	tabBar.openUserInfo(username);
};

const wipeFailedUploads = () => {
	const uploads = Session.get('uploading');

	if (uploads) {
		Session.set('uploading', uploads.filter((upload) => !upload.error));
	}
};

function roomHasGlobalPurge(room) {
	if (!settings.get('RetentionPolicy_Enabled')) {
		return false;
	}

	switch (room.t) {
		case 'c':
			return settings.get('RetentionPolicy_AppliesToChannels');
		case 'p':
			return settings.get('RetentionPolicy_AppliesToGroups');
		case 'd':
			return settings.get('RetentionPolicy_AppliesToDMs');
	}
	return false;
}

function roomHasPurge(room) {
	if (!room || !settings.get('RetentionPolicy_Enabled')) {
		return false;
	}

	if (room.retention && room.retention.enabled !== undefined) {
		return room.retention.enabled;
	}

	return roomHasGlobalPurge(room);
}

function roomFilesOnly(room) {
	if (!room) {
		return false;
	}

	if (room.retention && room.retention.overrideGlobal) {
		return room.retention.filesOnly;
	}

	return settings.get('RetentionPolicy_FilesOnly');
}

function roomExcludePinned(room) {
	if (!room) {
		return false;
	}

	if (room.retention && room.retention.overrideGlobal) {
		return room.retention.excludePinned;
	}

	return settings.get('RetentionPolicy_DoNotPrunePinned');
}

function roomMaxAge(room) {
	if (!room) {
		return;
	}
	if (!roomHasPurge(room)) {
		return;
	}

	if (room.retention && room.retention.overrideGlobal) {
		return room.retention.maxAge;
	}

	if (room.t === 'c') {
		return settings.get('RetentionPolicy_MaxAge_Channels');
	}
	if (room.t === 'p') {
		return settings.get('RetentionPolicy_MaxAge_Groups');
	}
	if (room.t === 'd') {
		return settings.get('RetentionPolicy_MaxAge_DMs');
	}
}

async function createFileFromUrl(url) {
	let response;
	try {
		response = await fetch(url);
	} catch (error) {
		throw error;
	}

	const data = await response.blob();
	const metadata = {
		type: data.type,
	};
	const { mime } = await import('../../../../utils/lib/mimeTypes');
	const file = new File([data], `File - ${ moment().format(settings.get('Message_TimeAndDateFormat')) }.${ mime.extension(data.type) }`, metadata);
	return file;
}

function addToInput(text) {
	const { input } = chatMessages[RoomManager.openedRoom];
	const initText = input.value.slice(0, input.selectionStart);
	const finalText = input.value.slice(input.selectionEnd, input.value.length);

	input.value = initText + text + finalText;
	$(input).change().trigger('input');
}

callbacks.add('enter-room', wipeFailedUploads);

export const dropzoneHelpers = {
	dragAndDrop() {
		return settings.get('FileUpload_Enabled') && 'dropzone--disabled';
	},

	isDropzoneDisabled() {
		return settings.get('FileUpload_Enabled') ? 'dropzone-overlay--enabled' : 'dropzone-overlay--disabled';
	},

	dragAndDropLabel() {
		if (!userCanDrop(this._id)) {
			return 'error-not-allowed';
		}
		if (!settings.get('FileUpload_Enabled')) {
			return 'FileUpload_Disabled';
		}
		return 'Drop_to_upload_file';
	},
};

Template.roomOld.helpers({
	...dropzoneHelpers,
	tabBar() {
		return Template.instance().tabBar;
	},
	subscribed() {
		const { state } = Template.instance();
		return state.get('subscribed');
	},
	messagesHistory() {
		const showInMainThread = getUserPreference(Meteor.userId(), 'showMessageInMainThread', false);
		const { rid } = Template.instance();
		const room = Rooms.findOne(rid, { fields: { sysMes: 1 } });
		const hideSettings = settings.collection.findOne('Hide_System_Messages') || {};
		const settingValues = Array.isArray(room.sysMes) ? room.sysMes : hideSettings.value || [];
		const hideMessagesOfType = new Set(settingValues.reduce((array, value) => [...array, ...value === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [value]], []));
		const query = {
			rid,
			_hidden: { $ne: true },
			...!showInMainThread && {
				$or: [
					{ tmid: { $exists: 0 } },
					{ tshow: { $eq: true } },
				],
			},
		};

		if (hideMessagesOfType.size) {
			query.t = { $nin: Array.from(hideMessagesOfType.values()) };
		}

		const options = {
			sort: {
				ts: 1,
			},
		};

		return ChatMessage.find(query, options);
	},

	hasMore() {
		return RoomHistoryManager.hasMore(this._id);
	},

	hasMoreNext() {
		return RoomHistoryManager.hasMoreNext(this._id);
	},

	isLoading() {
		return RoomHistoryManager.isLoading(this._id);
	},

	windowId() {
		return `chat-window-${ this._id }`;
	},

	uploading() {
		return Session.get('uploading');
	},

	roomLeader() {
		const roles = RoomRoles.findOne({ rid: this._id, roles: 'leader', 'u._id': { $ne: Meteor.userId() } });
		if (roles) {
			const leader = Users.findOne({ _id: roles.u._id }, { fields: { status: 1, statusText: 1 } }) || {};

			return {
				...roles.u,
				name: settings.get('UI_Use_Real_Name') ? roles.u.name || roles.u.username : roles.u.username,
				status: leader.status || 'offline',
				statusDisplay: leader.statusText || t(leader.status || 'offline'),
			};
		}
	},

	chatNowLink() {
		return roomTypes.getRouteLink('d', { name: this.username });
	},

	announcement() {
		return Template.instance().state.get('announcement');
	},

	announcementDetails() {
		const roomData = Session.get(`roomData${ this._id }`);
		if (!roomData) { return false; }
		if (roomData.announcementDetails != null && roomData.announcementDetails.callback != null) {
			return () => callbacks.run(roomData.announcementDetails.callback, this._id);
		}
	},

	messageboxData() {
		const { sendToBottomIfNecessary, subscription } = Template.instance();
		const { _id: rid } = this;
		const isEmbedded = Layout.isEmbedded();
		const showFormattingTips = settings.get('Message_ShowFormattingTips');

		return {
			rid,
			subscription: subscription.get(),
			isEmbedded,
			showFormattingTips: showFormattingTips && !isEmbedded,
			onInputChanged: (input) => {
				if (!chatMessages[rid]) {
					return;
				}

				chatMessages[rid].initializeInput(input, { rid });
			},
			onResize: () => sendToBottomIfNecessary && sendToBottomIfNecessary(),
			onKeyUp: (...args) => chatMessages[rid] && chatMessages[rid].keyup.apply(chatMessages[rid], args),
			onKeyDown: (...args) => chatMessages[rid] && chatMessages[rid].keydown.apply(chatMessages[rid], args),
			onSend: (...args) => chatMessages[rid] && chatMessages[rid].send.apply(chatMessages[rid], args),
		};
	},

	getAnnouncementStyle() {
		const { room } = Template.instance();
		if (!room) { return ''; }
		return room.announcementDetails && room.announcementDetails.style !== undefined ? room.announcementDetails.style : '';
	},

	maxMessageLength() {
		return settings.get('Message_MaxAllowedSize');
	},

	unreadData() {
		const data = { count: Template.instance().state.get('count') };

		const room = RoomManager.getOpenedRoomByRid(this._id);
		if (room) {
			data.since = room.unreadSince.get();
		}

		return data;
	},

	containerBarsShow(unreadData, uploading) {
		const hasUnreadData = unreadData && (unreadData.count && unreadData.since);
		const isUploading = uploading && uploading.length;

		if (hasUnreadData || isUploading) {
			return 'show';
		}
	},

	formatUnreadSince() {
		if (!this.since) {
			return;
		}

		return moment(this.since).calendar(null, { sameDay: 'LT' });
	},
	adminClass() {
		if (hasRole(Meteor.userId(), 'admin')) { return 'admin'; }
	},

	messageViewMode() {
		const viewMode = getUserPreference(Meteor.userId(), 'messageViewMode');
		const modes = ['', 'cozy', 'compact'];
		return modes[viewMode] || modes[0];
	},

	selectable() {
		return Template.instance().selectable.get();
	},

	hideUsername() {
		return getUserPreference(Meteor.userId(), 'hideUsernames') ? 'hide-usernames' : undefined;
	},

	hideAvatar() {
		return getUserPreference(Meteor.userId(), 'displayAvatars') ? undefined : 'hide-avatars';
	},
	canPreview() {
		const { room, state } = Template.instance();

		if (room && room.t !== 'c') {
			return true;
		}

		if (settings.get('Accounts_AllowAnonymousRead') === true) {
			return true;
		}

		if (hasAllPermission('preview-c-room')) {
			return true;
		}

		return state.get('subscribed');
	},
	hideLeaderHeader() {
		return Template.instance().hideLeaderHeader.get() ? 'animated-hidden' : '';
	},
	hasLeader() {
		if (RoomRoles.findOne({ rid: this._id, roles: 'leader', 'u._id': { $ne: Meteor.userId() } }, { fields: { _id: 1 } })) {
			return 'has-leader';
		}
	},
	hasPurge() {
		const { room } = Template.instance();
		return roomHasPurge(room);
	},
	filesOnly() {
		const { room } = Template.instance();
		return roomFilesOnly(room);
	},
	excludePinned() {
		const { room } = Template.instance();
		return roomExcludePinned(room);
	},
	purgeTimeout() {
		const { room } = Template.instance();
		moment.relativeTimeThreshold('s', 60);
		moment.relativeTimeThreshold('ss', 0);
		moment.relativeTimeThreshold('m', 60);
		moment.relativeTimeThreshold('h', 24);
		moment.relativeTimeThreshold('d', 31);
		moment.relativeTimeThreshold('M', 12);

		return moment.duration(roomMaxAge(room) * 1000 * 60 * 60 * 24).humanize();
	},
	messageContext,
	openedThread() {
		FlowRouter.watchPathChange();
		const tab = FlowRouter.getParam('tab');
		const mid = FlowRouter.getParam('context');
		const rid = Template.currentData()._id;
		const jump = FlowRouter.getQueryParam('jump');
		const subscription = Template.instance().subscription.get();

		if (tab !== 'thread' || !mid || rid !== Session.get('openedRoom')) {
			return;
		}

		const room = Rooms.findOne({ _id: rid }, {
			fields: {
				t: 1,
				usernames: 1,
				uids: 1,
				name: 1,
			},
		});

		return {
			rid,
			mid,
			room,
			jump,
			subscription,
		};
	},
});

export const dropzoneEvents = {
	'dragenter .dropzone'(e) {
		const types = e.originalEvent && e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.types;

		if (types != null && types.length > 0 && _.some(types, (type) => type.indexOf('text/') === -1 || type.indexOf('text/uri-list') !== -1 || type.indexOf('text/plain') !== -1) && userCanDrop(this._id)) {
			e.currentTarget.classList.add('over');
		}
		e.stopPropagation();
	},

	'dragleave .dropzone-overlay'(e) {
		e.currentTarget.parentNode.classList.remove('over');
		e.stopPropagation();
	},

	'dragover .dropzone-overlay'(e) {
		document.querySelectorAll('.over.dropzone').forEach((dropzone) => {
			if (dropzone !== e.currentTarget.parentNode) {
				dropzone.classList.remove('over');
			}
		});
		e = e.originalEvent || e;
		if (['move', 'linkMove'].includes(e.dataTransfer.effectAllowed)) {
			e.dataTransfer.dropEffect = 'move';
		} else {
			e.dataTransfer.dropEffect = 'copy';
		}
		e.stopPropagation();
	},

	async 'dropped .dropzone-overlay'(event, instance) {
		event.currentTarget.parentNode.classList.remove('over');

		const e = event.originalEvent || event;

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

		if (!userCanDrop(this._id) || !settings.get('FileUpload_Enabled')) {
			return false;
		}

		let files = (e.dataTransfer && e.dataTransfer.files) || [];

		if (files.length < 1) {
			const transferData = e.dataTransfer.getData('text') || e.dataTransfer.getData('url');

			if (e.dataTransfer.types.includes('text/uri-list')) {
				const url = e.dataTransfer.getData('text/html').match('\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>');
				const imgURL = url && url[1];

				if (!imgURL) {
					return;
				}

				const file = await createFileFromUrl(imgURL);
				if (typeof file === 'string') {
					return addToInput(file);
				}
				files = [file];
			}
			if (e.dataTransfer.types.includes('text/plain') && !e.dataTransfer.types.includes('text/x-moz-url')) {
				return addToInput(transferData.trim());
			}
		}
		const { mime } = await import('../../../../utils/lib/mimeTypes');
		const filesToUpload = Array.from(files).map((file) => {
			Object.defineProperty(file, 'type', { value: mime.lookup(file.name) });
			return {
				file,
				name: file.name,
			};
		});

		return instance.onFile && instance.onFile(filesToUpload);
	},
};
Meteor.startup(() => {
	Template.roomOld.events({
		...getCommonRoomEvents(),
		...dropzoneEvents,
		'click .toggle-hidden'(e) {
			const id = e.currentTarget.dataset.message;
			document.querySelector(`#${ id }`).classList.toggle('message--ignored');
		},

		'click .message'(e, template) {
			if (template.selectable.get()) {
				(document.selection != null ? document.selection.empty() : undefined) || (typeof window.getSelection === 'function' ? window.getSelection().removeAllRanges() : undefined);
				const data = Blaze.getData(e.currentTarget);
				const { msg: { _id } } = messageArgs(data);

				if (!template.selectablePointer) {
					template.selectablePointer = _id;
				}

				if (!e.shiftKey) {
					template.selectedMessages = template.getSelectedMessages();
					template.selectedRange = [];
					template.selectablePointer = _id;
				}

				template.selectMessages(_id);

				const selectedMessages = $('.messages-box .message.selected').map((i, message) => message.id);
				const removeClass = _.difference(selectedMessages, template.getSelectedMessages());
				const addClass = _.difference(template.getSelectedMessages(), selectedMessages);
				removeClass.forEach((message) => $(`.messages-box #${ message }`).removeClass('selected'));
				addClass.forEach((message) => $(`.messages-box #${ message }`).addClass('selected'));
			}
		},
		'click .jump-recent button'(e, template) {
			e.preventDefault();
			template.atBottom = true;
			RoomHistoryManager.clear(template && template.data && template.data._id);
		},
		'load .gallery-item'(e, template) {
			template.sendToBottomIfNecessary();
		},

		'rendered .js-block-wrapper'(e, template) {
			template.sendToBottomIfNecessary();
		},
		'click .new-message'(event, instance) {
			instance.atBottom = true;
			instance.sendToBottomIfNecessary();
			chatMessages[RoomManager.openedRoom].input.focus();
		},
		'click .upload-progress-close'(e) {
			e.preventDefault();
			Session.set(`uploading-cancel-${ this.id }`, true);
		},
		'click .unread-bar > button.mark-read'(e, t) {
			readMessage.readNow(t.data._id);
		},

		'click .unread-bar > button.jump-to'(e, t) {
			const { _id } = t.data;
			const room = RoomHistoryManager.getRoom(_id);
			let message = room && room.firstUnread.get();
			if (!message) {
				const subscription = Subscriptions.findOne({ rid: _id });
				message = ChatMessage.find({ rid: _id, ts: { $gt: subscription != null ? subscription.ls : undefined } }, { sort: { ts: 1 }, limit: 1 }).fetch()[0];
			}
			RoomHistoryManager.getSurroundingMessages(message, 50);
		},
		'scroll .wrapper': _.throttle(function(e, t) {
			const $roomLeader = $('.room-leader');
			if ($roomLeader.length) {
				if (e.target.scrollTop < t.lastScrollTop) {
					t.hideLeaderHeader.set(false);
				} else if (t.isAtBottom(100) === false && e.target.scrollTop > $roomLeader.height()) {
					t.hideLeaderHeader.set(true);
				}
			}
			t.lastScrollTop = e.target.scrollTop;
			const height = e.target.clientHeight;
			const isLoading = RoomHistoryManager.isLoading(this._id);
			const hasMore = RoomHistoryManager.hasMore(this._id);
			const hasMoreNext = RoomHistoryManager.hasMoreNext(this._id);

			if ((isLoading === false && hasMore === true) || hasMoreNext === true) {
				if (hasMore === true && t.lastScrollTop <= height / 3) {
					RoomHistoryManager.getMore(this._id);
				} else if (hasMoreNext === true && Math.ceil(t.lastScrollTop) >= e.target.scrollHeight - height) {
					RoomHistoryManager.getMoreNext(this._id);
				}
			}
		}, 100),

		'click .time a'(e) {
			e.preventDefault();
			const { msg } = messageArgs(this);
			const repliedMessageId = msg.attachments[0].message_link.split('?msg=')[1];
			FlowRouter.go(FlowRouter.current().context.pathname, null, { msg: repliedMessageId, hash: Random.id() });
		},
	});

	Template.roomOld.onCreated(function() {
		// this.scrollOnBottom = true
		// this.typing = new msgTyping this.data._id
		const rid = this.data._id;
		this.tabBar = this.data.tabBar;

		this.onFile = (filesToUpload) => {
			fileUpload(filesToUpload, chatMessages[rid].input, { rid });
		};

		this.rid = rid;

		this.subscription = new ReactiveVar();
		this.state = new ReactiveDict();
		this.userDetail = new ReactiveVar('');
		const user = Meteor.user();
		this.autorun((c) => {
			const room = Rooms.findOne({ _id: rid }, {
				fields: {
					t: 1,
					usernames: 1,
					uids: 1,
				},
			});

			if (room.t !== 'd') {
				return c.stop();
			}

			if (roomTypes.getConfig(room.t).isGroupChat(room)) {
				return;
			}
			const usernames = Array.from(new Set(room.usernames));
			this.userDetail.set(this.userDetail.get() || (usernames.length === 1 ? usernames[0] : usernames.filter((username) => username !== user.username)[0]));
		});

		this.autorun(() => {
			const rid = Template.currentData()._id;
			const room = Rooms.findOne({ _id: rid }, { fields: { announcement: 1 } });
			this.state.set('announcement', room.announcement);
		});

		this.autorun(() => {
			const subscription = Subscriptions.findOne({ rid });
			this.subscription.set(subscription);
			this.state.set({
				subscribed: !!subscription,
				autoTranslate: subscription && subscription.autoTranslate,
				autoTranslateLanguage: subscription && subscription.autoTranslateLanguage,
			});
		});

		this.showUsersOffline = new ReactiveVar(false);
		this.atBottom = !FlowRouter.getQueryParam('msg');
		this.unreadCount = new ReactiveVar(0);

		this.selectable = new ReactiveVar(false);
		this.selectedMessages = [];
		this.selectedRange = [];
		this.selectablePointer = null;

		this.flexTemplate = new ReactiveVar();

		this.groupDetail = new ReactiveVar();

		this.hideLeaderHeader = new ReactiveVar(false);

		this.resetSelection = (enabled) => {
			this.selectable.set(enabled);
			$('.messages-box .message.selected').removeClass('selected');
			this.selectedMessages = [];
			this.selectedRange = [];
			this.selectablePointer = null;
		};

		this.selectMessages = (to) => {
			if ((this.selectablePointer === to) && (this.selectedRange.length > 0)) {
				this.selectedRange = [];
			} else {
				const message1 = ChatMessage.findOne(this.selectablePointer);
				const message2 = ChatMessage.findOne(to);

				const minTs = _.min([message1.ts, message2.ts]);
				const maxTs = _.max([message1.ts, message2.ts]);

				this.selectedRange = _.pluck(ChatMessage.find({ rid: message1.rid, ts: { $gte: minTs, $lte: maxTs } }).fetch(), '_id');
			}
		};

		this.getSelectedMessages = () => {
			let previewMessages;
			const messages = this.selectedMessages;
			let addMessages = false;
			for (const message of Array.from(this.selectedRange)) {
				if (messages.indexOf(message) === -1) {
					addMessages = true;
					break;
				}
			}

			if (addMessages) {
				previewMessages = _.compact(_.uniq(this.selectedMessages.concat(this.selectedRange)));
			} else {
				previewMessages = _.compact(_.difference(this.selectedMessages, this.selectedRange));
			}

			return previewMessages;
		};

		this.clearUserDetail = () => {
			this.userDetail.set(null);
			this.tabBar.setData({});
			this.tabBar.close();
		};

		Meteor.call('getRoomRoles', this.data._id, function(error, results) {
			if (error) {
				handleError(error);
			}

			return Array.from(results).forEach((record) => {
				delete record._id;
				RoomRoles.upsert({ rid: record.rid, 'u._id': record.u._id }, record);
			});
		});

		this.rolesObserve = RoomRoles.find({ rid: this.data._id }).observe({
			added: (role) => {
				if (!role.u || !role.u._id) {
					return;
				}
				ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $addToSet: { roles: role._id } }, { multi: true });
			}, // Update message to re-render DOM
			changed: (role) => {
				if (!role.u || !role.u._id) {
					return;
				}
				ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $inc: { rerender: 1 } }, { multi: true });
			}, // Update message to re-render DOM
			removed: (role) => {
				if (!role.u || !role.u._id) {
					return;
				}
				ChatMessage.update({ rid: this.data._id, 'u._id': role.u._id }, { $pull: { roles: role._id } }, { multi: true });
			},
		});

		this.sendToBottomIfNecessary = () => {
			if (this.atBottom === true) {
				this.sendToBottom();
			}
		};
	}); // Update message to re-render DOM

	Template.roomOld.onDestroyed(function() {
		if (this.rolesObserve) {
			this.rolesObserve.stop();
		}

		readMessage.off(this.data._id);

		window.removeEventListener('resize', this.onWindowResize);

		this.observer && this.observer.disconnect();

		const chatMessage = chatMessages[this.data._id];
		chatMessage.onDestroyed && chatMessage.onDestroyed(this.data._id);

		callbacks.remove('streamNewMessage', this.data._id);
	});

	const isAtBottom = function(element, scrollThreshold = 0) {
		return element.scrollTop + scrollThreshold >= element.scrollHeight - element.clientHeight;
	};

	Template.roomOld.onRendered(function() {
		const { _id: rid } = this.data;

		if (!chatMessages[rid]) {
			chatMessages[rid] = new ChatMessages();
		}

		const wrapper = this.find('.wrapper');

		const store = NewRoomManager.getStore(rid);

		const afterMessageGroup = () => {
			if (store.scroll && !store.atBottom) {
				wrapper.scrollTop = store.scroll;
			} else {
				this.sendToBottom();
			}
			wrapper.removeEventListener('MessageGroup', afterMessageGroup);

			wrapper.addEventListener('scroll', _.throttle(() => {
				store.update({ scroll: wrapper.scrollTop, atBottom: isAtBottom(wrapper, 50) });
			}, 30));
		};

		wrapper.addEventListener('MessageGroup', afterMessageGroup);

		chatMessages[rid].initializeWrapper(this.find('.wrapper'));
		chatMessages[rid].initializeInput(this.find('.js-input-message'), { rid });

		const wrapperUl = this.find('.wrapper > ul');
		const newMessage = this.find('.new-message');

		const template = this;

		const messageBox = $('.messages-box');

		template.isAtBottom = function(scrollThreshold = 0) {
			if (isAtBottom(wrapper, scrollThreshold)) {
				newMessage.className = 'new-message background-primary-action-color color-content-background-color not';
				return true;
			}
			return false;
		};

		template.sendToBottom = function() {
			wrapper.scrollTo(30, wrapper.scrollHeight);
			newMessage.className = 'new-message background-primary-action-color color-content-background-color not';
		};

		template.checkIfScrollIsAtBottom = function() {
			template.atBottom = template.isAtBottom(100);
		};

		template.observer = new ResizeObserver(() => template.sendToBottomIfNecessary());

		template.observer.observe(wrapperUl);

		const wheelHandler = _.throttle(function() {
			template.checkIfScrollIsAtBottom();
		}, 100);

		wrapper.addEventListener('mousewheel', wheelHandler);

		wrapper.addEventListener('wheel', wheelHandler);

		wrapper.addEventListener('touchstart', () => { template.atBottom = false; });

		wrapper.addEventListener('touchend', function() {
			template.checkIfScrollIsAtBottom();
			setTimeout(() => template.checkIfScrollIsAtBottom(), 1000);
			setTimeout(() => template.checkIfScrollIsAtBottom(), 2000);
		});

		Tracker.afterFlush(() => {
			wrapper.addEventListener('scroll', wheelHandler);
		});

		this.lastScrollTop = $('.messages-box .wrapper').scrollTop();

		const rtl = $('html').hasClass('rtl');

		const getElementFromPoint = function(topOffset = 0) {
			const messageBoxOffset = messageBox.offset();

			let element;
			if (rtl) {
				element = document.elementFromPoint((messageBoxOffset.left + messageBox.width()) - 1, messageBoxOffset.top + topOffset + 1);
			} else {
				element = document.elementFromPoint(messageBoxOffset.left + 1, messageBoxOffset.top + topOffset + 1);
			}

			if (element && element.classList.contains('message')) {
				return element;
			}
		};

		const updateUnreadCount = _.throttle(() => {
			Tracker.afterFlush(() => {
				const lastInvisibleMessageOnScreen = getElementFromPoint(0) || getElementFromPoint(20) || getElementFromPoint(40);

				if (!lastInvisibleMessageOnScreen || !lastInvisibleMessageOnScreen.id) {
					return this.unreadCount.set(0);
				}

				const lastMessage = ChatMessage.findOne(lastInvisibleMessageOnScreen.id);
				if (!lastMessage) {
					return this.unreadCount.set(0);
				}

				this.state.set('lastMessage', lastMessage.ts);
			});
		}, 300);

		const read = _.debounce(function() {
			if (rid !== Session.get('openedRoom')) {
				return;
			}
			readMessage.read(rid);
		}, 500);

		this.autorun(() => {
			if (rid !== Session.get('openedRoom')) {
				return;
			}

			let room = Rooms.findOne({ _id: rid }, { fields: { t: 1 } });

			if (room?.t === 'l') {
				room = Tracker.nonreactive(() => Rooms.findOne({ _id: rid }));
				roomTypes.getConfig(room.t).openCustomProfileTab(this, room, room.v.username);
			}
		});

		this.autorun(() => {
			if (!Object.values(roomTypes.roomTypes).map(({ route }) => route && route.name).filter(Boolean).includes(FlowRouter.getRouteName())) {
				return;
			}

			if (rid !== Session.get('openedRoom')) {
				return;
			}

			const subscription = Subscriptions.findOne({ rid }, { fields: { alert: 1, unread: 1 } });
			read();
			return subscription && (subscription.alert || subscription.unread) && readMessage.refreshUnreadMark(rid);
		});

		this.autorun(() => {
			const lastMessage = this.state.get('lastMessage');

			const subscription = Subscriptions.findOne({ rid }, { fields: { ls: 1 } });
			if (!subscription) {
				this.unreadCount.set(0);
				return;
			}

			const count = ChatMessage.find({ rid, ts: { $lte: lastMessage, $gt: subscription && subscription.ls } }).count();

			this.unreadCount.set(count);
		});

		this.autorun(() => {
			const count = RoomHistoryManager.getRoom(rid).unreadNotLoaded.get() + this.unreadCount.get();
			this.state.set('count', count);
		});

		this.autorun(() => {
			Rooms.findOne(rid);
			const count = this.state.get('count');
			if (count === 0) {
				return read();
			}
			readMessage.refreshUnreadMark(rid);
		});

		readMessage.on(template.data._id, () => this.unreadCount.set(0));

		wrapper.addEventListener('scroll', updateUnreadCount);
		// salva a data da renderização para exibir alertas de novas mensagens
		$.data(this.firstNode, 'renderedAt', new Date());

		const webrtc = WebRTC.getInstanceByRoomId(template.data._id);
		if (webrtc) {
			this.autorun(() => {
				const remoteItems = webrtc.remoteItems.get();
				if (remoteItems && remoteItems.length > 0) {
					this.tabBar.open('members-list');
				}

				if (webrtc.localUrl.get()) {
					this.tabBar.open('members-list');
				}
			});
		}
		callbacks.add('streamNewMessage', (msg) => {
			if (rid !== msg.rid || msg.editedAt || msg.tmid) {
				return;
			}

			if (msg.u._id === Meteor.userId()) {
				return template.sendToBottom();
			}

			if (!template.isAtBottom()) {
				newMessage.classList.remove('not');
			}
		}, callbacks.priority.MEDIUM, rid);

		this.autorun(function() {
			if (template.data._id !== RoomManager.openedRoom) {
				return;
			}

			const room = Rooms.findOne({ _id: template.data._id });
			if (!room) {
				return FlowRouter.go('home');
			}
		});
	});
});

callbacks.add('enter-room', (sub) => {
	if (!sub) {
		return;
	}
	const isAReplyInDMFromChannel = FlowRouter.getQueryParam('reply') && sub.t === 'd';
	if (isAReplyInDMFromChannel && chatMessages[sub.rid]) {
		chatMessages[sub.rid].restoreReplies();
	}
	setTimeout(() => readMessage.read(sub.rid), 1000);
});


text:
#ifndef BASIC_SIMPLIFIER_PLUGIN_H_
#define BASIC_SIMPLIFIER_PLUGIN_H_

#include"simplifier_plugin.h"

class bool_rewriter;

/**
   \brief Simplifier for the basic family.
*/
class basic_simplifier_plugin : public simplifier_plugin {
    bool_rewriter * m_rewriter;
public:
    basic_simplifier_plugin(ast_manager & m);
    virtual ~basic_simplifier_plugin();
    bool_rewriter & get_rewriter() { return *m_rewriter; }
    bool eliminate_and() const;
    void set_eliminate_and(bool f);
    void mk_eq(expr * lhs, expr * rhs, expr_ref & result);
    void mk_iff(expr * lhs, expr * rhs, expr_ref & result);
    void mk_xor(expr * lhs, expr * rhs, expr_ref & result);
    void mk_implies(expr * lhs, expr * rhs, expr_ref & result);
    void mk_ite(expr * c, expr * t, expr * e, expr_ref & result);
    void mk_and(unsigned num_args, expr * const * args, expr_ref & result);
    void mk_or(unsigned num_args, expr * const * args, expr_ref & result);
    void mk_and(expr * arg1, expr * arg2, expr_ref & result);
    void mk_or(expr * arg1, expr * arg2, expr_ref & result);
    void mk_and(expr * arg1, expr * arg2, expr * arg3, expr_ref & result);
    void mk_or(expr * arg1, expr * arg2, expr * arg3, expr_ref & result);
    void mk_nand(unsigned num_args, expr * const * args, expr_ref & result);
    void mk_nor(unsigned num_args, expr * const * args, expr_ref & result);
    void mk_nand(expr * arg1, expr * arg2, expr_ref & result);
    void mk_nor(expr * arg1, expr * arg2, expr_ref & result);
    void mk_distinct(unsigned num_args, expr * const * args, expr_ref & result);
    void mk_not(expr * n, expr_ref & result);
    virtual bool reduce(func_decl * f, unsigned num_args, expr * const * args, expr_ref & result);
    virtual void enable_ac_support(bool flag);
};

/**
   \brief Functor that compares expressions, but puts the expressions e and f(e) close to each other, where
   f is in family m_fid, and has kind m_dkind;
*/
struct expr_lt_proc {
    family_id  m_fid;
    decl_kind  m_dkind;

    expr_lt_proc(family_id fid = null_family_id, decl_kind k = null_decl_kind):m_fid(fid), m_dkind(k) {}

    unsigned get_id(expr * n) const {
        if (m_fid != null_family_id && is_app_of(n, m_fid, m_dkind))
            return (to_app(n)->get_arg(0)->get_id() << 1) + 1;
        else
            return n->get_id() << 1;
    }

    bool operator()(expr * n1, expr * n2) const {
        return get_id(n1) < get_id(n2);
    }
};

#endif /* BASIC_SIMPLIFIER_PLUGIN_H_ */

redpajama_set_name: RedPajamaGithub


text:
(function ($, bootbox, Util, Rule, Config) {
    var page = {el: {}, func: {}};
    $(function () {
        page.func.init = function () {
            page.el.inputUrl = $('#inputUrl');
            page.el.inputGroup = $('#inputGroup');
            page.el.inputGroup = $('#inputGroup');
            page.el.inputJsonp = $('#inputJsonp');
            page.el.textAreaResponse = $('#textAreaResponse');
            page.el.alertError = $('#alertError');
            page.el.btnSave = $('#btnSave');
            page.el.btnReset = $('#btnReset');
            page.el.strongMessage = $('#strongMessage');

            page.el.textAreaResponse.autosize({append: "\n"});
        };

        page.func.bindEvent = function () {
            page.el.btnSave.click(function () {
                var rule = page.func.getRuleData();
                var checkResult = Rule.checkRule(rule);
                if (checkResult !== true) {
                    page.func.showError(checkResult);
                    return;
                }
                page.func.clearMessage();
                page.el.btnSave.prop('disabled', true);
                $.ajax({
                    url: Config.url.addRule,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        rule: Rule.serialize(rule)
                    },
                    success: function (resp) {
                        if (resp.error == 0) {
                            page.func.showSuccess('保存成功');
                        } else {
                            page.func.showError('保存失败:' + resp.message);
                        }
                        page.el.btnSave.prop('disabled', false);
                    },
                    error: function (xhr, status, error) {
                        page.func.showError('保存失败:' + (status ? status : error));
                        page.el.btnSave.prop('disabled', false);
                    }
                });
            });

            page.el.btnReset.click(function () {
                $.each([page.el.inputUrl, page.el.inputGroup, page.el.textAreaResponse, page.el.inputJsonp],
                    function (index, item) {
                        item.val('');
                    });
            });
        };

        page.func.getRuleData = function () {
            var rule = {
                url: $.trim(page.el.inputUrl.val()),
                group: $.trim(page.el.inputGroup.val()),
                jsonp: $.trim(page.el.inputJsonp.val()),
                res: $.trim(page.el.textAreaResponse.val()),
            };
            return rule;
        };
        page.func.showError = function (message) {
            page.el.strongMessage.html(message);
            page.el.alertError.removeClass('hidden').removeClass('alert-success').addClass('alert-danger');
            page.el.alertError.show();
        };

        page.func.showSuccess = function (message) {
            page.el.strongMessage.html(message);
            page.el.alertError.removeClass('hidden').removeClass('alert-danger').addClass('alert-success');
            page.el.alertError.show();
            page.el.alertError.hide(1000, 'linear', function () {
                page.func.clearMessage();
            });
        };

        page.func.clearMessage = function () {
            page.el.strongMessage.html('');
            page.el.alertError.addClass('hidden');
        };

        page.func.init();
        page.func.bindEvent();
    });
})(jQuery, bootbox, Util, Rule, Config);


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/functions/v1/functions.proto

package com.google.cloud.functions.v1;

public interface GenerateUploadUrlRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.functions.v1.GenerateUploadUrlRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The project and location in which the Google Cloud Storage signed URL
   * should be generated, specified in the format `projects/*/locations/*`.
   *

   *
   * string parent = 1;
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * The project and location in which the Google Cloud Storage signed URL
   * should be generated, specified in the format `projects/*/locations/*`.
   *

   *
   * string parent = 1;
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Resource name of a KMS crypto key (managed by the user) used to
   * encrypt/decrypt function source code objects in staging Cloud Storage
   * buckets. When you generate an upload url and upload your source code, it
   * gets copied to a staging Cloud Storage bucket in an internal regional
   * project. The source code is then copied to a versioned directory in the
   * sources bucket in the consumer project during the function deployment.
   * It must match the pattern
   * `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.
   * The Google Cloud Functions service account
   * (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) must be
   * granted the role 'Cloud KMS CryptoKey Encrypter/Decrypter
   * (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the
   * Key/KeyRing/Project/Organization (least access preferred). GCF will
   * delegate access to the Google Storage service account in the internal
   * project.
   *

   *
   * string kms_key_name = 2 [(.google.api.resource_reference) = { ... }
   *
   * @return The kmsKeyName.
   */
  java.lang.String getKmsKeyName();
  /**
   *
   *
   *

   * Resource name of a KMS crypto key (managed by the user) used to
   * encrypt/decrypt function source code objects in staging Cloud Storage
   * buckets. When you generate an upload url and upload your source code, it
   * gets copied to a staging Cloud Storage bucket in an internal regional
   * project. The source code is then copied to a versioned directory in the
   * sources bucket in the consumer project during the function deployment.
   * It must match the pattern
   * `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.
   * The Google Cloud Functions service account
   * (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) must be
   * granted the role 'Cloud KMS CryptoKey Encrypter/Decrypter
   * (roles/cloudkms.cryptoKeyEncrypterDecrypter)' on the
   * Key/KeyRing/Project/Organization (least access preferred). GCF will
   * delegate access to the Google Storage service account in the internal
   * project.
   *

   *
   * string kms_key_name = 2 [(.google.api.resource_reference) = { ... }
   *
   * @return The bytes for kmsKeyName.
   */
  com.google.protobuf.ByteString getKmsKeyNameBytes();
}


text:
Getting you the file...

        The file should download automatically, but if not, click here to start the download.


text:
const spellingErrors = {
  "utilizaton":"utilization",
  "uzing":"using"
};

//SpellCheck function
const SpellCheck = (term) => {
  let rebuild = false;
  const fixed = term.text.split(" ").map((w) => {
    if (spellingErrors[w]) {
      rebuild = true;
      return spellingErrors[w];
    }
    return w;
  });

  if (rebuild) {
    term.text = fixed.join(" ");
    term.rebuild();
  }

  return term;
};

module.exports = SpellCheck;


text:
<?php namespace Aliyun\MTS\Request;

use Aliyun\Core\RpcAcsRequest;

class SubmitAnalysisJobRequest extends RpcAcsRequest
{

    private $ownerId;

    private $resourceOwnerAccount;

    private $resourceOwnerId;

    private $input;

    private $analysisConfig;

    private $userData;

    private $pipelineId;

    private $priority;

    private $ownerAccount;

    public function  __construct()
    {
        parent::__construct("Mts", "2014-06-18", "SubmitAnalysisJob");
    }

    public function getOwnerId()
    {
        return $this->ownerId;
    }

    public function setOwnerId($ownerId)
    {
        $this->ownerId                    = $ownerId;
        $this->queryParameters["OwnerId"] = $ownerId;
    }

    public function getResourceOwnerAccount()
    {
        return $this->resourceOwnerAccount;
    }

    public function setResourceOwnerAccount($resourceOwnerAccount)
    {
        $this->resourceOwnerAccount                    = $resourceOwnerAccount;
        $this->queryParameters["ResourceOwnerAccount"] = $resourceOwnerAccount;
    }

    public function getResourceOwnerId()
    {
        return $this->resourceOwnerId;
    }

    public function setResourceOwnerId($resourceOwnerId)
    {
        $this->resourceOwnerId                    = $resourceOwnerId;
        $this->queryParameters["ResourceOwnerId"] = $resourceOwnerId;
    }

    public function getInput()
    {
        return $this->input;
    }

    public function setInput($input)
    {
        $this->input                    = $input;
        $this->queryParameters["Input"] = $input;
    }

    public function getAnalysisConfig()
    {
        return $this->analysisConfig;
    }

    public function setAnalysisConfig($analysisConfig)
    {
        $this->analysisConfig                    = $analysisConfig;
        $this->queryParameters["AnalysisConfig"] = $analysisConfig;
    }

    public function getUserData()
    {
        return $this->userData;
    }

    public function setUserData($userData)
    {
        $this->userData                    = $userData;
        $this->queryParameters["UserData"] = $userData;
    }

    public function getPipelineId()
    {
        return $this->pipelineId;
    }

    public function setPipelineId($pipelineId)
    {
        $this->pipelineId                    = $pipelineId;
        $this->queryParameters["PipelineId"] = $pipelineId;
    }

    public function getPriority()
    {
        return $this->priority;
    }

    public function setPriority($priority)
    {
        $this->priority                    = $priority;
        $this->queryParameters["Priority"] = $priority;
    }

    public function getOwnerAccount()
    {
        return $this->ownerAccount;
    }

    public function setOwnerAccount($ownerAccount)
    {
        $this->ownerAccount                    = $ownerAccount;
        $this->queryParameters["OwnerAccount"] = $ownerAccount;
    }

}


text:
#import "DDUtility.h"

@implementation DDUtility

+(void) print:(NSString*)string {
	NSFileHandle *standardOutput = [NSFileHandle fileHandleWithStandardOutput];
	NSData *dataToWrite = [string dataUsingEncoding:NSUTF8StringEncoding];
	[standardOutput writeData:dataToWrite];
}

@end


text:
<?php
/**
 * Progress Indicators (Premium)
 *
 * @package WordPress
 * @subpackage Launch_Effect
 *
 */
?>
				<?php
					$launchDate = ler('lefx_proglaunchdate');

					if($launchDate == 0) { $launchDate = '1/1/2011'; }

					$launchDate = explode('/',$launchDate);

					$startDate = ler('lefx_progstartdate');
					$endDate = ler('lefx_proglaunchdate');

					if($startDate == 0) { $startDate = 'Yesterday'; }
					if($endDate == 0) { $endDate = 'Tomorrow'; }

					$startDate =  strtotime($startDate);
					$nowDate = time();
					$endDate =  strtotime($endDate);

					$duration = $endDate - $startDate;
					$timeLeft = $endDate - $nowDate;

					if ($timeLeft < 1) { $timeLeft = 0; }

					$daysLeft = $timeLeft/86400;

					if ($duration > 0) {
						$complete = (($duration - $timeLeft)/$duration)*100;
					}
					$complete = isset($complete)&&$complete>0?$complete:0;

				?>

				<input type="hidden" id="launchMonth" value="<?php echo $launchDate[0]; ?>" />
				<input type="hidden" id="launchDay" value="<?php echo $launchDate[1]; ?>" />
				<input type="hidden" id="launchYear" value="<?php echo $launchDate[2]; ?>" />
				<?php if(get_option('lefx_progbarenable') == 'true' || get_option('lefx_progcountenable') == 'true'): ?>

						<?php

							if($timeLeft !== 0) {
								le('lefx_progtitle');
							} else {
								le('lefx_progtitlecomplete');
							}

						?>

				<?php endif; ?>
				<?php if(get_option('lefx_progbarenable') == 'true'): ?>

					<div id="bar" <?php if(ler('lefx_progbarstyle') == 'Stylish') { echo 'class="stylish"'; } ?>>

						<input type="hidden" class="barComplete" value="<?php echo round($complete); ?>" />

<?php echo round($complete); ?>%

				<?php endif; ?>
				<?php if(get_option('lefx_progcountenable') == 'true'):

						echo '
';

					?>

						<input type="hidden" class="daysLeft" value="<?php echo round($daysLeft); ?>" />

							{dnn}
							<?php le('lefx_progcountdays'); ?>

							{hnn}
							<?php le('lefx_progcounthours'); ?>

							{mnn}
							<?php le('lefx_progcountmins'); ?>

							{snn}
							<?php le('lefx_progcountsecs'); ?>

				<?php endif; ?>
				<?php if(get_option('lefx_progbarenable') == 'true' || get_option('lefx_progcountenable') == 'true') echo '
'; ?>


text:
require 'spec_helper'

RSpec.describe Cryptoexchange::Exchanges::Mercatox::Market do
  it { expect(described_class::NAME).to eq 'mercatox' }
  it { expect(described_class::API_URL).to eq 'https://mercatox.com/api/public/v1' }
end


text:
require 'rails_helper'

RSpec.describe(TicketPdf, type: :model) do
  include I18nSpecHelper

  let(:lottery) do
    Lottery.create!(event_date: Time.zone.today)
  end

  let(:guest) do
    Guest.create!(full_name: 'Bubbles')
  end

  let(:table) do
    Table.create!(
      lottery: lottery,
      number: 1,
      capacity: 6,
    )
  end

  let(:ticket) do
    Ticket.create!(
      number: 1,
      lottery: lottery,
      state: 'paid',
      ticket_type: 'meal_and_lottery',
      table: table,
      guest: guest,
    )
  end

  let(:ticket_pdf) do
    TicketPdf.new(ticket: ticket)
  end

  context('#filename') do
    it('returns "ticket_6.pdf" when the ticket#number == 6') do
      ticket.number = 6
      assert_equal(
        'ticket_6.pdf',
        ticket_pdf.filename,
      )
    end

    it('returns "billet_6.pdf" when the ticket#number == 6 and I18n.locale == :fr') do
      with_locale(:fr) do
        ticket.number = 6
        assert_equal(
          'billet_6.pdf',
          ticket_pdf.filename,
        )
      end
    end
  end

  context('#render') do
    it('returns not nil') do
      expect(ticket_pdf.render).to be_present
    end
  end
end


text:
<!DOCTYPE html>

  <title>Documentation - JSDuck</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="fragment" content="!">

  <link rel="shortcut icon" type="image/ico" href="favicon.ico" />
  <link rel="stylesheet" href="resources/css/app-851b66f18114a2a31d488e9c8d7cb964.css" type="text/css" />

Documentation - JSDuck

Documentation JSDuck

StompJS

Classes

Frame

Stomp

Utilities

StompUtils

StompLogger

Generated with JSDuck 4.6.2.


text:
package org.joda.beans.test;

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

import org.joda.beans.Bean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;

/**
 * Assertion class to compare beans.
 *

 * This class fulfils a similar role to other assertion libraries in testing code.
 * It should generally be statically imported.
 */
public final class BeanAssert {

    /**
     * Restricted constructor.
     */
    private BeanAssert() {
    }

    //-----------------------------------------------------------------------
    /**
     * Asserts that two beans are equal, providing a better error message.
     *
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     */
    public static void assertBeanEquals(Bean expected, Bean actual) {
        assertBeanEquals(null, expected, actual, 0d);
    }

    /**
     * Asserts that two beans are equal, providing a better error message.
     *

     * Note that specifying a tolerance can mean that two beans compare as not
     * equal using {@link Object#equals(Object)} but equal using this method,
     * because the standard equals method has no tolerance.
     *
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     * @param tolerance  the tolerance to use for {@code double} and {@code float}
     */
    public static void assertBeanEquals(Bean expected, Bean actual, double tolerance) {
        assertBeanEquals(null, expected, actual, tolerance);
    }

    /**
     * Asserts that two beans are equal, providing a better error message.
     *
     * @param baseMsg  the message to use in any error, null uses default message
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     */
    public static void assertBeanEquals(String baseMsg, Bean expected, Bean actual) {
        assertBeanEquals(baseMsg, expected, actual, 0d);
    }

    /**
     * Asserts that two beans are equal, providing a better error message.
     *

     * Note that specifying a tolerance can mean that two beans compare as not
     * equal using {@link Object#equals(Object)} but equal using this method,
     * because the standard equals method has no tolerance.
     *
     * @param baseMsg  the message to use in any error, null uses default message
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     * @param tolerance  the tolerance to use for {@code double} and {@code float}
     */
    public static void assertBeanEquals(String baseMsg, Bean expected, Bean actual, double tolerance) {
        if (expected == null) {
            throw new AssertionError(baseMsg + ": Expected bean must not be null");
        }
        if (actual == null) {
            throw new AssertionError(baseMsg + ": Actual bean must not be null");
        }
        if (expected.equals(actual) == false) {
            String comparisonMsg = buildMessage(baseMsg, 10, expected, actual, tolerance);
            if (comparisonMsg.isEmpty()) {
                return; // no errors, just double/float within tolerance
            }
            throw new BeanComparisonError(comparisonMsg, expected, actual);
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Asserts that two beans are equal, providing a better error message.
     *
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     */
    public static void assertBeanEqualsFullDetail(Bean expected, Bean actual) {
        assertBeanEqualsFullDetail(null, expected, actual, 0d);
    }

    /**
     * Asserts that two beans are equal, providing a better error message.
     *

     * Note that specifying a tolerance can mean that two beans compare as not
     * equal using {@link Object#equals(Object)} but equal using this method,
     * because the standard equals method has no tolerance.
     *
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     * @param tolerance  the tolerance to use for {@code double} and {@code float}
     */
    public static void assertBeanEqualsFullDetail(Bean expected, Bean actual, double tolerance) {
        assertBeanEqualsFullDetail(null, expected, actual, tolerance);
    }

    /**
     * Asserts that two beans are equal, providing a better error message, with
     * an unlimited number of errors reported.
     *
     * @param baseMsg  the message to use in any error, null uses default message
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     */
    public static void assertBeanEqualsFullDetail(String baseMsg, Bean expected, Bean actual) {
        assertBeanEqualsFullDetail(baseMsg, expected, actual, 0d);
    }

    /**
     * Asserts that two beans are equal, providing a better error message, with
     * an unlimited number of errors reported.
     *

     * Note that specifying a tolerance can mean that two beans compare as not
     * equal using {@link Object#equals(Object)} but equal using this method,
     * because the standard equals method has no tolerance.
     *
     * @param baseMsg  the message to use in any error, null uses default message
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     * @param tolerance  the tolerance to use for {@code double} and {@code float}
     */
    public static void assertBeanEqualsFullDetail(String baseMsg, Bean expected, Bean actual, double tolerance) {
        if (expected == null) {
            throw new AssertionError(baseMsg + ": Expected bean must not be null");
        }
        if (actual == null) {
            throw new AssertionError(baseMsg + ": Actual bean must not be null");
        }
        if (expected.equals(actual) == false) {
            String comparisonMsg = buildMessage(baseMsg, Integer.MAX_VALUE, expected, actual, tolerance);
            if (comparisonMsg.isEmpty()) {
                return; // no errors, just double/float within tolerance
            }
            throw new BeanComparisonError(comparisonMsg, expected, actual);
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Compares the two beans.
     *
     * @param baseMsg  the message, may be null
     * @param maxErrors  the maximum number of errors to report
     * @param expected  the expected value, not null
     * @param actual  the actual value, not null
     * @param tolerance  the tolerance to use for {@code double} and {@code float}
     * @return the message, not null
     */
    private static String buildMessage(String baseMsg, int maxErrors, Bean expected, Bean actual, double tolerance) {
        List<String> diffs = new ArrayList<>();
        buildMessage(diffs, "", expected, actual, tolerance);
        if (diffs.size() == 0) {
            return "";
        }
        StringBuilder buf = new StringBuilder();
        buf.append(baseMsg != null ? baseMsg + ": " : "");
        buf.append("Bean did not equal expected. Differences:");
        int size = diffs.size();
        if (size > maxErrors) {
            diffs = diffs.subList(0, maxErrors);
        }
        for (String diff : diffs) {
            buf.append('\n').append(diff);
        }
        if (size > maxErrors) {
            buf.append("\n...and " + (size - 10) + " more differences");
        }
        return buf.toString();
    }

    private static void buildMessage(List<String> diffs, String prefix, Object expected, Object actual, double tolerance) {
        if (expected == null && actual == null) {
            return;
        }
        if (expected == null && actual != null) {
            diffs.add(prefix + ": Expected null, but was " + buildSummary(actual, true));
            return;
        }
        if (expected != null && actual == null) {
            diffs.add(prefix + ": Was null, but expected " + buildSummary(expected, true));
            return;
        }
        if (expected instanceof List && actual instanceof List) {
            List<?> expectedList = (List<?>) expected;
            List<?> actualList = (List<?>) actual;
            if (expectedList.size() != actualList.size()) {
                diffs.add(prefix + ": List size differs, expected " + expectedList.size() + " but was " + actualList.size());
                return;
            }
            for (int i = 0; i < expectedList.size(); i++) {
                buildMessage(diffs, prefix + '[' + i + "]", expectedList.get(i), actualList.get(i), tolerance);
            }
            return;
        }
        if (expected instanceof Map && actual instanceof Map) {
            Map<?, ?> expectedMap = (Map<?, ?>) expected;
            Map<?, ?> actualMap = (Map<?, ?>) actual;
            if (expectedMap.size() != actualMap.size()) {
                diffs.add(prefix + ": Map size differs, expected " + expectedMap.size() + " but was " + actualMap.size());
                return;
            }
            if (expectedMap.keySet().equals(actualMap.keySet()) == false) {
                diffs.add(prefix + ": Map keyset differs, expected " + buildSummary(expectedMap.keySet(), false) + " but was " + buildSummary(actualMap.keySet(), false));
                return;
            }
            for (Object key : expectedMap.keySet()) {
                buildMessage(diffs, prefix + '[' + key + "]", expectedMap.get(key), actualMap.get(key), tolerance);
            }
            return;
        }
        if (expected != null && expected.getClass() != actual.getClass()) {
            diffs.add(prefix + ": Class differs, expected " + buildSummary(expected, true) + " but was " + buildSummary(actual, true));
            return;
        }
        if (expected instanceof Bean) {
            for (MetaProperty<?> prop : ((Bean) expected).metaBean().metaPropertyIterable()) {
                buildMessage(diffs, prefix + '.' + prop.name(), prop.get((Bean) expected), prop.get((Bean) actual), tolerance);
            }
            return;
        }
        if (expected instanceof Double && actual instanceof Double && tolerance != 0d) {
            double e = (Double) expected;
            double a = (Double) actual;
            if (!JodaBeanUtils.equalWithTolerance(e, a, tolerance)) {
                diffs.add(prefix + ": Double values differ by more than allowed tolerance, expected " +
                    buildSummary(expected, true) + " but was " + buildSummary(actual, false));
            }
            return;
        }
        if (expected instanceof double[] && actual instanceof double[] && tolerance != 0d) {
            double[] e = (double[]) expected;
            double[] a = (double[]) actual;
            if (e.length != a.length) {
                diffs.add(prefix + ": Double arrays differ in length, expected " +
                                buildSummary(expected, true) + " but was " + buildSummary(actual, false));
            } else {
                for (int i = 0; i < a.length; i++) {
                    if (!JodaBeanUtils.equalWithTolerance(e[i], a[i], tolerance)) {
                        diffs.add(prefix + ": Double arrays differ by more than allowed tolerance, expected " +
                            buildSummary(expected, true) + " but was " + buildSummary(actual, false));
                        break;
                    }
                }
            }
            return;
        }
        if (expected instanceof Float && actual instanceof Float && tolerance != 0d) {
            float e = (Float) expected;
            float a = (Float) actual;
            if (!JodaBeanUtils.equalWithTolerance(e, a, tolerance)) {
                diffs.add(prefix + ": Float values differ by more than allowed tolerance, expected " +
                    buildSummary(expected, true) + " but was " + buildSummary(actual, false));
            }
            return;
        }
        if (expected instanceof float[] && actual instanceof float[] && tolerance != 0d) {
            float[] e = (float[]) expected;
            float[] a = (float[]) actual;
            if (e.length != a.length) {
                diffs.add(prefix + ": Double arrays differ in length, expected " +
                                buildSummary(expected, true) + " but was " + buildSummary(actual, false));
            } else {
                for (int i = 0; i < a.length; i++) {
                    if (!JodaBeanUtils.equalWithTolerance(e[i], a[i], tolerance)) {
                        diffs.add(prefix + ": Float arrays differ by more than allowed tolerance, expected " +
                            buildSummary(expected, true) + " but was " + buildSummary(actual, false));
                        break;
                    }
                }
            }
            return;
        }
        if (JodaBeanUtils.equal(expected, actual) == false) {
            diffs.add(prefix + ": Content differs, expected " + buildSummary(expected, true) + " but was " + buildSummary(actual, false));
            return;
        }
        return;  // equal
    }

    /**
     * Builds a summary of an object.
     *
     * @param obj  the object to summarise, not null
     */
    private static String buildSummary(Object obj, boolean includeType) {
        String type = obj.getClass().getSimpleName();
        String toStr;
        if (obj instanceof double[]) {
            toStr = Arrays.toString((double[]) obj);
        } else if (obj instanceof float[]) {
            toStr = Arrays.toString((float[]) obj);
        } else {
            toStr = obj.toString();
        }
        if (toStr.length() > 60) {
            toStr = toStr.substring(0, 57) + "...";
        }
        return (includeType ? type + " " : "") + "<" + toStr + ">";
    }

}


text:
var pool = require('../iframe-pool')
var util = require('../util')

var urls, oCrawler, defaultCallback, results, state
var timeout, fetchTimer, runTimer, interval, fetchPromise
var win = window

module.exports = BrowserAdapter

/**
 * Browser crawler constructor. Use Singleton Pattern to keep it simple
 * @param {Array} urls_ - array-like object with a `length` property and a `splice` method
 * @param {Object} oCrawler_ - using this to communicate with the outer crawler. The structure is like this:
 *    {
 *      emitDrain: function(){},
 *      emitProgress: function(result){}, // the result argument is the result of `callback`
 *      on: function(eventName){}, // eventName: 'run' | 'pause'
 *    }
 * @param {Function} callback - the default callback function to handle the fetched result.
 * @param {number} [timeout_] - timeout for requests
 * @param {number} [interval_] - the interval between tasks. Maybe changed in future.
 * @constructor
 */
function BrowserAdapter(urls_, oCrawler_, callback, interval_, timeout_) {
  if (typeof urls_.length != 'number' || !oCrawler_
    || typeof callback != 'function') throw TypeError('arguments error')

  if (BrowserAdapter.instance) {
    reset.apply(BrowserAdapter.instance, arguments)
    return BrowserAdapter.instance
  }
  BrowserAdapter.instance = this

  this.reset = reset
  reset.apply(this, arguments)

  win.addEventListener('message', function(event) {
    var data = event.data
    if (!data ||  !data.bolero) return
    data.win = event.source
    fetchPromise.resRej.resolve(data)
  })
}

// reset variables. If param is not designed, use the old value passed by Ctor
function reset(urls_, oCrawler_, callback, interval_, timeout_) {
  urls = urls_ || urls
  oCrawler = oCrawler_ || oCrawler
  defaultCallback = callback || defaultCallback
  timeout = timeout_ || timeout || 20000
  interval = interval_ || interval ||  1000

  results = []
  state = 'pause'

  oCrawler.on('run', function() {
    state != 'run' && run()
  })
  oCrawler.on('pause', function() {
    state = 'pause'
    if (runTimer) {
      clearTimeout(runTimer)
      runTimer = null
    }
  })
}

function run() {
  if (!urls.length) {
    state = 'pause'
    return oCrawler.emitDrain(results)
  }

  var url = urls.shift(), callback
  if (url && typeof url == 'object') {
    callback = url.callback
    url = url.url
  }
  callback = callback || defaultCallback
  if (typeof url != 'string' || typeof callback != 'function')
    throw TypeError('url format is wrong, url' + url)

  fetch(url, callback)

  state = 'run'
}

function fetch(url, callback) {
  var message = {
    bolero: true,
    url: url
  }
  if (typeof callback.domCallback == 'function'
    || util.isFunctionString(callback.domCallback))
    message.domCallback = callback.domCallback.toString()

  pool.getWindow(url, !!message.domCallback).then(function(win) {
    win = win.win // can't resolve a cross-origin window directly
    win.postMessage(message, '*')

    var resRej
    fetchPromise = new Promise(function(res, rej) {
      fetchTimer = setTimeout(function() {
        pool.free(win)
        rej(Error('timeout:browser-adapter: ' + url))
      }, timeout)
      resRej = {
        resolve: res,
        reject: rej
      }
    })
    fetchPromise.resRej = resRej
    return fetchPromise

  }).then(function(response) {
    clearTimeout(fetchTimer)

    pool.free(response.win)
    delete response.win
    delete response.bolero

    // TODO: allow callback return a Promise?
    var result = {
      url: response.url,
      data: callback(response.html, response),
      timestamp: Date.now()
    }
    results.push(result)
    oCrawler.emitProgress(result)

    if (state == 'run'){
      if (!urls.length) {
        state = 'pause'
        return oCrawler.emitDrain(results)
      }
      runTimer = setTimeout(run, interval)
    }
  }).catch(function(err) {
    console.error(err.stack)
    // TODO:emit error
    oCrawler.emitProgress(err)
  })
}


text:
namespace Petstore.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The custom domain assigned to this storage account. This can be set via
    /// Update.
    /// </summary>
    public partial class CustomDomain
    {
        /// <summary>
        /// Initializes a new instance of the CustomDomain class.
        /// </summary>
        public CustomDomain() { }

        /// <summary>
        /// Initializes a new instance of the CustomDomain class.
        /// </summary>
        /// <param name="name">Gets or sets the custom domain name. Name is the
        /// CNAME source.</param>
        /// <param name="useSubDomain">Indicates whether indirect CName
        /// validation is enabled. Default value is false. This should only be
        /// set on updates</param>
        public CustomDomain(string name, bool? useSubDomain = default(bool?))
        {
            Name = name;
            UseSubDomain = useSubDomain;
        }

        /// <summary>
        /// Gets or sets the custom domain name. Name is the CNAME source.
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets indicates whether indirect CName validation is
        /// enabled. Default value is false. This should only be set on updates
        /// </summary>
        [JsonProperty(PropertyName = "useSubDomain")]
        public bool? UseSubDomain { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Name == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Name");
            }
        }
    }
}


text:
using namespace vnotex;

DeleteConfirmDialog::DeleteConfirmDialog(const QString &p_title,
                                         const QString &p_text,
                                         const QString &p_info,
                                         const QVector<ConfirmItemInfo> &p_items,
                                         DeleteConfirmDialog::Flags p_flags,
                                         bool p_noAskAgainChecked,
                                         QWidget *p_parent)
    : ScrollDialog(p_parent),
      m_items(p_items)
{
    setupUI(p_title, p_text, p_info, p_flags, p_noAskAgainChecked);

    updateItemsList();

    updateCountLabel();
}

void DeleteConfirmDialog::setupUI(const QString &p_title,
                                  const QString &p_text,
                                  const QString &p_info,
                                  DeleteConfirmDialog::Flags p_flags,
                                  bool p_noAskAgainChecked)
{
    auto mainWidget = new QWidget(this);
    setCentralWidget(mainWidget);

    auto mainLayout = new QVBoxLayout(mainWidget);

    // Text.
    if (!p_text.isEmpty()) {
        auto textLabel = new QLabel(p_text, mainWidget);
        textLabel->setWordWrap(true);
        mainLayout->addWidget(textLabel);
    }

    // Info.
    if (!p_info.isEmpty()) {
        auto infoLabel = new QLabel(p_info, mainWidget);
        infoLabel->setWordWrap(true);
        mainLayout->addWidget(infoLabel);
    }

    // Ask again.
    if (p_flags & Flag::AskAgain) {
        m_noAskCB = new QCheckBox(tr("Do not ask again"), mainWidget);
        m_noAskCB->setChecked(p_noAskAgainChecked);
        mainLayout->addWidget(m_noAskCB);
    }

    // Count.
    {
        QHBoxLayout *labelLayout = new QHBoxLayout();

        m_countLabel = new QLabel("Items", mainWidget);

        labelLayout->addWidget(m_countLabel);
        labelLayout->addStretch();
        labelLayout->setContentsMargins(0, 0, 0, 0);

        mainLayout->addLayout(labelLayout);
    }

    // List and preview.
    {
        auto listLayout = new QHBoxLayout();

        m_listWidget = new QListWidget(mainWidget);
        connect(m_listWidget, &QListWidget::currentRowChanged,
                this, &DeleteConfirmDialog::currentFileChanged);
        connect(m_listWidget, &QListWidget::itemActivated,
                this, [this](QListWidgetItem *p_item) {
                    if (!p_item) {
                        return;
                    }

                    auto widget = getItemWidget(p_item);
                    Q_ASSERT(widget);
                    QString filePath = m_items[widget->getData().toInt()].m_path;
                    if (!filePath.isEmpty()) {
                        WidgetUtils::openUrlByDesktop(QUrl::fromLocalFile(filePath));
                    }
                });

        listLayout->addWidget(m_listWidget);

        if (p_flags & Flag::Preview) {
            m_previewer = new QLabel(mainWidget);
            m_previewer->setScaledContents(true);

            m_previewArea = new QScrollArea(mainWidget);
            m_previewArea->setBackgroundRole(QPalette::Dark);
            m_previewArea->setWidget(m_previewer);
            m_previewArea->setMinimumSize(256, 256);

            listLayout->addWidget(m_previewArea);
        }

        mainLayout->addLayout(listLayout);
    }

    setDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

    setWindowTitle(p_title);
}

QVector<ConfirmItemInfo> DeleteConfirmDialog::getConfirmedItems() const
{
    QVector<ConfirmItemInfo> confirmedItems;

    for (int i = 0; i < m_listWidget->count(); ++i) {
        SelectionItemWidget *widget = getItemWidget(m_listWidget->item(i));
        if (widget->isChecked()) {
            confirmedItems.push_back(m_items[widget->getData().toInt()]);
        }
    }

    return confirmedItems;
}

void DeleteConfirmDialog::updateItemsList()
{
    m_listWidget->clear();

    for (int i = 0; i < m_items.size(); ++i) {
        auto itemWidget = new SelectionItemWidget(m_items[i].m_icon, m_items[i].m_name, this);
        itemWidget->setChecked(true);
        itemWidget->setData(i);
        itemWidget->setToolTip(m_items[i].m_tip);
        connect(itemWidget, &SelectionItemWidget::checkStateChanged,
                this, &DeleteConfirmDialog::updateCountLabel);

        QListWidgetItem *item = new QListWidgetItem(m_listWidget);
        QSize size = itemWidget->sizeHint();
        size.setHeight(size.height() * 2);
        item->setSizeHint(size);

        m_listWidget->setItemWidget(item, itemWidget);
    }

    m_listWidget->setMinimumSize(m_listWidget->sizeHint());
    m_listWidget->setCurrentRow(-1);
    m_listWidget->setCurrentRow(0);
}

bool DeleteConfirmDialog::isNoAskChecked() const
{
    return m_noAskCB->isChecked();
}

void DeleteConfirmDialog::currentFileChanged(int p_row)
{
    if (m_previewer) {
        bool succeed = false;
        if (p_row > -1) {
            SelectionItemWidget *widget = getItemWidget(m_listWidget->item(p_row));
            if (widget) {
                int idx = widget->getData().toInt();
                Q_ASSERT(idx < m_items.size());
                QPixmap image(m_items[idx].m_path);
                if (!image.isNull()) {
                    m_previewer->setPixmap(image);
                    m_previewer->adjustSize();
                    succeed = true;
                }
            }
        }

        m_previewArea->setVisible(succeed);
        if (succeed) {
            resizeToHideScrollBarLater(true, true);
        }
    }
}

SelectionItemWidget *DeleteConfirmDialog::getItemWidget(QListWidgetItem *p_item) const
{
    QWidget *wid = m_listWidget->itemWidget(p_item);
    return static_cast<SelectionItemWidget *>(wid);
}

void DeleteConfirmDialog::updateCountLabel()
{
    int total = m_listWidget->count();
    int checked = 0;

    for (int i = 0; i < total; ++i) {
        SelectionItemWidget *widget = getItemWidget(m_listWidget->item(i));
        if (widget->isChecked()) {
            ++checked;
        }
    }

    m_countLabel->setText(tr("%1/%2 Items").arg(checked).arg(total));
}


text:
<!--
  ~ Copyright 2020 Stéphane Baiget
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <com.google.android.material.appbar.AppBarLayout
        style="@style/Widget.MaterialComponents.AppBarLayout.Surface"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
        tools:listitem="@layout/list_item_saved_games"
        />
</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
package com.google.web.bindery.event.shared;

import com.google.web.bindery.event.shared.Event.Type;

/**
 * Dispatches {@link Event}s to interested parties. Eases decoupling by allowing
 * objects to interact without having direct dependencies upon one another, and
 * without requiring event sources to deal with maintaining handler lists. There
 * will typically be one EventBus per application, broadcasting events that may
 * be of general interest.
 *
 * @see SimpleEventBus
 * @see ResettableEventBus
 * @see com.google.web.bindery.event.shared.testing.CountingEventBus
 */
public abstract class EventBus {

  /**
   * Invokes {@code event.dispatch} with {@code handler}.
   *

   * Protected to allow EventBus implementations in different packages to
   * dispatch events even though the {@code event.dispatch} method is protected.
   */
  protected static <H> void dispatchEvent(Event<H> event, H handler) {
    event.dispatch(handler);
  }

  /**
   * Sets {@code source} as the source of {@code event}.
   *

   * Protected to allow EventBus implementations in different packages to set an
   * event source even though the {@code event.setSource} method is protected.
   */
  protected static void setSourceOfEvent(Event<?> event, Object source) {
    event.setSource(source);
  }

  /**
   * Adds an unfiltered handler to receive events of this type from all sources.
   *

   * It is rare to call this method directly. More typically an {@link Event}
   * subclass will provide a static register method, or a widget
   * will accept handlers directly.
   *
   * @param <H> The type of handler
   * @param type the event type associated with this handler
   * @param handler the handler
   * @return the handler registration, can be stored in order to remove the
   *         handler later
   */
  public abstract <H> HandlerRegistration addHandler(Type<H> type, H handler);

  /**
   * Adds a handler to receive events of this type from the given source.
   *

   * It is rare to call this method directly. More typically a {@link Event}
   * subclass will provide a static register method, or a widget
   * will accept handlers directly.
   *
   * @param <H> The type of handler
   * @param type the event type associated with this handler
   * @param source the source associated with this handler
   * @param handler the handler
   * @return the handler registration, can be stored in order to remove the
   *         handler later
   */
  public abstract <H> HandlerRegistration addHandlerToSource(Type<H> type, Object source, H handler);

  /**
   * Fires the event from no source. Only unfiltered handlers will receive it.
   *

   * Any exceptions thrown by handlers will be bundled into a
   * {@link UmbrellaException} and then re-thrown after all handlers have
   * completed. An exception thrown by a handler will not prevent other handlers
   * from executing.
   *
   * @throws UmbrellaException wrapping exceptions thrown by handlers
   *
   * @param event the event to fire
   */
  public abstract void fireEvent(Event<?> event);

  /**
   * Fires the given event to the handlers listening to the event's type.
   *

   * Any exceptions thrown by handlers will be bundled into a
   * {@link UmbrellaException} and then re-thrown after all handlers have
   * completed. An exception thrown by a handler will not prevent other handlers
   * from executing.
   *
   * @throws UmbrellaException wrapping exceptions thrown by handlers
   *
   * @param event the event to fire
   */
  public abstract void fireEventFromSource(Event<?> event, Object source);
}


text:
package com.fanlehai.hadoop.minmaxcount;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.hadoop.io.Writable;
import java.util.Date;

public class MinMaxCountTuple implements Writable {
	private Date min = new Date();
	private Date max = new Date();
	private long count = 0;

	private final static SimpleDateFormat frmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

	public Date getMin() {
		return min;
	}

	public void setMin(Date min) {
		this.min = min;
	}

	public Date getMax() {
		return max;
	}

	public void setMax(Date max) {
		this.max = max;
	}

	public long getCount() {
		return count;
	}

	public void setCount(long count) {
		this.count = count;
	}

	public void readFields(DataInput in) throws IOException {
		min = new Date(in.readLong());
		max = new Date(in.readLong());
		count = in.readLong();
	}

	public void write(DataOutput out) throws IOException {
		out.writeLong(min.getTime());
		out.writeLong(max.getTime());
		out.writeLong(count);
	}

	public String toString() {
		return frmt.format(min) + "\t" + frmt.format(max) + "\t" + count;
	}
}


text:
@interface TubeScene : ZoneScene

@end


text:
package num2words_test

import (
	"fmt"
	"testing"

	"github.com/divan/num2words"
	. "github.com/smartystreets/goconvey/convey"
)

func TestConvert(t *testing.T) {
	Convert := num2words.Convert
	ConvertAnd := num2words.ConvertAnd
	Convey("Should convert correctly", t, func() {
		Convey("Small numbers should convert correctly", func() {
			So(Convert(0), ShouldEqual, "zero")
			So(Convert(1), ShouldEqual, "one")
			So(Convert(5), ShouldEqual, "five")
			So(Convert(10), ShouldEqual, "ten")
			So(Convert(11), ShouldEqual, "eleven")
			So(Convert(12), ShouldEqual, "twelve")
			So(Convert(17), ShouldEqual, "seventeen")
		})
		Convey("Tens should convert correctly", func() {
			So(Convert(20), ShouldEqual, "twenty")
			So(Convert(30), ShouldEqual, "thirty")
			So(Convert(40), ShouldEqual, "forty")
			So(Convert(50), ShouldEqual, "fifty")
			So(Convert(60), ShouldEqual, "sixty")
			So(Convert(90), ShouldEqual, "ninety")
		})
		Convey("Combined numbers should convert correctly", func() {
			So(Convert(21), ShouldEqual, "twenty-one")
			So(Convert(34), ShouldEqual, "thirty-four")
			So(Convert(49), ShouldEqual, "forty-nine")
			So(Convert(53), ShouldEqual, "fifty-three")
			So(Convert(68), ShouldEqual, "sixty-eight")
			So(Convert(99), ShouldEqual, "ninety-nine")
		})
		Convey("Big numbers should convert correctly", func() {
			So(Convert(100), ShouldEqual, "one hundred")
			So(Convert(200), ShouldEqual, "two hundred")
			So(Convert(500), ShouldEqual, "five hundred")
			So(Convert(123), ShouldEqual, "one hundred twenty-three")
			So(Convert(666), ShouldEqual, "six hundred sixty-six")
			So(Convert(1024), ShouldEqual, "one thousand twenty-four")
		})
		Convey("Negative numbers should convert correclty", func() {
			So(Convert(-123), ShouldEqual, "minus one hundred twenty-three")
		})
		Convey("Convert with 'and' should convert correclty", func() {
			So(ConvertAnd(123), ShouldEqual, "one hundred and twenty-three")
			So(ConvertAnd(514), ShouldEqual, "five hundred and fourteen")
			So(ConvertAnd(1111), ShouldEqual, "one thousand one hundred and eleven")
		})
	})
}

func ExampleConvert() {
	fmt.Println(num2words.Convert(11))
	fmt.Println(num2words.Convert(123))
	fmt.Println(num2words.Convert(-99))
	// Output: eleven
	// one hundred twenty-three
	// minus ninety-nine
}

func ExampleConvertAnd() {
	fmt.Println(num2words.ConvertAnd(123))
	fmt.Println(num2words.ConvertAnd(514))
	// Output: one hundred and twenty-three
	// five hundred and fourteen
}


text:
<html>
<applet code="MathsClouds1.java" width="100%" height="100%">
<param name="archive" value="MathsClouds.jar">
<param name="img" value="whitecloud$greycloud$blackcloud$lightning$tick$cross">
<param name="sleep" value="50">
</applet>
</body>
</html>


text:
namespace Test {
namespace HomogeneousPolynomials {

void AddTests3 (Directory &parent)
{
    Directory &dir = parent.GetSubDirectory("HomogeneousPolynomial");

    // the reason all the different combinations are enumerated by hand is
    // so that this source file can be easily broken into several source
    // files, reducing the compilation resources required and allowing
    // parallel compilation.

    // // add_particular_tests_for_scalar<Tenh::Sint8>(dir);
    // // add_particular_tests_for_scalar<Tenh::Sint32>(dir);
    // // add_particular_tests_for_scalar<Tenh::Sint64>(dir);

    // TODO: re-add tests for integral types once integral types are working

    add_particular_tests<complex<double>,1,1>(dir);
    add_particular_tests<complex<double>,1,2>(dir);
    add_particular_tests<complex<double>,1,3>(dir);
    add_particular_tests<complex<double>,2,1>(dir);
    add_particular_tests<complex<double>,2,2>(dir);
    add_particular_tests<complex<double>,2,3>(dir);
    add_particular_tests<complex<double>,3,1>(dir);
    add_particular_tests<complex<double>,3,2>(dir);
    add_particular_tests<complex<double>,3,3>(dir);
}

} // end of namespace Vector
} // end of namespace Test


text:
package me.vilsol.nmswrapper.wraps.unparsed;

import me.vilsol.nmswrapper.*;
import me.vilsol.nmswrapper.reflections.*;
import me.vilsol.nmswrapper.wraps.*;

@ReflectiveClass(name = "PacketStatusOutServerInfo")
public class NMSPacketStatusOutServerInfo extends NMSWrap {

    public NMSPacketStatusOutServerInfo(Object nmsObject){
        super(nmsObject);
    }

    public NMSPacketStatusOutServerInfo(NMSServerPing serverPing){
        super("PacketStatusOutServerInfo", new Object[]{NMSServerPing.class}, new Object[]{serverPing});
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.PacketStatusOutServerInfo#a(net.minecraft.server.v1_9_R1.PacketListener)
     */
    @ReflectiveMethod(name = "a", types = {NMSPacketListener.class})
    public void a(NMSPacketListener packetListener){
        NMSWrapper.getInstance().exec(nmsObject, packetListener);
    }

}


text:
var exports = {};

//////////////
//  Colors  //
//////////////
/**
  Reset = "\x1b[0m"
  Bright = "\x1b[1m"
  Dim = "\x1b[2m"
  Underscore = "\x1b[4m"
  Blink = "\x1b[5m"
  Reverse = "\x1b[7m"
  Hidden = "\x1b[8m"

  FgBlack = "\x1b[30m"
  FgRed = "\x1b[31m"
  FgGreen = "\x1b[32m"
  FgYellow = "\x1b[33m"
  FgBlue = "\x1b[34m"
  FgMagenta = "\x1b[35m"
  FgCyan = "\x1b[36m"
  FgWhite = "\x1b[37m"

  BgBlack = "\x1b[40m"
  BgRed = "\x1b[41m"
  BgGreen = "\x1b[42m"
  BgYellow = "\x1b[43m"
  BgBlue = "\x1b[44m"
  BgMagenta = "\x1b[45m"
  BgCyan = "\x1b[46m"
  BgWhite = "\x1b[47m"
 **/

////////////////
//  Packages  //
////////////////
const pug = require("pug");
const pdf = require("html-pdf");
const Promise = require("promise");
const jsonfile = require("jsonfile");
const _ = require("underscore");
const inquirer = require("inquirer");
const path = require("path");

const settings = require("./settings");
const helpers = require("./helpers");

const template_file = path.normalize(__dirname + "/../templates/template.pug");
const PDF_SETTINGS = {
  format: "letter",
  orientation: "landscape"
};

/**
 * Will run on first use or when use runs "receipt-gen edit"
 * @param {object} settings The current options (if any exist)
 */
const edit_settings = (settings) => {
  var company_question = {
    "type": "input",
    "name": "company_name",
    "message": "Company Name: "
  }
  if (settings.company_name) {
    company_question.default = settings.company_name;
  }

  var phone_question = {
    "type": "input",
    "name": "company_phone",
    "message": "Company Phone Number: "
  }
  if (settings.company_phone) {
    phone_question.default = settings.company_phone;
  }

  var email_question = {
    "type": "input",
    "name": "company_email",
    "message": "Company Email: "
  }
  if (settings.company_email) {
    email_question.default = settings.company_email;
  }

  var dest_question = {
    "type": "input",
    "name": "receipt_destination",
    "message": "Receipt Destination: "
  }
  if (settings.receipt_destination) {
    dest_question.default = settings.receipt_destination;
  }

  return inquirer.prompt([company_question, phone_question, email_question, dest_question])
};

const get_receipt_details = () => {
  const receipient_name_question = {
    "type": "input",
    "name": "receipient_name",
    "message": "Customer Name: "
  };

  const transactions_question = {
    "type": "input",
    "name": "transactions",
    "message": "Please input the transactions in form of `Item1|amount1,Item2|amount2`: "
  };

  var promises = [
    settings.getSettings(),
    inquirer.prompt([receipient_name_question, transactions_question])
  ];
  return Promise.all(promises).then((promise_results) => {
    var settings = promise_results[0];
    const answers = promise_results[1];

    settings.recipient_name = answers.receipient_name;
    settings.transactions = _.reduce(answers.transactions.split(","), (acc, item) => {
      // produces [description, price]
      const components = item.split("|");
      acc.push({
        description: components[0],
        amount: parseInt(components[1])
      });
      return acc;
    }, []);

    return settings;
  }).catch((err) => {
    console.log(err);
    console.log(err.stack);
  });
};

const generate_receipt = (options) => {
  // Create receipt
  const compiler = pug.compileFile(template_file);

  const total = _.reduce(options.transactions, (acc, e) => {
    acc = acc + e.amount;
    return acc;
  }, 0);

  const date = helpers.getDate();

  const template = compiler({
    "company_name": options.company_name,
    "phone": options.company_phone,
    "email": options.company_email,
    "date": date,
    "receipt_number": options.receipt_number,
    "recipient_name": options.recipient_name,
    "transactions": options.transactions,
    "total": total
  });

  if (!options.receipt_destination) {
    options.receipt_destination = "";
  } else if (options.receipt_destination.length > 0 && options.receipt_destination.substr(options.receipt_destination.length-1) !== "/") {
    options.receipt_destination += "/";
  }

  const filename = options.receipt_destination + date + "." + options.receipt_number + ".pdf";

  // Save Receipt
  return new Promise((resolve, reject) => {
    pdf.create(template, PDF_SETTINGS).toFile(filename, (err, res) => {
      if (err) {
        console.error("\x1b[31m", "Error: ", err);
        return reject(err);
      }
      return resolve({
        filename: filename,
        pdf_create: res,
        receipt_number: options.receipt_number
      });
    });
  });
};

/**
 * The main process that is executed to create a receipt.
 */
exports.run = (should_edit) => {
  console.log("\x1b[33m", "Let's get crackin'!");

  //check for the "edit" arg.
  //else print out usage and begin
  settings.getSettings().then((receipt_settings) => {
    if (should_edit) {
      //console.log("\x1b[33m", "Editing your company information...");
      return edit_settings(receipt_settings).then(settings.createSettingsFile).then(() => {
        console.log("\x1b[33m", "All done! Rerun receipt-gen to create a receipt!");
        process.exit(0);
      }).catch((err) => {
        console.log(err);
        console.log(err.stack);
        process.exit(1);
      });
    }

    console.log("\x1b[33m", "If you want to edit your company information, rerun this program with `receipt-gen edit`.");
    //prompt for receipt info: person's name, amount, etc
    get_receipt_details().then((details) => {
      return Promise.all([generate_receipt(details), settings.incrementReceiptNumber()]);
    }).then((receipt_details) => {
      receipt_details = _.first(receipt_details);

      console.log("\x1b[32m", "All Done! Visit your new receipt at ", receipt_details.pdf_create.filename)
      process.exit(0);
    }).catch((err) => {
      console.log(err);
      console.log(err.stack);
      process.exit(1);
    });

  }).catch(() => {
    console.log("\x1b[33m", "Running first time setup...");
    edit_settings({}).then(settings.createSettingsFile).then(() => {
      console.log("\x1b[33m", "All done! Run receipt-gen again to create your first receipt!");
      process.exit(0);
    }).catch((err) => {
      console.error("\x1b[31m", "Error creating settings configuration", err);
      process.exit(1);
    });
  });
};

module.exports = exports;