text:
import contextlib
import copy
import datetime
import functools
import logging
import os
import socket
import threading

from king_phisher import find
from king_phisher import utilities

from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import GtkSource

GObject.type_register(GtkSource.View)

GOBJECT_PROPERTY_MAP = {
	'calendar': None,  # delayed definition
	'checkbutton': 'active',
	'combobox': (
		lambda c, v: c.set_active_iter(gtk_list_store_search(c.get_model(), v)),
		lambda c: c.get_model().get_value(c.get_active_iter() or c.get_model().get_iter_first(), 0)
	),
	'entry': 'text',
	'spinbutton': 'value',
	'switch': 'active',
	'textview': (
		lambda t, v: t.get_buffer().set_text(v),
		lambda t: t.get_buffer().get_text(t.get_buffer().get_start_iter(), t.get_buffer().get_end_iter(), False)
	)
}
"""
The dictionary which maps GObjects to either the names of properties to
store text or a tuple which contains a set and get function. If a tuple
of two functions is specified the set function will be provided two
parameters, the object and the value and the get function will just be
provided the object.
"""

# official python3 work-around per https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
_cmp = lambda i1, i2: (i1 > i2) - (i1 < i2)

def which_glade():
	"""
	Locate the glade data file which stores the UI information in a Gtk Builder
	format.

	:return: The path to the glade data file.
	:rtype: str
	"""
	return find.data_file(os.environ.get('KING_PHISHER_GLADE_FILE', 'king-phisher-client.ui'))

def glib_idle_add_wait(function, *args):
	"""
	Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
	and block until it has completed. This is useful for threads that need
	to update GUI data.

	:param function function: The function to call.
	:param args: The arguments to *function*.
	:return: The result of the function call.
	"""
	gsource_completed = threading.Event()
	results = []
	@functools.wraps(function)
	def wrapper():
		results.append(function(*args))
		gsource_completed.set()
		return False
	GLib.idle_add(wrapper)
	gsource_completed.wait()
	return results.pop()

def gobject_get_value(gobject, gtype=None):
	"""
	Retreive the value of a GObject widget. Only objects with value
	retrieving functions present in the :py:data:`.GOBJECT_PROPERTY_MAP`
	can be processed by this function.

	:param gobject: The object to retrieve the value for.
	:type gobject: :py:class:`GObject.Object`
	:param str gtype: An explicit type to treat *gobject* as.
	:return: The value of *gobject*.
	:rtype: str
	"""
	gtype = (gtype or gobject.__class__.__name__)
	gtype = gtype.lower()
	if isinstance(GOBJECT_PROPERTY_MAP[gtype], (list, tuple)):
		try:
			value = GOBJECT_PROPERTY_MAP[gtype][1](gobject)
		except AttributeError:
			return None
	else:
		value = gobject.get_property(GOBJECT_PROPERTY_MAP[gtype])
	return value

@contextlib.contextmanager
def gobject_signal_blocked(gobject, signal_name):
	"""
	This is a context manager that can be used with the 'with' statement
	to execute a block of code while *signal_name* is blocked.

	:param gobject: The object to block the signal on.
	:type gobject: :py:class:`GObject.Object`
	:param str signal_name: The name of the signal to block.
	"""
	signal_id = GObject.signal_lookup(signal_name, gobject.__class__)
	handler_id = GObject.signal_handler_find(gobject, GObject.SignalMatchType.ID, signal_id, 0, None, 0, 0)
	GObject.signal_handler_block(gobject, handler_id)
	yield
	GObject.signal_handler_unblock(gobject, handler_id)

def gobject_signal_accumulator(test=None):
	"""
	Create an accumulator function for use with GObject signals. All return
	values will be collected and returned in a list. If provided, *test* is a
	callback that will be called with two arguments, the return value from the
	handler and the list of accumulated return values.

	.. code-block:: python

	  stop = test(retval, accumulated)

	:param test: A callback to test whether additional handler should be executed.
	"""
	if test is None:
		test = lambda retval, accumulated: True
	def _accumulator(_, accumulated, retval):
		if accumulated is None:
			accumulated = []
		stop = test(retval, accumulated)
		accumulated.append(retval)
		return (stop, accumulated)
	return _accumulator

def gtk_calendar_get_pydate(calendar):
	"""
	Get the Python date from a :py:class:`Gtk.Calendar` instance.

	:param calendar: The calendar to get the date from.
	:type calendar: :py:class:`Gtk.Calendar`
	:return: The date as returned by the calendar's :py:meth:`~Gtk.Calendar.get_date` method.
	:rtype: :py:class:`datetime.date`
	"""
	if not isinstance(calendar, Gtk.Calendar):
		raise ValueError('calendar must be a Gtk.Calendar instance')
	calendar_day = calendar.get_date()
	return datetime.date(calendar_day[0], calendar_day[1] + 1, calendar_day[2])

def gtk_calendar_set_pydate(calendar, pydate):
	"""
	Set the date on a :py:class:`Gtk.Calendar` instance from a Python
	:py:class:`datetime.date` object.

	:param calendar: The calendar to set the date for.
	:type calendar: :py:class:`Gtk.Calendar`
	:param pydate: The date to set on the calendar.
	:type pydate: :py:class:`datetime.date`
	"""
	calendar.select_month(pydate.month - 1, pydate.year)
	calendar.select_day(pydate.day)

GOBJECT_PROPERTY_MAP['calendar'] = (
	gtk_calendar_set_pydate,
	gtk_calendar_get_pydate
)

def gtk_list_store_search(list_store, value, column=0):
	"""
	Search a :py:class:`Gtk.ListStore` for a value and return a
	:py:class:`Gtk.TreeIter` to the first match.

	:param list_store: The list store to search.
	:type list_store: :py:class:`Gtk.ListStore`
	:param value: The value to search for.
	:param int column: The column in the row to check.
	:return: The row on which the value was found.
	:rtype: :py:class:`Gtk.TreeIter`
	"""
	for row in list_store:
		if row[column] == value:
			return row.iter
	return None

def gtk_menu_get_item_by_label(menu, label):
	"""
	Retrieve a menu item from a menu by it's label. If more than one items share
	the same label, only the first is returned.

	:param menu: The menu to search for the item in.
	:type menu: :py:class:`Gtk.Menu`
	:param str label: The label to search for in *menu*.
	:return: The identified menu item if it could be found, otherwise None is returned.
	:rtype: :py:class:`Gtk.MenuItem`
	"""
	for item in menu:
		if item.get_label() == label:
			return item

def gtk_menu_insert_by_path(menu, menu_path, menu_item):
	"""
	Add a new menu item into the existing menu at the path specified in
	*menu_path*.

	:param menu: The existing menu to add the new item to.
	:type menu: :py:class:`Gtk.Menu` :py:class:`Gtk.MenuBar`
	:param list menu_path: The labels of submenus to traverse to insert the new item.
	:param menu_item: The new menu item to insert.
	:type menu_item: :py:class:`Gtk.MenuItem`
	"""
	utilities.assert_arg_type(menu, (Gtk.Menu, Gtk.MenuBar), 1)
	utilities.assert_arg_type(menu_path, list, 2)
	utilities.assert_arg_type(menu_item, Gtk.MenuItem, 3)
	while len(menu_path):
		label = menu_path.pop(0)
		menu_cursor = gtk_menu_get_item_by_label(menu, label)
		if menu_cursor is None:
			raise ValueError('missing node labeled: ' + label)
		menu = menu_cursor.get_submenu()
	menu.append(menu_item)

def gtk_menu_position(event, *args):
	"""
	Create a menu at the given location for an event. This function is meant to
	be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method.
	The *event* object must be passed in as the first parameter, which can be
	accomplished using :py:func:`functools.partial`.

	:param event: The event to retrieve the coordinates for.
	"""
	if not hasattr(event, 'get_root_coords'):
		raise TypeError('event object has no get_root_coords method')
	coords = event.get_root_coords()
	return (coords[0], coords[1], True)

def gtk_style_context_get_color(sc, color_name, default=None):
	"""
	Look up a color by it's name in the :py:class:`Gtk.StyleContext` specified
	in *sc*, and return it as an :py:class:`Gdk.RGBA` instance if the color is
	defined. If the color is not found, *default* will be returned.

	:param sc: The style context to use.
	:type sc: :py:class:`Gtk.StyleContext`
	:param str color_name: The name of the color to lookup.
	:param default: The default color to return if the specified color was not found.
	:type default: str, :py:class:`Gdk.RGBA`
	:return: The color as an RGBA instance.
	:rtype: :py:class:`Gdk.RGBA`
	"""
	found, color_rgba = sc.lookup_color(color_name)
	if found:
		return color_rgba
	if isinstance(default, str):
		color_rgba = Gdk.RGBA()
		color_rgba.parse(default)
		return color_rgba
	elif isinstance(default, Gdk.RGBA):
		return default
	return

def gtk_sync():
	"""Wait while all pending GTK events are processed."""
	while Gtk.events_pending():
		Gtk.main_iteration()

def gtk_treesortable_sort_func_numeric(model, iter1, iter2, column_id):
	"""
	Sort the model by comparing text numeric values with place holders such as
	1,337. This is meant to be set as a sorting function using
	:py:meth:`Gtk.TreeSortable.set_sort_func`. The user_data parameter must be
	the column id which contains the numeric values to be sorted.

	:param model: The model that is being sorted.
	:type model: :py:class:`Gtk.TreeSortable`
	:param iter1: The iterator of the first item to compare.
	:type iter1: :py:class:`Gtk.TreeIter`
	:param iter2: The iterator of the second item to compare.
	:type iter2: :py:class:`Gtk.TreeIter`
	:param column_id: The ID of the column containing numeric values.
	:return: An integer, -1 if item1 should come before item2, 0 if they are the same and 1 if item1 should come after item2.
	:rtype: int
	"""
	column_id = column_id or 0
	item1 = model.get_value(iter1, column_id).replace(',', '')
	item2 = model.get_value(iter2, column_id).replace(',', '')
	if item1.isdigit() and item2.isdigit():
		return _cmp(int(item1), int(item2))
	if item1.isdigit():
		return -1
	elif item2.isdigit():
		return 1
	item1 = model.get_value(iter1, column_id)
	item2 = model.get_value(iter2, column_id)
	return _cmp(item1, item2)

def gtk_treeview_selection_iterate(treeview):
	"""
	Iterate over the a treeview's selected rows.

	:param treeview: The treeview for which to iterate over.
	:type treeview: :py:class:`Gtk.TreeView`
	:return: The rows which are selected within the treeview.
	:rtype: :py:class:`Gtk.TreeIter`
	"""
	selection = treeview.get_selection()
	(model, tree_paths) = selection.get_selected_rows()
	if not tree_paths:
		return
	for tree_path in tree_paths:
		yield model.get_iter(tree_path)

def gtk_treeview_selection_to_clipboard(treeview, columns=0):
	"""
	Copy the currently selected values from the specified columns in the
	treeview to the users clipboard. If no value is selected in the treeview,
	then the clipboard is left unmodified. If multiple values are selected, they
	will all be placed in the clipboard on separate lines.

	:param treeview: The treeview instance to get the selection from.
	:type treeview: :py:class:`Gtk.TreeView`
	:param column: The column numbers to retrieve the value for.
	:type column: int, list, tuple
	"""
	treeview_selection = treeview.get_selection()
	(model, tree_paths) = treeview_selection.get_selected_rows()
	if not tree_paths:
		return
	if isinstance(columns, int):
		columns = (columns,)
	tree_iters = map(model.get_iter, tree_paths)
	selection_lines = []
	for ti in tree_iters:
		values = (model.get_value(ti, column) for column in columns)
		values = (('' if value is None else str(value)) for value in values)
		selection_lines.append(' '.join(values).strip())
	selection_lines = os.linesep.join(selection_lines)
	clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
	clipboard.set_text(selection_lines, -1)

def gtk_treeview_get_column_titles(treeview):
	"""
	Iterate over a GTK TreeView and return a tuple containing the id and title
	of each of it's columns.

	:param treeview: The treeview instance to retrieve columns from.
	:type treeview: :py:class:`Gtk.TreeView`
	"""
	for column_id, column in enumerate(treeview.get_columns()):
		column_name = column.get_title()
		yield (column_id, column_name)

def gtk_treeview_set_column_titles(treeview, column_titles, column_offset=0, renderers=None):
	"""
	Populate the column names of a GTK TreeView and set their sort IDs.

	:param treeview: The treeview to set column names for.
	:type treeview: :py:class:`Gtk.TreeView`
	:param list column_titles: The names of the columns.
	:param int column_offset: The offset to start setting column names at.
	:param list renderers: A list containing custom renderers to use for each column.
	:return: A dict of all the :py:class:`Gtk.TreeViewColumn` objects keyed by their column id.
	:rtype: dict
	"""
	columns = {}
	for column_id, column_title in enumerate(column_titles, column_offset):
		renderer = renderers[column_id - column_offset] if renderers else Gtk.CellRendererText()
		if isinstance(renderer, Gtk.CellRendererToggle):
			column = Gtk.TreeViewColumn(column_title, renderer, active=column_id)
		else:
			column = Gtk.TreeViewColumn(column_title, renderer, text=column_id)
		column.set_property('reorderable', True)
		column.set_sort_column_id(column_id)
		treeview.append_column(column)
		columns[column_id] = column
	return columns

def gtk_widget_destroy_children(widget):
	"""
	Destroy all GTK child objects of *widget*.

	:param widget: The widget to destroy all the children of.
	:type widget: :py:class:`Gtk.Widget`
	"""
	for child in widget.get_children():
		child.destroy()

def show_dialog(message_type, message, parent, secondary_text=None, message_buttons=Gtk.ButtonsType.OK, use_markup=False, secondary_use_markup=False):
	"""
	Display a dialog and return the response. The response is dependent on
	the value of *message_buttons*.

	:param message_type: The GTK message type to display.
	:type message_type: :py:class:`Gtk.MessageType`
	:param str message: The text to display in the dialog.
	:param parent: The parent window that the dialog should belong to.
	:type parent: :py:class:`Gtk.Window`
	:param str secondary_text: Optional subtext for the dialog.
	:param message_buttons: The buttons to display in the dialog box.
	:type message_buttons: :py:class:`Gtk.ButtonsType`
	:param bool use_markup: Whether or not to treat the message text as markup.
	:param bool secondary_use_markup: Whether or not to treat the secondary text as markup.
	:return: The response of the dialog.
	:rtype: int
	"""
	dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT, message_type, message_buttons)
	dialog.set_property('text', message)
	dialog.set_property('use-markup', use_markup)
	dialog.set_property('secondary-text', secondary_text)
	dialog.set_property('secondary-use-markup', secondary_use_markup)
	if secondary_use_markup:
		signal_label_activate_link = lambda _, uri: utilities.open_uri(uri)
		for label in dialog.get_message_area().get_children():
			if not isinstance(label, Gtk.Label):
				continue
			label.connect('activate-link', signal_label_activate_link)
	dialog.show_all()
	response = dialog.run()
	dialog.destroy()
	return response

def show_dialog_error(*args, **kwargs):
	"""Display an error dialog with :py:func:`.show_dialog`."""
	return show_dialog(Gtk.MessageType.ERROR, *args, **kwargs)

def show_dialog_exc_socket_error(error, parent, title=None):
	"""
	Display an error dialog with details regarding a :py:exc:`socket.error`
	exception that has been raised.

	:param error: The exception instance that has been raised.
	:type error: :py:exc:`socket.error`
	:param parent: The parent window that the dialog should belong to.
	:type parent: :py:class:`Gtk.Window`
	:param title: The title of the error dialog that is displayed.
	"""
	title = title or 'Connection Error'
	if isinstance(error, socket.timeout):
		description = 'The connection to the server timed out.'
	else:
		error_number, error_message = error.args
		if error_number == 111:
			description = 'The server refused the connection.'
		else:
			description = "Socket error #{0} ({1}).".format((error_number or 'N/A'), error_message)
	return show_dialog(Gtk.MessageType.ERROR, title, parent, secondary_text=description)

def show_dialog_info(*args, **kwargs):
	"""Display an informational dialog with :py:func:`.show_dialog`."""
	return show_dialog(Gtk.MessageType.INFO, *args, **kwargs)

def show_dialog_warning(*args, **kwargs):
	"""Display an warning dialog with :py:func:`.show_dialog`."""
	return show_dialog(Gtk.MessageType.WARNING, *args, **kwargs)

def show_dialog_yes_no(*args, **kwargs):
	"""
	Display a dialog which asks a yes or no question with
	:py:func:`.show_dialog`.

	:return: True if the response is Yes.
	:rtype: bool
	"""
	kwargs['message_buttons'] = Gtk.ButtonsType.YES_NO
	return show_dialog(Gtk.MessageType.QUESTION, *args, **kwargs) == Gtk.ResponseType.YES

class GladeDependencies(object):
	"""
	A class for defining how objects should be loaded from a GTK Builder data
	file for use with :py:class:`.GladeGObject`.
	"""
	__slots__ = ('children', 'top_level', 'name')
	def __init__(self, children=None, top_level=None, name=None):
		children = children or ()
		utilities.assert_arg_type(children, tuple, 1)
		self.children = children
		"""A tuple of string names or :py:class:`.GladeProxy` instances listing the children widgets to load from the parent."""
		self.top_level = top_level
		"""A tuple of string names listing additional top level widgets to load such as images."""
		self.name = name
		"""The string of the name of the top level parent widget to load."""

	def __repr__(self):
		return "<{0} name='{1}' >".format(self.__class__.__name__, self.name)

class GladeProxyDestination(object):
	"""
	A class that is used to define how a :py:class:`.GladeProxy` object shall
	be loaded into a parent :py:class:`.GladeGObject` instance. This includes
	the information such as what container widget in the parent the proxied
	widget should be added to and what method should be used. The proxied widget
	will be added to the parent by calling
	:py:attr:`~.GladeProxyDestination.method` with the proxied widget as the
	first argument.
	"""
	__slots__ = ('widget', 'method', 'args', 'kwargs')
	def __init__(self, widget, method, args=None, kwargs=None):
		utilities.assert_arg_type(widget, str, 1)
		utilities.assert_arg_type(method, str, 2)
		self.widget = widget
		"""The name of the parent widget for this proxied child."""
		self.method = method
		"""The method of the parent widget that should be called to add the proxied child."""
		self.args = args or ()
		"""Arguments to append after the proxied child instance when calling :py:attr:`~.GladeProxyDestination.method`."""
		self.kwargs = kwargs or {}
		"""Key word arguments to append after the proxied child instance when calling :py:attr:`~.GladeProxyDestination.method`."""

	def __repr__(self):
		return "<{0} widget='{1}' method='{2}' >".format(self.__class__.__name__, self.widget, self.method)

class GladeProxy(object):
	"""
	A class that can be used to load another top level widget from the GTK
	builder data file in place of a child. This is useful for reusing small
	widgets as children in larger ones.
	"""
	__slots__ = ('destination',)
	name = None
	"""The string of the name of the top level widget to load."""
	children = ()
	"""A tuple of string names or :py:class:`.GladeProxy` instances listing the children widgets to load from the top level."""
	def __init__(self, destination):
		utilities.assert_arg_type(destination, GladeProxyDestination, 1)
		self.destination = destination
		"""A :py:class:`.GladeProxyDestination` instance describing how this proxied widget should be added to the parent."""

	def __repr__(self):
		return "<{0} name='{1}' destination={2} >".format(self.__class__.__name__, self.name, repr(self.destination))

class GladeGObjectMeta(type):
	"""
	A meta class that will update the :py:attr:`.GladeDependencies.name` value
	in the :py:attr:`.GladeGObject.dependencies` attribute of instances if no
	value is defined.
	"""
	assigned_name = type('assigned_name', (str,), {})
	"""A type subclassed from str that is used to define names which have been automatically assigned by this class."""
	def __init__(cls, *args, **kwargs):
		dependencies = getattr(cls, 'dependencies', None)
		if dependencies is not None:
			dependencies = copy.deepcopy(dependencies)
			setattr(cls, 'dependencies', dependencies)
			if isinstance(dependencies.name, (None.__class__, cls.assigned_name)):
				dependencies.name = cls.assigned_name(cls.__name__)
		super(GladeGObjectMeta, cls).__init__(*args, **kwargs)

# stylized metaclass definition to be Python 2.7 and 3.x compatible
class GladeGObject(GladeGObjectMeta('_GladeGObject', (object,), {})):
	"""
	A base object to wrap GTK widgets loaded from Glade data files. This
	provides a number of convenience methods for managing the main widget and
	child widgets. This class is meant to be subclassed by classes representing
	objects from the Glade data file.
	"""
	dependencies = GladeDependencies()
	"""A :py:class:`.GladeDependencies` instance which defines information for loading the widget from the GTK builder data."""
	config_prefix = ''
	"""A prefix to be used for keys when looking up value in the :py:attr:`~.GladeGObject.config`."""
	top_gobject = 'gobject'
	"""The name of the attribute to set a reference of the top level GObject to."""
	objects_persist = True
	"""Whether objects should be automatically loaded from and saved to the configuration."""
	def __init__(self, application):
		"""
		:param application: The parent application for this object.
		:type application: :py:class:`Gtk.Application`
		"""
		utilities.assert_arg_type(application, Gtk.Application, arg_pos=1)
		self.config = application.config
		"""A reference to the King Phisher client configuration."""
		self.application = application
		"""The parent :py:class:`Gtk.Application` instance."""
		self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)

		builder = Gtk.Builder()
		self.gtk_builder = builder
		"""A :py:class:`Gtk.Builder` instance used to load Glade data with."""

		top_level_dependencies = [gobject.name for gobject in self.dependencies.children if isinstance(gobject, GladeProxy)]
		top_level_dependencies.append(self.dependencies.name)
		if self.dependencies.top_level is not None:
			top_level_dependencies.extend(self.dependencies.top_level)
		builder.add_objects_from_file(which_glade(), top_level_dependencies)
		builder.connect_signals(self)
		gobject = builder.get_object(self.dependencies.name)
		setattr(self, self.top_gobject, gobject)
		if isinstance(gobject, Gtk.Window):
			gobject.set_transient_for(self.application.get_active_window())
			self.application.add_reference(self)
			if isinstance(gobject, Gtk.ApplicationWindow):
				application.add_window(gobject)
			if isinstance(gobject, Gtk.Dialog):
				gobject.set_modal(True)

		self.gobjects = utilities.FreezableDict()
		"""A :py:class:`~king_phisher.utilities.FreezableDict` which maps gobjects to their unique GTK Builder id."""
		self._load_child_dependencies(self.dependencies)
		self.gobjects.freeze()
		self._load_child_proxies()

		if self.objects_persist:
			self.objects_load_from_config()

	def _load_child_dependencies(self, dependencies):
		for child in dependencies.children:
			if isinstance(child, GladeProxy):
				self._load_child_dependencies(child)
				child = child.destination.widget

			gobject = self.gtk_builder_get(child, parent_name=dependencies.name)
			# the following five lines ensure that the types match up, this is to enforce clean development
			gtype = child.split('_', 1)[0]
			if gobject is None:
				raise TypeError("gobject {0} could not be found in the glade file".format(child))
			elif gobject.__class__.__name__.lower() != gtype:
				raise TypeError("gobject {0} is of type {1} expected {2}".format(child, gobject.__class__.__name__, gtype))
			self.gobjects[child] = gobject

	def _load_child_proxies(self):
		for child in self.dependencies.children or []:
			if not isinstance(child, GladeProxy):
				continue
			dest = child.destination
			method = getattr(self.gobjects[dest.widget], dest.method)
			if method is None:
				raise ValueError("gobject {0} does not have method {1}".format(dest.widget, dest.method))
			src_widget = self.gtk_builder.get_object(child.name)
			self.logger.debug("setting proxied widget {0} via {1}.{2}".format(child.name, dest.widget, dest.method))
			method(src_widget, *dest.args, **dest.kwargs)

	def destroy(self):
		"""Destroy the top-level GObject."""
		getattr(self, self.top_gobject).destroy()

	@property
	def parent(self):
		return self.application.get_active_window()

	def get_entry_value(self, entry_name):
		"""
		Get the value of the specified entry then remove leading and trailing
		white space and finally determine if the string is empty, in which case
		return None.

		:param str entry_name: The name of the entry to retrieve text from.
		:return: Either the non-empty string or None.
		:rtype: None, str
		"""
		text = self.gobjects['entry_' + entry_name].get_text()
		text = text.strip()
		if not text:
			return None
		return text

	def gtk_builder_get(self, gobject_id, parent_name=None):
		"""
		Find the child GObject with name *gobject_id* from the GTK builder.

		:param str gobject_id: The object name to look for.
		:param str parent_name: The name of the parent object in the builder data file.
		:return: The GObject as found by the GTK builder.
		:rtype: :py:class:`GObject.Object`
		"""
		parent_name = parent_name or self.dependencies.name
		gtkbuilder_id = "{0}.{1}".format(parent_name, gobject_id)
		self.logger.debug('loading GTK builder object with id: ' + gtkbuilder_id)
		return self.gtk_builder.get_object(gtkbuilder_id)

	def objects_load_from_config(self):
		"""
		Iterate through :py:attr:`.gobjects` and set the GObject's value
		from the corresponding value in the :py:attr:`~.GladeGObject.config`.
		"""
		for gobject_id, gobject in self.gobjects.items():
			if not '_' in gobject_id:
				continue
			gtype, config_name = gobject_id.split('_', 1)
			config_name = self.config_prefix + config_name
			if not gtype in GOBJECT_PROPERTY_MAP or not config_name in self.config:
				continue
			value = self.config[config_name]
			if value is None:
				continue
			if isinstance(GOBJECT_PROPERTY_MAP[gtype], (list, tuple)):
				GOBJECT_PROPERTY_MAP[gtype][0](gobject, value)
			else:
				gobject.set_property(GOBJECT_PROPERTY_MAP[gtype], value)

	def objects_save_to_config(self):
		for gobject_id, gobject in self.gobjects.items():
			if not '_' in gobject_id:
				continue
			gtype, config_name = gobject_id.split('_', 1)
			config_name = self.config_prefix + config_name
			if not gtype in GOBJECT_PROPERTY_MAP:
				continue
			self.config[config_name] = gobject_get_value(gobject, gtype)

class FileMonitor(object):
	"""Monitor a file for changes."""
	def __init__(self, path, on_changed):
		"""
		:param str path: The path to monitor for changes.
		:param on_changed: The callback function to be called when changes are detected.
		:type on_changed: function
		"""
		self.logger = logging.getLogger('KingPhisher.Utility.FileMonitor')
		self.on_changed = on_changed
		self.path = path
		self._gfile = Gio.file_new_for_path(path)
		self._gfile_monitor = self._gfile.monitor(Gio.FileMonitorFlags.NONE, None)
		self._gfile_monitor.connect('changed', self.cb_changed)
		self.logger.debug('starting file monitor for: ' + path)

	def __del__(self):
		self.stop()

	def stop(self):
		"""Stop monitoring the file."""
		if self._gfile_monitor.is_cancelled():
			return
		self._gfile_monitor.cancel()
		self.logger.debug('cancelled file monitor for: ' + self.path)

	def cb_changed(self, gfile_monitor, gfile, gfile_other, gfile_monitor_event):
		self.logger.debug("file monitor {0} received event: {1}".format(self.path, gfile_monitor_event.value_name))
		self.on_changed(self.path, gfile_monitor_event)


text:
// Copyright 2022 Google LLC
//
// 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.
package com.google.firebase.perf.util;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.robolectric.Shadows.shadowOf;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnDrawListener;
import androidx.test.core.app.ApplicationProvider;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.LooperMode;

/** Unit tests for {@link FirstDrawDoneListener}. */
@RunWith(RobolectricTestRunner.class)
@LooperMode(LooperMode.Mode.PAUSED)
public class FirstDrawDoneListenerTest {
  private View testView;

  @Before
  public void setUp() {
    testView = new View(ApplicationProvider.getApplicationContext());
  }

  @Test
  @Config(sdk = 25)
  public void registerForNextDraw_delaysAddingListenerForAPIsBelow26()
      throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
    ArrayList<OnDrawListener> mOnDrawListeners =
        initViewTreeObserverWithListener(testView.getViewTreeObserver());
    assertThat(mOnDrawListeners.size()).isEqualTo(0);

    // OnDrawListener is not registered, it is delayed for later
    FirstDrawDoneListener.registerForNextDraw(testView, () -> {});
    assertThat(mOnDrawListeners.size()).isEqualTo(0);

    // Register listener after the view is attached to a window
    List<View.OnAttachStateChangeListener> attachListeners = dispatchAttachedToWindow(testView);
    assertThat(mOnDrawListeners.size()).isEqualTo(1);
    assertThat(mOnDrawListeners.get(0)).isInstanceOf(FirstDrawDoneListener.class);
    assertThat(attachListeners).isEmpty();
  }

  @Test
  @Config(sdk = 26)
  public void registerForNextDraw_directlyAddsListenerForApi26AndAbove()
      throws NoSuchFieldException, IllegalAccessException {
    ArrayList<OnDrawListener> mOnDrawListeners =
        initViewTreeObserverWithListener(testView.getViewTreeObserver());
    assertThat(mOnDrawListeners.size()).isEqualTo(0);

    // Immediately register an OnDrawListener to ViewTreeObserver
    FirstDrawDoneListener.registerForNextDraw(testView, () -> {});
    assertThat(mOnDrawListeners.size()).isEqualTo(1);
    assertThat(mOnDrawListeners.get(0)).isInstanceOf(FirstDrawDoneListener.class);
  }

  @Test
  @Config(sdk = 26)
  public void onDraw_postsCallbackToFrontOfQueue() {
    Handler handler = new Handler(Looper.getMainLooper());
    Runnable drawDoneCallback = mock(Runnable.class);
    Runnable otherCallback = mock(Runnable.class);
    InOrder inOrder = inOrder(drawDoneCallback, otherCallback);

    FirstDrawDoneListener.registerForNextDraw(testView, drawDoneCallback);
    handler.post(otherCallback); // 3rd in queue
    handler.postAtFrontOfQueue(otherCallback); // 2nd in queue
    testView.getViewTreeObserver().dispatchOnDraw(); // 1st in queue
    verify(drawDoneCallback, never()).run();
    verify(otherCallback, never()).run();

    // Execute all posted tasks
    shadowOf(Looper.getMainLooper()).idle();
    inOrder.verify(drawDoneCallback, times(1)).run();
    inOrder.verify(otherCallback, times(2)).run();
    inOrder.verifyNoMoreInteractions();
  }

  @Test
  @Config(sdk = 26)
  public void onDraw_unregistersItself_inLayoutChangeListener()
      throws NoSuchFieldException, IllegalAccessException {
    ArrayList<OnDrawListener> mOnDrawListeners =
        initViewTreeObserverWithListener(testView.getViewTreeObserver());
    FirstDrawDoneListener.registerForNextDraw(testView, () -> {});
    assertThat(mOnDrawListeners.size()).isEqualTo(1);

    // Does not remove OnDrawListener before onDraw, even if OnGlobalLayout is triggered
    testView.getViewTreeObserver().dispatchOnGlobalLayout();
    assertThat(mOnDrawListeners.size()).isEqualTo(1);

    // Removes OnDrawListener in the next OnGlobalLayout after onDraw
    testView.getViewTreeObserver().dispatchOnDraw();
    testView.getViewTreeObserver().dispatchOnGlobalLayout();
    assertThat(mOnDrawListeners.size()).isEqualTo(0);
  }

  /**
   * Returns ViewTreeObserver.mOnDrawListeners field through reflection. Since reflections are
   * employed, prefer to be used in tests with fixed API level using @Config(sdk = X).
   *
   * @param vto ViewTreeObserver instance to initialize and return the mOnDrawListeners from
   */
  private static ArrayList<OnDrawListener> initViewTreeObserverWithListener(ViewTreeObserver vto)
      throws NoSuchFieldException, IllegalAccessException {
    // Adding a listener forces ViewTreeObserver.mOnDrawListeners to be initialized and non-null.
    OnDrawListener placeHolder = () -> {};
    vto.addOnDrawListener(placeHolder);
    vto.removeOnDrawListener(placeHolder);

    // Obtain mOnDrawListeners field through reflection
    Field mOnDrawListeners =
        android.view.ViewTreeObserver.class.getDeclaredField("mOnDrawListeners");
    mOnDrawListeners.setAccessible(true);
    ArrayList<OnDrawListener> listeners = (ArrayList<OnDrawListener>) mOnDrawListeners.get(vto);
    assertThat(listeners).isNotNull();
    assertThat(listeners.size()).isEqualTo(0);
    return listeners;
  }

  /**
   * Simulates {@link View}'s dispatchAttachedToWindow() on API 25 using reflection.
   *
   * <p>This only simulates the part where dispatchAttachedToWindow() notifies the list of {@link
   * View.OnAttachStateChangeListener}.
   *
   * @param view the view in which we are simulating dispatchAttachedToWindow().
   * @return list of {@link View.OnAttachStateChangeListener} from the input {@link View}
   */
  private static List<View.OnAttachStateChangeListener> dispatchAttachedToWindow(View view)
      throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    assert Build.VERSION.SDK_INT == 25;
    Class<?> listenerInfo = Class.forName("android.view.View$ListenerInfo");
    Field mListenerInfo = View.class.getDeclaredField("mListenerInfo");
    mListenerInfo.setAccessible(true);
    Object li = mListenerInfo.get(view);
    assertThat(li).isNotNull();
    Field mOnAttachStateChangeListeners =
        listenerInfo.getDeclaredField("mOnAttachStateChangeListeners");
    mOnAttachStateChangeListeners.setAccessible(true);
    CopyOnWriteArrayList<View.OnAttachStateChangeListener> listeners =
        (CopyOnWriteArrayList<View.OnAttachStateChangeListener>)
            mOnAttachStateChangeListeners.get(li);
    assertThat(listeners).isNotNull();
    assertThat(listeners).isNotEmpty();
    for (View.OnAttachStateChangeListener listener : listeners) {
      listener.onViewAttachedToWindow(view);
    }
    return listeners;
  }
}

redpajama_set_name: RedPajamaGithub


text:
/*!  \file kfbxvector2.h
 */

#ifndef FBXFILESDK_KFBXMATH_KFBXVECTOR2_H
#define FBXFILESDK_KFBXMATH_KFBXVECTOR2_H

/**************************************************************************************

 Copyright (C) 2001 - 2009 Autodesk, Inc. and/or its licensors.
 All Rights Reserved.

 The coded instructions, statements, computer programs, and/or related material
 (collectively the "Data") in these files contain unpublished information
 proprietary to Autodesk, Inc. and/or its licensors, which is protected by
 Canada and United States of America federal copyright law and by international
 treaties.

 The Data may not be disclosed or distributed to third parties, in whole or in
 part, without the prior written consent of Autodesk, Inc. ("Autodesk").

 THE DATA IS PROVIDED "AS IS" AND WITHOUT WARRANTY.
 ALL WARRANTIES ARE EXPRESSLY EXCLUDED AND DISCLAIMED. AUTODESK MAKES NO
 WARRANTY OF ANY KIND WITH RESPECT TO THE DATA, EXPRESS, IMPLIED OR ARISING
 BY CUSTOM OR TRADE USAGE, AND DISCLAIMS ANY IMPLIED WARRANTIES OF TITLE,
 NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR USE.
 WITHOUT LIMITING THE FOREGOING, AUTODESK DOES NOT WARRANT THAT THE OPERATION
 OF THE DATA WILL BE UNINTERRUPTED OR ERROR FREE.

 IN NO EVENT SHALL AUTODESK, ITS AFFILIATES, PARENT COMPANIES, LICENSORS
 OR SUPPLIERS ("AUTODESK GROUP") BE LIABLE FOR ANY LOSSES, DAMAGES OR EXPENSES
 OF ANY KIND (INCLUDING WITHOUT LIMITATION PUNITIVE OR MULTIPLE DAMAGES OR OTHER
 SPECIAL, DIRECT, INDIRECT, EXEMPLARY, INCIDENTAL, LOSS OF PROFITS, REVENUE
 OR DATA, COST OF COVER OR CONSEQUENTIAL LOSSES OR DAMAGES OF ANY KIND),
 HOWEVER CAUSED, AND REGARDLESS OF THE THEORY OF LIABILITY, WHETHER DERIVED
 FROM CONTRACT, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE), OR OTHERWISE,
 ARISING OUT OF OR RELATING TO THE DATA OR ITS USE OR ANY OTHER PERFORMANCE,
 WHETHER OR NOT AUTODESK HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS
 OR DAMAGE.

**************************************************************************************/

#include <fbxfilesdk/components/kbaselib/kaydaradef_h.h>
#include <fbxfilesdk/components/kbaselib/kaydara.h>
#include <fbxfilesdk/components/kbaselib/klib/karrayul.h>

#include <fbxfilesdk/kfbxplugins/kfbxtypes.h>

#include <fbxfilesdk/fbxfilesdk_nsbegin.h>

	/**	FBX SDK 2-elements vector class.
  * \nosubgrouping
  */
	class KFBX_DLL KFbxVector2 : public fbxDouble2
	{

	public:

	/**
	  * \name Constructors and Destructor
	  */
	//@{

	//! Constructor.
	KFbxVector2();

	/** Copy constructor.
	  * \param pVector2 The vector copied to this one.
	  */
	KFbxVector2(const KFbxVector2& pVector2);

	/** Constructor.
	  *	\param pX X component.
	  *	\param pY Y component.
	  */
	KFbxVector2(double pX, double pY);

	//! Destructor.
	~KFbxVector2();

	//@}

	/**
	  * \name Access
	  */
	//@{

	/** Assignment operation.
	  * \param pVector2   The vector assigned to this one.
	  * \return           This vector after assignment.
	  */
	KFbxVector2& operator=(const KFbxVector2& pVector2);

	/** Accessor.
	  * \param pIndex The index of the component to access.
	  * \return The reference to the indexed component.
	  * \remarks          The pIndex parameter is not checked for values out of bounds. The valid values are 0 and 1.
	  */
	double& operator[](int pIndex);

    /** Accessor.
    * \param pIndex The index of the component to access.
    * \return The const reference to the indexed component.
    * \remarks          The pIndex parameter is not checked for values out of bounds. The valid values are 0 and 1.
    */
    const double& operator[](int pIndex) const;

	/** Get a vector element.
	  * \param pIndex The index of the component to access.
	  * \return The value of the indexed component.
	  * \remarks          The pIndex parameter is not checked for values out of bounds. The valid values are 0 and 1.
	  */
	double GetAt(int pIndex) const;

	/** Set a vector element.
      * \param pIndex The index of the component to set.
	  * \param pValue The new value to set the component.
	  * \remarks          The pIndex parameter is not checked for values out of bounds. The valid values are 0 and 1.
	  */
	void SetAt(int pIndex, double pValue);

	/** Set vector.
	  * \param pX The X component value.
  	  * \param pY The Y component value.
	  */
	void Set(double pX, double pY);

	//@}

	/**
	  * \name Scalar Operations
	  */
	//@{

	/** Add a value to all vector components.
	  * \param pValue The value to add to each component of the vector.
	  * \return           A new vector with the result of adding pValue to each component of this vector.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2 operator+(double pValue) const;

	/** Subtract a value from all vector components.
	  * \param pValue The value to subtract from each component of the vector.
	  * \return           A new vector with the result of subtracting pValue from each component of this vector.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2 operator-(double pValue) const;

	/** Multiply a value to all vector components.
	  * \param pValue The value multiplying each component of the vector.
	  * \return           A new vector with the result of multiplying each component of this vector by pValue.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2 operator*(double pValue) const;

	/**	Divide all vector components by a value.
	  * \param pValue The value dividing each component of the vector.
	  * \return           A new vector with the result of dividing each component of this vector by pValue.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2 operator/(double pValue) const;

	/** Add a value to all vector components.
	  * \param pValue The value to add to each component of the vector.
	  * \return           The result of adding pValue to each component of this vector, replacing this vector.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2& operator+=(double pValue);

	/** Subtract a value from all vector components.
	  * \param pValue The value to subtract from each component of the vector.
	  * \return           The result of subtracting pValue from each component of this vector, replacing this vector.
  	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2& operator-=(double pValue);

	/** Multiply a value to all vector elements.
	  * \param pValue The value multiplying each component of the vector.
	  * \return           The result of multiplying each component of this vector by pValue, replacing this vector.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2& operator*=(double pValue);

	/**	Divide all vector elements by a value.
	  * \param pValue The value dividing each component of the vector.
	  * \return           The result of multiplying each component of this vector by pValue, replacing this vector.
	  * \remarks          The pValue parameter is not checked.
	  */
	KFbxVector2& operator/=(double pValue);

	//@}

	/**
	  * \name Vector Operations
	  */
	//@{

	/**	Unary minus operator.
	  * \return The vector that is the negation of \c this.
	  */
	KFbxVector2 operator-() const;

	/** Add two vectors together.
	  * \param pVector Vector to add.
	  * \return            The result of this vector + pVector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2 operator+(const KFbxVector2& pVector) const;

	/** Subtract a vector from another vector.
	  * \param pVector Vector to subtract.
	  * \return            The result of this vector - pVector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2 operator-(const KFbxVector2& pVector) const;

	/** Memberwise multiplication of two vectors.
	  * \param pVector      Multiplying vector.
	  * \return             The result of this vector * pVector.
	  * \remarks            The values in pVector are not checked.
	  */
	KFbxVector2 operator*(const KFbxVector2& pVector) const;

	/** Memberwise division of a vector with another vector.
	  * \param pVector     Dividing vector.
	  * \return            The result of this vector / pVector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2 operator/(const KFbxVector2& pVector) const;

	/** Add two vectors together.
	  * \param pVector Vector to add.
	  * \return            The result of this vector + pVector, replacing this vector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2& operator+=(const KFbxVector2& pVector);

	/** Subtract a vector from another vector.
	  * \param pVector Vector to subtract.
	  * \return            The result of this vector - pVector, replacing this vector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2& operator-=(const KFbxVector2& pVector);

	/** Memberwise multiplication of two vectors.
	  * \param pVector Multiplying vector.
	  * \return            The result of this vector * pVector, replacing this vector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2& operator*=(const KFbxVector2& pVector);

	/** Memberwise division of a vector with another vector.
	  * \param pVector Dividing vector.
	  * \remarks           The values in pVector are not checked.
	  * \return            The result of this vector / pVector, replacing this vector.
	  * \remarks           The values in pVector are not checked.
	  */
	KFbxVector2& operator/=(const KFbxVector2& pVector);

	/** Calculate the dot product of two vectors.
	  * \param pVector The second vector.
	  * \return The dot product value.
      * \remarks          pVector is considered a XYZ vector with fourth weight element, so only the first 3 elements are considered.
	  */
	double DotProduct(const KFbxVector2& pVector) const;

	//@}

	/**
	  * \name Boolean Operations
	  */
	//@{

	/**	Equivalence operator.
	  * \param pVector The vector to be compared to \e this.
	  * \return            \c true if the two vectors are equal (each element is within a 1.0e-6 tolerance), \c false otherwise.
	  */
	bool operator==(const KFbxVector2 & pVector) const;

	/**	Non-equivalence operator.
	  * \param pVector The vector to be compared to \e this.
	  * \return            \c false if the two vectors are equal (each element is within a 1.0e-6 tolerance), \c true otherwise.
	  */
	bool operator!=(const KFbxVector2 & pVector) const;

	//@}

	/**
	  * \name Length
	  */
	//@{

	/** Get the vector's length.
	  * \return The mathematical length of the vector.
	  */
	double Length() const;

	/** Get the vector's length squared.
	  * \return The mathematical square length of the vector.
	  */
	double SquareLength() const;

	/** Find the distance between 2 vectors.
	  * \param pVector The second vector.
	  * \return The mathematical distance between the two vectors.
	  */
	double Distance(const KFbxVector2& pVector) const;

	//! Normalize the vector, length set to 1.
	void Normalize();

	//@}

	/**
	  * \name Casting
	  */
	//@{

	//! Cast the vector in a double pointer.
	operator double* ();

    //! Cast the vector in a const double pointer.
    operator const double* () const;

	//@}

	};

	typedef  class KFBX_DLL KArrayTemplate<KFbxVector2>				KArrayKFbxVector2;

	inline EFbxType FbxTypeOf( KFbxVector2 const &pItem )		{ return eDOUBLE2;	}

#include <fbxfilesdk/fbxfilesdk_nsend.h>

#endif // FBXFILESDK_KFBXMATH_KFBXVECTOR2_H


text:
package ru.javavlad.list;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class UserConvert {

    public HashMap<Integer, User> process(List<User> list) {
        return list.stream().collect(Collectors
                            .toMap(u -> u.getId(), u -> u, (u1, u2) -> u2, HashMap::new));
    }
}


text:
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AzureServiceBusTransport.Specifications
{
    using System.Collections.Generic;
    using GreenPipes;
    using Pipeline;

    public class ServiceBusMessageSchedulerSpecification :
        IPipeSpecification<ConsumeContext>
    {
        public void Apply(IPipeBuilder<ConsumeContext> builder)
        {
            builder.AddFilter(new ServiceBusMessageSchedulerFilter());
        }

        public IEnumerable<ValidationResult> Validate()
        {
            yield break;
        }
    }
}


text:
using Xunit;

namespace System.Xml.Tests
{
    public class ObjectTests
    {
        [Fact]
        public static void ReadContentAsObject1()
        {
            var reader = Utils.CreateFragmentReader("<Root>-005.5</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("-005.5", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject10()
        {
            var reader = Utils.CreateFragmentReader("<Root>9999.9</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("9999.9", reader.ReadContentAs(typeof(object), null));
        }

        [Fact]
        public static void ReadContentAsObject11()
        {
            var reader = Utils.CreateFragmentReader("<Root>44.44</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("44.44", reader.ReadContentAs(typeof(object), null));
        }

        [Fact]
        public static void ReadContentAsObject12()
        {
            var reader = Utils.CreateFragmentReader("<Root>44.55</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("44.55", reader.ReadContentAs(typeof(object), null));
        }

        [Fact]
        public static void ReadContentAsObject2()
        {
            var reader = Utils.CreateFragmentReader("<Root>0001</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("0001", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject3()
        {
            var reader = Utils.CreateFragmentReader("<Root>0</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("0", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject4()
        {
            var reader = Utils.CreateFragmentReader("<Root>9999.9</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("9999.9", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject5()
        {
            var reader = Utils.CreateFragmentReader("<Root>44.44</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("44.44", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject6()
        {
            var reader = Utils.CreateFragmentReader("<Root>44.55</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("44.55", reader.ReadContentAsObject());
        }

        [Fact]
        public static void ReadContentAsObject7()
        {
            var reader = Utils.CreateFragmentReader("<Root>-005.5</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("-005.5", reader.ReadContentAs(typeof(object), null));
        }

        [Fact]
        public static void ReadContentAsObject8()
        {
            var reader = Utils.CreateFragmentReader("<Root>0001</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("0001", reader.ReadContentAs(typeof(object), null));
        }

        [Fact]
        public static void ReadContentAsObject9()
        {
            var reader = Utils.CreateFragmentReader("<Root>0</Root>");
            reader.PositionOnElement("Root");
            reader.Read();
            Assert.Equal("0", reader.ReadContentAs(typeof(object), null));
        }
    }
}


text:
set -eu

function has_change() {
    if git diff --no-ext-diff --quiet --exit-code; then
        return 1 # not changed if the command successed
    else
        return 0 # changed if the command failed
    fi
}

BASEDIR=$(dirname $0)
cd "$BASEDIR"

if has_change; then
    echo "This repository has been changed. Abort."
    exit 1
fi

make composer.phar
./composer.phar update

npx updates -u -m
rm -rf node_modules package-lock.json
npm update

if ! has_change; then
    echo "Not changed."
    exit 0
fi

git checkout -b updates-`date '+%Y%m%d'`
git commit -a -m '[no author] Update dependencies' -S


text:
package sttp.client3.internal

import java.nio.file.Files
import java.nio.file.Path

import scala.io.Source

// wrap a Path
trait SttpFileExtensions { self: SttpFile =>

  def toPath: Path = underlying.asInstanceOf[Path]
  def toFile: java.io.File = toPath.toFile

  def readAsString: String = {
    val s = Source.fromFile(toFile, "UTF-8");
    try s.getLines().mkString("\n")
    finally s.close()
  }

  def readAsByteArray: Array[Byte] = Files.readAllBytes(toPath)
}

trait SttpFileCompanionExtensions {
  def fromPath(path: Path): SttpFile =
    new SttpFile(path) {
      val name: String = path.getFileName.toString
      def size: Long = Files.size(path)
    }
  def fromFile(file: java.io.File): SttpFile = fromPath(file.toPath)
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Security;
using Rxns.DDD.Commanding;
using Rxns.DDD.CQRS;
using Rxns.Health;
using Rxns.Interfaces;
using Rxns.Logging;

namespace Rxns
{
    /// <summary>
    /// A factory class which knows how chain molecules to reactors, estbalishing
    /// a reaction that has begun to listen to input from the outside world, and react.
    /// </summary>
    public class RxnCreator
    {
        private static readonly string[] _allRoutes = new[]
        {
            typeof(IRxnProcessor<>).Name,
            typeof(IDomainCommandHandler<,>).Name,
            typeof(IDomainQueryHandler<,>).Name,
            typeof(IReactTo<>).Name
        };

        public static Type[] DiscoverRoutes(string name, IResolveTypes container)
        {
            var reactorMolecules = container.Resolve<IRxnCfg[]>().Where(c => c.Reactor?.ToLower() == name.ToLower());
            var reactor = container.Resolve<IManageReactors>().GetOrCreate(name);

            return reactorMolecules.SelectMany(r => DiscoverRoutes(r)).Concat(reactor.Reactor.Molecules.SelectMany(r => DiscoverRoutes(r))).Distinct().ToArray();
        }

        public static Type[] DiscoverRoutes(object rxn)
        {
            var types = new List<Type>();

            types.Add(typeof(RxnQuestion));
            //all these types listen for events which seperate the eventstream into what is essentially topics
            //these topics map to routes

            foreach (var route in _allRoutes)
            {
                types.AddRange(rxn.GetType().GetInterfaces().Where(i => i.Name.Equals(route, StringComparison.OrdinalIgnoreCase))
                    .Select(pr => pr.GenericTypeArguments.First()).ToArray());
            }

            return types.ToArray();
        }

        public static IDisposable AttachPublisher<TEvent>(object IRxnPublisher, Type evt, IReactor<TEvent> reactor)
        {
            var p = IRxnPublisher;

            reactor.OnInformation("Configuring publisher '{0}:{1}'", p.GetType().Name, evt.Name);
            try
            {
                p.Invoke("ConfigiurePublishFunc", new object[] { new Action<TEvent>(reactor.Output.OnNext) });
            }
            catch (Exception e)
            {
                reactor.OnError( new Exception("Cannot configure publisher because of: {0}".FormatWith(e.Message)));
                return Disposable.Empty;
            }

            return new DisposableAction(() =>
            {
                var publisher = p;
                publisher.Invoke("ConfigiurePublishFunc", new object[] { new Action<TEvent>(eve => { }) });
            });
        }

        /// <summary>
        /// Attaches a reaction component to a reactor, leaving it ready to use
        /// </summary>
        /// <param name="ireactTo">The component to attach</param>
        /// <param name="evt">The base rxn the reaction should use</param>
        /// <param name="reactor">The reactor to attach the component too</param>
        /// <param name="inputScheduler">The schedule used to sent events to the reaction</param>
        /// <returns>A resource that is used to end the reaction</returns>
        public static IDisposable AttachReaction(object ireactTo, Type evt, IReactor<IRxn> reactor, IScheduler inputScheduler)
        {
            return AttachReactToImpl(ireactTo, evt, reactor, inputScheduler);
        }

        /// <summary>
        /// A default implementation of the AttachReaction method
        /// </summary>
        public static Func<object, Type, IReactor<IRxn>, IScheduler, IDisposable> AttachReactToImpl =
            (processor, evt, reactor, inputScheduler) =>
            {
                IObservable<IRxn> inputStream;
                IDeliveryScheme<IRxn> postman = null;
                var p = processor;

                var inputConfigInterface = typeof(IRxnCfg);
                var inputStreamType = typeof(IObservable<>).MakeGenericType(typeof(IRxn));

                if (p.ImplementsInterface(inputConfigInterface))
                {
                    reactor.OnVerbose("Found configuration interface'");
                    //configure input stream
                    inputStream = reactor.Input.Where(e => e.GetType().IsAssignableTo(evt));

                    var method = inputConfigInterface.GetMethod("ConfigureInput", new Type[] { inputStreamType });
                    inputStream = method.Invoke(p, new[] { inputStream }) as IObservable<IRxn>;

                    postman = p.GetProperty("InputDeliveryScheme") as IDeliveryScheme<IRxn>;
                }
                else
                {
                    inputStream = reactor.Input.Where(e => e.GetType().IsAssignableTo(evt));
                }

                if (inputScheduler != null) inputStream = inputStream.ObserveOn(inputScheduler);

                reactor.OnInformation("Establishing reaction for: {0}:{1}", p.GetType().Name, evt.Name);
                var input = processor.GetProperty("Input") as ISubject<IRxn>;
                var output = processor.GetProperty("Output") as ISubject<IRxn>;

                var inputResource = Disposable.Empty;
                var outputResource = Disposable.Empty;
                //verify null before connecting channels as null is ok in my books.
                if (input != null)
                    inputResource = postman != null
                        ? inputStream.Subscribe(e => postman.Deliver(e, t => input.OnNext(t)), reactor.OnError)
                        : inputStream.Subscribe(e => input.OnNext(e), reactor.OnError);

                if (output != null)
                    outputResource = output.Subscribe((processor as IReportStatus ?? reactor), e => reactor.Output.OnNext(e), (evnt, e) => OnError((processor as IReportStatus ?? reactor), processor, evnt, e));

                return new CompositeDisposable(inputResource, outputResource);
            };

        /// <summary>
        /// Attaches a processing component (IrxnProcessor) to a reactor, leaving it ready to use
        /// </summary>
        /// <param name="irxnProcessor">The component to attach</param>
        /// <param name="processorTypeCanBeNull">The base type used for reaction pipeline. Null defaults to the IRxn</param>
        /// <param name="reactor">The reactor to attach to</param>
        /// <param name="inputScheduler">The sheduler used for the Process method</param>
        /// <returns>A resource which ends the reaction</returns>
        public static IDisposable AttachProcessor(object irxnProcessor, Type processorTypeCanBeNull, IReactor<IRxn> reactor, IScheduler inputScheduler)
        {
            return StartProcessorImpl(irxnProcessor, processorTypeCanBeNull, reactor, inputScheduler);
        }

        /// <summary>
        /// A default implementation of the AttachProcessor method
        /// </summary>
        public static Func<object, Type, IReactor<IRxn>, IScheduler, IDisposable> StartProcessorImpl =
            (processor, processorType, reactor, inputScheduler) =>
            {

                IObservable<IRxn> inputStream = reactor.Input;
                var shouldMonitorHealth = false;
                string processorName = null;

                if (processorType != null && !processorType.IsAssignableTo<IRxn>()) throw new NotSupportedException("{0} must implement IRxn to be used with an rxnProcessor");

                var inputConfigInterface = typeof(IRxnCfg);
                var eventObs = typeof(IObservable<>).MakeGenericType(typeof(IRxn));
                IDeliveryScheme<IRxn> postman = null;

                //we try and gather all the interface here so we can efficently branch to our
                //process methods
                if (processorType == null)
                {
                    var interfaceName = typeof(IRxnProcessor<>).Name;
                    var allProcessors = processor.GetType().GetInterfaces().Where(i => i.Name.Equals(interfaceName));
                    var allProcessorTypes = allProcessors.Select(pr => pr.GenericTypeArguments.First()).ToArray();

                    reactor.Handles(allProcessorTypes);

                    if (!allProcessorTypes.AnyItems()) throw new NotSupportedException("processors must implement IRxnProcess<T :IRxn> to be connected with this method");

                    inputStream = inputStream.Where(e => allProcessorTypes.Any(evnt => e.GetType().IsAssignableTo(evnt)));

                    if (allProcessorTypes.Length > 1)
                        reactor.OnVerbose("Combining '{0}' interfaces into a single pipeline", allProcessorTypes.Length);
                    else if (allProcessorTypes.Length == 1)
                        reactor.OnVerbose("Creating single pipeline for IRxnProcessor<{0}>", allProcessorTypes.First().Name);
                }
                else
                {
                    if (processor.GetType().GetMethod("Process", new[] { processorType }) == null) throw new NotSupportedException("processors must implement IRxnProcess<{0}> to be connected with this method".FormatWith(processorType));

                    inputStream = reactor.Input.Where(e => e.GetType().IsAssignableTo(processorType));
                    reactor.OnVerbose("Creating single pipeline for IrxnProcessor<{0}>", processorType.Name);
                }

                var cfg = processor as IRxnCfg;

                if (cfg != null)
                {

                    reactor.OnVerbose("Found configuration interface");

                    inputStream = cfg.ConfigureInput(inputStream);
                    postman = cfg.InputDeliveryScheme;
                    shouldMonitorHealth = cfg.MonitorHealth;

                    var healthReporter = processor as IReportHealth;
                    if (healthReporter != null) processorName = healthReporter.ReporterName;
                }

                if (processorName.IsNullOrWhitespace()) processorName = processor.GetType().Name;

                Func<IRxn, IObservable<IRxn>> doDelivery;
                if (postman != null)
                    doDelivery = evnt => postman.Deliver(evnt, e => processor.Invoke("Process", new object[] { e }) as IObservable<IRxn>);
                else
                    doDelivery = e => processor.Invoke("Process", new object[] { e }) as IObservable<IRxn>; //p.Invoke("Process", new object[] {e}) as IObservable<IRxn>;

                //todo: make integration neater
                if (true)
                {
                    var health = HealthMonitor.ForQueue<IRxn>(reactor, processorName);
                    inputStream = inputStream.Monitor(health.Select(h => h.Before()).ToArray());

                    //now hook everything up
                    if (inputScheduler != null) inputStream = inputStream.ObserveOn(inputScheduler);

                    return inputStream.Subscribe(processor as IReportStatus ?? reactor, evnt =>
                    {
                        try
                        {
                            var result = doDelivery(evnt);

                            //publish all events that resulted from the processing

                            if (result != null)
                                result
                                    .MonitorR(health.Select(h => h.After()).ToArray())
                                    .Subscribe(reactor.Output.OnNext, error => OnError((processor as IReportStatus ?? reactor), processor, evnt, error));
                        }
                        catch (Exception e)
                        {
                            foreach (var trg in health.Select(h => h.After()).ToArray())
                                if (trg.When(evnt)) trg.Do(evnt);

                            OnError((processor as IReportStatus ?? reactor), processor, evnt, e);
                        }
                    });
                }
                else
                {
                    //now hook everything up
                    if (inputScheduler != null) inputStream = inputStream.ObserveOn(inputScheduler);

                    return inputStream.Subscribe(processor as IReportStatus ?? reactor, evnt =>
                    {
                        var result = doDelivery(evnt);

                        //publish all events that resulted from the processing
                        if (result != null)
                            result.Subscribe(reactor.Output.OnNext, error => OnError((processor as IReportStatus ?? reactor), processor, evnt, error));
                    });
                }
            };

        public static IObservable<IRxn> MonitorHealth<T>(IReportHealth doctor, string processorName,out Func<IEnumerable<IMonitorAction<IRxn>>> before, Func<IObservable<IRxn>> doDelivery)
        {
            var health = HealthMonitor.ForQueue<IRxn>(doctor, processorName);
            before = () => health.Select(h => h.Before());

            //let them hook it up
            //if (inputScheduler != null) inputStream = inputStream.ObserveOn(inputScheduler);

            //return inputStream.Subscribe(processor as IReportStatus ?? reactor, evnt =>
            //{
            try
            {
                var result = doDelivery();

                //publish all events that resulted from the processing

                if (result != null)
                    return result
                        .MonitorR(health.Select(h => h.After()).ToArray());

            }
            catch (Exception e)
            {

                OnError(ReportStatus.Log, doctor, null, e);
            }
            //});
            return Rxn.Empty();

        }

        /// <summary>
        /// Called each time an error occours during a reaction. Override this static method if you wish to override the default behaviour
        /// of OnErroring the reactor or the processor (if it supports IReportStatus)
        /// </summary>
        public static Action<IReportStatus, object, IRxn, Exception> OnError = (reporter, impl, evnt, error) =>
        {
            reporter.OnError(new ReactionException(error, "[{0}] On {1}{2} -> {3}", impl.GetType().Name, evnt.GetType().Name, PrettyPrint(evnt), error.Message));
        };

        private static object PrettyPrint(IRxn obj)
        {
            return obj.GetType().GetProperties().Select(p => "{0}:{1}".FormatWith(p.Name, p.CanRead ? p.GetValue(obj) : "(na)")).ToStringEach();
        }

        /// <summary>
        /// A class is able to specificy what reactor it should be hooked up to by defining the IRxnCfg class. If none is specified
        /// the default reactor is provided.
        /// </summary>
        /// <param name="processorPublisherReaction">The class to query for a reaction config</param>
        /// <param name="getReactorByName">The factory function that know hows to get a reactor by its name</param>
        /// <returns>The reactor as specified by the class</returns>
        public static IReactor<IRxn> GetReactorFor(object processorPublisherReaction, Func<string, IReactor<IRxn>> getReactorByName)
        {
            var inputConfigInterface = typeof(IRxnCfg);

            if (processorPublisherReaction.ImplementsInterface(inputConfigInterface))
            {
                var name = processorPublisherReaction.GetProperty("Reactor") as string ?? ReactorManager.DefaultReactorName;
                return getReactorByName(name);
            }

            return getReactorByName(ReactorManager.DefaultReactorName);
        }

        public static bool? IsIsolatedProcess(IRxnFilterCfg cfg, string reactorName)
        {
            if (reactorName == ReactorManager.DefaultReactorName) return null;
            if (!cfg.IsolateReactors.AnyItems()) return null;

            return cfg.IsolateReactors.Contains(reactorName, new CaseInsensitveEqualityComparer());
        }
        public static Func<string, RxnMode, IResolveTypes, IReactor<IRxn>> getReactorByName = (reactorName, cfg, con) => con.Resolve<IManageReactors>().StartReactor(reactorName, cfg).Reactor;

        public static IDisposable StartRxnPublishers(IReportStatus logger, IResolveTypes container, Type[] events)
        {
            var startedProcessors = new List<dynamic>();
            var resources = new CompositeDisposable();
            var cfg = container.Resolve<IRxnFilterCfg>();

            foreach (var @event in events.EmptyIfNull())
            {
                try
                {
                    //now we create an rxnProcessor of each IRxn discovered, then ask the container
                    //for any interfaces which implement them.
                    var processorForEvent = typeof(IRxnPublisher<>).MakeGenericType(@event);
                    var allProcessorsForEventType = typeof(IEnumerable<>).MakeGenericType(processorForEvent);
                    var allProcessors = (IEnumerable<dynamic>)container.Resolve(allProcessorsForEventType);

                    var distinctProcessors = allProcessors.Distinct().ToArray();
                    //now register any processors found with the subscription to the events they are interested in
                    foreach (var publisher in distinctProcessors)
                    {
                        var pcfg = publisher as IRxnCfg;

                        var mode = pcfg?.Mode ?? RxnMode.InProcess;
                        var reactor = RxnCreator.GetReactorFor(publisher as object, name => getReactorByName(name, mode, container));

                        var isOutOfProcess = mode == RxnMode.OutOfProcess;
                        var outOfProcessReactor = pcfg?.Reactor;

                        var isolationState = IsIsolatedProcess(cfg, reactor.Name);
                        if (isolationState == null)
                        {
                            //normal
                        }
                        else if (!isolationState.Value)
                        {
                            logger.OnVerbose($"Bypassing '{publisher.GetType().Name}' due to isolation mode being active {cfg.IsolateReactors.ToStringEach()}");
                            return Disposable.Empty;
                        }

                        if (isOutOfProcess && outOfProcessReactor.IsNullOrWhitespace())
                        {
                            throw new Exception("Cant out of process on default reactor");
                        }
                        else if (isOutOfProcess)
                        {

                            IDisposableExtensions.DisposedBy(reactor.Connect(publisher), resources);

                            var startupReactor = getReactorByName(pcfg.Reactor, RxnMode.OutOfProcess, container);
                            return Disposable.Empty;
                        }

                        IDisposableExtensions.DisposedBy(reactor.Connect(publisher), resources);
                    }
                    startedProcessors.AddRange(distinctProcessors); //so we need to keep a list processors we see so we dont attach them twice

                }
                catch (Exception e)
                {
                    logger.OnError(e);
                }
            }

            return resources;
        }

        public static IDisposable StartReactions(IReportStatus logger, IResolveTypes container, Type[] events, IScheduler eventDelivery)
        {
            var reactors = new CompositeDisposable();
            var cfg = container.Resolve<IRxnFilterCfg>();

            foreach (var @event in events.EmptyIfNull())
            {
                try
                {
                    var processorForEvent = typeof(IReactTo<>).MakeGenericType(@event);
                    var allProcessorsForEventType = typeof(IEnumerable<>).MakeGenericType(processorForEvent);
                    var allProcessors = (IEnumerable<dynamic>)container.Resolve(allProcessorsForEventType);

                    //now attach any processors found with the subscription to the events they are interested in
                    foreach (object reaction in allProcessors.Distinct())
                    {
                        var pcfg = reaction as IRxnCfg;

                        var mode = pcfg?.Mode ?? RxnMode.InProcess;
                        var isOutOfProcess = mode == RxnMode.OutOfProcess;
                        var outOfProcessReactor = pcfg?.Reactor;

                        var reactor = RxnCreator.GetReactorFor(reaction, name => getReactorByName(name, mode, container));

                        var isolationState = IsIsolatedProcess(cfg, reactor.Name);
                        if (isolationState == null)
                        {
                            //normal
                        }
                        else if (!isolationState.Value)
                        {
                            logger.OnVerbose($"Bypassing '{reaction.GetType().Name}' due to isolation mode being active {cfg.IsolateReactors.ToStringEach()}");
                            return Disposable.Empty;
                        }

                        if (isOutOfProcess && outOfProcessReactor.IsNullOrWhitespace())
                        {
                            throw new Exception("Cant out of process on default reactor");
                        }
                        else if (isOutOfProcess)
                        {
                            reactor.Handles(reaction.GetType().GenericTypeArguments.First());

                            return getReactorByName(outOfProcessReactor, RxnMode.OutOfProcess, container);
                        }

                        IDisposableExtensions.DisposedBy(reactor.Connect((IReactTo<IRxn>)reaction, eventDelivery), reactors);

                        reactors.Add(reactor);
                    }
                }
                catch (Exception e)
                {
                    logger.OnError(e);
                }
            }

            return reactors;
        }

        public static IDisposable StartRxnProcessors(IReportStatus logger, IResolveTypes container, Type[] events, IScheduler eventDelivery)
        {
            var startedProcessors = new List<dynamic>();
            var resources = new CompositeDisposable();
            var cfg = container.Resolve<IRxnFilterCfg>();

            foreach (var @event in events.EmptyIfNull().Concat(new[] { typeof(IDomainCommand), typeof(IDomainQuery) }))
            {
                try
                {
                    //now we create an rxnProcessor of each IRxn discovered, then ask the container
                    //for any interfaces which implement them.
                    var processorForEvent = typeof(IRxnProcessor<>).MakeGenericType(@event);
                    var allProcessorsForEventType = typeof(IEnumerable<>).MakeGenericType(processorForEvent);
                    var allProcessors = ((IEnumerable<dynamic>)container.Resolve(allProcessorsForEventType)).ToArray();

                    //now register any processors found with the subscription to the events they are interested in
                    var distinctProcessors = allProcessors.Distinct().ToArray();
                    foreach (var p in distinctProcessors.Except(startedProcessors))
                    {
                        var pcfg = p as IRxnCfg;
                        var outOfProcessReactor = pcfg?.Reactor;

                        var reactor = RxnCreator.GetReactorFor((object)p, name => getReactorByName(name, pcfg?.Mode ?? RxnMode.InProcess, container));

                        var isolationState = IsIsolatedProcess(cfg, reactor.Name);
                        var isOutOfProcess = (pcfg?.Mode == RxnMode.OutOfProcess) && (isolationState.HasValue && !isolationState.Value);

                        if (isolationState == null)
                        {
                            //normal
                        }
                        else if (!isolationState.Value)
                        {
                            logger.OnVerbose($"Bypassing '{p.GetType().Name}' due to isolation mode being active {cfg.IsolateReactors.ToStringEach()}");

                            return Disposable.Empty;
                        }

                        if (isOutOfProcess && outOfProcessReactor.IsNullOrWhitespace())
                        {
                            throw new Exception("Cant out of process on default reactor");
                        }
                        else if (isOutOfProcess)
                        {
                            var startupReactor = getReactorByName(pcfg?.Reactor, RxnMode.OutOfProcess, container);
                            return Disposable.Empty;
                        }

                        logger.OnInformation($"Connecting {reactor.Name}");

                        //this method will hookup ALL process methods of a processor in one call
                        IDisposableExtensions.DisposedBy(reactor.Connect((object)p, eventDelivery), resources);

                    }

                    startedProcessors.AddRange(distinctProcessors); //so we need to keep a list processors we see so we dont attach them twice
                }
                catch (Exception e)
                {
                    logger.OnError(e);
                }
            }

            return resources;
        }

    }
}


text:
namespace kengine {
    struct SFMLWindowComponent {
        sf::RenderWindow window;
    };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Config_GetCapabilities.xml -->
<items>

  <!-- acceptVersions -->
  <item shouldPass="false" owsLocator="acceptVersions" owsCode="InvalidParameterValue">
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptVersions=]]></url>
  </item>
  <item shouldPass="false" owsLocator="acceptVersions" owsCode="VersionNegotiationFailed">
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptVersions=a,b]]></url>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="2.0.2" src="serviceProperties.serviceVersion"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptVersions=a,2.0.2]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptVersions=a,2.0.2&version=bad]]></url>
  </item>
  <item shouldPass="false" owsLocator="ows:AcceptVersions/ows:Version" owsCode="InvalidParameterValue">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptVersions><ows:Version></ows:Version></ows:AcceptVersions>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="false" owsLocator="ows:AcceptVersions/ows:Version" owsCode="VersionNegotiationFailed">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptVersions>
          <ows:Version>1</ows:Version><ows:Version>2</ows:Version>
        </ows:AcceptVersions>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="2.0.2" src="serviceProperties.serviceVersion"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptVersions>
          <ows:Version>1</ows:Version><ows:Version>2.0.2</ows:Version>
        </ows:AcceptVersions>
      </csw:GetCapabilities>
    ]]></xml>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW" version="bad">
        <ows:AcceptVersions>
          <ows:Version>1</ows:Version><ows:Version>2.0.2</ows:Version>
        </ows:AcceptVersions>
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- acceptFormats -->
  <item shouldPass="false" owsLocator="acceptFormats" owsCode="InvalidParameterValue">
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=]]></url>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="application/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=application/xml]]></url>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="text/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=a,text/xml]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=text/xml&outputFormat=bad]]></url>
  </item>
  <item shouldPass="false" owsLocator="ows:AcceptFormats/ows:OutputFormat" owsCode="InvalidParameterValue">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats><ows:OutputFormat></ows:OutputFormat></ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="application/xml" src="operationResponse.outputFormat"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats><ows:OutputFormat>application/xml</ows:OutputFormat></ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="text/xml" src="operationResponse.outputFormat"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW" outputFormat="bad">
        <ows:AcceptFormats>
          <ows:OutputFormat>1</ows:OutputFormat><ows:OutputFormat>text/xml</ows:OutputFormat>
        </ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceIdentification"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=a,b]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats>
          <ows:OutputFormat>1</ows:OutputFormat><ows:OutputFormat>2</ows:OutputFormat>
        </ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- acceptFormats
  <item shouldPass="false" owsLocator="acceptFormats" owsCode="InvalidParameterValue">
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=a,b]]></url>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="application/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=application/xml]]></url>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="text/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=a,text/xml]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&acceptFormats=text/xml&outputFormat=bad]]></url>
  </item>
  <item shouldPass="false" owsLocator="ows:AcceptFormats/ows:OutputFormat" owsCode="InvalidParameterValue">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats><ows:OutputFormat></ows:OutputFormat></ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats>
          <ows:OutputFormat>1</ows:OutputFormat><ows:OutputFormat>2</ows:OutputFormat>
        </ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="application/xml" src="operationResponse.outputFormat"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:AcceptFormats><ows:OutputFormat>application/xml</ows:OutputFormat></ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="text/xml" src="operationResponse.outputFormat"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW" outputFormat="bad">
        <ows:AcceptFormats>
          <ows:OutputFormat>1</ows:OutputFormat><ows:OutputFormat>text/xml</ows:OutputFormat>
        </ows:AcceptFormats>
      </csw:GetCapabilities>
    ]]></xml>
  </item> -->

  <!-- outputFormat -->
  <item shouldPass="false" owsLocator="outputFormat" owsCode="InvalidParameterValue">
    <url><![CDATA[service=CSW&request=GetCapabilities&outputFormat=]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&Outputformat=a]]></url>
  </item>
  <item shouldPass="false" owsLocator="@outputFormat" owsCode="InvalidParameterValue">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        service="CSW" outputFormat="">
      </csw:GetCapabilities>
    ]]></xml>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        service="CSW" outputFormat="a">
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="application/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&outputFormat=application/xml]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        service="CSW" version = "2.0.2" outputFormat="application/xml">
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertEquals" expected="text/xml" src="operationResponse.outputFormat"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&outputFormat=text/xml]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        service="CSW" version = "2.0.2" outputFormat="text/xml">
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- invalid sections -->
  <item shouldPass="false" owsLocator="sections" owsCode="InvalidParameterValue">
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=123]]></url>
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=123,456]]></url>
  </item>
  <item shouldPass="false" owsLocator="ows:Sections/ows:Section" owsCode="InvalidParameterValue">
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:Sections>
          <ows:Section>ServiceProvider</ows:Section><ows:Section>xyz</ows:Section>
        </ows:Sections>
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- validate responses (ogc:Filter_Capabilities is not optional) -->
  <item shouldPass="true">
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceIdentification"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceProvider"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:OperationsMetadata"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ogc:Filter_Capabilities"/>
    <url><![CDATA[service=CSW&request=GetCapabilities]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceIdentification"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceProvider"/>
    <assertion type="assertNull"    src="xpath-node:/csw:Capabilities/ows:OperationsMetadata"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ogc:Filter_Capabilities"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=ServiceIdentification,ServiceProvider]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:Sections>
          <ows:Section>ServiceIdentification</ows:Section><ows:Section>ServiceProvider</ows:Section>
        </ows:Sections>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertNull"    src="xpath-node:/csw:Capabilities/ows:ServiceIdentification"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceProvider"/>
    <assertion type="assertNull"    src="xpath-node:/csw:Capabilities/ows:OperationsMetadata"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ogc:Filter_Capabilities"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=ServiceProvider]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:Sections><ows:Section>ServiceProvider</ows:Section></ows:Sections>
      </csw:GetCapabilities>
    ]]></xml>
  </item>
  <item shouldPass="true">
    <assertion type="assertNull"    src="xpath-node:/csw:Capabilities/ows:ServiceIdentification"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:ServiceProvider"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ows:OperationsMetadata"/>
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ogc:Filter_Capabilities"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=ServiceProvider&sections=OperationsMetadata]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:Sections>
          <ows:Section>ServiceProvider</ows:Section><ows:Section>OperationsMetadata</ows:Section>
        </ows:Sections>
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- validate one of the HTTP endpoints within the response -->
  <item shouldPass="true">
    <assertion type="assertEquals" expected="/geoportal/csw"
      src="xpath-string:/csw:Capabilities/ows:OperationsMetadata/ows:Operation[@name='GetCapabilities']/ows:DCP/ows:HTTP/ows:Get/@xlink:href"/>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
      </csw:GetCapabilities>
    ]]></xml>
  </item>

  <!-- empty sections parameter should return all non-optional sections -->
  <item shouldPass="true">
    <assertion type="assertNotNull" src="xpath-node:/csw:Capabilities/ogc:Filter_Capabilities"/>
    <assertion type="assertEquals" expected="1.0" src="xpath-number:count(/csw:Capabilities/*)"/>
    <url><![CDATA[service=CSW&request=GetCapabilities&sections=]]></url>
    <xml><![CDATA[
      <?xml version="1.0" encoding="UTF-8"?>
      <csw:GetCapabilities xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
        xmlns:ows="http://www.opengis.net/ows" service="CSW">
        <ows:Sections>
        </ows:Sections>
      </csw:GetCapabilities>
    ]]></xml>
  </item>

</items>


text:
volatile int sink;
int main(int argc, char **argv) {
  int shift = argc * 32;
#if GOOD_SHIFT
  shift = 3;
#endif
  if ((argc << shift) == 16)  // False.
    return 1;
  return 0;
}

// CHECK_WARN: shift exponent 32 is too large
// CHECK_NOWARN-NOT: ERROR
// FIXME: Currently, coverage instrumentation kicks in after ubsan, so we get
// more than the minimal number of instrumented blocks.
// FIXME: Currently, ubsan with -fno-sanitize-recover and w/o asan will fail
// to dump coverage.
// CHECK1:  1 PCs written
// CHECK2:  2 PCs written
// CHECK3:  2 PCs written