#' \code{mf <- memoise(f)} creates \code{mf}, a memoised copy of
#' \code{f}. A memoised copy is basically a
#' lazier version of the same function: it saves the answers of
#' new invocations, and re-uses the answers of old ones. Under the right
#' circumstances, this can provide a very nice speedup indeed.
#'
#' There are two main ways to use the \code{memoise} function. Say that
#' you wish to memoise \code{glm}, which is in the \code{stats}
#' package; then you could use \cr
#'   \code{  mem_glm <- memoise(glm)}, or you could use\cr
#'   \code{  glm <- memoise(stats::glm)}. \cr
#' The first form has the advantage that you still have easy access to
#' both the memoised and the original function. The latter is especially
#' useful to bring the benefits of memoisation to an existing block
#' of R code.
#'
#' Two example situations where \code{memoise} could be of use:
#' \itemize{
#'   \item You're evaluating a function repeatedly over the rows (or
#'     larger chunks) of a dataset, and expect to regularly get the same
#'     input.
#'   \item You're debugging or developing something, which involves
#'     a lot of re-running the code.  If there are a few expensive calls
#'     in there, memoising them can make life a lot more pleasant.
#'     If the code is in a script file that you're \code{source()}ing,
#'     take care that you don't just put \cr
#'       \code{  glm <- memoise(stats::glm)} \cr
#'     at the top of your file: that would reinitialise the memoised
#'     function every time the file was sourced. Wrap it in \cr
#'       \code{  if (!is.memoised(glm)) }, or do the memoisation call
#'     once at the R prompt, or put it somewhere else where it won't get
#'     repeated.
#' }
#'
#' It is recommended that functions in a package are not memoised at build-time,
#' but when the package is loaded. The simplest way to do this is within
#' \code{.onLoad()} with, for example
#'
#'
#' \preformatted{
#' # file.R
#' fun <- function() {
#'  some_expensive_process()
#' }
#'
#' # zzz.R
#' .onLoad <- function(libname, pkgname) {
#'  fun <<- memoise::memoise(fun)
#' }
#' }
#' @name memoise
#' @title Memoise a function.
#' @param f     Function of which to create a memoised copy.
#' @param ... optional variables to use as additional restrictions on
#'   caching, specified as one-sided formulas (no LHS). See Examples for usage.
#' @param envir Environment of the returned function.
#' @param cache Cache function.
#' @param omit_args Names of arguments to ignore when calculating hash.
#' @seealso \code{\link{forget}}, \code{\link{is.memoised}},
#'   \code{\link{timeout}}, \url{http://en.wikipedia.org/wiki/Memoization}
#' @aliases memoise memoize
#' @export memoise memoize
#' @importFrom digest digest
#' @examples
#' # a() is evaluated anew each time. memA() is only re-evaluated
#' # when you call it with a new set of parameters.
#' a <- function(n) { runif(n) }
#' memA <- memoise(a)
#' replicate(5, a(2))
#' replicate(5, memA(2))
#'
#' # Caching is done based on parameters' value, so same-name-but-
#' # changed-value correctly produces two different outcomes...
#' N <- 4; memA(N)
#' N <- 5; memA(N)
#' # ... and same-value-but-different-name correctly produces
#' #     the same cached outcome.
#' N <- 4; memA(N)
#' N2 <- 4; memA(N2)
#'
#' # memoise() knows about default parameters.
#' b <- function(n, dummy="a") { runif(n) }
#' memB <- memoise(b)
#' memB(2)
#' memB(2, dummy="a")
#' # This works, because the interface of the memoised function is the same as
#' # that of the original function.
#' formals(b)
#' formals(memB)
#' # However, it doesn't know about parameter relevance.
#' # Different call means different caching, no matter
#' # that the outcome is the same.
#' memB(2, dummy="b")
#'
#' # You can create multiple memoisations of the same function,
#' # and they'll be independent.
#' memA(2)
#' memA2 <- memoise(a)
#' memA(2)  # Still the same outcome
#' memA2(2) # Different cache, different outcome
#'
#' # Don't do the same memoisation assignment twice: a brand-new
#' # memoised function also means a brand-new cache, and *that*
#' # you could as easily and more legibly achieve using forget().
#' # (If you're not sure whether you already memoised something,
#' #  use is.memoised() to check.)
#' memA(2)
#' memA <- memoise(a)
#' memA(2)
#' # Making a memoized automatically time out after 10 seconds.
#' memA3 <- memoise(a, ~{current <- as.numeric(Sys.time()); (current - current %% 10) %/% 10 })
#' memA3(2)
#'
#' # The timeout function is an easy way to do the above.
#' memA4 <- memoise(a, ~timeout(10))
#' memA4(2)
#' @importFrom stats setNames
memoise <- memoize <- function(f, ..., envir = environment(f), cache = cache_memory(), omit_args = c()) {
  f_formals <- formals(args(f))
  if(is.memoised(f)) {
    stop("`f` must not be memoised.", call. = FALSE)
  }

  validate_formulas(...)
  additional <- list(...)

  memo_f <- function(...) {
    mc <- match.call()
    encl <- parent.env(environment())
    called_args <- as.list(mc)[-1]

    # Formals with a default
    default_args <- Filter(function(x) !identical(x, quote(expr = )), as.list(formals()))

    # That has not been called
    default_args <- default_args[setdiff(names(default_args), names(called_args))]

    # Ignored specified arguments when hashing
    called_args[encl$`_omit_args`] <- NULL

    # Evaluate all the arguments
    args <- c(lapply(called_args, eval, parent.frame()),
              lapply(default_args, eval, envir = environment()))

    hash <- encl$`_cache`$digest(
      c(as.character(body(encl$`_f`)), args,
        lapply(encl$`_additional`, function(x) eval(x[[2L]], environment(x))))
    )

    if (encl$`_cache`$has_key(hash)) {
      res <- encl$`_cache`$get(hash)
    } else {
      # modify the call to use the original function and evaluate it
      mc[[1L]] <- encl$`_f`
      res <- withVisible(eval(mc, parent.frame()))
      encl$`_cache`$set(hash, res)
    }

    if (res$visible) {
      res$value
    } else {
      invisible(res$value)
    }
  }
  formals(memo_f) <- f_formals
  attr(memo_f, "memoised") <- TRUE

  # This should only happen for primitive functions
  if (is.null(envir)) {
     envir <- baseenv()
  }

  memo_f_env <- new.env(parent = envir)
  memo_f_env$`_cache` <- cache
  memo_f_env$`_f` <- f
  memo_f_env$`_additional` <- additional
  memo_f_env$`_omit_args` <- omit_args
  environment(memo_f) <- memo_f_env

  class(memo_f) <- c("memoised", "function")

  memo_f
}

#' Return a new number after a given number of seconds
#'
#' This function will return a number corresponding to the system time and
#' remain stable until a given number of seconds have elapsed, after which it
#' will update to the current time. This makes it useful as a way to timeout
#' and invalidate a memoised cache after a certain period of time.
#' @param seconds Number of seconds after which to timeout.
#' @param current The current time as a numeric.
#' @return A numeric that will remain constant until the seconds have elapsed.
#' @seealso \code{\link{memoise}}
#' @export
#' @examples
#' a <- function(n) { runif(n) }
#' memA <- memoise(a, ~timeout(10))
#' memA(2)
timeout <- function(seconds, current = as.numeric(Sys.time())) {
  (current - current %% seconds) %/% seconds
}

validate_formulas <- function(...) {
  format.name <- function(x, ...) format(as.character(x), ...)
  is_formula <- function(x) {
    if (is.call(x) && identical(x[[1]], as.name("~"))) {
      if (length(x) > 2L) {
        stop("`x` must be a one sided formula [not ", format(x), "].", call. = FALSE)
      }
    } else {
      stop("`", format(x), "` must be a formula.", call. = FALSE)
    }
  }

  dots <- eval(substitute(alist(...)))
  lapply(dots, is_formula)
}

#' @export
print.memoised <- function(x, ...) {
  cat("Memoised Function:\n")
  tryCatch(print(environment(x)$`_f`), error = function(e) stop("No function defined!", call. = FALSE))
}

#' Forget past results.
#' Resets the cache of a memoised function.
#'
#' @param f memoised function
#' @export
#' @seealso \code{\link{memoise}}, \code{\link{is.memoised}}
#' @examples
#' memX <- memoise(function() { Sys.sleep(1); runif(1) })
#' # The forget() function
#' system.time(print(memX()))
#' system.time(print(memX()))
#' forget(memX)
#' system.time(print(memX()))
forget <- function(f) {
  if (!is.memoised(f)) {
    return(FALSE)
  }

  env <- environment(f)
  if (!exists("_cache", env, inherits = FALSE)) return(FALSE) # nocovr

  cache <- get("_cache", env)
  cache$reset()

  TRUE
}

#' Test whether a function is a memoised copy.
#' Memoised copies of functions carry an attribute
#' \code{memoised = TRUE}, which is what \code{is.memoised()} tests for.
#' @param f Function to test.
#' @seealso \code{\link{memoise}}, \code{\link{forget}}
#' @export is.memoised is.memoized
#' @aliases is.memoised is.memoized
#' @examples
#' mem_lm <- memoise(lm)
#' is.memoised(lm) # FALSE
#' is.memoised(mem_lm) # TRUE
is.memoised <- is.memoized <- function(f) {
  is.function(f) && inherits(f, "memoised")
}

#' Test whether a memoised function has been cached for particular arguments.
#' @param f Function to test.
#' @return A function, with the same arguments as \code{f}, that can be called to test
#'   if \code{f} has cached results.
#' @seealso \code{\link{is.memoised}}, \code{\link{memoise}}
#' @export
#' @examples
#' mem_sum <- memoise(sum)
#' has_cache(mem_sum)(1, 2, 3) # FALSE
#' mem_sum(1, 2, 3)
#' has_cache(mem_sum)(1, 2, 3) # TRUE
has_cache <- function(f) {
  if(!is.memoised(f)) stop("`f` is not a memoised function!", call. = FALSE)

  # Modify the function body of the function to simply return TRUE and FALSE
  # rather than get or set the results of the cache
  body <- body(f)
  body[[10]] <- quote(if (encl$`_cache`$has_key(hash)) return(TRUE) else return(FALSE))
  body(f) <- body

  f
}

#' Drops the cache of a memoised function for particular arguments.
#' @param f Memoised function.
#' @return A function, with the same arguments as \code{f}, that can be called to drop
#'   the cached results of \code{f}.
#' @seealso \code{\link{has_cache}}, \code{\link{memoise}}
#' @export
#' @examples
#' mem_sum <- memoise(sum)
#' mem_sum(1, 2, 3)
#' mem_sum(2, 3, 4)
#' has_cache(mem_sum)(1, 2, 3) # TRUE
#' has_cache(mem_sum)(2, 3, 4) # TRUE
#' drop_cache(mem_sum)(1, 2, 3) # TRUE
#' has_cache(mem_sum)(1, 2, 3) # FALSE
#' has_cache(mem_sum)(2, 3, 4) # TRUE
drop_cache <- function(f) {
  if(!is.memoised(f)) stop("`f` is not a memoised function!", call. = FALSE)

  # Modify the function body of the function to simply drop the key
  # and return TRUE if successfully removed
  body <- body(f)
  body[[10]] <- quote(if (encl$`_cache`$has_key(hash)) {
    encl$`_cache`$drop_key(hash)
    return(TRUE)
  } else {
    return(FALSE)
  })
  body(f) <- body

  f
}


# frozen_string_literal: true

require "spec_helper"

module Decidim
  describe ContentRenderers::UserGroupRenderer do
    let(:user_group) { create(:user_group, :confirmed) }
    let(:renderer) { described_class.new(content) }
    let(:presenter) { Decidim::UserGroupPresenter.new(user_group) }

    context "when content has a valid Decidim::UserGroup Global ID" do
      let(:content) { "This text contains a valid Decidim::UserGroup Global ID: #{user_group.to_global_id}" }

      it "renders the mention" do
        expect(renderer.render).to eq(%(This text contains a valid Decidim::UserGroup Global ID: @#{user_group.nickname}))
      end
    end

    context "when content has more than one Decidim::UserGroup Global ID" do
      let(:content) { "This text contains two valid Decidim::UserGroup Global ID: #{user_group.to_global_id} #{user_group.to_global_id}" }

      it "renders the two mentions" do
        rendered = renderer.render
        mention = %(@#{user_group.nickname})
        expect(rendered.scan(mention).length).to eq(2)
      end
    end

    context "when content has an unparsed mention" do
      let(:content) { "This text mentions a non valid user_group: @unvalid" }

      it "ignores the mention" do
        expect(renderer.render).to eq(content)
      end
    end

    context "when content has an invalid Decidim::User Global ID" do
      let(:content) { "This text contains a invalid gid for removed user_group: #{user_group.to_global_id}" }

      before { user_group.destroy }

      it "removes the Global ID" do
        expect(renderer.render).to eq("This text contains a invalid gid for removed user_group: ")
      end

      it "does not raises an exception" do
        expect { renderer.render }.not_to raise_error
      end
    end
  end
end


Page.MasterDetail.Blank.MenuBar

$projectType == Blank|MenuBar & groupidentity == wts.Page.MasterDetail


Package.describe({
  name: 'barbatus:typescript',
  version: '0.7.0',
  summary: 'TypeScript for Meteor',
  git: 'https://github.com/barbatus/typescript',
  documentation: 'README.md'
});

Package.registerBuildPlugin({
  name: 'typescript',
  use: ['barbatus:typescript-compiler'],
  sources: ['plugin.js']
});

Package.onUse(function(api) {
  api.versionsFrom('1.4.1');

  api.use('isobuild:compiler-plugin@1.0.0');
  api.use('barbatus:typescript-compiler@0.10.0');

  api.imply('modules@0.11.6');

  api.imply('barbatus:typescript-runtime@1.1.0');
});

Package.onTest(function(api) {
  api.use('tinytest@1.0.12');
  api.use('barbatus:typescript');

  api.addFiles('tests/runtime-tests.ts', 'client');
  api.addFiles('tests/runtime-react-tests.tsx', 'client');
});


within Buildings.Fluid.Movers.Examples;
model PumpsParallel "Two flow machines in parallel"
  extends Modelica.Icons.Example;

  package Medium = Buildings.Media.Water "Medium model";

  parameter Modelica.SIunits.MassFlowRate m_flow_nominal= 1
    "Nominal mass flow rate";

  parameter Modelica.SIunits.Density rho_nominal=1000
    "Density, used to compute fluid mass";

  Buildings.Fluid.FixedResistances.PressureDrop dpIn1(
    redeclare package Medium = Medium,
    dp_nominal=1000,
    m_flow_nominal=0.5*m_flow_nominal) "Pressure drop"
    annotation (Placement(transformation(extent={{-20,100},{0,120}})));
  Buildings.Fluid.Movers.SpeedControlled_y floMac1(
    redeclare package Medium = Medium,
    per(pressure(V_flow={0, m_flow_nominal/rho_nominal}, dp={2*4*1000, 0})),
    energyDynamics=Modelica.Fluid.Types.Dynamics.FixedInitial)
    "Model of a flow machine"
    annotation (Placement(transformation(extent={{20,100},{40,120}})));

  Buildings.Fluid.FixedResistances.PressureDrop dpOut1(
    redeclare package Medium = Medium,
    dp_nominal=1000,
    m_flow_nominal=0.5*m_flow_nominal) "Pressure drop"
    annotation (Placement(transformation(extent={{58,100},{78,120}})));
  Buildings.Fluid.Sources.Boundary_pT sou(
    redeclare package Medium = Medium,
    use_p_in=false,
    nPorts=2,
    T=293.15) annotation (Placement(transformation(extent={{-92,48},{-72,68}})));

  Buildings.Fluid.FixedResistances.PressureDrop dpIn(
    redeclare package Medium = Medium,
    m_flow_nominal=m_flow_nominal,
    dp_nominal=1000) "Pressure drop"
    annotation (Placement(transformation(extent={{-60,50},{-40,70}})));
  Buildings.Fluid.FixedResistances.PressureDrop dpOut3(
    redeclare package Medium = Medium,
    m_flow_nominal=m_flow_nominal,
    dp_nominal=1000) "Pressure drop"
    annotation (Placement(transformation(extent={{100,50},{120,70}})));

  Buildings.Fluid.FixedResistances.PressureDrop dpIn2(
    redeclare package Medium = Medium,
    dp_nominal=1000,
    m_flow_nominal=0.5*m_flow_nominal) "Pressure drop"
    annotation (Placement(transformation(extent={{-20,0},{0,20}})));
  Buildings.Fluid.Movers.SpeedControlled_y floMac2(
    redeclare package Medium = Medium,
    per(pressure(V_flow={0, m_flow_nominal/rho_nominal}, dp={2*4*1000, 0})),
    energyDynamics=Modelica.Fluid.Types.Dynamics.FixedInitial,
    inputType=Buildings.Fluid.Types.InputType.Constant) "Model of a flow machine"
    annotation (Placement(transformation(extent={{20,0},{40,20}})));
  Buildings.Fluid.FixedResistances.PressureDrop dpOut2(
    redeclare package Medium = Medium,
    dp_nominal=1000,
    m_flow_nominal=0.5*m_flow_nominal) "Pressure drop"
    annotation (Placement(transformation(extent={{58,0},{78,20}})));
  Modelica.Blocks.Sources.Step const1(
    height=-1,
    offset=1,
    startTime=150)
    annotation (Placement(transformation(extent={{0,130},{20,150}})));
equation
  connect(dpIn1.port_b, floMac1.port_a) annotation (Line(
      points={{5.55112e-16,110},{20,110}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(floMac1.port_b, dpOut1.port_a) annotation (Line(
      points={{40,110},{58,110}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(sou.ports[1], dpIn.port_a) annotation (Line(
      points={{-72,60},{-60,60}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpIn.port_b, dpIn1.port_a) annotation (Line(
      points={{-40,60},{-30,60},{-30,110},{-20,110}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpOut1.port_b, dpOut3.port_a) annotation (Line(
      points={{78,110},{90,110},{90,60},{100,60}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpOut3.port_b, sou.ports[2]) annotation (Line(
      points={{120,60},{140,60},{140,-20},{-66,-20},{-66,56},{-72,56}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpIn2.port_b,floMac2. port_a) annotation (Line(
      points={{5.55112e-16,10},{20,10}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(floMac2.port_b,dpOut2. port_a) annotation (Line(
      points={{40,10},{58,10}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpIn.port_b, dpIn2.port_a) annotation (Line(
      points={{-40,60},{-30,60},{-30,10},{-20,10}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(dpOut2.port_b, dpOut3.port_a) annotation (Line(
      points={{78,10},{90,10},{90,60},{100,60}},
      color={0,127,255},
      smooth=Smooth.None));
  connect(const1.y, floMac1.y) annotation (Line(
      points={{21,140},{29.8,140},{29.8,122}},
      color={0,0,127},
      smooth=Smooth.None));
  annotation (
    Diagram(coordinateSystem(preserveAspectRatio=false,extent={{-100,-100},{160,
            160}}), graphics),
    __Dymola_Commands(file="modelica://Buildings/Resources/Scripts/Dymola/Fluid/Movers/Examples/PumpsParallel.mos"
        "Simulate and plot"),
    Documentation(info="
This example tests the configuration of two flow machines that are installed in parallel.
Both flow machines start with full speed.
At t=150 second, the speed of the flow machine on the top is reduced to zero.
As its speed is reduced, the mass flow rate changes its direction in such a way that the flow machine
at the top has reverse flow.
", revisions="

February 20, 2016, by Ruben Baetens:

Removal of dynamicBalance as parameter for massDynamics and energyDynamics.

April 2, 2015, by Filip Jorissen:

Set constant speed for pump using a parameter
instead of a realInput.

May 29, 2014, by Michael Wetter:

Removed undesirable annotation Evaluate=true,
and set rho_nominal to a constant to avoid a non-literal
nominal value for V_flow_max and VMachine_flow.

February 14, 2012, by Michael Wetter:

Added filter for start-up and shut-down transient.

March 24 2010, by Michael Wetter:

First implementation.

"),
    experiment(
      StopTime=300,
      Tolerance=1e-06));
end PumpsParallel;


#include "instructions/push_cpath_top.hpp"

namespace rubinius {
  namespace interpreter {
    intptr_t push_cpath_top(STATE, CallFrame* call_frame, intptr_t const opcodes[]) {
      instructions::push_cpath_top(state, call_frame);

      call_frame->next_ip(instructions::data_push_cpath_top.width);
      return ((instructions::Instruction)opcodes[call_frame->ip()])(state, call_frame, opcodes);
    }
  }
}


using System;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
using System.Text;

namespace Microsoft.AspNetCore.SignalR.Protocol
{
    /// <summary>
    /// Represents a failure to bind arguments for a StreamDataMessage. This does not represent an actual
    /// message that is sent on the wire, it is returned by <see cref="IHubProtocol.TryParseMessage"/>
    /// to indicate that a binding failure occurred when parsing a StreamDataMessage. The stream ID is associated
    /// so that the error can be sent to the relevant hub method.
    /// </summary>
    public class StreamBindingFailureMessage : HubMessage
    {
        /// <summary>
        /// Gets the id of the relevant stream
        /// </summary>
        public string Id { get; }

        /// <summary>
        /// Gets the exception thrown during binding.
        /// </summary>
        public ExceptionDispatchInfo BindingFailure { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvocationBindingFailureMessage"/> class.
        /// </summary>
        /// <param name="id">The stream ID.</param>
        /// <param name="bindingFailure">The exception thrown during binding.</param>
        public StreamBindingFailureMessage(string id, ExceptionDispatchInfo bindingFailure)
        {
            Id = id;
            BindingFailure = bindingFailure;
        }
    }
}


/* TA-LIB Copyright (c) 1999-2007, Mario Fortier
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * - Neither name of author nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* List of contributors:
 *
 *  Initial  Name/description
 *  -------------------------------------------------------------------
 *  MF       Mario Fortier
 *
 *
 * Change history:
 *
 *  MMDDYY BY   Description
 *  -------------------------------------------------------------------
 *  112400 MF   Template creation.
 *  052603 MF   Adapt code to compile with .NET Managed C++
 *
 */

/**** START GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/
/* All code within this section is automatically
 * generated by gen_code. Any modification will be lost
 * next time gen_code is run.
 */
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */    #include "TA-Lib-Core.h"
/* Generated */    #define TA_INTERNAL_ERROR(Id) (RetCode::InternalError)
/* Generated */    namespace TicTacTec { namespace TA { namespace Library {
/* Generated */ #elif defined( _JAVA )
/* Generated */    #include "ta_defs.h"
/* Generated */    #include "ta_java_defs.h"
/* Generated */    #define TA_INTERNAL_ERROR(Id) (RetCode.InternalError)
/* Generated */ #else
/* Generated */    #include <string.h>
/* Generated */    #include <math.h>
/* Generated */    #include "ta_func.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #ifndef TA_UTILITY_H
/* Generated */    #include "ta_utility.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #ifndef TA_MEMORY_H
/* Generated */    #include "ta_memory.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #define TA_PREFIX(x) TA_##x
/* Generated */ #define INPUT_TYPE   double
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */ int Core::StochLookback( int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                        int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                        MAType        optInSlowK_MAType,
/* Generated */                        int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                        MAType        optInSlowD_MAType ) /* Generated */
/* Generated */ #elif defined( _JAVA )
/* Generated */ public int stochLookback( int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                         int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                         MAType        optInSlowK_MAType,
/* Generated */                         int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                         MAType        optInSlowD_MAType ) /* Generated */
/* Generated */ #else
/* Generated */ int TA_STOCH_Lookback( int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                      int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                      TA_MAType     optInSlowK_MAType,
/* Generated */                      int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                      TA_MAType     optInSlowD_MAType ) /* Generated */
/* Generated */ #endif
/**** END GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/
{
   /* insert local variable here */
   int retValue;

/**** START GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/
/* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */    /* min/max are checked for optInFastK_Period. */
/* Generated */    if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInFastK_Period = 5;
/* Generated */    else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */       return -1;
/* Generated */
/* Generated */    /* min/max are checked for optInSlowK_Period. */
/* Generated */    if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowK_Period = 3;
/* Generated */    else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */       return -1;
/* Generated */
/* Generated */    #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */    if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowK_MAType = (TA_MAType)0;
/* Generated */    else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */       return -1;
/* Generated */
/* Generated */    #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */    /* min/max are checked for optInSlowD_Period. */
/* Generated */    if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowD_Period = 3;
/* Generated */    else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */       return -1;
/* Generated */
/* Generated */    #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */    if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowD_MAType = (TA_MAType)0;
/* Generated */    else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */       return -1;
/* Generated */
/* Generated */    #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */
/**** END GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/

   /* insert lookback code here. */

   /* Account for the initial data needed for Fast-K. */
   retValue = (optInFastK_Period - 1);

   /* Add the smoothing being done for %K slow */
   retValue += LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );

   /* Add the smoothing being done for %D slow. */
   retValue += LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );

   return retValue;
}

/**** START GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/
/*
 * TA_STOCH - Stochastic
 *
 * Input  = High, Low, Close
 * Output = double, double
 *
 * Optional Parameters
 * -------------------
 * optInFastK_Period:(From 1 to 100000)
 *    Time period for building the Fast-K line
 *
 * optInSlowK_Period:(From 1 to 100000)
 *    Smoothing for making the Slow-K line. Usually set to 3
 *
 * optInSlowK_MAType:
 *    Type of Moving Average for Slow-K
 *
 * optInSlowD_Period:(From 1 to 100000)
 *    Smoothing for making the Slow-D line
 *
 * optInSlowD_MAType:
 *    Type of Moving Average for Slow-D
 *
 *
 */
/* Generated */
/* Generated */ #if defined( _MANAGED ) && defined( USE_SUBARRAY )
/* Generated */ enum class Core::RetCode Core::Stoch( int    startIdx,
/* Generated */                                       int    endIdx,
/* Generated */                                       SubArray^    inHigh,
/* Generated */                                       SubArray^    inLow,
/* Generated */                                       SubArray^    inClose,
/* Generated */                                       int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                                       int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowK_MAType,
/* Generated */                                       int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowD_MAType,
/* Generated */                                       [Out]int%    outBegIdx,
/* Generated */                                       [Out]int%    outNBElement,
/* Generated */                                       cli::array<double>^  outSlowK,
/* Generated */                                       cli::array<double>^  outSlowD )
/* Generated */ #elif defined( _MANAGED )
/* Generated */ enum class Core::RetCode Core::Stoch( int    startIdx,
/* Generated */                                       int    endIdx,
/* Generated */                                       cli::array<double>^ inHigh,
/* Generated */                                       cli::array<double>^ inLow,
/* Generated */                                       cli::array<double>^ inClose,
/* Generated */                                       int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                                       int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowK_MAType,
/* Generated */                                       int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowD_MAType,
/* Generated */                                       [Out]int%    outBegIdx,
/* Generated */                                       [Out]int%    outNBElement,
/* Generated */                                       cli::array<double>^  outSlowK,
/* Generated */                                       cli::array<double>^  outSlowD )
/* Generated */ #elif defined( _JAVA )
/* Generated */ public RetCode stoch( int    startIdx,
/* Generated */                       int    endIdx,
/* Generated */                       double       inHigh[],
/* Generated */                       double       inLow[],
/* Generated */                       double       inClose[],
/* Generated */                       int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                       int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                       MAType        optInSlowK_MAType,
/* Generated */                       int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                       MAType        optInSlowD_MAType,
/* Generated */                       MInteger     outBegIdx,
/* Generated */                       MInteger     outNBElement,
/* Generated */                       double        outSlowK[],
/* Generated */                       double        outSlowD[] )
/* Generated */ #else
/* Generated */ TA_RetCode TA_STOCH( int    startIdx,
/* Generated */                      int    endIdx,
/* Generated */                      const double inHigh[],
/* Generated */                      const double inLow[],
/* Generated */                      const double inClose[],
/* Generated */                      int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                      int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                      TA_MAType     optInSlowK_MAType,
/* Generated */                      int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                      TA_MAType     optInSlowD_MAType,
/* Generated */                      int          *outBegIdx,
/* Generated */                      int          *outNBElement,
/* Generated */                      double        outSlowK[],
/* Generated */                      double        outSlowD[] )
/* Generated */ #endif
/**** END GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/
{
   /* Insert local variables here. */
   ENUM_DECLARATION(RetCode) retCode;
   double lowest, highest, tmp, diff;
   ARRAY_REF( tempBuffer );
   int outIdx, lowestIdx, highestIdx;
   int lookbackTotal, lookbackK, lookbackKSlow, lookbackDSlow;
   int trailingIdx, today, i;
   #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) &&!defined(_JAVA)
   int bufferIsAllocated;
   #endif

/**** START GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/
/* Generated */
/* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */
/* Generated */    /* Validate the requested output range. */
/* Generated */    if( startIdx < 0 )
/* Generated */       return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex);
/* Generated */    if( (endIdx < 0) || (endIdx < startIdx))
/* Generated */       return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex);
/* Generated */
/* Generated */    #if !defined(_JAVA)
/* Generated */    /* Verify required price component. */
/* Generated */    if(!inHigh||!inLow||!inClose)
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #endif /* !defined(_JAVA)*/
/* Generated */    /* min/max are checked for optInFastK_Period. */
/* Generated */    if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInFastK_Period = 5;
/* Generated */    else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    /* min/max are checked for optInSlowK_Period. */
/* Generated */    if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowK_Period = 3;
/* Generated */    else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */    if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowK_MAType = (TA_MAType)0;
/* Generated */    else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */    /* min/max are checked for optInSlowD_Period. */
/* Generated */    if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowD_Period = 3;
/* Generated */    else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */    if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */       optInSlowD_MAType = (TA_MAType)0;
/* Generated */    else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */    #if !defined(_JAVA)
/* Generated */    if( !outSlowK )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    if( !outSlowD )
/* Generated */       return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */    #endif /* !defined(_JAVA) */
/* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */
/* Generated */
/**** END GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/

   /* Insert TA function code here. */

   /* With stochastic, there is a total of 4 different lines that
    * are defined: FASTK, FASTD, SLOWK and SLOWD.
    *
    * The D is the signal line usually drawn over its
    * corresponding K function.
    *
    *                    (Today's Close - LowestLow)
    *  FASTK(Kperiod) =  --------------------------- * 100
    *                     (HighestHigh - LowestLow)
    *
    *  FASTD(FastDperiod, MA type) = MA Smoothed FASTK over FastDperiod
    *
    *  SLOWK(SlowKperiod, MA type) = MA Smoothed FASTK over SlowKperiod
    *
    *  SLOWD(SlowDperiod, MA Type) = MA Smoothed SLOWK over SlowDperiod
    *
    * The HighestHigh and LowestLow are the extreme values among the
    * last 'Kperiod'.
    *
    * SLOWK and FASTD are equivalent when using the same period.
    *
    * The following shows how these four lines are made available in TA-LIB:
    *
    *  TA_STOCH  : Returns the SLOWK and SLOWD
    *  TA_STOCHF : Returns the FASTK and FASTD
    *
    * The TA_STOCH function correspond to the more widely implemented version
    * found in many software/charting package. The TA_STOCHF is more rarely
    * used because its higher volatility cause often whipsaws.
    */

   /* Identify the lookback needed. */
   lookbackK      = optInFastK_Period-1;
   lookbackKSlow  = LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );
   lookbackDSlow  = LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );
   lookbackTotal  = lookbackK + lookbackDSlow + lookbackKSlow;

   /* Move up the start index if there is not
    * enough initial data.
    */
   if( startIdx < lookbackTotal )
      startIdx = lookbackTotal;

   /* Make sure there is still something to evaluate. */
   if( startIdx > endIdx )
   {
      /* Succeed... but no data in the output. */
      VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
      VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
      return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
   }

   /* Do the K calculation:
    *
    *    Kt = 100 x ((Ct-Lt)/(Ht-Lt))
    *
    * Kt is today stochastic
    * Ct is today closing price.
    * Lt is the lowest price of the last K Period (including today)
    * Ht is the highest price of the last K Period (including today)
    */

   /* Proceed with the calculation for the requested range.
    * Note that this algorithm allows the input and
    * output to be the same buffer.
    */
   outIdx = 0;

   /* Calculate just enough K for ending up with the caller
    * requested range. (The range of k must consider all
    * the lookback involve with the smoothing).
    */
   trailingIdx = startIdx-lookbackTotal;
   today       = trailingIdx+lookbackK;
   lowestIdx   = highestIdx = -1;
   diff = highest = lowest  = 0.0;

   /* Allocate a temporary buffer large enough to
    * store the K.
    *
    * If the output is the same as the input, great
    * we just save ourself one memory allocation.
    */
   #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) && !defined( _JAVA )
      bufferIsAllocated = 0;
   #endif

   #if defined(USE_SINGLE_PRECISION_INPUT) || defined( USE_SUBARRAY )
      /* Always alloc, since output is of different type and
       * its allocated size is not guarantee to be as large as
       * the input.
       */
      ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
   #else
      if( (outSlowK == inHigh) ||
          (outSlowK == inLow)  ||
          (outSlowK == inClose) )
      {
         tempBuffer = outSlowK;
      }
      else if( (outSlowD == inHigh) ||
               (outSlowD == inLow)  ||
               (outSlowD == inClose) )
      {
         tempBuffer = outSlowD;
      }
      else
      {
         #if !defined( _MANAGED ) && !defined(_JAVA)
            bufferIsAllocated = 1;
         #endif
         ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
      }
   #endif

   /* Do the K calculation */
   while( today <= endIdx )
   {
      /* Set the lowest low */
      tmp = inLow[today];
      if( lowestIdx < trailingIdx )
      {
         lowestIdx = trailingIdx;
         lowest = inLow[lowestIdx];
         i = lowestIdx;
         while( ++i<=today )
         {
            tmp = inLow[i];
            if( tmp < lowest )
            {
               lowestIdx = i;
               lowest = tmp;
            }
         }
         diff = (highest - lowest)/100.0;
      }
      else if( tmp <= lowest )
      {
         lowestIdx = today;
         lowest = tmp;
         diff = (highest - lowest)/100.0;
      }

      /* Set the highest high */
      tmp = inHigh[today];
      if( highestIdx < trailingIdx )
      {
         highestIdx = trailingIdx;
         highest = inHigh[highestIdx];
         i = highestIdx;
         while( ++i<=today )
         {
            tmp = inHigh[i];
            if( tmp > highest )
            {
               highestIdx = i;
               highest = tmp;
            }
         }
         diff = (highest - lowest)/100.0;
      }
      else if( tmp >= highest )
      {
         highestIdx = today;
         highest = tmp;
         diff = (highest - lowest)/100.0;
      }

      /* Calculate stochastic. */
      if( diff != 0.0 )
        tempBuffer[outIdx++] = (inClose[today]-lowest)/diff;
      else
        tempBuffer[outIdx++] = 0.0;

      trailingIdx++;
      today++;
   }

   /* Un-smoothed K calculation completed. This K calculation is not returned
    * to the caller. It is always smoothed and then return.
    * Some documentation will refer to the smoothed version as being
    * "K-Slow", but often this end up to be shorten to "K".
    */
   retCode = FUNCTION_CALL_DOUBLE(MA)( 0, outIdx-1,
                                       tempBuffer, optInSlowK_Period,
                                       optInSlowK_MAType,
                                       outBegIdx, outNBElement, tempBuffer );

   if( (retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) ) || ((int)VALUE_HANDLE_DEREF(outNBElement) == 0) )
   {
      #if defined(USE_SINGLE_PRECISION_INPUT)
         ARRAY_FREE( tempBuffer );
      #else
         ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
      #endif
      /* Something wrong happen? No further data? */
      VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
      VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
      return retCode;
   }

   /* Calculate the %D which is simply a moving average of
    * the already smoothed %K.
    */
   retCode = FUNCTION_CALL_DOUBLE(MA)( 0, (int)VALUE_HANDLE_DEREF(outNBElement)-1,
                                       tempBuffer, optInSlowD_Period,
                                       optInSlowD_MAType,
                                       outBegIdx, outNBElement, outSlowD );

   /* Copy tempBuffer into the caller buffer.
    * (Calculation could not be done directly in the
    *  caller buffer because more input data then the
    *  requested range was needed for doing %D).
    */
   ARRAY_MEMMOVE( outSlowK, 0, tempBuffer,lookbackDSlow,(int)VALUE_HANDLE_DEREF(outNBElement));

   /* Don't need K anymore, free it if it was allocated here. */
   #if defined(USE_SINGLE_PRECISION_INPUT)
      ARRAY_FREE( tempBuffer );
   #else
      ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
   #endif

   if( retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) )
   {
      /* Something wrong happen while processing %D? */
      VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
      VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
      return retCode;
   }

   /* Note: Keep the outBegIdx relative to the
    *       caller input before returning.
    */
   VALUE_HANDLE_DEREF(outBegIdx) = startIdx;

   return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
}

/**** START GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/
/* Generated */
/* Generated */ #define  USE_SINGLE_PRECISION_INPUT
/* Generated */ #if !defined( _MANAGED ) && !defined( _JAVA )
/* Generated */    #undef   TA_PREFIX
/* Generated */    #define  TA_PREFIX(x) TA_S_##x
/* Generated */ #endif
/* Generated */ #undef   INPUT_TYPE
/* Generated */ #define  INPUT_TYPE float
/* Generated */ #if defined( _MANAGED )
/* Generated */ enum class Core::RetCode Core::Stoch( int    startIdx,
/* Generated */                                       int    endIdx,
/* Generated */                                       cli::array<float>^ inHigh,
/* Generated */                                       cli::array<float>^ inLow,
/* Generated */                                       cli::array<float>^ inClose,
/* Generated */                                       int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                                       int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowK_MAType,
/* Generated */                                       int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                                       MAType        optInSlowD_MAType,
/* Generated */                                       [Out]int%    outBegIdx,
/* Generated */                                       [Out]int%    outNBElement,
/* Generated */                                       cli::array<double>^  outSlowK,
/* Generated */                                       cli::array<double>^  outSlowD )
/* Generated */ #elif defined( _JAVA )
/* Generated */ public RetCode stoch( int    startIdx,
/* Generated */                       int    endIdx,
/* Generated */                       float        inHigh[],
/* Generated */                       float        inLow[],
/* Generated */                       float        inClose[],
/* Generated */                       int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                       int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                       MAType        optInSlowK_MAType,
/* Generated */                       int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                       MAType        optInSlowD_MAType,
/* Generated */                       MInteger     outBegIdx,
/* Generated */                       MInteger     outNBElement,
/* Generated */                       double        outSlowK[],
/* Generated */                       double        outSlowD[] )
/* Generated */ #else
/* Generated */ TA_RetCode TA_S_STOCH( int    startIdx,
/* Generated */                        int    endIdx,
/* Generated */                        const float  inHigh[],
/* Generated */                        const float  inLow[],
/* Generated */                        const float  inClose[],
/* Generated */                        int           optInFastK_Period, /* From 1 to 100000 */
/* Generated */                        int           optInSlowK_Period, /* From 1 to 100000 */
/* Generated */                        TA_MAType     optInSlowK_MAType,
/* Generated */                        int           optInSlowD_Period, /* From 1 to 100000 */
/* Generated */                        TA_MAType     optInSlowD_MAType,
/* Generated */                        int          *outBegIdx,
/* Generated */                        int          *outNBElement,
/* Generated */                        double        outSlowK[],
/* Generated */                        double        outSlowD[] )
/* Generated */ #endif
/* Generated */ {
/* Generated */    ENUM_DECLARATION(RetCode) retCode;
/* Generated */    double lowest, highest, tmp, diff;
/* Generated */    ARRAY_REF( tempBuffer );
/* Generated */    int outIdx, lowestIdx, highestIdx;
/* Generated */    int lookbackTotal, lookbackK, lookbackKSlow, lookbackDSlow;
/* Generated */    int trailingIdx, today, i;
/* Generated */    #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) &&!defined(_JAVA)
/* Generated */    int bufferIsAllocated;
/* Generated */    #endif
/* Generated */  #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */     if( startIdx < 0 )
/* Generated */        return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex);
/* Generated */     if( (endIdx < 0) || (endIdx < startIdx))
/* Generated */        return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex);
/* Generated */     #if !defined(_JAVA)
/* Generated */     if(!inHigh||!inLow||!inClose)
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #endif
/* Generated */     if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */        optInFastK_Period = 5;
/* Generated */     else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */        optInSlowK_Period = 3;
/* Generated */     else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */     if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */        optInSlowK_MAType = (TA_MAType)0;
/* Generated */     else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #endif
/* Generated */     if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */        optInSlowD_Period = 3;
/* Generated */     else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */     if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */        optInSlowD_MAType = (TA_MAType)0;
/* Generated */     else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #endif
/* Generated */     #if !defined(_JAVA)
/* Generated */     if( !outSlowK )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     if( !outSlowD )
/* Generated */        return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */     #endif
/* Generated */  #endif
/* Generated */    lookbackK      = optInFastK_Period-1;
/* Generated */    lookbackKSlow  = LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );
/* Generated */    lookbackDSlow  = LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );
/* Generated */    lookbackTotal  = lookbackK + lookbackDSlow + lookbackKSlow;
/* Generated */    if( startIdx < lookbackTotal )
/* Generated */       startIdx = lookbackTotal;
/* Generated */    if( startIdx > endIdx )
/* Generated */    {
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */       return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
/* Generated */    }
/* Generated */    outIdx = 0;
/* Generated */    trailingIdx = startIdx-lookbackTotal;
/* Generated */    today       = trailingIdx+lookbackK;
/* Generated */    lowestIdx   = highestIdx = -1;
/* Generated */    diff = highest = lowest  = 0.0;
/* Generated */    #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) && !defined( _JAVA )
/* Generated */       bufferIsAllocated = 0;
/* Generated */    #endif
/* Generated */    #if defined(USE_SINGLE_PRECISION_INPUT) || defined( USE_SUBARRAY )
/* Generated */       ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
/* Generated */    #else
/* Generated */       if( (outSlowK == inHigh) ||
/* Generated */           (outSlowK == inLow)  ||
/* Generated */           (outSlowK == inClose) )
/* Generated */       {
/* Generated */          tempBuffer = outSlowK;
/* Generated */       }
/* Generated */       else if( (outSlowD == inHigh) ||
/* Generated */                (outSlowD == inLow)  ||
/* Generated */                (outSlowD == inClose) )
/* Generated */       {
/* Generated */          tempBuffer = outSlowD;
/* Generated */       }
/* Generated */       else
/* Generated */       {
/* Generated */          #if !defined( _MANAGED ) && !defined(_JAVA)
/* Generated */             bufferIsAllocated = 1;
/* Generated */          #endif
/* Generated */          ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
/* Generated */       }
/* Generated */    #endif
/* Generated */    while( today <= endIdx )
/* Generated */    {
/* Generated */       tmp = inLow[today];
/* Generated */       if( lowestIdx < trailingIdx )
/* Generated */       {
/* Generated */          lowestIdx = trailingIdx;
/* Generated */          lowest = inLow[lowestIdx];
/* Generated */          i = lowestIdx;
/* Generated */          while( ++i<=today )
/* Generated */          {
/* Generated */             tmp = inLow[i];
/* Generated */             if( tmp < lowest )
/* Generated */             {
/* Generated */                lowestIdx = i;
/* Generated */                lowest = tmp;
/* Generated */             }
/* Generated */          }
/* Generated */          diff = (highest - lowest)/100.0;
/* Generated */       }
/* Generated */       else if( tmp <= lowest )
/* Generated */       {
/* Generated */          lowestIdx = today;
/* Generated */          lowest = tmp;
/* Generated */          diff = (highest - lowest)/100.0;
/* Generated */       }
/* Generated */       tmp = inHigh[today];
/* Generated */       if( highestIdx < trailingIdx )
/* Generated */       {
/* Generated */          highestIdx = trailingIdx;
/* Generated */          highest = inHigh[highestIdx];
/* Generated */          i = highestIdx;
/* Generated */          while( ++i<=today )
/* Generated */          {
/* Generated */             tmp = inHigh[i];
/* Generated */             if( tmp > highest )
/* Generated */             {
/* Generated */                highestIdx = i;
/* Generated */                highest = tmp;
/* Generated */             }
/* Generated */          }
/* Generated */          diff = (highest - lowest)/100.0;
/* Generated */       }
/* Generated */       else if( tmp >= highest )
/* Generated */       {
/* Generated */          highestIdx = today;
/* Generated */          highest = tmp;
/* Generated */          diff = (highest - lowest)/100.0;
/* Generated */       }
/* Generated */       if( diff != 0.0 )
/* Generated */         tempBuffer[outIdx++] = (inClose[today]-lowest)/diff;
/* Generated */       else
/* Generated */         tempBuffer[outIdx++] = 0.0;
/* Generated */       trailingIdx++;
/* Generated */       today++;
/* Generated */    }
/* Generated */    retCode = FUNCTION_CALL_DOUBLE(MA)( 0, outIdx-1,
/* Generated */                                        tempBuffer, optInSlowK_Period,
/* Generated */                                        optInSlowK_MAType,
/* Generated */                                        outBegIdx, outNBElement, tempBuffer );
/* Generated */    if( (retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) ) || ((int)VALUE_HANDLE_DEREF(outNBElement) == 0) )
/* Generated */    {
/* Generated */       #if defined(USE_SINGLE_PRECISION_INPUT)
/* Generated */          ARRAY_FREE( tempBuffer );
/* Generated */       #else
/* Generated */          ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
/* Generated */       #endif
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */       return retCode;
/* Generated */    }
/* Generated */    retCode = FUNCTION_CALL_DOUBLE(MA)( 0, (int)VALUE_HANDLE_DEREF(outNBElement)-1,
/* Generated */                                        tempBuffer, optInSlowD_Period,
/* Generated */                                        optInSlowD_MAType,
/* Generated */                                        outBegIdx, outNBElement, outSlowD );
/* Generated */    ARRAY_MEMMOVE( outSlowK, 0, tempBuffer,lookbackDSlow,(int)VALUE_HANDLE_DEREF(outNBElement));
/* Generated */    #if defined(USE_SINGLE_PRECISION_INPUT)
/* Generated */       ARRAY_FREE( tempBuffer );
/* Generated */    #else
/* Generated */       ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
/* Generated */    #endif
/* Generated */    if( retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) )
/* Generated */    {
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */       VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */       return retCode;
/* Generated */    }
/* Generated */    VALUE_HANDLE_DEREF(outBegIdx) = startIdx;
/* Generated */    return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
/* Generated */ }
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */ }}} // Close namespace TicTacTec.TA.Lib
/* Generated */ #endif
/**** END GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/


'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
  n = n + '';
  var i = n.indexOf('.');
  return (i == -1) ? 0 : n.length - i - 1;
}

function getVF(n, opt_precision) {
  var v = opt_precision;

  if (undefined === v) {
    v = Math.min(getDecimals(n), 3);
  }

  var base = Math.pow(10, v);
  var f = ((n * base) | 0) % base;
  return {v: v, f: f};
}

$provide.value("$locale", {
  "DATETIME_FORMATS": {
    "AMPMS": [
      "AM",
      "PM"
    ],
    "DAY": [
      "Jumapili",
      "Jumatatu",
      "Jumanne",
      "Jumatano",
      "Alhamisi",
      "Ijumaa",
      "Jumamosi"
    ],
    "ERANAMES": [
      "Kabla ya Kristo",
      "Baada ya Kristo"
    ],
    "ERAS": [
      "BC",
      "AD"
    ],
    "MONTH": [
      "Januari",
      "Februari",
      "Machi",
      "Aprili",
      "Mei",
      "Juni",
      "Julai",
      "Agosti",
      "Septemba",
      "Oktoba",
      "Novemba",
      "Desemba"
    ],
    "SHORTDAY": [
      "Jumapili",
      "Jumatatu",
      "Jumanne",
      "Jumatano",
      "Alhamisi",
      "Ijumaa",
      "Jumamosi"
    ],
    "SHORTMONTH": [
      "Jan",
      "Feb",
      "Mac",
      "Apr",
      "Mei",
      "Jun",
      "Jul",
      "Ago",
      "Sep",
      "Okt",
      "Nov",
      "Des"
    ],
    "fullDate": "EEEE, d MMMM y",
    "longDate": "d MMMM y",
    "medium": "d MMM y h:mm:ss a",
    "mediumDate": "d MMM y",
    "mediumTime": "h:mm:ss a",
    "short": "dd/MM/y h:mm a",
    "shortDate": "dd/MM/y",
    "shortTime": "h:mm a"
  },
  "NUMBER_FORMATS": {
    "CURRENCY_SYM": "UGX",
    "DECIMAL_SEP": ".",
    "GROUP_SEP": ",",
    "PATTERNS": [
      {
        "gSize": 3,
        "lgSize": 3,
        "maxFrac": 3,
        "minFrac": 0,
        "minInt": 1,
        "negPre": "-",
        "negSuf": "",
        "posPre": "",
        "posSuf": ""
      },
      {
        "gSize": 3,
        "lgSize": 3,
        "maxFrac": 2,
        "minFrac": 2,
        "minInt": 1,
        "negPre": "\u00a4-",
        "negSuf": "",
        "posPre": "\u00a4",
        "posSuf": ""
      }
    ]
  },
  "id": "sw-ug",
  "pluralCat": function(n, opt_precision) {  var i = n | 0;  var vf = getVF(n, opt_precision);  if (i == 1 && vf.v == 0) {    return PLURAL_CATEGORY.ONE;  }  return PLURAL_CATEGORY.OTHER;}
});
}]);


package idrisct

modules = Utils
        , Basic.Category
        , Basic.Functor
        , Basic.Isomorphism
        , Basic.NaturalIsomorphism
        , Basic.NaturalTransformation
        , Cats.CatsAsCategory
        , Cats.FunctorsAsCategory
        , CoLimits.CoProduct
        , CoLimits.InitialObject
        , Discrete.DiscreteCategory
        , Discrete.FunctionAsFunctor
        , Dual.DualCategory
        , Dual.DualFunctor
        , Free.FreeFunctor
        , Free.Graph
        , Free.Path
        , Free.PathCategory
        , Hom.HomFunctor
        , Idris.EitherAsCoProduct
        , Idris.FunctorAsCFunctor
        , Idris.TypesAsCategory
        , Idris.TypesAsCategoryExtensional
        , Monoid.Monoid
        , Monoid.MonoidAsCategory
        , Monoid.MonoidMorphism
        , Monoid.MonoidMorphismAsFunctor
        , Monoid.MonoidsCategory
        , MonoidalCategory.MonoidalCategory
        , MonoidalCategory.MonoidalCategoryHelpers
        , MonoidalCategory.StrictMonoidalCategory
        , MonoidalCategory.SymmetricMonoidalCategory
        , MonoidalCategory.SymmetricMonoidalCategoryHelpers
        , PointedTypes.PointedTypesCategory
        , Preorder.MonotoneMap
        , Preorder.MonotoneMapAsFunctor
        , Preorder.PreorderAsCategory
        , Preorder.UniquePreorder
        , Product.ProductCategory
        , Product.ProductFunctor
        , Profunctors.Profunctor


html {
  height: 100%;
}

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  min-height: 100%;
}


=pod

=head1 NAME

SSL_new, SSL_up_ref - create a new SSL structure for a connection

=head1 SYNOPSIS

 #include <openssl/ssl.h>

 SSL *SSL_new(SSL_CTX *ctx);
 int SSL_up_ref(SSL *s);

=head1 DESCRIPTION

SSL_new() creates a new B<SSL> structure which is needed to hold the
data for a TLS/SSL connection. The new structure inherits the settings
of the underlying context B<ctx>: connection method,
options, verification settings, timeout settings. An B<SSL> structure is
reference counted. Creating an B<SSL> structure for the first time increments
the reference count. Freeing it (using SSL_free) decrements it. When the
reference count drops to zero, any memory or resources allocated to the B<SSL>
structure are freed. SSL_up_ref() increments the reference count for an
existing B<SSL> structure.

=head1 RETURN VALUES

The following return values can occur:

=over 4

=item NULL

The creation of a new SSL structure failed. Check the error stack to
find out the reason.

=item Pointer to an SSL structure

The return value points to an allocated SSL structure.

SSL_up_ref() returns 1 for success and 0 for failure.

=back

=head1 SEE ALSO

L<SSL_free(3)>, L<SSL_clear(3)>,
L<SSL_CTX_set_options(3)>,
L<SSL_get_SSL_CTX(3)>,
L<ssl(3)>

=head1 COPYRIGHT

Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the OpenSSL license (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


(function( factory ) {
	if ( typeof define === "function" && define.amd ) {
		define( ["jquery", "../jquery.validate"], factory );
	} else if (typeof module === "object" && module.exports) {
		module.exports = factory( require( "jquery" ) );
	} else {
		factory( jQuery );
	}
}(function( $ ) {

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: SK (Slovak; slovenčina, slovenský jazyk)
 */
$.extend( $.validator.messages, {
	required: "Povinné zadať.",
	maxlength: $.validator.format( "Maximálne {0} znakov." ),
	minlength: $.validator.format( "Minimálne {0} znakov." ),
	rangelength: $.validator.format( "Minimálne {0} a maximálne {1} znakov." ),
	email: "E-mailová adresa musí byť platná.",
	url: "URL musí byť platná.",
	date: "Musí byť dátum.",
	number: "Musí byť číslo.",
	digits: "Môže obsahovať iba číslice.",
	equalTo: "Dve hodnoty sa musia rovnať.",
	range: $.validator.format( "Musí byť medzi {0} a {1}." ),
	max: $.validator.format( "Nemôže byť viac ako {0}." ),
	min: $.validator.format( "Nemôže byť menej ako {0}." ),
	creditcard: "Číslo platobnej karty musí byť platné.",
	step: $.validator.format( "Musí byť násobkom čísla {0}." )
} );
return $;
}));


; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; RUN: opt < %s -instsimplify -S | FileCheck %s

; This tests checks optimization consistency for scalar and vector code.
; If m_Zero() is able to match a vector undef, but not a scalar undef,
; the two cases will simplify differently.

define i32 @test_scalar(i32 %a, i1 %b) {
; CHECK-LABEL: @test_scalar(
; CHECK-NEXT:    ret i32 undef
;
  %c = sext i1 %b to i32
  %d = ashr i32 undef, %c
  ret i32 %d
}

define <2 x i32> @test_vector(<2 x i32> %a, <2 x i1> %b) {
; CHECK-LABEL: @test_vector(
; CHECK-NEXT:    ret <2 x i32> undef
;
  %c = sext <2 x i1> %b to <2 x i32>
  %d = ashr <2 x i32> undef, %c
  ret <2 x i32> %d
}


/******************************************************************************
 *
 * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
 *
 *
 ******************************************************************************/

#ifndef _LINUX_WIRELESS_H
#define _LINUX_WIRELESS_H

/***************************** INCLUDES *****************************/

#if 0
#include <linux/types.h>		/* for __u* and __s* typedefs */
#include <linux/socket.h>		/* for "struct sockaddr" et al	*/
#include <linux/if.h>			/* for IFNAMSIZ and co... */
#else
#define __user
//typedef uint16_t	__u16;
#include <sys/socket.h>			/* for "struct sockaddr" et al	*/
#include <net/if.h>			/* for IFNAMSIZ and co... */
#endif

/****************************** TYPES ******************************/
#ifdef CONFIG_COMPAT
struct compat_iw_point {
         compat_caddr_t pointer;
         __u16 length;
         __u16 flags;
};
#endif
/* --------------------------- SUBTYPES --------------------------- */
/*
 *	For all data larger than 16 octets, we need to use a
 *	pointer to memory allocated in user space.
 */
struct	iw_point
{
  void __user	*pointer;	/* Pointer to the data  (in user space) */
  __u16		length;		/* number of fields or size in bytes */
  __u16		flags;		/* Optional params */
};

/* ------------------------ IOCTL REQUEST ------------------------ */
/*
 * This structure defines the payload of an ioctl, and is used
 * below.
 *
 * Note that this structure should fit on the memory footprint
 * of iwreq (which is the same as ifreq), which mean a max size of
 * 16 octets = 128 bits. Warning, pointers might be 64 bits wide...
 * You should check this when increasing the structures defined
 * above in this file...
 */
union	iwreq_data
{
	/* Config - generic */
	char		name[IFNAMSIZ];
	/* Name : used to verify the presence of  wireless extensions.
	 * Name of the protocol/provider... */

	struct iw_point	data;		/* Other large parameters */
};

/*
 * The structure to exchange data for ioctl.
 * This structure is the same as 'struct ifreq', but (re)defined for
 * convenience...
 * Do I need to remind you about structure size (32 octets) ?
 */
struct	iwreq
{
	union
	{
		char	ifrn_name[IFNAMSIZ];	/* if name, e.g. "eth0" */
	} ifr_ifrn;

	/* Data part (defined just above) */
	union	iwreq_data	u;
};

#endif	/* _LINUX_WIRELESS_H */


diagnosticMessage=Don't use a join with sub queries
diagnosticName=Join with sub queries


/*
 * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * File: mib.c
 *
 * Purpose: Implement MIB Data Structure
 *
 * Author: Tevin Chen
 *
 * Date: May 21, 1996
 *
 * Functions:
 *      STAvClearAllCounter - Clear All MIB Counter
 *      STAvUpdateIstStatCounter - Update ISR statistic counter
 *      STAvUpdateRDStatCounter - Update Rx statistic counter
 *      STAvUpdateRDStatCounterEx - Update Rx statistic counter and copy rcv data
 *      STAvUpdateTDStatCounter - Update Tx statistic counter
 *      STAvUpdateTDStatCounterEx - Update Tx statistic counter and copy tx data
 *      STAvUpdate802_11Counter - Update 802.11 mib counter
 *
 * Revision History:
 *
 */

#include "upc.h"
#include "mac.h"
#include "tether.h"
#include "mib.h"
#include "wctl.h"
#include "baseband.h"

/*---------------------  Static Definitions -------------------------*/
static int          msglevel                =MSG_LEVEL_INFO;
/*---------------------  Static Classes  ----------------------------*/

/*---------------------  Static Variables  --------------------------*/

/*---------------------  Static Functions  --------------------------*/

/*---------------------  Export Variables  --------------------------*/

/*---------------------  Export Functions  --------------------------*/

/*
 * Description: Clear All Statistic Counter
 *
 * Parameters:
 *  In:
 *      pStatistic  - Pointer to Statistic Counter Data Structure
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void STAvClearAllCounter (PSStatCounter pStatistic)
{
    // set memory to zero
	memset(pStatistic, 0, sizeof(SStatCounter));
}

/*
 * Description: Update Isr Statistic Counter
 *
 * Parameters:
 *  In:
 *      pStatistic  - Pointer to Statistic Counter Data Structure
 *      wisr        - Interrupt status
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void STAvUpdateIsrStatCounter (PSStatCounter pStatistic, BYTE byIsr0, BYTE byIsr1)
{
    /**********************/
    /* ABNORMAL interrupt */
    /**********************/
    // not any IMR bit invoke irq
    if (byIsr0 == 0) {
        pStatistic->ISRStat.dwIsrUnknown++;
        return;
    }

    if (byIsr0 & ISR_ACTX)              // ISR, bit0
        pStatistic->ISRStat.dwIsrTx0OK++;           // TXDMA0 successful

    if (byIsr0 & ISR_BNTX)              // ISR, bit2
        pStatistic->ISRStat.dwIsrBeaconTxOK++;      // BeaconTx successful

    if (byIsr0 & ISR_RXDMA0)            // ISR, bit3
        pStatistic->ISRStat.dwIsrRx0OK++;           // Rx0 successful

    if (byIsr0 & ISR_TBTT)              // ISR, bit4
        pStatistic->ISRStat.dwIsrTBTTInt++;         // TBTT successful

    if (byIsr0 & ISR_SOFTTIMER)         // ISR, bit6
        pStatistic->ISRStat.dwIsrSTIMERInt++;

    if (byIsr0 & ISR_WATCHDOG)          // ISR, bit7
        pStatistic->ISRStat.dwIsrWatchDog++;

    if (byIsr1 & ISR_FETALERR)              // ISR, bit8
        pStatistic->ISRStat.dwIsrUnrecoverableError++;

    if (byIsr1 & ISR_SOFTINT)               // ISR, bit9
        pStatistic->ISRStat.dwIsrSoftInterrupt++;       // software interrupt

    if (byIsr1 & ISR_MIBNEARFULL)           // ISR, bit10
        pStatistic->ISRStat.dwIsrMIBNearfull++;

    if (byIsr1 & ISR_RXNOBUF)               // ISR, bit11
        pStatistic->ISRStat.dwIsrRxNoBuf++;             // Rx No Buff

}

/*
 * Description: Update Rx Statistic Counter
 *
 * Parameters:
 *  In:
 *      pStatistic      - Pointer to Statistic Counter Data Structure
 *      byRSR           - Rx Status
 *      byNewRSR        - Rx Status
 *      pbyBuffer       - Rx Buffer
 *      cbFrameLength   - Rx Length
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void STAvUpdateRDStatCounter(PSStatCounter pStatistic,
			     BYTE byRSR, BYTE byNewRSR,
			     BYTE byRxSts, BYTE byRxRate,
			     PBYTE pbyBuffer, unsigned int cbFrameLength)
{
	/* need change */
	PS802_11Header pHeader = (PS802_11Header)pbyBuffer;

	if (byRSR & RSR_ADDROK)
		pStatistic->dwRsrADDROk++;
	if (byRSR & RSR_CRCOK) {
		pStatistic->dwRsrCRCOk++;
		pStatistic->ullRsrOK++;

		if (cbFrameLength >= ETH_ALEN) {
			/* update counters in case of successful transmission */
            if (byRSR & RSR_ADDRBROAD) {
                pStatistic->ullRxBroadcastFrames++;
		pStatistic->ullRxBroadcastBytes +=
		  (unsigned long long) cbFrameLength;
            }
            else if (byRSR & RSR_ADDRMULTI) {
                pStatistic->ullRxMulticastFrames++;
		pStatistic->ullRxMulticastBytes +=
		  (unsigned long long) cbFrameLength;
            }
            else {
                pStatistic->ullRxDirectedFrames++;
		pStatistic->ullRxDirectedBytes +=
		  (unsigned long long) cbFrameLength;
            }
        }
    }

    if(byRxRate==22) {
        pStatistic->CustomStat.ullRsr11M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr11MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "11M: ALL[%d], OK[%d]:[%02x]\n",
		(signed int) pStatistic->CustomStat.ullRsr11M,
		(signed int) pStatistic->CustomStat.ullRsr11MCRCOk, byRSR);
    }
    else if(byRxRate==11) {
        pStatistic->CustomStat.ullRsr5M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr5MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " 5M: ALL[%d], OK[%d]:[%02x]\n",
		(signed int) pStatistic->CustomStat.ullRsr5M,
		(signed int) pStatistic->CustomStat.ullRsr5MCRCOk, byRSR);
    }
    else if(byRxRate==4) {
        pStatistic->CustomStat.ullRsr2M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr2MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " 2M: ALL[%d], OK[%d]:[%02x]\n",
		(signed int) pStatistic->CustomStat.ullRsr2M,
		(signed int) pStatistic->CustomStat.ullRsr2MCRCOk, byRSR);
    }
    else if(byRxRate==2){
        pStatistic->CustomStat.ullRsr1M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr1MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " 1M: ALL[%d], OK[%d]:[%02x]\n",
		(signed int) pStatistic->CustomStat.ullRsr1M,
		(signed int) pStatistic->CustomStat.ullRsr1MCRCOk, byRSR);
    }
    else if(byRxRate==12){
        pStatistic->CustomStat.ullRsr6M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr6MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " 6M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr6M,
		(signed int) pStatistic->CustomStat.ullRsr6MCRCOk);
    }
    else if(byRxRate==18){
        pStatistic->CustomStat.ullRsr9M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr9MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " 9M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr9M,
		(signed int) pStatistic->CustomStat.ullRsr9MCRCOk);
    }
    else if(byRxRate==24){
        pStatistic->CustomStat.ullRsr12M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr12MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "12M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr12M,
		(signed int) pStatistic->CustomStat.ullRsr12MCRCOk);
    }
    else if(byRxRate==36){
        pStatistic->CustomStat.ullRsr18M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr18MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "18M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr18M,
		(signed int) pStatistic->CustomStat.ullRsr18MCRCOk);
    }
    else if(byRxRate==48){
        pStatistic->CustomStat.ullRsr24M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr24MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "24M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr24M,
		(signed int) pStatistic->CustomStat.ullRsr24MCRCOk);
    }
    else if(byRxRate==72){
        pStatistic->CustomStat.ullRsr36M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr36MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "36M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr36M,
		(signed int) pStatistic->CustomStat.ullRsr36MCRCOk);
    }
    else if(byRxRate==96){
        pStatistic->CustomStat.ullRsr48M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr48MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "48M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr48M,
		(signed int) pStatistic->CustomStat.ullRsr48MCRCOk);
    }
    else if(byRxRate==108){
        pStatistic->CustomStat.ullRsr54M++;
        if(byRSR & RSR_CRCOK) {
            pStatistic->CustomStat.ullRsr54MCRCOk++;
        }
	DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "54M: ALL[%d], OK[%d]\n",
		(signed int) pStatistic->CustomStat.ullRsr54M,
		(signed int) pStatistic->CustomStat.ullRsr54MCRCOk);
    }
    else {
	    DBG_PRT(MSG_LEVEL_DEBUG,
		    KERN_INFO "Unknown: Total[%d], CRCOK[%d]\n",
		    (signed int) pStatistic->dwRsrRxPacket+1,
		    (signed int)pStatistic->dwRsrCRCOk);
    }

    if (byRSR & RSR_BSSIDOK)
        pStatistic->dwRsrBSSIDOk++;

    if (byRSR & RSR_BCNSSIDOK)
        pStatistic->dwRsrBCNSSIDOk++;
    if (byRSR & RSR_IVLDLEN)  //invalid len (> 2312 byte)
        pStatistic->dwRsrLENErr++;
    if (byRSR & RSR_IVLDTYP)  //invalid packet type
        pStatistic->dwRsrTYPErr++;
    if ((byRSR & (RSR_IVLDTYP | RSR_IVLDLEN)) || !(byRSR & RSR_CRCOK))
        pStatistic->dwRsrErr++;

    if (byNewRSR & NEWRSR_DECRYPTOK)
        pStatistic->dwNewRsrDECRYPTOK++;
    if (byNewRSR & NEWRSR_CFPIND)
        pStatistic->dwNewRsrCFP++;
    if (byNewRSR & NEWRSR_HWUTSF)
        pStatistic->dwNewRsrUTSF++;
    if (byNewRSR & NEWRSR_BCNHITAID)
        pStatistic->dwNewRsrHITAID++;
    if (byNewRSR & NEWRSR_BCNHITAID0)
        pStatistic->dwNewRsrHITAID0++;

    // increase rx packet count
    pStatistic->dwRsrRxPacket++;
    pStatistic->dwRsrRxOctet += cbFrameLength;

    if (IS_TYPE_DATA(pbyBuffer)) {
        pStatistic->dwRsrRxData++;
    } else if (IS_TYPE_MGMT(pbyBuffer)){
        pStatistic->dwRsrRxManage++;
    } else if (IS_TYPE_CONTROL(pbyBuffer)){
        pStatistic->dwRsrRxControl++;
    }

    if (byRSR & RSR_ADDRBROAD)
        pStatistic->dwRsrBroadcast++;
    else if (byRSR & RSR_ADDRMULTI)
        pStatistic->dwRsrMulticast++;
    else
        pStatistic->dwRsrDirected++;

    if (WLAN_GET_FC_MOREFRAG(pHeader->wFrameCtl))
        pStatistic->dwRsrRxFragment++;

    if (cbFrameLength < ETH_ZLEN + 4) {
        pStatistic->dwRsrRunt++;
    } else if (cbFrameLength == ETH_ZLEN + 4) {
        pStatistic->dwRsrRxFrmLen64++;
    }
    else if ((65 <= cbFrameLength) && (cbFrameLength <= 127)) {
        pStatistic->dwRsrRxFrmLen65_127++;
    }
    else if ((128 <= cbFrameLength) && (cbFrameLength <= 255)) {
        pStatistic->dwRsrRxFrmLen128_255++;
    }
    else if ((256 <= cbFrameLength) && (cbFrameLength <= 511)) {
        pStatistic->dwRsrRxFrmLen256_511++;
    }
    else if ((512 <= cbFrameLength) && (cbFrameLength <= 1023)) {
        pStatistic->dwRsrRxFrmLen512_1023++;
    } else if ((1024 <= cbFrameLength) &&
	       (cbFrameLength <= ETH_FRAME_LEN + 4)) {
        pStatistic->dwRsrRxFrmLen1024_1518++;
    } else if (cbFrameLength > ETH_FRAME_LEN + 4) {
        pStatistic->dwRsrLong++;
    }
}

/*
 * Description: Update Rx Statistic Counter and copy Rx buffer
 *
 * Parameters:
 *  In:
 *      pStatistic      - Pointer to Statistic Counter Data Structure
 *      byRSR           - Rx Status
 *      byNewRSR        - Rx Status
 *      pbyBuffer       - Rx Buffer
 *      cbFrameLength   - Rx Length
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */

void
STAvUpdateRDStatCounterEx (
    PSStatCounter   pStatistic,
    BYTE            byRSR,
    BYTE            byNewRSR,
    BYTE            byRxSts,
    BYTE            byRxRate,
    PBYTE           pbyBuffer,
    unsigned int            cbFrameLength
    )
{
    STAvUpdateRDStatCounter(
                    pStatistic,
                    byRSR,
                    byNewRSR,
                    byRxSts,
                    byRxRate,
                    pbyBuffer,
                    cbFrameLength
                    );

    // rx length
    pStatistic->dwCntRxFrmLength = cbFrameLength;
    // rx pattern, we just see 10 bytes for sample
    memcpy(pStatistic->abyCntRxPattern, (PBYTE)pbyBuffer, 10);
}

/*
 * Description: Update Tx Statistic Counter
 *
 * Parameters:
 *  In:
 *      pStatistic      - Pointer to Statistic Counter Data Structure
 *      byTSR0          - Tx Status
 *      byTSR1          - Tx Status
 *      pbyBuffer       - Tx Buffer
 *      cbFrameLength   - Tx Length
 *      uIdx            - Index of Tx DMA
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void
STAvUpdateTDStatCounter (
    PSStatCounter   pStatistic,
    BYTE            byPktNum,
    BYTE            byRate,
    BYTE            byTSR
    )
{
    BYTE    byRetyCnt;
    // increase tx packet count
    pStatistic->dwTsrTxPacket++;

    byRetyCnt = (byTSR & 0xF0) >> 4;
    if (byRetyCnt != 0) {
        pStatistic->dwTsrRetry++;
        pStatistic->dwTsrTotalRetry += byRetyCnt;
        pStatistic->dwTxFail[byRate]+= byRetyCnt;
        pStatistic->dwTxFail[MAX_RATE] += byRetyCnt;

        if ( byRetyCnt == 0x1)
            pStatistic->dwTsrOnceRetry++;
        else
            pStatistic->dwTsrMoreThanOnceRetry++;

        if (byRetyCnt <= 8)
            pStatistic->dwTxRetryCount[byRetyCnt-1]++;

    }
    if ( !(byTSR & (TSR_TMO | TSR_RETRYTMO))) {

   if (byRetyCnt < 2)
        pStatistic->TxNoRetryOkCount ++;
   else
        pStatistic->TxRetryOkCount ++;

        pStatistic->ullTsrOK++;
        pStatistic->CustomStat.ullTsrAllOK++;
        // update counters in case that successful transmit
        pStatistic->dwTxOk[byRate]++;
        pStatistic->dwTxOk[MAX_RATE]++;

        if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_BROAD )  {
            pStatistic->ullTxBroadcastFrames++;
            pStatistic->ullTxBroadcastBytes += pStatistic->abyTxPktInfo[byPktNum].wLength;
        } else if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_MULTI ) {
            pStatistic->ullTxMulticastFrames++;
            pStatistic->ullTxMulticastBytes += pStatistic->abyTxPktInfo[byPktNum].wLength;
        } else if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_UNI ) {
            pStatistic->ullTxDirectedFrames++;
            pStatistic->ullTxDirectedBytes += pStatistic->abyTxPktInfo[byPktNum].wLength;
        }
    }
    else {

        pStatistic->TxFailCount ++;

        pStatistic->dwTsrErr++;
        if (byTSR & TSR_RETRYTMO)
            pStatistic->dwTsrRetryTimeout++;
        if (byTSR & TSR_TMO)
            pStatistic->dwTsrTransmitTimeout++;
    }

    if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_BROAD )  {
        pStatistic->dwTsrBroadcast++;
    } else if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_MULTI ) {
        pStatistic->dwTsrMulticast++;
    } else if ( pStatistic->abyTxPktInfo[byPktNum].byBroadMultiUni == TX_PKT_UNI ) {
        pStatistic->dwTsrDirected++;
    }
}

/*
 * Description: Update 802.11 mib counter
 *
 * Parameters:
 *  In:
 *      p802_11Counter  - Pointer to 802.11 mib counter
 *      pStatistic      - Pointer to Statistic Counter Data Structure
 *      dwCounter       - hardware counter for 802.11 mib
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void
STAvUpdate802_11Counter(
    PSDot11Counters         p802_11Counter,
    PSStatCounter           pStatistic,
    BYTE                    byRTSSuccess,
    BYTE                    byRTSFail,
    BYTE                    byACKFail,
    BYTE                    byFCSErr
    )
{
    //p802_11Counter->TransmittedFragmentCount
    p802_11Counter->MulticastTransmittedFrameCount =
      (unsigned long long) (pStatistic->dwTsrBroadcast +
			    pStatistic->dwTsrMulticast);
    p802_11Counter->FailedCount = (unsigned long long) (pStatistic->dwTsrErr);
    p802_11Counter->RetryCount = (unsigned long long) (pStatistic->dwTsrRetry);
    p802_11Counter->MultipleRetryCount =
      (unsigned long long) (pStatistic->dwTsrMoreThanOnceRetry);
    //p802_11Counter->FrameDuplicateCount
    p802_11Counter->RTSSuccessCount += (unsigned long long) byRTSSuccess;
    p802_11Counter->RTSFailureCount += (unsigned long long) byRTSFail;
    p802_11Counter->ACKFailureCount += (unsigned long long) byACKFail;
    p802_11Counter->FCSErrorCount +=   (unsigned long long) byFCSErr;
    //p802_11Counter->ReceivedFragmentCount
    p802_11Counter->MulticastReceivedFrameCount =
      (unsigned long long) (pStatistic->dwRsrBroadcast +
			    pStatistic->dwRsrMulticast);
}

/*
 * Description: Clear 802.11 mib counter
 *
 * Parameters:
 *  In:
 *      p802_11Counter  - Pointer to 802.11 mib counter
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */
void
STAvClear802_11Counter(PSDot11Counters p802_11Counter)
{
    // set memory to zero
	memset(p802_11Counter, 0, sizeof(SDot11Counters));
}

/*
 * Description: Clear 802.11 mib counter
 *
 * Parameters:
 *  In:
 *      pUsbCounter  - Pointer to USB mib counter
 *      ntStatus - URB status
 *  Out:
 *      none
 *
 * Return Value: none
 *
 */

void STAvUpdateUSBCounter(PSUSBCounter pUsbCounter, int ntStatus)
{

//    if ( ntStatus == USBD_STATUS_CRC ) {
        pUsbCounter->dwCrc++;
//    }

}


//
// streambuf.hpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef ASIO_STREAMBUF_HPP
#define ASIO_STREAMBUF_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "asio/detail/config.hpp"

#if !defined(ASIO_NO_IOSTREAM)

#include "asio/basic_streambuf.hpp"

namespace asio {

/// Typedef for the typical usage of basic_streambuf.
typedef basic_streambuf<> streambuf;

} // namespace asio

#endif // !defined(ASIO_NO_IOSTREAM)

#endif // ASIO_STREAMBUF_HPP


axapta.js

module.exports = function(hljs) {
  return {
    keywords: 'false int abstract private char interface boolean static null if for true ' +
      'while long throw finally protected extends final implements return void enum else ' +
      'break new catch byte super class case short default double public try this switch ' +
      'continue reverse firstfast firstonly forupdate nofetch sum avg minof maxof count ' +
      'order group by asc desc index hint like dispaly edit client server ttsbegin ' +
      'ttscommit str real date container anytype common div mod',
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.C_NUMBER_MODE,
      {
        className: 'preprocessor',
        begin: '#', end: '$'
      },
      {
        className: 'class',
        beginWithKeyword: true, end: '{',
        illegal: ':',
        keywords: 'class interface',
        contains: [
          {
            className: 'inheritance',
            beginWithKeyword: true,
            keywords: 'extends implements',
            relevance: 10
          },
          {
            className: 'title',
            begin: hljs.UNDERSCORE_IDENT_RE
          }
        ]
      }
    ]
  };
};


# -*- coding: utf-8 -*-
"""
unittests for table outputter
"""

# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals

# Import Salt Libs
import salt.output.table_out as table_out
import salt.utils.stringutils

# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase

class TableTestCase(TestCase, LoaderModuleMockMixin):
    """
    Test cases for salt.output.table_out
    """

    def setup_loader_modules(self):
        return {table_out: {}}

    # The test data should include unicode chars, and in Python 2 there should
    # be an example both of an encoded str type and an actual unicode type.
    # Since unicode_literals is imported, we will achieve the former using
    # salt.utils.stringutils.to_str and the latter by simply using a string
    # literal.
    data = [
        {
            "Food": salt.utils.stringutils.to_str("яйца, бекон, колбаса и спам"),
            "Price": 5.99,
        },
        {"Food": "спам, спам, спам, яйца и спам", "Price": 3.99},
    ]

    def test_output(self):
        ret = table_out.output(self.data)
        self.assertEqual(
            ret,
            (
                "    -----------------------------------------\n"
                "    |              Food             | Price |\n"
                "    -----------------------------------------\n"
                "    |  яйца, бекон, колбаса и спам  |  5.99 |\n"
                "    -----------------------------------------\n"
                "    | спам, спам, спам, яйца и спам |  3.99 |\n"
                "    -----------------------------------------"
            ),
        )