text:
package com.gzlk.android.isp.listener;

import com.gzlk.android.isp.helper.StringHelper;
import com.gzlk.android.isp.helper.ToastHelper;
import com.litesuits.http.data.HttpStatus;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.response.Response;

/**
 * 功能描述:网络活动监听

 * 创建作者:Hsiang Leekwok

 * 创建时间:2017/04/17 21:35

 * 作者邮箱:xiang.l.g@gmail.com

 * 最新版本:Version: 1.0.0

 * 修改时间:2017/04/17 21:35

 * 修改人员:

 * 修改备注:

 */

public abstract class OnHttpListener<T> extends HttpListener<T> {

    public OnHttpListener() {
        super();
    }

    public OnHttpListener(boolean readingNotify, boolean uploadingNotify) {
        super(true, readingNotify, uploadingNotify);
    }

    @Override
    public void onSuccess(T data, Response<T> response) {
        super.onSuccess(data, response);
        onSucceed(data, response);
    }

    /**
     * 网络调用成功之后的处理
     */
    public void onSucceed(T data, Response<T> response) {
    }

    /**
     * 网络调用失败后的处理
     */
    public void onFailed() {
    }

    @Override
    public void onFailure(HttpException e, Response<T> response) {
        super.onFailure(e, response);
        HttpStatus status = response.getHttpStatus();
        ToastHelper.make(null).showMsg(StringHelper.format("网咯操作失败: (%d)%s", (null == status ? -1 : status.getCode()), e.getMessage()));
        onFailed();
    }

    @Override
    public void onCancel(T t, Response<T> response) {
        super.onCancel(t, response);
        HttpStatus status = response.getHttpStatus();
        ToastHelper.make(null).showMsg(StringHelper.format("网咯操作已取消: (%d)", (null == status ? -1 : status.getCode())));
        onFailed();
    }
}


text:
NotifyCategoryDecl(motiontrail, EXPCL_DIRECT, EXPTP_DIRECT);

extern EXPCL_DIRECT void init_libmotiontrail();

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.huawei.streaming.cql.semanticanalyzer.parser.visitor;

import org.antlr.v4.runtime.misc.NotNull;

import com.huawei.streaming.cql.semanticanalyzer.parser.CQLParser;
import com.huawei.streaming.cql.semanticanalyzer.parser.context.DropApplicationContext;

/**
 * drop application 语法遍历
 *
 */
public class DropApplicationVisitor extends AbsCQLParserBaseVisitor<DropApplicationContext>
{
    private DropApplicationContext context = null;

    /**
     * <默认构造函数>
     */
    public DropApplicationVisitor()
    {
        context = new DropApplicationContext();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected DropApplicationContext defaultResult()
    {
        return context;
    }

    /**
     * {@inheritDoc}
     */
    public DropApplicationContext visitIfExists(@NotNull CQLParser.IfExistsContext ctx)
    {
        context.setIfExists(true);
        return context;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DropApplicationContext visitApplicationName(@NotNull CQLParser.ApplicationNameContext ctx)
    {
        context.setApplicationName(ctx.getText());
        return context;
    }

}


text:
package docker

import (
	"bytes"
	"regexp"
	"strings"

	"github.com/docker/docker/builder/dockerfile/parser"
	"github.com/opentable/sous/util/docker_registry"
	"github.com/opentable/sous/util/logging"
	"github.com/opentable/sous/util/logging/messages"
	"github.com/opentable/sous/util/shell"
)

type dockerfileInspector struct {
	versionArg, revisionArg bool
	runspecPath             string
	registry                docker_registry.Client
	rootAst                 *parser.Node
	froms                   []*parser.Node
	envs                    []*parser.Node
	ls                      logging.LogSink
	sh                      shell.Shell
	dev                     bool
	envmap                  map[string]string
}

func inspectDockerfile(path string, devBuild bool, sh shell.Shell, dfPath string, registry docker_registry.Client, log logging.LogSink) (*dockerfileInspector, error) {

	ast, err := parseDockerfile(path)
	if err != nil {
		return nil, err
	}

	detector := &dockerfileInspector{
		rootAst:  ast,
		registry: registry,
		froms:    []*parser.Node{},
		envs:     []*parser.Node{},
		ls:       log,
		sh:       sh,
		dev:      devBuild,
	}

	return detector, detector.process()
}

func (dfi *dockerfileInspector) process() error {
	if err := dfi.absorbDocker(dfi.rootAst); err != nil {
		return err
	}
	return dfi.fetchFromRunSpec()
}

func (dfi *dockerfileInspector) fetchFromRunSpec() error {
	for _, f := range dfi.froms {
		if dfi.dev {
			if imageEnv, err := inspectImage(dfi.sh, f.Value); err == nil {
				messages.ReportLogFieldsMessage("Inspecting local", logging.DebugLevel, dfi.ls, f.Value)
				dfi.mergeEnv(parseImageOutput(imageEnv))
				continue
			}
		}
		messages.ReportLogFieldsMessage("Fetching", logging.DebugLevel, dfi.ls, f.Value)
		md, err := dfi.registry.GetImageMetadata(f.Value, "")
		if err != nil {
			messages.ReportLogFieldsMessage("Error fetching", logging.DebugLevel, dfi.ls, f.Value, err)
			if err != nil {
				continue
			}
		}

		dfi.mergeEnv(md.Env)

		buf := bytes.NewBufferString(strings.Join(md.OnBuild, "\n"))
		ast, err := parseDocker(buf)
		messages.ReportLogFieldsMessage("Parsing ONBUILD", logging.DebugLevel, dfi.ls, f.Value)
		if err != nil {
			messages.ReportLogFieldsMessage("Error while parsing ONBUILD", logging.DebugLevel, dfi.ls, f.Value, err)
			return err
		}
		return dfi.absorbDocker(ast)
	}
	return nil
}

func (dfi *dockerfileInspector) mergeEnv(env map[string]string) {
	if dfi.envmap == nil {
		dfi.envmap = map[string]string{}
	}
	for k, v := range env {
		if _, already := dfi.envmap[k]; !already {
			dfi.envmap[k] = v
		}
	}
}

/*
func (dfi *dockerfileInspector) processEnv() error {
	for _, e := range dfi.envs {
		if e.Value == SOUS_RUN_IMAGE_SPEC {
			messages.ReportLogFieldsMessage("RunSpec path found Dockerfile ENV or ONBUILD ENV", logging.DebugLevel, dfi.ls, e.Next.Value)
			dfi.runspecPath = e.Next.Value
		}
	}
	return nil
}
*/

func (dfi *dockerfileInspector) absorbDocker(ast *parser.Node) error {
	// Parse for ENV SOUS_RUN_IMAGE_SPEC
	// Parse for FROM
	envs := []*parser.Node{}
	for _, node := range ast.Children {
		switch node.Value {
		case "env":
			dfi.envs = append(dfi.envs, node.Next)
			envs = append(envs, node.Next)
		case "from":
			dfi.froms = append(dfi.froms, node.Next)
		case "arg":
			pair := strings.SplitN(node.Next.Value, "=", 2)
			switch pair[0] {
			case AppVersionBuildArg:
				dfi.versionArg = true
			case AppRevisionBuildArg:
				dfi.revisionArg = true
			}
		}
	}
	dfi.mergeEnv(envNodesToMap(envs))
	return nil
}

func envNodesToMap(envs []*parser.Node) map[string]string {
	m := map[string]string{}
	for _, e := range envs {
		k := e.Value
		v := e.Next.Value
		m[k] = v
	}
	return m
}

var inspectFormat = `--format={{range .Config.OnBuild}}{{.}}
{{end}}{{range .Config.Env}}ENV {{.}}
{{end}}`

func inspectImage(sh shell.Shell, imageName string) (string, error) {
	cmd := []interface{}{"image", "inspect", inspectFormat, imageName}
	//docker image inspect docker.otenv.com/sous-otj-autobuild:local
	result, err := sh.Cmd("docker", cmd...).SucceedResult()
	if err != nil {
		return "", err
	}
	return result.Stdout.String(), nil
}

func (dfi *dockerfileInspector) envValue(name string) (string, bool) {
	v, t := dfi.envmap[name]
	return v, t
}

var envRE = regexp.MustCompile(`(?i)^env`)

func parseImageOutput(input string) map[string]string {
	envs := make(map[string]string)
	elementSlice := strings.Split(input, "\n")
	for _, env := range elementSlice {
		if !envRE.MatchString(env) {
			continue
		}
		env = envRE.ReplaceAllString(env, "")
		env = strings.Trim(env, "\" ")
		envSplit := strings.Split(env, "=")
		if len(envSplit) == 2 {
			key := envSplit[0]
			val := envSplit[1]
			envs[key] = val
		} else {
			envSplit := strings.Split(env, " ")
			if len(envSplit) == 2 {
				key := envSplit[0]
				val := envSplit[1]
				envs[key] = val
			}
		}
	}
	return envs
}


text:
The material system is built around the [alias/wavefront material](http://paulbourke.net/dataformats/mtl)
format with a few extensions for accessing the advanced rendering features
offered by polaris.

# Supported attributes of the mtl format

When polaris encounters a material without a material expression it will make
a best-effort attempt to construct one by analyzing any present mtl format
attributes. The following attributes of the wavefront material format are recognized
by the material parser:

| Attribute | Description         | Value type | Example                | Notes
|-----------|---------------------|------------|------------------------|------------
| Kd        | Diffuse  color      | Vector     | `Kd 0.9 0.1 0.1`       | Vector components should be in the `[0, 1)` range
| Ks        | Specular color      | Vector     | `Ks 1 1 1`             | Vector components should be in the `[0, 1)` range
| Tf        | Transmittance color | Vector     | `Tf 0.9 0 0`           | Vector components should be in the `[0, 1)` range
| Ke        | Emissive color      | Vector     | `Ke 10 10 10`          | No limit for emissive components
| map\_Kd   | Diffuse  texture    | String     | `map_Kd "foo.jpg"`     |
| map\_Ks   | Specular texture    | String     | `map_Ks "foo.png"`     |
| map\_Tf   | Transmittance texture | String   | `map_Tf "foo.tga"`     |
| map\_Ke   | Emissive texture    | String     | `map_Ke "foo.exr"`     | An exr/hdr file can be used for HDR rendering
| map\_bump | Bumpmap texture     | String     | `map_bump "stones-b.png"`|
| Ni        | Refractive Index    | Scalar     | `Ni 1.53`              |

Polaris uses [OpenImageIO](https://github.com/OpenImageIO/oiio) for loading image
files. This allows the renderer to parse most known image formats including
openEXR and HDR/RGBE for HDR renders.

# Extensions to the mtl format

In addition to the standard mtl attributes described above, polaris also
supports the following attribute extensions:

| Attribute   | Description                                  | Value type | Example                 | Notes
|-------------|----------------------------------------------|------------|-------------------------|------------
| include     | Include properties from an existing material | String     | `include "glass"`       | This attribute can be used to extend an existing material and overwrite one or more of its attributes
| KeScaler    | Scaler value for emissive texture            | Scalar     | `KeScaler 3.0`          | This attribute allows you to specify a 24-bit RGB emissive texture and apply a scaler to its RGB values. It's an alternative way to enable HDR rendering when exr/hdr files cannot be used
| map\_normal | Normal map texture                           | String     | `map_normal "stones-n.png"`|
| mat\_expr   | Define material expression                   | String     | `mat_expr diffuse(reflectance: {0.9, 0.0})` | See [material expressions](#material-expressions) following section for more details

When specifying a path to a texture or other external resource:
- A relative path (to the current file) can be used
- An absolute path can be used
- An http/https URL can be specified to pull the resource from a remote host

# Reserved material names

The scene compiler recognizes two reserved material names that can be defined
to override global scene properties:

- `scene_diffuse_material`: specifies the diffuse material for the scene background.
If defined, this material will be sampled by rays that do not intersect any of the
scene geometry. It can be used to specify a lat/lng skypbox envmap. If not defined,
it defaults to a black diffuse surface.
- `scene_emissive_material`: specifies a global emissive material that simulates
a directional light. By default its not used but it can be specified to enable
a HDR emissive env map.

# Material expressions

Material expressions can be used to specify layered materials, that is, materials
that either use a specific BxDF surface model or combine multiple surface models
using one or more operators.

## Sampling layered materials

Polaris uses a very simple approach to sampling layered materials. When its time
to evaluate a material for a ray intersection it will traverse the layered material
tree applying any operators it encounters till it hits a leaf node which is
then selected as the surface material.

For more info on layered materials and how they are sampled you can skim through
this very interesting [presentation](http://www.slideshare.net/takahiroharada/introduction-to-monte-carlo-ray-tracing-cedec2013)
by Takahiro Harada.

## BxDF models

### diffuse

This model simulates a smooth lambertian surface. This model supports the
following parameters:

| Parameter name | Description   | Type              | Default | Example
|----------------|---------------|-------------------|---------|-----------
| reflectance    | diffuse value | Vector OR texture | {0.2,0.2,0.2} | `reflectance: {0.9,0,0}` `reflectance: "stones-d.jpg"`

Examples:

| Expression                                                              | Output
|-------------------------------------------------------------------------|----------------
| `diffuse(reflectance: {0.999, 0, 0})`                                   | ![diffuse red material](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBNXR2RV9SN19vd0U)
| `diffuse(reflectance: "stones-d.png")`                                  | ![diffuse textured material](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBd2NONDl2UWp5RGM)

### conductor

This model simulates a smooth conductor. This model supports the following parameters:

| Parameter name | Description    | Type                | Default | Example
|----------------|----------------|---------------------|---------| ------------
| specularity    | specular value | Vector OR texture   | {1,1,1} | `specularity: {0.9,0,0}` `specularity: "stones-s.jpg"`
| intIOR         | internal IOR   | Scalar OR mat. name | "glass" | `intIOR: 1.345` `intIOR: "diamond"`
| extIOR         | external IOR   | Scalar OR mat. name | "air"   | `extIOR: 1` `extIOR: "air"`

Examples:

| Expression                                                               | Output
|--------------------------------------------------------------------------|----------------
|`conductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336})`             | ![gold conductor](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBVVdwUkVFTlhtUzA)
|`conductor(intIOR: "silver", specularity: {0.971519, 0.959915, 0.91532})` | ![silver conductor](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBSjBNdnBhS0ppOFk)
|`conductor(specularity: "checkerboard-bw.jpg")`                           | ![using a texture to modulate specularity](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBTHRjM1ljUWxieWM )

### dielectric

This model simulates an ideal dielectric material where the fresnel factor is
used to select whether a ray will get reflected or refracted. When rendering
complex geometry using dielectrics it is advised to increase the number of
ray bounces. This model supports the following parameters:

| Parameter name | Description    | Type                | Default | Example
|----------------|----------------|---------------------|---------| ------------
| specularity    | specular value | Vector OR texture   | {1,1,1} | `specularity: {0.9,0,0}` `specularity: "stones-s.jpg"`
| transmittance  | transmittance  | Vector OR texture   | {1,1,1} | `transmittance: {0.9,0,0}` `transmittance: "logo-t.jpg"`
| intIOR         | internal IOR   | Scalar OR mat. name | "glass" | `intIOR: 1.345` `intIOR: "diamond"`
| extIOR         | external IOR   | Scalar OR mat. name | "air"   | `extIOR: 1` `extIOR: "air"`

Examples:

| Expression                                                               | Output
|--------------------------------------------------------------------------|----------------
|`dielectric(intIOR: "glass")`                                             | ![smooth glass dielectric](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBZ1BreW5jc0FYUDA)
|`dielectric(intIOR: "glass", specularity: {0.04, 0.04, 0.04}, transmittance: {0.5, 0, 0.9})`  | ![smooth tinted glass](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBcGZXUW9HWmd0eWM)
|`dielectric(intIOR: "glass", specularity: "checkerboard-blue.jpg")`       | ![smooth glass dielectric with specularity texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBekE1RUJjcmVOVDg)
|`dielectric(intIOR: "glass", transmittance: "checkerboard-blue.jpg")`     | ![smooth glass dielectric with transmittance texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBR2NfTE13R2ZWVkk)

### roughConductor

This model simulates a rough conductor. It uses the BRDF formula described in
[microfacet models for refraction through rough surfaces](https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf).
This model supports the following parameters:

| Parameter name | Description    | Type                | Default | Example
|----------------|----------------|---------------------|---------| ------------
| specularity    | specular value | Vector OR texture   | {1,1,1} | `specularity: {0.9,0,0}` `specularity: "stones-s.jpg"`
| intIOR         | internal IOR   | Scalar OR mat. name | "glass" | `intIOR: 1.345` `intIOR: "diamond"`
| extIOR         | external IOR   | Scalar OR mat. name | "air"   | `extIOR: 1` `extIOR: "air"`
| roughness      | roughness factor| Scalar OR texture  | 0.1     | `roughness: 0.5` `roughness: "stones-r.jpg"

The following examples illustrate how the same material looks with different roughness values:

| Expression                                                                       | Output
|----------------------------------------------------------------------------------|----------------
|`roughConductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336}, roughness:0.1)` | ![rough conductor k=0.1](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBcVQwYzIwSjJQMVU)
|`roughConductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336}, roughness:0.25)`| ![rough conductor k=0.25](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBSUhscnhQSWJmdTA)
|`roughConductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336}, roughness:0.5)` | ![rough conductor k=0.5](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBclJFSFFKcjZ6YVk)
|`roughConductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336}, roughness:0.75)`| ![rough conductor k=0.75](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBckNmNHZjSzd4U1k)

### roughDielectric

This model simulates a rough dielectric material. It uses the BRDF and BTDF
formulas described in [microfacet models for refraction through rough surfaces](https://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf)
as well as the fresnel factor to select between ray reflection and refraction.

This model supports the following parameters:

| Parameter name | Description    | Type                | Default | Example
|----------------|----------------|---------------------|---------| ------------
| specularity    | specular value | Vector OR texture   | {1,1,1} | `specularity: {0.9,0,0}` `specularity: "stones-s.jpg"`
| transmittance  | transmittance  | Vector OR texture   | {1,1,1} | `transmittance: {0.9,0,0}` `transmittance: "logo-t.jpg"`
| intIOR         | internal IOR   | Scalar OR mat. name | "glass" | `intIOR: 1.345` `intIOR: "diamond"`
| extIOR         | external IOR   | Scalar OR mat. name | "air"   | `extIOR: 1` `extIOR: "air"`
| roughness      | roughness factor| Scalar OR texture  | 0.1     | `roughness: 0.5` `roughness: "stones-r.jpg"`

| Expression                                                                       | Output
|----------------------------------------------------------------------------------|----------------
|`roughDielectric(intIOR: "glass", specularity: {0.9, 0.9, 0.9}, roughness: 0.2)`  | ![rough dielectric k=0.2](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBUHdSbTNOaFcydEU)
|`roughDielectric(intIOR: "glass", roughness: "earth-r.jpg")`                      | ![rough dielectric with roughness texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBZ2libi0xZXNmdnc)

## emissive

This model describes a surface that emits light. It supports the following parameters:

| Parameter name | Description            | Type                | Default | Example
|----------------|------------------------|---------------------|---------| ------------
| radiance       | emitted radiance value | Vector OR texture   | {1,1,1} | `radiance: {5,5,5}` `radiance: "spot.jpg"`

## Operators

Operators are special functions that either modify or combine their operands.
Their operands are either another nested operator or a bxdf surface definition.
In addition, expression operands may also reference other materials **by name**.
For example:

```mtl
newmtl gold
  mat_expr conductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336})

newmtl silver
  mat_expr conductor(intIOR: "silver", specularity: {0.971519, 0.959915, 0.915324})

newmtl weird
  mat_expr mixMap("gold", "silver", "checkerboard-bw.jpg")
```

### mix

The mix operator accepts two expression operands `A` and `B` and a weight `W` in the `[0,1]`
range.

When sampling this operator, a random value is used to select either
`A` or `B` based on the weights (`A` chosen with probablity `W` and `B` chosen
with probability `1-W`).

Examples:

| Example                                                                          | Output
|----------------------------------------------------------------------------------|------------
| `mix(diffuse(reflectance: {0.999,0,0}), diffuse(reflectance: {0,0,0.999}), 0.5)` | ![mix two diffuse colors](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBZ0RPZ1lXbVdpemM)
| `mix(diffuse(reflectance: "stones-d.jpg"), conductor(intIOR: "silver", specularity: {0.971519, 0.959915, 0.91532}), 0.6)` | ![mix a diffuse texture with a conductor for a polished surface](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBWG5mQ3EzOWZORGc)

### mixMap

The mix operator accepts two expression operands `A` and `B` and a single channel texture
containing a per-pixel sampling weight.

When sampling this operator, the weight `W` is sampled from the weight texture
using the UV coordinates of the surface intersection and a random value is used
to select either `A` or `B` based on the weights (`A` chosen with probablity
`W` and `B` chosen with probability `1-W`).

Examples:

| Example                         | Output     |
|---------------------------------|------------
| `mix(conductor(intIOR: "gold", specularity: {1.0, 0.766, 0.336)), conductor(intIOR: "silver", specularity: {0.971519, 0.959915, 0.91532}), 0.6), "checkerboard-bw.jpg")`| ![mix two materials using a checkerboard texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBWGFwYl9vcGtxbEU)

### bumpMap

This is a pass-through operator that modifies the normal of the surface intersection
point using an image. It accepts an expression operand and a texture argument.

Bump maps are single-channel grayscale images and polaris needs to reconstruct
the bi-tangent vectors from by fetching 3 samples from the bumpmap texture. It
is usually faster to use a [normal map](#normalmap) instead.

| Example                                                         | Bump map | Output
|-----------------------------------------------------------------|----------|------------
| `bumpMap(diffuse(reflectance: "stones-d.png"), "stones-b.png")` | ![bump map texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBa1FJVVVxaV9TZ3c) | ![with bumpMap operator](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBNkgxQVpPRVVMWFU)

### normalMap

This is a pass-through operator that modifies the normal of the surface intersection
point using an image. It accepts an expression operand and a texture argument.

Normal maps are RGB images where each component specifies an offset for the X, Y and
~ coordinates. This operator achieves the same result as the [bumpMap](#bumpmap)
operator but it is a bit faster to evaluate.

| Example                                                           | Normal map | Output
|-------------------------------------------------------------------|------------|----------
| `normalMap(diffuse(reflectance: "stones-n.png"), "stones-b.png")` | ![normal map texture](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBTlhFdWVxM2kyOUk) | ![with normalMap operator](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBaUJTYV9NcHlUU0E)

### disperse
The disperse operator is used to simulate [light dispersion](https://en.wikipedia.org/wiki/Dispersion_(optics))
inside dielectric materials where essentially, rays exhibit a slightly different
IOR based on their wavelength.

This operator accepts an expression operand and two vectors (one for the internal
and one for the external IOR) with IOR values for the R, G and B channels. Unless
rendering a scene where light passes through dielectric materials (eg. glass filled with water),
the extIOR vector can be set to `{0,0,0}` which effectively makes polaris ignore it
and just use whatever value the leaf node defines for extIOR.

A correct approximation of dispersion would require a tracer capable of performing
spectral rendering. Polaris simulates dispersion using different IORs for the R, G and B
channels.

Whenever the dispersion operator is evaluated, we first check the path flags to
detect whether some ray has undergone dispersion somewhere along the path. If
this is the first time that the path will get dispersed then we randomly select
a channel, update the path flags to reflect the selected channel and force the
appropriate int/ext IORs to the leaf node. If we detect a prior dispersion event,
we lookup the path flags to select the appropriate int/ext IOR values based on
the previously selected channel.

In both cases, the disperse operator will setup a tint value to act as a color
filter for the selected R, G or B channel. Due to the way that polaris approximates
dispersion, the sample count needs to be effectively tripled to get a correct
image.

| Example                                                           | Output     |
|-------------------------------------------------------------------|------------
| `disperse(dielectric(intIOR: "diamond"), intIOR: {2.40,2.43,2.46}, extIOR: {0,0,0})` |  ![simulated diamond "fire"](https://drive.google.com/uc?export=download&id=0Bz9Vk3E_v2HBdjZScnNsNTJvVU0)

## Reference

### Example specularity values

The following tables (obtained [here](https://seblagarde.wordpress.com/2011/08/17/feeding-a-physical-based-lighting-mode/)) contain a list of specularity
values for dielectrics and common metals. It is important to note that dielectrics
have monochromatic specularity values whereas metals have RGB specularity values.

| Dielectric | Specularity
|------------|-------------
| Quartz     | {0.045593921, 0.045593921, 0.045593921}
| Ice        | {0.017908907, 0.017908907, 0.017908907}
| Water      | {0.020373188, 0.020373188, 0.020373188}
| Alcohol    | {0.01995505, 0.01995505, 0.01995505}
| Glass      | {0.04, 0.04, 0.04}
| Milk       | {0.022181983, 0.022181983, 0.022181983}
| Ruby       | {0.077271957, 0.077271957, 0.077271957}
| Crystal    | {0.111111111, 0.111111111, 0.111111111}
| Diamond    | {0.171968833, 0.171968833, 0.171968833}
| Skin       | {0.028, 0.028, 0.028}

| Metal     |  Specularity
|-----------|---------------------------------
| Silver    |  { 0.971519, 0.959915, 0.915324}
| Aluminium |  { 0.913183, 0.921494, 0.924524}
| Gold      |  { 1, 0.765557, 0.336057}
| Copper    |  { 0.955008, 0.637427, 0.538163}
| Chromium  |  { 0.549585, 0.556114, 0.554256}
| Nickel    |  { 0.659777, 0.608679, 0.525649}
| Titanium  |  { 0.541931, 0.496791, 0.449419}
| Cobalt    |  { 0.662124, 0.654864, 0.633732}
| Platinum  |  { 0.672411, 0.637331, 0.585456}

### Built-in IORs for known materials

The following table summarizes the list of built-in IOR values that can be
referenced **by name** for BxDF models that require an IOR value.

Note that material names are case-insensitive. Here is an example how to
reference material IORs by name:

```mtl
dielectric(intIOR: "glass", extIOR: "air")
```

| Material name            | IOR |
|--------------------------|---------------
| Acetone                | 1.36
| Actinolite             | 1.618
| Agalmatoite            | 1.550
| Agate                  | 1.544
| Agate, Moss            | 1.540
| Air                    | 1.0002926
| Alcohol                | 1.329
| Alexandrite            | 1.745
| Aluminum               | 1.44
| Amber                  | 1.546
| Amblygonite            | 1.611
| Amethyst               | 1.544
| Anatase                | 2.490
| Andalusite             | 1.641
| Anhydrite              | 1.571
| Apatite                | 1.632
| Apophyllite            | 1.536
| Aquamarine             | 1.577
| Aragonite              | 1.530
| Argon                  | 1.000281
| Asphalt                | 1.635
| Augelite               | 1.574
| Axinite                | 1.675
| Azurite                | 1.730
| Barite                 | 1.636
| Barytocalcite          | 1.684
| Benitoite              | 1.757
| Benzene                | 1.501
| Beryl                  | 1.577
| Beryllonite            | 1.553
| Brazilianite           | 1.603
| Bromine (liq)          | 1.661
| Bronze                 | 1.18
| Brownite               | 1.567
| Calcite                | 1.486
| Calspar                | 1.486
| Cancrinite             | 1.491
| Carbon Dioxide (gas)   | 1.000449
| Carbon Disulfide       | 1.628
| Carbon Tetrachloride   | 1.460
| Cassiterite            | 1.997
| Celestite              | 1.622
| Cerussite              | 1.804
| Ceylanite              | 1.770
| Chalcedony             | 1.530
| Chalk                  | 1.510
| Chalybite              | 1.630
| Chrome Green           | 2.4
| Chrome Red             | 2.42
| Chrome Yellow          | 2.31
| Chromium               | 2.97
| Chrysoberyl            | 1.745
| Chrysocolla            | 1.500
| Chrysoprase            | 1.534
| Citrine                | 1.550
| Clinozoisite           | 1.724
| Cobalt Blue            | 1.74
| Cobalt Green           | 1.97
| Cobalt Violet          | 1.71
| Colemanite             | 1.586
| Copper                 | 1.10
| Copper Oxide           | 2.705
| Coral                  | 1.486
| Cordierite             | 1.540
| Corundum               | 1.766
| Crocoite               | 2.310
| Crystal                | 2.00
| Cuprite                | 2.850
| Danburite              | 1.633
| Diamond                | 2.417
| Diopside               | 1.680
| Dolomite               | 1.503
| Dumortierite           | 1.686
| Ebonite                | 1.66
| Ekanite                | 1.600
| Elaeolite              | 1.532
| Emerald                | 1.576
| Emerald, Synth flux    | 1.561
| Emerald, Synth hydro   | 1.568
| Enstatite              | 1.663
| Epidote                | 1.733
| Ethanol                | 1.36
| Ethyl Alcohol          | 1.36
| Euclase                | 1.652
| Fabulite               | 2.409
| Feldspar, Adventurine  | 1.532
| Feldspar, Albite       | 1.525
| Feldspar, Amazonite    | 1.525
| Feldspar, Labradorite  | 1.565
| Feldspar, Microcline   | 1.525
| Feldspar, Oligoclase   | 1.539
| Feldspar, Orthoclase   | 1.525
| Fluoride               | 1.56
| Fluorite               | 1.434
| Formica                | 1.47
| Garnet, Almandine      | 1.760
| Garnet, Almandite      | 1.790
| Garnet, Andradite      | 1.820
| Garnet, Demantoid      | 1.880
| Garnet, Grossular      | 1.738
| Garnet, Hessonite      | 1.745
| Garnet, Rhodolite      | 1.760
| Garnet, Spessartite    | 1.810
| Gaylussite             | 1.517
| Glass                  | 1.51714
| Glass, Albite          | 1.4890
| Glass, Crown           | 1.520
| Glass, Crown, Zinc     | 1.517
| Glass, Flint, Dense    | 1.66
| Glass, Flint, Heaviest | 1.89
| Glass, Flint, Heavy    | 1.65548
| Glass, Flint, Lanthanum| 1.80
| Glass, Flint, Light    | 1.58038
| Glass, Flint, Medium   | 1.62725
| Glycerine              | 1.473
| Gold                   | 0.47
| Hambergite             | 1.559
| Hauynite               | 1.502
| Helium                 | 1.000036
| Hematite               | 2.940
| Hemimorphite           | 1.614
| Hiddenite              | 1.655
| Howlite                | 1.586
| Hypersthene            | 1.670
| Ice                    | 1.309
| Idocrase               | 1.713
| Iodine Crystal         | 3.34
| Iolite                 | 1.548
| Iron                   | 1.51
| Ivory                  | 1.540
| Jade, Nephrite         | 1.610
| Jadeite                | 1.665
| Jasper                 | 1.540
| Jet                    | 1.660
| Kornerupine            | 1.665
| Kunzite                | 1.655
| Kyanite                | 1.715
| Lapis Gem              | 1.500
| Lapis Lazuli           | 1.61
| Lazulite               | 1.615
| Lead                   | 2.01
| Leucite                | 1.509
| Magnesite              | 1.515
| Malachite              | 1.655
| Meerschaum             | 1.530
| Mercury (liq)          | 1.62
| Methanol               | 1.329
| Moldavite              | 1.500
| Moonstone, Adularia    | 1.525
| Moonstone, Albite      | 1.535
| Natrolite              | 1.480
| Nephrite               | 1.600
| Nitrogen (gas)         | 1.000297
| Nitrogen (liq)         | 1.2053
| Nylon                  | 1.53
| Obsidian               | 1.489
| Olivine                | 1.670
| Onyx                   | 1.486
| Opal                   | 1.450
| Oxygen (gas)           | 1.000276
| Oxygen (liq)           | 1.221
| Painite                | 1.787
| Pearl                  | 1.530
| Periclase              | 1.740
| Peridot                | 1.654
| Peristerite            | 1.525
| Petalite               | 1.502
| Phenakite              | 1.650
| Phosgenite             | 2.117
| Plastic                | 1.460
| Plexiglas              | 1.50
| Polystyrene            | 1.55
| Prase                  | 1.540
| Prasiolite             | 1.540
| Prehnite               | 1.610
| Proustite              | 2.790
| Purpurite              | 1.840
| Pyrite                 | 1.810
| Pyrope                 | 1.740
| Quartz                 | 1.544
| Quartz, Fused          | 1.45843
| Rhodizite              | 1.690
| Rhodochrisite          | 1.600
| Rhodonite              | 1.735
| Rock Salt              | 1.544
| Rubber, Natural        | 1.5191
| Ruby                   | 1.760
| Rutile                 | 2.62
| Sanidine               | 1.522
| Sapphire               | 1.760
| Scapolite              | 1.540
| Scapolite, Yellow      | 1.555
| Scheelite              | 1.920
| Selenium, Amorphous    | 2.92
| Serpentine             | 1.560
| Shell                  | 1.530
| Silicon                | 4.24
| Sillimanite            | 1.658
| Silver                 | 0.18
| Sinhalite              | 1.699
| Smaragdite             | 1.608
| Smithsonite            | 1.621
| Sodalite               | 1.483
| Sodium Chloride        | 1.544
| Sphalerite             | 2.368
| Sphene                 | 1.885
| Spinel                 | 1.712
| Spodumene              | 1.650
| Staurolite             | 1.739
| Steatite               | 1.539
| Steel                  | 2.50
| Stichtite              | 1.520
| Strontium Titanate     | 2.410
| Styrofoam              | 1.595
| Sulphur                | 1.960
| Synthetic Spinel       | 1.730
| Taaffeite              | 1.720
| Tantalite              | 2.240
| Tanzanite              | 1.691
| Teflon                 | 1.35
| Thomsonite             | 1.530
| Tiger eye              | 1.544
| Topaz                  | 1.620
| Topaz, Blue            | 1.610
| Topaz, Pink            | 1.620
| Topaz, White           | 1.630
| Topaz, Yellow          | 1.620
| Tourmaline             | 1.624
| Tremolite              | 1.600
| Tugtupite              | 1.496
| Turpentine             | 1.472
| Turquoise              | 1.610
| Ulexite                | 1.490
| Uvarovite              | 1.870
| Variscite              | 1.550
| Vivianite              | 1.580
| Wardite                | 1.590
| Water                  | 1.33157
| Willemite              | 1.690
| Witherite              | 1.532
| Wulfenite              | 2.300
| Zincite                | 2.010
| Zircon, High           | 1.960
| Zircon, Low            | 1.800
| Zirconia, Cubic        | 2.170

# Acknowledgments

The mitsuba model used in the example renderings was obtained from [McGuire2011](http://graphics.cs.williams.edu/data/meshes.xml).


text:
package com.yzong.dsf14.RMIFramework.infra;

import java.io.Serializable;

/**
 * This class holds the Remote Object Reference, which contains the hostname and port number for the
 * RMI Service Host. It also contains Object Key and Remote Interface Name.
 *
 * @author Jimmy Zong <yzong@cmu.edu>
 *
 */
public class RemoteObjectRef implements Serializable {

  private static final long serialVersionUID = -5251266551341123093L;
  private String HostName;
  private int Port;
  private long ObjKey;
  private String RemoteInterfaceName;

  public String getHostName() {
    return HostName;
  }

  public int getPort() {
    return Port;
  }

  public long getObjKey() {
    return ObjKey;
  }

  public String getRemoteInterfaceName() {
    return RemoteInterfaceName;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((HostName == null) ? 0 : HostName.hashCode());
    result = prime * result + (int) (ObjKey ^ (ObjKey >>> 32));
    result = prime * result + Port;
    result = prime * result + ((RemoteInterfaceName == null) ? 0 : RemoteInterfaceName.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    RemoteObjectRef other = (RemoteObjectRef) obj;
    if (HostName == null) {
      if (other.HostName != null)
        return false;
    } else if (!HostName.equals(other.HostName))
      return false;
    if (ObjKey != other.ObjKey)
      return false;
    if (Port != other.Port)
      return false;
    if (RemoteInterfaceName == null) {
      if (other.RemoteInterfaceName != null)
        return false;
    } else if (!RemoteInterfaceName.equals(other.RemoteInterfaceName))
      return false;
    return true;
  }

  public RemoteObjectRef(String host, int port, long objHash, String riName) {
    this.HostName = host;
    this.Port = port;
    this.ObjKey = objHash;
    this.RemoteInterfaceName = riName;
  }

  /**
   * Generates a RMI Stub Object from a Remote Object Reference. Intended to be used by the client.
   *
   * @return RMI Stub Object corresponding to the Remote Object Reference.
   */
  public Object localize() {
    Class<?> rmiStub;
    try {
      rmiStub = (Class<?>) Class.forName(RemoteInterfaceName + "_stub");
      RMIRemoteStub obj = (RMIRemoteStub) rmiStub.newInstance();
      obj.setSelfRoR(this);
      return obj;
    } catch (Exception e) {
      /* If any error occurs, return null. */
      return null;
    }
  }

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<widget xmlns="http://www.w3.org/ns/widgets" width="400" height="300" id="test-case:tc-extensions-share-cookies-016">
    <name>tc-extensions-share-cookies-016</name>
    <access origin="http://localhost" subdomains="true" />
	<!-- two domains -->
	<access origin="http://testsuites.oslo.osa"/>
	<access origin="http://www.testsuites.oslo.opera.com"/>
    <content src="index.html" />
	<feature name="opera:share-cookies" required="true" />
</widget>


text:
using System;
using System.Globalization;

namespace Paragon.Container.Core
{
    internal static class LocaleInformation
    {
        public static string GetLocale()
        {
            string letter = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var test = CultureInfo.CurrentCulture;
            switch (letter)
            {
                case "tr":
                    return "Turkish";
                case "de":
                    return "German";

                case "fr":
                    return "French";

                case "es":
                    return "Spanish";

                case "it":
                    return "Italian";

                case "ru":
                    return "Russian";

                default:
                    return "English";
            }
        }
    }
}


text:
@interface ViewController ()

@end

@implementation ViewController

NSString *rawResponse;

- (void)viewDidLoad
{
    [super viewDidLoad];

    _client = [[Client alloc] init];

    rawResponse = [[_client postBook] description];

    if ([rawResponse isEqual:@"false"]){
        _textView.text = @"Could not create the book.\n\nDid you enter your orgName (username) correctly on line 30 of Client.m?";
    } else {
        _textView.text = [@"Success! Here is the the object we stored; notice the timestamps and unique id we created for you\n\n" stringByAppendingString:rawResponse];
    }
}

@end


text:
* Do not prescribe string

## 0.0.1
* Initial release


text:
using System;

namespace Nest
{
	public interface IReindexRequest
	{
		IndexName To { get; set; }
		IndexName From { get; set; }
		Types Type { get; set; }
		Time Scroll { get; set; }
		int? Size { get; set; }

		QueryContainer Query { get; set; }

		ICreateIndexRequest CreateIndexRequest { get; set; }

		IPutMappingRequest PutMappingRequest { get; set; }
	}

	public class ReindexRequest : IReindexRequest
	{
		public IndexName To { get; set; }
		public IndexName From { get; set; }
		public Types Type { get; set; }
		public Time Scroll { get; set; }
		public int? Size { get; set; }
		public QueryContainer Query { get; set; }
		public ICreateIndexRequest CreateIndexRequest { get; set; }
		public IPutMappingRequest PutMappingRequest { get; set; }
		public ReindexRequest(IndexName from, IndexName to, Types type)
		{
			this.To = to;
			this.From = from;
			this.Type = type;
		}
	}

	public class ReindexDescriptor<T> : DescriptorBase<ReindexDescriptor<T>, IReindexRequest>, IReindexRequest where T : class
	{
		IndexName IReindexRequest.To { get; set; }
		IndexName IReindexRequest.From { get; set; }
		Types IReindexRequest.Type { get; set; }
		Time IReindexRequest.Scroll { get; set; }
		int? IReindexRequest.Size { get; set; }
		QueryContainer IReindexRequest.Query { get; set; }
		ICreateIndexRequest IReindexRequest.CreateIndexRequest { get; set; }
		IPutMappingRequest IReindexRequest.PutMappingRequest { get; set; }

		public ReindexDescriptor(IndexName from, IndexName to)
		{
			Assign(a => a.From = from)
			.Assign(a => a.To = to)
			.Assign(a => a.Type = typeof(T));
		}

		/// <summary>
		/// A search request can be scrolled by specifying the scroll parameter. The scroll parameter is a time value parameter (for example: scroll=5m), indicating for how long the nodes that participate in the search will maintain relevant resources in order to continue and support it. This is very similar in its idea to opening a cursor against a database.
		/// </summary>
		/// <param name="scrollTime">The scroll parameter is a time value parameter (for example: scroll=5m)</param>
		/// <returns></returns>
		public ReindexDescriptor<T> Scroll(Time scrollTime) => Assign(a => a.Scroll = scrollTime);

		/// <summary>
		/// The number of hits to return. Defaults to 100. When using scroll search type,
		/// size is actually multiplied by the number of shards!
		/// </summary>
		public ReindexDescriptor<T> Size(int? size) => Assign(a => a.Size = size);

		/// <summary>
		/// The number of hits to return. Defaults to 100.
		/// </summary>
		public ReindexDescriptor<T> Take(int? take) => Assign(a => a.Size = take);

		/// <summary>
		/// A query to optionally limit the documents to use for the reindex operation.
		/// </summary>
		public ReindexDescriptor<T> Query(Func<QueryContainerDescriptor<T>, QueryContainer> querySelector) =>
			Assign(a => a.Query = querySelector?.Invoke(new QueryContainerDescriptor<T>()));

		/// <summary>
		/// A query to optionally limit the documents to use for the reindex operation.
		/// </summary>
		public ReindexDescriptor<T> Query(QueryContainer query) => Assign(a => a.Query = query);

		/// <summary>
		/// Specify the document types to reindex. By default, will be <typeparamref name="T"/>
		/// </summary>
		public ReindexDescriptor<T> Type(Types type) => Assign(a => a.Type = type);

		/// <summary>
		/// Reindex all document types.
		/// </summary>
		public ReindexDescriptor<T> AllTypes() => this.Type(Types.AllTypes);

		/// <summary>
		/// CreateIndex selector if not explicitly specified will reuse settings from the originating index
		/// </summary>
		public ReindexDescriptor<T> CreateIndex(Func<CreateIndexDescriptor, ICreateIndexRequest> createIndexSelector) =>
			Assign(a => a.CreateIndexRequest = createIndexSelector.InvokeOrDefault(new CreateIndexDescriptor(a.From)));
	}
}


text:
title: OnMouseOut
page_title: OnMouseOut - RadTextBox
description: Check our Web Forms article about OnMouseOut.
slug: radtextbox/client-side-programming/events/onmouseout
tags: onmouseout
published: True
position: 11
---

# OnMouseOut

The **OnMouseOut** client-side event handler is called when the mouse moves off the input area of the control.

>note The **OnMouseOut** event is supported by all **RadInput** controls.
>

Two parameters are passed to the event handler:

* **sender** is the input control.

* **eventArgs** is an instance of [Sys.EventArgs](https://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys/EventArgsClass/default.aspx).

The following example uses the **OnMouseOut** event to display an alert:

````ASPNET
<telerik:RadTextBox RenderMode="Lightweight" ID="RadTextBox1" runat="server">
	<ClientEvents OnMouseOut="MouseOut" />
</telerik:RadTextBox>
````

````JavaScript
<script type="text/javascript">
	function MouseOut(sender, eventArgs)
	{
		alert(sender.get_id());
	}
</script>
````

# See Also

 * [OnMouseOver]({%slug radtextbox/client-side-programming/events/onmouseover%})


text:
from muntjac.test.server.component.abstract_listener_methods_test import \
    AbstractListenerMethodsTest

from muntjac.ui.tab_sheet import \
    TabSheet, SelectedTabChangeEvent, ISelectedTabChangeListener

class TabSheetListeners(AbstractListenerMethodsTest):

    def testSelectedTabChangeListenerAddGetRemove(self):
        self._testListenerAddGetRemove(TabSheet, SelectedTabChangeEvent,
                ISelectedTabChangeListener)


text:
//
//  BMAppDelegate.m
//  BMCommons
//
//  Created by Werner Altewischer on 21/02/12.
//  Copyright (c) 2012 BehindMedia. All rights reserved.
//

#import <BMCommons/BMAppDelegate.h>
#import <BMCommons/BMUICore.h>
#import <BMCommons/BMServiceManager.h>

@interface BMAppDelegate(Private)

- (void)showAlertForService:(id <BMService>)service withError:(NSError *)error;
- (void)pushForegroundService:(id <BMService>)service;
- (void)popForegroundService:(id <BMService>)service;
- (void)pushService:(id <BMService>)service;
- (void)popService:(id <BMService>)service;

@end

@implementation BMAppDelegate {
    UIWindow *_window;
	BMApplicationContext *_applicationContext;
    NSMutableDictionary *_activeForegroundServices;
    NSInteger _serviceCount;
}

@synthesize window = _window, applicationContext = _applicationContext;

#pragma mark -
#pragma mark Initialization and deallocation

+ (BMAppDelegate *)instance {
	return (BMAppDelegate *)[UIApplication sharedApplication].delegate;
}

- (id)init {
	if ((self = [super init])) {
        _activeForegroundServices = [NSMutableDictionary new];
        _applicationContext = (BMApplicationContext *)[[self applicationContextClass] sharedInstance];
	}
	return self;
}

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [BMBusyView setDefaultInitBlock:^(BMBusyView *bv) {
        [self initBusyView:bv];
        bv.delegate = self;
    }];

    [[BMServiceManager sharedInstance] addServiceDelegate:self];

    // Override point for customization after application launch.
	[_applicationContext initialize];

    return YES;
}

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

	[_applicationContext deactivate];
}

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

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

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

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
	[_applicationContext terminate];
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    [_applicationContext clearCaches];
}

- (UIViewController *)rootViewController {
    return nil;
}

#pragma mark - Protected methods

- (void)shakeDetected {

}

- (Class)applicationContextClass {
    return [BMApplicationContext class];
}

- (void)initBusyView:(BMBusyView *)theBusyView {

}

#pragma mark -
#pragma mark BMServiceDelegate implementation

- (void)serviceDidStart:(id <BMService>)service {
    //Push the service on the stack: will show busy view
    [self pushService:service];
}

/**
 * Implement to act on successful completion of a service.
 */
- (void)service:(id <BMService>)service succeededWithResult:(id)result {
    //Pop the service from the stack
    [self popService:service];
}

- (void)service:(id <BMService>)service updatedProgress:(double)progressPercentage withMessage:(NSString *)message {
    if (!service.isBackgroundService) {
        //Update the busy view progress and message
        [self updateBusyViewWithMessage:message andProgress:progressPercentage];
    }
}

/**
 * Implement to act on failure of a service.
 */
- (void)service:(id <BMService>)service failedWithError:(NSError *)error {
    [self popService:service];

    //Show an error alert in a generic way
    [self showAlertForService:service withError:error];
}

- (void)serviceWasCancelled:(id <BMService>)service {
    [self popService:service];
}

- (void)serviceWasSentToBackground:(id<BMService>)service {
    [self popForegroundService:service];
}

#pragma mark -
#pragma mark BMBusyViewDelegate

//The code below ties the busyview actions to the service manager, such as cancellation, send to background, etc.

- (void)busyViewWasCancelled:(BMBusyView *)theBusyView {
    //Handle cancellation of services in one place
    theBusyView.label.text = BMLocalizedString(@"busyview.title.cancelling", @"Cancelling...");
    for (NSString *identifier in [NSArray arrayWithArray:[_activeForegroundServices allKeys]]) {
        BOOL isCancellable = [_activeForegroundServices[identifier] boolValue];
        //Cancel the service if allowed
        if (isCancellable) {
            [[BMServiceManager sharedInstance] cancelServiceWithInstanceIdentifier:identifier];
        }
    }
}

- (void)busyViewWasSentToBackground:(BMBusyView *)theBusyView {
    //Handle sending to background
    theBusyView.label.text = BMLocalizedString(@"busyview.title.sendingtobackground", @"Sending to background...");
    for (NSString *identifier in [NSArray arrayWithArray:[_activeForegroundServices allKeys]]) {
        [[BMServiceManager sharedInstance] sendServiceToBackgroundWithInstanceIdentifier:identifier];
    }
}

#pragma mark - Protected methods

- (void)showError:(NSError *)error forService:(id <BMService>)service {

}

- (void)updateBusyViewWithMessage:(NSString *)message andProgress:(CGFloat)progressPercentage {
    [BMBusyView showBusyViewWithMessage:message andProgress:progressPercentage];
}

- (void)showBusyViewWithCancelEnabled:(BOOL)cancelEnabled backgroundEnabled:(BOOL)backgroundEnabled {
    //Configure the busy view
    BMBusyView *bv = [BMBusyView sharedBusyView];
    if (!bv) {
        bv = [BMBusyView showBusyViewAnimated:YES cancelEnabled:cancelEnabled];
    }
    bv.sendToBackgroundEnabled = backgroundEnabled;
    bv.cancelEnabled = cancelEnabled;
    bv.delegate = self;
}

- (void)hideBusyView {
    [BMBusyView hideBusyView];
}

@end

@implementation BMAppDelegate(Private)

- (void)showAlertForService:(id <BMService>)service withError:(NSError *)error {
    //Show alert on error
    //LogWarn is defined in BMLogging.h
    LogWarn(@"Service: %@ failed with error: %@", service, error);
    if (!service.isBackgroundService && !service.isErrorHandled) {
        //NSLocalizedString is redefined in BMLocalization such that the second parameter is the default value
        [self showError:error forService:service];
    }
}

- (void)pushForegroundService:(id <BMService>)service {
    //Keep track of whether cancel button should be enabled or not. Only for services that are cancellable by the user
    _activeForegroundServices[service.instanceIdentifier] = @(service.isUserCancellable);
    BOOL cancelEnabled = YES;
    for (id key in _activeForegroundServices) {
        NSNumber *n = _activeForegroundServices[key];
        cancelEnabled = cancelEnabled && [n boolValue];
    }

    [self showBusyViewWithCancelEnabled:cancelEnabled backgroundEnabled:service.isSendToBackgroundSupported];

    //Disable the idle timer of the app, thereby preventing it to go on standby
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}

- (void)popForegroundService:(id <BMService>)service {
    //Pop the foreground service
    [_activeForegroundServices removeObjectForKey:service.instanceIdentifier];
    if (_activeForegroundServices.count == 0) {
        //If no active foreground services are present anymore: hide the busy view
        [self hideBusyView];
        [UIApplication sharedApplication].idleTimerDisabled = NO;
    }
}

- (void)pushService:(id <BMService>)service {
    if (!service.isBackgroundService) {
        [self pushForegroundService:service];
    }
    _serviceCount++;
}

- (void)popService:(id <BMService>)service {
    if (service) {
        if (!service.isBackgroundService) {
            [self popForegroundService:service];
        }
        _serviceCount--;
    }
}

@end


text:
#include "config.h"
#include "CachedImage.h"

#include "BitmapImage.h"
#include "CachedImageClient.h"
#include "CachedResourceClient.h"
#include "CachedResourceClientWalker.h"
#include "CachedResourceLoader.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "FrameLoaderTypes.h"
#include "FrameView.h"
#include "MIMETypeRegistry.h"
#include "MemoryCache.h"
#include "RenderElement.h"
#include "SVGImage.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "SharedBuffer.h"
#include "SubresourceLoader.h"
#include <wtf/CurrentTime.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>

#if PLATFORM(IOS)
#include "SystemMemory.h"
#endif

#if USE(CG)
#include "PDFDocumentImage.h"
#endif

namespace WebCore {

CachedImage::CachedImage(CachedResourceRequest&& request, PAL::SessionID sessionID)
    : CachedResource(WTFMove(request), ImageResource, sessionID)
{
    setStatus(Unknown);
}

CachedImage::CachedImage(Image* image, PAL::SessionID sessionID)
    : CachedResource(URL(), ImageResource, sessionID)
    , m_image(image)
{
}

CachedImage::CachedImage(const URL& url, Image* image, PAL::SessionID sessionID, const String& domainForCachePartition)
    : CachedResource(url, ImageResource, sessionID)
    , m_image(image)
    , m_isManuallyCached(true)
{
    m_resourceRequest.setDomainForCachePartition(domainForCachePartition);

    // Use the incoming URL in the response field. This ensures that code using the response directly,
    // such as origin checks for security, actually see something.
    m_response.setURL(url);
}

CachedImage::~CachedImage()
{
    clearImage();
}

void CachedImage::load(CachedResourceLoader& loader)
{
    if (loader.shouldPerformImageLoad(url()))
        CachedResource::load(loader);
    else
        setLoading(false);
}

void CachedImage::setBodyDataFrom(const CachedResource& resource)
{
    ASSERT(resource.type() == type());
    const CachedImage& image = static_cast<const CachedImage&>(resource);

    CachedResource::setBodyDataFrom(resource);

    m_image = image.m_image;
    m_imageObserver = image.m_imageObserver;
    if (m_imageObserver)
        m_imageObserver->cachedImages().add(this);

    if (m_image && is<SVGImage>(*m_image))
        m_svgImageCache = std::make_unique<SVGImageCache>(&downcast<SVGImage>(*m_image));
}

void CachedImage::didAddClient(CachedResourceClient& client)
{
    if (m_data && !m_image && !errorOccurred()) {
        createImage();
        m_image->setData(m_data.copyRef(), true);
    }

    ASSERT(client.resourceClientType() == CachedImageClient::expectedType());
    if (m_image && !m_image->isNull())
        static_cast<CachedImageClient&>(client).imageChanged(this);

    if (m_image)
        m_image->startAnimationAsynchronously();

    CachedResource::didAddClient(client);
}

void CachedImage::didRemoveClient(CachedResourceClient& client)
{
    ASSERT(client.resourceClientType() == CachedImageClient::expectedType());

    m_pendingContainerContextRequests.remove(&static_cast<CachedImageClient&>(client));
    m_pendingImageDrawingClients.remove(&static_cast<CachedImageClient&>(client));

    if (m_svgImageCache)
        m_svgImageCache->removeClientFromCache(&static_cast<CachedImageClient&>(client));

    CachedResource::didRemoveClient(client);

    static_cast<CachedImageClient&>(client).didRemoveCachedImageClient(*this);
}

void CachedImage::addPendingImageDrawingClient(CachedImageClient& client)
{
    ASSERT(client.resourceClientType() == CachedImageClient::expectedType());
    if (m_pendingImageDrawingClients.contains(&client))
        return;
    if (!m_clients.contains(&client)) {
        // If the <html> element does not have its own background specified, painting the root box
        // renderer uses the style of the <body> element, see RenderView::rendererForRootBackground().
        // In this case, the client we are asked to add is the root box renderer. Since we can't add
        // a client to m_pendingImageDrawingClients unless it is one of the m_clients, we are going
        // to cancel the repaint optimization we do in CachedImage::imageFrameAvailable() by adding
        // all the m_clients to m_pendingImageDrawingClients.
        CachedResourceClientWalker<CachedImageClient> walker(m_clients);
        while (auto* client = walker.next())
            m_pendingImageDrawingClients.add(client);
    } else
        m_pendingImageDrawingClients.add(&client);
}

void CachedImage::switchClientsToRevalidatedResource()
{
    ASSERT(is<CachedImage>(resourceToRevalidate()));
    // Pending container size requests need to be transferred to the revalidated resource.
    if (!m_pendingContainerContextRequests.isEmpty()) {
        // A copy of pending size requests is needed as they are deleted during CachedResource::switchClientsToRevalidateResouce().
        ContainerContextRequests switchContainerContextRequests;
        for (auto& request : m_pendingContainerContextRequests)
            switchContainerContextRequests.set(request.key, request.value);
        CachedResource::switchClientsToRevalidatedResource();
        CachedImage& revalidatedCachedImage = downcast<CachedImage>(*resourceToRevalidate());
        for (auto& request : switchContainerContextRequests)
            revalidatedCachedImage.setContainerContextForClient(*request.key, request.value.containerSize, request.value.containerZoom, request.value.imageURL);
        return;
    }

    CachedResource::switchClientsToRevalidatedResource();
}

void CachedImage::allClientsRemoved()
{
    m_pendingContainerContextRequests.clear();
    m_pendingImageDrawingClients.clear();
    if (m_image && !errorOccurred())
        m_image->resetAnimation();
}

std::pair<Image*, float> CachedImage::brokenImage(float deviceScaleFactor) const
{
    if (deviceScaleFactor >= 3) {
        static NeverDestroyed<Image*> brokenImageVeryHiRes(&Image::loadPlatformResource("missingImage@3x").leakRef());
        return std::make_pair(brokenImageVeryHiRes, 3);
    }

    if (deviceScaleFactor >= 2) {
        static NeverDestroyed<Image*> brokenImageHiRes(&Image::loadPlatformResource("missingImage@2x").leakRef());
        return std::make_pair(brokenImageHiRes, 2);
    }

    static NeverDestroyed<Image*> brokenImageLoRes(&Image::loadPlatformResource("missingImage").leakRef());
    return std::make_pair(brokenImageLoRes, 1);
}

bool CachedImage::willPaintBrokenImage() const
{
    return errorOccurred() && m_shouldPaintBrokenImage;
}

Image* CachedImage::image()
{
    if (errorOccurred() && m_shouldPaintBrokenImage) {
        // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
        // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
        // when they need the real, deviceScaleFactor-appropriate broken image icon.
        return brokenImage(1).first;
    }

    if (m_image)
        return m_image.get();

    return &Image::nullImage();
}

Image* CachedImage::imageForRenderer(const RenderObject* renderer)
{
    if (errorOccurred() && m_shouldPaintBrokenImage) {
        // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
        // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
        // when they need the real, deviceScaleFactor-appropriate broken image icon.
        return brokenImage(1).first;
    }

    if (!m_image)
        return &Image::nullImage();

    if (m_image->isSVGImage()) {
        Image* image = m_svgImageCache->imageForRenderer(renderer);
        if (image != &Image::nullImage())
            return image;
    }
    return m_image.get();
}

void CachedImage::setContainerContextForClient(const CachedImageClient& client, const LayoutSize& containerSize, float containerZoom, const URL& imageURL)
{
    if (containerSize.isEmpty())
        return;
    ASSERT(containerZoom);
    if (!m_image) {
        m_pendingContainerContextRequests.set(&client, ContainerContext { containerSize, containerZoom, imageURL });
        return;
    }

    if (!m_image->isSVGImage()) {
        m_image->setContainerSize(containerSize);
        return;
    }

    m_svgImageCache->setContainerContextForClient(client, containerSize, containerZoom, imageURL);
}

LayoutSize CachedImage::imageSizeForRenderer(const RenderElement* renderer, float multiplier, SizeType sizeType)
{
    if (!m_image)
        return LayoutSize();

    LayoutSize imageSize;

    if (is<BitmapImage>(*m_image) && renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation)
        imageSize = LayoutSize(downcast<BitmapImage>(*m_image).sizeRespectingOrientation());
    else if (is<SVGImage>(*m_image) && sizeType == UsedSize)
        imageSize = LayoutSize(m_svgImageCache->imageSizeForRenderer(renderer));
    else
        imageSize = LayoutSize(m_image->size());

    if (multiplier == 1.0f)
        return imageSize;

    // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
    float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
    float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
    LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
    imageSize.scale(widthScale, heightScale);
    imageSize.clampToMinimumSize(minimumSize);
    ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
    return imageSize;
}

void CachedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
    if (m_image)
        m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
}

void CachedImage::notifyObservers(const IntRect* changeRect)
{
    CachedResourceClientWalker<CachedImageClient> w(m_clients);
    while (CachedImageClient* c = w.next())
        c->imageChanged(this, changeRect);
}

void CachedImage::checkShouldPaintBrokenImage()
{
    if (!m_loader || m_loader->reachedTerminalState())
        return;

    m_shouldPaintBrokenImage = m_loader->frameLoader()->client().shouldPaintBrokenImage(url());
}

bool CachedImage::isPDFResource() const
{
    if (m_response.mimeType().isEmpty())
        return url().path().endsWithIgnoringASCIICase(".pdf");
    return MIMETypeRegistry::isPDFMIMEType(m_response.mimeType());
}

bool CachedImage::isPostScriptResource() const
{
    if (m_response.mimeType().isEmpty())
        return url().path().endsWithIgnoringASCIICase(".ps");
    return MIMETypeRegistry::isPostScriptMIMEType(m_response.mimeType());
}

void CachedImage::clear()
{
    destroyDecodedData();
    clearImage();
    m_pendingContainerContextRequests.clear();
    m_pendingImageDrawingClients.clear();
    setEncodedSize(0);
}

inline void CachedImage::createImage()
{
    // Create the image if it doesn't yet exist.
    if (m_image)
        return;

    m_imageObserver = CachedImageObserver::create(*this);

    if (m_response.mimeType() == "image/svg+xml") {
        auto svgImage = SVGImage::create(*m_imageObserver);
        m_svgImageCache = std::make_unique<SVGImageCache>(svgImage.ptr());
        m_image = WTFMove(svgImage);
    } else if (isPDFResource() || isPostScriptResource()) {
#if USE(CG) && !USE(WEBKIT_IMAGE_DECODERS)
        m_image = PDFDocumentImage::create(m_imageObserver.get());
#endif
    } else
        m_image = BitmapImage::create(m_imageObserver.get());

    if (m_image) {
        // Send queued container size requests.
        if (m_image->usesContainerSize()) {
            for (auto& request : m_pendingContainerContextRequests)
                setContainerContextForClient(*request.key, request.value.containerSize, request.value.containerZoom, request.value.imageURL);
        }
        m_pendingContainerContextRequests.clear();
        m_pendingImageDrawingClients.clear();
    }
}

CachedImage::CachedImageObserver::CachedImageObserver(CachedImage& image)
{
    m_cachedImages.add(&image);
}

void CachedImage::CachedImageObserver::decodedSizeChanged(const Image& image, long long delta)
{
    for (auto cachedImage : m_cachedImages)
        cachedImage->decodedSizeChanged(image, delta);
}

void CachedImage::CachedImageObserver::didDraw(const Image& image)
{
    for (auto cachedImage : m_cachedImages)
        cachedImage->didDraw(image);
}

bool CachedImage::CachedImageObserver::canDestroyDecodedData(const Image& image)
{
    for (auto cachedImage : m_cachedImages) {
        if (&image != cachedImage->image())
            continue;
        if (!cachedImage->canDestroyDecodedData(image))
            return false;
    }
    return true;
}

void CachedImage::CachedImageObserver::imageFrameAvailable(const Image& image, ImageAnimatingState animatingState, const IntRect* changeRect, DecodingStatus decodingStatus)
{
    for (auto cachedImage : m_cachedImages)
        cachedImage->imageFrameAvailable(image, animatingState, changeRect, decodingStatus);
}

void CachedImage::CachedImageObserver::changedInRect(const Image& image, const IntRect* rect)
{
    for (auto cachedImage : m_cachedImages)
        cachedImage->changedInRect(image, rect);
}

inline void CachedImage::clearImage()
{
    if (!m_image)
        return;

    if (m_imageObserver) {
        m_imageObserver->cachedImages().remove(this);

        if (m_imageObserver->cachedImages().isEmpty()) {
            ASSERT(m_imageObserver->hasOneRef());
            m_image->setImageObserver(nullptr);
        }

        m_imageObserver = nullptr;
    }

    m_image = nullptr;
    m_lastUpdateImageDataTime = { };
    m_updateImageDataCount = 0;
}

void CachedImage::updateBufferInternal(SharedBuffer& data)
{
    m_data = &data;
    setEncodedSize(m_data->size());
    createImage();

    // Don't update the image with the new buffer very often. Changing the decoder
    // internal data and repainting the observers sometimes are very expensive operations.
    if (shouldDeferUpdateImageData())
        return;

    EncodedDataStatus encodedDataStatus = EncodedDataStatus::Unknown;

    if (isPostScriptResource()) {
#if PLATFORM(MAC) && !USE(WEBKIT_IMAGE_DECODERS)
        // Delay updating the image with the PostScript data till all the data
        // is received so it can be converted to PDF data.
        return;
#else
        // Set the encodedDataStatus to Error so loading this image will be canceled.
        encodedDataStatus = EncodedDataStatus::Error;
#endif
    } else {
        // Have the image update its data from its internal buffer. Decoding the image data
        // will be delayed until info (like size or specific image frames) are queried which
        // usually happens when the observers are repainted.
        encodedDataStatus = updateImageData(false);
    }

    if (encodedDataStatus > EncodedDataStatus::Error && encodedDataStatus < EncodedDataStatus::SizeAvailable)
        return;

    if (encodedDataStatus == EncodedDataStatus::Error || m_image->isNull()) {
        // Image decoding failed. Either we need more image data or the image data is malformed.
        error(errorOccurred() ? status() : DecodeError);
        if (m_loader && encodedDataStatus == EncodedDataStatus::Error)
            m_loader->cancel();
        if (inCache())
            MemoryCache::singleton().remove(*this);
        return;
    }

    // Tell our observers to try to draw.
    notifyObservers();
}

bool CachedImage::shouldDeferUpdateImageData() const
{
    static const double updateImageDataBackoffIntervals[] = { 0, 1, 3, 6, 15 };
    unsigned interval = std::min<unsigned>(m_updateImageDataCount, 4);

    // The first time through, the chunk time will be 0 and the image will get an update.
    return (MonotonicTime::now() - m_lastUpdateImageDataTime).seconds() < updateImageDataBackoffIntervals[interval];
}

RefPtr<SharedBuffer> CachedImage::convertedDataIfNeeded(SharedBuffer* data) const
{
    if (!data || !isPostScriptResource())
        return data;
#if PLATFORM(MAC) && !USE(WEBKIT_IMAGE_DECODERS)
    return SharedBuffer::create(PDFDocumentImage::convertPostScriptDataToPDF(data->createCFData()).get());
#else
    // Loading the image should have been canceled if the system does not support converting PostScript to PDF.
    ASSERT_NOT_REACHED();
    return nullptr;
#endif
}

void CachedImage::didUpdateImageData()
{
    m_lastUpdateImageDataTime = MonotonicTime::now();
    ASSERT(m_updateImageDataCount < std::numeric_limits<unsigned>::max());
    ++m_updateImageDataCount;
}

EncodedDataStatus CachedImage::updateImageData(bool allDataReceived)
{
    if (!m_image || !m_data)
        return EncodedDataStatus::Error;
    EncodedDataStatus result = m_image->setData(m_data.get(), allDataReceived);
    didUpdateImageData();
    return result;
}

void CachedImage::updateBuffer(SharedBuffer& data)
{
    ASSERT(dataBufferingPolicy() == BufferData);
    updateBufferInternal(data);
    CachedResource::updateBuffer(data);
}

void CachedImage::updateData(const char* data, unsigned length)
{
    ASSERT(dataBufferingPolicy() == DoNotBufferData);
    updateBufferInternal(SharedBuffer::create(data, length));
    CachedResource::updateData(data, length);
}

void CachedImage::finishLoading(SharedBuffer* data)
{
    m_data = convertedDataIfNeeded(data);
    if (m_data) {
        setEncodedSize(m_data->size());
        createImage();
    }

    EncodedDataStatus encodedDataStatus = updateImageData(true);

    if (encodedDataStatus == EncodedDataStatus::Error || m_image->isNull()) {
        // Image decoding failed; the image data is malformed.
        error(errorOccurred() ? status() : DecodeError);
        if (inCache())
            MemoryCache::singleton().remove(*this);
        return;
    }

    notifyObservers();
    CachedResource::finishLoading(data);
}

void CachedImage::didReplaceSharedBufferContents()
{
    if (m_image) {
        // Let the Image know that the SharedBuffer has been rejigged, so it can let go of any references to the heap-allocated resource buffer.
        // FIXME(rdar://problem/24275617): It would be better if we could somehow tell the Image's decoder to swap in the new contents without destroying anything.
        m_image->destroyDecodedData(true);
    }
    CachedResource::didReplaceSharedBufferContents();
}

void CachedImage::error(CachedResource::Status status)
{
    checkShouldPaintBrokenImage();
    clear();
    CachedResource::error(status);
    notifyObservers();
}

void CachedImage::responseReceived(const ResourceResponse& response)
{
    if (!m_response.isNull())
        clear();
    CachedResource::responseReceived(response);
}

void CachedImage::destroyDecodedData()
{
    bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
    if (canDeleteImage && !isLoading() && !hasClients()) {
        m_image = nullptr;
        setDecodedSize(0);
    } else if (m_image && !errorOccurred())
        m_image->destroyDecodedData();
}

void CachedImage::decodedSizeChanged(const Image& image, long long delta)
{
    if (&image != m_image)
        return;

    ASSERT(delta >= 0 || decodedSize() + delta >= 0);
    setDecodedSize(static_cast<unsigned>(decodedSize() + delta));
}

void CachedImage::didDraw(const Image& image)
{
    if (&image != m_image)
        return;

    double timeStamp = FrameView::currentPaintTimeStamp();
    if (!timeStamp) // If didDraw is called outside of a Frame paint.
        timeStamp = monotonicallyIncreasingTime();

    CachedResource::didAccessDecodedData(timeStamp);
}

bool CachedImage::canDestroyDecodedData(const Image& image)
{
    if (&image != m_image)
        return false;

    CachedResourceClientWalker<CachedImageClient> clientWalker(m_clients);
    while (CachedImageClient* client = clientWalker.next()) {
        if (!client->canDestroyDecodedData())
            return false;
    }

    return true;
}

void CachedImage::imageFrameAvailable(const Image& image, ImageAnimatingState animatingState, const IntRect* changeRect, DecodingStatus decodingStatus)
{
    if (&image != m_image)
        return;

    CachedResourceClientWalker<CachedImageClient> clientWalker(m_clients);
    VisibleInViewportState visibleState = VisibleInViewportState::No;

    while (CachedImageClient* client = clientWalker.next()) {
        // All the clients of animated images have to be notified. The new frame has to be drawn in all of them.
        if (animatingState == ImageAnimatingState::No && !m_pendingImageDrawingClients.contains(client))
            continue;
        if (client->imageFrameAvailable(*this, animatingState, changeRect) == VisibleInViewportState::Yes)
            visibleState = VisibleInViewportState::Yes;
    }

    if (visibleState == VisibleInViewportState::No && animatingState == ImageAnimatingState::Yes)
        m_image->stopAnimation();

    if (decodingStatus != DecodingStatus::Partial)
        m_pendingImageDrawingClients.clear();
}

void CachedImage::changedInRect(const Image& image, const IntRect* rect)
{
    if (&image != m_image)
        return;
    notifyObservers(rect);
}

bool CachedImage::currentFrameKnownToBeOpaque(const RenderElement* renderer)
{
    Image* image = imageForRenderer(renderer);
    return image->currentFrameKnownToBeOpaque();
}

bool CachedImage::isOriginClean(SecurityOrigin* origin)
{
    ASSERT_UNUSED(origin, origin);
    ASSERT(this->origin());
    ASSERT(origin->toString() == this->origin()->toString());
    return !loadFailedOrCanceled() && isCORSSameOrigin();
}

CachedResource::RevalidationDecision CachedImage::makeRevalidationDecision(CachePolicy cachePolicy) const
{
    if (UNLIKELY(isManuallyCached())) {
        // Do not revalidate manually cached images. This mechanism is used as a
        // way to efficiently share an image from the client to content and
        // the URL for that image may not represent a resource that can be
        // retrieved by standard means. If the manual caching SPI is used, it is
        // incumbent on the client to only use valid resources.
        return RevalidationDecision::No;
    }
    return CachedResource::makeRevalidationDecision(cachePolicy);
}

} // namespace WebCore


text:
using System;

namespace Realms.Sync
{
    /// <summary>
    /// An object encapsulating a Realm Object Server session. Sessions represent the communication between the client (and a local Realm file on disk), and the server (and a remote Realm at a given URL stored on a Realm Object Server).
    /// Sessions are always created by the SDK and vended out through various APIs. The lifespans of sessions associated with Realms are managed automatically.
    /// </summary>
    public class Session
    {
        /// <summary>
        /// Triggered when an error occurs on a session. The <c>sender</c> argument will be the session which has errored.
        /// </summary>
        public static event EventHandler<ErrorEventArgs> Error;

        /// <summary>
        /// Gets the <see cref="Uri"/> describing the remote Realm which this session connects to and synchronizes changes with.
        /// </summary>
        /// <value>The <see cref="Uri"/> where the Realm Object Server resides.</value>
        public Uri ServerUri => new Uri(Handle.GetServerUri());

        /// <summary>
        /// Gets the session's current state.
        /// </summary>
        /// <value>An enum value indicating the state of the session.</value>
        public SessionState State => Handle.GetState();

        /// <summary>
        /// Gets the <see cref="User"/> defined by the <see cref="SyncConfiguration"/> that is used to connect to the Realm Object Server.
        /// </summary>
        /// <value>The <see cref="User"/> that was used to create the <see cref="Realm"/>'s <see cref="SyncConfiguration"/>.</value>
        public User User => Handle.GetUser();

        /// <summary>
        /// Gets the on-disk path of the Realm file backing the <see cref="Realm"/> this Session represents.
        /// </summary>
        /// <value>The file path.</value>
        public string Path => Handle.GetPath();

        /// <summary>
        /// Gets an <see cref="IObservable{T}"/> that can be used to track upload or download progress.
        /// </summary>
        /// <remarks>
        /// To start receiving notifications, you should call <see cref="IObservable{T}.Subscribe"/> on the returned object.
        /// The token returned from <see cref="IObservable{T}.Subscribe"/> should be retained as long as progress
        /// notifications are desired. To stop receiving notifications, call <see cref="IDisposable.Dispose"/>
        /// on the token.
        /// You don't need to keep a reference to the observable itself.
        /// The progress callback will always be called once immediately upon subscribing in order to provide
        /// the latest available status information.
        /// </remarks>
        /// <returns>An observable that you can subscribe to and receive progress updates.</returns>
        /// <param name="direction">The transfer direction (upload or download) to track in the subscription callback.</param>
        /// <param name="mode">The desired behavior of this progress notification block.</param>
        /// <example>
        /// <code>
        /// class ProgressNotifyingViewModel
        /// {
        ///     private IDisposable notificationToken;
        ///
        ///     public void ShowProgress()
        ///     {
        ///         var observable = session.GetProgressObservable(ProgressDirection.Upload, ProgressMode.ReportIndefinitely);
        ///         notificationToken = observable.Subscribe(progress =>
        ///         {
        ///             // Update relevant properties by accessing
        ///             // progress.TransferredBytes and progress.TransferableBytes
        ///         });
        ///     }
        ///
        ///     public void HideProgress()
        ///     {
        ///         notificationToken?.Dispose();
        ///         notificationToken = null;
        ///     }
        /// }
        /// </code>
        /// In this example we're using <see href="https://msdn.microsoft.com/en-us/library/ff402849(v=vs.103).aspx">ObservableExtensions.Subscribe</see>
        /// found in the <see href="https://github.com/Reactive-Extensions/Rx.NET">Reactive Extensions</see> class library.
        /// If you prefer not to take a dependency on it, you can create a class that implements <see cref="IObserver{T}"/>
        /// and use it to subscribe instead.
        /// </example>
        public IObservable<SyncProgress> GetProgressObservable(ProgressDirection direction, ProgressMode mode)
        {
            return new SyncProgressObservable(this, direction, mode);
        }

        internal readonly SessionHandle Handle;

        private Session(SessionHandle handle)
        {
            Handle = handle;
        }

        /// <summary>
        /// Attempts to reconnect all sessions.
        /// </summary>
        /// <remarks>
        /// By default, the sync engine will attempt to reconnect sessions at incrementing intervals. This method is
        /// useful when you are monitoring connectivity yourself, using e.g.
        /// <see href="https://github.com/jamesmontemagno/ConnectivityPlugin">Connectivity Plugin</see> or through the
        /// native connectivity API and you wish to cancel that delay and try to reconnect immediately.
        /// </remarks>
        public static void Reconnect()
        {
            SharedRealmHandleExtensions.ReconnectSessions();
        }

        internal static Session Create(IntPtr sessionPtr)
        {
            if (sessionPtr == IntPtr.Zero)
            {
                return null;
            }

            var handle = new SessionHandle();
            handle.SetHandle(sessionPtr);

            return new Session(handle);
        }

        internal static Session Create(string path)
        {
            return Create(SessionHandle.SessionForPath(path));
        }

        internal static void RaiseError(Session session, Exception error)
        {
            var args = new ErrorEventArgs(error);
            Error?.Invoke(session, args);
        }

        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            var session = obj as Session;

            return session != null &&
                   session.Handle.GetRawPointer() == Handle.GetRawPointer();
        }

        /// <inheritdoc/>
        public override int GetHashCode()
        {
            return Handle.GetRawPointer().GetHashCode();
        }
    }
}


text:
package au.gov.dva.ptsdassist;

import gov.va.contentlib.UserDBHelper;
import gov.va.contentlib.Util;
import gov.va.contentlib.content.Content;
import gov.va.contentlib.content.ContentActivity;
import gov.va.contentlib.services.TtsContentProvider;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.openmhealth.ohmage.campaigns.va.ptsd_explorer.AppExitedEvent;
import com.openmhealth.ohmage.campaigns.va.ptsd_explorer.AppLaunchedEvent;
import com.openmhealth.ohmage.campaigns.va.ptsd_explorer.TimeElapsedBetweenSessionsEvent;
import com.openmhealth.ohmage.campaigns.va.ptsd_explorer.TotalTimeOnAppEvent;
import com.openmhealth.ohmage.core.EventLog;

public class PTSDAssist extends ContentActivity {

	private View splash = null;
	private long sessionStartTime;
	private boolean triggerAssessment = false;

	public void addSplash() {
		LayoutInflater inflater = LayoutInflater.from(this);
		splash = (View)inflater.inflate(R.layout.splash, getRootFrame(), false);
		getRootFrame().addView(splash);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String assessmentIntent = Util.getAssessmentIntent(this);
		if ((assessmentIntent != null) && assessmentIntent.equals(getIntent().getAction())) {
			triggerAssessment = true;
		}

		getSupportActionBar().hide();
		setContent(getDB().getContentForName("ROOT"));

		AlphaAnimation alpha = new AlphaAnimation(1,0);
		alpha.setInterpolator(new AccelerateDecelerateInterpolator());
		alpha.setDuration(1000L);
		alpha.setFillAfter(true);
		alpha.setFillBefore(true);
		alpha.setFillEnabled(true);
		alpha.setStartTime(AnimationUtils.currentAnimationTimeMillis()+3000);
		alpha.setAnimationListener(new Animation.AnimationListener() {
			public void onAnimationStart(Animation animation) {
			}
			public void onAnimationRepeat(Animation animation) {
			}
			public void onAnimationEnd(Animation animation) {
				getSupportActionBar().show();
				getRootFrame().removeView(splash);
				splash = null;
			}
		});
		splash.setAnimation(alpha);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String assessmentIntent = Util.getAssessmentIntent(this);
		if ((assessmentIntent != null) && assessmentIntent.equals(intent.getAction())) {
			triggerAssessment = true;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		sessionStartTime = System.currentTimeMillis();

		String lastSessionTSStr = UserDBHelper.instance(this).getSetting("lastSessionEndTime");
		if (lastSessionTSStr != null) {
			long lastSessionTS = Long.parseLong(lastSessionTSStr);
			TimeElapsedBetweenSessionsEvent e = new TimeElapsedBetweenSessionsEvent();
			e.timeElapsedBetweenSessions = System.currentTimeMillis() - lastSessionTS;
			EventLog.log(e);
		}

		AppLaunchedEvent e = new AppLaunchedEvent();
		e.accessibilityFeaturesActiveOnLaunch = TtsContentProvider.shouldSpeak(this) ? 1 : 0;
		EventLog.log(e);

		if (triggerAssessment) {
			triggerAssessment = false;
			Content c = getDB().getContentForName("takeAssessment");
			navigateToContent(c);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

        String uptimeStr = UserDBHelper.instance(this).getSetting("totalUptime");
        long uptime = (uptimeStr == null) ? 0 : Long.parseLong(uptimeStr);
        uptime += System.currentTimeMillis() - sessionStartTime;

        {
        	TotalTimeOnAppEvent e = new TotalTimeOnAppEvent();
        	e.totalTimeOnApp = uptime;
        	EventLog.log(e);
        }
        UserDBHelper.instance(this).setSetting("totalUptime",""+uptime);

        UserDBHelper.instance(this).setSetting("lastSessionEndTime", ""+System.currentTimeMillis());

        {
        	AppExitedEvent e = new AppExitedEvent();
        	e.appExitedAccessibilityFeaturesActive = TtsContentProvider.shouldSpeak(this) ? 1 : 0;
        	EventLog.log(e);
        }
	}

	@Override
	protected void onStart() {
		super.onStart();
//		new Thread(new Runnable() {
//			public void run() {
//			}
//		}).start();
//		FlurryAgent.onStartSession(this, "15TJQ1LZBD8MNZTRNF3K");

//		if(tts==null)
	//		checkForTTS();
	}

	@Override
	protected void onStop() {
//		FlurryAgent.onEndSession(this);

		super.onStop();
	}

}


text:
using System;
using System.Media;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
//using IrrKlang;
//using FMODNet;

namespace SEMIK1
{
    public class SoundFactory
    {
        //private static ISoundEngine player;
        public static string file;
        private static float volume = -1;
        private static FMOD.System system = null;
        private static FMOD.Sound sound = null;
        private static FMOD.Channel channel = null;
        private static bool inited = false;

        public static void Init()
        {
            try
            {
                //device = new SoundDevice();
                //device.Initialize(new SoundDeviceConfiguration
                //    {
                //        DebugMode = false,
                //        MaximumAllowedSounds = 4
                //    });
                inited = true;
            }
            catch (Exception e) {
                Logger.Log("SoundFactory exception");
                Logger.Log(e.ToString());
            }
        }
        public static void StopSound()
        {
            if (!inited) return;
            // if (player == null) return;
           //  player.StopAllSounds();
            //if (sound == null) return;
            if (channel == null) return;
            channel.stop();
        }

        public static void SetVolume(int vol)
        {
            if (!inited) return;
            volume = (float)vol / 100;
            if (channel != null)
            {
                channel.setVolume(volume);
            }
        }

        public static void TestSound(string id) {
            if (!inited) return;
            MessageBox.Show("Now testing sound \"" + id + "\" with volume " + volume.ToString());
            PlaySound(id);
        }

        public static void PlaySound(string id){
            if (!inited) return;
            if (!Properties.Settings.Default.use_sound) return;
            //if (player != null) player.StopAllSounds();
            //if (player == null) player = new ISoundEngine();
            if (sound != null) StopSound();
            if (volume == -1) volume = Properties.Settings.Default.sound_volume;
            switch (id)
            {
                case "TaxiFromGate":
                    file = Application.StartupPath + "/sfx/crew2_safetyaboard.mp3";
                break;
                case "BeforeTakeoff":
                    file = Application.StartupPath + "/sfx/crew_preparetakeoff.mp3";
                break;
                case "Descent":
                    file = Application.StartupPath + "/sfx/crew6_descent.mp3";
                break;
                case "Landing":
                    file = Application.StartupPath + "/sfx/crew7_beforelandnight.mp3";
                break;
                case "TaxiToGate":
                    file = Application.StartupPath + "/sfx/crew8_aftland.mp3";
                break;
            }

            try
            {
                FMOD.RESULT result;
                uint version = 0;

                result = FMOD.Factory.System_Create(ref system);
                ERRCHECK(result);

                result = system.getVersion(ref version);
                ERRCHECK(result);
                if (version < FMOD.VERSION.number)
                {
                    MessageBox.Show("Error!  You are using an old version of FMOD " + version.ToString("X") + ".  This program requires " + FMOD.VERSION.number.ToString("X") + ".");
                }

                result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
                ERRCHECK(result);

                result = system.createSound(file, FMOD.MODE.HARDWARE, ref sound);
                ERRCHECK(result);

                result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
                ERRCHECK(result);
                channel.setVolume(volume);
            }
            catch (Exception e) {
                Logger.Log("SoundFactory Error: " + e.ToString());
            }

            //player.SoundVolume = volume;
           // player.Play2D(file);
        }

        private static void ERRCHECK(FMOD.RESULT result)
        {
            if (result != FMOD.RESULT.OK)
            {
                //MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result));
                //Environment.Exit(-1);
                Logger.Log("FMOD error! " + result + " - " + FMOD.Error.String(result));
            }
        }

        public static void Dispose()
        {
            FMOD.RESULT result;

            /*
                Shut down
            */
            if (sound != null)
            {
                result = sound.release();
                ERRCHECK(result);
            }

            if (system != null)
            {
                result = system.close();
                ERRCHECK(result);
                result = system.release();
                ERRCHECK(result);
            }
        }
    }
}


text:
package com.hp.autonomy.frontend.find.idol.applications;

import com.hp.autonomy.frontend.find.core.configuration.CustomizationConfigService;
import com.hp.autonomy.frontend.find.core.customization.ReloadableCustomizationComponent;
import org.springframework.stereotype.Service;

@Service
public class CustomApplicationsConfigService extends CustomizationConfigService<CustomApplicationsConfig> implements ReloadableCustomizationComponent {
    public CustomApplicationsConfigService() {
        super(
            "applications.json",
            "defaultApplicationsConfigFile.json",
            CustomApplicationsConfig.class,
            CustomApplicationsConfig.builder().build()
        );
    }

    @Override
    public void reload() throws Exception {
        init();
    }
}


text:
package core.module.codec;

public class SetParameterAlarmLimitAck extends SetParameterAck {

    public SetParameterAlarmLimitAck() {
    }
}


text:
package com.forbesdigital.jee.oauth.spring.client;

import com.forbesdigital.jee.oauth.spring.AbstractExceptionTranslationFilter;
import com.forbesdigital.jee.oauth.OAuthTokenError;
import com.forbesdigital.jee.oauth.JsonObjectSerializer;
import com.forbesdigital.jee.oauth.spring.client.exceptions.AbstractOAuthTokenRequestException;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;

/**
 * Specific implementation of Exception Translation filter for Client Authentication.
 *
 * @author Laurent Prevost <laurent.prevost@lotaris.com>
 * @author Cristian Calugar <cristian.calugar@fortech.ro>
 */
public class ClientExceptionTranslationFilter extends AbstractExceptionTranslationFilter {

	protected final JsonObjectSerializer jsonSerializer = new JsonObjectSerializer();

	@Override
	protected void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
		RuntimeException exception) throws IOException, ServletException {

		// There are only two types of exception that we can get here: an AccessDeniedException or an AuthenticationException

		if (exception instanceof AbstractOAuthTokenRequestException) {
			sendUnauthorizedAccessResponse(response, (AbstractOAuthTokenRequestException) exception);
		} else if (exception instanceof AuthenticationException) {
			sendUnauthorizedAccessResponse(response);
		}
	}

	/**
	 * Builds the error response in case of an Authentication Exception thrown by request OAuth Token API call authorization.
	 * The returned response content is in JSON and has the standard format specified by OAauth2 specifications.
	 *
	 * @param response The response
	 */
	private void sendUnauthorizedAccessResponse(HttpServletResponse response) throws IOException {
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		response.setContentType("application/json");
		response.getOutputStream().print(buildErrorResponse(new OAuthTokenError(
				"invalid_client",
				"You are not allowed to access this resource.")));
	}

	/**
	 * Builds the error response in case of an Authentication Exception thrown by request OAuth Token API call authorization.
	 * The returned response content is in JSON and has the standard format specified by OAauth2 specifications.
	 *
	 * @param response The response
	 * @param tre An OAuth Token request exception
	 */
	private void sendUnauthorizedAccessResponse(HttpServletResponse response, AbstractOAuthTokenRequestException tre) throws IOException {
		response.setStatus(tre.getHttpStatusCode());
		response.setContentType("application/json");
		response.getOutputStream().print(buildErrorResponse(new OAuthTokenError(
				tre.getOAuth2ErrorCode(),
				tre.getMessage())));
	}

	/**
	 * Builds a JSON error response based on the provided transfer object.
	 *
	 * @param response holds error data
	 * @return a JSON representation of the provided TO
	 */
	private String buildErrorResponse(OAuthTokenError response) {
		try {
			return jsonSerializer.writeValueAsString(response);
		} catch (IOException ex) {
			// nothing to do here
		}
		return null;
	}

}