text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
    <title>Portal de comunicación para entornos educativos</title>

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">
    <link href="/sources/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="/sources/css/main.css" type="text/css" rel="stylesheet" media="screen,projection" />

Salir


text:
<?php

final class TransactionSearchConduitAPIMethod
  extends ConduitAPIMethod {

  public function getAPIMethodName() {
    return 'transaction.search';
  }

  public function getMethodDescription() {
    return pht('Read transactions for an object.');
  }

  public function getMethodStatus() {
    return self::METHOD_STATUS_UNSTABLE;
  }

  public function getMethodStatusDescription() {
    return pht('This method is new and experimental.');
  }

  protected function defineParamTypes() {
    return array(
      'objectIdentifier' => 'phid|string',
    ) + $this->getPagerParamTypes();
  }

  protected function defineReturnType() {
    return 'list<dict>';
  }

  protected function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $viewer = $request->getUser();
    $pager = $this->newPager($request);

    $object_name = $request->getValue('objectIdentifier', null);
    if (!strlen($object_name)) {
      throw new Exception(
        pht(
          'When calling "transaction.search", you must provide an object to '.
          'retrieve transactions for.'));
    }

    $object = id(new PhabricatorObjectQuery())
      ->setViewer($viewer)
      ->withNames(array($object_name))
      ->executeOne();
    if (!$object) {
      throw new Exception(
        pht(
          'No object "%s" exists.',
          $object_name));
    }

    if (!($object instanceof PhabricatorApplicationTransactionInterface)) {
      throw new Exception(
        pht(
          'Object "%s" does not implement "%s", so transactions can not '.
          'be loaded for it.'));
    }

    $xaction_query = PhabricatorApplicationTransactionQuery::newQueryForObject(
      $object);

    $xactions = $xaction_query
      ->withObjectPHIDs(array($object->getPHID()))
      ->setViewer($viewer)
      ->executeWithCursorPager($pager);

    if ($xactions) {
      $template = head($xactions)->getApplicationTransactionCommentObject();

      $query = new PhabricatorApplicationTransactionTemplatedCommentQuery();

      $comment_map = $query
        ->setViewer($viewer)
        ->setTemplate($template)
        ->withTransactionPHIDs(mpull($xactions, 'getPHID'))
        ->execute();

      $comment_map = msort($comment_map, 'getCommentVersion');
      $comment_map = array_reverse($comment_map);
      $comment_map = mgroup($comment_map, 'getTransactionPHID');
    } else {
      $comment_map = array();
    }

    $modular_classes = array();
    $modular_objects = array();
    $modular_xactions = array();
    foreach ($xactions as $xaction) {
      if (!$xaction instanceof PhabricatorModularTransaction) {
        continue;
      }

      // TODO: Hack things so certain transactions which don't have a modular
      // type yet can use a pseudotype until they modularize. Some day, we'll
      // modularize everything and remove this.
      switch ($xaction->getTransactionType()) {
        case DifferentialTransaction::TYPE_INLINE:
          $modular_template = new DifferentialRevisionInlineTransaction();
          break;
        default:
          $modular_template = $xaction->getModularType();
          break;
      }

      $modular_class = get_class($modular_template);
      if (!isset($modular_objects[$modular_class])) {
        try {
          $modular_object = newv($modular_class, array());
          $modular_objects[$modular_class] = $modular_object;
        } catch (Exception $ex) {
          continue;
        }
      }

      $modular_classes[$xaction->getPHID()] = $modular_class;
      $modular_xactions[$modular_class][] = $xaction;
    }

    $modular_data_map = array();
    foreach ($modular_objects as $class => $modular_type) {
      $modular_data_map[$class] = $modular_type
        ->setViewer($viewer)
        ->loadTransactionTypeConduitData($modular_xactions[$class]);
    }

    $data = array();
    foreach ($xactions as $xaction) {
      $comments = idx($comment_map, $xaction->getPHID());

      $comment_data = array();
      if ($comments) {
        $removed = head($comments)->getIsDeleted();

        foreach ($comments as $comment) {
          if ($removed) {
            // If the most recent version of the comment has been removed,
            // don't show the history. This is for consistency with the web
            // UI, which also prevents users from retrieving the content of
            // removed comments.
            $content = array(
              'raw' => '',
            );
          } else {
            $content = array(
              'raw' => (string)$comment->getContent(),
            );
          }

          $comment_data[] = array(
            'id' => (int)$comment->getID(),
            'phid' => (string)$comment->getPHID(),
            'version' => (int)$comment->getCommentVersion(),
            'authorPHID' => (string)$comment->getAuthorPHID(),
            'dateCreated' => (int)$comment->getDateCreated(),
            'dateModified' => (int)$comment->getDateModified(),
            'removed' => (bool)$comment->getIsDeleted(),
            'content' => $content,
          );
        }
      }

      $fields = array();
      $type = null;

      if (isset($modular_classes[$xaction->getPHID()])) {
        $modular_class = $modular_classes[$xaction->getPHID()];
        $modular_object = $modular_objects[$modular_class];
        $modular_data = $modular_data_map[$modular_class];

        $type = $modular_object->getTransactionTypeForConduit($xaction);
        $fields = $modular_object->getFieldValuesForConduit(
          $xaction,
          $modular_data);
      }

      if (!$fields) {
        $fields = (object)$fields;
      }

      // If we haven't found a modular type, fallback for some simple core
      // types. Ideally, we'll modularize everything some day.
      if ($type === null) {
        switch ($xaction->getTransactionType()) {
          case PhabricatorTransactions::TYPE_COMMENT:
            $type = 'comment';
            break;
        }
      }

      $data[] = array(
        'id' => (int)$xaction->getID(),
        'phid' => (string)$xaction->getPHID(),
        'type' => $type,
        'authorPHID' => (string)$xaction->getAuthorPHID(),
        'objectPHID' => (string)$xaction->getObjectPHID(),
        'dateCreated' => (int)$xaction->getDateCreated(),
        'dateModified' => (int)$xaction->getDateModified(),
        'comments' => $comment_data,
        'fields' => $fields,
      );
    }

    $results = array(
      'data' => $data,
    );

    return $this->addPagerResults($results, $pager);
  }
}

redpajama_set_name: RedPajamaGithub


text:
from heat.engine import properties
from heat.engine import constraints
from heat.engine import attributes
from heat.common.i18n import _
from avi.heat.avi_resource import AviResource
from avi.heat.avi_resource import AviNestedResource
from options import *

from options import *
from match import *

class ClientLogConfiguration(object):
    # all schemas
    enable_significant_log_collection_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Enable significant log collection. By default, this flag is enabled, which means that Avi SEs collect significant logs (logs corresponding to error conditions, such as when the response code for a request is 500) and forward them to Controller for further processing. Users can disable this flag to turn off default significant log collection."),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'enable_significant_log_collection',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'enable_significant_log_collection': enable_significant_log_collection_schema,
    }

class AnalyticsProfile(AviResource):
    resource_name = "analyticsprofile"
    # all schemas
    name_schema = properties.Schema(
        properties.Schema.STRING,
        _("The name of the analytics profile."),
        required=True,
        update_allowed=True,
    )
    description_schema = properties.Schema(
        properties.Schema.STRING,
        _(""),
        required=False,
        update_allowed=True,
    )
    apdex_response_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("If a client receives an HTTP response in less than the Satisfactory Latency Threshold, the request is considered Satisfied.  If the response time is greater than the Satisfactory Latency Threshold but less than the Tolerated Latency Factor multiplied by the Satisfactory Latency Threshold, it is considered Tolerated.  Greater than this number and the client's request is considered Frustrated."),
        required=False,
        update_allowed=True,
    )
    apdex_response_tolerated_factor_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Client tolerated response latency factor. Clientmust receive a response within this factor times the satisfactory threshold (apdex_response_threshold) to be considered tolerated"),
        required=False,
        update_allowed=True,
    )
    apdex_server_response_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("If Avi receives an HTTP response from a server in less than the Satisfactory Latency Threshold, the server response is considered Satisfied.  If the response time is greater than the Satisfactory Latency Threshold but less than the Tolerated Latency Factor multiplied by the Satisfactory Latency Threshold, it is considered Tolerated.  Greater than this number and the server response is considered Frustrated."),
        required=False,
        update_allowed=True,
    )
    apdex_server_response_tolerated_factor_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Server tolerated response latency factor. Servermust response within this factor times the satisfactory threshold (apdex_server_response_threshold) to be considered tolerated"),
        required=False,
        update_allowed=True,
    )
    apdex_rtt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Satisfactory client to Avi Round Trip Time(RTT)."),
        required=False,
        update_allowed=True,
    )
    apdex_rtt_tolerated_factor_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Tolerated client to Avi Round Trip Time(RTT) factor.  It is a multiple of apdex_rtt_tolerated_factor."),
        required=False,
        update_allowed=True,
    )
    apdex_server_rtt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Satisfactory client to Avi Round Trip Time(RTT)."),
        required=False,
        update_allowed=True,
    )
    apdex_server_rtt_tolerated_factor_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Tolerated client to Avi Round Trip Time(RTT) factor.  It is a multiple of apdex_rtt_tolerated_factor."),
        required=False,
        update_allowed=True,
    )
    apdex_rum_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("If a client is able to load a page in less than the Satisfactory Latency Threshold, the PageLoad is considered Satisfied.  If the load time is greater than the Satisfied Latency but less than the Tolerated Latency multiplied by Satisifed Latency, it is considered Tolerated.  Greater than this number and the client's request is considered Frustrated.  A PageLoad includes the time for DNS lookup, download of all HTTP objects, and page render time."),
        required=False,
        update_allowed=True,
    )
    apdex_rum_tolerated_factor_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Virtual service threshold factor for tolerated Page Load Time (PLT) as multiple of apdex_rum_threshold."),
        required=False,
        update_allowed=True,
    )
    conn_lossy_total_rexmt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between client and Avi is considered lossy when more than this percentage of packets are retransmitted."),
        required=False,
        update_allowed=True,
    )
    conn_lossy_timeo_rexmt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between client and Avi is considered lossy when more than this percentage of packets are retransmitted due to timeout."),
        required=False,
        update_allowed=True,
    )
    conn_lossy_ooo_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between client and Avi is considered lossy when more than this percentage of out of order packets are received."),
        required=False,
        update_allowed=True,
    )
    conn_lossy_zero_win_size_event_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between client and Avi is considered lossy when more than this percentage of times a packet could not be trasmitted due to zero window."),
        required=False,
        update_allowed=True,
    )
    conn_server_lossy_total_rexmt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between Avi and server is considered lossy when more than this percentage of packets are retransmitted."),
        required=False,
        update_allowed=True,
    )
    conn_server_lossy_timeo_rexmt_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between Avi and server is considered lossy when more than this percentage of packets are retransmitted due to timeout."),
        required=False,
        update_allowed=True,
    )
    conn_server_lossy_ooo_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between Avi and server is considered lossy when more than this percentage of out of order packets are received."),
        required=False,
        update_allowed=True,
    )
    conn_server_lossy_zero_win_size_event_threshold_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("A connection between Avi and server is considered lossy when more than this percentage of times a packet could not be trasmitted due to zero window."),
        required=False,
        update_allowed=True,
    )
    exclude_client_close_before_request_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude client closed connection before an HTTP request could be completed from being classified as an error."),
        required=False,
        update_allowed=True,
    )
    exclude_tcp_reset_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude TCP resets by client from the list of potential errors."),
        required=False,
        update_allowed=True,
    )
    exclude_server_tcp_reset_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude server TCP reset from errors.  It is common for applications like MS Exchange."),
        required=False,
        update_allowed=True,
    )
    exclude_persistence_change_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude persistence server changed while load balancing' from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_syn_retransmit_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude 'server unanswered syns' from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_invalid_dns_query_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude invalid dns queries from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_invalid_dns_domain_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude dns queries to domains outside the domains configured in the DNS application profile from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_no_dns_record_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude queries to domains that did not have configured services/records from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_unsupported_dns_query_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude unsupported dns queries from the list of errors."),
        required=False,
        update_allowed=True,
    )
    hs_performance_boost_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Adds free performance score credits to health score. It can be used for compensating health score for known slow applications."),
        required=False,
        update_allowed=True,
    )
    hs_max_anomaly_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum penalty that may be deducted from health score for anomalies."),
        required=False,
        update_allowed=True,
    )
    hs_max_resources_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum penalty that may be deducted from health score for high resource utilization."),
        required=False,
        update_allowed=True,
    )
    hs_max_security_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Maximum penalty that may be deducted from health score based on security assessment."),
        required=False,
        update_allowed=True,
    )
    hs_security_nonpfs_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Penalty for allowing non-PFS handshakes."),
        required=False,
        update_allowed=True,
    )
    hs_security_weak_signature_algo_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Penalty for allowing weak signature algorithm(s)."),
        required=False,
        update_allowed=True,
    )
    hs_security_ssl30_score_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when supporting SSL3.0 encryption protocol"),
        required=False,
        update_allowed=True,
    )
    hs_security_tls10_score_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when supporting TLS1.0 encryption protocol"),
        required=False,
        update_allowed=True,
    )
    hs_security_tls11_score_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when supporting TLS1.1 encryption protocol"),
        required=False,
        update_allowed=True,
    )
    hs_security_tls12_score_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when supporting TLS1.2 encryption protocol"),
        required=False,
        update_allowed=True,
    )
    hs_event_throttle_window_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Time window (in secs) within which only unique health change events should occur"),
        required=False,
        update_allowed=True,
    )
    hs_min_dos_rate_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("DoS connection rate below which the DoS security assessment will not kick in."),
        required=False,
        update_allowed=True,
    )
    hs_security_certscore_expired_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the certificate has expired"),
        required=False,
        update_allowed=True,
    )
    hs_security_certscore_le07d_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the certificate expires in less than or equal to 7 days"),
        required=False,
        update_allowed=True,
    )
    hs_security_certscore_le30d_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the certificate expires in less than or equal to 30 days"),
        required=False,
        update_allowed=True,
    )
    hs_security_certscore_gt30d_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the certificate expires in more than 30 days"),
        required=False,
        update_allowed=True,
    )
    hs_security_cipherscore_eq000b_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the minimum cipher strength is 0 bits"),
        required=False,
        update_allowed=True,
    )
    hs_security_cipherscore_lt128b_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the minimum cipher strength is less than 128 bits"),
        required=False,
        update_allowed=True,
    )
    hs_security_cipherscore_ge128b_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when the minimum cipher strength is greater than equal to 128 bits"),
        required=False,
        update_allowed=True,
    )
    hs_security_selfsignedcert_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Deprecated"),
        required=False,
        update_allowed=True,
    )
    hs_security_encalgo_score_rc4_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when RC4 algorithm is used for encryption."),
        required=False,
        update_allowed=True,
    )
    hs_security_encalgo_score_none_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Score assigned when no algorithm is used for encryption."),
        required=False,
        update_allowed=True,
    )
    hs_security_chain_invalidity_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Penalty for allowing certificates with invalid chain."),
        required=False,
        update_allowed=True,
    )
    hs_security_hsts_penalty_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Penalty for not enabling HSTS."),
        required=False,
        update_allowed=True,
    )
    disable_server_analytics_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Disable analytics on backend servers. This may be desired in container environment when there are large number of  ephemeral servers"),
        required=False,
        update_allowed=True,
    )
    disable_se_analytics_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Disable node (service engine) level analytics forvs metrics"),
        required=False,
        update_allowed=True,
    )
    hs_pscore_traffic_threshold_l4_client_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Threshold number of connections in 5min, below which apdexr, apdexc, rum_apdex, and other network quality metrics are not computed."),
        required=False,
        update_allowed=True,
    )
    hs_pscore_traffic_threshold_l4_server_schema = properties.Schema(
        properties.Schema.NUMBER,
        _("Threshold number of connections in 5min, below which apdexr, apdexc, rum_apdex, and other network quality metrics are not computed."),
        required=False,
        update_allowed=True,
    )
    exclude_gs_down_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude queries to GSLB services that are operationally down from the list of errors."),
        required=False,
        update_allowed=True,
    )
    exclude_no_valid_gs_member_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude queries to GSLB services that have no available members from the list of errors."),
        required=False,
        update_allowed=True,
    )
    client_log_config_schema = properties.Schema(
        properties.Schema.MAP,
        _(""),
        schema=ClientLogConfiguration.properties_schema,
        required=False,
        update_allowed=True,
    )
    exclude_http_error_codes_item_schema = properties.Schema(
        properties.Schema.NUMBER,
        _(""),
        required=True,
        update_allowed=False,
    )
    exclude_http_error_codes_schema = properties.Schema(
        properties.Schema.LIST,
        _("List of HTTP status codes to be excluded from being classified as an error.  Error connections or responses impacts health score, are included as significant logs, and may be classified as part of a DoS attack."),
        schema=exclude_http_error_codes_item_schema,
        required=False,
        update_allowed=True,
    )
    ranges_item_schema = properties.Schema(
        properties.Schema.MAP,
        _(""),
        schema=HTTPStatusRange.properties_schema,
        required=True,
        update_allowed=False,
    )
    ranges_schema = properties.Schema(
        properties.Schema.LIST,
        _("List of HTTP status code ranges to be excluded from being classified as an error."),
        schema=ranges_item_schema,
        required=False,
        update_allowed=True,
    )
    resp_code_block_item_schema = properties.Schema(
        properties.Schema.STRING,
        _(""),
        required=True,
        update_allowed=False,
        constraints=[
            constraints.AllowedValues(['HTTP_SECURITY_ACTION_SEND_RESPONSE', 'HTTP_SECURITY_ACTION_REDIRECT_TO_HTTPS', 'HTTP_SECURITY_ACTION_RATE_LIMIT', 'HTTP_SECURITY_ACTION_ALLOW', 'HTTP_SECURITY_ACTION_CLOSE_CONN']),
        ],
    )
    resp_code_block_schema = properties.Schema(
        properties.Schema.LIST,
        _("Block of HTTP response codes to be excluded from being classified as an error."),
        schema=resp_code_block_item_schema,
        required=False,
        update_allowed=True,
    )
    exclude_server_dns_error_as_error_schema = properties.Schema(
        properties.Schema.BOOLEAN,
        _("Exclude server dns error response from the list of errors."),
        required=False,
        update_allowed=True,
    )

    # properties list
    PROPERTIES = (
        'name',
        'description',
        'apdex_response_threshold',
        'apdex_response_tolerated_factor',
        'apdex_server_response_threshold',
        'apdex_server_response_tolerated_factor',
        'apdex_rtt_threshold',
        'apdex_rtt_tolerated_factor',
        'apdex_server_rtt_threshold',
        'apdex_server_rtt_tolerated_factor',
        'apdex_rum_threshold',
        'apdex_rum_tolerated_factor',
        'conn_lossy_total_rexmt_threshold',
        'conn_lossy_timeo_rexmt_threshold',
        'conn_lossy_ooo_threshold',
        'conn_lossy_zero_win_size_event_threshold',
        'conn_server_lossy_total_rexmt_threshold',
        'conn_server_lossy_timeo_rexmt_threshold',
        'conn_server_lossy_ooo_threshold',
        'conn_server_lossy_zero_win_size_event_threshold',
        'exclude_client_close_before_request_as_error',
        'exclude_tcp_reset_as_error',
        'exclude_server_tcp_reset_as_error',
        'exclude_persistence_change_as_error',
        'exclude_syn_retransmit_as_error',
        'exclude_invalid_dns_query_as_error',
        'exclude_invalid_dns_domain_as_error',
        'exclude_no_dns_record_as_error',
        'exclude_unsupported_dns_query_as_error',
        'hs_performance_boost',
        'hs_max_anomaly_penalty',
        'hs_max_resources_penalty',
        'hs_max_security_penalty',
        'hs_security_nonpfs_penalty',
        'hs_security_weak_signature_algo_penalty',
        'hs_security_ssl30_score',
        'hs_security_tls10_score',
        'hs_security_tls11_score',
        'hs_security_tls12_score',
        'hs_event_throttle_window',
        'hs_min_dos_rate',
        'hs_security_certscore_expired',
        'hs_security_certscore_le07d',
        'hs_security_certscore_le30d',
        'hs_security_certscore_gt30d',
        'hs_security_cipherscore_eq000b',
        'hs_security_cipherscore_lt128b',
        'hs_security_cipherscore_ge128b',
        'hs_security_selfsignedcert_penalty',
        'hs_security_encalgo_score_rc4',
        'hs_security_encalgo_score_none',
        'hs_security_chain_invalidity_penalty',
        'hs_security_hsts_penalty',
        'disable_server_analytics',
        'disable_se_analytics',
        'hs_pscore_traffic_threshold_l4_client',
        'hs_pscore_traffic_threshold_l4_server',
        'exclude_gs_down_as_error',
        'exclude_no_valid_gs_member_as_error',
        'client_log_config',
        'exclude_http_error_codes',
        'ranges',
        'resp_code_block',
        'exclude_server_dns_error_as_error',
    )

    # mapping of properties to their schemas
    properties_schema = {
        'name': name_schema,
        'description': description_schema,
        'apdex_response_threshold': apdex_response_threshold_schema,
        'apdex_response_tolerated_factor': apdex_response_tolerated_factor_schema,
        'apdex_server_response_threshold': apdex_server_response_threshold_schema,
        'apdex_server_response_tolerated_factor': apdex_server_response_tolerated_factor_schema,
        'apdex_rtt_threshold': apdex_rtt_threshold_schema,
        'apdex_rtt_tolerated_factor': apdex_rtt_tolerated_factor_schema,
        'apdex_server_rtt_threshold': apdex_server_rtt_threshold_schema,
        'apdex_server_rtt_tolerated_factor': apdex_server_rtt_tolerated_factor_schema,
        'apdex_rum_threshold': apdex_rum_threshold_schema,
        'apdex_rum_tolerated_factor': apdex_rum_tolerated_factor_schema,
        'conn_lossy_total_rexmt_threshold': conn_lossy_total_rexmt_threshold_schema,
        'conn_lossy_timeo_rexmt_threshold': conn_lossy_timeo_rexmt_threshold_schema,
        'conn_lossy_ooo_threshold': conn_lossy_ooo_threshold_schema,
        'conn_lossy_zero_win_size_event_threshold': conn_lossy_zero_win_size_event_threshold_schema,
        'conn_server_lossy_total_rexmt_threshold': conn_server_lossy_total_rexmt_threshold_schema,
        'conn_server_lossy_timeo_rexmt_threshold': conn_server_lossy_timeo_rexmt_threshold_schema,
        'conn_server_lossy_ooo_threshold': conn_server_lossy_ooo_threshold_schema,
        'conn_server_lossy_zero_win_size_event_threshold': conn_server_lossy_zero_win_size_event_threshold_schema,
        'exclude_client_close_before_request_as_error': exclude_client_close_before_request_as_error_schema,
        'exclude_tcp_reset_as_error': exclude_tcp_reset_as_error_schema,
        'exclude_server_tcp_reset_as_error': exclude_server_tcp_reset_as_error_schema,
        'exclude_persistence_change_as_error': exclude_persistence_change_as_error_schema,
        'exclude_syn_retransmit_as_error': exclude_syn_retransmit_as_error_schema,
        'exclude_invalid_dns_query_as_error': exclude_invalid_dns_query_as_error_schema,
        'exclude_invalid_dns_domain_as_error': exclude_invalid_dns_domain_as_error_schema,
        'exclude_no_dns_record_as_error': exclude_no_dns_record_as_error_schema,
        'exclude_unsupported_dns_query_as_error': exclude_unsupported_dns_query_as_error_schema,
        'hs_performance_boost': hs_performance_boost_schema,
        'hs_max_anomaly_penalty': hs_max_anomaly_penalty_schema,
        'hs_max_resources_penalty': hs_max_resources_penalty_schema,
        'hs_max_security_penalty': hs_max_security_penalty_schema,
        'hs_security_nonpfs_penalty': hs_security_nonpfs_penalty_schema,
        'hs_security_weak_signature_algo_penalty': hs_security_weak_signature_algo_penalty_schema,
        'hs_security_ssl30_score': hs_security_ssl30_score_schema,
        'hs_security_tls10_score': hs_security_tls10_score_schema,
        'hs_security_tls11_score': hs_security_tls11_score_schema,
        'hs_security_tls12_score': hs_security_tls12_score_schema,
        'hs_event_throttle_window': hs_event_throttle_window_schema,
        'hs_min_dos_rate': hs_min_dos_rate_schema,
        'hs_security_certscore_expired': hs_security_certscore_expired_schema,
        'hs_security_certscore_le07d': hs_security_certscore_le07d_schema,
        'hs_security_certscore_le30d': hs_security_certscore_le30d_schema,
        'hs_security_certscore_gt30d': hs_security_certscore_gt30d_schema,
        'hs_security_cipherscore_eq000b': hs_security_cipherscore_eq000b_schema,
        'hs_security_cipherscore_lt128b': hs_security_cipherscore_lt128b_schema,
        'hs_security_cipherscore_ge128b': hs_security_cipherscore_ge128b_schema,
        'hs_security_selfsignedcert_penalty': hs_security_selfsignedcert_penalty_schema,
        'hs_security_encalgo_score_rc4': hs_security_encalgo_score_rc4_schema,
        'hs_security_encalgo_score_none': hs_security_encalgo_score_none_schema,
        'hs_security_chain_invalidity_penalty': hs_security_chain_invalidity_penalty_schema,
        'hs_security_hsts_penalty': hs_security_hsts_penalty_schema,
        'disable_server_analytics': disable_server_analytics_schema,
        'disable_se_analytics': disable_se_analytics_schema,
        'hs_pscore_traffic_threshold_l4_client': hs_pscore_traffic_threshold_l4_client_schema,
        'hs_pscore_traffic_threshold_l4_server': hs_pscore_traffic_threshold_l4_server_schema,
        'exclude_gs_down_as_error': exclude_gs_down_as_error_schema,
        'exclude_no_valid_gs_member_as_error': exclude_no_valid_gs_member_as_error_schema,
        'client_log_config': client_log_config_schema,
        'exclude_http_error_codes': exclude_http_error_codes_schema,
        'ranges': ranges_schema,
        'resp_code_block': resp_code_block_schema,
        'exclude_server_dns_error_as_error': exclude_server_dns_error_as_error_schema,
    }

    # for supporting get_avi_uuid_by_name functionality
    field_references = {
        'ranges': getattr(HTTPStatusRange, 'field_references', {}),
        'client_log_config': getattr(ClientLogConfiguration, 'field_references', {}),
    }

def resource_mapping():
    return {
        'Avi::LBaaS::AnalyticsProfile': AnalyticsProfile,
    }


text:
#import "AppDelegate.h"
#if CC_CCBREADER
#import "CCBuilderReader.h"
#endif
#import "MainScene.h"
#import "HomeViewController.h"
#import "DBHelper.h"

@implementation AppController
{
    MainScene* mainScene;
    HomeViewController* homeViewController;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSMutableDictionary* cocos2dSetup;
#if CC_CCBREADER
    // Configure Cocos2d with the options set in SpriteBuilder
    NSString* configPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Published-iOS"]; // TODO: add support for Published-Android support
    configPath = [configPath stringByAppendingPathComponent:@"configCocos2d.plist"];

    cocos2dSetup = [NSMutableDictionary dictionaryWithContentsOfFile:configPath];

    // Configure CCFileUtils to work with SpriteBuilder
    [CCBReader configureCCFileUtils];
#else
    // Cocos2D takes a dictionary to start ... yeah I know ... but it does, and it is kind of neat
    cocos2dSetup = [NSMutableDictionary dictionary];

    // Let's add some setup stuff

    // File extensions
    // You can use anything you want, and completely dropping extensions will in most cases automatically scale the artwork correct
    // To make it easy to understand what resolutions I am using, I have changed this for this demo to -4x -2x and -1x
    // Notice that I deliberately added some of the artwork without extensions
    [CCFileUtils sharedFileUtils].suffixesDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                                  @"-2x", CCFileUtilsSuffixiPad,
                                                  @"-4x", CCFileUtilsSuffixiPadHD,
                                                  @"-1x", CCFileUtilsSuffixiPhone,
                                                  @"-1x", CCFileUtilsSuffixiPhoneHD,
                                                  @"-1x", CCFileUtilsSuffixiPhone5,
                                                  @"-2x", CCFileUtilsSuffixiPhone5HD,
                                                  @"", CCFileUtilsSuffixDefault,
                                                  nil];

    // Call this instead of line above if you are using SpriteBuilder
    //[CCBReader configureCCFileUtils];

    // Show FPS
    // We really want this when developing an app
    [cocos2dSetup setObject:@(YES) forKey:CCSetupShowDebugStats];

    // A acouple of other examples

    // Use a 16 bit color buffer
    // This will lower the color depth from 32 bits to 16 bits for that extra performance
    // Most will want 32, so we disbaled it
    // ---
    // [startUpOptions setObject:kEAGLColorFormatRGB565 forKey:CCSetupPixelFormat];

    // Use a simplified coordinate system that is shared across devices
    // Normally you work in the coordinate of the device (an iPad is 1024x768, an iPhone 4 480x320 and so on)
    // This feature makes it easier to use the same setup for all devices (easier is a relative term)
    // Most will want to handle iPad and iPhone exclusively, so it is disabled by default
    // ---
    // [startUpOptions setObject:CCScreenModeFixed forKey:CCSetupScreenMode];

    // All the supported keys can be found in CCConfiguration.h
#endif
    // We are done ...
    // Lets get this thing on the road!
    [self setupCocos2dWithOptions:cocos2dSetup];

    CCDirectorIOS* director = (CCDirectorIOS*)[CCDirector sharedDirector];
    [director setDisplayStats:NO];

    homeViewController = [[HomeViewController alloc] init];
    [director presentViewController:homeViewController animated:YES completion:NULL];

    // Stay positive. Always return a YES :)
    return YES;
}

- (void)pauseScene
{
    CCDirectorIOS* director = (CCDirectorIOS*)[CCDirector sharedDirector];
    [director pause];
}

- (void)runSceneWithManagedObject:(NSManagedObject*)object
{
    CCDirectorIOS* director = (CCDirectorIOS*)[CCDirector sharedDirector];
    if (mainScene == nil)
    {
        mainScene = [[MainScene alloc]initWithObject:object];
        [director runWithScene:mainScene];
    }
    else
    {
        [mainScene clearWithObject:object];
        [director resume];
    }

}

- (void)saveImage
{
    DatabaseHelper* helper = [DatabaseHelper sharedDatabaseHelper];
    [helper updateImage:[mainScene captureScreen] imageId:[mainScene getID].intValue];
}

- (void)showHome
{
    [self saveImage];
    [self pauseScene];
    CCDirectorIOS* director = (CCDirectorIOS*)[CCDirector sharedDirector];
    [director presentViewController:homeViewController animated:YES completion:NULL];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveImage];
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"FreeDrawModel"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                     */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }

    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end


text:
(function () {
    'use strict';

    function config($routeProvider, $httpProvider) {
        $httpProvider.defaults.headers["delete"] = {
            'Content-Type': 'application/json;charset=utf-8'
        };

        var CONTROLLER_AS_VIEW_MODEL = 'vm';

        $routeProvider
            .when('/', {
                templateUrl: 'app/pages/home/home.html',
                controller: 'HomeController'
            })
            .when('/Home', { redirectTo: '/' })
            .when('/Register', {
                templateUrl: 'app/pages/register/register.html',
                controller: 'RegisterController'
            })
            .when('/Login', {
                templateUrl: 'app/pages/login/login.html',
                controller: 'RegisterController'
            })
            .when('/Events', {
                templateUrl: 'app/pages/events/events.html',
                controller: 'EventsController'
            })
            .when('/unauthorized', {
                template: '
YOU ARE NOT AUTHORIZED!
'
            })
            .otherwise({ redirectTo: '/' });
    }

    angular.module('myApp.services', []);
    angular.module('myApp.directives', []);
    angular.module('myApp.filters', []);
    angular.module('myApp.controllers', ['myApp.services']);
    angular.module('myApp', ['ngRoute', 'ngCookies', 'myApp.controllers', 'myApp.directives', 'myApp.filters', 'kendo.directives']).
        config(['$routeProvider', '$httpProvider', config])
        .value('toastr', toastr)
        .constant('baseServiceUrl', 'http://localhost:38013/')
        .constant('VALIDATION', {
            'minEmailLength': 3,
            'maxEmailLength': 60,
            'minPasswordLength': 6,
            'maxPasswordLength': 32,
            'minUsernameLength': 3,
            'maxUsernameLength': 100,
        });
}());


text:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site
  ( app
  ) where

------------------------------------------------------------------------------
import           Control.Applicative
import           Control.Concurrent
import           Control.Concurrent.Async
import           Control.Concurrent.MVar
import           Control.Lens
import           Control.Monad
import           Control.Monad.Reader (asks)
import           Control.Monad.IO.Class (liftIO)
import qualified Data.Acid as AS
import           Data.ByteString (ByteString)
import           Data.Default (def)
import           Data.List (groupBy)
import           Data.Maybe
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import           Data.Time.Clock
import           Data.Time.Clock.POSIX
import qualified Network.Gravatar as G
import           Snap
import           Snap.Core
import           Snap.Snaplet
import           Snap.Snaplet.AcidState (Update, Query, update, query, acidInitManual)
import           Snap.Snaplet.Auth
import           Snap.Snaplet.Auth.Backends.JsonFile
import           Snap.Snaplet.Heist
import           Snap.Snaplet.Session.Backends.CookieSession
import           Snap.Util.FileServe
import           Heist
import qualified Heist.Interpreted as I
import qualified Text.XmlHtml as X
import           Web.Bugzilla
------------------------------------------------------------------------------
import           Application
import           Bugzilla

------------------------------------------------------------------------------
-- | Render login form
handleLogin :: Maybe T.Text -> Handler App (AuthManager App) ()
handleLogin authError = heistLocal (I.bindSplices errs) $ render "login"
  where
    errs = maybe noSplices splice authError
    splice err = "loginError" ## I.textSplice err

------------------------------------------------------------------------------
-- | Handle login submit
handleLoginSubmit :: Handler App (AuthManager App) ()
handleLoginSubmit = do
    mUser <- getParam "login"
    mPass <- getParam "password"
    case (mUser, mPass) of
      (Just user, Just pass) -> loginUser "login" "password" Nothing
                                          (\_ -> handleLogin err)
                                          (loginSuccess user pass)
      _                      -> handleLogin invalidErr
  where
    err = Just "Unknown user or password."
    invalidErr = Just "Invalid request. Try again."

    loginSuccess user pass = do
      let userText = TE.decodeUtf8 user
          passText = TE.decodeUtf8 pass

      -- Create a Bugzilla session for this user.
      session <- liftIO $ newBzSession userText (Just passText)
      mvSessions <- withTop' id $ gets $ _bzSessions
      liftIO $ modifyMVar_ mvSessions $
        return . M.insert userText session

      -- Synchronously update requests if there are none stored.
      mReqs <- query $ GetRequests userText
      when (isNothing mReqs) $ do
        reqs <- liftIO $ bzRequests session userText
        update $ UpdateRequests userText reqs

      -- We're now ready to display the dashboard.
      redirect "/dashboard"

------------------------------------------------------------------------------
-- | Logs out and redirects the user to the site index.
handleLogout :: Handler App (AuthManager App) ()
handleLogout = logout >> redirect "/"

------------------------------------------------------------------------------
-- | Handle new user form submit
handleNewUser :: Handler App (AuthManager App) ()
handleNewUser = method GET handleForm <|> method POST handleFormSubmit
  where
    handleForm = render "new_user"
    handleFormSubmit = do
      mUser <- getParam "login"
      case mUser of
        (Just user) -> do let newTime = posixSecondsToUTCTime 0
                              userText = TE.decodeUtf8 user
                          update $ AddUser userText (UserInfo newTime)
                          registerUser "login" "password"
                          redirect "/"
        _           -> redirect "/new_user"

------------------------------------------------------------------------------
-- | Handle dashboard
handleDashboard :: Handler App (AuthManager App) ()
handleDashboard = do
  mUser <- currentUser
  case mUser of
    Just user -> do
      let login = userLogin user
      curTime <- liftIO $ getCurrentTime
      mUserInfo <- query $ GetUser login
      update $ UpdateUser login (UserInfo curTime)
      mReqs <- query $ GetRequests login
      case (mUserInfo, mReqs) of
        (Just ui, Just reqs) -> renderDashboard curTime (ui ^. uiLastSeen) reqs
        (Nothing, _)         -> handleLogin $ Just "You don't exist."
        _                    -> handleLogin $ Just "You've been logged out. Please log in again."
    Nothing -> handleLogin $ Just "You need to be logged in for that."

renderDashboard :: UTCTime -> UTCTime -> [BzRequest] -> Handler App (AuthManager App) ()
renderDashboard curTime lastSeen requests = do
  let (nis, rs, fs, as, ps, rds) = countRequests requests
      splices = do "dashboardItems" ## I.mapSplices (dashboardItemSplice lastSeen curTime)
                                                    requests
                   "needinfoCount"  ## (return [X.TextNode . T.pack . show $ nis])
                   "reviewCount"    ## (return [X.TextNode . T.pack . show $ rs])
                   "feedbackCount"  ## (return [X.TextNode . T.pack . show $ fs])
                   "assignedCount"  ## (return [X.TextNode . T.pack . show $ as])
                   "pendingCount"   ## (return [X.TextNode . T.pack . show $ ps])
                   "reviewedCount"  ## (return [X.TextNode . T.pack . show $ rds])
  heistLocal (I.bindSplices splices) $ render "dashboard"

dashboardItemSplice :: UTCTime -> UTCTime -> BzRequest -> I.Splice (Handler App App)
dashboardItemSplice lastSeen curTime req = return $
    [divNode ["item", containerClass req] $
       [ divNode [reqClass req] $
           titleBadge req ++
             [X.Element "h1" [classes ["card-title", reqClass req]] [title req]]
       ] ++ extended req ++ [
         divNode ["summary"] [X.Element "p" [] [bugLink req]]
       ] ++ details req ++
       [ lastComment req
       , comments req
       ]
    ]

  where

    containerClass (NeedinfoRequest _ _ _) = "needinfo-container"
    containerClass (ReviewRequest _ _ _)   = "review-container"
    containerClass (FeedbackRequest _ _ _) = "feedback-container"
    containerClass (AssignedRequest _ _ _)   = "assigned-container"
    containerClass (PendingRequest _ _ _)   = "pending-container"
    containerClass (ReviewedRequest _ _ _)   = "reviewed-container"

    title r = linkNode (url r) [T.toUpper . reqClass $ r]
      where
        url (NeedinfoRequest _ _ _)   = bugURL r
        url (ReviewRequest _ _ att)   = attURL r att
        url (FeedbackRequest _ _ att) = attURL r att
        url (AssignedRequest _ _ _)   = bugURL r
        url (PendingRequest _ _ _)    = bugURL r
        url (ReviewedRequest _ _ _)   = bugURL r

    titleBadge (NeedinfoRequest _ cs flag) = timeBadgeNode lastSeen cs curTime
                                             (flagCreationDate flag)
    titleBadge (ReviewRequest _ cs att)    = timeBadgeNode lastSeen cs curTime
                                             (attachmentCreationTime att)
    titleBadge (FeedbackRequest _ cs att)  = timeBadgeNode lastSeen cs curTime
                                             (attachmentCreationTime att)
    titleBadge (AssignedRequest bug cs _)  = timeBadgeNode lastSeen cs curTime
                                             (bugCreationTime bug)
    titleBadge (PendingRequest bug cs _)   = timeBadgeNode lastSeen cs curTime
                                             (bugCreationTime bug)
    titleBadge (ReviewedRequest bug cs _)   = timeBadgeNode lastSeen cs curTime
                                              (bugCreationTime bug)

    reqClass (NeedinfoRequest _ _ _) = "needinfo"
    reqClass (ReviewRequest _ _ _)   = "review"
    reqClass (FeedbackRequest _ _ _) = "feedback"
    reqClass (AssignedRequest _ _ _) = "assigned"
    reqClass (PendingRequest _ _ _)  = "pending"
    reqClass (ReviewedRequest _ _ _) = "reviewed"

    bugLink r = linkNode (bugURL r) [bugIdText r, ": ", bugSummary . reqBug $ r]

    details (NeedinfoRequest bug _ flag) = []
    details (ReviewRequest bug _ att)    = [ divNode ["detail"] (attachmentNode att)
                                           ]
    details (FeedbackRequest bug _ att)  = [ divNode ["detail"] (attachmentNode att)
                                           ]
    details (AssignedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts)
                                           ]
    details (PendingRequest bug _ atts)  = [ divNode ["detail"] (concatMap attachmentNode atts)
                                           ]
    details (ReviewedRequest bug _ atts) = [ divNode ["detail"] (concatMap attachmentNode atts)
                                           ]

    attachmentNode att =
      [ X.Element "hr" [] []
      , divNode ["attachment"] $
          [ divNode ["attachment-icon"] []
          , pNode' ["attachment-summary"] [attachmentSummary att]
          ] ++ map attachmentFlagNode (attachmentFlags att)
      ]

    attachmentFlagNode f = divNode ["attachment-flag"] $
      [ maybe noSmallGravatar smallGravatarImg (flagRequestee f)
      , X.Element "p" [] $
          [ flagNameNode [flagName f, flagStatus f]
          , textNode [" " , fromMaybe "" (flagRequestee f)]
          ]
      ]

    extended (NeedinfoRequest bug _ flag) = [ divNode ["extended"]
      [ gravatarImg (flagSetter flag)
      , pNode [flagSetter flag]
      , timeNode curTime (flagCreationDate flag)
      ] ]
    extended (ReviewRequest bug _ att) = [ divNode ["extended"]
      [ gravatarImg (attachmentCreator att)
      , pNode [attachmentCreator att]
      , timeNode curTime (attachmentCreationTime att)
      ] ]
    extended (FeedbackRequest bug _ att) = [ divNode ["extended"]
      [ gravatarImg (attachmentCreator att)
      , pNode [attachmentCreator att]
      , timeNode curTime (attachmentCreationTime att)
      ] ]
    extended (AssignedRequest bug _ _) = []
    extended (PendingRequest bug _ _)  = []
    extended (ReviewedRequest bug _ _) = []

    lastComment r = divNode ["last-comment-wrapper"] $
                      map (commentNode r 200) (take 1 . reqComments $ r)

    comments r = divNode ["comments-wrapper"] $
                   [ divNode ["comments-inner-wrapper"] $
                     [ divNode ["comments"] $ map (commentNode r 0) (reqComments r)]]

    commentNode r limit c = divNode ["comment"] $
      [ divNode (commentHeaderClasses lastSeen $ commentCreationTime c) $
          [ gravatarImg (commentCreator c)
          , pNode [commentCreator c]
          , X.Element "p" [] $
            [ linkNode (commentURL r c) ["#", T.pack . show $ commentCount c]
            , textNode [" (", T.pack . show $ commentCreationTime c, ")"]
            ]
          ]
      ] ++ (mergedComments . T.lines . applyLimit limit . commentText $ c)

    mergedComments = concatMap mergeQuotes . groupBy (same numQuotes)
      where
        mergeQuotes [] = []
        mergeQuotes ls@(l:_)
          | isQuote l = if any (";" `T.isSuffixOf`) ls
                          then map (pQuoteNode . (:[])) ls
                          else [pQuoteNode [T.intercalate " " . map stripQuotes $ ls]]
          | otherwise = map (pNode . (:[])) ls

    commentTextNode line
      | ">" `T.isPrefixOf` line = X.Element "p" [classes ["quote"]] [X.TextNode line]
      | otherwise               = pNode [line]

    gravatarImg email = divNode ["gravatar"] [X.Element "img" [("src", url)] []]
      where
        url = T.pack $ G.gravatar settings email
        settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 48 }

    smallGravatarImg email = divNode ["small-gravatar"] [X.Element "img" [("src", url)] []]
      where
        url = T.pack $ G.gravatar settings email
        settings = def { G.gDefault = Just G.Retro, G.gSize = Just $ G.Size 32 }

    noGravatar = divNode ["no-gravatar"] []
    noSmallGravatar = divNode ["no-small-gravatar"] []

attURL :: BzRequest -> Attachment -> T.Text
attURL r att = T.concat [ "https://bugzilla.mozilla.org/page.cgi?id=splinter.html&bug="
                        , bugIdText r
                        , "&attachment="
                        , attachmentIdText att
                        ]

bugURL :: BzRequest -> T.Text
bugURL r = T.concat ["https://bugzilla.mozilla.org/show_bug.cgi?id=", bugIdText r]

commentURL :: BzRequest -> Comment -> T.Text
commentURL r c = T.concat [ "https://bugzilla.mozilla.org/show_bug.cgi?id="
                          , bugIdText r
                          , "#c"
                          , commentIdText c
                          ]

attachmentIdText :: Attachment -> T.Text
attachmentIdText = T.pack . show . attachmentId

bugIdText :: BzRequest -> T.Text
bugIdText = T.pack . show . bugId . reqBug

commentIdText :: Comment -> T.Text
commentIdText = T.pack . show . commentCount

classes :: [T.Text] -> (T.Text, T.Text)
classes cs = ("class", T.intercalate " " cs)

textNode :: [T.Text] -> X.Node
textNode = X.TextNode . T.concat

linkNode :: T.Text -> [T.Text] -> X.Node
linkNode url ts = X.Element "a" [("href", url)] [textNode ts]

pNode :: [T.Text] -> X.Node
pNode ts = X.Element "p" [] [textNode ts]

flagNameNode :: [T.Text] -> X.Node
flagNameNode ts = X.Element "span" [classes ["flag-name"]] [textNode ts]

pNode' :: [T.Text] -> [T.Text] -> X.Node
pNode' cs ts = X.Element "p" [classes cs] [textNode ts]

pQuoteNode :: [T.Text] -> X.Node
pQuoteNode ts = X.Element "p" [classes ["quote"]] [textNode ts]

isQuote :: T.Text -> Bool
isQuote = (">" `T.isPrefixOf`)

divNode :: [T.Text] -> [X.Node] -> X.Node
divNode cs es = X.Element "div" [classes cs] es

oneWeek, twoWeeks, oneMonth :: NominalDiffTime
oneWeek  = fromIntegral $ 1 * 604800
twoWeeks = fromIntegral $ 2 * 604800
oneMonth = fromIntegral $ 4 * 604800

timeNode :: UTCTime -> UTCTime -> X.Node
timeNode curTime itemTime
  | timeDiff > oneWeek  = node ["overdue"]
  | otherwise           = node []
  where
    timeDiff = curTime `diffUTCTime` itemTime
    node cs = X.Element "p" [classes cs]
                            [textNode [T.pack . show $ itemTime]]

timeBadgeNode :: UTCTime -> [Comment] -> UTCTime -> UTCTime -> [X.Node]
timeBadgeNode lastSeen cs curTime itemTime = newComment cs ++ overdue
  where
    newComment (c:_)
      | commentTimeDiff > 0 = [divNode ["left-badge"] [textNode ["+"]]]
      | otherwise           = []
      where
        commentTimeDiff = (commentCreationTime c) `diffUTCTime` lastSeen

    newComment _ = []

    overdue
      | overdueTimeDiff > oneMonth = [overdueNode ["!!!"]]
      | overdueTimeDiff > twoWeeks = [overdueNode ["!!"]]
      | overdueTimeDiff > oneWeek  = [overdueNode ["!"]]
      | otherwise                  = []
      where
        overdueTimeDiff = curTime `diffUTCTime` itemTime
        overdueNode ts  = divNode ["right-badge"] [textNode ts]

commentHeaderClasses :: UTCTime -> UTCTime -> [T.Text]
commentHeaderClasses lastSeen itemTime
  | timeDiff > 0 = ["comment-header", "new-comment"]
  | otherwise    = ["comment-header"]
  where
    timeDiff = itemTime `diffUTCTime` lastSeen

same :: Eq b => (a -> b) -> a -> a -> Bool
same f a b = f a == f b

numQuotes :: T.Text -> Int
numQuotes = length . takeWhile (== "> ") . T.chunksOf 2

stripQuotes :: T.Text -> T.Text
stripQuotes = T.concat . dropWhile (== "> ") . T.chunksOf 2

applyLimit :: Int -> T.Text -> T.Text
applyLimit 0 = id
applyLimit n = (`T.append` "...") . T.take n

countRequests :: [BzRequest] -> (Int, Int, Int, Int, Int, Int)
countRequests rs = go (0, 0, 0, 0, 0, 0) rs
  where
    go !count [] = count
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((NeedinfoRequest _ _ _) : rs) = go (nis + 1, rvs, fbs, as, ps, rds) rs
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewRequest _ _ _) : rs)   = go (nis, rvs + 1, fbs, as, ps, rds) rs
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((FeedbackRequest _ _ _) : rs) = go (nis, rvs, fbs + 1, as, ps, rds) rs
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((AssignedRequest _ _ _) : rs) = go (nis, rvs, fbs, as + 1, ps, rds) rs
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((PendingRequest _ _ _) : rs)  = go (nis, rvs, fbs, as, ps + 1, rds) rs
    go (!nis, !rvs, !fbs, !as, !ps, !rds) ((ReviewedRequest _ _ _) : rs) = go (nis, rvs, fbs, as, ps, rds + 1) rs

------------------------------------------------------------------------------
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login",     with auth handleLoginSubmit)
         , ("/logout",    with auth handleLogout)
         , ("/new_user",  with auth handleNewUser)
         , ("/dashboard", with auth handleDashboard)
         , ("",           serveDirectory "static")
         ]

------------------------------------------------------------------------------
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
    h <- nestSnaplet "" heist $ heistInit "templates"
    s <- nestSnaplet "sess" sess $
           initCookieSessionManager "site_key.txt" "sess" (Just 3600)

    -- NOTE: We're using initJsonFileAuthManager here because it's easy and
    -- doesn't require any kind of database server to run.  In practice,
    -- you'll probably want to change this to a more robust auth backend.
    a <- nestSnaplet "auth" auth $
           initJsonFileAuthManager defAuthSettings sess "users.json"

    state <- liftIO $ AS.openLocalState (AppState M.empty M.empty)
    onUnload (AS.closeAcidState state)
    acid <- nestSnaplet "acid" acid $ acidInitManual state

    addRoutes routes
    addAuthSplices h auth

    mvSessions <- liftIO $ newMVar M.empty
    t <- liftIO $ async $ pollBugzilla mvSessions state 15

    return $ App h s a acid t mvSessions

pollBugzilla :: MVar (M.Map UserLogin BugzillaSession) -> AS.AcidState AppState -> Int -> IO ()
pollBugzilla !mvSessions !state !intervalMin = do
  -- Wait appropriately.
  let intervalUs = 60000000 * intervalMin
  threadDelay intervalUs

  -- Update all users with current sessions.
  sessions <- readMVar mvSessions
  forM_ (M.toList sessions) $ \(user, session) -> do
    putStrLn $ "Updating requests from Bugzilla for user " ++ show user
    reqs <- bzRequests session user
    AS.update state $ UpdateRequests user reqs

  -- Do it again.
  pollBugzilla mvSessions state intervalMin


text:
package runtime

import (
	"runtime/internal/atomic"
	"runtime/internal/sys"
	"unsafe"
)

// Addresses collected in a cgo backtrace when crashing.
// Length must match arg.Max in x_cgo_callers in runtime/cgo/gcc_traceback.c.
type cgoCallers [32]uintptr

// Call from Go to C.
//
// This must be nosplit because it's used for syscalls on some
// platforms. Syscalls may have untyped arguments on the stack, so
// it's not safe to grow or scan the stack.
//
//go:nosplit
func cgocall(fn, arg unsafe.Pointer) int32 {
	if !iscgo && GOOS != "solaris" && GOOS != "illumos" && GOOS != "windows" {
		throw("cgocall unavailable")
	}

	if fn == nil {
		throw("cgocall nil")
	}

	if raceenabled {
		racereleasemerge(unsafe.Pointer(&racecgosync))
	}

	mp := getg().m
	mp.ncgocall++
	mp.ncgo++

	// Reset traceback.
	mp.cgoCallers[0] = 0

	// Announce we are entering a system call
	// so that the scheduler knows to create another
	// M to run goroutines while we are in the
	// foreign code.
	//
	// The call to asmcgocall is guaranteed not to
	// grow the stack and does not allocate memory,
	// so it is safe to call while "in a system call", outside
	// the $GOMAXPROCS accounting.
	//
	// fn may call back into Go code, in which case we'll exit the
	// "system call", run the Go code (which may grow the stack),
	// and then re-enter the "system call" reusing the PC and SP
	// saved by entersyscall here.
	entersyscall()

	// Tell asynchronous preemption that we're entering external
	// code. We do this after entersyscall because this may block
	// and cause an async preemption to fail, but at this point a
	// sync preemption will succeed (though this is not a matter
	// of correctness).
	osPreemptExtEnter(mp)

	mp.incgo = true
	errno := asmcgocall(fn, arg)

	// Update accounting before exitsyscall because exitsyscall may
	// reschedule us on to a different M.
	mp.incgo = false
	mp.ncgo--

	osPreemptExtExit(mp)

	exitsyscall()

	// Note that raceacquire must be called only after exitsyscall has
	// wired this M to a P.
	if raceenabled {
		raceacquire(unsafe.Pointer(&racecgosync))
	}

	// From the garbage collector's perspective, time can move
	// backwards in the sequence above. If there's a callback into
	// Go code, GC will see this function at the call to
	// asmcgocall. When the Go call later returns to C, the
	// syscall PC/SP is rolled back and the GC sees this function
	// back at the call to entersyscall. Normally, fn and arg
	// would be live at entersyscall and dead at asmcgocall, so if
	// time moved backwards, GC would see these arguments as dead
	// and then live. Prevent these undead arguments from crashing
	// GC by forcing them to stay live across this time warp.
	KeepAlive(fn)
	KeepAlive(arg)
	KeepAlive(mp)

	return errno
}

// Call from C back to Go.
//go:nosplit
func cgocallbackg(ctxt uintptr) {
	gp := getg()
	if gp != gp.m.curg {
		println("runtime: bad g in cgocallback")
		exit(2)
	}

	// The call from C is on gp.m's g0 stack, so we must ensure
	// that we stay on that M. We have to do this before calling
	// exitsyscall, since it would otherwise be free to move us to
	// a different M. The call to unlockOSThread is in unwindm.
	lockOSThread()

	// Save current syscall parameters, so m.syscall can be
	// used again if callback decide to make syscall.
	syscall := gp.m.syscall

	// entersyscall saves the caller's SP to allow the GC to trace the Go
	// stack. However, since we're returning to an earlier stack frame and
	// need to pair with the entersyscall() call made by cgocall, we must
	// save syscall* and let reentersyscall restore them.
	savedsp := unsafe.Pointer(gp.syscallsp)
	savedpc := gp.syscallpc
	exitsyscall() // coming out of cgo call
	gp.m.incgo = false

	osPreemptExtExit(gp.m)

	cgocallbackg1(ctxt)

	// At this point unlockOSThread has been called.
	// The following code must not change to a different m.
	// This is enforced by checking incgo in the schedule function.

	osPreemptExtEnter(gp.m)

	gp.m.incgo = true
	// going back to cgo call
	reentersyscall(savedpc, uintptr(savedsp))

	gp.m.syscall = syscall
}

func cgocallbackg1(ctxt uintptr) {
	gp := getg()
	if gp.m.needextram || atomic.Load(&extraMWaiters) > 0 {
		gp.m.needextram = false
		systemstack(newextram)
	}

	if ctxt != 0 {
		s := append(gp.cgoCtxt, ctxt)

		// Now we need to set gp.cgoCtxt = s, but we could get
		// a SIGPROF signal while manipulating the slice, and
		// the SIGPROF handler could pick up gp.cgoCtxt while
		// tracing up the stack.  We need to ensure that the
		// handler always sees a valid slice, so set the
		// values in an order such that it always does.
		p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
		atomicstorep(unsafe.Pointer(&p.array), unsafe.Pointer(&s[0]))
		p.cap = cap(s)
		p.len = len(s)

		defer func(gp *g) {
			// Decrease the length of the slice by one, safely.
			p := (*slice)(unsafe.Pointer(&gp.cgoCtxt))
			p.len--
		}(gp)
	}

	if gp.m.ncgo == 0 {
		// The C call to Go came from a thread not currently running
		// any Go. In the case of -buildmode=c-archive or c-shared,
		// this call may be coming in before package initialization
		// is complete. Wait until it is.
		<-main_init_done
	}

	// Add entry to defer stack in case of panic.
	restore := true
	defer unwindm(&restore)

	if raceenabled {
		raceacquire(unsafe.Pointer(&racecgosync))
	}

	type args struct {
		fn      *funcval
		arg     unsafe.Pointer
		argsize uintptr
	}
	var cb *args

	// Location of callback arguments depends on stack frame layout
	// and size of stack frame of cgocallback_gofunc.
	sp := gp.m.g0.sched.sp
	switch GOARCH {
	default:
		throw("cgocallbackg is unimplemented on arch")
	case "arm":
		// On arm, stack frame is two words and there's a saved LR between
		// SP and the stack frame and between the stack frame and the arguments.
		cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize))
	case "arm64":
		// On arm64, stack frame is four words and there's a saved LR between
		// SP and the stack frame and between the stack frame and the arguments.
		// Additional two words (16-byte alignment) are for saving FP.
		cb = (*args)(unsafe.Pointer(sp + 7*sys.PtrSize))
	case "amd64":
		// On amd64, stack frame is two words, plus caller PC.
		if framepointer_enabled {
			// In this case, there's also saved BP.
			cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize))
			break
		}
		cb = (*args)(unsafe.Pointer(sp + 3*sys.PtrSize))
	case "386":
		// On 386, stack frame is three words, plus caller PC.
		cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize))
	case "ppc64", "ppc64le", "s390x":
		// On ppc64 and s390x, the callback arguments are in the arguments area of
		// cgocallback's stack frame. The stack looks like this:
		// +--------------------+------------------------------+
		// |                    | ...                          |
		// | cgoexp_$fn         +------------------------------+
		// |                    | fixed frame area             |
		// +--------------------+------------------------------+
		// |                    | arguments area               |
		// | cgocallback        +------------------------------+ <- sp + 2*minFrameSize + 2*ptrSize
		// |                    | fixed frame area             |
		// +--------------------+------------------------------+ <- sp + minFrameSize + 2*ptrSize
		// |                    | local variables (2 pointers) |
		// | cgocallback_gofunc +------------------------------+ <- sp + minFrameSize
		// |                    | fixed frame area             |
		// +--------------------+------------------------------+ <- sp
		cb = (*args)(unsafe.Pointer(sp + 2*sys.MinFrameSize + 2*sys.PtrSize))
	case "mips64", "mips64le":
		// On mips64x, stack frame is two words and there's a saved LR between
		// SP and the stack frame and between the stack frame and the arguments.
		cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize))
	case "mips", "mipsle":
		// On mipsx, stack frame is two words and there's a saved LR between
		// SP and the stack frame and between the stack frame and the arguments.
		cb = (*args)(unsafe.Pointer(sp + 4*sys.PtrSize))
	}

	// Invoke callback.
	// NOTE(rsc): passing nil for argtype means that the copying of the
	// results back into cb.arg happens without any corresponding write barriers.
	// For cgo, cb.arg points into a C stack frame and therefore doesn't
	// hold any pointers that the GC can find anyway - the write barrier
	// would be a no-op.
	reflectcall(nil, unsafe.Pointer(cb.fn), cb.arg, uint32(cb.argsize), 0)

	if raceenabled {
		racereleasemerge(unsafe.Pointer(&racecgosync))
	}
	if msanenabled {
		// Tell msan that we wrote to the entire argument block.
		// This tells msan that we set the results.
		// Since we have already called the function it doesn't
		// matter that we are writing to the non-result parameters.
		msanwrite(cb.arg, cb.argsize)
	}

	// Do not unwind m->g0->sched.sp.
	// Our caller, cgocallback, will do that.
	restore = false
}

func unwindm(restore *bool) {
	if *restore {
		// Restore sp saved by cgocallback during
		// unwind of g's stack (see comment at top of file).
		mp := acquirem()
		sched := &mp.g0.sched
		switch GOARCH {
		default:
			throw("unwindm not implemented")
		case "386", "amd64", "arm", "ppc64", "ppc64le", "mips64", "mips64le", "s390x", "mips", "mipsle":
			sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + sys.MinFrameSize))
		case "arm64":
			sched.sp = *(*uintptr)(unsafe.Pointer(sched.sp + 16))
		}

		// Do the accounting that cgocall will not have a chance to do
		// during an unwind.
		//
		// In the case where a Go call originates from C, ncgo is 0
		// and there is no matching cgocall to end.
		if mp.ncgo > 0 {
			mp.incgo = false
			mp.ncgo--
			osPreemptExtExit(mp)
		}

		releasem(mp)
	}

	// Undo the call to lockOSThread in cgocallbackg.
	// We must still stay on the same m.
	unlockOSThread()
}

// called from assembly
func badcgocallback() {
	throw("misaligned stack in cgocallback")
}

// called from (incomplete) assembly
func cgounimpl() {
	throw("cgo not implemented")
}

var racecgosync uint64 // represents possible synchronization in C code

// Pointer checking for cgo code.

// We want to detect all cases where a program that does not use
// unsafe makes a cgo call passing a Go pointer to memory that
// contains a Go pointer. Here a Go pointer is defined as a pointer
// to memory allocated by the Go runtime. Programs that use unsafe
// can evade this restriction easily, so we don't try to catch them.
// The cgo program will rewrite all possibly bad pointer arguments to
// call cgoCheckPointer, where we can catch cases of a Go pointer
// pointing to a Go pointer.

// Complicating matters, taking the address of a slice or array
// element permits the C program to access all elements of the slice
// or array. In that case we will see a pointer to a single element,
// but we need to check the entire data structure.

// The cgoCheckPointer call takes additional arguments indicating that
// it was called on an address expression. An additional argument of
// true means that it only needs to check a single element. An
// additional argument of a slice or array means that it needs to
// check the entire slice/array, but nothing else. Otherwise, the
// pointer could be anything, and we check the entire heap object,
// which is conservative but safe.

// When and if we implement a moving garbage collector,
// cgoCheckPointer will pin the pointer for the duration of the cgo
// call.  (This is necessary but not sufficient; the cgo program will
// also have to change to pin Go pointers that cannot point to Go
// pointers.)

// cgoCheckPointer checks if the argument contains a Go pointer that
// points to a Go pointer, and panics if it does.
func cgoCheckPointer(ptr interface{}, arg interface{}) {
	if debug.cgocheck == 0 {
		return
	}

	ep := efaceOf(&ptr)
	t := ep._type

	top := true
	if arg != nil && (t.kind&kindMask == kindPtr || t.kind&kindMask == kindUnsafePointer) {
		p := ep.data
		if t.kind&kindDirectIface == 0 {
			p = *(*unsafe.Pointer)(p)
		}
		if p == nil || !cgoIsGoPointer(p) {
			return
		}
		aep := efaceOf(&arg)
		switch aep._type.kind & kindMask {
		case kindBool:
			if t.kind&kindMask == kindUnsafePointer {
				// We don't know the type of the element.
				break
			}
			pt := (*ptrtype)(unsafe.Pointer(t))
			cgoCheckArg(pt.elem, p, true, false, cgoCheckPointerFail)
			return
		case kindSlice:
			// Check the slice rather than the pointer.
			ep = aep
			t = ep._type
		case kindArray:
			// Check the array rather than the pointer.
			// Pass top as false since we have a pointer
			// to the array.
			ep = aep
			t = ep._type
			top = false
		default:
			throw("can't happen")
		}
	}

	cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, top, cgoCheckPointerFail)
}

const cgoCheckPointerFail = "cgo argument has Go pointer to Go pointer"
const cgoResultFail = "cgo result has Go pointer"

// cgoCheckArg is the real work of cgoCheckPointer. The argument p
// is either a pointer to the value (of type t), or the value itself,
// depending on indir. The top parameter is whether we are at the top
// level, where Go pointers are allowed.
func cgoCheckArg(t *_type, p unsafe.Pointer, indir, top bool, msg string) {
	if t.ptrdata == 0 || p == nil {
		// If the type has no pointers there is nothing to do.
		return
	}

	switch t.kind & kindMask {
	default:
		throw("can't happen")
	case kindArray:
		at := (*arraytype)(unsafe.Pointer(t))
		if !indir {
			if at.len != 1 {
				throw("can't happen")
			}
			cgoCheckArg(at.elem, p, at.elem.kind&kindDirectIface == 0, top, msg)
			return
		}
		for i := uintptr(0); i < at.len; i++ {
			cgoCheckArg(at.elem, p, true, top, msg)
			p = add(p, at.elem.size)
		}
	case kindChan, kindMap:
		// These types contain internal pointers that will
		// always be allocated in the Go heap. It's never OK
		// to pass them to C.
		panic(errorString(msg))
	case kindFunc:
		if indir {
			p = *(*unsafe.Pointer)(p)
		}
		if !cgoIsGoPointer(p) {
			return
		}
		panic(errorString(msg))
	case kindInterface:
		it := *(**_type)(p)
		if it == nil {
			return
		}
		// A type known at compile time is OK since it's
		// constant. A type not known at compile time will be
		// in the heap and will not be OK.
		if inheap(uintptr(unsafe.Pointer(it))) {
			panic(errorString(msg))
		}
		p = *(*unsafe.Pointer)(add(p, sys.PtrSize))
		if !cgoIsGoPointer(p) {
			return
		}
		if !top {
			panic(errorString(msg))
		}
		cgoCheckArg(it, p, it.kind&kindDirectIface == 0, false, msg)
	case kindSlice:
		st := (*slicetype)(unsafe.Pointer(t))
		s := (*slice)(p)
		p = s.array
		if p == nil || !cgoIsGoPointer(p) {
			return
		}
		if !top {
			panic(errorString(msg))
		}
		if st.elem.ptrdata == 0 {
			return
		}
		for i := 0; i < s.cap; i++ {
			cgoCheckArg(st.elem, p, true, false, msg)
			p = add(p, st.elem.size)
		}
	case kindString:
		ss := (*stringStruct)(p)
		if !cgoIsGoPointer(ss.str) {
			return
		}
		if !top {
			panic(errorString(msg))
		}
	case kindStruct:
		st := (*structtype)(unsafe.Pointer(t))
		if !indir {
			if len(st.fields) != 1 {
				throw("can't happen")
			}
			cgoCheckArg(st.fields[0].typ, p, st.fields[0].typ.kind&kindDirectIface == 0, top, msg)
			return
		}
		for _, f := range st.fields {
			if f.typ.ptrdata == 0 {
				continue
			}
			cgoCheckArg(f.typ, add(p, f.offset()), true, top, msg)
		}
	case kindPtr, kindUnsafePointer:
		if indir {
			p = *(*unsafe.Pointer)(p)
			if p == nil {
				return
			}
		}

		if !cgoIsGoPointer(p) {
			return
		}
		if !top {
			panic(errorString(msg))
		}

		cgoCheckUnknownPointer(p, msg)
	}
}

// cgoCheckUnknownPointer is called for an arbitrary pointer into Go
// memory. It checks whether that Go memory contains any other
// pointer into Go memory. If it does, we panic.
// The return values are unused but useful to see in panic tracebacks.
func cgoCheckUnknownPointer(p unsafe.Pointer, msg string) (base, i uintptr) {
	if inheap(uintptr(p)) {
		b, span, _ := findObject(uintptr(p), 0, 0)
		base = b
		if base == 0 {
			return
		}
		hbits := heapBitsForAddr(base)
		n := span.elemsize
		for i = uintptr(0); i < n; i += sys.PtrSize {
			if i != 1*sys.PtrSize && !hbits.morePointers() {
				// No more possible pointers.
				break
			}
			if hbits.isPointer() && cgoIsGoPointer(*(*unsafe.Pointer)(unsafe.Pointer(base + i))) {
				panic(errorString(msg))
			}
			hbits = hbits.next()
		}

		return
	}

	for _, datap := range activeModules() {
		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
			// We have no way to know the size of the object.
			// We have to assume that it might contain a pointer.
			panic(errorString(msg))
		}
		// In the text or noptr sections, we know that the
		// pointer does not point to a Go pointer.
	}

	return
}

// cgoIsGoPointer reports whether the pointer is a Go pointer--a
// pointer to Go memory. We only care about Go memory that might
// contain pointers.
//go:nosplit
//go:nowritebarrierrec
func cgoIsGoPointer(p unsafe.Pointer) bool {
	if p == nil {
		return false
	}

	if inHeapOrStack(uintptr(p)) {
		return true
	}

	for _, datap := range activeModules() {
		if cgoInRange(p, datap.data, datap.edata) || cgoInRange(p, datap.bss, datap.ebss) {
			return true
		}
	}

	return false
}

// cgoInRange reports whether p is between start and end.
//go:nosplit
//go:nowritebarrierrec
func cgoInRange(p unsafe.Pointer, start, end uintptr) bool {
	return start <= uintptr(p) && uintptr(p) < end
}

// cgoCheckResult is called to check the result parameter of an
// exported Go function. It panics if the result is or contains a Go
// pointer.
func cgoCheckResult(val interface{}) {
	if debug.cgocheck == 0 {
		return
	}

	ep := efaceOf(&val)
	t := ep._type
	cgoCheckArg(t, ep.data, t.kind&kindDirectIface == 0, false, cgoResultFail)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Omphalia atripes Rabenh.

### Remarks
null


text:
<link rel="import" href="../../../bower_components/polymer/polymer.html">

<link rel="import" href="../../shared/gr-rest-api-interface/gr-rest-api-interface.html">
<link rel="import" href="../../shared/gr-tooltip-content/gr-tooltip-content.html">
<link rel="import" href="../../../styles/shared-styles.html">

<dom-module id="gr-change-status">
  <template>

    <gr-tooltip-content
        has-tooltip
        position-below
        title="[[tooltipText]]"
        max-width="40em">

          [[_computeStatusString(status)]]

    </gr-tooltip-content>
  </template>

</dom-module>


text:
using System.Threading.Tasks;
using JustBehave;
using JustSaying.Messaging;
using JustSaying.TestingFramework;
using NSubstitute;

namespace JustSaying.UnitTests.JustSayingBus
{
    public class WhenPublishingMessages : GivenAServiceBus
    {
        private readonly IMessagePublisher _publisher = Substitute.For<IMessagePublisher>();

        protected override async Task When()
        {
            SystemUnderTest.AddMessagePublisher<GenericMessage>(_publisher, string.Empty);

            await SystemUnderTest.PublishAsync(new GenericMessage());
        }

        [Then]
        public void PublisherIsCalledToPublish()
        {
            _publisher.Received().PublishAsync(Arg.Any<GenericMessage>());
        }

        [Then]
        public void PublishMessageTimeStatsSent()
        {
            Monitor.Received(1).PublishMessageTime(Arg.Any<long>());
        }
    }
}


text:
GLSL practice
=============

## Sandbox

* https://github.com/mrdoob/glsl-sandbox
* https://www.shadertoy.com/


text:
class Game < ActiveRecord::Base
  has_many :hit_challenges
  has_many :prop_bets
  has_many :away_players
  has_many :home_players
  has_many :suites
  has_many :pitch_speeds

  accepts_nested_attributes_for :suites

   def total_hits
    home_players = self.home_players
    away_players = self.away_players
    total_at_bat = 0
    away_players.each do |p|
      total_at_bat += p.at_bat
    end
    home_players.each do |p|
      total_at_bat += p.at_bat
    end
    total_at_bat
  end

  def has_hit_challenge
    (self.hit_challenges.count > 0) ? true : false
  end

  def has_prop_bet
    (self.prop_bets.count > 0) ? true : false
  end

  def has_pitch_speed
    (self.pitch_speeds.count > 0) ? true : false
  end

end


text:
package com.wxs.aop.interceptor;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @Author: yoyo
 * @Description:
 * @Date: Created in 2019/4/4 14:18
 */
public class ClientInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        return null;
    }
}


text:
import {FocusableOption} from '@angular/cdk/a11y';
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  OnDestroy,
  ViewEncapsulation,
} from '@angular/core';
import {CanDisable, mixinDisabled} from '@angular/material/core';
import {Subject} from 'rxjs/Subject';

// Boilerplate for applying mixins to MatMenuItem.
/** @docs-private */
export class MatMenuItemBase {}
export const _MatMenuItemMixinBase = mixinDisabled(MatMenuItemBase);

/**
 * This directive is intended to be used inside an mat-menu tag.
 * It exists mostly to set the role attribute.
 */
@Component({
  moduleId: module.id,
  selector: '[mat-menu-item]',
  exportAs: 'matMenuItem',
  inputs: ['disabled'],
  host: {
    'role': 'menuitem',
    'class': 'mat-menu-item',
    '[class.mat-menu-item-highlighted]': '_highlighted',
    '[class.mat-menu-item-submenu-trigger]': '_triggersSubmenu',
    '[attr.tabindex]': '_getTabIndex()',
    '[attr.aria-disabled]': 'disabled.toString()',
    '[attr.disabled]': 'disabled || null',
    '(click)': '_checkDisabled($event)',
    '(mouseenter)': '_emitHoverEvent()',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  preserveWhitespaces: false,
  templateUrl: 'menu-item.html',
})
export class MatMenuItem extends _MatMenuItemMixinBase implements FocusableOption, CanDisable,
  OnDestroy {

  /** Stream that emits when the menu item is hovered. */
  _hovered: Subject<MatMenuItem> = new Subject();

  /** Whether the menu item is highlighted. */
  _highlighted: boolean = false;

  /** Whether the menu item acts as a trigger for a sub-menu. */
  _triggersSubmenu: boolean = false;

  constructor(private _elementRef: ElementRef) {
    super();
  }

  /** Focuses the menu item. */
  focus(): void {
    this._getHostElement().focus();
  }

  ngOnDestroy() {
    this._hovered.complete();
  }

  /** Used to set the `tabindex`. */
  _getTabIndex(): string {
    return this.disabled ? '-1' : '0';
  }

  /** Returns the host DOM element. */
  _getHostElement(): HTMLElement {
    return this._elementRef.nativeElement;
  }

  /** Prevents the default element actions if it is disabled. */
  _checkDisabled(event: Event): void {
    if (this.disabled) {
      event.preventDefault();
      event.stopPropagation();
    }
  }

  /** Emits to the hover stream. */
  _emitHoverEvent() {
    if (!this.disabled) {
      this._hovered.next(this);
    }
  }

  /** Gets the label to be used when determining whether the option should be focused. */
  getLabel(): string {
    const element: HTMLElement = this._elementRef.nativeElement;
    let output = '';

    if (element.childNodes) {
      const length = element.childNodes.length;

      // Go through all the top-level text nodes and extract their text.
      // We skip anything that's not a text node to prevent the text from
      // being thrown off by something like an icon.
      for (let i = 0; i < length; i++) {
        if (element.childNodes[i].nodeType === Node.TEXT_NODE) {
          output += element.childNodes[i].textContent;
        }
      }
    }

    return output.trim();
  }

}


text:
export default {
    CLIENT_ID     : process.env.GD_CLIENT_ID,
    API_KEY       : process.env.GD_API_KEY,
    APP_ID        : process.env.GD_APP_ID,
    API_URL       : 'https://apis.google.com/js/api.js',
    AUTH_SCOPE    : 'client:auth2:picker',
    SCOPE         : 'https://www.googleapis.com/auth/drive.file',
    DISCOVERY_DOCS: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
};


text:
Common Use Cases
================

Example Application
-------------------

Here is a simple *hello world* application that uses Flask-WeasyPrint:

.. code-block:: python

    from flask import Flask, render_template, url_for
    from flask_weasyprint import HTML, render_pdf

    app = Flask(__name__)

    @app.route('/hello/', defaults={'name': 'World'})
    @app.route('/hello/<name>/')
    def hello_html(name):
        return render_template('hello.html', name=name)

    @app.route('/hello_<name>.pdf')
    def hello_pdf(name):
        # Make a PDF from another view
        return render_pdf(url_for('hello_html', name=name))

    # Alternatively, if the PDF does not have a matching HTML page:

    @app.route('/hello_<name>.pdf')
    def hello_pdf(name):
        # Make a PDF straight from HTML in a string.
        html = render_template('hello.html', name=name)
        return render_pdf(HTML(string=html))

``templates/hello.html``:

.. code-block:: html+jinja

    <!doctype html>
    <title>Hello</title>
    <link rel=stylesheet href="{{ url_for('static', filename='style.css') }}" />

Hello, {{ name }}!

    Get as PDF

``static/style.css``:

.. code-block:: css

    body { font: 2em Fontin, serif }
    nav { font-size: .7em }

    @page { size: A5; margin: 1cm }
    @media print {
        nav { display: none }
    }

:func:`flask_weasyprint.render_pdf` helps making a :class:`flask.Response` with
the correct MIME type. You can give it an URL or an ``HTML`` object.

In the HTML you can use :func:`flask.url_for` or relative URLs.
Flask-WeasyPrint will do the right thing to fetch resources and make hyperlinks
absolute in the PDF output.

In CSS, ``@page`` and ``@media print`` can be used to have print-specific
styles. Here the "Get as PDF" link is not displayed in the PDF itself, although
it still exists in the HTML.

Testing Application
-------------------

A custom application has been created to test Flask-WeasyPrint. It includes
separate code for the common Flask application and the Flask-WeasyPrint
specific part.

You can find it in `Flask-WeasyPrint's repository`_.

.. _Flask-WeasyPrint's repository: https://github.com/Kozea/Flask-WeasyPrint/blob/master/tests/__init__.py


text:
require "stringio"
module Wizport
  module Rtf
    class Document < Element
      def initialize(file = nil, &block)
        super
        group do
          cmd :rtf, 1
          cmd :ansi
          cmd :ansicpg, 2052
          cmd :deff, 0
          group do
            cmd :fonttbl
            group do
              delimit do
                cmd :f, 0
                cmd :fcharset, 0
                write " Courier"
              end
            end
          end
          group do
            cmd :colortbl
            delimit
            delimit do
              cmd :red, 0
              cmd :green, 0
              cmd :blue, 0
            end
            delimit do
              cmd :red, 255
              cmd :green, 0
              cmd :blue,0
            end
          end
          block.arity<1 ? self.instance_eval(&block) : block.call(self) if block_given?
        end
        save file if file
      end

      def text(str, styles = {:align => :left})
        Wizport::Rtf::Text.new(self, str, styles)
      end

      #creates a new table.
      def table(rows = [],options = {}, &block)
        Wizport::Rtf::Table.new(self, rows, options, &block)
      end

      def image(file)
        Wizport::Rtf::Image.new(self, file)
      end

      def line_break
        cmd :par
      end

      #writes a page interruption (new page)
      def page_break
        cmd :page
      end

      def to_s

      end

      def to_doc
        @rtf.string
      end

      def save(file)
        File.open(file, 'w') { |file| file.write(to_doc) }
      end

    end
  end
end


text:
package de.university.reutlingen.aufgabe2.a3;

public class ProductDescription {
	private String produktGruppe;
	private String beschreibungsText;

	public ProductDescription(String produktGruppeX, String beschreibungsTextX) {
		this.produktGruppe = produktGruppeX;
		this.beschreibungsText = beschreibungsTextX;
	}

	public enum PriceLevel {
		LOW(9.99), MEDIUM(19.99), HIGH(49.99), EXCLUSIVE(99.99);
		private double zahl;

		private PriceLevel(double zahlX) {
			this.zahl = zahlX;
		}

		@Override
		public String toString() {
			return String.valueOf(zahl);
		}
	}

	public void setProduktGruppe(String value) {
		this.produktGruppe = value;
	}

	public String getProduktGruppe() {
		return this.produktGruppe;
	}

	public void setBeschreibungsText(String value) {
		this.beschreibungsText = value;
	}

	public String getBeschreibungsText() {
		return this.beschreibungsText;
	}

	@Override
	public String toString() {
		return "ProductDescription: " + produktGruppe
				+ ", beschreibungsText : " + beschreibungsText;
	}

}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Three.js StarterApp</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="assets/css/main.css">


text:
require 'spec_helper'

describe OAuth2::Provider.access_token_class do
  describe "any instance" do
    subject do
      OAuth2::Provider.access_token_class.new :authorization => build_authorization
    end

    it "is valid with an access grant, expiry time and access token" do
      subject.expires_at.should_not be_nil
      subject.access_token.should_not be_nil
      subject.authorization.should_not be_nil

      subject.should be_valid
    end

    it "is invalid without an access token" do
      subject.access_token = nil
      subject.should_not be_valid
    end

    it "is invalid without an access grant" do
      subject.authorization = nil
      subject.should_not be_valid
    end

    it "is invalid if expires_at is later than the authorization's value" do
      subject.authorization.expires_at = 1.minute.from_now
      subject.expires_at = 10.minutes.from_now
      subject.should_not be_valid
    end

    it "returns time in seconds until expiry when expires_in called" do
      subject.expires_at = 60.minutes.from_now
      subject.expires_in.should == (60 * 60)
    end

    it "returns 0 for expires_in when already expired" do
      subject.expires_at = 60.minutes.ago
      subject.expires_in.should == 0
    end

    it "returns nil for expires_in when no expiry time is set" do
      subject.expires_at = nil
      subject.expires_in.should be_nil
    end

    it "includes expires_in, refresh_token and access_token as JSON format" do
      subject.as_json.should == {"expires_in" => subject.expires_in, "access_token" => subject.access_token, "refresh_token" => subject.refresh_token}
    end

    it "excludes refresh_token from JSON format if no refresh token set" do
      subject.refresh_token = nil
      subject.as_json.should == {"expires_in" => subject.expires_in, "access_token" => subject.access_token}
    end

    it "excludes expires_in from JSON format if expiry time set" do
      subject.expires_at = nil
      subject.as_json.should == {"refresh_token" => subject.refresh_token, "access_token" => subject.access_token}
    end

    it "is refreshable, if it has a refresh token" do
      subject.refresh_token = 'abcd1234'
      subject.should be_refreshable
    end

    it "is not refreshable if it has no refresh token" do
      subject.refresh_token = nil
      subject.should_not be_refreshable
    end

    it "is not refreshable if it has a refresh token, but its authorization has expired" do
      subject.refresh_token = 'abcd1234'
      subject.authorization.expires_at = 60.minutes.ago
      subject.should_not be_refreshable
    end
  end

  describe "a new instance" do
    subject do
      OAuth2::Provider.access_token_class.new
    end

    it "uses .unique_random_token to assign random access and refresh tokens" do
      OAuth2::Provider.access_token_class.stubs(:unique_random_token).with(:access_token).returns('random-access-token')
      OAuth2::Provider.access_token_class.stubs(:unique_random_token).with(:refresh_token).returns('random-refresh-token')
      subject.access_token.should eql('random-access-token')
      subject.refresh_token.should eql('random-refresh-token')
    end

    it "expires in 1 month by default" do
      subject.expires_at.should == 1.month.from_now
    end

    it "allows default expiry time to be overidden" do
      overidden = OAuth2::Provider.access_token_class.new(:expires_at => nil)
      overidden.expires_at.should be_nil
    end
  end

  describe "refreshing an existing token" do
    subject do
      OAuth2::Provider.access_token_class.create! :authorization => create_authorization, :expires_at => 23.days.ago
    end

    it "returns a new access token with the same client, resource_owner and scope, but a new expiry time" do
      result = OAuth2::Provider.access_token_class.refresh_with(subject.refresh_token)
      result.should_not be_nil
      result.expires_at.should == 1.month.from_now
      result.authorization.should == subject.authorization
    end

    it "returns token with expires_at set to authorization.expires_at if validation would fail otherwise" do
      subject.authorization.update_attributes(:expires_at => 5.minutes.from_now)
      result = OAuth2::Provider.access_token_class.refresh_with(subject.refresh_token)
      result.expires_at.should == 5.minutes.from_now
    end

    it "returns nil if the provided token doesn't match" do
      OAuth2::Provider.access_token_class.refresh_with('wrong').should be_nil
    end

    it "returns nil if the existing refresh token is nil, whatever value is provided" do
      subject.update_attributes(:refresh_token => nil)
      OAuth2::Provider.access_token_class.refresh_with(nil).should be_nil
    end
  end
end