For more Landlab tutorials, click here: https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html

This ipython notebook walks you through the basic procedure for writing a Landlab component, using the example of a kinematic-wave flow model.

A Landlab component is implemented as a Python `class`. Although every Landlab component is unique in some respects, to be a component, a class must have at least the following standard ingredients:

(1) The class must inherit the base class `Component`.

(2) The class must include a set of standard variables defined in the header (i.e., before the `__init__` method), which describe the data arrays that the component uses.

(3) The class must have an `__init__` method defined, with a semi-standardized parameter list described below.

(4) The class must provide a function that does performs the component's "action", typically named `run_one_step()` and this function's parameter list must follow the convention described below.

A Landlab component is a class that inherits from `Component`. The name of the class should be in CamelCase, and should make sense when used in the sentence: "A *(component-name)* is a...". The class definition should be followed by a docstring. The docstring should include a list of parameters for the `__init__` method and succintly describe them.

from landlab import Component, FieldError

Landlab component that implements a two-dimensional

You can put other information here... Anything you

think a user might need to know. We use numpy style

docstrings written in restructured text. You can use

precip_rate : float, optional (defaults to 1 mm/hr)

precip_duration : float, optional (defaults to 1 hour)

infilt_rate : float, optional (defaults to 0)

def __init__():  # ignore this for now, we will add more stuff eventually.

The following docstring section 'Examples' should help the user understand what is the component's purpose and how it works. It is an example (or examples) of its use in a (more or less) simple case within the Landlab framework: a grid is created, the component is instantiated on this grid and run. Unlike in the example below, we strongly recommend commenting your example(s) to explain what is happening.

This is also the section that will be run during the integration tests of your component (once you have submitted a pull request to have your component merged into the Landlab release branch). All lines starting with >>> are run and should produce the results you provided: here, the test will fail if `kw.vel_coeff` does not return `100.0.`

Every component should have a name, as a string. Normally this will be the same as the class name.

### Header information: `_unit_agnostic`

Components also indicate whether they are unit agnostic or not. Unit agnostic components require that component users are consistent with units within and across components used in a single application, but do not require that inputs conform to a specific set of units.

This component is not unit agnostic because it includes an assumption that time units will be in hours but assumes that the Manning coefficient will be provided with time units of seconds.

All the metadata about the fields that a components requires and creates is described in a datastructured called `Component._info`.

Info is a dictionary with one key for each field. The value associated with that key is a dictionary that must contain all of the following elements (and no other elements).

* "intent": a string indicating whether the field is an input ("in"), and output ("out"), or both ("inout")

* "optional": a boolean indicating whether the field is an optional input or output

* "units": a string indicating what units the field has (use "-")

* "mapping": a string indicating the grid element (e.g., node, cell) on which the field is located

The code in the Component base class will check things like:

* Can the component be created if all of the required inputs exist?

* Is all this information present? Is something extra present?

* Does the component create outputs of the correct dtype?

"doc": "Land surface topographic elevation",

"doc": "Gradient of the ground surface",

"doc": "flow discharge component in the direction of the link",

"doc": "flow velocity component in the direction of the link",

### Class with complete header information

from landlab import Component, FieldError

Landlab component that implements a two-dimensional

KinwaveOverlandFlowModel(grid, [stuff to be added later])

precip_rate : float, optional (defaults to 1 mm/hr)

precip_duration : float, optional (defaults to 1 hour)

infilt_rate : float, optional (defaults to 0)

## The initialization method (`__init__`)

Every Landlab component should have an `__init__` method. The parameter signature should start with a `ModelGrid` object as the first parameter. Following this are component-specific parameters. In our example, the parameters for the kinematic wave model include: precipiation rate, precipitation duration, infiltration rate, and roughness coefficient (Manning's n).

The first thing the component `__init__` should do is call the `super` method. This calls the `__init__` of the component's base class.

Two things a component `__init__` method common does are (1) store the component's parameters as class attributes, and (2) create the necessary fields. When creating grid fields, it is important to first check to see whether a field with the same name (and mapping) already exists. For example, a driver or another component might have already created `topographic__elevation` when our kinematic wave component is initialized.

self, grid, precip_rate=1.0, precip_duration=1.0, infilt_rate=0.0, roughness=0.01

# Store parameters and do unit conversion

self._precip = precip_rate / 3600000.0  # convert to m/s

self._precip_duration = precip_duration * 3600.0  # h->s

self._infilt = infilt_rate / 3600000.0  # convert to m/s

self._vel_coef = 1.0 / roughness  # do division now to save time

# Calculate the ground-surface slope (assume it won't change)

Every Landlab component will have a method that implements the component's action. The go method can have any name you like, but the preferred practice for time-advancing components is to use the standard name `run_one_step()`. Landlab assumes that if a component has a method with this name, it will (a) be the primary "go" method, and (b) will be fully standardized as described here.

The `run_one_step` method should take either zero or one argument. If there is an argument, it should be a duration to run, `dt`; i.e., a timestep length. If the component does not evolve as time passes, this argument may be missing (see, e.g., the FlowRouter, which returns a steady state flow pattern independent of time).

The first step in the algorithm in the example below is to calculate water depth *at the links*, where we will be calculating the water discharge. In this particular case, we'll use the depth at the upslope of the two nodes. The grid method to do this, `map_value_at_max_node_to_link`, is one of many mapping functions available.

We then calculate velocity using the Manning equation, and specific discharge by multiplying velocity by depth.

Mass balance for the cells around nodes is computed using the `calc_flux_div_at_node` grid method.

"""Calculate water flow for a time period `dt`.

# Calculate water depth at links. This implements an "upwind" scheme

# in which water depth at the links is the depth at the higher of the

# Calculate velocity using the Manning equation.

-self._sign_slope * self._vel_coef * H_link ** 0.66667 * self._sqrt_slope

if self._current_time < self._precip_duration:

# Update water depth: simple forward Euler scheme

self._depth[self._grid.core_nodes] += dHdt[self._grid.core_nodes] * dt

# Very crude numerical hack: prevent negative water depth

self._depth[np.where(self._depth < 0.0)[0]] = 0.0

Sometimes, (though not in this example), it proves convenient to hard-code assumptions about boundary conditions into the `__init__` method.

We can resolve this issue by creating an additional component method that updates these components that can be called if the boundary conditions change. Whether the boundary conditions have changed can be assessed with a grid method called `bc_set_code`. This is an `int` which will change if the boundary conditions change.

# Store grid and parameters and do unit conversion

"""Call if boundary conditions are updated.

# do things necessary if BCs are updated.

if self._bc_set_code != self.grid.bc_set_code:

"""Calculate water flow over topography.

Landlab component that implements a two-dimensional

kinematic wave model. This is an extremely simple, unsophisticated

model, originally built simply to demonstrate the component creation

process. Limitations to the present version include: infiltration is

handled very crudely, the called is responsible for picking a stable

time step size (no adaptive time stepping is used in the `run_one_step`

method), precipitation rate is constant for a given duration (then zero),

and all parameters are uniform in space. Also, the terrain is assumed

>>> rg = RasterModelGrid((4, 5), xy_spacing=10.0)

>>> z = rg.add_zeros("topographic__elevation", at="node")

>>> s = rg.add_zeros("topographic__gradient", at="link")

"doc": "Land surface topographic elevation",

"doc": "Gradient of the ground surface",

"doc": "flow velocity component in the direction of the link",

precip_rate : float, optional (defaults to 1 mm/hr)

precip_duration : float, optional (defaults to 1 hour)

infilt_rate : float, optional (defaults to 0)

# Store parameters and do unit conversion

self._precip = precip_rate / 3600000.0  # convert to m/s

self._precip_duration = precip_duration * 3600.0  # h->s

self._infilt = infilt_rate / 3600000.0  # convert to m/s

# Calculate the ground-surface slope (assume it won't change)

"""Calculate water flow for a time period `dt`.

# Calculate velocity using the Manning equation.

if self._current_time < self._precip_duration:

# Update water depth: simple forward Euler scheme

# Very crude numerical hack: prevent negative water depth

self._depth[np.where(self._depth < 0.0)[0]] = 0.0

kinflow = KinwaveOverlandFlowModel(rg, precip_rate=100.0, precip_duration=100.0)

print("The discharge from node 6 to node 5 should be -0.000278 m2/s:")

print("The discharge from node 5 to node 4 should be -0.000556 m2/s:")

Next, we'll test the component on a larger grid and a larger domain.

rg.at_node["topographic__elevation"] = 0.01 * rg.y_of_node

The steady solution should be as follows. The unit discharge at the bottom edge should equal the precipitation rate, 100 mm/hr, times the slope length.

The slope length is the distance from the bottom edge of the bottom-most row of cells, to the top edge of the top-most row of cells. The base row of nodes are at y = 0, and the cell edges start half a cell width up from that, so y = 5 m. The top of the upper-most row of cells is half a cell width below the top grid edge, which is 610 m, so the top of the cells is 605 m. Hence the interior (cell) portion of the grid is 600 m long.

Hence, discharge out the bottom should be 100 mm/hr x 600 m = 0.1 m/hr x 600 m = 60 m2/hr. Let's convert this to m2/s:

The water depth should be just sufficient to carry this discharge with the given slope and roughness. We get this by inverting the Manning equation:

The slope gradient is 0.01 (because we set elevation to be 0.01 times the y coordinate). The discharge, as we've already established, is about 0.0167 m2/s, and the roughness is 0.01 (the default value). Therefore,

This looks pretty good. Let's check the values:

rg.at_node["surface_water__depth"][42:84]  # bottom row of core nodes

We see that the depth agrees with the analytical solution to within three decimal places: not bad. Ideally, we would build the above tests into the component as doctests or unit tests. We could also test the transient solutions: rising hydrograph, falling hydrograph. Finally, we haven't tested all the ingredients; for example, we haven't tested what happens when infiltration rate is greater than zero.

Nonetheless, the above example illustrates the basics of component-making. A great next step would be to create a unit test based on this example.

### Click here for more [Landlab tutorials](https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html)


import unittest
from doctest import DocTestSuite
from test import support
import weakref
import gc

# Modules under test
_thread = support.import_module('_thread')
threading = support.import_module('threading')
import _threading_local

class Weak(object):
    pass

def target(local, weaklist):
    weak = Weak()
    local.weak = weak
    weaklist.append(weakref.ref(weak))

class BaseLocalTest:

    def test_local_refs(self):
        self._local_refs(20)
        self._local_refs(50)
        self._local_refs(100)

    def _local_refs(self, n):
        local = self._local()
        weaklist = []
        for i in range(n):
            t = threading.Thread(target=target, args=(local, weaklist))
            t.start()
            t.join()
        del t

        gc.collect()
        self.assertEqual(len(weaklist), n)

        # XXX _threading_local keeps the local of the last stopped thread alive.
        deadlist = [weak for weak in weaklist if weak() is None]
        self.assertIn(len(deadlist), (n-1, n))

        # Assignment to the same thread local frees it sometimes (!)
        local.someothervar = None
        gc.collect()
        deadlist = [weak for weak in weaklist if weak() is None]
        self.assertIn(len(deadlist), (n-1, n), (n, len(deadlist)))

    def test_derived(self):
        # Issue 3088: if there is a threads switch inside the __init__
        # of a threading.local derived class, the per-thread dictionary
        # is created but not correctly set on the object.
        # The first member set may be bogus.
        import time
        class Local(self._local):
            def __init__(self):
                time.sleep(0.01)
        local = Local()

        def f(i):
            local.x = i
            # Simply check that the variable is correctly set
            self.assertEqual(local.x, i)

        with support.start_threads(threading.Thread(target=f, args=(i,))
                                   for i in range(10)):
            pass

    def test_derived_cycle_dealloc(self):
        # http://bugs.python.org/issue6990
        class Local(self._local):
            pass
        locals = None
        passed = False
        e1 = threading.Event()
        e2 = threading.Event()

        def f():
            nonlocal passed
            # 1) Involve Local in a cycle
            cycle = [Local()]
            cycle.append(cycle)
            cycle[0].foo = 'bar'

            # 2) GC the cycle (triggers threadmodule.c::local_clear
            # before local_dealloc)
            del cycle
            gc.collect()
            e1.set()
            e2.wait()

            # 4) New Locals should be empty
            passed = all(not hasattr(local, 'foo') for local in locals)

        t = threading.Thread(target=f)
        t.start()
        e1.wait()

        # 3) New Locals should recycle the original's address. Creating
        # them in the thread overwrites the thread state and avoids the
        # bug
        locals = [Local() for i in range(10)]
        e2.set()
        t.join()

        self.assertTrue(passed)

    def test_arguments(self):
        # Issue 1522237
        class MyLocal(self._local):
            def __init__(self, *args, **kwargs):
                pass

        MyLocal(a=1)
        MyLocal(1)
        self.assertRaises(TypeError, self._local, a=1)
        self.assertRaises(TypeError, self._local, 1)

    def _test_one_class(self, c):
        self._failed = "No error message set or cleared."
        obj = c()
        e1 = threading.Event()
        e2 = threading.Event()

        def f1():
            obj.x = 'foo'
            obj.y = 'bar'
            del obj.y
            e1.set()
            e2.wait()

        def f2():
            try:
                foo = obj.x
            except AttributeError:
                # This is expected -- we haven't set obj.x in this thread yet!
                self._failed = ""  # passed
            else:
                self._failed = ('Incorrectly got value %r from class %r\n' %
                                (foo, c))
                sys.stderr.write(self._failed)

        t1 = threading.Thread(target=f1)
        t1.start()
        e1.wait()
        t2 = threading.Thread(target=f2)
        t2.start()
        t2.join()
        # The test is done; just let t1 know it can exit, and wait for it.
        e2.set()
        t1.join()

        self.assertFalse(self._failed, self._failed)

    def test_threading_local(self):
        self._test_one_class(self._local)

    def test_threading_local_subclass(self):
        class LocalSubclass(self._local):
            """To test that subclasses behave properly."""
        self._test_one_class(LocalSubclass)

    def _test_dict_attribute(self, cls):
        obj = cls()
        obj.x = 5
        self.assertEqual(obj.__dict__, {'x': 5})
        with self.assertRaises(AttributeError):
            obj.__dict__ = {}
        with self.assertRaises(AttributeError):
            del obj.__dict__

    def test_dict_attribute(self):
        self._test_dict_attribute(self._local)

    def test_dict_attribute_subclass(self):
        class LocalSubclass(self._local):
            """To test that subclasses behave properly."""
        self._test_dict_attribute(LocalSubclass)

    def test_cycle_collection(self):
        class X:
            pass

        x = X()
        x.local = self._local()
        x.local.x = x
        wr = weakref.ref(x)
        del x
        gc.collect()
        self.assertIs(wr(), None)

class ThreadLocalTest(unittest.TestCase, BaseLocalTest):
    _local = _thread._local

class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest):
    _local = _threading_local.local

def test_main():
    suite = unittest.TestSuite()
    suite.addTest(DocTestSuite('_threading_local'))
    suite.addTest(unittest.makeSuite(ThreadLocalTest))
    suite.addTest(unittest.makeSuite(PyThreadingLocalTest))

    local_orig = _threading_local.local
    def setUp(test):
        _threading_local.local = _thread._local
    def tearDown(test):
        _threading_local.local = local_orig
    suite.addTest(DocTestSuite('_threading_local',
                               setUp=setUp, tearDown=tearDown)
                  )

    support.run_unittest(suite)

if __name__ == '__main__':
    test_main()


/*
 * Copyright (C) 2010-2020 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "MessageNames.h"

namespace IPC {

const char* description(MessageName name)
{
    switch (name) {
    case MessageName::WebPage_AddEvent:
        return "WebPage_AddEvent";
    case MessageName::WebPage_Close:
        return "WebPage_Close";
    case MessageName::WebPage_CreatePlugin:
        return "WebPage_CreatePlugin";
    case MessageName::WebPage_DeprecatedOperation:
        return "WebPage_DeprecatedOperation";
    case MessageName::WebPage_DidCreateWebProcessConnection:
        return "WebPage_DidCreateWebProcessConnection";
    case MessageName::WebPage_DidReceivePolicyDecision:
        return "WebPage_DidReceivePolicyDecision";
    case MessageName::WebPage_ExperimentalOperation:
        return "WebPage_ExperimentalOperation";
    case MessageName::WebPage_GetPluginProcessConnection:
        return "WebPage_GetPluginProcessConnection";
    case MessageName::WebPage_GetPlugins:
        return "WebPage_GetPlugins";
    case MessageName::WebPage_InterpretKeyEvent:
        return "WebPage_InterpretKeyEvent";
    case MessageName::WebPage_LoadSomething:
        return "WebPage_LoadSomething";
    case MessageName::WebPage_LoadSomethingElse:
        return "WebPage_LoadSomethingElse";
    case MessageName::WebPage_LoadURL:
        return "WebPage_LoadURL";
    case MessageName::WebPage_PreferencesDidChange:
        return "WebPage_PreferencesDidChange";
    case MessageName::WebPage_RunJavaScriptAlert:
        return "WebPage_RunJavaScriptAlert";
    case MessageName::WebPage_SendDoubleAndFloat:
        return "WebPage_SendDoubleAndFloat";
    case MessageName::WebPage_SendInts:
        return "WebPage_SendInts";
    case MessageName::WebPage_SetVideoLayerID:
        return "WebPage_SetVideoLayerID";
    case MessageName::WebPage_TemplateTest:
        return "WebPage_TemplateTest";
    case MessageName::WebPage_TestAsyncMessage:
        return "WebPage_TestAsyncMessage";
    case MessageName::WebPage_TestAsyncMessageReply:
        return "WebPage_TestAsyncMessageReply";
    case MessageName::WebPage_TestAsyncMessageWithConnection:
        return "WebPage_TestAsyncMessageWithConnection";
    case MessageName::WebPage_TestAsyncMessageWithConnectionReply:
        return "WebPage_TestAsyncMessageWithConnectionReply";
    case MessageName::WebPage_TestAsyncMessageWithMultipleArguments:
        return "WebPage_TestAsyncMessageWithMultipleArguments";
    case MessageName::WebPage_TestAsyncMessageWithMultipleArgumentsReply:
        return "WebPage_TestAsyncMessageWithMultipleArgumentsReply";
    case MessageName::WebPage_TestAsyncMessageWithNoArguments:
        return "WebPage_TestAsyncMessageWithNoArguments";
    case MessageName::WebPage_TestAsyncMessageWithNoArgumentsReply:
        return "WebPage_TestAsyncMessageWithNoArgumentsReply";
    case MessageName::WebPage_TestMultipleAttributes:
        return "WebPage_TestMultipleAttributes";
    case MessageName::WebPage_TestParameterAttributes:
        return "WebPage_TestParameterAttributes";
    case MessageName::WebPage_TestSyncMessage:
        return "WebPage_TestSyncMessage";
    case MessageName::WebPage_TestSynchronousMessage:
        return "WebPage_TestSynchronousMessage";
    case MessageName::WebPage_TouchEvent:
        return "WebPage_TouchEvent";
    case MessageName::WrappedAsyncMessageForTesting:
        return "IPC::WrappedAsyncMessageForTesting";
    case MessageName::SyncMessageReply:
        return "IPC::SyncMessageReply";
    case MessageName::InitializeConnection:
        return "IPC::InitializeConnection";
    case MessageName::LegacySessionState:
        return "IPC::LegacySessionState";
    }
    ASSERT_NOT_REACHED();
    return "<invalid message name>";
}

ReceiverName receiverName(MessageName messageName)
{
    switch (messageName) {
    case MessageName::WebPage_AddEvent:
    case MessageName::WebPage_Close:
    case MessageName::WebPage_CreatePlugin:
    case MessageName::WebPage_DeprecatedOperation:
    case MessageName::WebPage_DidCreateWebProcessConnection:
    case MessageName::WebPage_DidReceivePolicyDecision:
    case MessageName::WebPage_ExperimentalOperation:
    case MessageName::WebPage_GetPluginProcessConnection:
    case MessageName::WebPage_GetPlugins:
    case MessageName::WebPage_InterpretKeyEvent:
    case MessageName::WebPage_LoadSomething:
    case MessageName::WebPage_LoadSomethingElse:
    case MessageName::WebPage_LoadURL:
    case MessageName::WebPage_PreferencesDidChange:
    case MessageName::WebPage_RunJavaScriptAlert:
    case MessageName::WebPage_SendDoubleAndFloat:
    case MessageName::WebPage_SendInts:
    case MessageName::WebPage_SetVideoLayerID:
    case MessageName::WebPage_TemplateTest:
    case MessageName::WebPage_TestMultipleAttributes:
    case MessageName::WebPage_TestParameterAttributes:
    case MessageName::WebPage_TouchEvent:
        return ReceiverName::WebPage;
    case MessageName::WebPage_TestAsyncMessageReply:
    case MessageName::WebPage_TestAsyncMessageWithConnectionReply:
    case MessageName::WebPage_TestAsyncMessageWithMultipleArgumentsReply:
    case MessageName::WebPage_TestAsyncMessageWithNoArgumentsReply:
        return ReceiverName::AsyncReply;
    case MessageName::WrappedAsyncMessageForTesting:
    case MessageName::SyncMessageReply:
    case MessageName::InitializeConnection:
    case MessageName::LegacySessionState:
        return ReceiverName::IPC;
    }
    ASSERT_NOT_REACHED();
    return ReceiverName::Invalid;
}

bool isValidMessageName(MessageName messageName)
{
    if (messageName == IPC::MessageName::WebPage_LoadURL)
        return true;
#if ENABLE(TEST_FEATURE)
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessage)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageReply)
        return true;
#endif
#if ENABLE(TEST_FEATURE)
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithNoArguments)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithNoArgumentsReply)
        return true;
#endif
#if ENABLE(TEST_FEATURE)
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithMultipleArguments)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithMultipleArgumentsReply)
        return true;
#endif
#if ENABLE(TEST_FEATURE)
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithConnection)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestAsyncMessageWithConnectionReply)
        return true;
#endif
    if (messageName == IPC::MessageName::WebPage_TestSyncMessage)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestSynchronousMessage)
        return true;
    if (messageName == IPC::MessageName::WebPage_LoadURL)
        return true;
#if ENABLE(TOUCH_EVENTS)
    if (messageName == IPC::MessageName::WebPage_LoadSomething)
        return true;
#endif
#if (ENABLE(TOUCH_EVENTS) && (NESTED_MESSAGE_CONDITION || SOME_OTHER_MESSAGE_CONDITION))
    if (messageName == IPC::MessageName::WebPage_TouchEvent)
        return true;
#endif
#if (ENABLE(TOUCH_EVENTS) && (NESTED_MESSAGE_CONDITION && SOME_OTHER_MESSAGE_CONDITION))
    if (messageName == IPC::MessageName::WebPage_AddEvent)
        return true;
#endif
#if ENABLE(TOUCH_EVENTS)
    if (messageName == IPC::MessageName::WebPage_LoadSomethingElse)
        return true;
#endif
    if (messageName == IPC::MessageName::WebPage_DidReceivePolicyDecision)
        return true;
    if (messageName == IPC::MessageName::WebPage_Close)
        return true;
    if (messageName == IPC::MessageName::WebPage_PreferencesDidChange)
        return true;
    if (messageName == IPC::MessageName::WebPage_SendDoubleAndFloat)
        return true;
    if (messageName == IPC::MessageName::WebPage_SendInts)
        return true;
    if (messageName == IPC::MessageName::WebPage_CreatePlugin)
        return true;
    if (messageName == IPC::MessageName::WebPage_RunJavaScriptAlert)
        return true;
    if (messageName == IPC::MessageName::WebPage_GetPlugins)
        return true;
    if (messageName == IPC::MessageName::WebPage_GetPluginProcessConnection)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestMultipleAttributes)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestParameterAttributes)
        return true;
    if (messageName == IPC::MessageName::WebPage_TemplateTest)
        return true;
    if (messageName == IPC::MessageName::WebPage_SetVideoLayerID)
        return true;
#if PLATFORM(MAC)
    if (messageName == IPC::MessageName::WebPage_DidCreateWebProcessConnection)
        return true;
#endif
#if PLATFORM(MAC)
    if (messageName == IPC::MessageName::WebPage_InterpretKeyEvent)
        return true;
#endif
#if ENABLE(DEPRECATED_FEATURE)
    if (messageName == IPC::MessageName::WebPage_DeprecatedOperation)
        return true;
#endif
#if ENABLE(EXPERIMENTAL_FEATURE)
    if (messageName == IPC::MessageName::WebPage_ExperimentalOperation)
        return true;
#endif
    if (messageName == IPC::MessageName::WebPage_LoadURL)
        return true;
#if ENABLE(TOUCH_EVENTS)
    if (messageName == IPC::MessageName::WebPage_LoadSomething)
        return true;
#endif
#if (ENABLE(TOUCH_EVENTS) && (NESTED_MESSAGE_CONDITION || SOME_OTHER_MESSAGE_CONDITION))
    if (messageName == IPC::MessageName::WebPage_TouchEvent)
        return true;
#endif
#if (ENABLE(TOUCH_EVENTS) && (NESTED_MESSAGE_CONDITION && SOME_OTHER_MESSAGE_CONDITION))
    if (messageName == IPC::MessageName::WebPage_AddEvent)
        return true;
#endif
#if ENABLE(TOUCH_EVENTS)
    if (messageName == IPC::MessageName::WebPage_LoadSomethingElse)
        return true;
#endif
    if (messageName == IPC::MessageName::WebPage_DidReceivePolicyDecision)
        return true;
    if (messageName == IPC::MessageName::WebPage_Close)
        return true;
    if (messageName == IPC::MessageName::WebPage_PreferencesDidChange)
        return true;
    if (messageName == IPC::MessageName::WebPage_SendDoubleAndFloat)
        return true;
    if (messageName == IPC::MessageName::WebPage_SendInts)
        return true;
    if (messageName == IPC::MessageName::WebPage_CreatePlugin)
        return true;
    if (messageName == IPC::MessageName::WebPage_RunJavaScriptAlert)
        return true;
    if (messageName == IPC::MessageName::WebPage_GetPlugins)
        return true;
    if (messageName == IPC::MessageName::WebPage_GetPluginProcessConnection)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestMultipleAttributes)
        return true;
    if (messageName == IPC::MessageName::WebPage_TestParameterAttributes)
        return true;
    if (messageName == IPC::MessageName::WebPage_TemplateTest)
        return true;
    if (messageName == IPC::MessageName::WebPage_SetVideoLayerID)
        return true;
#if PLATFORM(MAC)
    if (messageName == IPC::MessageName::WebPage_DidCreateWebProcessConnection)
        return true;
#endif
#if PLATFORM(MAC)
    if (messageName == IPC::MessageName::WebPage_InterpretKeyEvent)
        return true;
#endif
#if ENABLE(DEPRECATED_FEATURE)
    if (messageName == IPC::MessageName::WebPage_DeprecatedOperation)
        return true;
#endif
#if ENABLE(EXPERIMENTAL_FEATURE)
    if (messageName == IPC::MessageName::WebPage_ExperimentalOperation)
        return true;
#endif
    if (messageName == IPC::MessageName::WrappedAsyncMessageForTesting)
        return true;
    if (messageName == IPC::MessageName::SyncMessageReply)
        return true;
    if (messageName == IPC::MessageName::InitializeConnection)
        return true;
    if (messageName == IPC::MessageName::LegacySessionState)
        return true;
    return false;
};

} // namespace IPC


version https://git-lfs.github.com/spec/v1
oid sha256:51b316ed411dd2664185e042b3c6e100ddf32830eee4401923b575960522a82a
size 19419


#include "tommath_private.h"
#ifdef BN_MP_GCD_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */

/* Greatest Common Divisor using the binary method */
mp_err mp_gcd(const mp_int *a, const mp_int *b, mp_int *c)
{
   mp_int  u, v;
   int     k, u_lsb, v_lsb;
   mp_err err;

   /* either zero than gcd is the largest */
   if (MP_IS_ZERO(a)) {
      return mp_abs(b, c);
   }
   if (MP_IS_ZERO(b)) {
      return mp_abs(a, c);
   }

   /* get copies of a and b we can modify */
   if ((err = mp_init_copy(&u, a)) != MP_OKAY) {
      return err;
   }

   if ((err = mp_init_copy(&v, b)) != MP_OKAY) {
      goto LBL_U;
   }

   /* must be positive for the remainder of the algorithm */
   u.sign = v.sign = MP_ZPOS;

   /* B1.  Find the common power of two for u and v */
   u_lsb = mp_cnt_lsb(&u);
   v_lsb = mp_cnt_lsb(&v);
   k     = MP_MIN(u_lsb, v_lsb);

   if (k > 0) {
      /* divide the power of two out */
      if ((err = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
         goto LBL_V;
      }

      if ((err = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
         goto LBL_V;
      }
   }

   /* divide any remaining factors of two out */
   if (u_lsb != k) {
      if ((err = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
         goto LBL_V;
      }
   }

   if (v_lsb != k) {
      if ((err = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
         goto LBL_V;
      }
   }

   while (!MP_IS_ZERO(&v)) {
      /* make sure v is the largest */
      if (mp_cmp_mag(&u, &v) == MP_GT) {
         /* swap u and v to make sure v is >= u */
         mp_exch(&u, &v);
      }

      /* subtract smallest from largest */
      if ((err = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
         goto LBL_V;
      }

      /* Divide out all factors of two */
      if ((err = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
         goto LBL_V;
      }
   }

   /* multiply by 2**k which we divided out at the beginning */
   if ((err = mp_mul_2d(&u, k, c)) != MP_OKAY) {
      goto LBL_V;
   }
   c->sign = MP_ZPOS;
   err = MP_OKAY;
LBL_V:
   mp_clear(&u);
LBL_U:
   mp_clear(&v);
   return err;
}
#endif


/**
 * Copyright (c) 2001-2020 Mathew A. Nelson and Robocode contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * https://robocode.sourceforge.io/license/epl-v10.html
 */
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by jni4net. See http://jni4net.sourceforge.net/
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

package robocode.control.events;

@net.sf.jni4net.attributes.ClrTypeInfo
public final class BattleFinishedEvent_ {

    //<generated-static>
    private static system.Type staticType;

    public static system.Type typeof() {
        return robocode.control.events.BattleFinishedEvent_.staticType;
    }

    private static void InitJNI(net.sf.jni4net.inj.INJEnv env, system.Type staticType) {
        robocode.control.events.BattleFinishedEvent_.staticType = staticType;
    }
    //</generated-static>
}


/*
 * Copyright 2017 The Bazel Authors. All rights reserved.
 *
 * 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.
 */
package com.google.idea.blaze.aspect.java.filteredgenjar;

import static com.google.common.truth.Truth.assertThat;

import com.google.devtools.intellij.IntellijAspectTestFixtureOuterClass.IntellijAspectTestFixture;
import com.google.devtools.intellij.ideinfo.IntellijIdeInfo.TargetIdeInfo;
import com.google.idea.blaze.BazelIntellijAspectTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests the filtered gen-jar functionality */
@RunWith(JUnit4.class)
public class FilteredGenJarTest extends BazelIntellijAspectTest {

  @Test
  public void testFilteredGenJarNotCreatedForSourceOnlyRule() throws Exception {
    IntellijAspectTestFixture testFixture = loadTestFixture(":source_only_fixture");
    TargetIdeInfo targetIdeInfo = findTarget(testFixture, ":source_only");
    assertThat(targetIdeInfo.getJavaIdeInfo().hasFilteredGenJar()).isFalse();
  }

  @Test
  public void testFilteredGenJarNotCreatedForOnlyGenRule() throws Exception {
    IntellijAspectTestFixture testFixture = loadTestFixture(":gen_only_fixture");
    TargetIdeInfo targetIdeInfo = findTarget(testFixture, ":gen_only");
    assertThat(targetIdeInfo.getJavaIdeInfo().hasFilteredGenJar()).isFalse();
  }

  @Test
  public void testFilteredGenJar() throws Exception {
    IntellijAspectTestFixture testFixture = loadTestFixture(":mixed_fixture");
    TargetIdeInfo targetIdeInfo = findTarget(testFixture, ":mixed");
    assertThat(targetIdeInfo.getJavaIdeInfo().hasFilteredGenJar()).isTrue();
    assertThat(targetIdeInfo.getJavaIdeInfo().getFilteredGenJar().getJar().getRelativePath())
        .isEqualTo(testRelative("mixed-filtered-gen.jar"));
    assertThat(targetIdeInfo.getJavaIdeInfo().getFilteredGenJar().getSourceJar().getRelativePath())
        .isEqualTo(testRelative("mixed-filtered-gen-src.jar"));
  }
}


//
//  Filter.swift
//  Kingfisher
//
//  Created by Wei Wang on 2016/08/31.
//
//  Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

import CoreImage
import Accelerate

// Reuse the same CI Context for all CI drawing.
private let ciContext = CIContext(options: nil)

/// Transformer method which will be used in to provide a `Filter`.
public typealias Transformer = (CIImage) -> CIImage?

/// Supply a filter to create an `ImageProcessor`.
public protocol CIImageProcessor: ImageProcessor {
    var filter: Filter { get }
}

extension CIImageProcessor {
    public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
        switch item {
        case .image(let image):
            return image.kf.apply(filter)
        case .data(_):
            return (DefaultImageProcessor.default >> self).process(item: item, options: options)
        }
    }
}

/// Wrapper for a `Transformer` of CIImage filters.
public struct Filter {

    let transform: Transformer

    public init(tranform: @escaping Transformer) {
        self.transform = tranform
    }

    /// Tint filter which will apply a tint color to images.
    public static var tint: (Color) -> Filter = {
        color in
        Filter { input in
            let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
            colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)

            let colorImage = colorFilter.outputImage
            let filter = CIFilter(name: "CISourceOverCompositing")!
            filter.setValue(colorImage, forKey: kCIInputImageKey)
            filter.setValue(input, forKey: kCIInputBackgroundImageKey)
            #if swift(>=4.0)
            return filter.outputImage?.cropped(to: input.extent)
            #else
            return filter.outputImage?.cropping(to: input.extent)
            #endif
        }
    }

    public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)

    /// Color control filter which will apply color control change to images.
    public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
        let (brightness, contrast, saturation, inputEV) = arg
        return Filter { input in
            let paramsColor = [kCIInputBrightnessKey: brightness,
                               kCIInputContrastKey: contrast,
                               kCIInputSaturationKey: saturation]

            let paramsExposure = [kCIInputEVKey: inputEV]
            #if swift(>=4.0)
            let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
            return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
            #else
            let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
            return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
            #endif
        }

    }
}

extension Kingfisher where Base: Image {
    /// Apply a `Filter` containing `CIImage` transformer to `self`.
    ///
    /// - parameter filter: The filter used to transform `self`.
    ///
    /// - returns: A transformed image by input `Filter`.
    ///
    /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
    public func apply(_ filter: Filter) -> Image {

        guard let cgImage = cgImage else {
            assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
            return base
        }

        let inputImage = CIImage(cgImage: cgImage)
        guard let outputImage = filter.transform(inputImage) else {
            return base
        }

        guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
            assertionFailure("[Kingfisher] Can not make an tint image within context.")
            return base
        }

        #if os(macOS)
            return fixedForRetinaPixel(cgImage: result, to: size)
        #else
            return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
        #endif
    }

}


//
//  ChartTableViewCell.swift
//  PNChartSwift
//
//  Created by YiChen Zhou on 8/14/17.
//

import UIKit

class ChartTableViewCell: UITableViewCell {
    @IBOutlet weak var cellLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


name: test all
on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master
env:
  PRISMA_TELEMETRY_INFORMATION: "prisma-client-go test.yml"

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v1

      - uses: actions/setup-go@v2
        with:
          go-version: '1.14'

      - uses: actions/cache@v2
        with:
          path: |
            ~/go/pkg/mod
            ~/.cache
          restore-keys: ${{ runner.os }}-go-
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}

      - name: deps
        run: go mod download

      - name: generate
        run: go generate ./...
        env:
          DEBUG: "*"
          PHOTON_GO_LOG: true

      - name: setup
        run: go run ./test/setup/init setup
        env:
          PHOTON_GO_LOG: true

      - name: test
        run: go test ./... -v
        env:
          PHOTON_GO_LOG: true


/*
 * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.nio.file;

import java.io.IOException;

/**
 * An object that may be registered with a watch service so that it can be
 * watched for changes and events.
 *
 *
 This interface defines the {@link #register register} method to register
 * the object with a {@link WatchService} returning a {@link WatchKey} to
 * represent the registration. An object may be registered with more than one
 * watch service. Registration with a watch service is cancelled by invoking the
 * key's {@link WatchKey#cancel cancel} method.
 *
 * @since 1.7
 *
 * @see Path#register
 */

public interface Watchable {

    /**
     * Registers an object with a watch service.
     *
     *
 If the file system object identified by this object is currently
     * registered with the watch service then the watch key, representing that
     * registration, is returned after changing the event set or modifiers to
     * those specified by the {@code events} and {@code modifiers} parameters.
     * Changing the event set does not cause pending events for the object to be
     * discarded. Objects are automatically registered for the {@link
     * StandardWatchEventKinds#OVERFLOW OVERFLOW} event. This event is not
     * required to be present in the array of events.
     *
     *
 Otherwise the file system object has not yet been registered with the
     * given watch service, so it is registered and the resulting new key is
     * returned.
     *
     *
 Implementations of this interface should specify the events they
     * support.
     *
     * @param   watcher
     *          the watch service to which this object is to be registered
     * @param   events
     *          the events for which this object should be registered
     * @param   modifiers
     *          the modifiers, if any, that modify how the object is registered
     *
     * @return  a key representing the registration of this object with the
     *          given watch service
     *
     * @throws  UnsupportedOperationException
     *          if unsupported events or modifiers are specified
     * @throws  IllegalArgumentException
     *          if an invalid of combination of events are modifiers are specified
     * @throws  ClosedWatchServiceException
     *          if the watch service is closed
     * @throws  IOException
     *          if an I/O error occurs
     * @throws  SecurityException
     *          if a security manager is installed and it denies an unspecified
     *          permission required to monitor this object. Implementations of
     *          this interface should specify the permission checks.
     */
    WatchKey register(WatchService watcher,
                      WatchEvent.Kind<?>[] events,
                      WatchEvent.Modifier... modifiers)
        throws IOException;

    /**
     * Registers an object with a watch service.
     *
     *
 An invocation of this method behaves in exactly the same way as the
     * invocation
     *

     *     watchable.{@link #register(WatchService,WatchEvent.Kind[],WatchEvent.Modifier[]) register}(watcher, events, new WatchEvent.Modifier[0]);
     *

     *
     * @param   watcher
     *          the watch service to which this object is to be registered
     * @param   events
     *          the events for which this object should be registered
     *
     * @return  a key representing the registration of this object with the
     *          given watch service
     *
     * @throws  UnsupportedOperationException
     *          if unsupported events are specified
     * @throws  IllegalArgumentException
     *          if an invalid of combination of events are specified
     * @throws  ClosedWatchServiceException
     *          if the watch service is closed
     * @throws  IOException
     *          if an I/O error occurs
     * @throws  SecurityException
     *          if a security manager is installed and it denies an unspecified
     *          permission required to monitor this object. Implementations of
     *          this interface should specify the permission checks.
     */
    WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events)
        throws IOException;
}


<?php

switch($a) {
    case 1 :
    case 2 :
    case 3 :
    case 3 :
}

switch($b) {
    case 1 :
    case 2 :
    case 3 :
    default :
}

switch($c) {
    case 1 :
        break 1;
    case 2 :
        break 1;
    case 3 :
        break 1;
    case 3 :
        break 1;
    case 3 :
        break 1;
    case 3 :
        break 1;
    case 3 :
        break 1;
    case 3 :
        break 1;
}

?>


#! /bin/sh
# PCP QA Test No. 314
# Exercise pmie_daily functionality - log rotation
#
# Copyright (c) 2007 Aconex.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard filters
. ./common.product
. ./common.filter
. ./common.check

_cleanup()
{
    cd $here
    if $was_running
    then
	_restore_auto_restart pmie
	_service pmie start >>$here/$seq.full 2>&1
    else
	_service pmie stop >>$here/$seq.full 2>&1
	$sudo $PCP_BINADM_DIR/pmsignal -a -s TERM pmie >>$here/$seq.full 2>&1
	_wait_pmie_end
    fi
    $sudo rm -fr $tmp.*
    $sudo rm -fr /tmp/$seq;
}

# wait for a file to appear ...
#
_wait_for()
{
    _i=0
    while [ ! -f "$1" ]
    do
	_i=`expr $_i + 1`
	if [ "$_i" -ge 100 ]
	then
	    echo "_wait_for: failed to see file $1 after 100 iterations"
	    return
	fi
	pmsleep 0.1
    done
}

signal=$PCP_BINADM_DIR/pmsignal
status=1	# failure is the default!
trap "_cleanup;
exit \$status" 0 1 2 3 15

was_running=false
[ -f $PCP_RUN_DIR/pmie.pid ] && was_running=true

if $was_running
then
    _stop_auto_restart pmie
fi

# create a pmie config file, causing frequent output (to log)
cat > $tmp.config << EOF1
delta = 0.2 seconds;
fetched = simple.numfetch;
EOF1

echo "=== pmie config ===" >$seq.full
cat $tmp.config >>$seq.full

# create pmie control files and test out various good/bad conditions

cat > $tmp.control << EOF2
\$version=1.0
LOCALHOSTNAME n /tmp/$seq/1.good.log -v -c $tmp.config
EOF2

echo "=== pmie control ===" >>$seq.full
cat $tmp.control >>$seq.full

# real QA test starts here
_service pmie stop >>$seq.full
_wait_pmie_end
$sudo $signal -a -s TERM pmie 2>/dev/null
$sudo rm -fr /tmp/$seq && mkdir /tmp/$seq || exit 1
$sudo chown -R $PCP_USER:$PCP_GROUP /tmp/$seq
pmstore simple.numfetch 0 >/dev/null

# fire em all up
echo "Starting pmie process"
echo "=== pmie_check ===" >>$seq.full
touch $tmp.log
$sudo chown $PCP_USER:$PCP_GROUP $tmp.log
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmie_check -c $tmp.control -VV -l $tmp.log
$sudo cat $tmp.log >>$seq.full
_wait_for /tmp/$seq/1.good.log
ps $PCP_PS_ALL_FLAGS | grep '[p]mie' >>$seq.full
sleep 6		# fill original log a bit
cat /tmp/$seq/1.good.log >>$seq.full
ps $PCP_PS_ALL_FLAGS | grep '[p]mie' >>$seq.full

echo "Rotate, rotate..."
previous=`pmdate -1d %Y%m%d`
echo "=== pmie_daily ===" >>$seq.full
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmie_daily -c $tmp.control -VV -l $tmp.log
$sudo cat $tmp.log >>$seq.full
_wait_for /tmp/$seq/1.good.log
ps $PCP_PS_ALL_FLAGS | grep '[p]mie' >>$seq.full
sleep 3		# fill rotated log a bit

echo "Shutdown pmie process"
echo "=== pmie_check ===" >>$seq.full
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmie_check -c $tmp.control -s -VV -l $tmp.log
$sudo cat $tmp.log >>$seq.full
ps $PCP_PS_ALL_FLAGS | grep '[p]mie' >>$seq.full

grep rotated /tmp/$seq/1.good.log >/dev/null \
	|| echo "First log not rotated?"
grep rotated /tmp/$seq/1.good.log.$previous >/dev/null \
	|| echo "New log not started?"

# look for data in each log file, checking rotation actually did something
oldlines=`wc -l < /tmp/$seq/1.good.log.$previous 2>/dev/null || echo 0`
newlines=`wc -l < /tmp/$seq/1.good.log 2>/dev/null || echo 0`
# 5 samples / sec x ~6 sec x 2 lines per sample + 6 lines for header and footer
# so 66
_within_tolerance "Old logfile line count" "$oldlines" 66 %75 -v
# 5 samples / sec x ~3 sec x 2 lines per sample + 6 lines for header and footer
# so 36
_within_tolerance "New logfile line count" "$newlines" 36 %75 -v

echo "=== previous log ($oldlines lines) ===" >>$seq.full
cat /tmp/$seq/1.good.log.$previous >>$seq.full
echo "=== current log ($newlines lines) ===" >>$seq.full
cat /tmp/$seq/1.good.log >>$seq.full

# success, all done
status=0
exit


// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use buffer::{BufferResult, RefReadBuffer, RefWriteBuffer};
use cryptoutil::symm_enc_or_dec;

pub trait BlockEncryptor {
    fn block_size(&self) -> usize;
    fn encrypt_block(&self, input: &[u8], output: &mut [u8]);
}

pub trait BlockEncryptorX8 {
    fn block_size(&self) -> usize;
    fn encrypt_block_x8(&self, input: &[u8], output: &mut [u8]);
}

pub trait BlockDecryptor {
    fn block_size(&self) -> usize;
    fn decrypt_block(&self, input: &[u8], output: &mut [u8]);
}

pub trait BlockDecryptorX8 {
    fn block_size(&self) -> usize;
    fn decrypt_block_x8(&self, input: &[u8], output: &mut [u8]);
}

#[derive(Debug, Clone, Copy)]
pub enum SymmetricCipherError {
    InvalidLength,
    InvalidPadding
}

pub trait Encryptor {
    fn encrypt(&mut self, input: &mut RefReadBuffer, output: &mut RefWriteBuffer, eof: bool)
        -> Result<BufferResult, SymmetricCipherError>;
}

pub trait Decryptor {
    fn decrypt(&mut self, input: &mut RefReadBuffer, output: &mut RefWriteBuffer, eof: bool)
        -> Result<BufferResult, SymmetricCipherError>;
}

pub trait SynchronousStreamCipher {
    fn process(&mut self, input: &[u8], output: &mut [u8]);
}

// TODO - Its a bit unclear to me why this is necessary
impl SynchronousStreamCipher for Box<SynchronousStreamCipher + 'static> {
    fn process(&mut self, input: &[u8], output: &mut [u8]) {
        let me = &mut **self;
        me.process(input, output);
    }
}

impl Encryptor for Box<SynchronousStreamCipher + 'static> {
    fn encrypt(&mut self, input: &mut RefReadBuffer, output: &mut RefWriteBuffer, _: bool)
            -> Result<BufferResult, SymmetricCipherError> {
        symm_enc_or_dec(self, input, output)
    }
}

impl Decryptor for Box<SynchronousStreamCipher + 'static> {
    fn decrypt(&mut self, input: &mut RefReadBuffer, output: &mut RefWriteBuffer, _: bool)
            -> Result<BufferResult, SymmetricCipherError> {
        symm_enc_or_dec(self, input, output)
    }
}


# Copyright 2019 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.

# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.

defmodule GoogleApi.Monitoring.V3.Model.WindowsBasedSli do
  @moduledoc """
  A WindowsBasedSli defines good_service as the count of time windows for which the provided service was of good quality. Criteria for determining if service was good are embedded in the window_criterion.

  ## Attributes

  *   `goodBadMetricFilter` (*type:* `String.t`, *default:* `nil`) - A monitoring filter (https://cloud.google.com/monitoring/api/v3/filters) specifying a TimeSeries with ValueType = BOOL. The window is good if any true values appear in the window.
  *   `goodTotalRatioThreshold` (*type:* `GoogleApi.Monitoring.V3.Model.PerformanceThreshold.t`, *default:* `nil`) - A window is good if its performance is high enough.
  *   `metricMeanInRange` (*type:* `GoogleApi.Monitoring.V3.Model.MetricRange.t`, *default:* `nil`) - A window is good if the metric's value is in a good range, averaged across returned streams.
  *   `metricSumInRange` (*type:* `GoogleApi.Monitoring.V3.Model.MetricRange.t`, *default:* `nil`) - A window is good if the metric's value is in a good range, summed across returned streams.
  *   `windowPeriod` (*type:* `String.t`, *default:* `nil`) - Duration over which window quality is evaluated. Must be an integer fraction of a day and at least 60s.
  """

  use GoogleApi.Gax.ModelBase

  @type t :: %__MODULE__{
          :goodBadMetricFilter => String.t(),
          :goodTotalRatioThreshold => GoogleApi.Monitoring.V3.Model.PerformanceThreshold.t(),
          :metricMeanInRange => GoogleApi.Monitoring.V3.Model.MetricRange.t(),
          :metricSumInRange => GoogleApi.Monitoring.V3.Model.MetricRange.t(),
          :windowPeriod => String.t()
        }

  field(:goodBadMetricFilter)
  field(:goodTotalRatioThreshold, as: GoogleApi.Monitoring.V3.Model.PerformanceThreshold)
  field(:metricMeanInRange, as: GoogleApi.Monitoring.V3.Model.MetricRange)
  field(:metricSumInRange, as: GoogleApi.Monitoring.V3.Model.MetricRange)
  field(:windowPeriod)
end

defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.WindowsBasedSli do
  def decode(value, options) do
    GoogleApi.Monitoring.V3.Model.WindowsBasedSli.decode(value, options)
  end
end

defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.WindowsBasedSli do
  def encode(value, options) do
    GoogleApi.Gax.ModelBase.encode(value, options)
  end
end


#begin document (wb/sel/70/sel_7041); part 000
wb/sel/70/sel_7041   -1    0    [WORD]     XX   (TOP*          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    1    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    2    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    3    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    4    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    5    [WORD]   VERB       *      mingle  -   1   -   *   -
wb/sel/70/sel_7041   -1    6    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    7    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    8    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1    9    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   10    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   11    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   12    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   13    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   14    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   15    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   16    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   17    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   18    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   19    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   20    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   21    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   22    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   23    [WORD]     XX       *          -   -   -   -   *   -
wb/sel/70/sel_7041   -1   24    [WORD]     XX       *)         -   -   -   -   *   -

#end document


/*
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Authors: Hans-Peter Oeri (University of St.Gallen) <hp@oeri.ch>      |
   +----------------------------------------------------------------------+
 */

#include <stdlib.h>
#include <unicode/ures.h>
#include <unicode/uenum.h>

#include <zend.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include <php.h>

#include "php_intl.h"
#include "intl_data.h"
#include "intl_common.h"

#include "resourcebundle/resourcebundle.h"
#include "resourcebundle/resourcebundle_iterator.h"
#include "resourcebundle/resourcebundle_class.h"
#include "resourcebundle/resourcebundle_arginfo.h"

zend_class_entry *ResourceBundle_ce_ptr = NULL;

static zend_object_handlers ResourceBundle_object_handlers;

/* {{{ ResourceBundle_object_free */
static void ResourceBundle_object_free( zend_object *object )
{
	ResourceBundle_object *rb = php_intl_resourcebundle_fetch_object(object);

	// only free local errors
	intl_error_reset( INTL_DATA_ERROR_P(rb) );

	if (rb->me) {
		ures_close( rb->me );
	}
	if (rb->child) {
		ures_close( rb->child );
	}

	zend_object_std_dtor( &rb->zend );
}
/* }}} */

/* {{{ ResourceBundle_object_create */
static zend_object *ResourceBundle_object_create( zend_class_entry *ce )
{
	ResourceBundle_object *rb;

	rb = zend_object_alloc(sizeof(ResourceBundle_object), ce);

	zend_object_std_init( &rb->zend, ce );
	object_properties_init( &rb->zend, ce);

	intl_error_init( INTL_DATA_ERROR_P(rb) );
	rb->me = NULL;
	rb->child = NULL;

	rb->zend.handlers = &ResourceBundle_object_handlers;

	return &rb->zend;
}
/* }}} */

/* {{{ ResourceBundle_ctor */
static int resourcebundle_ctor(INTERNAL_FUNCTION_PARAMETERS)
{
	const char *bundlename;
	size_t		bundlename_len = 0;
	const char *locale;
	size_t		locale_len = 0;
	zend_bool	fallback = 1;

	zval                  *object = return_value;
	ResourceBundle_object *rb = Z_INTL_RESOURCEBUNDLE_P( object );

	intl_error_reset( NULL );

	if( zend_parse_parameters( ZEND_NUM_ARGS(), "s!s!|b",
		&locale, &locale_len, &bundlename, &bundlename_len, &fallback ) == FAILURE )
	{
		return FAILURE;
	}

	if (rb->me) {
		zend_throw_error(NULL, "ResourceBundle object is already constructed");
		return FAILURE;
	}

	INTL_CHECK_LOCALE_LEN_OR_FAILURE(locale_len);

	if (locale == NULL) {
		locale = intl_locale_get_default();
	}

	if (bundlename_len >= MAXPATHLEN) {
		zend_argument_value_error(2, "is too long");
		return FAILURE;
	}

	if (fallback) {
		rb->me = ures_open(bundlename, locale, &INTL_DATA_ERROR_CODE(rb));
	} else {
		rb->me = ures_openDirect(bundlename, locale, &INTL_DATA_ERROR_CODE(rb));
	}

	INTL_CTOR_CHECK_STATUS(rb, "resourcebundle_ctor: Cannot load libICU resource bundle");

	if (!fallback && (INTL_DATA_ERROR_CODE(rb) == U_USING_FALLBACK_WARNING ||
			INTL_DATA_ERROR_CODE(rb) == U_USING_DEFAULT_WARNING)) {
		char *pbuf;
		intl_errors_set_code(NULL, INTL_DATA_ERROR_CODE(rb));
		spprintf(&pbuf, 0, "resourcebundle_ctor: Cannot load libICU resource "
				"'%s' without fallback from %s to %s",
				bundlename ? bundlename : "(default data)", locale,
				ures_getLocaleByType(
					rb->me, ULOC_ACTUAL_LOCALE, &INTL_DATA_ERROR_CODE(rb)));
		intl_errors_set_custom_msg(INTL_DATA_ERROR_P(rb), pbuf, 1);
		efree(pbuf);
		return FAILURE;
	}

	return SUCCESS;
}
/* }}} */

/* {{{ ResourceBundle object constructor */
PHP_METHOD( ResourceBundle, __construct )
{
	zend_error_handling error_handling;

	zend_replace_error_handling(EH_THROW, IntlException_ce_ptr, &error_handling);
	return_value = ZEND_THIS;
	if (resourcebundle_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU) == FAILURE) {
		if (!EG(exception)) {
			zend_throw_exception(IntlException_ce_ptr, "Constructor failed", 0);
		}
	}
	zend_restore_error_handling(&error_handling);
}
/* }}} */

/* {{{ */
PHP_FUNCTION( resourcebundle_create )
{
	object_init_ex( return_value, ResourceBundle_ce_ptr );
	if (resourcebundle_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU) == FAILURE) {
		zval_ptr_dtor(return_value);
		RETURN_NULL();
	}
}
/* }}} */

/* {{{ resourcebundle_array_fetch */
static void resourcebundle_array_fetch(zend_object *object, zval *offset, zval *return_value, int fallback)
{
	int32_t     meindex = 0;
	char *      mekey = NULL;
    zend_bool    is_numeric = 0;
	char         *pbuf;
	ResourceBundle_object *rb;

	intl_error_reset( NULL );
	rb = php_intl_resourcebundle_fetch_object(object);

	if(Z_TYPE_P(offset) == IS_LONG) {
		is_numeric = 1;
		meindex = (int32_t)Z_LVAL_P(offset);
		rb->child = ures_getByIndex( rb->me, meindex, rb->child, &INTL_DATA_ERROR_CODE(rb) );
	} else if(Z_TYPE_P(offset) == IS_STRING) {
		mekey = Z_STRVAL_P(offset);
		rb->child = ures_getByKey(rb->me, mekey, rb->child, &INTL_DATA_ERROR_CODE(rb) );
	} else {
		intl_errors_set(INTL_DATA_ERROR_P(rb), U_ILLEGAL_ARGUMENT_ERROR,
			"resourcebundle_get: index should be integer or string", 0);
		RETURN_NULL();
	}

	intl_error_set_code( NULL, INTL_DATA_ERROR_CODE(rb) );
	if (U_FAILURE(INTL_DATA_ERROR_CODE(rb))) {
		if (is_numeric) {
			spprintf( &pbuf, 0, "Cannot load resource element %d", meindex );
		} else {
			spprintf( &pbuf, 0, "Cannot load resource element '%s'", mekey );
		}
		intl_errors_set_custom_msg( INTL_DATA_ERROR_P(rb), pbuf, 1 );
		efree(pbuf);
		RETURN_NULL();
	}

	if (!fallback && (INTL_DATA_ERROR_CODE(rb) == U_USING_FALLBACK_WARNING || INTL_DATA_ERROR_CODE(rb) == U_USING_DEFAULT_WARNING)) {
		UErrorCode icuerror;
		const char * locale = ures_getLocaleByType( rb->me, ULOC_ACTUAL_LOCALE, &icuerror );
		if (is_numeric) {
			spprintf( &pbuf, 0, "Cannot load element %d without fallback from to %s", meindex, locale );
		} else {
			spprintf( &pbuf, 0, "Cannot load element '%s' without fallback from to %s", mekey, locale );
		}
		intl_errors_set_custom_msg( INTL_DATA_ERROR_P(rb), pbuf, 1 );
		efree(pbuf);
		RETURN_NULL();
	}

	resourcebundle_extract_value( return_value, rb );
}
/* }}} */

/* {{{ resourcebundle_array_get */
zval *resourcebundle_array_get(zend_object *object, zval *offset, int type, zval *rv)
{
	if(offset == NULL) {
		php_error( E_ERROR, "Cannot apply [] to ResourceBundle object" );
	}
	ZVAL_NULL(rv);
	resourcebundle_array_fetch(object, offset, rv, 1);
	return rv;
}
/* }}} */

/* {{{ Get resource identified by numerical index or key name. */
PHP_FUNCTION( resourcebundle_get )
{
	zend_bool   fallback = 1;
	zval *		offset;
	zval *      object;

	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oz|b",	&object, ResourceBundle_ce_ptr, &offset, &fallback ) == FAILURE) {
		RETURN_THROWS();
	}

	resourcebundle_array_fetch(Z_OBJ_P(object), offset, return_value, fallback);
}
/* }}} */

/* {{{ resourcebundle_array_count */
int resourcebundle_array_count(zend_object *object, zend_long *count)
{
	ResourceBundle_object *rb = php_intl_resourcebundle_fetch_object(object);

	if (rb->me == NULL) {
		intl_errors_set(&rb->error, U_ILLEGAL_ARGUMENT_ERROR,
				"Found unconstructed ResourceBundle", 0);
		return 0;
	}

	*count = ures_getSize( rb->me );

	return SUCCESS;
}
/* }}} */

/* {{{ Get resources count */
PHP_FUNCTION( resourcebundle_count )
{
	int32_t                len;
	RESOURCEBUNDLE_METHOD_INIT_VARS;

	if( zend_parse_method_parameters( ZEND_NUM_ARGS(), getThis(), "O", &object, ResourceBundle_ce_ptr ) == FAILURE ) {
		RETURN_THROWS();
	}

	RESOURCEBUNDLE_METHOD_FETCH_OBJECT;

	len = ures_getSize( rb->me );
	RETURN_LONG( len );
}

/* {{{ Get available locales from ResourceBundle name */
PHP_FUNCTION( resourcebundle_locales )
{
	char * bundlename;
	size_t    bundlename_len = 0;
	const char * entry;
	int entry_len;
	UEnumeration *icuenum;
	UErrorCode   icuerror = U_ZERO_ERROR;

	intl_errors_reset( NULL );

	if( zend_parse_parameters(ZEND_NUM_ARGS(), "s", &bundlename, &bundlename_len ) == FAILURE )
	{
		RETURN_THROWS();
	}

	if (bundlename_len >= MAXPATHLEN) {
		zend_argument_value_error(1, "is too long");
		RETURN_THROWS();
	}

	if(bundlename_len == 0) {
		// fetch default locales list
		bundlename = NULL;
	}

	icuenum = ures_openAvailableLocales( bundlename, &icuerror );
	INTL_CHECK_STATUS(icuerror, "Cannot fetch locales list");

	uenum_reset( icuenum, &icuerror );
	INTL_CHECK_STATUS(icuerror, "Cannot iterate locales list");

	array_init( return_value );
	while ((entry = uenum_next( icuenum, &entry_len, &icuerror ))) {
		add_next_index_stringl( return_value, (char *) entry, entry_len);
	}
	uenum_close( icuenum );
}
/* }}} */

/* {{{ Get text description for ResourceBundle's last error code. */
PHP_FUNCTION( resourcebundle_get_error_code )
{
	RESOURCEBUNDLE_METHOD_INIT_VARS;

	if( zend_parse_method_parameters( ZEND_NUM_ARGS(), getThis(), "O",
		&object, ResourceBundle_ce_ptr ) == FAILURE )
	{
		RETURN_THROWS();
	}

	rb = Z_INTL_RESOURCEBUNDLE_P( object );

	RETURN_LONG(INTL_DATA_ERROR_CODE(rb));
}
/* }}} */

/* {{{ Get text description for ResourceBundle's last error. */
PHP_FUNCTION( resourcebundle_get_error_message )
{
	zend_string* message = NULL;
	RESOURCEBUNDLE_METHOD_INIT_VARS;

	if( zend_parse_method_parameters( ZEND_NUM_ARGS(), getThis(), "O",
		&object, ResourceBundle_ce_ptr ) == FAILURE )
	{
		RETURN_THROWS();
	}

	rb = Z_INTL_RESOURCEBUNDLE_P( object );
	message = intl_error_get_message(INTL_DATA_ERROR_P(rb));
	RETURN_STR(message);
}
/* }}} */

PHP_METHOD(ResourceBundle, getIterator) {
	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}

	zend_create_internal_iterator_zval(return_value, ZEND_THIS);
}

/* {{{ resourcebundle_register_class
 * Initialize 'ResourceBundle' class
 */
void resourcebundle_register_class( void )
{
	zend_class_entry ce;

	INIT_CLASS_ENTRY( ce, "ResourceBundle", class_ResourceBundle_methods );

	ce.create_object = ResourceBundle_object_create;
	ce.get_iterator = resourcebundle_get_iterator;

	ResourceBundle_ce_ptr = zend_register_internal_class( &ce );

	ResourceBundle_object_handlers = std_object_handlers;
	ResourceBundle_object_handlers.offset = XtOffsetOf(ResourceBundle_object, zend);
	ResourceBundle_object_handlers.clone_obj	  = NULL; /* ICU ResourceBundle has no clone implementation */
	ResourceBundle_object_handlers.free_obj = ResourceBundle_object_free;
	ResourceBundle_object_handlers.read_dimension = resourcebundle_array_get;
	ResourceBundle_object_handlers.count_elements = resourcebundle_array_count;

	zend_class_implements(ResourceBundle_ce_ptr, 2, zend_ce_aggregate, zend_ce_countable);
}
/* }}} */


#include <hadouken/scripting/modules/bittorrent/feed_handle_wrapper.hpp>

#include <hadouken/scripting/modules/bittorrent/feed_status_wrapper.hpp>
#include <libtorrent/rss.hpp>

#include "../common.hpp"
#include "../../duktape.h"

using namespace hadouken::scripting::modules;
using namespace hadouken::scripting::modules::bittorrent;

void feed_handle_wrapper::initialize(duk_context* ctx, const libtorrent::feed_handle& handle)
{
    static duk_function_list_entry functions[] =
    {
        { "updateFeed",  update_feed,     0 },
        { "getStatus",   get_feed_status, 0 },
        { "getSettings", get_settings,    0 },
        { "setSettings", set_settings,    1 },
        { NULL,          NULL,            0 }
    };

    duk_idx_t idx = duk_push_object(ctx);
    duk_put_function_list(ctx, idx, functions);

    common::set_pointer<libtorrent::feed_handle>(ctx, idx, new libtorrent::feed_handle(handle));

    duk_push_c_function(ctx, finalize, 1);
    duk_set_finalizer(ctx, -2);
}

duk_ret_t feed_handle_wrapper::finalize(duk_context* ctx)
{
    common::finalize<libtorrent::feed_handle>(ctx);
    return 0;
}

duk_ret_t feed_handle_wrapper::update_feed(duk_context* ctx)
{
    return 0;
}

duk_ret_t feed_handle_wrapper::get_feed_status(duk_context* ctx)
{
    libtorrent::feed_handle* handle = common::get_pointer<libtorrent::feed_handle>(ctx);
    feed_status_wrapper::initialize(ctx, handle->get_feed_status());
    return 1;
}

duk_ret_t feed_handle_wrapper::get_settings(duk_context* ctx)
{
    return 0;
}

duk_ret_t feed_handle_wrapper::set_settings(duk_context* ctx)
{
    return 0;
}


load("@prysm//tools/go:def.bzl", "go_library")

go_library(
    name = "go_default_library",
    srcs = [
        "protector_mock.go",
        "slasher_mock.go",
    ],
    importpath = "github.com/prysmaticlabs/prysm/validator/testing",
    visibility = ["//validator:__subpackages__"],
    deps = [
        "//proto/slashing:go_default_library",
        "@com_github_golang_protobuf//proto:go_default_library",
        "@com_github_prysmaticlabs_ethereumapis//eth/v1alpha1:go_default_library",
        "@org_golang_google_grpc//:go_default_library",
    ],
)


/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * 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.
 */

package android.sax;

/**
 * Listens for the end of elements.
 */
public interface EndElementListener {

    /**
     * Invoked at the end of an element.
     */
    void end();
}


			Application Log

	    Timestamp
		Level
		Category
		Message

<?php
$colors=array(
	CLogger::LEVEL_PROFILE=>'#DFFFE0',
	CLogger::LEVEL_INFO=>'#FFFFDF',
	CLogger::LEVEL_WARNING=>'#FFDFE5',
	CLogger::LEVEL_ERROR=>'#FFC0CB',
);
foreach($data as $index=>$log)
{
	$color=($index%2)?'#F5F5F5':'#FFFFFF';
	if(isset($colors[$log[1]]))
		$color=$colors[$log[1]];
	$message='
'.CHtml::encode(wordwrap($log[0])).'
';
	$time=date('H:i:s.',$log[3]).(int)(($log[3]-(int)$log[3])*1000000);

	echo <<<EOD

		{$time}
		{$log[1]}
		{$log[2]}
		{$message}

EOD;
}
?>


<?php

/*
 * This file is part of SwiftMailer.
 * (c) 2004-2009 Chris Corbyn
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Header Signer Interface used to apply Header-Based Signature to a message
 *
 * @package    Swift
 * @subpackage Signatures
 * @author     Xavier De Cock <xdecock@gmail.com>
 */
interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream
{
    /**
     * Exclude an header from the signed headers
     *
     * @param string $header_name
     *
     * @return Swift_Signers_HeaderSigner
     */
    public function ignoreHeader($header_name);

    /**
     * Prepare the Signer to get a new Body
     *
     * @return Swift_Signers_HeaderSigner
     */
    public function startBody();

    /**
     * Give the signal that the body has finished streaming
     *
     * @return Swift_Signers_HeaderSigner
     */
    public function endBody();

    /**
     * Give the headers already given
     *
     * @param Swift_Mime_SimpleHeaderSet $headers
     *
     * @return Swift_Signers_HeaderSigner
     */
    public function setHeaders(Swift_Mime_HeaderSet $headers);

    /**
     * Add the header(s) to the headerSet
     *
     * @param Swift_Mime_HeaderSet $headers
     *
     * @return Swift_Signers_HeaderSigner
     */
    public function addSignature(Swift_Mime_HeaderSet $headers);

    /**
     * Return the list of header a signer might tamper
     *
     * @return array
     */
    public function getAlteredHeaders();
}


# Sales Sequence Functional Tests

The Functional Test Module for **Magento Sales Sequence** module.


/**
 ******************************************************************************
 *
 * @file       instrumentation.c
 * @author     The OpenPilot Team, http://www.openpilot.org Copyright (C) 2014.
 * @brief      Instrumentation infrastructure
 *             UAVObject wrapper layer for PiOS instrumentation
 * @see        The GNU Public License (GPL) Version 3
 *
 *****************************************************************************/
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <openpilot.h>
#include <instrumentation.h>
#include <pios_instrumentation.h>

static uint8_t publishedCountersInstances = 0;
static void counterCallback(const pios_perf_counter_t *counter, const int8_t index, void *context);
static xSemaphoreHandle sem;
void InstrumentationInit()
{
    PerfCounterInitialize();
    publishedCountersInstances = 1;
    vSemaphoreCreateBinary(sem);
}

void InstrumentationPublishAllCounters()
{
    if (xSemaphoreTake(sem, 0) != pdTRUE) {
        return;
    }
    PIOS_Instrumentation_ForEachCounter(&counterCallback, NULL);
    xSemaphoreGive(sem);
}

void counterCallback(const pios_perf_counter_t *counter, const int8_t index, __attribute__((unused)) void *context)
{
    if (publishedCountersInstances < index + 1) {
        PerfCounterCreateInstance();
        publishedCountersInstances++;
    }
    PerfCounterData data;
    data.Id = counter->id;
    data.Counter.Max   = counter->max;
    data.Counter.Min   = counter->min;
    data.Counter.Value = counter->value;
    PerfCounterInstSet(index, &data);
}


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util;

use function array_keys;
use function array_reverse;
use function defined;
use function get_defined_constants;
use function get_included_files;
use function in_array;
use function ini_get_all;
use function is_array;
use function is_file;
use function is_scalar;
use function preg_match;
use function serialize;
use function sprintf;
use function strpos;
use function var_export;
use Closure;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class GlobalState
{
    /**
     * @var string[]
     */
    private const SUPER_GLOBAL_ARRAYS = [
        '_ENV',
        '_POST',
        '_GET',
        '_COOKIE',
        '_SERVER',
        '_FILES',
        '_REQUEST',
    ];

    /**
     * @throws Exception
     */
    public static function getIncludedFilesAsString(): string
    {
        return self::processIncludedFilesAsString(get_included_files());
    }

    /**
     * @param string[] $files
     *
     * @throws Exception
     */
    public static function processIncludedFilesAsString(array $files): string
    {
        $excludeList = new ExcludeList;
        $prefix      = false;
        $result      = '';

        if (defined('__PHPUNIT_PHAR__')) {
            $prefix = 'phar://' . __PHPUNIT_PHAR__ . '/';
        }

        // Do not process bootstrap script
        unset($files[0]);

        foreach (array_reverse($files) as $file) {
            if (!empty($GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST']) &&
                in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_EXCLUDE_LIST'], true)) {
                continue;
            }

            if ($prefix !== false && strpos($file, $prefix) === 0) {
                continue;
            }

            // Skip virtual file system protocols
            if (preg_match('/^(vfs|phpvfs[a-z0-9]+):/', $file)) {
                continue;
            }

            if (!$excludeList->isExcluded($file) && is_file($file)) {
                $result = 'require_once \'' . $file . "';\n" . $result;
            }
        }

        return $result;
    }

    public static function getIniSettingsAsString(): string
    {
        $result = '';

        foreach (ini_get_all(null, false) as $key => $value) {
            $result .= sprintf(
                '@ini_set(%s, %s);' . "\n",
                self::exportVariable($key),
                self::exportVariable((string) $value)
            );
        }

        return $result;
    }

    public static function getConstantsAsString(): string
    {
        $constants = get_defined_constants(true);
        $result    = '';

        if (isset($constants['user'])) {
            foreach ($constants['user'] as $name => $value) {
                $result .= sprintf(
                    'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
                    $name,
                    $name,
                    self::exportVariable($value)
                );
            }
        }

        return $result;
    }

    public static function getGlobalsAsString(): string
    {
        $result = '';

        foreach (self::SUPER_GLOBAL_ARRAYS as $superGlobalArray) {
            if (isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray])) {
                foreach (array_keys($GLOBALS[$superGlobalArray]) as $key) {
                    if ($GLOBALS[$superGlobalArray][$key] instanceof Closure) {
                        continue;
                    }

                    $result .= sprintf(
                        '$GLOBALS[\'%s\'][\'%s\'] = %s;' . "\n",
                        $superGlobalArray,
                        $key,
                        self::exportVariable($GLOBALS[$superGlobalArray][$key])
                    );
                }
            }
        }

        $excludeList   = self::SUPER_GLOBAL_ARRAYS;
        $excludeList[] = 'GLOBALS';

        foreach (array_keys($GLOBALS) as $key) {
            if (!$GLOBALS[$key] instanceof Closure && !in_array($key, $excludeList, true)) {
                $result .= sprintf(
                    '$GLOBALS[\'%s\'] = %s;' . "\n",
                    $key,
                    self::exportVariable($GLOBALS[$key])
                );
            }
        }

        return $result;
    }

    private static function exportVariable($variable): string
    {
        if (is_scalar($variable) || $variable === null ||
            (is_array($variable) && self::arrayOnlyContainsScalars($variable))) {
            return var_export($variable, true);
        }

        return 'unserialize(' . var_export(serialize($variable), true) . ')';
    }

    private static function arrayOnlyContainsScalars(array $array): bool
    {
        $result = true;

        foreach ($array as $element) {
            if (is_array($element)) {
                $result = self::arrayOnlyContainsScalars($element);
            } elseif (!is_scalar($element) && $element !== null) {
                $result = false;
            }

            if (!$result) {
                break;
            }
        }

        return $result;
    }
}