text:
import unittest
from unittest.mock import patch, Mock

from flask import Flask
from cryptography.x509 import DNSName
from lemur.plugins.lemur_acme import acme_handlers

from lemur.tests.vectors import (
    ACME_CHAIN_SHORT_STR,
    ACME_CHAIN_LONG_STR,
    SAN_CERT_STR,
)

class TestAcmeHandler(unittest.TestCase):
    def setUp(self):
        self.acme = acme_handlers.AcmeHandler()

        # Creates a new Flask application for a test duration. In python 3.8, manual push of application context is
        # needed to run tests in dev environment without getting error 'Working outside of application context'.
        _app = Flask('lemur_test_acme')
        self.ctx = _app.app_context()
        assert self.ctx
        self.ctx.push()

    def tearDown(self):
        self.ctx.pop()

    def test_strip_wildcard(self):
        expected = ("example.com", False)
        result = self.acme.strip_wildcard("example.com")
        self.assertEqual(expected, result)

        expected = ("example.com", True)
        result = self.acme.strip_wildcard("*.example.com")
        self.assertEqual(expected, result)

    def test_authz_record(self):
        a = acme_handlers.AuthorizationRecord("domain", "host", "authz", "challenge", "id", "cname_delegation")
        self.assertEqual(type(a), acme_handlers.AuthorizationRecord)

    def test_setup_acme_client_fail(self):
        mock_authority = Mock()
        mock_authority.options = []
        with self.assertRaises(Exception):
            self.acme.setup_acme_client(mock_authority)

    def test_reuse_account_not_defined(self):
        mock_authority = Mock()
        mock_authority.options = []
        with self.assertRaises(Exception):
            self.acme.reuse_account(mock_authority)

    def test_reuse_account_from_authority(self):
        mock_authority = Mock()
        mock_authority.options = '[{"name": "acme_private_key", "value": "PRIVATE_KEY"}, {"name": "acme_regr", "value": "ACME_REGR"}]'

        self.assertTrue(self.acme.reuse_account(mock_authority))

    @patch("lemur.plugins.lemur_acme.acme_handlers.current_app")
    def test_reuse_account_from_config(self, mock_current_app):
        mock_authority = Mock()
        mock_authority.options = '[{"name": "mock_name", "value": "mock_value"}]'
        mock_current_app.config = {"ACME_PRIVATE_KEY": "PRIVATE_KEY", "ACME_REGR": "ACME_REGR"}

        self.assertTrue(self.acme.reuse_account(mock_authority))

    def test_reuse_account_no_configuration(self):
        mock_authority = Mock()
        mock_authority.options = '[{"name": "mock_name", "value": "mock_value"}]'

        self.assertFalse(self.acme.reuse_account(mock_authority))

    @patch("lemur.plugins.lemur_acme.acme_handlers.authorities_service")
    @patch("lemur.plugins.lemur_acme.acme_handlers.BackwardsCompatibleClientV2")
    def test_setup_acme_client_success(self, mock_acme, mock_authorities_service):
        mock_authority = Mock()
        mock_authority.options = '[{"name": "mock_name", "value": "mock_value"}, ' \
                                 '{"name": "store_account", "value": false}]'
        mock_client = Mock()
        mock_registration = Mock()
        mock_registration.uri = "http://test.com"
        mock_client.register = mock_registration
        mock_client.agree_to_tos = Mock(return_value=True)
        mock_acme.return_value = mock_client
        result_client, result_registration = self.acme.setup_acme_client(mock_authority)
        mock_authorities_service.update_options.assert_not_called()
        assert result_client
        assert result_registration

    def test_get_domains_single(self):
        options = {"common_name": "test.netflix.net"}
        result = self.acme.get_domains(options)
        self.assertEqual(result, [options["common_name"]])

    def test_get_domains_multiple(self):
        options = {
            "common_name": "test.netflix.net",
            "extensions": {
                "sub_alt_names": {"names": [DNSName("test2.netflix.net"), DNSName("test3.netflix.net")]}
            },
        }
        result = self.acme.get_domains(options)
        self.assertEqual(
            result, [options["common_name"], "test2.netflix.net", "test3.netflix.net"]
        )

    def test_get_domains_san(self):
        options = {
            "common_name": "test.netflix.net",
            "extensions": {
                "sub_alt_names": {"names": [DNSName("test.netflix.net"), DNSName("test2.netflix.net")]}
            },
        }
        result = self.acme.get_domains(options)
        self.assertEqual(
            result, [options["common_name"], "test2.netflix.net"]
        )

    def test_extract_cert_and_chain(self):
        # expecting the short chain
        leaf_pem, chain_pem = self.acme.extract_cert_and_chain(ACME_CHAIN_SHORT_STR,
                                                               [ACME_CHAIN_LONG_STR],
                                                               "(STAGING) Artificial Apricot R3")
        self.assertEqual(leaf_pem, SAN_CERT_STR)
        self.assertEqual(chain_pem, ACME_CHAIN_SHORT_STR[len(leaf_pem):].lstrip())

        # expecting the long chain
        leaf_pem, chain_pem = self.acme.extract_cert_and_chain(ACME_CHAIN_SHORT_STR,
                                                               [ACME_CHAIN_LONG_STR],
                                                               "(STAGING) Doctored Durian Root CA X3")
        self.assertEqual(leaf_pem, SAN_CERT_STR)
        self.assertEqual(chain_pem, ACME_CHAIN_LONG_STR[len(leaf_pem):].lstrip())


text:
import { Component } from '@angular/core';

@Component({
    selector: "uploader-with-file",
    template: `<ng-content></ng-content>`
})

/**
 * Modal body
 */
export class UploaderWithFileComponent {
}

redpajama_set_name: RedPajamaGithub


text:
<#
Copyright 2016 Iain Brighton

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

function Set-NSLBSSLVirtualServerProfile {
    <#
    .SYNOPSIS
        Updates an existing load balancing virtual server's SSL profile.

    .DESCRIPTION
        Updates an existing load balancing virtual server's SSL profile.

    .EXAMPLE
        Set-NSLBSSLVirtualServerProfile -Name 'vserver01' -ProfileName 'sslprofile01'

        Sets the load balancing virtual server SSL profile to 'sslprofile01'

    .PARAMETER Session
        The NetScaler session object.

    .PARAMETER Name
        The name or names of the load balancer virtual servers to set.

    .PARAMETER ProfileName
        The SSL profile name to assign to the virtual server.

    .PARAMETER Force
        Suppress confirmation when updating a virtual server.

    .PARAMETER Passthru
        Return the virtual server object.
    #>
    [cmdletbinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param(
        $Session = $script:session,

        [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName)]
        [alias('VirtualServerName')]
        [string[]]$Name,

        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName)]
        [string]$ProfileName,

        [Switch]$Force,

        [Switch]$PassThru
    )

    begin {
        _AssertSessionActive
    }

    process {
        foreach ($item in $Name) {
            if ($Force -or $PSCmdlet.ShouldProcess($item, 'Edit Virtual Server')) {
                try {
                    $params = @{
                        vservername = $item;
                        sslprofile = $ProfileName;
                    }

                    _InvokeNSRestApi -Session $Session -Method PUT -Type sslvserver -Payload $params

                    if ($PSBoundParameters.ContainsKey('PassThru')) {
                        return Get-NSLBVirtualServerSslProfile -Session $Session -Name $item
                    }
                }
                catch {
                    throw $_
                }
            }
        }
    }
}


text:
from k5test import *

# This file contains tests for kadmin command parsing.  Principal
# flags (which can also be used in kadm5.acl or krb5.conf) are tested
# in t_princflags.py.

# kadmin recognizes time intervals using either the
# krb5_string_to_deltat() formats or the relative getdate.y formats.
# (Absolute getdate.y formats also work with the current time
# subtracted; this isn't very useful and we won't test it here.)
intervals = (
    # krb5_string_to_deltat() formats.  Whitespace ( \t\n) is allowed
    # before or between most elements or at the end, but not after
    # 's'.  Negative or oversized numbers are allowed in most places,
    # but not after the first number in an HH:MM:SS form.
    ('28s', '0 days 00:00:28'),
    ('7m ', '0 days 00:07:00'),
    ('6m 9s', '0 days 00:06:09'),
    ('2h', '0 days 02:00:00'),
    ('2h-5s', '0 days 01:59:55'),
    ('2h3m', '0 days 02:03:00'),
    ('2h3m5s', '0 days 02:03:05'),
    ('5d ', '5 days 00:00:00'),
    ('5d-48s', '4 days 23:59:12'),
    ('5d18m', '5 days 00:18:00'),
    ('5d -6m56s', '4 days 23:54:56'),
    ('5d4h', '5 days 04:00:00'),
    ('5d4h 1s', '5 days 04:00:01'),
    ('5d4h3m', '5 days 04:03:00'),
    (' \t 15d \n 4h  3m  2s', '15 days 04:03:02'),
    ('10-8:45:0', '10 days 08:45:00'),
    ('1000:67:99', '41 days 17:08:39'),
    ('999:11', '41 days 15:11:00'),
    ('382512', '4 days 10:15:12'),

    # getdate.y relative formats (and "never", which is handled
    # specially as a zero interval).  Any number of relative forms can
    # be specified in any order.  Whitespace is ignored before or
    # after any token.  "month" and "year" are allowed as units but
    # depend on the current time, so we won't test them.  Plural unit
    # names are treated identically to singular unit names.  Numbers
    # before unit names are optional and may be signed; there are also
    # aliases for some numbers.  "ago" inverts the interval up to the
    # point where it appears.
    ('never', '0 days 00:00:00'),
    ('fortnight', '14 days 00:00:00'),
    ('3 day ago 4 weeks 8 hours', '25 days 08:00:00'),
    ('8 second -3 secs 5 minute ago 63 min', '0 days 00:57:55'),
    ('min mins min mins min', '0 days 00:05:00'),
    ('tomorrow tomorrow today yesterday now last minute', '0 days 23:59:00'),
    ('this second next minute first hour third fortnight fourth day '
     'fifth weeks sixth sec seventh secs eighth second ninth mins tenth '
     'day eleventh min twelfth sec', '91 days 01:22:34'))

realm = K5Realm(create_host=False, get_creds=False)
realm.run([kadminl, 'addpol', 'pol'])
for instr, outstr in intervals:
    realm.run([kadminl, 'modprinc', '-maxlife', instr, realm.user_princ])
    msg = 'Maximum ticket life: ' + outstr + '\n'
    realm.run([kadminl, 'getprinc', realm.user_princ], expected_msg=msg)

    realm.run([kadminl, 'modprinc', '-maxrenewlife', instr, realm.user_princ])
    msg = 'Maximum renewable life: ' + outstr + '\n'
    realm.run([kadminl, 'getprinc', realm.user_princ], expected_msg=msg)

    realm.run([kadminl, 'modpol', '-maxlife', instr, 'pol'])
    msg = 'Maximum password life: ' + outstr + '\n'
    realm.run([kadminl, 'getpol', 'pol'], expected_msg=msg)

    realm.run([kadminl, 'modpol', '-minlife', instr, 'pol'])
    msg = 'Minimum password life: ' + outstr + '\n'
    realm.run([kadminl, 'getpol', 'pol'], expected_msg=msg)

    realm.run([kadminl, 'modpol', '-failurecountinterval', instr, 'pol'])
    msg = 'Password failure count reset interval: ' + outstr + '\n'
    realm.run([kadminl, 'getpol', 'pol'], expected_msg=msg)

    realm.run([kadminl, 'modpol', '-lockoutduration', instr, 'pol'])
    msg = 'Password lockout duration: ' + outstr + '\n'
    realm.run([kadminl, 'getpol', 'pol'], expected_msg=msg)

success('kadmin command parsing tests')


text:
package common

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

type MSPPrincipal_Classification int32

const (
	MSPPrincipal_ByMSPRole MSPPrincipal_Classification = 0
	// one of a member of MSP network, and the one of an
	// administrator of an MSP network
	MSPPrincipal_ByOrganizationUnit MSPPrincipal_Classification = 1
	// groupping of entities, per MSP affiliation
	// E.g., this can well be represented by an MSP's
	// Organization unit
	MSPPrincipal_ByIdentity MSPPrincipal_Classification = 2
)

var MSPPrincipal_Classification_name = map[int32]string{
	0: "ByMSPRole",
	1: "ByOrganizationUnit",
	2: "ByIdentity",
}
var MSPPrincipal_Classification_value = map[string]int32{
	"ByMSPRole":          0,
	"ByOrganizationUnit": 1,
	"ByIdentity":         2,
}

func (x MSPPrincipal_Classification) String() string {
	return proto.EnumName(MSPPrincipal_Classification_name, int32(x))
}
func (MSPPrincipal_Classification) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor3, []int{0, 0}
}

type MSPRole_MSPRoleType int32

const (
	MSPRole_Member MSPRole_MSPRoleType = 0
	MSPRole_Admin  MSPRole_MSPRoleType = 1
)

var MSPRole_MSPRoleType_name = map[int32]string{
	0: "Member",
	1: "Admin",
}
var MSPRole_MSPRoleType_value = map[string]int32{
	"Member": 0,
	"Admin":  1,
}

func (x MSPRole_MSPRoleType) String() string {
	return proto.EnumName(MSPRole_MSPRoleType_name, int32(x))
}
func (MSPRole_MSPRoleType) EnumDescriptor() ([]byte, []int) { return fileDescriptor3, []int{2, 0} }

// MSPPrincipal aims to represent an MSP-centric set of identities.
// In particular, this structure allows for definition of
//  - a group of identities that are member of the same MSP
//  - a group of identities that are member of the same organization unit
//    in the same MSP
//  - a group of identities that are administering a specific MSP
//  - a specific identity
// Expressing these groups is done given two fields of the fields below
//  - Classification, that defines the type of classification of identities
//    in an MSP this principal would be defined on; Classification can take
//    three values:
//     (i)  ByMSPRole: that represents a classification of identities within
//          MSP based on one of the two pre-defined MSP rules, "member" and "admin"
//     (ii) ByOrganizationUnit: that represents a classification of identities
//          within MSP based on the organization unit an identity belongs to
//     (iii)ByIdentity that denotes that MSPPrincipal is mapped to a single
//          identity/certificate; this would mean that the Principal bytes
//          message
type MSPPrincipal struct {
	// Classification describes the way that one should process
	// Principal. An Classification value of "ByOrganizationUnit" reflects
	// that "Principal" contains the name of an organization this MSP
	// handles. A Classification value "ByIdentity" means that
	// "Principal" contains a specific identity. Default value
	// denotes that Principal contains one of the groups by
	// default supported by all MSPs ("admin" or "member").
	PrincipalClassification MSPPrincipal_Classification `protobuf:"varint,1,opt,name=PrincipalClassification,enum=common.MSPPrincipal_Classification" json:"PrincipalClassification,omitempty"`
	// Principal completes the policy principal definition. For the default
	// principal types, Principal can be either "Admin" or "Member".
	// For the ByOrganizationUnit/ByIdentity values of Classification,
	// PolicyPrincipal acquires its value from an organization unit or
	// identity, respectively.
	Principal []byte `protobuf:"bytes,2,opt,name=Principal,proto3" json:"Principal,omitempty"`
}

func (m *MSPPrincipal) Reset()                    { *m = MSPPrincipal{} }
func (m *MSPPrincipal) String() string            { return proto.CompactTextString(m) }
func (*MSPPrincipal) ProtoMessage()               {}
func (*MSPPrincipal) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} }

// OrganizationUnit governs the organization of the Principal
// field of a policy principal when a specific organization unity members
// are to be defined within a policy principal.
type OrganizationUnit struct {
	// MSPIdentifier represents the identifier of the MSP this organization unit
	// refers to
	MSPIdentifier string `protobuf:"bytes,1,opt,name=MSPIdentifier" json:"MSPIdentifier,omitempty"`
	// OrganizationUnitIdentifier defines the organization unit under the
	// MSP identified with MSPIdentifier
	OrganizationUnitIdentifier string `protobuf:"bytes,2,opt,name=OrganizationUnitIdentifier" json:"OrganizationUnitIdentifier,omitempty"`
}

func (m *OrganizationUnit) Reset()                    { *m = OrganizationUnit{} }
func (m *OrganizationUnit) String() string            { return proto.CompactTextString(m) }
func (*OrganizationUnit) ProtoMessage()               {}
func (*OrganizationUnit) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }

// MSPRole governs the organization of the Principal
// field of an MSPPrincipal when it aims to define one of the
// two dedicated roles within an MSP: Admin and Members.
type MSPRole struct {
	// MSPIdentifier represents the identifier of the MSP this principal
	// refers to
	MSPIdentifier string `protobuf:"bytes,1,opt,name=MSPIdentifier" json:"MSPIdentifier,omitempty"`
	// MSPRoleType defines which of the available, pre-defined MSP-roles
	// an identiy should posess inside the MSP with identifier MSPidentifier
	Role MSPRole_MSPRoleType `protobuf:"varint,2,opt,name=Role,enum=common.MSPRole_MSPRoleType" json:"Role,omitempty"`
}

func (m *MSPRole) Reset()                    { *m = MSPRole{} }
func (m *MSPRole) String() string            { return proto.CompactTextString(m) }
func (*MSPRole) ProtoMessage()               {}
func (*MSPRole) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }

func init() {
	proto.RegisterType((*MSPPrincipal)(nil), "common.MSPPrincipal")
	proto.RegisterType((*OrganizationUnit)(nil), "common.OrganizationUnit")
	proto.RegisterType((*MSPRole)(nil), "common.MSPRole")
	proto.RegisterEnum("common.MSPPrincipal_Classification", MSPPrincipal_Classification_name, MSPPrincipal_Classification_value)
	proto.RegisterEnum("common.MSPRole_MSPRoleType", MSPRole_MSPRoleType_name, MSPRole_MSPRoleType_value)
}

func init() { proto.RegisterFile("common/msp_principal.proto", fileDescriptor3) }

var fileDescriptor3 = []byte{
	// 316 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x8c, 0x92, 0xc1, 0x4b, 0xc3, 0x30,
	0x14, 0xc6, 0x97, 0xa1, 0x93, 0x3e, 0xb7, 0x52, 0x72, 0xd0, 0x31, 0x3d, 0x8c, 0xba, 0xc3, 0x40,
	0x6c, 0x61, 0xde, 0x05, 0xeb, 0x41, 0x3c, 0x14, 0x4b, 0xa7, 0x17, 0x41, 0xa4, 0xed, 0xb2, 0xed,
	0x41, 0x9b, 0x86, 0x34, 0x82, 0xf1, 0x0f, 0xf0, 0x2f, 0xf4, 0x0f, 0x92, 0xa5, 0x6e, 0x76, 0x03,
	0xc5, 0x53, 0x79, 0xdf, 0xf7, 0xfb, 0xbe, 0xd7, 0x84, 0xc0, 0x20, 0x2b, 0x8b, 0xa2, 0xe4, 0x7e,
	0x51, 0x89, 0x17, 0x21, 0x91, 0x67, 0x28, 0x92, 0xdc, 0x13, 0xb2, 0x54, 0x25, 0xed, 0xd4, 0x9e,
	0xfb, 0x49, 0xa0, 0x1b, 0x4e, 0xa3, 0x68, 0x6d, 0xd3, 0x67, 0x38, 0xde, 0x0c, 0x37, 0x79, 0x52,
	0x55, 0x38, 0xc7, 0x2c, 0x51, 0x58, 0xf2, 0x3e, 0x19, 0x92, 0xb1, 0x3d, 0x39, 0xf3, 0xea, 0xa8,
	0xd7, 0x8c, 0x79, 0xdb, 0x68, 0xfc, 0x5b, 0x07, 0x3d, 0x05, 0x6b, 0x63, 0xf5, 0xdb, 0x43, 0x32,
	0xee, 0xc6, 0x3f, 0x82, 0x7b, 0x0b, 0xf6, 0x0e, 0xdf, 0x03, 0x2b, 0xd0, 0xe1, 0x34, 0x8a, 0xcb,
	0x9c, 0x39, 0x2d, 0x7a, 0x04, 0x34, 0xd0, 0xf7, 0x72, 0x91, 0x70, 0x7c, 0x37, 0xc0, 0x23, 0x47,
	0xe5, 0x10, 0x6a, 0x03, 0x04, 0xfa, 0x6e, 0xc6, 0xb8, 0x42, 0xa5, 0x9d, 0xb6, 0xfb, 0x06, 0xce,
	0x2e, 0x45, 0x47, 0xd0, 0x0b, 0xa7, 0x51, 0x0d, 0xcd, 0x91, 0x49, 0x73, 0x1e, 0x2b, 0xde, 0x16,
	0xe9, 0x15, 0x0c, 0x76, 0x93, 0x8d, 0x48, 0xdb, 0x44, 0xfe, 0x20, 0xdc, 0x0f, 0x02, 0x07, 0xdf,
	0xff, 0xfb, 0xcf, 0x8d, 0x3e, 0xec, 0xad, 0x68, 0xd3, 0x6d, 0x4f, 0x4e, 0x1a, 0xd7, 0xbb, 0x92,
	0xd7, 0xdf, 0x07, 0x2d, 0x58, 0x6c, 0x40, 0x77, 0x04, 0x87, 0x0d, 0x91, 0x02, 0x74, 0x42, 0x56,
	0xa4, 0x4c, 0x3a, 0x2d, 0x6a, 0xc1, 0xfe, 0xf5, 0xac, 0x40, 0xee, 0x90, 0xe0, 0xe2, 0xe9, 0x7c,
	0x81, 0x6a, 0xf9, 0x9a, 0xae, 0x0a, 0xfd, 0xa5, 0x16, 0x4c, 0xe6, 0x6c, 0xb6, 0x60, 0xd2, 0x9f,
	0x27, 0xa9, 0xc4, 0xcc, 0x37, 0x0f, 0xa1, 0xf2, 0xeb, 0x75, 0x69, 0xc7, 0x8c, 0x97, 0x5f, 0x01,
	0x00, 0x00, 0xff, 0xff, 0x81, 0x8f, 0xfe, 0x6f, 0x35, 0x02, 0x00, 0x00,
}


text:
#pragma once
#include <aws/forecastquery/ForecastQueryService_EXPORTS.h>
#include <aws/forecastquery/ForecastQueryServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>

namespace Aws
{
namespace ForecastQueryService
{
namespace Model
{

  /**
   */
  class AWS_FORECASTQUERYSERVICE_API QueryForecastRequest : public ForecastQueryServiceRequest
  {
  public:
    QueryForecastRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "QueryForecast"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline const Aws::String& GetForecastArn() const{ return m_forecastArn; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline bool ForecastArnHasBeenSet() const { return m_forecastArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline void SetForecastArn(const Aws::String& value) { m_forecastArnHasBeenSet = true; m_forecastArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline void SetForecastArn(Aws::String&& value) { m_forecastArnHasBeenSet = true; m_forecastArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline void SetForecastArn(const char* value) { m_forecastArnHasBeenSet = true; m_forecastArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline QueryForecastRequest& WithForecastArn(const Aws::String& value) { SetForecastArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline QueryForecastRequest& WithForecastArn(Aws::String&& value) { SetForecastArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the forecast to query.

     */
    inline QueryForecastRequest& WithForecastArn(const char* value) { SetForecastArn(value); return *this;}

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline const Aws::String& GetStartDate() const{ return m_startDate; }

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline bool StartDateHasBeenSet() const { return m_startDateHasBeenSet; }

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline void SetStartDate(const Aws::String& value) { m_startDateHasBeenSet = true; m_startDate = value; }

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline void SetStartDate(Aws::String&& value) { m_startDateHasBeenSet = true; m_startDate = std::move(value); }

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline void SetStartDate(const char* value) { m_startDateHasBeenSet = true; m_startDate.assign(value); }

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline QueryForecastRequest& WithStartDate(const Aws::String& value) { SetStartDate(value); return *this;}

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline QueryForecastRequest& WithStartDate(Aws::String&& value) { SetStartDate(std::move(value)); return *this;}

    /**
     *
The start date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T08:00:00.

     */
    inline QueryForecastRequest& WithStartDate(const char* value) { SetStartDate(value); return *this;}

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline const Aws::String& GetEndDate() const{ return m_endDate; }

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline bool EndDateHasBeenSet() const { return m_endDateHasBeenSet; }

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline void SetEndDate(const Aws::String& value) { m_endDateHasBeenSet = true; m_endDate = value; }

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline void SetEndDate(Aws::String&& value) { m_endDateHasBeenSet = true; m_endDate = std::move(value); }

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline void SetEndDate(const char* value) { m_endDateHasBeenSet = true; m_endDate.assign(value); }

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline QueryForecastRequest& WithEndDate(const Aws::String& value) { SetEndDate(value); return *this;}

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline QueryForecastRequest& WithEndDate(Aws::String&& value) { SetEndDate(std::move(value)); return *this;}

    /**
     *
The end date for the forecast. Specify the date using this format:
     * yyyy-MM-dd'T'HH:mm:ss (ISO 8601 format). For example, 2015-01-01T20:00:00.

     */
    inline QueryForecastRequest& WithEndDate(const char* value) { SetEndDate(value); return *this;}

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetFilters() const{ return m_filters; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline bool FiltersHasBeenSet() const { return m_filtersHasBeenSet; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline void SetFilters(const Aws::Map<Aws::String, Aws::String>& value) { m_filtersHasBeenSet = true; m_filters = value; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline void SetFilters(Aws::Map<Aws::String, Aws::String>&& value) { m_filtersHasBeenSet = true; m_filters = std::move(value); }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& WithFilters(const Aws::Map<Aws::String, Aws::String>& value) { SetFilters(value); return *this;}

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& WithFilters(Aws::Map<Aws::String, Aws::String>&& value) { SetFilters(std::move(value)); return *this;}

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(const Aws::String& key, const Aws::String& value) { m_filtersHasBeenSet = true; m_filters.emplace(key, value); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(Aws::String&& key, const Aws::String& value) { m_filtersHasBeenSet = true; m_filters.emplace(std::move(key), value); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(const Aws::String& key, Aws::String&& value) { m_filtersHasBeenSet = true; m_filters.emplace(key, std::move(value)); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(Aws::String&& key, Aws::String&& value) { m_filtersHasBeenSet = true; m_filters.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(const char* key, Aws::String&& value) { m_filtersHasBeenSet = true; m_filters.emplace(key, std::move(value)); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(Aws::String&& key, const char* value) { m_filtersHasBeenSet = true; m_filters.emplace(std::move(key), value); return *this; }

    /**
     *
The filtering criteria to apply when retrieving the forecast. For example, to
     * get the forecast for client_21 in the electricity usage dataset,
     * specify the following:

 {"item_id" : "client_21"}

To
     * get the full forecast, use the CreateForecastExportJob
     * operation.

     */
    inline QueryForecastRequest& AddFilters(const char* key, const char* value) { m_filtersHasBeenSet = true; m_filters.emplace(key, value); return *this; }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline QueryForecastRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline QueryForecastRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
If the result of the previous request was truncated, the response includes a
     * NextToken. To retrieve the next set of results, use the token in
     * the next request. Tokens expire after 24 hours.

     */
    inline QueryForecastRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::String m_forecastArn;
    bool m_forecastArnHasBeenSet;

    Aws::String m_startDate;
    bool m_startDateHasBeenSet;

    Aws::String m_endDate;
    bool m_endDateHasBeenSet;

    Aws::Map<Aws::String, Aws::String> m_filters;
    bool m_filtersHasBeenSet;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
  };

} // namespace Model
} // namespace ForecastQueryService
} // namespace Aws


text:
'use strict';

KylinApp.controller('CubeMeasuresCtrl', function ($scope, $modal,MetaModel,cubesManager,CubeDescModel,SweetAlert,VdmUtil,TableModel,cubeConfig,modelsManager,kylinConfig) {
  $scope.num=0;
  $scope.convertedColumns=[];
  $scope.groupby=[];
  $scope.initUpdateMeasureStatus = function(){
    $scope.updateMeasureStatus = {
      isEdit:false,
      editIndex:-1
    }
  };
  $scope.initUpdateMeasureStatus();
  var needLengthKeyList=cubeConfig.needSetLengthEncodingList;
  $scope.getEncodings =function (name){
    var columnType = modelsManager.getColumnTypeByColumnName(name);
    var encodings =$scope.store.supportedEncoding,filterEncoding=[];
    var matchList=VdmUtil.getObjValFromLikeKey($scope.store.encodingMaps,columnType);
    if($scope.isEdit) {
      if (name && $scope.newMeasure.function.configuration&&$scope.newMeasure.function.configuration['topn.encoding.' + name]) {
        var version = $scope.newMeasure.function.configuration['topn.encoding_version.' + name] || 1;
        filterEncoding = VdmUtil.getFilterObjectListByOrFilterVal(encodings, 'value', $scope.newMeasure.function.configuration['topn.encoding.' + name].replace(/:\d+/, "") + (version ? "[v" + version + "]" : "[v1]"), 'suggest', true);
        matchList.push($scope.newMeasure.function.configuration['topn.encoding.' + name].replace(/:\d+/, ""));
        filterEncoding=VdmUtil.getObjectList(filterEncoding,'baseValue',matchList);
      }else{
        filterEncoding=VdmUtil.getFilterObjectListByOrFilterVal(encodings,'suggest', true);
        filterEncoding=VdmUtil.getObjectList(filterEncoding,'baseValue',matchList);
      }
    }else{
      filterEncoding=VdmUtil.getFilterObjectListByOrFilterVal(encodings,'suggest', true);
      filterEncoding=VdmUtil.getObjectList(filterEncoding,'baseValue',matchList);
    }
    return filterEncoding;
  }
  $scope.addNewMeasure = function (measure, index) {
    if(measure&&index>=0){
      $scope.updateMeasureStatus.isEdit = true;
      $scope.updateMeasureStatus.editIndex = index;
    }
    $scope.nextParameters = [];
    $scope.measureParamValueColumn=$scope.getCommonMetricColumns();
    $scope.newMeasure = (!!measure)? jQuery.extend(true, {},measure):CubeDescModel.createMeasure();
    if(!!measure && measure.function.parameter.next_parameter){
      $scope.nextPara.value = measure.function.parameter.next_parameter.value;
    }
    if($scope.newMeasure.function.parameter.value){
      if($scope.metaModel.model.metrics&&$scope.metaModel.model.metrics.indexOf($scope.newMeasure.function.parameter.value)!=-1){
          $scope.newMeasure.showDim=false;
      }else{
          $scope.newMeasure.showDim=true;
      }
    }else{
      $scope.newMeasure.showDim=false;
    }
    $scope.measureParamValueUpdate();
    if($scope.newMeasure.function.expression=="TOP_N"){
      $scope.convertedColumns=[];
      if($scope.newMeasure.function.configuration==null){
        var GroupBy = {
            name:$scope.newMeasure.function.parameter.next_parameter.value,
            encoding:"dict[v1]",
            valueLength:0,
            }
        $scope.convertedColumns.push(GroupBy);
      }
      for(var configuration in $scope.newMeasure.function.configuration) {
          if(/topn\.encoding\./.test(configuration)){
            var _name=configuration.slice(14);
            var item=$scope.newMeasure.function.configuration[configuration];
            var _encoding = item;
            var _valueLength = 0 ;
            var version=$scope.newMeasure.function.configuration['topn.encoding_version.'+_name]||1;
            item=$scope.removeVersion(item);
            var baseKey=item.replace(/:\d+/,'');
            if(needLengthKeyList.indexOf(baseKey)!=-1){
              var result=/:(\d+)/.exec(item);
              _valueLength=result?result[1]:0;
            }
            _encoding=baseKey;
            $scope.GroupBy = {
              name:_name,
              encoding: _encoding + (version ? "[v" + version + "]" : "[v1]"),
              valueLength:_valueLength,
              encoding_version:version||1
            }
            $scope.convertedColumns.push($scope.GroupBy);
        }
      };
    }
    if ($scope.newMeasure.function.expression === 'COUNT_DISTINCT') {
      $scope.convertedColumns=[];
      if ($scope.newMeasure.function.parameter.next_parameter) {
        $scope.recursion($scope.newMeasure.function.parameter.next_parameter, $scope.convertedColumns)
      }
    }
  };

  $scope.updateNextParameter = function(){
    for(var i= 0;i<$scope.nextParameters.length-1;i++){
      $scope.nextParameters[i].next_parameter=$scope.nextParameters[i+1];
    }
    $scope.newMeasure.function.parameter.next_parameter = $scope.nextParameters[0];
  }

  $scope.editNextParameter = function(parameter){
    $scope.openParameterModal(parameter);

  }

  $scope.addNextParameter = function(){
    $scope.openParameterModal();
  }

  $scope.removeParameter = function(parameters,index){
    if(index>-1){
      parameters.splice(index,1);
    }
    $scope.updateNextParameter();
  }

  $scope.nextPara = {
    "type":"column",
    "value":"",
    "next_parameter":null
  }

  $scope.openParameterModal = function (parameter) {
    $modal.open({
      templateUrl: 'nextParameter.html',
      controller: NextParameterModalCtrl,
      resolve: {
        scope: function () {
          return $scope;
        },
        para:function(){
          return parameter;
        }
      }
    });
  };
  $scope.nextParameters =[];

  $scope.removeElement = function (arr, element) {
    var index = arr.indexOf(element);
    if (index > -1) {
      arr.splice(index, 1);
    }
  };

  $scope.clearNewMeasure = function () {
    $scope.newMeasure = null;
    $scope.initUpdateMeasureStatus();
    $scope.nextParameterInit();
  };

  $scope.saveNewMeasure = function () {
    if ($scope.newMeasure.function.expression === 'TOP_N' ) {
      if($scope.newMeasure.function.parameter.value == ""){
        SweetAlert.swal('', '[TOP_N] ORDER|SUM by Column  is required', 'warning');
        return false;
      }
      if($scope.convertedColumns.length<1){
        SweetAlert.swal('', '[TOP_N] Group by Column is required', 'warning');
        return false;
      }

      var hasExisted = [];

      for (var column in $scope.convertedColumns){
        if(hasExisted.indexOf($scope.convertedColumns[column].name)==-1){
          hasExisted.push($scope.convertedColumns[column].name);
        }
        else{
          SweetAlert.swal('', 'The column named ['+$scope.convertedColumns[column].name+'] already exits.', 'warning');
          return false;
        }
        if ($scope.convertedColumns[column].encoding == 'int' && ($scope.convertedColumns[column].valueLength < 1 || $scope.convertedColumns[column].valueLength > 8)) {
          SweetAlert.swal('', 'int encoding column length should between 1 and 8.', 'warning');
          return false;
        }
      }
        $scope.nextPara.next_parameter={};
        $scope.newMeasure.function.configuration={};
        $scope.groupby($scope.nextPara);
        angular.forEach($scope.convertedColumns,function(item){
          var a='topn.encoding.'+item.name;
          var versionKey='topn.encoding_version.'+item.name;
          var version=$scope.getTypeVersion(item.encoding);
          var encoding="";
          if(needLengthKeyList.indexOf($scope.removeVersion(item.encoding))!=-1){
            encoding = $scope.removeVersion(item.encoding)+":"+item.valueLength;
          }else{
            encoding = $scope.removeVersion(item.encoding);
            item.valueLength=0;
          }
          $scope.newMeasure.function.configuration[a]= encoding;
          $scope.newMeasure.function.configuration[versionKey]=version;
          });
    }
    if ($scope.newMeasure.function.expression === 'COUNT_DISTINCT' && $scope.newMeasure.function.returntype!=='bitmap') {

      var hasExisted = [];

      for (var column in $scope.convertedColumns){
        if(hasExisted.indexOf($scope.convertedColumns[column].name)==-1){
          hasExisted.push($scope.convertedColumns[column].name);
        }
        else{
          SweetAlert.swal('', 'The column named ['+$scope.convertedColumns[column].name+'] already exits.', 'warning');
          return false;
        }
      }
      $scope.nextPara.next_parameter={};
      if ($scope.convertedColumns.length > 0) {
        $scope.groupby($scope.nextPara);
      } else {
        $scope.nextPara=null;
        $scope.newMeasure.function.parameter.next_parameter=null;
      }
    }

    if ($scope.isNameDuplicated($scope.cubeMetaFrame.measures, $scope.newMeasure) == true) {
      SweetAlert.swal('', 'The measure name: ' + $scope.newMeasure.name + ' is duplicated', 'warning');
      return false;
    }

    if($scope.nextPara && $scope.nextPara.value!=="" && ($scope.newMeasure.function.expression == 'EXTENDED_COLUMN' || $scope.newMeasure.function.expression == 'TOP_N'||$scope.newMeasure.function.expression == 'COUNT_DISTINCT')){
      $scope.newMeasure.function.parameter.next_parameter = jQuery.extend(true,{},$scope.nextPara);
    }

    if($scope.updateMeasureStatus.isEdit == true){
      $scope.cubeMetaFrame.measures[$scope.updateMeasureStatus.editIndex] = $scope.newMeasure;
    }
    else {
      $scope.cubeMetaFrame.measures.push($scope.newMeasure);
    }

    $scope.newMeasure = null;
    $scope.initUpdateMeasureStatus();
    $scope.nextParameterInit();
    return true;
  };

  $scope.isNameDuplicated = function (measures, newMeasure) {
    var names = [];
    for(var i = 0;i < measures.length; i++){
        names.push(measures[i].name);
    }
    var index = names.indexOf(newMeasure.name);
    return (index > -1 && index != $scope.updateMeasureStatus.editIndex);
  }

  $scope.nextParameterInit = function(){
    $scope.nextPara = {
      "type":"column",
      "value":"",
      "next_parameter": null
    }
    if($scope.newMeasure){
      $scope.newMeasure.function.parameter.next_parameter = null;
    }
  }

  $scope.addNewGroupByColumn = function () {
    $scope.nextGroupBy = {
      name:null,
      encoding:"dict[v1]",
      valueLength:0,
    }
    $scope.convertedColumns.push($scope.nextGroupBy);

  };

  $scope.removeColumn = function(arr,index){
    if (index > -1) {
      arr.splice(index, 1);
    }
  };
  $scope.refreshGroupBy=function (list,index,item) {
    var encoding;
    var name = item.name;
    if(item.encoding=="dict" || item.encoding=="date"|| item.encoding=="time"){
      item.valueLength=0;
    }
  };

  $scope.groupby= function (next_parameter){
    if($scope.num<$scope.convertedColumns.length-1){
      next_parameter.value=$scope.convertedColumns[$scope.num].name;
      next_parameter.type="column";
      next_parameter.next_parameter={};
      $scope.num++;
      $scope.groupby(next_parameter.next_parameter);
    }
    else{
      next_parameter.value=$scope.convertedColumns[$scope.num].name;
      next_parameter.type="column";
      next_parameter.next_parameter=null;
      $scope.num=0;
      return false;
    }
  }

  $scope.recursion = function (parameter, list) {
    list.push({name: parameter.value})
    if (parameter.next_parameter) {
      $scope.recursion(parameter.next_parameter, list)
    } else {
      return
    }
  }

  $scope.measureParamValueUpdate = function(){
    if($scope.newMeasure.function.expression !== 'EXTENDED_COLUMN' && $scope.newMeasure.showDim==true){
       $scope.measureParamValueColumn=$scope.getAllModelDimMeasureColumns();
    }
    if($scope.newMeasure.function.expression !== 'EXTENDED_COLUMN' && $scope.newMeasure.showDim==false){
       $scope.measureParamValueColumn=$scope.getCommonMetricColumns();
    }
    if($scope.newMeasure.function.expression == 'EXTENDED_COLUMN'){
      $scope.measureParamValueColumn=$scope.getExtendedHostColumn();
    }
  }

  //map right return type for param
  $scope.measureReturnTypeUpdate = function() {

    if ($scope.newMeasure.function.expression == 'TOP_N') {
      if ($scope.newMeasure.function.parameter.type == "" || !$scope.newMeasure.function.parameter.type) {
        $scope.newMeasure.function.parameter.type = 'column';
      }
      $scope.convertedColumns = [];
      $scope.newMeasure.function.returntype = "topn(100)";
      return;
    } else if ($scope.newMeasure.function.expression == 'COUNT_DISTINCT') {
      $scope.newMeasure.function.parameter.type= 'column';
      $scope.newMeasure.function.returntype = "hllc(10)";
      $scope.convertedColumns = [];
    } else if($scope.newMeasure.function.expression == 'EXTENDED_COLUMN'){
      $scope.newMeasure.function.parameter.type= 'column';
      $scope.newMeasure.function.returntype = "extendedcolumn(100)";
      return;
    }else if($scope.newMeasure.function.expression=='PERCENTILE'){
      $scope.newMeasure.function.parameter.type= 'column';
    }else{
      $scope.nextParameterInit();
    }

    if($scope.newMeasure.function.parameter.type=="constant"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){
      switch($scope.newMeasure.function.expression){
        case "SUM":
        case "COUNT":
          $scope.newMeasure.function.returntype = "bigint";
          break;
        default:
          $scope.newMeasure.function.returntype = "";
          break;
      }
    }
    if($scope.newMeasure.function.parameter.type=="column"&&$scope.newMeasure.function.expression!=="COUNT_DISTINCT"){
      $scope.newMeasure.function.returntype = $scope.getReturnType($scope.newMeasure.function.parameter.value, $scope.newMeasure.function.expression);
    }
  }

  // Open bulk add modal.
  $scope.openBulkAddModal = function () {

    $scope.initBulkAddMeasures();

    var modalInstance = $modal.open({
        templateUrl: 'bulkAddMeasures.html',
        controller: cubeBulkAddMeasureModalCtrl,
        backdrop: 'static',
        scope: $scope
    });
  };

    $scope.initBulkAddMeasures = function() {
    // init bulk add measure view model
    $scope.bulkMeasuresView = {
      SUM: [],
      MAX: [],
      MIN: [],
      RAW: [],
      PERCENTILE: []
    };
    angular.forEach($scope.getCommonMetricColumns(), function(paramValue) {
      var measures = _.filter($scope.cubeMetaFrame.measures, function(measure){ return measure.function.parameter.value == paramValue});
      for (var expression in $scope.bulkMeasuresView) {
        var bulkMeasure = {
          name: expression + '_' + paramValue.split('.')[1],
          parameter: paramValue,
          returntype: $scope.getReturnType(paramValue, expression),
          select: false,
          force: false
        };

        if (measures.length) {
          var measure = _.find(measures, function(measure){ return measure.function.expression == expression});
          if (!!measure) {
            bulkMeasure.name = measure.name;
            bulkMeasure.force = true;
            bulkMeasure.select = true;
          }
        }
        $scope.bulkMeasuresView[expression].push(bulkMeasure);
      }
    });

    // init expression selector
    $scope.bulkMeasureOptions = {
      expressionList: []
    };

    for (var expression in $scope.bulkMeasuresView) {
      var selectArr = _.filter($scope.bulkMeasuresView[expression], function(measure){ return measure.select && measure.force});
      var selectAll = $scope.getCommonMetricColumns().length == selectArr.length;
      var expressionSelect = {
        expression: expression,
        selectAll: selectAll,
        force: selectAll
      }
      $scope.bulkMeasureOptions.expressionList.push(expressionSelect);
    }

    $scope.bulkMeasureOptions.currentExpression = $scope.bulkMeasureOptions.expressionList[0];
  };

   $scope.getReturnType = function(parameter, expression) {
    if(parameter && (typeof parameter=="string")){
      var colType = $scope.getColumnType(VdmUtil.removeNameSpace(parameter), VdmUtil.getNameSpaceAliasName(parameter)); // $scope.getColumnType defined in cubeEdit.js
    }
    if(colType == '' || !colType) {
      return '';
    }

    switch(expression) {
      case 'SUM':
        if(colType === 'tinyint' || colType === 'smallint' || colType === 'int' || colType === 'bigint' || colType === 'integer') {
          return 'bigint';
        } else {
         if(colType.indexOf('decimal') != -1) {
            var returnRegex = new RegExp('(\\w+)(?:\\((\\w+?)(?:\\,(\\w+?))?\\))?');
            var returnValue = returnRegex.exec(colType);
            var precision = returnValue[2] || 0;
            var scale = returnValue[3] || 0;
            return 'decimal(' + precision + ',' + scale + ')';
          }else{
            return colType;
          }
        }
        break;
      case 'MIN':
      case 'MAX':
        return colType;
        break;
      case 'RAW':
        return 'raw';
        break;
      case 'COUNT':
        return 'bigint';
        break;
      case 'PERCENTILE':
        return 'percentile(100)';
        break;
      default:
        return '';
        break;
    }
  };

  if ($scope.state.mode == 'edit') {
    $scope.$on('$destroy', function () {
      // emit measures edit event in order to re-generate advanced dict.
      $scope.$emit('MeasuresEdited');
    });
  }

  $scope.isMeasureUnHidden = function(measure) {
    if (kylinConfig.getHiddenMeasures().indexOf(measure) == -1) {
      return true;
    } else {
      return false;
    }
  }

});

var NextParameterModalCtrl = function ($scope, scope,para,$modalInstance,cubeConfig, CubeService, MessageService, $location, SweetAlert,ProjectModel, loadingRequest,ModelService) {

  $scope.newmea={
    "measure":scope.newMeasure
  }

  $scope.cubeConfig = cubeConfig;
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

  $scope.getCommonMetricColumns = function(measure){
    return scope.getCommonMetricColumns(measure);
  }

  $scope.nextPara = {
    "type":"",
    "value":"",
    "next_parameter":null
  }

  var _index = scope.nextParameters.indexOf(para);
  if(para){
    $scope.nextPara = para;
  }

  $scope.ok = function(){
    if(_index!=-1){
      scope.nextParameters[_index] = $scope.nextPara;
    }
    else{
      scope.nextParameters.push($scope.nextPara);
    }

    scope.updateNextParameter();
    $modalInstance.dismiss('cancel');
  }

}

var cubeBulkAddMeasureModalCtrl = function($scope, $modalInstance, SweetAlert) {
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

  $scope.saveBulkMeasures = function () {
    $scope.bulkMeasures = [];
    // validation
    loopExp:
      for (var expression in $scope.bulkMeasuresView) {
        loopMeasureView:
          for (var measureView of $scope.bulkMeasuresView[expression]) {
            if (!measureView.force) {
              // validation
              var measureExisted = _.find($scope.cubeMetaFrame.measures, function(measure){ return measure.function.parameter.value == measureView.parameter && measure.function.expression == measureView.expression});
              if (!!measureExisted) {
                $scope.bulkMeasures = [];
                var errMsg = 'Duplicate measure for ' + measureView.name + ' and ' + measureExisted.name + '.';
                break loopExp;
              }
              if (measureView.select) {
                var measure = {
                  name: measureView.name,
                  function: {
                    expression: expression,
                    returntype: measureView.returntype,
                    parameter: {
                      type: 'column',
                      value: measureView.parameter
                    }
                  }
                };
                $scope.bulkMeasures.push(measure);
              }
            }
          }
      }
    if (!!errMsg) {
      SweetAlert.swal('', errMsg, 'warning');
    } else {
      $scope.cubeMetaFrame.measures = $scope.cubeMetaFrame.measures.concat($scope.bulkMeasures);
      $modalInstance.close();
    }
  };

  $scope.selectAll = function() {
    angular.forEach($scope.bulkMeasuresView[$scope.bulkMeasureOptions.currentExpression.expression], function(measure) {
      if (!measure.force) {
        measure.select = $scope.bulkMeasureOptions.currentExpression.selectAll;
      }
    });
  };

  $scope.measureChange = function(measureSelect) {
    if ($scope.bulkMeasureOptions.currentExpression.selectAll) {
      if (!measureSelect) {
        $scope.bulkMeasureOptions.currentExpression.selectAll = false;
      }
    } else {
      for(var measureView of $scope.bulkMeasuresView[$scope.bulkMeasureOptions.currentExpression.expression]) {
        if (!measureView.select) {
          return;
        }
      }
      $scope.bulkMeasureOptions.currentExpression.selectAll = true;
    }
  }
}


text:
package com.thales.ntis.subscriber.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.thales.ntis.subscriber.datex.D2LogicalModel;

@Service
public class DatexIIService extends AbstractDatexService {

    private static final Logger LOG = LoggerFactory.getLogger(DatexIIService.class);

    public synchronized void handle(D2LogicalModel request) {
        LOG.info("Validate D2Logical Model - Started");

        if (!validate(request)) {
            LOG.info("D2Logical Model is not valid");
            throw new RuntimeException("Incoming request does not appear to be valid!");
        }

        LOG.info("Validate D2Logical Model - Completed Successfuly");

        TrafficDataServiceFactory.newInstance(request).handle(request);

    }
}


text:
{% extends "layout.html" %} {% block page_title %} Treatments and therapy {% endblock %} {% block content %}

    {% include "../includes/phase_banner_beta.html" %}
    <form action="health-care-professionals" method="#" class="form">

                Back

Are you having, or do you have planned, any treatments?

Including chemotherapy, physiotherapy, dialysis, or medical massages or exercises.

                <fieldset id="speech" class="inline">
                    <legend for="speech">
                        Are you having, or do you have planned, any treatments?
                    </legend>

                            <input id="meds-Yes" type="radio" name="speech" value="Yes">Yes

                            <input id="meds-No" type="radio" name="speech" value="No">No

                </fieldset>

Treatment or therapy 1

                        Name of treatment or therapy

                        <input type="text" data-name="medication-1" class="form-control" id="medication1" name="medication1" value="">

                        When or how often

                        <input type="text" data-name="dosage-1" class="form-control" id="dosage1" name="dosage1" value="">

Add another treatment

Treatment or therapy 2

                        Name of treatment or therapy

                        <input type="text" data-name="medication-2" class="form-control" id="medication2" name="medication2" value="">

                        When or how often

                        <input type="text" data-name="dosage-2" class="form-control" id="dosage2" name="dosage2" value="">

Add another treatment

Treatment or therapy 3

                        Name of treatment or therapy

                        <input type="text" data-name="medication-3" class="form-control" id="medication3" name="medication3" value="">

                        When or how often

                        <input type="text" data-name="dosage-3" class="form-control" id="dosage3" name="dosage3" value="">

Add another treatment

                    <input type="submit" class="button" value="Continue">

                {% include "../includes/help.html" %}

    </form>

{% endblock %} {% block body_end %} {% include "includes/scripts.html" %}

{% endblock %}


text:
class ACDBCORE2D_PORT AcDbAssocIndexPersSubentId : public AcDbAssocPersSubentId
{
#ifdef __GNUC__
    typedef AcDbAssocPersSubentId __super;
    static_assert((std::is_same<__super, AcDbAssocPersSubentId>::value), "Incorrect __super class");
#endif

public:
	ACRX_DECLARE_MEMBERS(AcDbAssocIndexPersSubentId);

    explicit AcDbAssocIndexPersSubentId(AcDb::SubentType subentType = AcDb::kNullSubentType, unsigned int index = 0);

    bool operator ==(const AcDbAssocIndexPersSubentId& other) const
    {
        return mSubentType == other.mSubentType && mIndex == other.mIndex;
    }

    bool operator <(const AcDbAssocIndexPersSubentId& other) const
    {
        return mSubentType != other.mSubentType ? mSubentType < other.mSubentType : mIndex < other.mIndex;
    }

    virtual AcDb::SubentType subentType(const AcDbEntity*, AcDbDatabase*) const override { return mSubentType; }

    virtual bool isNull() const override { return mSubentType == AcDb::kNullSubentType; }

    /// <para>
    /// Writes the raw data of this class. It does not call the parent class
    /// AcDbAssocPersSubentId::dwg/dxfOutFields() that would write the class name.
    /// </para><para>
    /// This method must be used when serializing an AcDbAssocIndexPersSubentId
    /// that is an explicit data member, not a AcDbAssocPersSubentId* data member.
    /// The regular dwg/dxfInFields() can be used to read the data back.
    /// </para>
    /// <param  name="pFiler"> The filer to write the object data to. </param>
    /// <returns> Acad::eOk. </returns>
    ///
    virtual Acad::ErrorStatus dwgOutFieldsData(AcDbDwgFiler* pFiler) const;

    /// <para>
    /// Writes the raw data of this class. It does not call the parent class
    /// AcDbAssocPersSubentId::dwg/dxfOutFields() that would write the class name.
    /// </para><para>
    /// This method must be used when serializing an AcDbAssocIndexPersSubentId
    /// that is an explicit data member, not a AcDbAssocPersSubentId* data member.
    /// The regular dwg/dxfInFields() can be used to read the data back.
    /// </para>
    /// <param  name="pFiler"> The filer to write the object data to. </param>
    /// <returns> Acad::eOk. </returns>
    ///
    virtual Acad::ErrorStatus dxfOutFieldsData(AcDbDxfFiler* pFiler) const;

    ///  The standard filing protocol.
    /// <param  name="pFiler"> The filer to write the object data to. </param>
    /// <returns> Acad::ErrorStatus. </returns>
    ///
    virtual Acad::ErrorStatus dwgOutFields(AcDbDwgFiler* pFiler) const override;

    ///  The standard filing protocol.
    /// <param  name="pFiler"> The filer to read the object data from. </param>
    /// <returns> Acad::ErrorStatus. </returns>
    ///
    virtual Acad::ErrorStatus dwgInFields(AcDbDwgFiler* pFiler) override;

    ///  The standard filing protocol.
    /// <param  name="pFiler"> The filer to write the object data to. </param>
    /// <returns> Acad::ErrorStatus. </returns>
    ///
    virtual Acad::ErrorStatus dxfOutFields(AcDbDxfFiler* pFiler) const override;

    ///  The standard filing protocol.
    /// <param  name="pFiler"> The filer to read the object data from. </param>
    /// <returns> Acad::ErrorStatus. </returns>
    ///
    virtual Acad::ErrorStatus dxfInFields(AcDbDxfFiler* pFiler) override;

    // New methods

    unsigned int index() const { return mIndex; }

    void setSubentType(AcDb::SubentType subentType) { mSubentType = subentType; }
    void setIndex     (unsigned int newIndex)       { mIndex      = newIndex;   }

private:
    // For round-tripping via AcDbAssocSimplePersSubentId, encoding the
    // actual class type in subentType(), because it may only be in the range
    // of 0..3, so we have enough bits available to encode additional info.
    // Calls the virtual roundTripOffset() method to get the offset
    //
    int encodeActualClassInSubentType() const;

    static const int kRoundTripOffset = 1000000; // For this AcDbAssocIndexPersSubentId class
    virtual int roundTripOffset() const { return kRoundTripOffset; }

    friend void roundTripReadViaAcDbAssocSimplePersSubentId(AcDbAssocPersSubentId*&);

protected:
    AcDb::SubentType mSubentType;
    unsigned int     mIndex;

}; // class AcDbAssocIndexPersSubentId

/// <para>
/// AcDbAssocPersSubentId returned by AcDAssocExternalPersSubentIdManager and
/// AcDAssocExternalPersSubentIdHolder. It is identical to its base AcDbAssocIndexPersSubentId
/// class but is of a different class, so that its purpose can be found-out by
/// checking the class.
/// </para><para>
/// It is similar to AcDbAssocAsmBasedEntityPersSubentId that also is of a different
/// class because pers id collection and remapping needs to know which AcDbAssocPersSubentIds
/// are related to AcDbAssocPersSubentManager.
/// </para>
///
class ACDBCORE2D_PORT AcDbAssocExternalIndexPersSubentId : public AcDbAssocIndexPersSubentId
{
public:
	ACRX_DECLARE_MEMBERS(AcDbAssocExternalIndexPersSubentId);

    explicit AcDbAssocExternalIndexPersSubentId(AcDb::SubentType subentType = AcDb::kNullSubentType, unsigned int index = 0)
      : AcDbAssocIndexPersSubentId(subentType, index) {}

private:
    // For round-tripping to older dwg file format versions via AcDbAssocSimplePersSubentId
    //
    static const int kRoundTripOffset = 2000000; // For this AcDbAssocExternalIndexPersSubentId class
    virtual int roundTripOffset() const override { return kRoundTripOffset; }

    friend void roundTripReadViaAcDbAssocSimplePersSubentId(AcDbAssocPersSubentId*&);

}; // class AcDbAssocExternalIndexPersSubentId

///
/// Represents the persistent subentity id by an AcDbObjectId and a (persistent)
/// unsigned integer index related to that AcDbObject. The index can be interpreted
/// in any way the client (i.e.  a concrete AcDbAssocPersSubentIdPE protocol extension)
/// wants to.
///
/// <remarks>
/// </remarks>
///
class ACDBCORE2D_PORT AcDbAssocObjectAndIndexPersSubentId : public AcDbAssocIndexPersSubentId
{
#ifdef __GNUC__
    typedef AcDbAssocIndexPersSubentId __super;
    static_assert((std::is_same<__super, AcDbAssocIndexPersSubentId>::value), "Incorrect __super class");
#endif

public:
	ACRX_DECLARE_MEMBERS(AcDbAssocObjectAndIndexPersSubentId);

    AcDbAssocObjectAndIndexPersSubentId() {}
    AcDbAssocObjectAndIndexPersSubentId(const AcDbObjectId& objId, AcDb::SubentType subentType, unsigned int index);

    bool operator ==(const AcDbAssocObjectAndIndexPersSubentId& other) const;
    bool operator  <(const AcDbAssocObjectAndIndexPersSubentId& other) const;

    AcDbObjectId objectId() const { return mObjectId; }

    void setObjectId(const AcDbObjectId& objId) { mObjectId = objId; }

    virtual Acad::ErrorStatus dwgOutFieldsData(AcDbDwgFiler*) const override;
    virtual Acad::ErrorStatus dxfOutFieldsData(AcDbDxfFiler*) const override;

    virtual Acad::ErrorStatus dwgOutFields(AcDbDwgFiler*) const override;
    virtual Acad::ErrorStatus dwgInFields(AcDbDwgFiler* ) override;
    virtual Acad::ErrorStatus dxfOutFields(AcDbDxfFiler*) const override;
    virtual Acad::ErrorStatus dxfInFields(AcDbDxfFiler* ) override;

private:
    AcDbObjectId mObjectId;

}; // class AcDbAssocObjectAndIndexPersSubentId

#pragma pack (pop)


text:
if [ "phoneme_recognition" ==  "${PWD##*/}" ]
then
    # Install SND file format library
    sudo apt-get install libsndfile-dev

    # Setup vistual environment
    virtualenv venv
    source venv/bin/activate
    pip install --upgrade pip
    pip install --upgrade setuptools
    pip install numpy
    pip install -r requirements.txt
    deactivate

    # Install RecNet
    git clone https://github.com/joergfranke/recnet.git
    cd recnet
    ../venv/bin/python setup.py install
else
    echo "Please go in phoneme_recognition directory"
fi


text:
package Carp;

our $VERSION = '1.04';

=head1 NAME

carp    - warn of errors (from perspective of caller)

cluck   - warn of errors with stack backtrace
          (not exported by default)

croak   - die of errors (from perspective of caller)

confess - die of errors with stack backtrace

shortmess - return the message that carp and croak produce

longmess - return the message that cluck and confess produce

=head1 SYNOPSIS

    use Carp;
    croak "We're outta here!";

    use Carp qw(cluck);
    cluck "This is how we got here!";

    print FH Carp::shortmess("This will have caller's details added");
    print FH Carp::longmess("This will have stack backtrace added");

=head1 DESCRIPTION

The Carp routines are useful in your own modules because
they act like die() or warn(), but with a message which is more
likely to be useful to a user of your module.  In the case of
cluck, confess, and longmess that context is a summary of every
call in the call-stack.  For a shorter message you can use carp,
croak or shortmess which report the error as being from where
your module was called.  There is no guarantee that that is where
the error was, but it is a good educated guess.

You can also alter the way the output and logic of C<Carp> works, by
changing some global variables in the C<Carp> namespace. See the
section on C<GLOBAL VARIABLES> below.

Here is a more complete description of how shortmess works.  What
it does is search the call-stack for a function call stack where
it hasn't been told that there shouldn't be an error.  If every
call is marked safe, it then gives up and gives a full stack
backtrace instead.  In other words it presumes that the first likely
looking potential suspect is guilty.  Its rules for telling whether
a call shouldn't generate errors work as follows:

=over 4

=item 1.

Any call from a package to itself is safe.

=item 2.

Packages claim that there won't be errors on calls to or from
packages explicitly marked as safe by inclusion in @CARP_NOT, or
(if that array is empty) @ISA.  The ability to override what
@ISA says is new in 5.8.

=item 3.

The trust in item 2 is transitive.  If A trusts B, and B
trusts C, then A trusts C.  So if you do not override @ISA
with @CARP_NOT, then this trust relationship is identical to,
"inherits from".

=item 4.

Any call from an internal Perl module is safe.  (Nothing keeps
user modules from marking themselves as internal to Perl, but
this practice is discouraged.)

=item 5.

Any call to Carp is safe.  (This rule is what keeps it from
reporting the error where you call carp/croak/shortmess.)

=back

=head2 Forcing a Stack Trace

As a debugging aid, you can force Carp to treat a croak as a confess
and a carp as a cluck across I<all> modules. In other words, force a
detailed stack trace to be given.  This can be very helpful when trying
to understand why, or from where, a warning or error is being generated.

This feature is enabled by 'importing' the non-existent symbol
'verbose'. You would typically enable it by saying

    perl -MCarp=verbose script.pl

or by including the string C<MCarp=verbose> in the PERL5OPT
environment variable.

Alternately, you can set the global variable C<$Carp::Verbose> to true.
See the C<GLOBAL VARIABLES> section below.

=cut

# This package is heavily used. Be small. Be fast. Be good.

# Comments added by Andy Wardley <abw@kfs.org> 09-Apr-98, based on an
# _almost_ complete understanding of the package.  Corrections and
# comments are welcome.

# The members of %Internal are packages that are internal to perl.
# Carp will not report errors from within these packages if it
# can.  The members of %CarpInternal are internal to Perl's warning
# system.  Carp will not report errors from within these packages
# either, and will not report calls *to* these packages for carp and
# croak.  They replace $CarpLevel, which is deprecated.    The
# $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
# text and function arguments should be formatted when printed.

# Comments added by Jos I. Boumans <kane@dwim.org> 11-Aug-2004
# I can not get %CarpInternal or %Internal to work as advertised,
# therefor leaving it out of the below documentation.
# $CarpLevel may be decprecated according to the last comment, but
# after 6 years, it's still around and in heavy use ;)

=pod

=head1 GLOBAL VARIABLES

=head2 $Carp::CarpLevel

This variable determines how many call frames are to be skipped when
reporting where an error occurred on a call to one of C<Carp>'s
functions. For example:

    $Carp::CarpLevel = 1;
    sub bar     { .... or _error('Wrong input') }
    sub _error  { Carp::carp(@_) }

This would make Carp report the error as coming from C<bar>'s caller,
rather than from C<_error>'s caller, as it normally would.

Defaults to C<0>.

=head2 $Carp::MaxEvalLen

This variable determines how many characters of a string-eval are to
be shown in the output. Use a value of C<0> to show all text.

Defaults to C<0>.

=head2 $Carp::MaxArgLen

This variable determines how many characters of each argument to a
function to print. Use a value of C<0> to show the full length of the
argument.

Defaults to C<64>.

=head2 $Carp::MaxArgNums

This variable determines how many arguments to each function to show.
Use a value of C<0> to show all arguments to a function call.

Defaults to C<8>.

=head2 $Carp::Verbose

This variable makes C<Carp> use the C<longmess> function at all times.
This effectively means that all calls to C<carp> become C<cluck> and
all calls to C<croak> become C<confess>.

Note, this is analogous to using C<use Carp 'verbose'>.

Defaults to C<0>.

=cut

$CarpInternal{Carp}++;
$CarpInternal{warnings}++;
$CarpLevel = 0;     # How many extra package levels to skip on carp.
                    # How many calls to skip on confess.
                    # Reconciling these notions is hard, use
                    # %Internal and %CarpInternal instead.
$MaxEvalLen = 0;    # How much eval '...text...' to show. 0 = all.
$MaxArgLen = 64;    # How much of each argument to print. 0 = all.
$MaxArgNums = 8;    # How many arguments to print. 0 = all.
$Verbose = 0;       # If true then make shortmess call longmess instead

require Exporter;
@ISA = ('Exporter');
@EXPORT = qw(confess croak carp);
@EXPORT_OK = qw(cluck verbose longmess shortmess);
@EXPORT_FAIL = qw(verbose);	# hook to enable verbose mode

=head1 BUGS

The Carp routines don't handle exception objects currently.
If called with a first argument that is a reference, they simply
call die() or warn(), as appropriate.

=cut

# if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
# then the following method will be called by the Exporter which knows
# to do this thanks to @EXPORT_FAIL, above.  $_[1] will contain the word
# 'verbose'.

sub export_fail {
    shift;
    $Verbose = shift if $_[0] eq 'verbose';
    return @_;
}

# longmess() crawls all the way up the stack reporting on all the function
# calls made.  The error string, $error, is originally constructed from the
# arguments passed into longmess() via confess(), cluck() or shortmess().
# This gets appended with the stack trace messages which are generated for
# each function call on the stack.

sub longmess {
    {
	local($@, $!);
	# XXX fix require to not clear $@ or $!?
	# don't use require unless we need to (for Safe compartments)
	require Carp::Heavy unless $INC{"Carp/Heavy.pm"};
    }
    # Icky backwards compatibility wrapper. :-(
    my $call_pack = caller();
    if ($Internal{$call_pack} or $CarpInternal{$call_pack}) {
      return longmess_heavy(@_);
    }
    else {
      local $CarpLevel = $CarpLevel + 1;
      return longmess_heavy(@_);
    }
}

# shortmess() is called by carp() and croak() to skip all the way up to
# the top-level caller's package and report the error from there.  confess()
# and cluck() generate a full stack trace so they call longmess() to
# generate that.  In verbose mode shortmess() calls longmess() so
# you always get a stack trace

sub shortmess {	# Short-circuit &longmess if called via multiple packages
    {
	local($@, $!);
	# XXX fix require to not clear $@ or $!?
	# don't use require unless we need to (for Safe compartments)
	require Carp::Heavy unless $INC{"Carp/Heavy.pm"};
    }
    # Icky backwards compatibility wrapper. :-(
    my $call_pack = caller();
    local @CARP_NOT = caller();
    shortmess_heavy(@_);
}

# the following four functions call longmess() or shortmess() depending on
# whether they should generate a full stack trace (confess() and cluck())
# or simply report the caller's package (croak() and carp()), respectively.
# confess() and croak() die, carp() and cluck() warn.

sub croak   { die  shortmess @_ }
sub confess { die  longmess  @_ }
sub carp    { warn shortmess @_ }
sub cluck   { warn longmess  @_ }

1;


text:
using System.Collections.Generic;
using Contentful.Core.Models;
using StockportContentApi.ContentfulModels;

namespace StockportContentApiTests.Unit.Builders
{
    public class ContentfulGroupHomepageBuilder
    {
        private string _title = "title";
        private string _slug = "slug";
        private string _metaDescription = "metaDescription";
        private Asset _backgroundImage = new ContentfulAssetBuilder().Url("image-url.jpg").Build();
        private SystemProperties _sys = new SystemProperties
        {
            ContentType = new ContentType { SystemProperties = new SystemProperties { Id = "id" } }
        };
        private ContentfulEventBanner _eventBanner =
            new ContentfulEventBannerBuilder().Build();
        private string _featuredGroupsHeading = "heading";
        private List<ContentfulGroup> _featuredGroups = new List<ContentfulGroup>
        {
            new ContentfulGroupBuilder().Build()
        };

        public ContentfulGroupHomepage Build()
        {
            return new ContentfulGroupHomepage
            {
                Slug = _slug,
                MetaDescription = _metaDescription,
                Title = _title,
                BackgroundImage = _backgroundImage,
                EventBanner = _eventBanner,
                FeaturedGroupsHeading = _featuredGroupsHeading,
                FeaturedGroups = _featuredGroups,
                Alerts = new List<ContentfulAlert>
                {
                    new ContentfulAlertBuilder().Build()
                },
                BodyHeading = "bodyheading",
                Body = "body",
                SecondaryBodyHeading = "secondaryBodyHeading",
                SecondaryBody = "secondaryBody"
            };
        }

        public ContentfulGroupHomepageBuilder Slug(string slug)
        {
            _slug = slug;
            return this;
        }
        public ContentfulGroupHomepageBuilder MetaDescription(string metaDescription)
        {
            _metaDescription = metaDescription;
            return this;
        }
        public ContentfulGroupHomepageBuilder Title(string title)
        {
            _title = title;
            return this;
        }

        public ContentfulGroupHomepageBuilder EventBanner(ContentfulEventBanner banner)
        {
            _eventBanner = banner;
            return this;
        }

    }
}


text:
package v1

func (CloudInitNoCloudSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"":               "Represents a cloud-init nocloud user data source\nMore info: http://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html",
		"secretRef":      "UserDataSecretRef references a k8s secret that contains NoCloud userdata\n+ optional",
		"userDataBase64": "UserDataBase64 contains NoCloud cloud-init userdata as a base64 encoded string\n+ optional",
		"userData":       "UserData contains NoCloud inline cloud-init userdata\n+ optional",
	}
}

func (DomainSpec) SwaggerDoc() map[string]string {
	return map[string]string{
		"resources": "Resources describes the Compute Resources required by this vmi.",
		"cpu":       "CPU allow specified the detailed CPU topology inside the vmi.\n+optional",
		"memory":    "Memory allow specifying the VMI memory features.\n+optional",
		"machine":   "Machine type\n+optional",
		"firmware":  "Firmware\n+optional",
		"clock":     "Clock sets the clock and timers of the vmi.\n+optional",
		"features":  "Features like acpi, apic, hyperv\n+optional",
		"devices":   "Devices allows adding disks, network interfaces, ...",
	}
}

func (ResourceRequirements) SwaggerDoc() map[string]string {
	return map[string]string{
		"requests": "Requests is a description of the initial vmi resources.\nValid resource keys are \"memory\" and \"cpu\".\n+optional",
		"limits":   "Limits describes the maximum amount of compute resources allowed.\nValid resource keys are \"memory\" and \"cpu\".\n+optional",
	}
}

func (CPU) SwaggerDoc() map[string]string {
	return map[string]string{
		"":      "CPU allow specifying the CPU topology",
		"cores": "Cores specifies the number of cores inside the vmi.\nMust be a value greater or equal 1.",
	}
}

func (Memory) SwaggerDoc() map[string]string {
	return map[string]string{
		"":          "Memory allow specifying the VirtualMachineInstance memory features",
		"hugepages": "Hugepages allow to use hugepages for the VirtualMachineInstance instead of regular memory.\n+optional",
	}
}

func (Hugepages) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "Hugepages allow to use hugepages for the VirtualMachineInstance instead of regular memory.",
		"pageSize": "PageSize specifies the hugepage size, for x86_64 architecture valid values are 1Gi and 2Mi.",
	}
}

func (Machine) SwaggerDoc() map[string]string {
	return map[string]string{
		"type": "QEMU machine type is the actual chipset of the VirtualMachineInstance.",
	}
}

func (Firmware) SwaggerDoc() map[string]string {
	return map[string]string{
		"uuid": "UUID reported by the vmi bios\nDefaults to a random generated uid",
	}
}

func (Devices) SwaggerDoc() map[string]string {
	return map[string]string{
		"disks":      "Disks describes disks, cdroms, floppy and luns which are connected to the vmi",
		"watchdog":   "Watchdog describes a watchdog device which can be added to the vmi",
		"interfaces": "Interfaces describe network interfaces which are added to the vm",
	}
}

func (Disk) SwaggerDoc() map[string]string {
	return map[string]string{
		"name":       "Name is the device name",
		"volumeName": "Name of the volume which is referenced\nMust match the Name of a Volume.",
		"bootOrder":  "BootOrder is an integer value > 0, used to determine ordering of boot devices.\nLower values take precedence.\nDisks without a boot order are not tried if a disk with a boot order exists.\n+optional",
	}
}

func (DiskDevice) SwaggerDoc() map[string]string {
	return map[string]string{
		"":       "Represents the target of a volume to mount.\nOnly one of its members may be specified.",
		"disk":   "Attach a volume as a disk to the vmi",
		"lun":    "Attach a volume as a LUN to the vmi",
		"floppy": "Attach a volume as a floppy to the vmi",
		"cdrom":  "Attach a volume as a cdrom to the vmi",
	}
}

func (DiskTarget) SwaggerDoc() map[string]string {
	return map[string]string{
		"bus":      "Bus indicates the type of disk device to emulate.\nsupported values: virtio, sata, scsi, ide",
		"readonly": "ReadOnly\nDefaults to false",
	}
}

func (LunTarget) SwaggerDoc() map[string]string {
	return map[string]string{
		"bus":      "Bus indicates the type of disk device to emulate.\nsupported values: virtio, sata, scsi, ide",
		"readonly": "ReadOnly\nDefaults to false",
	}
}

func (FloppyTarget) SwaggerDoc() map[string]string {
	return map[string]string{
		"readonly": "ReadOnly\nDefaults to false",
		"tray":     "Tray indicates if the tray of the device is open or closed.\nAllowed values are \"open\" and \"closed\"\nDefaults to closed\n+optional",
	}
}

func (CDRomTarget) SwaggerDoc() map[string]string {
	return map[string]string{
		"bus":      "Bus indicates the type of disk device to emulate.\nsupported values: virtio, sata, scsi, ide",
		"readonly": "ReadOnly\nDefaults to true",
		"tray":     "Tray indicates if the tray of the device is open or closed.\nAllowed values are \"open\" and \"closed\"\nDefaults to closed\n+optional",
	}
}

func (Volume) SwaggerDoc() map[string]string {
	return map[string]string{
		"":     "Volume represents a named volume in a vmi.",
		"name": "Volume's name.\nMust be a DNS_LABEL and unique within the vmi.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names",
	}
}

func (VolumeSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"": "Represents the source of a volume to mount.\nOnly one of its members may be specified.",
		"persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace.\nDirectly attached to the vmi via qemu.\nMore info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims\n+optional",
		"cloudInitNoCloud":      "CloudInitNoCloud represents a cloud-init NoCloud user-data source.\nThe NoCloud data will be added as a disk to the vmi. A proper cloud-init installation is required inside the guest.\nMore info: http://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html\n+optional",
		"registryDisk":          "RegistryDisk references a docker image, embedding a qcow or raw disk\nMore info: https://kubevirt.gitbooks.io/user-guide/registry-disk.html\n+optional",
		"ephemeral":             "Ephemeral is a special volume source that \"wraps\" specified source and provides copy-on-write image on top of it.\n+optional",
		"emptyDisk":             "EmptyDisk represents a temporary disk which shares the vmis lifecycle\nMore info: https://kubevirt.gitbooks.io/user-guide/disks-and-volumes.html\n+optional",
	}
}

func (EphemeralVolumeSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"persistentVolumeClaim": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace.\nDirectly attached to the vmi via qemu.\nMore info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims\n+optional",
	}
}

func (EmptyDiskSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "EmptyDisk represents a temporary disk which shares the vmis lifecycle",
		"capacity": "Capacity of the sparse disk.",
	}
}

func (RegistryDiskSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"":                "Represents a docker image with an embedded disk",
		"image":           "Image is the name of the image with the embedded disk",
		"imagePullSecret": "ImagePullSecret is the name of the Docker registry secret required to pull the image. The secret must already exist.",
	}
}

func (ClockOffset) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "Exactly one of its members must be set.",
		"utc":      "UTC sets the guest clock to UTC on each boot. If an offset is specified,\nguest changes to the clock will be kept during reboots and are not reset.",
		"timezone": "Timezone sets the guest clock to the specified timezone.\nZone name follows the TZ environment variable format (e.g. 'America/New_York')",
	}
}

func (ClockOffsetUTC) SwaggerDoc() map[string]string {
	return map[string]string{
		"":              "UTC sets the guest clock to UTC on each boot.",
		"offsetSeconds": "OffsetSeconds specifies an offset in seconds, relative to UTC. If set,\nguest changes to the clock will be kept during reboots and not reset.",
	}
}

func (Clock) SwaggerDoc() map[string]string {
	return map[string]string{
		"":      "Represents the clock and timers of a vmi",
		"timer": "Timer specifies whih timers are attached to the vmi",
	}
}

func (Timer) SwaggerDoc() map[string]string {
	return map[string]string{
		"":       "Represents all available timers in a vmi",
		"hpet":   "HPET (High Precision Event Timer) - multiple timers with periodic interrupts.",
		"kvm":    "KVM \t(KVM clock) - lets guests read the host's wall clock time (paravirtualized). For linux guests.",
		"pit":    "PIT (Programmable Interval Timer) - a timer with periodic interrupts.",
		"rtc":    "RTC (Real Time Clock) - a continuously running timer with periodic interrupts.",
		"hyperv": "Hyperv (Hypervclock) - lets guests read the host's wall clock time (paravirtualized). For windows guests.",
	}
}

func (RTCTimer) SwaggerDoc() map[string]string {
	return map[string]string{
		"tickPolicy": "TickPolicy determines what happens when QEMU misses a deadline for injecting a tick to the guest\nOne of \"delay\", \"catchup\"",
		"present":    "Enabled set to false makes sure that the machine type or a preset can't add the timer.\nDefaults to true\n+optional",
		"track":      "Track the guest or the wall clock",
	}
}

func (HPETTimer) SwaggerDoc() map[string]string {
	return map[string]string{
		"tickPolicy": "TickPolicy determines what happens when QEMU misses a deadline for injecting a tick to the guest\nOne of \"delay\", \"catchup\", \"merge\", \"discard\"",
		"present":    "Enabled set to false makes sure that the machine type or a preset can't add the timer.\nDefaults to true\n+optional",
	}
}

func (PITTimer) SwaggerDoc() map[string]string {
	return map[string]string{
		"tickPolicy": "TickPolicy determines what happens when QEMU misses a deadline for injecting a tick to the guest\nOne of \"delay\", \"catchup\", \"discard\"",
		"present":    "Enabled set to false makes sure that the machine type or a preset can't add the timer.\nDefaults to true\n+optional",
	}
}

func (KVMTimer) SwaggerDoc() map[string]string {
	return map[string]string{
		"present": "Enabled set to false makes sure that the machine type or a preset can't add the timer.\nDefaults to true\n+optional",
	}
}

func (HypervTimer) SwaggerDoc() map[string]string {
	return map[string]string{
		"present": "Enabled set to false makes sure that the machine type or a preset can't add the timer.\nDefaults to true\n+optional",
	}
}

func (Features) SwaggerDoc() map[string]string {
	return map[string]string{
		"acpi":   "ACPI enables/disables ACPI insidejsondata guest\nDefaults to enabled\n+optional",
		"apic":   "Defaults to the machine type setting\n+optional",
		"hyperv": "Defaults to the machine type setting\n+optional",
	}
}

func (FeatureState) SwaggerDoc() map[string]string {
	return map[string]string{
		"":        "Represents if a feature is enabled or disabled",
		"enabled": "Enabled determines if the feature should be enabled or disabled on the guest\nDefaults to true\n+optional",
	}
}

func (FeatureAPIC) SwaggerDoc() map[string]string {
	return map[string]string{
		"enabled":        "Enabled determines if the feature should be enabled or disabled on the guest\nDefaults to true\n+optional",
		"endOfInterrupt": "EndOfInterrupt enables the end of interrupt notification in the guest\nDefaults to false\n+optional",
	}
}

func (FeatureSpinlocks) SwaggerDoc() map[string]string {
	return map[string]string{
		"enabled":   "Enabled determines if the feature should be enabled or disabled on the guest\nDefaults to true\n+optional",
		"spinlocks": "Retries indicates the number of retries\nMust be a value greater or equal 4096\nDefaults to 4096\n+optional",
	}
}

func (FeatureVendorID) SwaggerDoc() map[string]string {
	return map[string]string{
		"enabled":  "Enabled determines if the feature should be enabled or disabled on the guest\nDefaults to true\n+optional",
		"vendorid": "VendorID sets the hypervisor vendor id, visible to the vmi\nString up to twelve characters",
	}
}

func (FeatureHyperv) SwaggerDoc() map[string]string {
	return map[string]string{
		"":           "Hyperv specific features",
		"relaxed":    "Relaxed relaxes constraints on timer\nDefaults to the machine type setting\n+optional",
		"vapic":      "VAPIC indicates whether virtual APIC is enabled\nDefaults to the machine type setting\n+optional",
		"spinlocks":  "Spinlocks indicates if spinlocks should be made available to the guest\n+optional",
		"vpindex":    "VPIndex enables the Virtual Processor Index to help windows identifying virtual processors\nDefaults to the machine type setting\n+optional",
		"runtime":    "Runtime\nDefaults to the machine type setting\n+optional",
		"synic":      "SyNIC enable Synthetic Interrupt Controller\nDefaults to the machine type setting\n+optional",
		"synictimer": "SyNICTimer enable Synthetic Interrupt Controller timer\nDefaults to the machine type setting\n+optional",
		"reset":      "Reset enables Hyperv reboot/reset for the vmi\nDefaults to the machine type setting\n+optional",
		"vendorid":   "VendorID allows setting the hypervisor vendor id\nDefaults to the machine type setting\n+optional",
	}
}

func (Watchdog) SwaggerDoc() map[string]string {
	return map[string]string{
		"":     "Named watchdog device",
		"name": "Name of the watchdog",
	}
}

func (WatchdogDevice) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "Hardware watchdog device\nExactly one of its members must be set.",
		"i6300esb": "i6300esb watchdog device\n+optional",
	}
}

func (I6300ESBWatchdog) SwaggerDoc() map[string]string {
	return map[string]string{
		"":       "i6300esb watchdog device",
		"action": "The action to take. Valid values are poweroff, reset, shutdown.\nDefaults to reset",
	}
}

func (Interface) SwaggerDoc() map[string]string {
	return map[string]string{
		"name": "Logical name of the interface as well as a reference to the associated networks\nMust match the Name of a Network",
	}
}

func (InterfaceBindingMethod) SwaggerDoc() map[string]string {
	return map[string]string{
		"": "Represents the method which will be used to connect the interface to the guest.\nOnly one of its members may be specified.",
	}
}

func (InterfaceBridge) SwaggerDoc() map[string]string {
	return map[string]string{}
}

func (Network) SwaggerDoc() map[string]string {
	return map[string]string{
		"":     "Network represents a network type and a resource that should be connected to the vm.",
		"name": "Network name\nMust be a DNS_LABEL and unique within the vm.\nMore info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names",
	}
}

func (NetworkSource) SwaggerDoc() map[string]string {
	return map[string]string{
		"": "Represents the source resource that will be connected to the vm.\nOnly one of its members may be specified.",
	}
}

func (PodNetwork) SwaggerDoc() map[string]string {
	return map[string]string{
		"": "Represents the stock pod network interface",
	}
}


text:
package org.sellcom.core.util.function;

import java.util.function.Consumer;
import java.util.function.LongSupplier;

import org.sellcom.core.Contract;
import org.sellcom.core.internal.ReflectionUtils;

/**
 * Represents a supplier of {@code long}-valued results, possibly throwing an exception.
 *
 * @since 1.0
 */
@FunctionalInterface
public interface ThrowingLongSupplier extends LongSupplier {

	/**
	 * Returns a {@code LongSupplier} returning from the given supplier if this supplier throws an exception.
	 *
	 * @throws IllegalArgumentException if {@code fallback} is {@code null}
	 *
	 * @since 1.0
	 */
	default LongSupplier fallbackTo(LongSupplier fallback) {
		return fallbackTo(fallback, null);
	}

	/**
	 * Returns a {@code LongSupplier} returning from the given supplier if this supplier throws an exception.
	 *
	 * @throws IllegalArgumentException if {@code fallback} is {@code null}
	 *
	 * @since 1.0
	 */
	default LongSupplier fallbackTo(LongSupplier fallback, Consumer<Exception> exceptionConsumer) {
		Contract.checkArgument(fallback != null, "Fallback supplier must not be null");

		return () -> {
			try {
				return getAsLongThrowing();
			} catch (Exception e) {
				if (exceptionConsumer != null) {
					exceptionConsumer.accept(e);
				}

				return fallback.getAsLong();
			}
		};
	}

	/**
	 * Returns a result.
	 * Wraps any thrown checked exceptions with {@link UncheckedException}.
	 *
	 * @since 1.0
	 */
	@Override
	default long getAsLong() {
		try {
			return getAsLongThrowing();
		} catch (Error | RuntimeException e) {
			throw e;
		} catch (Exception e) {
			throw UncheckedException.wrap(e);
		}
	}

	/**
	 * Returns a result.
	 *
	 * @since 1.0
	 */
	long getAsLongThrowing() throws Exception;

	/**
	 * Returns a {@code LongSupplier} returning the given value if this supplier throws an exception.
	 *
	 * @since 1.0
	 */
	default LongSupplier orReturn(long value) {
		return orReturn(value, null);
	}

	/**
	 * Returns a {@code LongSupplier} returning the given value if this supplier throws an exception.
	 *
	 * @since 1.0
	 */
	default LongSupplier orReturn(long value, Consumer<Exception> exceptionConsumer) {
		return () -> {
			try {
				return getAsLongThrowing();
			} catch (Exception e) {
				if (exceptionConsumer != null) {
					exceptionConsumer.accept(e);
				}

				return value;
			}
		};
	}

	/**
	 * Returns a {@code ThrowingLongSupplier} throwing an exception of the given type if this supplier throws an exception.
	 * The original exception thrown by this supplier is the {@link Throwable#getCause() cause} of the thrown exception.
	 *
	 *
The exception class must have a constructor accepting a single {@code Throwable} as an argument.

	 *
	 * @throws IllegalArgumentException if {@code exceptionClass} is {@code null}
	 *
	 * @since 1.0
	 */
	default ThrowingLongSupplier orThrow(Class<? extends RuntimeException> exceptionClass) {
		Contract.checkArgument(exceptionClass != null, "Exception class must not be null");

		return () -> {
			try {
				return getAsLongThrowing();
			} catch (Exception e) {
				throw ReflectionUtils.createException(exceptionClass, e);
			}
		};
	}

	/**
	 * Returns a {@code ThrowingLongSupplier} throwing an exception of the given type if this supplier throws an exception.
	 * The original exception thrown by this supplier is the {@link Throwable#getCause() cause} of the thrown exception.
	 *
	 *
The exception class must have a constructor accepting {@code String} and {@code Throwable} as arguments.

	 *
	 * @throws IllegalArgumentException if {@code exceptionClass} is {@code null}
	 *
	 * @since 1.0
	 */
	default ThrowingLongSupplier orThrow(Class<? extends RuntimeException> exceptionClass, String message) {
		Contract.checkArgument(exceptionClass != null, "Exception class must not be null");

		return () -> {
			try {
				return getAsLongThrowing();
			} catch (Exception e) {
				throw ReflectionUtils.createException(exceptionClass, message, e);
			}
		};
	}

	/**
	 * Returns a {@code ThrowingLongSupplier} returning from the given supplier if this supplier throws an exception.
	 *
	 * @throws IllegalArgumentException if {@code other} is {@code null}
	 *
	 * @since 1.0
	 */
	default ThrowingLongSupplier orTryWith(ThrowingLongSupplier other) {
		return orTryWith(other, null);
	}

	/**
	 * Returns a {@code ThrowingLongSupplier} returning from the given supplier if this supplier throws an exception.
	 *
	 * @throws IllegalArgumentException if {@code other} is {@code null}
	 *
	 * @since 1.0
	 */
	default ThrowingLongSupplier orTryWith(ThrowingLongSupplier other, Consumer<Exception> exceptionConsumer) {
		Contract.checkArgument(other != null, "Other supplier must not be null");

		return () -> {
			try {
				return getAsLongThrowing();
			} catch (Exception e) {
				if (exceptionConsumer != null) {
					exceptionConsumer.accept(e);
				}

				return other.getAsLongThrowing();
			}
		};
	}

}