text:
#include "config.h"
#include <string.h>

#include "gfilemonitor.h"
#include "gioenumtypes.h"
#include "gfile.h"
#include "gvfs.h"
#include "glibintl.h"

struct _FileChange;
typedef struct _FileChange FileChange;
static void file_change_free (FileChange *change);

/**
 * SECTION:gfilemonitor
 * @short_description: File Monitor
 * @include: gio/gio.h
 *
 * Monitors a file or directory for changes.
 *
 * To obtain a #GFileMonitor for a file or directory, use
 * g_file_monitor(), g_file_monitor_file(), or
 * g_file_monitor_directory().
 *
 * To get informed about changes to the file or directory you are
 * monitoring, connect to the #GFileMonitor::changed signal. The
 * signal will be emitted in the <link
 * linkend="g-main-context-push-thread-default">thread-default main
 * context</link> of the thread that the monitor was created in
 * (though if the global default main context is blocked, this may
 * cause notifications to be blocked even if the thread-default
 * context is still running).
 **/

G_LOCK_DEFINE_STATIC(cancelled);

enum {
  CHANGED,
  LAST_SIGNAL
};

typedef struct {
  GFile *file;
  guint32 last_sent_change_time; /* 0 == not sent */
  guint32 send_delayed_change_at; /* 0 == never */
  guint32 send_virtual_changes_done_at; /* 0 == never */
} RateLimiter;

struct _GFileMonitorPrivate {
  gboolean cancelled;
  int rate_limit_msec;

  /* Rate limiting change events */
  GHashTable *rate_limiter;

  GMutex mutex;
  GSource *pending_file_change_source;
  GSList *pending_file_changes; /* FileChange */

  GSource *timeout;
  guint32 timeout_fires_at;

  GMainContext *context;
};

enum {
  PROP_0,
  PROP_RATE_LIMIT,
  PROP_CANCELLED
};

/* work around a limitation of the aliasing foo */
#undef g_file_monitor

G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GFileMonitor, g_file_monitor, G_TYPE_OBJECT)

static void
g_file_monitor_set_property (GObject      *object,
                             guint         prop_id,
                             const GValue *value,
                             GParamSpec   *pspec)
{
  GFileMonitor *monitor;

  monitor = G_FILE_MONITOR (object);

  switch (prop_id)
    {
    case PROP_RATE_LIMIT:
      g_file_monitor_set_rate_limit (monitor, g_value_get_int (value));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
g_file_monitor_get_property (GObject    *object,
                             guint       prop_id,
                             GValue     *value,
                             GParamSpec *pspec)
{
  GFileMonitor *monitor;
  GFileMonitorPrivate *priv;

  monitor = G_FILE_MONITOR (object);
  priv = monitor->priv;

  switch (prop_id)
    {
    case PROP_RATE_LIMIT:
      g_value_set_int (value, priv->rate_limit_msec);
      break;

    case PROP_CANCELLED:
      G_LOCK (cancelled);
      g_value_set_boolean (value, priv->cancelled);
      G_UNLOCK (cancelled);
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

#define DEFAULT_RATE_LIMIT_MSECS 800
#define DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS 2

static guint signals[LAST_SIGNAL] = { 0 };

static void
rate_limiter_free (RateLimiter *limiter)
{
  g_object_unref (limiter->file);
  g_slice_free (RateLimiter, limiter);
}

static void
g_file_monitor_finalize (GObject *object)
{
  GFileMonitor *monitor;

  monitor = G_FILE_MONITOR (object);

  if (monitor->priv->timeout)
    {
      g_source_destroy (monitor->priv->timeout);
      g_source_unref (monitor->priv->timeout);
    }

  g_hash_table_destroy (monitor->priv->rate_limiter);

  g_main_context_unref (monitor->priv->context);
  g_mutex_clear (&monitor->priv->mutex);

  G_OBJECT_CLASS (g_file_monitor_parent_class)->finalize (object);
}

static void
g_file_monitor_dispose (GObject *object)
{
  GFileMonitor *monitor;
  GFileMonitorPrivate *priv;

  monitor = G_FILE_MONITOR (object);
  priv = monitor->priv;

  if (priv->pending_file_change_source)
    {
      g_source_destroy (priv->pending_file_change_source);
      g_source_unref (priv->pending_file_change_source);
      priv->pending_file_change_source = NULL;
    }
  g_slist_free_full (priv->pending_file_changes, (GDestroyNotify) file_change_free);
  priv->pending_file_changes = NULL;

  /* Make sure we cancel on last unref */
  g_file_monitor_cancel (monitor);

  G_OBJECT_CLASS (g_file_monitor_parent_class)->dispose (object);
}

static void
g_file_monitor_class_init (GFileMonitorClass *klass)
{
  GObjectClass *object_class;

  object_class = G_OBJECT_CLASS (klass);
  object_class->finalize = g_file_monitor_finalize;
  object_class->dispose = g_file_monitor_dispose;
  object_class->get_property = g_file_monitor_get_property;
  object_class->set_property = g_file_monitor_set_property;

  /**
   * GFileMonitor::changed:
   * @monitor: a #GFileMonitor.
   * @file: a #GFile.
   * @other_file: (allow-none): a #GFile or #NULL.
   * @event_type: a #GFileMonitorEvent.
   *
   * Emitted when @file has been changed.
   *
   * If using #G_FILE_MONITOR_SEND_MOVED flag and @event_type is
   * #G_FILE_MONITOR_EVENT_MOVED, @file will be set to a #GFile containing the
   * old path, and @other_file will be set to a #GFile containing the new path.
   *
   * In all the other cases, @other_file will be set to #NULL.
   **/
  signals[CHANGED] =
    g_signal_new (I_("changed"),
		  G_TYPE_FILE_MONITOR,
		  G_SIGNAL_RUN_LAST,
		  G_STRUCT_OFFSET (GFileMonitorClass, changed),
		  NULL, NULL,
		  NULL,
		  G_TYPE_NONE, 3,
		  G_TYPE_FILE, G_TYPE_FILE, G_TYPE_FILE_MONITOR_EVENT);

  g_object_class_install_property (object_class,
                                   PROP_RATE_LIMIT,
                                   g_param_spec_int ("rate-limit",
                                                     P_("Rate limit"),
                                                     P_("The limit of the monitor to watch for changes, in milliseconds"),
                                                     0, G_MAXINT,
                                                     DEFAULT_RATE_LIMIT_MSECS,
                                                     G_PARAM_READWRITE|
                                                     G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));

  g_object_class_install_property (object_class,
                                   PROP_CANCELLED,
                                   g_param_spec_boolean ("cancelled",
                                                         P_("Cancelled"),
                                                         P_("Whether the monitor has been cancelled"),
                                                         FALSE,
                                                         G_PARAM_READABLE|
                                                         G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
}

static void
g_file_monitor_init (GFileMonitor *monitor)
{
  monitor->priv = g_file_monitor_get_instance_private (monitor);
  monitor->priv->rate_limit_msec = DEFAULT_RATE_LIMIT_MSECS;
  monitor->priv->rate_limiter = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal,
						       NULL, (GDestroyNotify) rate_limiter_free);
  monitor->priv->context = g_main_context_ref_thread_default ();
  g_mutex_init (&monitor->priv->mutex);
}

/**
 * g_file_monitor_is_cancelled:
 * @monitor: a #GFileMonitor
 *
 * Returns whether the monitor is canceled.
 *
 * Returns: %TRUE if monitor is canceled. %FALSE otherwise.
 **/
gboolean
g_file_monitor_is_cancelled (GFileMonitor *monitor)
{
  gboolean res;

  g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);

  G_LOCK (cancelled);
  res = monitor->priv->cancelled;
  G_UNLOCK (cancelled);

  return res;
}

/**
 * g_file_monitor_cancel:
 * @monitor: a #GFileMonitor.
 *
 * Cancels a file monitor.
 *
 * Returns: %TRUE if monitor was cancelled.
 **/
gboolean
g_file_monitor_cancel (GFileMonitor* monitor)
{
  GFileMonitorClass *klass;

  g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);

  G_LOCK (cancelled);
  if (monitor->priv->cancelled)
    {
      G_UNLOCK (cancelled);
      return TRUE;
    }

  monitor->priv->cancelled = TRUE;
  G_UNLOCK (cancelled);

  g_object_notify (G_OBJECT (monitor), "cancelled");

  klass = G_FILE_MONITOR_GET_CLASS (monitor);
  return (* klass->cancel) (monitor);
}

/**
 * g_file_monitor_set_rate_limit:
 * @monitor: a #GFileMonitor.
 * @limit_msecs: a non-negative integer with the limit in milliseconds
 *     to poll for changes
 *
 * Sets the rate limit to which the @monitor will report
 * consecutive change events to the same file.
 */
void
g_file_monitor_set_rate_limit (GFileMonitor *monitor,
                               gint          limit_msecs)
{
  GFileMonitorPrivate *priv;

  g_return_if_fail (G_IS_FILE_MONITOR (monitor));
  g_return_if_fail (limit_msecs >= 0);

  priv = monitor->priv;
  if (priv->rate_limit_msec != limit_msecs)
    {
      monitor->priv->rate_limit_msec = limit_msecs;
      g_object_notify (G_OBJECT (monitor), "rate-limit");
    }
}

struct _FileChange {
  GFile             *child;
  GFile             *other_file;
  GFileMonitorEvent  event_type;
};

static void
file_change_free (FileChange *change)
{
  g_object_unref (change->child);
  if (change->other_file)
    g_object_unref (change->other_file);

  g_slice_free (FileChange, change);
}

static gboolean
emit_cb (gpointer data)
{
  GFileMonitor *monitor = G_FILE_MONITOR (data);
  GSList *pending, *iter;

  g_mutex_lock (&monitor->priv->mutex);
  pending = g_slist_reverse (monitor->priv->pending_file_changes);
  monitor->priv->pending_file_changes = NULL;
  if (monitor->priv->pending_file_change_source)
    {
      g_source_unref (monitor->priv->pending_file_change_source);
      monitor->priv->pending_file_change_source = NULL;
    }
  g_mutex_unlock (&monitor->priv->mutex);

  g_object_ref (monitor);
  for (iter = pending; iter; iter = iter->next)
    {
       FileChange *change = iter->data;

       g_signal_emit (monitor, signals[CHANGED], 0,
	  	      change->child, change->other_file, change->event_type);
       file_change_free (change);
    }
  g_slist_free (pending);
  g_object_unref (monitor);

  return FALSE;
}

static void
emit_in_idle (GFileMonitor      *monitor,
	      GFile             *child,
	      GFile             *other_file,
	      GFileMonitorEvent  event_type)
{
  GSource *source;
  FileChange *change;
  GFileMonitorPrivate *priv;

  priv = monitor->priv;

  change = g_slice_new (FileChange);

  change->child = g_object_ref (child);
  if (other_file)
    change->other_file = g_object_ref (other_file);
  else
    change->other_file = NULL;
  change->event_type = event_type;

  g_mutex_lock (&monitor->priv->mutex);
  if (!priv->pending_file_change_source)
    {
      source = g_idle_source_new ();
      priv->pending_file_change_source = source;
      g_source_set_priority (source, 0);

      /* We don't ref monitor here - instead dispose will free any
       * pending idles.
       */
      g_source_set_callback (source, emit_cb, monitor, NULL);
      g_source_attach (source, monitor->priv->context);
    }
  /* We reverse this in the processor */
  priv->pending_file_changes = g_slist_prepend (priv->pending_file_changes, change);
  g_mutex_unlock (&monitor->priv->mutex);
}

static guint32
get_time_msecs (void)
{
  return g_get_monotonic_time () / G_TIME_SPAN_MILLISECOND;
}

static guint32
time_difference (guint32 from, guint32 to)
{
  if (from > to)
    return 0;
  return to - from;
}

/* Change event rate limiting support: */

static RateLimiter *
new_limiter (GFileMonitor *monitor,
	     GFile             *file)
{
  RateLimiter *limiter;

  limiter = g_slice_new0 (RateLimiter);
  limiter->file = g_object_ref (file);
  g_hash_table_insert (monitor->priv->rate_limiter, file, limiter);

  return limiter;
}

static void
rate_limiter_send_virtual_changes_done_now (GFileMonitor *monitor,
                                            RateLimiter  *limiter)
{
  if (limiter->send_virtual_changes_done_at != 0)
    {
      emit_in_idle (monitor, limiter->file, NULL,
		    G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT);
      limiter->send_virtual_changes_done_at = 0;
    }
}

static void
rate_limiter_send_delayed_change_now (GFileMonitor *monitor,
                                      RateLimiter *limiter,
                                      guint32 time_now)
{
  if (limiter->send_delayed_change_at != 0)
    {
      emit_in_idle (monitor,
		    limiter->file, NULL,
		    G_FILE_MONITOR_EVENT_CHANGED);
      limiter->send_delayed_change_at = 0;
      limiter->last_sent_change_time = time_now;
    }
}

typedef struct {
  guint32 min_time;
  guint32 time_now;
  GFileMonitor *monitor;
} ForEachData;

static gboolean
calc_min_time (GFileMonitor *monitor,
               RateLimiter *limiter,
               guint32 time_now,
               guint32 *min_time)
{
  gboolean delete_me;
  guint32 expire_at;

  delete_me = TRUE;

  if (limiter->last_sent_change_time != 0)
    {
      /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventually */
      expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec;

      if (time_difference (time_now, expire_at) > 0)
	{
	  delete_me = FALSE;
	  *min_time = MIN (*min_time,
			   time_difference (time_now, expire_at));
	}
    }

  if (limiter->send_delayed_change_at != 0)
    {
      delete_me = FALSE;
      *min_time = MIN (*min_time,
		       time_difference (time_now, limiter->send_delayed_change_at));
    }

  if (limiter->send_virtual_changes_done_at != 0)
    {
      delete_me = FALSE;
      *min_time = MIN (*min_time,
		       time_difference (time_now, limiter->send_virtual_changes_done_at));
    }

  return delete_me;
}

static gboolean
foreach_rate_limiter_fire (gpointer key,
			   gpointer value,
			   gpointer user_data)
{
  RateLimiter *limiter = value;
  ForEachData *data = user_data;

  if (limiter->send_delayed_change_at != 0 &&
      time_difference (data->time_now, limiter->send_delayed_change_at) == 0)
    rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now);

  if (limiter->send_virtual_changes_done_at != 0 &&
      time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0)
    rate_limiter_send_virtual_changes_done_now (data->monitor, limiter);

  return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
}

static gboolean
rate_limiter_timeout (gpointer timeout_data)
{
  GFileMonitor *monitor = timeout_data;
  ForEachData data;
  GSource *source;

  data.min_time = G_MAXUINT32;
  data.monitor = monitor;
  data.time_now = get_time_msecs ();
  g_hash_table_foreach_remove (monitor->priv->rate_limiter,
			       foreach_rate_limiter_fire,
			       &data);

  /* Remove old timeout */
  if (monitor->priv->timeout)
    {
      g_source_destroy (monitor->priv->timeout);
      g_source_unref (monitor->priv->timeout);
      monitor->priv->timeout = NULL;
      monitor->priv->timeout_fires_at = 0;
    }

  /* Set up new timeout */
  if (data.min_time != G_MAXUINT32)
    {
      source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */
      g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
      g_source_attach (source, monitor->priv->context);

      monitor->priv->timeout = source;
      monitor->priv->timeout_fires_at = data.time_now + data.min_time;
    }

  return FALSE;
}

static gboolean
foreach_rate_limiter_update (gpointer key,
			     gpointer value,
			     gpointer user_data)
{
  RateLimiter *limiter = value;
  ForEachData *data = user_data;

  return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
}

static void
update_rate_limiter_timeout (GFileMonitor *monitor,
                             guint new_time)
{
  ForEachData data;
  GSource *source;

  if (monitor->priv->timeout_fires_at != 0 && new_time != 0 &&
      time_difference (new_time, monitor->priv->timeout_fires_at) == 0)
    return; /* Nothing to do, we already fire earlier than that */

  data.min_time = G_MAXUINT32;
  data.monitor = monitor;
  data.time_now = get_time_msecs ();
  g_hash_table_foreach_remove (monitor->priv->rate_limiter,
			       foreach_rate_limiter_update,
			       &data);

  /* Remove old timeout */
  if (monitor->priv->timeout)
    {
      g_source_destroy (monitor->priv->timeout);
      g_source_unref (monitor->priv->timeout);
      monitor->priv->timeout_fires_at = 0;
      monitor->priv->timeout = NULL;
    }

  /* Set up new timeout */
  if (data.min_time != G_MAXUINT32)
    {
      source = g_timeout_source_new (data.min_time + 1);  /* + 1 to make sure we've really passed the time */
      g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
      g_source_attach (source, monitor->priv->context);

      monitor->priv->timeout = source;
      monitor->priv->timeout_fires_at = data.time_now + data.min_time;
    }
}

/**
 * g_file_monitor_emit_event:
 * @monitor: a #GFileMonitor.
 * @child: a #GFile.
 * @other_file: a #GFile.
 * @event_type: a set of #GFileMonitorEvent flags.
 *
 * Emits the #GFileMonitor::changed signal if a change
 * has taken place. Should be called from file monitor
 * implementations only.
 *
 * The signal will be emitted from an idle handler (in the <link
 * linkend="g-main-context-push-thread-default">thread-default main
 * context</link>).
 **/
void
g_file_monitor_emit_event (GFileMonitor      *monitor,
			   GFile             *child,
			   GFile             *other_file,
			   GFileMonitorEvent  event_type)
{
  guint32 time_now, since_last;
  gboolean emit_now;
  RateLimiter *limiter;

  g_return_if_fail (G_IS_FILE_MONITOR (monitor));
  g_return_if_fail (G_IS_FILE (child));

  limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child);

  if (event_type != G_FILE_MONITOR_EVENT_CHANGED)
    {
      if (limiter)
	{
	  rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ());
	  if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
	    limiter->send_virtual_changes_done_at = 0;
	  else
	    rate_limiter_send_virtual_changes_done_now (monitor, limiter);
	  update_rate_limiter_timeout (monitor, 0);
	}
      emit_in_idle (monitor, child, other_file, event_type);
    }
  else
    {
      /* Changed event, rate limit */
      time_now = get_time_msecs ();
      emit_now = TRUE;

      if (limiter)
	{
	  since_last = time_difference (limiter->last_sent_change_time, time_now);
	  if (since_last < monitor->priv->rate_limit_msec)
	    {
	      /* We ignore this change, but arm a timer so that we can fire it later if we
		 don't get any other events (that kill this timeout) */
	      emit_now = FALSE;
	      if (limiter->send_delayed_change_at == 0)
		{
		  limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec;
		  update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at);
		}
	    }
	}

      if (limiter == NULL)
	limiter = new_limiter (monitor, child);

      if (emit_now)
	{
	  emit_in_idle (monitor, child, other_file, event_type);

	  limiter->last_sent_change_time = time_now;
	  limiter->send_delayed_change_at = 0;
	  /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventually */
	  update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec);
	}

      /* Schedule a virtual change done. This is removed if we get a real one, and
	 postponed if we get more change events. */

      limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000;
      update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at);
    }
}


text:
/**
 * A class that represents a maze to navigate through.
 */
package week3example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Queue;
import java.util.Stack;

/**
 * A class that represents a 2D maze, represented using a graph.
 *
 * @author UCSD Intermediate Programming MOOC Team
 *
 */
public class Maze {
	private MazeNode[][] cells;
	private int width;
	private int height;

	private final int DEFAULT_SIZE = 10;

	/**
	 * Create a new empty maze with default size 10x10
	 */
	public Maze() {

		cells = new MazeNode[DEFAULT_SIZE][DEFAULT_SIZE];
		this.width = DEFAULT_SIZE;
		this.height = DEFAULT_SIZE;
	}

	/**
	 * Create a new empty Maze with specified height and width
	 *
	 * */
	public Maze(int width, int height) {
		cells = new MazeNode[height][width];
		this.width = width;
		this.height = height;
	}

	/**
	 * Reset the maze to have the given height and width
	 * @param width The width of the maze
	 * @param height The height of the maze
	 */
	public void initialize(int width, int height) {
		cells = new MazeNode[height][width];
		this.width = width;
		this.height = height;

	}

	/**
	 * Add a graph node (i.e. not a wall) at the given location.
	 * Any grid entry that doesn't contain a node is interpreted as a wall.
	 * @param row  The row where the node exists
	 * @param col  The column where the node exists
	 */
	public void addNode(int row, int col) {
		cells[row][col] = new MazeNode(row, col);
	}

	/**
	 * Link the nodes that are adjacent (and not null) to each other with an
	 * edge. There is an edge between any two adjacent nodes up, down, left or
	 * right.
	 */
	public void linkEdges() {
		int numRows = cells.length;
		for (int row = 0; row < numRows; row++) {
			int numCols = cells[row].length;
			for (int col = 0; col < numCols; col++) {
				if (cells[row][col] != null) {
					if (row > 0 && cells[row - 1][col] != null) {
						cells[row][col].addNeighbor(cells[row - 1][col]);
					}
					if (col > 0 && cells[row][col - 1] != null) {
						cells[row][col].addNeighbor(cells[row][col - 1]);
					}
					if (row < numRows - 1 && cells[row + 1][col] != null) {
						cells[row][col].addNeighbor(cells[row + 1][col]);
					}
					if (col < numCols - 1 && cells[row][col + 1] != null) {
						cells[row][col].addNeighbor(cells[row][col + 1]);
					}
				}
			}
		}
	}

	/**
	 * Print the maze grid to the screen.
	 */
	public void printMaze() {
		for (int r = 0; r < height; r++) {
			for (int c = 0; c < width; c++) {
				if (cells[r][c] == null) {
					System.out.print('*');
				} else {
					System.out.print(cells[r][c].getDisplayChar());
				}
			}
			System.out.print("\n");
		}

	}

	/**
	 * Change the display of the maze so that it will print the
	 * path found from start to goal.
	 *
	 * NOTE: This method could use redesigning so that it did not expose
	 * the MazeNode class to the outside world.
	 *
	 * @param path A path of MazeNodes from start to goal.
	 */
	public void setPath(List<MazeNode> path) {
		int index = 0;
		for (MazeNode n : path) {
			if (index == 0) {
				n.setDisplayChar(MazeNode.START);
			} else if (index == path.size() - 1) {
				n.setDisplayChar(MazeNode.GOAL);
			} else {
				n.setDisplayChar(MazeNode.PATH);
			}
			index++;
		}

	}

	/**
	 * Clear (reset) the maze so that it will not disply a path
	 * from start to goal.
	 */
	public void clearPath() {
		for (int r = 0; r < cells.length; r++) {
			for (int c = 0; c < cells[r].length; c++) {
				MazeNode n = cells[r][c];
				if (n != null) {
					n.setDisplayChar(MazeNode.EMPTY);
				}
			}
		}
	}

	/** depth first search from (startRow,startCol) to (endRow,endCol)
	 *
	 * NOTE: This method is refactored during the videos in week 3.
	 * The refactored code is shown commented out below.
	 *
	 * @param startRow  The row of the starting position
	 * @param startCol  The column of the starting position
	 * @param endRow The row of the end position
	 * @param endCol The column of the end position
	 * @return the path from starting position to ending position, or
	 * an empty list if there is no path.
	 */
	public List<MazeNode> dfs(int startRow, int startCol, int endRow, int endCol) {

		// Initialize everything
		MazeNode start = cells[startRow][startCol];
		MazeNode goal = cells[endRow][endCol];

		if (start == null || goal == null) {
			System.out.println("Start or goal node is null!  No path exists.");
			return new LinkedList<MazeNode>();
		}

		HashMap<MazeNode, MazeNode> parentMap = new HashMap<MazeNode, MazeNode>();

		HashSet<MazeNode> visited = new HashSet<MazeNode>();
		Stack<MazeNode> toExplore = new Stack<MazeNode>();
		toExplore.push(start);
		boolean found = false;

		// Do the search
		while (!toExplore.empty()) {
			MazeNode curr = toExplore.pop();
			if (curr == goal) {
				found = true;
				break;
			}
			List<MazeNode> neighbors = curr.getNeighbors();
			ListIterator<MazeNode> it = neighbors.listIterator(neighbors.size());
			while (it.hasPrevious()) {
				MazeNode next = it.previous();
				if (!visited.contains(next)) {
					visited.add(next);
					parentMap.put(next, curr);
					toExplore.push(next);
				}
			}
		}

		if (!found) {
			System.out.println("No path exists");
			return new LinkedList<MazeNode>();
		}

		// reconstruct the path
		LinkedList<MazeNode> path = new LinkedList<MazeNode>();
		MazeNode curr = goal;
		while (curr != start) {
			path.addFirst(curr);
			curr = parentMap.get(curr);
		}
		path.addFirst(start);
		return path;
	}

	/** breadth first search from (startRow,startCol) to (endRow,endCol)
	 *
	 * Note: This method could also stand to be refactored.
	 *
	 * @param startRow  The row of the starting position
	 * @param startCol  The column of the starting position
	 * @param endRow The row of the end position
	 * @param endCol The column of the end position
	 * @return the path from starting position to ending position, or
	 * an empty list if there is no path.
	 */
	public List<MazeNode> bfs(int startRow, int startCol, int endRow, int endCol) {
		MazeNode start = cells[startRow][startCol];
		MazeNode goal = cells[endRow][endCol];

		if (start == null || goal == null) {
			System.out.println("Start or goal node is null!  No path exists.");
			return new LinkedList<MazeNode>();
		}

		HashSet<MazeNode> visited = new HashSet<MazeNode>();
		Queue<MazeNode> toExplore = new LinkedList<MazeNode>();
		HashMap<MazeNode, MazeNode> parentMap = new HashMap<MazeNode, MazeNode>();
		toExplore.add(start);
		boolean found = false;
		while (!toExplore.isEmpty()) {
			MazeNode curr = toExplore.remove();
			if (curr == goal) {
				found = true;
				break;
			}
			List<MazeNode> neighbors = curr.getNeighbors();
			ListIterator<MazeNode> it = neighbors.listIterator(neighbors.size());
			while (it.hasPrevious()) {
				MazeNode next = it.previous();
				if (!visited.contains(next)) {
					visited.add(next);
					parentMap.put(next, curr);
					toExplore.add(next);
				}
			}
		}

		if (!found) {
			System.out.println("No path exists");
			return new ArrayList<MazeNode>();
		}
		// reconstruct the path
		LinkedList<MazeNode> path = new LinkedList<MazeNode>();
		MazeNode curr = goal;
		while (curr != start) {
			path.addFirst(curr);
			curr = parentMap.get(curr);
		}
		path.addFirst(start);
		return path;
	}

/*	public List<MazeNode> dfsRefactored(int startRow, int startCol,
										int endRow, int endCol) {
		// Initialize
		MazeNode start = cells[startRow][startCol];
		MazeNode goal = cells[endRow][endCol];

		if (start == null || goal == null) {
			System.out.println("Start or goal node is null!  No path exists.");
			return new LinkedList<MazeNode>();
		}

		HashMap<MazeNode, MazeNode> parentMap = new HashMap<MazeNode, MazeNode>();
		boolean found = dfsSearch(start, goal, parentMap);

		if (!found) {
			System.out.println("No path exists");
			return new LinkedList<MazeNode>();
		}

		// reconstruct the path
		return constructPath(start, goal, parentMap);

	}

	private static boolean dfsSearch(MazeNode start, MazeNode goal,
									HashMap<MazeNode, MazeNode> parentMap) {
		HashSet<MazeNode> visited = new HashSet<MazeNode>();
		Stack<MazeNode> toExplore = new Stack<MazeNode>();
		toExplore.push(start);
		boolean found = false;

		while (!toExplore.empty()) {
			MazeNode curr = toExplore.pop();
			if (curr == goal) {
				found = true;
				break;
			}
			List<MazeNode> neighbors = curr.getNeighbors();
			ListIterator<MazeNode> it = neighbors.listIterator(neighbors.size());
			while (it.hasPrevious()) {
				MazeNode next = it.previous();
				if (!visited.contains(next)) {
					visited.add(next);
					parentMap.put(next, curr);
					toExplore.push(next);
				}
			}
		}
		return found;
	}

	private static List<MazeNode> constructPath(MazeNode start, MazeNode goal, HashMap<MazeNode, MazeNode> parentMap) {
		LinkedList<MazeNode> path = new LinkedList<MazeNode>();
		MazeNode curr = goal;
		while (curr != start) {
			path.addFirst(curr);
			curr = parentMap.get(curr);
		}
		path.addFirst(start);
		return path;
	}

*/
	public static void main(String[] args) {
		String mazeFile = "data/mazes/maze1.maze";
		Maze maze = new Maze();
		MazeLoader.loadMaze(mazeFile, maze);
		maze.printMaze();
		List<MazeNode> path = maze.dfs(3, 3, 2, 0);
		maze.setPath(path);
		System.out.println("\n");
		maze.printMaze();
		maze.clearPath();
		maze.setPath(maze.bfs(3, 3, 2, 0));
		System.out.println("\n");
		maze.printMaze();
	}
}

redpajama_set_name: RedPajamaGithub


text:
Baybay Downfall: Spanish Invasion is a RPG game set in the Philippines.
The main characters are:
1. Lapu Lapu
2. Andres Bonifacio
3. Emilio Aguinaldo.

There are 3 time periods in the game.
1. Pre Spanish Colonial
(Where you play as Lapu Lapu)
2. Spanish Colonial
(Where you play as Andres Bonifacio
3. Post Spanish Colonial
(Where you play as Emilio Aguinaldo)

**For more details** _see_ [Baybay Downfall: Spanish Invasion Wiki](https://github.com/SkyELITE21/baybay_dsi/wiki).

### Download

Currently, The game is not yet available for download but Android Game Developers may help me in building my very first game.

### Support or Contact

**For normal vistors** _see_ [Baybay Downfall: Spanish Invasion Github Website](https://skyelite21.github.io/baybay_dsi)
**For those who want to** _help_ **please** _see_ [SkyELITE21 Website](https://skyelite21.weebly.com/).
**Thank you for viewing and come back again at beta or release stage!** :)
**To support me, please click on the link below.**
 [Earn free bitcoin](http://www.freebiebitcoin.com).


text:
an IRC notification bot

---

notbot accepts POST requests from clients that wish to send notifications to an IRC channel.

## Notifiers

Add new sources for IRC notifications by implementing the Notifier interface:

```
type Notifier interface {
        Notifications(*rest.Request) []string
}
```

There are currently three Notifiers: GitHub, GitLab and Sensu, each living under a route of the same name:

```
handler.SetRoutes(
        &rest.Route{"POST", "/github", Post},
        &rest.Route{"POST", "/gitlab", Post},
        &rest.Route{"POST", "/sensu", Post},
)
```

## TODO

All the client to specify the target channel in the POST request.


text:
require "rails_helper"

RSpec.describe GroupsController, :type => :routing do
  describe "routing" do

    it "routes to #index" do
      expect(:get => "/groups").to route_to("groups#index")
    end

    it "routes to #new" do
      expect(:get => "/groups/new").to route_to("groups#new")
    end

    it "routes to #show" do
      expect(:get => "/groups/1").to route_to("groups#show", :id => "1")
    end

    it "routes to #edit" do
      expect(:get => "/groups/1/edit").to route_to("groups#edit", :id => "1")
    end

    it "routes to #create" do
      expect(:post => "/groups").to route_to("groups#create")
    end

    it "routes to #update" do
      expect(:put => "/groups/1").to route_to("groups#update", :id => "1")
    end

    it "routes to #destroy" do
      expect(:delete => "/groups/1").to route_to("groups#destroy", :id => "1")
    end

  end
end


text:
using MySql.Data.MySqlClient;
using System;

namespace MySqlLibrary
{
    class Startup
    {
        public static void Main()
        {
            /* Please first create the library by running
               "create-library.sql" in MySQL WorkBench */

            Console.Write("Enter MySQL password: ");
            string pass = Console.ReadLine();

            CreateDB("library", pass);

            string connectionStr = "Server=localhost;Database=library;Uid=root;Pwd=" + pass + ";";
            MySqlConnection connection = new MySqlConnection(connectionStr);

            ListAllBooks(connection);
            Console.WriteLine();
            FindBookById(2, connection);
            Console.WriteLine();
            AddBook("Nemo", "Mark Twain", "222-222-222-22", connection);
            AddBook("Harry Potter 2", "J. K. Rolling", "111-111-111-11", connection);
        }

        private static void ListAllBooks(MySqlConnection connection)
        {
            connection.Open();
            using (connection)
            {
                MySqlCommand command = new MySqlCommand("select b.Name as Book, a.Name as Author from books as b " +
                                                        "join authors as a " +
                                                        "on a.Id = b.AuthorId", connection);
                MySqlDataReader reader = command.ExecuteReader();

                Console.WriteLine("Books currently in library: ");
                Console.WriteLine();

                using (reader)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine(string.Format("- {0} -\t by {1}", reader["Book"], reader["Author"]));
                    }
                }
            }
        }

        private static void FindBookById(int id, MySqlConnection connection)
        {
            connection.Open();
            using (connection)
            {
                MySqlCommand command = new MySqlCommand("select b.Name as Book, a.Name as Author from books as b " +
                                                        "join authors as a " +
                                                        "on a.Id = b.AuthorId " +
                                                        "where b.Id=@id", connection);
                command.Parameters.AddWithValue("@id", id);
                MySqlDataReader reader = command.ExecuteReader();
                using (reader)
                {
                    if (reader.Read())
                    {
                        Console.WriteLine("The book with id of " + id + " is: ");
                        Console.WriteLine(string.Format("- {0} -\t by {1}", reader["Book"], reader["Author"]));
                    }
                    else
                    {
                        Console.WriteLine("There is no book with id of " + id + " in the library.");
                    }
                }
            }
        }

        private static void AddBook(string name, string author, string isbn, MySqlConnection connection)
        {
            connection.Open();
            using (connection)
            {
                MySqlCommand checkAuthor = new MySqlCommand("select a.Id as Id from authors as a " +
                                                            "join books as b " +
                                                            "on a.Id = b.AuthorId " +
                                                            "where a.Name = @author", connection);
                checkAuthor.Parameters.AddWithValue("@author", author);
                var reader = checkAuthor.ExecuteReader();

                int authorId;
                if (reader.Read())
                {
                    authorId = (int)reader["Id"];
                    reader.Close();
                }
                else
                {
                    reader.Close();
                    MySqlCommand createAuthor = new MySqlCommand("insert into authors(Name) " +
                                                                 "values (@author)", connection);
                    createAuthor.Parameters.AddWithValue("@author", author);
                    createAuthor.ExecuteNonQuery();

                    Console.WriteLine("Author " + author + " added successfully!");

                    var cmdSelectIdentity = new MySqlCommand("select @@Identity", connection);
                    authorId = int.Parse(cmdSelectIdentity.ExecuteScalar().ToString());
                }

                MySqlCommand command = new MySqlCommand("insert into books(Name, AuthorId, ISBN) " +
                                                        "values (@name, @authorId, @isbn)", connection);
                command.Parameters.AddWithValue("@name", name);
                command.Parameters.AddWithValue("@authorId", authorId);
                command.Parameters.AddWithValue("@isbn", isbn);
                command.ExecuteNonQuery();

                Console.WriteLine("Book " + name + " added successfully!");
            }
        }

        private static void CreateDB(string name, string pass)
        {
            string connectionStr = "Server=localhost;Uid=root;Pwd=" + pass + ";";
            MySqlConnection con = new MySqlConnection(connectionStr);

            string magicString = @"CREATE DATABASE  IF NOT EXISTS `library`;
USE `library`;

DROP TABLE IF EXISTS `authors`;

CREATE TABLE `authors` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `Id_UNIQUE` (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

LOCK TABLES `authors` WRITE;
INSERT INTO `authors` VALUES (1,'J. K. Rolling'),(2,'John Steinbeck');
UNLOCK TABLES;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(100) NOT NULL,
  `AuthorId` int(11) NOT NULL,
  `ISBN` varchar(20) NOT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `Id_UNIQUE` (`Id`),
  UNIQUE KEY `ISBN_UNIQUE` (`ISBN`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

LOCK TABLES `books` WRITE;
INSERT INTO `books` VALUES (1,'Harry Potter',1,'1234-5678-123-9'),(2,'Of Mice and Man',2,'9876-2414-1111-0');
UNLOCK TABLES;";

            con.Open();
            using (con)
            {
                MySqlCommand createCommand = new MySqlCommand(magicString, con);

                createCommand.ExecuteScalar();
            }
        }
    }
}


text:
package org.scalaide.core.text

import org.eclipse.jface.text.IRegion

trait Document {

  doc =>

  def apply(i: Int): Char

  def length: Int

  def text: String

  def textRange(start: Int, end: Int): String

  def textRangeOpt(start: Int, end: Int): Option[String]

  def lines: Seq[IRegion]

  def lineCount: Int

  def lineInformation(lineNumber: Int): IRegion

  def lineInformationOfOffset(offset: Int): IRegion

  def head: Char

  def headOpt: Option[Char]

  def tail: String

  def tailOpt: Option[String]

  def init: String

  def initOpt: Option[String]

  def last: Char

  def lastOpt: Option[Char]

  /**
   * This is either the delimiter of the first line, the platform line delimiter
   * if it is a legal line delimiter or the first one of the legal line
   * delimiters. The default line delimiter should be used when performing
   * document manipulations that span multiple lines. The legal line delimiters
   * usually are "\r", "\n" and "\r\n".
   */
  def defaultLineDelimiter: String
}

private[core] trait InternalDocument extends Document {
  def replace(start: Int, end: Int, text: String): Unit
}


text:
var JwtPager=React.createClass({
    displayName:'Pager',
	getInitialState:function(){
		return {limit:20, pageNo:1, totalRow:0, totalPage:0, firstClass:'disabled', lastClass:''}
	},
    onFirst:function(){
		this.state.pageNo=1;
		this.props.onPageChange(this.state.pageNo);
		this.setState({firstClass:'disabled', lastClass:''});
	},
	onLast:function(){
		this.state.pageNo=this.state.totalPage;
		this.props.onPageChange(this.state.pageNo);
		this.setState({firstClass:'', lastClass:'disabled'});
	},
	onPrevious:function(){
		if(this.state.pageNo>1){
			this.state.pageNo--;
			this.props.onPageChange(this.state.pageNo);
			this.setState({firstClass:this.state.pageNo===1?'disabled':'', lastClass:''});
		}else{
			this.setState({firstClass:'disabled', lastClass:''});
		}
	},
	onNext:function(){
		if(this.state.totalPage>this.state.pageNo){
			this.state.pageNo++;
			this.props.onPageChange(this.state.pageNo);
			this.setState({firstClass:'', lastClass:this.state.totalPage==this.state.pageNo?'disabled':''});
		}else{
			this.setState({firstClass:'', lastClass:'disabled'});
		}
	},
	componentDidMount:function(){
        this.state.limit=this.props.limit;
		this.state.totalRow=this.props.totalRow;
		this.state.totalPage=parseInt(this.props.totalRow/this.props.limit)+((this.props.totalRow%this.props.limit==0)?0:1);

    },
    render:function(){
    	var classNames='pagination pull-'+this.props.pos;
        return(
            React.createElement("ul", {className: classNames},
			   React.createElement("li", {className: this.state.firstClass}, React.createElement("a", {onClick: this.onFirst, href: "javascript:;"}, React.createElement("span", {className: "glyphicon glyphicon-step-backward"}))),
               React.createElement("li", {className: this.state.firstClass}, React.createElement("a", {onClick: this.onPrevious, href: "javascript:;"}, React.createElement("span", {className: "glyphicon glyphicon-arrow-left"}))),
               React.createElement("li", {className: this.state.lastClass}, React.createElement("a", {onClick: this.onNext, href: "javascript:;"}, React.createElement("span", {className: "glyphicon glyphicon-arrow-right"}))),
			   React.createElement("li", {className: this.state.lastClass}, React.createElement("a", {onClick: this.onLast, href: "javascript:;"}, React.createElement("span", {className: "glyphicon glyphicon-step-forward"})))
            )
            )
    }
});

export default JwtPager;


text:
"""Runs a pose estimation experiment on the symmetric_solids dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
from absl import app
from absl import flags
from absl import logging
import numpy as np
import tensorflow as tf
from implicit_pdf import data
from implicit_pdf import evaluation
from implicit_pdf import models

tfkl = tf.keras.layers
FLAGS = flags.FLAGS

#################################### I/O #######################################
flags.DEFINE_string('outdir',
                    'ipdf_output/',
                    'The directory in which to save results and images.')
flags.DEFINE_bool('save_models', True, 'Whether to save the vision and IPDF'
                  ' models at the end of training.')
################################ Model Specs ###################################
flags.DEFINE_multi_integer('head_network_specs',
                           [256]*2,
                           'The sizes of the dense layers in the head network.')
#################################### Data ######################################
flags.DEFINE_multi_string('symsol_shapes', ['tet'],
                          'Can be any subset of the 8 shapes of SYMSOL I & II: '
                          'tet, cube, icosa, cyl, cone, tetX, cylO, sphereX, or'
                          ' \'symsol1\' for the first five.')
flags.DEFINE_integer('downsample_continuous_gt', 0,
                     'Whether, and how much, to downsample the cone and '
                     'cylinder ground truth rotations, which can make '
                     'evaluation slow.')
################################# Training #####################################
flags.DEFINE_integer('number_training_iterations',
                     10_000,
                     'The number of iterations to train.')
flags.DEFINE_integer('number_eval_iterations', None,
                     'The number of iterations to eval.')

flags.DEFINE_float('learning_rate', 1e-4, 'The learning rate.')
flags.DEFINE_integer('batch_size', 32, 'The batch size.')
flags.DEFINE_integer('test_batch_size', 32, 'The batch size for evaluation, '
                     'where it may be helpful to evaluate with a larger grid '
                     'and reduce this batch size if memory issues arise.')
flags.DEFINE_string('optimizer', 'Adam', 'The name of the optimizer to use.')
flags.DEFINE_integer('number_train_queries', 2**12,
                     'The number of sampled points on SO(3) for each loss '
                     'evaluation.')
flags.DEFINE_integer('number_eval_queries', 2**16,
                     'The number of sampled points on SO(3) to use for '
                     'evaluation.')
flags.DEFINE_enum('so3_sampling_mode', 'random',
                  ['random', 'grid'],
                  'How to sample from SO(3): \'random\' samples rotations '
                  'uniformly and \'grid\' creates an equivolumetric grid based '
                  'off Yershova et al. (2010).')
flags.DEFINE_integer('number_fourier_components', 1,
                     'The number of components in the positional encoding '
                     'for the implicit model.')
flags.DEFINE_integer('eval_every', -1, 'How often to evaluate.  If -1, evaluate'
                     '  100 times during training.')
flags.DEFINE_bool('skip_spread_evaluation', False, 'Whether to skip the '
                  'evaluation of the spread metric, which can be slow for '
                  'shapes with many ground truths.')
################################################################################
################################################################################

flags.DEFINE_bool('mock', False,
                  'Skip download of dataset and pre-trained weights. '
                  'Useful for testing.')

def main(_):

  outdir = FLAGS.outdir
  checkpoint_dir = os.path.join(outdir, 'checkpoints')

  number_training_iterations = FLAGS.number_training_iterations
  learning_rate = FLAGS.learning_rate

  if FLAGS.eval_every == -1:
    eval_every = number_training_iterations // 100
  else:
    eval_every = FLAGS.eval_every

  symsol_shapes = FLAGS.symsol_shapes
  if 'symsol1' in symsol_shapes:
    symsol_shapes = data.SHAPE_NAMES[:5]
  ######################   Create the models   ###############################
  vision_model, len_visual_description = models.create_vision_model(
      weights=None if FLAGS.mock else 'imagenet')

  model_head = models.ImplicitSO3(len_visual_description,
                                  FLAGS.number_fourier_components,
                                  FLAGS.head_network_specs,
                                  FLAGS.so3_sampling_mode,
                                  FLAGS.number_train_queries,
                                  FLAGS.number_eval_queries)
  ######################   Load the datasets   ###############################
  dset_train = data.load_symsol(symsol_shapes, mode='train', mock=FLAGS.mock)
  dset_train = dset_train.repeat().shuffle(1000).batch(FLAGS.batch_size)

  dset_val_list = []
  for symsol_shape in symsol_shapes:
    dset_val_list.append(
        data.load_symsol(
            [symsol_shape],
            mode='test',
            downsample_continuous_gt=FLAGS.downsample_continuous_gt,
            mock=FLAGS.mock))
  dset_val_tags = symsol_shapes

  visualization_images, visualization_rotations_gt = [[], []]
  for image, rotations_gt in tf.data.experimental.sample_from_datasets(
      dset_val_list).take(8):
    visualization_images.append(image)
    visualization_rotations_gt.append(rotations_gt)

  measurement_labels = []
  for tag in dset_val_tags:
    measurement_labels += [f'gt_log_likelihood_{tag}', f'spread_{tag}']
  measurements = {}
  ##########################  Optimizer  #####################################
  optimizer = tf.keras.optimizers.get(FLAGS.optimizer)
  optimizer.learning_rate = learning_rate
  #########################  Logging setup  ##################################
  train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)
  log_dir = os.path.join(outdir, 'logs')
  train_summary_writer = tf.summary.create_file_writer(log_dir)
  #########################  Checkpointing  ##################################
  checkpoint = tf.train.Checkpoint(
      vision_model=vision_model, model_head=model_head, optimizer=optimizer)

  checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))

  max_ckpts_to_keep = 1
  checkpoint_manager = tf.train.CheckpointManager(
      checkpoint, directory=checkpoint_dir, max_to_keep=max_ckpts_to_keep)

  def cosine_decay(step, warmup_steps=1000):
    warmup_factor = min(step, warmup_steps) / warmup_steps
    decay_step = max(step - warmup_steps, 0) / (
        number_training_iterations - warmup_steps)
    return learning_rate * warmup_factor * (1 + tf.cos(decay_step * np.pi)) / 2

  @tf.function
  def train_step(vision_model, model_head, optimizer, images, rotations_gt):
    with tf.GradientTape() as tape:
      vision_description = vision_model(images, training=True)
      loss = model_head.compute_loss(vision_description, rotations_gt)
    grads = tape.gradient(
        loss,
        vision_model.trainable_variables + model_head.trainable_variables)
    optimizer.apply_gradients(
        zip(grads, vision_model.trainable_variables +
            model_head.trainable_variables))
    return loss

  logging.info('Started training.')
  for batch_data in dset_train:
    step_num = optimizer.iterations.numpy()
    if step_num > number_training_iterations:
      break

    tf.keras.backend.set_value(optimizer.learning_rate,
                               cosine_decay(step_num))
    images, rotations_gt = batch_data
    loss = train_step(vision_model, model_head, optimizer, images, rotations_gt)

    train_loss(loss)

    if (step_num) % 100 == 0:
      avg_loss = train_loss.result()
      train_loss.reset_states()
      with train_summary_writer.as_default():
        tf.summary.scalar('loss', avg_loss, step=step_num)
        tf.summary.scalar(
            'learning_rate', optimizer.learning_rate, step=step_num)
      logging.info('Step %d, training loss=%.2f', step_num, avg_loss)

    if (step_num+1) % eval_every == 0:
      measurements = eval_step(
          vision_model,
          model_head,
          dset_val_list,
          dset_val_tags)

      with train_summary_writer.as_default():
        logline = f'Step {step_num}: '
        for k, v in measurements.items():
          tf.summary.scalar(k, v, step=step_num)
          logline += f'{k}={v:.2f} '
        logging.info(logline)
        logging.info('Started visualize_so3.')
        distribution_images = evaluation.visualize_model_output(
            vision_model, model_head, visualization_images,
            visualization_rotations_gt)
        tf.summary.image('output_distribution', distribution_images,
                         step=step_num)

      logging.info('Saving checkpoint.')
      checkpoint_manager.save()

  logging.info('Finished training.')
  #######################  Save the models  ##################################
  if FLAGS.save_models:
    visual_input = tfkl.Input(shape=(len_visual_description,))
    query_input = tfkl.Input(shape=(None, model_head.len_query,))
    inp = [visual_input, query_input]
    saveable_head_model = tf.keras.Model(inp, model_head(inp))
    models_saved = False
    if not models_saved:
      vision_model.save(os.path.join(outdir, 'base_vision_model'))
      saveable_head_model.save(os.path.join(outdir, 'ipdf_head_model'))

    logging.info('Saved models.')

def eval_step(vision_model, model_head, dataset_list,
              dataset_measurement_tags):
  """Evaluate distribution-based metrics.

  Args:
    vision_model: The model which produces a feature vector to hand to IPDF.
    model_head: The IPDF model.
    dataset_list: A list of datasets, to evaluate separately.
    dataset_measurement_tags: The names to associate with each dataset in
      dataset_list, when outputting metrics.
  Returns:
    A dictionary of values indexed by their associated descriptor tag.
  """
  assert len(dataset_list) == len(dataset_measurement_tags)
  measurements = {}
  logging.info('Started eval_step.')
  for dataset, tag in zip(dataset_list, dataset_measurement_tags):
    avg_log_likelihood, spread = evaluation.eval_spread_and_loglikelihood(
        vision_model,
        model_head,
        dataset,
        batch_size=FLAGS.test_batch_size,
        skip_spread_evaluation=FLAGS.skip_spread_evaluation,
        number_eval_iterations=FLAGS.number_eval_iterations)
    measurements[f'gt_log_likelihood_{tag}'] = avg_log_likelihood
    measurements[f'spread_{tag}'] = spread

  return measurements

if __name__ == '__main__':
  app.run(main)


text:
package vapourdrive.furnaceevolved;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import vapourdrive.furnaceevolved.proxies.CommonProxy;

@Mod(modid = Reference.ModID, version = Reference.Version, name = Reference.Name, dependencies = "before:JustEnoughItems;after:MineTweaker")
public class FurnaceEvolved
{
	@Instance(Reference.ModID)
	public static FurnaceEvolved Instance;

	@SidedProxy(clientSide = "vapourdrive.furnaceevolved.proxies.ClientProxy", serverSide = "vapourdrive.furnaceevolved.proxies.CommonProxy")
	public static CommonProxy proxy;
	public static final Logger log = LogManager.getLogger(Reference.ModID);

	@EventHandler
	public void preInit(FMLPreInitializationEvent event)
	{
		proxy.preInit(event);
	}

	@EventHandler
	public void init(FMLInitializationEvent event)
	{
		proxy.Init(event);
	}

	@EventHandler
	public void postInit(FMLPostInitializationEvent event)
	{
		proxy.postInit(event);
	}

	@EventHandler
	public void serverStarted(FMLServerAboutToStartEvent event)
	{
		proxy.serverStarted(event);
	}
}


text:
using FieldTag = uint16_t;

struct Slice {
    uint16_t off;
    uint16_t len;
};

#define FIELD_TYPES(X) \
    X(Int32,  int32_t) \
    X(UInt32, uint32_t) \
    X(Float,  float) \
    X(Double, double) \
    X(Str,    Slice) \
    X(Buf,    Slice)

enum class FieldType : uint16_t {
#define X(xName, xType) e##xName,
    FIELD_TYPES(X)
#undef X
    Count
};

size_t fieldTypeSize(FieldType type);
const char *fieldTypeName(FieldType type);

struct FieldDescriptor {
    FieldTag  tag;
    FieldType type;
};

struct Schema {
    const Schema          *prototype;
    uint32_t               hash;
    const FieldDescriptor *fields;
    uint16_t               fieldCount;
    uint16_t               fixedSize;
};

struct Message {
    const Message *prototype;
    const Schema  *schema;
    const uint8_t *fixedBuffer;
    uint16_t       fixedSize;
    const uint8_t *dynamicBuffer;
    uint16_t       dynamicSize;
};

class MessageBuilder {
public:
    MessageBuilder();

    void prepare(const Message *prototype = nullptr);

    void addField(FieldTag tag, int32_t val);
    void addField(FieldTag tag, const char *str);
    void addField(FieldTag tag, const char *str, size_t len);
    // TODO: Other addField methods

    Message build();

private:
    const Message               *prototype_;
    Schema                       schema_;
    std::vector<FieldDescriptor> fields_;
    std::vector<uint8_t>         fixedBuffer_;
    std::vector<uint8_t>         dynamicBuffer_;
    uint16_t                     dynamicBase_;
};

// A writer should insert the message schema into this to figure
// out if a schema message should be sent or the fixed hash
class SchemaWriterMap {
public:
    SchemaWriterMap();

    std::tuple<uint32_t, bool> insert(const Schema *schema);

private:
    void insert(std::vector<Schema>::iterator it, const Schema *schema, uint32_t hash);

    static bool compare(const Schema &lhs, const Schema &rhs);
    static bool compareFields(const Schema &lhs, const Schema &rhs);
    static std::tuple<FieldDescriptor, bool> prev(const Schema **schema, int *index);

private:
    std::vector<Schema> schemas_;
    std::vector<std::unique_ptr<FieldDescriptor[]>> fields_;
};

struct Buffer {
    const uint8_t *ptr;
    size_t len;
};

struct Frame {
    uint16_t len;
    uint8_t  version;
    uint8_t  flags;
    uint32_t hash;
};

class MessageWriter {
public:
    MessageWriter();

    const std::vector<Buffer> &write(const Message &message);
private:

private:
    SchemaWriterMap      schemaWriterMap_;
    std::vector<Buffer>  buffers_;
    Frame                messageFrame_;
    std::vector<uint8_t> schemaBuffer_;
};

#endif // SNW_MSG_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NHibernate;
using Purchasing.Core.Domain;
using Purchasing.Tests.Core;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Data.NHibernate;
using UCDArch.Testing.Extensions;

namespace Purchasing.Tests.RepositoryTests
{
    /// <summary>
    /// Entity Name:		WorkgroupAccount
    /// LookupFieldName:	Id
    /// </summary>
    [TestClass]
    public class WorkgroupAccountRepositoryTests : AbstractRepositoryTests<WorkgroupAccount, int, WorkgroupAccountMap>
    {
        /// <summary>
        /// Gets or sets the WorkgroupAccount repository.
        /// </summary>
        /// <value>The WorkgroupAccount repository.</value>
        public IRepository<WorkgroupAccount> WorkgroupAccountRepository { get; set; }
        public IRepositoryWithTypedId<Account, string> AccountRepository { get; set; }
        public IRepositoryWithTypedId<User, string> UserRepository { get; set; }

        #region Init and Overrides

        /// <summary>
        /// Initializes a new instance of the <see cref="WorkgroupAccountRepositoryTests"/> class.
        /// </summary>
        public WorkgroupAccountRepositoryTests()
        {
            WorkgroupAccountRepository = new Repository<WorkgroupAccount>();
            AccountRepository = new RepositoryWithTypedId<Account, string>();
            UserRepository = new RepositoryWithTypedId<User, string>();
        }

        /// <summary>
        /// Gets the valid entity of type T
        /// </summary>
        /// <param name="counter">The counter.</param>
        /// <returns>A valid entity of type T</returns>
        protected override WorkgroupAccount GetValid(int? counter)
        {
            var rtValue = CreateValidEntities.WorkgroupAccount(counter, true);
            rtValue.Account = AccountRepository.Queryable.First();
            rtValue.Workgroup = Repository.OfType<Workgroup>().Queryable.First();
            return rtValue;
        }

        /// <summary>
        /// A Query which will return a single record
        /// </summary>
        /// <param name="numberAtEnd"></param>
        /// <returns></returns>
        protected override IQueryable<WorkgroupAccount> GetQuery(int numberAtEnd)
        {
            return WorkgroupAccountRepository.Queryable.Where(a => a.Id == numberAtEnd);
        }

        /// <summary>
        /// A way to compare the entities that were read.
        /// For example, this would have the assert.AreEqual("Comment" + counter, entity.Comment);
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="counter"></param>
        protected override void FoundEntityComparison(WorkgroupAccount entity, int counter)
        {
            Assert.AreEqual(counter, entity.Id);
        }

        /// <summary>
        /// Updates , compares, restores.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="action">The action.</param>
        protected override void UpdateUtility(WorkgroupAccount entity, ARTAction action)
        {
            const string updateValue = "Name2";
            switch (action)
            {
                case ARTAction.Compare:
                    Assert.AreEqual(updateValue, entity.Account.Name);
                    break;
                case ARTAction.Restore:
                    entity.Account = AccountRepository.Queryable.Single(a => a.Id == "1");
                    break;
                case ARTAction.Update:
                    RestoreValue = entity.Account.Name;
                    entity.Account= AccountRepository.Queryable.Single(a => a.Id == "2");
                    break;
            }
        }

        /// <summary>
        /// Loads the data.
        /// </summary>
        protected override void LoadData()
        {
            AccountRepository.DbContext.BeginTransaction();
            LoadAccounts(3);
            LoadOrganizations(3);
            LoadWorkgroups(3);
            LoadUsers(3);
            AccountRepository.DbContext.CommitTransaction();

            WorkgroupAccountRepository.DbContext.BeginTransaction();
            LoadRecords(5);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
        }

        #endregion Init and Overrides

        #region Workgroup Tests

        [TestMethod]
        [ExpectedException(typeof (ApplicationException))]
        public void TestWorkgroupAccountsFieldWorkgroupWithAValueOfNullDoesNotSave()
        {
            WorkgroupAccount record = null;
            try
            {
                #region Arrange
                record = GetValid(9);
                record.Workgroup = null;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(record);
                Assert.AreEqual(record.Workgroup, null);
                var results = record.ValidationResults().AsMessageList();
                results.AssertErrorsAre("The Workgroup field is required.");
                Assert.IsTrue(record.IsTransient());
                Assert.IsFalse(record.IsValid());
                throw;
            }
        }

        [TestMethod]
        [ExpectedException(typeof (TransientObjectException))]
        public void TestWorkgroupAccountNewWorkgroupDoesNotSave()
        {
            var thisFar = false;
            try
            {
                #region Arrange
                var record = GetValid(9);
                record.Workgroup = new Workgroup();
                thisFar = true;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch(Exception exOuter) when (exOuter.InnerException is Exception ex)
            {
                Assert.IsTrue(thisFar);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Purchasing.Core.Domain.Workgroup, Entity: Purchasing.Core.Domain.Workgroup", ex.Message);
                throw ex;
            }
        }

        [TestMethod]
        public void TestWorkgroupAccountWithExistingWorkgroupSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Workgroup = Repository.OfType<Workgroup>().Queryable.Single(a => a.Id == 3);
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(3, record.Workgroup.Id);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }

        #endregion Workgroup Tests

        #region Account Tests

        [TestMethod]
        [ExpectedException(typeof (ApplicationException))]
        public void TestWorkgroupAccountsFieldAccountWithAValueOfNullDoesNotSave()
        {
            WorkgroupAccount record = null;
            try
            {
                #region Arrange
                record = GetValid(9);
                record.Account = null;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch (Exception)
            {
                Assert.IsNotNull(record);
                Assert.AreEqual(record.Account, null);
                var results = record.ValidationResults().AsMessageList();
                results.AssertErrorsAre("The Account field is required.");
                Assert.IsTrue(record.IsTransient());
                Assert.IsFalse(record.IsValid());
                throw;
            }
        }

        [TestMethod]
        [ExpectedException(typeof (TransientObjectException))]
        public void TestWorkgroupAccountNewAccountDoesNotSave()
        {
            var thisFar = false;
            try
            {
                #region Arrange
                var record = GetValid(9);
                record.Account = new Account();
                thisFar = true;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch(Exception exOuter) when (exOuter.InnerException is Exception ex)
            {
                Assert.IsTrue(thisFar);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Purchasing.Core.Domain.Account, Entity: Purchasing.Core.Domain.Account", ex.Message);
                throw ex;
            }
        }

        [TestMethod]
        public void TestWorkgroupAccountWithExistingAccountSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Account = AccountRepository.Queryable.Single(a => a.Id == "3");
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual("3", record.Account.Id);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
        #endregion Account Tests

        #region Approver Tests

        [TestMethod]
        [ExpectedException(typeof (TransientObjectException))]
        public void TestWorkgroupAccountNewApproverDoesNotSave()
        {
            var thisFar = false;
            try
            {
                #region Arrange
                var record = GetValid(9);
                record.Approver = new User();
                thisFar = true;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch(Exception exOuter) when (exOuter.InnerException is Exception ex)
            {
                Assert.IsTrue(thisFar);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Purchasing.Core.Domain.User, Entity: Purchasing.Core.Domain.User", ex.Message);
                throw ex;
            }
        }

        [TestMethod]
        public void TestWorkgroupAccountWithExistingApproverSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Approver = UserRepository.Queryable.Single(a => a.Id == "3");
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual("3", record.Approver.Id);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }

        //Delete this one if not nullable
        [TestMethod]
        public void TestWorkgroupAccountWithNullApproverSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Approver = null;
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(null, record.Approver);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
        #endregion Approver Tests

        #region AccountManager Tests

        [TestMethod]
        [ExpectedException(typeof (TransientObjectException))]
        public void TestWorkgroupAccountNewAccountManagerDoesNotSave()
        {
            var thisFar = false;
            try
            {
                #region Arrange
                var record = GetValid(9);
                record.AccountManager = new User();
                thisFar = true;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch(Exception exOuter) when (exOuter.InnerException is Exception ex)
            {
                Assert.IsTrue(thisFar);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Purchasing.Core.Domain.User, Entity: Purchasing.Core.Domain.User", ex.Message);
                throw ex;
            }
        }

        [TestMethod]
        public void TestWorkgroupAccountWithExistingAccountManagerSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.AccountManager = UserRepository.Queryable.Single(a => a.Id == "3");
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual("3", record.AccountManager.Id);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }

        //Delete this one if not nullable
        [TestMethod]
        public void TestWorkgroupAccountWithNullAccountManagerSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.AccountManager = null;
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(null, record.AccountManager);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
        #endregion AccountManager Tests

        #region Purchaser Tests

        [TestMethod]
        [ExpectedException(typeof (TransientObjectException))]
        public void TestWorkgroupAccountNewPurchaserDoesNotSave()
        {
            var thisFar = false;
            try
            {
                #region Arrange
                var record = GetValid(9);
                record.Purchaser = new User();
                thisFar = true;
                #endregion Arrange

                #region Act
                WorkgroupAccountRepository.DbContext.BeginTransaction();
                WorkgroupAccountRepository.EnsurePersistent(record);
                WorkgroupAccountRepository.DbContext.CommitTransaction();
                #endregion Act
            }
            catch(Exception exOuter) when (exOuter.InnerException is Exception ex)
            {
                Assert.IsTrue(thisFar);
                Assert.IsNotNull(ex);
                Assert.AreEqual("object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Purchasing.Core.Domain.User, Entity: Purchasing.Core.Domain.User", ex.Message);
                throw ex;
            }
        }

        [TestMethod]
        public void TestWorkgroupAccountWithExistingPurchaserSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Purchaser = UserRepository.Queryable.Single(a => a.Id == "3");
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual("3", record.Purchaser.Id);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }

        //Delete this one if not nullable
        [TestMethod]
        public void TestWorkgroupAccountWithNullPurchaserSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Purchaser = null;
            #endregion Arrange

            #region Act
            WorkgroupAccountRepository.DbContext.BeginTransaction();
            WorkgroupAccountRepository.EnsurePersistent(record);
            WorkgroupAccountRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(null, record.Purchaser);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
        #endregion Purchaser Tests

        #region Reflection of Database.

        /// <summary>
        /// Tests all fields in the database have been tested.
        /// If this fails and no other tests, it means that a field has been added which has not been tested above.
        /// </summary>
        [TestMethod]
        public void TestAllFieldsInTheDatabaseHaveBeenTested()
        {
            #region Arrange
            var expectedFields = new List<NameAndType>();
            expectedFields.Add(new NameAndType("Account", "Purchasing.Core.Domain.Account", new List<string>
            {
                 "[System.ComponentModel.DataAnnotations.RequiredAttribute()]"
            }));
            expectedFields.Add(new NameAndType("AccountManager", "Purchasing.Core.Domain.User", new List<string>
            {
                "[System.ComponentModel.DataAnnotations.DisplayAttribute(Name = \"Account Manager\")]"
            }));
            expectedFields.Add(new NameAndType("Approver", "Purchasing.Core.Domain.User", new List<string>()));
            expectedFields.Add(new NameAndType("Id", "System.Int32", new List<string>
            {
                "[Newtonsoft.Json.JsonPropertyAttribute()]",
                "[System.Xml.Serialization.XmlIgnoreAttribute()]"
            }));
            expectedFields.Add(new NameAndType("Purchaser", "Purchasing.Core.Domain.User", new List<string>()));
            expectedFields.Add(new NameAndType("Workgroup", "Purchasing.Core.Domain.Workgroup", new List<string>
            {
                 "[System.ComponentModel.DataAnnotations.RequiredAttribute()]"
            }));
            #endregion Arrange

            AttributeAndFieldValidation.ValidateFieldsAndAttributes(expectedFields, typeof(WorkgroupAccount));

        }

        #endregion Reflection of Database.

    }
}


text:
package com.liuawei.web.controller.MappingRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/demo")
public class HelloSpring2 {

	@RequestMapping(value="/hello2")
	public ModelAndView HelloSpring() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("message", "HelloSpring");
		mv.setViewName("helloSpring");
		return mv;
	}
}


text:
Typography

Use typography to present your design and content as clearly and efficiently as possible.

<demo-view path="docs/components/typography-demo/typography-demo-basic">
  <aui-typography-demo-basic></aui-typography-demo-basic>
</demo-view>

Theme

  You can also add new configurations

export class GlobalVariables implements PartialThemeVariables {
  ...
  typography = {
    lyTyp: {
      lyTyp: {
        myTitle: () => lyl `{
          font-family: 'Roboto', sans-serif
          text-align: center
          padding-above: 1em
          opacity: .6
          font-size: 32px
          font-weight: 400
        }`
      }
    }
  };
}

  You can use it like this

<h2 lyTyp="myTitle">Hello</h2>

Truncate text

<demo-view path="docs/components/typography-demo/truncate-text">
  <aui-truncate-text></aui-truncate-text>
</demo-view>


text:
var 	reqprom = require("request-promise")
	,	config = require('../config')
	,	xmldoc = require("xmldoc");

exports.handleGet = function(req, res) {

	var targetSys = req.params.target;
	var serviceList = [];
	var respXML = {};

	var serviceName = "";
	var serviceType = "";
	var consumerScheme = "";
	var serviceAddress = req.connection.remoteAddress;
	console.log("serviceAddress: " + serviceAddress);

	if ((serviceAddress.indexOf("[") < 0) && (serviceAddress.indexOf(":") > -1)) {
		if (serviceAddress.indexOf("::") > -1) {

		} else {
			serviceAddress = serviceAddress.substring( serviceAddress.lastIndexOf(":")+1 );
		}
	}

	console.log(serviceAddress);

	var getOrchestrationRules_options = {
			uri: 'http://' + config.listen.ip + ':1102/orchestrationstore/configuration/' + targetSys,
		    json: true // Automatically parses the JSON string in the response
	};

	//send request to Orchestration store to get the rules for the system
	var waitfor = reqprom(getOrchestrationRules_options).then(function(response) {
		console.log("response[0].rules: " + response[0].rules);
		return response[0].rules;
	});

	//concurrent sends to service registry to get the service instances according to the name in the rule
	//todo: This will change once the rule definition becomes clear.
	waitfor = waitfor.map(function(rule) {

		serviceName = rule.split(',')[0];
		serviceType = rule.split(',')[1];

		console.log("serviceName: " + serviceName);
		var getService_options = {
				uri: 'http://' + config.serviceregistry.ip + ':' + config.serviceregistry.port + '/servicediscovery/service/' + serviceName,
			    json: true // Automatically parses the JSON string in the response
		};
		return reqprom(getService_options);
	});

	//select service provider from list
	// criteria = 	meta data
	//				QoS
	//				security

	//concurrent test for protocol mismatch and therefore translator engagement
	waitfor = waitfor.map(function(service) {
//		service.forEach(function(entry) {
//			console.log("retrieved service name " + entry.name.toString());
//			console.log("retrieved service type " + entry.type.toString());
//			console.log("desired service type " + serviceType.toString());
//			console.log("match " + entry.type.toString().indexOf(serviceType.toString()));
//		});
		console.log("service: " + JSON.stringify(service[0]));
		if(service[0].hasOwnProperty("type")) {
			console.log("retrieved service type " + service[0].type.toString());
			console.log("desired service type " + serviceType.toString());
			consumerScheme = serviceType.replace("_","");
			console.log("match " + service[0].type.toString().indexOf(serviceType.toString()));
			if(service[0].type.toString().indexOf(serviceType.toString()) === -1) {
				//if the ip address does not contain a period and it does not have the square brackets for ipv6 then add them
				if (service[0].host.indexOf(':') > -1 && service[0].host.indexOf('[') === -1) {
					service[0].host = '[' + service[0].host + ']';
				}

				var xmlbody = 	'<translatorSetup>' +
								'<providerName>' + service[0].type + '</providerName>' +
								'<providerType>' + service[0].type + '</providerType>' +
								'<providerAddress>' + service[0].host + ':' + service[0].port + '</providerAddress>' +
								'<consumerName>' + serviceType + '</consumerName>' +
								'<consumerType>' + serviceType + '</consumerType>' +
								'<consumerAddress>' + serviceAddress + '</consumerAddress>' +
								'</translatorSetup>';
				console.log("xmlbody " + xmlbody);
				//request translator to create interfaces
				var postTranslator_options = {
						uri: 'http://' + config.translator.ip + ':' + config.translator.port + '/translator/',
					    json: false, // Automatically parses the JSON string in the response
					    headers: {'Content-Type': 'application/xml'},
					    method: 'post',
					    body: xmlbody//post message content {providername, providertype, provideraddress, consumername, consumertype, consumeraddress}
				};

				return reqprom(postTranslator_options)
				.then(function(response) {
					console.log("actual:" + response);
					respXML = new xmldoc.XmlDocument(response);
					return respXML;
				}).then(function(respXML) {
					//replace the address value with the end-point details returned from the translator
					service[0].host = respXML.valueWithPath("ip");
					service[0].port = respXML.valueWithPath("port");
					service[0].type = serviceType;

					return service;
				});
			} else {
				return service;
			}
		}else {
			return null;
		}
	});

	//
	waitfor = waitfor.map(function(service){//conditional logic tree with promise framework
		console.log("final service " + JSON.stringify(service));
		if(service !== null) {
			var path = service[0].properties.property.filter( function(property) { return property.name === "path" ? true : false; })[0].value;
			if(path.startsWith("/")) {
				path = (path[1]==='/'? path.substring(1) : path);
			} else {
				path = "/" + path;
			}
			if(service[0].port.endsWith("/")) {
				service[0].port = service[0].port.substring(0,service[0].port.length-1);
			}

			serviceList.push({
				"name":		service[0].name,
				"address":	consumerScheme + "://" + service[0].host + ":" + service[0].port + path  //path.substring(1)
			});
		}
	});

	//
	waitfor = waitfor.finally(function() {
			console.log({"target":targetSys, "services":serviceList});
			res.setHeader('Content-Type','application/json');
			res.send({"target":targetSys, "services":serviceList});
	});
};

exports.handleGetCoap = function(req, res) {

	//var targetSys = req.url.split('?')[1].split('=')[1];
	var targetSys = req.url.split('/')[2];
	console.log("targetSys: " + targetSys);
	var serviceList = [];
	var respXML = {};

	var serviceName = "";
	var serviceType = "";
	var consumerScheme = "";
	var serviceAddress = req.rsinfo.address;
	console.log("serviceAddress: " + serviceAddress);
	if(serviceAddress.indexOf(":") > -1) {
		serviceAddress = serviceAddress.substring(serviceAddress.lastIndexOf(":")+1);
	}

	console.log(serviceAddress);

	var getOrchestrationRules_options = {
			uri: 'http://' + config.listen.ip + ':1102/orchestrationstore/configuration/' + targetSys,
		    json: true // Automatically parses the JSON string in the response
	};

	//send request to Orchestration store to get the rules for the system
	var waitfor = reqprom(getOrchestrationRules_options).then(function(response) {
		console.log("response[0].rules: " + response[0].rules);
		return response[0].rules;
	});

	//concurrent sends to service registry to get the service instances according to the name in the rule
	//todo: This will change once the rule definition becomes clear.
	waitfor = waitfor.map(function(rule) {

		serviceName = rule.split(',')[0];
		serviceType = rule.split(',')[1];

		console.log("serviceName: " + serviceName);
		var getService_options = {
				uri: 'http://' + config.serviceregistry.ip + ':' + config.serviceregistry.port + '/servicediscovery/service/' + serviceName,
			    json: true // Automatically parses the JSON string in the response
		};
		console.log("service lookup at: " + getService_options.uri);
		return reqprom(getService_options);
	});

	//concurrent test for protocol mismatch and therefore translator engagement
	waitfor = waitfor.map(function(service) {
		console.log("retrieved service type " + service[0].type.toString());
		console.log("desired service type " + serviceType.toString());
		consumerScheme = serviceType.replace("_","");
		console.log("match " + service[0].type.toString().indexOf(serviceType.toString()));
		if(service[0].type.toString().indexOf(serviceType.toString()) === -1) {
			//if the ip address does not contain a period and it does not have the square brackets for ipv6 then add them
			if (service[0].host.indexOf('.') === -1 && service[0].host.indexOf('[') === -1) {
				service[0].host = '[' + service[0].host + ']';
			}

			var xmlbody = 	'<translatorSetup>' +
							'<providerName>' + service[0].type + '</providerName>' +
							'<providerType>' + service[0].type + '</providerType>' +
							'<providerAddress>' + service[0].host + ':' + service[0].port + '</providerAddress>' +
							'<consumerName>' + serviceType + '</consumerName>' +
							'<consumerType>' + serviceType + '</consumerType>' +
							'<consumerAddress>' + serviceAddress + '</consumerAddress>' +
							'</translatorSetup>';
			//request translator to create interfaces
			console.log("xmlbody " + xmlbody);
			var postTranslator_options = {
					uri: 'http://' + config.translator.ip + ':' + config.translator.port + '/translator/',
				    json: false, // Automatically parses the JSON string in the response
				    headers: {'Content-Type': 'application/xml'},
				    method: 'post',
				    body: xmlbody//post message content {providername, providertype, provideraddress, consumername, consumertype, consumeraddress}
			};

			return reqprom(postTranslator_options)
			.then(function(response) {
				console.log("actual:" + response);
				respXML = new xmldoc.XmlDocument(response);
				return respXML;
			}).then(function(respXML) {
				//replace the address value with the end-point details returned from the translator
				service[0].host = respXML.valueWithPath("ip");
				service[0].port = respXML.valueWithPath("port");
				service[0].type = serviceType;

				return service;
			});
		} else {
			return service;
		}
	});

	//
	waitfor = waitfor.map(function(service){//conditional logic tree with promise framework
		console.log("final service " + JSON.stringify(service));
		var path = service[0].properties.property.filter( function(property) { return property.name === "path" ? true : false; })[0].value;
		if(path.startsWith("/")) {
			path = (path[1]==='/'? path.substring(1) : path);
		} else {
			path = "/" + path;
		}
		serviceList.push({
			"name":		service[0].name,
			"address":	consumerScheme + "://" + service[0].host + ":" + service[0].port + path  //path.substring(1)
		});
	});

	//
	waitfor = waitfor.finally(function() {
			console.log({"target":targetSys, "services":serviceList});
			res.setOption('Content-Format','application/json');
			var responsePayload = {"target":targetSys, "services":serviceList};
			res.end(JSON.stringify(responsePayload));
	});
};


text:
package com.hellorin.stickyMoss.companies.domain;

import lombok.*;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

/**
 * Created by hellorin on 21.06.17.
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode(exclude = {"version", "id"})
@Entity(name = "ABSTRACT_COMPANIES")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "companyType")
public abstract class AbstractCompany {
    @Version
    private Long version;

    @Id
    @GeneratedValue
    @Getter
    private Long id;

    @NotNull
    @Getter
    private String name;

    @NotNull
    @Getter
    @Setter
    private CompanySize companySize;

    public AbstractCompany(@NonNull final String name, @NonNull final CompanySize companySize) {
        if (!name.isEmpty()) {
            this.name = name;
            this.companySize = companySize;
        } else {
            throw new IllegalArgumentException("Company's name cannot be empty");
        }
    }
}


text:
/* @flow strict */

import BpkBarchart from './src/BpkBarchart';
import BpkBarchartBars from './src/BpkBarchartBars';
import BpkBarchartDefs from './src/BpkBarchartDefs';
import BpkChartAxis from './src/BpkChartAxis';
import BpkChartGridLines from './src/BpkChartGridLines';
import BpkChartMargin from './src/BpkChartMargin';
import themeAttributes from './src/themeAttributes';

export default BpkBarchart;

export {
  BpkBarchartBars,
  BpkBarchartDefs,
  BpkChartAxis,
  BpkChartGridLines,
  BpkChartMargin,
  themeAttributes,
};


text:
package au.gov.amsa.ais.router;

import au.gov.amsa.ais.router.model.Connection;
import au.gov.amsa.ais.router.model.Group;
import au.gov.amsa.ais.router.model.Port;

public class RouterMain {

    public static void main(String[] args) throws InterruptedException {

        // setup connections
        Connection terrestrial = Connection.builder().id("terrestrial").host("mariweb.amsa.gov.au")
                .port(9010).readTimeoutSeconds(10).retryIntervalSeconds(1).build();

        Connection satellite = Connection.builder().id("satellite").host("mariweb.amsa.gov.au")
                .port(9100).readTimeoutSeconds(10).retryIntervalSeconds(5).build();

        // set up groups
        Group groupAll = Group.builder().id("all").member(terrestrial).member(satellite).build();

        Group kembla = Group.builder().id("Port Kembla").member(terrestrial).filterPattern("Kembla")
                .build();

        // set up ports
        Port portAll = Port.builder().group(groupAll).port(9000).build();

        Port portTerrestrial = Port.builder().group(terrestrial).port(9001).build();

        Port portKembla = Port.builder().group(kembla).port(9002).build();

        // start
        Router.start(portAll, portTerrestrial, portKembla);

        Thread.sleep(Long.MAX_VALUE);

    }
}


text:
Two variables *a* and *b* with types *Ta* and *Tb* are of the *same* type if
1. *Ta* and *Tb* are both denoted by the same type identifier, or
2. *Ta* is declared in a type declaration of the form *Ta* = *Tb*, or
3. *a* and *b* appear in the same identifier list in a variable, record field,
   or formal parameter declaration.

## Equal types [B]
Two types *Ta* and *Tb* are *equal* if
1. *Ta* and *Tb* are the *same* type, or
2. *Ta* and *Tb* are open array types with *equal* element types, or
3. *Ta* and *Tb* are array types with *equal* element types and length, or
4. *Ta* and *Tb* are procedure types whose formal parameter lists *match*, or
5. *Ta* and *Tb* are pointer types with *equal* base types.

## Matching formal parameter lists [C]
Two formal parameter lists *match* if
1. they have the same number of parameters, and
2. they have either *equal* function result types or none, and
3. parameters at corresponding positions have *equal* types, and
4. parameters at corresponding positions are both either value or VAR
   parameters.

## Type extension (base type) [D]
Given a type declaration *Tb* = RECORD (*Ta*) ... END, *Tb* is a
*direct extension* of *Ta*, and *Ta* is a *direct base type* of *Tb*. A type
*Tb* is an *extension* of a type *Ta* (*Ta* is a *base type* of *Tb*) if
1. *Ta* and *Tb* are the *same* types, or
2. *Tb* is a *direct extension* of an *extension* of *Ta*.

If *Pa* = POINTER TO *Ta* and *Pb* = POINTER TO *Tb*, *Pb* is an *extension* of
*Pa* (*Pa* is a *base type* of *Pb*) if *Tb* is an *extension* of *Ta*.

## Assignment compatible [E]
An expression *e* of type *Te* is *assignment compatible* with a variable *v*
of type *Tv* if one of the following conditions hold:
1. *Te* and *Tv* are *equal* and are not open array types;
2. *Te* and *Tv* are record types and *Te* is an *extension* of *Tv* and the
   dynamic type of *v* is *Tv*;
3. *Te* and *Tv* are pointer types and *Te* is an *extension* of *Tv*;
4. *Tv* is a pointer or a procedure type and *e* is NIL;
5. *Tv* is array of CHAR, *e* is a string constant with *n* characters,
    and *n* < *LEN(v)*;
6. *Tv* is ARRAY *n* OF *Ta*, *e* is ARRAY OF *Tb* where *Ta* and *Tb* are
   *equal* and *LEN(e) <= LEN(v)*;
7. *Tv* is a procedure type and *e* is the name of a procedure whose formal
   parameters *match* those of *Tv*.

## Parameters

Let *f* be the formal parameter and *a* the corresponding actual parameter. If
*f* is an open array, then *a* must be *array compatible* to *f* and the lengths
of *f* are taken from *a*. Otherwise *a* must be *parameter compatible* to *f*.

### Array compatible [F]
An actual parameter *a* of type *Ta* is *array compatible* with a formal
parameter *f* of type *Tf* if
1. *Tf* and *Ta* are *equal* types, or
2. *Tf* is an open array, *Ta* is any array, and their element types are *array
   compatible*, or
3. *f* is a value parameter of type ARRAY OF CHAR and *a* is a string.

### Parameter compatible [G]
An actual parameter *a* of type *Ta* is *parameter compatible* with a formal
parameter *f* of type *Tf* if:
1. *Tf* and *Ta* are *equal* types, or
2. *f* is a value parameter and *Ta* is *assignment compatible* (except E.5 and
   E.6) with *Tf*, or
3. *f* is an VAR parameter and *Tf* and *Ta* are record types and *Ta* is an
   *extension* of *Tf*, or
4. *f* is a parameter of type ARRAY *m* OF BYTE and *Ta* is any type with size
   *n* = *m* bytes.

## RETURN expression [H]
The type of the expression must be *assignment compatible* with the result type
specified in the procedure heading and can be neither a record nor an array.

## BYTE and INTEGER [I]
The type BYTE is compatible with the type INTEGER, and vice versa.

## String and CHAR [J]
A string of length 1 can be used wherever a character constant is allowed and
vice versa.


text:
package fr.elongeau.bank.account.core.events;

import fr.elongeau.bank.account.commons.vos.Name;
import fr.elongeau.bank.account.core.EntityId;
import fr.elongeau.bank.account.core.user.User;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.Value;

@Value
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@SuppressWarnings({"PMD.SingularField", "PMD.UnusedPrivateField"})
public final class UserCreated extends AbstractEvent<User> implements Event<User> {

    private final Name name;

    public UserCreated(
            final EntityId<User> id,
            final Name name
                      ) {
        this(
                new EventId<User>(
                        System.nanoTime(),
                        User.class,
                        id
                ),
                name
            );
    }

    public UserCreated(
            final EventId<User> eventId,
            final Name name
                      ) {
        super(eventId);
        this.name = name;
    }
}