#'
#' The Elementwise class.
#'
#' This virtual class represents an elementwise atom.
#'
#' @name Elementwise-class
#' @aliases Elementwise
#' @rdname Elementwise-class
Elementwise <- setClass("Elementwise", contains = c("VIRTUAL", "Atom"))

#' @param object An \linkS4class{Elementwise} object.
#' @describeIn Elementwise Dimensions is the same as the sum of the arguments' dimensions.
setMethod("dim_from_args", "Elementwise", function(object) {
  sum_dims(lapply(object@args, dim))
})

#' @describeIn Elementwise Verify that all the dimensions are the same or can be promoted.
setMethod("validate_args", "Elementwise", function(object) {
  sum_dims(lapply(object@args, dim))
  callNextMethod()
})

#' @describeIn Elementwise Is the expression symmetric?
setMethod("is_symmetric", "Elementwise", function(object) {
  symm_args <- all(sapply(object@args, is_symmetric))
  return(nrow(object) == ncol(object) && symm_args)
})

#
# Gradient to Diagonal
#
# Converts elementwise gradient into a diagonal matrix.
#
# @param value A scalar value or matrix.
# @return A sparse matrix.
# @rdname Elementwise-elemwise_grad_to_diag
Elementwise.elemwise_grad_to_diag <- function(value, rows, cols) {
  value <- as.vector(value)
  sparseMatrix(i = 1:rows, j = 1:cols, x = value, dims = c(rows, cols))
}

#
# Promotes LinOp
#
# Promotes the LinOp if necessary.
# @param arg The LinOp to promote.
# @param dim The desired dimensions.
# @return The promoted LinOp.
# @rdname Elementwise-promote
Elementwise.promote <- function(arg, dim) {
  if(any(dim(arg) != dim))
    lo.promote(arg, dim)
  else
    arg
}

#'
#' The Abs class.
#'
#' This class represents the elementwise absolute value.
#'
#' @slot x An \linkS4class{Expression} object.
#' @name Abs-class
#' @aliases Abs
#' @rdname Abs-class
.Abs <- setClass("Abs", representation(x = "Expression"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} object.
#' @rdname Abs-class
Abs <- function(x) { .Abs(x = x) }

setMethod("initialize", "Abs", function(.Object, ..., x) {
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object An \linkS4class{Abs} object.
#' @param values A list of arguments to the atom.
#' @describeIn Abs The elementwise absolute value of the input.
setMethod("to_numeric", "Abs", function(object, values) { abs(values[[1]]) })

#' @describeIn Abs Does the atom handle complex numbers?
setMethod("allow_complex", "Abs", function(object) { TRUE })

#' @describeIn Abs The atom is positive.
setMethod("sign_from_args", "Abs", function(object) { c(TRUE, FALSE) })

#' @describeIn Abs The atom is convex.
setMethod("is_atom_convex", "Abs", function(object) { TRUE })

#' @describeIn Abs The atom is not concave.
setMethod("is_atom_concave", "Abs", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn Abs A logical value indicating whether the atom is weakly increasing.
setMethod("is_incr", "Abs", function(object, idx) { is_nonneg(object@args[[idx]]) })

#' @describeIn Abs A logical value indicating whether the atom is weakly decreasing.
setMethod("is_decr", "Abs", function(object, idx) { is_nonpos(object@args[[idx]]) })

#' @describeIn Abs Is \code{x} piecewise linear?
setMethod("is_pwl", "Abs", function(object) {
  is_pwl(object@args[[1]]) && (is_real(object@args[[1]]) || is_imag(object@args[[1]]))
})

setMethod(".grad", "Abs", function(object, values) {
  # Grad: +1 if positive, -1 if negative
  rows <- size(expr(object))
  cols <- size(object)
  D <- array(0, dim = dim(expr(object)))
  D <- D + (values[[1]] > 0)
  D <- D - (values[[1]] < 0)
  list(Elementwise.elemwise_grad_to_diag(D, rows, cols))
})

#'
#' The Entr class.
#'
#' This class represents the elementwise operation \eqn{-xlog(x)}.
#'
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @name Entr-class
#' @aliases Entr
#' @rdname Entr-class
.Entr <- setClass("Entr", representation(x = "ConstValORExpr"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} or numeric constant.
#' @rdname Entr-class
Entr <- function(x) { .Entr(x = x) }

setMethod("initialize", "Entr", function(.Object, ..., x) {
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object An \linkS4class{Entr} object.
#' @param values A list of arguments to the atom.
#' @describeIn Entr The elementwise entropy function evaluated at the value.
setMethod("to_numeric", "Entr", function(object, values) {
  xlogy <- function(x, y) {
    tmp <- x*log(y)
    tmp[x == 0] <- 0
    tmp
  }

  x <- values[[1]]
  results <- -xlogy(x, x)

  # Return -Inf outside the domain
  results[is.na(results)] <- -Inf
  if(all(dim(results) == 1))
    results <- as.vector(results)
  results
})

#' @describeIn Entr The sign of the atom is unknown.
setMethod("sign_from_args", "Entr", function(object) { c(FALSE, FALSE) })

#' @describeIn Entr The atom is not convex.
setMethod("is_atom_convex", "Entr", function(object) { FALSE })

#' @describeIn Entr The atom is concave.
setMethod("is_atom_concave", "Entr", function(object) { TRUE })

#' @param idx An index into the atom.
#' @describeIn Entr The atom is weakly increasing.
setMethod("is_incr", "Entr", function(object, idx) { FALSE })

#' @describeIn Entr The atom is weakly decreasing.
setMethod("is_decr", "Entr", function(object, idx) { FALSE })

#' @param values A list of numeric values for the arguments
#' @describeIn Entr Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Entr", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)

  # Outside domain or on boundary
  if(min(values[[1]]) <= 0)
    return(list(NA_real_))   # Non-differentiable
  else {
    grad_vals <- -log(values[[1]]) - 1
    return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)))
  }
})

#' @describeIn Entr Returns constraints descrbing the domain of the node
setMethod(".domain", "Entr", function(object) { list(object@args[[1]] >= 0) })

#'
#' The Exp class.
#'
#' This class represents the elementwise natural exponential \eqn{e^x}.
#'
#' @slot x An \linkS4class{Expression} object.
#' @name Exp-class
#' @aliases Exp
#' @rdname Exp-class
.Exp <- setClass("Exp", representation(x = "Expression"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} object.
#' @rdname Exp-class
Exp <- function(x) { .Exp(x = x) }

setMethod("initialize", "Exp", function(.Object, ..., x) {
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object An \linkS4class{Exp} object.
#' @param values A list of arguments to the atom.
#' @describeIn Exp The matrix with each element exponentiated.
setMethod("to_numeric", "Exp", function(object, values) { exp(values[[1]]) })

#' @describeIn Exp The atom is positive.
setMethod("sign_from_args", "Exp", function(object) { c(TRUE, FALSE) })

#' @describeIn Exp The atom is convex.
setMethod("is_atom_convex", "Exp", function(object) { TRUE })

#' @describeIn Exp The atom is not concave.
setMethod("is_atom_concave", "Exp", function(object) { FALSE })

#' @describeIn Exp Is the atom log-log convex?
setMethod("is_atom_log_log_convex", "Exp", function(object) { TRUE })

#' @describeIn Exp Is the atom log-log concave?
setMethod("is_atom_log_log_concave", "Exp", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn Exp The atom is weakly increasing.
setMethod("is_incr", "Exp", function(object, idx) { TRUE })

#' @describeIn Exp The atom is not weakly decreasing.
setMethod("is_decr", "Exp", function(object, idx) { FALSE })

#' @param values A list of numeric values for the arguments
#' @describeIn Exp Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Exp", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)
  grad_vals <- exp(values[[1]])
  list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))
})

#'
#' The Huber class.
#'
#' This class represents the elementwise Huber function, \eqn{Huber(x, M) = }
#' \itemize{
#'   \item{\eqn{2M|x|-M^2}}{for \eqn{|x| \geq |M|}}
#'    \item{\eqn{|x|^2}}{for \eqn{|x| \leq |M|.}}
#'  }
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @slot M A positive scalar value representing the threshold. Defaults to 1.
#' @name Huber-class
#' @aliases Huber
#' @rdname Huber-class
.Huber <- setClass("Huber", representation(x = "ConstValORExpr", M = "ConstValORExpr"),
                           prototype(M = 1), contains = "Elementwise")

#' @param x An \linkS4class{Expression} object.
#' @param M A positive scalar value representing the threshold. Defaults to 1.
#' @rdname Huber-class
Huber <- function(x, M = 1) { .Huber(x = x, M = M) }

setMethod("initialize", "Huber", function(.Object, ..., x, M = 1) {
  .Object@M <- as.Constant(M)
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object A \linkS4class{Huber} object.
#' @param values A list of arguments to the atom.
#' @describeIn Huber The Huber function evaluted elementwise on the input value.
setMethod("to_numeric", "Huber", function(object, values) {
  huber_loss <- function(delta, r) {
    if(delta < 0)
      return(Inf)
    else if(delta >= 0 && abs(r) <= delta)
      return(r^2/2)
    else
      return(delta * (abs(r) - delta/2))
  }

  M_val <- value(object@M)
  val <- values[[1]]
  if(is.null(dim(val)))
    result <- 2*huber_loss(M_val, val)
  else if(is.vector(val))
    result <- 2*sapply(val, function(v) { huber_loss(M_val, v) })
  else
    result <- 2*apply(val, 1:length(dim(val)), function(v) { huber_loss(M_val, v) })

  if(all(dim(result) == 1))
    result <- as.vector(result)
  return(result)
})

#' @describeIn Huber The atom is positive.
setMethod("sign_from_args", "Huber", function(object) { c(TRUE, FALSE) })

#' @describeIn Huber The atom is convex.
setMethod("is_atom_convex", "Huber", function(object) { TRUE })

#' @describeIn Huber The atom is not concave.
setMethod("is_atom_concave", "Huber", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn Huber A logical value indicating whether the atom is weakly increasing.
setMethod("is_incr", "Huber", function(object, idx) { is_nonneg(object@args[[idx]]) })

#' @describeIn Huber A logical value indicating whether the atom is weakly decreasing.
setMethod("is_decr", "Huber", function(object, idx) { is_nonpos(object@args[[idx]]) })

#' @describeIn Huber The atom is quadratic if \code{x} is affine.
setMethod("is_quadratic", "Huber", function(object) { is_affine(object@args[[1]]) })

#' @describeIn Huber A list containing the parameter \code{M}.
setMethod("get_data", "Huber", function(object) { list(object@M) })

#' @describeIn Huber Check that \code{M} is a non-negative constant.
setMethod("validate_args", "Huber", function(object) {
  if(!(is_nonneg(object@M) && is_constant(object@M) && is_scalar(object@M)))
    stop("M must be a non-negative scalar constant")
  callNextMethod()
})

#' @param values A list of numeric values for the arguments
#' @describeIn Huber Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Huber", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)

  val_abs <- abs(values[[1]])
  M_val <- as.numeric(value(object@M))
  min_val <- ifelse(val_abs >= M_val, M_val, val_abs)

  grad_vals <- 2*(sign(values[[1]]) * min_val)
  list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))
})

# x^{-1} for x > 0.
InvPos <- function(x) { Power(x, -1) }

#'
#' The KLDiv class.
#'
#' The elementwise KL-divergence \eqn{x\log(x/y) - x + y}.
#'
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @slot y An \linkS4class{Expression} or numeric constant.
#' @name KLDiv-class
#' @aliases KLDiv
#' @rdname KLDiv-class
.KLDiv <- setClass("KLDiv", representation(x = "ConstValORExpr", y = "ConstValORExpr"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} or numeric constant.
#' @param y An \linkS4class{Expression} or numeric constant.
#' @rdname KLDiv-class
KLDiv <- function(x, y) { .KLDiv(x = x, y = y) }

setMethod("initialize", "KLDiv", function(.Object, ..., x, y) {
  .Object@x <- x
  .Object@y <- y
  callNextMethod(.Object, ..., atom_args = list(.Object@x, .Object@y))
})

#' @param object A \linkS4class{KLDiv} object.
#' @param values A list of arguments to the atom.
#' @describeIn KLDiv The KL-divergence evaluted elementwise on the input value.
setMethod("to_numeric", "KLDiv", function(object, values) {
  x <- intf_convert_if_scalar(values[[1]])
  y <- intf_convert_if_scalar(values[[2]])

  # TODO: Return Inf outside domain
  xlogy <- function(x, y) {
    tmp <- x*log(y)
    tmp[x == 0] <- 0
    tmp
  }
  xlogy(x, x/y) - x + y
})

#' @describeIn KLDiv The atom is positive.
setMethod("sign_from_args", "KLDiv", function(object) { c(TRUE, FALSE) })

#' @describeIn KLDiv The atom is convex.
setMethod("is_atom_convex", "KLDiv", function(object) { TRUE })

#' @describeIn KLDiv The atom is not concave.
setMethod("is_atom_concave", "KLDiv", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn KLDiv The atom is not monotonic in any argument.
setMethod("is_incr", "KLDiv", function(object, idx) { FALSE })

#' @describeIn KLDiv The atom is not monotonic in any argument.
setMethod("is_decr", "KLDiv", function(object, idx) { FALSE })

#' @param values A list of numeric values for the arguments
#' @describeIn KLDiv Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "KLDiv", function(object, values) {
  if(min(values[[1]]) <= 0 || min(values[[2]]) <= 0)
    return(list(NA_real_, NA_real_))   # Non-differentiable
  else {
    div <- values[[1]]/values[[2]]
    grad_vals <- list(log(div), 1-div)
    grad_list <- list()
    for(idx in 1:length(values)) {
      rows <- size(object@args[[idx]])
      cols <- size(object)
      grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals[[idx]], rows, cols)))
    }
    return(grad_list)
  }
})

#' @describeIn KLDiv Returns constraints describng the domain of the node
setMethod(".domain", "KLDiv", function(object) { list(object@args[[1]] >= 0, object@args[[2]] >= 0) })

#'
#' The Log class.
#'
#' This class represents the elementwise natural logarithm \eqn{\log(x)}.
#'
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @name Log-class
#' @aliases Log
#' @rdname Log-class
.Log <- setClass("Log", representation(x = "ConstValORExpr"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} or numeric constant.
#' @rdname Log-class
Log <- function(x) { .Log(x = x) }

setMethod("initialize", "Log", function(.Object, ..., x) {
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object A \linkS4class{Log} object.
#' @param values A list of arguments to the atom.
#' @describeIn Log The elementwise natural logarithm of the input value.
setMethod("to_numeric", "Log", function(object, values) { log(values[[1]]) })

#' @describeIn Log The sign of the atom is unknown.
setMethod("sign_from_args", "Log", function(object) { c(FALSE, FALSE) })

#' @describeIn Log The atom is not convex.
setMethod("is_atom_convex", "Log", function(object) { FALSE })

#' @describeIn Log The atom is concave.
setMethod("is_atom_concave", "Log", function(object) { TRUE })

#' @describeIn Log Is the atom log-log convex?
setMethod("is_atom_log_log_convex", "Log", function(object) { FALSE })

#' @describeIn Log Is the atom log-log concave?
setMethod("is_atom_log_log_concave", "Log", function(object) { TRUE })

#' @param idx An index into the atom.
#' @describeIn Log The atom is weakly increasing.
setMethod("is_incr", "Log", function(object, idx) { TRUE })

#' @describeIn Log The atom is not weakly decreasing.
setMethod("is_decr", "Log", function(object, idx) { FALSE })

#' @param values A list of numeric values for the arguments
#' @describeIn Log Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Log", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)

  # Outside domain or on boundary
  if(min(values[[1]]) <= 0)
    return(list(NA_real_))   # Non-differentiable
  else {
    grad_vals <- 1.0/values[[1]]
    return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)))
  }
})

#' @describeIn Log Returns constraints describng the domain of the node
setMethod(".domain", "Log", function(object) { list(object@args[[1]] >= 0) })

#'
#' The Log1p class.
#'
#' This class represents the elementwise operation \eqn{\log(1 + x)}.
#'
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @name Log1p-class
#' @aliases Log1p
#' @rdname Log1p-class
.Log1p <- setClass("Log1p", contains = "Log")

#' @param x An \linkS4class{Expression} or numeric constant.
#' @rdname Log1p-class
Log1p <- function(x) { .Log1p(x = x) }

#' @param object A \linkS4class{Log1p} object.
#' @param values A list of arguments to the atom.
#' @describeIn Log1p The elementwise natural logarithm of one plus the input value.
setMethod("to_numeric", "Log1p", function(object, values) { log(1 + values[[1]]) })

#' @describeIn Log1p The sign of the atom.
setMethod("sign_from_args", "Log1p", function(object) { c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]])) })

#' @param values A list of numeric values for the arguments
#' @describeIn Log1p Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Log1p", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)

  # Outside domain or on boundary.
  if(min(values[[1]]) <= -1)
    return(list(NA_real_))   # Non-differentiable.
  else {
    grad_vals <- 1.0/(values[[1]] + 1)
    return(list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)))
  }
})

#' @describeIn Log1p Returns constraints describng the domain of the node
setMethod(".domain", "Log1p", function(object) { list(object@args[[1]] >= -1) })

#'
#' The Logistic class.
#'
#' This class represents the elementwise operation \eqn{\log(1 + e^x)}.
#' This is a special case of log(sum(exp)) that evaluates to a vector rather than to a scalar,
#' which is useful for logistic regression.
#'
#' @slot x An \linkS4class{Expression} or numeric constant.
#' @name Logistic-class
#' @aliases Logistic
#' @rdname Logistic-class
.Logistic <- setClass("Logistic", representation(x = "ConstValORExpr"), contains = "Elementwise")

#' @param x An \linkS4class{Expression} or numeric constant.
#' @rdname Logistic-class
Logistic <- function(x) { .Logistic(x = x) }

setMethod("initialize", "Logistic", function(.Object, ..., x) {
  .Object@x <- x
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object A \linkS4class{Logistic} object.
#' @param values A list of arguments to the atom.
#' @describeIn Logistic Evaluates \code{e^x} elementwise, adds one, and takes the natural logarithm.
setMethod("to_numeric", "Logistic", function(object, values) { log(1 + exp(values[[1]])) })

#' @describeIn Logistic The atom is positive.
setMethod("sign_from_args", "Logistic", function(object) { c(TRUE, FALSE) })

#' @describeIn Logistic The atom is convex.
setMethod("is_atom_convex", "Logistic", function(object) { TRUE })

#' @describeIn Logistic The atom is not concave.
setMethod("is_atom_concave", "Logistic", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn Logistic The atom is weakly increasing.
setMethod("is_incr", "Logistic", function(object, idx) { TRUE })

#' @describeIn Logistic The atom is not weakly decreasing.
setMethod("is_decr", "Logistic", function(object, idx) { FALSE })

#' @param values A list of numeric values for the arguments
#' @describeIn Logistic Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Logistic", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)
  exp_val <- exp(values[[1]])
  grad_vals <- exp_val/(1 + exp_val)
  list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))
})

#'
#' The MaxElemwise class.
#'
#' This class represents the elementwise maximum.
#'
#' @slot arg1 The first \linkS4class{Expression} in the maximum operation.
#' @slot arg2 The second \linkS4class{Expression} in the maximum operation.
#' @slot ... Additional \linkS4class{Expression} objects in the maximum operation.
#' @name MaxElemwise-class
#' @aliases MaxElemwise
#' @rdname MaxElemwise-class
.MaxElemwise <- setClass("MaxElemwise", validity = function(object) {
                           if(is.null(object@args) || length(object@args) < 2)
                             stop("[MaxElemwise: validation] args must have at least 2 arguments")
                           return(TRUE)
                         }, contains = "Elementwise")

#' @param arg1 The first \linkS4class{Expression} in the maximum operation.
#' @param arg2 The second \linkS4class{Expression} in the maximum operation.
#' @param ... Additional \linkS4class{Expression} objects in the maximum operation.
#' @rdname MaxElemwise-class
MaxElemwise <- function(arg1, arg2, ...) { .MaxElemwise(atom_args = list(arg1, arg2, ...)) }

#' @param object A \linkS4class{MaxElemwise} object.
#' @param values A list of arguments to the atom.
#' @describeIn MaxElemwise The elementwise maximum.
setMethod("to_numeric", "MaxElemwise", function(object, values) {
  # Reduce(function(x, y) { ifelse(x >= y, x, y) }, values)
  Reduce("pmax", values)
})

#' @describeIn MaxElemwise The sign of the atom.
setMethod("sign_from_args", "MaxElemwise", function(object) {
  # Reduces the list of argument signs according to the following rules:
  #    NONNEGATIVE, ANYTHING = NONNEGATIVE
  #    ZERO, UNKNOWN = NONNEGATIVE
  #    ZERO, ZERO = ZERO
  #    ZERO, NONPOSITIVE = ZERO
  #    UNKNOWN, NONPOSITIVE = UNKNOWN
  #    NONPOSITIVE, NONPOSITIVE = NONPOSITIVE
  is_pos <- any(sapply(object@args, is_nonneg))
  is_neg <- all(sapply(object@args, is_nonpos))
  c(is_pos, is_neg)
})

#' @describeIn MaxElemwise The atom is convex.
setMethod("is_atom_convex", "MaxElemwise", function(object) { TRUE })

#' @describeIn MaxElemwise The atom is not concave.
setMethod("is_atom_concave", "MaxElemwise", function(object) { FALSE })

#' @describeIn MaxElemwise Is the atom log-log convex?
setMethod("is_atom_log_log_convex", "MaxElemwise", function(object) { TRUE })

#' @describeIn MaxElemwise Is the atom log-log concave?
setMethod("is_atom_log_log_concave", "MaxElemwise", function(object) { FALSE })

#' @param idx An index into the atom.
#' @describeIn MaxElemwise The atom is weakly increasing.
setMethod("is_incr", "MaxElemwise", function(object, idx) { TRUE })

#' @describeIn MaxElemwise The atom is not weakly decreasing.
setMethod("is_decr", "MaxElemwise", function(object, idx) { FALSE })

#' @describeIn MaxElemwise Are all the arguments piecewise linear?
setMethod("is_pwl", "MaxElemwise", function(object) { all(sapply(object@args, is_pwl)) })

#' @param values A list of numeric values for the arguments
#' @describeIn MaxElemwise Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "MaxElemwise", function(object, values) {
  max_vals <- to_numeric(object, values)
  vals_dim <- dim(max_vals)
  if(is.null(vals_dim))
    unused <- matrix(TRUE, nrow = length(max_vals), ncol = 1)
  else
    unused <- array(TRUE, dim = vals_dim)
  grad_list <- list()
  idx <- 1
  for(value in values) {
    rows <- size(object@args[[idx]])
    cols <- size(object)
    grad_vals <- (value == max_vals) & unused

    # Remove all the max_vals that were used
    unused[value == max_vals] <- FALSE
    grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)))
    idx <- idx + 1
  }
  grad_list
})

#'
#' The MinElemwise class.
#'
#' This class represents the elementwise minimum.
#'
#' @slot arg1 The first \linkS4class{Expression} in the minimum operation.
#' @slot arg2 The second \linkS4class{Expression} in the minimum operation.
#' @slot ... Additional \linkS4class{Expression} objects in the minimum operation.
#' @name MinElemwise-class
#' @aliases MinElemwise
#' @rdname MinElemwise-class
.MinElemwise <- setClass("MinElemwise", validity = function(object) {
                  if(is.null(object@args) || length(object@args) < 2)
                    stop("[MinElemwise: validation] args must have at least 2 arguments")
                  return(TRUE)
                }, contains = "Elementwise")

#' @param arg1 The first \linkS4class{Expression} in the minimum operation.
#' @param arg2 The second \linkS4class{Expression} in the minimum operation.
#' @param ... Additional \linkS4class{Expression} objects in the minimum operation.
#' @rdname MinElemwise-class
MinElemwise <- function(arg1, arg2, ...) { .MinElemwise(atom_args = list(arg1, arg2, ...)) }

#' @param object A \linkS4class{MinElemwise} object.
#' @param values A list of arguments to the atom.
#' @describeIn MinElemwise The elementwise minimum.
setMethod("to_numeric", "MinElemwise", function(object, values) {
  # Reduce(function(x, y) { ifelse(x <= y, x, y) }, values)
  Reduce("pmin", values)
})

#' @describeIn MinElemwise The sign of the atom.
setMethod("sign_from_args", "MinElemwise", function(object) {
  is_pos <- all(sapply(object@args, is_nonneg))
  is_neg <- any(sapply(object@args, is_nonpos))
  c(is_pos, is_neg)
})

#' @describeIn MinElemwise The atom is not convex.
setMethod("is_atom_convex", "MinElemwise", function(object) { FALSE })

#' @describeIn MinElemwise The atom is not concave.
setMethod("is_atom_concave", "MinElemwise", function(object) { TRUE })

#' @describeIn MinElemwise Is the atom log-log convex?
setMethod("is_atom_log_log_convex", "MinElemwise", function(object) { FALSE })

#' @describeIn MinElemwise Is the atom log-log concave?
setMethod("is_atom_log_log_concave", "MinElemwise", function(object) { TRUE })

#' @param idx An index into the atom.
#' @describeIn MinElemwise The atom is weakly increasing.
setMethod("is_incr", "MinElemwise", function(object, idx) { TRUE })

#' @describeIn MinElemwise The atom is not weakly decreasing.
setMethod("is_decr", "MinElemwise", function(object, idx) { FALSE })

#' @describeIn MinElemwise Are all the arguments piecewise linear?
setMethod("is_pwl", "MinElemwise", function(object) { all(sapply(object@args, is_pwl)) })

#' @param values A list of numeric values for the arguments
#' @describeIn MinElemwise Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "MinElemwise", function(object, values) {
  min_vals <- to_numeric(object, values)
  vals_dim <- dim(min_vals)
  if(is.null(vals_dim))
    unused <- matrix(TRUE, nrow = length(min_vals), ncol = 1)
  else
    unused <- array(TRUE, dim = vals_dim)
  grad_list <- list()
  idx <- 1
  for(value in values) {
    rows <- size(object@args[[idx]])
    cols <- size(object)
    grad_vals <- (value == min_vals) & unused

    # Remove all the min_vals that were used
    unused[value == min_vals] <- FALSE
    grad_list <- c(grad_list, list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols)))
    idx <- idx + 1
  }
  grad_list
})
#'
#' An alias for -MinElemwise(x, 0)
#'
#' @param x An R numeric value or \linkS4class{Expression}.
#' @return An alias for -MinElemwise(x, 0)
#' @rdname Neg-int
Neg <- function(x) { -MinElemwise(x, 0) }
#'
#' An alias for MaxElemwise(x, 0)
#'
#' @param x An R numeric value or \linkS4class{Expression}.
#' @return An alias for MaxElemwise(x, 0)
#' @rdname Pos-int
Pos <- function(x) { MaxElemwise(x, 0) }

#'
#' The Power class.
#'
#' This class represents the elementwise power function \eqn{f(x) = x^p}.
#' If \code{expr} is a CVXR expression, then \code{expr^p} is equivalent to \code{Power(expr, p)}.
#'
#' \describe{
#' \item{For \eqn{p = 0}}{\eqn{f(x) = 1}, constant, positive}
#' \item{For \eqn{p = 1}}{\eqn{f(x) = x}, affine, increasing, same sign as \eqn{x}}
#' \item{For \eqn{p = 2,4,8,...}}{\eqn{f(x) = |x|^p}, convex, signed monotonicity, positive}
#' \item{For \eqn{p < 0}}{\eqn{f(x) = \begin{cases} x^p & \text{for $x > 0$} \\ +\infty & \text{ for $x \leq 0$} \end{cases}}, this function is convex, decreasing, and positive}
#' \item{For \eqn{0 < p < 1}}{\eqn{f(x) = \begin{cases} x^p & \text{for $x \geq 0$} \\ -\infty & \text{ for $x < 0$} \end{cases}}, this function is concave, increasing, and positive}
#' \item{For \eqn{p > 1, p \neq 2,4,8,\ldots}}{\eqn{f(x) = \begin{cases} x^p & \text{for $x \geq 0$} \\ +\infty & \text{for $x < 0$} \end{cases}}, this function is convex, increasing, and positive.}
#' }
#'
#' @slot x The \linkS4class{Expression} to be raised to a power.
#' @slot p A numeric value indicating the scalar power.
#' @slot max_denom The maximum denominator considered in forming a rational approximation of \code{p}.
#' @name Power-class
#' @aliases Power
#' @rdname Power-class
.Power <- setClass("Power", representation(x = "ConstValORExpr", p = "NumORgmp", max_denom = "numeric", w = "NumORgmp", approx_error = "numeric"),
                          prototype(max_denom = 1024, w = NA_real_, approx_error = NA_real_), contains = "Elementwise")

#' @param x The \linkS4class{Expression} to be raised to a power.
#' @param p A numeric value indicating the scalar power.
#' @param max_denom The maximum denominator considered in forming a rational approximation of \code{p}.
#' @rdname Power-class
Power <- function(x, p, max_denom = 1024) { .Power(x = x, p = p, max_denom = max_denom) }

setMethod("initialize", "Power", function(.Object, ..., x, p, max_denom = 1024, w = NA_real_, approx_error = NA_real_) {
  p_old <- p

  # How we convert p to a rational depends on the branch of the function
  if(p > 1) {
    pw <- pow_high(p)
    p <- pw[[1]]
    w <- pw[[2]]
  } else if(p > 0 && p < 1) {
    pw <- pow_mid(p)
    p <- pw[[1]]
    w <- pw[[2]]
  } else if(p < 0) {
    pw <- pow_neg(p)
    p <- pw[[1]]
    w <- pw[[2]]
  }

  if(p == 1) {
    # In case p is a fraction equivalent to 1
    p <- 1
    w <- NA_real_
  } else if(p == 0) {
    p <- 0
    w <- NA_real_
  }

  .Object@p <- p
  .Object@w <- w
  .Object@approx_error <- as.double(abs(.Object@p - p_old))

  .Object@x <- x
  .Object@max_denom <- max_denom
  callNextMethod(.Object, ..., atom_args = list(.Object@x))
})

#' @param object A \linkS4class{Power} object.
#' @param values A list of arguments to the atom.
#' @describeIn Power Throw an error if the power is negative and cannot be handled.
setMethod("to_numeric", "Power", function(object, values) {
  # Throw error if negative and Power doesn't handle that
  if(object@p < 0 && min(values[[1]]) <= 0)
    stop("Power cannot be applied to negative or zero values")
  else if(!is_power2(object@p) && object@p != 0 && min(values[[1]]) < 0)
    stop("Power cannot be applied to negative values")
  else
    return(values[[1]]^(as.double(object@p)))
})

#' @describeIn Power The sign of the atom.
setMethod("sign_from_args", "Power", function(object) {
  if(object@p == 1)   # Same as input
    c(is_nonneg(object@args[[1]]), is_nonpos(object@args[[1]]))
  else   # Always positive
    c(TRUE, FALSE)
})

#' @describeIn Power Is \eqn{p \leq 0} or \eqn{p \geq 1}?
setMethod("is_atom_convex", "Power", function(object) {
  # p == 0 is affine here.
  object@p <= 0 || object@p >= 1
})

#' @describeIn Power Is \eqn{p \geq 0} or \eqn{p \leq 1}?
setMethod("is_atom_concave", "Power", function(object) {
  # p == 0 is affine here.
  object@p >= 0 && object@p <= 1
})

#' @describeIn Power Is the atom log-log convex?
setMethod("is_atom_log_log_convex", "Power", function(object) { TRUE })

#' @describeIn Power Is the atom log-log concave?
setMethod("is_atom_log_log_concave", "Power", function(object) { TRUE })

#' @describeIn Power A logical value indicating whether the atom is constant.
setMethod("is_constant", "Power", function(object) { object@p == 0 || callNextMethod() })

#' @param idx An index into the atom.
#' @describeIn Power A logical value indicating whether the atom is weakly increasing.
setMethod("is_incr", "Power", function(object, idx) {
  if(object@p >= 0 && object@p <= 1)
    return(TRUE)
  else if(object@p > 1) {
    if(is_power2(object@p))
      return(is_nonneg(object@args[[idx]]))
    else
      return(TRUE)
  } else
    return(FALSE)
})

#' @describeIn Power A logical value indicating whether the atom is weakly decreasing.
setMethod("is_decr", "Power", function(object, idx) {
  if(object@p <= 0)
    return(TRUE)
  else if(object@p > 1) {
    if(is_power2(object@p))
      return(is_nonpos(object@args[[idx]]))
    else
      return(FALSE)
  } else
    return(FALSE)
})

#' @describeIn Power A logical value indicating whether the atom is quadratic.
setMethod("is_quadratic", "Power", function(object) {
  if(object@p == 0)
    return(TRUE)
  else if(object@p == 1)
    return(is_quadratic(object@args[[1]]))
  else if(object@p == 2)
    return(is_affine(object@args[[1]]))
  else
    return(is_constant(object@args[[1]]))
})

#' @describeIn Power A logical value indicating whether the atom is quadratic of piecewise affine.
setMethod("is_qpwa", "Power", function(object) {
  if(object@p == 0)
    return(TRUE)
  else if(object@p == 1)
    return(is_qpwa(object@args[[1]]))
  else if(object@p == 2)
    return(is_pwl(object@args[[1]]))
  else
    return(is_constant(object@args[[1]]))
})

#' @param values A list of numeric values for the arguments
#' @describeIn Power Gives the (sub/super)gradient of the atom w.r.t. each variable
setMethod(".grad", "Power", function(object, values) {
  rows <- size(object@args[[1]])
  cols <- size(object)

  if(object@p == 0) # All zeros
    return(list(sparseMatrix(i = c(), j = c(), dims = c(rows, cols))))

  # Outside domain or on boundary
  if(!is_power2(object@p) && min(values[[1]]) <= 0) {
    if(object@p < 1)
      return(list(NA_real_))  # Non-differentiable
    else   # Round up to zero
      values[[1]] <- ifelse(values[[1]] >= 0, values[[1]], 0)
  }

  grad_vals <- as.double(object@p) * (values[[1]]^(as.double(object@p) - 1))
  list(Elementwise.elemwise_grad_to_diag(grad_vals, rows, cols))
})

#' @describeIn Power Returns constraints describng the domain of the node
setMethod(".domain", "Power", function(object) {
  if((object@p < 1 && object@p != 0) || (object@p > 1 && !is_power2(object@p)))
    list(object@args[[1]] >= 0)
  else
    list()
})

#' @describeIn Power A list containing the output of \code{pow_low, pow_mid}, or \code{pow_high} depending on the input power.
setMethod("get_data", "Power", function(object) { list(object@p, object@w) })

#' @param args A list of arguments to reconstruct the atom. If args=NULL, use the current args of the atom
#' @param id_objects Currently unused.
#' @describeIn Power Returns a shallow  copy of the power atom
setMethod("copy", "Power", function(object, args = NULL, id_objects = list()) {
  if(is.null(args))
    args <- object@args
  data <- get_data(object)
  copy <- do.call(class(object), args)
  copy@p <- data[[1]]
  copy@w <- data[[2]]
  copy@approx_error <- object@approx_error
  copy
})

#' @describeIn Power Returns the expression in string form.
setMethod("name", "Power", function(x) {
  paste(class(x), "(", name(x@args[[1]]), ", ", x@p, ")", sep = "")
})

Scalene <- function(x, alpha, beta) { alpha*Pos(x) + beta*Neg(x) }

{'repo_name': 'cvxgrp/CVXR', 'stars': '118', 'repo_language': 'R', 'file_name': 'dot-ProblemData__get_const_vec.Rd', 'mime_type': 'text/plain', 'hash': -5560918287112159547, 'source_dataset': 'data'}


/*
 * linux/drivers/net/ethernet/amd/am79c961a.h
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#ifndef _LINUX_am79c961a_H
#define _LINUX_am79c961a_H

/* use 0 for production, 1 for verification, >2 for debug. debug flags: */
#define DEBUG_TX	 2
#define DEBUG_RX	 4
#define DEBUG_INT	 8
#define DEBUG_IC	16
#ifndef NET_DEBUG
#define NET_DEBUG 	0
#endif

#define NET_UID		0
#define NET_RDP		0x10
#define NET_RAP		0x12
#define NET_RESET	0x14
#define NET_IDP		0x16

/*
 * RAP registers
 */
#define CSR0		0
#define CSR0_INIT	0x0001
#define CSR0_STRT	0x0002
#define CSR0_STOP	0x0004
#define CSR0_TDMD	0x0008
#define CSR0_TXON	0x0010
#define CSR0_RXON	0x0020
#define CSR0_IENA	0x0040
#define CSR0_INTR	0x0080
#define CSR0_IDON	0x0100
#define CSR0_TINT	0x0200
#define CSR0_RINT	0x0400
#define CSR0_MERR	0x0800
#define CSR0_MISS	0x1000
#define CSR0_CERR	0x2000
#define CSR0_BABL	0x4000
#define CSR0_ERR	0x8000

#define CSR3		3
#define CSR3_EMBA	0x0008
#define CSR3_DXMT2PD	0x0010
#define CSR3_LAPPEN	0x0020
#define CSR3_DXSUFLO	0x0040
#define CSR3_IDONM	0x0100
#define CSR3_TINTM	0x0200
#define CSR3_RINTM	0x0400
#define CSR3_MERRM	0x0800
#define CSR3_MISSM	0x1000
#define CSR3_BABLM	0x4000
#define CSR3_MASKALL	0x5F00

#define CSR4		4
#define CSR4_JABM	0x0001
#define CSR4_JAB	0x0002
#define CSR4_TXSTRTM	0x0004
#define CSR4_TXSTRT	0x0008
#define CSR4_RCVCCOM	0x0010
#define CSR4_RCVCCO	0x0020
#define CSR4_MFCOM	0x0100
#define CSR4_MFCO	0x0200
#define CSR4_ASTRP_RCV	0x0400
#define CSR4_APAD_XMIT	0x0800

#define CTRL1		5
#define CTRL1_SPND	0x0001

#define LADRL		8
#define LADRM1		9
#define LADRM2		10
#define LADRH		11
#define PADRL		12
#define PADRM		13
#define PADRH		14

#define MODE		15
#define MODE_DISRX	0x0001
#define MODE_DISTX	0x0002
#define MODE_LOOP	0x0004
#define MODE_DTCRC	0x0008
#define MODE_COLL	0x0010
#define MODE_DRETRY	0x0020
#define MODE_INTLOOP	0x0040
#define MODE_PORT_AUI	0x0000
#define MODE_PORT_10BT	0x0080
#define MODE_DRXPA	0x2000
#define MODE_DRXBA	0x4000
#define MODE_PROMISC	0x8000

#define BASERXL		24
#define BASERXH		25
#define BASETXL		30
#define BASETXH		31

#define POLLINT		47

#define SIZERXR		76
#define SIZETXR		78

#define CSR_MFC		112

#define RMD_ENP		0x0100
#define RMD_STP		0x0200
#define RMD_CRC		0x0800
#define RMD_FRAM	0x2000
#define RMD_ERR		0x4000
#define RMD_OWN		0x8000

#define TMD_ENP		0x0100
#define TMD_STP		0x0200
#define TMD_MORE	0x1000
#define TMD_ERR		0x4000
#define TMD_OWN		0x8000

#define TST_RTRY	0x0400
#define TST_LCAR	0x0800
#define TST_LCOL	0x1000
#define TST_UFLO	0x4000
#define TST_BUFF	0x8000

#define ISALED0		0x0004
#define ISALED0_LNKST	0x8000

struct dev_priv {
    unsigned long	rxbuffer[RX_BUFFERS];
    unsigned long	txbuffer[TX_BUFFERS];
    unsigned char	txhead;
    unsigned char	txtail;
    unsigned char	rxhead;
    unsigned char	rxtail;
    unsigned long	rxhdr;
    unsigned long	txhdr;
    spinlock_t		chip_lock;
    struct timer_list	timer;
};

#endif

{'repo_name': 'OLIMEX/DIY-LAPTOP', 'stars': '358', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': -7783258225177625364, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "psputil.hxx"

#include <unx/printerjob.hxx>
#include <unx/printergfx.hxx>
#include <ppdparser.hxx>
#include <strhelper.hxx>
#include <printerinfomanager.hxx>

#include <rtl/ustring.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>

#include <osl/thread.h>
#include <osl/security.hxx>

#include <algorithm>
#include <cstddef>
#include <deque>
#include <vector>

using namespace psp;

#define nBLOCKSIZE 0x2000

namespace psp
{

static bool
AppendPS (FILE* pDst, osl::File* pSrc, unsigned char* pBuffer)
{
    assert(pBuffer);
    if ((pDst == nullptr) || (pSrc == nullptr))
        return false;

    if (pSrc->setPos(osl_Pos_Absolut, 0) != osl::FileBase::E_None)
        return false;

    sal_uInt64 nIn = 0;
    sal_uInt64 nOut = 0;
    do
    {
        pSrc->read  (pBuffer, nBLOCKSIZE, nIn);
        if (nIn > 0)
            nOut = fwrite (pBuffer, 1, sal::static_int_cast<sal_uInt32>(nIn), pDst);
    }
    while ((nIn > 0) && (nIn == nOut));

    return true;
}

} // namespace psp

/*
 * private convenience routines for file handling
 */

std::unique_ptr<osl::File>
PrinterJob::CreateSpoolFile (const OUString& rName, const OUString& rExtension)
{
    OUString aFile = rName + rExtension;
    OUString aFileURL;
    osl::File::RC nError = osl::File::getFileURLFromSystemPath( aFile, aFileURL );
    if (nError != osl::File::E_None)
        return nullptr;
    aFileURL = maSpoolDirName + "/" + aFileURL;

    std::unique_ptr<osl::File> pFile( new osl::File (aFileURL) );
    nError = pFile->open (osl_File_OpenFlag_Read | osl_File_OpenFlag_Write | osl_File_OpenFlag_Create);
    if (nError != osl::File::E_None)
    {
        return nullptr;
    }

    osl::File::setAttributes (aFileURL,
                          osl_File_Attribute_OwnWrite | osl_File_Attribute_OwnRead);
    return pFile;
}

/*
 * public methods of PrinterJob: for use in PrinterGfx
 */

void
PrinterJob::GetScale (double &rXScale, double &rYScale) const
{
    rXScale = mfXScale;
    rYScale = mfYScale;
}

sal_uInt16
PrinterJob::GetDepth () const
{
    sal_Int32 nLevel = GetPostscriptLevel();
    bool  bColor = IsColorPrinter ();

    return nLevel > 1 && bColor ? 24 : 8;
}

sal_uInt16
PrinterJob::GetPostscriptLevel (const JobData *pJobData) const
{
    sal_uInt16 nPSLevel = 2;

    if( pJobData == nullptr )
        pJobData = &m_aLastJobData;

    if( pJobData->m_nPSLevel )
        nPSLevel = pJobData->m_nPSLevel;
    else
        if( pJobData->m_pParser )
            nPSLevel = pJobData->m_pParser->getLanguageLevel();

    return nPSLevel;
}

bool
PrinterJob::IsColorPrinter () const
{
    bool bColor = false;

    if( m_aLastJobData.m_nColorDevice )
        bColor = m_aLastJobData.m_nColorDevice != -1;
    else if( m_aLastJobData.m_pParser )
        bColor = m_aLastJobData.m_pParser->isColorDevice();

    return bColor;
}

osl::File*
PrinterJob::GetCurrentPageBody ()
{
    return maPageVector.back().get();
}

/*
 * public methods of PrinterJob: the actual job / spool handling
 */
PrinterJob::PrinterJob()
    : mnFileMode(0)
    , m_pGraphics(nullptr)
    , mnResolution(96)
    , mnWidthPt(0)
    , mnHeightPt(0)
    , mnMaxWidthPt(0)
    , mnMaxHeightPt(0)
    , mnLandscapes(0)
    , mnPortraits(0)
    , mnLMarginPt(0)
    , mnRMarginPt(0)
    , mnTMarginPt(0)
    , mnBMarginPt(0)
    , mfXScale(1)
    , mfYScale(1)
    , m_bQuickJob(false)
{
}

/* remove all our temporary files, uses external program "rm", since
   osl functionality is inadequate */
static void
removeSpoolDir (const OUString& rSpoolDir)
{
    OUString aSysPath;
    if( osl::File::E_None != osl::File::getSystemPathFromFileURL( rSpoolDir, aSysPath ) )
    {
        // Conversion did not work, as this is quite a dangerous action,
        // we should abort here...
        OSL_FAIL( "psprint: couldn't remove spool directory" );
        return;
    }
    OString aSysPathByte =
        OUStringToOString (aSysPath, osl_getThreadTextEncoding());
    if (system (OString("rm -rf " + aSysPathByte).getStr()) == -1)
        OSL_FAIL( "psprint: couldn't remove spool directory" );
}

/* creates a spool directory with a "pidgin random" value based on
   current system time */
static OUString
createSpoolDir ()
{
    TimeValue aCur;
    osl_getSystemTime( &aCur );
    sal_Int32 nRand = aCur.Seconds ^ (aCur.Nanosec/1000);

    OUString aTmpDir;
    osl_getTempDirURL( &aTmpDir.pData );

    do
    {
        OUString aDir = aTmpDir + "/psp" + OUString::number(nRand);
        if( osl::Directory::create( aDir ) == osl::FileBase::E_None )
        {
            osl::File::setAttributes( aDir,
                                        osl_File_Attribute_OwnWrite
                                      | osl_File_Attribute_OwnRead
                                      | osl_File_Attribute_OwnExe );
            return aDir;
        }
        nRand++;
    } while( nRand );
    return OUString();
}

PrinterJob::~PrinterJob ()
{
    maPageVector.clear();
    maHeaderVector.clear();

    // mpJobHeader->remove();
    mpJobHeader.reset();
    // mpJobTrailer->remove();
    mpJobTrailer.reset();

    // XXX should really call osl::remove routines
    if( !maSpoolDirName.isEmpty() )
        removeSpoolDir (maSpoolDirName);

    // osl::Directory::remove (maSpoolDirName);
}

static void WriteLocalTimePS( osl::File *rFile )
{
    TimeValue aStartTime, tLocal;
    oslDateTime date_time;
    if (osl_getSystemTime( &aStartTime ) &&
        osl_getLocalTimeFromSystemTime( &aStartTime, &tLocal ) &&
        osl_getDateTimeFromTimeValue( &tLocal, &date_time ))
    {
        char ar[ 256 ];
        snprintf(
            ar, sizeof (ar),
            "%04d-%02d-%02d %02d:%02d:%02d ",
            date_time.Year, date_time.Month, date_time.Day,
            date_time.Hours, date_time.Minutes, date_time.Seconds );
        WritePS( rFile, ar );
    }
    else
        WritePS( rFile, "Unknown-Time" );
}

static bool isAscii( const OUString& rStr )
{
    sal_Int32 nLen = rStr.getLength();
    for( sal_Int32 i = 0; i < nLen; i++ )
        if( rStr[i] > 127 )
            return false;
    return true;
}

bool
PrinterJob::StartJob (
                      const OUString& rFileName,
                      int nMode,
                      const OUString& rJobName,
                      const OUString& rAppName,
                      const JobData& rSetupData,
                      PrinterGfx* pGraphics,
                      bool bIsQuickJob
                      )
{
    m_bQuickJob = bIsQuickJob;
    mnMaxWidthPt = mnMaxHeightPt = 0;
    mnLandscapes = mnPortraits = 0;
    m_pGraphics = pGraphics;
    InitPaperSize (rSetupData);

    // create file container for document header and trailer
    maFileName = rFileName;
    mnFileMode = nMode;
    maSpoolDirName = createSpoolDir ();
    maJobTitle = rJobName;

    OUString aExt(".ps");
    mpJobHeader  = CreateSpoolFile ("psp_head", aExt);
    mpJobTrailer = CreateSpoolFile ("psp_tail", aExt);
    if( ! (mpJobHeader && mpJobTrailer) ) // existing files are removed in destructor
        return false;

    // write document header according to Document Structuring Conventions (DSC)
    WritePS (mpJobHeader.get(),
             "%!PS-Adobe-3.0\n"
             "%%BoundingBox: (atend)\n" );

    // Creator (this application)
    OUString aFilterWS = WhitespaceToSpace( rAppName, false );
    WritePS (mpJobHeader.get(), "%%Creator: (");
    WritePS (mpJobHeader.get(), aFilterWS);
    WritePS (mpJobHeader.get(), ")\n");

    // For (user name)
    osl::Security aSecurity;
    OUString aUserName;
    if( aSecurity.getUserName( aUserName ) )
    {
        WritePS (mpJobHeader.get(), "%%For: (");
        WritePS (mpJobHeader.get(), aUserName);
        WritePS (mpJobHeader.get(), ")\n");
    }

    // Creation Date (locale independent local time)
    WritePS (mpJobHeader.get(), "%%CreationDate: (");
    WriteLocalTimePS (mpJobHeader.get());
    WritePS (mpJobHeader.get(), ")\n");

    // Document Title
    /* #i74335#
    * The title should be clean ascii; rJobName however may
    * contain any Unicode character. So implement the following
    * algorithm:
    * use rJobName, if it contains only ascii
    * use the filename, if it contains only ascii
    * else omit %%Title
    */
    aFilterWS = WhitespaceToSpace( rJobName, false );
    OUString aTitle( aFilterWS );
    if( ! isAscii( aTitle ) )
    {
        aTitle = WhitespaceToSpace( rFileName.copy(rFileName.lastIndexOf('/')+1), false );
        if( ! isAscii( aTitle ) )
            aTitle.clear();
    }

    maJobTitle = aFilterWS;
    if( !aTitle.isEmpty() )
    {
        WritePS (mpJobHeader.get(), "%%Title: (");
        WritePS (mpJobHeader.get(), aTitle);
        WritePS (mpJobHeader.get(), ")\n");
    }

    // Language Level
    OStringBuffer pLevel;
    getValueOf(GetPostscriptLevel(&rSetupData), pLevel);
    pLevel.append('\n');
    WritePS (mpJobHeader.get(), "%%LanguageLevel: ");
    WritePS (mpJobHeader.get(), pLevel.makeStringAndClear());

    // Other
    WritePS (mpJobHeader.get(), "%%DocumentData: Clean7Bit\n");
    WritePS (mpJobHeader.get(), "%%Pages: (atend)\n");
    WritePS (mpJobHeader.get(), "%%Orientation: (atend)\n");
    WritePS (mpJobHeader.get(), "%%PageOrder: Ascend\n");
    WritePS (mpJobHeader.get(), "%%EndComments\n");

    // write Prolog
    writeProlog (mpJobHeader.get(), rSetupData);

    // mark last job setup as not set
    m_aLastJobData.m_pParser = nullptr;
    m_aLastJobData.m_aContext.setParser( nullptr );

    return true;
}

bool
PrinterJob::EndJob()
{
    // no pages ? that really means no print job
    if( maPageVector.empty() )
        return false;

    // write document setup (done here because it
    // includes the accumulated fonts
    if( mpJobHeader )
        writeSetup( mpJobHeader.get(), m_aDocumentJobData );
    m_pGraphics->OnEndJob();
    if( ! (mpJobHeader && mpJobTrailer) )
        return false;

    // write document trailer according to Document Structuring Conventions (DSC)
    OStringBuffer aTrailer(512);
    aTrailer.append( "%%Trailer\n" );
    aTrailer.append( "%%BoundingBox: 0 0 " );
    aTrailer.append( static_cast<sal_Int32>(mnMaxWidthPt) );
    aTrailer.append( " " );
    aTrailer.append( static_cast<sal_Int32>(mnMaxHeightPt) );
    if( mnLandscapes > mnPortraits )
        aTrailer.append("\n%%Orientation: Landscape");
    else
        aTrailer.append("\n%%Orientation: Portrait");
    aTrailer.append( "\n%%Pages: " );
    aTrailer.append( static_cast<sal_Int32>(maPageVector.size()) );
    aTrailer.append( "\n%%EOF\n" );
    WritePS (mpJobTrailer.get(), aTrailer.getStr());

    /*
     * spool the set of files to their final destination, this is U**X dependent
     */

    FILE* pDestFILE = nullptr;

    /* create a destination either as file or as a pipe */
    bool bSpoolToFile = !maFileName.isEmpty();
    if (bSpoolToFile)
    {
        const OString aFileName = OUStringToOString (maFileName,
                                                               osl_getThreadTextEncoding());
        if( mnFileMode )
        {
            int nFile = open( aFileName.getStr(), O_CREAT | O_EXCL | O_RDWR, mnFileMode );
            if( nFile != -1 )
            {
                pDestFILE = fdopen( nFile, "w" );
                if( pDestFILE == nullptr )
                {
                    close( nFile );
                    unlink( aFileName.getStr() );
                    return false;
                }
            }
            else
            {
                (void)chmod( aFileName.getStr(), mnFileMode );
            }
        }
        if (pDestFILE == nullptr)
            pDestFILE = fopen (aFileName.getStr(), "w");

        if (pDestFILE == nullptr)
            return false;
    }
    else
    {
        PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get ();
        pDestFILE = rPrinterInfoManager.startSpool( m_aLastJobData.m_aPrinterName, m_bQuickJob );
        if (pDestFILE == nullptr)
            return false;
    }

    /* spool the document parts to the destination */

    unsigned char pBuffer[ nBLOCKSIZE ];

    AppendPS (pDestFILE, mpJobHeader.get(), pBuffer);
    mpJobHeader->close();

    bool bSuccess = true;
    std::vector< std::unique_ptr<osl::File> >::iterator pPageBody;
    std::vector< std::unique_ptr<osl::File> >::iterator pPageHead;
    for (pPageBody  = maPageVector.begin(), pPageHead  = maHeaderVector.begin();
         pPageBody != maPageVector.end() && pPageHead != maHeaderVector.end();
         ++pPageBody, ++pPageHead)
    {
        if( *pPageHead )
        {
            osl::File::RC nError = (*pPageHead)->open(osl_File_OpenFlag_Read);
            if (nError == osl::File::E_None)
            {
                AppendPS (pDestFILE, pPageHead->get(), pBuffer);
                (*pPageHead)->close();
            }
        }
        else
            bSuccess = false;
        if( *pPageBody )
        {
            osl::File::RC nError = (*pPageBody)->open(osl_File_OpenFlag_Read);
            if (nError == osl::File::E_None)
            {
                AppendPS (pDestFILE, pPageBody->get(), pBuffer);
                (*pPageBody)->close();
            }
        }
        else
            bSuccess = false;
    }

    AppendPS (pDestFILE, mpJobTrailer.get(), pBuffer);
    mpJobTrailer->close();

    /* well done */

    if (bSpoolToFile)
        fclose (pDestFILE);
    else
    {
        PrinterInfoManager& rPrinterInfoManager = PrinterInfoManager::get();
        if (!rPrinterInfoManager.endSpool( m_aLastJobData.m_aPrinterName,
            maJobTitle, pDestFILE, m_aDocumentJobData, true, OUString()))
        {
            bSuccess = false;
        }
    }

    return bSuccess;
}

void
PrinterJob::InitPaperSize (const JobData& rJobSetup)
{
    int nRes = rJobSetup.m_aContext.getRenderResolution ();

    OUString aPaper;
    int nWidth, nHeight;
    rJobSetup.m_aContext.getPageSize (aPaper, nWidth, nHeight);

    int nLeft = 0, nRight = 0, nUpper = 0, nLower = 0;
    const PPDParser* pParser = rJobSetup.m_aContext.getParser();
    if (pParser != nullptr)
        pParser->getMargins (aPaper, nLeft, nRight, nUpper, nLower);

    mnResolution    = nRes;

    mnWidthPt       = nWidth;
    mnHeightPt      = nHeight;

    if( mnWidthPt > mnMaxWidthPt )
        mnMaxWidthPt = mnWidthPt;
    if( mnHeightPt > mnMaxHeightPt )
        mnMaxHeightPt = mnHeightPt;

    mnLMarginPt     = nLeft;
    mnRMarginPt     = nRight;
    mnTMarginPt     = nUpper;
    mnBMarginPt     = nLower;

    mfXScale        = 72.0 / static_cast<double>(mnResolution);
    mfYScale        = -1.0 * 72.0 / static_cast<double>(mnResolution);
}

void
PrinterJob::StartPage (const JobData& rJobSetup)
{
    InitPaperSize (rJobSetup);

    OUString aPageNo = OUString::number (static_cast<sal_Int32>(maPageVector.size())+1); // sequential page number must start with 1
    OUString aExt    = aPageNo + ".ps";

    maHeaderVector.push_back( CreateSpoolFile ( "psp_pghead", aExt) );
    maPageVector.push_back( CreateSpoolFile ( "psp_pgbody", aExt) );

    osl::File* pPageHeader = maHeaderVector.back().get();
    osl::File* pPageBody   = maPageVector.back().get();

    if( ! (pPageHeader && pPageBody) )
        return;

    // write page header according to Document Structuring Conventions (DSC)
    WritePS (pPageHeader, "%%Page: ");
    WritePS (pPageHeader, aPageNo);
    WritePS (pPageHeader, " ");
    WritePS (pPageHeader, aPageNo);
    WritePS (pPageHeader, "\n");

    if( rJobSetup.m_eOrientation == orientation::Landscape )
    {
        WritePS (pPageHeader, "%%PageOrientation: Landscape\n");
        mnLandscapes++;
    }
    else
    {
        WritePS (pPageHeader, "%%PageOrientation: Portrait\n");
        mnPortraits++;
    }

    OStringBuffer pBBox;

    psp::appendStr  ("%%PageBoundingBox: ",    pBBox);
    psp::getValueOf (mnLMarginPt,              pBBox);
    psp::appendStr  (" ",                      pBBox);
    psp::getValueOf (mnBMarginPt,              pBBox);
    psp::appendStr  (" ",                      pBBox);
    psp::getValueOf (mnWidthPt  - mnRMarginPt, pBBox);
    psp::appendStr  (" ",                      pBBox);
    psp::getValueOf (mnHeightPt - mnTMarginPt, pBBox);
    psp::appendStr  ("\n",                     pBBox);

    WritePS (pPageHeader, pBBox.makeStringAndClear());

    /* #i7262# #i65491# write setup only before first page
     *  (to %%Begin(End)Setup, instead of %%Begin(End)PageSetup)
     *  don't do this in StartJob since the jobsetup there may be
     *  different.
     */
    bool bWriteFeatures = true;
    if( 1 == maPageVector.size() )
    {
        m_aDocumentJobData = rJobSetup;
        bWriteFeatures = false;
    }

    if ( writePageSetup( pPageHeader, rJobSetup, bWriteFeatures ) )
    {
        m_aLastJobData = rJobSetup;
    }
}

void
PrinterJob::EndPage ()
{
    osl::File* pPageHeader = maHeaderVector.back().get();
    osl::File* pPageBody   = maPageVector.back().get();

    if( ! (pPageBody && pPageHeader) )
        return;

    // copy page to paper and write page trailer according to DSC

    OStringBuffer pTrailer;
    psp::appendStr ("grestore grestore\n", pTrailer);
    psp::appendStr ("showpage\n",          pTrailer);
    psp::appendStr ("%%PageTrailer\n\n",   pTrailer);
    WritePS (pPageBody, pTrailer.makeStringAndClear());

    // this page is done for now, close it to avoid having too many open fd's

    pPageHeader->close();
    pPageBody->close();
}

namespace {

struct less_ppd_key
{
    bool operator()(const PPDKey* left, const PPDKey* right)
    { return left->getOrderDependency() < right->getOrderDependency(); }
};

}

static bool writeFeature( osl::File* pFile, const PPDKey* pKey, const PPDValue* pValue, bool bUseIncluseFeature )
{
    if( ! pKey || ! pValue )
        return true;

    OStringBuffer aFeature(256);
    aFeature.append( "[{\n" );
    if( bUseIncluseFeature )
        aFeature.append( "%%IncludeFeature:" );
    else
        aFeature.append( "%%BeginFeature:" );
    aFeature.append( " *" );
    aFeature.append( OUStringToOString( pKey->getKey(), RTL_TEXTENCODING_ASCII_US ) );
    aFeature.append( ' ' );
    aFeature.append( OUStringToOString( pValue->m_aOption, RTL_TEXTENCODING_ASCII_US ) );
    if( !bUseIncluseFeature )
    {
        aFeature.append( '\n' );
        aFeature.append( OUStringToOString( pValue->m_aValue, RTL_TEXTENCODING_ASCII_US ) );
        aFeature.append( "\n%%EndFeature" );
    }
    aFeature.append( "\n} stopped cleartomark\n" );
    sal_uInt64 nWritten = 0;
    return !(pFile->write( aFeature.getStr(), aFeature.getLength(), nWritten )
        || nWritten != static_cast<sal_uInt64>(aFeature.getLength()));
}

bool PrinterJob::writeFeatureList( osl::File* pFile, const JobData& rJob, bool bDocumentSetup )
{
    bool bSuccess = true;

    // emit features ordered to OrderDependency
    // ignore features that are set to default

    // sanity check
    if( rJob.m_pParser == rJob.m_aContext.getParser() &&
        rJob.m_pParser &&
        ( m_aLastJobData.m_pParser == rJob.m_pParser || m_aLastJobData.m_pParser == nullptr )
        )
    {
        std::size_t i;
        std::size_t nKeys = rJob.m_aContext.countValuesModified();
        ::std::vector< const PPDKey* > aKeys( nKeys );
        for(  i = 0; i < nKeys; i++ )
            aKeys[i] = rJob.m_aContext.getModifiedKey( i );
        ::std::sort( aKeys.begin(), aKeys.end(), less_ppd_key() );

        for( i = 0; i < nKeys && bSuccess; i++ )
        {
            const PPDKey* pKey = aKeys[i];
            bool bEmit = false;
            if( bDocumentSetup )
            {
                if( pKey->getSetupType()    == PPDKey::SetupType::DocumentSetup )
                    bEmit = true;
            }
            if( pKey->getSetupType()    == PPDKey::SetupType::PageSetup        ||
                pKey->getSetupType()    == PPDKey::SetupType::AnySetup )
                bEmit = true;
            if( bEmit )
            {
                const PPDValue* pValue = rJob.m_aContext.getValue( pKey );
                if( pValue
                    && pValue->m_eType == eInvocation
                    && ( m_aLastJobData.m_pParser == nullptr
                         || m_aLastJobData.m_aContext.getValue( pKey ) != pValue
                         || bDocumentSetup
                         )
                   )
                {
                    // try to avoid PS level 2 feature commands if level is set to 1
                    if( GetPostscriptLevel( &rJob ) == 1 )
                    {
                        bool bHavePS2 =
                            ( pValue->m_aValue.indexOf( "<<" ) != -1 )
                            ||
                            ( pValue->m_aValue.indexOf( ">>" ) != -1 );
                        if( bHavePS2 )
                            continue;
                    }
                    bSuccess = writeFeature( pFile, pKey, pValue, PrinterInfoManager::get().getUseIncludeFeature() );
                }
            }
        }
    }
    else
        bSuccess = false;

    return bSuccess;
}

bool PrinterJob::writePageSetup( osl::File* pFile, const JobData& rJob, bool bWriteFeatures )
{
    bool bSuccess = true;

    WritePS (pFile, "%%BeginPageSetup\n%\n");
    if ( bWriteFeatures )
        bSuccess = writeFeatureList( pFile, rJob, false );
    WritePS (pFile, "%%EndPageSetup\n");

    OStringBuffer pTranslate;

    if( rJob.m_eOrientation == orientation::Portrait )
    {
        psp::appendStr  ("gsave\n[",   pTranslate);
        psp::getValueOfDouble (        pTranslate, mfXScale, 5);
        psp::appendStr  (" 0 0 ",      pTranslate);
        psp::getValueOfDouble (        pTranslate, mfYScale, 5);
        psp::appendStr  (" ",          pTranslate);
        psp::getValueOf (mnRMarginPt,  pTranslate);
        psp::appendStr  (" ",          pTranslate);
        psp::getValueOf (mnHeightPt-mnTMarginPt,
                                  pTranslate);
        psp::appendStr  ("] concat\ngsave\n",
                                  pTranslate);
    }
    else
    {
        psp::appendStr  ("gsave\n",    pTranslate);
        psp::appendStr  ("[ 0 ",       pTranslate);
        psp::getValueOfDouble (        pTranslate, -mfYScale, 5);
        psp::appendStr  (" ",          pTranslate);
        psp::getValueOfDouble (        pTranslate, mfXScale, 5);
        psp::appendStr  (" 0 ",        pTranslate );
        psp::getValueOfDouble (        pTranslate, mnLMarginPt, 5 );
        psp::appendStr  (" ",          pTranslate);
        psp::getValueOf (mnBMarginPt,  pTranslate );
        psp::appendStr ("] concat\ngsave\n",
                                 pTranslate);
    }

    WritePS (pFile, pTranslate.makeStringAndClear());

    return bSuccess;
}

void PrinterJob::writeJobPatch( osl::File* pFile, const JobData& rJobData )
{
    if( ! PrinterInfoManager::get().getUseJobPatch() )
        return;

    const PPDKey* pKey = nullptr;

    if( rJobData.m_pParser )
        pKey = rJobData.m_pParser->getKey( "JobPatchFile" );
    if( ! pKey )
        return;

    // order the patch files
    // according to PPD spec the JobPatchFile options must be int
    // and should be emitted in order
    std::deque< sal_Int32 > patch_order;
    int nValueCount = pKey->countValues();
    for( int i = 0; i < nValueCount; i++ )
    {
        const PPDValue* pVal = pKey->getValue( i );
        patch_order.push_back( pVal->m_aOption.toInt32() );
        if( patch_order.back() == 0 && pVal->m_aOption != "0" )
        {
            WritePS( pFile, "% Warning: left out JobPatchFile option \"" );
            OString aOption = OUStringToOString( pVal->m_aOption, RTL_TEXTENCODING_ASCII_US );
            WritePS( pFile, aOption.getStr() );
            WritePS( pFile,
                     "\"\n% as it violates the PPD spec;\n"
                     "% JobPatchFile options need to be numbered for ordering.\n" );
        }
    }

    std::sort(patch_order.begin(), patch_order.end());
    patch_order.erase(std::unique(patch_order.begin(), patch_order.end()), patch_order.end());

    for (auto const& elem : patch_order)
    {
        // note: this discards patch files not adhering to the "int" scheme
        // as there won't be a value for them
        writeFeature( pFile, pKey, pKey->getValue( OUString::number(elem) ), false );
    }
}

void PrinterJob::writeProlog (osl::File* pFile, const JobData& rJobData )
{
    WritePS( pFile, "%%BeginProlog\n" );

    // JobPatchFile feature needs to be emitted at begin of prolog
    writeJobPatch( pFile, rJobData );

    static const char pProlog[] = {
        "%%BeginResource: procset PSPrint-Prolog 1.0 0\n"
        "/ISO1252Encoding [\n"
        "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
        "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
        "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
        "/.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef /.notdef\n"
        "/space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quotesingle\n"
        "/parenleft /parenright /asterisk /plus /comma /hyphen /period /slash\n"
        "/zero /one /two /three /four /five /six /seven\n"
        "/eight /nine /colon /semicolon /less /equal /greater /question\n"
        "/at /A /B /C /D /E /F /G\n"
        "/H /I /J /K /L /M /N /O\n"
        "/P /Q /R /S /T /U /V /W\n"
        "/X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore\n"
        "/grave /a /b /c /d /e /f /g\n"
        "/h /i /j /k /l /m /n /o\n"
        "/p /q /r /s /t /u /v /w\n"
        "/x /y /z /braceleft /bar /braceright /asciitilde /unused\n"
        "/Euro /unused /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl\n"
        "/circumflex /perthousand /Scaron /guilsinglleft /OE /unused /Zcaron /unused\n"
        "/unused /quoteleft /quoteright /quotedblleft /quotedblright /bullet /endash /emdash\n"
        "/tilde /trademark /scaron /guilsinglright /oe /unused /zcaron /Ydieresis\n"
        "/space /exclamdown /cent /sterling /currency /yen /brokenbar /section\n"
        "/dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron\n"
        "/degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered\n"
        "/cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown\n"
        "/Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla\n"
        "/Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis\n"
        "/Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply\n"
        "/Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls\n"
        "/agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla\n"
        "/egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis\n"
        "/eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide\n"
        "/oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis] def\n"
        "\n"
        "/psp_definefont { exch dup findfont dup length dict begin { 1 index /FID ne\n"
        "{ def } { pop pop } ifelse } forall /Encoding 3 -1 roll def\n"
        "currentdict end exch pop definefont pop } def\n"
        "\n"
        "/pathdict dup 8 dict def load begin\n"
        "/rcmd { { currentfile 1 string readstring pop 0 get dup 32 gt { exit }\n"
        "{ pop } ifelse } loop dup 126 eq { pop exit } if 65 sub dup 16#3 and 1\n"
        "add exch dup 16#C and -2 bitshift 16#3 and 1 add exch 16#10 and 16#10\n"
        "eq 3 1 roll exch } def\n"
        "/rhex { dup 1 sub exch currentfile exch string readhexstring pop dup 0\n"
        "get dup 16#80 and 16#80 eq dup 3 1 roll { 16#7f and } if 2 index 0 3\n"
        "-1 roll put 3 1 roll 0 0 1 5 -1 roll { 2 index exch get add 256 mul }\n"
        "for 256 div exch pop exch { neg } if } def\n"
        "/xcmd { rcmd exch rhex exch rhex exch 5 -1 roll add exch 4 -1 roll add\n"
        "1 index 1 index 5 -1 roll { moveto } { lineto } ifelse } def end\n"
        "/readpath { 0 0 pathdict begin { xcmd } loop end pop pop } def\n"
        "\n"
        "systemdict /languagelevel known not {\n"
        "/xshow { exch dup length 0 1 3 -1 roll 1 sub { dup 3 index exch get\n"
        "exch 2 index exch get 1 string dup 0 4 -1 roll put currentpoint 3 -1\n"
        "roll show moveto 0 rmoveto } for pop pop } def\n"
        "/rectangle { 4 -2 roll moveto 1 index 0 rlineto 0 exch rlineto neg 0\n"
        "rlineto closepath } def\n"
        "/rectfill { rectangle fill } def\n"
        "/rectstroke { rectangle stroke } def } if\n"
        "/bshow { currentlinewidth 3 1 roll currentpoint 3 index show moveto\n"
        "setlinewidth false charpath stroke setlinewidth } def\n"
        "/bxshow { currentlinewidth 4 1 roll setlinewidth exch dup length 1 sub\n"
        "0 1 3 -1 roll { 1 string 2 index 2 index get 1 index exch 0 exch put dup\n"
        "currentpoint 3 -1 roll show moveto currentpoint 3 -1 roll false charpath\n"
        "stroke moveto 2 index exch get 0 rmoveto } for pop pop setlinewidth } def\n"
        "\n"
        "/psp_lzwfilter { currentfile /ASCII85Decode filter /LZWDecode filter } def\n"
        "/psp_ascii85filter { currentfile /ASCII85Decode filter } def\n"
        "/psp_lzwstring { psp_lzwfilter 1024 string readstring } def\n"
        "/psp_ascii85string { psp_ascii85filter 1024 string readstring } def\n"
        "/psp_imagedict {\n"
        "/psp_bitspercomponent { 3 eq { 1 }{ 8 } ifelse } def\n"
        "/psp_decodearray { [ [0 1 0 1 0 1] [0 255] [0 1] [0 255] ] exch get }\n"
        "def 7 dict dup\n"
        "/ImageType 1 put dup\n"
        "/Width 7 -1 roll put dup\n"
        "/Height 5 index put dup\n"
        "/BitsPerComponent 4 index psp_bitspercomponent put dup\n"
        "/Decode 5 -1 roll psp_decodearray put dup\n"
        "/ImageMatrix [1 0 0 1 0 0] dup 5 8 -1 roll put put dup\n"
        "/DataSource 4 -1 roll 1 eq { psp_lzwfilter } { psp_ascii85filter } ifelse put\n"
        "} def\n"
        "%%EndResource\n"
        "%%EndProlog\n"
    };
    WritePS (pFile, pProlog);
}

bool PrinterJob::writeSetup( osl::File* pFile, const JobData& rJob )
{
    WritePS (pFile, "%%BeginSetup\n%\n");

    // download fonts
    std::vector< OString > aFonts;
    m_pGraphics->writeResources( pFile, aFonts );

    if( !aFonts.empty() )
    {
        std::vector< OString >::const_iterator it = aFonts.begin();
        OStringBuffer aLine( 256 );
        aLine.append( "%%DocumentSuppliedResources: font " );
        aLine.append( *it );
        aLine.append( "\n" );
        WritePS ( pFile, aLine.getStr() );
        while( (++it) != aFonts.end() )
        {
            aLine.setLength(0);
            aLine.append( "%%+ font " );
            aLine.append( *it );
            aLine.append( "\n" );
            WritePS ( pFile, aLine.getStr() );
        }
    }

    bool bSuccess = true;
    // in case of external print dialog the number of copies is prepended
    // to the job, let us not complicate things by emitting our own copy count
    bool bExternalDialog = PrinterInfoManager::get().checkFeatureToken( GetPrinterName(), "external_dialog" );
    if( ! bExternalDialog && rJob.m_nCopies > 1 )
    {
        // setup code
        OString aLine = "/#copies " +
                OString::number(static_cast<sal_Int32>(rJob.m_nCopies)) +
                " def\n";
        sal_uInt64 nWritten = 0;
        bSuccess = !(pFile->write(aLine.getStr(), aLine.getLength(), nWritten)
            || nWritten != static_cast<sal_uInt64>(aLine.getLength()));

        if( bSuccess && GetPostscriptLevel( &rJob ) >= 2 )
            WritePS (pFile, "<< /NumCopies null /Policies << /NumCopies 1 >> >> setpagedevice\n" );
    }

    bool bFeatureSuccess = writeFeatureList( pFile, rJob, true );

    WritePS (pFile, "%%EndSetup\n");

    return bSuccess && bFeatureSuccess;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

{'repo_name': 'LibreOffice/core', 'stars': '907', 'repo_language': 'None', 'file_name': 'README', 'mime_type': 'text/plain', 'hash': 1522532709299923495, 'source_dataset': 'data'}


package p000a.p005b.p007b;

import android.os.Bundle;

/* renamed from: a.b.b.c */
class C0018c implements Runnable {
    /* renamed from: a */
    final /* synthetic */ String f11a;
    /* renamed from: b */
    final /* synthetic */ Bundle f12b;
    /* renamed from: c */
    final /* synthetic */ C0890g f13c;

    C0018c(C0890g c0890g, String str, Bundle bundle) {
        this.f13c = c0890g;
        this.f11a = str;
        this.f12b = bundle;
    }

    public void run() {
        this.f13c.f1895b.mo1396a(this.f11a, this.f12b);
    }
}

{'repo_name': 'Hengle/DeepNewdsForAndroid', 'stars': '234', 'repo_language': 'Java', 'file_name': 'androidx.versionedparcelable_versionedparcelable.version', 'mime_type': 'text/plain', 'hash': 7253552201971360709, 'source_dataset': 'data'}


/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.systemui.util.concurrency;

import com.android.systemui.util.time.FakeSystemClock;

import java.util.Collections;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class FakeExecutor implements DelayableExecutor {
    private final FakeSystemClock mClock;
    private PriorityQueue<QueuedRunnable> mQueuedRunnables = new PriorityQueue<>();
    private boolean mIgnoreClockUpdates;

    /**
     * Initializes a fake executor.
     *
     * @param clock FakeSystemClock allowing control over delayed runnables. It is strongly
     *              recommended that this clock have its auto-increment setting set to false to
     *              prevent unexpected advancement of the time.
     */
    public FakeExecutor(FakeSystemClock clock) {
        mClock = clock;
        mClock.addListener(() -> {
            if (!mIgnoreClockUpdates) {
                runAllReady();
            }
        });
    }

    /**
     * Runs a single runnable if it's scheduled to run according to the internal clock.
     *
     * If constructed to advance the clock automatically, this will advance the clock enough to
     * run the next pending item.
     *
     * This method does not advance the clock past the item that was run.
     *
     * @return Returns true if an item was run.
     */
    public boolean runNextReady() {
        if (!mQueuedRunnables.isEmpty() && mQueuedRunnables.peek().mWhen <= mClock.uptimeMillis()) {
            mQueuedRunnables.poll().mRunnable.run();
            return true;
        }

        return false;
    }

    /**
     * Runs all Runnables that are scheduled to run according to the internal clock.
     *
     * If constructed to advance the clock automatically, this will advance the clock enough to
     * run all the pending items. This method does not advance the clock past items that were
     * run. It is equivalent to calling {@link #runNextReady()} in a loop.
     *
     * @return Returns the number of items that ran.
     */
    public int runAllReady() {
        int num = 0;
        while (runNextReady()) {
            num++;
        }

        return num;
    }

    /**
     * Advances the internal clock to the next item to run.
     *
     * The clock will only move forward. If the next item is set to run in the past or there is no
     * next item, the clock does not change.
     *
     * Note that this will cause one or more items to actually run.
     *
     * @return The delta in uptimeMillis that the clock advanced, or 0 if the clock did not advance.
     */
    public long advanceClockToNext() {
        if (mQueuedRunnables.isEmpty()) {
            return 0;
        }

        long startTime = mClock.uptimeMillis();
        long nextTime = mQueuedRunnables.peek().mWhen;
        if (nextTime <= startTime) {
            return 0;
        }
        updateClock(nextTime);

        return nextTime - startTime;
    }

    /**
     * Advances the internal clock to the last item to run.
     *
     * The clock will only move forward. If the last item is set to run in the past or there is no
     * next item, the clock does not change.
     *
     * @return The delta in uptimeMillis that the clock advanced, or 0 if the clock did not advance.
     */
    public long advanceClockToLast() {
        if (mQueuedRunnables.isEmpty()) {
            return 0;
        }

        long startTime = mClock.uptimeMillis();
        long nextTime = Collections.max(mQueuedRunnables).mWhen;
        if (nextTime <= startTime) {
            return 0;
        }

        updateClock(nextTime);

        return nextTime - startTime;
    }

    /**
     * Returns the number of un-executed runnables waiting to run.
     */
    public int numPending() {
        return mQueuedRunnables.size();
    }

    @Override
    public Runnable executeDelayed(Runnable r, long delay, TimeUnit unit) {
        if (delay < 0) {
            delay = 0;
        }
        return executeAtTime(r, mClock.uptimeMillis() + unit.toMillis(delay));
    }

    @Override
    public Runnable executeAtTime(Runnable r, long uptime, TimeUnit unit) {
        long uptimeMillis = unit.toMillis(uptime);

        QueuedRunnable container = new QueuedRunnable(r, uptimeMillis);

        mQueuedRunnables.offer(container);

        return () -> mQueuedRunnables.remove(container);
    }

    @Override
    public void execute(Runnable command) {
        executeDelayed(command, 0);
    }

    /**
     * Run all Executors in a loop until they all report they have no ready work to do.
     *
     * Useful if you have Executors the post work to other Executors, and you simply want to
     * run them all until they stop posting work.
     */
    public static void exhaustExecutors(FakeExecutor ...executors) {
        boolean didAnything;
        do {
            didAnything = false;
            for (FakeExecutor executor : executors) {
                didAnything = didAnything || executor.runAllReady() != 0;
            }
        } while (didAnything);
    }

    private void updateClock(long nextTime) {
        mIgnoreClockUpdates = true;
        mClock.setUptimeMillis(nextTime);
        mIgnoreClockUpdates = false;
    }

    private static class QueuedRunnable implements Comparable<QueuedRunnable> {
        private static AtomicInteger sCounter = new AtomicInteger();

        Runnable mRunnable;
        long mWhen;
        private int mCounter;

        private QueuedRunnable(Runnable r, long when) {
            mRunnable = r;
            mWhen = when;

            // PrioirityQueue orders items arbitrarily when equal. We want to ensure that
            // otherwise-equal elements are ordered according to their insertion order. Because this
            // class only is constructed right before insertion, we use a static counter to track
            // insertion order of otherwise equal elements.
            mCounter = sCounter.incrementAndGet();
        }

        @Override
        public int compareTo(QueuedRunnable other) {
            long diff = mWhen - other.mWhen;

            if (diff == 0) {
                return mCounter - other.mCounter;
            }

            return diff > 0 ? 1 : -1;
        }
    }
}

{'repo_name': 'aosp-mirror/platform_frameworks_base', 'stars': '9245', 'repo_language': 'Java', 'file_name': 'DatabaseCursorTest.java', 'mime_type': 'text/x-java', 'hash': 350854508217822869, 'source_dataset': 'data'}


### 世卫权衡应对武汉肺炎措施 李一平：绝不可低估中共的邪恶程度(图)
------------------------

#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md)   |   [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki)   |   [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android)   |   [网门安卓版](https://github.com/oGate2/oGate)   |   [神州正道安卓版](https://github.com/SzzdOgate/update)

   李一平（图片来源：视频截图）

  【看中国2020年1月24日讯】中国（中共）周四（1月23日）封锁了

   武汉肺炎

  爆发集中的两个城市，该病毒已造成18人死亡，630多人感染。世界各地政府努力预防该病毒在全球蔓延。

    李一平

  在其自媒体中呼吁，绝不可低估中共的邪恶程度。

  卫生官员担心，在周六（2月25日）开始的为期一周的

   中国

  农历新年假期中，随着亿万中国人在国内外旅行，病毒的传播速度可能会加快。

  中国国家电视台称已确诊634例。截至周三（1月22日），中国国家卫生委员会在中部湖北省确认有17人死亡。此外，北京南部的河北省卫生部门周四（1月23日）表示，一名感染

   武汉肺炎

  的80岁男子死亡，这是湖北以外首例确诊死亡的人。

  据法广报导，武汉肺炎的祸首被认为是武汉海鲜市场销售的野生动物，有研究推测，如同17年前有人吃果子狸引发非典一样，这次病毒也是由蝙蝠传播给野生动物的，如竹鼠、獾等，而中间宿主可能是蛇。

  武汉是一个拥有1100万人口的城市，大部分交通于周四暂停，人们被告知不要离开。一些戴着面罩的准军事人员在封闭的汉口火车站入口处站岗。几个小时后，邻近的黄岗镇（约有700万人）也被下达了类似的封锁措施。

  中共官媒援引武汉市政府病毒工作队的话说，该市将于周五（1月24日）暂停所有网上叫车服务，以“更大程度地切断病毒的传播”。

  世界卫生组织驻北京代表高登·加利亚（Gauden Galea）说：“在公共卫生历史上，1100万人的封锁是前所未有的。”

  据路透社报导，新型冠状病毒已创建警报，目前没有疫苗，还存在许多未知，现在定义它有多危险以及它在人与人之间传播的容易程度还为时过早。

  中共财政部说，将向湖北省政府拨款人民币10亿元（合1.45亿美元），以帮助控制疫情。

  《新京报》援引一家建筑公司的消息来源称，除了限制行动外，武汉还计划在六天内建立一家新医院来治疗患者。

  附近的鄂州市关闭了火车站。北京取消了大型聚会，包括两次农历新年庙会，并向游客关闭了首都最著名的旅游景点紫禁城，直至另行通知。

  美国国务院警告旅行者，在中国旅行要加倍小心，世界各地的机场都在对从中国入境的旅客进行检查。

  由中共治下的香港已有两个确诊病例，香港正将两个度假营地变成隔离站。台湾则禁止任何来自武汉的人前往台湾。

  澳大利亚首席医疗官布伦丹·墨菲（Brendan Murphy）表示：“现阶段的早期证据表明情况并不那么严重。”

   世卫

  组织将在周四（1月23日）决定是否将疫情宣布为全球卫生紧急情况，这将加强国际对策。之前世卫组织宣布过5次国际公共卫生紧急情况。

  世卫组织紧急情况规划负责人迈克尔·赖安（Michael Ryan）周三表示，根据中国提供的数据，近四分之三的病例发生在40岁以上的人群中，其中约40％患有基本的健康状况。

  疫情是周四的全球股市下跌的一个重要因素，其中中国股市跌幅为八个月以来最大。中国人民币跌至两周低点。

  暴发此类事件的经济影响很难量化，国际航空运输协会（International Air Transport Association）在2006年的估算， 2003年的萨斯使中国GDP减少了仅1个百分点。

  目前，许多中国人取消了旅行，购买口罩和避免前往购物中心。七部原本在农历新年期间上映的中国电影被延后。

  未经证实的网络爆料称：“武汉的类SARS冠状病毒就是来源于中共军方2018年从舟山蝙蝠身上发现并分离的新型冠状病毒。病毒序列可以在美国国立卫生研究院的基因子据库找到（NIH的GenBank)，由南京军区军事医学科学研究所递交。并且通过技术故意更改舟山蝙蝠病毒，适于人类传播的新病毒。”

    为什么爆发在武汉？知情人进一步解释，因武汉有中国唯一的P4生物实验室，在那里可进行人工基因变异。病毒爆发可能是发生意外导致病毒泄露或者是故意泄露。

  全民共振李一平在其自媒体中表示，中共体制的逆淘汰使得有能力的官员无法得到重用，无能而效率低下。并且这个政权很可能是要故意引起一大批人的死亡。这次的疫情受到伤害最大的就是老年人，这批老年人因为身体素质、抵抗能力比较差，被病毒感染后的死亡率会非常高，现在的死亡率是3%左右，如果该病毒在全国大规模扩散，3%将是4000-5000万，其中绝大多数将是老年人，这正好符合中共的利益。

  李一平分析，中共担心社会老龄化，它就必须付出大量的养老金，这对现行体制是沉重的负担。过去几十年，中共已经通过大撒币、官员私吞等挥霍了大量中国人的钱，它没有足够的钱养活这么一大批老人，如果来一场瘟疫，这些人就自己死亡了。很多人都有这样的怀疑。

  “绝对不要低估这帮人，他们邪恶的程度！”他说。

  在这场灾难过后，大家一定要想办法，结束这个体制。“否则类似灾难绝对不会是最后一次，今后还会一而再、再而三地发生！”李一平表示。

  他呼吁，等灾难结束后，所有受到伤害的人们走出来发动“国殇日”悼念活动，让悲痛化作改变社会的力量，让悲痛成为变革的动力，这样才可以为自己，为下一代，为父母创造一个比较安全的生存环境。

    BBC中文周四（1月23日）在油管上发布的采访视频显示，目前已有十多名医护人员感染该病毒，一名武汉年轻女护士哭诉道，“只有家人知道多么辛苦。有时候，因为我是外地的嘛，爸爸妈妈都不在，失眠。每天都会打电话视频，首先（让他们）安心，（他们）担心我们这里上班的这种状态，每天看新闻，真的很担心。我们说不要紧，我们说我们的防护很到位。其实，是为了让他们安心。我们自己其实说不怕是不可能的。谁都怕，真的很担心。但是，我们在这个工作岗位上，我们必须就要有自己是使命感，必须去做这样的事情。”

手机上长按并复制下列链接或二维码分享本文章：

https://github.com/gfw-breaker/banned-news/blob/master/pages/p9/920661.md

原文地址（需翻墙访问）：https://www.secretchina.com/news/gb/2020/01/24/920661.html

------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md)  |  [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md)  | [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md)

{'repo_name': 'gfw-breaker/banned-news', 'stars': '105', 'repo_language': 'Python', 'file_name': 'hp-12202019112936.md', 'mime_type': 'text/plain', 'hash': 3655678838379393369, 'source_dataset': 'data'}


#import "IFKShape.h"

@interface IFKCircleShape : IFKShape

@property (nonatomic, copy) NSNumber *inputRadius;

@end

{'repo_name': 'iyegoroff/react-native-image-filter-kit', 'stars': '132', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 5707547529836347712, 'source_dataset': 'data'}


package network

// Copyright (c) Microsoft and contributors.  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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/autorest/validation"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// VpnSitesConfigurationClient is the network Client
type VpnSitesConfigurationClient struct {
	BaseClient
}

// NewVpnSitesConfigurationClient creates an instance of the VpnSitesConfigurationClient client.
func NewVpnSitesConfigurationClient(subscriptionID string) VpnSitesConfigurationClient {
	return NewVpnSitesConfigurationClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewVpnSitesConfigurationClientWithBaseURI creates an instance of the VpnSitesConfigurationClient client using a
// custom endpoint.  Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds,
// Azure stack).
func NewVpnSitesConfigurationClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesConfigurationClient {
	return VpnSitesConfigurationClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// Download gives the sas-url to download the configurations for vpn-sites in a resource group.
// Parameters:
// resourceGroupName - the resource group name.
// virtualWANName - the name of the VirtualWAN for which configuration of all vpn-sites is needed.
// request - parameters supplied to download vpn-sites configuration.
func (client VpnSitesConfigurationClient) Download(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (result VpnSitesConfigurationDownloadFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesConfigurationClient.Download")
		defer func() {
			sc := -1
			if result.Response() != nil {
				sc = result.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	if err := validation.Validate([]validation.Validation{
		{TargetValue: request,
			Constraints: []validation.Constraint{{Target: "request.OutputBlobSasURL", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
		return result, validation.NewError("network.VpnSitesConfigurationClient", "Download", err.Error())
	}

	req, err := client.DownloadPreparer(ctx, resourceGroupName, virtualWANName, request)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", nil, "Failure preparing request")
		return
	}

	result, err = client.DownloadSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnSitesConfigurationClient", "Download", result.Response(), "Failure sending request")
		return
	}

	return
}

// DownloadPreparer prepares the Download request.
func (client VpnSitesConfigurationClient) DownloadPreparer(ctx context.Context, resourceGroupName string, virtualWANName string, request GetVpnSitesConfigurationRequest) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
		"virtualWANName":    autorest.Encode("path", virtualWANName),
	}

	const APIVersion = "2020-03-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration", pathParameters),
		autorest.WithJSON(request),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DownloadSender sends the Download request. The method will close the
// http.Response Body if it receives an error.
func (client VpnSitesConfigurationClient) DownloadSender(req *http.Request) (future VpnSitesConfigurationDownloadFuture, err error) {
	var resp *http.Response
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	future.Future, err = azure.NewFutureFromResponse(resp)
	return
}

// DownloadResponder handles the response to the Download request. The method always
// closes the http.Response Body.
func (client VpnSitesConfigurationClient) DownloadResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
		autorest.ByClosing())
	result.Response = resp
	return
}

{'repo_name': 'hashicorp/terraform-provider-kubernetes', 'stars': '748', 'repo_language': 'Go', 'file_name': 'main.tf', 'mime_type': 'text/plain', 'hash': -3859376280185392588, 'source_dataset': 'data'}


#pragma once

#include <type_traits>
#include <nall/stdint.hpp>

//pull all type traits used by nall from std namespace into nall namespace
//this removes the requirement to prefix type traits with std:: within nall

namespace nall {
  using std::add_const;
  using std::conditional;
  using std::conditional_t;
  using std::decay;
  using std::declval;
  using std::enable_if;
  using std::enable_if_t;
  using std::false_type;
  using std::is_floating_point;
  using std::is_floating_point_v;
  using std::forward;
  using std::initializer_list;
  using std::is_array;
  using std::is_base_of;
  using std::is_base_of_v;
  using std::is_function;
  using std::is_integral;
  using std::is_integral_v;
  using std::is_same;
  using std::is_same_v;
  using std::is_signed;
  using std::is_signed_v;
  using std::is_unsigned;
  using std::is_unsigned_v;
  using std::move;
  using std::nullptr_t;
  using std::remove_extent;
  using std::remove_reference;
  using std::swap;
  using std::true_type;
}

namespace std {
  #if INTMAX_BITS >= 128
  template<> struct is_signed<int128_t> : true_type {};
  template<> struct is_unsigned<uint128_t> : true_type {};
  #endif
}

{'repo_name': 'byuu/bsnes', 'stars': '444', 'repo_language': 'C++', 'file_name': 'cgb_border.inc', 'mime_type': 'text/plain', 'hash': 4051319249263134195, 'source_dataset': 'data'}


#include <iostream>
#include <cstring>
#include <vector>
#include <deque>
#include <map>
#include <string>
#include <algorithm>
using namespace std;

string name[] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"};
vector<string> ans;
int main()
{
  char c;
  int sum = 0;
  while((c = getchar()) != '\n')
  {
    sum += c-'0';
  }
  if(!sum)  ans.push_back( name[0] );
  while(sum)
  {
    ans.push_back( name[ sum%10 ] );
    sum /= 10;
  }
  cout << ans[ans.size()-1];
  for(int i = ans.size()-2; i >= 0; i--)
    cout << " " << ans[i];
  cout << endl;
  return 0;
}


#include <Rcpp.h>
#include "XlsxWorkBook.h"
using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector xlsx_sheets(std::string path) {
  return XlsxWorkBook(path).sheets();
}

// [[Rcpp::export]]
std::vector<std::string> xlsx_strings(std::string path) {
  return XlsxWorkBook(path).stringTable();
}

// [[Rcpp::export]]
std::set<int> xlsx_date_formats(std::string path) {
  return XlsxWorkBook(path).dateFormats();
}

{'repo_name': 'tidyverse/readxl', 'stars': '556', 'repo_language': 'C++', 'file_name': 'revdep-notes.md', 'mime_type': 'text/plain', 'hash': -5605272040733272722, 'source_dataset': 'data'}


/*
 * Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved.
 *
 * This product is licensed to you under the Apache License, Version 2.0 (the "License").
 * You may not use this product except in compliance with the License.
 *
 * This product may include a number of subcomponents with separate copyright notices
 * and license terms. Your use of these subcomponents is subject to the terms and
 * conditions of the subcomponent's license, as noted in the LICENSE file.
 */

package com.vmware.mangle.model;

import lombok.Getter;
import lombok.Setter;

/**
 * @author bkaranam
 *
 */
@Getter
@Setter
public class VCHealth {
    private String value;
}

{'repo_name': 'vmware/mangle', 'stars': '108', 'repo_language': 'Java', 'file_name': 'checkstyle-suppression.xml', 'mime_type': 'text/xml', 'hash': -3289807106853832876, 'source_dataset': 'data'}


package org.dcache.util.expression;

import org.junit.Before;
import org.junit.Test;
import org.parboiled.Parboiled;
import org.parboiled.parserunners.BasicParseRunner;
import org.parboiled.support.ParsingResult;

import static org.junit.Assert.assertEquals;

public class ExpressionTest
{
    private SymbolTable symbols;

    @Before
    public void setup()
    {
        symbols = new SymbolTable();
        symbols.put("number", 1.0);
    }

    private Expression createExpression(String s)
    {
        ExpressionParser parser =
            Parboiled.createParser(ExpressionParser.class);
        ParsingResult<Expression> result =
            new BasicParseRunner(parser.Top()).run(s);
        return result.resultValue;
    }

    private Expression createCheckedExpression(String s)
        throws TypeMismatchException, UnknownIdentifierException
    {
        Expression expression = createExpression(s);
        expression.check(symbols);
        return expression;
    }

    private Object evaluate(String s)
        throws TypeMismatchException, UnknownIdentifierException
    {
        Expression expression = createExpression(s);
        expression.check(symbols);
        return expression.evaluate(symbols);
    }

    @Test
    public void testLiterals()
        throws Exception
    {
        assertEquals(-1.0, evaluate("-1"));
        assertEquals(1.0, evaluate("1"));
        assertEquals(1.1, evaluate("1.1"));
        assertEquals(true, evaluate("true"));
        assertEquals(false, evaluate("false"));
        assertEquals("foo", evaluate("\"foo\""));
        assertEquals("foo", evaluate("'foo'"));

        assertEquals(1000.0, evaluate("1k"));
        assertEquals(1000.0, evaluate("1 K"));
        assertEquals(1000000.0, evaluate("1 M"));
        assertEquals(1000000000.0, evaluate("1 G"));
        assertEquals(1000000000000.0, evaluate("1 T"));
        assertEquals(1000000000000000.0, evaluate("1 P"));
        assertEquals(Math.scalb(1.0, 10), evaluate("1 Ki"));
        assertEquals(Math.scalb(1.0, 20), evaluate("1 Mi"));
        assertEquals(Math.scalb(1.0, 30), evaluate("1 Gi"));
        assertEquals(Math.scalb(1.0, 40), evaluate("1 Ti"));
        assertEquals(Math.scalb(1.0, 50), evaluate("1 Pi"));
    }

    @Test
    public void testOperators()
        throws Exception
    {
        assertEquals(2.0, evaluate("1+1"));
        assertEquals(0.0, evaluate("1-1"));
        assertEquals(4.0, evaluate("2*2"));
        assertEquals(2.5, evaluate("5/2"));
        assertEquals(1.0, evaluate("5%2"));
        assertEquals(27.0, evaluate("3**3"));

        assertEquals(true, evaluate("1 < 2"));
        assertEquals(false, evaluate("2 < 2"));
        assertEquals(true, evaluate("2 <= 2"));
        assertEquals(true, evaluate("2 == 2"));
        assertEquals(false, evaluate("2 != 2"));
        assertEquals(false, evaluate("2 > 2"));
        assertEquals(true, evaluate("2 >= 2"));

        assertEquals(true, evaluate("true == true"));
        assertEquals(false, evaluate("true != true"));

        assertEquals(true, evaluate("'bla' == \"bla\""));
        assertEquals(false, evaluate("'bla' == 'false'"));
        assertEquals(false, evaluate("'bla' != \"bla\""));
        assertEquals(true, evaluate("'bla' != 'false'"));

        assertEquals(-1.0, evaluate("--+-++1"));
        assertEquals(1.0, evaluate("-+-++1"));

        assertEquals(1.0, evaluate("true ? 1 : 2"));
        assertEquals(2.0, evaluate("false ? 1 : 2"));

        assertEquals(true, evaluate("true ? true : false"));
        assertEquals(false, evaluate("false ? true : false"));

        assertEquals("a", evaluate("true ? 'a' : 'b'"));
        assertEquals("b", evaluate("false ? 'a' : 'b'"));

        assertEquals(true, evaluate("'blabla' =~ '(bla)+'"));
        assertEquals(false, evaluate("'blabla' !~ '(bla)+'"));

        assertEquals(true, evaluate("true and true"));
        assertEquals(false, evaluate("true and false"));

        assertEquals(true, evaluate("true or false"));
        assertEquals(false, evaluate("false or false"));

        assertEquals(true, evaluate("not false"));
        assertEquals(false, evaluate("not true"));
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerIfCondition()
        throws Exception
    {
        evaluate("1 ? 2 :3");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerIfValues()
        throws Exception
    {
        evaluate("true ? 2 : false");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerNumberEqualsString()
        throws Exception
    {
        evaluate("2.1 == '1'");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerNumberAndNumber()
        throws Exception
    {
        evaluate("2.1 and 1");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerNotNumber()
        throws Exception
    {
        evaluate("not 2.1");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerUminusString()
        throws Exception
    {
        evaluate("-'bla'");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerBooleanLEBoolean()
        throws Exception
    {
        evaluate("true <= true");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerNumberPlusBoolean()
        throws Exception
    {
        evaluate("1+false");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerNumberPlusString()
        throws Exception
    {
        evaluate("1+'one'");
    }

    @Test(expected=TypeMismatchException.class)
    public void testTypeCheckerMatchNumber()
        throws Exception
    {
        evaluate("1 =~ 2");
    }

    @Test
    public void testIdentifierWithTrailingSpace()
        throws Exception
    {
        assertEquals(1.0, evaluate("number "));
    }
}

{'repo_name': 'dCache/dcache', 'stars': '169', 'repo_language': 'Java', 'file_name': 'hsqldb.properties', 'mime_type': 'text/plain', 'hash': -5853560785206954205, 'source_dataset': 'data'}