text:
/*!
    @header

    Thread Safety Information

    All functions in this header are thread safe unless otherwise specified.
*/

#ifndef __CTFONTCOLLECTION__
#define __CTFONTCOLLECTION__

#include <CoreText/CTDefines.h>
#include <CoreText/CTFontDescriptor.h>

CF_IMPLICIT_BRIDGING_ENABLED

#if defined(__cplusplus)
extern "C" {
#endif

/*! --------------------------------------------------------------------------
    @group Collection Types
*///--------------------------------------------------------------------------

/*!
    @typedef    CTFontCollectionRef
    @abstract   The Core Text font collection reference.
    @discussion An opaque reference to an immutable font collection.
*/
typedef const struct __CTFontCollection * CTFontCollectionRef;

/*!
    @typedef    CTMutableFontCollectionRef
    @abstract   The Core Text mutable font collection reference.
    @discussion An opaque reference to a mutable font collection.
*/
typedef struct __CTFontCollection * CTMutableFontCollectionRef;

/*!
    @function   CTFontCollectionGetTypeID
    @abstract   Returns the type identifier for Core Text font collection references.
    @result     The identifier for the opaque types CTFontCollectionRef or CTMutableFontCollectionRef.
*/
CFTypeID CTFontCollectionGetTypeID( void ) CT_AVAILABLE(10_5, 3_2);

/*!
    @typedef    CTFontCollectionSortDescriptorsCallback
    @abstract   Collection sorting callback.
    @discussion This callback can be specified to obtain the matching font descriptors of a collection in sorted order. Return the appropriate comparison result of first descriptor to second descriptor.
*/
typedef CFComparisonResult (*CTFontCollectionSortDescriptorsCallback)(
    CTFontDescriptorRef first,
    CTFontDescriptorRef second,
    void *refCon );

/*! --------------------------------------------------------------------------
    @group Collection Matching Options
*///--------------------------------------------------------------------------

/*!
    @defined    kCTFontCollectionRemoveDuplicatesOption
    @abstract   Option key to specify filtering of duplicates.
    @discussion Specify this option key in the options dictionary with a non- zero value to enable automatic filtering of duplicate font descriptors.
*/
extern const CFStringRef kCTFontCollectionRemoveDuplicatesOption    CT_AVAILABLE(10_5, 3_2);

/*!
    @defined    kCTFontCollectionIncludeDisabledOption
    @abstract   Option key to include disabled fonts in the matching results.
    @discussion Specify this option key in the options dictionary with a non-zero value to enable matching of disabled fonts. You can pass font descriptors specifying disabled fonts to CTFontManagerEnableFontDescriptors, but you cannot use such a font descriptor to query font attributes from the system database or create a CTFontRef.
*/
extern const CFStringRef kCTFontCollectionIncludeDisabledFontsOption CT_AVAILABLE_MAC(10_7);

/*!
    @defined    kCTFontCollectionDisallowAutoActivationOption
    @abstract   Option key to avoid auto-activating fonts.
    @discussion Specify this option key in the options dictionary with a non-zero value to disallow searches for missing fonts (font descriptors returning no results).
*/
extern const CFStringRef kCTFontCollectionDisallowAutoActivationOption CT_AVAILABLE_MAC(10_7);

/*! --------------------------------------------------------------------------
    @group Collection Creation
*///--------------------------------------------------------------------------

/*!
    @function   CTFontCollectionCreateFromAvailableFonts
    @abstract   Returns a new font collection matching all available fonts.

    @param      options
                The options dictionary. See constant option keys.

    @result     This function creates a new collection containing all fonts available to the current application.
*/
CTFontCollectionRef CTFontCollectionCreateFromAvailableFonts( CFDictionaryRef options ) CT_AVAILABLE(10_5, 3_2);

/*!
    @function   CTFontCollectionCreateWithFontDescriptors
    @abstract   Returns a new collection based on the array of font descriptors.

    @param      queryDescriptors
                An array of font descriptors to use for matching. May be NULL, in which case the matching descriptors will be NULL.

    @param      options
                The options dictionary. See constant option keys.

    @result     This function creates a new collection based on the provided font descriptors. The contents of this collection is defined by matching the provided descriptors against all available font descriptors.
*/
CTFontCollectionRef CTFontCollectionCreateWithFontDescriptors(
    CFArrayRef          queryDescriptors,
    CFDictionaryRef     options ) CT_AVAILABLE(10_5, 3_2);

/*!
    @function   CTFontCollectionCreateCopyWithFontDescriptors
    @abstract   Returns a copy of the original collection augmented with the new font descriptors.

    @param      original
                The original font collection reference.

    @param      queryDescriptors
                An array of font descriptors to augment those of the original collection.

    @param      options
                The options dictionary. See constant option keys.

    @result     This function creates a copy of the original font collection augmented by the new font descriptors and options. The new font descriptors are merged with the existing descriptors to create a single set.
*/
CTFontCollectionRef CTFontCollectionCreateCopyWithFontDescriptors(
    CTFontCollectionRef original,
    CFArrayRef          queryDescriptors,
    CFDictionaryRef     options ) CT_AVAILABLE(10_5, 3_2);

/*!
    @function   CTFontCollectionCreateMutableCopy
    @abstract   Returns a mutable copy of the original collection.

    @param      original
                The original font collection reference.

    @result     This function creates a mutable copy of the original font collection.
*/
CTMutableFontCollectionRef CTFontCollectionCreateMutableCopy(
    CTFontCollectionRef original ) CT_AVAILABLE_MAC(10_7);

/*! --------------------------------------------------------------------------
    @group Editing the query descriptors
*///--------------------------------------------------------------------------

/*!
    @function   CTFontCollectionCopyQueryDescriptors
    @abstract   Returns the array of descriptors to match.

    @param      collection
                The font collection reference.

    @result     This function returns a retained reference to the array of descriptors to be used to query (match) the system font database. The return value is undefined if CTFontCollectionCreateFromAvailableFonts was used to create the collection.
*/
CFArrayRef CTFontCollectionCopyQueryDescriptors( CTFontCollectionRef collection ) CT_AVAILABLE_MAC(10_7);

/*!
    @function   CTFontCollectionSetQueryDescriptors
    @abstract   Replaces the array of descriptors to match.

    @param      collection
                The font collection reference.

    @param      descriptors
                An array of CTFontDescriptorRef. May be NULL to represent an empty collection, in which case the matching descriptors will also be NULL.
*/
void CTFontCollectionSetQueryDescriptors(
    CTMutableFontCollectionRef  collection,
    CFArrayRef                  descriptors ) CT_AVAILABLE_MAC(10_7);

/*!
    @function   CTFontCollectionCopyExclusionDescriptors
    @abstract   Returns the array of descriptors to exclude from the match.

    @param      collection
                The font collection reference.

    @result     This function returns a retained reference to the array of descriptors to be used to query (match) the system font database.
*/
CFArrayRef CTFontCollectionCopyExclusionDescriptors( CTFontCollectionRef collection ) CT_AVAILABLE_MAC(10_7);

/*!
    @function   CTFontCollectionSetExclusionDescriptors
    @abstract   Replaces the array of descriptors to exclude from the match.

    @param      collection
                The font collection reference.

    @param      descriptors
                An array of CTFontDescriptorRef. May be NULL.
*/
void CTFontCollectionSetExclusionDescriptors(
    CTMutableFontCollectionRef  collection,
    CFArrayRef                  descriptors ) CT_AVAILABLE_MAC(10_7);

/*! --------------------------------------------------------------------------
    @group Retrieving Matching Descriptors
*///--------------------------------------------------------------------------

/*!
    @function   CTFontCollectionCreateMatchingFontDescriptors
    @abstract   Returns an array of font descriptors matching the collection.

    @param      collection
                The font collection reference.

    @result     This function returns a retained reference to an array of normalized font descriptors   matching the collection definition.
*/
CFArrayRef CTFontCollectionCreateMatchingFontDescriptors( CTFontCollectionRef collection ) CT_AVAILABLE(10_5, 3_2);

/*!
    @function   CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback
    @abstract   Returns the array of matching font descriptors sorted with the callback function.

    @param      collection
                The collection reference.

    @param      sortCallback
                The sorting callback function that defines the sort order.

    @param      refCon
                Pointer to client data define context for the callback.

    @result     This function returns an array of font descriptors matching the criteria of the collection and sorted by the results of the sorting callback function.
*/
CFArrayRef CTFontCollectionCreateMatchingFontDescriptorsSortedWithCallback(
    CTFontCollectionRef                     collection,
    CTFontCollectionSortDescriptorsCallback sortCallback,
    void                                    *refCon ) CT_AVAILABLE(10_5, 3_2);

/*!
    @function   CTFontCollectionCreateMatchingFontDescriptorsWithOptions
    @abstract   Returns an array of font descriptors matching the collection.

    @param      collection
                The font collection reference.

    @param      options
                The options dictionary. See constant option keys. May be NULL, in which case this call returns the same results as CTFontCollectionCreateMatchingFontDescriptors, using the options passed in when the collection was created.

    @result     This function returns a retained reference to an array of normalized font descriptors   matching the collection definition.
*/
CFArrayRef CTFontCollectionCreateMatchingFontDescriptorsWithOptions( CTFontCollectionRef collection,
    CFDictionaryRef     options ) CT_AVAILABLE_MAC(10_7);

/*!
    @function   CTFontCollectionCreateMatchingFontDescriptorsForFamily
    @abstract   Returns an array of font descriptors matching the specified family, one descriptor for each style in the collection.

    @param      collection
                The font collection reference.

    @param      familyName
                The font family name

    @result     This function returns a retained reference to an array of normalized font descriptors matching the collection definition.
*/
CFArrayRef CTFontCollectionCreateMatchingFontDescriptorsForFamily(
    CTFontCollectionRef collection,
    CFStringRef         familyName,
    CFDictionaryRef     options ) CT_AVAILABLE_MAC(10_7);

/*! --------------------------------------------------------------------------
    @group Bulk attribute access
*///--------------------------------------------------------------------------
/*!
    @enum       CTFontCollectionCopyOptions
    @abstract   Option bits for use with CTFontCollectionCopyFontAttribute(s).

    @constant   kCTFontCollectionCopyStandardSort
                Passing this option indicates that the return values should be sorted in standard UI order, suitable for display to the user. This is the same sorting behavior used by NSFontPanel and Font Book.

    @constant   kCTFontCollectionCopyUnique
                Passing this option indicates that duplicate values should be removed from the results.
 */
enum
{
    kCTFontCollectionCopyDefaultOptions = 0,
    kCTFontCollectionCopyUnique = (1L << 0),
    kCTFontCollectionCopyStandardSort = (1L << 1)
};
typedef uint32_t CTFontCollectionCopyOptions;

/*!
    @function   CTFontCollectionCopyFontAttribute
    @abstract   Returns an array of font descriptor attribute values.

    @param      collection
                The font collection reference.

    @param      attributeName
                The attribute to retrieve for each descriptor in the collection.

    @param      options
                Options to alter the return value.

    @result     This function returns a retained reference to a CFArray, or NULL on error. The caller is responsible for releasing the array. The array contains one value for each descriptor, in the same order as the results from CTFontCollectionCreateMatchingDescriptors. When the kCTFontCollectionCopyUnique is set, duplicate values will be removed. When kCTFontCollectionCopyStandardSort is set, the values will be sorted in standard UI order.
 */
CFArrayRef CTFontCollectionCopyFontAttribute(
    CTFontCollectionRef         collection,
    CFStringRef                 attributeName,
    CTFontCollectionCopyOptions options ) CT_AVAILABLE_MAC(10_7);

/*!
    @function   CTFontCollectionCopyFontAttributes
    @abstract   Returns an array of dictionaries containing font descriptor attribute values.

    @param      collection
                The font collection reference.

    @param      attributeNames
                The attributes to retrieve for each descriptor in the collection.

    @param      options
                Options to alter the return value.

    @result     This function returns a retained reference to a CFArray, or NULL on error. The caller is responsible for releasing the array. The array contains one value for each descriptor, in the same order as the results from CTFontCollectionCreateMatchingDescriptors. When the kCTFontCollectionCopyUnique is set, duplicate values will be removed. When kCTFontCollectionCopyStandardSort is set, the values will be sorted in standard UI order.
 */
CFArrayRef CTFontCollectionCopyFontAttributes(
    CTFontCollectionRef         collection,
    CFSetRef                    attributeNames,
    CTFontCollectionCopyOptions options ) CT_AVAILABLE_MAC(10_7);

#if defined(__cplusplus)
}
#endif

CF_IMPLICIT_BRIDGING_DISABLED

#endif


text:
import logging
log = logging.getLogger(__name__)

import functools
import math
import numpy
from pubsub import pub
from threading import Lock
import time
import wx
from wx.lib.agw import floatspin

from spacq.interface.resources import AcquisitionThread
from spacq.interface.units import Quantity

from ....config.measurement import MeasurementConfigPanel
from ....tool.box import Dialog, MessageDialog

try:
	from ..two_dimensional import TwoDimensionalPlot
except ImportError as e:
	plot_available = False
	log.debug('Could not import TwoDimensionalPlot: {0}'.format(str(e)))
else:
	plot_available = True

"""
A historical live view plot for scalar values.
"""

class PlotSettings(object):
	"""
	Wrapper for all the settings configured via dialog.
	"""

	def __init__(self):
		self.enabled = plot_available
		self.num_points = 500
		self.delay = Quantity(0.2, 's')
		self.update_x = True
		self.time_value = 0
		self.time_mode = 0
		self.update_y = True
		self.y_scale = 0
		self.units_from = ''
		self.units_to = ''

class PlotSettingsDialog(Dialog):
	"""
	Set up the live view plot.
	"""

	def __init__(self, parent, ok_callback, *args, **kwargs):
		Dialog.__init__(self, parent=parent, title='Plot settings')

		self.ok_callback = ok_callback

		dialog_box = wx.BoxSizer(wx.VERTICAL)

		# Enabled.
		self.enabled_checkbox = wx.CheckBox(self, label='Enabled')
		if not plot_available:
			self.enabled_checkbox.Disable()
		dialog_box.Add(self.enabled_checkbox, flag=wx.ALL, border=5)

		# Capture.
		capture_static_box = wx.StaticBox(self, label='Capture')
		capture_box = wx.StaticBoxSizer(capture_static_box, wx.VERTICAL)
		capture_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=5)
		capture_box.Add(capture_sizer, flag=wx.CENTER)
		dialog_box.Add(capture_box, flag=wx.EXPAND|wx.ALL, border=5)

		## Number of points.
		capture_sizer.Add(wx.StaticText(self, label='Points:'),
				flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
		self.points_input = wx.SpinCtrl(self, min=2, max=1e4, initial=100)
		capture_sizer.Add(self.points_input, flag=wx.CENTER)

		## Delay.
		capture_sizer.Add(wx.StaticText(self, label='Delay (s):'),
				flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
		# TODO: Input should be a time amount directly (eg. '200 ms').
		self.delay_input = floatspin.FloatSpin(self, min_val=0.2, max_val=1e4, increment=0.1, digits=2)
		capture_sizer.Add(self.delay_input, flag=wx.CENTER)

		# Axes.
		axes_static_box = wx.StaticBox(self, label='Axes')
		axes_box = wx.StaticBoxSizer(axes_static_box, wx.HORIZONTAL)
		dialog_box.Add(axes_box, flag=wx.EXPAND|wx.ALL, border=5)

		## x
		x_static_box = wx.StaticBox(self, label='x')
		x_box = wx.StaticBoxSizer(x_static_box, wx.VERTICAL)
		axes_box.Add(x_box, flag=wx.EXPAND)

		self.update_x_axis = wx.CheckBox(self, label='Autofit')
		x_box.Add(self.update_x_axis)

		### Value.
		self.time_value = wx.RadioBox(self, label='Value', choices=['Time', 'Points'])
		x_box.Add(self.time_value, flag=wx.EXPAND)

		### Mode.
		self.time_mode = wx.RadioBox(self, label='Mode', choices=['Relative', 'Absolute'])
		x_box.Add(self.time_mode, flag=wx.EXPAND)

		## y
		y_static_box = wx.StaticBox(self, label='y')
		y_box = wx.StaticBoxSizer(y_static_box, wx.VERTICAL)
		axes_box.Add(y_box, flag=wx.EXPAND)

		self.update_y_axis = wx.CheckBox(self, label='Autofit')
		y_box.Add(self.update_y_axis)

		### Conversion.
		conversion_static_box = wx.StaticBox(self, label='Conversion')
		conversion_box = wx.StaticBoxSizer(conversion_static_box, wx.VERTICAL)
		conversion_sizer = wx.FlexGridSizer(rows=1, cols=2, hgap=5)
		conversion_box.Add(conversion_sizer)
		y_box.Add(conversion_box)

		conversion_sizer.Add(wx.StaticText(self, label='Exp. scale:'),
				flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
		self.y_scale = floatspin.FloatSpin(self, min_val=-100, max_val=100, increment=1, digits=2)
		conversion_sizer.Add(self.y_scale)

		#### Units.
		units_static_box = wx.StaticBox(self, label='Units')
		units_box = wx.StaticBoxSizer(units_static_box, wx.VERTICAL)
		units_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=5)
		units_box.Add(units_sizer)
		conversion_box.Add(units_box, flag=wx.EXPAND)

		units_sizer.Add(wx.StaticText(self, label='From:'),
				flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
		self.units_from_input = wx.TextCtrl(self)
		units_sizer.Add(self.units_from_input)

		units_sizer.Add(wx.StaticText(self, label='To:'),
				flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
		self.units_to_input = wx.TextCtrl(self)
		units_sizer.Add(self.units_to_input)

		# End buttons.
		button_box = wx.BoxSizer(wx.HORIZONTAL)
		dialog_box.Add(button_box, flag=wx.CENTER)

		ok_button = wx.Button(self, wx.ID_OK)
		self.Bind(wx.EVT_BUTTON, self.OnOk, ok_button)
		button_box.Add(ok_button)

		cancel_button = wx.Button(self, wx.ID_CANCEL)
		button_box.Add(cancel_button)

		self.SetSizerAndFit(dialog_box)

	def OnOk(self, evt=None):
		self.ok_callback(self)

		self.Destroy()

	def GetValue(self):
		plot_settings = PlotSettings()
		plot_settings.enabled = self.enabled_checkbox.Value
		plot_settings.num_points = self.points_input.Value
		plot_settings.delay = Quantity(self.delay_input.GetValue(), 's')
		plot_settings.update_x = self.update_x_axis.Value
		plot_settings.time_value = self.time_value.Selection
		plot_settings.time_mode = self.time_mode.Selection
		plot_settings.update_y = self.update_y_axis.Value
		plot_settings.y_scale = self.y_scale.GetValue()
		plot_settings.units_from = self.units_from_input.Value
		plot_settings.units_to = self.units_to_input.Value

		return plot_settings

	def SetValue(self, plot_settings):
		self.enabled_checkbox.Value = plot_settings.enabled
		self.points_input.Value = plot_settings.num_points
		self.delay_input.SetValue(plot_settings.delay.value)
		self.update_x_axis.Value = plot_settings.update_x
		self.time_value.Selection = plot_settings.time_value
		self.time_mode.Selection = plot_settings.time_mode
		self.update_y_axis.Value = plot_settings.update_y
		self.y_scale.SetValue(plot_settings.y_scale)
		self.units_from_input.Value = plot_settings.units_from
		self.units_to_input.Value = plot_settings.units_to

class ScalarLiveViewPanel(wx.Panel):
	"""
	A panel to display a live view plot of a scalar resource.
	"""

	def __init__(self, parent, global_store, *args, **kwargs):
		wx.Panel.__init__(self, parent, *args, **kwargs)

		self.global_store = global_store
		self._measurement_resource_name = None

		# Defaults.
		self.plot_settings = PlotSettings()
		self.unit_conversion = 0

		self.enabled = False
		self.capturing_data = False
		self.restart_live_view = False
		self.resource_backup = None

		# This lock blocks the acquisition thread from acquiring.
		self.running_lock = Lock()

		# Initialize recorded values.
		self.init_values()

		# Plot and toolbar.
		display_box = wx.BoxSizer(wx.VERTICAL)

		## Plot.
		if plot_available:
			self.plot = TwoDimensionalPlot(self, color='blue')
			display_box.Add(self.plot.control, proportion=1, flag=wx.EXPAND)

			self.plot.x_label = 'Time (s)'
		else:
			display_box.Add((500, -1), proportion=1, flag=wx.EXPAND)

		## Controls.
		if plot_available:
			controls_box = wx.BoxSizer(wx.HORIZONTAL)
			display_box.Add(controls_box, flag=wx.CENTER|wx.ALL, border=5)

			### Numeric display.
			numeric_display_static_box = wx.StaticBox(self, label='Reading')
			numeric_display_box = wx.StaticBoxSizer(numeric_display_static_box, wx.HORIZONTAL)
			controls_box.Add(numeric_display_box, flag=wx.CENTER)

			self.numeric_display = wx.TextCtrl(self, size=(100, -1), style=wx.TE_READONLY)
			self.numeric_display.BackgroundColour = wx.LIGHT_GREY
			numeric_display_box.Add(self.numeric_display)

			### Capture.
			capture_static_box = wx.StaticBox(self, label='Control')
			capture_box = wx.StaticBoxSizer(capture_static_box)
			controls_box.Add(capture_box, flag=wx.CENTER|wx.LEFT, border=10)

			self.run_button = wx.Button(self, label='Run')
			self.Bind(wx.EVT_BUTTON, self.OnRun, self.run_button)
			capture_box.Add(self.run_button, flag=wx.CENTER)

			self.pause_button = wx.Button(self, label='Pause')
			self.Bind(wx.EVT_BUTTON, self.OnPause, self.pause_button)
			capture_box.Add(self.pause_button, flag=wx.CENTER)

			self.reset_button = wx.Button(self, label='Reset')
			self.Bind(wx.EVT_BUTTON, self.OnReset, self.reset_button)
			capture_box.Add(self.reset_button, flag=wx.CENTER|wx.LEFT, border=10)

			### Settings.
			settings_static_box = wx.StaticBox(self, label='Settings')
			settings_box = wx.StaticBoxSizer(settings_static_box, wx.HORIZONTAL)
			controls_box.Add(settings_box, flag=wx.CENTER|wx.LEFT, border=10)

			self.plot_settings_button = wx.Button(self, label='Plot...')
			self.Bind(wx.EVT_BUTTON, self.OnPlotSettings, self.plot_settings_button)
			settings_box.Add(self.plot_settings_button, flag=wx.CENTER)

		self.SetSizer(display_box)

		# Acquisition thread.
		callback = functools.partial(wx.CallAfter, self.add_value)
		self.acq_thread = AcquisitionThread(self.plot_settings.delay, callback,
				running_lock=self.running_lock)
		self.acq_thread.daemon = True
		self.acq_thread.start()

		# Wait for a resource to begin capturing.
		self.OnPause()
		self.run_button.Disable()

		# Subscriptions.
		pub.subscribe(self.msg_resource, 'resource.added')
		pub.subscribe(self.msg_resource, 'resource.removed')
		pub.subscribe(self.msg_data_capture_start, 'data_capture.start')
		pub.subscribe(self.msg_data_capture_data, 'data_capture.data')
		pub.subscribe(self.msg_data_capture_stop, 'data_capture.stop')

	@property
	def running(self):
		return self.pause_button.Enabled

	@property
	def resource(self):
		return self.acq_thread.resource

	@resource.setter
	def resource(self, value):
		# Ignore unreadable resources.
		if value is not None and not value.readable:
			value = None

		if self.running:
			# Currently running.
			running = True
			self.OnPause()
		else:
			running = False

		self.acq_thread.resource = value

		self.run_button.Enable(value is not None)

		# Resume if applicable.
		if running:
			self.OnRun()

	@property
	def measurement_resource_name(self):
		if self._measurement_resource_name is None:
			return ''
		else:
			return self._measurement_resource_name

	@measurement_resource_name.setter
	def measurement_resource_name(self, value):
		if value:
			self._measurement_resource_name = value
			try:
				self.resource = self.global_store.resources[self._measurement_resource_name]
			except KeyError:
				self.resource = None
		else:
			self._measurement_resource_name = None
			self.resource = None

	def init_values(self):
		"""
		Clear captured values.
		"""

		self._points = numpy.array([])
		self._times = numpy.array([])
		self._values = numpy.array([])

		self.current_value = None

		self.start_time = None

	def update_plot(self):
		"""
		Redraw the plot.
		"""

		if not len(self._points) > 0:
			display_time = [0]
			display_values = [0]
		else:
			if self.plot_settings.time_value == 0: # Time.
				display_time = self._times

				if self.plot_settings.time_mode == 0: # Relative.
					# Calculate the number of seconds passed since each point.
					max_time = self._times[-1]
					display_time = [x - max_time for x in display_time]
				elif self.plot_settings.time_mode == 1: # Absolute.
					display_time = [x - self.start_time for x in display_time]
			elif self.plot_settings.time_value == 1: # Points.
				display_time = self._points

				if self.plot_settings.time_mode == 0: # Relative.
					# Calculate the number of seconds passed since each point.
					max_point = self._points[-1]
					display_time = [x - max_point for x in display_time]

			display_values = [x * 10 ** (self.plot_settings.y_scale + self.unit_conversion) for
					x in self._values]

		if self.plot_settings.update_x:
			self.plot.x_autoscale()
		if self.plot_settings.update_y:
			self.plot.y_autoscale()

		self.plot.x_data, self.plot.y_data = display_time, display_values

	def add_value(self, value):
		"""
		Update the plot with a new value.
		"""

		if not self.plot_settings.enabled:
			return

		# Extract the value of a Quantity.
		try:
			# Label with the base dimensions.
			if self.unit_conversion == 0:
				self.plot.y_label = '({0})'.format(value.original_units)
			value = value.original_value
		except AttributeError:
			pass

		# Update values.
		try:
			self._points = numpy.append(self._points, self._points[-1] + 1)
		except IndexError:
			self._points = numpy.append(self._points, 0)
		cur_time = time.time()
		self._times = numpy.append(self._times, cur_time)
		self._values = numpy.append(self._values, value)

		if self.start_time is None:
			self.start_time = cur_time

		cut_idx = len(self._points) - int(self.plot_settings.num_points)
		if cut_idx > 0:
			self._points = self._points[cut_idx:]
			self._times = self._times[cut_idx:]
			self._values = self._values[cut_idx:]

		# Set number display.
		self.current_value = value * 10 ** (self.plot_settings.y_scale + self.unit_conversion)
		self.numeric_display.Value = '{0:.6g}'.format(self.current_value)

		# Plot.
		self.update_plot()

	def close(self):
		"""
		Perform cleanup.
		"""

		# Unsubscriptions.
		pub.unsubscribe(self.msg_resource, 'resource.added')
		pub.unsubscribe(self.msg_resource, 'resource.removed')
		pub.unsubscribe(self.msg_data_capture_start, 'data_capture.start')
		pub.unsubscribe(self.msg_data_capture_data, 'data_capture.data')
		pub.unsubscribe(self.msg_data_capture_stop, 'data_capture.stop')

		# Ensure the thread exits.
		self.acq_thread.resource = None
		self.acq_thread.done = True
		if not self.running:
			self.running_lock.release()
		self.acq_thread.join()
		del self.acq_thread

	def OnRun(self, evt=None):
		"""
		Let the acquisition thread run.
		"""

		self.run_button.Disable()

		if self.acq_thread.resource is None:
			return

		self.running_lock.release()

		self.pause_button.Enable()

	def OnPause(self, evt=None):
		"""
		Block the acquisition thread.
		"""

		if not self.running:
			return

		self.running_lock.acquire()

		if self.acq_thread.resource is not None:
			self.run_button.Enable()
		self.pause_button.Disable()

	def OnReset(self, evt=None):
		self.init_values()
		self.update_plot()

	def OnPlotSettings(self, evt=None):
		"""
		Open the plot settings dialog.
		"""

		def ok_callback(dlg):
			self.plot_settings = dlg.GetValue()

			if self.plot_settings.units_from and self.plot_settings.units_to:
				try:
					quantity_from = Quantity(1, self.plot_settings.units_from)
					quantity_to = Quantity(1, self.plot_settings.units_to)
				except ValueError as e:
					self.unit_conversion = 0
					MessageDialog(self, str(e), 'Invalid unit').Show()
				else:
					# We don't actually care about the units; just the prefix values.
					self.unit_conversion = math.log(quantity_from.value, 10) - math.log(quantity_to.value, 10)
			else:
				self.unit_conversion = 0

			self.acq_thread.delay = self.plot_settings.delay

			if self.plot_settings.time_value == 0:
				self.plot.x_label = 'Time (s)'
			elif self.plot_settings.time_value == 1:
				self.plot.x_label = 'Points'

			if self.plot_settings.y_scale != 0:
				self.plot.y_label = '/ 10 ^ {0}'.format(self.plot_settings.y_scale)
			else:
				self.plot.y_label = ''

			if self.plot_settings.units_to:
				self.plot.y_label += ' ({0})'.format(self.plot_settings.units_to)

			self.update_plot()

		dlg = PlotSettingsDialog(self, ok_callback)
		dlg.SetValue(self.plot_settings)
		dlg.Show()

	def msg_resource(self, name, value=None):
		if self.measurement_resource_name is not None and name == self.measurement_resource_name:
			self.resource = value

	def msg_data_capture_start(self, name):
		if name == self.measurement_resource_name:
			if self.enabled:
				self.capturing_data = True

				# Keep track of whether to restart the capture afterwards.
				self.restart_live_view = self.running

				# Disable live view.
				self.resource_backup = self.resource
				self.resource = None

	def msg_data_capture_data(self, name, value):
		if name == self.measurement_resource_name:
			if self.capturing_data:
				self.add_value(value)

	def msg_data_capture_stop(self, name):
		if name == self.measurement_resource_name:
			if self.capturing_data:
				self.capturing_data = False

				# Re-enable live view.
				self.resource = self.resource_backup
				self.resource_backup = None

				if self.restart_live_view:
					self.OnRun()

class ScalarMeasurementFrame(wx.Frame):
	def __init__(self, parent, global_store, *args, **kwargs):
		wx.Frame.__init__(self, parent, *args, **kwargs)

		# Frame.
		frame_box = wx.BoxSizer(wx.VERTICAL)

		## Measurement setup.
		self.measurement_config_panel = MeasurementConfigPanel(self, global_store)
		frame_box.Add(self.measurement_config_panel, flag=wx.EXPAND)

		## Live view.
		self.live_view_panel = ScalarLiveViewPanel(self, global_store)
		self.live_view_panel.SetMinSize((-1, 400))
		frame_box.Add(self.live_view_panel, proportion=1, flag=wx.EXPAND)

		self.SetSizerAndFit(frame_box)

		self.Bind(wx.EVT_CLOSE, self.OnClose)

	def OnClose(self, evt):
		if self.live_view_panel.capturing_data:
			msg = 'Cannot close, as a sweep is currently in progress.'
			MessageDialog(self, msg, 'Sweep in progress').Show()

			evt.Veto()
			return

		self.live_view_panel.close()
		self.measurement_config_panel.close()

		evt.Skip()

redpajama_set_name: RedPajamaGithub


text:
const { Sprite } = require('../..');

describe('Sprite', function ()
{
    it('should have DisplayObject shortened names', function ()
    {
        const p = new Sprite();

        assert.isOk(p.setRenderable);
        assert.isOk(p.re);
        assert.equal(p.setRenderable, p.re);
        assert.isOk(p.t);
        assert.equal(p.setTransform, p.t);
        assert.isOk(p.ma);
        assert.isOk(p.setMask);
        assert.equal(p.setMask, p.ma);
        assert.isOk(p.a);
        assert.isOk(p.setAlpha);
        assert.equal(p.setAlpha, p.a);
        assert.isOk(p.i);
        assert.isOk(p.setTint);
        assert.equal(p.setTint, p.i);
        assert.isOk(p.c);
        assert.isOk(p.setColorTransform);
        assert.equal(p.setColorTransform, p.c);
    });
});


text:
import { Injectable } from '@angular/core';

import { Hero } from './hero.model';

@Injectable()
export class HeroCollectorService {
  hero: Hero;

  constructor() { }
}
// #enddocregion example


text:
title: Manipulate Arrays With push()
localeTitle: Manipular matrices con empuje ()
---
## Manipular matrices con empuje ()

El método `push()` permite agregar (agregar al final) un elemento a una matriz. Al igual que…

```javascript
var arr = [1, 2, 3, 4];
 arr.push(5); // Now, the array is [1, 2, 3, 4, 5]

```


text:
package broker

import (
	"flag"
	"fmt"
	"io/ioutil"

	"github.com/BurntSushi/toml"
	"math"
)

//Configure schema
type Configure struct {
	HttpPort int
	MsgPort  int

	Auth     bool
	UserName string
	Token    string

	Retry int

	Aof       string
	SyncType  int
	Threshold int
}

//Config is the default config file
var Config *Configure = new(Configure)

//LoadConfig load default config and cmd-line flags
func LoadConfig() {
	var configFile string
	//todo the default config Path
	flag.IntVar(&Config.HttpPort, "httpport", 13000, "the http port")
	flag.IntVar(&Config.MsgPort, "port", 13001, "the msg port")
	flag.IntVar(&Config.Retry, "r", 3, "the retry times")
	flag.StringVar(&Config.Aof, "aof", "msgo.aof", "the aof file path")
	flag.IntVar(&Config.SyncType, "sync", 0, "the default sync type of aof")
	flag.IntVar(&Config.Threshold, "rewrite-threshold", 10000, "the default threshold of deleteOps that triggers rewrite operation")
	flag.StringVar(&configFile, "c", "", "the config file path")
	flag.Parse()
	if configFile != "" {
		Bytes, err := ioutil.ReadFile(configFile)
		if err != nil {
			panic(fmt.Sprintf("reading config file error %s: %v", configFile, err))
		}
		if _, err := toml.Decode(string(Bytes), Config); err != nil {
			panic(fmt.Sprintf("parse config file error %s: %v", configFile, err))
		}
	}
	ArbitrateConfigs(Config)
}

//ArbitrateConfigs will check the config file
func ArbitrateConfigs(c *Configure) {
	//check the ClusterName, ClusterName is used to Identify the clusters in the Local NetWork
	if c.HttpPort == c.MsgPort {
		panic("port conflict")
	}
	if c.HttpPort > math.MaxInt16 || c.HttpPort < 1024 {
		panic(fmt.Errorf("illegal http port %d", c.HttpPort))
	}

	if c.MsgPort > math.MaxInt16 || c.MsgPort < 1024 {
		panic(fmt.Errorf("illegal msg port %d", c.MsgPort))
	}

	if c.Retry > 10 {
		c.Retry = 10
	}
	if c.Retry < 1 {
		c.Retry = 1
	}
	if c.SyncType < 0 || c.SyncType > 2 {
		c.SyncType = 0
	}
	if c.Threshold < 1000 {
		c.Threshold = 1000
	}
	if c.Threshold > 1000000 {
		c.Threshold = 1000000
	}
}


text:
require "assert"
require "nm/ext"

module Nm::Ext
  class UnitTests < Assert::Context
    desc "Nm ruby extension"
    subject{ Nm }

    should "define an invalid runtime error" do
      assert_that(subject::InvalidError.new).is_a(RuntimeError)
    end
  end

  class AddCallDataTests < UnitTests
    desc "__nm_add_partial_data__"

    should "be added to ::Hash" do
      assert_that({}).responds_to(:__nm_add_partial_data__)
    end

    should "be added to ::Array" do
      assert_that([]).responds_to(:__nm_add_partial_data__)
    end

    should "be added to nil" do
      assert_that(nil).responds_to(:__nm_add_partial_data__)
    end
  end

  class HashAddCallDataTests < AddCallDataTests
    desc "on ::Hash"

    let(:h){ { 1 => "1" } }

    should "merge and return hash and nil data" do
      add = { 2 => "2" }
      assert_that(h.__nm_add_partial_data__(add)).equals(h.merge(add))
      assert_that(h.__nm_add_partial_data__(nil)).equals(h)
    end

    should "complain if adding Array data" do
      add = []
      assert_that{ h.__nm_add_partial_data__(add) }.raises(Nm::InvalidError)
    end
  end

  class ArrayAddCallDataTests < AddCallDataTests
    desc "on ::Array"

    let(:a){ [1, 2] }

    should "concat and return array and nil data" do
      add = [3, 4]
      assert_that(a.__nm_add_partial_data__(add)).equals(a.concat(add))
      assert_that(a.__nm_add_partial_data__(nil)).equals(a)
    end

    should "complain if adding Hash data" do
      add = {}
      assert_that{ a.__nm_add_partial_data__(add) }.raises(Nm::InvalidError)
    end
  end

  class NilAddCallDataTests < AddCallDataTests
    desc "on nil"

    let(:n){ nil }

    should "return any given data" do
      add_hash = { 1 => "1" }
      add_array = [3, 4]
      assert_that(n.__nm_add_partial_data__(add_hash)).equals(add_hash)
      assert_that(n.__nm_add_partial_data__(add_array)).equals(add_array)
      assert_that(n.__nm_add_partial_data__(nil)).equals(n)
    end
  end
end


text:
namespace llvm {

class BlockFrequencyInfo;
class MachineBlockFrequencyInfo;

/// BlockFrequencyImpl implements block frequency algorithm for IR and
/// Machine Instructions. Algorithm starts with value ENTRY_FREQ
/// for the entry block and then propagates frequencies using branch weights
/// from (Machine)BranchProbabilityInfo. LoopInfo is not required because
/// algorithm can find "backedges" by itself.
template<class BlockT, class FunctionT, class BlockProbInfoT>
class BlockFrequencyImpl {

  DenseMap<const BlockT *, BlockFrequency> Freqs;

  BlockProbInfoT *BPI;

  FunctionT *Fn;

  typedef GraphTraits< Inverse<BlockT *> > GT;

  const uint32_t EntryFreq;

  std::string getBlockName(BasicBlock *BB) const {
    return BB->getName().str();
  }

  std::string getBlockName(MachineBasicBlock *MBB) const {
    std::string str;
    raw_string_ostream ss(str);
    ss << "BB#" << MBB->getNumber();

    if (const BasicBlock *BB = MBB->getBasicBlock())
      ss << " derived from LLVM BB " << BB->getName();

    return ss.str();
  }

  void setBlockFreq(BlockT *BB, BlockFrequency Freq) {
    Freqs[BB] = Freq;
    DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") = " << Freq << "\n");
  }

  /// getEdgeFreq - Return edge frequency based on SRC frequency and Src -> Dst
  /// edge probability.
  BlockFrequency getEdgeFreq(BlockT *Src, BlockT *Dst) const {
    BranchProbability Prob = BPI->getEdgeProbability(Src, Dst);
    return getBlockFreq(Src) * Prob;
  }

  /// incBlockFreq - Increase BB block frequency by FREQ.
  ///
  void incBlockFreq(BlockT *BB, BlockFrequency Freq) {
    Freqs[BB] += Freq;
    DEBUG(dbgs() << "Frequency(" << getBlockName(BB) << ") += " << Freq
                 << " --> " << Freqs[BB] << "\n");
  }

  // All blocks in postorder.
  std::vector<BlockT *> POT;

  // Map Block -> Position in reverse-postorder list.
  DenseMap<BlockT *, unsigned> RPO;

  // For each loop header, record the per-iteration probability of exiting the
  // loop. This is the reciprocal of the expected number of loop iterations.
  typedef DenseMap<BlockT*, BranchProbability> LoopExitProbMap;
  LoopExitProbMap LoopExitProb;

  // (reverse-)postorder traversal iterators.
  typedef typename std::vector<BlockT *>::iterator pot_iterator;
  typedef typename std::vector<BlockT *>::reverse_iterator rpot_iterator;

  pot_iterator pot_begin() { return POT.begin(); }
  pot_iterator pot_end() { return POT.end(); }

  rpot_iterator rpot_begin() { return POT.rbegin(); }
  rpot_iterator rpot_end() { return POT.rend(); }

  rpot_iterator rpot_at(BlockT *BB) {
    rpot_iterator I = rpot_begin();
    unsigned idx = RPO.lookup(BB);
    assert(idx);
    std::advance(I, idx - 1);

    assert(*I == BB);
    return I;
  }

  /// isBackedge - Return if edge Src -> Dst is a reachable backedge.
  ///
  bool isBackedge(BlockT *Src, BlockT *Dst) {
    unsigned a = RPO.lookup(Src);
    if (!a)
      return false;
    unsigned b = RPO.lookup(Dst);
    assert(b && "Destination block should be reachable");
    return a >= b;
  }

  /// getSingleBlockPred - return single BB block predecessor or NULL if
  /// BB has none or more predecessors.
  BlockT *getSingleBlockPred(BlockT *BB) {
    typename GT::ChildIteratorType
      PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
      PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);

    if (PI == PE)
      return 0;

    BlockT *Pred = *PI;

    ++PI;
    if (PI != PE)
      return 0;

    return Pred;
  }

  void doBlock(BlockT *BB, BlockT *LoopHead,
               SmallPtrSet<BlockT *, 8> &BlocksInLoop) {

    DEBUG(dbgs() << "doBlock(" << getBlockName(BB) << ")\n");
    setBlockFreq(BB, 0);

    if (BB == LoopHead) {
      setBlockFreq(BB, EntryFreq);
      return;
    }

    if(BlockT *Pred = getSingleBlockPred(BB)) {
      if (BlocksInLoop.count(Pred))
        setBlockFreq(BB, getEdgeFreq(Pred, BB));
      // TODO: else? irreducible, ignore it for now.
      return;
    }

    bool isInLoop = false;
    bool isLoopHead = false;

    for (typename GT::ChildIteratorType
         PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
         PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
         PI != PE; ++PI) {
      BlockT *Pred = *PI;

      if (isBackedge(Pred, BB)) {
        isLoopHead = true;
      } else if (BlocksInLoop.count(Pred)) {
        incBlockFreq(BB, getEdgeFreq(Pred, BB));
        isInLoop = true;
      }
      // TODO: else? irreducible.
    }

    if (!isInLoop)
      return;

    if (!isLoopHead)
      return;

    // This block is a loop header, so boost its frequency by the expected
    // number of loop iterations. The loop blocks will be revisited so they all
    // get this boost.
    typename LoopExitProbMap::const_iterator I = LoopExitProb.find(BB);
    assert(I != LoopExitProb.end() && "Loop header missing from table");
    Freqs[BB] /= I->second;
    DEBUG(dbgs() << "Loop header scaled to " << Freqs[BB] << ".\n");
  }

  /// doLoop - Propagate block frequency down through the loop.
  void doLoop(BlockT *Head, BlockT *Tail) {
    DEBUG(dbgs() << "doLoop(" << getBlockName(Head) << ", "
                 << getBlockName(Tail) << ")\n");

    SmallPtrSet<BlockT *, 8> BlocksInLoop;

    for (rpot_iterator I = rpot_at(Head), E = rpot_at(Tail); ; ++I) {
      BlockT *BB = *I;
      doBlock(BB, Head, BlocksInLoop);

      BlocksInLoop.insert(BB);
      if (I == E)
        break;
    }

    // Compute loop's cyclic probability using backedges probabilities.
    BlockFrequency BackFreq;
    for (typename GT::ChildIteratorType
         PI = GraphTraits< Inverse<BlockT *> >::child_begin(Head),
         PE = GraphTraits< Inverse<BlockT *> >::child_end(Head);
         PI != PE; ++PI) {
      BlockT *Pred = *PI;
      assert(Pred);
      if (isBackedge(Pred, Head))
        BackFreq += getEdgeFreq(Pred, Head);
    }

    // The cyclic probability is freq(BackEdges) / freq(Head), where freq(Head)
    // only counts edges entering the loop, not the loop backedges.
    // The probability of leaving the loop on each iteration is:
    //
    //   ExitProb = 1 - CyclicProb
    //
    // The Expected number of loop iterations is:
    //
    //   Iterations = 1 / ExitProb
    //
    uint64_t D = std::max(getBlockFreq(Head).getFrequency(), UINT64_C(1));
    uint64_t N = std::max(BackFreq.getFrequency(), UINT64_C(1));
    if (N < D)
      N = D - N;
    else
      // We'd expect N < D, but rounding and saturation means that can't be
      // guaranteed.
      N = 1;

    // Now ExitProb = N / D, make sure it fits in an i32/i32 fraction.
    assert(N <= D);
    if (D > UINT32_MAX) {
      unsigned Shift = 32 - countLeadingZeros(D);
      D >>= Shift;
      N >>= Shift;
      if (N == 0)
        N = 1;
    }
    BranchProbability LEP = BranchProbability(N, D);
    LoopExitProb.insert(std::make_pair(Head, LEP));
    DEBUG(dbgs() << "LoopExitProb[" << getBlockName(Head) << "] = " << LEP
                 << " from 1 - " << BackFreq << " / " << getBlockFreq(Head)
                 << ".\n");
  }

  friend class BlockFrequencyInfo;
  friend class MachineBlockFrequencyInfo;

  BlockFrequencyImpl() : EntryFreq(BlockFrequency::getEntryFrequency()) { }

  void doFunction(FunctionT *fn, BlockProbInfoT *bpi) {
    Fn = fn;
    BPI = bpi;

    // Clear everything.
    RPO.clear();
    POT.clear();
    LoopExitProb.clear();
    Freqs.clear();

    BlockT *EntryBlock = fn->begin();

    std::copy(po_begin(EntryBlock), po_end(EntryBlock), std::back_inserter(POT));

    unsigned RPOidx = 0;
    for (rpot_iterator I = rpot_begin(), E = rpot_end(); I != E; ++I) {
      BlockT *BB = *I;
      RPO[BB] = ++RPOidx;
      DEBUG(dbgs() << "RPO[" << getBlockName(BB) << "] = " << RPO[BB] << "\n");
    }

    // Travel over all blocks in postorder.
    for (pot_iterator I = pot_begin(), E = pot_end(); I != E; ++I) {
      BlockT *BB = *I;
      BlockT *LastTail = 0;
      DEBUG(dbgs() << "POT: " << getBlockName(BB) << "\n");

      for (typename GT::ChildIteratorType
           PI = GraphTraits< Inverse<BlockT *> >::child_begin(BB),
           PE = GraphTraits< Inverse<BlockT *> >::child_end(BB);
           PI != PE; ++PI) {

        BlockT *Pred = *PI;
        if (isBackedge(Pred, BB) && (!LastTail || RPO[Pred] > RPO[LastTail]))
          LastTail = Pred;
      }

      if (LastTail)
        doLoop(BB, LastTail);
    }

    // At the end assume the whole function as a loop, and travel over it once
    // again.
    doLoop(*(rpot_begin()), *(pot_begin()));
  }

public:
  /// getBlockFreq - Return block frequency. Return 0 if we don't have it.
  BlockFrequency getBlockFreq(const BlockT *BB) const {
    typename DenseMap<const BlockT *, BlockFrequency>::const_iterator
      I = Freqs.find(BB);
    if (I != Freqs.end())
      return I->second;
    return 0;
  }

  void print(raw_ostream &OS) const {
    OS << "\n\n---- Block Freqs ----\n";
    for (typename FunctionT::iterator I = Fn->begin(), E = Fn->end(); I != E;) {
      BlockT *BB = I++;
      OS << " " << getBlockName(BB) << " = " << getBlockFreq(BB) << "\n";

      for (typename GraphTraits<BlockT *>::ChildIteratorType
           SI = GraphTraits<BlockT *>::child_begin(BB),
           SE = GraphTraits<BlockT *>::child_end(BB); SI != SE; ++SI) {
        BlockT *Succ = *SI;
        OS << "  " << getBlockName(BB) << " -> " << getBlockName(Succ)
           << " = " << getEdgeFreq(BB, Succ) << "\n";
      }
    }
  }

  void dump() const {
    print(dbgs());
  }
};

}

#endif


text:
<?php

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ValidCustomer extends Constraint
{
    public $unknownCustomerCodeMessage = 'error.unknown_customer_code';
    public $emptyNameMessage = 'error.empty_name';
    public $emptyVatNumberMessage = 'error.empty_vat_number';
    public $invalidVatNumberMessage = 'error.invalid_vat_number';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}


text:
<resources>

    <string name="picker_custom_lunar">LunarTimePicker</string>

    <string name="picker_time">TimePicker</string>
    <string name="picker_province">OptionsPicker</string>

    <string name="picker_custom_time">CustomLayoutTimePicker</string>
    <string name="picker_custom_province">CustomLayoutOptionsPicker</string>
    <string name="picker_custom_parent">CustomParentView</string>

    <string name="picker_non_linkage">OptionsPicker(Non-Linkage)</string>
    <string name="picker_json_parse_sample">AreaDataParseSample</string>

    <string name="picker_text_parse">Parse Data</string>
    <string name="picker_text_show">Show OptionsPicker</string>
</resources>


text:
from datetime import date

from app.models import RepExercisesHistory, RepExercisesTaxonomy, Users
from app.service import RepExercisesHistoryService, RepExercisesTaxonomyService, UsersService
from app.service_tests.service_test_case import ServiceTestCase

class RepExercisesHistoryTests(ServiceTestCase):
    def setUp(self):
        super(RepExercisesHistoryTests, self).setUp()

        # sample users for tests
        user_1 = Users('p@p.p', 'Patrick', 'pass')
        user_2 = Users('j@j.j', 'Jaytrick', 'pass')
        UsersService.add_user_to_database(user_1)
        UsersService.add_user_to_database(user_2)

        # sample exercises for tests
        RepExercisesTaxonomyService.add_entry_to_db(
            RepExercisesTaxonomy(
                name='test_rows',
                is_back=True,
                is_chest=False,
                is_shoulders=True,
                is_biceps=True,
                is_triceps=False,
                is_legs=False,
                is_core=True,
                is_balance=False,
                is_cardio=False,
                is_weight_per_hand=True
            )
        )
        RepExercisesTaxonomyService.add_entry_to_db(
            RepExercisesTaxonomy(
                name='test_press',
                is_back=False,
                is_chest=True,
                is_shoulders=True,
                is_biceps=False,
                is_triceps=True,
                is_legs=False,
                is_core=True,
                is_balance=False,
                is_cardio=False,
                is_weight_per_hand=True
            )
        )

    # add_entry_to_db tests #
    def test_add_entry_to_db(self):
        entry_to_add = RepExercisesHistory(
            user_id=2,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1990, month=12, day=23)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_to_add)
        actual_entry = list(RepExercisesHistory.query.all())[0]
        self.assertEqual(actual_entry, entry_to_add)

    # get_list_of_all_history tests #
    def test_get_list_of_all_history_no_history(self):
        expected_list = []
        actual_list = RepExercisesHistoryService.get_list_of_all_history()
        self.assertListEqual(actual_list, expected_list)

    def test_get_list_of_all_history_one_entry(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1990, month=12, day=23)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)

        expected_list = [entry_1]
        actual_list = RepExercisesHistoryService.get_list_of_all_history()

        self.assertListEqual(actual_list, expected_list)

    def test_get_list_of_all_history_multiple_entries(self):
        expected_list = [
            RepExercisesHistory(
                user_id=1,
                exercise_id=1,
                sets=11,
                reps=23,
                weight=12.5,
                date=date(year=1990, month=12, day=23)
            ),
            RepExercisesHistory(
                user_id=2,
                exercise_id=2,
                sets=11,
                reps=23,
                weight=12.5,
                date=date(year=1890, month=12, day=23)
            ),
            RepExercisesHistory(
                user_id=2,
                exercise_id=1,
                sets=11,
                reps=23,
                weight=12.5,
                date=date(year=1997, month=12, day=23)
            )
        ]

        # add in entries
        RepExercisesHistoryService.add_entry_to_db(expected_list[0])
        RepExercisesHistoryService.add_entry_to_db(expected_list[1])
        RepExercisesHistoryService.add_entry_to_db(expected_list[2])

        actual_list = RepExercisesHistoryService.get_list_of_all_history()

        # no guarantee about ordering is made
        self.assertListEqual(sorted(actual_list, key=self._sort_key_date),
                             sorted(expected_list, key=self._sort_key_date))

    # get_list_of_users_exercises tests #
    def test_get_list_of_users_exercises_no_exercises(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1990, month=12, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12,
            date=date(year=1990, month=11, day=23)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)

        expected_list = []
        actual_list = RepExercisesHistoryService.get_list_of_users_exercises(1)

        self.assertListEqual(actual_list, expected_list)

    def test_get_list_of_users_exercises_pulls_correct_exercises(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=29)
        )
        entry_3 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=25,
            weight=12.5,
            date=date(year=1890, month=11, day=13)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)
        RepExercisesHistoryService.add_entry_to_db(entry_3)

        expected_results = [entry_1, entry_3]  # entry_2 was done by a different user
        actual_results = RepExercisesHistoryService.get_list_of_users_exercises(2)

        # no guarantee about ordering is made
        self.assertListEqual(sorted(actual_results, key=self._sort_key_date),
                             sorted(expected_results, key=self._sort_key_date))

    # get_user_history_by_exercise tests #
    def test_get_user_history_by_exercise_empty_db(self):
        expected_results = []
        actual_results = RepExercisesHistoryService.get_user_history_by_exercise(user_id=1, exercise_id=2)

        self.assertListEqual(actual_results, expected_results)

    def test_get_user_history_by_exercise_user_not_done_that_exercise(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=29)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)

        expected_results = []
        actual_results = RepExercisesHistoryService.get_user_history_by_exercise(user_id=1, exercise_id=2)

        self.assertListEqual(actual_results, expected_results)

    def test_get_user_history_by_exercise_user_did_that_exercise(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=29)
        )
        entry_3 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1892, month=11, day=29)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)
        RepExercisesHistoryService.add_entry_to_db(entry_3)

        expected_results = [entry_1, entry_3]
        actual_results = RepExercisesHistoryService.get_user_history_by_exercise(user_id=2, exercise_id=2)

        # no guarantee about ordering is made
        self.assertListEqual(sorted(actual_results, key=self._sort_key_date),
                             sorted(expected_results, key=self._sort_key_date))

    def test_get_user_history_by_exercise_different_user_did_that_exercise(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=29)
        )
        entry_3 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1892, month=11, day=29)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)
        RepExercisesHistoryService.add_entry_to_db(entry_3)

        expected_results = []
        actual_results = RepExercisesHistoryService.get_user_history_by_exercise(1, 2)

        self.assertListEqual(actual_results, expected_results)

    # get_user_history_by_date tests #
    def test_get_user_history_by_date_empty_db(self):
        expected_results = []
        actual_results = RepExercisesHistoryService.get_user_history_by_date(user_id=1, exercise_date='2017-07-20')

        self.assertListEqual(actual_results, expected_results)

    def test_get_user_history_by_date_no_match(self):
        entry_1 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=29)
        )
        entry_3 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1892, month=11, day=29)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)
        RepExercisesHistoryService.add_entry_to_db(entry_3)

        expected_results = []
        actual_results = RepExercisesHistoryService.get_user_history_by_date(user_id=1, exercise_date='1892-11-23')
        self.assertListEqual(actual_results, expected_results)

    def test_get_user_history_by_date_match(self):
        entry_1 = RepExercisesHistory(
            user_id=1,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_2 = RepExercisesHistory(
            user_id=1,
            exercise_id=1,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1890, month=11, day=23)
        )
        entry_3 = RepExercisesHistory(
            user_id=2,
            exercise_id=2,
            sets=11,
            reps=23,
            weight=12.5,
            date=date(year=1892, month=11, day=29)
        )

        RepExercisesHistoryService.add_entry_to_db(entry_1)
        RepExercisesHistoryService.add_entry_to_db(entry_2)
        RepExercisesHistoryService.add_entry_to_db(entry_3)

        expected_results = [entry_1, entry_2]
        actual_results = RepExercisesHistoryService.get_user_history_by_date(user_id=1, exercise_date='1890-11-23')

        self.assertListEqual(sorted(actual_results, key=self._sort_key_exercise_id),
                             sorted(expected_results, key=self._sort_key_exercise_id))

    @staticmethod
    def _sort_key_date(x):
        return x.date

    @staticmethod
    def _sort_key_exercise_id(x):
        return x.exercise_id


text:
import { Factory } from 'miragejs';

export default Factory.extend({
  afterCreate(session) {
    if (!session.user) {
      throw new Error('Missing `user` relationship');
    }
  },
});


text:
<?php

final class PhabricatorStorageSetupCheck extends PhabricatorSetupCheck {

  public function getDefaultGroup() {
    return self::GROUP_OTHER;
  }

  /**
   * @phutil-external-symbol class PhabricatorStartup
   */
  protected function executeChecks() {
    $engines = PhabricatorFileStorageEngine::loadWritableChunkEngines();
    $chunk_engine_active = (bool)$engines;

    $this->checkS3();

    if (!$chunk_engine_active) {
      $doc_href = PhabricatorEnv::getDocLink('Configuring File Storage');

      $message = pht(
        'Large file storage has not been configured, which will limit '.
        'the maximum size of file uploads. See %s for '.
        'instructions on configuring uploads and storage.',
        phutil_tag(
          'a',
          array(
            'href' => $doc_href,
            'target' => '_blank',
          ),
          pht('Configuring File Storage')));

      $this
        ->newIssue('large-files')
        ->setShortName(pht('Large Files'))
        ->setName(pht('Large File Storage Not Configured'))
        ->setMessage($message);
    }

    $post_max_size = ini_get('post_max_size');
    if ($post_max_size && ((int)$post_max_size > 0)) {
      $post_max_bytes = phutil_parse_bytes($post_max_size);
      $post_max_need = (32 * 1024 * 1024);
      if ($post_max_need > $post_max_bytes) {
        $summary = pht(
          'Set %s in your PHP configuration to at least 32MB '.
          'to support large file uploads.',
          phutil_tag('tt', array(), 'post_max_size'));

        $message = pht(
          'Adjust %s in your PHP configuration to at least 32MB. When '.
          'set to smaller value, large file uploads may not work properly.',
          phutil_tag('tt', array(), 'post_max_size'));

        $this
          ->newIssue('php.post_max_size')
          ->setName(pht('PHP post_max_size Not Configured'))
          ->setSummary($summary)
          ->setMessage($message)
          ->setGroup(self::GROUP_PHP)
          ->addPHPConfig('post_max_size');
      }
    }

    // This is somewhat arbitrary, but make sure we have enough headroom to
    // upload a default file at the chunk threshold (8MB), which may be
    // base64 encoded, then JSON encoded in the request, and may need to be
    // held in memory in the raw and as a query string.
    $need_bytes = (64 * 1024 * 1024);

    $memory_limit = PhabricatorStartup::getOldMemoryLimit();
    if ($memory_limit && ((int)$memory_limit > 0)) {
      $memory_limit_bytes = phutil_parse_bytes($memory_limit);
      $memory_usage_bytes = memory_get_usage();

      $available_bytes = ($memory_limit_bytes - $memory_usage_bytes);

      if ($need_bytes > $available_bytes) {
        $summary = pht(
          'Your PHP memory limit is configured in a way that may prevent '.
          'you from uploading large files or handling large requests.');

        $message = pht(
          'When you upload a file via drag-and-drop or the API, chunks must '.
          'be buffered into memory before being written to permanent '.
          'storage. Phabricator needs memory available to store these '.
          'chunks while they are uploaded, but PHP is currently configured '.
          'to severly limit the available memory.'.
          "\n\n".
          'PHP processes currently have very little free memory available '.
          '(%s). To work well, processes should have at least %s.'.
          "\n\n".
          '(Note that the application itself must also fit in available '.
          'memory, so not all of the memory under the memory limit is '.
          'available for running workloads.)'.
          "\n\n".
          "The easiest way to resolve this issue is to set %s to %s in your ".
          "PHP configuration, to disable the memory limit. There is ".
          "usually little or no value to using this option to limit ".
          "Phabricator process memory.".
          "\n\n".
          "You can also increase the limit or ignore this issue and accept ".
          "that you may encounter problems uploading large files and ".
          "processing large requests.",
          phutil_format_bytes($available_bytes),
          phutil_format_bytes($need_bytes),
          phutil_tag('tt', array(), 'memory_limit'),
          phutil_tag('tt', array(), '-1'));

        $this
          ->newIssue('php.memory_limit.upload')
          ->setName(pht('Memory Limit Restricts File Uploads'))
          ->setSummary($summary)
          ->setMessage($message)
          ->setGroup(self::GROUP_PHP)
          ->addPHPConfig('memory_limit')
          ->addPHPConfigOriginalValue('memory_limit', $memory_limit);
      }
    }

    $local_path = PhabricatorEnv::getEnvConfig('storage.local-disk.path');
    if (!$local_path) {
      return;
    }

    if (!Filesystem::pathExists($local_path) ||
        !is_readable($local_path) ||
        !is_writable($local_path)) {

      $message = pht(
        'Configured location for storing uploaded files on disk ("%s") does '.
        'not exist, or is not readable or writable. Verify the directory '.
        'exists and is readable and writable by the webserver.',
        $local_path);

      $this
        ->newIssue('config.storage.local-disk.path')
        ->setShortName(pht('Local Disk Storage'))
        ->setName(pht('Local Disk Storage Not Readable/Writable'))
        ->setMessage($message)
        ->addPhabricatorConfig('storage.local-disk.path');
    }
  }

  private function checkS3() {
    $access_key = PhabricatorEnv::getEnvConfig('amazon-s3.access-key');
    $secret_key = PhabricatorEnv::getEnvConfig('amazon-s3.secret-key');
    $region = PhabricatorEnv::getEnvConfig('amazon-s3.region');
    $endpoint = PhabricatorEnv::getEnvConfig('amazon-s3.endpoint');

    $how_many = 0;

    if (strlen($access_key)) {
      $how_many++;
    }

    if (strlen($secret_key)) {
      $how_many++;
    }

    if (strlen($region)) {
      $how_many++;
    }

    if (strlen($endpoint)) {
      $how_many++;
    }

    // Nothing configured, no issues here.
    if ($how_many === 0) {
      return;
    }

    // Everything configured, no issues here.
    if ($how_many === 4) {
      return;
    }

    $message = pht(
      'File storage in Amazon S3 has been partially configured, but you are '.
      'missing some required settings. S3 will not be available to store '.
      'files until you complete the configuration. Either configure S3 fully '.
      'or remove the partial configuration.');

    $this->newIssue('storage.s3.partial-config')
      ->setShortName(pht('S3 Partially Configured'))
      ->setName(pht('Amazon S3 is Only Partially Configured'))
      ->setMessage($message)
      ->addPhabricatorConfig('amazon-s3.access-key')
      ->addPhabricatorConfig('amazon-s3.secret-key')
      ->addPhabricatorConfig('amazon-s3.region')
      ->addPhabricatorConfig('amazon-s3.endpoint');
  }

}


text:
#ifndef __MEM_VV_STORE_H__
#define __MEM_VV_STORE_H__

#include "vv_store.h"
#include "mem_vec_store.h"

namespace fm
{

class local_vv_store;

namespace detail
{

class matrix_store;

class mem_vv_store: public vv_store
{
	const smp_vec_store &get_mem_data() const {
		return static_cast<const smp_vec_store &>(get_data());
	}
	smp_vec_store &get_mem_data() {
		return static_cast<smp_vec_store &>(get_data());
	}
protected:
	mem_vv_store(const scalar_type &type): vv_store(type, true) {
	}
	mem_vv_store(const std::vector<off_t> &offs,
			mem_vec_store::ptr vec): vv_store(offs, vec) {
	}
public:
	typedef std::shared_ptr<mem_vv_store> ptr;
	typedef std::shared_ptr<const mem_vv_store> const_ptr;

	static ptr cast(vec_store::ptr store);

	static ptr create(const scalar_type &type) {
		return ptr(new mem_vv_store(type));
	}

	static ptr create(const std::vector<off_t> &offs, const scalar_type &type) {
		smp_vec_store::ptr vec = smp_vec_store::create(offs.back(), type);
		return ptr(new mem_vv_store(offs, vec));
	}

	static ptr create(const detail::simple_raw_array &data,
			const std::vector<off_t> &offs, const scalar_type &type) {
		assert(offs.front() == 0 && (size_t) offs.back() == data.get_num_bytes());
		smp_vec_store::ptr vec = smp_vec_store::create(data, type);
		return ptr(new mem_vv_store(offs, vec));
	}

	static ptr create(const std::vector<off_t> &offs, mem_vec_store::ptr store) {
		return ptr(new mem_vv_store(offs, store));
	}

	virtual void set_data(const set_vv_operate &op);

	char *get_raw_arr() {
		return get_mem_data().get_raw_arr();
	}
	const char *get_raw_arr() const {
		return get_mem_data().get_raw_arr();
	}

	char*get_raw_arr(off_t idx) {
		return get_raw_arr() + get_vec_off(idx);
	}

	const char*get_raw_arr(off_t idx) const {
		return get_raw_arr() + get_vec_off(idx);
	}

	virtual vec_store::ptr shallow_copy() {
		// TODO the vector offsets may also be very large.
		return mem_vv_store::ptr(new mem_vv_store(*this));
	}
	virtual vec_store::const_ptr shallow_copy() const {
		// TODO the vector offsets may also be very large.
		return mem_vv_store::ptr(new mem_vv_store(*this));
	}
};

}

}

#endif


text:
use syntect::parsing::{SyntaxSet, ParseState, ScopeStackOp, ScopeStack};
use syntect::highlighting::{ScopeSelector, ScopeSelectors};
use syntect::easy::{ScopeRegionIterator};

use std::path::Path;
use std::io::{BufRead, BufReader};
use std::fs::File;
use walkdir::{DirEntry, WalkDir};
use std::str::FromStr;

#[derive(Debug)]
struct Selectors {
    comment: ScopeSelector,
    doc_comment: ScopeSelectors,
    function: ScopeSelector,
    types: ScopeSelectors,
}

impl Default for Selectors {
    fn default() -> Selectors {
        Selectors {
            comment: ScopeSelector::from_str("comment - comment.block.attribute").unwrap(),
            doc_comment: ScopeSelectors::from_str("comment.line.documentation, comment.block.documentation").unwrap(),
            function: ScopeSelector::from_str("entity.name.function").unwrap(),
            types: ScopeSelectors::from_str("entity.name.class, entity.name.struct, entity.name.enum, entity.name.type").unwrap(),
        }
    }
}

#[derive(Debug, Default)]
struct Stats {
    selectors: Selectors,
    files: usize,
    functions: usize,
    types: usize,
    lines: usize,
    chars: usize,
    code_lines: usize,
    comment_lines: usize,
    comment_chars: usize,
    comment_words: usize,
    doc_comment_lines: usize,
    doc_comment_words: usize,
}

fn print_stats(stats: &Stats) {
    println!();
    println!("################## Stats ###################");
    println!("File count:                           {:>6}", stats.files);
    println!("Total characters:                     {:>6}", stats.chars);
    println!();
    println!("Function count:                       {:>6}", stats.functions);
    println!("Type count (structs, enums, classes): {:>6}", stats.types);
    println!();
    println!("Code lines (traditional SLOC):        {:>6}", stats.code_lines);
    println!("Total lines (w/ comments & blanks):   {:>6}", stats.lines);
    println!("Comment lines (comment but no code):  {:>6}", stats.comment_lines);
    println!("Blank lines (lines-blank-comment):    {:>6}", stats.lines-stats.code_lines-stats.comment_lines);
    println!();
    println!("Lines with a documentation comment:   {:>6}", stats.doc_comment_lines);
    println!("Total words written in doc comments:  {:>6}", stats.doc_comment_words);
    println!("Total words written in all comments:  {:>6}", stats.comment_words);
    println!("Characters of comment:                {:>6}", stats.comment_chars);
}

fn is_ignored(entry: &DirEntry) -> bool {
    entry.file_name()
         .to_str()
         .map(|s| s.starts_with('.') && s.len() > 1 || s.ends_with(".md"))
         .unwrap_or(false)
}

fn count_line(ops: &[(usize, ScopeStackOp)], line: &str, stack: &mut ScopeStack, stats: &mut Stats) {
    stats.lines += 1;

    let mut line_has_comment = false;
    let mut line_has_doc_comment = false;
    let mut line_has_code = false;
    for (s, op) in ScopeRegionIterator::new(ops, line) {
        stack.apply(op).unwrap();
        if s.is_empty() { // in this case we don't care about blank tokens
            continue;
        }
        if stats.selectors.comment.does_match(stack.as_slice()).is_some() {
            let words = s.split_whitespace().filter(|w| w.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '\'')).count();
            if stats.selectors.doc_comment.does_match(stack.as_slice()).is_some() {
                line_has_doc_comment = true;
                stats.doc_comment_words += words;
            }
            stats.comment_chars += s.len();
            stats.comment_words += words;
            line_has_comment = true;
        } else if !s.chars().all(|c| c.is_whitespace()) {
            line_has_code = true;
        }
        if stats.selectors.function.does_match(stack.as_slice()).is_some() {
            stats.functions += 1;
        }
        if stats.selectors.types.does_match(stack.as_slice()).is_some() {
            stats.types += 1;
        }
    }
    if line_has_comment && !line_has_code {
        stats.comment_lines += 1;
    }
    if line_has_doc_comment {
        stats.doc_comment_lines += 1;
    }
    if line_has_code {
        stats.code_lines += 1;
    }
}

fn count(ss: &SyntaxSet, path: &Path, stats: &mut Stats) {
    let syntax = match ss.find_syntax_for_file(path).unwrap_or(None) {
        Some(syntax) => syntax,
        None => return
    };
    stats.files += 1;
    let mut state = ParseState::new(syntax);

    let f = File::open(path).unwrap();
    let mut reader = BufReader::new(f);
    let mut line = String::new();
    let mut stack = ScopeStack::new();
    while reader.read_line(&mut line).unwrap() > 0 {
        {
            let ops = state.parse_line(&line, ss).unwrap();
            stats.chars += line.len();
            count_line(&ops, &line, &mut stack, stats);
        }
        line.clear();
    }
}

fn main() {
    let ss = SyntaxSet::load_defaults_newlines(); // note we load the version with newlines

    let args: Vec<String> = std::env::args().collect();
    let path = if args.len() < 2 {
        "."
    } else {
        &args[1]
    };

    println!("################## Files ###################");
    let mut stats = Stats::default();
    let walker = WalkDir::new(path).into_iter();
    for entry in walker.filter_entry(|e| !is_ignored(e)) {
        let entry = entry.unwrap();
        if entry.file_type().is_file() {
            println!("{}", entry.path().display());
            count(&ss, entry.path(), &mut stats);
        }
    }

    // println!("{:?}", stats);
    print_stats(&stats);
}


text:
"use strict";
var Event = function(type, options) {
  this.type = type;

  for (var option in options) {
    if (!options.hasOwnProperty(option)) { continue; }

    this[option] = options[option];
  }
};

var indexOf = function(callbacks, callback) {
  for (var i=0, l=callbacks.length; i<l; i++) {
    if (callbacks[i][0] === callback) { return i; }
  }

  return -1;
};

var callbacksFor = function(object) {
  var callbacks = object._promiseCallbacks;

  if (!callbacks) {
    callbacks = object._promiseCallbacks = {};
  }

  return callbacks;
};

var EventTarget = {
  mixin: function(object) {
    object.on = this.on;
    object.off = this.off;
    object.trigger = this.trigger;
    return object;
  },

  on: function(eventNames, callback, binding) {
    var allCallbacks = callbacksFor(this), callbacks, eventName;
    eventNames = eventNames.split(/\s+/);
    binding = binding || this;

    while (eventName = eventNames.shift()) {
      callbacks = allCallbacks[eventName];

      if (!callbacks) {
        callbacks = allCallbacks[eventName] = [];
      }

      if (indexOf(callbacks, callback) === -1) {
        callbacks.push([callback, binding]);
      }
    }
  },

  off: function(eventNames, callback) {
    var allCallbacks = callbacksFor(this), callbacks, eventName, index;
    eventNames = eventNames.split(/\s+/);

    while (eventName = eventNames.shift()) {
      if (!callback) {
        allCallbacks[eventName] = [];
        continue;
      }

      callbacks = allCallbacks[eventName];

      index = indexOf(callbacks, callback);

      if (index !== -1) { callbacks.splice(index, 1); }
    }
  },

  trigger: function(eventName, options) {
    var allCallbacks = callbacksFor(this),
        callbacks, callbackTuple, callback, binding, event;

    if (callbacks = allCallbacks[eventName]) {
      // Don't cache the callbacks.length since it may grow
      for (var i=0; i<callbacks.length; i++) {
        callbackTuple = callbacks[i];
        callback = callbackTuple[0];
        binding = callbackTuple[1];

        if (typeof options !== 'object') {
          options = { detail: options };
        }

        event = new Event(eventName, options);
        callback.call(binding, event);
      }
    }
  }
};

exports.EventTarget = EventTarget;


text:
import 'vs/css!./media/hover';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorHoverBackground, editorHoverBorder, textLinkForeground, editorHoverForeground, editorHoverStatusBarBackground, textCodeBlockBackground } from 'vs/platform/theme/common/colorRegistry';
import { IHoverService, IHoverOptions } from 'vs/workbench/services/hover/browser/hover';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { HoverWidget } from 'vs/workbench/services/hover/browser/hoverWidget';
import { IContextViewProvider, IDelegate } from 'vs/base/browser/ui/contextview/contextview';

export class HoverService implements IHoverService {
	declare readonly _serviceBrand: undefined;

	private _currentHoverOptions: IHoverOptions | undefined;

	constructor(
		@IInstantiationService private readonly _instantiationService: IInstantiationService,
		@IContextViewService private readonly _contextViewService: IContextViewService
	) {
	}

	showHover(options: IHoverOptions, focus?: boolean): void {
		if (this._currentHoverOptions === options) {
			return;
		}
		this._currentHoverOptions = options;

		const hover = this._instantiationService.createInstance(HoverWidget, options);
		hover.onDispose(() => this._currentHoverOptions = undefined);
		const provider = this._contextViewService as IContextViewProvider;
		provider.showContextView(new HoverContextViewDelegate(hover, focus));
		hover.onRequestLayout(() => provider.layout());
	}

	hideHover(): void {
		if (!this._currentHoverOptions) {
			return;
		}
		this._currentHoverOptions = undefined;
		this._contextViewService.hideContextView();
	}
}

class HoverContextViewDelegate implements IDelegate {

	get anchorPosition() {
		return this._hover.anchor;
	}

	constructor(
		private readonly _hover: HoverWidget,
		private readonly _focus: boolean = false
	) {
	}

	render(container: HTMLElement) {
		this._hover.render(container);
		if (this._focus) {
			this._hover.focus();
		}
		return this._hover;
	}

	getAnchor() {
		return {
			x: this._hover.x,
			y: this._hover.y
		};
	}

	layout() {
		this._hover.layout();
	}
}

registerSingleton(IHoverService, HoverService, true);

registerThemingParticipant((theme, collector) => {
	const hoverBackground = theme.getColor(editorHoverBackground);
	if (hoverBackground) {
		collector.addRule(`.monaco-workbench .workbench-hover { background-color: ${hoverBackground}; }`);
	}
	const hoverBorder = theme.getColor(editorHoverBorder);
	if (hoverBorder) {
		collector.addRule(`.monaco-workbench .workbench-hover { border: 1px solid ${hoverBorder}; }`);
		collector.addRule(`.monaco-workbench .workbench-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
		collector.addRule(`.monaco-workbench .workbench-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
		collector.addRule(`.monaco-workbench .workbench-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
	}
	const link = theme.getColor(textLinkForeground);
	if (link) {
		collector.addRule(`.monaco-workbench .workbench-hover a { color: ${link}; }`);
	}
	const hoverForeground = theme.getColor(editorHoverForeground);
	if (hoverForeground) {
		collector.addRule(`.monaco-workbench .workbench-hover { color: ${hoverForeground}; }`);
	}
	const actionsBackground = theme.getColor(editorHoverStatusBarBackground);
	if (actionsBackground) {
		collector.addRule(`.monaco-workbench .workbench-hover .hover-row .actions { background-color: ${actionsBackground}; }`);
	}
	const codeBackground = theme.getColor(textCodeBlockBackground);
	if (codeBackground) {
		collector.addRule(`.monaco-workbench .workbench-hover code { background-color: ${codeBackground}; }`);
	}
});


text:
namespace k8s.Util.Common
{
    public static class Config
    {
        public static string ServiceAccountCaPath => KubernetesClientConfiguration.ServiceAccountPath + "/ca.crt";
        public static string ServiceAccountTokenPath => KubernetesClientConfiguration.ServiceAccountPath + "/token";
        public static string ServiceAccountNamespacePath => KubernetesClientConfiguration.ServiceAccountPath + "/namespace";
        public static string EnvKubeconfig => "KUBECONFIG";
        public static string EnvServiceHost => "KUBERNETES_SERVICE_HOST";
        public static string EnvServicePort => "KUBERNETES_SERVICE_PORT";

        // The last resort host to try
        public static string DefaultFallbackHost => "http://localhost:8080";
    }
}


text:
package org.eclipse.swt.snippets;

/*
 * Button example snippet: create a tri-state button (toggle three states)
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 *
 * @since 3.5
 */
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class Snippet315 {
	public static void main(String[] args) {
		Display display = new Display ();
		Shell shell = new Shell (display);
		shell.setLayout(new GridLayout());
		final Button button = new Button (shell, SWT.CHECK);
		button.setLayoutData(new GridData(GridData.GRAB_VERTICAL | GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_CENTER));
		button.setText ("Tri-state");
		/* Make the button toggle between three states */
		button.addListener (SWT.Selection, new Listener() {
			@Override
			public void handleEvent (Event e) {
				if (button.getSelection()) {
					if (!button.getGrayed()) {
						button.setGrayed(true);
					}
				} else {
					if (button.getGrayed()) {
						button.setGrayed(false);
						button.setSelection (true);
					}
				}
			}
		});
		/* Read the tri-state button (application code) */
		button.addListener (SWT.Selection, new Listener() {
			@Override
			public void handleEvent (Event e) {
				if (button.getGrayed()) {
					System.out.println("Grayed");
				} else {
					if (button.getSelection()) {
						System.out.println("Selected");
					} else {
						System.out.println("Not selected");
					}
				}
			}
		});
		shell.setSize(300, 300);
		shell.open ();
		while (!shell.isDisposed ()) {
			if (!display.readAndDispatch ()) display.sleep ();
		}
		display.dispose ();
	}
}


text:
package logger

import (
	"fmt"
	"log"
	"os"
)

// Logger is the server logger
type Logger struct {
	logger     *log.Logger
	debug      bool
	trace      bool
	infoLabel  string
	errorLabel string
	fatalLabel string
	debugLabel string
	traceLabel string
}

// NewStdLogger creates a logger with output directed to Stderr
func NewStdLogger(time, debug, trace, colors, pid bool) *Logger {
	flags := 0
	if time {
		flags = log.LstdFlags | log.Lmicroseconds
	}

	pre := ""
	if pid {
		pre = pidPrefix()
	}

	l := &Logger{
		logger: log.New(os.Stderr, pre, flags),
		debug:  debug,
		trace:  trace,
	}

	if colors {
		setColoredLabelFormats(l)
	} else {
		setPlainLabelFormats(l)
	}

	return l
}

// NewFileLogger creates a logger with output directed to a file
func NewFileLogger(filename string, time, debug, trace, pid bool) *Logger {
	fileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
	f, err := os.OpenFile(filename, fileflags, 0660)
	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}

	flags := 0
	if time {
		flags = log.LstdFlags | log.Lmicroseconds
	}

	pre := ""
	if pid {
		pre = pidPrefix()
	}

	l := &Logger{
		logger: log.New(f, pre, flags),
		debug:  debug,
		trace:  trace,
	}

	setPlainLabelFormats(l)
	return l
}

// Generate the pid prefix string
func pidPrefix() string {
	return fmt.Sprintf("[%d] ", os.Getpid())
}

func setPlainLabelFormats(l *Logger) {
	l.infoLabel = "[INF] "
	l.debugLabel = "[DBG] "
	l.errorLabel = "[ERR] "
	l.fatalLabel = "[FTL] "
	l.traceLabel = "[TRC] "
}

func setColoredLabelFormats(l *Logger) {
	colorFormat := "[\x1b[%dm%s\x1b[0m] "
	l.infoLabel = fmt.Sprintf(colorFormat, 32, "INF")
	l.debugLabel = fmt.Sprintf(colorFormat, 36, "DBG")
	l.errorLabel = fmt.Sprintf(colorFormat, 31, "ERR")
	l.fatalLabel = fmt.Sprintf(colorFormat, 31, "FTL")
	l.traceLabel = fmt.Sprintf(colorFormat, 33, "TRC")
}

// Noticef logs a notice statement
func (l *Logger) Noticef(format string, v ...interface{}) {
	l.logger.Printf(l.infoLabel+format, v...)
}

// Errorf logs an error statement
func (l *Logger) Errorf(format string, v ...interface{}) {
	l.logger.Printf(l.errorLabel+format, v...)
}

// Fatalf logs a fatal error
func (l *Logger) Fatalf(format string, v ...interface{}) {
	l.logger.Fatalf(l.fatalLabel+format, v...)
}

// Debugf logs a debug statement
func (l *Logger) Debugf(format string, v ...interface{}) {
	if l.debug {
		l.logger.Printf(l.debugLabel+format, v...)
	}
}

// Tracef logs a trace statement
func (l *Logger) Tracef(format string, v ...interface{}) {
	if l.trace {
		l.logger.Printf(l.traceLabel+format, v...)
	}
}


text:
Game = new Meteor.Collection('Games');

Game.CreateNew = function(users, holes, course){

	var players = [];

	users.forEach(function(el,ix){
		players.push({
			_id : el._id,
			id : el.id,
			score : 0,
			strokes : 0,
			name : el.name
		});
	});

	return {
		completed : false,
		created : (new Date()),
		courseName : course.name,
		course : course._id,
		players : players,
		holes : holes,
		createdBy : Meteor.userId()

	};
};

Game.InsertTemplate = function(gameObj){
	return Game.insert(gameObj);
};

Game.SaveUpdate = function(game){
	Game.update(game._id, { $set : {
			players : game.players,
			holes : game.holes
		}
	});
};

Game.AddPlayer = function(game, user){
	var player = {
			score : 0,
			strokes: 0
		};

	if(user._id){
		player._id = user._id;
		player.id = user._id;
		player.name = user.username;
	} else {
		player.id = Math.random().toString(36).substring(7);
		player.name = user;
	}

	game.players.push(player);

	game.holes.forEach(function(hole){
		hole.players.push({
			id : player.id,
			score : null
		});
	});

	Game.SaveUpdate(game);

};

Game.RemovePlayer = function(game, playerId){
	var currentUserId =  Meteor.userId();

	if(game.createdBy === currentUserId || playerId === currentUserId){

		game.players.forEach(function(el, ix, players){
			if(el.id === playerId){
				players.splice(ix, 1);
			}
		});

		game.holes.forEach(function(hole){
			hole.players.forEach(function(holePlayer, ix, holePlayers){
				if(holePlayer.id === playerId){
					holePlayers.splice(ix, 1);
				}
			});
		});

		Game.SaveUpdate(game);

	} else {
		return false;
	}
};

Game.SaveUserScore = function(game, playerId){
	var player;

	game.players.some(function(p){
		if(p.id === playerId){
			player = p;
			return true;
		}
	});

	if(player){
		Game.UpdateScoreForUser(game, player);
	}

	Game.SaveUpdate(game);
};

Game.UpdateAllScores = function(game){

	game.players.forEach(function(p){
		Game.UpdateScoreForUser(game, p);
	});

};

Game.UpdateScoreForUser = function(game, player){
	var totalPar = 0;
	player.strokes = 0;

	game.holes.forEach(function(hole){
		hole.players.some(function(hp){
			if(hp.id === player.id && hp.score){
				player.strokes += hp.score;
				totalPar += hole.par;
				return true;
			}
		});
	});

	player.score = player.strokes - totalPar;
};

Game.FinishGame = function(game){
	// Finalize Scores
	Game.UpdateAllScores(game);

	// Save final scores to Users
	game.players.forEach(function(p){
		if(p._id){
			var user = User.findOne(p._id);
			if(!user.scores){
				user.scores = [];
			}

			var gameScore = {};
			gameScore[game._id] = p.score;

			user.scores.push(gameScore);

			User.update(user._id, { $set : {
					scores : user.scores
				}
			});
		}
	});

	// Save Course
	var holes = [];

	game.holes.forEach(function(h){
		var hole = Hole.CreateNew([], h.number);
		hole.par = h.par;
		hole.notes = h.notes;
		hole.lat = h.lat;
		hole.lng = h.lng;
		hole.accuracy = h.accuracy;
		holes.push(hole);
	});

	var updateGameAndRedirect = function() {
		console.log('updateGameAndRedirect');
		// Mark game as complete & Save
		Game.update(game._id, { $set : {
				players : game.players,
				holes : game.holes,
				completed : (new Date())
			}
		}, function() {
			// Redirect to Game Dashboard
			window.location ='/game/' + game._id;
			$('.is-loading').removeClass('is-loading');
		});
	}

	var existingCourse = Course.findOne({name : game.courseName});

	if(existingCourse){
		existingCourse.holes = holes;
		Course.SaveCourse(existingCourse, updateGameAndRedirect);
	} else {
		var newCourse = Course.CreateNew(game.course, holes);
		Course.SaveCourse(newCourse, updateGameAndRedirect);
	}
};

Game.SortPlayers = function(game){

	game.players.sort(function(a,b){
		var aName = a.name.toLowerCase(),
			bName = b.name.toLowerCase();

		if(aName < bName) { return -1; }
		if(aName > bName) { return 1; }
		return 0;
	});

	game.holes.forEach(function(hole){
		hole.players.sort(function(y,z){
			var yName = Game.GetPlayerName(game, y).toLowerCase(),
				zName = Game.GetPlayerName(game, z).toLowerCase();

			if(yName < zName) { return -1; }
			if(yName > zName) { return 1; }
			return 0;
		});
	});

	return game;
};

Game.GetPlayerName = function(game, player){
	var name = '';
	game.players.forEach(function(el){
		if(el.id === player.id){
			name = el.name;
			return;
		}
	});

	return name;
};

Game.FinishGamePrompt = function(e, template){
	e.preventDefault();
	if(confirm('Are you sure you want to finish this game? You will not be able to edit any scores after you do this.')){
		var game = Template.instance().data.game;
		template.firstNode.classList.add('is-loading');
		Game.FinishGame(game);
	}
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Apache log4cxx: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Alphabetical List

Class List

Class Hierarchy

Class Members

LocationInfo Member List
This is the complete list of members for LocationInfo, including all inherited members.

clear()	LocationInfo

getClassName() const 	LocationInfo

getFileName() const 	LocationInfo

getLineNumber() const 	LocationInfo

getLocationUnavailable()	LocationInfo	 [static]

getMethodName() const 	LocationInfo

LocationInfo(const char *const fileName, const char *const functionName, int lineNumber)	LocationInfo

LocationInfo()	LocationInfo

LocationInfo(const LocationInfo &src)	LocationInfo

NA	LocationInfo	 [static]

NA_METHOD	LocationInfo	 [static]

operator=(const LocationInfo &src)	LocationInfo

write(log4cxx::helpers::ObjectOutputStream &os, log4cxx::helpers::Pool &p) const 	LocationInfo


text:
App.NewPostRoute = Ember.Route.extend(App.CurrentUserHelper, {
  model: function() {
    if (!this.get('currentUser')) {
      this.transitionTo('posts');
      return;
    }
    return this.store.createRecord('post');
  },
  deactivate: function() {
    if (!this.controller.get('model').get('id')) {
      this.controller.get('model').deleteRecord();
    }
  }
});


text:
require 'uniware'

# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration

require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  FIXTURES_PATH = File.dirname(__FILE__) + '/support/fixtures/%s.xml'
  REQUEST_FIXTURES_PATH = FIXTURES_PATH % ['%sRequest']
  RESPONSE_FIXTURES_PATH = FIXTURES_PATH % ['%sResponse']
  config.before(:each) do
    ['CreateSaleOrder'].each do |op|
      stub_request(:post, /staging.unicommerce.com/).
        with(:headers => {'Soapaction' => "\"%s\"" % [op + 'Request']},
             :body => File.new(REQUEST_FIXTURES_PATH % [op]).read.strip).
        to_return(:status => 200, :body => File.new(RESPONSE_FIXTURES_PATH % [op]).read)
    end
  end
end


text:
JavaScript library to draw and animate times table multiplication

# (つ▀¯▀)つ Usage
Call MultiCircleDREAM library in head tag (⌐■_■)✎__

    <script type="text/javascript" src="multicircledream.lib.js">

Initialize MultiCircleDREAM after the canvas tag. I recommand you to put it at the end of your html page (⌐■_■)✎__

    MultiCircleDREAM.init(put_your_canvas_id_here, width(optional), height(optional));

Done ! \\ ٩( ᐛ )و //
It is ready and make an animation with defaults parameters. Of course, it's possible to set it with the methods below (optional) (⌐■_■)✎__

    MultiCircleDREAM.stop(); //stop the animation

    MultiCircleDREAM.start(); //start the animation

    MultiCircleDREAM.setBase(number);

    MultiCircleDREAM.setSpeed(float);

    MultiCircleDREAM.setMultiplicator(float);

That's all you need to know about it. Thank you for having read. ⊂(◉‿◉)つ


text:
declare interface Window {
  __REDUX_DEVTOOLS_EXTENSION__: any;
  __REDUX_DEVTOOLS_EXTENSION_COMPOSE__: any;
}

declare interface NodeModule {
  hot?: { accept: (path: string, callback: () => void) => void };
}

declare interface System {
  import<T = any>(module: string): Promise<T>;
}
declare var System: System;

// declare const process: any;
// declare const require: any;


text:
@implementation UIImage (Tint)

-(UIImage *) imageWithTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
    //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device's main screen.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);

    //Draw the tinted image in context
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];

    if (blendMode != kCGBlendModeDestinationIn) {
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    }

    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return tintedImage;
}

+ (UIImage*)createImageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

@end


text:
[![npm package](https://img.shields.io/npm/v/react-mustache.svg?style=flat-square)](https://www.npmjs.org/package/react-mustache)
[![Build Status](https://travis-ci.org/elviejokike/react-mustache.svg?branch=master)](https://travis-ci.org/elviejokike/react-mustache)

React wrapper-component for mustache. Can be used to render templates inside a react component.

## Usage

```
import ReactMustache from 'react-mustache'
```

```
<ReactMustache template="Welcome {{title}}" data={{title: 'Mr. Gregory'}} />
```