text:
Stagers in Kurma are used to provide a pluggable interface to control [pod](https://github.com/appc/spec/blob/master/spec/pods.md)  orchestration and supervision.

When a pod is launched, the Kurma daemon will resolve all of the dependencies
for the applications in the [pod](https://github.com/appc/spec/blob/master/spec/pods.md)
and provide them in the form of a [stager manifest](https://github.com/apcera/kurma/blob/master/Documentation/stager_specification.md#stager-manifest) and bind mount them into the stager's filesystem.

This way, a stager has everything it needs for launching the workloads:

```sh
$ pstree -p 23097
stager(23097)─┬─init(23111)
              ├─example-workload(23117)─┬─{example-workload}(23122)
              │                         └─{example-workload}(23124)
              └─{stager}(23104)
```

## Prerequisites

A stager itself is just an [ACI image](https://github.com/appc/spec/blob/master/spec/aci.md) and is loaded in just like any other image. In order for an image to be used as a stager, it must meet the following:

1. The image cannot have any [dependencies](https://github.com/appc/spec/blob/master/spec/aci.md#dependency-matching). A stager should not need any overlay filesystems set up, since the Kurma daemon does not handle any union filesystems. This is the responsibility of the stager for its apps.

2. The image must have a signature with a key that is known and trusted by the
   Kurma daemon. This list of keys is defined in its configuration file and only
   manageable there. Since a stager can execute with host privilege, it must
   ensure the image can be executed in that context first.

## Execution

When a stager is executed, it will be launched chrooted within a directory
containing its root filesystem (cf. [ACE Filesystem setup](https://github.com/appc/spec/blob/master/spec/ace.md#filesystem-setup)).
This ensures its filesystem has all of its dependencies and avoids and mismatches with the host's filesystem.

When the stager is launched, it will be in its own mount namespace. It will
typically have its own network namespace, unless the storm is configured to
share the host's network namespace. The executable will be the `exec`
setting of the stager's [AppC Image Manifest](https://github.com/appc/spec/blob/master/spec/aci.md#image-manifest-schema).

The mount namespace is configured to be private. This ensures that any mounts
made within the stager or its applications will not [propagate](http://lwn.net/Articles/690679/) to the host.

The network namespace will be preconfigured with the networking devices for the
container. Note that it may be the host's network namespace, if the pod is
supposed to be using the host's networking.

## Filesystem Configuration

The filesystem for the stager will be pre-populated with everything the stager
will need for the pod and its applications. The following paths will be created
and stagers should ensure they don't include anything related to the following
paths.

* `/manifest` - This contains the JSON manifest containing the information
  needed for the stager. See the "Stager Manifest" section for the format.
* `/layers/*` - This directory contains read-only bind mounts to the extracted
  root filesystem of each of the layers needed for the applications in the
  pod. They are named with the
  [AppC Image ID](https://github.com/appc/spec/blob/master/spec/aci.md#image-id)
  in the form of `sha512-[checksum]`. The bind mounts are all read-only, as the
  stager and the applications should not be modifying these. The stager should
  be using these as a base for setting up the app filesystem with either a union
  filesystem or copying the layers.
* `/volumes/*` - This directory contains all of the volumes referenced by the
  PodManifest. The name of the directory will match the name of the volume from
  the PodManifest

The stager will be chrooted within its root directory and contain each of the
items referenced above. The following additional elements will be mounted:

* `/dev` from the host will be bind mounted in.
* `/proc` will be mounted for the stager.
* `/sys` will be mounted read only.
* `/sys/fs/cgroups` will be mounted read-write, scoped to just the stager's
  cgroup.

A verbose example of a stager root directory:

```
tree ./pods/5512aee5/stager/ -L 2
├── apps
│   └── api-proxy
├── bin
│   ├── busybox
│   └── modprobe -> busybox
├── containers
│   ├── api-proxy
│   └── init
├── dev
├── etc
│   ├── ld.so.cache
│   ├── ld.so.conf
│   └── resolv.conf
├── init
│   ├── dev
│   ├── etc
│   ├── init
│   ├── proc
│   └── sys
├── layers
│   └── sha512-cb1c48f988819de775f9127c9ee5d3cb7205d519c401c08030f6cb6a77f9e4cafd9e928c071cf6b67cf7c8846cac1aa32a23c995e4254195e0d77c4e787f0dac
├── lib
│   ├── ld-linux-x86-64.so.2
│   ├── libc.so.6
│   ├── libdl.so.2
│   ├── libpthread.so.0
│   └── modules -> /proc/1/root/lib/modules
├── lib64 -> lib
├── logs
│   ├── api-proxy
│   └── init.log
├── manifest
├── opt
│   └── stager
├── proc
├── stager
├── state.json
├── sys
├── tmp
│   └── scratch653127451
└── volumes
    └── api-proxy-kurma-socket
```

Example mounts from stager:

```
sudo cat /proc/23097/mounts
rootfs / rootfs rw 0 0
/dev/disk/by-uuid/3af531bb-7c15-4e60-b23f-4853c47ccc91 / ext4 rw,relatime,data=ordered 0 0
...
/dev/disk/by-uuid/3af531bb-7c15-4e60-b23f-4853c47ccc91 /layers/sha512-cb1c48f988819de775f9127c9ee5d3cb7205d519c401c08030f6cb6a77f9e4cafd9e928c071cf6b67cf7c8846cac1aa32a23c995e4254195e0d77c4e787f0dac ext4 ro,relatime,data=ordered 0 0
/dev/disk/by-uuid/3af531bb-7c15-4e60-b23f-4853c47ccc91 /volumes/api-proxy-kurma-socket/kurma.sock ext4 rw,relatime,data=ordered 0 0
none /apps/api-proxy aufs rw,relatime,si=5e9500bff3167de0 0 0
/dev/disk/by-uuid/3af531bb-7c15-4e60-b23f-4853c47ccc91 /apps/api-proxy/var/lib/kurma ext4 rw,relatime,data=ordered 0 0
/dev/disk/by-uuid/3af531bb-7c15-4e60-b23f-4853c47ccc91 /apps/api-proxy/var/lib/kurma/kurma.sock ext4 rw,relatime,data=ordered 0 0
```

## Lifetime Management

The stager is expected to stay alive for the lifetime of the pod. If at any
point the stager exits, Kurma will consider the pod errored and tear it and any
remaining processes down.

When the stager is launched, it will be passed an additional file handler as
descriptor `4`. The descriptor is expected to be closed once the stager has
finished setting up the workloads and the pod is considered running.

## Stager Manifest

The stager manifest is a JSON document that contains the information necessary
to configure and run the applications within the pod, and to match up the
provided filesystem information to its place within the pod.

At the top level, the structure is as follows:

```
{
    "kurmaVersion": "0.4.1",
    "name": "example1",
	"pod": { },
	"images": { },
	"appImageOrder": { },
	"stagerConfig": { }
}
```

* `kurmaVersion` - The `kurmaVersion` will contain the version of Kurma that was
  used at the time the pod was launched. This is primarily used when `kurmad` is
  in use and to ensure compatibility when the daemon is upgraded independent of
  the pod.
* `name` - The `name` element is the string name that was given to the pod. It
  could optionally be used by the stager to configure the hostname in the
  applications.
* `pod` - The `pod` element contains the
  [AppC Pod Manifest](https://github.com/appc/spec/blob/master/spec/pods.md)
  object and the definition for the applications in the pod as provided.
* `images` - The `images` element contains a map of the Image ID for an image to
  the
  [AppC Image Manifest](https://github.com/appc/spec/blob/master/spec/aci.md).
* `appImageOrder` - The `appImageOrder` element contains a map of the
  application name from the Pod Manifest and a string array containing the Image
  IDs of all the images that make up its filesystem, with the first element
  being the top most image, and the last being the lower most.
* `stagerConfig` - The `stagerConfig` element is a JSON document containing what
  ever configuration was provided to Kurma. This is specific to the stager and
  provides a way to pass down configuration parameters from the administrator to
  inform the stager. For instance, in the default configuration, it will pass
  over whether to use overlay or aufs for the union filesystem.

An example document is:

```json
{
    "kurmaVersion": "0.4.1",
	"pod": {
		"acVersion": "0.7.4",
		"acKind": "PodManifest",
		"apps": [{
			"name": "nats",
			"image": {
				"id": "sha512-de8f22333d0234270a8a18d47dcc475a69489ab18bf7e7fbbcdee50b6d0a1c8f536750c5c55e9a0e63574053f2fc51bbba20caedb14220e0c157e6d8fb35f4fc"
			}
		}]
	},
	"images": {
		"sha512-de8f22333d0234270a8a18d47dcc475a69489ab18bf7e7fbbcdee50b6d0a1c8f536750c5c55e9a0e63574053f2fc51bbba20caedb14220e0c157e6d8fb35f4fc": {
			"acKind": "ImageManifest",
			"acVersion": "0.7.0",
			"name": "registry-1.docker.io/library/nats",
			"labels": [{
				"name": "version",
				"value": "latest"
			}, {
				"name": "os",
				"value": "linux"
			}, {
				"name": "arch",
				"value": "amd64"
			}],
			"app": {
				"exec": ["/gnatsd", "-c", "/gnatsd.conf"],
				"user": "0",
				"group": "0",
				"ports": [{
					"name": "4222-tcp",
					"protocol": "tcp",
					"port": 4222,
					"count": 1,
					"socketActivated": false
				}, {
					"name": "6222-tcp",
					"protocol": "tcp",
					"port": 6222,
					"count": 1,
					"socketActivated": false
				}, {
					"name": "8222-tcp",
					"protocol": "tcp",
					"port": 8222,
					"count": 1,
					"socketActivated": false
				}]
			},
			"annotations": [{
				"name": "authors",
				"value": "Derek Collison \u003cderek@apcera.com\u003e"
			}, {
				"name": "created",
				"value": "2015-12-09T20:18:21Z"
			}, {
				"name": "appc.io/docker/registryurl",
				"value": "registry-1.docker.io"
			}, {
				"name": "appc.io/docker/repository",
				"value": "library/nats"
			}, {
				"name": "appc.io/docker/imageid",
				"value": "f5c45d5f9cacc583e02dbc3cba8b5e35cb054334fc8db24f3a51e8873839af48"
			}, {
				"name": "appc.io/docker/parentimageid",
				"value": "e5da1391e6bdf3ec19c5f2216b2af8056a23d3cdb802f56a738cdb7ee230cda6"
			}]
		}
	},
	"appImageOrder": {
		"nats": ["sha512-de8f22333d0234270a8a18d47dcc475a69489ab18bf7e7fbbcdee50b6d0a1c8f536750c5c55e9a0e63574053f2fc51bbba20caedb14220e0c157e6d8fb35f4fc"]
	},
	"stagerConfig": {}
}
```

## Call Ins

There are a number of functions that Kurma may be calling in to the stager to
perform on an ongoing basis. These are instrumented through additional
executables. These are done by Kurma calling them by entering the mount and
network namespace. If the executables need to enter other namespaces, they must
instrument that.

The following executables are expected within the stager:

* `/opt/stager/status` to check the status of the applications in the pod.
* `/opt/stager/logs` to request log files for an application within the pod.
* `/opt/stager/run` to run a new process within an application in the pod.
* `/opt/stager/attach` to attach to the input/output of an application.

#### `status`

The `status` command is called to get the current pod state. It is not called on
a regular pole interval, but it is triggered by an API call to get the pod's
internal status.

It takes no information in, it is expected just to output JSON over stdout with
the pod's application status, primarily accounting for whether the applications
are running and if not, what their exit code was.

The response is in the following format when the pod is in a steady state:

```json
{
	"nats": {
        "pid": 1234,
        "exited": false
	}
}
```

For an exited application, it would return `running` of `false` and an `exitCode`.

```json
{
	"nats": {
        "exited": true,
		"exitCode": 1,
		"exitReason": "killed"
	}
}
```

#### `logs`

#### `run`

The `run` command is used to execute a specified command within one of the
applications in the pod. A single command line argument will be passed with the
name of the application to run the command in.

The settings for the command to run will be passed over a separate file
descriptor in JSON form and will always be available on file descriptor 3.

The JSON input is similar to the AppC Spec's "App" field of the
ImageManifest. It could look like the following:

```json
{
    "exec": [ "/bin/bash" ],
    "user": "0",
    "group": "0",
    "supplementaryGIDs": [ 20, 21 ],
    "workingDirectory": "/",
    "environment": [
        { "name": "PATH", "value": "/usr/bin:/usr/sbin:/bin:/sbin" }
    ],
    "tty": true
}
```

* **exec** (list of strings, required) executable to launch and any flags
* **user**, **group** (string, required) indicates either the username/group
  name or the UID/GID the app is to be run as (freeform string). The user and
  group values may be all numbers to indicate a UID/GID, however it is possible
  on some systems (POSIX) to have usernames that are all numerical. The user and
  group values will first be resolved using the image's own `/etc/passwd` or
  `/etc/group`. If no valid matches are found, then if the string is all
  numerical, it shall be converted to an integer and used as the UID/GID. If the
  user or group field begins with a "/", the owner and group of the file found
  at that absolute path inside the rootfs is used as the UID/GID of the
  process. Example values for the fields include `root`, `1000`, or
  `/usr/bin/ping`.
* **supplementaryGIDs** (list of unsigned integers, optional) indicates
  additional (supplementary) group IDs (GIDs) as which the app's processes
  should run.
* **workingDirectory** (string, optional) working directory of the launched
  application
* **environment** (list of objects, optional) represents the app's environment
  variables. The listed objects must have two key-value pairs:
  **name** and **value**. The **name** must consist solely of letters, digits,
  and underscores '_' as outlined in
  [IEEE Std 1003.1-2001](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html). The
  **value** is an arbitrary string. These values are not evaluated in any way,
  and no substitutions are made.
* **tty** (boolean, optional, defaults to "false" if unsupplied) if set to true,
  a tty will be allocated and given to the process as its stdin/stdout/stderr.

It is expected that the JSON configuration should be read in within 10
seconds. Failure to read all of the configuration, including the EOF, will
result in the `run` command being torn down and an error being returned.

The command's stdin/stdout/stderr should be passed along directly to the child
command within the pod's application.

The `run` command is expected to either exec or block until the child command is
complete. The exit code should be propagated back to the parent.

Example:

```shell
$ /opt/stager/run ubuntu
```

#### `attach`

The `attach` command is used to attach the executor to stdin/stdout/stderr of an
application within the pod. The command will be called with an argument for
which application should be attached to.

Example:

```
$ /opt/stager/attach nats
```

The command should take stdin/stdout/stderr of the `attach` command and connect
it to stdin/stdout/stderr of the command executed for the specified application.

## Considerations

There are a number of important considerations that a stager should be aware of
and chose how it manages.

* Mount and network namespaces are created by the top level daemon. If the
  stager is using user namespaces, the owner of non-user namespaces is important
  to ensure isolation. It may be necessary for the stager to create another
  mount and network namespace under the user namespace and transfer the
  networking to it. See "Interaction of user namespaces and other types of
  namespaces" in
  [user_namespaces(7)](http://man7.org/linux/man-pages/man7/user_namespaces.7.html).
* The stager is responsible for lifecycle management within the pod.
* The stager controls the security scoping for the applications it runs. If the
  stager takes over PID 1 within a container, and it is implementing shared PID
  namespaces between apps, it should be aware of things like traversal through
  `/proc`.
  * Using `/proc/1/root/`, a container could access the root filesystem of the
    stager. Generally, this only contains the pod's data, so it may just be
    leaking data across applications. It should manage that.
  * With shared namespaces, be aware of where it may be possible to dump memory
    and see information.
* Additional call in functions may need to be entering additional namespaces,
  and should be contious of when they enter into the purview of the applications
  in the pod.


text:
@interface MXMAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) NSTimer *idleTimerControlTimer;

@end

redpajama_set_name: RedPajamaGithub


text:
#include "condition_variable.hpp"
#include "lock.hpp"
#include <cassert>

#include "profile.hpp"

namespace ioa {

  condition_variable::condition_variable () {
    BEGIN_SYS_CALL;
    int r = pthread_cond_init (&m_cond, 0);
    END_SYS_CALL;
    assert (r == 0);
  }

  condition_variable::~condition_variable () {
    BEGIN_SYS_CALL;
    int r = pthread_cond_destroy (&m_cond);
    END_SYS_CALL;
    assert (r == 0);
  }

  void condition_variable::wait (lock& lock) {
    BEGIN_SYS_CALL;
    int r = pthread_cond_wait (&m_cond, &lock.m_mutex.m_mutex);
    END_SYS_CALL;
    assert (r == 0);
  }

  void condition_variable::notify_one () {
    BEGIN_SYS_CALL;
    int r = pthread_cond_signal (&m_cond);
    END_SYS_CALL;
    assert (r == 0);
  }

}


text:
'use strict';

const chai = require('chai');
const expect = chai.expect;
const utils = require('./utils.js');
const auth = utils.auth;

describe('profile', function() {

  beforeEach(function() {
    utils.setFirebaseData();
  });

  describe('service', function() {

    describe('registration', function() {
      const publicId = 'alice';
      const userId = `codeCombat:${publicId}`;
      const detailsPath = `classMentors/userProfiles/${publicId}/services/codeCombat/details`;
      let details;

      beforeEach(function() {
        details = {
          id: userId,
          name: userId,
          registeredBefore: utils.timestamp()
        };
      });

      it('should allow a user to register a service', function() {
        expect(auth.alice).can.write(details).to.path(detailsPath);
      });

      it('should disallow a user to register a service without a user id', function() {
        delete details.id;
        expect(auth.alice).cannot.write(details).to.path(detailsPath);
      });

      it('should disallow a user to register a service without a user name', function() {
        delete details.name;
        expect(auth.alice).cannot.write(details).to.path(detailsPath);
      });

      it('should disallow a user to register a service without an initial timestamp', function() {
        delete details.registeredBefore;
        expect(auth.alice).cannot.write(details).to.path(detailsPath);

        details.registeredBefore = 1;
        expect(auth.alice).cannot.write(details).to.path(detailsPath);
      });

    });

    describe('removal', function() {
      const servicePath = 'classMentors/userProfiles/bob/services/codeCombat';

      it('should allow a user to remove a service', function() {
        expect(auth.bob).can.write(null).to.path(servicePath);
      });

    });

    describe('update request', function() {

      function requestPatch(publicId) {
        var servicePath = `classMentors/userProfiles/${publicId}/services/codeCombat`;

        return {
          'queue/tasks/someRandomTaskId': {id: publicId, service: 'codeCombat'},
          [`${servicePath}/lastUpdateRequest`]: {'.sv': 'timestamp'}
        };
      }

      it('should allow users to request an update', function() {
        const patch = requestPatch('bob');

        expect(auth.bob).can.patch(patch).to.path('/');
      });

      it('should allow any users to request other users update', function() {
        const patch = requestPatch('bob');

        expect(auth.alice).can.patch(patch).to.path('/');
      });
    });

  });

});


text:
{% extends '_base.html' %}

{% block content %}

DOJ findings

The below reports were released by the Department of Justice on March 4, 2015. The report concerning whether Darren Wilson should be federally prosecuted for killing Michael Brown concluded that the case lacked prosecutorial merit and so Wilson should not be charged. Another report accuses Ferguson police and courts of violating citizens' constitutional rights.

Report on Darren Wilson

Report on Ferguson

Evidence released by McCulloch

The below documents are evidence the grand jury considered that was released by St. Louis County Prosecutor Robert McCulloch.

Portions highlighted in yellow are notes that St. Louis Public Radio reporters have made to help understand these documents or passages we've marked for later reference. We have not redacted these documents — other than the notes, they are as provided.

UPDATED DEC. 15 with new evidence released.

{% endblock %}


text:
cloaked-octo-batman
===================


text:
import pathlib
import platform

rootPath = pathlib.Path(__file__).parent.parent.absolute()
aabPath = pathlib.Path(rootPath, 'client/build/outputs/bundle/release/client-release.aab')
distPath = pathlib.Path(rootPath, 'server/build/distributions/server.zip')
installPath = pathlib.Path(rootPath, 'server/build/install/server')

gradleCmd = './gradlew'
if platform.system() == 'Windows':
  gradleCmd = r".\gradlew.bat"


text:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.47
 * Generated at: 2015-07-13 10:37:51 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.WEB_002dINF.views.modules.act;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class actModelCreate_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0;
private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_1;

static {
  _jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getAdminPath", com.thinkgem.jeesite.common.config.Global.class, "getAdminPath", new Class[] {});
  _jspx_fnmap_1= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getDictList", com.thinkgem.jeesite.modules.sys.utils.DictUtils.class, "getDictList", new Class[] {java.lang.String.class});
}

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  static {
    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(5);
    _jspx_dependants.put("/WEB-INF/views/include/taglib.jsp", Long.valueOf(1430867052000L));
    _jspx_dependants.put("/WEB-INF/tags/sys/message.tag", Long.valueOf(1430867052000L));
    _jspx_dependants.put("/WEB-INF/tlds/fns.tld", Long.valueOf(1430867052000L));
    _jspx_dependants.put("/WEB-INF/tlds/shiros.tld", Long.valueOf(1430867052000L));
    _jspx_dependants.put("/WEB-INF/tlds/fnc.tld", Long.valueOf(1430867052000L));
  }

  private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody;
  private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.release();
    _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release();
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\n');
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      if (_jspx_meth_c_005fset_005f0(_jspx_page_context))
        return;
      out.write('\n');
      if (_jspx_meth_c_005fset_005f1(_jspx_page_context))
        return;
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\t<title>新建模型 - 模型管理</title>\n");
      out.write("\t<meta name=\"decorator\" content=\"default\"/>\n");
      out.write("\t\n");
      out.write("\n");
      out.write("\n");
      out.write("\t
\n");
      out.write("\t\t
模型管理
\n");
      out.write("\t\t
新建模型
\n");
      out.write("\t

\n");
      out.write("\t");
      if (_jspx_meth_sys_005fmessage_005f0(_jspx_page_context))
        return;
      out.write("\n");
      out.write("\t<form id=\"inputForm\" action=\"");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
      out.write("/act/model/create\" target=\"_blank\" method=\"post\" class=\"form-horizontal\">\n");
      out.write("\t\t
\n");
      out.write("\t\t\t流程分类:\n");
      out.write("\t\t\t
\n");
      out.write("\t\t\t\t<select id=\"category\" name=\"category\" class=\"required input-medium\">\n");
      out.write("\t\t\t\t\t");
      if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context))
        return;
      out.write("\n");
      out.write("\t\t\t\t</select>\n");
      out.write("\t\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t\t模块名称:\n");
      out.write("\t\t\t
\n");
      out.write("\t\t\t\t<input id=\"name\" name=\"name\" type=\"text\" class=\"required\" />\n");
      out.write("\t\t\t\t\n");
      out.write("\t\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t\t模块标识:\n");
      out.write("\t\t\t
\n");
      out.write("\t\t\t\t<input id=\"key\" name=\"key\" type=\"text\" class=\"required\" />\n");
      out.write("\t\t\t\t\n");
      out.write("\t\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t\t模块描述:\n");
      out.write("\t\t\t
\n");
      out.write("\t\t\t\t<textarea id=\"description\" name=\"description\" class=\"required\"></textarea>\n");
      out.write("\t\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t
\n");
      out.write("\t\t\t<input id=\"btnSubmit\" class=\"btn btn-primary\" type=\"submit\" value=\"提 交\"/>\n");
      out.write("\t\t\t<input id=\"btnCancel\" class=\"btn\" type=\"button\" value=\"返 回\" onclick=\"history.go(-1)\"/>\n");
      out.write("\t\t
\n");
      out.write("\t</form>\n");
      out.write("\n");
      out.write("\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }

  private boolean _jspx_meth_c_005fset_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:set
    org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
    _jspx_th_c_005fset_005f0.setPageContext(_jspx_page_context);
    _jspx_th_c_005fset_005f0.setParent(null);
    // /WEB-INF/views/include/taglib.jsp(11,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f0.setVar("ctx");
    // /WEB-INF/views/include/taglib.jsp(11,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}${fns:getAdminPath()}", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, _jspx_fnmap_0, false));
    int _jspx_eval_c_005fset_005f0 = _jspx_th_c_005fset_005f0.doStartTag();
    if (_jspx_th_c_005fset_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
      return true;
    }
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
    return false;
  }

  private boolean _jspx_meth_c_005fset_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:set
    org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
    _jspx_th_c_005fset_005f1.setPageContext(_jspx_page_context);
    _jspx_th_c_005fset_005f1.setParent(null);
    // /WEB-INF/views/include/taglib.jsp(12,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f1.setVar("ctxStatic");
    // /WEB-INF/views/include/taglib.jsp(12,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}/static", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
    int _jspx_eval_c_005fset_005f1 = _jspx_th_c_005fset_005f1.doStartTag();
    if (_jspx_th_c_005fset_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
      return true;
    }
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
    return false;
  }

  private boolean _jspx_meth_sys_005fmessage_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  sys:message
    org.apache.jsp.tag.websys.message_tag _jspx_th_sys_005fmessage_005f0 = (new org.apache.jsp.tag.websys.message_tag());
    _jsp_instancemanager.newInstance(_jspx_th_sys_005fmessage_005f0);
    _jspx_th_sys_005fmessage_005f0.setJspContext(_jspx_page_context);
    // /WEB-INF/views/modules/act/actModelCreate.jsp(37,1) name = content type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
    _jspx_th_sys_005fmessage_005f0.setContent((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${message}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
    _jspx_th_sys_005fmessage_005f0.doTag();
    _jsp_instancemanager.destroyInstance(_jspx_th_sys_005fmessage_005f0);
    return false;
  }

  private boolean _jspx_meth_c_005fforEach_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:forEach
    org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
    _jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context);
    _jspx_th_c_005fforEach_005f0.setParent(null);
    // /WEB-INF/views/modules/act/actModelCreate.jsp(43,5) name = items type = java.lang.Object reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fforEach_005f0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${fns:getDictList('act_category')}", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, _jspx_fnmap_1, false));
    // /WEB-INF/views/modules/act/actModelCreate.jsp(43,5) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fforEach_005f0.setVar("dict");
    int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 };
    try {
      int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag();
      if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
        do {
          out.write("\n");
          out.write("\t\t\t\t\t\t<option value=\"");
          out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.value}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
          out.write('"');
          out.write('>');
          out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.label}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
          out.write("</option>\n");
          out.write("\t\t\t\t\t");
          int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody();
          if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
            break;
        } while (true);
      }
      if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
        return true;
      }
    } catch (java.lang.Throwable _jspx_exception) {
      while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0)
        out = _jspx_page_context.popBody();
      _jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception);
    } finally {
      _jspx_th_c_005fforEach_005f0.doFinally();
      _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0);
    }
    return false;
  }
}


text:
require 'test_helper'

class PerformanceReviewsControllerTest < ActionController::TestCase
end


text:
namespace RimDev.Descriptor.Generic
{
    public class DescriptorContainer<T> : DescriptorContainer, IDescriptor<T>
    {
        public IDescriptor<T> SetDescription(string description)
        {
            Description = description;

            return this;
        }

        public IDescriptor<T> SetName(string name)
        {
            Name = name;

            return this;
        }

        public IDescriptor<T> SetType(string type)
        {
            Type = type;

            return this;
        }
    }
}


text:
.tikslus_notify_vertical_vleft li.hera,.tikslus_notify_vertical_vright li.hera,.tikslus_notify_vertical_vcenter li.hera{
/*padding: 0.2em;*/
background-color: #ffbf40;
margin-bottom: 2.5em;
position: relative;
opacity: 1;

}

.tikslus_notify_vertical_vleft li.hera p,.tikslus_notify_vertical_vright li.hera p,.tikslus_notify_vertical_vcenter li.hera p{
padding-right: 3%;
padding-left:3%;
color: #fff;
}

.tikslus_notify_vertical_vleft li.hera .progress,.tikslus_notify_vertical_vright li.hera .progress,.tikslus_notify_vertical_vcenter li.hera .progress{
background-color:#ffde40 !important;
height:0.2em !important;
width:0;
}

.tikslus_notify_vertical_vleft .tikslus_picture ,.tikslus_notify_vertical_vright .tikslus_picture ,.tikslus_notify_vertical_vcenter .tikslus_picture {
float: left;
max-width: 22%;
margin: 0.2em;
}

.tikslus_notify_vertical_vleft li.hera .title,.tikslus_notify_vertical_vright li.hera .title,.tikslus_notify_vertical_vcenter li.hera .title,{
padding: 4px;
font-size: 1.2em;
color: #fff !important;

background-color:#ffcf70 !important;
   -webkit-border-bottom-right-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;

  -moz-border-radius-bottomright: 5px;
  -moz-border-radius-bottomleft: 5px;

    border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;

}

.tikslus_notify_vertical_vleft li.hera .btns,.tikslus_notify_vertical_vright li.hera .btns,.tikslus_notify_vertical_vcenter li.hera .btns{
/* margin: 0.5em; */
/* position: absolute; */
/* bottom: 15%; */
/* right: 0%; */
display: inline-block;
/* margin: 0; */
/* top: 99%; */
/* left: -1%; */
width: 100%;
background-color: #ffcf70 !important;
color: #fff !important;
min-height: 2em;
}

}

.tikslus_notify_vertical_vleft li.hera .btns ul,.tikslus_notify_vertical_vright li.hera .btns ul,.tikslus_notify_vertical_vcenter li.hera .btns ul{
list-style:none;
}
.tikslus_notify_vertical_vleft li.hera .btns ul.user_buttons,.tikslus_notify_vertical_vright li.hera .btns ul.user_buttons,.tikslus_notify_vertical_vcenter li.hera .btns ul.user_buttons{
list-style:none;
width:100%;
margin:0;
padding:0;
}

.tikslus_notify_vertical_vleft li.hera .btns ul li,.tikslus_notify_vertical_vright li.hera .btns ul li,.tikslus_notify_vertical_vcenter li.hera .btns ul li{
float:right;
display:block;
margin:0.25em;
}

.tikslus_notify_vertical_vleft li.hera .btns ul.user_buttons li,.tikslus_notify_vertical_vright li.hera .btns ul.user_buttons li,.tikslus_notify_vertical_vcenter li.hera .btns ul.user_buttons li{
float:right;
display:block;
margin:0.25em;
}

.tikslus_notify_vertical_vleft li.hera .btns ul li a,.tikslus_notify_vertical_vright li.hera .btns ul li a,.tikslus_notify_vertical_vcenter li.hera .btns ul li a{
text-decoration: none;
display: block;

background-color:#ffc700 !important;
color:#fff !important;

font-size: 0.9em;
padding: 0.2em;
}

.tikslus_notify_vertical_vleft li.hera .btns ul li a:hover,.tikslus_notify_vertical_vright li.hera .btns ul li a:hover,.tikslus_notify_vertical_vcenter li.hera .btns ul li a:hover{
color:#222;
background-color: #ffe473 !important;
}

.tikslus_notify_vertical_vleft li.hera .btns ul li.closenotification a.close:hover,.tikslus_notify_vertical_vright li.hera .btns ul li.closenotification a.close:hover,.tikslus_notify_vertical_vcenter li.hera .btns ul li.closenotification a.close:hover,{
background-color: #ffe473 !important;
}

.tikslus_notify_vertical_vleft li.hera .btns ul.user_buttons li a,.tikslus_notify_vertical_vright li.hera .btns ul.user_buttons li a,.tikslus_notify_vertical_vcenter li.hera .btns ul.user_buttons li a{
text-decoration: none;
display: block;

background-color:#ffc700 !important;
color:#fff !important;

font-size: 0.9em;
padding: 0.2em;
}

.tikslus_notify_vertical_vleft li.hera .btns ul.user_buttons li a:hover,.tikslus_notify_vertical_vright li.hera .btns ul.user_buttons li a:hover,.tikslus_notify_vertical_vcenter li.hera .btns ul.user_buttons li a:hover{
background-color: #ffe473 !important;
}

.tikslus_notify_vertical_vleft li.hera .closenotification,.tikslus_notify_vertical_vright li.hera .closenotification,.tikslus_notify_vertical_vcenter li.hera .closenotification,{

display:block;

margin: 0;
color: #fff !important;
position:absolute;
top:0;
right:0;

}

}

.tikslus_notify_vertical_vleft li.hera .closenotification .left{
left:0%;
}
.tikslus_notify_vertical_vright li.hera .closenotification .right{
right:0%;
}

.tikslus_notify_vertical li.hera .closenotification .top{
top:-1%;
}
.tikslus_notify_vertical li.hera .closenotification .bottom{
bottom:0%;
}


text:
abstract class NeedsXEarly {
  val x: Int
}
class Foo extends { val x = 1 } with NeedsXEarly


text:
- Search in files: `grep -rnw '/path/to/somewhere/' -e "pattern"`

## MacOS
https://www.podfeet.com/blog/tutorials-5/encrypt-file-folder-osx/

- zip -e filename.encrypted 'filename.png'
- zip -er foldername.encrypted 'foldername'

- unzip -P 'password' filename.encrypted -d .
- unzip -P 'password' filename.encrypted -d encrypted

default password

## Overige
URL: http://snazzylabs.com/article/5-killer-macos-tricks-hidden-in-terminal/

DOCK:
Super-fast animation: defaults write com.apple.dock autohide-time-modifier -float 0.12;
No animation: defaults write com.apple.dock autohide-time-modifier -int 0;
Revert to default: defaults delete com.apple.dock autohide-time-modifier;

defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}'

killall Dock;

URL: http://snazzylabs.com/tutorial/five-advanced-tricks-for-mac-users/

Tip 1: Screenshot
defaults write com.apple.screencapture type jpg

Tip 2: Encrypt
encrypt (change path): openssl enc -aes-256-cbc -e -in {path-in} -out {path-out}
decrypt (change path): openssl enc -aes-256-cbc -d -in {path-in} -out {path-out}

Tip 3: Updates
defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 1

Tip 5: Prevent sleep
caffeinate -i -t 3600

Avetica tar:
tar -czf(v) [filename].tar.gz [files]

Fix damaged applications:
- sudo spctl --master-disable
- sudo spctl --master-enable

Terminal commands:
 - defaults write com.apple.Terminal NSQuitAlwaysKeepsWindows -bool false

https://mallinson.ca/osx-web-development/

- defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}'
- killall Dock

- defaults write com.apple.finder AppleShowAllFiles FALSE
- killall Finder


text:
Many of these tests are copies of the tests of JSONEncoder from swift, that can be found at https://github.com/apple/swift/blob/1e110b8f63836734113cdb28970ebcea8fd383c2/test/stdlib/TestJSONEncoder.swift.

These tests are licensed at the Apache 2.0 License with Runtime Library Exception. This license is contained in this repository in the file SWIFT-LICENSE.txt in the base folder.

Basically these tests were rewritten using Quick and Nimble. Some parts of the original file are also directly copied (and marked as copied).

The current tests cover:
 * general tests from JSONEncoder plus a few additionals
 *  `LinearCodingStack`
 * dynamic meta tree unwrapping
 * `StandardCodingKey`
 * Representation
 * ErrorContainer

 Additional, a few smaller usability concepts are tested
  * Not allowing top level single value types
  * Not allowing nil values


text:
<?php

/**
 * Short description for class.
 *
 * @package       cake
 * @subpackage    cake.tests.fixtures
 */
class DataTestFixture extends CakeTestFixture {

/**
 * name property
 *
 * @var string 'DataTest'
 * @access public
 */
	var $name = 'DataTest';

/**
 * fields property
 *
 * @var array
 * @access public
 */
	var $fields = array(
		'id' => array('type' => 'integer', 'key' => 'primary'),
		'count' => array('type' => 'integer', 'default' => 0),
		'float' => array('type' => 'float', 'default' => 0),
		//'timestamp' => array('type' => 'timestamp', 'default' => null, 'null' => true),
		'created' => array('type' => 'datetime', 'default' => null),
		'updated' => array('type' => 'datetime', 'default' => null)
	);

/**
 * records property
 *
 * @var array
 * @access public
 */
	var $records = array();
}

?>


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

#ifndef FUZZTEST_FUZZTEST_INTERNAL_RUNTIME_H_
#define FUZZTEST_FUZZTEST_INTERNAL_RUNTIME_H_

#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <functional>
#include <iostream>
#include <memory>
#include <optional>
#include <random>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include "absl/functional/function_ref.h"
#include "absl/random/random.h"
#include "absl/random/seed_sequences.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "./fuzztest/domain.h"
#include "./fuzztest/internal/coverage.h"
#include "./fuzztest/internal/domain.h"
#include "./fuzztest/internal/fixture_driver.h"
#include "./fuzztest/internal/io.h"
#include "./fuzztest/internal/logging.h"
#include "./fuzztest/internal/meta.h"
#include "./fuzztest/internal/polymorphic_value.h"
#include "./fuzztest/internal/registration.h"
#include "./fuzztest/internal/serialization.h"
#include "./fuzztest/internal/type_support.h"

namespace fuzztest {

// The mode in which we are running the fuzz tests.
enum class RunMode {
  // Run without instrumentation and coverage-guidance for a short time.
  kUnitTest,

  // Run coverage-guided fuzzing until a failure is detected or the test is
  // manually terminated.
  kFuzz
};

namespace internal {

class FuzzTestFuzzer {
 public:
  virtual ~FuzzTestFuzzer() = default;
  virtual void RunInUnitTestMode() = 0;
  // Returns fuzzing mode's exit code. Zero indicates success.
  virtual int RunInFuzzingMode(int* argc, char*** argv) = 0;
};

class FuzzTest;

using FuzzTestFuzzerFactory =
    std::function<std::unique_ptr<FuzzTestFuzzer>(const FuzzTest&)>;

class FuzzTest {
 public:
  FuzzTest(BasicTestInfo test_info, FuzzTestFuzzerFactory factory)
      : test_info_(test_info), make_(std::move(factory)) {}

  FuzzTest(const FuzzTest&) = delete;
  FuzzTest& operator=(const FuzzTest&) = delete;

  const char* suite_name() const { return test_info_.suite_name; }
  const char* test_name() const { return test_info_.test_name; }
  std::string full_name() const {
    return suite_name() + std::string(".") + test_name();
  }
  const std::vector<std::string_view>& param_names() const {
    return param_names_;
  }
  const char* file() const { return test_info_.file; }
  int line() const { return test_info_.line; }
  bool uses_fixture() const { return test_info_.uses_fixture; }
  auto make() const { return make_(*this); }

 private:
  BasicTestInfo test_info_;
  std::vector<std::string_view> param_names_;
  FuzzTestFuzzerFactory make_;
};

struct RuntimeStats {
  absl::Time start_time;
  size_t runs;
  size_t edges_covered;
  size_t total_edges;
  // Number of executed inputs that increase coverage.
  size_t useful_inputs;
};

void InstallSignalHandlers(FILE* report_out);

// Some failures are not necessarily detected by signal handlers or by
// sanitizers. For example, we could have test framework failures like
// `EXPECT_EQ` failures from GoogleTest.
// If such a failure is detected, the external system can set
// `external_failure_was_detected` to true to bubble it up.
// Note: Even though failures should happen within the code under test, they
// could be set from other threads at any moment. We make it an atomic to avoid
// a race condition.
extern std::atomic<bool> external_failure_was_detected;

// If true, fuzzing should terminate as soon as possible.
// Atomic because it is set from signal handlers.
extern std::atomic<bool> termination_requested;

extern RunMode run_mode;
extern absl::Duration fuzz_time_limit;

class OnFailure {
 public:
  void Enable(const RuntimeStats* stats, absl::Time (*clock_fn)()) {
    enabled_ = true;
    stats_ = stats;
    clock_fn_ = clock_fn;
    // In case we have not installed them yet, do so now.
    InstallSignalHandlers(GetStderr());
  }
  void Disable() { enabled_ = false; }

  template <typename Domain>
  struct Args {
    const corpus_type_t<Domain>& corpus_value;
    Domain& domain;
    static constexpr size_t kNumArgs =
        std::tuple_size_v<typename Domain::value_type>;
  };

  void SetCurrentTest(const FuzzTest* test) { test_ = test; }

  template <typename Domain>
  void SetCurrentArgs(Args<Domain>* args) {
    current_args_ = CurrentArgs(std::in_place, args);
    num_args_ = args->kNumArgs;
  }

  void UnsetCurrentArgs() { current_args_ = {}; }

  void PrintFinalStats(absl::FormatRawSink out) const;
  void PrintFinalStatsOnDefaultSink() const;
  void PrintReport(absl::FormatRawSink out) const;
  void PrintReportOnDefaultSink() const;

 private:
  void DumpReproducer(std::string_view outdir) const;

  struct ArgumentPrintVisitor {
    template <typename ArgWithDomain>
    void operator()(const ArgWithDomain& arg, absl::FormatRawSink out,
                    size_t index, PrintMode mode) {
      Switch<ArgWithDomain::kNumArgs>(index, [&](auto I) {
        PrintValue(ExtractInnerDomain<I>(arg.domain),
                   std::get<I>(arg.corpus_value), out, mode);
      });
    }
  };

  struct ArgumentSerializeVisitor {
    template <typename ArgWithDomain, typename DependentTest = FuzzTest>
    std::string operator()(const ArgWithDomain& arg) {
      return arg.domain.SerializeCorpus(arg.corpus_value).ToString();
    }
  };

  using CurrentArgs =
      VisitableValue<ArgumentPrintVisitor, ArgumentSerializeVisitor>;

  bool enabled_ = false;
  CurrentArgs current_args_;
  size_t num_args_;
  const FuzzTest* test_;
  const RuntimeStats* stats_;
  absl::Time (*clock_fn_)() = nullptr;
};
extern OnFailure on_failure;
extern void (*crash_handler_hook)();

template <typename Arg, size_t I, typename Tuple>
decltype(auto) GetDomainOrArbitrary(const Tuple& t) {
  if constexpr (I < std::tuple_size_v<Tuple>) {
    return std::get<I>(t);
  } else {
    return Arbitrary<std::decay_t<Arg>>();
  }
}

// Used to capture buffer overflows more reliably. See more at use site.
//
// TODO(b/194687521): Remove this when we (or ASAN) detect overflows
// in strings.
struct ForceVector {
  operator std::string_view() const { return {value.data(), value.size()}; }
  std::vector<char> value;
};

template <typename Dest, typename Src>
decltype(auto) ForceVectorForStringView(Src&& src) {
  // We only do this when Src is a std::string. If it's a string view it is
  // handled by the string view domain itself.
  if constexpr (std::is_same_v<void(std::decay_t<Dest>, std::decay_t<Src>),
                               void(std::string_view, std::string)>) {
    return ForceVector{std::vector<char>(src.begin(), src.end())};
  } else {
    return std::forward<Src>(src);
  }
}

template <typename RegBase, typename Fixture, typename TargetFunction,
          typename = void>
class FuzzTestExternalEngineAdaptor;

template <typename RegBase, typename Fixture, typename TargetFunction,
          typename = void>
class FuzzTestFuzzerImpl;

template <typename RegBase, typename Fixture, typename BaseFixture,
          typename... Args>
class FuzzTestFuzzerImpl<
    RegBase, Fixture, void (BaseFixture::*)(Args...),
    std::enable_if_t<std::is_base_of_v<BaseFixture, Fixture>>>
    : public FuzzTestFuzzer {
 public:
  using TargetFunction = void (BaseFixture::*)(Args...);

  FuzzTestFuzzerImpl(
      const FuzzTest& test,
      std::unique_ptr<FixtureDriver<RegBase, Fixture, TargetFunction>>
          fixture_driver)
      : test_(test),
        fixture_driver_(std::move(fixture_driver)),
        execution_coverage_(internal::GetExecutionCoverage()),
        corpus_coverage_(execution_coverage_ != nullptr
                             ? execution_coverage_->GetCounterMap().size()
                             : 0) {
    FUZZTEST_INTERNAL_CHECK_PRECONDITION(fixture_driver_ != nullptr,
                                         "Invalid fixture driver!");
    stats_.start_time = absl::Now();
    const char* corpus_out_dir_chars = getenv("FUZZTEST_TESTSUITE_OUT_DIR");
    if (corpus_out_dir_chars) corpus_out_dir_ = corpus_out_dir_chars;

    std::vector<double> weights = {100.};
    corpus_distribution_ =
        absl::discrete_distribution<>(weights.begin(), weights.end());
  }
  ~FuzzTestFuzzerImpl() { on_failure.Disable(); }

  // TODO(fniksic): Refactor to reduce code complexity and improve readability.
  void RunInUnitTestMode() override {
    fixture_driver_->SetUpFuzzTest();
    [&] {
      on_failure.Enable(&stats_, [] { return absl::Now(); });
      on_failure.SetCurrentTest(&test_);

      // TODO(sbenzaquen): Currently, some infrastructure code assumes that replay
      // works in unit test mode, so we support it. However, we would like to
      // limit replaying to fuzzing mode only, where we can guarantee that only
      // a single FUZZ_TEST is selected to run. Once we make sure that no
      // existing infra tries to replay in unit test mode, we can remove this.
      if (ReplayInputsIfAvailable()) {
        // If ReplayInputs returns, it means the replay didn't crash.
        // In replay mode, we only replay.
        on_failure.Disable();
        return;
      }

      run_mode = RunMode::kUnitTest;

      PopulateFromSeeds();

      const auto time_limit = stats_.start_time + absl::Seconds(1);
      // TODO(b/242206122): Use seed_sequence() if a env_var is set.
      // We use a fixed random seed in unit-test mode to minimize
      // non-determinism on CI systems (continuous integration), which might
      // categorize the test as "flaky", and in order to avoid confusing users.
      // While this reduces the effectiveness of unit-test mode, this should be
      // mitigated by running this tests continuously in fuzzing mode as well.
      std::seed_seq golden_sequence{3, 8, 9, 9, 8, 3, 7, 8};
      PRNG prng(golden_sequence);
      Input mutation{params_domain_.Init(prng)};
      constexpr size_t max_iterations = 10000;
      for (int i = 0; i < max_iterations; ++i) {
        external_failure_was_detected.store(false, std::memory_order_relaxed);
        RunOneInput(mutation);
        if (external_failure_was_detected.load(std::memory_order_relaxed)) {
          break;
        }
        // We mutate the value, except that every num_mutations_per_value we
        // generate a new one through Init.
        constexpr size_t num_mutations_per_value = 100;
        if (i % num_mutations_per_value < num_mutations_per_value - 1) {
          MutateValue(mutation, prng);
        } else {
          mutation.args = params_domain_.Init(prng);
        }

        if (absl::Now() > time_limit) {
          // Break the test after 1 second of running to avoid time outs on
          // unittests when the fuzz test is doing a lot of work in a single
          // iteration.
          break;
        }
      }
      on_failure.SetCurrentTest(nullptr);
    }();
    fixture_driver_->TearDownFuzzTest();
  }

  // TODO(fniksic): Refactor to reduce code complexity and improve readability.
  int RunInFuzzingMode(int* argc, char*** argv) override {
    fixture_driver_->SetUpFuzzTest();
    const int exit_code = [&] {
      run_mode = RunMode::kFuzz;

      if (IsSilenceTargetEnabled()) SilenceTargetStdoutAndStderr();

      on_failure.Enable(&stats_, [] { return absl::Now(); });
      on_failure.SetCurrentTest(&test_);

      if (ReplayInputsIfAvailable()) {
        // If ReplayInputs returns, it means the replay didn't crash.
        // We don't want to actually run the fuzzer so exit now.
        return 0;
      }

      if (execution_coverage_ == nullptr) {
        absl::FPrintF(
            GetStderr(),
            "\n\n[!] To fuzz, please build with --config=fuzztest.\n\n\n");
        return 1;
      }

      stats_.total_edges = execution_coverage_->GetCounterMap().size();

      PRNG prng(seed_sequence());

      if (MinimizeCorpusIfInMinimizationMode(prng)) {
        absl::FPrintF(
            GetStderr(),
            "[*] Selected %d corpus inputs in minimization mode - exiting.\n",
            stats_.useful_inputs);
        return 0;
      }

      PopulateFromSeeds();
      InitializeCorpus(prng);

      FUZZTEST_INTERNAL_CHECK(
          !corpus_.empty(),
          "No seed input coverage registered. Test function "
          "might be uninstrumented?");

      constexpr size_t kRunsPerInit = 32000;
      size_t next_init = kRunsPerInit;
      if (const char* max_fuzzing_runs_env =
              getenv("FUZZTEST_MAX_FUZZING_RUNS")) {
        if (size_t max_fuzzing_runs;
            absl::SimpleAtoi(max_fuzzing_runs_env, &max_fuzzing_runs)) {
          absl::FPrintF(GetStderr(), "[.] Limiting to %d fuzzing runs.\n",
                        max_fuzzing_runs);
          runs_limit_ = stats_.runs + max_fuzzing_runs;
        } else {
          absl::FPrintF(
              GetStderr(),
              "[!] Failed to parse FUZZTEST_MAX_FUZZING_RUNS as "
              "non-negative integer - will not limit fuzzing runs.\n");
        }
      }

      if (fuzz_time_limit != absl::InfiniteDuration()) {
        absl::FPrintF(GetStderr(), "[.] Fuzzing timeout set to: %s\n",
                      absl::FormatDuration(fuzz_time_limit));
        time_limit_ = stats_.start_time + fuzz_time_limit;
      }

      // Fuzz corpus elements in round robin fashion.
      while (!ShouldStop()) {
        Input input_to_mutate = [&]() -> Input {
          // Try a brand new random element every now and then.
          // Otherwise, go to next corpus element in queue.
          if (stats_.runs > next_init) {
            next_init = stats_.runs + kRunsPerInit;
            return {params_domain_.Init(prng)};
          } else {
            size_t idx = static_cast<size_t>(corpus_distribution_(prng));
            FUZZTEST_INTERNAL_CHECK(0 <= idx && idx < corpus_.size(),
                                    "Corpus input weights are outdated!\n");
            return corpus_[idx];
          }
        }();
        constexpr int kMutationsPerInput = 32;
        for (int i = 0; i < kMutationsPerInput; ++i) {
          if (ShouldStop()) break;
          Input mutation = input_to_mutate;
          MutateValue(mutation, prng);
          TrySampleAndUpdateInMemoryCorpus(std::move(mutation));
        }
      }

      absl::FPrintF(GetStderr(), "\n[.] Fuzzing was terminated.\n");
      on_failure.PrintFinalStatsOnDefaultSink();
      absl::FPrintF(GetStderr(), "\n");
      return 0;
    }();
    fixture_driver_->TearDownFuzzTest();
    return exit_code;
  }

 private:
  using PRNG = std::mt19937;
  using ParamsDomain =
      decltype(std::declval<FixtureDriver<RegBase, Fixture, TargetFunction>>()
                   .GetDomains());
  using corpus_type = typename ParamsDomain::corpus_type;
  struct Input {
    corpus_type args;
    size_t depth = 0;
    absl::Duration run_time = absl::ZeroDuration();
  };

  struct RunResult {
    bool new_coverage;
    absl::Duration run_time;
  };

  void PopulateFromSeeds() {
    for (const auto& seed : fixture_driver_->GetSeeds()) {
      TrySampleAndUpdateInMemoryCorpus(Input{seed},
                                       /*write_to_file=*/false);
    }
  }

  bool ReplayInputsIfAvailable() {
    run_mode = RunMode::kFuzz;

    if (const auto replay_corpus = ReadReplayFile()) {
      for (const auto& corpus_value : *replay_corpus) {
        RunOneInput({corpus_value});
      }
      return true;
    }

    if (const auto to_minimize = ReadReproducerToMinimize()) {
      PRNG prng(seed_sequence());

      const auto original_serialized =
          params_domain_.SerializeCorpus(*to_minimize).ToString();

      // In minimize mode we keep mutating the given reproducer value with
      // `only_shrink=true` until we crash. We drop mutations that don't
      // actually change the value.
      // That way any crash is a smaller reproduction case.
      // We start with a lot of mutations which can speed up minimization.
      // We reduce the number of mutations if we can't find a crash, similar to
      // simulated annealing.
      int num_mutations = 20;
      while (true) {
        auto copy = *to_minimize;
        for (int i = 0; i < num_mutations; ++i) {
          params_domain_.Mutate(copy, prng, true);
        }
        num_mutations = std::max(1, num_mutations - 1);
        // We compare the serialized version. Not very efficient but works for
        // now.
        if (params_domain_.SerializeCorpus(copy).ToString() ==
            original_serialized)
          continue;
        RunOneInput({std::move(copy)});
      }
    }

    return false;
  }

  std::optional<std::vector<corpus_type>> ReadReplayFile() {
    auto file_or_dir = absl::NullSafeStringView(getenv("FUZZTEST_REPLAY"));
    if (file_or_dir.empty()) return std::nullopt;
    std::vector<corpus_type> result;
    for (const auto& [path, data] :
         ReadFileOrDirectory(std::string(file_or_dir))) {
      if (auto corpus_value = TryParse(data)) {
        result.push_back(*std::move(corpus_value));
      } else {
        absl::FPrintF(GetStderr(), "[!] Invalid input file %s.\n===\n%s\n===\n",
                      path, data);
        continue;
      }
    }
    return result;
  }

  std::optional<corpus_type> ReadReproducerToMinimize() {
    auto file =
        absl::NullSafeStringView(getenv("FUZZTEST_MINIMIZE_REPRODUCER"));
    if (file.empty()) return std::nullopt;
    auto data = ReadFile(std::string(file));

    if (!data) {
      FUZZTEST_INTERNAL_CHECK(false, "Failed to read minimizer file!");
    }

    auto res = TryParse(*data);
    if (!res) {
      absl::FPrintF(GetStderr(), "[!] Invalid input file %s.\n===\n%s\n===\n",
                    file, *data);
      FUZZTEST_INTERNAL_CHECK(false, "Failed to read minimizer file!");
    }
    return res;
  }

  std::optional<corpus_type> TryParse(std::string_view data) {
    if (auto parsed = IRObject::FromString(data)) {
      return params_domain_.ParseCorpus(*parsed);
    }
    return std::nullopt;
  }

  void MutateValue(Input& input, PRNG& prng) {
    // Do a random number of mutations on the value at once, skewed
    // towards 1 and decreasing probability as we go up.
    // Doing multiple smaller mutations at once allows reaching states that
    // require larger mutations.
    // The current implementation with a Poisson distribution has
    // probabilities:
    // - 1 mutation:  0.368
    // - 2 mutations: 0.368
    // - 3 mutations: 0.184
    // - 4 mutations: 0.061
    // - 5 mutations: 0.015
    // - 6 mutations: 0.003
    // ...
    // The distribution and parameters have not been benchmarked or
    // optimized in any significant way.
    for (int mutations_at_once = absl::Poisson<int>(prng) + 1;
         mutations_at_once > 0; --mutations_at_once) {
      params_domain_.Mutate(input.args, prng, /* only_shrink= */ false);
    }
  }

  void UpdateCorpusDistribution() {
    std::vector<double> weights(corpus_.size());
    absl::Duration average_time = absl::ZeroDuration();
    for (const Input& i : corpus_) {
      average_time += i.run_time;
    }
    average_time /= corpus_.size();
    // Prefer faster inputs than slower inputs, the maximum bias
    // is 30x. These weights are dynamic and won't make slow-but-interesting
    // inputs neglected: As more and more "slow but touched new coverage"
    // inputs come in, the average execution time will be larger and slow input
    // will get higher weights.
    for (size_t i = 0; i < corpus_.size(); ++i) {
      weights[i] = 100;
      if (corpus_[i].run_time > average_time * 10)
        weights[i] = 10;
      else if (corpus_[i].run_time > average_time * 4)
        weights[i] = 25;
      else if (corpus_[i].run_time > average_time * 2)
        weights[i] = 50;
      else if (corpus_[i].run_time * 3 > average_time * 4)
        weights[i] = 75;
      else if (corpus_[i].run_time * 4 < average_time)
        weights[i] = 300;
      else if (corpus_[i].run_time * 3 < average_time)
        weights[i] = 200;
      else if (corpus_[i].run_time * 2 < average_time)
        weights[i] = 150;
    }
    corpus_distribution_ =
        absl::discrete_distribution<>(weights.begin(), weights.end());
  }

  // Runs on `sample` and returns new coverage and run time. If there's new
  // coverage, outputs updated runtime stats. Additionally, if `write_to_file`
  // is true, tries to write the sample to a file.
  RunResult TrySample(const Input& sample, bool write_to_file = true) {
    RunResult run_result = RunOneInput(sample);
    if (!run_result.new_coverage) return run_result;

    if (write_to_file) TryWriteCorpusFile(sample);
    ++stats_.useful_inputs;
    stats_.edges_covered = corpus_coverage_.GetNumberOfCoveredEdges();
    const absl::Duration fuzzing_time = absl::Now() - stats_.start_time;
    const int64_t fuzzing_secs = absl::ToInt64Seconds(fuzzing_time);
    const int runs_per_sec =
        fuzzing_secs ? stats_.runs / fuzzing_secs : stats_.runs;
    absl::FPrintF(GetStderr(),
                  "[*] Corpus size: %5d | Edges covered: %6d | "
                  "Fuzzing time: %12s | Total runs:  %1.2e | Runs/secs: %5d\n",
                  stats_.useful_inputs, stats_.edges_covered,
                  absl::FormatDuration(fuzzing_time), stats_.runs,
                  runs_per_sec);
    return run_result;
  }

  // Runs on `sample` and records it into the in-memory corpus if it finds new
  // coverage. If `write_to_file` is set, tries to write the corpus data to a
  // file when recording it. Updates the memory dictionary on new coverage, and
  // occasionally even if there is no new coverage.
  void TrySampleAndUpdateInMemoryCorpus(Input sample,
                                        bool write_to_file = true) {
    auto [new_coverage, run_time] = TrySample(sample, write_to_file);
    if (execution_coverage_ != nullptr &&
        (stats_.runs % 4096 == 0 || new_coverage)) {
      params_domain_.UpdateMemoryDictionary(sample.args);
    }
    if (!new_coverage) return;
    // New coverage, update corpus and weights.
    sample.run_time = run_time;
    corpus_.push_back(std::move(sample));
    UpdateCorpusDistribution();
  }

  void ForEachInputFile(absl::Span<const std::string> files,
                        absl::FunctionRef<void(Input&&)> consume) {
    int parsed_input_counter = 0;
    int invalid_input_counter = 0;
    for (const auto& path : files) {
      std::optional<std::string> data = ReadFile(path);
      if (!data) continue;
      if (auto corpus_value = TryParse(*data)) {
        ++parsed_input_counter;
        consume(Input{*std::move(corpus_value)});
      } else {
        ++invalid_input_counter;
        absl::FPrintF(GetStderr(), "[!] Invalid input file %s.\n", path);
      }
    }
    absl::FPrintF(GetStderr(),
                  "[*] Parsed %d inputs and ignored %d inputs from the test "
                  "suite input dir.\n",
                  parsed_input_counter, invalid_input_counter);
  }

  // Returns true if we're in minimization mode.
  bool MinimizeCorpusIfInMinimizationMode(PRNG& prng) {
    auto inputdir =
        absl::NullSafeStringView(getenv("FUZZTEST_MINIMIZE_TESTSUITE_DIR"));
    if (inputdir.empty()) return false;
    std::vector<std::string> files = ListDirectory(std::string(inputdir));
    // Shuffle to potentially improve previously minimized corpus.
    std::shuffle(files.begin(), files.end(), prng);
    ForEachInputFile(files, [this](Input&& input) {
      TrySample(input, /*write_to_file=*/true);
    });
    return true;
  }

  std::vector<Input> TryReadCorpusFromFiles() {
    std::vector<Input> inputs;
    auto inputdir =
        absl::NullSafeStringView(getenv("FUZZTEST_TESTSUITE_IN_DIR"));
    if (inputdir.empty()) return inputs;
    std::vector<std::string> files = ListDirectory(std::string(inputdir));
    ForEachInputFile(files, [&inputs](Input&& input) {
      inputs.push_back(std::move(input));
    });
    return inputs;
  }

  void TryWriteCorpusFile(const Input& input) {
    if (corpus_out_dir_.empty()) return;
    if (WriteDataToDir(params_domain_.SerializeCorpus(input.args).ToString(),
                       corpus_out_dir_)
            .empty()) {
      absl::FPrintF(GetStderr(), "[!] Failed to write corpus file.\n");
    }
  }

  void InitializeCorpus(PRNG& prng) {
    std::vector<Input> inputs = TryReadCorpusFromFiles();
    // Since inputs processed earlier have the adventage of increasing coverage
    // and being kept in corpus, shuffle the input order to make it fair.
    std::shuffle(inputs.begin(), inputs.end(), prng);
    for (auto& input : inputs) {
      TrySampleAndUpdateInMemoryCorpus(std::move(input),
                                       /*write_to_file=*/false);
    }
    if (corpus_.empty()) {
      TrySampleAndUpdateInMemoryCorpus(Input{params_domain_.Init(prng)});
    }
  }

  RunResult RunOneInput(const Input& input) {
    ++stats_.runs;
    bool new_coverage = false;
    absl::Duration run_time;
    ApplyIndex<sizeof...(Args)>([&](auto... I) {
      auto args = params_domain_.GetValue(input.args);
      OnFailure::Args<ParamsDomain> debug_args{input.args, params_domain_};
      on_failure.SetCurrentArgs(&debug_args);

      // Reset and observe the coverage map and start tracing in
      // the tightest scope possible. In particular, we can't include the call
      // to GetValue in the scope as it will run user code.
      if (execution_coverage_ != nullptr) {
        execution_coverage_->ResetState();
      }
      absl::Time start = absl::Now();
      // Set tracing after absl::Now(), otherwise it will make
      // FuzzingModeTest.MinimizesDuplicatedCorpustest flaky because
      // randomness in absl::Now() being traced by cmp coverage.
      if (execution_coverage_ != nullptr) {
        execution_coverage_->SetIsTracing(true);
      }
      fixture_driver_->SetUpIteration();
      // ForceVectorForStringView is a temporary hack for realiably finding
      // buffer overflows. ASAN cannot detect small overflows in
      // std::string-s. See related bug at
      // https://bugs.llvm.org/show_bug.cgi?id=26380. As a temporary
      // workaround, we enable finding overflows by copying the contents
      // of the original string into a separate temporary heap buffer.
      // TODO(b/194687521): Remove this when we (or ASAN) detect overflows
      // in strings.
      fixture_driver_->Test(
          ForceVectorForStringView<Args>(std::get<I>(std::move(args)))...);
      fixture_driver_->TearDownIteration();
      if (execution_coverage_ != nullptr) {
        execution_coverage_->SetIsTracing(false);
      }
      run_time = absl::Now() - start;

      if (execution_coverage_ != nullptr) {
        new_coverage = corpus_coverage_.Update(execution_coverage_);
      }
      on_failure.UnsetCurrentArgs();
    });
    return {new_coverage, run_time};
  }

  bool ShouldStop() {
    if (runs_limit_.has_value() && stats_.runs >= *runs_limit_) return true;
    if (time_limit_ != absl::InfiniteFuture() && absl::Now() > time_limit_)
      return true;
    return termination_requested.load(std::memory_order_relaxed);
  }

  absl::SeedSeq& seed_sequence() {
    if (seed_sequence_.size() == 0) {
      seed_sequence_ = absl::MakeSeedSeq();
    }
    return seed_sequence_;
  }

  const FuzzTest& test_;
  std::unique_ptr<FixtureDriver<RegBase, Fixture, TargetFunction>>
      fixture_driver_;
  ParamsDomain params_domain_ = fixture_driver_->GetDomains();
  absl::SeedSeq seed_sequence_;
  ExecutionCoverage* execution_coverage_;
  CorpusCoverage corpus_coverage_;
  std::deque<Input> corpus_;
  // Corpus distribution is only used in Fuzzing mode.
  absl::discrete_distribution<> corpus_distribution_;

  std::string_view corpus_out_dir_;
  RuntimeStats stats_{};
  std::optional<size_t> runs_limit_;
  absl::Time time_limit_ = absl::InfiniteFuture();

#ifdef FUZZTEST_COMPATIBILITY_MODE
  friend class FuzzTestExternalEngineAdaptor<RegBase, Fixture, TargetFunction>;
#endif  // FUZZTEST_COMPATIBILITY_MODE
};

}  // namespace internal
}  // namespace fuzztest

#endif  // FUZZTEST_FUZZTEST_INTERNAL_RUNTIME_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Exceptional.Client.SampleWebsite.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ThrowException()
        {
            throw new Exception("Oh no, something went wrong! you'll need to check the inner exception.", new Exception("This was the root cause for the exception"));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="BlhRolMenu" table="blh_rol_menu">
    <id name="id" type="integer" column="id">
      <generator strategy="SEQUENCE"/>
    </id>
    <field name="usuario" type="integer" column="usuario" nullable="true"/>
    <many-to-one field="idMenu" target-entity="BlhMenu">
      <join-columns>
        <join-column name="id_menu" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="idRol" target-entity="BlhRol">
      <join-columns>
        <join-column name="id_rol" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using Azure.AI.TextAnalytics.Models;

namespace Azure.AI.TextAnalytics
{
    /// <summary>
    /// Collection of <see cref="JobMetadata"/> objects corresponding
    /// to a batch of documents, and information about the batch operation.
    /// </summary>
    public class AnalyzeOperationResult
    {
        /// <summary>
        /// </summary>
        /// <param name="jobState"></param>
        /// <param name="idToIndexMap"></param>
        internal AnalyzeOperationResult(AnalyzeJobState jobState, IDictionary<string, int> idToIndexMap)
        {
            Errors = Transforms.ConvertToErrors(jobState.Errors);
            Statistics = jobState.Statistics;
            DisplayName = jobState.DisplayName;
            Status = jobState.Status;
            Tasks = new AnalyzeTasks(jobState.Tasks, idToIndexMap);
        }

        /// <summary>
        /// Tasks
        /// </summary>
        public AnalyzeTasks Tasks { get; }

        /// <summary>
        /// DisplayName
        /// </summary>
        public string DisplayName { get; }

        /// <summary>
        /// Status
        /// </summary>
        public TextAnalyticsOperationStatus Status { get; }

        /// <summary>
        /// Errors for AnalyzeOperationResult
        /// </summary>
        public IReadOnlyList<TextAnalyticsError> Errors { get; }

        /// <summary> if showStats=true was specified in the request this field will contain information about the request payload. </summary>
        public TextDocumentBatchStatistics Statistics { get; }
    }
}


text:
class AddTypeToPatient < ActiveRecord::Migration
  def change
    add_column :patients, :type, :integer
  end
end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: List of All Members for QDomDocumentType</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

List of All Members for QDomDocumentType

This is the complete list of members for QDomDocumentType, including inherited members.

enum EncodingPolicy

enum NodeType

QDomDocumentType ()

QDomDocumentType ( const QDomDocumentType & )

appendChild ( const QDomNode & ) : QDomNode

attributes () const : QDomNamedNodeMap

childNodes () const : QDomNodeList

clear ()

cloneNode ( bool ) const : QDomNode

columnNumber () const : int

entities () const : QDomNamedNodeMap

firstChild () const : QDomNode

firstChildElement ( const QString & ) const : QDomElement

hasAttributes () const : bool

hasChildNodes () const : bool

insertAfter ( const QDomNode &, const QDomNode & ) : QDomNode

insertBefore ( const QDomNode &, const QDomNode & ) : QDomNode

internalSubset () const : QString

isAttr () const : bool

isCDATASection () const : bool

isCharacterData () const : bool

isComment () const : bool

isDocument () const : bool

isDocumentFragment () const : bool

isDocumentType () const : bool

isElement () const : bool

isEntity () const : bool

isEntityReference () const : bool

isNotation () const : bool

isNull () const : bool

isProcessingInstruction () const : bool

isSupported ( const QString &, const QString & ) const : bool

isText () const : bool

lastChild () const : QDomNode

lastChildElement ( const QString & ) const : QDomElement

lineNumber () const : int

localName () const : QString

name () const : QString

namedItem ( const QString & ) const : QDomNode

namespaceURI () const : QString

nextSibling () const : QDomNode

nextSiblingElement ( const QString & ) const : QDomElement

nodeName () const : QString

nodeType () const : QDomNode::NodeType

nodeValue () const : QString

normalize ()

notations () const : QDomNamedNodeMap

ownerDocument () const : QDomDocument

parentNode () const : QDomNode

prefix () const : QString

previousSibling () const : QDomNode

previousSiblingElement ( const QString & ) const : QDomElement

publicId () const : QString

removeChild ( const QDomNode & ) : QDomNode

replaceChild ( const QDomNode &, const QDomNode & ) : QDomNode

save ( QTextStream &, int ) const

save ( QTextStream &, int, EncodingPolicy ) const

setNodeValue ( const QString & )

setPrefix ( const QString & )

systemId () const : QString

toAttr () const : QDomAttr

toCDATASection () const : QDomCDATASection

toCharacterData () const : QDomCharacterData

toComment () const : QDomComment

toDocument () const : QDomDocument

toDocumentFragment () const : QDomDocumentFragment

toDocumentType () const : QDomDocumentType

toElement () const : QDomElement

toEntity () const : QDomEntity

toEntityReference () const : QDomEntityReference

toNotation () const : QDomNotation

toProcessingInstruction () const : QDomProcessingInstruction

toText () const : QDomText

operator!= ( const QDomNode & ) const : bool

operator= ( const QDomDocumentType & ) : QDomDocumentType &

operator== ( const QDomNode & ) const : bool

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
<!DOCTYPE html>

    <title>Dragonfly - Command Processor</title>
    <link rel="stylesheet" href="qunit/qunit.css" media="screen">

Dragonfly - Command Processor


text:
var fs = require('fs');
var path = require('path');

module.exports = function install(options) {

  // add local modules
  options.modules.forEach(function(module) {
    var modulePath = path.join(options.dir, module);
    options.pkg.dependencies[module] = 'file:' + modulePath;
    console.log('add local dependency:', module, ':', 'file:' + modulePath);
  });

  // write modified package.json
  fs.writeFileSync(options.packagePath, JSON.stringify(options.pkg, null, 2));

};


text:
import * as echarts from 'echarts';
import * as gexf from './gexf';
import prepareBoxplotData from './prepareBoxplotData';

export var version = '1.0.0';

export {gexf};

export {prepareBoxplotData};

// For backward compatibility, where the namespace `dataTool` will
// be mounted on `echarts` is the extension `dataTool` is imported.
// But the old version of echarts do not have `dataTool` namespace,
// so check it before mounting.
if (echarts.dataTool) {
    echarts.dataTool.version = version;
    echarts.dataTool.gexf = gexf;
    echarts.dataTool.prepareBoxplotData = prepareBoxplotData;
}


text:
require 'spec_helper'

require 'chef/knife/briefcase_put'

describe Chef::Knife::BriefcasePut do
  before do
    knife_config do
      briefcase_signers 'test+knife-briefcase-1@3ofcoins.net'
      briefcase_holders [
        'test+knife-briefcase-2@3ofcoins.net',
        'test+knife-briefcase-1@3ofcoins.net' ]
    end
  end

  it 'stores encrypted file to a data bag' do
    expect { knife('briefcase', 'put', 'an-item-id', __FILE__).zero? }

    briefcase = ridley.data_bag.find('briefcase')
    expect { briefcase }

    item = briefcase.item.find('an-item-id')
    expect { item }
    expect { item['id'] == 'an-item-id' }
    expect { item['content'] =~ /^-----BEGIN PGP MESSAGE-----/ }

    executed_block = false
    expect { crypto.decrypt(GPGME::Data.from_str(item['content'])).to_s == File.read(__FILE__) }

    _verify_yields = false
    expect { crypto.verify(GPGME::Data.from_str(item['content'])) { |sig| _verify_yields = true ; sig.valid? } }
    expect { _verify_yields }
  end

  it 'reads from stdin when no file given' do
    @knife_stdin = 'whatever'
    expect { knife('briefcase', 'put', 'an-item-id').zero? }

    encrypted = ridley.data_bag.find('briefcase').item.find('an-item-id')['content']
    expect { crypto.decrypt(GPGME::Data.from_str(encrypted)).to_s == 'whatever' }
  end

  it 'reads from stdin for file named "-"' do
    @knife_stdin = 'whatever'
    expect { knife('briefcase', 'put', 'an-item-id', '-').zero? }

    encrypted = ridley.data_bag.find('briefcase').item.find('an-item-id')['content']
    expect { crypto.decrypt(GPGME::Data.from_str(encrypted)).to_s == 'whatever' }
  end

  it 'overwrites previously stored value' do
    spec_helper = Pathname.new(__FILE__).dirname.dirname.dirname.join('spec_helper.rb')

    expect { knife('briefcase', 'put', 'an-item-id', __FILE__).zero? }
    expect { knife('briefcase', 'put', 'an-item-id', spec_helper.to_s).zero? }

    encrypted = ridley.data_bag.find('briefcase').item.find('an-item-id')['content']
    deny { crypto.decrypt(GPGME::Data.from_str(encrypted)).to_s == File.read(__FILE__) }
    expect { crypto.decrypt(GPGME::Data.from_str(encrypted)).to_s == spec_helper.read }
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Docs.MarkdownLite
{
    using System;
    using System.Collections.Immutable;
    using System.Linq;
    using System.Text.RegularExpressions;

    using Microsoft.Docs.MarkdownLite.Matchers;

    public class MarkdownNpTableBlockRule : IMarkdownRule
    {
        private static readonly Matcher _NpTableMatcher =
            // @" *\|?(.+)\n"
            Matcher.WhiteSpacesOrEmpty + Matcher.Char('|').Maybe() + Matcher.AnyCharNot('\n').RepeatAtLeast(1).ToGroup("header") + Matcher.NewLine +
            // @" *\|? *"
            Matcher.WhiteSpacesOrEmpty + Matcher.Char('|').Maybe() + Matcher.WhiteSpacesOrEmpty +
            // @"([-:]+ *\|[-| :]*)"
            (Matcher.AnyCharIn('-', ':').RepeatAtLeast(1) + Matcher.WhiteSpacesOrEmpty + '|' + Matcher.AnyCharIn('-', '|', ' ', ':').RepeatAtLeast(0)).ToGroup("align") +
            // @"\n"
            Matcher.NewLine +
            // @"((?:.*\|.*(?:\n|$))*)"
            (Matcher.AnyCharNotIn('\n', '|').RepeatAtLeast(0) + '|' + Matcher.AnyCharNot('\n').RepeatAtLeast(0) + (Matcher.NewLine | Matcher.EndOfString)).RepeatAtLeast(0).ToGroup("body") +
            // @"\n*"
            Matcher.NewLine.RepeatAtLeast(0);

        public virtual string Name => "NpTable";

        [Obsolete("Please use NewLineMatcher.")]
        public virtual Regex NpTable => Regexes.Block.Tables.NpTable;

        public virtual Matcher NpTableMatcher => _NpTableMatcher;

        public virtual IMarkdownToken TryMatch(IMarkdownParser parser, IMarkdownParsingContext context)
        {
            if (NpTable != Regexes.Block.Tables.NpTable || parser.Options.LegacyMode)
            {
                return TryMatchOld(parser, context);
            }
            var match = context.Match(NpTableMatcher);
            if (match?.Length > 0)
            {
                var header = match["header"].GetValue().ReplaceRegex(Regexes.Lexers.UselessTableHeader, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter);
                var align = ParseAligns(match["align"].GetValue().ReplaceRegex(Regexes.Lexers.UselessTableAlign, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter));
                if (header.Length > align.Length)
                {
                    return null;
                }
                var sourceInfo = context.Consume(match.Length);

                var rows = (from row in match["body"].GetValue().ReplaceRegex(Regexes.Lexers.EndWithNewLine, string.Empty).Split('\n')
                            select row.ReplaceRegex(Regexes.Lexers.UselessTableRow, string.Empty)).ToList();
                var cells = new string[rows.Count][];
                for (int i = 0; i < rows.Count; i++)
                {
                    var columns = rows[i].SplitRegex(Regexes.Lexers.TableSplitter);
                    if (columns.Length == header.Length)
                    {
                        cells[i] = columns;
                    }
                    else if (columns.Length < header.Length)
                    {
                        cells[i] = new string[header.Length];
                        for (int j = 0; j < columns.Length; j++)
                        {
                            cells[i][j] = columns[j];
                        }
                        for (int j = columns.Length; j < cells[i].Length; j++)
                        {
                            cells[i][j] = string.Empty;
                        }
                    }
                    else // columns.Length > header.Length
                    {
                        cells[i] = new string[header.Length];
                        for (int j = 0; j < header.Length; j++)
                        {
                            cells[i][j] = columns[j];
                        }
                    }
                }

                return new TwoPhaseBlockToken(
                    this,
                    parser.Context,
                    sourceInfo,
                    (p, t) =>
                        new MarkdownTableBlockToken(
                            t.Rule,
                            t.Context,
                            (from text in header
                             let si = t.SourceInfo.Copy(text)
                             select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray(),
                            align.ToImmutableArray(),
                            cells.Select(
                                (row, index) =>
                                    (from col in row
                                     let si = t.SourceInfo.Copy(col, index + 2)
                                     select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray()
                            ).ToImmutableArray(),
                            t.SourceInfo));
            }
            return null;
        }

        private IMarkdownToken TryMatchOld(IMarkdownParser parser, IMarkdownParsingContext context)
        {
            var match = NpTable.Match(context.CurrentMarkdown);
            if (match.Length == 0)
            {
                return null;
            }
            var header = match.Groups[1].Value.ReplaceRegex(Regexes.Lexers.UselessTableHeader, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter);
            var align = ParseAligns(match.Groups[2].Value.ReplaceRegex(Regexes.Lexers.UselessTableAlign, string.Empty).SplitRegex(Regexes.Lexers.TableSplitter));
            if (header.Length > align.Length)
            {
                return null;
            }
            var sourceInfo = context.Consume(match.Length);

            var rows = (from row in match.Groups[3].Value.ReplaceRegex(Regexes.Lexers.EndWithNewLine, string.Empty).Split('\n')
                        select row.ReplaceRegex(Regexes.Lexers.UselessTableRow, string.Empty)).ToList();
            var cells = new string[rows.Count][];
            for (int i = 0; i < rows.Count; i++)
            {
                var columns = rows[i].SplitRegex(Regexes.Lexers.TableSplitter);
                if (columns.Length == header.Length)
                {
                    cells[i] = columns;
                }
                else if (columns.Length < header.Length)
                {
                    cells[i] = new string[header.Length];
                    for (int j = 0; j < columns.Length; j++)
                    {
                        cells[i][j] = columns[j];
                    }
                    for (int j = columns.Length; j < cells[i].Length; j++)
                    {
                        cells[i][j] = string.Empty;
                    }
                }
                else // columns.Length > header.Length
                {
                    cells[i] = new string[header.Length];
                    for (int j = 0; j < header.Length; j++)
                    {
                        cells[i][j] = columns[j];
                    }
                }
            }

            return new TwoPhaseBlockToken(
                this,
                parser.Context,
                sourceInfo,
                (p, t) =>
                    new MarkdownTableBlockToken(
                        t.Rule,
                        t.Context,
                        (from text in header
                         let si = t.SourceInfo.Copy(text)
                         select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray(),
                        align.ToImmutableArray(),
                        cells.Select(
                            (row, index) =>
                                (from col in row
                                 let si = t.SourceInfo.Copy(col, index + 2)
                                 select new MarkdownTableItemBlockToken(t.Rule, t.Context, p.TokenizeInline(si), si)).ToImmutableArray()
                        ).ToImmutableArray(),
                        t.SourceInfo));
        }

        protected virtual Align[] ParseAligns(string[] aligns)
        {
            var result = new Align[aligns.Length];
            for (int i = 0; i < aligns.Length; i++)
            {
                if (Regexes.Lexers.TableAlignRight.IsMatch(aligns[i]))
                {
                    result[i] = Align.Right;
                }
                else if (Regexes.Lexers.TableAlignCenter.IsMatch(aligns[i]))
                {
                    result[i] = Align.Center;
                }
                else if (Regexes.Lexers.TableAlignLeft.IsMatch(aligns[i]))
                {
                    result[i] = Align.Left;
                }
                else
                {
                    result[i] = Align.NotSpec;
                }
            }
            return result;
        }
    }
}