text:
<?php

/*
 * This file is part of the tmilos/jose-jwt package.
 *
 * (c) Milos Tomic <tmilos@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Tmilos\JoseJwt\Jws;

use Tmilos\JoseJwt\Error\JoseJwtException;

class HmacUsingSha implements JwsAlgorithm
{
    /** @var string */
    private $hashMethod;

    /**
     * @param string $hashMethod
     */
    public function __construct($hashMethod)
    {
        $this->hashMethod = $hashMethod;
    }

    /**
     * @param string $securedInput
     * @param string $key
     *
     * @return string
     */
    public function sign($securedInput, $key)
    {
        if (null === $key || trim($key) === '') {
            throw new JoseJwtException('Hmac key can not be empty');
        }

        return hash_hmac($this->hashMethod, $securedInput, $key, true);
    }

    /**
     * @param string $signature
     * @param string $securedInput
     * @param string $key
     *
     * @return bool
     */
    public function verify($signature, $securedInput, $key)
    {
        if (null == $key || trim($key) === '') {
            throw new JoseJwtException('Hmac key can not be empty');
        }

        $calculatedSignature = hash_hmac($this->hashMethod, $securedInput, $key, true);

        return $signature === $calculatedSignature;
    }
}


text:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import MovieItem from './MovieItem';
import { getAllMovies, readMovie, deleteMovie, loadMovieForm } from '../actions';

const MoviesList = ({ movies, onDeleteMovie, onReadMovie, onGetAllMovies, onLoadMovieForm }) => {
    const handleEdit = (movieId) => {
        onReadMovie(movies, movieId);
        onLoadMovieForm();
    };

    const handleDelete = (movieId) => {
        onDeleteMovie(movies, movieId);
        onGetAllMovies();
    };

    const list = [];

    if (Object.keys(movies).length) {
        movies.forEach((movie) => {
            list.push(
                <MovieItem
                    key={movie.name}
                    movie={ movie }
                    handleEdit={ (movieId) => handleEdit(movieId) }
                    handleDelete={ (movieId) => handleDelete(movieId) }
                />
            );
        });
    }
    return <div> {list} </div>;
};

MoviesList.propTypes = {
    movies: PropTypes.object,
    movieObj: PropTypes.object,
    onGetAllMovies: PropTypes.object,
    onReadMovie: PropTypes.func,
    onDeleteMovie: PropTypes.func,
    onUpdateMovie: PropTypes.func,
    onLoadMovieForm: PropTypes.func
};

const mapStateToProps = (state) => {
    return {
        movies: state.movieCollectionReducer.movies,
        movieObj: state.movieCollectionReducer.movieObj,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        onGetAllMovies: () => dispatch(getAllMovies()),
        onDeleteMovie: (movies, movieId) => dispatch(deleteMovie(movies, movieId)),
        onReadMovie: (movies, movieId) => dispatch(readMovie(movies, movieId)),
        onLoadMovieForm: () => dispatch(loadMovieForm())
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(MoviesList);

redpajama_set_name: RedPajamaGithub


text:
package gwt.material.design.addins.client.camera.events;

import com.google.gwt.event.shared.EventHandler;
import gwt.material.design.addins.client.camera.MaterialCameraCapture;

/**
 * Handler for {@link CameraCaptureEvent}s.
 *
 * @author gilberto-torrezan
 * @see MaterialCameraCapture
 */
public interface CameraCaptureHandler extends EventHandler {

    /**
     * Fired when there's a change on the state of the camera capture.
     */
    void onCameraCaptureChange(CameraCaptureEvent event);

}


text:
using System;
using System.Globalization;
using System.ServiceModel;

namespace RadyoCommon
{
    public abstract class ServiceBase
    {
        protected delegate void ParameterlessMethod();

        protected void RunInTryCatch(ParameterlessMethod action)
        {
            try
            {
                action();
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

    }
}


text:
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf,SparkContext}

object RddAggregateByKey{
    def main(args:Array[String]){
	val conf = new SparkConf().setAppName("RDD Aggregate").setMaster("local")
	val sc = new SparkContext(conf)
	val stocks = sc.textFile("./stocks")
	val projdata = stocks.map(line => (line.split("\t")(1), line.split("\t")(7).toInt))
	val volMax = projdata.aggregateByKey(0)(math.max(_,_), math.max(_,_))
	val volMin = projdata.aggregateByKey(100000000)(math.min(_,_), math.min(_,_))
	val aggRdd = volMax ++ volMin
	aggRdd.saveAsTextFile("./voulme")
    }
}


text:
package org.tourgune.mdp.api.rowmapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.tourgune.mdp.api.bean.PriceBean;
import org.tourgune.mdp.api.utils.TablesDB;

public class PricesBeanRowMapper implements RowMapper {

	public Object mapRow (ResultSet rs, int rowNum) throws SQLException {

		PriceBean priceBean = new PriceBean();
		priceBean.setCountry(rs.getString(TablesDB.STORED_PROCEDURE_COUNTRY));
		priceBean.setAal1(rs.getString(TablesDB.STORED_PROCEDURE_AAL1));
		priceBean.setAal2(rs.getString(TablesDB.STORED_PROCEDURE_AAL2));
		priceBean.setAal3(rs.getString(TablesDB.STORED_PROCEDURE_AAL3));
		priceBean.setAal4(rs.getString(TablesDB.STORED_PROCEDURE_AAL4));
		priceBean.setLocality(rs.getString(TablesDB.STORED_PROCEDURE_LOCALITY));
		priceBean.setAccType(rs.getString(TablesDB.STORED_PROCEDURE_ACC_TYPE));
		priceBean.setProduct(rs.getString(TablesDB.STORED_PROCEDURE_PRODUCT));
		priceBean.setDataDate(rs.getString(TablesDB.STORED_PROCEDURE_DATE));

		int category = rs.getInt(TablesDB.STORED_PROCEDURE_CATEGORY);
		priceBean.setCategory(rs.wasNull() ? null : category);

		priceBean.setPrice(rs.getFloat(TablesDB.STORED_PROCEDURE_PRICE));
		priceBean.setNumAcc(rs.getInt(TablesDB.STORED_PROCEDURE_NUM_ACC));

		return priceBean;
	}
}


text:
package org.apache.sling.junit.performance.runner;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Execute the annotated method after every performance iteration of the performance test.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface AfterPerformanceTest {
}


text:
from ..remote import RemoteModel

class ConfigErrorGridRemote(RemoteModel):
    """

    |  ``Timestamp:`` none
    |  ``attribute type:`` string

    |  ``ConfigErrorID:`` none
    |  ``attribute type:`` string

    |  ``DeviceID:`` none
    |  ``attribute type:`` string

    |  ``ErrMsg:`` none
    |  ``attribute type:`` string

    """

    properties = ("Timestamp",
                  "ConfigErrorID",
                  "DeviceID",
                  "ErrMsg",
                  )


text:
namespace supersonic {

class BoundExpression;
class BufferAllocator;

FailureOrOwned<BoundExpression> BoundNegate(unique_ptr<BoundExpression> source,
                                            BufferAllocator* allocator,
                                            rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundPlus(unique_ptr<BoundExpression> left,
                                          unique_ptr<BoundExpression> right,
                                          BufferAllocator* allocator,
                                          rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundMultiply(unique_ptr<BoundExpression> left,
                                              unique_ptr<BoundExpression> right,
                                              BufferAllocator* allocator,
                                              rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundMinus(unique_ptr<BoundExpression> left,
                                           unique_ptr<BoundExpression> right,
                                           BufferAllocator* allocator,
                                           rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundDivideSignaling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundDivideNulling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundDivideQuiet(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundCppDivideSignaling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundCppDivideNulling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundModulusSignaling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

FailureOrOwned<BoundExpression> BoundModulusNulling(
    unique_ptr<BoundExpression> left,
    unique_ptr<BoundExpression> right,
    BufferAllocator* allocator,
    rowcount_t max_row_count);

}  // namespace supersonic

#endif  // SUPERSONIC_EXPRESSION_CORE_ARITHMETIC_BOUND_EXPRESSIONS_H_


text:
"""Tests for search_space_utils."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl.testing import parameterized
import tensorflow.compat.v1 as tf

from tunas import basic_specs
from tunas import mobile_search_space_v3
from tunas import schema
from tunas import search_space_utils

class SearchSpaceUtilsTest(tf.test.TestCase, parameterized.TestCase):

  def test_normalize_strides(self):
    self.assertEqual(search_space_utils.normalize_strides(1), (1, 1))
    self.assertEqual(search_space_utils.normalize_strides((2, 2)), (2, 2))
    with self.assertRaisesWithPredicateMatch(
        ValueError, 'neither an integer nor a pair of integers'):
      search_space_utils.normalize_strides((1, 2, 3))

  def test_scale_filters(self):
    self.assertEqual(search_space_utils.scale_filters(32, 1/4, 8), 8)
    self.assertEqual(search_space_utils.scale_filters(64, 1/3, 8), 24)
    self.assertEqual(search_space_utils.scale_filters(64, 1.4, 32), 96)
    self.assertEqual(search_space_utils.scale_filters(64, 3, 32), 192)
    self.assertEqual(search_space_utils.scale_filters(68, 1.0, 8), 72)
    self.assertEqual(search_space_utils.scale_filters(68, 1.2, 8), 80)
    self.assertEqual(search_space_utils.scale_filters(76, 1.0, 8), 80)
    self.assertEqual(search_space_utils.scale_filters(76, 1.2, 8), 88)

  def test_make_divisible(self):
    # If value < divisor then make_divisor(value, divisor) == divisor
    self.assertEqual(search_space_utils.make_divisible(7, 8), 8)
    self.assertEqual(search_space_utils.make_divisible(92, 100), 100)

    # If value % divisor == 0 then make_divisible(value, divisor) == value
    self.assertEqual(search_space_utils.make_divisible(8, 8), 8)
    self.assertEqual(search_space_utils.make_divisible(56, 8), 56)
    self.assertEqual(search_space_utils.make_divisible(72, 8), 72)

    # Otherwise, try to round to the nearest multiple of `base`.
    self.assertEqual(search_space_utils.make_divisible(1023, 8), 1024)
    self.assertEqual(search_space_utils.make_divisible(1025, 8), 1024)

    # We shouldn't round down by more than 10%. So this function outputs 24
    # rather than 16.
    self.assertEqual(search_space_utils.make_divisible(18, 8), 24)

  def test_tf_make_divisible(self):
    # If value < divisor then make_divisor(value, divisor) == divisor
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(7, 8)), 8)
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(92, 100)), 100)

    # If value % divisor == 0 then make_divisible(value, divisor) == value
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(8, 8)), 8)
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(56, 8)), 56)
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(72, 8)), 72)

    # Otherwise, try to round to the nearest multiple of `base`.
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(1023, 8)), 1024)
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(1025, 8)), 1024)

    # We shouldn't round down by more than 10%. So this function outputs 24
    # rather than 16.
    self.assertEqual(
        self.evaluate(search_space_utils.tf_make_divisible(18, 8)), 24)

    # Test behavior with Tensor inputs of different dtypes.
    self.assertEqual(
        self.evaluate(
            search_space_utils.tf_make_divisible(
                tf.constant(56, tf.int32), 8)),
        56)
    self.assertEqual(
        self.evaluate(
            search_space_utils.tf_make_divisible(
                tf.constant(56, tf.float32), 8)),
        56)

  def test_tf_scale_filters_values(self):
    output1 = search_space_utils.tf_scale_filters(32, 1/4, 8)
    self.assertEqual(self.evaluate(output1), 8)

    output2 = search_space_utils.tf_scale_filters(64, 1/3, 8)
    self.assertEqual(self.evaluate(output2), 24)

    output3 = search_space_utils.tf_scale_filters(64, 1.4, 32)
    self.assertEqual(self.evaluate(output3), 96)

    output4 = search_space_utils.tf_scale_filters(64, 3, 32)
    self.assertEqual(self.evaluate(output4), 192)

    output5 = search_space_utils.tf_scale_filters(68, 1.0, 8)
    self.assertEqual(self.evaluate(output5), 72)

    output6 = search_space_utils.tf_scale_filters(68, 1.2, 8)
    self.assertEqual(self.evaluate(output6), 80)

    output7 = search_space_utils.tf_scale_filters(76, 1.0, 8)
    self.assertEqual(self.evaluate(output7), 80)

    output8 = search_space_utils.tf_scale_filters(76, 1.2, 8)
    self.assertEqual(self.evaluate(output8), 88)

  def test_tf_scale_filters_types_and_shapes(self):
    output1 = search_space_utils.tf_scale_filters(32, 1/4, 8)
    self.assertEqual(output1.shape, [])
    self.assertEqual(output1.dtype, tf.int32)

    output2 = search_space_utils.tf_scale_filters(
        tf.constant(64, tf.int32),
        tf.constant(1/3, tf.float32),
        tf.constant(8, tf.int32))
    self.assertEqual(output2.shape, [])
    self.assertEqual(output2.dtype, tf.int32)

  def test_prune_simple_model_spec_no_tags(self):
    pruned_spec = search_space_utils.prune_model_spec(
        model_spec=[
            schema.OneOf(['a', 'b', 'c'], basic_specs.OP_TAG),
            schema.OneOf(['z', 'w'], basic_specs.FILTERS_TAG),
        ],
        genotype=[2, 1],
        prune_filters_by_value=True)

    self.assertEqual(
        pruned_spec,
        [
            schema.OneOf(['c'], basic_specs.OP_TAG),
            schema.OneOf(['w'], basic_specs.FILTERS_TAG),
        ])

  def test_prune_simple_model_spec_validation_no_tags(self):
    model_spec = [
        schema.OneOf(['a', 'b', 'c'], basic_specs.OP_TAG),
        schema.OneOf(['z', 'w'], basic_specs.FILTERS_TAG),
    ]

    with self.assertRaisesWithLiteralMatch(
        ValueError, 'Genotype contains 1 oneofs but model_spec contains 2'):
      search_space_utils.prune_model_spec(
          model_spec=model_spec,
          genotype=[0],
          prune_filters_by_value=True)

  def test_prune_model_spec_with_path_dropout_training(self):
    model_spec = {
        'op1': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=2, strides=2),
                basic_specs.ZeroSpec(),
            ], basic_specs.OP_TAG),
        'op2': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=3, strides=4),
            ], basic_specs.OP_TAG),
        'filter': schema.OneOf([32], basic_specs.FILTERS_TAG),
    }

    model_spec = search_space_utils.prune_model_spec(
        model_spec,
        {basic_specs.OP_TAG: [0, 0]},
        path_dropout_rate=0.2,
        training=True)

    self.assertCountEqual(model_spec.keys(), ['op1', 'op2', 'filter'])
    self.assertEqual(model_spec['op1'].mask.shape, tf.TensorShape([1]))
    self.assertIsNone(model_spec['op2'].mask)
    self.assertIsNone(model_spec['filter'].mask)

    self.assertEqual(
        model_spec['op1'].choices,
        [mobile_search_space_v3.ConvSpec(kernel_size=2, strides=2)])
    self.assertEqual(
        model_spec['op2'].choices,
        [mobile_search_space_v3.ConvSpec(kernel_size=3, strides=4)])
    self.assertEqual(
        model_spec['filter'].choices,
        [32])

    self.assertEqual(model_spec['op1'].tag, basic_specs.OP_TAG)
    self.assertEqual(model_spec['op2'].tag, basic_specs.OP_TAG)
    self.assertEqual(model_spec['filter'].tag, basic_specs.FILTERS_TAG)

    op_mask_sum = 0
    for _ in range(100):
      # The value should either be 0 or 1 / (1 - path_dropout_rate) = 1.25
      op_mask_value = self.evaluate(model_spec['op1'].mask)
      self.assertTrue(
          abs(op_mask_value - 0) < 1e-6 or abs(op_mask_value - 1.25) < 1e-6,
          msg='Unexpected op_mask_value: {}'.format(op_mask_value))
      op_mask_sum += op_mask_value[0]

    # The probability of this test failing by random chance is roughly 0.002%.
    # Our random number generators are deterministically seeded, so the test
    # shouldn't be flakey.
    self.assertGreaterEqual(op_mask_sum, 75)
    self.assertLessEqual(op_mask_sum, 113)

  def test_prune_model_spec_with_path_dropout_rate_tensor(self):
    model_spec = {
        'op1': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=2, strides=2),
                basic_specs.ZeroSpec(),
            ], basic_specs.OP_TAG),
        'op2': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=3, strides=4),
            ], basic_specs.OP_TAG),
        'filter': schema.OneOf([32], basic_specs.FILTERS_TAG),
    }

    model_spec = search_space_utils.prune_model_spec(
        model_spec,
        {basic_specs.OP_TAG: [0, 0]},
        path_dropout_rate=tf.constant(2.0)  / tf.constant(10.0),
        training=True)

    self.assertCountEqual(model_spec.keys(), ['op1', 'op2', 'filter'])
    self.assertEqual(model_spec['op1'].mask.shape, tf.TensorShape([1]))
    self.assertIsNone(model_spec['op2'].mask)
    self.assertIsNone(model_spec['filter'].mask)

    # The value should either be 0 or 1 / (1 - path_dropout_rate) = 1.25
    op_mask_value = self.evaluate(model_spec['op1'].mask)
    self.assertTrue(
        abs(op_mask_value - 0) < 1e-6 or abs(op_mask_value - 1.25) < 1e-6,
        msg='Unexpected op_mask_value: {}'.format(op_mask_value))

  def test_prune_model_spec_with_path_dropout_eval(self):
    model_spec = {
        'op1': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=2, strides=2),
                basic_specs.ZeroSpec(),
            ], basic_specs.OP_TAG),
        'op2': schema.OneOf(
            [
                mobile_search_space_v3.ConvSpec(kernel_size=3, strides=4),
            ], basic_specs.OP_TAG),
        'filter': schema.OneOf([32], basic_specs.FILTERS_TAG),
    }
    model_spec = search_space_utils.prune_model_spec(
        model_spec,
        {basic_specs.OP_TAG: [0, 0]},
        path_dropout_rate=0.2,
        training=False)

    self.assertCountEqual(model_spec.keys(), ['op1', 'op2', 'filter'])
    # Even though path_dropout_rate=0.2, the controller should not populate
    # the mask for op1 because we called prune_model_spec() with training=False.
    # In other words, path_dropout_rate should only affect the behavior during
    # training, not during evaluation.
    self.assertIsNone(model_spec['op1'].mask)
    self.assertIsNone(model_spec['op2'].mask)
    self.assertIsNone(model_spec['filter'].mask)

    self.assertEqual(model_spec['op1'].tag, basic_specs.OP_TAG)
    self.assertEqual(model_spec['op2'].tag, basic_specs.OP_TAG)
    self.assertEqual(model_spec['filter'].tag, basic_specs.FILTERS_TAG)

    self.assertEqual(
        model_spec['op1'].choices,
        [mobile_search_space_v3.ConvSpec(kernel_size=2, strides=2)])
    self.assertEqual(
        model_spec['op2'].choices,
        [mobile_search_space_v3.ConvSpec(kernel_size=3, strides=4)])
    self.assertEqual(
        model_spec['filter'].choices,
        [32])

  def test_prune_model_spec_prune_filters_by_value(self):
    model_spec = {
        'op': schema.OneOf(['a', 'b', 'c'], basic_specs.OP_TAG),
        'filters': schema.OneOf([128, 256, 512], basic_specs.FILTERS_TAG),
    }
    genotype = {
        basic_specs.OP_TAG: [1],
        basic_specs.FILTERS_TAG: [512],  # Use values instead of indices
    }
    pruned_spec = search_space_utils.prune_model_spec(
        model_spec, genotype, prune_filters_by_value=True)

    expected_spec = {
        'op': schema.OneOf(['b'], basic_specs.OP_TAG),
        'filters': schema.OneOf([512], basic_specs.FILTERS_TAG),
    }
    self.assertEqual(pruned_spec, expected_spec)

  def test_prune_model_spec_prune_filters_by_value_with_invalid_value(self):
    model_spec = {
        'op': schema.OneOf(['a', 'b', 'c'], basic_specs.OP_TAG),
        'filters': schema.OneOf([128, 256, 512], basic_specs.FILTERS_TAG),
    }
    genotype = {
        basic_specs.OP_TAG: [1],
        basic_specs.FILTERS_TAG: [1024],  # Use values instead of indices
    }
    with self.assertRaises(ValueError):
      search_space_utils.prune_model_spec(
          model_spec, genotype, prune_filters_by_value=True)

  def test_scale_conv_tower_spec_filter_multipliers(self):
    model_spec = basic_specs.ConvTowerSpec(
        blocks=[
            basic_specs.block(
                layers=[
                    schema.OneOf(
                        [
                            basic_specs.FilterMultiplier(3.0),
                            basic_specs.FilterMultiplier(6.0)
                        ], basic_specs.FILTERS_TAG)
                ],
                filters=48)
        ],
        filters_base=8)
    scaled_spec = search_space_utils.scale_conv_tower_spec(
        model_spec,
        multipliers=(0.5, 1, 2),
        base=8)

    # FilterMultiplier objects should not be affected by the scaling function.
    self.assertEqual(
        scaled_spec.blocks[0].layers[0].choices,
        [
            basic_specs.FilterMultiplier(3.0),
            basic_specs.FilterMultiplier(6.0),
        ])

    # However, absolute filter sizes should still be scaled.
    self.assertEqual(
        scaled_spec.blocks[0].filters.choices,
        [24, 48, 96])

  def test_tf_argmax_or_zero(self):
    # Pruned OneOf structure without mask
    oneof = schema.OneOf([1], 'foo')
    self.assertEqual(
        self.evaluate(search_space_utils.tf_argmax_or_zero(oneof)), 0)

    # Unpruned OneOf structure without mask
    with self.assertRaisesWithPredicateMatch(
        ValueError, 'Expect pruned structure'):
      oneof = schema.OneOf([1, 2], 'foo')
      search_space_utils.tf_argmax_or_zero(oneof)

    # Unpruned OneOf structure with mask
    oneof = schema.OneOf([1, 2], 'foo', tf.constant([0.0, 1.0]))
    self.assertEqual(
        self.evaluate(search_space_utils.tf_argmax_or_zero(oneof)), 1)

  def test_tf_indices_with_masks(self):
    model_spec = [
        schema.OneOf([1], 'foo', mask=tf.constant([1])),
        schema.OneOf([2, 3], 'bar', mask=tf.constant([0, 1])),
        schema.OneOf([4, 5, 6], 'baz', mask=tf.constant([0, 0, 1])),
    ]
    indices = search_space_utils.tf_indices(model_spec)
    self.assertAllEqual(self.evaluate(indices), [0, 1, 2])

  def test_parse_list(self):
    self.assertEqual([], search_space_utils.parse_list('', str))
    self.assertEqual([], search_space_utils.parse_list('   \t', str))
    self.assertEqual(['hello'], search_space_utils.parse_list('hello', str))
    self.assertEqual(['he', 'lo'], search_space_utils.parse_list('he:lo', str))
    self.assertEqual([42], search_space_utils.parse_list('42', int))
    self.assertEqual([4, 2], search_space_utils.parse_list('4:2', int))
    self.assertEqual([1, 2, 3], search_space_utils.parse_list('1:2:3', int))
    self.assertAllClose(
        [1.5, 2.5], search_space_utils.parse_list('1.5:2.5', float))

  def test_reward_for_single_cost_model_mnas(self):
    # Test for MNAS (soft) reward function
    estimated_cost = 1
    rl_cost_model_target = 0.5
    rl_cost_model_exponent = -0.07
    accuracy = 0.8

    rl_stats = search_space_utils.reward_for_single_cost_model(
        quality=accuracy,
        rl_reward_function='mnas',
        estimated_cost=estimated_cost,
        rl_cost_model_target=rl_cost_model_target,
        rl_cost_model_exponent=rl_cost_model_exponent)
    expected_rl_cost_ratio = estimated_cost / rl_cost_model_target
    self.assertAllClose(expected_rl_cost_ratio,
                        rl_stats['rl_cost_ratio'])
    expected_rl_cost_adjustment = pow(expected_rl_cost_ratio,
                                      rl_cost_model_exponent)
    self.assertAllClose(expected_rl_cost_adjustment,
                        self.evaluate(rl_stats['rl_cost_adjustment']))
    expected_rl_reward = accuracy * expected_rl_cost_adjustment
    self.assertAllClose(expected_rl_reward,
                        self.evaluate(rl_stats['rl_reward']))

  def test_reward_for_single_cost_model_abs(self):
    # Test for ABS reward function.
    estimated_cost = 1
    rl_cost_model_target = 0.5
    rl_cost_model_exponent = -0.07
    accuracy = 0.8

    rl_stats = search_space_utils.reward_for_single_cost_model(
        accuracy,
        rl_reward_function='abs',
        estimated_cost=estimated_cost,
        rl_cost_model_target=rl_cost_model_target,
        rl_cost_model_exponent=rl_cost_model_exponent)
    expected_rl_cost_ratio = estimated_cost / rl_cost_model_target
    self.assertAllClose(expected_rl_cost_ratio,
                        rl_stats['rl_cost_ratio'])
    expected_rl_cost_adjustment = (
        rl_cost_model_exponent * abs(expected_rl_cost_ratio - 1))
    self.assertAllClose(expected_rl_cost_adjustment,
                        self.evaluate(rl_stats['rl_cost_adjustment']))
    expected_rl_reward = accuracy + expected_rl_cost_adjustment
    self.assertAllClose(expected_rl_reward,
                        self.evaluate(rl_stats['rl_reward']))

  def test_reward_for_single_cost_model_mnas_hard(self):
    # Test for MNAS_HARD reward function.
    estimated_cost = 1
    rl_cost_model_target = 0.5
    rl_cost_model_exponent = -0.07
    accuracy = 0.8

    rl_stats = search_space_utils.reward_for_single_cost_model(
        accuracy,
        rl_reward_function='mnas_hard',
        estimated_cost=estimated_cost,
        rl_cost_model_target=rl_cost_model_target,
        rl_cost_model_exponent=rl_cost_model_exponent)
    expected_rl_cost_ratio = estimated_cost / rl_cost_model_target
    self.assertAllClose(expected_rl_cost_ratio,
                        rl_stats['rl_cost_ratio'])
    expected_rl_cost_adjustment = min(
        pow(expected_rl_cost_ratio, rl_cost_model_exponent), 1)
    self.assertAllClose(expected_rl_cost_adjustment,
                        self.evaluate(rl_stats['rl_cost_adjustment']))
    expected_rl_reward = accuracy * expected_rl_cost_adjustment
    self.assertAllClose(expected_rl_reward,
                        self.evaluate(rl_stats['rl_reward']))

if __name__ == '__main__':
  tf.disable_v2_behavior()
  tf.test.main()


text:
package com.cardpay.pccredit.QZBankInterface.service;

/**
 * 循环贷接口,经ESB转发
 * Created by johhny on 15/4/13.
 */
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cardpay.pccredit.QZBankInterface.model.Circle;
import com.cardpay.pccredit.QZBankInterface.model.Circle_ACCT_INFO;
import com.cardpay.pccredit.QZBankInterface.util.DateUtil;
import com.cardpay.pccredit.common.Arith;
import com.cardpay.pccredit.customer.model.CustomerInfor;
import com.cardpay.pccredit.intopieces.constant.Constant;
import com.cardpay.pccredit.manager.constant.ManagerBelongMapConstants;
import com.dc.eai.data.Array;
import com.dc.eai.data.CompositeData;
import com.dc.eai.data.Field;
import com.dc.eai.data.FieldAttr;
import com.dc.eai.data.FieldType;
import com.wicresoft.jrad.base.database.dao.common.CommonDao;
import com.wicresoft.jrad.modules.dictionary.DictionaryManager;
import com.wicresoft.jrad.modules.dictionary.model.Dictionary;
import com.wicresoft.jrad.modules.dictionary.model.DictionaryItem;
import com.wicresoft.util.spring.Beans;
@Service
public class IESBForCircleCredit {
	@Autowired
	private CommonDao commonDao;
    /**
     * 组装CompositeData报文
     * @return
     */
    public static CompositeData createCircleCreditRequest(Circle circle,List<Circle_ACCT_INFO> acct_info_ls){
    	SimpleDateFormat formatter2 = new SimpleDateFormat("dd");
    	SimpleDateFormat formatter8 = new SimpleDateFormat("yyyyMMdd");
    	SimpleDateFormat formatter10 = new SimpleDateFormat("yyyy-MM-dd");

        CompositeData cd = new CompositeData();

        //SYS_HEAD
        CompositeData syaHead_struct = new CompositeData();
        //在syaHead_struct中加SERVICECODE
        Field serviceCodeField = new Field(new FieldAttr(FieldType.FIELD_STRING, 11));
        serviceCodeField.setValue("02002000010");//循环贷服务服务码
        syaHead_struct.addField("SERVICE_CODE", serviceCodeField);

        //在syaHead_struct中加SERVICESCENE
        Field serviceSceneField = new Field(new FieldAttr(FieldType.FIELD_STRING, 2));
        serviceSceneField.setValue("01"); //循环贷对应服务场景01
        syaHead_struct.addField("SERVICE_SCENE", serviceSceneField);

       //在syaHead_struct中加TRAN_DATE
        Field tran_datefield = new Field(new FieldAttr(FieldType.FIELD_STRING, 8));
        tran_datefield.setValue(formatter8.format(new Date())); //交易日期
        syaHead_struct.addField("TRAN_DATE", tran_datefield);

        //在syaHead_struct中加CONSUMER_ID
        Field consumer_idField = new Field(new FieldAttr(FieldType.FIELD_STRING, 6));
        consumer_idField.setValue("300025"); //消费系统编号
        syaHead_struct.addField("CONSUMER_ID", consumer_idField);

        cd.addStruct("SYS_HEAD", syaHead_struct);

        //BODY
        CompositeData body_struct = new CompositeData();

        //合同号
        Field CONTRACT_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //CONTRACT_NO.setValue("0001");//todo:传入合同号
        CONTRACT_NO.setValue(circle.getContractNo());//todo:传入合同号
        body_struct.addField("CONTRACT_NO", CONTRACT_NO);

        //卡号
        Field CARD_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //CARD_NO.setValue("0000001");//todo:传入卡号
        CARD_NO.setValue(circle.getCardNo());//todo:传入卡号
        body_struct.addField("CARD_NO", CARD_NO);

        //客户号
        Field CLIENT_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //CLIENT_NO.setValue("00001");//todo:传入客户号
        CLIENT_NO.setValue(circle.getClientNo());//todo:传入客户号
        body_struct.addField("CLIENT_NO", CLIENT_NO);

        //担保方式 todo:非ESB提供数据字典
        Field GUARANTEE_MODE=new Field(new FieldAttr(FieldType.FIELD_STRING,10));
        //GUARANTEE_MODE.setValue("100");//抵押
        GUARANTEE_MODE.setValue(circle.getGuaranteeMode());//抵押.setValue("100");//抵押
        body_struct.addField("GUARANTEE_MODE", GUARANTEE_MODE);

        //担保方式细分 todo:非ESB提供数据字典
        Field GUARANTEE_MODE_DETAIL=new Field(new FieldAttr(FieldType.FIELD_STRING,10));
        //GUARANTEE_MODE_DETAIL.setValue("1");
        GUARANTEE_MODE_DETAIL.setValue(circle.getGuaranteeModeDetail());
        body_struct.addField("GUARANTEE_MODE_DETAIL", GUARANTEE_MODE_DETAIL);

        //币种
        Field CCY=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //CCY.setValue("CNY");//人民币
        CCY.setValue(circle.getCcy1());//人民币
        body_struct.addField("CCY", CCY);

        //合同金额
        Field CONTRACT_AMT=new Field(new FieldAttr(FieldType.FIELD_DOUBLE,20,2));
        //CONTRACT_AMT.setValue("");//todo:传入合同金额
        if(circle.getContractAmt() != null && !circle.getContractAmt().equals("")){
        	CONTRACT_AMT.setValue(Double.valueOf(circle.getContractAmt()));//todo:传入合同金额
        }else{
        	CONTRACT_AMT.setValue(Double.valueOf("0.0"));//todo:传入合同金额
        }

        body_struct.addField("CONTRACT_AMT", CONTRACT_AMT);

        //贷款起始日期
        Field START_DATE=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //START_DATE.setValue("20150414");//todo:传入起始日期 YYYYMMdd
        START_DATE.setValue(formatter10.format(circle.getStartDate()));//todo:传入起始日期 YYYYMMdd
        body_struct.addField("START_DATE", START_DATE);

        //贷款结束日期
        Field END_DATE=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //END_DATE.setValue("20160414");//todo:传入结束日期
        //END_DATE.setValue(formatter10.format(circle.getEndDate()));//todo:传入结束日期
        //结束日期加上期限传给信贷
        END_DATE.setValue(formatter10.format(DateUtil.shiftMonth(circle.getEndDate(), Integer.parseInt(circle.getTerm()))));
        //END_DATE.setValue(formatter10.format(circle.getEndDate()));
        body_struct.addField("END_DATE", END_DATE);

        //外币时需要换算
        Field EXCHANGE_RATE=new Field(new FieldAttr(FieldType.FIELD_DOUBLE,20,2));
        //EXCHANGE_RATE.setValue("0.2");//todo:传入外币需要换算汇率
        if(circle.getExchangeRate() != null && !circle.getExchangeRate().equals("")){
        	EXCHANGE_RATE.setValue(Double.valueOf(circle.getExchangeRate()));//todo:传入外币需要换算汇率
        }else{
        	EXCHANGE_RATE.setValue(Double.valueOf("0.0"));//todo:传入外币需要换算汇率
        }
        body_struct.addField("EXCHANGE_RATE", EXCHANGE_RATE);

        //管理机构
        Field MANA_ORG=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //MANA_ORG.setValue("9350501001");//todo:传入管理机构
        MANA_ORG.setValue(circle.getManaOrg());
        body_struct.addField("MANA_ORG", MANA_ORG);

        //登记人
        Field REGISTERED_ID=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //REGISTERED_ID.setValue("0389");//todo:传入当前客户经理柜员号
        REGISTERED_ID.setValue(circle.getRegisteredId());
        body_struct.addField("REGISTERED_ID", REGISTERED_ID);

        //登记机构
        Field REGIST_ORG_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //REGIST_ORG_NO.setValue("9350501001");//todo:传入登记机构
        REGIST_ORG_NO.setValue(circle.getRegistOrgNo());
        body_struct.addField("REGIST_ORG_NO", REGIST_ORG_NO);

        //入账机构码
        Field INCOME_ORG_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //INCOME_ORG_NO.setValue("0003");//todo:传入入账机构码(没找到)
        INCOME_ORG_NO.setValue(circle.getIncomeOrgNo());
        body_struct.addField("INCOME_ORG_NO", INCOME_ORG_NO);

        //登记日期
        Field REGISTERED_DATE=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        REGISTERED_DATE.setValue("2015-04-14");//todo:传入登记日期
        REGISTERED_DATE.setValue(formatter10.format(circle.getRegisteredDate()));//todo:传入登记日期
        body_struct.addField("REGISTERED_DATE", REGISTERED_DATE);

        //期限
        Field TERM=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //TERM.setValue("2");//todo:传入期限
        TERM.setValue(circle.getTerm());//todo:传入期限
        body_struct.addField("TERM", TERM);

        //期限类型 todo:非ESB提供数据字典
        Field TERM_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //TERM_TYPE.setValue("002");
        TERM_TYPE.setValue(circle.getTermType());
        body_struct.addField("TERM_TYPE", TERM_TYPE);

        //顺延标志
        Field DEFER_FLAG=new Field(new FieldAttr(FieldType.FIELD_STRING, 2));
        //DEFER_FLAG.setValue("1");
        DEFER_FLAG.setValue(circle.getDeferFlag());
        body_struct.addField("DEFER_FLAG", DEFER_FLAG);

        //执行利率
        Field ACT_INT_RATE=new Field(new FieldAttr(FieldType.FIELD_DOUBLE, 20,7));
        //ACT_INT_RATE.setValue("0.5");//todo:传入执行利率
        ACT_INT_RATE.setValue(Arith.div(Double.valueOf(circle.getActIntRate()), 100.0, 4));//todo:传入执行利率
        body_struct.addField("ACT_INT_RATE", ACT_INT_RATE);

        //逾期利率
        Field OVERDUE_INT_RATE=new Field(new FieldAttr(FieldType.FIELD_DOUBLE, 20,7));
        //OVERDUE_INT_RATE.setValue("0.01");//todo:传入逾期利率
        OVERDUE_INT_RATE.setValue(Arith.div(Double.valueOf(circle.getOverdueIntRate()), 100.0, 4));//todo:传入逾期利率
        body_struct.addField("OVERDUE_INT_RATE", OVERDUE_INT_RATE);

        //违约利率
        Field PENALTY_INT_RATE=new Field(new FieldAttr(FieldType.FIELD_DOUBLE, 20,7));
        //PENALTY_INT_RATE.setValue("0.01");//todo:传入违约利率
        PENALTY_INT_RATE.setValue(Arith.div(Double.valueOf(circle.getPenaltyIntRate()), 100.0, 4));//todo:传入违约利率
        body_struct.addField("PENALTY_INT_RATE", PENALTY_INT_RATE);

        //还款方式 todo:非ESB提供数据字典
        Field REPAY_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //REPAY_TYPE.setValue("A004");
        REPAY_TYPE.setValue(circle.getRepayType());
        body_struct.addField("REPAY_TYPE", REPAY_TYPE);

        //还款日期
        Field REPAY_DATE=new Field(new FieldAttr(FieldType.FIELD_STRING, 2));
        //REPAY_DATE.setValue("21");//todo:传入还款日期(不是年月日 日期即可)
        REPAY_DATE.setValue(circle.getRepayDate());//todo:传入还款日期
        body_struct.addField("REPAY_DATE", REPAY_DATE);

        //五级分类
        Field FIVE_LEVEL_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //FIVE_LEVEL_TYPE.setValue("10");
        FIVE_LEVEL_TYPE.setValue(circle.getFiveLevelType());
        body_struct.addField("FIVE_LEVEL_TYPE", FIVE_LEVEL_TYPE);

        //特殊贷款类型 todo:非ESB提供数据字典
        Field SPE_LOAN_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //SPE_LOAN_TYPE.setValue("1");
        SPE_LOAN_TYPE.setValue(circle.getSpeLoanType());
        body_struct.addField("SPE_LOAN_TYPE", SPE_LOAN_TYPE);

        //额度占用类型 todo:非ESB提供数据字典
        Field LIMIT_USEED_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //LIMIT_USEED_TYPE.setValue("01");
        LIMIT_USEED_TYPE.setValue(circle.getLimitUseedType());
        body_struct.addField("LIMIT_USEED_TYPE", LIMIT_USEED_TYPE);

        //借款用途 todo:非ESB提供数据字典
        Field DR_USAGE=new Field(new FieldAttr(FieldType.FIELD_STRING, 8));
        //DR_USAGE.setValue("12");//todo:传入借款用途
        DR_USAGE.setValue(circle.getDrUsage());//todo:传入借款用途
        body_struct.addField("DR_USAGE", DR_USAGE);

        //工业转型升级标识 todo:非ESB提供数据字典
        Field FLAG=new Field(new FieldAttr(FieldType.FIELD_STRING, 1));
        //FLAG.setValue("2");
        FLAG.setValue(circle.getFlag());
        body_struct.addField("FLAG", FLAG);

        //贷款种类 todo:缺少数据字典
        Field LOAN_KIND=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_KIND.setValue("100034");//todo:传入贷款种类
        LOAN_KIND.setValue(circle.getLoanKind());//todo:传入贷款种类
        body_struct.addField("LOAN_KIND", LOAN_KIND);

        //涉农贷款类型 todo:缺少数据字典
        Field AGRI_LOAN_KIND=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //AGRI_LOAN_KIND.setValue("1010");//todo:传入涉农贷款类型
        AGRI_LOAN_KIND.setValue(circle.getAgriLoanKind());//todo:传入涉农贷款类型
        body_struct.addField("AGRI_LOAN_KIND", AGRI_LOAN_KIND);

        //个人经营性贷款类型 todo:缺少数据字典
        Field PERSON_LOAN_KIND=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //PERSON_LOAN_KIND.setValue("10");//todo:传入个人经营性贷款类型
        PERSON_LOAN_KIND.setValue(circle.getPersonLoanKind());//todo:传入个人经营性贷款类型
        body_struct.addField("PERSON_LOAN_KIND", PERSON_LOAN_KIND);

        //调整类型 todo:缺少数据字典
        Field ADJUST_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 1));
        //ADJUST_TYPE.setValue("2");//todo:传入调整类型
        ADJUST_TYPE.setValue(circle.getAdjustType());//todo:传入调整类型
        body_struct.addField("ADJUST_TYPE", ADJUST_TYPE);

        //新兴产业类型 todo:缺少数据字典
        Field NEW_PRD_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //NEW_PRD_TYPE.setValue("0");//todo:传入新兴产业类型
        NEW_PRD_TYPE.setValue(circle.getNewPrdType());//todo:传入新兴产业类型
        body_struct.addField("NEW_PRD_TYPE", NEW_PRD_TYPE);

        //新兴产业贷款
        Field NEW_PRD_LOAN=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //NEW_PRD_LOAN.setValue("0");//todo:传入新兴产业贷款
        NEW_PRD_LOAN.setValue(circle.getNewPrdLoan());//todo:传入新兴产业贷款
        body_struct.addField("NEW_PRD_LOAN", NEW_PRD_LOAN);

        //贷款投向
        Field LOAN_DIRECTION=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_DIRECTION.setValue("01");//todo:传入贷款投向
        LOAN_DIRECTION.setValue(circle.getLoanDirection().substring(1, circle.getLoanDirection().length()));//todo:传入贷款投向
        body_struct.addField("LOAN_DIRECTION", LOAN_DIRECTION);

        //贷款归属1
        Field LOAN_BELONG1=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_BELONG1.setValue("10");//todo:传入贷款归属1
        LOAN_BELONG1.setValue(circle.getLoanBelong1());//todo:传入贷款归属1
        body_struct.addField("LOAN_BELONG1", LOAN_BELONG1);

        //贷款归属2
        Field LOAN_BELONG2=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_BELONG2.setValue("2015");//todo:传入贷款归属2
        LOAN_BELONG2.setValue(circle.getLoanBelong2());//todo:传入贷款归属2
        body_struct.addField("LOAN_BELONG2", LOAN_BELONG2);

        //贷款归属3
        Field LOAN_BELONG3=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_BELONG3.setValue("2070");//todo:传入贷款归属3
        LOAN_BELONG3.setValue(circle.getLoanBelong3());//todo:传入贷款归属3
        body_struct.addField("LOAN_BELONG3", LOAN_BELONG3);

        //贷款归属4
        Field LOAN_BELONG4=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //LOAN_BELONG4.setValue("1030");//todo:传入贷款归属4
        LOAN_BELONG4.setValue(circle.getLoanBelong4());//todo:传入贷款归属4
        body_struct.addField("LOAN_BELONG4", LOAN_BELONG4);

        //业务类型
        Field BUSS_TYPE=new Field(new FieldAttr(FieldType.FIELD_STRING, 50));
        //BUSS_TYPE.setValue("001");//todo:传入业务类型 001 消费类 002 经营类
        BUSS_TYPE.setValue(circle.getBussType());//todo:传入业务类型 001 消费类 002 经营类
        body_struct.addField("BUSS_TYPE", BUSS_TYPE);

        //主管客户经理
        Field CHI_CUST_MANAGER=new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //CHI_CUST_MANAGER.setValue("1");//todo:传入主管客户经理
        CHI_CUST_MANAGER.setValue(circle.getChiCustManager());
        body_struct.addField("CHI_CUST_MANAGER", CHI_CUST_MANAGER);

        /*
        客户信息数组 todo:需要在前端补录应在前端补录
         */
        Array CLIENT_ARRAY = new Array(); //CLIENT_NO数组
        CompositeData CusArrayStruct = new CompositeData();

        //客户号
        Field A_CLIENT_NO = new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
        //A_CLIENT_NO.setValue("N_016");//todo:传入客户号
        A_CLIENT_NO.setValue(circle.getClientNo());//todo:传入客户号
        CusArrayStruct.addField("CLIENT_NO", A_CLIENT_NO);

        //客户名称
        Field CLIENT_NAME = new Field(new FieldAttr(FieldType.FIELD_STRING, 150));
        //CLIENT_NAME.setValue("张三");//todo:传入客户名称
        CLIENT_NAME.setValue(circle.getClientName());//todo:传入客户名称
        CusArrayStruct.addField("CLIENT_NAME", CLIENT_NAME);

        //性别
        Field SEX = new Field(new FieldAttr(FieldType.FIELD_STRING, 2));
        //SEX.setValue("01");//todo:传入性别,男:01 ;女:02; 未知:03
        SEX.setValue(circle.getSex());//todo:传入性别,男:01 ;女:02; 未知:03
        CusArrayStruct.addField("SEX", SEX);

        //客户类型
        Field CLIENT_TYPE = new Field(new FieldAttr(FieldType.FIELD_STRING, 6));
        //CLIENT_TYPE.setValue("Z");//个人客户 todo:文档中多个个人客户码,测试需明确
        CLIENT_TYPE.setValue(circle.getClientType());//个人客户 todo:文档中多个个人客户码,测试需明确
        CusArrayStruct.addField("CLIENT_TYPE", CLIENT_TYPE);

        //证件类型
        Field GLOBAL_TYPE = new Field(new FieldAttr(FieldType.FIELD_STRING, 5));
        GLOBAL_TYPE.setValue("99");//默认值
        //GLOBAL_TYPE.setValue("0");//身份证
        //GLOBAL_TYPE.setValue(circle.getGlobalType());//身份证
        //转换"证件类型" 为 "信贷证件类型"
        String tmp_title = "";
        DictionaryManager dictMgr = Beans.get(DictionaryManager.class);
        Dictionary dictionary = dictMgr.getDictionaryByName("CERT_TYPE");
        List<DictionaryItem> dictItems = dictionary.getItems();
		for(DictionaryItem item : dictItems){
			if(item.getName().equals(circle.getGlobalType())){
				tmp_title = item.getTitle();
				break;
			}
		}

		Dictionary dictionary_for_xd = dictMgr.getDictionaryByName("CERT_TYPE_FOR_XD");
		List<DictionaryItem> dictItems_for_xd = dictionary_for_xd.getItems();
		for(DictionaryItem item : dictItems_for_xd){
			if(item.getTitle().equals(tmp_title)){
				GLOBAL_TYPE.setValue(item.getName());
				break;
			}
		}
        CusArrayStruct.addField("GLOBAL_TYPE", GLOBAL_TYPE);

        //证件号码
        Field GLOBAL_ID = new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //GLOBAL_ID.setValue("320482198601271100");//todo:传入证件号码
        GLOBAL_ID.setValue(circle.getGlobalId());//todo:传入证件号码
        CusArrayStruct.addField("GLOBAL_ID", GLOBAL_ID);

        //长期证件标志 todo:数据字典缺失
        Field LONG_GLOBAL_TYPE = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //LONG_GLOBAL_TYPE.setValue("1");//todo:传入标识
        LONG_GLOBAL_TYPE.setValue(circle.getLongGlobalType());//todo:传入标识
        CusArrayStruct.addField("LONG_GLOBAL_TYPE", LONG_GLOBAL_TYPE);

        //签发日期
        Field ISS_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //ISS_DATE.setValue("2015-04-14");//todo:传入数值,无则置空
        ISS_DATE.setValue(formatter10.format(circle.getIssDate()));
        CusArrayStruct.addField("ISS_DATE", ISS_DATE);

        //证件有效日期
        Field GLOBAL_EFF_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //GLOBAL_EFF_DATE.setValue("");//todo:传入数值,无则置空
        GLOBAL_EFF_DATE.setValue(formatter10.format(circle.getGlobalEffDate()));
        CusArrayStruct.addField("GLOBAL_EFF_DATE", GLOBAL_EFF_DATE);

        //农户标识 todo:数据字典缺失
        Field AGRI_FLAG = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //AGRI_FLAG.setValue("1");//todo:传入数值,无则置空
        AGRI_FLAG.setValue(circle.getAgriFlag());
        CusArrayStruct.addField("AGRI_FLAG", AGRI_FLAG);

        //国家代码
        Field COUNTRY_CODE = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //COUNTRY_CODE.setValue("CHN");//中国
        COUNTRY_CODE.setValue(circle.getCountryCode());//中国
        CusArrayStruct.addField("COUNTRY_CODE", COUNTRY_CODE);

        //民族代码
        Field NATIONALITY_CODE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //NATIONALITY_CODE.setValue("01");//todo:传入民族,例如 "汉"
        NATIONALITY_CODE.setValue(circle.getNationalityCode());//todo:传入民族,例如 "汉"
        CusArrayStruct.addField("NATIONALITY_CODE", NATIONALITY_CODE);

        //户籍所在地
        Field REG_PERM_RESIDENCE = new Field(new FieldAttr(FieldType.FIELD_STRING, 60));
        //REG_PERM_RESIDENCE.setValue("320114");//todo:传入户籍所在地
        REG_PERM_RESIDENCE.setValue(circle.getRegPermResidence());//todo:传入户籍所在地
        CusArrayStruct.addField("REG_PERM_RESIDENCE", REG_PERM_RESIDENCE);

        //地址
        Field ADDRESS = new Field(new FieldAttr(FieldType.FIELD_STRING, 300));
        //ADDRESS.setValue("南京市雨花台");//todo:传入地址
        ADDRESS.setValue(circle.getAddress());//todo:传入地址
        CusArrayStruct.addField("ADDRESS", ADDRESS);

        //出生日期
        Field BIRTH_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //BIRTH_DATE.setValue("1986-01-27");//todo:传入出生日期,格式YYYYMMdd
        BIRTH_DATE.setValue(formatter10.format(circle.getBirthDate()));//todo:传入出生日期,格式YYYYMMdd
        CusArrayStruct.addField("BIRTH_DATE", BIRTH_DATE);

        //最高学历 todo:字典项缺失
        Field EDUCATION = new Field(new FieldAttr(FieldType.FIELD_STRING, 1));
        //EDUCATION.setValue("10");//todo:传入最高学历
        EDUCATION.setValue(circle.getEducation());//todo:传入最高学历
        CusArrayStruct.addField("EDUCATION", EDUCATION);

        //最高学位 todo:字典项缺失
        Field DEGREE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //DEGREE.setValue("2");//todo:传入最高学位
        DEGREE.setValue(circle.getDegree());//todo:传入最高学位
        CusArrayStruct.addField("DEGREE", DEGREE);

        //签约日期
        Field SIGN_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //SIGN_DATE.setValue("2015-04-14");//todo:传入签约日期,格式YYYYMMdd
        SIGN_DATE.setValue(formatter10.format(circle.getSignDate()));//todo:传入签约日期,格式YYYYMMdd
        CusArrayStruct.addField("SIGN_DATE", SIGN_DATE);

        //持卡情况 todo:数据字典项缺失
        Field HOLD_CARD_MSG = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //HOLD_CARD_MSG.setValue("1");//todo:传入持卡情况
        HOLD_CARD_MSG.setValue(circle.getHoldCardMsg());//todo:传入持卡情况
        CusArrayStruct.addField("HOLD_CARD_MSG", HOLD_CARD_MSG);

        //是否拥有外国护照或居住权 todo:数据字典项缺失
        Field PASSPORT_FLAG = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //PASSPORT_FLAG.setValue("1");//todo:传入数值
        PASSPORT_FLAG.setValue(circle.getPassportFlag());//todo:传入数值
        CusArrayStruct.addField("PASSPORT_FLAG", PASSPORT_FLAG);

        //信用等级 todo:数据字典项缺失
        Field CREDIT_LEVEL = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //CREDIT_LEVEL.setValue("11");//todo:传入信用等级
        CREDIT_LEVEL.setValue(circle.getCreditLevel());//todo:传入信用等级
        CusArrayStruct.addField("CREDIT_LEVEL", CREDIT_LEVEL);

        //信用到期日期
        Field EXPIRY_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //EXPIRY_DATE.setValue("2016-04-14");//todo:传入到期日期
        if(circle.getExpiryDate() != null){
        	EXPIRY_DATE.setValue(formatter10.format(circle.getExpiryDate()));//todo:传入到期日期
        }
        else{
        	EXPIRY_DATE.setValue("");//todo:传入到期日期
        }
        CusArrayStruct.addField("EXPIRY_DATE", EXPIRY_DATE);

        //是否关联客户 todo:数据字典项缺失
        Field REL_CLIENT_FLAG = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //REL_CLIENT_FLAG.setValue("1");//todo:传入持卡情况
        REL_CLIENT_FLAG.setValue(circle.getRelClientFlag());//todo:传入持卡情况
        CusArrayStruct.addField("REL_CLIENT_FLAG", REL_CLIENT_FLAG);

        //与我行关系 todo:数据字典项缺失
        Field OWN_BRANCH_RELATION = new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //OWN_BRANCH_RELATION.setValue("B1");//todo:传入我行关系
        OWN_BRANCH_RELATION.setValue(circle.getOwnBranchRelation());//todo:传入我行关系
        CusArrayStruct.addField("OWN_BRANCH_RELATION", OWN_BRANCH_RELATION);

        //我行职务
        Field POST = new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //POST.setValue("6");//todo:传入我行职务情况
        POST.setValue(circle.getPost());//todo:传入我行职务情况
        CusArrayStruct.addField("POST", POST);

        //贷款卡标识 todo:数据字典项缺失
        Field LOAN_CARD_FLAG = new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //LOAN_CARD_FLAG.setValue("1");//todo:传入贷款卡标识
        LOAN_CARD_FLAG.setValue(circle.getLoanCardFlag());//todo:传入贷款卡标识
        CusArrayStruct.addField("LOAN_CARD_FLAG", LOAN_CARD_FLAG);

        //贷款卡号
        Field LOAN_CARD_NO = new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //LOAN_CARD_NO.setValue("111111");//todo:传入贷款卡号
        LOAN_CARD_NO.setValue(circle.getLoanCardNo());//todo:传入贷款卡号
        CusArrayStruct.addField("LOAN_CARD_NO", LOAN_CARD_NO);

        //手机号码
        Field MOBILE = new Field(new FieldAttr(FieldType.FIELD_STRING, 30));
        //MOBILE.setValue("15961100228");//todo:传入手机号码
        MOBILE.setValue(circle.getMobile());//todo:传入手机号码
        CusArrayStruct.addField("MOBILE", MOBILE);

        //上级机构 todo:数据字典项缺失
        Field HIGHER_ORG_NO = new Field(new FieldAttr(FieldType.FIELD_STRING, 32));
        //HIGHER_ORG_NO.setValue("12");//todo:传入上级机构
        if(circle.getHigherOrgNo().equals("000000")){
        	HIGHER_ORG_NO.setValue(Constant.QZ_ORG_ROOT_ID);
		}
        else{
        	HIGHER_ORG_NO.setValue(circle.getHigherOrgNo());
        }
        CusArrayStruct.addField("HIGHER_ORG_NO", HIGHER_ORG_NO);

        //客户经理
        Field ACCT_EXEC = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //ACCT_EXEC.setValue("0389");//todo:传入客户经理柜员号
        ACCT_EXEC.setValue(circle.getAcctExec());
        CusArrayStruct.addField("ACCT_EXEC", ACCT_EXEC);

        //开户日期
        Field OPEN_ACCT_DATE = new Field(new FieldAttr(FieldType.FIELD_STRING, 10));
        //OPEN_ACCT_DATE.setValue("2015-01-22");//todo:传入开户日期,YYYYMMdd
        OPEN_ACCT_DATE.setValue(formatter10.format(circle.getOpenAcctDate()));//todo:传入开户日期,YYYYMMdd
        CusArrayStruct.addField("OPEN_ACCT_DATE", OPEN_ACCT_DATE);

        //信息加入数组
        CLIENT_ARRAY.addStruct(CusArrayStruct);
        body_struct.addArray("CLIENT_ARRAY",CLIENT_ARRAY);
        /*
        客户信息数组结束
         */

        /*
        费用信息数组开始
         */
        Array FEE_ARRAY = new Array(); //FEE_ARRAY数组
        CompositeData FeeArrayStruct = new CompositeData();

        //币种
        Field FEE_CCY=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
        //FEE_CCY.setValue("CNY");//人民币
        FEE_CCY.setValue(circle.getFeeCcy());//人民币
        FeeArrayStruct.addField("CCY", FEE_CCY);

        //费用金额
        Field FEE_AMOUNT=new Field(new FieldAttr(FieldType.FIELD_DOUBLE,20,2));
        //FEE_AMOUNT.setValue(1000.00);//todo:传入费用金额
        FEE_AMOUNT.setValue(Double.valueOf(circle.getFeeAmount()));//todo:传入费用金额
        FeeArrayStruct.addField("FEE_AMOUNT", FEE_AMOUNT);

        //账号
        Field ACCT_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 50));
        //ACCT_NO.setValue("2233");//todo:传入账号
        ACCT_NO.setValue(circle.getAcctNo2());//todo:传入账号 费用账号与放款账号一样 modified by nihc 20150718
        FeeArrayStruct.addField("ACCT_NO", ACCT_NO);

        //信息加入数组
        FEE_ARRAY.addStruct(FeeArrayStruct);
        body_struct.addArray("FEE_ARRAY",FEE_ARRAY);
        /*
        费用信息数组结束
         */

        /*
        账户信息数组开始
        ***!!!该部分内容由核心查询获取后填入!!!***
         */
        Array ACCT_INFO_ARRAY = new Array(); //ACCT_INFO_ARRAY数组
        for(Circle_ACCT_INFO circle_ACCT_INFO1 : acct_info_ls){
        	CompositeData AcctInfoArrayStruct = new CompositeData();
        	//账户性质
            Field ACCT_CHRT=new Field(new FieldAttr(FieldType.FIELD_STRING, 5));
    		//ACCT_CHRT.setValue("02");//todo:传入账户性质
            ACCT_CHRT.setValue(circle_ACCT_INFO1.getAcctChrt());//todo:传入账户性质???
            AcctInfoArrayStruct.addField("ACCT_CHRT", ACCT_CHRT);

            //是否本行
            Field OWN_BRANCH_FLAG=new Field(new FieldAttr(FieldType.FIELD_STRING,1));
    		//OWN_BRANCH_FLAG.setValue("1");//todo:传入是否本行信息
            OWN_BRANCH_FLAG.setValue(circle_ACCT_INFO1.getOwnBranchFlag());//todo:传入是否本行信息???
            AcctInfoArrayStruct.addField("OWN_BRANCH_FLAG", OWN_BRANCH_FLAG);

            //账号
            Field AI_ACCT_NO=new Field(new FieldAttr(FieldType.FIELD_STRING, 50));
    		//AI_ACCT_NO.setValue("1111111");//todo:传入账号(没找到)
            AI_ACCT_NO.setValue(circle_ACCT_INFO1.getAcctNo());//todo:传入账号
            AcctInfoArrayStruct.addField("ACCT_NO", AI_ACCT_NO);

            //户名
            Field ACCT_NAME=new Field(new FieldAttr(FieldType.FIELD_STRING, 150));
            ACCT_NAME.setValue(circle_ACCT_INFO1.getAcctName());//todo:传入户名
            AcctInfoArrayStruct.addField("ACCT_NAME", ACCT_NAME);

            //开户机构
            Field OPEN_ACCT_BRANCH_ID=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
            OPEN_ACCT_BRANCH_ID.setValue(circle_ACCT_INFO1.getOpenAcctBranchId());//todo:传入户名
            AcctInfoArrayStruct.addField("OPEN_ACCT_BRANCH_ID", OPEN_ACCT_BRANCH_ID);

            //开户行名
            Field OPEN_ACCT_BRANCH_NAME=new Field(new FieldAttr(FieldType.FIELD_STRING, 150));
            OPEN_ACCT_BRANCH_NAME.setValue(circle_ACCT_INFO1.getOpenAcctBranchName());//todo:传入开户行名
            AcctInfoArrayStruct.addField("OPEN_ACCT_BRANCH_NAME", OPEN_ACCT_BRANCH_NAME);

            //支付金额
            Field PAY_AMT=new Field(new FieldAttr(FieldType.FIELD_DOUBLE, 20,2));
            PAY_AMT.setValue(Double.valueOf(circle_ACCT_INFO1.getPayAmt()));//todo:传入支付金额???
            AcctInfoArrayStruct.addField("PAY_AMT", PAY_AMT);

            //科目号
            Field GL_CODE=new Field(new FieldAttr(FieldType.FIELD_STRING, 20));
            GL_CODE.setValue(circle_ACCT_INFO1.getGlCode());//todo:传入科目号
            AcctInfoArrayStruct.addField("GL_CODE", GL_CODE);

            //币别
            Field AI_CCY=new Field(new FieldAttr(FieldType.FIELD_STRING, 3));
            AI_CCY.setValue(circle_ACCT_INFO1.getCcy());//todo:传入币别
            AcctInfoArrayStruct.addField("CCY", AI_CCY);

            //全国联行号
            Field C_INTERBANK_ID=new Field(new FieldAttr(FieldType.FIELD_STRING, 15));
            C_INTERBANK_ID.setValue(circle_ACCT_INFO1.getcInterbankId());//todo:传入全国联行号
            AcctInfoArrayStruct.addField("C_INTERBANK_ID", C_INTERBANK_ID);

            //信息加入数组
            ACCT_INFO_ARRAY.addStruct(AcctInfoArrayStruct);
        }

        body_struct.addArray("ACCT_INFO_ARRAY",ACCT_INFO_ARRAY);

        /*
        账户信息数组结束
         */
        cd.addStruct("BODY",body_struct);

        return cd;
    }

    /**
     * 返回成功与否
     * @param resp
     * @param circle
     * @return
     *
     *  <service version="2.0">
			<BODY>
			</BODY>
			<SYS_HEAD>
			<RET_STATUS attr="s,8">S</RET_STATUS>
			<RET attr="array">
				<struct>
					<RET_MSG attr="s,200"></RET_MSG>
					<RET_CODE attr="s,6">000000</RET_CODE>
				</struct>
			</RET>
			<TRAN_TIMESTAMP attr="s,9">81730440</TRAN_TIMESTAMP>
			<TRAN_DATE attr="s,8">20160101</TRAN_DATE>
			<SERVICE_SCENE attr="s,2">10</SERVICE_SCENE>
			<SERVICE_CODE attr="s,30">11002000080</SERVICE_CODE>
			</SYS_HEAD>
		</service>
     */
	public String parseEcifResponse(CompositeData resp,Circle circle) {
		String retMsg = "";
		if(resp == null){
			retMsg = "解析放贷返回信息失败";
			return retMsg;
		}
		CompositeData SYS_HEAD = resp.getStruct("SYS_HEAD");

        //根据数组名称去获取数组
        Array RET = SYS_HEAD.getArray("RET");

        String RET_CODE = "";
        String RET_MSG = "";
        if(null != RET && RET.size() > 0){
            int m = RET.size();
            CompositeData array_element = null;
            for (int i = 0; i < m; i++) {
                //数组中的元素也是CompositeData,这是固定的写法。根据游标就可以获取到数组中的所有元素
                array_element = RET.getStruct(i);

                RET_CODE = array_element.getField("RET_CODE").strValue();
                RET_MSG = array_element.getField("RET_MSG").strValue();
            }
        }
        //更新贷款信息表
        circle.setRetCode(RET_CODE);
        circle.setRetMsg("000000".equals(RET_CODE) ? "放款成功" : RET_MSG);
        circle.setRetContno("000000".equals(RET_CODE) ? RET_MSG : "");
        commonDao.updateObject(circle);
        if(RET_CODE.equals( com.cardpay.pccredit.QZBankInterface.constant.Constant.RET_CODE_CIRCLE)){
        	retMsg ="放款成功";
        	return retMsg;
        }
        else{
        	retMsg = RET_MSG;
        	return retMsg;
        }
	}
}


text:
UIView-Hierarchy
================


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BBCDEBUG_LEVEL 1
#include "XMLValue.h"

BBC_AUDIOTOOLBOX_START

XMLValue::XMLValue() : subvalues(NULL)
{
}

XMLValue::XMLValue(const XMLValue& obj) : subvalues(NULL)
{
  operator = (obj);
}

XMLValue::~XMLValue()
{
  if (subvalues) delete subvalues;
}

/*--------------------------------------------------------------------------------*/
/** Assignment operator
 */
/*--------------------------------------------------------------------------------*/
XMLValue& XMLValue::operator = (const XMLValue& obj)
{
  name  = obj.name;
  value = obj.value;
  attrs = obj.attrs;

  // create/copy set of subvalues
  SetSubValues(obj.subvalues);

  return *this;
}

/*--------------------------------------------------------------------------------*/
/** Set subvalues list
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::SetSubValues(const XMLValues *_subvalues)
{
  // try not to delete and re-allocate, use std::vector<> assignment instead
  if (_subvalues)
  {
    // if subvalues list already exists, use assignment to avoid object delete and new
    if (subvalues) *subvalues = *_subvalues;
    // else no alternative but to create new object
    else           subvalues  = new XMLValues(*_subvalues);
  }
  // delete existing list of sub values
  else if (subvalues)
  {
    delete subvalues;
    subvalues = NULL;
  }
}

/*--------------------------------------------------------------------------------*/
/** Add a set of sub values to the lsit
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::AddSubValues(const XMLValues& _subvalues)
{
  if (_subvalues.size())
  {
    if (!subvalues) subvalues = new XMLValues;
    if (subvalues)
    {
      uint_t i;
      for (i = 0; i < _subvalues.size(); i++)
      {
        subvalues->AddValue(_subvalues[i]);
      }
    }
  }
}

/*--------------------------------------------------------------------------------*/
/** Add a single sub value to the lsit
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::AddSubValue(const XMLValue& _subvalue)
{
  if (!subvalues) subvalues = new XMLValues;
  if (subvalues)  subvalues->AddValue(_subvalue);
}

/*--------------------------------------------------------------------------------*/
/** Add a single sub value to the list (if set or forced)
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::AddSubValue(const INamedParameter& _parameter, bool force)
{
  if (force || _parameter.IsSet())
  {
    XMLValue subvalue;
    subvalue.SetValue(_parameter, force);
    AddSubValue(subvalue);
  }
}

/*--------------------------------------------------------------------------------*/
/** Set attribute from NamedParameter, if set (or forced)
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::SetAttribute(const INamedParameter& _parameter, bool force)
{
  if (force || _parameter.IsSet()) SetValueOrAttribute(_parameter.GetName(), _parameter.ToString(), true);
}

/*--------------------------------------------------------------------------------*/
/** Set XMLValue object as a XML value (name/value pair) with optional attributes
 */
/*--------------------------------------------------------------------------------*/
void XMLValue::SetValueOrAttribute(const std::string& _name, const std::string& _value, bool _attr)
{
  if (_attr) attrs[_name] = _value;
  else
  {
    name  = _name;
    value = _value;
  }
}

void XMLValue::SetValueOrAttribute(const std::string& _name, const char *_value, bool _attr)
{
  if (_attr) attrs[_name] = _value;
  else
  {
    name  = _name;
    value = _value;
  }
}

void XMLValue::SetTimeValueOrAttribute(const std::string& _name, uint64_t _value, bool _attr)
{
  SetValueOrAttribute(_name, GenerateTime(_value), _attr);
}

/*--------------------------------------------------------------------------------*/
/** Return ptr to attributes within specified value with specified name or NULL
 */
/*--------------------------------------------------------------------------------*/
const std::string *XMLValue::GetAttribute(const std::string& _name) const
{
  ATTRS::const_iterator it;
  const std::string *attr = NULL;

  if ((it = attrs.find(_name)) != attrs.end())
  {
    attr = &it->second;
  }

  return attr;
}

/*--------------------------------------------------------------------------------*/
/** Erase attribute
 */
/*--------------------------------------------------------------------------------*/
bool XMLValue::EraseAttribute(const std::string& _name)
{
  ATTRS::iterator it;
  bool success = false;

  if ((it = attrs.find(_name)) != attrs.end())
  {
    attrs.erase(it);
    success = true;
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set a NamedParameter from an attribute
 *
 * @note if the attribute is found, it is ERASED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValue::GetAttributeAndErase(INamedParameter& val)
{
  ATTRS::iterator it;
  bool success = false;

  if ((it = attrs.find(val.GetName())) != attrs.end())
  {
    success = val.FromString(it->second);
    BBCDEBUG5(("%s<%s>: Converted '%s' to '%s'", val.GetName(), StringFrom(&val).c_str(), it->second.c_str(), val.ToString().c_str()));

    // erase attribute from list
    attrs.erase(it);
  }
  else BBCDEBUG4(("%s<%s>: Attribute not found!", val.GetName(), StringFrom(&val).c_str()));

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Return whether this object is 'empty'
 *
 * 'empty' means:
 * 1. no value
 * 2. no attributes
 * 3. no subvalues (or 0-length list)
 */
/*--------------------------------------------------------------------------------*/
bool XMLValue::Empty() const
{
  return value.empty() && !HasAttributes() && (!subvalues || !subvalues->size());
}

/*----------------------------------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------------*/
/** Add a value to the internal list
 */
/*--------------------------------------------------------------------------------*/
void XMLValues::AddValue(const XMLValue& value)
{
  push_back(value);
}

/*--------------------------------------------------------------------------------*/
/** Set value from NamedParameter
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::AddValue(const INamedParameter& parameter, bool force)
{
  bool added = false;

  if (force || parameter.IsSet())
  {
    XMLValue value;
    value.SetValue(parameter, force);
    AddValue(value);
  }

  return added;
}

/*--------------------------------------------------------------------------------*/
/** Return ptr to value with specified name or NULL
 *
 * @note index represents the index'th entry OF THE SPECIFIED NAME and therefore should start at 0 and increment by 1
 */
/*--------------------------------------------------------------------------------*/
const XMLValue* XMLValues::GetValue(const std::string& name, uint_t index) const
{
  const XMLValue *value = NULL;
  uint_t i;

  // simple search and compare
  // (MUST use a list because there can be MULTIPLE values of the same name)
  for (i = 0; i < size(); i++)
  {
    if (operator[](i).name == name)
    {
      // find indexed copy
      if (index) index--;
      else
      {
        value = &operator[](i);
        break;
      }
    }
  }

  if (!value) BBCDEBUG4(("No value named '%s' index %u!", name.c_str(), index));

  return value;
}

/*--------------------------------------------------------------------------------*/
/** Return ptr to value with specified name or NULL
 *
 * @note index represents the index'th entry OF THE SPECIFIED NAME and therefore should start at 0 and increment by 1
 */
/*--------------------------------------------------------------------------------*/
XMLValue* XMLValues::GetValueWritable(const std::string& name, uint_t index)
{
  XMLValue *value = NULL;
  uint_t i;

  // simple search and compare
  // (MUST use a list because there can be MULTIPLE values of the same name)
  for (i = 0; i < size(); i++)
  {
    if (operator[](i).name == name)
    {
      // find indexed copy
      if (index) index--;
      else
      {
        value = &operator[](i);
        break;
      }
    }
  }

  if (!value) BBCDEBUG4(("No value named '%s' index %u!", name.c_str(), index));

  return value;
}

/*--------------------------------------------------------------------------------*/
/** Remove and delete value from internal list of values
 *
 * @param value address of value to be erased
 *
 * @note value passed MUST be the address of the desired item
 */
/*--------------------------------------------------------------------------------*/
void XMLValues::EraseValue(const XMLValue *value)
{
  iterator it;

  for (it = begin(); it != end(); ++it)
  {
    const XMLValue& value1 = *it;

    // note address comparison not value comparison!
    if (value == &value1)
    {
      erase(it);
      break;
    }
  }
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(std::string& res, const std::string& name)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    res = value->value;
    EraseValue(value);
    success = true;
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(double& res, const std::string& name)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    success = (sscanf(value->value.c_str(), "%lf", &res) > 0);
    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 * @param hex true if value is expected to be hexidecimal
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(uint_t& res, const std::string& name, bool hex)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    if (hex) success = (sscanf(value->value.c_str(), "%x", &res) > 0);
    else     success = (sscanf(value->value.c_str(), "%u", &res) > 0);

    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(ulong_t& res, const std::string& name, bool hex)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    if (hex) success = (sscanf(value->value.c_str(), "%lx", &res) > 0);
    else     success = (sscanf(value->value.c_str(), "%lu", &res) > 0);
    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 * @param hex true if value is expected to be hexidecimal
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(sint_t& res, const std::string& name, bool hex)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    if (hex) success = (sscanf(value->value.c_str(), "%x", (uint_t *)&res) > 0);
    else     success = (sscanf(value->value.c_str(), "%d", &res) > 0);
    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 * @param hex true if value is expected to be hexidecimal
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(slong_t& res, const std::string& name, bool hex)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    if (hex) success = (sscanf(value->value.c_str(), "%lx", (ulong_t *)&res) > 0);
    else     success = (sscanf(value->value.c_str(), "%ld", &res) > 0);
    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(bool& res, const std::string& name)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    res = (value->value == "true");
    EraseValue(value);
    success = true;
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set internal variables from value with specified name
 *
 * @param res internal variable to be modified
 * @param name value name
 *
 * @return true if value found and variable set
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetTimeValueAndErase(uint64_t& res, const std::string& name)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(name)) != NULL)
  {
    success = CalcTime(res, value->value);
    EraseValue(value);
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Set NamedParameter from value
 *
 * @note the value, if found, is REMOVED from the list
 */
/*--------------------------------------------------------------------------------*/
bool XMLValues::GetValueAndErase(INamedParameter& parameter)
{
  const XMLValue *value;
  bool success = false;

  if ((value = GetValue(parameter.GetName())) != NULL)
  {
    success = parameter.FromString(value->value);
    EraseValue(value);
  }

  return success;
}

BBC_AUDIOTOOLBOX_END


text:
@interface AB_ReactiveSet()
{
    RACSubject* subject;
    NSMutableOrderedSet* set;
}

@end

@implementation AB_ReactiveSet

- (instancetype) init
{
    if (self == [super init])
    {
        subject = [RACSubject subject];
        set = [NSMutableOrderedSet orderedSet];
    }

    return self;
}

- (void) add:(id)obj
{
    if ([set containsObject:obj])
    {
        [set removeObject:obj];
    }
    [set addObject:obj];
    [subject sendNext:set];
}

- (void) remove:(id)obj
{
    if ([set containsObject:obj])
    {
        [set removeObject:obj];
    }
    [subject sendNext:set];
}

- (void) dealloc
{
    [subject sendCompleted];
}

- (RACSignal*) valuesChanged
{
    return subject;
}

@end


text:
package dbus

import (
	"github.com/guelfey/go.dbus"
)

func (c *Conn) initJobs() {
	c.jobListener.jobs = make(map[dbus.ObjectPath]chan string)
}

func (c *Conn) jobComplete(signal *dbus.Signal) {
	var id uint32
	var job dbus.ObjectPath
	var unit string
	var result string
	dbus.Store(signal.Body, &id, &job, &unit, &result)
	c.jobListener.Lock()
	out, ok := c.jobListener.jobs[job]
	if ok {
		out <- result
	}
	c.jobListener.Unlock()
}

func (c *Conn) startJob(job string, args ...interface{}) (<-chan string, error) {
	c.jobListener.Lock()
	defer c.jobListener.Unlock()

	ch := make(chan string, 1)
	var path dbus.ObjectPath
	err := c.sysobj.Call(job, 0, args...).Store(&path)
	if err != nil {
		return nil, err
	}
	c.jobListener.jobs[path] = ch
	return ch, nil
}

func (c *Conn) runJob(job string, args ...interface{}) (string, error) {
	respCh, err := c.startJob(job, args...)
	if err != nil {
		return "", err
	}
	return <-respCh, nil
}

// StartUnit enqeues a start job and depending jobs, if any (unless otherwise
// specified by the mode string).
//
// Takes the unit to activate, plus a mode string. The mode needs to be one of
// replace, fail, isolate, ignore-dependencies, ignore-requirements. If
// "replace" the call will start the unit and its dependencies, possibly
// replacing already queued jobs that conflict with this. If "fail" the call
// will start the unit and its dependencies, but will fail if this would change
// an already queued job. If "isolate" the call will start the unit in question
// and terminate all units that aren't dependencies of it. If
// "ignore-dependencies" it will start a unit but ignore all its dependencies.
// If "ignore-requirements" it will start a unit but only ignore the
// requirement dependencies. It is not recommended to make use of the latter
// two options.
//
// Result string: one of done, canceled, timeout, failed, dependency, skipped.
// done indicates successful execution of a job. canceled indicates that a job
// has been canceled  before it finished execution. timeout indicates that the
// job timeout was reached. failed indicates that the job failed. dependency
// indicates that a job this job has been depending on failed and the job hence
// has been removed too. skipped indicates that a job was skipped because it
// didn't apply to the units current state.
func (c *Conn) StartUnit(name string, mode string) (string, error) {
	return c.runJob("StartUnit", name, mode)
}

// StopUnit is similar to StartUnit but stops the specified unit rather
// than starting it.
func (c *Conn) StopUnit(name string, mode string) (string, error) {
	return c.runJob("StopUnit", name, mode)
}

// ReloadUnit reloads a unit.  Reloading is done only if the unit is already running and fails otherwise.
func (c *Conn) ReloadUnit(name string, mode string) (string, error) {
	return c.runJob("ReloadUnit", name, mode)
}

// RestartUnit restarts a service.  If a service is restarted that isn't
// running it will be started.
func (c *Conn) RestartUnit(name string, mode string) (string, error) {
	return c.runJob("RestartUnit", name, mode)
}

// TryRestartUnit is like RestartUnit, except that a service that isn't running
// is not affected by the restart.
func (c *Conn) TryRestartUnit(name string, mode string) (string, error) {
	return c.runJob("TryRestartUnit", name, mode)
}

// ReloadOrRestart attempts a reload if the unit supports it and use a restart
// otherwise.
func (c *Conn) ReloadOrRestartUnit(name string, mode string) (string, error) {
	return c.runJob("ReloadOrRestartUnit", name, mode)
}

// ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try"
// flavored restart otherwise.
func (c *Conn) ReloadOrTryRestartUnit(name string, mode string) (string, error) {
	return c.runJob("ReloadOrTryRestartUnit", name, mode)
}

// StartTransientUnit() may be used to create and start a transient unit, which
// will be released as soon as it is not running or referenced anymore or the
// system is rebooted. name is the unit name including suffix, and must be
// unique. mode is the same as in StartUnit(), properties contains properties
// of the unit.
func (c *Conn) StartTransientUnit(name string, mode string, properties ...Property) (string, error) {
	// the dbus interface for this method does not use the last argument and
	// should simply be given an empty list.  We use a concrete type here
	// (instead of the more appropriate interface{}) to satisfy the dbus library.
	return c.runJob("StartTransientUnit", name, mode, properties, make([]string, 0))
}

// KillUnit takes the unit name and a UNIX signal number to send.  All of the unit's
// processes are killed.
func (c *Conn) KillUnit(name string, signal int32) {
	c.sysobj.Call("KillUnit", 0, name, "all", signal).Store()
}

// ListUnits returns an array with all currently loaded units. Note that
// units may be known by multiple names at the same time, and hence there might
// be more unit names loaded than actual units behind them.
func (c *Conn) ListUnits() ([]UnitStatus, error) {
	result := make([][]interface{}, 0)
	err := c.sysobj.Call("ListUnits", 0).Store(&result)
	if err != nil {
		return nil, err
	}

	resultInterface := make([]interface{}, len(result))
	for i := range result {
		resultInterface[i] = result[i]
	}

	status := make([]UnitStatus, len(result))
	statusInterface := make([]interface{}, len(status))
	for i := range status {
		statusInterface[i] = &status[i]
	}

	err = dbus.Store(resultInterface, statusInterface...)
	if err != nil {
		return nil, err
	}

	return status, nil
}

type UnitStatus struct {
	Name        string          // The primary unit name as string
	Description string          // The human readable description string
	LoadState   string          // The load state (i.e. whether the unit file has been loaded successfully)
	ActiveState string          // The active state (i.e. whether the unit is currently started or not)
	SubState    string          // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
	Followed    string          // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
	Path        dbus.ObjectPath // The unit object path
	JobId       uint32          // If there is a job queued for the job unit the numeric job id, 0 otherwise
	JobType     string          // The job type as string
	JobPath     dbus.ObjectPath // The job object path
}

// EnableUnitFiles() may be used to enable one or more units in the system (by
// creating symlinks to them in /etc or /run).
//
// It takes a list of unit files to enable (either just file names or full
// absolute paths if the unit files are residing outside the usual unit
// search paths), and two booleans: the first controls whether the unit shall
// be enabled for runtime only (true, /run), or persistently (false, /etc).
// The second one controls whether symlinks pointing to other units shall
// be replaced if necessary.
//
// This call returns one boolean and an array with the changes made. The
// boolean signals whether the unit files contained any enablement
// information (i.e. an [Install]) section. The changes list consists of
// structures with three strings: the type of the change (one of symlink
// or unlink), the file name of the symlink and the destination of the
// symlink.
func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
	var carries_install_info bool

	result := make([][]interface{}, 0)
	err := c.sysobj.Call("EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
	if err != nil {
		return false, nil, err
	}

	resultInterface := make([]interface{}, len(result))
	for i := range result {
		resultInterface[i] = result[i]
	}

	changes := make([]EnableUnitFileChange, len(result))
	changesInterface := make([]interface{}, len(changes))
	for i := range changes {
		changesInterface[i] = &changes[i]
	}

	err = dbus.Store(resultInterface, changesInterface...)
	if err != nil {
		return false, nil, err
	}

	return carries_install_info, changes, nil
}

type EnableUnitFileChange struct {
	Type        string // Type of the change (one of symlink or unlink)
	Filename    string // File name of the symlink
	Destination string // Destination of the symlink
}


text:
'use strict';

const Command = require('../../Command.js');
const trackFunctions = require('../../TrackFunctions.js');
const eventTypes = require('../../resources/trackables.json').eventTypes;
const rewardTypes = require('../../resources/trackables.json').rewardTypes;

class SetPing extends Command {
  constructor(bot) {
    super(bot, 'settings.setping', 'set ping');
    this.usages = [
      { description: 'Set ping for an event or item', parameters: ['event or reward', '@role or user mention'] },
    ];
    this.regex = new RegExp(`^${this.call}\\s+?((${eventTypes.join('|')}|${rewardTypes.join('|')}|all|events|items|fissures|syndicates|conclave)(.+)?)?$`, 'i');
    this.requiresAuth = true;
    this.allowDM = false;
  }

  async run(message) {
    const regex = new RegExp(`(${eventTypes.join('|')}|${rewardTypes.join('|')}|all|events|items|fissures|syndicates|conclave)(.+)?`, 'i');
    const match = message.content.match(regex);
    if (message.channel.type === 'dm') {
      this.messagemanager.reply(message, 'Operator, you can\'t do that privately, it\'s the same as directly messaging you anyway!');
      return this.messageManager.statuses.FAILURE;
    } else if (match) {
      const trackables = trackFunctions.trackablesFromParameters(match[1].trim());
      const eventsAndItems = [].concat(trackables.events).concat(trackables.items);
      const pingString = match[2] ? match[2].trim() : undefined;

      if (!eventsAndItems.length) {
        const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix');
        this.messageManager.embed(message,
          trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true);
        return this.messageManager.statuses.FAILURE;
      }
      if (!pingString) {
        const results = [];
        for (const eventOrItem of eventsAndItems) {
          if (eventOrItem) {
            if (!pingString) {
              results.push(this.bot.settings.removePing(message.guild, eventOrItem));
            } else {
              results.push(this.bot.settings.setPing(message.guild, eventOrItem, pingString));
            }
          }
        }
        Promise.all(results);
      }
      this.messageManager.notifySettingsChange(message, true, true);
      return this.messageManager.statuses.SUCCESS;
    }
    const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix');
    this.messageManager.embed(message, trackFunctions
        .getTrackInstructionEmbed(message, prefix, this.call), true, true);
    return this.messageManager.statuses.FAILURE;
  }
}

module.exports = SetPing;


text: DROP FUNCTION IF EXISTS update_entity_relationship_activation_history();


text:
package org.apache.webapp.admin.host;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Arrays;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.JMException;

import org.apache.webapp.admin.ApplicationServlet;
import org.apache.webapp.admin.LabelValueBean;
import org.apache.webapp.admin.Lists;
import org.apache.webapp.admin.TomcatTreeBuilder;

/**
 * The Action that sets up Edit Host transactions.
 *
 * @author Manveen Kaur
 * @version $Revision: 1.6 $ $Date: 2003/08/24 22:52:45 $
 */

public class EditHostAction extends Action {

    /**
     * The MBeanServer we will be interacting with.
     */
    private MBeanServer mBServer = null;

    /**
     * The MessageResources we will be retrieving messages from.
     */
    private MessageResources resources = null;

    // --------------------------------------------------------- Public Methods

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an ActionForward instance describing where and how
     * control should be forwarded, or null if the response has
     * already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param actionForm The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */
    public ActionForward perform(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
        throws IOException, ServletException {

        // Acquire the resources that we need
        HttpSession session = request.getSession();
        Locale locale = (Locale) session.getAttribute(Action.LOCALE_KEY);
        if (resources == null) {
            resources = getServlet().getResources();
        }

        // Acquire a reference to the MBeanServer containing our MBeans
        try {
            mBServer = ((ApplicationServlet) getServlet()).getServer();
        } catch (Throwable t) {
            throw new ServletException
            ("Cannot acquire MBeanServer reference", t);
        }

        // Set up the object names of the MBeans we are manipulating
        ObjectName hname = null;
        StringBuffer sb = null;
        try {
            hname = new ObjectName(request.getParameter("select"));
        } catch (Exception e) {
            String message =
                resources.getMessage("error.hostName.bad",
                                     request.getParameter("select"));
            getServlet().log(message);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            return (null);
        }

        String adminHost = null;
        String domain = hname.getDomain();
        // Get the host name the admin app runs on
        // this host cannot be deleted from the admin tool
        try {
            adminHost = Lists.getAdminAppHost(
                                  mBServer, domain ,request);
        } catch (Exception e) {
            String message =
                resources.getMessage("error.hostName.bad",
                                        adminHost);
            getServlet().log(message);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            return (null);
        }
        request.setAttribute("adminAppHost", adminHost);

        // Fill in the form values for display and editing
        HostForm hostFm = new HostForm();
        session.setAttribute("hostForm", hostFm);
        hostFm.setAdminAction("Edit");
        hostFm.setObjectName(hname.toString());
        sb = new StringBuffer("Host (");
        sb.append(hname.getKeyProperty("host"));
        sb.append(")");
        hostFm.setNodeLabel(sb.toString());
        hostFm.setDebugLvlVals(Lists.getDebugLevels());
        hostFm.setBooleanVals(Lists.getBooleanValues());

        String attribute = null;
        try {

            // Copy scalar properties
            attribute = "name";
            hostFm.setHostName
                ((String) mBServer.getAttribute(hname, attribute));
            attribute = "debug";
            hostFm.setDebugLvl
                (((Integer) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "appBase";
            hostFm.setAppBase
                ((String) mBServer.getAttribute(hname, attribute));
            attribute = "autoDeploy";
            hostFm.setAutoDeploy
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "deployXML";
            hostFm.setDeployXML
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "deployOnStartup";
            hostFm.setDeployOnStartup
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "unpackWARs";
            hostFm.setUnpackWARs
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "xmlNamespaceAware";
            hostFm.setXmlNamespaceAware
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());
            attribute = "xmlValidation";
            hostFm.setXmlValidation
                (((Boolean) mBServer.getAttribute(hname, attribute)).toString());

        } catch (Throwable t) {
            getServlet().log
                (resources.getMessage(locale, "users.error.attribute.get",
                                      attribute), t);
            response.sendError
                (HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                 resources.getMessage(locale, "users.error.attribute.get",
                                      attribute));
            return (null);
        }

        // retrieve all aliases
        String operation = null;
        try {
            operation = "findAliases";
            String aliases[] =
                (String[]) mBServer.invoke(hname, operation, null, null);

            hostFm.setAliasVals(new ArrayList(Arrays.asList(aliases)));

        } catch (Throwable t) {
            getServlet().log
            (resources.getMessage(locale, "users.error.invoke",
                                  operation), t);
            response.sendError
                (HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                resources.getMessage(locale, "users.error.invoke",
                                     operation));
            return (null);
        }

        // Forward to the host display page
        return (mapping.findForward("Host"));

    }
}


text:
class PollAnswersController < AdminController
  before_action :set_entity, only: %i[edit update destroy]

  # post /poll_answers/check
  def check
    @entity = PollAnswer.instance_for_check(params[:entity_id], entity_parameters)

    render 'shared/forms/check'
  end

  # post /poll_answers
  def create
    @entity = PollAnswer.new(creation_parameters)
    if @entity.save
      NetworkEntitySyncJob.perform_later(@entity.class.to_s, @entity.id)
      form_processed_ok(admin_poll_answer_path(id: @entity.id))
    else
      form_processed_with_error(:new)
    end
  end

  # get /poll_answers/:id/edit
  def edit
  end

  # patch /poll_answers/:id
  def update
    if @entity.update(entity_parameters)
      form_processed_ok(admin_poll_question_path(id: @entity.poll_question_id))
    else
      form_processed_with_error(:edit)
    end
  end

  # delete /poll_answers/:id
  def destroy
    flash[:notice] = t('.success') if @entity.destroy
    redirect_to(admin_poll_question_path(id: @entity.poll_question_id))
  end

  protected

  def component_class
    Biovision::Components::PollsComponent
  end

  def set_entity
    @entity = PollAnswer.find_by(id: params[:id])
    handle_http_404('Cannot find poll answer') if @entity.nil?
  end

  def entity_parameters
    params.require(:poll_answer).permit(PollAnswer.entity_parameters)
  end

  def creation_parameters
    params.require(:poll_answer).permit(PollAnswer.creation_parameters)
  end
end


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

declare var gapi: any;

@Injectable()
export class GapiLoadIndicatorService {

	public readonly gapiLoaded: Promise<any>;
	public readonly gapiClienLoaded: Promise<any>;

	constructor() {
		this.gapiLoaded = this.checkIfPresent(() => !!gapi, () => gapi);
		this.gapiClienLoaded = this.checkIfPresent(() => !!gapi.client, () => gapi.client);
	}

	private checkIfPresent<T>(predicate: () => boolean, getResult: () => T): Promise<T> {
		if (predicate()) {
			return Promise.resolve(getResult());
		} else {
			return new Promise((resolve, reject) =>
				setImmediate(() =>
					resolve(this.checkIfPresent(predicate, getResult))));
		}
	}

}