text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Server xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />

View Javadoc

1
19  package org.apache.hadoop.hbase;
20
21  import org.apache.hadoop.classification.InterfaceAudience;
22  import org.apache.hadoop.conf.Configuration;
23  import org.apache.hadoop.hbase.catalog.CatalogTracker;
24  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
25
26  /**
27   * Defines the set of shared functions implemented by HBase servers (Masters
28   * and RegionServers).
29   */
30  @InterfaceAudience.Private
31  public interface Server extends Abortable, Stoppable {
32    /**
33     * Gets the configuration object for this server.
34     */
35    Configuration getConfiguration();
36
37    /**
38     * Gets the ZooKeeper instance for this server.
39     */
40    ZooKeeperWatcher getZooKeeper();
41
42    /**
43     * @return Master's instance of {@link CatalogTracker}
44     */
45    CatalogTracker getCatalogTracker();
46
47    /**
48     * @return The unique server name for this server.
49     */
50    ServerName getServerName();
51  }

This page was automatically generated by Maven


text:
//
//  ciny.h
//  CinyTest
//
//  Created by Brandon Stansbury on 4/8/14.
//  Copyright (c) 2014 Brandon Stansbury. All rights reserved.
//

#ifndef CinyTest_ciny_h
#define CinyTest_ciny_h

#include <stddef.h>
#include <limits.h>
#include <stdint.h>

/**
 @file
 CinyTest type and function definitions.
 */

/**
 @defgroup public Public types and functions
 The public API for CinyTest.
 Guaranteed to be stable within a major version.
 @{
 */

/**
 Current version of CinyTest as MAJOR.MINOR.PATCH string (using semantic versioning).
 */
#define CT_VERSION "1.2.1"

/**
 Type definition for a unit test function.
 @param context Test context created in a suite's setup function.
 */
typedef void (*ct_test_function)(void *);

/**
 Type definition for a unit test setup or teardown function.
 @param contextref Pointer to a test context for initialization or destruction.
 The test context will be passed to all unit tests for a given suite.
 */
typedef void (*ct_setupteardown_function)(void **);

/**
 A test case.
 A named function that executes a single unit test.
 */
struct ct_testcase {
    const char *name;       /**< The function name of the test. */
    ct_test_function test;  /**< The test function. */
};

/**
 Make a test case.
 Uses the name of the unit test function as the name of the test case.
 @param test_function The unit test function for the test case.
 @return A test case.
 */
#define ct_maketest(test_function) ct_maketest_named(#test_function, test_function)
/**
 Make a test case with a name.
 @param name The name of the test case.
 @param test The unit test function for the test case.
 @return A test case.
 */
inline struct ct_testcase ct_maketest_named(const char *name, ct_test_function test)
{
    return (struct ct_testcase){ name, test };
}

/**
 A test suite.
 A named collection of test cases with optional setup and teardown functions.
 */
struct ct_testsuite {
    const char *name;                       /**< The name of the test suite. */
    const struct ct_testcase *tests;        /**< The collection of tests to run. */
    size_t count;                           /**< The number of tests to be run. */
    ct_setupteardown_function setup;        /**< The test setup function. Run before each test case. May be NULL. */
    ct_setupteardown_function teardown;     /**< The test teardown function. Runs after each test case. May be NULL. */
};

/**
 Make a test suite for the list of tests.
 Uses the enclosing function as the test suite name.
 @param test_list The list of tests to run.
 The size of the test array is calculated inline so test_list must be an array lvalue.
 @return A test suite.
 */
#define ct_makesuite(test_list) ct_makesuite_setup(test_list, NULL)
/**
 Make a test suite with a setup function.
 Uses the enclosing function as the test suite name.
 @param test_list The list of tests to run.
 The size of the test array is calculated inline so test_list must be an array lvalue.
 @param setup_function The setup function. Runs before each test case.
 @return A test suite.
 */
#define ct_makesuite_setup(test_list, setup_function) ct_makesuite_setup_teardown(test_list, setup_function, NULL)
/**
 Make a test suite with a setup and teardown function.
 Uses the enclosing function as the test suite name.
 @param test_list The list of tests to run.
 The size of the test array is calculated inline so test_list must be an array lvalue.
 @param setup_function The setup function. Runs before each test case.
 @param teardown_function The teardown function. Runs after each test case.
 @return A test suite.
 */
#define ct_makesuite_setup_teardown(test_list, setup_function, teardown_function) \
ct_makesuite_setup_teardown_named(__func__, \
                                    test_list, \
                                    (sizeof (test_list) / sizeof (test_list)[0]), \
                                    setup_function, \
                                    teardown_function)
/**
 Make a test suite with a setup function, teardown function, and a name.
 @param name The name of the test suite.
 @param tests The collection of test cases.
 @param count The number of test cases.
 @param setup The setup function. Runs before each test case. Can be NULL.
 @param teardown The teardown function. Runs after each test case. Can be NULL.
 @return A test suite.
 */
inline struct ct_testsuite ct_makesuite_setup_teardown_named(const char * restrict name,
                                             const struct ct_testcase tests[],
                                             size_t count,
                                             ct_setupteardown_function setup,
                                             ct_setupteardown_function teardown)
{
    return (struct ct_testsuite){ name, tests, count, setup, teardown };
}

/**
 Run a unit test suite.
 @param suite The test suite to run.
 @return The number of failed tests.
 */
size_t ct_runsuite(const struct ct_testsuite *suite);

/**
 Mark a test as ignored.
 To prevent unnecessary test execution this assertion should be the first statement of the test function.
 @param message A printf-style format string literal with optional arguments to display when the test is ignored.
 */
#define ct_ignore(...) ct_internal_ignore("" __VA_ARGS__)

/**
 Assert failure unconditionally.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertfail(...) ct_internal_assertfail(__FILE__, __LINE__, "" __VA_ARGS__)

/**
 Assert whether an expression is true.
 @param expression The expression to evaluate against the value true.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_asserttrue(expression, ...) ct_internal_asserttrue(expression, #expression, __FILE__, __LINE__, "" __VA_ARGS__)
/**
 Assert whether an expression is false.
 @param expression The expression to evaluate against the value false.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertfalse(expression, ...) ct_internal_assertfalse(expression, #expression, __FILE__, __LINE__, "" __VA_ARGS__)

/**
 Assert whether an expression is NULL.
 @param expression The expression to evaluate against the value NULL.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnull(expression, ...) ct_internal_assertnull(expression, #expression, __FILE__, __LINE__, "" __VA_ARGS__)
/**
 Assert whether an expression is not NULL.
 @param expression The expression to evaluate against the value !NULL.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotnull(expression, ...) ct_internal_assertnotnull(expression, #expression, __FILE__, __LINE__, "" __VA_ARGS__)

/**
 Assert whether two values are equal.
 Compares any two basic value types but does not handle pointers, structs, unions, arrays, or function pointers.
 @see ct_assertsame for pointer equality.
 @see ct_assertequalstr for string equality.
 @param expected The expected value.
 @param actual The actual value.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertequal(expected, actual, ...) \
do { \
    ct_checkvalue(expected); \
    ct_checkvalue(actual); \
    ct_internal_assertequal(ct_makevalue(expected), #expected, ct_makevalue(actual), #actual, __FILE__, __LINE__, "" __VA_ARGS__); \
} while (0)
/**
 Assert whether two values are not equal.
 Compares any two basic value types but does not handle pointers, structs, unions, arrays, or function pointers.
 @see ct_assertnotsame for pointer equality.
 @see ct_assertnotequalstr for string equality.
 @param expected The expected value.
 @param actual The actual value.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotequal(expected, actual, ...) \
do { \
    ct_checkvalue(expected); \
    ct_checkvalue(actual); \
    ct_internal_assertnotequal(ct_makevalue(expected), #expected, ct_makevalue(actual), #actual, __FILE__, __LINE__, "" __VA_ARGS__); \
} while (0)

/**
 Assert whether two floating point values are equal within plus or minus a degree of error.
 @param expected The expected value.
 @param actual The actual value.
 @param precision The range of precision within which expected and actual may be considered equal.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertaboutequal(expected, actual, precision, ...) ct_internal_assertaboutequal(expected, #expected, actual, #actual, precision, __FILE__, __LINE__, "" __VA_ARGS__)
/**
 Assert whether two floating point values are not equal within plus or minus a degree of error.
 @param expected The expected value.
 @param actual The actual value.
 @param precision The range of precision within which expected and actual may be considered not equal.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotaboutequal(expected, actual, precision, ...) ct_internal_assertnotaboutequal(expected, #expected, actual, #actual, precision, __FILE__, __LINE__, "" __VA_ARGS__)

/**
 Assert whether two pointers refer to the same object.
 @param expected The expected pointer.
 @param actual The actual pointer.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertsame(expected, actual, ...) ct_internal_assertsame(expected, #expected, actual, #actual, __FILE__, __LINE__, "" __VA_ARGS__)
/**
 Assert whether two pointers refer to different objects.
 @param expected The expected pointer.
 @param actual The actual pointer.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotsame(expected, actual, ...) ct_internal_assertnotsame(expected, #expected, actual, #actual, __FILE__, __LINE__, "" __VA_ARGS__)

/**
 Assert whether two strings are equal.
 The first argument is a string literal used to automatically determine the number of characters to compare.
 If the first argument cannot be a string literal @see ct_assertequalstrn.
 @param expected The expected string. Must be a string literal expression.
 @param actual The actual string.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertequalstr(expected, actual, ...) ct_internal_assertequalstrn("" expected, #expected, actual, #actual, sizeof (expected), __FILE__, __LINE__, "" __VA_ARGS__);
/**
 Assert whether two strings are equal.
 Compares up to n characters for equality.
 @param expected The expected string.
 @param actual The actual string.
 @param n The maximum number of characters to compare for equality. Must not be greater than the size of expected.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertequalstrn(expected, actual, n, ...) ct_internal_assertequalstrn(expected, #expected, actual, #actual, n, __FILE__, __LINE__, "" __VA_ARGS__);
/**
 Assert whether two strings are not equal.
 The first argument is a string literal used to automatically determine the number of characters to compare.
 If the first argument cannot be a string literal @see ct_assertnotequalstrn.
 @param expected The expected string. Must be a string literal expression.
 @param actual The actual string.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotequalstr(expected, actual, ...) ct_internal_assertnotequalstrn("" expected, #expected, actual, #actual, sizeof (expected), __FILE__, __LINE__, "" __VA_ARGS__);
/**
 Assert whether two strings are not equal.
 Compares up to n characters for inequality.
 @param expected The expected string.
 @param actual The actual string.
 @param n The maximum number of characters to compare for inequality. Must not be greater than the size of expected.
 @param message A printf-style format string literal with optional arguments to display when the assertion fails.
 */
#define ct_assertnotequalstrn(expected, actual, n, ...) ct_internal_assertnotequalstrn(expected, #expected, actual, #actual, n, __FILE__, __LINE__, "" __VA_ARGS__);

/**
 @}
 */

/**
 @defgroup internal Internal types and functions
 Implementation details of CinyTest.
 These functions and types provide a greater degree of control over how assertion comparisons are
 defined and displayed. They are not intended for direct use over the public API and may
 change in the future without revving the major version. Regardless, full documentation is provided
 since they are defined in the public header and as long as all parameter constraints are observed
 these functions and types are safe to use.
 @{
 */
/**
 Value type annotation.
 An enumeration of possible simple value types used for equality assertions.
 */
enum ct_valuetype_annotation {
    CT_ANNOTATE_INVALID,            /**< Expression did not evaluate to a valid value type. */
    CT_ANNOTATE_INTEGRAL,           /**< Value is a signed integral type. */
    CT_ANNOTATE_UNSIGNEDINTEGRAL,   /**< Value is an unsigned integral type. */
    CT_ANNOTATE_FLOATINGPOINT,      /**< Value is a floating point type. */
    CT_ANNOTATE_COMPLEX             /**< Value is a complex number type. */
};
/**
 A comparable value.
 A unified type structure over simple value types to aid in equality assertions.
 */
struct ct_comparable_value {
    union {
        intmax_t integral_value;            /**< Access the value as a signed integral. */
        uintmax_t uintegral_value;          /**< Access the value as an unsigned integral. */
        long double floating_value;         /**< Access the value as a floating point. */
        long double _Complex complex_value; /**< Access the value as a complex number. */
    };
    enum ct_valuetype_annotation type;      /**< Designates the correct type of the value. If type is CT_ANNOTATE_INVALID then the value is undefined. */
};

/**
 Convert a value expression into a comparable value type.
 @param v The value expression to convert.
 @return A comparable value structure for the given value expression.
 */
#define ct_makevalue(v) ct_makevalue_factory(v)(0, v)
/**
 Select a makevalue function for converting the given value expression into a comparable value type.
 @param v The value expression for which to select the comparable value creation function.
 @return A function pointer to a typed makevalue function.
 */
#define ct_makevalue_factory(v) \
_Generic(v, \
            ct_valuetype_variants(signed char,          ct_makevalue_integral), \
            ct_valuetype_variants(short,                ct_makevalue_integral), \
            ct_valuetype_variants(int,                  ct_makevalue_integral), \
            ct_valuetype_variants(long,                 ct_makevalue_integral), \
            ct_valuetype_variants(long long,            ct_makevalue_integral), \
            ct_valuetype_variants(char,                 ct_makevalue_char), \
            ct_valuetype_variants(_Bool,                ct_makevalue_uintegral), \
            ct_valuetype_variants(unsigned char,        ct_makevalue_uintegral), \
            ct_valuetype_variants(unsigned short,       ct_makevalue_uintegral), \
            ct_valuetype_variants(unsigned int,         ct_makevalue_uintegral), \
            ct_valuetype_variants(unsigned long,        ct_makevalue_uintegral), \
            ct_valuetype_variants(unsigned long long,   ct_makevalue_uintegral), \
            ct_valuetype_variants(float,                ct_makevalue_floating), \
            ct_valuetype_variants(double,               ct_makevalue_floating), \
            ct_valuetype_variants(long double,          ct_makevalue_floating), \
            ct_valuetype_variants(float _Complex,       ct_makevalue_complex), \
            ct_valuetype_variants(double _Complex,      ct_makevalue_complex), \
            ct_valuetype_variants(long double _Complex, ct_makevalue_complex), \
            default:                                    ct_makevalue_invalid)
/**
 Generate all unique value-type variants for a generic selection.
 @param T The compile-time type for which to generate the variants.
 @param e The expression to use in the generic selection for all type variants.
 */
#define ct_valuetype_variants(T, e) T: e, const T: e, volatile T: e, _Atomic T: e, const volatile T: e, const _Atomic T: e, volatile _Atomic T: e, const volatile _Atomic T: e

/**
 Create a char comparable value structure based on whether char is signed or unsigned.
 */
#if CHAR_MIN < 0
#define ct_makevalue_char ct_makevalue_integral
#else
#define ct_makevalue_char ct_makevalue_uintegral
#endif
/**
 Create a signed integral comparable value structure.
 @param placeholder An unused parameter to match arity for all makevalue functions. May be any value as it is ignored by the function.
 @param value The widest possible expression of the signed integral value to be converted.
 @return A comparable value structure for the signed integral value.
 */
inline struct ct_comparable_value ct_makevalue_integral(int placeholder, intmax_t value)
{
    (void)placeholder;
    return (struct ct_comparable_value){ .integral_value = value, .type = CT_ANNOTATE_INTEGRAL };
}
/**
 Create an unsigned integral comparable value structure.
 @param placeholder An unused parameter to match arity for all makevalue functions. May be any value as it is ignored by the function.
 @param value The widest possible expression of the unsigned integral value to be converted.
 @return A comparable value structure for the unsigned integral value.
 */
inline struct ct_comparable_value ct_makevalue_uintegral(int placeholder, uintmax_t value)
{
    (void)placeholder;
    return (struct ct_comparable_value){ .uintegral_value = value, .type = CT_ANNOTATE_UNSIGNEDINTEGRAL };
}
/**
 Create a floating point comparable value structure.
 @param placeholder An unused parameter to match arity for all makevalue functions. May be any value as it is ignored by the function.
 @param value The widest possible expression of the floating point value to be converted.
 @return A comparable value structure for the floating point value.
 */
inline struct ct_comparable_value ct_makevalue_floating(int placeholder, long double value)
{
    (void)placeholder;
    return (struct ct_comparable_value){ .floating_value = value, .type = CT_ANNOTATE_FLOATINGPOINT };
}
/**
 Create a complex number comparable value structure.
 @param placeholder An unused parameter to match arity for all makevalue functions. May be any value as it is ignored by the function.
 @param value The widest possible expression of the complex number value to be converted.
 @return A comparable value structure for the complex number value.
 */
inline struct ct_comparable_value ct_makevalue_complex(int placeholder, long double _Complex value)
{
    (void)placeholder;
    return (struct ct_comparable_value){ .complex_value = value, .type = CT_ANNOTATE_COMPLEX };
}
/**
 Create a comparable value structure for an expression that cannot be converted into a simple value type.
 @param placeholder An unused parameter to allow for a variadic parameter. May be any value as it is ignored by the function.
 @param expression The expression that cannot be represented as a comparable value structure. Ignored by the function.
 @return An invalid comparable value structure used for checking a mismatched equality assertion.
 */
inline struct ct_comparable_value ct_makevalue_invalid(int placeholder, ...)
{
    (void)placeholder;
    return (struct ct_comparable_value){ .type = CT_ANNOTATE_INVALID };
}

/**
 Verify whether the expression can be converted into a valid value type.
 Failure raises a static assertion listing the offending expression and lists possible remedies.
 @param v The expression to verify as a simple value type.
 */
#define ct_checkvalue(v) _Static_assert(_Generic(&ct_makevalue_factory(v), struct ct_comparable_value (*)(int, ...): 0, default: 1), "(" #v ") is an invalid value type; use ct_assert[not]same for pointer types, ct_assert[not]equalstr for string types, or custom comparisons with ct_asserttrue/false for structs, unions, and arrays.")

/**
 Mark a test as ignored.
 To prevent unnecessary test execution this assertion should be the first statement of the test function.
 @see ct_ignore
 @param format The printf-style format string to display when the test is ignored.
 @param format_args Format arguments for the format string.
 */
_Noreturn void ct_internal_ignore(const char * restrict, ...);

/**
 Assert failure unconditionally with contextual details and message.
 @see ct_assertfail
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
_Noreturn void ct_internal_assertfail(const char * restrict, int, const char * restrict, ...);

/**
 Assert whether the expression is true, with contextual details and message.
 @see ct_asserttrue
 @param expression The expression to evaluate against the value true.
 @param stringized_expression The string representation of the expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_asserttrue(_Bool, const char * restrict, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether the expression is false, with contextual details and message.
 @see ct_assertfalse
 @param expression The expression to evaluate against the value false.
 @param stringized_expression The string representation of the expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertfalse(_Bool, const char * restrict, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether the expression is NULL, with contextual details and message.
 @see ct_assertnull
 @param expression The expression to evaluate against the value NULL.
 @param stringized_expression The string representation of the expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnull(const void * restrict, const char * restrict, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether the expression is not NULL, with contextual details and message.
 @see ct_assertnotnull
 @param expression The expression to evaluate against the value !NULL.
 @param stringized_expression The string representation of the expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnotnull(const void * restrict, const char * restrict, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two values are equal, with contextual details and message.
 @see ct_assertequal
 @param expected The expected value.
 @param stringized_expected The string representation of the expected value expression.
 @param actual The actual value.
 @param stringized_actual The string representation of the actual value expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertequal(struct ct_comparable_value, const char *, struct ct_comparable_value, const char *, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two values are not equal, with contextual details and message.
 @see ct_assertnotequal
 @param expected The expected value.
 @param stringized_expected The string representation of the expected value expression.
 @param actual The actual value.
 @param stringized_actual The string representation of the actual value expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnotequal(struct ct_comparable_value, const char *, struct ct_comparable_value, const char *, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two floating point values are equal within plus or minus a degree of error, with contextual details and message.
 @see ct_assertaboutequal
 @param expected The expected value.
 @param stringized_expected The string representation of the expected value expression.
 @param actual The actual value.
 @param stringized_actual The string representation of the actual value expression.
 @param precision The range of precision within which expected and actual may be considered equal.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertaboutequal(long double, const char *, long double, const char *, long double, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two floating point values are not equal within plus or minus a degree of error, with contextual details and message.
 @see ct_assertnotaboutequal
 @param expected The expected value.
 @param stringized_expected The string representation of the expected value expression.
 @param actual The actual value.
 @param stringized_actual The string representation of the actual value expression.
 @param precision The range of precision within which expected and actual may be considered not equal.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnotaboutequal(long double, const char *, long double, const char *, long double, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two pointers refer to the same object, with contextual details and message.
 @see ct_assertsame
 @param expected The expected pointer.
 @param stringized_expected The string representation of the expected pointer expression.
 @param actual The actual pointer.
 @param stringized_actual The string representation of the actual pointer expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertsame(const void *, const char *, const void *, const char *, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two pointers refer to different objects, with contextual details and message.
 @see ct_assertnotsame
 @param expected The expected pointer.
 @param stringized_expected The string representation of the expected pointer expression.
 @param actual The actual pointer.
 @param stringized_actual The string representation of the actual pointer expression.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnotsame(const void *, const char *, const void *, const char *, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two strings are equal, with contextual details and message.
 @see ct_assertequalstr
 @see ct_assertequalstrn
 @param expected The expected string.
 @param stringized_expected The string representation of the expected string expression.
 @param actual The actual string.
 @param stringized_actual The string representation of the actual string expression.
 @param n The maximum number of characters to compare for equality. Must not be greater than the size of expected.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertequalstrn(const char *, const char *, const char *, const char *, size_t, const char * restrict, int, const char * restrict, ...);

/**
 Assert whether two strings are not equal, with contextual details and message.
 @see ct_assertnotequalstr
 @see ct_assertnotequalstrn
 @param expected The expected string.
 @param stringized_expected The string representation of the expected string expression.
 @param actual The actual string.
 @param stringized_actual The string representation of the actual string expression.
 @param n The maximum number of characters to compare for inequality. Must not be greater than the size of expected.
 @param file The name of the file in which the assert fired.
 @param line The line number on which the assert fired.
 @param format The printf-style format string to display when the assertion fails.
 @param format_args Format arguments for the format string.
 */
void ct_internal_assertnotequalstrn(const char *, const char *, const char *, const char *, size_t, const char * restrict, int, const char * restrict, ...);

/**
 @}
 */

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.intravita.android.tsr.robot.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.intravita.android.tsr.R;
import com.intravita.android.tsr.activity.ColorPickerActivity.OnColorChangedListener;

/**
 * A Custom View that displays a Hue Saturation Brightness/Value color picker complete with a color wheel
 * for simultaneously selecting hue [0...360) and saturation [0...1] and a brightness bar for selecting
 * brightness [0...1].  To indicate the current selection crosshairs are drawn on the color wheel and a
 * height indicator is drawn on the brightness bar.
 *

 * To obtain updates on the selected color, create an {@link OnColorChangedListener} and either pass the
 * listener into the constructor or use
 * {@link HSBColorPickerView#setOnColorChangedListener(OnColorChangedListener)}.
 *

 * Make sure to set the initial color using {@link HSBColorPickerView#setNewColor(int)}.
 */
public class HSBColorPickerView extends View {

	//private static final String TAG = "Orbotix";
	private static final int DEFAULT_COLOR = Color.GREEN;
	private static final int SPACE_BETWEEN_WHEEL_AND_BAR = 10;
	private static final float ARC_WIDTH = 50.0f;
	private static final float CROSSHAIRS_SIZE = 30.0f;
	private static final float BRIGHTNESS_INDICATOR_SIZE = 15.0f;

	// Color Wheel
	private Bitmap mWheel;
	private Point mWheelPosition;
	private Point mWheelCenter;
	private double mRadius;

	// Background
	private Bitmap mBackground;
	private Point mBackgroundPosition;

	// Brightness Bar
	private Path mArcPath;
	private RectF mInnerArcRect;
	private RectF mOuterArcRect;

	// Touch control
	private boolean isTrackingHSWheel;
	private boolean isTrackingBBar;

	// Color
	private float[] mPreviousColor;
	private float[] mNewColor;

	// listener
	private OnColorChangedListener mListener;

	public HSBColorPickerView(Context context, AttributeSet attrs, int defStyle, int startingColor) {
		super(context, attrs, defStyle);
		mPreviousColor = new float[3];
		mNewColor = new float[3];
		Color.colorToHSV(startingColor, mPreviousColor);
		System.arraycopy(mPreviousColor, 0, mNewColor, 0, mPreviousColor.length);
		mBackground = BitmapFactory.decodeResource(getResources(), R.drawable.color_picker_wheel_background);
		mWheel = BitmapFactory.decodeResource(getResources(), R.drawable.color_wheel);
	}

	public HSBColorPickerView(Context context, AttributeSet attrs, int defStyle) {
		this(context, attrs, defStyle, DEFAULT_COLOR);
	}

	public HSBColorPickerView(Context context, AttributeSet attrs) {
		this(context, attrs, 0, DEFAULT_COLOR);
	}

	public HSBColorPickerView(Context context) {
		this(context, null, 0, DEFAULT_COLOR);
	}

	/**
	 * Changes the currently displayed color to the new color. This implementation invalidates the view.
	 * This can also be used to set the initial color when this view is shown. The
	 * {@link com.intravita.android.tsr.activity.app.ColorPickerActivity.OnColorChangedListener} will be notified of the change.
	 *
	 * @param newColor the desired color for this view to display in the color wheel and brightness bar.
	 */
	public void setNewColor(int newColor) {
		Color.colorToHSV(newColor, mNewColor);
		updateListener();
		invalidate();
	}

	/**
	 * Sets the {@link com.intravita.android.tsr.activity.app.ColorPickerActivity.OnColorChangedListener} to be sensorUpdated when the color in this
	 * view is changed either by user input or by setting a color using {@link HSBColorPickerView#setNewColor(int)}.
	 */
	public void setOnColorChangedListener(OnColorChangedListener listener) {
		mListener = listener;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// draw the background and color wheel
		canvas.drawBitmap(mBackground, mBackgroundPosition.x, mBackgroundPosition.y, null);
		canvas.drawBitmap(mWheel, mWheelPosition.x, mWheelPosition.y, null);

		// setup paint for the gradient filling
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
		paint.setStrokeWidth(2.0f);
		// create a shader that will show the range of brightness settings
		float[] gradientStartColor = new float[3];
		float[] gradientEndColor = new float[3];
		System.arraycopy(mNewColor, 0, gradientStartColor, 0, mNewColor.length);
		System.arraycopy(mNewColor, 0, gradientEndColor, 0, mNewColor.length);
		gradientStartColor[2] = 1.0f;
		gradientEndColor[2] = 0.0f;
		Shader gradientShader = new LinearGradient((float)(mWheelPosition.x + mRadius),
												   mWheelPosition.y,
												   mOuterArcRect.right,
												   mWheelPosition.y + mWheel.getHeight(),
												   Color.HSVToColor(gradientStartColor),
												   Color.HSVToColor(gradientEndColor),
												   Shader.TileMode.MIRROR);
		paint.setShader(gradientShader);
		canvas.drawPath(mArcPath, paint);

		drawHSCrosshairs(canvas);
		drawBrightnessIndicator(canvas);
	}

	private void drawHSCrosshairs(Canvas canvas) {
		float crosshairsRadius = CROSSHAIRS_SIZE / 2.0f;
		float[] HSCrosshairsCenter = findCrosshairsCenter();
		//Log.d(TAG, String.format("Reference point: (%f, %f)", HSCrosshairsCenter[0], HSCrosshairsCenter[1]));
		// find the actual coordinates of the center of the crosshairs wrt the whole screen
		float absoluteCenterX = (float)mWheelCenter.x + HSCrosshairsCenter[0];
		// note: the (-) is intentional due to the inversion of the y coordinate system (wrt cartesian)
		float absoluteCenterY = (float)mWheelCenter.y - HSCrosshairsCenter[1];

		// make convenience variables for size
		float topBottomWidth = 0.35f * CROSSHAIRS_SIZE;
		float topBottomHeight = 0.3f * CROSSHAIRS_SIZE;
		float leftRightWidth = 0.3f * CROSSHAIRS_SIZE;
		float leftRightHeight = 0.35f * CROSSHAIRS_SIZE;

		// make convenience variables for bounds
		float left = absoluteCenterX - crosshairsRadius;
		float right = absoluteCenterX + crosshairsRadius;
		float top = absoluteCenterY - crosshairsRadius;
		float bottom = absoluteCenterY + crosshairsRadius;

		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setStrokeWidth(1.0f);

		// draw the top triangle
		Path topTrianglePath = new Path();
		topTrianglePath.moveTo(absoluteCenterX - topBottomWidth, top);
		topTrianglePath.lineTo(absoluteCenterX + topBottomWidth, top);
		topTrianglePath.lineTo(absoluteCenterX, top + topBottomHeight);
		topTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(topTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(topTrianglePath, paint);

		// draw the bottom triangle
		Path bottomTrianglePath = new Path();
		bottomTrianglePath.moveTo(absoluteCenterX + topBottomWidth, bottom);
		bottomTrianglePath.lineTo(absoluteCenterX - topBottomWidth, bottom);
		bottomTrianglePath.lineTo(absoluteCenterX, bottom - topBottomHeight);
		bottomTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(bottomTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(bottomTrianglePath, paint);

		// draw the left triangle
		Path leftTrianglePath = new Path();
		leftTrianglePath.moveTo(left, absoluteCenterY + leftRightHeight);
		leftTrianglePath.lineTo(left, absoluteCenterY - leftRightHeight);
		leftTrianglePath.lineTo(left + leftRightWidth, absoluteCenterY);
		leftTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(leftTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(leftTrianglePath, paint);

		// draw the right triangle
		Path rightTrianglePath = new Path();
		rightTrianglePath.moveTo(right, absoluteCenterY - leftRightHeight);
		rightTrianglePath.lineTo(right, absoluteCenterY + leftRightHeight);
		rightTrianglePath.lineTo(right - leftRightWidth, absoluteCenterY);
		rightTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(rightTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(rightTrianglePath, paint);
	}

	private void drawBrightnessIndicator(Canvas canvas) {
        // get a representation of the height of the indicator within the bar
        float brightnessHeight = mNewColor[2] * mWheel.getHeight();
        //Log.d(TAG, String.format("Brightness height: %f", brightnessHeight));
        // convert the height to an absolute y position based on the bar's position
        float absoluteY = mWheelPosition.y + mWheel.getHeight() - brightnessHeight;
        // get the y value "above" the x axis for the x coordinate calculation
        // note: because of symmetry, the sign doesn't matter so we'll use the positive
        float heightAboveXAxis = Math.abs(brightnessHeight - (float)mRadius);
        //Log.d(TAG, String.format("Height above X: %f", heightAboveXAxis));
        float leftEdgeRadius = (float)(mRadius + SPACE_BETWEEN_WHEEL_AND_BAR);
        float rightEdgeRadius = leftEdgeRadius + ARC_WIDTH;
        // get the x coordinate relative to the center of the wheel
        float leftXInCircle = (float) Math.sqrt(leftEdgeRadius * leftEdgeRadius - heightAboveXAxis * heightAboveXAxis);
        float rightXInCircle = (float) Math.sqrt(rightEdgeRadius * rightEdgeRadius - heightAboveXAxis * heightAboveXAxis);
        // get the absolute x and y coordinates of the left edge of the bar at the bar height
        float leftX = mWheelCenter.x + leftXInCircle;
        float rightX = mWheelCenter.x + rightXInCircle;

        float indicatorHeight = BRIGHTNESS_INDICATOR_SIZE / 2.0f;
        float indicatorWidth = BRIGHTNESS_INDICATOR_SIZE;

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setStrokeWidth(1.0f);

		Path leftTrianglePath = new Path();
		leftTrianglePath.moveTo(leftX, absoluteY - indicatorHeight);
		leftTrianglePath.lineTo(leftX + indicatorWidth, absoluteY);
		leftTrianglePath.lineTo(leftX, absoluteY + indicatorHeight);
		leftTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(leftTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(leftTrianglePath, paint);

		Path rightTrianglePath = new Path();
		rightTrianglePath.moveTo(rightX, absoluteY - indicatorHeight);
		rightTrianglePath.lineTo(rightX - indicatorWidth, absoluteY);
		rightTrianglePath.lineTo(rightX, absoluteY + indicatorHeight);
		rightTrianglePath.close();
		paint.setColor(Color.BLUE);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawPath(rightTrianglePath, paint);
		paint.setColor(Color.WHITE);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawPath(rightTrianglePath, paint);
	}

	/**
	 * Uses the currently selected color to determine the point on the hue/saturation wheel that corresponds
	 * to that hue/saturation combination.
	 *
	 * @return a float[2] where float[0] is the x coordinate and float[1] is the y coordinate.
	 */
	private float[] findCrosshairsCenter() {
        // find hypotenuse for calculations
		float distanceFromCenter = mNewColor[1] * (float)mRadius;
		// angle should be in degrees so we need to change to radians
		float angle = mNewColor[0] * ((float)Math.PI / 180.0f);
		float xFromCenter = distanceFromCenter * (float)Math.cos(angle);
		float yFromCenter = distanceFromCenter * (float)Math.sin(angle);
		return new float[] {xFromCenter, yFromCenter};
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		int height = bottom - top;
		int width = right - left;
		//Log.d(TAG, String.format("Height: %d Width: %d", height, width));

		float sizeMultiplier = 1.0f;
		int forcedPadding = 10;

		// determine the position of the background image first
		// then all other items will depend on this one
		// for now, we will just use simple midpoint adjustment
		int pos_x = 0;
		if (mBackground.getWidth() < width) {
			pos_x = (width - mBackground.getWidth()) / 2;
		} else if (mBackground.getWidth() > width) {
			sizeMultiplier = (float)(width) / (float)mBackground.getWidth();
			mBackground = Bitmap.createScaledBitmap(mBackground, (int)(mBackground.getWidth() * sizeMultiplier), (int)(mBackground.getHeight() * sizeMultiplier), true);
			pos_x = (width - mBackground.getWidth()) / 2;
		}
		int pos_y = 0;
		if (mBackground.getHeight() < height) {
			pos_y = (height - mBackground.getHeight()) / 2;
		} else if (mBackground.getHeight() > height) {
			sizeMultiplier = (float)(height - forcedPadding) / (float)mBackground.getHeight();
			mBackground = Bitmap.createScaledBitmap(mBackground, (int)(mBackground.getWidth() * sizeMultiplier), (int)(mBackground.getHeight() * sizeMultiplier), true);
			pos_y = (height - mBackground.getHeight()) / 2;
		}
		mBackgroundPosition = new Point(pos_x, pos_y);

		// determine the position of the color wheel
		pos_y = 0;
		if (sizeMultiplier < 1.0f) {
			mWheel = Bitmap.createScaledBitmap(mWheel, (int)(mWheel.getWidth() * sizeMultiplier) - forcedPadding, (int)(mWheel.getHeight() * sizeMultiplier) - forcedPadding, true);
		}
		if (mWheel.getHeight() < height) {
			pos_y = (height - mWheel.getHeight()) / 2;
		}
		// put the wheel in the center, taking into account the brightness bar
		pos_x = (int) (mBackgroundPosition.x + (mBackground.getWidth() - mWheel.getWidth() - SPACE_BETWEEN_WHEEL_AND_BAR - ARC_WIDTH) / 2);
		mRadius = mWheel.getWidth()/2.0;
		mWheelPosition = new Point(pos_x, pos_y);
		mWheelCenter = new Point(mWheelPosition.x + (int)mRadius, mWheelPosition.y + (int)mRadius);

		// make the Path for the arc
		// find the angle for the inner arc
		double angle = Math.acos(mRadius / (mRadius + (double)SPACE_BETWEEN_WHEEL_AND_BAR));
		// change angle to degrees
		angle *= (180.0/Math.PI);
		// get the complementary angle (which is the one we want)
		angle = 90 - angle;
		//Log.d(TAG, String.format("Angle: %f", angle));
		// make the rects that hold the ovals for the arcs
		// the first (inner) will have a radius equal to the sum of the color wheel radius
		// and the space between the color wheel and the brightness bar
		mInnerArcRect = new RectF(mWheelPosition.x - SPACE_BETWEEN_WHEEL_AND_BAR,
								  mWheelPosition.y - SPACE_BETWEEN_WHEEL_AND_BAR,
								  mWheelPosition.x + mWheel.getWidth() + SPACE_BETWEEN_WHEEL_AND_BAR,
								  mWheelPosition.y + mWheel.getHeight() + SPACE_BETWEEN_WHEEL_AND_BAR);
		// the second (outer) will have a radius equal to the sum of the inner radius
		// and the width of the brightness bar
		mOuterArcRect = new RectF(mInnerArcRect.left - ARC_WIDTH,
								  mInnerArcRect.top - ARC_WIDTH,
								  mInnerArcRect.right + ARC_WIDTH,
								  mInnerArcRect.bottom + ARC_WIDTH);
		// create a path to hold the bar drawing
		mArcPath = new Path();
		// add the first arc
		mArcPath.arcTo(mInnerArcRect, (float)(angle * -1.0), (float)(2.0 * angle));
		// find the angle for the outer arc
		angle = Math.acos(mRadius / (mRadius + (double)SPACE_BETWEEN_WHEEL_AND_BAR + (double)ARC_WIDTH));
		// change angle to degrees
		angle *= (180.0/Math.PI);
		// get the complementary angle (which is the one we want)
		angle = 90 - angle;
		//Log.d(TAG, String.format("Angle: %f", angle));
		// add the second arc (a line is added in between the end points of the arcs)
		mArcPath.arcTo(mOuterArcRect, (float)angle, (float)(-2.0*angle));
		mArcPath.close();
	}

	@Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX() - mWheelCenter.x;
        float y = event.getY() - mWheelCenter.y;
        double distanceFromCenter = Math.sqrt(x*x + y*y);
        boolean inWheel = false;
        boolean inBar = false;
        if (distanceFromCenter <= mRadius) {
        	inWheel = true;
        } else if (distanceFromCenter <= (mRadius + SPACE_BETWEEN_WHEEL_AND_BAR + ARC_WIDTH) &&
        		event.getX() > mWheelCenter.x){
        	inBar = true;
        }

        switch (event.getAction()) {
        	// always change to the new color immediately using the appropriate control
            case MotionEvent.ACTION_DOWN:
                isTrackingHSWheel = inWheel;
                isTrackingBBar = inBar;
                if (inWheel) {
                    setCurrentHueSaturation(x, y, distanceFromCenter);
                } else if (inBar) {
                	setCurrentBrightness(event.getY());
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (isTrackingHSWheel) {
                    setCurrentHueSaturation(x, y, distanceFromCenter);
                } else if (isTrackingBBar) {
                	setCurrentBrightness(event.getY());
                }
                break;
            case MotionEvent.ACTION_UP:
            	isTrackingHSWheel = false;
                isTrackingBBar = false;
                break;
        }
        return true;
    }

	private void setCurrentBrightness(float yPosition) {
		// get the height (in pixels) from the bottom of the bar (wheel too) to the touch
		float touchHeight = (float)mWheelPosition.y + (float)mWheel.getHeight() - yPosition;
		// normalize the height of the touch
		float brightness = touchHeight / (float)mWheel.getHeight();

        // replace the brightness with the new value if it is in [0, 1]
        if (0.0f <= brightness && brightness <= 1.0f) {
            // set the new brightness
            mNewColor[2] = brightness;
            updateListener();
            //Log.d(TAG, String.format("Set brightness to: %f", brightness));
            invalidate();
        }
	}

	private void setCurrentHueSaturation(float x, float y, double distance) {
		// get the angle of the point in the color wheel
		// note: the (-) is intentional due to the inversion of the y coordinate system (wrt cartesian)
		float angle = -(float) Math.atan2(y, x);
		//Log.d(TAG, String.format("Angle Rad: %f", angle));
        if (angle < 0.0f) {
        	angle += (float)(2.0 * Math.PI);
        }
        // change angle to degrees
		float hue = (float)(angle * (180.0/Math.PI));
		//Log.d(TAG, String.format("Angle Deg: %f", hue));
		// normalize the distance from center
        float saturation = (float)(distance / mRadius);
        // replace the hue and saturation with the new values
        mNewColor[0] = hue;
        // only replace the saturation if the value is within range, otherwise the crosshairs will be
        // drawn outside of the wheel
        if (saturation <= 1.0f) {
        	mNewColor[1] = saturation;
        }
        updateListener();
        invalidate();
	}

	private void updateListener() {
		if (mListener != null) {
	        mListener.OnColorChanged(Color.HSVToColor(mNewColor));
		}
	}

}


text:
Fixes for IIS to make it more secure

##Done
1. SSL2 to SSL3 complete switch.
2. Harden IIS Up with lots of fixes

##To Do
Make Single Launch Script


text:
import { expect } from "chai";
import { BasicTests } from "test/helper/Basic";
import { Offline } from "test/helper/Offline";
import { StereoSignal } from "test/helper/StereoSignal";
import { Signal } from "Tone/signal/Signal";
import { Mono } from "./Mono";

describe("Mono", () => {

	BasicTests(Mono);

	context("Mono", () => {

		it("Makes a mono signal in both channels", () => {
			return Offline(() => {
				const mono = new Mono().toDestination();
				const signal = new Signal(2).connect(mono);
			}, 0.1, 2).then((buffer) => {
				expect(buffer.toArray()[0][0]).to.equal(2);
				expect(buffer.toArray()[1][0]).to.equal(2);
				expect(buffer.toArray()[0][100]).to.equal(2);
				expect(buffer.toArray()[1][100]).to.equal(2);
				expect(buffer.toArray()[0][1000]).to.equal(2);
				expect(buffer.toArray()[1][1000]).to.equal(2);
			});
		});

		it("Sums a stereo signal into a mono signal", () => {
			return Offline(() => {
				const mono = new Mono().toDestination();
				const signal = StereoSignal(2, 2).connect(mono);
			}, 0.1, 2).then((buffer) => {
				expect(buffer.toArray()[0][0]).to.equal(2);
				expect(buffer.toArray()[1][0]).to.equal(2);
				expect(buffer.toArray()[0][100]).to.equal(2);
				expect(buffer.toArray()[1][100]).to.equal(2);
				expect(buffer.toArray()[0][1000]).to.equal(2);
				expect(buffer.toArray()[1][1000]).to.equal(2);
			});
		});
	});
});


text:
<?php echo $title; ?>

        头像
        <input type="file" name="file" nv-file-select="" uploader="uploader">

        昵称
        {{ user_info.nickname }}

        性别
        男
        女
        保密

        联系电话
        {{ user_info.phone }}

        出生年月日

            <input type="text" class="input-text text-right SID-Date" placeholder="请选择日期" readonly="readonly" value="{{ user_info.birthday }}" style="padding: 0;color: #666666;margin-right: -10px;"/>

            <input type="radio" class="input-radio"  value="1" name="sex" ng-model="gender"/>
            男
            <input type="radio" class="input-radio"  value="0" name="sex" ng-model="gender"/>
            女
            保存
            取消

            <input type="text" class="input-text" placeholder="请输入新的昵称" ng-model="nickname" style="width: 145px;;"/>
            保存
            取消


text:
<?php

declare(strict_types=1);

/*
 * This file is part of boo/bnet.
 *
 * (c) Jonas Stendahl <jonas@stendahl.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Boo\BattleNet\Tests\Apis\Warcraft;

use Boo\BattleNet\Apis\Warcraft\PlayableSpecializationApi;
use Boo\BattleNet\Tests\Apis\AbstractApiTest;

/**
 * DO NOT EDIT. This file was auto-generated based on the Battle.net API docs.
 *
 * @internal
 * @covers \Boo\BattleNet\Apis\AbstractApi
 * @covers \Boo\BattleNet\Apis\Warcraft\PlayableSpecializationApi
 */
final class PlayableSpecializationApiTest extends AbstractApiTest
{
    public function testGetPlayableSpecializationIndex(): void
    {
        $client = $this->getClient();
        $api = new PlayableSpecializationApi($this->getRequestFactory(), $this->getRegion(), $this->getApiKey());
        $request = $api->getPlayableSpecializationIndex('static-eu', '');

        $this->assertSame('GET', $request->getMethod());
        $this->assertSame('application/json', $request->getHeaderLine('Accept'));
        $this->assertSame('gzip', $request->getHeaderLine('Accept-Encoding'));
    }

    public function testGetPlayableSpecialization(): void
    {
        $client = $this->getClient();
        $api = new PlayableSpecializationApi($this->getRequestFactory(), $this->getRegion(), $this->getApiKey());
        $request = $api->getPlayableSpecialization(262, 'static-eu', '');

        $this->assertSame('GET', $request->getMethod());
        $this->assertSame('application/json', $request->getHeaderLine('Accept'));
        $this->assertSame('gzip', $request->getHeaderLine('Accept-Encoding'));
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.desmond.uibackgroundjob.KeepTaskRefActivity">

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="No Result"
        android:layout_margin="20dp"
        android:textSize="18sp"/>

    <Button
        android:id="@+id/create_task_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Create Task"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/result"
        android:onClick="createTask"/>

    <Button
        android:id="@+id/delete_task_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete Task"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/create_task_btn"
        android:onClick="deleteTask"/>

</RelativeLayout>


text:
/**
 * Created by liusp on 2016/8/11.
 */
'use strict';
import { NativeModules } from 'react-native';

const Pay = NativeModules.Pay||{};

module.exports = {
    Pay,
};


text:
export const UP_ARROW_KEY = 38
export const DOWN_ARROW_KEY = 40
export const ENTER_KEY = 13
export const RESULT_SIZE = 5


text:
<!DOCTYPE html>
<html>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script>
'use strict';

let expected = ['immutable', 'immutable', 'immutable', 'immutable', 'immutable'];

async_test(function(t) {
  let worker = new Worker('immutable-prototype-worker.js');
  worker.onmessage = t.step_func_done(function(result) {
    assert_array_equals(expected, result.data);
  });
}, 'worker prototype chain should be immutable');
</script>
</html>


text:
"""Tests for preprocessors."""

import os
import textwrap
import unittest.mock as mock
from absl.testing import parameterized
import numpy as np
from prompt_tuning.data import preprocessors
import seqio
from seqio import test_utils
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds

TEST_DATA = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "test_data")

INPUTS_SIZE = 10
TARGETS_SIZE = 5
TEXT_SIZE = 10

TEST_T5_FEATURES = {
    "inputs": seqio.Feature(
        vocabulary=seqio.SentencePieceVocabulary(
            os.path.join(TEST_DATA, "t5_vocab"), 100),
        add_eos=True,
        required=False),
    "targets": seqio.Feature(
        vocabulary=seqio.SentencePieceVocabulary(
            os.path.join(TEST_DATA, "t5_vocab"), 100),
        add_eos=True)
}

def create_fake_text_dataset(examples: int = 10, text_size: int = TEXT_SIZE):
  text = np.reshape(
      # Start at 2 so we skip EOS=1 which could be a problem on any tests that
      # actually decode the fake inputs.
      np.arange(2, examples * text_size + 2),
      (-1, text_size)).astype(np.int32)
  return tf.data.Dataset.from_tensor_slices({"targets": text})

class PreprocessorsTest(tf.test.TestCase):

  def test_remove_first_text_token(self):
    input_strings = ["This is my first example", "The second"]
    gold_strings = [" ".join(s.split()[1:]) for s in input_strings]
    ds = tf.data.Dataset.from_tensor_slices({"inputs": input_strings})

    processed_ds = preprocessors.remove_first_text_token(ds)

    for res, gold in zip(processed_ds, gold_strings):
      self.assertEqual(res["inputs"].numpy().decode("utf-8"), gold)

  def test_add_sentinel_to_beginning(self):
    vocab_size = 100
    offset = 0
    field = "targets"
    ds = tf.data.Dataset.from_tensor_slices({
        field: tf.zeros([3, 4], dtype=tf.int32),
    })
    output_features = {
        field: mock.MagicMock(vocabulary=mock.MagicMock(vocab_size=vocab_size))
    }

    processed_ds = preprocessors.add_sentinel_to_beginning(
        ds, output_features, field, offset)

    for ex in processed_ds:
      self.assertEqual(ex[field][0].numpy().item(), vocab_size - (offset + 1))

  def test_tsv_to_qa(self):
    fake_data = textwrap.dedent("""
    id\tcontext\tquestion\tanswer\tanswers
    0\tThe capital of France is Paris\tWhat is the capital of France?\tParis\tParis|||paris
    1\tAn ant can carry many times it's body weight making it v strong.\tAre ants strong?\tYes\tYes
    """.strip("\n"))
    ds = tf.data.Dataset.from_tensor_slices(fake_data.split("\n")[1:-1])
    ds = preprocessors.preprocess_tsv_to_qa(ds)

    gold_data = [{
        "id": "0",
        "question": "What is the capital of France ? ",
        "answer": "Paris",
        "answers": ["Paris", "paris"],
        "context": "The capital of France is Paris",
        "inputs":
            "question: What is the capital of France ? context: The capital of"
            " France is Paris",
        "targets": "Paris"
    }, {
        "id":
            "1",
        "question":
            "Are ants strong ? ",
        "answer":
            "Yes",
        "answers": ["Yes"],
        "context":
            "An ant can carry many times it ' s body weight making it v strong . ",
        "inputs":
            "question: Are ants strong ? context: An ant can carry many times "
            "it ' s body weight making it v strong . ",
        "targets":
            "Yes"
    }]

    for ex, gold in zip(ds, gold_data):
      self.assertEqual(ex["id"].numpy().decode("utf-8"), gold["id"])
      self.assertEqual(ex["question"].numpy().decode("utf-8"), gold["question"])
      self.assertEqual(ex["answer"].numpy().decode("utf-8"), gold["answer"])
      self.assertEqual(ex["context"].numpy().decode("utf-8"), gold["context"])
      self.assertEqual(ex["targets"].numpy().decode("utf-8"), gold["targets"])
      for answer, gold_answer in zip(ex["answers"].numpy(), gold["answers"]):
        self.assertEqual(answer.decode("utf-8"), gold_answer)

  def test_preprocess_text_generation(self):
    example = tf.data.Dataset.from_tensor_slices({
        "source_aligned": {
            "en": ["english input"],
            "es": ["spanish input"]
        },
        "target_aligned": {
            "en": ["english target"],
            "es": ["spanish target"]
        }
    })
    processed_example = preprocessors.preprocess_text_generation(
        example,
        source_key="source_aligned",
        target_key="target_aligned",
        task_name=None,
        prefix="summarize:",
        source_nested_key="en",
        target_nested_key="es",
    )
    test_utils.assert_dataset(processed_example, {
        "inputs": "summarize: english input",
        "targets": "spanish target"
    })

class BARTTaskTest(parameterized.TestCase):

  @parameterized.named_parameters(
      dict(testcase_name="text_infilling",
           preprocessor=preprocessors.text_infilling),
      dict(testcase_name="token_deletion",
           preprocessor=preprocessors.token_deletion))
  def test_inputs_shorter_than_targets(self, preprocessor):
    ds = create_fake_text_dataset()
    ds = preprocessor(ds,
                      {"inputs": INPUTS_SIZE + 1, "targets": TARGETS_SIZE + 1},
                      TEST_T5_FEATURES,
                      noise_density=0.5)
    for ex in tfds.as_numpy(ds):
      self.assertLess(ex["inputs"].shape[0], ex["targets"].shape[0])

  @parameterized.named_parameters(
      dict(testcase_name="text_infilling",
           preprocessor=preprocessors.text_infilling),
      dict(testcase_name="token_deletion",
           preprocessor=preprocessors.token_deletion))
  def test_extra_id_not_in_targets(self, preprocessor):
    ds = create_fake_text_dataset()
    ds = preprocessor(ds,
                      {"inputs": INPUTS_SIZE + 1, "targets": TARGETS_SIZE + 1},
                      TEST_T5_FEATURES,
                      noise_density=0.5)
    vocab = TEST_T5_FEATURES["targets"].vocabulary
    for ex in tfds.as_numpy(ds):
      targets_text = vocab.decode(ex["targets"].tolist())
      self.assertNotIn("extra_id", targets_text)

  @parameterized.named_parameters(
      dict(testcase_name="text_infilling",
           preprocessor=preprocessors.text_infilling),
      dict(testcase_name="token_deletion",
           preprocessor=preprocessors.token_deletion))
  def test_target_tokens_match_original_tokens(self, preprocessor):
    ds = create_fake_text_dataset()
    processed_ds = preprocessor(
        ds,
        {"inputs": INPUTS_SIZE + 1, "targets": TARGETS_SIZE + 1},
        TEST_T5_FEATURES,
        noise_density=0.5)
    for processed_ex, ex in zip(tfds.as_numpy(processed_ds), tfds.as_numpy(ds)):
      np.testing.assert_array_equal(processed_ex["targets"], ex["targets"])

  def test_extra_id_not_in_token_deletion_inputs(self):
    ds = create_fake_text_dataset()
    ds = preprocessors.token_deletion(
        ds,
        {"inputs": INPUTS_SIZE + 1, "targets": TARGETS_SIZE + 1},
        TEST_T5_FEATURES,
        noise_density=0.5)
    vocab = TEST_T5_FEATURES["inputs"].vocabulary
    for ex in tfds.as_numpy(ds):
      inputs_text = vocab.decode(ex["inputs"].tolist())
      self.assertNotIn("extra_id", inputs_text)

  def test_extra_id_in_text_infilling_inputs(self):
    ds = create_fake_text_dataset()
    ds = preprocessors.text_infilling(
        ds,
        {"inputs": INPUTS_SIZE + 1, "targets": TARGETS_SIZE + 1},
        TEST_T5_FEATURES,
        noise_density=0.5)
    vocab = TEST_T5_FEATURES["inputs"].vocabulary
    for ex in tfds.as_numpy(ds):
      inputs_text = vocab.decode(ex["inputs"].tolist())
      self.assertIn("extra_id", inputs_text)

if __name__ == "__main__":
  tf.test.main()


text:
<?php

namespace Psy\Test\Formatter;

use Psy\Formatter\CodeFormatter;
use Psy\Test\Formatter\Fixtures\SomeClass;

class CodeFormatterTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @dataProvider reflectors
     */
    public function testFormat($reflector, $expected)
    {
        $formatted = CodeFormatter::format($reflector);
        $formattedWithoutColors = \preg_replace('#' . \chr(27) . '\[\d\d?m#', '', $formatted);

        $this->assertEquals($expected, self::trimLines($formattedWithoutColors));
        $this->assertNotEquals($expected, self::trimLines($formatted));
    }

    public function reflectors()
    {
        $expectClass = <<<'EOS'
  > 14| class SomeClass
    15| {
    16|     const SOME_CONST = 'some const';
    17|     private $someProp = 'some prop';
    18|
    19|     public function someMethod($someParam)
    20|     {
    21|         return 'some method';
    22|     }
    23|
    24|     public static function someClosure()
    25|     {
    26|         return function () {
    27|             return 'some closure';
    28|         };
    29|     }
    30| }
EOS;

        $expectMethod = <<<'EOS'
  > 19|     public function someMethod($someParam)
    20|     {
    21|         return 'some method';
    22|     }
EOS;

        $expectClosure = <<<'EOS'
  > 26|         return function () {
    27|             return 'some closure';
    28|         };
EOS;

        return [
            [new \ReflectionClass('Psy\Test\Formatter\Fixtures\SomeClass'), $expectClass],
            [new \ReflectionObject(new SomeClass()), $expectClass],
            [new \ReflectionMethod('Psy\Test\Formatter\Fixtures\SomeClass', 'someMethod'), $expectMethod],
            [new \ReflectionFunction(SomeClass::someClosure()), $expectClosure],
        ];
    }

    /**
     * @dataProvider invalidReflectors
     * @expectedException \Psy\Exception\RuntimeException
     */
    public function testCodeFormatterThrowsExceptionForReflectorsItDoesntUnderstand($reflector)
    {
        CodeFormatter::format($reflector);
    }

    public function invalidReflectors()
    {
        $reflectors = [
            [new \ReflectionExtension('json')],
            [new \ReflectionParameter(['Psy\Test\Formatter\Fixtures\SomeClass', 'someMethod'], 'someParam')],
            [new \ReflectionProperty('Psy\Test\Formatter\Fixtures\SomeClass', 'someProp')],
        ];

        if (\version_compare(PHP_VERSION, '7.1.0', '>=')) {
            $reflectors[] = [new \ReflectionClassConstant('Psy\Test\Formatter\Fixtures\SomeClass', 'SOME_CONST')];
        }

        return $reflectors;
    }

    /**
     * @dataProvider filenames
     * @expectedException \Psy\Exception\RuntimeException
     */
    public function testCodeFormatterThrowsExceptionForMissingFile($filename)
    {
        $reflector = $this->getMockBuilder('ReflectionClass')
            ->disableOriginalConstructor()
            ->getMock();

        $reflector
            ->expects($this->once())
            ->method('getFileName')
            ->will($this->returnValue($filename));

        CodeFormatter::format($reflector);
    }

    public function filenames()
    {
        if (\defined('HHVM_VERSION')) {
            $this->markTestSkipped('We have issues with PHPUnit mocks on HHVM.');
        }

        return [[null], ['not a file']];
    }

    private static function trimLines($code)
    {
        return \rtrim(\implode("\n", \array_map('rtrim', \explode("\n", $code))));
    }
}


text:
import torch

from . import Distribution
from .. import util

class Exponential(Distribution):
    def __init__(self, rate):
        rate = util.to_tensor(rate)
        super().__init__(name='Exponential', address_suffix='Exponential', torch_dist=torch.distributions.Exponential(rate))

    def __repr__(self):
        return 'Exponential(rate:{})'.format(self.rate)

    @property
    def rate(self):
        return self._torch_dist.mean


text:
import json

from nose.plugins.skip import SkipTest
from nose.tools import assert_equal, assert_true, assert_false

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

from desktop.lib.django_test_util import make_logged_in_client
from desktop.lib.test_utils import add_to_group, grant_access
from hadoop.pseudo_hdfs4 import is_live_cluster, get_db_prefix
from libzookeeper.conf import ENSEMBLE

from indexer.controller import get_solr_ensemble, CollectionManagerController

def test_get_ensemble():

  clear = ENSEMBLE.set_for_testing('zoo:2181')
  try:
    assert_equal('zoo:2181/solr', get_solr_ensemble())
  finally:
    clear()

  clear = ENSEMBLE.set_for_testing('zoo:2181,zoo2:2181')
  try:
    assert_equal('zoo:2181,zoo2:2181/solr', get_solr_ensemble())
  finally:
    clear()

class TestIndexerWithSolr:

  @classmethod
  def setup_class(cls):

    if not is_live_cluster():
      raise SkipTest()

    cls.client = make_logged_in_client(username='test', is_superuser=False)
    cls.user = User.objects.get(username='test')
    add_to_group('test')
    grant_access("test", "test", "indexer")

    resp = cls.client.post(reverse('indexer:install_examples'))
    content = json.loads(resp.content)

    assert_equal(content.get('status'), 0)

  @classmethod
  def teardown_class(cls):
    pass

  def test_is_solr_cloud_mode(self):
    assert_true(CollectionManagerController(self.user).is_solr_cloud_mode())

  def test_collection_exists(self):
    db = CollectionManagerController(self.user)
    assert_false(db.collection_exists('does_not_exist'))

  def test_get_collections(self):
    db = CollectionManagerController(self.user)
    db.get_collections()

  def test_create_collection(self):
    db = CollectionManagerController(self.user)

    name = get_db_prefix(name='solr') + 'test_create_collection'
    fields = [{'name': 'my_test', 'type': 'text'}]

    try:
      db.create_collection(name, fields, unique_key_field='id', df='text')
    finally:
      db.delete_collection(name, core=False)

  def test_collections_fields(self):
    db = CollectionManagerController(self.user)

    db.get_fields('log_analytics')
    resp = self.client.post(reverse('indexer:install_examples'))
    content = json.loads(resp.content)

    assert_equal(content.get('status'), 0)
    assert_equal(content.get('fields'), 0)
    assert_equal(content.get('unique_key'), 0)


text:
Title: How to configure private Alfresco Nexus repository
Added: v3.0.0
Last reviewed: 2019-10-18
---
# How to configure private Alfresco Nexus repository

The first matter to consider is to ensure that you have credentials for the Alfresco Private Repository ([artifacts.alfresco.com](artifacts.alfresco.com)), where the Alfresco artifacts are stored. Enterprise customers and partners can
request these credentials opening a ticket on the [Alfresco Support Portal](http://support.alfresco.com).

Once you have suitable credentials, you need to add support for Alfresco private Maven repository to your configuration. This would typically be done by
adding your access credentials to the `settings.xml` contained in your `~/.m2` directory (for Linux and OS X). On Windows this resolves to
`C:\Users\<username>\.m2`.

To do this, load `settings.xml` into your editor and add the following new server configuration in the `<servers>` section:

```
<server>
    <id>alfresco-private-repository</id>
    <username>username</username>
    <password>password</password>
</server>
```

You will need to replace the placeholder text with your real username and password as allocated by Alfresco. The id value should not be changed as it
is used in the Alfresco SDK project build files to specify the Enterprise artifacts Maven repository.

It is possible to use encrypted passwords here. See the [official Maven documentation](http://maven.apache.org/guides/mini/guide-encryption.html) for details
on how to do this.

At this point you have configured Maven to have access to the Alfresco Private Repository.


text:
namespace Amazon.Ec2;

public sealed class DescribeInstanceTypesRequest : DescribeRequest, IEc2Request
{
    public DescribeInstanceTypesRequest(params string[] instanceTypes)
    {
        ArgumentNullException.ThrowIfNull(instanceTypes);

        InstanceTypes = instanceTypes;
    }

    public string[] InstanceTypes { get; }

    List<KeyValuePair<string, string>> IEc2Request.ToParams()
    {
        var parameters = GetParameters("DescribeInstanceTypes");

        AddIds(parameters, "InstanceType", InstanceTypes);

        return parameters;
    }
}


text:
namespace AntMe
{
    /// <summary>
    /// List of possible Map Tile Orientations.
    /// </summary>
    public enum MapTileOrientation
    {
        /// <summary>
        /// Tile is not rotated.
        /// </summary>
        NotRotated = 0,

        /// <summary>
        /// Tile is rotated by 90 Degrees.
        /// </summary>
        RotBy90Degrees = 90,

        /// <summary>
        /// Tile is rotated by 180 Degrees.
        /// </summary>
        RotBy180Degrees = 180,

        /// <summary>
        /// Tile is rotated by 270 Degrees.
        /// </summary>
        RotBy270Degrees = 270
    }
}


text:
<?php

namespace Symfony\Bundle\SecurityBundle\Tests\Functional;

/**
 * @group legacy
 */
class AnonymousTest extends AbstractWebTestCase
{
    public function testAnonymous()
    {
        $client = $this->createClient(['test_case' => 'Anonymous', 'root_config' => 'config.yml']);

        $client->request('GET', '/');

        $this->assertSame(401, $client->getResponse()->getStatusCode());
    }
}


text:
package com.lzy.okhttpdemo.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * ================================================
 * 作    者:廖子尧
 * 版    本:1.0
 * 创建日期:2016/1/25
 * 描    述:
 * 修订历史:
 * ================================================
 */
public class ApkUtils {

    /** 安装一个apk文件 */
    public static void install(Context context, File uriFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(uriFile), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /** 卸载一个app */
    public static void uninstall(Context context, String packageName) {
        //通过程序的包名创建URI
        Uri packageURI = Uri.parse("package:" + packageName);
        //创建Intent意图
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        //执行卸载程序
        context.startActivity(intent);
    }

    /** 检查手机上是否安装了指定的软件 */
    public static boolean isAvailable(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        // 从pinfo中将包名字逐一取出,压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
        return packageNames.contains(packageName);
    }

    /** 检查手机上是否安装了指定的软件 */
    public static boolean isAvailable(Context context, File file) {
        return isAvailable(context, getPackageName(context, file.getAbsolutePath()));
    }

    /** 根据文件路径获取包名 */
    public static String getPackageName(Context context, String filePath) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            return appInfo.packageName;  //得到安装包名称
        }
        return null;
    }

    /** 从apk中获取版本信息 */
    public static String getChannelFromApk(Context context, String channelPrefix) {
        //从apk包中获取
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        //默认放在meta-inf/里, 所以需要再拼接一下
        String key = "META-INF/" + channelPrefix;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith(key)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String[] split = ret.split(channelPrefix);
        String channel = "";
        if (split.length >= 2) {
            channel = ret.substring(key.length());
        }
        return channel;
    }
}


text:
#ifndef __PEPXML_READER_DEFS_H__
#define __PEPXML_READER_DEFS_H__

/* Configuration flags for pre-loading the run summary */
typedef unsigned char pipeline_analysis_flags;
#define load_analysis_summary	1
#define load_dataset_derivation	2
#define load_all_analysis		3

/* Configuration flags for pre-loading the run summary */
typedef unsigned char run_summary_flags;
#define load_sample_enzyme		1
#define load_search_summary		2
#define load_analysis_timestamp	4
#define load_all_summary		7

#endif


text:
import json
from parser import ParserError
from yaml.error import MarkedYAMLError
from future.builtins import (  # noqa
    bytes, dict, int, list, object, range, str,
    ascii, chr, hex, input, next, oct, open,
    pow, round, filter, map, zip)
import copy
import types
from jinja2 import TemplateSyntaxError
from jinja2.environment import get_spontaneous_environment
from jsonschema import validate, ValidationError
from jsonschema.exceptions import SchemaError
import repoze.lru
from conf.appconfig import CONFIG_PROVIDERS, CONFIG_PROVIDER_LIST, \
    BOOLEAN_TRUE_VALUES, API_PORT, CONFIG_NAMES
from orchestrator.cluster_config.default import DefaultConfigProvider
from orchestrator.cluster_config.effective import MergedConfigProvider
from orchestrator.cluster_config.etcd import EtcdConfigProvider
from orchestrator.cluster_config.github import GithubConfigProvider
from orchestrator.cluster_config.s3 import S3ConfigProvider
from orchestrator.jinja import conditions, filters
from orchestrator.services.errors import ConfigProviderNotFound
from orchestrator.services.exceptions import ConfigValueError, \
    ConfigValidationError, ConfigParseError
from orchestrator.util import dict_merge

__author__ = 'sukrit'

def get_providers():
    for provider_type in CONFIG_PROVIDER_LIST:
        provider_type = provider_type.strip()
        if provider_type in CONFIG_PROVIDERS:
            yield provider_type
    yield 'effective'

def _get_effective_provider():
    """
    Gets the effective config provider.

    :return: Effective Config provider.
    :rtype: orchestrator.cluster_config.effective.MergedConfigProvider
    """
    providers = list()
    for provider_type in get_providers():
        if provider_type != 'effective':
            provider = get_provider(provider_type)
            if provider:
                providers.append(provider)
    return MergedConfigProvider(*providers)

def _get_etcd_provider(ttl=None):
    """
    Gets the etcd config provider.

    :keyword ttl: time to live in seconds
    :type ttl: number
    :return: Instance of EtcdConfigProvider
    :rtype: EtcdConfigProvider
    """
    return EtcdConfigProvider(
        etcd_host=CONFIG_PROVIDERS['etcd']['host'],
        etcd_port=CONFIG_PROVIDERS['etcd']['port'],
        config_base=CONFIG_PROVIDERS['etcd']['base']+'/config',
        ttl=ttl
    )

def _get_s3_provider():
    """
    Gets S3 Config Provider

    :return: Instance of S3ConfigProvider
    :rtype: S3ConfigProvider
    """
    return S3ConfigProvider(
        bucket=CONFIG_PROVIDERS['s3']['bucket'],
        config_base=CONFIG_PROVIDERS['s3']['base']
    )

def _get_github_provider():
    """
    Gets Github Config Provider

    :return: Instance of GithubConfigProvider
    :rtype: GithubConfigProvider
    """
    return GithubConfigProvider(
        token=CONFIG_PROVIDERS['github']['token'],
        config_base=CONFIG_PROVIDERS['github']['config_base']
    )

def _get_default_provider():
    return DefaultConfigProvider()

@repoze.lru.lru_cache(1)
def _load_job_schema(schema_name=None):
    """
    Helper function that loads given schema

    :param schema_name:
    :return:
    """
    base_url = 'http://localhost:%d' % API_PORT
    schema_name = schema_name or 'job-config-v1'
    fname = 'schemas/{0}.json'.format(schema_name)
    with open(fname) as schema_file:
        data = schema_file.read().replace('${base_url}', base_url)
        return json.loads(data)

def get_provider(provider_type):
    """
    Factory method to create config provider instance.

    :param provider_type:
    :type provider_type: str
    :param args: Arguments for the provider
    :param kwargs: Keyword arguments for the provider.
    :return: AbstractConfigProvider instance.
    :rtype: AbstractConfigProvider
    """
    if provider_type not in get_providers():
        raise ConfigProviderNotFound(provider_type)

    locator = '_get_%s_provider' % (provider_type)
    if locator in globals():
        return globals()[locator]()

def validate_schema(config, schema_name=None):
    """
    Validates schema for given configuration.

    :param config: Config dictionary
    :type config: dict
    :return: config if validation passes
    :rtype: dict
    """
    schema_name = schema_name or 'job-config-v1'
    schema = _load_job_schema(schema_name)
    try:
        validate(config, schema)
    except ValidationError as ex:
        message = 'Failed to validate config against schema {0}. ' \
                  'Reason: {1}'.format(schema_name, ex.message)
        raise ConfigValidationError(message, '/'.join(ex.schema_path),
                                    ex.schema)
    return config

def _json_compatible_config(config):
    """
    Converts the config to json compatible config for schema validation.
    This is needed because json schema does not handle a non-valid json
    config (like non string keys) which may be valid in other types like yaml.

    :return:
    """
    return json.loads(json.dumps(config))

def load_config(*paths, **kwargs):
    """
    Loads config for given path and provider type.

    :param paths: Tuple consisting of nested level path
    :type paths: tuple
    :keyword default_variables: Variables to be applied during template
    evaluation
    :type default_variables: dict
    :keyword provider_type: Type of provider
    :type provider_type: str
    :keyword config_names: List of config names to be loaded. Defaults to
        CONFIG_NAMES defined in appconfig
    :type config_names: list
    :return: Parsed configuration
    :rtype: dict
    """
    default_variables = kwargs.get('default_variables', {})
    provider_type = kwargs.get('provider_type', 'effective')
    config_names = kwargs.get('config_names', CONFIG_NAMES)
    provider = get_provider(provider_type)
    try:
        configs = [provider.load(name, *paths) for name in config_names]
        unified_config = dict_merge(*configs)
        return dict(
            normalize_config(
                validate_schema(
                    evaluate_config(
                        validate_schema(
                            _json_compatible_config(unified_config)
                        ), default_variables
                    ), schema_name='job-config-evaluated-v1'
                )
            )
        )

    except (MarkedYAMLError, ParserError, SchemaError) as error:
        raise ConfigParseError(str(error), paths)

def write_config(name, config, *paths, **kwargs):
    """
    Writes config for given path

    :param config: Dictionary based configuration
    :type config: dict
    :param provider_type: Type of provider
    :type provider_type: str
    :return: None
    """
    provider_type = kwargs.get('provider_type', 'effective')
    provider = get_provider(provider_type)
    if provider:
        provider.write(name, config, *paths)

def _get_jinja_environment():
    """
    Creates Jinja env for evaluating config

    :return: Jinja Environment
    """
    env = get_spontaneous_environment()
    env.line_statement_prefix = '#'

    return filters.apply_filters(conditions.apply_conditions(env))

def evaluate_template(template_value, variables={}):
    env = _get_jinja_environment()
    return env.from_string(str(template_value)).render(**variables).strip()

def evaluate_variables(variables, default_variables={}):

    merged_vars = dict_merge({}, default_variables)

    def get_sort_key(item):
        return item[1]['priority']

    def as_tuple(vars):
        for variable_name, variable_val in vars.items():
            variable_val = copy.deepcopy(variable_val)
            if not hasattr(variable_val, 'items'):
                variable_val = {
                    'value': variable_val,
                    'template': False,
                    'priority': 0
                }
            variable_val.setdefault('template', True)
            variable_val.setdefault('priority', 1)
            variable_val.setdefault('value', '')
            val = variable_val['value']
            if isinstance(val, bool):
                variable_val['value'] = str(val).lower()
            yield (variable_name, variable_val)

    def expand(var_name, var_value):
        try:
            merged_vars[var_name] = evaluate_template(
                var_value['value'], merged_vars) if var_value['template'] \
                else var_value['value']
        except Exception as exc:
            raise ConfigValueError('/variables/%s/' % var_name, var_value,
                                   str(exc))

    sorted_vars = sorted(as_tuple(variables), key=get_sort_key)
    for sorted_var_name, sorted_var_value in sorted_vars:
        expand(sorted_var_name, sorted_var_value)

    return merged_vars

def evaluate_value(value, variables={}, location='/'):
    """
    Renders tokenized values (using nested strategy)

    :param value: Value that needs to be evaluated (str , list, dict, int etc)
    :param variables: Variables to be used for Jinja2 templates
    :param identifier: Identifier used to identify tokenized values. Only str
        values that begin with identifier are evaluated.
    :return: Evaluated object.
    """
    value = copy.deepcopy(value)
    if hasattr(value, 'items'):
        if 'variables' in value:
            variables = evaluate_variables(value['variables'], variables)
            del(value['variables'])

        if 'value' in value:
            value.setdefault('encrypted', False)
            value.setdefault('template', True)
            if value['template']:
                try:
                    value['value'] = evaluate_template(value['value'],
                                                       variables)
                except TemplateSyntaxError as error:
                    raise ConfigValueError(location, value['value'],
                                           reason=error.message)
            del(value['template'])
            if not value['encrypted']:
                value = value['value']
            return value

        else:
            if '__defaults__' in value:
                defaults = value.get('__defaults__')
                del(value['__defaults__'])
            else:
                defaults = None
            for each_k, each_v in value.items():
                if defaults and hasattr(each_v, 'items'):
                    each_v = dict_merge(each_v, defaults)
                value[each_k] = evaluate_value(each_v, variables,
                                               '%s%s/' % (location, each_k))
            return {
                each_k: evaluate_value(each_v, variables)
                for each_k, each_v in value.items()
            }

    elif isinstance(value, (list, tuple, set, types.GeneratorType)):
        return [evaluate_value(each_v, variables, '%s[]/' % (location, ))
                for each_v in value]

    return value.strip() if isinstance(value, (str,)) else value

def _normalize_environment_config(env_config):
    if isinstance(env_config, dict):
        return {
            'value': str(env_config.get('value') or ''),
            'encrypted': env_config.get('encrypted', False)
        }
    return {
        'value': str(env_config),
        'encrypted': False
    }

def normalize_config(config):
    """
    Normalizes the config
    :param config:
    :return:
    """
    for config_key, config_val in config.items():
        if isinstance(config_val, dict):
            if config_key == 'environment':
                yield config_key, {
                    env_key: _normalize_environment_config(env_val)
                    for env_key, env_val in config_val.items()
                }
            else:
                yield config_key, dict(normalize_config(config_val))
        else:
            yield config_key, config_val

def evaluate_config(config, default_variables={}, var_key='variables'):
    """
    Performs rendering of all template values defined in config. Also takes
    user defined variables nd default variables for substitution in the config
    .
    :param config:
    :param default_variables:
    :param var_key:
    :return: Evaluated config
    :rtype: dict
    """
    updated_config = copy.deepcopy(config)
    updated_config.setdefault(var_key, {})
    updated_config.setdefault('deployers', {})

    if 'defaults' in updated_config:
        # We do not want to do any processing ind efaults section.
        # It is only used for YAML substitution which at this point is already
        # done.
        del(updated_config['defaults'])

    for deployer_name, deployer in \
            list(updated_config.get('deployers').items()):
        updated_config['deployers'][deployer_name].setdefault(
            'variables', {})
        updated_config['deployers'][deployer_name]['variables']\
            .setdefault('deployer', deployer_name)

    updated_config = transform_string_values(
        evaluate_value(updated_config, default_variables))

    # Remove all disabled deployers
    for deployer_name, deployer in \
            list(updated_config.get('deployers').items()):
        if not deployer.get('enabled', True):
            del(updated_config['deployers'][deployer_name])
    return updated_config

def transform_string_values(config):
    """
    Transforms the string values to appropriate type in config

    :param config: dictionary configuration with evaluated template parameters
    :type config: dict
    :return: transformed config
    :rtype: dict
    """
    new_config = copy.deepcopy(config)

    def convert_keys(use_config, location='/'):
        if hasattr(use_config, 'items'):
            for each_k, each_v in use_config.items():
                try:
                    if each_v is None:
                        continue
                    elif each_k in ('enabled', 'force-ssl',) and \
                            isinstance(each_v, str):
                        use_config[each_k] = each_v.lower() in \
                            BOOLEAN_TRUE_VALUES
                    elif each_k in ('port', 'nodes', 'min-nodes', 'attempts')\
                            and isinstance(each_v, str):
                        use_config[each_k] = int(each_v)
                    elif hasattr(each_v, 'items'):
                        convert_keys(each_v, '%s%s/' %
                                             (location, each_k))
                    elif isinstance(each_v,
                                    (list, tuple, set, types.GeneratorType)):
                        for idx, val in enumerate(each_v):
                            convert_keys(
                                val, '%s%s[%d]/' % (location, each_k, idx))
                except ValueError as error:
                    raise ConfigValueError(location + each_k, each_v,
                                           error.message)

    convert_keys(new_config)
    return new_config


text:
PONY_EXTERN_C_BEGIN

#ifdef PLATFORM_IS_ARM
#include <string.h>
#include <stdio.h>
#endif

static __thread struct _Unwind_Exception exception;
static __thread uintptr_t landing_pad;

static void exception_cleanup(_Unwind_Reason_Code reason,
  struct _Unwind_Exception* exception)
{
  (void)reason;
  (void)exception;
}

void pony_throw()
{
#ifdef PLATFORM_IS_ARM
  memcpy(exception.exception_class, "Pony\0\0\0\0", 8);
#else
  exception.exception_class = 0x506F6E7900000000; // "Pony"
#endif
  exception.exception_cleanup = exception_cleanup;
  _Unwind_RaiseException(&exception);

  abort();
}

static void set_registers(struct _Unwind_Exception* exception,
  struct _Unwind_Context* context)
{
  _Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
    (uintptr_t)exception);
  _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), 0);
  _Unwind_SetIP(context, landing_pad);
}

#ifdef PLATFORM_IS_ARM

_Unwind_Reason_Code __gnu_unwind_frame(_Unwind_Exception*, _Unwind_Context*);

static _Unwind_Reason_Code continue_unwind(_Unwind_Exception* exception,
  _Unwind_Context* context)
{
  if(__gnu_unwind_frame(exception, context) != _URC_OK)
    return _URC_FAILURE;

  return _URC_CONTINUE_UNWIND;
}

_Unwind_Reason_Code pony_personality_v0(_Unwind_State state,
  _Unwind_Exception* exception, _Unwind_Context* context)
{
  if(exception == NULL || context == NULL)
    return _URC_FAILURE;

  // Save exception in r12.
  _Unwind_SetGR(context, 12, (uintptr_t)exception);

  switch(state & _US_ACTION_MASK)
  {
    case _US_VIRTUAL_UNWIND_FRAME:
    {
      if(!ponyint_lsda_scan(context, &landing_pad))
        return continue_unwind(exception, context);

      // Save r13.
      exception->barrier_cache.sp = _Unwind_GetGR(context, 13);

      // Save barrier.
      exception->barrier_cache.bitpattern[0] = 0;
      exception->barrier_cache.bitpattern[1] = 0;
      exception->barrier_cache.bitpattern[2] =
        (uint32_t)_Unwind_GetLanguageSpecificData(context);
      exception->barrier_cache.bitpattern[3] = (uint32_t)landing_pad;
      exception->barrier_cache.bitpattern[4] = 0;
      return _URC_HANDLER_FOUND;
    }

    case _US_UNWIND_FRAME_STARTING:
    {

      if(exception->barrier_cache.sp == _Unwind_GetGR(context, 13))
      {
        // Load barrier.
        landing_pad = exception->barrier_cache.bitpattern[3];

        // No need to search again, just set the registers.
        set_registers(exception, context);
        return _URC_INSTALL_CONTEXT;
      }

      return continue_unwind(exception, context);
    }

    case _US_UNWIND_FRAME_RESUME:
      return continue_unwind(exception, context);

    default:
      abort();
  }

  return _URC_FAILURE;
}

#else

_Unwind_Reason_Code pony_personality_v0(int version, _Unwind_Action actions,
  uint64_t ex_class, struct _Unwind_Exception* exception,
  struct _Unwind_Context* context)
{
  (void)ex_class;

  if(version != 1 || exception == NULL || context == NULL)
    return _URC_FATAL_PHASE1_ERROR;

  // The search phase sets up the landing pad.
  if(actions & _UA_SEARCH_PHASE)
  {
    if(!ponyint_lsda_scan(context, &landing_pad))
      return _URC_CONTINUE_UNWIND;

    return _URC_HANDLER_FOUND;
  }

  if(actions & _UA_CLEANUP_PHASE)
  {
    if(!(actions & _UA_HANDLER_FRAME))
      return _URC_CONTINUE_UNWIND;

    // No need to search again, just set the registers.
    set_registers(exception, context);
    return _URC_INSTALL_CONTEXT;
  }

  return _URC_FATAL_PHASE1_ERROR;
}

#endif

PONY_EXTERN_C_END

#endif