text:
![](./media/image06.png)

#Lab 2 - Traffic Management for APIs

![](./media/image18.png)

## Objectives

The goal of this lesson is to introduce you to Traffic Management
policies and applying a couple of these policies to the API Proxy you
created in the previous lesson.

The total estimated time required for this exercise: 30 minutes.

## Pre-Requisites
-   Lab 1 is completed

## Background

To maintain performance and availability across a diverse base of client
apps, it's critical to maintain app traffic within the limits of the
capacity of your APIs and backend services. It's also important to
ensure that apps don't consume more resources than permitted.

Apigee Edge provides three policies that enable you to optimize
traffic management to minimize latency for apps while maintaining the
health of backend services.

> NB, a policy in Apigee Edge is a unit of re-usable logic that performs
a certain task. There are policy types for transforming messages,
caching data, checking tokens or keys, creating tokens, and so on.

Each of the traffic management policy types addresses a distinct aspect
of traffic management. In some cases, you might use the three policy
types in a single API proxy.

In addition, Apigee Edge includes a cache, that can also be accessed via
policies, to manage traffic and handling of requests.

### Spike Arrest

This policy smoothes traffic spikes by dividing a limit that you define
into smaller intervals. For example, if you define a limit of 100
messages per second, the Spike Arrest policy enforces a limit of about 1
request every 10 milliseconds (1000 / 100); and 30 messages per minute
is smoothed into about 1 request every 2 seconds (60 / 30). The Spike
Arrest limit should be close to capacity calculated for either your
backend service or the API proxy itself. The limit should also be
configured for shorter time intervals, such as seconds or minutes. This
policy should be used to prevent sudden traffic bursts caused by
malicious attackers attempting to disrupt a service using a
denial-of-service (DOS) attack or by buggy client applications.  See
[SpikeArrest](http://docs.apigee.com/api-services/reference/spike-arrest-policy).

### Quota

This policy enforces consumption limits on client apps by maintaining a
distributed 'counter' that tallies incoming requests. The counter can
tally API calls for any identifiable entity, including apps, developers,
API keys, access tokens, and so on. Usually, API keys are used to
identify client apps. This policy is computationally expensive so, for
high-traffic APIs, it should configured for longer time intervals, such
as a day or month. This policy should be used to enforce business
contracts or SLAs with developers and partners, rather than for
operational traffic management.  See [Quota](http://docs.apigee.com/api-services/reference/quota-policy).

### Concurrent Rate Limit

This policy enables traffic management between API Services and your
backend services. Some backend services, such as legacy applications,
may have strict limits on the number of simultaneous connections they
can support. This policy enforces a limit on the number of requests that
can be sent at any given time from API services to your backend
service. This number is counted across all of the distributed instances
of API Services that may be calling your backend service. Policy limits
and time duration should be configured to match the capacity available
for your backend service.  See [Concurrent Rate Limit](http://docs.apigee.com/api-services/reference/concurrent-rate-limit-policy).

### Caching Policies

Apigee Edge supports different caching policies enabling you to:

* Reduce latency: A request satisfied from the cache gets the
  representation and displays it in a shorter time. The server is more
  responsive with requests satisfied from the cache, which is closer to
  the client than the origin server.

* Reduce network traffic: Representations are reused, reducing the
  impact of processing duplicate or redundant requests. Using a cache
  also reduces the amount of bandwidth you use.

* Persist data across transactions: You can store session data for reuse
  across HTTP transactions.

* Support security:You may need "scope" access to the contents of a
  cache so it can only be accessed in a particular environment or by a
  specific API proxy.

The various caching policies supported by Apigee Edge are:

| Policy name    | Description |
| :------------- | :---------- |
| ResponseCache | Uses a cache to cache the response  from the backend resource. This reduces the number of requests to the resource. When the response is already available in cache, it is returned directly by Edge, without contacting the backend.  [ResponseCache policy](http://apigee.com/docs/api-services/reference/response-cache-policy). |
| PopulateCache | Write arbitrary data, not necessarily response content, to the cache. You can use composite keys for the cache, so that you could cache user information, client information, Nonces, and so on. Each cache item can be tagged with an individual Time-to-Live, so data can be available for 10 seconds or 10 hours or 10 days, etc. [PopulateCache](http://apigee.com/docs/api-services/reference/populate-cache-policy). |
| LookupCache | Retrieve values that have been cached with the PopulateCache policy. [LookupCache](http://apigee.com/docs/api-services/reference/lookup-cache-policy). |
| InvalidateCache | Purges values that have been cached by PopulateCache. [Invalidate Cache policy](http://apigee.com/docs/api-services/reference/invalidate-cache-policy). |

## Part 1: Adding a Spike Arrest Policy

**Estimated Time: 6 minutes**

1. Go to the Apigee Edge Management UI browser tab.

2. Ensure you're viewing the list of API Proxies.  If not, Use the upper navbar to select "API Proxies".
![](./media/cap500-select-API-Proxies.png)

3. From the list of proxies, Click the name of *your* API proxy.

4. Click on the develop tab.
![](./media/select-develop.png)

5. Click on Proxy Endpoints > PreFlow.
![](./media/select-preflow.png)

  Each proxy has a number of different places at which developers can
  attach policies. You can specify that your policies will run during
  request processing, or during response processing - *Request flow* or
  *Response flow* in Apigee parlance. For each of those, you can set up
  conditions to apply policies to a subset of cases - for example a
  condition will typically match a url path and verb.  `GET /payments`
  might have a conditional flow. There is also a "preflow" and
  "postflow" which act like wildcards - the policies attached here will
  run all requests on this proxy, before or after any conditional flow,
  respectively.

6. Click on `+ Step` on the Request Flow.
![](./media/add-step.png)

  By doing this, you are adding a policy step that will run in the
  Request Pre-flow. It will run for all inbound requests. You will see a
  modal dialog that allows you to select a particular policy:
  ![](./media/modal-add-a-step.png)

  Feel free to scroll to examine the list of available policies.

  Select the 'Spike Arrest' policy, and click "Add".

7. You have now added a policy, and you will be presented with this view:
![](./media/spike-arrest.png)

8. Modify the configuration of the policy, specifying "10pm" - 10 per minute - for the Rate.
![](./media/spike-arrest2.png)

  This shows you the basics related to configuring policies in Apigee
  Edge. There are numerous policy types, and for each one, you may
  configure certain properties to affect their behavior.

  Your configuration should look
  something like the following. The DisplayName and name are not of critical importance:

  ```
  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <SpikeArrest async="false" continueOnError="false" enabled="true" name="Spike-Arrest-1">
      <DisplayName>Spike Arrest 10pm</DisplayName>
      <Properties/>
      <Identifier ref="request.header.some-header-name"/>
      <MessageWeight ref="request.header.weight"/>
      <Rate>10pm</Rate>
  </SpikeArrest>
  ```

9. Save the changes to the proxy and ensure that it is deployed
successfully to the 'test' environment.
![](./media/spike-arrest3.png)

  Think of Spike Arrest as a way to generally protect against traffic
  spikes (system wide) rather than as a way to limit traffic to a
  specific number of requests *per user*. Your APIs and backend can
  handle a certain amount of traffic, and the Spike Arrest policy helps
  you smooth traffic to the general amounts you want, or to set safety
  limits.

  The runtime Spike Arrest behavior differs from what you might expect
  to see from the literal per-minute or per-second values you enter.

  For example, say you enter a rate of 30pm (30 requests per minute). In
  testing, you might think you could send 30 requests in 1 second, as
  long as they came within a minute. But that's not how the policy
  enforces the setting. Thirty requests inside a
  1-second period could be considered a mini spike in some environments.

  Instead, Spike Arrest smooths the allowed traffic by dividing your
  settings into smaller intervals:

  * **Per-minute** rates get smoothed into requests allowed intervals of
    **seconds**. For example, 30pm gets smoothed like this: 60 seconds
    (1 minute) / 30pm = 2-second intervals, or about 1 request allowed
    every 2 seconds. A second request inside of 2 seconds will fail.
    Also, a 31st request within a minute will fail.

  * **Per-second** rates get smoothed into requests allowed in intervals
    of **milliseconds**. For example, 10ps gets smoothed like this: 1000
    milliseconds (1 second) / 10ps = 100-millisecond intervals, or about
    1 request allowed every 100 milliseconds . A second request inside
    of 100ms will fail. Also, an 11th request within a second will fail.

10. Now, test the proxy.  Use Postman to quickly send more than 2 requests in 6 seconds and observe that certain requests will receive an error with the errorCode `policies.ratelimit.SpikeArrestViolation`.

11. Let's use the Trace UI to examine what's happening. Return to the Edge UI, and select the Trace tab again.
![](./media/trace.png)

12. Return to Postman, and send a few more requests. Now back to the Edge UI.  Examine the trace. You should see some requests returning 500 errors, indicating that the SpikeArrest has sent back the call.
![](./media/trace2.png)

13. Stop the Trace session.

## Part 2: Adding a Response Cache

**Estimated Time: 10 minutes**

Now we'll introduce the ResponseCache policy.

1. Go to the Apigee Edge Management UI browser tab.

2. Select your API proxy. Select the Develop tab

3. Click on Proxy Endpoints -> PreFlow
![](./media/cache1.png)

4. Click on "+ Step" on the Request Flow.
![](./media/cache2.png)

5. From the resulting modal dialog, Select the 'Response Cache' policy, and click Add.
You should see something like the following:
![](./media/add-cache-policy.png)

  You have now added a second policy to the Request Pre-Flow. Remember,
  these are policies that will run for every inbound request handled by
  this proxy. They run in sequence. You get to specify the order.

  The configuration for this policy looks like the following:
  ```
  <ResponseCache async="false" continueOnError="false" enabled="true" name="Response-Cache-1">
    <DisplayName>Response Cache-1</DisplayName>
    <Properties/>
    <CacheKey>
        <Prefix/>
        <KeyFragment ref="request.uri" type="string"/>
    </CacheKey>
    <Scope>Exclusive</Scope>
    <ExpirySettings>
        <ExpiryDate/>
        <TimeOfDay/>
        <TimeoutInSec ref="">3600</TimeoutInSec>
    </ExpirySettings>
    <SkipCacheLookup/>
    <SkipCachePopulation/>
  </ResponseCache>
  ```

  This stipulates that the cache should timeout after 3600 seconds, or
  one hour. You can modify this to whatever setting you like. As implied
  by the configuration options, you can also set the expiry to a
  particular time of day - say 3:00am Pacific time each day. This allows
  you to hold a cache all day, and refresh it at the beginning of each
  day, for example. For more information, see [the
  documentation](http://apigee.com/docs/api-services/reference/response-cache-policy).

  Apigee Edge provides a default cache resource that can be used for
  quick testing, which is what is being used in this lesson. Cache
  policies like ResponseCache can also used named cache resources.  A
  Named cache resource can be manipulated administratively, outside of
  policy control. For examine, if you would like to clear a cache
  administratively, you can do that with a named cache resource. It
  takes just a moment.

  For more information on Cache Resources, see [Manage Caches for an
  Environment](http://apigee.com/docs/api-services/content/manage-caches-environment).

10. Your Proxy Endpoints → Default → PreFlow should now look as follows:
![](./media/cache3.png)

11. Click the Target Endpoints → default → PostFlow
![](./media/cache4.png)

12. Verify that it looks as follows:
![](./media/cache5.png)

13. Save the changes to the API Proxy, and wait for it to successfully deploy.

14. Now, let's test the modifications you've made.  Click the Trace tab and start a Trace session.

15. From Postman, send a test '/GET payment' request from Postman
![](./media/postman.png)

16. In the Postman UI, you should see a success response, and a timing.

16. Wait for 6 to 10 seconds, to avoid the Spike Arrest policy from
  stopping your requests) and send the same request again from
  Postman. You should see a faster response this time.

17. Go back to the Edge UI, in the Trace view and review the transaction
  map of both the requests including the overall elapsed time to process
  both requests.

  The first transaction map will show you that the request was proxied
  to the backend. It should look as follows:
  ![](./media/trace-cache1.png)

  The view for the second transaction will show you that the response
  was served from cache. It will look as follows:
  ![](./media/trace-cache.png)

  After configuring the Response Cache policy, as expected, after the
  initial request, the second and all other requests for the next 3600
  seconds will be served from the cache and hence avoid executing any
  other policies. Since no request is sent to the target service, the
  overall transaction time has also dropped significantly. This can also
  increase concurrency at high transaction rates.

**Questions:**

* Suppose you modified the ResponseCache policy to have a TTL of 10 seconds.  Then, suppose you sent new requests in.  At this point, Would you expect the cache to be re-filled every 10 seconds?  Explain.

* What would you need to do in order to allow an administrator the ability to clear the cache?

## Summary

That completes this hands-on lesson. You learned how to use the Spike
Arrest to protect the environment from traffic spikes and to use the
Response Cache policy to provide a better overall experience for the API
consumer while reducing network traffic. Obviously like any other
policy, these policies must be used appropriately based upon your use
cases.


text:
using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RelhaxModpack.Automation.Tasks
{
    /// <summary>
    /// Provides an implementation to parse a browser session's response HTML result via an HtmlPath parser.
    /// </summary>
    public abstract class BrowserSessionParseTask : BrowserSessionMacroTask, IHtmlParseTask
    {
        /// <summary>
        /// Control if the result response string should be parsed as an html document.
        /// </summary>
        public string ParseResult { get; set; }

        /// <summary>
        /// The HtmlPath argument to use for parsing.
        /// </summary>
        public string HtmlPath { get; set; } = string.Empty;

        /// <summary>
        /// Controls for debugging, if the HTML result should be written to disk.
        /// </summary>
        public string WriteHtmlResult { get; set; }

        /// <summary>
        /// Parsed result of the argument ParseResult.
        /// </summary>
        /// <seealso cref="ParseResult"/>
        protected bool parseResult;

        /// <summary>
        /// Parsed result of the argument WriteHtmlResult.
        /// </summary>
        /// <seealso cref="WriteHtmlResult"/>
        protected bool writeHtmlResult = false;

        /// <summary>
        /// The html result string from the HTTP request.
        /// </summary>
        protected string htmlText;

        /// <summary>
        /// The result from the HtmlPath parser.
        /// </summary>
        /// <remarks>Check parserExitCode to know if the HtmlPath parser completed successful.</remarks>
        protected string htmlPathResult;

        /// <summary>
        /// The HtmlPath parser.
        /// </summary>
        protected HtmlTextParser htmlTextParser;

        /// <summary>
        /// The exit code from the HtmlPath parser when executed.
        /// </summary>
        protected HtmlXpathParserExitCode parserExitCode;

        /// <summary>
        /// Flag to determine if the task successfully ran the HtmlParser.
        /// </summary>
        protected bool htmlStringGotten;

        /// <summary>
        /// Flag to determine if the macro with the given name can be created.
        /// </summary>
        /// <seealso cref="BrowserSessionMacroTask.MacroName"/>
        protected bool macroSetup;

        #region Xml serialization
        /// <summary>
        /// Defines a list of properties in the class to be serialized into xml attributes.
        /// </summary>
        /// <returns>A list of string property names.</returns>
        /// <remarks>Xml attributes will always be written, xml elements are optional.</remarks>
        public override string[] PropertiesForSerializationAttributes()
        {
            return base.PropertiesForSerializationAttributes().Concat(new string[] { nameof(ParseResult), nameof(HtmlPath), nameof(WriteHtmlResult) }).ToArray();
        }
        #endregion

        #region Task execution
        /// <summary>
        /// Process any macros that exist in the task's arguments.
        /// </summary>
        public override void ProcessMacros()
        {
            base.ProcessMacros();
            parseResult = bool.Parse(ProcessMacro(nameof(ParseResult), ParseResult));
            if (parseResult)
            {
                HtmlPath = ProcessMacro(nameof(HtmlPath), HtmlPath);
                writeHtmlResult = bool.Parse(ProcessMacro(nameof(WriteHtmlResult), WriteHtmlResult));
            }
        }

        /// <summary>
        /// Validates that all task arguments are correct and the task is initialized correctly to execute.
        /// </summary>
        public override void ValidateCommands()
        {
            //don't call base, need to do it manually because parsing macro is based on parseResult
            if (ValidateCommandTrue(string.IsNullOrEmpty(Url), string.Format("The parameter {0} is null or empty", nameof(Url))))
                return;
            if (ValidateCommandTrue(parseResult && string.IsNullOrEmpty(MacroName), "The argument MacroName is empty string"))
                return;
            if (ValidateCommandTrue(parseResult && string.IsNullOrEmpty(HtmlPath), string.Format("ParseResult is true but HtmlPath is null or empty")))
                return;
            if (ValidateCommandTrue(parseResult && string.IsNullOrEmpty(WriteHtmlResult), string.Format("ParseResult is true but WriteHtmlResult is null or empty")))
                return;
        }

        /// <summary>
        /// Runs the main feature of the task.
        /// </summary>
        public override async Task RunTask()
        {
            htmlStringGotten = await GetHtmlString();
            if (!htmlStringGotten)
                return;
            if (string.IsNullOrEmpty(htmlText) && parseResult)
            {
                return;
            }
            else if (parseResult)
            {
                macroSetup = CheckIfMacroExits();
                if (!macroSetup)
                {
                    return;
                }
                ParseHtmlResult();
                if (parserExitCode == HtmlXpathParserExitCode.None)
                {
                    CreateMacro(htmlPathResult);
                }
            }
        }

        /// <summary>
        /// Validate that the task executed without error and any expected output resources were processed correctly.
        /// </summary>
        public override void ProcessTaskResults()
        {
            if (ProcessTaskResultFalse(htmlStringGotten, "Failed to get the Html string"))
                return;
            if (ProcessTaskResultTrue(string.IsNullOrEmpty(htmlText) && parseResult, "Cannot parse an empty response string"))
                return;
            if (ProcessTaskResultTrue(parseResult && !macroSetup, "Failed to create desired macro name when parsing html result"))
                return;
            if (ProcessTaskResultFalse(parserExitCode == HtmlXpathParserExitCode.None, string.Format("The html parser exited with code {0}", parserExitCode)))
                return;
        }

        /// <summary>
        /// Run the HtmlParser engine.
        /// </summary>
        /// <returns>The exit code from the HtmlParser engine.</returns>
        public virtual async Task<HtmlXpathParserExitCode> ParseHtmlResult()
        {
            Logging.Debug("Parsing HTML result with HtmlPath {0}", HtmlPath);
            htmlTextParser = new HtmlTextParser(HtmlPath, writeHtmlResult, htmlText, ID + ".html");
            parserExitCode = await htmlTextParser.RunParserAsync();
            htmlPathResult = htmlTextParser.ResultString;
            htmlPathResult = htmlPathResult.Replace(""", "\"").Replace("'", "'").Replace("<", "<").Replace(">", ">").Replace("&", "&");
            return parserExitCode;
        }

        /// <summary>
        /// Gets the string to parse for HtmlPath.
        /// </summary>
        /// <returns>True if the string was successfully retrieved, false otherwise.</returns>
        protected abstract Task<bool> GetHtmlString();
        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

<title>Twisted Documentation: TRIAL.1</title>
<link href="../howto/stylesheet.css" rel="stylesheet" type="text/css"/>

TRIAL.1

NAME

SYNOPSIS

DESCRIPTION

AUTHOR

REPORTING BUGS

COPYRIGHT

NAME

trial - run unit tests

SYNOPSIS

trial  [options] [[file|package|module|TestCase|testmethod]...]

trial  --help

DESCRIPTION

trial loads and executes a suite of unit tests, obtained from modules,
packages and files listed on the command line.

trial will take either filenames or fully qualified Python names as
arguments.  Thus 'trial myproject/foo.py', 'trial myproject.foo' and
 'trial myproject.foo.SomeTestCase.test_method' are all valid ways to
invoke trial.

-b, --debug

Run the tests in the Python debugger. Also does post-mortem
debugging on exceptions. Will load '.pdbrc' from current directory if
it exists.

-B, --debug-stacktraces

Report Deferred creation and callback stack traces

--coverage

Generate coverage information in _trial_temp/coverage/. Requires Python 2.3
or higher.

--disablegc

Disable the garbage collector.  I don't know why this is in trial.

-x, --extra

Add an extra argument. (This is a hack necessary for interfacing with emacs's
`gud'.)

-e, --rterrors

Print tracebacks to standard output as soon as they occur

--force-gc

Run gc.collect() before and after each test case. This can be used to
isolate errors that occur when objects get collected.  This option would be
the default, except it makes tests run about ten times slower.

-h, --help

Print a usage message to standard output, then exit.

--help-reporters

Print a list of valid reporters to standard output, then exit.

--help-reactors

List the names of possibly available reactors.

-l, --logfile <logfile>

Direct the log to a different file. The default file is 'test.log'.
<logfile> is relative to _trial_temp.

-n, --dry-run

Go through all the tests and make them pass without running.

-N, --no-recurse

By default, trial recurses through packages to find every module inside
every subpackage.  Unless, that is, you specify this option.

--nopm

Don't automatically jump into debugger for post-mortem analysis of
exceptions.  Only usable in conjunction with --debug.

--profile

Run tests under the Python profiler.

-r, --reactor <reactor>

Choose which reactor to use.  See --help-reactors for a list.

--recursionlimit

Set Python's recursion limit. See sys.setrecursionlimit()

--reporter

Select the reporter to use for Trial's output.  Use the --help-reporters
option to see a list of valid reporters.

--spew

Print an insanely verbose log of everything that happens. Useful when
debugging freezes or locks in complex code.

--tbformat <format>

Format to display tracebacks with. Acceptable values are 'default', 'brief'
and 'verbose'. 'brief' produces tracebacks that play nicely with Emacs' GUD.

--temp-directory <directory>

WARNING: Do not use this options unless you know what you are doing.
By default, trial creates a directory called _trial_temp under the current
working directory.  When trial runs, it first deletes this directory,
then creates it, then changes into the directory to run the tests. The log
file and any coverage files are stored here. Use this option if you wish to
have trial run in a directory other than _trial_temp. Be warned, trial
will delete the directory before re-creating it.

--testmodule <filename>

Ask trial to look into <filename> and run any tests specified using the
Emacs-style buffer variable 'test-case-name'.

--unclean-warnings

As of Twisted 8.0, trial will report an error if the reactor is left unclean
at the end of the test. This option is provided to assist in migrating from
Twisted 2.5 to Twisted 8.0 and later. Enabling this option will turn the errors
into warnings.

-u, --until-failure

Keep looping the tests until one of them raises an error or a failure.
This is particularly useful for reproducing intermittent failures.

--version

Prints the Twisted version number and exit.

--without-module <modulenames>

Simulate the lack of the specified comma-separated list of modules. This makes
it look like the modules are not present in the system, causing tests to check
the behavior for that configuration.

-z, --random [<seed>]

Run the tests in random order using the specified seed.

AUTHOR

Written by Jonathan M. Lange

REPORTING BUGS

To report a bug, visit http://twistedmatrix.com/bugs/

COPYRIGHT

Copyright © 2003-2008 Twisted Matrix Laboratories
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Index

    Version: 10.0.0


text:
<dom-module id="get-student-data">
  <template>
    <iron-ajax
        id = "studentPopulateAjax"
        method="GET"
        handle-as="json"
        on-response="_studentPopulateResponse"
        last-response="{{studentData}}"
        url="http://127.0.0.1:8000/myapp/classesfromuser/{{pk}}/">
	  </iron-ajax>
    <template is="dom-if" if="{{bool}}">
      <template is="dom-repeat" items="{{studentData}}">
          <student-class element-color="var(--paper-blue-500)" class-name$="{{item.classId}}" class-pk$="{{item.classPK}}" location-req$="{{item.locationFlag}}" code-req$="{{item.codeFlag}}"></student-class>
      </template>
    </template>
  </template>

  <script>
    Polymer({

      is: 'get-student-data',

      properties: {

          pk: {
            type: String
          },

          studentData: {
            type: Object,
            value: function() { return {}; }
          },

          bool: {
					type: Boolean,
					value: true
				  }

      },

      ready: function() {
        this.pk = document.querySelector('#localStorage').value.userPK;
        this.$.studentPopulateAjax.generateRequest();
      },

      refresh: function() {
			this.bool = false;
			this.$.studentPopulateAjax.generateRequest();
		  },

      _studentPopulateResponse: function(){
				this.bool = true;
		},

   });
  </script>
</dom-module>


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.12
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.pjsip.pjsua2;

public final class pjsua_create_media_transport_flag {
  public final static pjsua_create_media_transport_flag PJSUA_MED_TP_CLOSE_MEMBER = new pjsua_create_media_transport_flag("PJSUA_MED_TP_CLOSE_MEMBER", pjsua2JNI.PJSUA_MED_TP_CLOSE_MEMBER_get());

  public final int swigValue() {
    return swigValue;
  }

  public String toString() {
    return swigName;
  }

  public static pjsua_create_media_transport_flag swigToEnum(int swigValue) {
    if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
      return swigValues[swigValue];
    for (int i = 0; i < swigValues.length; i++)
      if (swigValues[i].swigValue == swigValue)
        return swigValues[i];
    throw new IllegalArgumentException("No enum " + pjsua_create_media_transport_flag.class + " with value " + swigValue);
  }

  private pjsua_create_media_transport_flag(String swigName) {
    this.swigName = swigName;
    this.swigValue = swigNext++;
  }

  private pjsua_create_media_transport_flag(String swigName, int swigValue) {
    this.swigName = swigName;
    this.swigValue = swigValue;
    swigNext = swigValue+1;
  }

  private pjsua_create_media_transport_flag(String swigName, pjsua_create_media_transport_flag swigEnum) {
    this.swigName = swigName;
    this.swigValue = swigEnum.swigValue;
    swigNext = this.swigValue+1;
  }

  private static pjsua_create_media_transport_flag[] swigValues = { PJSUA_MED_TP_CLOSE_MEMBER };
  private static int swigNext = 0;
  private final int swigValue;
  private final String swigName;
}


text:
class SrsFastCoroutine;

// Each ST-coroutine must implements this interface,
// to do the cycle job and handle some events.
//
// Thread do a job then terminated normally, it's a SrsOneCycleThread:
//      class SrsOneCycleThread : public ISrsCoroutineHandler {
//          public: SrsCoroutine trd;
//          public: virtual srs_error_t cycle() {
//              // Do something, then return this cycle and thread terminated normally.
//          }
//      };
//
// Thread has its inside loop, such as the RTMP receive thread:
//      class SrsReceiveThread : public ISrsCoroutineHandler {
//          public: SrsCoroutine* trd;
//          public: virtual srs_error_t cycle() {
//              while (true) {
//                  // Check whether thread interrupted.
//                  if ((err = trd->pull()) != srs_success) {
//                      return err;
//                  }
//                  // Do something, such as st_read() packets, it'll be wakeup
//                  // when user stop or interrupt the thread.
//              }
//          }
//      };
class ISrsCoroutineHandler
{
public:
    ISrsCoroutineHandler();
    virtual ~ISrsCoroutineHandler();
public:
    // Do the work. The ST-coroutine will terminated normally if it returned.
    // @remark If the cycle has its own loop, it must check the thread pull.
    virtual srs_error_t cycle() = 0;
};

// Start the object, generally a croutine.
class ISrsStartable
{
public:
    ISrsStartable();
    virtual ~ISrsStartable();
public:
    virtual srs_error_t start() = 0;
};

// The corotine object.
class SrsCoroutine : public ISrsStartable
{
public:
    SrsCoroutine();
    virtual ~SrsCoroutine();
public:
    virtual void stop() = 0;
    virtual void interrupt() = 0;
    // @return a copy of error, which should be freed by user.
    //      NULL if not terminated and user should pull again.
    virtual srs_error_t pull() = 0;
    virtual const SrsContextId& cid() = 0;
};

// An empty coroutine, user can default to this object before create any real coroutine.
// @see https://github.com/ossrs/srs/pull/908
class SrsDummyCoroutine : public SrsCoroutine
{
public:
    SrsDummyCoroutine();
    virtual ~SrsDummyCoroutine();
public:
    virtual srs_error_t start();
    virtual void stop();
    virtual void interrupt();
    virtual srs_error_t pull();
    virtual const SrsContextId& cid();
};

// A ST-coroutine is a lightweight thread, just like the goroutine.
// But the goroutine maybe run on different thread, while ST-coroutine only
// run in single thread, because it use setjmp and longjmp, so it may cause
// problem in multiple threads. For SRS, we only use single thread module,
// like NGINX to get very high performance, with asynchronous and non-blocking
// sockets.
// @reamrk For multiple processes, please use go-oryx to fork many SRS processes.
//      Please read https://github.com/ossrs/go-oryx
// @remark For debugging of ST-coroutine, read _st_iterate_threads_flag of ST/README
//      https://github.com/ossrs/state-threads/blob/st-1.9/README#L115
// @remark We always create joinable thread, so we must join it or memory leak,
//      Please read https://github.com/ossrs/srs/issues/78
class SrsSTCoroutine : public SrsCoroutine
{
private:
    SrsFastCoroutine* impl_;
public:
    // Create a thread with name n and handler h.
    // @remark User can specify a cid for thread to use, or we will allocate a new one.
    SrsSTCoroutine(std::string n, ISrsCoroutineHandler* h);
    SrsSTCoroutine(std::string n, ISrsCoroutineHandler* h, SrsContextId cid);
    virtual ~SrsSTCoroutine();
public:
    // Set the stack size of coroutine, default to 0(64KB).
    void set_stack_size(int v);
public:
    // Start the thread.
    // @remark Should never start it when stopped or terminated.
    virtual srs_error_t start();
    // Interrupt the thread then wait to terminated.
    // @remark If user want to notify thread to quit async, for example if there are
    //      many threads to stop like the encoder, use the interrupt to notify all threads
    //      to terminate then use stop to wait for each to terminate.
    virtual void stop();
    // Interrupt the thread and notify it to terminate, it will be wakeup if it's blocked
    // in some IO operations, such as st_read or st_write, then it will found should quit,
    // finally the thread should terminated normally, user can use the stop to join it.
    virtual void interrupt();
    // Check whether thread is terminated normally or error(stopped or termianted with error),
    // and the thread should be running if it return ERROR_SUCCESS.
    // @remark Return specified error when thread terminated normally with error.
    // @remark Return ERROR_THREAD_TERMINATED when thread terminated normally without error.
    // @remark Return ERROR_THREAD_INTERRUPED when thread is interrupted.
    virtual srs_error_t pull();
    // Get the context id of thread.
    virtual const SrsContextId& cid();
};

// For utest to mock the thread create.
typedef void* (*_ST_THREAD_CREATE_PFN)(void *(*start)(void *arg), void *arg, int joinable, int stack_size);
extern _ST_THREAD_CREATE_PFN _pfn_st_thread_create;

// High performance coroutine.
class SrsFastCoroutine
{
private:
    std::string name;
    int stack_size;
    ISrsCoroutineHandler* handler;
private:
    srs_thread_t trd;
    SrsContextId cid_;
    srs_error_t trd_err;
private:
    bool started;
    bool interrupted;
    bool disposed;
    // Cycle done, no need to interrupt it.
    bool cycle_done;
private:
    // Sub state in disposed, we need to wait for thread to quit.
    bool stopping_;
    SrsContextId stopping_cid_;
public:
    SrsFastCoroutine(std::string n, ISrsCoroutineHandler* h);
    SrsFastCoroutine(std::string n, ISrsCoroutineHandler* h, SrsContextId cid);
    ~SrsFastCoroutine();
public:
    void set_stack_size(int v);
public:
    srs_error_t start();
    void stop();
    void interrupt();
    inline srs_error_t pull() {
        if (trd_err == srs_success) {
            return srs_success;
        }
        return srs_error_copy(trd_err);
    }
    const SrsContextId& cid();
private:
    srs_error_t cycle();
    static void* pfn(void* arg);
};

// Like goroytine sync.WaitGroup.
class SrsWaitGroup
{
private:
    int nn_;
    srs_cond_t done_;
public:
    SrsWaitGroup();
    virtual ~SrsWaitGroup();
public:
    // When start for n coroutines.
    void add(int n);
    // When coroutine is done.
    void done();
    // Wait for all corotine to be done.
    void wait();
};

#endif


text:
package com.google.gerrit.httpd.plugins;

import static com.google.gerrit.common.FileUtil.lastModified;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CHARACTER_ENCODING;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CONTENT_TYPE;

import com.google.common.base.CharMatcher;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;
import com.google.common.net.HttpHeaders;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.gerrit.httpd.resources.Resource;
import com.google.gerrit.httpd.resources.ResourceKey;
import com.google.gerrit.httpd.resources.SmallResource;
import com.google.gerrit.httpd.restapi.RestApiServlet;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.documentation.MarkdownFormatter;
import com.google.gerrit.server.mime.MimeUtilFileTypeRegistry;
import com.google.gerrit.server.plugins.Plugin;
import com.google.gerrit.server.plugins.Plugin.ApiType;
import com.google.gerrit.server.plugins.PluginContentScanner;
import com.google.gerrit.server.plugins.PluginEntry;
import com.google.gerrit.server.plugins.PluginsCollection;
import com.google.gerrit.server.plugins.ReloadPluginListener;
import com.google.gerrit.server.plugins.StartPluginListener;
import com.google.gerrit.server.ssh.SshInfo;
import com.google.gerrit.util.http.RequestUtil;
import com.google.gwtexpui.server.CacheHeaders;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.inject.servlet.GuiceFilter;

import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.Attributes;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Singleton
class HttpPluginServlet extends HttpServlet
    implements StartPluginListener, ReloadPluginListener {
  private static final int SMALL_RESOURCE = 128 * 1024;
  private static final long serialVersionUID = 1L;
  private static final Logger log
      = LoggerFactory.getLogger(HttpPluginServlet.class);

  private final MimeUtilFileTypeRegistry mimeUtil;
  private final Provider<String> webUrl;
  private final Cache<ResourceKey, Resource> resourceCache;
  private final String sshHost;
  private final int sshPort;
  private final RestApiServlet managerApi;

  private List<Plugin> pending = Lists.newArrayList();
  private ContextMapper wrapper;
  private final ConcurrentMap<String, PluginHolder> plugins
      = Maps.newConcurrentMap();

  @Inject
  HttpPluginServlet(
      MimeUtilFileTypeRegistry mimeUtil,
      @CanonicalWebUrl Provider<String> webUrl,
      @Named(HttpPluginModule.PLUGIN_RESOURCES) Cache<ResourceKey, Resource> cache,
      SshInfo sshInfo,
      RestApiServlet.Globals globals,
      PluginsCollection plugins) {
    this.mimeUtil = mimeUtil;
    this.webUrl = webUrl;
    this.resourceCache = cache;
    this.managerApi = new RestApiServlet(globals, plugins);

    String sshHost = "review.example.com";
    int sshPort = 29418;
    if (!sshInfo.getHostKeys().isEmpty()) {
      String host = sshInfo.getHostKeys().get(0).getHost();
      int c = host.lastIndexOf(':');
      if (0 <= c) {
        sshHost = host.substring(0, c);
        sshPort = Integer.parseInt(host.substring(c+1));
      } else {
        sshHost = host;
        sshPort = 22;
      }
    }
    this.sshHost = sshHost;
    this.sshPort = sshPort;
  }

  @Override
  public synchronized void init(ServletConfig config) throws ServletException {
    super.init(config);

    wrapper = new ContextMapper(config.getServletContext().getContextPath());
    for (Plugin plugin : pending) {
      install(plugin);
    }
    pending = null;
  }

  @Override
  public synchronized void onStartPlugin(Plugin plugin) {
    if (pending != null) {
      pending.add(plugin);
    } else {
      install(plugin);
    }
  }

  @Override
  public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) {
    install(newPlugin);
  }

  private void install(Plugin plugin) {
    GuiceFilter filter = load(plugin);
    final String name = plugin.getName();
    final PluginHolder holder = new PluginHolder(plugin, filter);
    plugin.add(new RegistrationHandle() {
      @Override
      public void remove() {
        plugins.remove(name, holder);
      }
    });
    plugins.put(name, holder);
  }

  private GuiceFilter load(Plugin plugin) {
    if (plugin.getHttpInjector() != null) {
      final String name = plugin.getName();
      final GuiceFilter filter;
      try {
        filter = plugin.getHttpInjector().getInstance(GuiceFilter.class);
      } catch (RuntimeException e) {
        log.warn(String.format("Plugin %s cannot load GuiceFilter", name), e);
        return null;
      }

      try {
        ServletContext ctx =
            PluginServletContext.create(plugin, wrapper.getFullPath(name));
        filter.init(new WrappedFilterConfig(ctx));
      } catch (ServletException e) {
        log.warn(String.format("Plugin %s failed to initialize HTTP", name), e);
        return null;
      }

      plugin.add(new RegistrationHandle() {
        @Override
        public void remove() {
          filter.destroy();
        }
      });
      return filter;
    }
    return null;
  }

  @Override
  public void service(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    List<String> parts = Lists.newArrayList(
      Splitter.on('/').limit(3).omitEmptyStrings()
        .split(Strings.nullToEmpty(RequestUtil.getEncodedPathInfo(req))));

    if (isApiCall(req, parts)) {
      managerApi.service(req, res);
      return;
    }

    String name = parts.get(0);
    final PluginHolder holder = plugins.get(name);
    if (holder == null) {
      CacheHeaders.setNotCacheable(res);
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    HttpServletRequest wr = wrapper.create(req, name);
    FilterChain chain = new FilterChain() {
      @Override
      public void doFilter(ServletRequest req, ServletResponse res)
          throws IOException {
        onDefault(holder, (HttpServletRequest) req, (HttpServletResponse) res);
      }
    };
    if (holder.filter != null) {
      holder.filter.doFilter(wr, res, chain);
    } else {
      chain.doFilter(wr, res);
    }
  }

  private static boolean isApiCall(HttpServletRequest req, List<String> parts) {
    String method = req.getMethod();
    int cnt = parts.size();
    return cnt == 0
        || (cnt == 1 && ("PUT".equals(method) || "DELETE".equals(method)))
        || (cnt == 2 && parts.get(1).startsWith("gerrit~"));
  }

  private void onDefault(PluginHolder holder,
      HttpServletRequest req,
      HttpServletResponse res) throws IOException {
    if (!"GET".equals(req.getMethod()) && !"HEAD".equals(req.getMethod())) {
      CacheHeaders.setNotCacheable(res);
      res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
      return;
    }

    String pathInfo = RequestUtil.getEncodedPathInfo(req);
    if (pathInfo.length() < 1) {
      Resource.NOT_FOUND.send(req, res);
      return;
    }

    String file = pathInfo.substring(1);
    PluginResourceKey key = PluginResourceKey.create(holder.plugin, file);
    Resource rsc = resourceCache.getIfPresent(key);
    if (rsc != null && req.getHeader(HttpHeaders.IF_MODIFIED_SINCE) == null) {
      rsc.send(req, res);
      return;
    }

    String uri = req.getRequestURI();
    if ("".equals(file)) {
      res.sendRedirect(uri + holder.docPrefix + "index.html");
      return;
    }

    if (file.startsWith(holder.staticPrefix)) {
      if (holder.plugin.getApiType() == ApiType.JS) {
        sendJsPlugin(holder.plugin, key, req, res);
      } else {
        PluginContentScanner scanner = holder.plugin.getContentScanner();
        Optional<PluginEntry> entry = scanner.getEntry(file);
        if (entry.isPresent()) {
          if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
            rsc.send(req, res);
          } else {
            sendResource(scanner, entry.get(), key, res);
          }
        } else {
          resourceCache.put(key, Resource.NOT_FOUND);
          Resource.NOT_FOUND.send(req, res);
        }
      }
    } else if (file.equals(
        holder.docPrefix.substring(0, holder.docPrefix.length() - 1))) {
      res.sendRedirect(uri + "/index.html");
    } else if (file.startsWith(holder.docPrefix) && file.endsWith("/")) {
      res.sendRedirect(uri + "index.html");
    } else if (file.startsWith(holder.docPrefix)) {
      PluginContentScanner scanner = holder.plugin.getContentScanner();
      Optional<PluginEntry> entry = scanner.getEntry(file);
      if (!entry.isPresent()) {
        entry = findSource(scanner, file);
      }
      if (!entry.isPresent() && file.endsWith("/index.html")) {
        String pfx = file.substring(0, file.length() - "index.html".length());
        long pluginLastModified = lastModified(holder.plugin.getSrcFile());
        if (hasUpToDateCachedResource(rsc, pluginLastModified)) {
          rsc.send(req, res);
        } else {
          sendAutoIndex(scanner, pfx, holder.plugin.getName(), key, res,
              pluginLastModified);
        }
      } else if (entry.isPresent() && entry.get().getName().endsWith(".md")) {
        if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
          rsc.send(req, res);
        } else {
          sendMarkdownAsHtml(scanner, entry.get(), holder.plugin.getName(),
              key, res);
        }
      } else if (entry.isPresent()) {
        if (hasUpToDateCachedResource(rsc, entry.get().getTime())) {
          rsc.send(req, res);
        } else {
          sendResource(scanner, entry.get(), key, res);
        }
      } else {
        resourceCache.put(key, Resource.NOT_FOUND);
        Resource.NOT_FOUND.send(req, res);
      }
    } else {
      resourceCache.put(key, Resource.NOT_FOUND);
      Resource.NOT_FOUND.send(req, res);
    }
  }

  private boolean hasUpToDateCachedResource(Resource cachedResource, long lastUpdateTime) {
    return cachedResource != null
        && cachedResource.isUnchanged(lastUpdateTime);
  }

  private void appendEntriesSection(PluginContentScanner scanner, List<PluginEntry> entries,
      String sectionTitle, StringBuilder md, String prefix,
      int nameOffset) throws IOException {
    if (!entries.isEmpty()) {
      md.append("## ").append(sectionTitle).append(" ##\n");
      for(PluginEntry entry : entries) {
        String rsrc = entry.getName().substring(prefix.length());
        String entryTitle;
        if (rsrc.endsWith(".html")) {
          entryTitle = rsrc.substring(nameOffset, rsrc.length() - 5).replace('-', ' ');
        } else if (rsrc.endsWith(".md")) {
          entryTitle = extractTitleFromMarkdown(scanner, entry);
          if (Strings.isNullOrEmpty(entryTitle)) {
            entryTitle = rsrc.substring(nameOffset, rsrc.length() - 3).replace('-', ' ');
          }
          rsrc = rsrc.substring(0, rsrc.length() - 3) + ".html";
        } else {
          entryTitle = rsrc.substring(nameOffset).replace('-', ' ');
        }
        md.append(String.format("* [%s](%s)\n", entryTitle, rsrc));
      }
      md.append("\n");
    }
  }

  private void sendAutoIndex(PluginContentScanner scanner,
      String prefix, String pluginName,
      PluginResourceKey cacheKey, HttpServletResponse res,long lastModifiedTime)
      throws IOException {
    List<PluginEntry> cmds = Lists.newArrayList();
    List<PluginEntry> servlets = Lists.newArrayList();
    List<PluginEntry> restApis = Lists.newArrayList();
    List<PluginEntry> docs = Lists.newArrayList();
    PluginEntry about = null;
    Enumeration<PluginEntry> entries = scanner.entries();
    while (entries.hasMoreElements()) {
      PluginEntry entry = entries.nextElement();
      String name = entry.getName();
      Optional<Long> size = entry.getSize();
      if (name.startsWith(prefix)
          && (name.endsWith(".md")
              || name.endsWith(".html"))
              && size.isPresent()
          && 0 < size.get() && size.get() <= SMALL_RESOURCE) {
        name = name.substring(prefix.length());
        if (name.startsWith("cmd-")) {
          cmds.add(entry);
        } else if (name.startsWith("servlet-")) {
          servlets.add(entry);
        } else if (name.startsWith("rest-api-")) {
          restApis.add(entry);
        } else if (name.startsWith("about.")) {
          if (about == null) {
            about = entry;
          }
        } else {
          docs.add(entry);
        }
      }
    }

    Collections.sort(cmds, PluginEntry.COMPARATOR_BY_NAME);
    Collections.sort(docs, PluginEntry.COMPARATOR_BY_NAME);

    StringBuilder md = new StringBuilder();
    md.append(String.format("# Plugin %s #\n", pluginName));
    md.append("\n");
    appendPluginInfoTable(md, scanner.getManifest().getMainAttributes());

    if (about != null) {
      InputStreamReader isr = new InputStreamReader(scanner.getInputStream(about));
      BufferedReader reader = new BufferedReader(isr);
      StringBuilder aboutContent = new StringBuilder();
      String line;
      while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (line.isEmpty()) {
          aboutContent.append("\n");
        } else {
          aboutContent.append(line).append("\n");
        }
      }
      reader.close();

      // Only append the About section if there was anything in it
      if (aboutContent.toString().trim().length() > 0) {
        md.append("## About ##\n");
        md.append("\n").append(aboutContent);
      }
    }

    appendEntriesSection(scanner, docs, "Documentation", md, prefix, 0);
    appendEntriesSection(scanner, servlets, "Servlets", md, prefix, "servlet-".length());
    appendEntriesSection(scanner, restApis, "REST APIs", md, prefix, "rest-api-".length());
    appendEntriesSection(scanner, cmds, "Commands", md, prefix, "cmd-".length());

    sendMarkdownAsHtml(md.toString(), pluginName, cacheKey, res, lastModifiedTime);
  }

  private void sendMarkdownAsHtml(String md, String pluginName,
      PluginResourceKey cacheKey, HttpServletResponse res, long lastModifiedTime)
      throws UnsupportedEncodingException, IOException {
    Map<String, String> macros = Maps.newHashMap();
    macros.put("PLUGIN", pluginName);
    macros.put("SSH_HOST", sshHost);
    macros.put("SSH_PORT", "" + sshPort);
    String url = webUrl.get();
    if (Strings.isNullOrEmpty(url)) {
      url = "http://review.example.com/";
    }
    macros.put("URL", url);

    Matcher m = Pattern.compile("(\\\\)?@([A-Z_]+)@").matcher(md);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      String key = m.group(2);
      String val = macros.get(key);
      if (m.group(1) != null) {
        m.appendReplacement(sb, "@" + key + "@");
      } else if (val != null) {
        m.appendReplacement(sb, val);
      } else {
        m.appendReplacement(sb, "@" + key + "@");
      }
    }
    m.appendTail(sb);

    byte[] html = new MarkdownFormatter()
      .markdownToDocHtml(sb.toString(), "UTF-8");
    resourceCache.put(cacheKey, new SmallResource(html)
        .setContentType("text/html")
        .setCharacterEncoding("UTF-8")
        .setLastModified(lastModifiedTime));
    res.setContentType("text/html");
    res.setCharacterEncoding("UTF-8");
    res.setContentLength(html.length);
    res.setDateHeader("Last-Modified", lastModifiedTime);
    res.getOutputStream().write(html);
  }

  private static void appendPluginInfoTable(StringBuilder html, Attributes main) {
    if (main != null) {
      String t = main.getValue(Attributes.Name.IMPLEMENTATION_TITLE);
      String n = main.getValue(Attributes.Name.IMPLEMENTATION_VENDOR);
      String v = main.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
      String u = main.getValue(Attributes.Name.IMPLEMENTATION_URL);
      String a = main.getValue("Gerrit-ApiVersion");

      html.append("
");
      if (!Strings.isNullOrEmpty(t)) {
        html.append("
Name	")
            .append(t)
            .append("
\n");
      }
      if (!Strings.isNullOrEmpty(n)) {
        html.append("
Vendor	")
            .append(n)
            .append("
\n");
      }
      if (!Strings.isNullOrEmpty(v)) {
        html.append("
Version	")
            .append(v)
            .append("
\n");
      }
      if (!Strings.isNullOrEmpty(u)) {
        html.append("
URL	")
            .append(String.format("%s", u, u))
            .append("
\n");
      }
      if (!Strings.isNullOrEmpty(a)) {
        html.append("
API Version	")
            .append(a)
            .append("
\n");
      }
      html.append("
\n");
    }
  }

  private static String extractTitleFromMarkdown(PluginContentScanner scanner, PluginEntry entry)
        throws IOException {
    String charEnc = null;
    Map<Object, String> atts = entry.getAttrs();
    if (atts != null) {
      charEnc = Strings.emptyToNull(atts.get(ATTR_CHARACTER_ENCODING));
    }
    if (charEnc == null) {
      charEnc = "UTF-8";
    }
    return new MarkdownFormatter().extractTitleFromMarkdown(
          readWholeEntry(scanner, entry),
          charEnc);
  }

  private static Optional<PluginEntry> findSource(
      PluginContentScanner scanner, String file) throws IOException {
    if (file.endsWith(".html")) {
      int d = file.lastIndexOf('.');
      return scanner.getEntry(file.substring(0, d) + ".md");
    }
    return Optional.absent();
  }

  private void sendMarkdownAsHtml(PluginContentScanner scanner, PluginEntry entry,
      String pluginName, PluginResourceKey key, HttpServletResponse res)
      throws IOException {
    byte[] rawmd = readWholeEntry(scanner, entry);
    String encoding = null;
    Map<Object, String> atts = entry.getAttrs();
    if (atts != null) {
      encoding = Strings.emptyToNull(atts.get(ATTR_CHARACTER_ENCODING));
    }

    String txtmd = RawParseUtils.decode(
        Charset.forName(encoding != null ? encoding : "UTF-8"),
        rawmd);
    long time = entry.getTime();
    if (0 < time) {
      res.setDateHeader("Last-Modified", time);
    }
    sendMarkdownAsHtml(txtmd, pluginName, key, res, time);
  }

  private void sendResource(PluginContentScanner scanner, PluginEntry entry,
      PluginResourceKey key, HttpServletResponse res)
      throws IOException {
    byte[] data = null;
    Optional<Long> size = entry.getSize();
    if (size.isPresent() && size.get() <= SMALL_RESOURCE) {
      data = readWholeEntry(scanner, entry);
    }

    String contentType = null;
    String charEnc = null;
    Map<Object, String> atts = entry.getAttrs();
    if (atts != null) {
      contentType = Strings.emptyToNull(atts.get(ATTR_CONTENT_TYPE));
      charEnc = Strings.emptyToNull(atts.get(ATTR_CHARACTER_ENCODING));
    }
    if (contentType == null) {
      contentType = mimeUtil.getMimeType(entry.getName(), data).toString();
      if ("application/octet-stream".equals(contentType)
          && entry.getName().endsWith(".js")) {
        contentType = "application/javascript";
      }
    }

    long time = entry.getTime();
    if (0 < time) {
      res.setDateHeader("Last-Modified", time);
    }
    if (size.isPresent()) {
      res.setHeader("Content-Length", size.get().toString());
    }
    res.setContentType(contentType);
    if (charEnc != null) {
      res.setCharacterEncoding(charEnc);
    }
    if (data != null) {
      resourceCache.put(key, new SmallResource(data)
          .setContentType(contentType)
          .setCharacterEncoding(charEnc)
          .setLastModified(time));
      res.getOutputStream().write(data);
    } else {
      writeToResponse(res, scanner.getInputStream(entry));
    }
  }

  private void sendJsPlugin(Plugin plugin, PluginResourceKey key,
      HttpServletRequest req, HttpServletResponse res) throws IOException {
    Path path = plugin.getSrcFile();
    if (req.getRequestURI().endsWith(getJsPluginPath(plugin))
        && Files.exists(path)) {
      res.setHeader("Content-Length", Long.toString(Files.size(path)));
      res.setContentType("application/javascript");
      writeToResponse(res, Files.newInputStream(path));
    } else {
      resourceCache.put(key, Resource.NOT_FOUND);
      Resource.NOT_FOUND.send(req, res);
    }
  }

  private static String getJsPluginPath(Plugin plugin) {
    return String.format("/plugins/%s/static/%s", plugin.getName(),
        plugin.getSrcFile().getFileName());
  }

  private void writeToResponse(HttpServletResponse res, InputStream inputStream)
      throws IOException {
    try (OutputStream out = res.getOutputStream();
        InputStream in = inputStream) {
      ByteStreams.copy(in, out);
    }
  }

  private static byte[] readWholeEntry(PluginContentScanner scanner, PluginEntry entry)
      throws IOException {
    byte[] data = new byte[entry.getSize().get().intValue()];
    InputStream in = scanner.getInputStream(entry);
    try {
      IO.readFully(in, data, 0, data.length);
    } finally {
      in.close();
    }
    return data;
  }

  private static class PluginHolder {
    final Plugin plugin;
    final GuiceFilter filter;
    final String staticPrefix;
    final String docPrefix;

    PluginHolder(Plugin plugin, GuiceFilter filter) {
      this.plugin = plugin;
      this.filter = filter;
      this.staticPrefix =
        getPrefix(plugin, "Gerrit-HttpStaticPrefix", "static/");
      this.docPrefix =
        getPrefix(plugin, "Gerrit-HttpDocumentationPrefix", "Documentation/");
    }

    private static String getPrefix(Plugin plugin, String attr, String def) {
      Path path = plugin.getSrcFile();
      PluginContentScanner scanner = plugin.getContentScanner();
      if (path == null || scanner == PluginContentScanner.EMPTY) {
        return def;
      }
      try {
        String prefix =
            scanner.getManifest().getMainAttributes().getValue(attr);
        if (prefix != null) {
          return CharMatcher.is('/').trimFrom(prefix) + "/";
        } else {
          return def;
        }
      } catch (IOException e) {
        log.warn(String.format("Error getting %s for plugin %s, using default",
            attr, plugin.getName()), e);
        return null;
      }
    }
  }
}


text:
package org.spongepowered.api.block;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;

import java.util.Collection;

/**
 * Represents a block with type and data.
 *
 *
This interface represents something directly analogous to block states
 * in Minecraft.

 */
public interface BlockState {

    /**
     * Get the base type of block.
     *
     *
The type does not include block data such as the contents of
     * inventories.

     *
     * @return The type of block
     */
    BlockType getType();

    /**
     * Get all properties defined on this BlockState, with their current values.
     *
     * @return Map of all current properties
     */
    ImmutableMap<BlockProperty<?>, ? extends Comparable<?>> getProperties();

    /**
     * Get all property names defined on this BlockState
     *
     * @return Collection of property names
     */
    Collection<String> getPropertyNames();

    /**
     * Get a property from its name.
     *
     * @param name The name of the property
     * @return The property with the given name
     */
    Optional<BlockProperty<?>> getPropertyByName(String name);

    /**
     * Get the current value of a given property.
     *
     * @param name Property to get value of
     * @return Current value of the property
     */
    Optional<? extends Comparable<?>> getPropertyValue(String name);

    /**
     * Get an altered BlockState with the given property set to the given value.
     *
     *
This does not alter the current BlockState instance

     *
     * @param property Property to change value of
     * @param value New value of property
     * @return A BlockState with the property's value modified
     */
    BlockState withProperty(BlockProperty<?> property, Comparable<?> value);

    /**
     * Get an altered BlockState with the given property set to the next valid
     * value for that property, cycling to the lowest value after the highest
     * value.
     *
     *
This does not alter the current BlockState instance

     *
     * @param property Property to change value of
     * @return A BlockState with the property's value modified
     */
    BlockState cycleProperty(BlockProperty<?> property);

    /**
     * Get the data value of the block at the given position.
     *
     *
The data value is a number between 0 and 15 (inclusive) that
     * represents a value for differentiation with certain blocks. For example,
     * the base dirt block has a data value that changes the variant of dirt.
     * The base data value is generally 0.

     *
     *
However, be aware that data values are being deprecated in
     * Minecraft because they are a waste of bytes and add extra complexity to
     * block differentiation. Most blocks don't use a data value, so that's
     * a waste of four bits of data per block. In the future, there will
     * only be one number to represent each 'state' of a block.

     *
     * @return The data value
     * @deprecated Exists for backwards-compatibility/transitional use
     */
    @Deprecated
    byte getDataValue();

}


text:
namespace DressZone.Models.Shop
{
    using Common.Contracts;
    using DressZone.Models.Shop.Common;
    using System;
    public class GenderType
    {

        public GenderType()
        {
            this.CreatedOn = DateTime.Now;
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime? CreatedOn { get; set; }
        public DateTime? DeletedOn { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime? ModifiedOn { get; set; }
    }

}


text:
/bin/rm -rf ~/.cpan/{build,sources}/ ~/.cpanm/{sources,work}

find ~/data/perl5/cpan/mini/authors/id/ -type f -atime +90 -delete


text:
<!DOCTYPE html />

	<title>UdpClientAdapter.cs</title>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
	<link href="../../nocco.css" rel="stylesheet" media="all" type="text/css" />

				Jump To …

								NModbus4\GlobalSuppressions.cs

								NModbus4\InvalidModbusRequestException.cs

								NModbus4\Modbus.cs

								NModbus4\SlaveException.cs

								NModbus4\Data\DataStore.cs

								NModbus4\Data\DataStoreEventArgs.cs

								NModbus4\Data\DataStoreFactory.cs

								NModbus4\Data\DiscreteCollection.cs

								NModbus4\Data\IModbusMessageDataCollection.cs

								NModbus4\Data\ModbusDataCollection.cs

								NModbus4\Data\ModbusDataType.cs

								NModbus4\Data\RegisterCollection.cs

								NModbus4\Device\IModbusMaster.cs

								NModbus4\Device\IModbusSerialMaster.cs

								NModbus4\Device\ModbusDevice.cs

								NModbus4\Device\ModbusIpMaster.cs

								NModbus4\Device\ModbusMaster.cs

								NModbus4\Device\ModbusMasterTcpConnection.cs

								NModbus4\Device\ModbusSerialMaster.cs

								NModbus4\Device\ModbusSerialSlave.cs

								NModbus4\Device\ModbusSlave.cs

								NModbus4\Device\ModbusSlaveRequestEventArgs.cs

								NModbus4\Device\ModbusTcpSlave.cs

								NModbus4\Device\ModbusUdpSlave.cs

								NModbus4\Device\TcpConnectionEventArgs.cs

								NModbus4\Extensions\Enron\EnronModbus.cs

								NModbus4\IO\EmptyTransport.cs

								NModbus4\IO\IStreamResource.cs

								NModbus4\IO\ModbusAsciiTransport.cs

								NModbus4\IO\ModbusIpTransport.cs

								NModbus4\IO\ModbusRtuTransport.cs

								NModbus4\IO\ModbusSerialTransport.cs

								NModbus4\IO\ModbusTransport.cs

								NModbus4\IO\SerialPortAdapter.cs

								NModbus4\IO\StreamResourceUtility.cs

								NModbus4\IO\TcpClientAdapter.cs

								NModbus4\IO\UdpClientAdapter.cs

								NModbus4\Message\AbstractModbusMessage.cs

								NModbus4\Message\AbstractModbusMessageWithData.cs

								NModbus4\Message\DiagnosticsRequestResponse.cs

								NModbus4\Message\IModbusMessage.cs

								NModbus4\Message\IModbusRequest.cs

								NModbus4\Message\ModbusMessageFactory.cs

								NModbus4\Message\ModbusMessageImpl.cs

								NModbus4\Message\ReadCoilsInputsRequest.cs

								NModbus4\Message\ReadCoilsInputsResponse.cs

								NModbus4\Message\ReadHoldingInputRegistersRequest.cs

								NModbus4\Message\ReadHoldingInputRegistersResponse.cs

								NModbus4\Message\ReadWriteMultipleRegistersRequest.cs

								NModbus4\Message\SlaveExceptionResponse.cs

								NModbus4\Message\WriteMultipleCoilsRequest.cs

								NModbus4\Message\WriteMultipleCoilsResponse.cs

								NModbus4\Message\WriteMultipleRegistersRequest.cs

								NModbus4\Message\WriteMultipleRegistersResponse.cs

								NModbus4\Message\WriteSingleCoilRequestResponse.cs

								NModbus4\Message\WriteSingleRegisterRequestResponse.cs

								NModbus4\Properties\AssemblyInfo.cs

								NModbus4\Unme.Common\DisposableUtility.cs

								NModbus4\Unme.Common\EventUtility.cs

								NModbus4\Unme.Common\SequenceUtility.cs

								NModbus4\Utility\DiscriminatedUnion.cs

								NModbus4\Utility\ModbusUtility.cs

								NModbus4.UnitTests\SlaveExceptionFixture.cs

								NModbus4.UnitTests\Data\DataStoreEventArgsFixture.cs

								NModbus4.UnitTests\Data\DataStoreFixture.cs

								NModbus4.UnitTests\Data\DiscreteCollectionFixture.cs

								NModbus4.UnitTests\Data\ModbusDataCollectionFixture.cs

								NModbus4.UnitTests\Data\RegisterCollectionFixture.cs

								NModbus4.UnitTests\Device\ModbusMasterFixture.cs

								NModbus4.UnitTests\Device\ModbusSlaveFixture.cs

								NModbus4.UnitTests\Device\TcpConnectionEventArgsFixture.cs

								NModbus4.UnitTests\IO\ModbusAsciiTransportFixture.cs

								NModbus4.UnitTests\IO\ModbusRtuTransportFixture.cs

								NModbus4.UnitTests\IO\ModbusSerialTransportFixture.cs

								NModbus4.UnitTests\IO\ModbusTcpTransportFixture.cs

								NModbus4.UnitTests\IO\ModbusTransportFixture.cs

								NModbus4.UnitTests\IO\UdpClientAdapterFixture.cs

								NModbus4.UnitTests\Message\DiagnosticsRequestResponseFixture.cs

								NModbus4.UnitTests\Message\MessageUtility.cs

								NModbus4.UnitTests\Message\ModbusMessageFactoryFixture.cs

								NModbus4.UnitTests\Message\ModbusMessageFixture.cs

								NModbus4.UnitTests\Message\ModbusMessageImplFixture.cs

								NModbus4.UnitTests\Message\ModbusMessageWithDataFixture.cs

								NModbus4.UnitTests\Message\ReadCoilsInputsRequestFixture.cs

								NModbus4.UnitTests\Message\ReadCoilsInputsResponseFixture.cs

								NModbus4.UnitTests\Message\ReadHoldingInputRegistersRequestFixture.cs

								NModbus4.UnitTests\Message\ReadHoldingInputRegistersResponseFixture.cs

								NModbus4.UnitTests\Message\ReadWriteMultipleRegistersRequestFixture.cs

								NModbus4.UnitTests\Message\ReturnQueryDataRequestResponseFixture.cs

								NModbus4.UnitTests\Message\SlaveExceptionResponseFixture.cs

								NModbus4.UnitTests\Message\WriteMultipleCoilsRequestFixture.cs

								NModbus4.UnitTests\Message\WriteMultipleCoilsResponseFixture.cs

								NModbus4.UnitTests\Message\WriteMultipleRegistersRequestFixture.cs

								NModbus4.UnitTests\Message\WriteMultipleRegistersResponseFixture.cs

								NModbus4.UnitTests\Message\WriteSingleCoilRequestResponseFixture.cs

								NModbus4.UnitTests\Message\WriteSingleRegisterRequestResponseFixture.cs

								NModbus4.UnitTests\Properties\AssemblyInfo.cs

								NModbus4.UnitTests\Utility\CollectionUtilityFixture.cs

								NModbus4.UnitTests\Utility\DiscriminatedUnionFixture.cs

								NModbus4.UnitTests\Utility\ModbusUtilityFixture.cs

								NModbus4.UnitTests\Utility\SerialConnectionFixture.cs

								Samples\Driver.cs

								Samples\Properties\AssemblyInfo.cs

UdpClientAdapter.cs

								¶

namespace Modbus.IO
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    using Unme.Common;

								¶

Concrete Implementor - http://en.wikipedia.org/wiki/Bridge_Pattern

    internal class UdpClientAdapter : IStreamResource
    {

								¶

strategy for cross platform r/w

        private UdpClient _udpClient;
        private List<byte> Buffer;

        public UdpClientAdapter(UdpClient udpClient)
        {
            if (udpClient == null)
                throw new ArgumentNullException("udpClient");

            _udpClient = udpClient;
        }

        public int InfiniteTimeout
        {
            get { return Timeout.Infinite; }
        }

        public int ReadTimeout
        {
            get { return _udpClient.Client.ReceiveTimeout; }
            set { _udpClient.Client.ReceiveTimeout = value; }
        }

        public int WriteTimeout
        {
            get { return _udpClient.Client.SendTimeout; }
            set { _udpClient.Client.SendTimeout = value; }
        }

        public void DiscardInBuffer()
        {

								¶

no-op

        }

        public int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", "Argument offset must be greater than or equal to 0.");
            if (offset > buffer.Length)
                throw new ArgumentOutOfRangeException("offset", "Argument offset cannot be greater than the length of buffer.");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", "Argument count must be greater than or equal to 0.");
            if (count > buffer.Length - offset)
                throw new ArgumentOutOfRangeException("count", "Argument count cannot be greater than the length of buffer minus offset.");

            if (Buffer == null || Buffer.Count == 0)
            {
                IPEndPoint remoteIpEndPoint = null;
                Buffer = _udpClient.Receive(ref remoteIpEndPoint).ToList();
            }

            if (Buffer.Count < count)
                throw new IOException("Not enough bytes in the datagram.");

            Buffer.CopyTo(0, buffer, offset, count);
            Buffer.RemoveRange(0, count);

            return count;
        }

        public void Write(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", "Argument offset must be greater than or equal to 0.");
            if (offset > buffer.Length)
                throw new ArgumentOutOfRangeException("offset", "Argument offset cannot be greater than the length of buffer.");
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", "Argument count must be greater than or equal to 0.");
            if (count > buffer.Length - offset)
                throw new ArgumentOutOfRangeException("count", "Argument count cannot be greater than the length of buffer minus offset.");

            _udpClient.Send(buffer.Skip(offset).ToArray(), count);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
                DisposableUtility.Dispose(ref _udpClient);
        }
    }
}


text:
package br.com.moip.resource.links;

public class OrderLink {
    private String title;
    private String href;

    public OrderLink(String title, String href){
        this.title = title;
        this.href = href;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }
}


text:
package io.crate.expression;

import io.crate.data.Input;

import javax.annotation.Nullable;
import java.util.List;

public interface NestableInput<T> extends Input<T> {

    /**
     * Returns an implementation for a child.
     *
     * @param name The name of the child
     * @return an implementation for the child or null if not applicable or if there is no child available
     * with the given name
     */
    @Nullable
    default NestableInput<?> getChild(String name) {
        return null;
    }

    @Nullable
    static NestableInput<?> getChildByPath(NestableInput<?> impl, List<String> path) {
        for (int i = 0; i < path.size(); i++) {
            impl = impl.getChild(path.get(i));
            if (impl == null) {
                return null;
            }
        }
        return impl;
    }
}


text:
<?php
	class Admin extends CI_Controller{

		public function __construct(){
			parent::__construct();
			$this->load->library("session");
			$this->load->model("Madmin");
			$this->load->library('form_validation');
			$this->load->helper("url",'form');
		}

		public function index(){
			$info = $this->session->userdata('adminInfo');
			$data['info'] = $info;
			$data['admin'] = $this->Madmin->select($info);
			if(empty($info))
				header('location: '.base_url().'index.php/admin/login');
			$this->load->view("admin/admin-view",$data);
		}

		public function login(){
			$info = $this->session->userdata('adminInfo');
			if(!empty($info))
				header('location: '.base_url().'index.php/admin');

			$this->form_validation->set_rules('fadmin', 'Tên đăng nhập', 'required',array(
				'required' => "Bạn chưa nhập %s"
				));
			$this->form_validation->set_rules('fpass', 'Mật khẩu', 'required',array(
				'required' => "Bạn chưa nhập %s"
				));
			if($this->form_validation->run() == FALSE){
				$data['error'] = "";
            	$this->load->view("admin/login-admin",$data);
        	}else{
        		$name = $this->input->post('fadmin');
				$pass = $this->input->post('fpass');
				$data["check"] = $this->Madmin->checkLogin($name, $pass);
				if ($data['check'] == 1){
					$adminData = $name;
					$this->session->set_userdata('adminInfo', $adminData);
					header('location: '.base_url().'index.php/admin');
				}
				$this->load->view("admin/login-admin",$data);
        	}
		}

		public function logout(){
			$this->session->unset_userdata('adminInfo');
			header('location: '.base_url().'index.php/admin/login');
		}
	}
?>


text:
A logging library for c++. Includes a type safe printf, and c++ stream format output. You can assign various streams and formatters to the logger to make a single logger output to a number of different places

To make a logger object, you use `make_logger` and give it a hesiod `stream` with a `formatter` defined:
```C++
static auto info = hesiod::make_logger<char>(hesiod::stream<standard_formatter>(std::cout));
```

A `hesiod::stream` is more or less a wrapper around a `std::stream` that is parameterised with a `hesiod::formatter`, which looks like:

```
class html_formatter : public hesiod::formatter<char> {
public:
    static std::string start() {
        return "<font face=\"courier new\" size=\"2\" color=\"#FF0000\"";
    }

    static std::string end() {
        return "</font>";
    }

    static std::string line() {
        return "<hr>";
    }
};
```

A formatter has 3 static functions that tell the stream what to do before outputting data, after outputting data, and what to do when the stream encounters a `hesiod::endl`

Putting it together:

```
#include <iostream>
#include <fstream>

#include "hesiod/lib.hpp"
#include "hesiod/stream.hpp"
#include "hesiod/logger.hpp"
#include "hesiod/manipulator.hpp"
#include "hesiod/standard_formatter.hpp"

namespace log {

using standard_formatter = hesiod::standard_formatter<char>;

class html_formatter : public hesiod::formatter<char> {
public:
    static std::string start() {
        return "<font face=\"courier new\" size=\"2\" color=\"#FF0000\"";
    }

    static std::string end() {
        return "</font>";
    }

    static std::string line() {
        return "<hr>";
    }
};

static auto info = hesiod::make_logger<char>(hesiod::stream<standard_formatter>(std::cout));

static std::ofstream html_file("log.html", std::ios::out);
static std::ofstream text_file("log.txt", std::ios::out);

static auto error = hesiod::make_logger<char>(
    hesiod::stream<standard_formatter>(std::cout),
    hesiod::stream<html_formatter>(html_file),
    hesiod::stream<standard_formatter>(text_file)
);

static auto endl = hesiod::endl;
}

int main(int argc, char **argv) {
    log::info.write("Write % log\n", "info");
    log::error.write("Write % log\n", "error");

    log::info.writeln("Write2 % log", "info");
    log::error.writeln("Write2 % log", "error");

    log::info << "Stream " << "info " << "3" << 4 << 5.5 << log::endl;
    log::error << "Stream " << "error " << "3" << 4 << 5.5 << log::endl;

    return 0;
}
```


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/memory/p10_mss_freq_system.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p10_mss_freq_system.C
/// @brief Matches OMI freq with DDR freq
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

// fapi2
#include <p10_mss_freq_system.H>
#include <lib/freq/p10_sync.H>
#include <generic/memory/lib/utils/find.H>
#include <generic/memory/lib/utils/count_dimm.H>

extern "C"
{
///
/// @brief Matches OMI freq with DDR freq
/// @param[in] i_target PROC_CHIP target
/// @return FAPI2_RC_SUCCESS iff ok
///
    fapi2::ReturnCode p10_mss_freq_system( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target )
    {
        const auto& l_ports = mss::find_targets<fapi2::TARGET_TYPE_MEM_PORT>(i_target);

        // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
        // attributes for the PHY, etc. If there is even one DIMM on this proc,
        // we do the right thing.
        if (mss::count_dimm(l_ports) == 0)
        {
            FAPI_INF("... skipping freq_system - no DIMM ...");
            return fapi2::FAPI2_RC_SUCCESS;
        }

        std::map< fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>, uint64_t > l_freq_map;
        uint32_t l_omi_freq = 0;
        uint32_t l_selected_omi_freq = 0;
        mss::speed_equality l_equal_dimm_speed;

        // Get OMI freq
        FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_FREQ_OMI_MHZ, i_target, l_omi_freq) );

        // Populate dimm speed map
        FAPI_TRY( mss::dimm_speed_map(l_ports, l_freq_map, l_equal_dimm_speed),
                  "Failed to get dimm speed mapping" );

        FAPI_INF("Dimm speed for all OCMBs are the same : %s",
                 uint8_t(l_equal_dimm_speed) ? "true" : "false");

        // Select OMI freq, or check in the case of Cronus
        FAPI_TRY( mss::select_omi_freq(l_freq_map,
                                       l_equal_dimm_speed,
                                       l_omi_freq,
                                       l_selected_omi_freq) );

        // Set attributes.
        FAPI_TRY( mss::set_freq_system_attrs(i_target, l_selected_omi_freq) );

    fapi_try_exit:
        return fapi2::current_err;
    }

} //extern "C"


text:
<?php
class Cache_Static extends Cache_SharedMemoryCache {
    /**
     * The cached data.
     * @var array
     */
    private static $__data;

    // CONSTRUCTION
    //------------------------------------------------------
    public function __construct() {
        $this->clear();
    }

    // CACHE IMPLEMENTATION
    //------------------------------------------------------
    public function save($name, $value) {
        self::$__data[$this->getNamespace()][$name] = $value;
        return true;
    }
    public function has($name) {
        return isset(self::$__data[$this->getNamespace()][$name]);
    }
    public function load($name) {
        if(isset(self::$__data[$this->getNamespace()][$name])) {
            return self::$__data[$this->getNamespace()][$name];
        }
        return null;
    }
    public function delete($name) {
        unset(self::$__data[$this->getNamespace()][$name]);
        return true;
    }
    public function clear() {
        self::$__data = array(
            $this->getNamespace() => array()
        );
        return true;
    }
}
?>


text:
/*
Authors:

1. Chetan Jhurani (chetan.jhurani@gmail.com, jhurani@txcorp.com)
     For more information and relevant publications, visit
     http://www.ices.utexas.edu/~chetan/

2. Travis M. Austin (austin@txcorp.com)

Contact address:

Tech-X Corporation
5621 Arapahoe Ave
Boulder, CO 80303
http://www.txcorp.com

*/

#ifndef P_NORM_SPARSITY_SPARSE_MATRIX_H
#define P_NORM_SPARSITY_SPARSE_MATRIX_H

// -----------------------------------------------------------------------------

#include "sparsity_union/sparse_vectors_union_w_trans.h"
#include "p_norm_sparsity_vectors/p_norm_sparsity_sparse_vectors.h"
#include "sparse_vectors/sparse_vectors.h"
#include "math/precision_traits.h"
#include "cpp/vector_vector_id.h"
#include "internal_api_error/internal_api_error.h"
#include <sstream>
#include <vector>
#include <cassert>

// -----------------------------------------------------------------------------
// Objective: To compute the p-norm sparsity pattern of sparse matrices given in
// various forms.
// 1. Both row and col oriented values given for a general matrix.  They would
//    refer to the same numerical matrix.  The purpose is that if data in both
//    orientations is known, then it would be easier to use what is given rather
//    than create a transpose.
// 2. Row or col values given for a matrix whose absolute value is symmetric.
// 3. Row-oriented general sparse matrix, for which we'll have to create a
//    transpose first.
// -----------------------------------------------------------------------------

// Output ids will be sorted, unique, and relative to row ids.

template
<
    typename index_type,
    typename offset_type,
    typename value_type
>
bool p_norm_sparsity_sparse_matrix(

// algorithmic options:
    typename precision_traits<value_type>::scalar ratio,
    typename precision_traits<value_type>::scalar p,
    index_type min_num_nnz_per_row,
    index_type min_num_nnz_per_col,

// input data:
    index_type num_rows,
    index_type num_cols,
    const offset_type* row_offsets, // offsets in rows
    const index_type* row_ids,      // ids in rows, must be sorted.
    const value_type* row_values,   // values in rows
    const offset_type* col_offsets, // offsets in columns
    const index_type* col_ids,      // ids in columns, need not be sorted.
    const value_type* col_values,   // values in columns

// output ids:
    std::vector< std::vector<index_type> >& row_oriented_sparse_pat)
{
    if(
        !row_offsets || !row_ids || !row_values ||
        !col_offsets || !col_ids || !col_values)
    {
        assert(false);

        std::ostringstream oss;
        oss << "p_norm_sparsity_sparse_matrix: Unacceptable input argument(s).";
        if(!row_offsets) oss << " !row_offsets.";
        if(!row_ids)     oss << " !row_ids.";
        if(!row_values)  oss << " !row_values.";
        if(!col_offsets) oss << " !col_offsets.";
        if(!col_ids)     oss << " !col_ids.";
        if(!col_values)  oss << " !col_values.";

        internal_api_error_set_last(oss.str());

        return false;
    }

    std::vector< std::vector<index_type> > tmp_row_pat, tmp_col_pat;

    bool success =
        // row-wise pattern
        p_norm_sparsity_sparse_vectors(
            ratio,
            p,
            min_num_nnz_per_row,
            num_rows,
            num_cols,
            row_offsets,
            row_values,
            tmp_row_pat)
        &&
        // col-wise pattern
        p_norm_sparsity_sparse_vectors(
            ratio,
            p,
            min_num_nnz_per_col,
            num_cols,
            num_rows,
            col_offsets,
            col_values,
            tmp_col_pat);

    if(success)
    {
        sparse_vectors_ids<const index_type, const offset_type>
            row_id_vecs(num_rows, num_cols, row_offsets, row_ids);

        // union of the two patterns
        success = sparse_vectors_union_w_trans(
            vector_vector_id<index_type>(tmp_row_pat),
            row_id_vecs,
            vector_vector_id<index_type>(tmp_col_pat),
            row_oriented_sparse_pat);
    }

   assert(success);

    if(!success)
        internal_api_error_set_last("p_norm_sparsity_sparse_matrix: Error.");

    return success;
}

// -----------------------------------------------------------------------------

// If matrix is actually abs_sym, this will work for both row- and column-
// oriented data.  Output ids will be sorted, unique, and relative to row ids.
// "abs_sym" means its element-wise absolute value is symmetric.

template
<
    typename index_type,
    typename offset_type,
    typename value_type
>
bool p_norm_sparsity_sparse_matrix_abs_sym(
    typename precision_traits<value_type>::scalar ratio,
    typename precision_traits<value_type>::scalar p,
    index_type min_num_nnz,
    index_type matrix_size,
    const offset_type* offsets, // offsets in rows/cols
    const index_type* ids,      // ids in rows/cols, must be sorted
    const value_type* values,   // values in rows/cols
    std::vector< std::vector<index_type> >& row_oriented_sparse_pat)
{
    if(!offsets || !ids || !values)
    {
        assert(false);

        std::ostringstream oss;
        oss << "p_norm_sparsity_sparse_matrix_abs_sym: Unacceptable input argument(s).";
        if(!offsets) oss << " !offsets.";
        if(!ids)     oss << " !ids.";
        if(!values)  oss << " !values.";

        internal_api_error_set_last(oss.str());

        return false;
    }

    std::vector< std::vector<index_type> > tmp_pat;

    bool success =
        p_norm_sparsity_sparse_vectors(
            ratio,
            p,
            min_num_nnz,
            matrix_size,
            matrix_size,
            offsets,
            values,
            tmp_pat);

    if(success)
    {
        sparse_vectors_ids<const index_type, const offset_type>
            id_vecs(matrix_size, matrix_size, offsets, ids);

        success = sparse_vectors_union_w_self_trans(
            vector_vector_id<index_type>(tmp_pat),
            id_vecs,
            row_oriented_sparse_pat);
    }

   assert(success);

    if(!success)
        internal_api_error_set_last("p_norm_sparsity_sparse_matrix_abs_sym: Error.");

    return success;
}

// -----------------------------------------------------------------------------

// Output ids will be sorted, unique, and relative to row ids.

template
<
    typename index_type,
    typename offset_type,
    typename value_type
>
bool p_norm_sparsity_sparse_matrix_row_oriented(
    typename precision_traits<value_type>::scalar ratio,
    typename precision_traits<value_type>::scalar p,
    index_type min_num_nnz_per_row,
    index_type min_num_nnz_per_col,
    index_type num_rows,
    index_type num_cols,
    const offset_type* row_offsets, // offsets in rows
    const index_type* row_ids,      // ids in rows, must be sorted.
    const value_type* row_values,   // values in rows
    std::vector< std::vector<index_type> >& row_oriented_sparse_pat)
{
    if(!row_offsets || !row_ids || !row_values)
    {
        assert(false);

        std::ostringstream oss;
        oss << "p_norm_sparsity_sparse_matrix_row_oriented: Unacceptable input argument(s).";
        if(!row_offsets) oss << " !row_offsets.";
        if(!row_ids)     oss << " !row_ids.";
        if(!row_values)  oss << " !row_values.";

        internal_api_error_set_last(oss.str());

        return false;
    }

    const sparse_vectors
        <const index_type, const offset_type, const value_type>
        row_oriented(num_rows, num_cols, row_offsets, row_ids, row_values);

    sparse_vectors<index_type, offset_type, value_type> col_oriented;

    bool success =
        row_oriented.get_transpose(col_oriented)
        &&
        p_norm_sparsity_sparse_matrix(
                ratio,
                p,
                min_num_nnz_per_row,
                min_num_nnz_per_col,
                num_rows,
                num_cols,
                row_offsets,
                row_ids,
                row_values,
                col_oriented.vec_offsets(),
                col_oriented.vec_ids(),
                col_oriented.vec_values(),
                row_oriented_sparse_pat);

   assert(success);

    if(!success)
        internal_api_error_set_last("p_norm_sparsity_sparse_matrix_row_oriented: Error.");

    return success;
}

// -----------------------------------------------------------------------------

#endif // P_NORM_SPARSITY_SPARSE_MATRIX_H


text:
package org.apache.solr.handler.component;

import org.apache.lucene.util.Constants;
import org.apache.solr.BaseDistributedSearchTestCase;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.BinaryResponseParser;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.junit.BeforeClass;
import org.junit.Test;

/** */
// See: https://issues.apache.org/jira/browse/SOLR-12028 Tests cannot remove files on Windows
// machines occasionally
public class DistributedQueryElevationComponentTest extends BaseDistributedSearchTestCase {

  @BeforeClass
  public static void betterNotBeJ9() {
    assumeFalse(
        "FIXME: SOLR-5791: This test fails under IBM J9", Constants.JAVA_VENDOR.startsWith("IBM"));
  }

  public DistributedQueryElevationComponentTest() {
    stress = 0;

    // TODO: a better way to do this?
    configString = "solrconfig-elevate.xml";
    schemaString = "schema11.xml";
  }

  @Test
  @ShardsFixed(num = 3)
  public void test() throws Exception {

    del("*:*");
    indexr(id, "1", "int_i", "1", "text", "XXXX XXXX", "field_t", "anything");
    indexr(id, "2", "int_i", "2", "text", "YYYY YYYY", "plow_t", "rake");
    indexr(id, "3", "int_i", "3", "text", "ZZZZ ZZZZ");
    indexr(id, "4", "int_i", "4", "text", "XXXX XXXX");
    indexr(id, "5", "int_i", "5", "text", "ZZZZ ZZZZ ZZZZ");
    indexr(id, "6", "int_i", "6", "text", "ZZZZ");

    index_specific(2, id, "7", "int_i", "7", "text", "solr");
    commit();

    handle.put("explain", SKIPVAL);
    handle.put("debug", SKIPVAL);
    handle.put("maxScore", SKIPVAL);
    handle.put("timestamp", SKIPVAL);
    handle.put("score", SKIPVAL);
    handle.put("wt", SKIP);
    handle.put("distrib", SKIP);
    handle.put("shards.qt", SKIP);
    handle.put("shards", SKIP);
    handle.put("q", SKIP);
    handle.put("qt", SKIP);
    query(
        "q",
        "*:*",
        "qt",
        "/elevate",
        "shards.qt",
        "/elevate",
        "rows",
        "500",
        "sort",
        "id desc",
        CommonParams.FL,
        "id, score, [elevated]");

    query(
        "q",
        "ZZZZ",
        "qt",
        "/elevate",
        "shards.qt",
        "/elevate",
        "rows",
        "500",
        CommonParams.FL,
        "*, [elevated]",
        "forceElevation",
        "true",
        "sort",
        "int_i desc");

    query(
        "q",
        "solr",
        "qt",
        "/elevate",
        "shards.qt",
        "/elevate",
        "rows",
        "500",
        CommonParams.FL,
        "*, [elevated]",
        "forceElevation",
        "true",
        "sort",
        "int_i asc");

    query(
        "q",
        "ZZZZ",
        "qt",
        "/elevate",
        "shards.qt",
        "/elevate",
        "rows",
        "500",
        CommonParams.FL,
        "*, [elevated]",
        "forceElevation",
        "true",
        "sort",
        "id desc");

    // See SOLR-4854 for background on following test code

    // Uses XML response format by default
    QueryResponse response =
        query(
            "q",
            "XXXX",
            "qt",
            "/elevate",
            "shards.qt",
            "/elevate",
            "rows",
            "500",
            CommonParams.FL,
            "id, [elevated]",
            "enableElevation",
            "true",
            "forceElevation",
            "true",
            "elevateIds",
            "6",
            "sort",
            "id desc");

    assertTrue(response.getResults().getNumFound() > 0);
    SolrDocument document = response.getResults().get(0);
    assertEquals("6", document.getFieldValue("id"));
    assertEquals(true, document.getFieldValue("[elevated]"));

    // Force javabin format
    final String clientUrl = ((HttpSolrClient) clients.get(0)).getBaseURL();
    SolrClient client = getHttpSolrClient(clientUrl);
    ((HttpSolrClient) client).setParser(new BinaryResponseParser());
    SolrQuery solrQuery =
        new SolrQuery("XXXX")
            .setParam("qt", "/elevate")
            .setParam("shards.qt", "/elevate")
            .setRows(500)
            .setFields("id,[elevated]")
            .setParam("enableElevation", "true")
            .setParam("forceElevation", "true")
            .setParam("elevateIds", "6", "wt", "javabin")
            .setSort("id", SolrQuery.ORDER.desc);
    setDistributedParams(solrQuery);
    response = client.query(solrQuery);
    client.close();

    assertTrue(response.getResults().getNumFound() > 0);
    document = response.getResults().get(0);
    assertEquals("6", document.getFieldValue("id"));
    assertEquals(true, document.getFieldValue("[elevated]"));
  }

  @Override
  protected void indexr(Object... fields) throws Exception {
    SolrInputDocument doc = new SolrInputDocument();
    addFields(doc, fields);
    indexDoc(doc);
  }
}