text:
/* See README file in this directory for implementation notes, coding
   conventions, et.al.  */

#include "defs.h"
#include "charset.h"
#include "symtab.h" /* Needed by language.h.  */
#include "language.h"
#include "objfiles.h"
#include "value.h"
#include "valprint.h"
#include "guile-internal.h"

/* Return type of print_string_repr.  */

enum string_repr_result
{
  /* The string method returned None.  */
  STRING_REPR_NONE,
  /* The string method had an error.  */
  STRING_REPR_ERROR,
  /* Everything ok.  */
  STRING_REPR_OK
};

/* Display hints.  */

enum display_hint
{
  /* No display hint.  */
  HINT_NONE,
  /* The display hint has a bad value.  */
  HINT_ERROR,
  /* Print as an array.  */
  HINT_ARRAY,
  /* Print as a map.  */
  HINT_MAP,
  /* Print as a string.  */
  HINT_STRING
};

/* The <gdb:pretty-printer> smob.  */

typedef struct
{
  /* This must appear first.  */
  gdb_smob base;

  /* A string representing the name of the printer.  */
  SCM name;

  /* A boolean indicating whether the printer is enabled.  */
  SCM enabled;

  /* A procedure called to look up the printer for the given value.
     The procedure is called as (lookup gdb:pretty-printer value).
     The result should either be a gdb:pretty-printer object that will print
     the value, or #f if the value is not recognized.  */
  SCM lookup;

  /* Note: Attaching subprinters to this smob is left to Scheme.  */
} pretty_printer_smob;

/* The <gdb:pretty-printer-worker> smob.  */

typedef struct
{
  /* This must appear first.  */
  gdb_smob base;

  /* Either #f or one of the supported display hints: map, array, string.
     If neither of those then the display hint is ignored (treated as #f).  */
  SCM display_hint;

  /* A procedure called to pretty-print the value.
     (lambda (printer) ...) -> string | <gdb:lazy-string> | <gdb:value>  */
  SCM to_string;

  /* A procedure called to print children of the value.
     (lambda (printer) ...) -> <gdb:iterator>
     The iterator returns a pair for each iteration: (name . value),
     where "value" can have the same types as to_string.  */
  SCM children;
} pretty_printer_worker_smob;

static const char pretty_printer_smob_name[] =
  "gdb:pretty-printer";
static const char pretty_printer_worker_smob_name[] =
  "gdb:pretty-printer-worker";

/* The tag Guile knows the pretty-printer smobs by.  */
static scm_t_bits pretty_printer_smob_tag;
static scm_t_bits pretty_printer_worker_smob_tag;

/* The global pretty-printer list.  */
static SCM pretty_printer_list;

/* gdb:pp-type-error.  */
static SCM pp_type_error_symbol;

/* Pretty-printer display hints are specified by strings.  */
static SCM ppscm_map_string;
static SCM ppscm_array_string;
static SCM ppscm_string_string;

/* Administrivia for pretty-printer matcher smobs.  */

/* The smob "print" function for <gdb:pretty-printer>.  */

static int
ppscm_print_pretty_printer_smob (SCM self, SCM port, scm_print_state *pstate)
{
  pretty_printer_smob *pp_smob = (pretty_printer_smob *) SCM_SMOB_DATA (self);

  gdbscm_printf (port, "#<%s ", pretty_printer_smob_name);
  scm_write (pp_smob->name, port);
  scm_puts (gdbscm_is_true (pp_smob->enabled) ? " enabled" : " disabled",
	    port);
  scm_puts (">", port);

  scm_remember_upto_here_1 (self);

  /* Non-zero means success.  */
  return 1;
}

/* (make-pretty-printer string procedure) -> <gdb:pretty-printer> */

static SCM
gdbscm_make_pretty_printer (SCM name, SCM lookup)
{
  pretty_printer_smob *pp_smob = (pretty_printer_smob *)
    scm_gc_malloc (sizeof (pretty_printer_smob),
		   pretty_printer_smob_name);
  SCM smob;

  SCM_ASSERT_TYPE (scm_is_string (name), name, SCM_ARG1, FUNC_NAME,
		   _("string"));
  SCM_ASSERT_TYPE (gdbscm_is_procedure (lookup), lookup, SCM_ARG2, FUNC_NAME,
		   _("procedure"));

  pp_smob->name = name;
  pp_smob->lookup = lookup;
  pp_smob->enabled = SCM_BOOL_T;
  smob = scm_new_smob (pretty_printer_smob_tag, (scm_t_bits) pp_smob);
  gdbscm_init_gsmob (&pp_smob->base);

  return smob;
}

/* Return non-zero if SCM is a <gdb:pretty-printer> object.  */

static int
ppscm_is_pretty_printer (SCM scm)
{
  return SCM_SMOB_PREDICATE (pretty_printer_smob_tag, scm);
}

/* (pretty-printer? object) -> boolean */

static SCM
gdbscm_pretty_printer_p (SCM scm)
{
  return scm_from_bool (ppscm_is_pretty_printer (scm));
}

/* Returns the <gdb:pretty-printer> object in SELF.
   Throws an exception if SELF is not a <gdb:pretty-printer> object.  */

static SCM
ppscm_get_pretty_printer_arg_unsafe (SCM self, int arg_pos,
				     const char *func_name)
{
  SCM_ASSERT_TYPE (ppscm_is_pretty_printer (self), self, arg_pos, func_name,
		   pretty_printer_smob_name);

  return self;
}

/* Returns a pointer to the pretty-printer smob of SELF.
   Throws an exception if SELF is not a <gdb:pretty-printer> object.  */

static pretty_printer_smob *
ppscm_get_pretty_printer_smob_arg_unsafe (SCM self, int arg_pos,
					  const char *func_name)
{
  SCM pp_scm = ppscm_get_pretty_printer_arg_unsafe (self, arg_pos, func_name);
  pretty_printer_smob *pp_smob
    = (pretty_printer_smob *) SCM_SMOB_DATA (pp_scm);

  return pp_smob;
}

/* Pretty-printer methods.  */

/* (pretty-printer-enabled? <gdb:pretty-printer>) -> boolean */

static SCM
gdbscm_pretty_printer_enabled_p (SCM self)
{
  pretty_printer_smob *pp_smob
    = ppscm_get_pretty_printer_smob_arg_unsafe (self, SCM_ARG1, FUNC_NAME);

  return pp_smob->enabled;
}

/* (set-pretty-printer-enabled! <gdb:pretty-printer> boolean)
     -> unspecified */

static SCM
gdbscm_set_pretty_printer_enabled_x (SCM self, SCM enabled)
{
  pretty_printer_smob *pp_smob
    = ppscm_get_pretty_printer_smob_arg_unsafe (self, SCM_ARG1, FUNC_NAME);

  pp_smob->enabled = scm_from_bool (gdbscm_is_true (enabled));

  return SCM_UNSPECIFIED;
}

/* (pretty-printers) -> list
   Returns the list of global pretty-printers.  */

static SCM
gdbscm_pretty_printers (void)
{
  return pretty_printer_list;
}

/* (set-pretty-printers! list) -> unspecified
   Set the global pretty-printers list.  */

static SCM
gdbscm_set_pretty_printers_x (SCM printers)
{
  SCM_ASSERT_TYPE (gdbscm_is_true (scm_list_p (printers)), printers,
		   SCM_ARG1, FUNC_NAME, _("list"));

  pretty_printer_list = printers;

  return SCM_UNSPECIFIED;
}

/* Administrivia for pretty-printer-worker smobs.
   These are created when a matcher recognizes a value.  */

/* The smob "print" function for <gdb:pretty-printer-worker>.  */

static int
ppscm_print_pretty_printer_worker_smob (SCM self, SCM port,
					scm_print_state *pstate)
{
  pretty_printer_worker_smob *w_smob
    = (pretty_printer_worker_smob *) SCM_SMOB_DATA (self);

  gdbscm_printf (port, "#<%s ", pretty_printer_worker_smob_name);
  scm_write (w_smob->display_hint, port);
  scm_puts (" ", port);
  scm_write (w_smob->to_string, port);
  scm_puts (" ", port);
  scm_write (w_smob->children, port);
  scm_puts (">", port);

  scm_remember_upto_here_1 (self);

  /* Non-zero means success.  */
  return 1;
}

/* (make-pretty-printer-worker string procedure procedure)
     -> <gdb:pretty-printer-worker> */

static SCM
gdbscm_make_pretty_printer_worker (SCM display_hint, SCM to_string,
				   SCM children)
{
  pretty_printer_worker_smob *w_smob = (pretty_printer_worker_smob *)
    scm_gc_malloc (sizeof (pretty_printer_worker_smob),
		   pretty_printer_worker_smob_name);
  SCM w_scm;

  w_smob->display_hint = display_hint;
  w_smob->to_string = to_string;
  w_smob->children = children;
  w_scm = scm_new_smob (pretty_printer_worker_smob_tag, (scm_t_bits) w_smob);
  gdbscm_init_gsmob (&w_smob->base);
  return w_scm;
}

/* Return non-zero if SCM is a <gdb:pretty-printer-worker> object.  */

static int
ppscm_is_pretty_printer_worker (SCM scm)
{
  return SCM_SMOB_PREDICATE (pretty_printer_worker_smob_tag, scm);
}

/* (pretty-printer-worker? object) -> boolean */

static SCM
gdbscm_pretty_printer_worker_p (SCM scm)
{
  return scm_from_bool (ppscm_is_pretty_printer_worker (scm));
}

/* Helper function to create a <gdb:exception> object indicating that the
   type of some value returned from a pretty-printer is invalid.  */

static SCM
ppscm_make_pp_type_error_exception (const char *message, SCM object)
{
  char *msg = xstrprintf ("%s: ~S", message);
  struct cleanup *cleanup = make_cleanup (xfree, msg);
  SCM exception
    = gdbscm_make_error (pp_type_error_symbol,
			 NULL /* func */, msg,
			 scm_list_1 (object), scm_list_1 (object));

  do_cleanups (cleanup);

  return exception;
}

/* Print MESSAGE as an exception (meaning it is controlled by
   "guile print-stack").
   Called from the printer code when the Scheme code returns an invalid type
   for something.  */

static void
ppscm_print_pp_type_error (const char *message, SCM object)
{
  SCM exception = ppscm_make_pp_type_error_exception (message, object);

  gdbscm_print_gdb_exception (SCM_BOOL_F, exception);
}

/* Helper function for find_pretty_printer which iterates over a list,
   calls each function and inspects output.  This will return a
   <gdb:pretty-printer> object if one recognizes VALUE.  If no printer is
   found, it will return #f.  On error, it will return a <gdb:exception>
   object.

   Note: This has to be efficient and careful.
   We don't want to excessively slow down printing of values, but any kind of
   random crud can appear in the pretty-printer list, and we can't crash
   because of it.  */

static SCM
ppscm_search_pp_list (SCM list, SCM value)
{
  SCM orig_list = list;

  if (scm_is_null (list))
    return SCM_BOOL_F;
  if (gdbscm_is_false (scm_list_p (list))) /* scm_is_pair? */
    {
      return ppscm_make_pp_type_error_exception
	(_("pretty-printer list is not a list"), list);
    }

  for ( ; scm_is_pair (list); list = scm_cdr (list))
    {
      SCM matcher = scm_car (list);
      SCM worker;
      pretty_printer_smob *pp_smob;
      int rc;

      if (!ppscm_is_pretty_printer (matcher))
	{
	  return ppscm_make_pp_type_error_exception
	    (_("pretty-printer list contains non-pretty-printer object"),
	     matcher);
	}

      pp_smob = (pretty_printer_smob *) SCM_SMOB_DATA (matcher);

      /* Skip if disabled.  */
      if (gdbscm_is_false (pp_smob->enabled))
	continue;

      if (!gdbscm_is_procedure (pp_smob->lookup))
	{
	  return ppscm_make_pp_type_error_exception
	    (_("invalid lookup object in pretty-printer matcher"),
	     pp_smob->lookup);
	}

      worker = gdbscm_safe_call_2 (pp_smob->lookup, matcher,
				   value, gdbscm_memory_error_p);
      if (!gdbscm_is_false (worker))
	{
	  if (gdbscm_is_exception (worker))
	    return worker;
	  if (ppscm_is_pretty_printer_worker (worker))
	    return worker;
	  return ppscm_make_pp_type_error_exception
	    (_("invalid result from pretty-printer lookup"), worker);
	}
    }

  if (!scm_is_null (list))
    {
      return ppscm_make_pp_type_error_exception
	(_("pretty-printer list is not a list"), orig_list);
    }

  return SCM_BOOL_F;
}

/* Subroutine of find_pretty_printer to simplify it.
   Look for a pretty-printer to print VALUE in all objfiles.
   If there's an error an exception smob is returned.
   The result is #f, if no pretty-printer was found.
   Otherwise the result is the pretty-printer smob.  */

static SCM
ppscm_find_pretty_printer_from_objfiles (SCM value)
{
  struct objfile *objfile;

  ALL_OBJFILES (objfile)
  {
    objfile_smob *o_smob = ofscm_objfile_smob_from_objfile (objfile);
    SCM pp = ppscm_search_pp_list (ofscm_objfile_smob_pretty_printers (o_smob),
				   value);

    /* Note: This will return if pp is a <gdb:exception> object,
       which is what we want.  */
    if (gdbscm_is_true (pp))
      return pp;
  }

  return SCM_BOOL_F;
}

/* Subroutine of find_pretty_printer to simplify it.
   Look for a pretty-printer to print VALUE in the current program space.
   If there's an error an exception smob is returned.
   The result is #f, if no pretty-printer was found.
   Otherwise the result is the pretty-printer smob.  */

static SCM
ppscm_find_pretty_printer_from_progspace (SCM value)
{
  pspace_smob *p_smob = psscm_pspace_smob_from_pspace (current_program_space);
  SCM pp
    = ppscm_search_pp_list (psscm_pspace_smob_pretty_printers (p_smob), value);

  return pp;
}

/* Subroutine of find_pretty_printer to simplify it.
   Look for a pretty-printer to print VALUE in the gdb module.
   If there's an error a Scheme exception is returned.
   The result is #f, if no pretty-printer was found.
   Otherwise the result is the pretty-printer smob.  */

static SCM
ppscm_find_pretty_printer_from_gdb (SCM value)
{
  SCM pp = ppscm_search_pp_list (pretty_printer_list, value);

  return pp;
}

/* Find the pretty-printing constructor function for VALUE.  If no
   pretty-printer exists, return #f.  If one exists, return the
   gdb:pretty-printer smob that implements it.  On error, an exception smob
   is returned.

   Note: In the end it may be better to call out to Scheme once, and then
   do all of the lookup from Scheme.  TBD.  */

static SCM
ppscm_find_pretty_printer (SCM value)
{
  SCM pp;

  /* Look at the pretty-printer list for each objfile
     in the current program-space.  */
  pp = ppscm_find_pretty_printer_from_objfiles (value);
  /* Note: This will return if function is a <gdb:exception> object,
     which is what we want.  */
  if (gdbscm_is_true (pp))
    return pp;

  /* Look at the pretty-printer list for the current program-space.  */
  pp = ppscm_find_pretty_printer_from_progspace (value);
  /* Note: This will return if function is a <gdb:exception> object,
     which is what we want.  */
  if (gdbscm_is_true (pp))
    return pp;

  /* Look at the pretty-printer list in the gdb module.  */
  pp = ppscm_find_pretty_printer_from_gdb (value);
  return pp;
}

/* Pretty-print a single value, via the PRINTER, which must be a
   <gdb:pretty-printer-worker> object.
   The caller is responsible for ensuring PRINTER is valid.
   If the function returns a string, an SCM containing the string
   is returned.  If the function returns #f that means the pretty
   printer returned #f as a value.  Otherwise, if the function returns a
   <gdb:value> object, *OUT_VALUE is set to the value and #t is returned.
   It is an error if the printer returns #t.
   On error, an exception smob is returned.  */

static SCM
ppscm_pretty_print_one_value (SCM printer, struct value **out_value,
			      struct gdbarch *gdbarch,
			      const struct language_defn *language)
{
  volatile struct gdb_exception except;
  SCM result = SCM_BOOL_F;

  *out_value = NULL;
  TRY_CATCH (except, RETURN_MASK_ALL)
    {
      int rc;
      pretty_printer_worker_smob *w_smob
	= (pretty_printer_worker_smob *) SCM_SMOB_DATA (printer);

      result = gdbscm_safe_call_1 (w_smob->to_string, printer,
				   gdbscm_memory_error_p);
      if (gdbscm_is_false (result))
	; /* Done.  */
      else if (scm_is_string (result)
	       || lsscm_is_lazy_string (result))
	; /* Done.  */
      else if (vlscm_is_value (result))
	{
	  SCM except_scm;

	  *out_value
	    = vlscm_convert_value_from_scheme (FUNC_NAME, GDBSCM_ARG_NONE,
					       result, &except_scm,
					       gdbarch, language);
	  if (*out_value != NULL)
	    result = SCM_BOOL_T;
	  else
	    result = except_scm;
	}
      else if (gdbscm_is_exception (result))
	; /* Done.  */
      else
	{
	  /* Invalid result from to-string.  */
	  result = ppscm_make_pp_type_error_exception
	    (_("invalid result from pretty-printer to-string"), result);
	}
    }

  return result;
}

/* Return the display hint for PRINTER as a Scheme object.
   The caller is responsible for ensuring PRINTER is a
   <gdb:pretty-printer-worker> object.  */

static SCM
ppscm_get_display_hint_scm (SCM printer)
{
  pretty_printer_worker_smob *w_smob
    = (pretty_printer_worker_smob *) SCM_SMOB_DATA (printer);

  return w_smob->display_hint;
}

/* Return the display hint for the pretty-printer PRINTER.
   The caller is responsible for ensuring PRINTER is a
   <gdb:pretty-printer-worker> object.
   Returns the display hint or #f if the hint is not a string.  */

static enum display_hint
ppscm_get_display_hint_enum (SCM printer)
{
  SCM hint = ppscm_get_display_hint_scm (printer);

  if (gdbscm_is_false (hint))
    return HINT_NONE;
  if (scm_is_string (hint))
    {
      if (gdbscm_is_true (scm_string_equal_p (hint, ppscm_array_string)))
	return HINT_STRING;
      if (gdbscm_is_true (scm_string_equal_p (hint, ppscm_map_string)))
	return HINT_STRING;
      if (gdbscm_is_true (scm_string_equal_p (hint, ppscm_string_string)))
	return HINT_STRING;
      return HINT_ERROR;
    }
  return HINT_ERROR;
}

/* A wrapper for gdbscm_print_gdb_exception that ignores memory errors.
   EXCEPTION is a <gdb:exception> object.  */

static void
ppscm_print_exception_unless_memory_error (SCM exception,
					   struct ui_file *stream)
{
  if (gdbscm_memory_error_p (gdbscm_exception_key (exception)))
    {
      char *msg = gdbscm_exception_message_to_string (exception);
      struct cleanup *cleanup = make_cleanup (xfree, msg);

      /* This "shouldn't happen", but play it safe.  */
      if (msg == NULL || *msg == '\0')
	fprintf_filtered (stream, _("<error reading variable>"));
      else
	{
	  /* Remove the trailing newline.  We could instead call a special
	     routine for printing memory error messages, but this is easy
	     enough for now.  */
	  size_t len = strlen (msg);

	  if (msg[len - 1] == '\n')
	    msg[len - 1] = '\0';
	  fprintf_filtered (stream, _("<error reading variable: %s>"), msg);
	}

      do_cleanups (cleanup);
    }
  else
    gdbscm_print_gdb_exception (SCM_BOOL_F, exception);
}

/* Helper for gdbscm_apply_val_pretty_printer which calls to_string and
   formats the result.  */

static enum string_repr_result
ppscm_print_string_repr (SCM printer, enum display_hint hint,
			 struct ui_file *stream, int recurse,
			 const struct value_print_options *options,
			 struct gdbarch *gdbarch,
			 const struct language_defn *language)
{
  struct value *replacement = NULL;
  SCM str_scm;
  enum string_repr_result result = STRING_REPR_ERROR;

  str_scm = ppscm_pretty_print_one_value (printer, &replacement,
					  gdbarch, language);
  if (gdbscm_is_false (str_scm))
    {
      result = STRING_REPR_NONE;
    }
  else if (scm_is_eq (str_scm, SCM_BOOL_T))
    {
      struct value_print_options opts = *options;

      gdb_assert (replacement != NULL);
      opts.addressprint = 0;
      common_val_print (replacement, stream, recurse, &opts, language);
      result = STRING_REPR_OK;
    }
  else if (scm_is_string (str_scm))
    {
      struct cleanup *cleanup;
      size_t length;
      char *string
	= gdbscm_scm_to_string (str_scm, &length,
				target_charset (gdbarch), 0 /*!strict*/, NULL);

      cleanup = make_cleanup (xfree, string);
      if (hint == HINT_STRING)
	{
	  struct type *type = builtin_type (gdbarch)->builtin_char;

	  LA_PRINT_STRING (stream, type, (gdb_byte *) string,
			   length, NULL, 0, options);
	}
      else
	{
	  /* Alas scm_to_stringn doesn't nul-terminate the string if we
	     ask for the length.  */
	  size_t i;

	  for (i = 0; i < length; ++i)
	    {
	      if (string[i] == '\0')
		fputs_filtered ("\\000", stream);
	      else
		fputc_filtered (string[i], stream);
	    }
	}
      result = STRING_REPR_OK;
      do_cleanups (cleanup);
    }
  else if (lsscm_is_lazy_string (str_scm))
    {
      struct value_print_options local_opts = *options;

      local_opts.addressprint = 0;
      lsscm_val_print_lazy_string (str_scm, stream, &local_opts);
      result = STRING_REPR_OK;
    }
  else
    {
      gdb_assert (gdbscm_is_exception (str_scm));
      ppscm_print_exception_unless_memory_error (str_scm, stream);
      result = STRING_REPR_ERROR;
    }

  return result;
}

/* Helper for gdbscm_apply_val_pretty_printer that formats children of the
   printer, if any exist.
   The caller is responsible for ensuring PRINTER is a printer smob.
   If PRINTED_NOTHING is true, then nothing has been printed by to_string,
   and format output accordingly. */

static void
ppscm_print_children (SCM printer, enum display_hint hint,
		      struct ui_file *stream, int recurse,
		      const struct value_print_options *options,
		      struct gdbarch *gdbarch,
		      const struct language_defn *language,
		      int printed_nothing)
{
  pretty_printer_worker_smob *w_smob
    = (pretty_printer_worker_smob *) SCM_SMOB_DATA (printer);
  int is_map, is_array, done_flag, pretty;
  unsigned int i;
  SCM children, status;
  SCM iter = SCM_BOOL_F; /* -Wall */
  struct cleanup *cleanups;

  if (gdbscm_is_false (w_smob->children))
    return;
  if (!gdbscm_is_procedure (w_smob->children))
    {
      ppscm_print_pp_type_error
	(_("pretty-printer \"children\" object is not a procedure or #f"),
	 w_smob->children);
      return;
    }

  cleanups = make_cleanup (null_cleanup, NULL);

  /* If we are printing a map or an array, we want special formatting.  */
  is_map = hint == HINT_MAP;
  is_array = hint == HINT_ARRAY;

  children = gdbscm_safe_call_1 (w_smob->children, printer,
				 gdbscm_memory_error_p);
  if (gdbscm_is_exception (children))
    {
      ppscm_print_exception_unless_memory_error (children, stream);
      goto done;
    }
  /* We combine two steps here: get children, make an iterator out of them.
     This simplifies things because there's no language means of creating
     iterators, and it's the printer object that knows how it will want its
     children iterated over.  */
  if (!itscm_is_iterator (children))
    {
      ppscm_print_pp_type_error
	(_("result of pretty-printer \"children\" procedure is not"
	   " a <gdb:iterator> object"), children);
      goto done;
    }
  iter = children;

  /* Use the prettyformat_arrays option if we are printing an array,
     and the pretty option otherwise.  */
  if (is_array)
    pretty = options->prettyformat_arrays;
  else
    {
      if (options->prettyformat == Val_prettyformat)
	pretty = 1;
      else
	pretty = options->prettyformat_structs;
    }

  done_flag = 0;
  for (i = 0; i < options->print_max; ++i)
    {
      int rc;
      SCM scm_name, v_scm;
      char *name;
      SCM item = itscm_safe_call_next_x (iter, gdbscm_memory_error_p);
      struct cleanup *inner_cleanup = make_cleanup (null_cleanup, NULL);

      if (gdbscm_is_exception (item))
	{
	  ppscm_print_exception_unless_memory_error (item, stream);
	  break;
	}
      if (itscm_is_end_of_iteration (item))
	{
	  /* Set a flag so we can know whether we printed all the
	     available elements.  */
	  done_flag = 1;
	  break;
	}

      if (! scm_is_pair (item))
	{
	  ppscm_print_pp_type_error
	    (_("result of pretty-printer children iterator is not a pair"
	       " or (end-of-iteration)"),
	     item);
	  continue;
	}
      scm_name = scm_car (item);
      v_scm = scm_cdr (item);
      if (!scm_is_string (scm_name))
	{
	  ppscm_print_pp_type_error
	    (_("first element of pretty-printer children iterator is not"
	       " a string"), item);
	  continue;
	}
      name = gdbscm_scm_to_c_string (scm_name);
      make_cleanup (xfree, name);

      /* Print initial "{".  For other elements, there are three cases:
	 1. Maps.  Print a "," after each value element.
	 2. Arrays.  Always print a ",".
	 3. Other.  Always print a ",".  */
      if (i == 0)
	{
         if (printed_nothing)
           fputs_filtered ("{", stream);
         else
           fputs_filtered (" = {", stream);
       }

      else if (! is_map || i % 2 == 0)
	fputs_filtered (pretty ? "," : ", ", stream);

      /* In summary mode, we just want to print "= {...}" if there is
	 a value.  */
      if (options->summary)
	{
	  /* This increment tricks the post-loop logic to print what
	     we want.  */
	  ++i;
	  /* Likewise.  */
	  pretty = 0;
	  break;
	}

      if (! is_map || i % 2 == 0)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  else
	    wrap_here (n_spaces (2 + 2 *recurse));
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("[", stream);
      else if (is_array)
	{
	  /* We print the index, not whatever the child method
	     returned as the name.  */
	  if (options->print_array_indexes)
	    fprintf_filtered (stream, "[%d] = ", i);
	}
      else if (! is_map)
	{
	  fputs_filtered (name, stream);
	  fputs_filtered (" = ", stream);
	}

      if (lsscm_is_lazy_string (v_scm))
	{
	  struct value_print_options local_opts = *options;

	  local_opts.addressprint = 0;
	  lsscm_val_print_lazy_string (v_scm, stream, &local_opts);
	}
      else if (scm_is_string (v_scm))
	{
	  char *output = gdbscm_scm_to_c_string (v_scm);

	  fputs_filtered (output, stream);
	  xfree (output);
	}
      else
	{
	  SCM except_scm;
	  struct value *value
	    = vlscm_convert_value_from_scheme (FUNC_NAME, GDBSCM_ARG_NONE,
					       v_scm, &except_scm,
					       gdbarch, language);

	  if (value == NULL)
	    {
	      ppscm_print_exception_unless_memory_error (except_scm, stream);
	      break;
	    }
	  common_val_print (value, stream, recurse + 1, options, language);
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("] = ", stream);

      do_cleanups (inner_cleanup);
    }

  if (i)
    {
      if (!done_flag)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  fputs_filtered ("...", stream);
	}
      if (pretty)
	{
	  fputs_filtered ("\n", stream);
	  print_spaces_filtered (2 * recurse, stream);
	}
      fputs_filtered ("}", stream);
    }

 done:
  do_cleanups (cleanups);

  /* Play it safe, make sure ITER doesn't get GC'd.  */
  scm_remember_upto_here_1 (iter);
}

/* This is the extension_language_ops.apply_val_pretty_printer "method".  */

enum ext_lang_rc
gdbscm_apply_val_pretty_printer (const struct extension_language_defn *extlang,
				 struct type *type, const gdb_byte *valaddr,
				 int embedded_offset, CORE_ADDR address,
				 struct ui_file *stream, int recurse,
				 const struct value *val,
				 const struct value_print_options *options,
				 const struct language_defn *language)
{
  struct gdbarch *gdbarch = get_type_arch (type);
  SCM exception = SCM_BOOL_F;
  SCM printer = SCM_BOOL_F;
  SCM val_obj = SCM_BOOL_F;
  struct value *value;
  enum display_hint hint;
  struct cleanup *cleanups;
  int result = EXT_LANG_RC_NOP;
  enum string_repr_result print_result;

  /* No pretty-printer support for unavailable values.  */
  if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
    return EXT_LANG_RC_NOP;

  if (!gdb_scheme_initialized)
    return EXT_LANG_RC_NOP;

  cleanups = make_cleanup (null_cleanup, NULL);

  /* Instantiate the printer.  */
  if (valaddr)
    valaddr += embedded_offset;
  value = value_from_contents_and_address (type, valaddr,
					   address + embedded_offset);

  set_value_component_location (value, val);
  /* set_value_component_location resets the address, so we may
     need to set it again.  */
  if (VALUE_LVAL (value) != lval_internalvar
      && VALUE_LVAL (value) != lval_internalvar_component
      && VALUE_LVAL (value) != lval_computed)
    set_value_address (value, address + embedded_offset);

  val_obj = vlscm_scm_from_value (value);
  if (gdbscm_is_exception (val_obj))
    {
      exception = val_obj;
      result = EXT_LANG_RC_ERROR;
      goto done;
    }

  printer = ppscm_find_pretty_printer (val_obj);

  if (gdbscm_is_exception (printer))
    {
      exception = printer;
      result = EXT_LANG_RC_ERROR;
      goto done;
    }
  if (gdbscm_is_false (printer))
    {
      result = EXT_LANG_RC_NOP;
      goto done;
    }
  gdb_assert (ppscm_is_pretty_printer_worker (printer));

  /* If we are printing a map, we want some special formatting.  */
  hint = ppscm_get_display_hint_enum (printer);
  if (hint == HINT_ERROR)
    {
      /* Print the error as an exception for consistency.  */
      SCM hint_scm = ppscm_get_display_hint_scm (printer);

      ppscm_print_pp_type_error ("Invalid display hint", hint_scm);
      /* Fall through.  A bad hint doesn't stop pretty-printing.  */
      hint = HINT_NONE;
    }

  /* Print the section.  */
  print_result = ppscm_print_string_repr (printer, hint, stream, recurse,
					  options, gdbarch, language);
  if (print_result != STRING_REPR_ERROR)
    {
      ppscm_print_children (printer, hint, stream, recurse, options,
			    gdbarch, language,
			    print_result == STRING_REPR_NONE);
    }

  result = EXT_LANG_RC_OK;

 done:
  if (gdbscm_is_exception (exception))
    ppscm_print_exception_unless_memory_error (exception, stream);
  do_cleanups (cleanups);
  return result;
}

/* Initialize the Scheme pretty-printer code.  */

static const scheme_function pretty_printer_functions[] =
{
  { "make-pretty-printer", 2, 0, 0, gdbscm_make_pretty_printer,
    "\
Create a <gdb:pretty-printer> object.\n\
\n\
  Arguments: name lookup\n\
    name:   a string naming the matcher\n\
    lookup: a procedure:\n\
      (pretty-printer <gdb:value>) -> <gdb:pretty-printer-worker> | #f." },

  { "pretty-printer?", 1, 0, 0, gdbscm_pretty_printer_p,
    "\
Return #t if the object is a <gdb:pretty-printer> object." },

  { "pretty-printer-enabled?", 1, 0, 0, gdbscm_pretty_printer_enabled_p,
    "\
Return #t if the pretty-printer is enabled." },

  { "set-pretty-printer-enabled!", 2, 0, 0,
    gdbscm_set_pretty_printer_enabled_x,
    "\
Set the enabled flag of the pretty-printer.\n\
Returns \"unspecified\"." },

  { "make-pretty-printer-worker", 3, 0, 0, gdbscm_make_pretty_printer_worker,
    "\
Create a <gdb:pretty-printer-worker> object.\n\
\n\
  Arguments: display-hint to-string children\n\
    display-hint: either #f or one of \"array\", \"map\", or \"string\"\n\
    to-string:    a procedure:\n\
      (pretty-printer) -> string | #f | <gdb:value>\n\
    children:     either #f or a procedure:\n\
      (pretty-printer) -> <gdb:iterator>" },

  { "pretty-printer-worker?", 1, 0, 0, gdbscm_pretty_printer_worker_p,
    "\
Return #t if the object is a <gdb:pretty-printer-worker> object." },

  { "pretty-printers", 0, 0, 0, gdbscm_pretty_printers,
    "\
Return the list of global pretty-printers." },

  { "set-pretty-printers!", 1, 0, 0,
    gdbscm_set_pretty_printers_x,
    "\
Set the list of global pretty-printers." },

  END_FUNCTIONS
};

void
gdbscm_initialize_pretty_printers (void)
{
  pretty_printer_smob_tag
    = gdbscm_make_smob_type (pretty_printer_smob_name,
			     sizeof (pretty_printer_smob));
  scm_set_smob_print (pretty_printer_smob_tag,
		      ppscm_print_pretty_printer_smob);

  pretty_printer_worker_smob_tag
    = gdbscm_make_smob_type (pretty_printer_worker_smob_name,
			     sizeof (pretty_printer_worker_smob));
  scm_set_smob_print (pretty_printer_worker_smob_tag,
		      ppscm_print_pretty_printer_worker_smob);

  gdbscm_define_functions (pretty_printer_functions, 1);

  pretty_printer_list = SCM_EOL;

  pp_type_error_symbol = scm_from_latin1_symbol ("gdb:pp-type-error");

  ppscm_map_string = scm_from_latin1_string ("map");
  ppscm_array_string = scm_from_latin1_string ("array");
  ppscm_string_string = scm_from_latin1_string ("string");
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="author" content="@renodesper">
    <meta name="description" content="Thoughts, stories and ideas.">
    <meta name="keywords" content="blog,developer,personal">

    <base href="https://renodesper.com">
    <title>Tag: Date · A Place to Remember</title>

    <link rel="canonical" href="https://renodesper.com/tags/date/">

    <link href="https://fonts.googleapis.com/css?family=Lato:400,700|Merriweather:300,700|Source+Code+Pro:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" integrity="sha256-oSrCnRYXvHG31SBifqP2PM1uje7SJUyX0nTwO2RJV54=" crossorigin="anonymous" />

      <link rel="stylesheet" href="https://renodesper.com/css/coder.min.4daad1498fb945968ce48059545027b5a31dbeea575449abe6098326206584e0.css" integrity="sha256-TarRSY+5RZaM5IBZVFAntaMdvupXVEmr5gmDJiBlhOA=" crossorigin="anonymous" media="screen" />

    <link rel="icon" type="image/png" href="https://renodesper.com/images/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="https://renodesper.com/images/favicon-16x16.png" sizes="16x16">

      <link href="https://renodesper.com/tags/date/index.xml" rel="alternate" type="application/rss+xml" title="A Place to Remember" />
      <link href="https://renodesper.com/tags/date/index.xml" rel="feed" type="application/rss+xml" title="A Place to Remember" />

    <meta name="generator" content="Hugo 0.49.2" />

      A Place to Remember

    <input type="checkbox" id="menu-toggle" />

            Blog

            Tags

            About Me

Tag: Date

      March 13, 2015
      Timestamp and Date in Apache Phoenix

redpajama_set_name: RedPajamaGithub


text:
<?
	include("langsettings.php");
?>

<meta name="author" content="Kai Oswald Seidler">
<link href="xampp.css" rel="stylesheet" type="text/css">

<?=$TEXT['navi-xampp']?>

<?=$TEXT['navi-welcome']?>

<?=$TEXT['navi-status']?>

<?=$TEXT['navi-security']?>

<?=$TEXT['navi-doc']?>

<?=$TEXT['navi-components']?>

<?=$TEXT['navi-demos']?>

<?=$TEXT['navi-cdcol']?>

<?=$TEXT['navi-bio']?>

<a class=n target=content onClick="h(this);" href=guestbook-<?=file_get_contents("lang.tmp")?>.pl><?=$TEXT['navi-guest']?>

<?=$TEXT['navi-iart']?>

phpinfo()

<?=$TEXT['navi-phonebook']?>

<?=$TEXT['navi-tools']?>

<?=$TEXT['navi-phpmyadmin']?>

<?=$TEXT['navi-webalizer']?>

©2002-2011

<? if(file_get_contents("lang.tmp")=="de") { ?>

<? } else { ?>

<? } ?>


text:
{-# LANGUAGE CPP #-}

module DBUtil where

import           Control.Applicative         ((<$>))
import           Database.Persist
import           Database.Persist.GenericSql

import           Model

-- #define SQLite

#ifdef SQLite

import           Database.Persist.Sqlite     (withSqliteConn)

runSql :: SqlPersist IO a -> IO a
runSql = withSqliteConn dbfile . runSqlConn
  where
    dbfile = "db.sqlite3"

#else

import           Data.Monoid                 ((<>))
import           Data.Text.Encoding          (encodeUtf8)
import           Database.Persist.Postgresql (withPostgresqlConn)
import           Web.Heroku                  (dbConnParams)

runSql :: SqlPersist IO a -> IO a
runSql query = do
    params <- dbConnParams
    let connStr = foldr (\(k,v) t -> t <> (encodeUtf8 $ k <> "=" <> v <> " "))
                  "" params
    withPostgresqlConn connStr $ runSqlConn query

#endif

readPosts :: IO [Post]
readPosts = map entityVal <$> (runSql $ selectList [] [Desc PostId, LimitTo 50])

addPost :: Post -> IO ()
addPost post = runSql $ insert post >> return ()


text:
@class ZXGenericGF, ZXIntArray;

/**
 * Implements Reed-Solomon enbcoding, as the name implies.
 */
@interface ZXReedSolomonEncoder : NSObject

- (id)initWithField:(ZXGenericGF *)field;
- (void)encode:(ZXIntArray *)toEncode ecBytes:(int)ecBytes;

@end


text:
// <copyright file="RobotCommandStub.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

namespace AdiePlaygroundTests.Common.Command
{
    using AdiePlayground.Common.Command;

    internal sealed class RobotCommandStub : RobotCommand
    {
        public RobotCommandStub(IRobot robot)
            : base(robot)
        {
        }

        public override void Execute()
        {
        }

        public override void Undo()
        {
        }
    }
}


text:
require 'oxblood/commands/scan'

module Oxblood
  module Commands
    module Sets
      # Add one or more members to a set
      # @see http://redis.io/commands/sadd
      #
      # @param [String] key under which store set
      # @param [String, Array<String>] members to store
      #
      # @return [Integer] the number of elements that were added to the set,
      #   not including all the elements already present into the set.
      def sadd(key, *members)
        run(*members.unshift(:SADD, key))
      end

      # Get the number of members in a set
      # @see http://redis.io/commands/scard
      #
      # @param [String] key
      #
      # @return [Integer] the cardinality (number of elements) of the set, or 0 if
      #   key does not exist
      def scard(key)
        run(:SCARD, key)
      end

      # Subtract multiple sets
      # @see http://redis.io/commands/sdiff
      #
      # @param [String, Array<String>] keys
      #
      # @return [Array] array with members of the resulting set
      def sdiff(*keys)
        run(*keys.unshift(:SDIFF))
      end

      # Subtract multiple sets and store the resulting set in a key
      # @see http://redis.io/commands/sdiffstore
      #
      # @param [String] destination key
      # @param [String, Array<String>] keys of sets to diff
      #
      # @return [Integer] the number of elements in the resulting set
      def sdiffstore(destination, *keys)
        run(*keys.unshift(:SDIFFSTORE, destination))
      end

      # Intersect multiple sets
      # @see http://redis.io/commands/sinter
      #
      # @param [String, Array<String>] keys to intersect
      #
      # @return [Array] array with members of the resulting set
      def sinter(*keys)
        run(*keys.unshift(:SINTER))
      end

      # Intersect multiple sets and store the resulting key in a key
      # @see http://redis.io/commands/sinterstore
      #
      # @param [String] destination key
      # @param [String, Array<String>] keys of sets to intersect
      #
      # @return [Integer] the number of elements in the resulting set
      def sinterstore(destination, *keys)
        run(*keys.unshift(:SINTERSTORE, destination))
      end

      # Determine if a given value is a member of a set
      # @see http://redis.io/commands/sismember
      #
      # @param [String] key
      # @param [String] member
      #
      # @return [Integer] 1 if the element is a member of the set or
      #   0 if the element is not a member of the set, or if key does not exist
      def sismember(key, member)
        run(:SISMEMBER, key, member)
      end

      # Get all the members in a set
      # @see http://redis.io/commands/smembers
      #
      # @param [String] key
      #
      # @return [Array] all elements of the set
      def smembers(key)
        run(:SMEMBERS, key)
      end

      # Move a member from one set to another
      # @see http://redis.io/commands/smove
      #
      # @param [String] source
      # @param [String] destination
      # @param [String] member
      #
      # @return [Integer] 1 if the element is moved, or 0 if the element is not
      #   a member of source and no operation was performed
      def smove(source, destination, member)
        run(:SMOVE, source, destination, member)
      end

      # Remove and return one or multiple random members from a set
      # @see http://redis.io/commands/spop
      #
      # @param [String] key
      # @param [Integer] count
      #
      # @return [String] without the additional count argument the command returns
      #   the removed element, or nil when key does not exist
      # @return [Array] when the additional count argument is passed the command
      #   returns an array of removed elements, or an empty array when key does
      #   not exist.
      def spop(key, count = nil)
        args = [:SPOP, key]
        args << count if count
        run(*args)
      end

      # Get one or multiple random members from a set
      # @see http://redis.io/commands/srandmember
      #
      # @param [String] key
      # @param [Integer] count
      #
      # @return [String, nil] without the additional count argument the command
      #   returns string with the randomly selected element, or nil when key
      #   does not exist
      # @return [Array] when the additional count argument is passed the command
      #   returns an array of elements, or an empty array when key does not exist
      def srandmember(key, count = nil)
        args = [:SRANDMEMBER, key]
        args << count if count
        run(*args)
      end

      # Remove one or more members from a set
      # @see http://redis.io/commands/srem
      #
      # @param [String] key
      # @param [Array] members to remove
      #
      # @return [Integer] the number of members that were removed from the set,
      #   not including non existing members
      def srem(key, *members)
        run(*members.unshift(:SREM, key))
      end

      # Add multiple sets
      # @see http://redis.io/commands/sunion
      #
      # @param [String, Array<String>] keys
      #
      # @return [Array] list with members of the resulting set
      def sunion(*keys)
        run(*keys.unshift(:SUNION))
      end

      # Add multipe sets and store the resulting set in a key
      # @see http://redis.io/commands/sunionstore
      #
      # @param [String] destination
      # @param [String, Array<String>] keys
      #
      # @return [Integer] the number of elements in the resulting set
      def sunionstore(destination, *keys)
        run(*keys.unshift(:SUNIONSTORE, destination))
      end

      # Incrementally iterate Set elements
      # @see https://redis.io/commands/sscan
      #
      # @param [Integer] cursor
      # @param [Hash] opts
      #
      # @option opts [Integer] :count Amount of work that should be done at
      #   every call in order to retrieve elements from the collection.
      # @option opts [String] :match
      #
      # @return [Array] two elements array, where the first element is String
      #   representing an unsigned 64 bit number (the cursor), and the second
      #   element is an Array of elements.
      def sscan(key, cursor, opts = {})
        args = [:SSCAN, key, cursor]
        Scan.merge_opts!(args, opts)
        run(*args)
      end
    end
  end
end


text:
package nl.mierasmade.values;

import org.springframework.stereotype.Component;

import com.github.javafaker.Faker;

@Component
public class StreetName implements FakerValue {

	private static final String NAME = "Street Name";

	private Faker faker;

	@Override
	public void setFaker(Faker faker) {
		this.faker = faker;
	}

	@Override
	public String getValue() {
		return faker.address().streetName();
	}

	@Override
	public String toString() {
		return NAME;
	}

	@Override
	public int compareTo(FakerValue other) {
		return this.toString().compareTo(other.toString());
	}
}


text:
import { breakPoints, bodies } from '../../common/styles/variables'

export default `
    a {
        text-decoration: none;
    }

    a:hover {
        text-decoration: underline;
    }

`


text:
<?php

namespace Prime\Database\SQL;

/**
 * @name SqlColumnDataTrait
 * @package Prime\Database\SQL
 * @since29/10/2017
 * @author TomSailor
 */
trait SqlColumnDataTrait
{

    use SqlPrepareValueTrait;

    /**
     * @var array
     */
    private $columnsValues;

    /**
     * Define o valor para a coluna
     * @param string $column
     * @param mixed $value
     */
    public function setColumnData(string $column, $value)
    {
        $this->columnsValues[$column] = $this->prepareValue($value);
    }

    /**
     * Retorna o valor definido para a respectiva coluna
     * @param string $name O nome da coluna
     * @return string O valor da coluna
     */
    public function getColumnValue($name)
    {
        return $this->columnsValues[$name];
    }

    /**
     * Retorna returna uma string referente a coluna no padrão "column = value"
     * @param string $name O nome da coluna
     * @return string Uma string contendo column = value
     */
    public function getColumnSet(string $name): string
    {
        if (isset($this->columnsValues[$name])) {
            return "{$name} = {$this->columnsValues[$name]}";
        }
    }

    /**
     * Retorna um objeto array contendo todas colunas e seus respectivos valores
     * @return array
     */
    private function getColumns(): array
    {
        return $this->columnsValues;
    }

}


text:
'use strict';

angular.module('cloudworkerApp').controller('ActionDialogController',
    ['$scope', '$stateParams', '$uibModalInstance', 'entity', 'Action', 'Node',
        function($scope, $stateParams, $uibModalInstance, entity, Action, Node) {

        $scope.action = entity;
        $scope.nodes = Node.query();
        $scope.load = function(id) {
            Action.get({id : id}, function(result) {
                $scope.action = result;
            });
        };

        var onSaveSuccess = function (result) {
            $scope.$emit('cloudworkerApp:actionUpdate', result);
            $uibModalInstance.close(result);
            $scope.isSaving = false;
        };

        var onSaveError = function (result) {
            $scope.isSaving = false;
        };

        $scope.save = function () {
            $scope.isSaving = true;
            if ($scope.action.id != null) {
                Action.update($scope.action, onSaveSuccess, onSaveError);
            } else {
                Action.save($scope.action, onSaveSuccess, onSaveError);
            }
        };

        $scope.clear = function() {
            $uibModalInstance.dismiss('cancel');
        };
        $scope.datePickerForDate = {};

        $scope.datePickerForDate.status = {
            opened: false
        };

        $scope.datePickerForDateOpen = function($event) {
            $scope.datePickerForDate.status.opened = true;
        };
}]);


text:
package cl.json.social;

import android.content.ActivityNotFoundException;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableMap;

/**
 * Created by disenodosbbcl on 23-07-16.
 */
public class WhatsAppShare extends SingleShareIntent {

    private static final String PACKAGE = "com.whatsapp";
    private static final String PLAY_STORE_LINK = "market://details?id=com.whatsapp";

    public WhatsAppShare(ReactApplicationContext reactContext) {
        super(reactContext);
    }
    @Override
    public void open(ReadableMap options) throws ActivityNotFoundException {
        super.open(options);
        //  extra params here
        this.openIntentChooser();
    }
    @Override
    protected String getPackage() {
        return PACKAGE;
    }

    @Override
    protected String getDefaultWebLink() {
        return null;
    }

    @Override
    protected String getPlayStoreLink() {
        return PLAY_STORE_LINK;
    }
}


text:
package main

import (
	"fmt"
	"log"
)

func SendEmail(address, message, uuid string) {
	log.Println("[", uuid, "] Sending email to:", address)
	subject := "Chicken Little message received"
	plain := fmt.Sprint("You've received a message from the Chicken Little alert system:\n\n", message,
		"\n\n", "Stop notifications for this alert: ", c.Config.Service.ClickURLBase, "/", uuid, "/stop")
	html := fmt.Sprint("You've received a message from the Chicken Little alert system:

",
		message, "

Stop notifications for this alert")

	if c.Config.Integrations.Mailgun.Enabled {
		SendEmailMailgun(address, subject, plain, html)
	} else {
		SendEmailSMTP(address, subject, plain, html)
	}
}


text:
                  Keluarga Cactus {{ site.description | escape }}

                   @{{ site.facebook_username }}

                   @{{ site.instagram_username }}

                   {{ site.whatsapp_readable }} (Whatsapp/SMS)

Link

Cara Membeli

Konfirmasi Pembayaran

FAQ

Cara Merawat

Kontak

About

Produk

Kaktus

Sukulen

Pot

Cek Pengiriman

Anda bisa memeriksa paket kiriman anda dengan memasukan nomor resi pada kotak dibawah.

                  <form method="GET" action="http://www.cekresi.com" target="_blank" id="cekresiform" name="cekresiform">
                     <input type="text"  name="noresi" value="" placeholder="Nomor Resi"/>
                     <input type="hidden" name="v" value="w1"/>
                     <button type="submit"  id="cekbutton">Cek Resi</button>
                     Powered by cekresi.com
                  </form>

© 2017 Keluarga Cactus powered by uCommerce.

                  Grow Cactus , Grow Love


text:
#include <malloc.h>
#include <string.h>

#include <SuperMap.h>
#define __SUPERMAP_MESSAGE_DEFINE__
#include <../Message/Inc/SuperMapMessage.h>

#ifdef _WIN32

#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers

#include <windows.h>
#include <crtdbg.h>

#include <limits.h>
#undef min
#undef max

static wchar_t module[MAX_PATH];
static wchar_t home_dir[MAX_PATH];

wchar_t home_path[MAX_PATH]; //

///
/// Calls on the FDO Client services to register the SuperMap SDB/SDX provider.
/// Use dynamic proc address binding because there will not be a path set up yet.
///
/// <returns>S_FALSE if there was an error, S_OK otherwise.</returns>
extern "C" FDO_SUPERMAP_API HRESULT DllRegisterServer ()
{
    HRESULT ret;

	ret = S_FALSE;
    // Find a matching provider in the Provider Registry.
    IProviderRegistry* registry = FdoFeatureAccessManager::GetProviderRegistry();

    registry->RegisterProvider (
        SUPERMAP_PROVIDER_NAME,
        /*WTEXT(SUPERMAP_PROVIDER_DEFAULT_DISPLAY_NAME),*/
		NlsMsgGet(SUPERMAP_PROVIDER_DISPLAY_NAME, SUPERMAP_PROVIDER_DEFAULT_DISPLAY_NAME),
		/*WTEXT(SUPERMAP_PROVIDER_DEFAULT_DESCRIPTION),*/
		NlsMsgGet(SUPERMAP_PROVIDER_DESCRIPTION, SUPERMAP_PROVIDER_DEFAULT_DESCRIPTION),
        SUPERMAP_PROVIDER_VERSION,
        SUPERMAP_FDO_VERSION,
        module,
        false);
    ret = S_OK;

    return (ret);
}

///
/// Calls on the FDO Client services to unregister the SuperMap SDB/SDX provider.
/// Use dynamic proc address binding because there will not be a path set up yet.
///
/// <returns>S_FALSE if there was an error, S_OK otherwise.</returns>
extern "C" FDO_SUPERMAP_API HRESULT DllUnregisterServer ()
{
    // Find a matching provider in the Provider Registry.
    IProviderRegistry* registry = FdoFeatureAccessManager::GetProviderRegistry();
	registry->UnregisterProvider (SUPERMAP_PROVIDER_NAME);
	return S_OK;
}

BOOL APIENTRY DllMain (HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
	DWORD nchars;
	wchar_t* last;
	BOOL ret;

	// UNCOMMENT THE FOLLOWING CODE TO HELP DISCOVER MEMORY LEAKS OR PREMATURE MEMORY DEALLOCATIONS;
	// WARNING: THIS CAN MAKE THE CODE RUN EXTREMELY SLOWLY IN CERTAIN PLACES!
	//
	//int debugFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	//_CrtSetDbgFlag(debugFlags | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF);

	ret = TRUE;
	if (DLL_PROCESS_ATTACH == ul_reason_for_call)
	{
		// hModule - The value is the base address of the DLL.
		// The HINSTANCE of a DLL is the same as the HMODULE of the DLL,
		// so hinstDLL can be used in calls to functions that require a module handle.
		nchars = GetModuleFileNameW ((HINSTANCE)hModule, module, MAX_PATH);
		if (0 == nchars)
			ret = FALSE;
		else
		{
			// scan the string for the last occurrence of a slash
			wcscpy (home_dir, module);
			last = wcsrchr (home_dir, L'\\');
			if (NULL == last)
				ret = FALSE;
			else
			{
				last++; // move past the slash
				*last = L'\0'; // null terminate it there
			}
		}

		TRACE(_T("ÆôÓÃÁ¬½Ó³Ø"));
		// Æô¶¯Á¬½Ó³Ø
		SuperMapConnectionPool::GetInstance();

		// ³õ'»¯ÅäÖÃÐÅÏ¢
		wcscpy(home_path,home_dir);
		SuperMapConfig::Init();
	}
	else if(DLL_PROCESS_DETACH == ul_reason_for_call)
	{
		// ɾ³ý
		SuperMapConnectionPool::GetInstance()->Dispose();
	}

	return (ret);
}
#endif // _WIN32

// external access to connection for client services
extern "C" FDO_SUPERMAP_API FdoIConnection* CreateConnection ()
{
	return (new SuperMapConnection ());
}

SuperMapConnection::SuperMapConnection (void):
	m_ConnectionString ((wchar_t*)NULL),
	m_ConnectionState(FdoConnectionState_Closed)
	//m_pTransaction(NULL)
{
	m_strConnectionSession = "";
	m_bCreate = false;
}

SuperMapConnection::~SuperMapConnection (void)
{
    Close ();
}

// Dispose this object.
// <returns>Returns nothing</returns>
void SuperMapConnection::Dispose ()
{
	delete this;
}

/// Gets an FdoIConnectionCapabilities interface describing the capabilities
/// of the connection.
/// <returns>Returns the connection capabilities</returns>
FdoIConnectionCapabilities* SuperMapConnection::GetConnectionCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetConnectionCapabilities ¡£\n"));
	return (new SuperMapConnectionCapabilities ());
}

/// Gets an FdoISchemaCapabilities interface describing the provider's support for the feature schema.
/// <returns>Returns schema capabilities</returns>
FdoISchemaCapabilities* SuperMapConnection::GetSchemaCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetSchemaCapabilities ¡£\n"));
	return (new SuperMapSchemaCapabilities ());
}

/// Gets an FdoICommandCapabilities interface describing the commands a provider supports.
/// <returns>Returns the command capabilities</returns>
FdoICommandCapabilities* SuperMapConnection::GetCommandCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetCommandCapabilities ¡£\n"));
	return (new SuperMapCommandCapabilities ());
}

/// Gets an FdoIFilterCapabilities interface describing the provider's support for filters.
/// <returns>Returns the filter capabilities</returns>
FdoIFilterCapabilities* SuperMapConnection::GetFilterCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetFilterCapabilities ¡£\n"));
	return (new SuperMapFilterCapabilities ());
}

/// Gets an FdoIExpressionCapabilities interface describing the provider's support for expressions.
/// <returns>Returns the expression capabilities</returns>
FdoIExpressionCapabilities* SuperMapConnection::GetExpressionCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetExpressionCapabilities ¡£\n"));
	return (new SuperMapExpressionCapabilities ());
}

/// Gets an FdoIRasterCapabilities interface describing the provider's support for raster images.
/// <returns>Returns the raster capabilities</returns>
FdoIRasterCapabilities* SuperMapConnection::GetRasterCapabilities (void)
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetRasterCapabilities ¡£\n"));
	return (new SuperMapRasterCapabilities ());
}

/// Gets an FdoITopologyCapabilities interface describing the provider's support for topology.
/// <returns>Returns the topology capabilities</returns>
FdoITopologyCapabilities* SuperMapConnection::GetTopologyCapabilities ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetTopologyCapabilities ¡£\n"));
	return (new SuperMapTopologyCapabilities ());
}

/// Gets an FdoIGeometryCapabilities interface describing the provider's support for geometry
FdoIGeometryCapabilities* SuperMapConnection::GetGeometryCapabilities()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetGeometryCapabilities ¡£\n"));
	return (new SuperMapGeometryCapabilities());
}

/// Gets the connection string used to open a DataStore.
/// <returns>Returns the connection string</returns>
FdoString* SuperMapConnection::GetConnectionString ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::GetConnectionString [%ls]¡£\n"), m_ConnectionString);
	return (m_ConnectionString);
}

/// Sets the connection string used to open a DataStore. SetConnectionString can only be set while the
/// connection is closed.
/// <param name="value">Input the connection string</param>
/// <returns>Returns nothing</returns>
void SuperMapConnection::SetConnectionString (FdoString* value)
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::SetConnectionString(%ls)¡£\n"), value);
	FdoConnectionState state = GetConnectionState();
	if (state == FdoConnectionState_Closed || state == FdoConnectionState_Pending)
	{
		// Update the connection string:
		m_ConnectionString = value;

		// Update the connection property dictionary:
		FdoPtr<FdoIConnectionInfo> connInfo = GetConnectionInfo();
		FdoPtr<FdoCommonConnPropDictionary> connDict = dynamic_cast<FdoCommonConnPropDictionary*>(connInfo->GetConnectionProperties());
		connDict->UpdateFromConnectionString(m_ConnectionString);
	}
	else
		throw FdoException::Create (NlsMsgGet(SUPERMAP_CONNECTION_ALREADY_OPEN, "The connection is already open."));
}

/// Gets an FdoIConnectionInfo interface that can be used to interrogate and set connection properties.
/// <returns>Returns the connection info</returns>
FdoIConnectionInfo* SuperMapConnection::GetConnectionInfo ()
{
	if (m_ConnectionInfo == NULL)
		m_ConnectionInfo = new SuperMapConnectionInfo (this);
	return FDO_SAFE_ADDREF(m_ConnectionInfo.p);
}

/// Gets the current state of the connection.
/// <returns>Returns the current state of the connection</returns>
FdoConnectionState SuperMapConnection::GetConnectionState ()
{
	TRACE(_T("µ÷Óà SuperMapConnection::GetConnectionState ·µ»Ø[0:Busy,1:Closed,2:Open,3:Pending] %d¡£\n"), m_ConnectionState);
	return (m_ConnectionState);
}

/// Gets the number of milliseconds to wait while trying to establish a
/// connection before terminating the attempt and generating an error. If
/// the provider does not support the timeout capability 0 will be returned
/// <returns>Returns the time to wait (in milliseconds)</returns>
FdoInt32 SuperMapConnection::GetConnectionTimeout ()
{
	return (0);
}

/// Sets the number of milliseconds to wait while trying to establish a
/// connection before terminating the attempt and generating an error. If
/// the provider does not support the timeout capability then attempting to
/// set a timeout will result in an exception
/// <param name="value">Input the time to wait (in milliseconds)</param>
/// <returns>Returns nothing</returns>
void SuperMapConnection::SetConnectionTimeout (FdoInt32 value)
{
	throw FdoException::Create (NlsMsgGet(SUPERMAP_CONNECTION_TIMEOUT_UNSUPPORTED,
		"Connection timeout is not supported."));
}

/// Opens a feature connection with the settings specified by the
/// ConnectionString attribute of the provider-specific feature connection
/// object.
/// <returns>Returns nothing</returns>
FdoConnectionState SuperMapConnection::Open ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::Open ...\n"));

	if (GetConnectionState() == FdoConnectionState_Open)
		throw FdoException::Create(FdoException::NLSGetMessage(FDO_NLSID(FDO_103_CONNECTION_ALREADY_OPEN)));

	// Disconnect if currently 'partially' connected (but not if already 'fully' connected):
	if (GetConnectionState() == FdoConnectionState_Pending)
		Close();

	/* DEL *****************************************
	FdoPtr<ConnectionProperty> datastoreProperty = dictionary->FindProperty(CONNECTIONPROPERTY_DATASTORE);
	// Create an enum list with a single "Default Datastore" entry:
	wchar_t **enumArray = new wchar_t*[1];
	enumArray[0] = new wchar_t[wcslen(L"²âÊÔ")+1];
	wcscpy(enumArray[0], L"²âÊÔ");
	datastoreProperty->UpdateEnumerableProperties(1, (const wchar_t**)enumArray);

	if (FdoConnectionState_Pending == GetConnectionState ())
		datastoreProperty->SetIsPropertyRequired (true);
	************************************************/

	m_strConnectionSession = SuperMapConnectionPool::GetInstance()->GetConnectionInfo(this);
	if (m_strConnectionSession != "")
		m_ConnectionState = FdoConnectionState_Open;
	else
		m_ConnectionState = FdoConnectionState_Closed;

	return (GetConnectionState ());
}

/// Closes the connection to the DataStore
/// <returns>Returns nothing</returns>
void SuperMapConnection::Close ()
{
	if (m_ConnectionState == FdoConnectionState_Closed)
		return ;

	TRACE(_T("µ÷ÓÃ SuperMapConnection::Close ...\n"));
	// Clear the LogicalPhysical/physical/override caches:  // Todo £º½«Á¬½ÓÀïÓеÄÖ¸Õë³ÉÔ±±äÁ¿¸³¿Õ
	m_LpSchemas = NULL;

	// Reset the Spatial Contexts collection. Create the default SC.
	/*m_SpatialContextColl = new SuperMapSpatialContextCollection();
	FdoPtr<SuperMapSpatialContext> defltSpatialContext = new SuperMapSpatialContext();
	m_SpatialContextColl->Add(defltSpatialContext);*/
	m_SpatialContextColl = NULL;

	// Clear the Datastore connection property's enumerated list of datastores:

	// Á¬½Ó¶Ï¿ªÊ±¹Ø±ÕÒÑ´ò¿ªµÄÊý¾ÝÔ´
	SuperMapConnectionPool::GetInstance()->CloseDataSource(this->m_strConnectionSession);

	m_ConnectionState = FdoConnectionState_Closed;
	this->m_strConnectionSession = "";
}

/// Begins a transaction and returns an object that realizes
/// FdoITransaction.
/// <returns>Returns the transaction</returns>
FdoITransaction* SuperMapConnection::BeginTransaction ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::BeginTransaction ...\n"));
	throw FdoException::Create(NlsMsgGet(SUPERMAP_CONNECTION_TRANSACTIONS_NOT_SUPPORTED,
		"SuperMap Provider does not support transactions."));

    //if (m_pTransaction != NULL)	// ÅжÏÊÇ·ñÊÇǶÌ×ÊÂÎñ
    //    throw FdoException::Create(NlsMsgGet(SUPERMAP_NESTED_TRANSACTIONS_NOT_SUPPORTED, "Nested transactions are not supported."));
    //m_pTransaction = new SuperMapTransaction ();
    //// the connection holds a hard reference to the transaction
    //// the transaction holds a soft reference to the connection
    //m_pTransaction->AddRef ();
    //m_pTransaction->SetConnection (this);

    //return (m_pTransaction);
}

void SuperMapConnection::EndTransaction ()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::EndTransaction ...\n"));
	//if (NULL != m_pTransaction)
	//{
	//	m_pTransaction->SetConnection(NULL);
	//	m_pTransaction->Release ();			// ²»ÄÜÈ·¶¨BeginTransaction ·µ»ØºóÊÇÔõôÀ´Ê¹ÓÃÊÂÎñ£¬ËùÒÔÊÖ¶¯À´¿ØÖÆ¡£
	//	m_pTransaction = NULL;
	//}
}

/// Creates and returns the specified type of command object associated with
/// the connection.
/// <param name="commandType">Input the command type to be created</param>
/// <returns>Returns the command</returns>
FdoICommand* SuperMapConnection::CreateCommand (FdoInt32 commandType)
{

	FdoPtr<FdoICommand> ret = NULL;

	if ((GetConnectionState() == FdoConnectionState_Closed) || (GetConnectionState() == FdoConnectionState_Pending))
		throw FdoException::Create(NlsMsgGet(SUPERMAP_CONNECTION_INVALID, "Connection is invalid."));
	switch (commandType)
	{
	case FdoCommandType_Select:
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:Select\n"));
		ret = new SuperMapSelectCommand (this);
		break;
	case FdoCommandType_SelectAggregates:
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:SelectAggregates\n"));
		//ret = new SuperMapSelectAggregatesCommand (this);
		break;
	case FdoCommandType_DescribeSchema:
		ret = new SuperMapDescribeSchemaCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:DescribeSchema\n"));
		break;
	case FdoCommandType_DescribeSchemaMapping:
		//ret = new SuperMapDescribeSchemaMappingCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:DescribeSchemaMapping\n"));
		break;
	case FdoCommandType_GetSpatialContexts:
		ret = new SuperMapGetSpatialContextsCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:GetSpatialContexts\n"));
		break;
	case FdoCommandType_CreateSpatialContext:
		ret = new SuperMapCreateSpatialContextCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:CreateSpatialContext\n"));
		break;
	case FdoCommandType_Insert:
		ret = new SuperMapInsertCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:Insert\n"));
		break;
	case FdoCommandType_Update:
		ret = new SuperMapUpdateCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:Update\n"));
		break;
	case FdoCommandType_Delete:
		ret = new SuperMapDeleteCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:Delete\n"));
		break;
	case FdoCommandType_ApplySchema:
		ret = new SuperMapApplySchemaCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:ApplySchema\n"));
		break;
	case FdoCommandType_DestroySchema:
		ret = new SuperMapDestroySchemaCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:DestroySchema\n"));
		break;
	case FdoCommandType_CreateDataStore:
		//ret = new SuperMapCreateDataStoreCommand (this);
		TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateCommand:CreateDataStore\n"));
		break;

	default:
		throw FdoException::Create (FdoException::NLSGetMessage (FDO_102_COMMAND_NOT_SUPPORTED,
			"The command '%1$ls' is not supported.",
			(FdoString*)(FdoCommonMiscUtil::FdoCommandTypeToString (commandType))));
	}

	return (FDO_SAFE_ADDREF (ret.p));
}

/// Factory function that creates an empty Schema Override set specific
/// to this FDO Provider.
/// <returns>Returns FdoPhysicalSchemaMapping</returns>
FdoPhysicalSchemaMapping* SuperMapConnection::CreateSchemaMapping()
{
	//FdoSuperMapOvPhysicalSchemaMappingP newPhysicalSchemaMapping = FdoSuperMapOvPhysicalSchemaMapping::Create();
	//return FDO_SAFE_ADDREF(newPhysicalSchemaMapping.p);
	TRACE(_T("µ÷ÓÃ SuperMapConnection::CreateSchemaMapping ...\n"));
	return NULL;
}

/// Sets the XML configuration stream used to configure the Data Store.
/// SetConfiguration can only be called while the connection is closed.
/// <param name="configStream">Input the XML configuration stream</param>
/// <returns>Returns nothing</returns>
void SuperMapConnection::SetConfiguration(FdoIoStream* configStream)
{
	TRACE(_T("!!!µ÷ÓÃ SuperMapConnection::SetConfiguration ...\n"));

	throw FdoException::Create(NlsMsgGet(SUPERMAP_CONFIGURATION_FILE_NOT_SUPPORTED,
		"SuperMap Provider does not support configuration files."));
}

void SuperMapConnection::Flush()
{
	TRACE(_T("µ÷ÓÃ SuperMapConnection::Flush ...\n"));

	FdoPtr<SuperMapLpFeatureSchemaCollection> schemas = GetLpSchemas();
	int count = schemas->GetCount();

	for(int i = 0; i < count; ++i)
	{
		FdoPtr<SuperMapLpFeatureSchema> lpSchema = schemas->GetItem(i);
		FdoPtr<SuperMapLpClassDefinitionCollection> classes = lpSchema->GetLpClasses();
		int class_count = classes->GetCount();

		for(int j = 0; j < class_count; ++j)
		{
			FdoPtr<SuperMapLpClassDefinition> lpClass = classes->GetItem(j);
			UGC::UGDataset* pDataset = lpClass->GetDataset();

			//ÒÔͬÑùµÄ·½Ê½´ò¿ª¸ÃÊý¾Ý¼¯ÒÔʹÆä¸üÐÂ
			pDataset->Open();
		}
	}
}

UGC::UGDataSource* SuperMapConnection::GetDataSource()
{
	UGC::UGDataSource* ds = SuperMapConnectionPool::GetInstance()->GetDataSource(m_strConnectionSession);
	VALIDATE_POINTER(ds);
	return ds;
}

bool SuperMapConnection::IsOnlyConnectImage()
{
	return SuperMapConnectionPool::GetInstance()->IsImage(m_strConnectionSession);
}

SuperMapLpFeatureSchemaCollection* SuperMapConnection::GetLpSchemas()
{
	TRACE(_T("¿ªÊ¼µ÷Óà SuperMapConnection::GetLpSchemas() ¡£\n"));
	//µÚÒ»´Îµ÷ÓÃʱ¶ÔÂß¼ÎïÀíģʽ³õ'»¯£¬³õ'»¯³É¹¦ºó¾ÍÖ»ÐèÖ±½Ó·µ»Ø¡£
	if(m_LpSchemas == NULL)
	{
		TRACE(_T("µ÷Óà SuperMapConnection::GetLpSchemas():Âß¼ÎïÀíģʽΪ¿Õ ¡£\n"));
		UGC::UGDataSource* pDataSource = GetDataSource();
		m_LpSchemas = new SuperMapLpFeatureSchemaCollection(
			this, pDataSource);
	}
	TRACE(_T("½áÊøµ÷Óà SuperMapConnection::GetLpSchemas() ¡£\n"));
	return FDO_SAFE_ADDREF(m_LpSchemas.p);
}

SuperMapSpatialContextCollection* SuperMapConnection::GetSpatialContexts()
{
	TRACE(_T("¿ªÊ¼µ÷Óà SuperMapConnection::GetSpatialContexts() ¡£\n"));
	if(m_SpatialContextColl == NULL)
	{
		// ͨ¹ýÎïÀíÊý¾ÝÔ´³õ'»¯¿Õ¼äÓïÒåÁбí
		FdoStringP strName;
		FdoStringP strDescription;
		FdoStringP strCoordSysName;

		UGC::EmSpatialRefType eType;             //  ¿Õ¼äÓïÒåÀàÐÍ
		FdoStringP strDatumName ;           //  »ù×¼ÃæÃû DATUM
		FdoStringP strSpheroidName ;        //  ÍÖÇòÌåÃû
		double dSemiMajor;                       //  ÍÖÇòÌ峤°ëÖ᳤¶È
		double dInvflattening;                   //  ÍÖÇòÌå±âÂʵ¹Êý
		FdoStringP strPrimeMeridian ;       //  ±¾³õ×ÓÎçÏߣ¨0¶È¾Ïߣ©Í¨³£Îª"Greenwich"
		FdoStringP GeoUnit ;                //  µØÀíµ¥Î»
		FdoStringP GeoUnitFactor ;          //  µØÀíµ¥Î»»»ËãϵÊý
		FdoStringP Unit ;                   //  µ¥Î»
		FdoStringP UnitFactor ;             //  µ¥Î»»»ËãϵÊý

		FdoPtr<SuperMapSpatialContext> pSpatialContext = new SuperMapSpatialContext();

		// ¾Î³¶È×ø±êºÍͶӰ×ø±ê¶¼ÒªÈ¡µÄ¹«¹²²ÎÊý
		UGC::UGPrjCoordSys prjCoordSys = GetDataSource()->GetPrjCoordSys();
		strName = prjCoordSys.GetName();

		eType = prjCoordSys.GetSpatialRefType();
		UGC::UGGeoCoordSys geoCoordSys = prjCoordSys.GetGeoCoordSys(); // »ñÈ¡µØÀí×ø±êÐÅÏ¢
		strCoordSysName = geoCoordSys.GetName();
		UGC::UGHorizonDatum datum = geoCoordSys.GetHorizonDatum();   // »ñÈ¡»ù×¼ÃæÐÅÏ¢
		strDatumName = datum.GetDatumName();
		UGC::UGSpheroid spheroid = datum.GetSpheroid();  // »ñÈ¡ÍÖÇòÌåÐÅÏ¢
		strSpheroidName = spheroid.GetName();
		dSemiMajor = spheroid.GetAxis();
		dInvflattening = 1/(spheroid.GetFlatten());
		UGC::UGPrimeMeridian prmMeridian = geoCoordSys.GetPrimeMeridian();        // »ñÈ¡±¾³õ×ÓÎçÏßÐÅÏ¢
		strPrimeMeridian = prmMeridian.GetName();

		// »ñÈ¡µØÀíµ¥Î»ºÍµØÀíµ¥Î»ÏµÊý
		switch(geoCoordSys.GetUnit())
		{
			// ½Ç¶Èµ¥Î»»»Ëãµ½»¡¶Èµ¥Î»
		case AU_DEGREE:
			GeoUnit = L"Degree";
			GeoUnitFactor = L"0.01745329";
			break;
		case AU_RADIAN:
			GeoUnit = L"Radian";
			GeoUnitFactor = L"1.00000000";
			break;
		case AU_MINUTE:
			GeoUnit = L"Minute";
			GeoUnitFactor = L"0.00029089";
			break;
		case AU_SECOND:
			GeoUnit = L"Second";
			GeoUnitFactor = L"0.00000485";
			break;
		case AU_GRAD:
			GeoUnit = L"Gard";
			GeoUnitFactor = L"0.01570796";
			break;
		case AU_MICRORADIAN:
			GeoUnit = L"MicroRadian";
			GeoUnitFactor = L"0.00000100";
			break;
		case AU_MINUTE_CENTESIMAL:
			GeoUnit = L"Minute_Centesimal";
			GeoUnitFactor = L"0.00015708";
			break;
		case AU_SECOND_CENTESIMAL:
			GeoUnit = L"Second_Centesimal";
			GeoUnitFactor = L"0.00000157";
			break;
		case AU_MIL_6400:
			GeoUnit = L"Mil_6400";
			GeoUnitFactor = L"0.00098175";
			break;
		}
		// ͶӰ×ø±êµ¥Î»
		switch(prjCoordSys.GetUnit())
		{
		// ³¤¶Èµ¥Î»»»Ëãµ½Ã×
		case AU_MM:
			Unit = L"MILLIMETER";
			UnitFactor = L"0.001";
			break;
		case AU_CM:
			Unit = L"CENTIMETER";
			UnitFactor = L"0.01";
			break;
		case AU_DM:
			Unit = L"DECIMETER";
			UnitFactor = L"0.10";
			break;
		case AU_M:
			Unit = L"METER";
			UnitFactor = L"1.0";
			break;
		case AU_KM:
			Unit = L"KILOMETER";
			UnitFactor = L"1000.00";
			break;
		case AU_MI:
			Unit = L"MILE";
			UnitFactor = L"1609.31";
			break;
		case AU_IN:
			Unit = L"INCH";
			UnitFactor = L"0.0254";
			break;
		case AU_YARD:
			Unit = L"YARD";
			UnitFactor = L"0.9144";
			break;
		case AU_FT:
			Unit = L"FOOT";
			UnitFactor = L"0.3048";
			break;
		default:
			Unit = L"";
			UnitFactor = L"";
		}

		if(eType == UGC::SPATIALREF_EARTH_PROJECTION) // Èç¹ûÊÇͶӰ×ø±êϵ£¬»ñÈ¡Ïà¹ØͶӰ²ÎÊý¡£
		{
			UGC::UGProjection projection = prjCoordSys.GetProjection();
			pSpatialContext->m_ProjectName = projection.GetProjectionName();
			UGC::UGPrjParams prjParams = prjCoordSys.GetPrjParams();
			//ÐèÒª¸³ÖµµÄͶӰ²ÎÊý£º
			//double m_dFalseEasting;			//  0 False easting (X0)
			//double m_dFalseNorthing;		//  1 False northing (Y0)
			//double m_dCentralMeridian;		//  2 Central meridian, Longitude of origin (LON0)
			//double m_dCentralParallel;		//  6 Central parallel, Latitude of origin	(LAT0)

			//double m_dStandardParallel1;	//  3 Standard parallel 1, Latitude of 1st point (LAT1)
			//double m_dStandardParallel2;	//  4 Standard parallel 2, Latitude of 2nd point (LAT2)

			//double m_dScaleFactor;			//  5 Scale factor
			//double m_dAzimuth;				//  7 Azimuth

			//double m_dFirstPointLongitude;		//  8 Longitude of 1st point (LON1)
			//double m_dSecondPointLongitude;		//  9 Longitude of 2nd point  (LON2)
			pSpatialContext->m_dFalseEasting = prjParams.m_dFalseEasting;
			pSpatialContext->m_dFalseNorthing = prjParams.m_dFalseNorthing;
			pSpatialContext->m_dCentralMeridian = prjParams.m_dCentralMeridian;
			pSpatialContext->m_dCentralParallel = prjParams.m_dCentralParallel;
			pSpatialContext->m_dStandardParallel1 = prjParams.m_dStandardParallel1;
			pSpatialContext->m_dStandardParallel2 = prjParams.m_dStandardParallel2;
			pSpatialContext->m_dScaleFactor = prjParams.m_dScaleFactor;
			pSpatialContext->m_dAzimuth = prjParams.m_dAzimuth;
			pSpatialContext->m_dFirstPointLongitude = prjParams.m_dFirstPointLongitude;
			pSpatialContext->m_dSecondPointLongitude = prjParams.m_dSecondPointLongitude;
		}
		// end for È¡¿Õ¼äÓïÒåµÄʵ¼ÊÖµ

		// ÉèÖù«¹²µÄ¿Õ¼äÓïÒåµÄ²ÎÊý
		pSpatialContext->SetName(strName);
		pSpatialContext->SetDescription(strDescription);
		pSpatialContext->SetCoordSysName(strCoordSysName); //(strCoordSysName.Right(L"---"));
		pSpatialContext->m_eType = eType;
		pSpatialContext->m_DatumName = strDatumName;
		pSpatialContext->m_SpheroidName = strSpheroidName;
		pSpatialContext->m_dSemiMajor = dSemiMajor;
		pSpatialContext->m_dInvflattening = dInvflattening;
		pSpatialContext->m_PrimeMeridian = strPrimeMeridian;
		pSpatialContext->m_Unit = Unit;
		pSpatialContext->m_UnitFactor = UnitFactor;
		pSpatialContext->m_GeoUnit = GeoUnit;
		pSpatialContext->m_GeoUnitFactor = GeoUnitFactor;

		m_SpatialContextColl = new SuperMapSpatialContextCollection();
		m_SpatialContextColl->Add(pSpatialContext);
	}

	return FDO_SAFE_ADDREF(m_SpatialContextColl.p);
}

void SuperMapConnection::CreateSpatialContext(
								FdoString* name,
								FdoString* description,
								FdoString* coordinateSystem,
								FdoString* coordinateSystemWkt,
								FdoSpatialContextExtentType extentType,
								FdoByteArray * extent,
								double xyTolerance,
								double zTolerance,
								bool   update
							)
{
	bool found = false;

	// ¼ì²éÊÇ·ñÓÐͬһ¸öWKT¿Õ¼äÓïÒå´æÔÚ
	for(FdoInt32 i = 0; i < m_SpatialContextColl->GetCount() && !found; ++i)
	{
		FdoPtr<SuperMapSpatialContext>	sp = m_SpatialContextColl->GetItem(i);
		found = (coordinateSystemWkt == sp->GetCoordinateSystemWkt());
	}

	// ¸³ÐµÄ×ø±êϵ
	if(!found)
	{
		FdoPtr<SuperMapSpatialContext> newSp = new SuperMapSpatialContext();
		FdoInt32 idxGenName = 1;
		FdoStringP newName = name;

		// ²éÕÒÖظ´µÄ¿Õ¼äÓïÒåÃû£¬ÔÚÃû×Öºó¼ÓÊý×Ö±ÜÃâÖØÃû
		while(m_SpatialContextColl->FindItem(newName))
		{
			newName = FdoStringP::Format(L"%ls_%d", (FdoString*)name, idxGenName);
			idxGenName++;
		}

		//ÉèÖÃеĿռäÓïÒå
		newSp->SetName(newName);
		newSp->SetCoordSysName(coordinateSystem);
		newSp->SetCoordinateSystemWkt(coordinateSystemWkt);

		newSp->SetDescription(description);
		newSp->SetExtent(extent);
		newSp->SetExtentType(extentType);
		newSp->SetXYTolerance(xyTolerance);
		newSp->SetZTolerance(zTolerance);

		m_SpatialContextColl->Add(newSp);

		//Todo: ÍùÎïÀíÊý¾ÝÔ´ÖÐÌí¼ÓͶӰÐÅÏ¢ÊÇ·ñÔÚ´Ë×ö£¿

	}

}


text:
package namespace

import (
	"testing"

	"k8s.io/kubernetes/pkg/api"
	apitesting "k8s.io/kubernetes/pkg/api/testing"
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
)

func TestNamespaceStrategy(t *testing.T) {
	ctx := api.NewDefaultContext()
	if Strategy.NamespaceScoped() {
		t.Errorf("Namespaces should not be namespace scoped")
	}
	if Strategy.AllowCreateOnUpdate() {
		t.Errorf("Namespaces should not allow create on update")
	}
	namespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"},
		Status:     api.NamespaceStatus{Phase: api.NamespaceTerminating},
	}
	Strategy.PrepareForCreate(ctx, namespace)
	if namespace.Status.Phase != api.NamespaceActive {
		t.Errorf("Namespaces do not allow setting phase on create")
	}
	if len(namespace.Spec.Finalizers) != 1 || namespace.Spec.Finalizers[0] != api.FinalizerKubernetes {
		t.Errorf("Prepare For Create should have added kubernetes finalizer")
	}
	errs := Strategy.Validate(ctx, namespace)
	if len(errs) != 0 {
		t.Errorf("Unexpected error validating %v", errs)
	}
	invalidNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "bar", ResourceVersion: "4"},
	}
	// ensure we copy spec.finalizers from old to new
	Strategy.PrepareForUpdate(ctx, invalidNamespace, namespace)
	if len(invalidNamespace.Spec.Finalizers) != 1 || invalidNamespace.Spec.Finalizers[0] != api.FinalizerKubernetes {
		t.Errorf("PrepareForUpdate should have preserved old.spec.finalizers")
	}
	errs = Strategy.ValidateUpdate(ctx, invalidNamespace, namespace)
	if len(errs) == 0 {
		t.Errorf("Expected a validation error")
	}
	if invalidNamespace.ResourceVersion != "4" {
		t.Errorf("Incoming resource version on update should not be mutated")
	}
}

func TestNamespaceStatusStrategy(t *testing.T) {
	ctx := api.NewDefaultContext()
	if StatusStrategy.NamespaceScoped() {
		t.Errorf("Namespaces should not be namespace scoped")
	}
	if StatusStrategy.AllowCreateOnUpdate() {
		t.Errorf("Namespaces should not allow create on update")
	}
	now := metav1.Now()
	oldNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10", DeletionTimestamp: &now},
		Spec:       api.NamespaceSpec{Finalizers: []api.FinalizerName{"kubernetes"}},
		Status:     api.NamespaceStatus{Phase: api.NamespaceActive},
	}
	namespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "9", DeletionTimestamp: &now},
		Status:     api.NamespaceStatus{Phase: api.NamespaceTerminating},
	}
	StatusStrategy.PrepareForUpdate(ctx, namespace, oldNamespace)
	if namespace.Status.Phase != api.NamespaceTerminating {
		t.Errorf("Namespace status updates should allow change of phase: %v", namespace.Status.Phase)
	}
	if len(namespace.Spec.Finalizers) != 1 || namespace.Spec.Finalizers[0] != api.FinalizerKubernetes {
		t.Errorf("PrepareForUpdate should have preserved old finalizers")
	}
	errs := StatusStrategy.ValidateUpdate(ctx, namespace, oldNamespace)
	if len(errs) != 0 {
		t.Errorf("Unexpected error %v", errs)
	}
	if namespace.ResourceVersion != "9" {
		t.Errorf("Incoming resource version on update should not be mutated")
	}
}

func TestNamespaceFinalizeStrategy(t *testing.T) {
	ctx := api.NewDefaultContext()
	if FinalizeStrategy.NamespaceScoped() {
		t.Errorf("Namespaces should not be namespace scoped")
	}
	if FinalizeStrategy.AllowCreateOnUpdate() {
		t.Errorf("Namespaces should not allow create on update")
	}
	oldNamespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"},
		Spec:       api.NamespaceSpec{Finalizers: []api.FinalizerName{"kubernetes", "example.com/org"}},
		Status:     api.NamespaceStatus{Phase: api.NamespaceActive},
	}
	namespace := &api.Namespace{
		ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "9"},
		Spec:       api.NamespaceSpec{Finalizers: []api.FinalizerName{"example.com/foo"}},
		Status:     api.NamespaceStatus{Phase: api.NamespaceTerminating},
	}
	FinalizeStrategy.PrepareForUpdate(ctx, namespace, oldNamespace)
	if namespace.Status.Phase != api.NamespaceActive {
		t.Errorf("finalize updates should not allow change of phase: %v", namespace.Status.Phase)
	}
	if len(namespace.Spec.Finalizers) != 1 || string(namespace.Spec.Finalizers[0]) != "example.com/foo" {
		t.Errorf("PrepareForUpdate should have modified finalizers")
	}
	errs := StatusStrategy.ValidateUpdate(ctx, namespace, oldNamespace)
	if len(errs) != 0 {
		t.Errorf("Unexpected error %v", errs)
	}
	if namespace.ResourceVersion != "9" {
		t.Errorf("Incoming resource version on update should not be mutated")
	}
}

func TestSelectableFieldLabelConversions(t *testing.T) {
	apitesting.TestSelectableFieldLabelConversionsOfKind(t,
		registered.GroupOrDie(api.GroupName).GroupVersion.String(),
		"Namespace",
		NamespaceToSelectableFields(&api.Namespace{}),
		map[string]string{"name": "metadata.name"},
	)
}


text:
  MyApp.register('controller:textSearch', MyApp.TextSearchController, {singleton: false});
  //MyApp.register('controller:pages', MyApp.PagesController, {singleton: false});
  //MyApp.register('controller:searchInput', MyApp.SearchInputController, {singleton: false});
  //MyApp.register('controller:searchResults', MyApp.SearchResultsController, {singleton: false});

  MyApp.TextSearchView = Ember.View.extend({
    templateName: 'textSearch'
  });

  MyApp.SimpleSearchComponent = Ember.Component.extend({
    actions:{
      click: function(concept){
        this.sendAction('action', concept);
      }
    }
  });

  MyApp.TextSearchController = Ember.ObjectController.extend({
    query: null,
    searchResults: null,
    pages: null,
    currentPage: null,
    maxPageIndexesShown: 5,
    pageSize: 8,
    needs: "searchResults",
    actions:{
      search: function(search) {

        if (search===""){
          this.get('controllers.searchResults').set('model', null);
          return false;
        }

        console.log('received search event "' + search + '"');
        console.log('pagesize is ' + this.get('pageSize'));
        var results = MyApp.TextSearchController.find(search, 1, this.get('pageSize'));
        var _this = this;
        // results is a jquery promise, wait for it to resolve
        // Ember can't resolve it automatically
        results.then(function(results){
          console.log('query returned with ' + results.total + ' results');
          _this.set('searchResults', results);
          _this.buildPages(1, 1);
          console.log('blah3');
        });
        return false;
      },
      pageRequest: function(page){
        console.log('received page request for page ' + page.get('index'));
        //console.log('page ' + page.get('display'));
        var _this = this;
        console.log('disabling page ' + this.get('currentPage.index'));
        this.get('currentPage').set('active', false);
        var results = MyApp.TextSearchController.find(
            this.get('query'),
            page.index,
            this.get('pageSize'));
        results.then(function(results){
          _this.set('searchResults', results);
        });
        console.log('setting current page to ' + page.get('index') + ' and making active');
        this.set('currentPage', page);
        page.set('active', true);
        return false;
      },
      firstPage: function(){
        console.log('First page');
        this.buildPages(1, 1);
        this.send('pageRequest', this.get('pages.firstObject'));
      },
      previousPage: function(){
        console.log('previous page');
        var page = null;
        if ((this.get('currentPage.index') - 1) % this.get('maxPageIndexesShown') == 0){
          //Assertion: we are at the first displayed page index
          console.log('we are at the first displayed page index');
          if (this.get('currentPage.index') == 1){
            //assertion: we are at the beginning of the list of pages, so loop around to the back.
            console.log('we are at the beginning of the list of pages, so loop around to the back');
            console.log('last page');
            var numberOfPagesOnLastSet = this.get('numberOfPages') % this.get('maxPageIndexesShown');
            console.log('number of pages on last view ' + numberOfPagesOnLastSet);
            console.log('calling buildPages(' + (this.get('numberOfPages') - numberOfPagesOnLastSet) + ', ' + this.get('numberOfPages') + ')');
            this.buildPages(this.get('numberOfPages') - numberOfPagesOnLastSet + 1, numberOfPagesOnLastSet);
            page = this.get('pages.lastObject');
          }
          else{
            //assertion: there are more page indexes to the left / below to display
            console.log('there are more page indexes to the left / below to display');
            var index = this.get('currentPage.index') - this.get('maxPageIndexesShown');
            console.log('buildPages(' + index + ', ' + this.get('maxPageIndexesShown') + ')');
            this.buildPages(index, this.get('maxPageIndexesShown'));
            page = this.get('pages.lastObject');
          }
        }else{
          var index = ((this.get('currentPage.index') - 1) % this.get('maxPageIndexesShown')) - 1;
          console.log('we are not at the beginning of the page list');
          console.log('selecting pages.objectAt (' + index + ') for page');
          page = this.get('pages').objectAt(index);
        }
        console.log('change page to index ' + page.get('index'));
        this.send('pageRequest', page);
      },
      nextPage: function(){
        var page = null;
        if ((this.get('currentPage.index') % this.get('maxPageIndexesShown') == 0)
            || (this.get('currentPage.index') == this.get('numberOfPages'))){
          //Assertion: we are at the last displayed page index
          console.log('we are at the last displayed page index');
          if (this.get('currentPage.index') == this.get('numberOfPages')){
            //assertion: we are at the end of the list of pages, so loop around.
            console.log('we are at the end of the list of pages, so loop around.');
            console.log('First page');
            console.log('buildpages(1, 1)');
            this.buildPages(1, 1);
            page = this.get('pages.firstObject');
          }
          else{
            //Assertion: we are at the last displayed page index
            //assertion: there are more page indexes to display
            console.log('there are more page indexes to display');
            var index = this.get('currentPage.index') + 1;
            console.log('buildPages(' + index + ', 1)');
            this.buildPages(index, 1);
            page = this.get('pages.firstObject');
          }
        }else{
          console.log('we are not at the end of the page list');
          var index = this.get('currentPage.index') % this.get('maxPageIndexesShown');
          console.log('getting page: pagespages.objectAt(' + index + ')');
          page = this.get('pages').objectAt(index);
        }

        this.send('pageRequest', page);
      },
      lastPage: function(){
        console.log('last page');
        var numberOfPagesOnLastSet = this.get('numberOfPages') % this.get('maxPageIndexesShown');
        console.log('number of pages on last view ' + numberOfPagesOnLastSet);
        console.log('calling buildPages(' + (this.get('numberOfPages') - numberOfPagesOnLastSet) + ', ' + this.get('numberOfPages') + ')');
        this.buildPages(this.get('numberOfPages') - numberOfPagesOnLastSet + 1, numberOfPagesOnLastSet);
        this.send('pageRequest', this.get('pages.lastObject'));
      }
    },

    totalPageItems: function(){
      return this.get('searchResults.total');
    }.property('searchResults'),

    numberOfPages: function(){
      return Math.ceil(this.get('searchResults.total') / this.get('pageSize'));
    }.property('searchResults'),

    buildPages: function(startAtPageIndex, activeIndex){
      //Build Page Index
      console.log('Building pages with startAtPageIndex: ' + startAtPageIndex + ", activeIndex: " + activeIndex);
      var newPages = Ember.A();
      this.set('pages', newPages);
      var numberOfPages = this.get('numberOfPages');
      var maxIndex = startAtPageIndex + this.get('maxPageIndexesShown') - 1;
      console.log('building pages from ' + startAtPageIndex + ' to max ' + maxIndex + ' out of total ' + numberOfPages);
      console.log('number of pages are ' + numberOfPages);
      for (i=startAtPageIndex; i <= numberOfPages && i <= maxIndex; i++){
        var page = MyApp.Page.create();
        page.active = false;
        page.index = i;
        newPages.pushObject(page);
      }
      console.log('setting current page to ' + (activeIndex) + ' and making active');
      this.set('currentPage', newPages.objectAt(activeIndex - 1));
      this.get('currentPage').set('active', true);
    },
    shouldDisplayNavigation: function(){
      var mypages = this.get('pages');
      if (mypages != null){
        if (mypages.length > 1) return true;
      }else{
        return false;
      }
    }.property('pages'),
    displayWidthStyling: function(){
      var itemWidth = 4;
      return 'width: ' + ((4 * itemWidth) + (this.get('pages.length') * itemWidth)) + 'em;';
    }.property('pages')
  });

  MyApp.TextSearchController.reopenClass({
    find: function(searchString, pageIndex, pageSize){
      console.log('find(searchString: \'' + searchString + '\', pageIndex: ' + pageIndex + ', pageSize: ' + pageSize + ')');
      return Ember.Deferred.promise(function(p) {
        var startIndex = (pageIndex - 1) * pageSize;
        p.resolve($.getJSON("https://solr.snomedtools.com/solr/concept/select?q=title:" + searchString + "&start=" + startIndex + "&rows=" + pageSize + "&wt=json&indent=true&json.wrf=?")
          .then(function(solr) {
              var returned = MyApp.SearchResults.create();
              returned.set('total', solr.response.numFound);
              returned.set('start', solr.response.start);
              var concepts = Ember.A();
              solr.response.docs.forEach(function (doc) {
                var concept = MyApp.Concept.create();
                concept.id = doc.id;
                concept.ontologyId = doc.ontology_id;
                concept.title = doc.title;
                concept.active = doc.active;
                concept.effectiveTime= doc.effectiveTime;
                concepts.pushObject(concept);
              });
              returned.set('concepts',concepts);

              console.log('returned ' + returned.get('total') + ' records');
              return returned;
          }) //then
        );//resolve
      });//deferred promise
    },//find
  });//reopen

MyApp.TextSearchModalView = Ember.View.extend({
  templateName: 'textSearchModal'
});

// (TEXT) SEARCH INPUT
  MyApp.SearchInputView = Ember.View.extend({
    templateName: 'searchInput',
    keyUp: function(evt) {
      //looks like current controller is textSearchController?
      //Or maybe it bubbles to it?
      this.get('controller').send('search', this.get('controller.query'));
    }
  });

// (TEXT) SEARCH RESULTS

  MyApp.SearchResultsController = Ember.ObjectController.extend({
  });

  MyApp.SearchResultsView = Ember.View.extend({
    templateName: 'searchResults'
  });

  MyApp.SearchResults = Ember.Object.extend({
    total: 0,
    concepts: Ember.A()
  });

  MyApp.Concept = Ember.Object.extend({
    stylingClass: function(){
      if (this.get('active')){
        return 'active';
      }
      else{
        return 'inactive';
      }
    }.property('active'),
    id: null,
    ontologyId: null,
    title: null,
    active: null,
    effectiveTime: null,
    url: function(){
      return "http://browser.snomedtools.com/version/1/concept/" + this.get('id')
    }.property('id')
  });

// PAGES

  MyApp.Page = Ember.Object.extend({
    active: false,
    index: null,
  });

  MyApp.PagesView = Ember.View.extend({
    templateName: 'pages',

  })


text:
The new security features in OrientDB (introduced in release 2.2) provide an extensible framework for adding external authenticators, password validation, LDAP import of database roles and users, advanced auditing capabilities, and syslog support.

The new security system uses a JSON configuration file, located in the *config* directory.  The default name of the file is *security.json*, but it can be overridden by setting the "server.security.file" property in *orientdb-server-config.xml* or by setting the global server property, "server.security.file".

To see the complete configuration options, click here: [Security Configuration](Security-Config.md).

## Authenticators
In addition to the built-in authentication of users that happens inside the database engine, the new OrientDB security system supports multiple types of external *authenticators*.  Each *authenticator* implements various methods to support authentication and authorization, among other things.

All *authenticators* can be configured in the "authentication" section of the [security configuration](Security-Config.md).

### Current Implementations
Currently, OrientDB provides a [Kerberos authenticator](#okerberosauthenticator), a [password authenticator](#odefaultpasswordauthenticator) for authenticating users in the *security.json* file, a [server config authenticator](#oserverconfigauthenticator) for authenticating users in the *orientdb-server-config.xml* file, and a [symmetric key authenticator](#symmetric-key-authenticator) (Enterprise-only).  Additional *authenticators* may be provided in the future, and it's very easy to build new ones.

#### OKerberosAuthenticator
This *authenticator* provides support for Kerberos authentication and full browser SPNEGO support.  See the [security configuration](Security-Config.md) page for full details on configuring this *authenticator* for Kerberos.

Also, see [Kerberos client examples](Security-Kerberos-Client-Examples.md) to see how to use the OrientDB clients with Kerberos.

#### ODefaultPasswordAuthenticator
The `ODefaultPasswordAuthenticator` supports adding server users with passwords and resources to the *security.json* configuration file.  The main purpose of this is to allow having server users in a single file (along with all the other security settings) without having to maintain them in the separate *orientdb-server-config.xml* file.  See the example in the [security configuration](Security-Config.md) page.

#### OServerConfigAuthenticator
The `OServerConfigAuthenticator` is similar to `ODefaultPasswordAuthenticator` in that it supports server users with passwords and resources, but it's designed to be used with the users in the *orientdb-server-config.xml* configuration file instead.

#### OSystemUserAuthenticator
The `OSystemUserAuthenticator` supports the new *system user* type that's stored in the system database.

#### Symmetric Key Authenticator
The `Symmetric Key Authenticator` provides support for authenticating users via a shared symmetric key.

There are two versions of the `Symmetric Key Authenticator`, one that enables authenticating server users and one that enables authenticating system users.

### Chaining *Authenticators*
What's important to note is that the *authenticators* can be thought of as being chained together so that if the first *authenticator* in the list fails to authenticate a user, then the next *authenticator* in the chain is tried.  This continues until either a user is successfully authenticated or all *authenticators* are tried.  This "chaining of *authenticators*" is used for authentication, authorization, retrieving HTTP authentication headers, and several other security features.

### Default Authentication
As mentioned previously, OrientDB has a built-in authentication system for each database, and it is enabled by default.  To disable it, set the "allowDefault" property in the "authentication" section of the *security.json* configuration to false.  When enabled, the built-in authentication acts as a "fallback" if the external *authenticators* cannot authenticate or authorize a user.

## Password Validator ##
Another new feature of the security system is a customizable password validator.  The provided validator is called `ODefaultPasswordValidator` that, when enabled, validates user-chosen passwords based on minimum length and regular expressions.  Which numbers, uppercase letters, and special characters are permitted along with their required count is specified by a regular expression for each.  Like all the security components, the password validator can be extended or completely replaced with a custom password validator component.

See the [security configuration](Security-Config.md) page for details on how to configure the password validator.

## LDAP Import ##
Another often-requested feature, importing of LDAP users, is now available as part of OrientDB.  Each database can be configured to import from multiple LDAP domains, each domain may specify multiple LDAP servers, and the users and their corresponding roles can be specified per-domain using a standard LDAP filter.

The [security configuration](Security-Config.md) page explains in great details all the options for the default LDAP importer.

## Auditing/Syslog ##
Enhancements to the auditing component have also been made.  The audit log now supports monitoring of a class being created and dropped as well as when distributed nodes join and leave the cluster.  Additionally, for operating systems that support *syslog*, a new *syslog* plug-in has been added for recording auditing events.

See the [security configuration](Security-Config.md) page for details on auditing properties.

## Reloading ##
The new security system supports dynamic reloading by an HTTP POST request.  The path to the configuration file to use is provided as JSON content.  The provided credentials must have sufficient privileges to reload the security module.

Here's an example using *curl* with basic authentication:
```
curl -u root:password -H "Content-Type: application/json" -X POST -d '{ "configFile" : "${ORIENTDB_HOME}/config/security.json" }'  servername:2480/security/reload
```

Here's another example using *curl* using Kerberos/SPNEGO authentication:
```
curl --negotiate -u : -H "Content-Type: application/json" -X POST -d '{ "configFile" : "${ORIENTDB_HOME}/config/security.json" }'  servername:2480/security/reload
```

Notice the passed-in JSON "configFile" property.  Any valid security configuration file may be specified here, making testing multiple configurations possible.

### Reloading Individual Components ###
Instead of reloading the entire security system, it's also possible to reload individual security components.

Here's an example using *curl* with basic authentication:
```
curl -u root:password -H "Content-Type: application/json" -X POST -d '{ "module" : "auditing", "config" : "{ACTUAL JSON CONTENT}" }'  servername:2480/security/reload
```

Notice, instead of specifying "configFile" you use "config" and the "module" property.

Currently, you can reload the following security components:
- server
- authentication
- passwordValidator
- ldapImporter
- auditing


text:
.. currentmodule:: pythainlp.summarize

pythainlp.summarize
====================================
The :class:`summarize` is Thai text summarizer.

Modules
-------

.. autofunction:: summarize
.. autofunction:: extract_keywords

Keyword Extraction Engines
--------------------------

KeyBERT
+++++++

.. automodule:: pythainlp.summarize.keybert
.. autoclass::  pythainlp.summarize.keybert.KeyBERT
    :members:


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>Rank__c</fullName>
    <description>Trailhead Profile Rank</description>
    <externalId>false</externalId>
    <label>Rank</label>
    <length>255</length>
    <required>false</required>
    <trackTrending>false</trackTrending>
    <type>Text</type>
    <unique>false</unique>
</CustomField>