text:
package fm.http

import fm.common.Implicits._
import fm.common.{Base64, ImmutableDate, IndexedSeqProxy}
import java.nio.charset.StandardCharsets
import java.util.Date
import io.netty.handler.codec.http.{DefaultHttpHeaders, EmptyHttpHeaders, HttpHeaderNames, HttpHeaders}
import io.netty.handler.codec.http.cookie.{ClientCookieEncoder, ServerCookieEncoder}
import io.netty.util.AsciiString
import java.time._
import java.time.format.DateTimeFormatter
import scala.collection.JavaConverters._
import scala.util.Try
import scala.util.matching.Regex

object Headers {
  val empty: ImmutableHeaders = ImmutableHeaders(EmptyHttpHeaders.INSTANCE)

  def apply(headerValues: (CharSequence, Any)*): ImmutableHeaders = {
    if (headerValues.isEmpty) return empty

    val headers: MutableHeaders = MutableHeaders()
    headers.withHeaders(headerValues:_*)

    // Convert to immutable headers - this is safe since we know we won't be touching the MutableHeaders again
    ImmutableHeaders(headers.nettyHeaders)
  }

  def noCache(headerValues: (CharSequence, Any)*): ImmutableHeaders = {
    val headers: MutableHeaders = MutableHeaders()
    headers.withNoCache
    headers.withHeaders(headerValues:_*)

    // Convert to immutable headers - this is safe since we know we won't be touching the MutableHeaders again
    ImmutableHeaders(headers.nettyHeaders)
  }

  private val GMT: ZoneId = ZoneId.of("GMT")

  private[http] def formatDate(): String = formatDate(OffsetDateTime.now)
  private[http] def formatDate(millis: Long): String = formatDate(Instant.ofEpochMilli(millis))
  private[http] def formatDate(date: Date): String = formatDate(date.toInstant)
  private[http] def formatDate(date: ImmutableDate): String = formatDate(date.toInstant)
  private[http] def formatDate(date: OffsetDateTime): String = formatDate(date.toZonedDateTime)
  private[http] def formatDate(date: Instant): String = formatDate(ZonedDateTime.ofInstant(date, GMT))
  private[http] def formatDate(date: LocalDateTime): String = formatDate(date.atZone(ZoneId.systemDefault()))

  private[http] def formatDate(date: ZonedDateTime): String = {
    date.withZoneSameInstant(GMT).format(DateTimeFormatter.RFC_1123_DATE_TIME)
  }

//  private[http] def parseZonedDateTime(s: String): Option[ZonedDateTime] = {
//    if (s.isNullOrBlank) return None
//    val cleaned: String = if(s.contains(";")) s.substring(0, s.indexOf(";")) else s
//    Try{ ZonedDateTime.parse(cleaned, DateTimeFormatter.RFC_1123_DATE_TIME) }.toOption
//  }

  private[http] def parseImmutableDate(s: String): Option[ImmutableDate] = {
    if (s.isNullOrBlank) return None
    val cleaned: String = if(s.contains(";")) s.substring(0, s.indexOf(";")) else s
    Try{ ZonedDateTime.parse(cleaned, DateTimeFormatter.RFC_1123_DATE_TIME) }.toOption.map{ _.toInstant }.map{ ImmutableDate(_) }
  }

  // A very very simple Regex for parsing the filename from the Content-Disposition Header
  private[http] val ContentDispositionAttachmentFileNamePattern: Regex = """attachment; filename="(.*)"""".r

  private[http] def parseContentDispositionAttachmentFileName(s: String): Option[String] = s match {
    case ContentDispositionAttachmentFileNamePattern(name) => name.toBlankOption
    case _ => None
  }

  private[http] object NonStandardNames {
    private implicit def toAsciiString(s: String): AsciiString = new AsciiString(s)

    //
    // Non-Standard Request Headers
    //
    val DNT: AsciiString = "DNT"
    val X_REQUESTED_WITH: AsciiString = "X-Requested-With"
    val X_FORWARDED_FOR: AsciiString = "X-Forwarded-For"
    val X_FORWARDED_PROTO: AsciiString = "X-Forwarded-Proto"
    val X_FORWARDED_PORT: AsciiString = "X-Forwarded-Port"
    val X_SSL: AsciiString = "X-SSL"

    //
    // Non-Standard Response Headers
    //
    val X_FRAME_OPTIONS: AsciiString = "X-Frame-Options"
    val X_XSS_PROTECTION: AsciiString = "X-XSS-Protection"
    val X_CONTENT_TYPE_OPTIONS: AsciiString = "X-Content-Type-Options"
    val X_POWERED_BY: AsciiString = "X-Powered-By"
    val X_UA_COMPATIBLE: AsciiString = "X-UA-Compatible"
  }

  private val BasicAuthHeader: Regex = """Basic (.+)""".r
  private val BasicAuthSplit: Regex = """(.+):(.*)""".r

  private val DigestAuthHeader: Regex = """Digest (.+)""".r
  private val DigestAuthParam: Regex = """(\w+)=(?:"([^"]+)"|([^,]+)),?""".r

  /**
   * Given the value of the Authorization header parse the username/password for Basic auth
   */
  def parseBasicAuthorization(value: String): Option[(String,String)] = try {
    value match {
      case BasicAuthHeader(encoded) => new String(Base64.decode(encoded), StandardCharsets.ISO_8859_1) match {
        case BasicAuthSplit(user, pass) => Some((user, pass))
        case _ => None
      }
      case _ => None
    }
  } catch {
    // This will catch Base64 decoding exceptions and just return None
    case ex: Exception => None
  }

  def makeBasicAuthorization(user: String, pass: String): String = "Basic "+Base64.encodeBytes((user+":"+pass).getBytes(StandardCharsets.ISO_8859_1))

  /**
   * Given the value of the WWW-Authenticate or Authorization headers parse the Digest auth params
   */
  private def parseDigestAuthParams(str: String): Option[Map[String,String]] = {
    str match {
      case DigestAuthHeader(paramsStr) =>
        val params: Map[String, String] = Map(DigestAuthParam.findAllIn(paramsStr).matchData.map{ m =>
            val k: String = m.group(1)
            val v: String = if (null != m.group(2)) m.group(2) else m.group(3)
            (k,v)
          }.toSeq: _*)

       Some(params)

      case _ => None
    }
  }

  /**
   * Create the WWW-Authenticate or Authorization header value given the Digest auth params
   */
  def makeDigestAuthorization(params: Seq[(String,String)]): String = {
    "Digest "+params.map{case (k,v) => k+"=\""+v+"\""}.mkString(", ")
  }
}

sealed trait Headers extends IndexedSeqProxy[(String, String)] {
  import Headers._

  private[http] def nettyHeaders: HttpHeaders
  def self: Vector[(String, String)] = nettyHeaders.asScala.toVector.map{ entry => entry.getKey() -> entry.getValue() }

  def toMutableHeaders: MutableHeaders = this match {
    case ImmutableHeaders(headers) => MutableHeaders(cloneNettyHeaders())
    case self: MutableHeaders => self
  }

  def toImmutableHeaders: ImmutableHeaders = this match {
    case self: ImmutableHeaders => self
    case MutableHeaders(headers) => ImmutableHeaders(cloneNettyHeaders())
  }

  private def cloneNettyHeaders(): HttpHeaders = {
    val h = new DefaultHttpHeaders
    h.add(nettyHeaders)
    h
  }

  /** Adds the passed in headers */
  def withHeaders(headerValues: (CharSequence, Any)*): Headers

  /** Add the Cache-Control and Expires headers to prevent caching of this response */
  def withNoCache: Headers

  /** These are the client side cookies that are being sent with the request */
  def withCookies(c: Traversable[Cookie]): Headers

  /** These are the server side cookies that are being sent with the response */
  def withSetCookies(c: Traversable[Cookie]): Headers

  /** These are the client side cookies that are being sent with the request */
  def addCookie(c: Cookie): Headers = {
    withCookies(cookies.filterNot{ _.name === c.name } :+ c)
  }

  /** These are the server side cookies that are being sent with the response */
  def addSetCookie(c: Cookie): Headers = {
    withSetCookies(setCookies.filterNot{ _.name === c.name } :+ c)
  }

  override def toString: String = self.map{ case (k,v) => s"$k: $v" }.mkString("\n")

  def apply(name: CharSequence): String = get(name).getOrElse{ throw new NoSuchElementException("No header value for: "+name) }
  def get(name: CharSequence): Option[String] = Option(nettyHeaders.get(name))

  def getAll(name: CharSequence): Vector[String] = nettyHeaders.getAll(name).asScala.toVector

  def getBool(name: CharSequence): Option[Boolean] = get(name).flatMap{ _.parseBoolean }
  def getDate(name: CharSequence): Option[ImmutableDate] = get(name).flatMap{ parseImmutableDate }
  def getInt(name: CharSequence): Option[Int] = get(name).flatMap{ _.toIntOption }
  def getLong(name: CharSequence): Option[Long] = get(name).flatMap{ _.toLongOption }

  /** A helper to find a client-sent cookie by name */
  def getCookie(name: String): Option[Cookie] = cookies.find{ _.name === name }

  /**
   * If the Host header has a port in it (e.g. frugalmechanic.com:8080) then
   * this will strip it out.
   */
  def hostWithoutPort: Option[String] = host.map { h: String =>
    val idx = h.indexOf(":")
    if(-1 === idx) h else h.substring(0, idx)
  }

  /**
   * The port from the host header (e.g. frugalmechanic.com:8080)
   */
  def hostPort: Option[Int] = host.flatMap { h: String =>
    val idx = h.indexOf(":")
    if(-1 === idx) None else h.substring(idx + 1).toIntOption
  }

  def accept: Option[String] = get(HttpHeaderNames.ACCEPT)
  def acceptCharset: Option[String] = get(HttpHeaderNames.ACCEPT_CHARSET)
  def acceptEncoding: Option[String] = get(HttpHeaderNames.ACCEPT_ENCODING)
  def acceptLanguage: Option[String] = get(HttpHeaderNames.ACCEPT_LANGUAGE)
  def acceptPatch: Option[String] = get(HttpHeaderNames.ACCEPT_PATCH)
  def acceptRanges: Option[String] = get(HttpHeaderNames.ACCEPT_RANGES)
  def accessControlAllowCredentials: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS)
  def accessControlAllowHeaders: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS)
  def accessControlAllowMethods: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS)
  def accessControlAllowOrigin: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN)
  def accessControlExposeHeaders: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS)
  def accessControlMaxAge: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE)
  def accessControlRequestHeaders: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS)
  def accessControlRequestMethod: Option[String] = get(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD)
  def age: Option[Long] = getLong(HttpHeaderNames.AGE)
  def allow: Option[String] = get(HttpHeaderNames.ALLOW)
  def authorization: Option[String] = get(HttpHeaderNames.AUTHORIZATION)
  def cacheControl: Option[String] = get(HttpHeaderNames.CACHE_CONTROL)
  def connection: Option[String] = get(HttpHeaderNames.CONNECTION)
  def contentBase: Option[String] = get(HttpHeaderNames.CONTENT_BASE)
  def contentDisposition: Option[String] = get(HttpHeaderNames.CONTENT_DISPOSITION)
  def contentDispositionAttachmentFileName: Option[String] = contentDisposition.flatMap{ parseContentDispositionAttachmentFileName }
  def contentEncoding: Option[String] = get(HttpHeaderNames.CONTENT_ENCODING)
  def contentLanguage: Option[String] = get(HttpHeaderNames.CONTENT_LANGUAGE)
  def contentLength: Option[Long] = getLong(HttpHeaderNames.CONTENT_LENGTH)
  def contentLocation: Option[String] = get(HttpHeaderNames.CONTENT_LOCATION)
  def contentMD5: Option[String] = get(HttpHeaderNames.CONTENT_MD5)
  def contentRange: Option[String] = get(HttpHeaderNames.CONTENT_RANGE)
  def contentTransferEncoding: Option[String] = get(HttpHeaderNames.CONTENT_TRANSFER_ENCODING)
  def contentType: Option[String] = get(HttpHeaderNames.CONTENT_TYPE)

  /** This is the raw value of the client side cookies that are being sent with the request */
  def cookie: Option[String] = get(HttpHeaderNames.COOKIE)

  /** These are the client side cookies that are being sent with the request */
  def cookies: Vector[Cookie] = cookie.map{ Cookie.tryParseCookieHeader }.getOrElse{ Vector.empty }

  def date: Option[ImmutableDate] = getDate(HttpHeaderNames.DATE)
  def eTag: Option[String] = get(HttpHeaderNames.ETAG)
  def expect: Option[String] = get(HttpHeaderNames.EXPECT)
  def expires: Option[ImmutableDate] = getDate(HttpHeaderNames.EXPIRES)
  def from: Option[String] = get(HttpHeaderNames.FROM)
  def host: Option[String] = get(HttpHeaderNames.HOST)
  def ifMatch: Option[String] = get(HttpHeaderNames.IF_MATCH)
  def ifModifiedSince: Option[ImmutableDate] = getDate(HttpHeaderNames.IF_MODIFIED_SINCE)
  def ifNoneMatch: Option[String] = get(HttpHeaderNames.IF_NONE_MATCH)
  def ifRange: Option[String] = get(HttpHeaderNames.IF_RANGE)
  def ifUnmodifiedSince: Option[ImmutableDate] = getDate(HttpHeaderNames.IF_UNMODIFIED_SINCE)
  def lastModified: Option[ImmutableDate] = getDate(HttpHeaderNames.LAST_MODIFIED)
  def location: Option[String] = get(HttpHeaderNames.LOCATION)
  def maxForwards: Option[String] = get(HttpHeaderNames.MAX_FORWARDS)
  def origin: Option[String] = get(HttpHeaderNames.ORIGIN)
  def pragma: Option[String] = get(HttpHeaderNames.PRAGMA)
  def proxyAuthencate: Option[String] = get(HttpHeaderNames.PROXY_AUTHENTICATE)
  def proxyAuthorization: Option[String] = get(HttpHeaderNames.PROXY_AUTHORIZATION)
  def range: Option[String] = get(HttpHeaderNames.RANGE)
  def referer: Option[String] = get(HttpHeaderNames.REFERER)
  def retryAfter: Option[String] = get(HttpHeaderNames.RETRY_AFTER)
  def secWebSocketAccept: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT)
  def secWebSocketKey: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_KEY)
  def secWebSocketKey1: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_KEY1)
  def secWebSocketKey2: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_KEY2)
  def secWebSocketLocation: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION)
  def secWebSocketOrigin: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)
  def secWebSocketProtocol: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL)
  def secWebSocketVersion: Option[String] = get(HttpHeaderNames.SEC_WEBSOCKET_VERSION)
  def server: Option[String] = get(HttpHeaderNames.SERVER)

  /** This is the raw value of the server side cookies that are being sent with the response */
  def setCookie: Vector[String] = getAll(HttpHeaderNames.SET_COOKIE)

  /** These are the server side cookies that are being sent with the response */
  def setCookies: Vector[Cookie] = setCookie.flatMap{ Cookie.tryParseSetCookieHeader }

  def setCookie2: Vector[String] = getAll(HttpHeaderNames.SET_COOKIE2)
  def te: Option[String] = get(HttpHeaderNames.TE)
  def trailer: Option[String] = get(HttpHeaderNames.TRAILER)
  def transferEncoding: Option[String] = get(HttpHeaderNames.TRANSFER_ENCODING)
  def upgrade: Option[String] = get(HttpHeaderNames.UPGRADE)
  def userAgent: Option[String] = get(HttpHeaderNames.USER_AGENT)
  def vary: Option[String] = get(HttpHeaderNames.VARY)
  def via: Option[String] = get(HttpHeaderNames.VIA)
  def warning: Option[String] = get(HttpHeaderNames.WARNING)
  def webSocketLocation: Option[String] = get(HttpHeaderNames.WEBSOCKET_LOCATION)
  def webSocketOrigin: Option[String] = get(HttpHeaderNames.WEBSOCKET_ORIGIN)
  def webSocketProtocol: Option[String] = get(HttpHeaderNames.WEBSOCKET_PROTOCOL)
  def wwwAuthenticate: Option[String] = get(HttpHeaderNames.WWW_AUTHENTICATE)

  //
  // Non-Standard
  //
  def dnt: Option[String] = get(NonStandardNames.DNT)
  def xSSL: Option[Boolean] = getBool(NonStandardNames.X_SSL)
  def xRequestedWith: Option[String] = get(NonStandardNames.X_REQUESTED_WITH)
  def xForwardedFor: Option[String] = get(NonStandardNames.X_FORWARDED_FOR)
  def xForwardedProto: Option[String] = get(NonStandardNames.X_FORWARDED_PROTO)
  def xForwardedPort: Option[String] = get(NonStandardNames.X_FORWARDED_PORT)
  def xFrameOptions: Option[String] = get(NonStandardNames.X_FRAME_OPTIONS)
  def xXSSProtection: Option[String] = get(NonStandardNames.X_XSS_PROTECTION)
  def xContentTypeOptions: Option[String] = get(NonStandardNames.X_CONTENT_TYPE_OPTIONS)
  def xPoweredBy: Option[String] = get(NonStandardNames.X_POWERED_BY)
  def xUACompatible: Option[String] = get(NonStandardNames.X_UA_COMPATIBLE)

  //
  // Basic Auth helpers
  //

  /**
   * The Basic Auth username and password from the Authorization header
   */
  def basicAuthUserAndPass: Option[(String,String)] = authorization.flatMap{ Headers.parseBasicAuthorization }

  /** The Basic Auth username from the Authorization header */
  def basicAuthUser: Option[String] = basicAuthUserAndPass.map{ _._1 }

  /** The Basic Auth password from the Authorization header */
  def basicAuthPass: Option[String] = basicAuthUserAndPass.map{ _._2 }

  //
  // Digest Auth Helpers
  //

  def digestAuthParams: Option[Map[String,String]] = digestAuthParamsWWWAuthenticate orElse digestAuthParamsAuthorization

  def digestAuthParamsWWWAuthenticate: Option[Map[String,String]] = wwwAuthenticate.flatMap{ Headers.parseDigestAuthParams }
  def digestAuthParamsAuthorization: Option[Map[String,String]] = authorization.flatMap{ Headers.parseDigestAuthParams }

  def digestAuthUser: Option[String] = digestAuthParams.flatMap{ _.get("username") }

  //
  // Misc Auth Helpers
  //

  /** Either the Basic or Digest auth username from the Authorization header */
  def authUser: Option[String] = basicAuthUser orElse digestAuthUser
}

final case class ImmutableHeaders(nettyHeaders: HttpHeaders) extends Headers {
  def withHeaders(headerValues: (CharSequence, Any)*): ImmutableHeaders = toMutableHeaders.withHeaders(headerValues:_*).toImmutableHeaders

  def withNoCache: ImmutableHeaders = toMutableHeaders.withNoCache.toImmutableHeaders

  def withCookies(c: Traversable[Cookie]): ImmutableHeaders = {
    val m = toMutableHeaders
    m.cookies = c
    m.toImmutableHeaders
  }

  def withSetCookies(c: Traversable[Cookie]): ImmutableHeaders = {
    val m = toMutableHeaders
    m.setCookies = c
    m.toImmutableHeaders
  }
}

final case class MutableHeaders(nettyHeaders: HttpHeaders = new DefaultHttpHeaders(false /* don't validate */)) extends Headers {
  import Headers._

  def add(name: CharSequence, value: String): Unit = add(name, Option(value))

  def add(name: CharSequence, value: Option[String]): Unit = value match {
    case Some(v) => nettyHeaders.add(name, v)
    case None    => // Don't add
  }

  def set(name: CharSequence, value: String): Unit = set(name, Option(value))

  def set(name: CharSequence, value: Option[String]): Unit = value match {
    case Some(v) => nettyHeaders.set(name, v)
    case None    => nettyHeaders.remove(name)
  }

  def setAll(name: CharSequence, values: Traversable[String]): Unit = {
    nettyHeaders.remove(name)
    values.foreach{ add(name, _) }
  }

  def setAll(name: CharSequence, values: Option[Traversable[String]]): Unit = setAll(name, values.getOrElse{ Nil })

  def setDate(name: CharSequence, value: Date): Unit = setDate(name, Option(value))
  def setDate(name: CharSequence, value: Option[Date]): Unit = set(name, value.map{ formatDate })

  def setImmutableDate(name: CharSequence, value: ImmutableDate): Unit = setImmutableDate(name, Option(value))
  def setImmutableDate(name: CharSequence, value: Option[ImmutableDate]): Unit = set(name, value.map{ formatDate })

  def setOffsetDateTime(name: CharSequence, value: OffsetDateTime): Unit = setOffsetDateTime(name, Option(value))
  def setOffsetDateTime(name: CharSequence, value: Option[OffsetDateTime]): Unit = set(name, value.map{ formatDate })

  def setZonedDateDate(name: CharSequence, value: ZonedDateTime): Unit = setZonedDateDate(name, Option(value))
  def setZonedDateDate(name: CharSequence, value: Option[ZonedDateTime]): Unit = set(name, value.map{ formatDate })

  def setInstant(name: CharSequence, value: Instant): Unit = setInstant(name, Option(value))
  def setInstant(name: CharSequence, value: Option[Instant]): Unit = set(name, value.map{ formatDate })

  def setLocalDateTime(name: CharSequence, value: LocalDateTime): Unit = setLocalDateTime(name, Option(value))
  def setLocalDateTime(name: CharSequence, value: Option[LocalDateTime]): Unit = set(name, value.map{ formatDate })

  def setInt(name: CharSequence, value: Int): Unit = set(name, value.toString)
  def setInt(name: CharSequence, value: Option[Int]): Unit = set(name, value.map{ _.toString })

  def setLong(name: CharSequence, value: Long): Unit = set(name, value.toString)
  def setLong(name: CharSequence, value: Option[Long]): Unit = set(name, value.map{ _.toString })

  def remove(name: String): Unit = nettyHeaders.remove(name)

  def withHeaders(headerValues: (CharSequence, Any)*): MutableHeaders = {
    headerValues.foreach { case (name, value) =>
      value match {
        case str: String => set(name, str)
        case date: Date => setDate(name, date)
        case date: ImmutableDate => setImmutableDate(name, date)
        case date: OffsetDateTime => setOffsetDateTime(name, date)
        case date: ZonedDateTime => setZonedDateDate(name, date)
        case date: Instant => setInstant(name, date)
        case date: LocalDateTime => setLocalDateTime(name, date)
        case int: Int => setInt(name, int)
        case long: Long => setLong(name, long)
        case _ => throw new IllegalArgumentException("Unknown Headers value type: "+value)
      }
    }

    this
  }

  def withNoCache: MutableHeaders = {
    // http://stackoverflow.com/a/2068407
    cacheControl = "no-cache, no-store, must-revalidate"
    pragma = "no-cache"
    expires = "0"
    this
  }

  def withCookies(c: Traversable[Cookie]): MutableHeaders = {
    cookies = c
    this
  }

  def withSetCookies(c: Traversable[Cookie]): MutableHeaders = {
    setCookies = c
    this
  }

  def accept_=(v: String): Unit = set(HttpHeaderNames.ACCEPT, v)
  def accept_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT, v)

  def acceptCharset_=(v: String): Unit = set(HttpHeaderNames.ACCEPT_CHARSET, v)
  def acceptCharset_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT_CHARSET, v)

  def acceptEncoding_=(v: String): Unit = set(HttpHeaderNames.ACCEPT_ENCODING, v)
  def acceptEncoding_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT_ENCODING, v)

  def acceptLanguage_=(v: String): Unit = set(HttpHeaderNames.ACCEPT_LANGUAGE, v)
  def acceptLanguage_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT_LANGUAGE, v)

  def acceptPatch_=(v: String): Unit = set(HttpHeaderNames.ACCEPT_PATCH, v)
  def acceptPatch_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT_PATCH, v)

  def acceptRanges_=(v: String): Unit = set(HttpHeaderNames.ACCEPT_RANGES, v)
  def acceptRanges_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCEPT_RANGES, v)

  def accessControlAllowCredentials_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, v)
  def accessControlAllowCredentials_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, v)

  def accessControlAllowHeaders_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, v)
  def accessControlAllowHeaders_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, v)

  def accessControlAllowMethods_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, v)
  def accessControlAllowMethods_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, v)

  def accessControlAllowOrigin_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, v)
  def accessControlAllowOrigin_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, v)

  def accessControlExposeHeaders_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, v)
  def accessControlExposeHeaders_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, v)

  def accessControlMaxAge_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, v)
  def accessControlMaxAge_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, v)

  def accessControlRequestHeaders_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS, v)
  def accessControlRequestHeaders_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS, v)

  def accessControlRequestMethod_=(v: String): Unit = set(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD, v)
  def accessControlRequestMethod_=(v: Option[String]): Unit = set(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD, v)

  def age_=(v: Long): Unit = setLong(HttpHeaderNames.AGE, v)
  def age_=(v: Option[Long]): Unit = setLong(HttpHeaderNames.AGE, v)

  def allow_=(v: String): Unit = set(HttpHeaderNames.ALLOW, v)
  def allow_=(v: Option[String]): Unit = set(HttpHeaderNames.ALLOW, v)

  def authorization_=(v: String): Unit = set(HttpHeaderNames.AUTHORIZATION, v)
  def authorization_=(v: Option[String]): Unit = set(HttpHeaderNames.AUTHORIZATION, v)

  def cacheControl_=(v: String): Unit = set(HttpHeaderNames.CACHE_CONTROL, v)
  def cacheControl_=(v: Option[String]): Unit = set(HttpHeaderNames.CACHE_CONTROL, v)

  def connection_=(v: String): Unit = set(HttpHeaderNames.CONNECTION, v)
  def connection_=(v: Option[String]): Unit = set(HttpHeaderNames.CONNECTION, v)

  def contentBase_=(v: String): Unit = set(HttpHeaderNames.CONTENT_BASE, v)
  def contentBase_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_BASE, v)

  def contentDisposition_=(v: String): Unit = set(HttpHeaderNames.CONTENT_DISPOSITION, v)
  def contentDisposition_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_DISPOSITION, v)

  def contentDispositionAttachmentFileName_=(v: String): Unit = contentDisposition = makeContentDispositionAttachmentWithFileName(v)
  def contentDispositionAttachmentFileName_=(v: Option[String]): Unit = contentDisposition = v.map{ makeContentDispositionAttachmentWithFileName }

  def contentEncoding_=(v: String): Unit = set(HttpHeaderNames.CONTENT_ENCODING, v)
  def contentEncoding_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_ENCODING, v)

  def contentLanguage_=(v: String): Unit = set(HttpHeaderNames.CONTENT_LANGUAGE, v)
  def contentLanguage_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_LANGUAGE, v)

  def contentLength_=(v: Long): Unit = setLong(HttpHeaderNames.CONTENT_LENGTH, v)
  def contentLength_=(v: Option[Long]): Unit = setLong(HttpHeaderNames.CONTENT_LENGTH, v)

  def contentLocation_=(v: String): Unit = set(HttpHeaderNames.CONTENT_LOCATION, v)
  def contentLocation_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_LOCATION, v)

  def contentMD5_=(v: String): Unit = set(HttpHeaderNames.CONTENT_MD5, v)
  def contentMD5_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_MD5, v)

  def contentRange_=(v: String): Unit = set(HttpHeaderNames.CONTENT_RANGE, v)
  def contentRange_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_RANGE, v)

  def contentTransferEncoding_=(v: String): Unit = set(HttpHeaderNames.CONTENT_TRANSFER_ENCODING, v)
  def contentTransferEncoding_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_TRANSFER_ENCODING, v)

  def contentType_=(v: String): Unit = set(HttpHeaderNames.CONTENT_TYPE, v)
  def contentType_=(v: Option[String]): Unit = set(HttpHeaderNames.CONTENT_TYPE, v)

  def cookie_=(v: String): Unit = set(HttpHeaderNames.COOKIE, v)
  def cookie_=(v: Option[String]): Unit = set(HttpHeaderNames.COOKIE, v)

  def cookies_=(v: Traversable[Cookie]): Unit = cookie = if (v.nonEmpty) Some(ClientCookieEncoder.LAX.encode(v.toSeq.map{ _.toNettyCookie }.asJava)) else None
  def cookies_=(v: Option[Traversable[Cookie]]): Unit = cookies = v.getOrElse{ Nil }

  def date_=(v: ImmutableDate): Unit = setImmutableDate(HttpHeaderNames.DATE, v)
  def date_=(v: Option[ImmutableDate]): Unit = setImmutableDate(HttpHeaderNames.DATE, v)

  def eTag_=(v: String): Unit = set(HttpHeaderNames.ETAG, v)
  def eTag_=(v: Option[String]): Unit = set(HttpHeaderNames.ETAG, v)

  def expect_=(v: String): Unit = set(HttpHeaderNames.EXPECT, v)
  def expect_=(v: Option[String]): Unit = set(HttpHeaderNames.EXPECT, v)

  def expires_=(v: String): Unit = set(HttpHeaderNames.EXPIRES, v)
  def expires_=(v: ImmutableDate): Unit = setImmutableDate(HttpHeaderNames.EXPIRES, v)
  def expires_=(v: Option[ImmutableDate]): Unit = setImmutableDate(HttpHeaderNames.EXPIRES, v)

  def from_=(v: String): Unit = set(HttpHeaderNames.FROM, v)
  def from_=(v: Option[String]): Unit = set(HttpHeaderNames.FROM, v)

  def host_=(v: String): Unit = set(HttpHeaderNames.HOST, v)
  def host_=(v: Option[String]): Unit = set(HttpHeaderNames.HOST, v)

  def ifMatch_=(v: String): Unit = set(HttpHeaderNames.IF_MATCH, v)
  def ifMatch_=(v: Option[String]): Unit = set(HttpHeaderNames.IF_MATCH, v)

  def ifModifiedSince_=(v: ImmutableDate): Unit = setImmutableDate(HttpHeaderNames.IF_MODIFIED_SINCE, v)
  def ifModifiedSince_=(v: Option[ImmutableDate]): Unit = setImmutableDate(HttpHeaderNames.IF_MODIFIED_SINCE, v)

  def ifNoneMatch_=(v: String): Unit = set(HttpHeaderNames.IF_NONE_MATCH, v)
  def ifNoneMatch_=(v: Option[String]): Unit = set(HttpHeaderNames.IF_NONE_MATCH, v)

  def ifRange_=(v: String): Unit = set(HttpHeaderNames.IF_RANGE, v)
  def ifRange_=(v: Option[String]): Unit = set(HttpHeaderNames.IF_RANGE, v)

  def ifUnmodifiedSince_=(v: ImmutableDate): Unit = setImmutableDate(HttpHeaderNames.IF_UNMODIFIED_SINCE, v)
  def ifUnmodifiedSince_=(v: Option[ImmutableDate]): Unit = setImmutableDate(HttpHeaderNames.IF_UNMODIFIED_SINCE, v)

  def lastModified_=(v: ImmutableDate): Unit = setImmutableDate(HttpHeaderNames.LAST_MODIFIED, v)
  def lastModified_=(v: Option[ImmutableDate]): Unit = setImmutableDate(HttpHeaderNames.LAST_MODIFIED, v)

  def location_=(v: String): Unit = set(HttpHeaderNames.LOCATION, v)
  def location_=(v: Option[String]): Unit = set(HttpHeaderNames.LOCATION, v)

  def maxForwards_=(v: String): Unit = set(HttpHeaderNames.MAX_FORWARDS, v)
  def maxForwards_=(v: Option[String]): Unit = set(HttpHeaderNames.MAX_FORWARDS, v)

  def origin_=(v: String): Unit = set(HttpHeaderNames.ORIGIN, v)
  def origin_=(v: Option[String]): Unit = set(HttpHeaderNames.ORIGIN, v)

  def pragma_=(v: String): Unit = set(HttpHeaderNames.PRAGMA, v)
  def pragma_=(v: Option[String]): Unit = set(HttpHeaderNames.PRAGMA, v)

  def proxyAuthencate_=(v: String): Unit = set(HttpHeaderNames.PROXY_AUTHENTICATE, v)
  def proxyAuthencate_=(v: Option[String]): Unit = set(HttpHeaderNames.PROXY_AUTHENTICATE, v)

  def proxyAuthorization_=(v: String): Unit = set(HttpHeaderNames.PROXY_AUTHORIZATION, v)
  def proxyAuthorization_=(v: Option[String]): Unit = set(HttpHeaderNames.PROXY_AUTHORIZATION, v)

  def range_=(v: String): Unit = set(HttpHeaderNames.RANGE, v)
  def range_=(v: Option[String]): Unit = set(HttpHeaderNames.RANGE, v)

  def referer_=(v: String): Unit = set(HttpHeaderNames.REFERER, v)
  def referer_=(v: Option[String]): Unit = set(HttpHeaderNames.REFERER, v)

  def retryAfter_=(v: String): Unit = set(HttpHeaderNames.RETRY_AFTER, v)
  def retryAfter_=(v: Option[String]): Unit = set(HttpHeaderNames.RETRY_AFTER, v)

  def secWebSocketAccept_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, v)
  def secWebSocketAccept_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, v)

  def secWebSocketKey_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY, v)
  def secWebSocketKey_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY, v)

  def secWebSocketKey1_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, v)
  def secWebSocketKey1_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, v)

  def secWebSocketKey2_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, v)
  def secWebSocketKey2_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, v)

  def secWebSocketLocation_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, v)
  def secWebSocketLocation_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, v)

  def secWebSocketOrigin_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, v)
  def secWebSocketOrigin_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, v)

  def secWebSocketProtocol_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, v)
  def secWebSocketProtocol_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, v)

  def secWebSocketVersion_=(v: String): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, v)
  def secWebSocketVersion_=(v: Option[String]): Unit = set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, v)

  def server_=(v: String): Unit = set(HttpHeaderNames.SERVER, v)
  def server_=(v: Option[String]): Unit = set(HttpHeaderNames.SERVER, v)

  def setCookie_=(v: Traversable[String]): Unit = setAll(HttpHeaderNames.SET_COOKIE, v)
  def setCookie_=(v: Option[Traversable[String]]): Unit = setAll(HttpHeaderNames.SET_COOKIE, v)

  def setCookies_=(v: Traversable[Cookie]): Unit = setCookie = if (v.nonEmpty) Some(v.toSeq.map{ c: Cookie => ServerCookieEncoder.LAX.encode(c.toNettyCookie) }) else None
  def setCookies_=(v: Option[Traversable[Cookie]]): Unit = setCookies = v.getOrElse{ Nil }

  def setCookie2_=(v: Traversable[String]): Unit = setAll(HttpHeaderNames.SET_COOKIE2, v)
  def setCookie2_=(v: Option[Traversable[String]]): Unit = setAll(HttpHeaderNames.SET_COOKIE2, v)

  def te_=(v: String): Unit = set(HttpHeaderNames.TE, v)
  def te_=(v: Option[String]): Unit = set(HttpHeaderNames.TE, v)

  def trailer_=(v: String): Unit = set(HttpHeaderNames.TRAILER, v)
  def trailer_=(v: Option[String]): Unit = set(HttpHeaderNames.TRAILER, v)

  def transferEncoding_=(v: String): Unit = set(HttpHeaderNames.TRANSFER_ENCODING, v)
  def transferEncoding_=(v: Option[String]): Unit = set(HttpHeaderNames.TRANSFER_ENCODING, v)

  def upgrade_=(v: String): Unit = set(HttpHeaderNames.UPGRADE, v)
  def upgrade_=(v: Option[String]): Unit = set(HttpHeaderNames.UPGRADE, v)

  def userAgent_=(v: String): Unit = set(HttpHeaderNames.USER_AGENT, v)
  def userAgent_=(v: Option[String]): Unit = set(HttpHeaderNames.USER_AGENT, v)

  def vary_=(v: String): Unit = set(HttpHeaderNames.VARY, v)
  def vary_=(v: Option[String]): Unit = set(HttpHeaderNames.VARY, v)

  def via_=(v: String): Unit = set(HttpHeaderNames.VIA, v)
  def via_=(v: Option[String]): Unit = set(HttpHeaderNames.VIA, v)

  def warning_=(v: String): Unit = set(HttpHeaderNames.WARNING, v)
  def warning_=(v: Option[String]): Unit = set(HttpHeaderNames.WARNING, v)

  def webSocketLocation_=(v: String): Unit = set(HttpHeaderNames.WEBSOCKET_LOCATION, v)
  def webSocketLocation_=(v: Option[String]): Unit = set(HttpHeaderNames.WEBSOCKET_LOCATION, v)

  def webSocketOrigin_=(v: String): Unit = set(HttpHeaderNames.WEBSOCKET_ORIGIN, v)
  def webSocketOrigin_=(v: Option[String]): Unit = set(HttpHeaderNames.WEBSOCKET_ORIGIN, v)

  def webSocketProtocol_=(v: String): Unit = set(HttpHeaderNames.WEBSOCKET_PROTOCOL, v)
  def webSocketProtocol_=(v: Option[String]): Unit = set(HttpHeaderNames.WEBSOCKET_PROTOCOL, v)

  def wwwAuthenticate_=(v: String): Unit = set(HttpHeaderNames.WWW_AUTHENTICATE, v)
  def wwwAuthenticate_=(v: Option[String]): Unit = set(HttpHeaderNames.WWW_AUTHENTICATE, v)

  //
  // Non-Standard
  //
  def dnt_=(v: String): Unit = set(NonStandardNames.DNT, v)
  def dnt_=(v: Option[String]): Unit = set(NonStandardNames.DNT, v)

  def xRequestedWith_=(v: String): Unit = set(NonStandardNames.X_REQUESTED_WITH, v)
  def xRequestedWith_=(v: Option[String]): Unit = set(NonStandardNames.X_REQUESTED_WITH, v)

  def xForwardedFor_=(v: String): Unit = set(NonStandardNames.X_FORWARDED_FOR, v)
  def xForwardedFor_=(v: Option[String]): Unit = set(NonStandardNames.X_FORWARDED_FOR, v)

  def xForwardedProto_=(v: String): Unit = set(NonStandardNames.X_FORWARDED_PROTO, v)
  def xForwardedProto_=(v: Option[String]): Unit = set(NonStandardNames.X_FORWARDED_PROTO, v)

  def xFrameOptions_=(v: String): Unit = set(NonStandardNames.X_FRAME_OPTIONS, v)
  def xFrameOptions_=(v: Option[String]): Unit = set(NonStandardNames.X_FRAME_OPTIONS, v)

  def xXSSProtection_=(v: String): Unit = set(NonStandardNames.X_XSS_PROTECTION, v)
  def xXSSProtection_=(v: Option[String]): Unit = set(NonStandardNames.X_XSS_PROTECTION, v)

  def xContentTypeOptions_=(v: String): Unit = set(NonStandardNames.X_CONTENT_TYPE_OPTIONS, v)
  def xContentTypeOptions_=(v: Option[String]): Unit = set(NonStandardNames.X_CONTENT_TYPE_OPTIONS, v)

  def xPoweredBy_=(v: String): Unit = set(NonStandardNames.X_POWERED_BY, v)
  def xPoweredBy_=(v: Option[String]): Unit = set(NonStandardNames.X_POWERED_BY, v)

  def xUACompatible_=(v: String): Unit = set(NonStandardNames.X_UA_COMPATIBLE, v)
  def xUACompatible_=(v: Option[String]): Unit = set(NonStandardNames.X_UA_COMPATIBLE, v)

  //
  // Private Helpers
  //

  private def makeContentDispositionAttachmentWithFileName(v: String): String = {
    val escapedName: String = v.replace("\"", "\\\"") // Replace " with \"
    s"""attachment; filename="$escapedName""""
  }
}


text:
$packageName = 'adwcleaner'
$url = 'http://files01.techspot.com/temp/adwcleaner.exe'
$fileFullPath = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)\adwcleaner.exe"

Get-ChocolateyWebFile $packageName $fileFullPath $url

Install-ChocolateyDesktopLink $fileFullPath

redpajama_set_name: RedPajamaGithub


text:
package org.adligo.tests4j.system.shared.trials;

/**
 * The data for IgnoreTest and IgnoreTrial, to make ignoring tests and trials
 * harder to do, and to provide more information about a test or trial
 * which is in progress.
 * @author scott
 *
 */
public @interface Ignored {
  /**
   * The name of the person who ignored the
   * test.
   * TODO make this required when reading annotations.
   * @return
   */
  String ignoredBy();
  /**
   * The date of when the test was ignored
   * in the format YYYY-MM-DD.
   * TODO make this required when reading annotations.
   * @return
   */
  String ignoredOn();
  /**
   * The name of the person who is working on the
   * test, this is a optional value and defaluts
   * to the ignroedBy value.
   * @return
   */
  String developer() default "default";
  /**
   * The date of when the test was is expected to be completed
   * in the format YYYY-MM-DD. This is a optional value.
   * TODO have test4j print a warning list of ignored items that
   * are expected to be completed in 3 days.
   * Also have tests4j fail the test or trial when the current date is past
   * the expectedOn value.
   * @return
   */
  String expectedOn() default "default";
}


text:
<?php
namespace BeGateway;

abstract class ResponseBase {

  protected $_response;
  protected $_responseArray;

  public function __construct($message){
    $this->_response = json_decode($message);
    $this->_responseArray = json_decode($message, true);
  }
  public abstract function isSuccess();

  public function isError() {
    if (!is_object($this->getResponse()))
      return true;

    if (isset($this->getResponse()->errors))
      return true;

    if (isset($this->getResponse()->response))
      return true;

    return false;
  }

  public function isValid() {
    return !($this->_response === false || $this->_response == null);
  }

  public function getResponse() {
    return $this->_response;
  }

  public function getResponseArray() {
    return $this->_responseArray;
  }

}
?>


text:
<?php

namespace Acme\Bundle\TestBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClientsType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('clientName')
        ;

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\Bundle\TestBundle\Entity\Clients'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_bundle_testbundle_clients';
    }
}


text:
set -e

# if we have "--link some-docker:docker" and not DOCKER_HOST, let's set DOCKER_HOST automatically
if [ -z "${DOCKER_HOST}" -a "${DOCKER_PORT_2375_TCP}" ]; then
	export DOCKER_HOST='tcp://docker:2375'
fi

exec "$@"


text:
package pubsub

import (
	"context"
	"errors"
	"fmt"

	"github.com/tendermint/tendermint/libs/service"
	tmsync "github.com/tendermint/tendermint/libs/sync"
)

type operation int

const (
	sub operation = iota
	pub
	unsub
	shutdown
)

var (
	// ErrSubscriptionNotFound is returned when a client tries to unsubscribe
	// from not existing subscription.
	ErrSubscriptionNotFound = errors.New("subscription not found")

	// ErrAlreadySubscribed is returned when a client tries to subscribe twice or
	// more using the same query.
	ErrAlreadySubscribed = errors.New("already subscribed")
)

// Query defines an interface for a query to be used for subscribing. A query
// matches against a map of events. Each key in this map is a composite of the
// even type and an attribute key (e.g. "{eventType}.{eventAttrKey}") and the
// values are the event values that are contained under that relationship. This
// allows event types to repeat themselves with the same set of keys and
// different values.
type Query interface {
	Matches(events map[string][]string) (bool, error)
	String() string
}

type cmd struct {
	op operation

	// subscribe, unsubscribe
	query        Query
	subscription *Subscription
	clientID     string

	// publish
	msg    interface{}
	events map[string][]string
}

// Server allows clients to subscribe/unsubscribe for messages, publishing
// messages with or without events, and manages internal state.
type Server struct {
	service.BaseService

	cmds    chan cmd
	cmdsCap int

	// check if we have subscription before
	// subscribing or unsubscribing
	mtx           tmsync.RWMutex
	subscriptions map[string]map[string]struct{} // subscriber -> query (string) -> empty struct
}

// Option sets a parameter for the server.
type Option func(*Server)

// NewServer returns a new server. See the commentary on the Option functions
// for a detailed description of how to configure buffering. If no options are
// provided, the resulting server's queue is unbuffered.
func NewServer(options ...Option) *Server {
	s := &Server{
		subscriptions: make(map[string]map[string]struct{}),
	}
	s.BaseService = *service.NewBaseService(nil, "PubSub", s)

	for _, option := range options {
		option(s)
	}

	// if BufferCapacity option was not set, the channel is unbuffered
	s.cmds = make(chan cmd, s.cmdsCap)

	return s
}

// BufferCapacity allows you to specify capacity for the internal server's
// queue. Since the server, given Y subscribers, could only process X messages,
// this option could be used to survive spikes (e.g. high amount of
// transactions during peak hours).
func BufferCapacity(cap int) Option {
	return func(s *Server) {
		if cap > 0 {
			s.cmdsCap = cap
		}
	}
}

// BufferCapacity returns capacity of the internal server's queue.
func (s *Server) BufferCapacity() int {
	return s.cmdsCap
}

// Subscribe creates a subscription for the given client.
//
// An error will be returned to the caller if the context is canceled or if
// subscription already exist for pair clientID and query.
//
// outCapacity can be used to set a capacity for Subscription#Out channel (1 by
// default). Panics if outCapacity is less than or equal to zero. If you want
// an unbuffered channel, use SubscribeUnbuffered.
func (s *Server) Subscribe(
	ctx context.Context,
	clientID string,
	query Query,
	outCapacity ...int) (*Subscription, error) {
	outCap := 1
	if len(outCapacity) > 0 {
		if outCapacity[0] <= 0 {
			panic("Negative or zero capacity. Use SubscribeUnbuffered if you want an unbuffered channel")
		}
		outCap = outCapacity[0]
	}

	return s.subscribe(ctx, clientID, query, outCap)
}

// SubscribeUnbuffered does the same as Subscribe, except it returns a
// subscription with unbuffered channel. Use with caution as it can freeze the
// server.
func (s *Server) SubscribeUnbuffered(ctx context.Context, clientID string, query Query) (*Subscription, error) {
	return s.subscribe(ctx, clientID, query, 0)
}

func (s *Server) subscribe(ctx context.Context, clientID string, query Query, outCapacity int) (*Subscription, error) {
	s.mtx.RLock()
	clientSubscriptions, ok := s.subscriptions[clientID]
	if ok {
		_, ok = clientSubscriptions[query.String()]
	}
	s.mtx.RUnlock()
	if ok {
		return nil, ErrAlreadySubscribed
	}

	subscription := NewSubscription(outCapacity)
	select {
	case s.cmds <- cmd{op: sub, clientID: clientID, query: query, subscription: subscription}:
		s.mtx.Lock()
		if _, ok = s.subscriptions[clientID]; !ok {
			s.subscriptions[clientID] = make(map[string]struct{})
		}
		s.subscriptions[clientID][query.String()] = struct{}{}
		s.mtx.Unlock()
		return subscription, nil
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-s.Quit():
		return nil, errors.New("service is shutting down")
	}
}

// Unsubscribe removes the subscription on the given query. An error will be
// returned to the caller if the context is canceled or if subscription does
// not exist.
func (s *Server) Unsubscribe(ctx context.Context, clientID string, query Query) error {
	s.mtx.RLock()
	clientSubscriptions, ok := s.subscriptions[clientID]
	if ok {
		_, ok = clientSubscriptions[query.String()]
	}
	s.mtx.RUnlock()
	if !ok {
		return ErrSubscriptionNotFound
	}

	select {
	case s.cmds <- cmd{op: unsub, clientID: clientID, query: query}:
		s.mtx.Lock()
		delete(clientSubscriptions, query.String())
		if len(clientSubscriptions) == 0 {
			delete(s.subscriptions, clientID)
		}
		s.mtx.Unlock()
		return nil
	case <-ctx.Done():
		return ctx.Err()
	case <-s.Quit():
		return nil
	}
}

// UnsubscribeAll removes all client subscriptions. An error will be returned
// to the caller if the context is canceled or if subscription does not exist.
func (s *Server) UnsubscribeAll(ctx context.Context, clientID string) error {
	s.mtx.RLock()
	_, ok := s.subscriptions[clientID]
	s.mtx.RUnlock()
	if !ok {
		return ErrSubscriptionNotFound
	}

	select {
	case s.cmds <- cmd{op: unsub, clientID: clientID}:
		s.mtx.Lock()
		delete(s.subscriptions, clientID)
		s.mtx.Unlock()
		return nil
	case <-ctx.Done():
		return ctx.Err()
	case <-s.Quit():
		return nil
	}
}

// NumClients returns the number of clients.
func (s *Server) NumClients() int {
	s.mtx.RLock()
	defer s.mtx.RUnlock()
	return len(s.subscriptions)
}

// NumClientSubscriptions returns the number of subscriptions the client has.
func (s *Server) NumClientSubscriptions(clientID string) int {
	s.mtx.RLock()
	defer s.mtx.RUnlock()
	return len(s.subscriptions[clientID])
}

// Publish publishes the given message. An error will be returned to the caller
// if the context is canceled.
func (s *Server) Publish(ctx context.Context, msg interface{}) error {
	return s.PublishWithEvents(ctx, msg, make(map[string][]string))
}

// PublishWithEvents publishes the given message with the set of events. The set
// is matched with clients queries. If there is a match, the message is sent to
// the client.
func (s *Server) PublishWithEvents(ctx context.Context, msg interface{}, events map[string][]string) error {
	select {
	case s.cmds <- cmd{op: pub, msg: msg, events: events}:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	case <-s.Quit():
		return nil
	}
}

// OnStop implements Service.OnStop by shutting down the server.
func (s *Server) OnStop() {
	s.cmds <- cmd{op: shutdown}
}

// NOTE: not goroutine safe
type state struct {
	// query string -> client -> subscription
	subscriptions map[string]map[string]*Subscription
	// query string -> queryPlusRefCount
	queries map[string]*queryPlusRefCount
}

// queryPlusRefCount holds a pointer to a query and reference counter. When
// refCount is zero, query will be removed.
type queryPlusRefCount struct {
	q        Query
	refCount int
}

// OnStart implements Service.OnStart by starting the server.
func (s *Server) OnStart() error {
	go s.loop(state{
		subscriptions: make(map[string]map[string]*Subscription),
		queries:       make(map[string]*queryPlusRefCount),
	})
	return nil
}

// OnReset implements Service.OnReset
func (s *Server) OnReset() error {
	return nil
}

func (s *Server) loop(state state) {
loop:
	for cmd := range s.cmds {
		switch cmd.op {
		case unsub:
			if cmd.query != nil {
				state.remove(cmd.clientID, cmd.query.String(), ErrUnsubscribed)
			} else {
				state.removeClient(cmd.clientID, ErrUnsubscribed)
			}
		case shutdown:
			state.removeAll(nil)
			break loop
		case sub:
			state.add(cmd.clientID, cmd.query, cmd.subscription)
		case pub:
			if err := state.send(cmd.msg, cmd.events); err != nil {
				s.Logger.Error("Error querying for events", "err", err)
			}
		}
	}
}

func (state *state) add(clientID string, q Query, subscription *Subscription) {
	qStr := q.String()

	// initialize subscription for this client per query if needed
	if _, ok := state.subscriptions[qStr]; !ok {
		state.subscriptions[qStr] = make(map[string]*Subscription)
	}
	// create subscription
	state.subscriptions[qStr][clientID] = subscription

	// initialize query if needed
	if _, ok := state.queries[qStr]; !ok {
		state.queries[qStr] = &queryPlusRefCount{q: q, refCount: 0}
	}
	// increment reference counter
	state.queries[qStr].refCount++
}

func (state *state) remove(clientID string, qStr string, reason error) {
	clientSubscriptions, ok := state.subscriptions[qStr]
	if !ok {
		return
	}

	subscription, ok := clientSubscriptions[clientID]
	if !ok {
		return
	}

	subscription.cancel(reason)

	// remove client from query map.
	// if query has no other clients subscribed, remove it.
	delete(state.subscriptions[qStr], clientID)
	if len(state.subscriptions[qStr]) == 0 {
		delete(state.subscriptions, qStr)
	}

	// decrease ref counter in queries
	state.queries[qStr].refCount--
	// remove the query if nobody else is using it
	if state.queries[qStr].refCount == 0 {
		delete(state.queries, qStr)
	}
}

func (state *state) removeClient(clientID string, reason error) {
	for qStr, clientSubscriptions := range state.subscriptions {
		if _, ok := clientSubscriptions[clientID]; ok {
			state.remove(clientID, qStr, reason)
		}
	}
}

func (state *state) removeAll(reason error) {
	for qStr, clientSubscriptions := range state.subscriptions {
		for clientID := range clientSubscriptions {
			state.remove(clientID, qStr, reason)
		}
	}
}

func (state *state) send(msg interface{}, events map[string][]string) error {
	for qStr, clientSubscriptions := range state.subscriptions {
		q := state.queries[qStr].q

		match, err := q.Matches(events)
		if err != nil {
			return fmt.Errorf("failed to match against query %s: %w", q.String(), err)
		}

		if match {
			for clientID, subscription := range clientSubscriptions {
				if cap(subscription.out) == 0 {
					// block on unbuffered channel
					subscription.out <- NewMessage(msg, events)
				} else {
					// don't block on buffered channels
					select {
					case subscription.out <- NewMessage(msg, events):
					default:
						state.remove(clientID, qStr, ErrOutOfCapacity)
					}
				}
			}
		}
	}

	return nil
}


text:
"""Status

nagios config:
use       regular-service
params    $HOSTNAME$
"""

from greplin.nagios import parseArgs, Maximum, ResponseBuilder
import time

def check(argv):
  """Runs the check."""
  _ = parseArgs('check_slow.py', ('NAME', str), argv=argv)
  time.sleep(5)

  (ResponseBuilder().addRule('harrypotter', Maximum(42, 108), 69)).finish()

if __name__ == '__main__':
  import sys
  check(sys.argv)


text:
.. Buzzword Bingo API Server documentation master file, created by
   sphinx-quickstart on Wed Apr 11 13:53:21 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Buzzword Bingo API Server's documentation!
=====================================================

Contents:

.. toctree::
   :maxdepth: 2

   modules
   todo

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="color_primary">#48C2AE</color>
    <color name="color_primary_dark">#23776B</color>
    <color name="color_accent">#48C2AE</color>
    <color name="white">#FFFFFF</color>
    <color name="gray">#999</color>
    <color name="light_gray">#ccc</color>
    <color name="lighter_gray">#e0e0e0</color>
    <color name="dark_gray">#444</color>
</resources>


text:
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d
from theano.tensor.signal import pool

def elu(x, alpha=1.0):
	return T.switch(x > 0, x, T.exp(x)-1)

def l2_reg(x, lmbd=0.05):
	"""
	L_2 regularization

	Parameters
	----------

	returns
	----------
	"""

	l2 = 0
	for elements in x:
		l2 += T.sum(elements[0]**2)

	return lmbd / 2 * l2

class ConvLayer(object):
	"""
	Performs a convolution on an input layer.

	Parameters
	----------
	:type input: theano.tensor.dtensor4
	:param input: symbolic image tensor, of shape image_shape

	:type filter_shape: tuple or list of length 4
	:param filter_shape: (number of filters, num input feature maps,
						  filter height, filter width)

	:type image_shape: tuple or list of length 4
	:param image_shape: (batch size, num input feature maps,
						 image height, image width)

	:type padding: tuple or list of length 2
	:param padding:

	:type stride: tuple or list of length 2
	:param stride:

	:type activation_fn: theano.Op or function
	:param activation_fn: Non linearity to be applied in the hidden
						  layer (sigmoid, tanh, relu, elu)

	References
	----------
    .. [1] http://deeplearning.net/tutorial/lenet.html
    .. [2] http://neuralnetworksanddeeplearning.com/chap6.html
    .. [3] http://cs231n.github.io/convolutional-networks/
	"""

	def __init__(self, input, filter_shape, image_shape, padding=(0, 0),
				 stride=(1, 1), activation_fn=None, seed=3235):

		assert image_shape[1] == filter_shape[1]

		# rng = np.random.RandomState(seed)

		self.input = input
		self.filter_shape = filter_shape
		self.image_shape = image_shape
		self.activation_fn = activation_fn

		fan_in = np.prod(filter_shape[1:])
		fan_out = filter_shape[0]*np.prod(filter_shape[2:]) // 2
		W_bound = np.sqrt(6/(fan_in+fan_out))
		w = np.random.uniform(low=-W_bound, high=W_bound, size=filter_shape)
		b_vals = np.random.uniform(size=filter_shape[0])

		# Initiliaze weights with random variables
		self.W = theano.shared(name='weights',
							   value=w.astype(theano.config.floatX),
							   borrow=True)
		self.b = theano.shared(name='bias',
							   value=b_vals.astype(theano.config.floatX),
							   borrow=True)

		conv_out = conv2d(input=input, filters=self.W, border_mode=padding,
						  subsample=stride, filter_shape=filter_shape,
						  input_shape=image_shape)

		l_output = conv_out + self.b.dimshuffle(('x', 0, 'x', 'x'))
		self.output = (l_output if activation_fn is None
					   else activation_fn(l_output))

		# Parameters of the model
		self.params = [self.W, self.b]

class BatchNormLayer(object):
	"""
	This layer implements batch normalization of its inputs. This is
	performed by taking the mean and standard deviation across axis 0.

    .. math::
	    y = \gamma \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta

	A remedy to internal covariate shift, the solution is to normalize
	each batch by both mean and variance by insertin a BatchNorm layer
	immediately after fully connected layers (or convolutional layers,
	and before non-linearities.

	Parameters
	----------
	:type input: theano.tensor.dtensor4
	:param input: symbolic image tensor, of shape image_shape

	:type gamma: theano.tensor.dtensor4
	:param gamma: symbolic image tensor, of shape image_shape

	:type beta: theano.tensor.dtensor4
	:param beta: symbolic image tensor, of shape image_shape

	:type activation_fn: theano.Op or function
	:param activation_fn: Non linearity to be applied in the hidden
						  layer (sigmoid, tanh, relu, elu)

	References
	----------
    .. [1] https://arxiv.org/abs/1502.03167
    .. [2] https://arxiv.org/abs/1502.03167
	"""

	def __init__(self, input, shape, gamma=None, beta=None, epsilon=1e-6,
				 activation_fn=None):
		self.input = input
		self.shape = shape

		rng = np.random.RandomState(45)

		if gamma is None:
			gamma_values = rng.uniform(low=-1.0, high=1.0, size=shape)\
							.astype(theano.config.floatX)
			gamma = theano.shared(name='gamma', value=gamma_values,
								  borrow=True)

		if beta is None:
			beta_values = np.zeros(shape=shape, dtype=theano.config.floatX)\
							.astype(theano.config.floatX)
			beta = theano.shared(name='beta', value=beta_values, borrow=True)

		self.gamma = gamma
		self.beta = beta

		self.mean = T.mean(input, axis=0)
		self.std = T.std(input + epsilon, axis=0)

		l_output = T.nnet.bn.batch_normalization(input, self.gamma, self.beta,
												 self.mean, self.std)

		self.output = (l_output if activation_fn is None
					   else activation_fn(l_output))

		self.params = [self.gamma, self.beta]

class PoolingLayer(object):
	"""
	Performs a pooling operation, a form of non-linear down-sampling.
	The pooling operation partitions the input image into a set of
	non-overlapping rectangles and, for each such sub-region outputs
	the corresponding value.

	Parameters
	----------
	:type input: theano.tensor.dtensor4
	:param input: symbolic image tensor, of shape image_shape

	:type pool_shape: tuple or list of length 2
	:param pool_shape: the downsampling (pooling) factor (#rows, #cols)

	:type ignore_border: bool (1-Default)
	:param ignore_border: inlcude border in computation of pooling

	References
	----------
    .. [1] http://deeplearning.net/tutorial/lenet.html
    .. [2] http://neuralnetworksanddeeplearning.com/chap6.html
    .. [3] http://cs231n.github.io/convolutional-networks/
	"""

	def __init__(self, input, pool_shape=(2, 2), ignore_border=True,
				 activation_fn=None):
		self.input = input
		self.pool_shape = pool_shape
		self.ignore_border = ignore_border

		l_output = pool.pool_2d(input=input, ds=pool_shape,
								ignore_border=ignore_border)

		self.output = (l_output if activation_fn is None
			   		   else activation_fn(l_output))

class FC(object):
	"""
	Typical hidden layer of a MLP: units are fully-connected and have
	sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
	and the bias vector b is of shape (n_out,).

	NOTE : The nonlinearity used here is tanh

	Hidden unit activation is given by: tanh(dot(W, input.T) + b)

	Parameters
	----------
	:type rng: numpy.random.RandomState
	:param rng: a random number generator used to initialize weights

	:type input: theano.tensor.dmatrix
	:param input: a symbolic tensor of shape (n_examples, n_in)

	:type n_in: int
	:param n_in: dimensionality of input

	:type n_out: int
	:param n_out: number of hidden units

	:type activation: theano.Op or function
	:param activation: Non linearity to be applied in the hidden
	                   layer  (sigmoid, tanh, relu, elu)

	References
	----------
    .. [1] http://deeplearning.net/tutorial/mlp.html
    .. [2] http://neuralnetworksanddeeplearning.com/chap6.html
    .. [3] http://cs231n.github.io/convolutional-networks/
	"""

	def __init__(self, input, n_in, n_out, W=None, b=None, seed=35,
	         	 activation_fn=None):

		# rng = np.random.RandomState(seed)

		self.input = input

		if W is None:
			W_values = np.random.uniform(low=-np.sqrt(6./(n_in+n_out)),
								   high=np.sqrt(6./(n_in+n_out)),
								   size=(n_out, n_in)).astype(theano.config.floatX)

			if activation_fn == theano.tensor.nnet.sigmoid:
				W_values *= 4

			W = theano.shared(name='Weights', value=W_values, borrow=True)

		if b is None:
			b_values = np.zeros(n_out, dtype=theano.config.floatX)
			b = theano.shared(name='bias', value=b_values, borrow=True)

		self.W = W
		self.b = b

		l_output = (T.dot(self.W, input.T)).T + self.b
		self.output = (l_output if activation_fn is None
					   else activation_fn(l_output))

		# Parameters of the fully connected layer
		self.params = [self.W, self.b]

def dropout_from_layer(layer, p, seed=35):
    """
    p is the probablity of dropping a unit

    Parameters
	----------
	:type rng: numpy.random.RandomState
	:param rng: a random number generator used to initialize weights

	:type layer:
	:param layer: Input layer to perform dropout

	:type p: float32
	:param p: Probablity of dropping a unit

	Returns
	-------

	References
	----------
	.. [1] https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf
    """

    srng = T.shared_randomstreams.RandomStreams(seed=seed)
    mask = srng.binomial(n=1, p=1-p, size=layer.shape)
    output = layer * T.cast(mask, theano.config.floatX)

    return output

class Dropout(FC):
	def __init__(self, input, n_in, n_out, W=None, b=None, seed=35,
				 activation_fn=None, dropout_rate=0.5):

		super().__init__(input=input, n_in=n_in, n_out=n_out, W=W, b=b,
						 seed=seed, activation_fn=activation_fn)

		self.output = dropout_from_layer(self.output, p=dropout_rate, seed=seed)


text:
package org.apache.zeppelin.interpreter.launcher;

import java.io.IOException;
import java.util.Map;

import org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils;

public class ClusterInterpreterProcess extends RemoteInterpreterManagedProcess {

  public ClusterInterpreterProcess(
      String intpRunner,
      int intpEventServerPort,
      String intpEventServerHost,
      String interpreterPortRange,
      String intpDir,
      String localRepoDir,
      Map<String, String> env,
      int connectTimeout,
      int connectionPoolSize,
      String interpreterSettingName,
      String interpreterGroupId,
      boolean isUserImpersonated) {

    super(intpRunner,
      intpEventServerPort,
      intpEventServerHost,
      interpreterPortRange,
      intpDir,
      localRepoDir,
      env,
      connectTimeout,
      connectionPoolSize,
      interpreterSettingName,
      interpreterGroupId,
      isUserImpersonated);
  }

  @Override
  public void start(String userName) throws IOException {
    super.start(userName);
  }

  @Override
  public boolean isRunning() {
    if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible(getHost(), getPort())) {
      return true;
    }
    return false;
  }

  @Override
  public String getErrorMessage() {
    return null;
  }
}


text:
class QString;

namespace Quartz {

class QzCoreContext;

namespace Ext {

class Extension;
class PluginEnv;
QZ_INTERFACE IExtensionAdapter;

enum class DependencyType { Required, Optional };

using ExtensionList = QVector<std::shared_ptr<Extension>>;
using DependencyList = QVector<QPair<QString, DependencyType>>;
using AdapterList = QVector<std::shared_ptr<IExtensionAdapter>>;

class QUARTZ_CORE_API Plugin {
public:
    Plugin(const QString& pluginId, const QString& pluginName);

    virtual ~Plugin();

    const QString& pluginId() const;

    const QString& pluginName() const;

    void setContext(QzCoreContext* context);

    QzCoreContext* coreContext() const;

    virtual const ExtensionList& extensions() const = 0;

    virtual const AdapterList& adapters() const = 0;

    virtual const DependencyList& dependencies() const = 0;

    template <typename Context>
    Context* context() const {
        return static_cast<Context*>(coreContext());
    }

private:
    struct Data;
    std::unique_ptr<Data> m_data;
};

} // namespace Ext
} // namespace Quartz

extern "C" {

struct PluginWrapper {
    Quartz::Ext::Plugin* plugin;
    bool enabled;
};

struct PluginInputWrapper {
    std::unique_ptr<Quartz::Ext::PluginEnv> env;
    Quartz::QzCoreContext* appContext;
};

} // extern C


text:
function x = sym( x )

% SYM   Symmetrize.
%    SYM(X), where X is a matrix, returns the symmetric or Hermitian part
%    of X; that is, SYM(X) = 0.5 * ( X + X' ). If X is an array, SYM(X)
%    symmetrizes each of the submatrices X(:,:,k). X must satisfy
%    size(X,1) = size(X,2).
%
%    SYM(X) is useful in CVX when constructing LMIs. Sometimes, numerical
%    errors will cause a construct to be slightly non-symmetric, causing
%    CVX to flag it as an error. If you are sure the asymmetry is solely
%    due to this effect, SYM(X) will correct it for you.

sx = size(x);
if sx(1) ~= sx(2),
    error( 'Argument must be square in its first two dimensions.' );
elseif sx(1) > 1,
    x = 0.5 * ( x + conj( permute( x, [2,1,3:length(sx)] ) ) );
end

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.