text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>org.mam.archsandbox</id>
    <name>arch-sandbox</name>
    <version>1.0</version>
    <publisher>admin</publisher>
    <url>http://mam.org</url>
    <description/>
    <copyright>2016 by admin</copyright>
    <icon>appicon.png</icon>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>true</analytics>
    <guid>0061bfae-9ea9-4611-9bbb-a346f10ff49e</guid>
    <property name="ti.ui.defaultunit" type="string">dp</property>
    <ios>
        <enable-launch-screen-storyboard>true</enable-launch-screen-storyboard>
        <plist>
            <dict>
                <key>UISupportedInterfaceOrientations~iphone</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                </array>
                <key>UISupportedInterfaceOrientations~ipad</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                    <string>UIInterfaceOrientationPortraitUpsideDown</string>
                    <string>UIInterfaceOrientationLandscapeLeft</string>
                    <string>UIInterfaceOrientationLandscapeRight</string>
                </array>
                <key>UIRequiresPersistentWiFi</key>
                <false/>
                <key>UIPrerenderedIcon</key>
                <false/>
                <key>UIStatusBarHidden</key>
                <false/>
                <key>UIStatusBarStyle</key>
                <string>UIStatusBarStyleDefault</string>
            </dict>
        </plist>
    </ios>
    <android xmlns:android="http://schemas.android.com/apk/res/android">
        <manifest>
            <application android:theme="@style/materialTheme"/>
        </manifest>
    </android>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules>
        <module platform="commonjs">ti.cloud</module>
    </modules>
    <deployment-targets>
        <target device="iphone">false</target>
        <target device="ipad">false</target>
        <target device="android">true</target>
        <target device="mobileweb">false</target>
        <target device="windows">false</target>
    </deployment-targets>
    <sdk-version>6.0.0.GA</sdk-version>
    <plugins>
        <plugin version="1.0">ti.alloy</plugin>
    </plugins>
    <property name="appc-app-id" type="string">57f565e4d2019ce327179435</property>
    <property name="acs-authbase-url-development" type="string">https://secure-identity.cloud.appcelerator.com</property>
    <property name="acs-base-url-development" type="string">https://api.cloud.appcelerator.com</property>
    <property name="acs-oauth-secret-development" type="string">wK6HxzqpLnGy1z4beklQAPW7ATvU3jI8</property>
    <property name="acs-oauth-key-development" type="string">53MEj15UNGuf7UGUT7OZyYnmctzPTv3Z</property>
    <property name="acs-api-key-development" type="string">y1OQ2Aunq8AIxdk3JBwA74fim09OimSG</property>
    <property name="acs-username-development" type="string">appc_app_user_dev</property>
    <property name="acs-password-development" type="string">fJGlfnxyEwAwvQOpws</property>
    <property name="acs-authbase-url-production" type="string">https://secure-identity.cloud.appcelerator.com</property>
    <property name="acs-base-url-production" type="string">https://api.cloud.appcelerator.com</property>
    <property name="acs-oauth-secret-production" type="string">xWu6bT09cxKPPkVGjunXR2VX49CrtCRj</property>
    <property name="acs-oauth-key-production" type="string">9NUltNvbgQzLINyd8TStD0thVhP8PrI7</property>
    <property name="acs-api-key-production" type="string">V9P8qK5NpUeTmFIKWVjO2TVgt7V0b8ef</property>
    <property name="acs-username-production" type="string">appc_app_user</property>
    <property name="acs-password-production" type="string">38StbQPNnjNXNF0SyG</property>
    <property name="appc-org-id" type="string">100103261</property>
    <property name="appc-creator-user-id" type="string">1d75029b-3c19-40ae-acee-987e3d0d696d</property>
</ti:app>


text:
import pytest

from mollie.api.objects.list import ObjectList
from mollie.api.objects.method import Method

from .utils import assert_list_object

def test_list_iterator_behaviour(client, response):
    """Verify the behaviour of the List object in iterator circumstances."""
    response.get("https://api.mollie.com/v2/methods", "methods_list")

    methods = client.methods.list()
    assert isinstance(methods, ObjectList)

    # walk the list using next()
    iterated = 0
    while True:
        try:
            item = next(methods)
            assert isinstance(item, Method)
            iterated += 1
        except StopIteration:
            # read all items from the iterator
            break

    assert iterated == methods.count
    assert iterated == len(methods)

    # use for loop as iterator
    iterated = 0
    for item in methods:
        assert isinstance(item, Method)
        iterated += 1

    assert iterated == methods.count

def test_list_multiple_iterations(client, response):
    """Verify that we can iterate a list multiple times."""
    response.get("https://api.mollie.com/v2/methods", "methods_list")

    methods = client.methods.list()
    # iterate once using next()
    items_first_run = 0
    while True:
        try:
            next(methods)
            items_first_run += 1
        except StopIteration:
            break
    assert items_first_run == methods.count

    # iterate again
    items_second_run = 0
    while True:
        try:
            next(methods)
            items_second_run += 1
        except StopIteration:
            break
    assert items_second_run == methods.count

    methods = client.methods.list()
    # iterate once using for loop
    items_third_run = 0
    for item in methods:
        items_third_run += 1
    assert items_third_run == methods.count
    # iterate again
    items_fourth_run = 0
    for item in methods:
        items_fourth_run += 1
    assert items_fourth_run == methods.count

def test_list_multiple_api_calls(client, response):
    """Verify that we can iterate over a paginated result set."""
    response.get("https://api.mollie.com/v2/customers?limit=5", "customers_list_first")
    response.get("https://api.mollie.com/v2/customers?from=cst_8pknKQJzJa&limit=5", "customers_list_second")
    response.get("https://api.mollie.com/v2/customers?from=cst_prs8JjDf57&limit=5", "customers_list_third")
    response.get("https://api.mollie.com/v2/customers?from=cst_g328m9rhGe&limit=5", "customers_list_fourth")
    response.get("https://api.mollie.com/v2/customers?from=cst_prs8JjDf57&limit=5", "customers_list_third")
    response.get("https://api.mollie.com/v2/customers?from=cst_8pknKQJzJa&limit=5", "customers_list_second")
    response.get("https://api.mollie.com/v2/customers?from=cst_HwBHgJgRAf&limit=5", "customers_list_first")

    customers = client.customers.list(limit=5)
    assert customers.count == 5
    forward_first_id = next(customers).id
    customer_ids = [customer.id for customer in customers]
    while customers.has_next():
        customers = customers.get_next()
        for customer in customers:
            customer_ids.append(customer.id)

    assert len(customer_ids) == 17, "Unexpected number of customers"
    assert len(set(customer_ids)) == 17, "Unexpected number of unique customers"

    # now reverse the behaviour
    while customers.has_previous():
        customers = customers.get_previous()
    reverse_last_id = next(customers).id

    assert (
        forward_first_id == reverse_last_id
    ), "Expected the first customer of the first page to be stable, but it wasn't"

def test_list_supports_integer_sequences(client, response):
    response.get("https://api.mollie.com/v2/customers", "customers_list")

    customers = client.customers.list()
    first_customer = customers[1]
    assert first_customer.id == "cst_8wmqcHMN4y", "Getting a customer by index should be possible"

    last_customer = customers[-1]
    assert last_customer.id == "cst_8wmqcHMN4x", "Getting a customer by negative index should be possible"

    with pytest.raises(IndexError) as excinfo:
        customers[1000]
    assert str(excinfo.value) == "list index out of range", "A non-existent index should raise an IndexError"

def test_list_supports_slice_sequences(client, response):
    response.get("https://api.mollie.com/v2/methods", "methods_list")

    methods = client.methods.list()
    # Baseline for result checks
    assert [x.id for x in methods] == [
        "ideal",
        "creditcard",
        "paypal",
        "bancontact",
        "banktransfer",
        "sofort",
        "kbc",
        "belfius",
        "inghomepay",
        "giftcard",
    ]

    sliced = methods[1:3]
    assert_list_object(sliced, Method, 2), "Slicing should be possible"
    assert [x.id for x in sliced] == ["creditcard", "paypal"]

    slice_forward = methods[5:]
    assert_list_object(slice_forward, Method, 5), "Slicing forward should possible"
    assert [x.id for x in slice_forward] == ["sofort", "kbc", "belfius", "inghomepay", "giftcard"]

    slice_backwards = methods[:3]
    assert_list_object(slice_backwards, Method, 3), "Slicing backwards should be possible"
    assert [x.id for x in slice_backwards] == ["ideal", "creditcard", "paypal"]

    slice_stepped = methods[0:5:2]
    assert_list_object(slice_stepped, Method, 3), "Slicing with a step value should be possble"
    assert [x.id for x in slice_stepped] == ["ideal", "paypal", "banktransfer"]

    slice_step_only = methods[::3]
    assert_list_object(slice_step_only, Method, 4), "Slicing with only a step value should be possible"
    assert [x.id for x in slice_step_only] == ["ideal", "bancontact", "kbc", "giftcard"]

redpajama_set_name: RedPajamaGithub


text:
namespace media {

// TODO(wjia): this type should be defined in a common place and
// shared with device manager.
typedef int VideoCaptureSessionId;

// Color formats from camera. This list is sorted in order of preference.
enum VideoPixelFormat {
  PIXEL_FORMAT_I420,
  PIXEL_FORMAT_YV12,
  PIXEL_FORMAT_NV12,
  PIXEL_FORMAT_NV21,
  PIXEL_FORMAT_UYVY,
  PIXEL_FORMAT_YUY2,
  PIXEL_FORMAT_RGB24,
  PIXEL_FORMAT_ARGB,
  PIXEL_FORMAT_MJPEG,
  PIXEL_FORMAT_TEXTURE,  // Capture format as a GL texture.
  PIXEL_FORMAT_UNKNOWN,  // Color format not set.
  PIXEL_FORMAT_MAX,
};

// Policies for capture devices that has source content with dynamic resolution.
enum ResolutionChangePolicy {
  // Capture device outputs a fixed resolution all the time. The resolution of
  // the first frame is the resolution for all frames.
  // It is implementation specific for the capture device to scale, letter-box
  // and pillar-box. The only guarantee is that resolution will never change.
  RESOLUTION_POLICY_FIXED,

  // Capture device outputs frames with dynamic resolution. The width and height
  // will not exceed the maximum dimensions specified. The typical scenario is
  // the frames will have the same aspect ratio as the original content and
  // scaled down to fit inside the limit.
  RESOLUTION_POLICY_DYNAMIC_WITHIN_LIMIT,

  RESOLUTION_POLICY_LAST,
};

// Some drivers use rational time per frame instead of float frame rate, this
// constant k is used to convert between both: A fps -> [k/k*A] seconds/frame.
const int kFrameRatePrecision = 10000;

// Video capture format specification.
// This class is used by the video capture device to specify the format of every
// frame captured and returned to a client. It is also used to specify a
// supported capture format by a device.
class MEDIA_EXPORT VideoCaptureFormat {
 public:
  VideoCaptureFormat();
  VideoCaptureFormat(const gfx::Size& frame_size,
                     float frame_rate,
                     VideoPixelFormat pixel_format);

  std::string ToString() const;
  static std::string PixelFormatToString(VideoPixelFormat format);

  // Returns the required buffer size to hold an image of a given
  // VideoCaptureFormat with no padding and tightly packed.
  size_t ImageAllocationSize() const;

  // Checks that all values are in the expected range. All limits are specified
  // in media::Limits.
  bool IsValid() const;

  gfx::Size frame_size;
  float frame_rate;
  VideoPixelFormat pixel_format;
};

typedef std::vector<VideoCaptureFormat> VideoCaptureFormats;

// Parameters for starting video capture.
// This class is used by the client of a video capture device to specify the
// format of frames in which the client would like to have captured frames
// returned.
class MEDIA_EXPORT VideoCaptureParams {
 public:
  VideoCaptureParams();

  // Requests a resolution and format at which the capture will occur.
  VideoCaptureFormat requested_format;

  // Policy for resolution change.
  ResolutionChangePolicy resolution_change_policy;
};

}  // namespace media

#endif  // MEDIA_BASE_VIDEO_CAPTURE_TYPES_H_


text:
require 'spec_helper'

describe PublicPagesController do
  before do
    @account = Factory(:account)
    Account.stub!(:find).and_return(@account)
  end

    describe "GET to show" do
      context "with page using no template" do
        before do
          @page = Factory(:page, :account => @account)

          get :show, :account_id => @account.id, :id => @page.name
        end

        it { should respond_with(:success) }
        it { should assign_to(:page).with(@page) }
        it "should not load template" do
          PageTemplate.should_not_receive(:find)
        end
      end

      context "with page using template" do
        before do
          @page_template = Factory(:page_template)
          @page = Factory(:page, :template => @page_template, :account => @account)
          PageTemplate.stub!(:find).and_return(@page_template)

          @content_drop = ContentDrop.new(@account)
          @site_drop = SiteDrop.new(@account)
          SiteDrop.stub!(:new).and_return(@site_drop)
          ContentDrop.stub!(:new).and_return(@content_drop)

          @page_template.should_receive(:render)

          get :show, :account_id => @account.id, :id => @page.name
        end

        it { should respond_with(:success) }
        it { should assign_to(:page).with(@page) }
      end
    end

end


text:
jQuery(function(){

    //EVERY INLINE-GROUP NEEDS A SPECIFIC CLASS
	$('.inline-group').each(function(index){
        if($(this).find('.tabular').length > 0 && $(this).find('.field-position').length > 0){
            $(this).addClass('sortable-tabular-inline');
        }
        else if($(this).find('.inline-related fieldset.module .field-position').length > 0){
            $(this).addClass('sortable-stacked-inline');
            $(this).find('.inline-related').addClass('inline-sortable-item');
		}
    });

    var temp_html_bottom = "";
    //EVERY TABULAR INLINE NEEDS TO BE SORTABLE
    $('.sortable-tabular-inline').each(function(index){
        $(this).find('tbody tr').addClass('inline-sortable-item');
        $(this).find('tbody').sortable({
            cancel:".add-row",
            axis: 'y',
            delay: '150',
            start: function(event,ui){
                temp_html_bottom = $(this).find('.add-row');
                $(this).find('.add-row').remove();
            },
            stop: function(event,ui){
                $(this).append(temp_html_bottom);
                $(this).find("input,textarea,select")
                    .bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                    e.stopImmediatePropagation();
                });
            },
            update: function(event, ui) {
                var item = ui.item;
                var items = $(this).find('tr').get();
                $(items).each(function(index) {
                    var input = $(this).find('.field-position>input');

                    input.attr('value', index+1);
                });
                $(this).find('tr').removeClass('row1').removeClass('row2');
                $(this).find('tr:even').addClass('row1');
                $(this).find('tr:odd').addClass('row2');
            }

        });

       $(this).find('tbody').bind('sortupdate', reorder);
       $(this).find("input,textarea,select")
			.bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
      		e.stopImmediatePropagation();
       });
    });

    //EVERY STACKED INLINE NEEDS TO BE SORTABLE
    $('.sortable-stacked-inline').each(function(index){
        $(this).find('tr').addClass('inline-sortable-item');
        $(this).sortable({
            cancel:".add-row,h2",
            axis: 'y',
            delay: '150',
            items: '.inline-related',
            stop: function(event,ui){
                $(this).find("input,textarea,select")
                    .bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                        e.stopImmediatePropagation();
                    });
            },
            update: function(event, ui) {
                var item = ui.item;
                var items = $(this).find('.inline-related').get();
                $(items).each(function(index) {
                    // input = $(this).find('.field-position>input');
                    var input = $(this).find('.field-position').find("input");
                    input.attr('value', index+1);
                });
                $(this).find('tr').removeClass('row1').removeClass('row2');
                $(this).find('tr:even').addClass('row1');
                $(this).find('tr:odd').addClass('row2');
            }

        });
        $(this).bind('sortupdate', reorder);
        $(this).find("input,textarea,select")
			.bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
      		e.stopImmediatePropagation();
        });
    });

    function reorder(){

        if($(this).parents('.inline-group').hasClass('sortable-tabular-inline')){
            $(this).find('.form-row').not('.empty-form').each(function(index){
                $(this).find('.field-position>input').val(index+1);
            });
        }
        else if($(this).hasClass('sortable-stacked-inline')){
            $(this).find('.inline-sortable-item').not('.empty-form').each(function(index){
                $(this).find('.field-position>input').val(index+1);
            });
        }
    }

    $('.add-row a').on('click',function(){
        var parent = $(this).parents('.inline-group');
        if(parent.hasClass('sortable-tabular-inline')){
            parent.find('.ui-sortable').find("input,textarea,select")
                .bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                    e.stopImmediatePropagation();
            });
            parent.find('.ui-sortable').trigger('sortupdate');
        }
        else if(parent.hasClass('sortable-stacked-inline')){
            parent.find("input,textarea,select")
                .bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                    e.stopImmediatePropagation();
            });
            parent.trigger('sortupdate');
        }

	});

});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.islarf6546.gmail.lock_screen_prototype">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:enabled="true"
            android:exported="true"
            android:name=".Receiver">
        </receiver>

        <service
            android:name=".Lock_Disable"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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 org.modeshape.jcr;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.TimeUnit;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.modeshape.jcr.api.RepositoryFactory;

/**
 * Unit test for {@link JcrRepositoryFactory}
 */
@SuppressWarnings( "deprecation" )
public class JcrRepositoryFactoryTest {

    private String url;
    private Map<String, String> params;
    private Repository repository;
    private RepositoryFactory repositoryFactory;

    @Before
    public void beforeEach() throws Exception {
        Iterator<javax.jcr.RepositoryFactory> repositoryFactoryIterator = ServiceLoader.load(javax.jcr.RepositoryFactory.class)
                                                                                .iterator();
        if (!repositoryFactoryIterator.hasNext()) {
            fail("No RepositoryFactory implementation located");
        }
        repositoryFactory = (RepositoryFactory)repositoryFactoryIterator.next();
    }

    @After
    public void afterEach() throws Exception {
        // Shut down all repositories after each test, since multiple tests may use the same URL ...
        repositoryFactory.shutdown(10, TimeUnit.SECONDS);
    }

    @Test
    public void shouldReturnRepositoryFromConfigurationFile() throws RepositoryException {
        url = "file:src/test/resources/config/simple-repo-config.json";
        params = Collections.singletonMap(RepositoryFactory.URL, url);

        repository = repositoryFor(params);
        assertThat(repository, is(notNullValue()));
    }

    @Test
    public void shouldNotReturnRepositoryFromConfigurationFileIfRepositoryNameMatches() throws RepositoryException {
        url = "file:src/test/resources/config/simple-repo-config.json";
        params = new HashMap<String, String>();
        params.put(RepositoryFactory.URL, url);
        params.put(RepositoryFactory.REPOSITORY_NAME, "Another Test Repository");

        repository = repositoryFor(params);
        assertThat(repository, is(notNullValue()));
    }

    @Test
    public void shouldNotReturnRepositoryFromConfigurationFileIfRepositoryNameDiffers() throws RepositoryException {
        url = "file:src/test/resources/config/simple-repo-config.json";
        params = new HashMap<String, String>();
        params.put(RepositoryFactory.URL, url);
        repository = repositoryFor(params);
        assertThat(repository, is(notNullValue()));

        params.put(RepositoryFactory.REPOSITORY_NAME, "some name");
        repository = repositoryFor(params);
        assertThat(repository, is(nullValue()));
    }

    @Test
    public void shouldReturnRepositoryFromConfigurationClasspathResourceUsingFileScheme() throws RepositoryException {
        url = "file:///config/simple-repo-config.json";
        params = Collections.singletonMap(RepositoryFactory.URL, url);

        repository = repositoryFor(params);
        assertThat(repository, is(notNullValue()));
    }

    @Test
    public void shouldReturnSameRepositoryFromSameConfigurationFile() throws RepositoryException {
        url = "file:///config/simple-repo-config.json";
        params = Collections.singletonMap(RepositoryFactory.URL, url);

        repository = repositoryFor(params);
        assertThat(repository, is(notNullValue()));

        Repository repository2 = repositoryFor(params);
        assertThat(repository2, is(notNullValue()));
        assertThat(repository, is(repository2));

    }

    @Test
    public void shouldNotReturnRepositoryForInvalidUrl() {
        try {
            url = "file:?Test Repository Source";
            repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
            fail("Expected repository exception");
        } catch (RepositoryException e) {
            // expected
        }

        try {
            url = "file:src/test/resources/nonExistentFile";
            repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
            fail("Expected repository exception");
        } catch (RepositoryException e) {
            // expected
        }

        try {
            url = "file:src/test/resources/nonExistentFile";
            repositoryFor(Collections.singletonMap(RepositoryFactory.URL, url));
            fail("Expected repository exception");
        } catch (RepositoryException e) {
            // expected
        }
    }

    protected Repository repositoryFor( Map<String, String> parameters ) throws RepositoryException {
        return repositoryFactory.getRepository(parameters);
    }
}


text:
// Copyright 2020 The Nomulus 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 google.registry.flows.certs;

import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.ALGORITHM_CONSTRAINED;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.EXPIRED;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.INVALID_ECDSA_CURVE;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.NOT_YET_VALID;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.RSA_KEY_LENGTH_TOO_SHORT;
import static google.registry.flows.certs.CertificateChecker.CertificateViolation.VALIDITY_LENGTH_TOO_LONG;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT;
import static google.registry.testing.CertificateSamples.SAMPLE_CERT3;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import google.registry.testing.FakeClock;
import google.registry.util.SelfSignedCaCertificate;
import java.security.AlgorithmParameters;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;

/** Unit tests for {@link CertificateChecker} */
class CertificateCheckerTest {

  private static final String SSL_HOST = "www.example.tld";

  private FakeClock fakeClock = new FakeClock();
  private CertificateChecker certificateChecker =
      new CertificateChecker(
          ImmutableSortedMap.of(START_OF_TIME, 825, DateTime.parse("2020-09-01T00:00:00Z"), 398),
          30,
          15,
          2048,
          ImmutableSet.of("secp256r1", "secp384r1"),
          fakeClock);

  @Test
  void test_checkCertificate_compliantCertPasses() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).isEmpty();
  }

  @Test
  void test_checkCertificate_severalViolations() throws Exception {
    fakeClock.setTo(DateTime.parse("2010-01-01T00:00:00Z"));
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyGen.initialize(1024, new SecureRandom());

    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2010-04-01T00:00:00Z"),
                DateTime.parse("2014-07-01T00:00:00Z"))
            .cert();

    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(NOT_YET_VALID, VALIDITY_LENGTH_TOO_LONG, RSA_KEY_LENGTH_TOO_SHORT);
  }

  @Test
  void test_checkCertificate_expiredCertificate() throws Exception {
    fakeClock.setTo(DateTime.parse("2014-01-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2010-04-01T00:00:00Z"),
                DateTime.parse("2012-07-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).containsExactly(EXPIRED);
  }

  @Test
  void test_checkCertificate_notYetValid() throws Exception {
    fakeClock.setTo(DateTime.parse("2010-01-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2010-04-01T00:00:00Z"),
                DateTime.parse("2012-07-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).containsExactly(NOT_YET_VALID);
  }

  @Test
  void test_checkCertificate_validityLengthWayTooLong() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2016-04-01T00:00:00Z"),
                DateTime.parse("2021-07-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(VALIDITY_LENGTH_TOO_LONG);
  }

  @Test
  void test_checkCertificate_olderValidityLengthIssuedAfterCutoff() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2022-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(VALIDITY_LENGTH_TOO_LONG);
  }

  @Test
  void test_checkCertificate_olderValidityLengthIssuedBeforeCutoff() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2019-09-01T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).isEmpty();
  }

  @Test
  void test_checkCertificate_rsaKeyLengthTooShort() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyGen.initialize(1024, new SecureRandom());

    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();

    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(RSA_KEY_LENGTH_TOO_SHORT);
  }

  @Test
  void test_checkCertificate_rsaKeyLengthLongerThanRequired() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyGen.initialize(4096, new SecureRandom());

    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();

    assertThat(certificateChecker.checkCertificate(certificate)).isEmpty();
  }

  @Test
  void test_checkCertificate_invalidAlgorithm() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", new BouncyCastleProvider());
    keyGen.initialize(2048, new SecureRandom());

    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();

    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(ALGORITHM_CONSTRAINED);
  }

  @Test
  void test_checkCertificate_validCertificateString() {
    fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
    assertThat(certificateChecker.checkCertificate(SAMPLE_CERT3)).isEmpty();
    assertThat(certificateChecker.checkCertificate(SAMPLE_CERT))
        .containsExactly(VALIDITY_LENGTH_TOO_LONG);
  }

  @Test
  void test_checkCertificate_invalidCertificateString() {
    fakeClock.setTo(DateTime.parse("2020-11-01T00:00:00Z"));
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> certificateChecker.checkCertificate("bad certificate string"));
    assertThat(thrown).hasMessageThat().contains("Unable to read given certificate");
  }

  @Test
  void test_getCertificate_throwsException_invalidCertificateString() {
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> certificateChecker.getCertificate("invalidCertificateString"));
    assertThat(thrown).hasMessageThat().contains("Unable to read given certificate");
  }

  @Test
  void test_getCertificate_returnsCertificateObject() throws Exception {
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    assertThat(certificateChecker.getCertificate(certificateStr).equals(certificate)).isTrue();
  }

  @Test
  void test_serializeCertificate_returnsCertificateString() throws Exception {
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(
            certificateChecker.getCertificate(certificateChecker.serializeCertificate(certificate)))
        .isEqualTo(certificate);
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsFalse_greaterThan30() throws Exception {
    fakeClock.setTo(DateTime.parse("2021-07-20T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr))
        .isFalse();
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsFalse_hasExpired() throws Exception {
    fakeClock.setTo(DateTime.parse("2021-10-20T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr))
        .isFalse();
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsTrue_on15days() throws Exception {
    fakeClock.setTo(DateTime.parse("2021-08-16T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-08-30T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-08-01T00:00:00Z");
    assertThat(
            certificateChecker.shouldReceiveExpiringNotification(
                lastExpiringNotificationSentDate, certificateStr))
        .isTrue();
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsTrue_on30days() throws Exception {
    fakeClock.setTo(DateTime.parse("2021-01-01T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-01-02T00:00:00Z"),
                DateTime.parse("2021-01-30T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr))
        .isTrue();
  }

  @Test
  void
      test_shouldReceiveExpiringNotification_returnsFalse_between30and15_lastSentDateIsNotStartOfTime()
          throws Exception {
    fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-06-02T00:00:00Z"),
                DateTime.parse("2021-07-25T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-07-04T00:00:00Z");
    assertThat(
            certificateChecker.shouldReceiveExpiringNotification(
                lastExpiringNotificationSentDate, certificateStr))
        .isFalse();
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsTrue_between30and15_lastSentDateIsStartOfTime()
      throws Exception {
    fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-06-02T00:00:00Z"),
                DateTime.parse("2021-07-25T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    assertThat(certificateChecker.shouldReceiveExpiringNotification(START_OF_TIME, certificateStr))
        .isTrue();
  }

  @Test
  void
      test_shouldReceiveExpiringNotification_returnsFalse_between15and0_lastSentDateBetween30and15_butLate()
          throws Exception {
    fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-06-02T00:00:00Z"),
                DateTime.parse("2021-07-18T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-07-01T00:00:00Z");
    // The first notification date is late and difference between now and
    // lastExpiringNotificationSentDate is within expirationWarningIntervalDays.
    assertThat(
            certificateChecker.shouldReceiveExpiringNotification(
                lastExpiringNotificationSentDate, certificateStr))
        .isFalse();
  }

  @Test
  void test_shouldReceiveExpiringNotification_returnsTrue_between15and0_lastSentDateBetween30and15()
      throws Exception {
    fakeClock.setTo(DateTime.parse("2021-07-05T00:00:00Z"));
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                SSL_HOST,
                DateTime.parse("2020-06-02T00:00:00Z"),
                DateTime.parse("2021-07-18T00:00:00Z"))
            .cert();
    String certificateStr = certificateChecker.serializeCertificate(certificate);
    DateTime lastExpiringNotificationSentDate = DateTime.parse("2021-06-20T00:00:00Z");
    assertThat(
            certificateChecker.shouldReceiveExpiringNotification(
                lastExpiringNotificationSentDate, certificateStr))
        .isTrue();
  }

  @Test
  void test_CertificateViolation_RsaKeyLengthDisplayMessageFormatsCorrectly() {
    assertThat(RSA_KEY_LENGTH_TOO_SHORT.getDisplayMessage(certificateChecker))
        .isEqualTo("RSA key length is too short; the minimum allowed length is 2048 bits.");
  }

  @Test
  void test_CertificateViolation_validityLengthDisplayMessageFormatsCorrectly() {
    assertThat(VALIDITY_LENGTH_TOO_LONG.getDisplayMessage(certificateChecker))
        .isEqualTo(
            "Certificate validity period is too long; it must be less than or equal to 398 days.");
  }

  @Test
  void test_checkCurveName_invalidCurve_returnsViolation() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    // Invalid curve
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC");
    apParam.init(new ECGenParameterSpec("secp128r1"));
    ECParameterSpec spec = apParam.getParameterSpec(ECParameterSpec.class);
    keyGen.initialize(spec, new SecureRandom());
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate))
        .containsExactly(INVALID_ECDSA_CURVE);
  }

  @Test
  void test_checkCurveName_p256Curve_returnsNoViolations() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    // valid P-256 curve
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC");
    apParam.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec spec = apParam.getParameterSpec(ECParameterSpec.class);
    keyGen.initialize(spec, new SecureRandom());
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).isEmpty();
  }

  @Test
  void test_checkCurveName_p384Curve_returnsNoViolations() throws Exception {
    fakeClock.setTo(DateTime.parse("2020-10-01T00:00:00Z"));
    // valid P-384 curve
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    AlgorithmParameters apParam = AlgorithmParameters.getInstance("EC");
    apParam.init(new ECGenParameterSpec("secp384r1"));
    ECParameterSpec spec = apParam.getParameterSpec(ECParameterSpec.class);
    keyGen.initialize(spec, new SecureRandom());
    X509Certificate certificate =
        SelfSignedCaCertificate.create(
                keyGen.generateKeyPair(),
                SSL_HOST,
                DateTime.parse("2020-09-02T00:00:00Z"),
                DateTime.parse("2021-10-01T00:00:00Z"))
            .cert();
    assertThat(certificateChecker.checkCertificate(certificate)).isEmpty();
  }
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

abstract class Concrete5_Model_WorkflowProgress extends Object {

	protected $wpID;
	protected $wpDateAdded;
	protected $wfID;
	protected $response;
	protected $wpDateLastAction;

	/**
	 * Gets the Workflow object attached to this WorkflowProgress object
	 * @return Workflow
	 */
	public function getWorkflowObject() {
		if ($this->wfID > 0) {
			$wf = Workflow::getByID($this->wfID);
		} else {
			$wf = new EmptyWorkflow();
		}
		return $wf;
	}

	/**
	 * Gets an optional WorkflowResponse object. This is set in some cases
	 */
	public function getWorkflowProgressResponseObject() {
		return $this->response;
	}

	public function setWorkflowProgressResponseObject($obj) {
		$this->response = $obj;
	}

	/**
	 * Gets the date of the last action
	 */
	public function getWorkflowProgressDateLastAction() {
		return $this->wpDateLastAction;
	}

	/**
	 * Gets the ID of the progress object
	 */
	public function getWorkflowProgressID() {return $this->wpID;}

	/**
	 * Get the category ID
	 */
	public function getWorkflowProgressCategoryID() {return $this->wpCategoryID;}

	/**
	 * Gets the date the WorkflowProgress object was added
	 * @return datetime
	 */
	public function getWorkflowProgressDateAdded() {return $this->wpDateAdded;}

	/**
	 * Get the WorkflowRequest object for the current WorkflowProgress object
	 * @return WorkflowRequest
	 */
	public function getWorkflowRequestObject() {
		if ($this->wrID > 0) {
			$cat = WorkflowProgressCategory::getByID($this->wpCategoryID);
			$handle = $cat->getWorkflowProgressCategoryHandle();
			$class = Loader::helper("text")->camelcase($handle) . 'WorkflowRequest';
			$wr = call_user_func_array(array($class, 'getByID'), array($this->wrID));
			if (is_object($wr)) {
				$wr->setCurrentWorkflowProgressObject($this);
				return $wr;
			}
		}
	}

	/**
	 * Creates a WorkflowProgress object (which will be assigned to a Page, File, etc... in our system.
	 */
	public static function add($wpCategoryHandle, Workflow $wf, WorkflowRequest $wr) {
		$db = Loader::db();
		$wpDateAdded = Loader::helper('date')->getLocalDateTime();
		$wpCategoryID = $db->GetOne('select wpCategoryID from WorkflowProgressCategories where wpCategoryHandle = ?', array($wpCategoryHandle));
		$db->Execute('insert into WorkflowProgress (wfID, wrID, wpDateAdded, wpCategoryID) values (?, ?, ?, ?)', array(
			$wf->getWorkflowID(), $wr->getWorkflowRequestID(), $wpDateAdded, $wpCategoryID
		));
		$wp = self::getByID($db->Insert_ID());
		$wp->addWorkflowProgressHistoryObject($wr);
		return $wp;
	}

	public function delete() {
		$db = Loader::db();
		$wr = $this->getWorkflowRequestObject();
		$db->Execute('delete from WorkflowProgress where wpID = ?', array($this->wpID));
		// now we clean up any WorkflowRequests that aren't in use any longer
		$cnt = $db->GetOne('select count(wpID) from WorkflowProgress where wrID = ?', array($this->wrID));
		if ($cnt == 0) {
			$wr->delete();
		}
	}

	public static function getByID($wpID) {
		$db = Loader::db();
		$r = $db->GetRow('select WorkflowProgress.*, WorkflowProgressCategories.wpCategoryHandle from WorkflowProgress inner join WorkflowProgressCategories on WorkflowProgress.wpCategoryID = WorkflowProgressCategories.wpCategoryID where wpID  = ?', array($wpID));
		if (!is_array($r) || (!$r['wpID'])) {
			return false;
		}
		$class = Loader::helper("text")->camelcase($r['wpCategoryHandle']) . 'WorkflowProgress';

		$wp = new $class;
		$wp->setPropertiesFromArray($r);
		$wp->loadDetails();
		return $wp;
	}

	public static function getRequestedTask() {
		$task = '';
		foreach($_POST as $key => $value) {
			if (strpos($key, 'action_') > -1) {
				return substr($key, 7);
			}
		}
	}

	/**
	 * The function that is automatically run when a workflowprogress object is started
	 */
	public function start() {
		$wf = $this->getWorkflowObject();
		if (is_object($wf)) {
			$r = $wf->start($this);
			$this->updateOnAction($wf);
		}
		return $r;
	}

	public function updateOnAction(Workflow $wf) {
		$db = Loader::db();
		$num = $wf->getWorkflowProgressCurrentStatusNum($this);
		$time = Loader::helper('date')->getLocalDateTime();
		$db->Execute('update WorkflowProgress set wpDateLastAction = ?, wpCurrentStatus = ? where wpID = ?', array($time, $num, $this->wpID));
	}

	/**
	 * Attempts to run a workflow task on the bound WorkflowRequest object first, then if that doesn't exist, attempts to run
	 * it on the current WorkflowProgress object
	 * @return WorkflowProgressResponse
	 */
	public function runTask($task, $args = array()) {
		$wf = $this->getWorkflowObject();
		if (in_array($task, $wf->getAllowedTasks())) {
			$wpr = call_user_func_array(array($wf, $task), array($this, $args));
			$this->updateOnAction($wf);
		}
		if (!($wpr instanceof WorkflowProgressResponse)) {
			$wpr = new WorkflowProgressResponse();
		}
		return $wpr;
	}

	public function getWorkflowProgressActions() {
		$w = $this->getWorkflowObject();
		$req = $this->getWorkflowRequestObject();
		$actions = $req->getWorkflowRequestAdditionalActions($this);
		$actions = array_merge($actions, $w->getWorkflowProgressActions($this));
		return $actions;
	}

	abstract function getWorkflowProgressFormAction();
	abstract function loadDetails();

	public function getWorkflowProgressHistoryObjectByID($wphID) {
		$class = get_class($this) . 'History';
		$db = Loader::db();
		$row = $db->GetRow('select * from WorkflowProgressHistory where wphID = ?', array($wphID));
		if (is_array($row) && ($row['wphID'])) {
			$obj = new $class();
			$obj->setPropertiesFromArray($row);
			$obj->object = @unserialize($row['object']);
			return $obj;
		}
	}

	public function addWorkflowProgressHistoryObject($obj) {
		$db = Loader::db();
		$db->Execute('insert into WorkflowProgressHistory (wpID, object) values (?, ?)', array($this->wpID, serialize($obj)));
	}

	public function markCompleted() {
		$db = Loader::db();
		$db->Execute('update WorkflowProgress set wpIsCompleted = 1 where wpID = ?', array($this->wpID));
	}

	abstract public function getPendingWorkflowProgressList();

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Sclerotinia trifoliorum var. fabae M.A. Keay, 1939

### Remarks
null


text:
package com.smoketurner.notification.application.store;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.concurrent.ExecutionException;
import org.junit.Ignore;
import org.junit.Test;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.kv.DeleteValue;
import com.basho.riak.client.api.commands.kv.FetchValue;
import com.basho.riak.client.api.commands.kv.UpdateValue;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.smoketurner.notification.application.exceptions.NotificationStoreException;

public class CursorStoreTest {

  private static final String TEST_USER = "test";
  private static final String CURSOR_NAME = "notifications";
  private final MetricRegistry registry = new MetricRegistry();
  private final RiakClient client = mock(RiakClient.class);
  private final CursorStore store = new CursorStore(registry, client);

  @Test
  @Ignore
  public void testFetch() throws Exception {
    final FetchValue.Response response = mock(FetchValue.Response.class);

    final Optional<Long> expected = Optional.of(1L);

    when(client.execute(any(FetchValue.class))).thenReturn(response);

    final Optional<Long> actual = store.fetch(TEST_USER, CURSOR_NAME);
    verify(client).execute(any(FetchValue.class));
    assertThat(actual).isEqualTo(expected);
  }

  @Test
  public void testStore() throws Exception {
    store.store(TEST_USER, CURSOR_NAME, 1L);
    verify(client).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreNullUsername() throws Exception {
    try {
      store.store(null, CURSOR_NAME, 1L);
      failBecauseExceptionWasNotThrown(NullPointerException.class);
    } catch (NullPointerException e) {
    }
    verify(client, never()).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreEmptyUsername() throws Exception {
    try {
      store.store("", CURSOR_NAME, 1L);
      failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
    }
    verify(client, never()).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreNullCursorName() throws Exception {
    try {
      store.store(TEST_USER, null, 1L);
      failBecauseExceptionWasNotThrown(NullPointerException.class);
    } catch (NullPointerException e) {
    }
    verify(client, never()).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreEmptyCursorName() throws Exception {
    try {
      store.store(TEST_USER, "", 1L);
      failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
    }
    verify(client, never()).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreExecutionException() throws Exception {
    when(client.execute(any(UpdateValue.class))).thenThrow(new ExecutionException(new Exception()));

    try {
      store.store(TEST_USER, CURSOR_NAME, 1L);
      failBecauseExceptionWasNotThrown(NotificationStoreException.class);
    } catch (NotificationStoreException e) {
    }

    verify(client).execute(any(UpdateValue.class));
  }

  @Test
  public void testStoreInterruptedException() throws Exception {
    when(client.execute(any(UpdateValue.class))).thenThrow(new InterruptedException());

    try {
      store.store(TEST_USER, CURSOR_NAME, 1L);
      failBecauseExceptionWasNotThrown(NotificationStoreException.class);
    } catch (NotificationStoreException e) {
    }

    verify(client).execute(any(UpdateValue.class));
  }

  @Test
  public void testDelete() throws Exception {
    store.delete(TEST_USER, CURSOR_NAME);
    verify(client).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteNullUsername() throws Exception {
    try {
      store.delete(null, CURSOR_NAME);
      failBecauseExceptionWasNotThrown(NullPointerException.class);
    } catch (NullPointerException e) {
    }
    verify(client, never()).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteEmptyUsername() throws Exception {
    try {
      store.delete("", CURSOR_NAME);
      failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
    }
    verify(client, never()).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteNullCursorName() throws Exception {
    try {
      store.delete(TEST_USER, null);
      failBecauseExceptionWasNotThrown(NullPointerException.class);
    } catch (NullPointerException e) {
    }
    verify(client, never()).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteEmptyCursorName() throws Exception {
    try {
      store.delete(TEST_USER, "");
      failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
    }
    verify(client, never()).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteExecutionException() throws Exception {
    when(client.execute(any(DeleteValue.class))).thenThrow(new ExecutionException(new Exception()));

    try {
      store.delete(TEST_USER, CURSOR_NAME);
      failBecauseExceptionWasNotThrown(NotificationStoreException.class);
    } catch (NotificationStoreException e) {
    }

    verify(client).execute(any(DeleteValue.class));
  }

  @Test
  public void testDeleteInterruptedException() throws Exception {
    when(client.execute(any(DeleteValue.class))).thenThrow(new InterruptedException());

    try {
      store.delete(TEST_USER, CURSOR_NAME);
      failBecauseExceptionWasNotThrown(NotificationStoreException.class);
    } catch (NotificationStoreException e) {
    }

    verify(client).execute(any(DeleteValue.class));
  }

  @Test
  public void testGetCursorKey() {
    assertThat(store.getCursorKey(TEST_USER, CURSOR_NAME)).isEqualTo("test-notifications");
  }
}


text:
package org.pitest.maven;

import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.pitest.functional.F;
import org.pitest.functional.FCollection;
import org.pitest.functional.predicate.Predicate;
import org.pitest.mutationtest.config.ReportOptions;
import org.pitest.testapi.TestGroupConfig;
import org.pitest.util.Glob;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Extracts configuration from surefire plugin and create pitest equivalents
 */
public class SurefireConfigConverter {

  public ReportOptions update(ReportOptions option, Xpp3Dom configuration) {
    if (configuration == null) {
      return option;
    }
    convertExcludes(option, configuration);
    convertGroups(option, configuration);
    return option;
  }

  private void convertGroups(ReportOptions option, Xpp3Dom configuration) {
    TestGroupConfig existing = option.getGroupConfig();
    if (existing == null || (existing.getExcludedGroups().isEmpty()
        && existing.getIncludedGroups().isEmpty())) {
      List<String> groups = extractStrings("groups", configuration);
      List<String> excluded = extractStrings("excludedGroups", configuration);
      TestGroupConfig gc = new TestGroupConfig(excluded, groups);
      option.setGroupConfig(gc);
    }
  }

  private List<String> extractStrings(String element, Xpp3Dom configuration) {
    Xpp3Dom groups = configuration.getChild(element);
    if (groups != null) {
      String[] parts = groups.getValue().split(" ");
      return Arrays.asList(parts);
    } else {
      return Collections.emptyList();
    }
  }

  private void convertExcludes(ReportOptions option, Xpp3Dom configuration) {
    List<Predicate<String>> excludes = FCollection.map(
        extract("excludes", configuration), filenameToClassFilter());
    excludes.addAll(option.getExcludedClasses());
    option.setExcludedClasses(excludes);
  }

  private F<String, Predicate<String>> filenameToClassFilter() {
    return new F<String, Predicate<String>>() {
      public Predicate<String> apply(String a) {
        return new Glob(a.replace(".java", "").replace("/", "."));
      }
    };
  }

  private List<String> extract(String childname, Xpp3Dom config) {
    final Xpp3Dom subelement = config.getChild(childname);
    if (subelement != null) {
      List<String> result = new LinkedList<String>();
      final Xpp3Dom[] children = subelement.getChildren();
      for (Xpp3Dom child : children) {
        result.add(child.getValue());
      }
      return result;
    }

    return Collections.emptyList();
  }

}


text:
var slugify = require('slug')

module.exports = function(tag) {
  return '/tag/' + slugify(tag)
}


text:
<?php

use CookBook\Accounts\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker::create();

    foreach(range(1, 10) as $index)
    {
      User::create([
        'email' => $faker->unique()->email(),
        'username' => $faker->unique()->userName(),
        'password' => 'password',
      ]);
    }
  }

}


text:
function def = setDefaultParameters(def,arr,subvalue)
  % Set default parameters from a property->value list to struct, include
  % also those parameters that are not given in def.
  %
  % parameters:
  %   - def: default values
  %   - arr: property->value list struct
  %   - subvalue: is sub property->value list is searcher from struct
  %
  % Created: Antti Stenvall (antti@stenvall.fi)
  %

  f = fields(def);
  if nargin > 2 && ~isempty(subvalue)
    subInd = find(strcmp(arr,subvalue),1);
    if isempty(subInd) || length(arr) == subInd
      return;
    else
      arr = arr{subInd+1};
    end
  end

  for k=1:length(f)
    ind = find(strcmp(arr,f{k}),1);
    if ~isempty(ind) && length(arr) ~= ind
      def.(f{k}) = arr{ind+1};
    end
  end

  for k=1:2:length(arr)
    if ~any(strcmp(f,arr{k}))
      if length(arr) > k
        def.(arr{k}) = arr{k+1};
      end
    end
  end
end


text:
package org.apache.spark.storage

import java.io.File

/**
 * References a particular segment of a file (potentially the entire file),
 * based off an offset and a length.
 */
private[spark] class FileSegment(val file: File, val offset: Long, val length: Long) {
  override def toString = "(name=%s, offset=%d, length=%d)".format(file.getName, offset, length)
}


text:
namespace views {

MouseWatcherViewHost::MouseWatcherViewHost(View* view,
                                           const gfx::Insets& hot_zone_insets)
    : view_(view), hot_zone_insets_(hot_zone_insets) {}

MouseWatcherViewHost::~MouseWatcherViewHost() = default;

bool MouseWatcherViewHost::Contains(const gfx::Point& screen_point,
                                    EventType type) {
  bool in_view = IsCursorInViewZone(screen_point);
  if (!in_view || (type == EventType::kExit && !IsMouseOverWindow()))
    return false;
  return true;
}

// Returns whether or not the cursor is currently in the view's "zone" which
// is defined as a slightly larger region than the view.
bool MouseWatcherViewHost::IsCursorInViewZone(const gfx::Point& screen_point) {
  gfx::Rect bounds = view_->GetLocalBounds();
  gfx::Point view_topleft(bounds.origin());
  View::ConvertPointToScreen(view_, &view_topleft);
  bounds.set_origin(view_topleft);
  bounds.SetRect(view_topleft.x() - hot_zone_insets_.left(),
                 view_topleft.y() - hot_zone_insets_.top(),
                 bounds.width() + hot_zone_insets_.width(),
                 bounds.height() + hot_zone_insets_.height());

  return bounds.Contains(screen_point.x(), screen_point.y());
}

// Returns true if the mouse is over the view's window.
bool MouseWatcherViewHost::IsMouseOverWindow() {
  Widget* widget = view_->GetWidget();
  if (!widget)
    return false;

  return display::Screen::GetScreen()->IsWindowUnderCursor(
      widget->GetNativeWindow());
}

}  // namespace views


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>D-Index</title>
<meta name="date" content="2014-07-12">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I S T U

D

deleteAccount(Account) - Method in interface banking.dao.AccountDao

deleteAccount(Account) - Method in class banking.dao.mapimpl.AccountDaoMapImpl

deleteAccount(Integer) - Method in class banking.rest.resources.AccountResource

Removes an account.

deleteAccountById(Integer) - Static method in class banking.dao.mapimpl.BankingDatabaseMapImpl

deleteCustomer(Customer) - Method in interface banking.dao.CustomerDao

deleteCustomer(Customer) - Method in class banking.dao.mapimpl.CustomerDaoMapImpl

deleteCustomer(Integer) - Method in class banking.rest.resources.CustomerResource

Removes a customer.

deleteCustomerById(Integer) - Static method in class banking.dao.mapimpl.BankingDatabaseMapImpl

A B C D E F G H I S T U

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
.. title:: Tornado Web Server

.. meta::
    :google-site-verification: g4bVhgwbVO1d9apCUsT-eKlApg31Cygbp8VGZY8Rf0g

|Tornado Web Server|
====================

.. |Tornado Web Server| image:: tornado.png
    :alt: Tornado Web Server

`Tornado <http://www.tornadoweb.org>`_ is a Python web framework and
asynchronous networking library, originally developed at `FriendFeed
<http://friendfeed.com>`_.  By using non-blocking network I/O, Tornado
can scale to tens of thousands of open connections, making it ideal for
`long polling <http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_,
`WebSockets <http://en.wikipedia.org/wiki/WebSocket>`_, and other
applications that require a long-lived connection to each user.

Quick links
-----------

* Current version: |version| (`download from PyPI <https://pypi.python.org/pypi/tornado>`_, :doc:`release notes <releases>`)
* `Source (github) <https://github.com/tornadoweb/tornado>`_
* Mailing lists: `discussion <http://groups.google.com/group/python-tornado>`_ and `announcements <http://groups.google.com/group/python-tornado-announce>`_
* `Stack Overflow <http://stackoverflow.com/questions/tagged/tornado>`_
* `Wiki <https://github.com/tornadoweb/tornado/wiki/Links>`_

Hello, world
------------

Here is a simple "Hello, world" example web app for Tornado::

    import tornado.ioloop
    import tornado.web

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")

    def make_app():
        return tornado.web.Application([
            (r"/", MainHandler),
        ])

    if __name__ == "__main__":
        app = make_app()
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()

This example does not use any of Tornado's asynchronous features; for
that see this `simple chat room
<https://github.com/tornadoweb/tornado/tree/stable/demos/chat>`_.

Installation
------------

::

    pip install tornado

Tornado is listed in `PyPI <http://pypi.python.org/pypi/tornado>`_ and
can be installed with ``pip``. Note that the source distribution
includes demo applications that are not present when Tornado is
installed in this way, so you may wish to download a copy of the
source tarball or clone the `git repository
<https://github.com/tornadoweb/tornado>`_ as well.

**Prerequisites**: Tornado runs on Python 2.7, and 3.4+
For Python 2, version 2.7.9 or newer is *strongly*
recommended for the improved SSL support. In addition to the requirements
which will be installed automatically by ``pip`` or ``setup.py install``,
the following optional packages may be useful:

* `concurrent.futures <https://pypi.python.org/pypi/futures>`_ is the
  recommended thread pool for use with Tornado and enables the use of
  `~tornado.netutil.ThreadedResolver`.  It is needed only on Python 2;
  Python 3 includes this package in the standard library.
* `pycurl <http://pycurl.sourceforge.net>`_ is used by the optional
  ``tornado.curl_httpclient``.  Libcurl version 7.22 or higher is required.
* `Twisted <http://www.twistedmatrix.com>`_ may be used with the classes in
  `tornado.platform.twisted`.
* `pycares <https://pypi.python.org/pypi/pycares>`_ is an alternative
  non-blocking DNS resolver that can be used when threads are not
  appropriate.
* `monotonic <https://pypi.python.org/pypi/monotonic>`_ or `Monotime
  <https://pypi.python.org/pypi/Monotime>`_ add support for a
  monotonic clock, which improves reliability in environments where
  clock adjustments are frequent. No longer needed in Python 3.

**Platforms**: Tornado should run on any Unix-like platform, although
for the best performance and scalability only Linux (with ``epoll``)
and BSD (with ``kqueue``) are recommended for production deployment
(even though Mac OS X is derived from BSD and supports kqueue, its
networking performance is generally poor so it is recommended only for
development use).  Tornado will also run on Windows, although this
configuration is not officially supported and is recommended only for
development use. Without reworking Tornado IOLoop interface, it's not
possible to add a native Tornado Windows IOLoop implementation or
leverage Windows' IOCP support from frameworks like AsyncIO or Twisted.

Documentation
-------------

This documentation is also available in `PDF and Epub formats
<https://readthedocs.org/projects/tornado/downloads/>`_.

.. toctree::
   :titlesonly:

   guide
   webframework
   http
   networking
   coroutine
   integration
   utilities
   faq
   releases

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Discussion and support
----------------------

You can discuss Tornado on `the Tornado developer mailing list
<http://groups.google.com/group/python-tornado>`_, and report bugs on
the `GitHub issue tracker
<https://github.com/tornadoweb/tornado/issues>`_.  Links to additional
resources can be found on the `Tornado wiki
<https://github.com/tornadoweb/tornado/wiki/Links>`_.  New releases are
announced on the `announcements mailing list
<http://groups.google.com/group/python-tornado-announce>`_.

Tornado is available under
the `Apache License, Version 2.0
<http://www.apache.org/licenses/LICENSE-2.0.html>`_.

This web site and all documentation is licensed under `Creative
Commons 3.0 <http://creativecommons.org/licenses/by/3.0/>`_.


text:
package org.apache.nifi.web.api.dto;

import com.wordnik.swagger.annotations.ApiModelProperty;
import javax.xml.bind.annotation.XmlType;

/**
 * Banners that should appear on the top and bottom of this NiFi.
 */
@XmlType(name = "banners")
public class BannerDTO {

    private String headerText;
    private String footerText;

    /* getters / setters */
    /**
     * The banner footer text.
     *
     * @return The footer text
     */
    @ApiModelProperty(
            value = "The footer text."
    )
    public String getFooterText() {
        return footerText;
    }

    public void setFooterText(String footerText) {
        this.footerText = footerText;
    }

    /**
     * The banner header text.
     *
     * @return The header text
     */
    @ApiModelProperty(
            value = "The header text."
    )
    public String getHeaderText() {
        return headerText;
    }

    public void setHeaderText(String headerText) {
        this.headerText = headerText;
    }

}


text:
@interface NSWindow (GrowlAdditions)

- (NSPoint)frameOrigin;
- (NSSize)frameSize;

@end


text:
#include "utils/includes.h"

#include "utils/common.h"
#include "utils/eloop.h"
#include "drivers/driver.h"
#include "radius/radius.h"
#include "radius/radius_client.h"
#include "hostapd.h"
#include "ieee802_1x.h"
#include "ap_config.h"
#include "sta_info.h"
#include "ap_drv_ops.h"
#include "accounting.h"

/* Default interval in seconds for polling TX/RX octets from the driver if
 * STA is not using interim accounting. This detects wrap arounds for
 * input/output octets and updates Acct-{Input,Output}-Gigawords. */
#define ACCT_DEFAULT_UPDATE_INTERVAL 300

static void accounting_sta_get_id(struct hostapd_data *hapd,
				  struct sta_info *sta);

static struct radius_msg * accounting_msg(struct hostapd_data *hapd,
					  struct sta_info *sta,
					  int status_type)
{
	struct radius_msg *msg;
	char buf[128];
	u8 *val;
	size_t len;
	int i;

	msg = radius_msg_new(RADIUS_CODE_ACCOUNTING_REQUEST,
			     radius_client_get_id(hapd->radius));
	if (msg == NULL) {
		printf("Could not create net RADIUS packet\n");
		return NULL;
	}

	if (sta) {
		radius_msg_make_authenticator(msg, (u8 *) sta, sizeof(*sta));

		os_snprintf(buf, sizeof(buf), "%08X-%08X",
			    sta->acct_session_id_hi, sta->acct_session_id_lo);
		if (!radius_msg_add_attr(msg, RADIUS_ATTR_ACCT_SESSION_ID,
					 (u8 *) buf, os_strlen(buf))) {
			printf("Could not add Acct-Session-Id\n");
			goto fail;
		}
	} else {
		radius_msg_make_authenticator(msg, (u8 *) hapd, sizeof(*hapd));
	}

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_ACCT_STATUS_TYPE,
				       status_type)) {
		printf("Could not add Acct-Status-Type\n");
		goto fail;
	}

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_ACCT_AUTHENTIC,
				       hapd->conf->ieee802_1x ?
				       RADIUS_ACCT_AUTHENTIC_RADIUS :
				       RADIUS_ACCT_AUTHENTIC_LOCAL)) {
		printf("Could not add Acct-Authentic\n");
		goto fail;
	}

	if (sta) {
		val = ieee802_1x_get_identity(sta->eapol_sm, &len);
		if (!val) {
			os_snprintf(buf, sizeof(buf), RADIUS_ADDR_FORMAT,
				    MAC2STR(sta->addr));
			val = (u8 *) buf;
			len = os_strlen(buf);
		}

		if (!radius_msg_add_attr(msg, RADIUS_ATTR_USER_NAME, val,
					 len)) {
			printf("Could not add User-Name\n");
			goto fail;
		}
	}

	if (hapd->conf->own_ip_addr.af == AF_INET &&
	    !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IP_ADDRESS,
				 (u8 *) &hapd->conf->own_ip_addr.u.v4, 4)) {
		printf("Could not add NAS-IP-Address\n");
		goto fail;
	}

#ifdef CONFIG_IPV6
	if (hapd->conf->own_ip_addr.af == AF_INET6 &&
	    !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IPV6_ADDRESS,
				 (u8 *) &hapd->conf->own_ip_addr.u.v6, 16)) {
		printf("Could not add NAS-IPv6-Address\n");
		goto fail;
	}
#endif /* CONFIG_IPV6 */

	if (hapd->conf->nas_identifier &&
	    !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IDENTIFIER,
				 (u8 *) hapd->conf->nas_identifier,
				 os_strlen(hapd->conf->nas_identifier))) {
		printf("Could not add NAS-Identifier\n");
		goto fail;
	}

	if (sta &&
	    !radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT, sta->aid)) {
		printf("Could not add NAS-Port\n");
		goto fail;
	}

	os_snprintf(buf, sizeof(buf), RADIUS_802_1X_ADDR_FORMAT ":%s",
		    MAC2STR(hapd->own_addr), hapd->conf->ssid.ssid);
	if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLED_STATION_ID,
				 (u8 *) buf, os_strlen(buf))) {
		printf("Could not add Called-Station-Id\n");
		goto fail;
	}

	if (sta) {
		os_snprintf(buf, sizeof(buf), RADIUS_802_1X_ADDR_FORMAT,
			    MAC2STR(sta->addr));
		if (!radius_msg_add_attr(msg, RADIUS_ATTR_CALLING_STATION_ID,
					 (u8 *) buf, os_strlen(buf))) {
			printf("Could not add Calling-Station-Id\n");
			goto fail;
		}

		if (!radius_msg_add_attr_int32(
			    msg, RADIUS_ATTR_NAS_PORT_TYPE,
			    RADIUS_NAS_PORT_TYPE_IEEE_802_11)) {
			printf("Could not add NAS-Port-Type\n");
			goto fail;
		}

		os_snprintf(buf, sizeof(buf), "CONNECT %d%sMbps %s",
			    radius_sta_rate(hapd, sta) / 2,
			    (radius_sta_rate(hapd, sta) & 1) ? ".5" : "",
			    radius_mode_txt(hapd));
		if (!radius_msg_add_attr(msg, RADIUS_ATTR_CONNECT_INFO,
					 (u8 *) buf, os_strlen(buf))) {
			printf("Could not add Connect-Info\n");
			goto fail;
		}

		for (i = 0; ; i++) {
			val = ieee802_1x_get_radius_class(sta->eapol_sm, &len,
							  i);
			if (val == NULL)
				break;

			if (!radius_msg_add_attr(msg, RADIUS_ATTR_CLASS,
						 val, len)) {
				printf("Could not add Class\n");
				goto fail;
			}
		}
	}

	return msg;

 fail:
	radius_msg_free(msg);
	return NULL;
}

static int accounting_sta_update_stats(struct hostapd_data *hapd,
				       struct sta_info *sta,
				       struct hostap_sta_driver_data *data)
{
	if (hostapd_drv_read_sta_data(hapd, data, sta->addr))
		return -1;

	if (sta->last_rx_bytes > data->rx_bytes)
		sta->acct_input_gigawords++;
	if (sta->last_tx_bytes > data->tx_bytes)
		sta->acct_output_gigawords++;
	sta->last_rx_bytes = data->rx_bytes;
	sta->last_tx_bytes = data->tx_bytes;

	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS,
		       HOSTAPD_LEVEL_DEBUG, "updated TX/RX stats: "
		       "Acct-Input-Octets=%lu Acct-Input-Gigawords=%u "
		       "Acct-Output-Octets=%lu Acct-Output-Gigawords=%u",
		       sta->last_rx_bytes, sta->acct_input_gigawords,
		       sta->last_tx_bytes, sta->acct_output_gigawords);

	return 0;
}

static void accounting_interim_update(void *eloop_ctx, void *timeout_ctx)
{
	struct hostapd_data *hapd = eloop_ctx;
	struct sta_info *sta = timeout_ctx;
	int interval;

	if (sta->acct_interim_interval) {
		accounting_sta_interim(hapd, sta);
		interval = sta->acct_interim_interval;
	} else {
		struct hostap_sta_driver_data data;
		accounting_sta_update_stats(hapd, sta, &data);
		interval = ACCT_DEFAULT_UPDATE_INTERVAL;
	}

	eloop_register_timeout(interval, 0, accounting_interim_update,
			       hapd, sta);
}

/**
 * accounting_sta_start - Start STA accounting
 * @hapd: hostapd BSS data
 * @sta: The station
 */
void accounting_sta_start(struct hostapd_data *hapd, struct sta_info *sta)
{
	struct radius_msg *msg;
	int interval;

	if (sta->acct_session_started)
		return;

	accounting_sta_get_id(hapd, sta);
	hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS,
		       HOSTAPD_LEVEL_INFO,
		       "starting accounting session %08X-%08X",
		       sta->acct_session_id_hi, sta->acct_session_id_lo);

	time(&sta->acct_session_start);
	sta->last_rx_bytes = sta->last_tx_bytes = 0;
	sta->acct_input_gigawords = sta->acct_output_gigawords = 0;
	hostapd_drv_sta_clear_stats(hapd, sta->addr);

	if (!hapd->conf->radius->acct_server)
		return;

	if (sta->acct_interim_interval)
		interval = sta->acct_interim_interval;
	else
		interval = ACCT_DEFAULT_UPDATE_INTERVAL;
	eloop_register_timeout(interval, 0, accounting_interim_update,
			       hapd, sta);

	msg = accounting_msg(hapd, sta, RADIUS_ACCT_STATUS_TYPE_START);
	if (msg)
		radius_client_send(hapd->radius, msg, RADIUS_ACCT, sta->addr);

	sta->acct_session_started = 1;
}

static void accounting_sta_report(struct hostapd_data *hapd,
				  struct sta_info *sta, int stop)
{
	struct radius_msg *msg;
	int cause = sta->acct_terminate_cause;
	struct hostap_sta_driver_data data;
	struct os_time now;
	u32 gigawords;

	if (!hapd->conf->radius->acct_server)
		return;

	msg = accounting_msg(hapd, sta,
			     stop ? RADIUS_ACCT_STATUS_TYPE_STOP :
			     RADIUS_ACCT_STATUS_TYPE_INTERIM_UPDATE);
	if (!msg) {
		printf("Could not create RADIUS Accounting message\n");
		return;
	}

	os_get_time(&now);
	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_ACCT_SESSION_TIME,
				       now.sec - sta->acct_session_start)) {
		printf("Could not add Acct-Session-Time\n");
		goto fail;
	}

	if (accounting_sta_update_stats(hapd, sta, &data) == 0) {
		if (!radius_msg_add_attr_int32(msg,
					       RADIUS_ATTR_ACCT_INPUT_PACKETS,
					       data.rx_packets)) {
			printf("Could not add Acct-Input-Packets\n");
			goto fail;
		}
		if (!radius_msg_add_attr_int32(msg,
					       RADIUS_ATTR_ACCT_OUTPUT_PACKETS,
					       data.tx_packets)) {
			printf("Could not add Acct-Output-Packets\n");
			goto fail;
		}
		if (!radius_msg_add_attr_int32(msg,
					       RADIUS_ATTR_ACCT_INPUT_OCTETS,
					       data.rx_bytes)) {
			printf("Could not add Acct-Input-Octets\n");
			goto fail;
		}
		gigawords = sta->acct_input_gigawords;
#if __WORDSIZE == 64
		gigawords += data.rx_bytes >> 32;
#endif
		if (gigawords &&
		    !radius_msg_add_attr_int32(
			    msg, RADIUS_ATTR_ACCT_INPUT_GIGAWORDS,
			    gigawords)) {
			printf("Could not add Acct-Input-Gigawords\n");
			goto fail;
		}
		if (!radius_msg_add_attr_int32(msg,
					       RADIUS_ATTR_ACCT_OUTPUT_OCTETS,
					       data.tx_bytes)) {
			printf("Could not add Acct-Output-Octets\n");
			goto fail;
		}
		gigawords = sta->acct_output_gigawords;
#if __WORDSIZE == 64
		gigawords += data.tx_bytes >> 32;
#endif
		if (gigawords &&
		    !radius_msg_add_attr_int32(
			    msg, RADIUS_ATTR_ACCT_OUTPUT_GIGAWORDS,
			    gigawords)) {
			printf("Could not add Acct-Output-Gigawords\n");
			goto fail;
		}
	}

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_EVENT_TIMESTAMP,
				       now.sec)) {
		printf("Could not add Event-Timestamp\n");
		goto fail;
	}

	if (eloop_terminated())
		cause = RADIUS_ACCT_TERMINATE_CAUSE_ADMIN_REBOOT;

	if (stop && cause &&
	    !radius_msg_add_attr_int32(msg, RADIUS_ATTR_ACCT_TERMINATE_CAUSE,
				       cause)) {
		printf("Could not add Acct-Terminate-Cause\n");
		goto fail;
	}

	radius_client_send(hapd->radius, msg,
			   stop ? RADIUS_ACCT : RADIUS_ACCT_INTERIM,
			   sta->addr);
	return;

 fail:
	radius_msg_free(msg);
}

/**
 * accounting_sta_interim - Send a interim STA accounting report
 * @hapd: hostapd BSS data
 * @sta: The station
 */
void accounting_sta_interim(struct hostapd_data *hapd, struct sta_info *sta)
{
	if (sta->acct_session_started)
		accounting_sta_report(hapd, sta, 0);
}

/**
 * accounting_sta_stop - Stop STA accounting
 * @hapd: hostapd BSS data
 * @sta: The station
 */
void accounting_sta_stop(struct hostapd_data *hapd, struct sta_info *sta)
{
	if (sta->acct_session_started) {
		accounting_sta_report(hapd, sta, 1);
		eloop_cancel_timeout(accounting_interim_update, hapd, sta);
		hostapd_logger(hapd, sta->addr, HOSTAPD_MODULE_RADIUS,
			       HOSTAPD_LEVEL_INFO,
			       "stopped accounting session %08X-%08X",
			       sta->acct_session_id_hi,
			       sta->acct_session_id_lo);
		sta->acct_session_started = 0;
	}
}

static void accounting_sta_get_id(struct hostapd_data *hapd,
				  struct sta_info *sta)
{
	sta->acct_session_id_lo = hapd->acct_session_id_lo++;
	if (hapd->acct_session_id_lo == 0) {
		hapd->acct_session_id_hi++;
	}
	sta->acct_session_id_hi = hapd->acct_session_id_hi;
}

/**
 * accounting_receive - Process the RADIUS frames from Accounting Server
 * @msg: RADIUS response message
 * @req: RADIUS request message
 * @shared_secret: RADIUS shared secret
 * @shared_secret_len: Length of shared_secret in octets
 * @data: Context data (struct hostapd_data *)
 * Returns: Processing status
 */
static RadiusRxResult
accounting_receive(struct radius_msg *msg, struct radius_msg *req,
		   const u8 *shared_secret, size_t shared_secret_len,
		   void *data)
{
	if (radius_msg_get_hdr(msg)->code != RADIUS_CODE_ACCOUNTING_RESPONSE) {
		printf("Unknown RADIUS message code\n");
		return RADIUS_RX_UNKNOWN;
	}

	if (radius_msg_verify(msg, shared_secret, shared_secret_len, req, 0)) {
		printf("Incoming RADIUS packet did not have correct "
		       "Authenticator - dropped\n");
		return RADIUS_RX_INVALID_AUTHENTICATOR;
	}

	return RADIUS_RX_PROCESSED;
}

static void accounting_report_state(struct hostapd_data *hapd, int on)
{
	struct radius_msg *msg;

	if (!hapd->conf->radius->acct_server || hapd->radius == NULL)
		return;

	/* Inform RADIUS server that accounting will start/stop so that the
	 * server can close old accounting sessions. */
	msg = accounting_msg(hapd, NULL,
			     on ? RADIUS_ACCT_STATUS_TYPE_ACCOUNTING_ON :
			     RADIUS_ACCT_STATUS_TYPE_ACCOUNTING_OFF);
	if (!msg)
		return;

	if (!radius_msg_add_attr_int32(msg, RADIUS_ATTR_ACCT_TERMINATE_CAUSE,
				       RADIUS_ACCT_TERMINATE_CAUSE_NAS_REBOOT))
	{
		printf("Could not add Acct-Terminate-Cause\n");
		radius_msg_free(msg);
		return;
	}

	radius_client_send(hapd->radius, msg, RADIUS_ACCT, NULL);
}

/**
 * accounting_init: Initialize accounting
 * @hapd: hostapd BSS data
 * Returns: 0 on success, -1 on failure
 */
int accounting_init(struct hostapd_data *hapd)
{
	struct os_time now;

	/* Acct-Session-Id should be unique over reboots. If reliable clock is
	 * not available, this could be replaced with reboot counter, etc. */
	os_get_time(&now);
	hapd->acct_session_id_hi = now.sec;

	if (radius_client_register(hapd->radius, RADIUS_ACCT,
				   accounting_receive, hapd))
		return -1;

	accounting_report_state(hapd, 1);

	return 0;
}

/**
 * accounting_deinit: Deinitilize accounting
 * @hapd: hostapd BSS data
 */
void accounting_deinit(struct hostapd_data *hapd)
{
	accounting_report_state(hapd, 0);
}


text:
import "./css/site.css";

import React from "react";
import ReactDOM from "react-dom";
import { MemoryRouter as Router } from "react-router";
import { Provider } from "mobx-react";
import { AppContainer } from "react-hot-loader";
if (DEBUG) var DevTools = require("mobx-react-devtools").default;

import stores from "./stores";
import App from "COMPONENTS/App.dev";

ReactDOM.render(
  <AppContainer>
    <Provider {...stores}>
      <Router>
        <App />
      </Router>
    </Provider>
  </AppContainer>,
  document.getElementById('app')
);

// Hot-reloading
if (module.hot) {
  module.hot.accept();
}


text:
class DWARFUnit;
class DWARFCompileUnit;
class NameToDIE;
class SymbolFileDWARF;
class SymbolFileDWARFDwo;

typedef std::shared_ptr<DWARFUnit> DWARFUnitSP;

enum DWARFProducer {
  eProducerInvalid = 0,
  eProducerClang,
  eProducerGCC,
  eProducerLLVMGCC,
  eProcucerOther
};

class DWARFUnit {
  using die_iterator_range =
      llvm::iterator_range<DWARFDebugInfoEntry::collection::iterator>;

public:
  virtual ~DWARFUnit();

  void ExtractUnitDIEIfNeeded();
  void ExtractDIEsIfNeeded();

  class ScopedExtractDIEs {
    DWARFUnit *m_cu;
  public:
    bool m_clear_dies = false;
    ScopedExtractDIEs(DWARFUnit *cu);
    ~ScopedExtractDIEs();
    DISALLOW_COPY_AND_ASSIGN(ScopedExtractDIEs);
    ScopedExtractDIEs(ScopedExtractDIEs &&rhs);
    ScopedExtractDIEs &operator=(ScopedExtractDIEs &&rhs);
  };
  ScopedExtractDIEs ExtractDIEsScoped();

  DWARFDIE LookupAddress(const dw_addr_t address);
  size_t AppendDIEsWithTag(const dw_tag_t tag,
                           DWARFDIECollection &matching_dies,
                           uint32_t depth = UINT32_MAX) const;
  bool Verify(lldb_private::Stream *s) const;
  virtual void Dump(lldb_private::Stream *s) const = 0;
  //------------------------------------------------------------------
  /// Get the data that contains the DIE information for this unit.
  ///
  /// This will return the correct bytes that contain the data for
  /// this DWARFUnit. It could be .debug_info or .debug_types
  /// depending on where the data for this unit originates.
  ///
  /// @return
  ///   The correct data for the DIE information in this unit.
  //------------------------------------------------------------------
  virtual const lldb_private::DWARFDataExtractor &GetData() const = 0;
  //------------------------------------------------------------------
  /// Get the size in bytes of the compile unit header.
  ///
  /// @return
  ///     Byte size of the compile unit header
  //------------------------------------------------------------------
  virtual uint32_t GetHeaderByteSize() const = 0;
  // Offset of the initial length field.
  dw_offset_t GetOffset() const { return m_offset; }
  lldb::user_id_t GetID() const;
  //------------------------------------------------------------------
  /// Get the size in bytes of the length field in the header.
  ///
  /// In DWARF32 this is just 4 bytes, and DWARF64 it is 12 where 4
  /// are 0xFFFFFFFF followed by the actual 64 bit length.
  ///
  /// @return
  ///     Byte size of the compile unit header length field
  //------------------------------------------------------------------
  size_t GetLengthByteSize() const { return IsDWARF64() ? 12 : 4; }

  bool ContainsDIEOffset(dw_offset_t die_offset) const {
    return die_offset >= GetFirstDIEOffset() &&
           die_offset < GetNextCompileUnitOffset();
  }
  dw_offset_t GetFirstDIEOffset() const {
    return m_offset + GetHeaderByteSize();
  }
  dw_offset_t GetNextCompileUnitOffset() const;
  // Size of the CU data (without initial length and without header).
  size_t GetDebugInfoSize() const;
  // Size of the CU data incl. header but without initial length.
  uint32_t GetLength() const { return m_length; }
  uint16_t GetVersion() const { return m_version; }
  const DWARFAbbreviationDeclarationSet *GetAbbreviations() const;
  dw_offset_t GetAbbrevOffset() const;
  uint8_t GetAddressByteSize() const { return m_addr_size; }
  dw_addr_t GetBaseAddress() const { return m_base_addr; }
  dw_addr_t GetAddrBase() const { return m_addr_base; }
  dw_addr_t GetRangesBase() const { return m_ranges_base; }
  void SetAddrBase(dw_addr_t addr_base, dw_addr_t ranges_base,
                   dw_offset_t base_obj_offset);
  void BuildAddressRangeTable(SymbolFileDWARF *dwarf,
                              DWARFDebugAranges *debug_aranges);

  lldb::ByteOrder GetByteOrder() const;

  lldb_private::TypeSystem *GetTypeSystem();

  const DWARFDebugAranges &GetFunctionAranges();

  DWARFFormValue::FixedFormSizes GetFixedFormSizes();

  void SetBaseAddress(dw_addr_t base_addr);

  DWARFBaseDIE GetUnitDIEOnly() { return DWARFDIE(this, GetUnitDIEPtrOnly()); }

  DWARFDIE DIE() { return DWARFDIE(this, DIEPtr()); }

  DWARFDIE GetDIE(dw_offset_t die_offset);

  static uint8_t GetAddressByteSize(const DWARFUnit *cu);

  static bool IsDWARF64(const DWARFUnit *cu);

  static uint8_t GetDefaultAddressSize();

  void *GetUserData() const;

  void SetUserData(void *d);

  bool Supports_DW_AT_APPLE_objc_complete_type();

  bool DW_AT_decl_file_attributes_are_invalid();

  bool Supports_unnamed_objc_bitfields();

  SymbolFileDWARF *GetSymbolFileDWARF() const;

  DWARFProducer GetProducer();

  uint32_t GetProducerVersionMajor();

  uint32_t GetProducerVersionMinor();

  uint32_t GetProducerVersionUpdate();

  static lldb::LanguageType LanguageTypeFromDWARF(uint64_t val);

  lldb::LanguageType GetLanguageType();

  bool IsDWARF64() const { return m_is_dwarf64; }

  bool GetIsOptimized();

  SymbolFileDWARFDwo *GetDwoSymbolFile() const;

  dw_offset_t GetBaseObjOffset() const;

  die_iterator_range dies() {
    ExtractDIEsIfNeeded();
    return die_iterator_range(m_die_array.begin(), m_die_array.end());
  }

protected:
  DWARFUnit(SymbolFileDWARF *dwarf);

  SymbolFileDWARF *m_dwarf = nullptr;
  std::unique_ptr<SymbolFileDWARFDwo> m_dwo_symbol_file;
  const DWARFAbbreviationDeclarationSet *m_abbrevs = nullptr;
  void *m_user_data = nullptr;
  // The compile unit debug information entry item
  DWARFDebugInfoEntry::collection m_die_array;
  mutable llvm::sys::RWMutex m_die_array_mutex;
  // It is used for tracking of ScopedExtractDIEs instances.
  mutable llvm::sys::RWMutex m_die_array_scoped_mutex;
  // ScopedExtractDIEs instances should not call ClearDIEsRWLocked()
  // as someone called ExtractDIEsIfNeeded().
  std::atomic<bool> m_cancel_scopes;
  // GetUnitDIEPtrOnly() needs to return pointer to the first DIE.
  // But the first element of m_die_array after ExtractUnitDIEIfNeeded()
  // would possibly move in memory after later ExtractDIEsIfNeeded().
  DWARFDebugInfoEntry m_first_die;
  llvm::sys::RWMutex m_first_die_mutex;
  // A table similar to the .debug_aranges table, but this one points to the
  // exact DW_TAG_subprogram DIEs
  std::unique_ptr<DWARFDebugAranges> m_func_aranges_ap;
  dw_addr_t m_base_addr = 0;
  dw_offset_t m_length = 0;
  uint16_t m_version = 0;
  uint8_t m_addr_size = 0;
  DWARFProducer m_producer = eProducerInvalid;
  uint32_t m_producer_version_major = 0;
  uint32_t m_producer_version_minor = 0;
  uint32_t m_producer_version_update = 0;
  lldb::LanguageType m_language_type = lldb::eLanguageTypeUnknown;
  bool m_is_dwarf64 = false;
  lldb_private::LazyBool m_is_optimized = lldb_private::eLazyBoolCalculate;
  dw_addr_t m_addr_base = 0;   // Value of DW_AT_addr_base
  dw_addr_t m_ranges_base = 0; // Value of DW_AT_ranges_base
  // If this is a dwo compile unit this is the offset of the base compile unit
  // in the main object file
  dw_offset_t m_base_obj_offset = DW_INVALID_OFFSET;

  // Offset of the initial length field.
  dw_offset_t m_offset;

private:
  void ParseProducerInfo();
  void ExtractDIEsRWLocked();
  void ClearDIEsRWLocked();

  // Get the DWARF unit DWARF debug informration entry. Parse the single DIE
  // if needed.
  const DWARFDebugInfoEntry *GetUnitDIEPtrOnly() {
    ExtractUnitDIEIfNeeded();
    // m_first_die_mutex is not required as m_first_die is never cleared.
    if (!m_first_die)
      return NULL;
    return &m_first_die;
  }

  // Get all DWARF debug informration entries. Parse all DIEs if needed.
  const DWARFDebugInfoEntry *DIEPtr() {
    ExtractDIEsIfNeeded();
    if (m_die_array.empty())
      return NULL;
    return &m_die_array[0];
  }

  void AddUnitDIE(const DWARFDebugInfoEntry &cu_die);
  void ExtractDIEsEndCheck(lldb::offset_t offset) const;

  DISALLOW_COPY_AND_ASSIGN(DWARFUnit);
};

#endif // SymbolFileDWARF_DWARFUnit_h_


text:
class Notification;

namespace extensions {

extern const base::Feature kAllowFullscreenAppNotificationsFeature;

class NotificationsApiFunction : public ChromeAsyncExtensionFunction {
 public:
  // Whether the current extension and channel allow the API. Public for
  // testing.
  bool IsNotificationsApiAvailable();

 protected:
  NotificationsApiFunction();
  ~NotificationsApiFunction() override;

  bool CreateNotification(const std::string& id,
                          api::notifications::NotificationOptions* options);
  bool UpdateNotification(const std::string& id,
                          api::notifications::NotificationOptions* options,
                          Notification* notification);

  bool IsNotificationsApiEnabled() const;

  bool AreExtensionNotificationsAllowed() const;

  // Returns true if the API function is still allowed to run even when the
  // notifications for a notifier have been disabled.
  virtual bool CanRunWhileDisabled() const;

  // Called inside of RunAsync.
  virtual bool RunNotificationsApi() = 0;

  // UITHreadExtensionFunction:
  bool RunAsync() override;

  message_center::NotificationType MapApiTemplateTypeToType(
      api::notifications::TemplateType type);
};

class NotificationsCreateFunction : public NotificationsApiFunction {
 public:
  NotificationsCreateFunction();

  // NotificationsApiFunction:
  bool RunNotificationsApi() override;

 protected:
  ~NotificationsCreateFunction() override;

 private:
  std::unique_ptr<api::notifications::Create::Params> params_;

  DECLARE_EXTENSION_FUNCTION("notifications.create", NOTIFICATIONS_CREATE)
};

class NotificationsUpdateFunction : public NotificationsApiFunction {
 public:
  NotificationsUpdateFunction();

  // NotificationsApiFunction:
  bool RunNotificationsApi() override;

 protected:
  ~NotificationsUpdateFunction() override;

 private:
  std::unique_ptr<api::notifications::Update::Params> params_;

  DECLARE_EXTENSION_FUNCTION("notifications.update", NOTIFICATIONS_UPDATE)
};

class NotificationsClearFunction : public NotificationsApiFunction {
 public:
  NotificationsClearFunction();

  // NotificationsApiFunction:
  bool RunNotificationsApi() override;

 protected:
  ~NotificationsClearFunction() override;

 private:
  std::unique_ptr<api::notifications::Clear::Params> params_;

  DECLARE_EXTENSION_FUNCTION("notifications.clear", NOTIFICATIONS_CLEAR)
};

class NotificationsGetAllFunction : public NotificationsApiFunction {
 public:
  NotificationsGetAllFunction();

  // NotificationsApiFunction:
  bool RunNotificationsApi() override;

 protected:
  ~NotificationsGetAllFunction() override;

 private:
  DECLARE_EXTENSION_FUNCTION("notifications.getAll", NOTIFICATIONS_GET_ALL)
};

class NotificationsGetPermissionLevelFunction
    : public NotificationsApiFunction {
 public:
  NotificationsGetPermissionLevelFunction();

  // NotificationsApiFunction:
  bool CanRunWhileDisabled() const override;
  bool RunNotificationsApi() override;

 protected:
  ~NotificationsGetPermissionLevelFunction() override;

 private:
  DECLARE_EXTENSION_FUNCTION("notifications.getPermissionLevel",
                             NOTIFICATIONS_GET_ALL)
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_NOTIFICATIONS_NOTIFICATIONS_API_H_


text:
package com.groupon.lex.metrics.history.xdr.support.writer;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import lombok.NonNull;

public class GzipWriter extends AbstractOutputStreamWriter {
    public GzipWriter(@NonNull FileWriter out) throws IOException {
        super(new GZIPOutputStream(newAdapter(out)));
    }
}