text:
use exonum_crypto::Hash;

use super::{AsReadonly, IndexType, RawAccess, ViewWithMetadata};
use crate::{Fork, ObjectHash, ProofMapIndex};

/// Name of the state aggregator proof map.
const STATE_AGGREGATOR: &str = "__STATE_AGGREGATOR__";

pub fn get_state_aggregator<T: RawAccess>(
    access: T,
    namespace: &str,
) -> ProofMapIndex<T, str, Hash> {
    let view = ViewWithMetadata::get_or_create_unchecked(
        access,
        &(STATE_AGGREGATOR, namespace).into(),
        IndexType::ProofMap,
    )
    .expect("Internal MerkleDB failure while aggregating state");
    ProofMapIndex::new(view)
}

/// System-wide information about the database.
///
/// # Examples
///
/// ```
/// # use exonum_merkledb::{access::CopyAccessExt, Database, ObjectHash, TemporaryDB, SystemSchema};
/// let db = TemporaryDB::new();
/// let fork = db.fork();
/// fork.get_proof_list("list").extend(vec![1_u32, 2, 3]);
/// fork.get_map(("plain_map", &1)).put(&1_u8, "so plain".to_owned());
/// fork.get_map(("plain_map", &2)).put(&2_u8, "s0 plane".to_owned());
///
/// let patch = fork.into_patch();
/// let state_hash = SystemSchema::new(&patch).state_hash();
/// // ^-- State hash of the entire database including changes in the `patch`.
/// db.merge(patch).unwrap();
///
/// let snapshot = db.snapshot();
/// let aggregator = SystemSchema::new(&snapshot).state_aggregator();
/// assert_eq!(aggregator.object_hash(), state_hash);
/// assert_eq!(aggregator.keys().collect::<Vec<_>>(), vec!["list".to_owned()]);
/// // ^-- No other aggregated indexes so far.
/// let index_hash = aggregator.get(&"list".to_owned()).unwrap();
/// assert_eq!(
///     index_hash,
///     snapshot.get_proof_list::<_, u32>("list").object_hash()
/// );
///
/// // It is possible to prove that an index has a specific state
/// // given `state_hash`:
/// let proof = aggregator.get_proof("list".to_owned());
/// proof.check_against_hash(state_hash).unwrap();
/// ```
#[derive(Debug, Clone, Copy)]
pub struct SystemSchema<T>(T);

impl<T: RawAccess> SystemSchema<T> {
    /// Creates an instance based on the specified `access`.
    pub fn new(access: T) -> Self {
        Self(access)
    }

    /// Returns the state hash of the database. The state hash is up to date for `Snapshot`s
    /// (including `Patch`es), but is generally stale for `Fork`s.
    ///
    /// See [state aggregation] for details how the database state is aggregated.
    ///
    /// [state aggregation]: index.html#state-aggregation
    pub fn state_hash(&self) -> Hash {
        get_state_aggregator(self.0.clone(), "").object_hash()
    }
}

impl<T: RawAccess + AsReadonly> SystemSchema<T> {
    /// Returns the state aggregator of the database. The aggregator is up to date for `Snapshot`s
    /// (including `Patch`es), but is generally stale for `Fork`s.
    ///
    /// See [state aggregation] for details how the database state is aggregated.
    ///
    /// [state aggregation]: index.html#state-aggregation
    pub fn state_aggregator(&self) -> ProofMapIndex<T::Readonly, str, Hash> {
        get_state_aggregator(self.0.as_readonly(), "")
    }
}

impl SystemSchema<&Fork> {
    /// Updates state hash of the database.
    pub(crate) fn update_state_aggregators(
        &mut self,
        entries: impl IntoIterator<Item = (String, String, Hash)>,
    ) {
        for (ns, index_name, hash) in entries {
            get_state_aggregator(self.0, &ns).put(&index_name, hash);
        }
    }

    /// Removes indexes with the specified names from the aggregated indexes
    /// in the default namespace.
    pub(crate) fn remove_aggregated_indexes(&mut self, names: impl IntoIterator<Item = String>) {
        let mut aggregator = get_state_aggregator(self.0, "");
        for name in names {
            aggregator.remove(&name);
        }
    }

    /// Removes an aggregation namespace, moving all aggregated indexes in the namespace into
    /// the default aggregator.
    pub(crate) fn merge_namespace(&mut self, namespace: &str) {
        debug_assert!(!namespace.is_empty(), "Cannot remove default namespace");

        let mut ns_aggregator = get_state_aggregator(self.0, namespace);
        let mut default_aggregator = get_state_aggregator(self.0, "");
        for (index_name, hash) in &ns_aggregator {
            default_aggregator.put(&index_name, hash);
        }
        ns_aggregator.clear();
    }

    /// Removes an aggregation namespace.
    pub(crate) fn remove_namespace(&mut self, namespace: &str) {
        get_state_aggregator(self.0, namespace).clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        access::{AccessExt, CopyAccessExt},
        migration::Migration,
        Database, HashTag, TemporaryDB,
    };

    fn initial_changes(fork: &Fork) {
        fork.get_proof_list("list").extend(vec![1_u32, 2, 3]);
        fork.get_list("non_hashed_list").push(1_u64);
        fork.get_proof_entry("entry").set("oops!".to_owned());
        {
            let mut map = fork.get_proof_map("map");
            for i in 0..5 {
                map.put(&i, i.to_string());
            }
        }
        fork.get_proof_list(("grouped_list", &1_u8)).push(5_u8);
    }

    fn further_changes(fork: &Fork) {
        fork.get_proof_list::<_, u32>("list").clear();
        fork.get_map("non_hashed_map").put(&1_u32, "!".to_owned());
        fork.get_proof_list("list").push(1_u32);
        fork.get_proof_map("another_map")
            .put(&1_u64, "?".to_owned());
    }

    #[test]
    fn state_update() {
        let db = TemporaryDB::new();
        let fork = db.fork();
        initial_changes(&fork);

        let patch = fork.into_patch();
        let system_schema = SystemSchema::new(&patch);
        let aggregator = system_schema.state_aggregator();
        assert_eq!(
            aggregator.keys().collect::<Vec<_>>(),
            vec!["entry".to_owned(), "list".to_owned(), "map".to_owned()]
        );
        assert_eq!(
            aggregator.get(&"entry".to_owned()).unwrap(),
            patch.get_proof_entry::<_, String>("entry").object_hash()
        );
        assert_eq!(
            aggregator.get(&"list".to_owned()).unwrap(),
            patch.get_proof_list::<_, u32>("list").object_hash()
        );
        assert_eq!(
            aggregator.get(&"map".to_owned()).unwrap(),
            patch.get_proof_map::<_, i32, String>("map").object_hash()
        );
        assert_eq!(aggregator.object_hash(), system_schema.state_hash());
    }

    #[test]
    fn state_update_after_merge() {
        let db = TemporaryDB::new();
        let fork = db.fork();
        initial_changes(&fork);
        db.merge_sync(fork.into_patch()).unwrap();
        let fork = db.fork();
        further_changes(&fork);

        let patch = fork.into_patch();
        let system_schema = SystemSchema::new(&patch);
        let aggregator = system_schema.state_aggregator();
        let expected_index_names = vec![
            "another_map".to_owned(),
            "entry".to_owned(),
            "list".to_owned(),
            "map".to_owned(),
        ];
        assert_eq!(aggregator.keys().collect::<Vec<_>>(), expected_index_names);
        assert_eq!(
            aggregator.get(&"list".to_owned()).unwrap(),
            patch.get_proof_list::<_, u32>("list").object_hash()
        );
        assert_eq!(
            aggregator.get(&"map".to_owned()).unwrap(),
            patch.get_proof_map::<_, i32, String>("map").object_hash()
        );
        assert_eq!(aggregator.object_hash(), system_schema.state_hash());
        db.merge_sync(patch).unwrap();

        let snapshot = db.snapshot();
        let system_schema = SystemSchema::new(&snapshot);
        let aggregator = system_schema.state_aggregator();
        assert_eq!(aggregator.keys().collect::<Vec<_>>(), expected_index_names);
        assert_eq!(
            aggregator.get(&"list".to_owned()).unwrap(),
            snapshot.get_proof_list::<_, u32>("list").object_hash()
        );
        assert_eq!(
            aggregator.get(&"map".to_owned()).unwrap(),
            snapshot
                .get_proof_map::<_, i32, String>("map")
                .object_hash()
        );
        assert_eq!(aggregator.object_hash(), system_schema.state_hash());
    }

    #[test]
    fn migrated_indexes_do_not_influence_state_hash() {
        let db = TemporaryDB::new();
        let fork = db.fork();
        {
            let mut map = fork.get_map("test.map");
            map.put(&1_u64, "foo".to_owned());
            map.put(&2_u64, "bar".to_owned());
        }
        db.merge(fork.into_patch()).unwrap();
        let snapshot = db.snapshot();
        let system_schema = SystemSchema::new(&snapshot);
        assert_eq!(system_schema.state_hash(), HashTag::empty_map_hash());

        // Create a merkelized index in a migration. It should not be aggregated.
        let fork = db.fork();
        {
            let migration = Migration::new("test", &fork);
            let mut map = migration.get_proof_map("map");
            map.put(&1_u64, "1".to_owned());
            map.put(&3_u64, "3".to_owned());

            let map = fork.get_map::<_, u64, String>("test.map");
            assert_eq!(map.get(&1).unwrap(), "foo");
            assert!(map.get(&3).is_none());
        }
        db.merge(fork.into_patch()).unwrap();
        let snapshot = db.snapshot();
        let system_schema = SystemSchema::new(&snapshot);
        assert_eq!(system_schema.state_hash(), HashTag::empty_map_hash());
    }
}


text:
/**
 * @file
 *   This file implements the OpenThread Thread API (for both FTD and MTD).
 */

#define WPP_NAME "thread_api.tmh"

#include "openthread-core-config.h"

#include <openthread/thread.h>
#include <openthread/platform/settings.h>

#include "common/instance.hpp"
#include "common/logging.hpp"
#include "common/settings.hpp"

using namespace ot;

uint32_t otThreadGetChildTimeout(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetTimeout();
}

void otThreadSetChildTimeout(otInstance *aInstance, uint32_t aTimeout)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    instance.GetThreadNetif().GetMle().SetTimeout(aTimeout);
}

const uint8_t *otThreadGetExtendedPanId(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMac().GetExtendedPanId();
}

otError otThreadSetExtendedPanId(otInstance *aInstance, const uint8_t *aExtendedPanId)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);
    uint8_t mlPrefix[8];

    VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED,
                 error = OT_ERROR_INVALID_STATE);

    instance.GetThreadNetif().GetMac().SetExtendedPanId(aExtendedPanId);

    mlPrefix[0] = 0xfd;
    memcpy(mlPrefix + 1, aExtendedPanId, 5);
    mlPrefix[6] = 0x00;
    mlPrefix[7] = 0x00;
    instance.GetThreadNetif().GetMle().SetMeshLocalPrefix(mlPrefix);

    instance.GetThreadNetif().GetActiveDataset().Clear();
    instance.GetThreadNetif().GetPendingDataset().Clear();

exit:
    return error;
}

otError otThreadGetLeaderRloc(otInstance *aInstance, otIp6Address *aAddress)
{
    otError error;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit(aAddress != NULL, error = OT_ERROR_INVALID_ARGS);

    error = instance.GetThreadNetif().GetMle().GetLeaderAddress(*static_cast<Ip6::Address *>(aAddress));

exit:
    return error;
}

otLinkModeConfig otThreadGetLinkMode(otInstance *aInstance)
{
    otLinkModeConfig config;
    Instance &instance = *static_cast<Instance *>(aInstance);
    uint8_t mode = instance.GetThreadNetif().GetMle().GetDeviceMode();

    memset(&config, 0, sizeof(otLinkModeConfig));

    if (mode & Mle::ModeTlv::kModeRxOnWhenIdle)
    {
        config.mRxOnWhenIdle = 1;
    }

    if (mode & Mle::ModeTlv::kModeSecureDataRequest)
    {
        config.mSecureDataRequests = 1;
    }

    if (mode & Mle::ModeTlv::kModeFFD)
    {
        config.mDeviceType = 1;
    }

    if (mode & Mle::ModeTlv::kModeFullNetworkData)
    {
        config.mNetworkData = 1;
    }

    return config;
}

otError otThreadSetLinkMode(otInstance *aInstance, otLinkModeConfig aConfig)
{
    uint8_t mode = 0;
    Instance &instance = *static_cast<Instance *>(aInstance);

    if (aConfig.mRxOnWhenIdle)
    {
        mode |= Mle::ModeTlv::kModeRxOnWhenIdle;
    }

    if (aConfig.mSecureDataRequests)
    {
        mode |= Mle::ModeTlv::kModeSecureDataRequest;
    }

    if (aConfig.mDeviceType)
    {
        mode |= Mle::ModeTlv::kModeFFD;
    }

    if (aConfig.mNetworkData)
    {
        mode |= Mle::ModeTlv::kModeFullNetworkData;
    }

    return instance.GetThreadNetif().GetMle().SetDeviceMode(mode);
}

const otMasterKey *otThreadGetMasterKey(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return &instance.GetThreadNetif().GetKeyManager().GetMasterKey();
}

otError otThreadSetMasterKey(otInstance *aInstance, const otMasterKey *aKey)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit(aKey != NULL, error = OT_ERROR_INVALID_ARGS);
    VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED,
                 error = OT_ERROR_INVALID_STATE);

    error = instance.GetThreadNetif().GetKeyManager().SetMasterKey(*aKey);
    instance.GetThreadNetif().GetActiveDataset().Clear();
    instance.GetThreadNetif().GetPendingDataset().Clear();

exit:
    return error;
}

const otIp6Address *otThreadGetMeshLocalEid(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return &instance.GetThreadNetif().GetMle().GetMeshLocal64();
}

const uint8_t *otThreadGetMeshLocalPrefix(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetMeshLocalPrefix();
}

otError otThreadSetMeshLocalPrefix(otInstance *aInstance, const uint8_t *aMeshLocalPrefix)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED,
                 error = OT_ERROR_INVALID_STATE);

    error = instance.GetThreadNetif().GetMle().SetMeshLocalPrefix(aMeshLocalPrefix);
    instance.GetThreadNetif().GetActiveDataset().Clear();
    instance.GetThreadNetif().GetPendingDataset().Clear();

exit:
    return error;
}

const otIp6Address *otThreadGetLinkLocalIp6Address(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return &instance.GetThreadNetif().GetMle().GetLinkLocalAddress();
}

const char *otThreadGetNetworkName(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMac().GetNetworkName();
}

otError otThreadSetNetworkName(otInstance *aInstance, const char *aNetworkName)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED,
                 error = OT_ERROR_INVALID_STATE);

    error = instance.GetThreadNetif().GetMac().SetNetworkName(aNetworkName);
    instance.GetThreadNetif().GetActiveDataset().Clear();
    instance.GetThreadNetif().GetPendingDataset().Clear();

exit:
    return error;
}

uint32_t otThreadGetKeySequenceCounter(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetKeyManager().GetCurrentKeySequence();
}

void otThreadSetKeySequenceCounter(otInstance *aInstance, uint32_t aKeySequenceCounter)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    instance.GetThreadNetif().GetKeyManager().SetCurrentKeySequence(aKeySequenceCounter);
}

uint32_t otThreadGetKeySwitchGuardTime(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetKeyManager().GetKeySwitchGuardTime();
}

void otThreadSetKeySwitchGuardTime(otInstance *aInstance, uint32_t aKeySwitchGuardTime)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    instance.GetThreadNetif().GetKeyManager().SetKeySwitchGuardTime(aKeySwitchGuardTime);
}

otError otThreadBecomeDetached(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().BecomeDetached();
}

otError otThreadBecomeChild(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().BecomeChild(Mle::kAttachAny);
}

otError otThreadGetNextNeighborInfo(otInstance *aInstance, otNeighborInfoIterator *aIterator, otNeighborInfo *aInfo)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit((aInfo != NULL) && (aIterator != NULL), error = OT_ERROR_INVALID_ARGS);

    error = instance.GetThreadNetif().GetMle().GetNextNeighborInfo(*aIterator, *aInfo);

exit:
    return error;
}

otDeviceRole otThreadGetDeviceRole(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return static_cast<otDeviceRole>(instance.GetThreadNetif().GetMle().GetRole());
}

otError otThreadGetLeaderData(otInstance *aInstance, otLeaderData *aLeaderData)
{
    otError error;
    Instance &instance = *static_cast<Instance *>(aInstance);

    VerifyOrExit(aLeaderData != NULL, error = OT_ERROR_INVALID_ARGS);

    error = instance.GetThreadNetif().GetMle().GetLeaderData(*aLeaderData);

exit:
    return error;
}

uint8_t otThreadGetLeaderRouterId(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetLeaderRouterId();
}

uint8_t otThreadGetLeaderWeight(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetWeighting();
}

uint32_t otThreadGetPartitionId(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetPartitionId();
}

uint16_t otThreadGetRloc16(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().GetRloc16();
}

otError otThreadGetParentInfo(otInstance *aInstance, otRouterInfo *aParentInfo)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);
    Router *parent;

    VerifyOrExit(aParentInfo != NULL, error = OT_ERROR_INVALID_ARGS);

    parent = instance.GetThreadNetif().GetMle().GetParent();
    aParentInfo->mExtAddress      = parent->GetExtAddress();
    aParentInfo->mRloc16          = parent->GetRloc16();
    aParentInfo->mRouterId        = Mle::Mle::GetRouterId(parent->GetRloc16());
    aParentInfo->mNextHop         = parent->GetNextHop();
    aParentInfo->mPathCost        = parent->GetCost();
    aParentInfo->mLinkQualityIn   = parent->GetLinkInfo().GetLinkQuality();
    aParentInfo->mLinkQualityOut  = parent->GetLinkQualityOut();
    aParentInfo->mAge             = static_cast<uint8_t>(TimerMilli::MsecToSec(TimerMilli::GetNow() -
                                                                               parent->GetLastHeard()));
    aParentInfo->mAllocated       = parent->IsAllocated();
    aParentInfo->mLinkEstablished = parent->GetState() == Neighbor::kStateValid;

exit:
    return error;
}

otError otThreadGetParentAverageRssi(otInstance *aInstance, int8_t *aParentRssi)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);
    Router *parent;

    VerifyOrExit(aParentRssi != NULL, error = OT_ERROR_INVALID_ARGS);

    parent = instance.GetThreadNetif().GetMle().GetParent();
    *aParentRssi = parent->GetLinkInfo().GetAverageRss();

    VerifyOrExit(*aParentRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED);

exit:
    return error;
}

otError otThreadGetParentLastRssi(otInstance *aInstance, int8_t *aLastRssi)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);
    Router *parent;

    VerifyOrExit(aLastRssi != NULL, error = OT_ERROR_INVALID_ARGS);

    parent = instance.GetThreadNetif().GetMle().GetParent();
    *aLastRssi = parent->GetLinkInfo().GetLastRss();

    VerifyOrExit(*aLastRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED);

exit:
    return error;
}

const char *otGetVersionString(void)
{
    /**
     * PLATFORM_VERSION_ATTR_PREFIX and PLATFORM_VERSION_ATTR_SUFFIX are
     * intended to be used to specify compiler directives to indicate
     * what linker section the platform version string should be stored.
     *
     * This is useful for specifying an exact locaiton of where the version
     * string will be located so that it can be easily retrieved from the
     * raw firmware image.
     *
     * If PLATFORM_VERSION_ATTR_PREFIX is unspecified, the keyword `static`
     * is used instead.
     *
     * If both are unspecified, the location of the string in the firmware
     * image will be undefined and may change.
     */

#ifdef PLATFORM_VERSION_ATTR_PREFIX
    PLATFORM_VERSION_ATTR_PREFIX
#else
    static
#endif
    const char sVersion[] =
        PACKAGE_NAME "/" PACKAGE_VERSION "; " OPENTHREAD_CONFIG_PLATFORM_INFO
#if defined(__DATE__)
        "; " __DATE__ " " __TIME__
#endif
#ifdef PLATFORM_VERSION_ATTR_SUFFIX
        PLATFORM_VERSION_ATTR_SUFFIX
#endif
        ; // Trailing semicolon to end statement.

    return sVersion;
}

#if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC
void otThreadSetReceiveDiagnosticGetCallback(otInstance *aInstance, otReceiveDiagnosticGetCallback aCallback,
                                             void *aCallbackContext)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    instance.GetThreadNetif().GetNetworkDiagnostic().SetReceiveDiagnosticGetCallback(aCallback, aCallbackContext);
}

otError otThreadSendDiagnosticGet(otInstance *aInstance, const otIp6Address *aDestination,
                                  const uint8_t aTlvTypes[], uint8_t aCount)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticGet(*static_cast<const Ip6::Address *>
                                                                              (aDestination),
                                                                              aTlvTypes,
                                                                              aCount);
}

otError otThreadSendDiagnosticReset(otInstance *aInstance, const otIp6Address *aDestination,
                                    const uint8_t aTlvTypes[], uint8_t aCount)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticReset(*static_cast<const Ip6::Address *>
                                                                                (aDestination),
                                                                                aTlvTypes,
                                                                                aCount);
}
#endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC

otError otThreadSetEnabled(otInstance *aInstance, bool aEnabled)
{
    otError error = OT_ERROR_NONE;
    Instance &instance = *static_cast<Instance *>(aInstance);

    if (aEnabled)
    {
        VerifyOrExit(instance.GetThreadNetif().GetMac().GetPanId() != Mac::kPanIdBroadcast,
                     error = OT_ERROR_INVALID_STATE);
        error = instance.GetThreadNetif().GetMle().Start(true, false);
    }
    else
    {
        error = instance.GetThreadNetif().GetMle().Stop(true);
    }

exit:
    return error;
}

bool otThreadGetAutoStart(otInstance *aInstance)
{
#if OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT
    uint8_t autoStart = 0;
    uint16_t autoStartLength = sizeof(autoStart);

    if (otPlatSettingsGet(aInstance, Settings::kKeyThreadAutoStart, 0, &autoStart, &autoStartLength) !=
        OT_ERROR_NONE)
    {
        autoStart = 0;
    }

    return autoStart != 0;
#else
    OT_UNUSED_VARIABLE(aInstance);
    return false;
#endif
}

otError otThreadSetAutoStart(otInstance *aInstance, bool aStartAutomatically)
{
#if OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT
    uint8_t autoStart = aStartAutomatically ? 1 : 0;
    return otPlatSettingsSet(aInstance, Settings::kKeyThreadAutoStart, &autoStart, sizeof(autoStart));
#else
    OT_UNUSED_VARIABLE(aInstance);
    OT_UNUSED_VARIABLE(aStartAutomatically);
    return OT_ERROR_NOT_IMPLEMENTED;
#endif
}

bool otThreadIsSingleton(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().IsSingleton();
}

otError otThreadDiscover(otInstance *aInstance, uint32_t aScanChannels, uint16_t aPanId, bool aJoiner,
                         bool aEnableEui64Filtering, otHandleActiveScanResult aCallback, void *aCallbackContext)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().Discover(aScanChannels, aPanId, aJoiner, aEnableEui64Filtering, aCallback,
                                                       aCallbackContext);
}

bool otThreadIsDiscoverInProgress(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return instance.GetThreadNetif().GetMle().IsDiscoverInProgress();
}

const otIpCounters *otThreadGetIp6Counters(otInstance *aInstance)
{
    Instance &instance = *static_cast<Instance *>(aInstance);

    return &instance.GetThreadNetif().GetMeshForwarder().GetCounters();
}

redpajama_set_name: RedPajamaGithub


text:
.styleSans196.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 196.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans3.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 3.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans224.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 224.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans727.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 727.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans725.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 725.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans718.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 718.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans720.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 720.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans726.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 726.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans724.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 724.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans26.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 26.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 11.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 10.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans24.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 24.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 9.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans185.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 185.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans791.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 791.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans717.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 717.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 7.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 8.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 13.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans25.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 25.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 1.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans369.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 369.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 12.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans762.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 762.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 5.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans620.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 620.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans140.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 140.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans151.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 151.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans73.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 73.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans628.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 628.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans212.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 212.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans271.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 271.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans44.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 44.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans315.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 315.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 6.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans337.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 337.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans188.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 188.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 2.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans308.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 308.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 4.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 14.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans299.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 299.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans155.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 155.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans30.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 30.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans107.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 107.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans65.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 65.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans453.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 453.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans367.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 367.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans649.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 649.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans792.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 792.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans100.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 100.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans43.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 43.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans70.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 70.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans101.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 101.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans46.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 46.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans167.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 167.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans336.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 336.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans22.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 22.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans594.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 594.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans172.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 172.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans653.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 653.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans51.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 51.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans505.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 505.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans27.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 27.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans289.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 289.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans430.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 430.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans647.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 647.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans61.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 61.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans29.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 29.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans554.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 554.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 15.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans129.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 129.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans488.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 488.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans152.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 152.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans69.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 69.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans226.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 226.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans213.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 213.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans56.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 56.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans219.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 219.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans32.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 32.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans28.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 28.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans239.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 239.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans48.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 48.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans774.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 774.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans198.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 198.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans331.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 331.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans195.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 195.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans19.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 19.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans90.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 90.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans567.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 567.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans719.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 719.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans429.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 429.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans201.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 201.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans39.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 39.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans99.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 99.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans202.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 202.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans763.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 763.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 20.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}

.styleSans552.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle> {
    font-family: Sans;
    font-size: 552.0pt;
    font-weight: normal;
    font-style: normal;
    text-align: 0;
    letter-spacing: 0pt;
    line-height: 0pt;
}


text:
class AddAddressAndAlternateEmailToMembers < ActiveRecord::Migration
  def self.up
    add_column :members, :address, :string
    add_column :members, :alternate_email, :string
  end

  def self.down
    remove_column :members, :alternate_email
    remove_column :members, :address
  end
end


text:
okyahoo
=======

OK Yahoo is search api for old phones


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/item_test"
        android:icon="@android:drawable/ic_menu_help"
        android:title="Test"
        app:showAsAction="collapseActionView"/>
    <item android:id="@+id/item_test1"
        android:icon="@android:drawable/ic_menu_compass"
        android:title="Test 1"
        app:showAsAction="collapseActionView"/>
    <item android:id="@+id/item_test2"
        android:icon="@android:drawable/ic_menu_call"
        android:title="Test 2"
        app:showAsAction="collapseActionView"/>
</menu>


text:
Dumpty - http://artctrl.me/write/posts/dumpty.html

Contents © 2016 William Mckee - licensed under a Creative Commons Attribution 4.0 International Licence.

Mr Dumpty. Head to toe in bandages. Forty Doctors. Lengthy diagnose. Solution agreed. Experimental. Low success. No choice. Never wake up.

Mrs Dumpty. Tears flowed. Tissues wiped. Rumours. Demanding answers. Sitting. Falling. Refused information.

Top secret. The Kings Secret Police controlled access. They guarded. Allowed The Forty Doctors. Signed a contract. Whisleblowers punished.

Local Police. First on scene. The Kings Secret Police removed them. Media were restricted. Several witnesses. Shipped off. An unknown location. Unable to contact.

"They won't say what happened", Mrs Dumpty sobbed. "Climbing and the fool fell. Needs keep feet on floor", tears bursting.

No visitors at hospital over night. Options were motel or home. Her credit cards frozen. Forced to travel home. Husband in hospital. Must return.

Home to a broken door. A note explained that all value has been seized. Signed the Kings Secret Police. Will not be returned. Costs too significant.

The Kings Police gone. The covered window visible. Mrs Dumpty peaked in. Gone. A new patient. Not Husband. Tap. Span. Nurse.

"Can I help you?" Nurse spoke. Mrs Dumpty explained. Nurse order follow to reception. Press keys. Look up.
"Your Husbands last name?" Nurse asked. "Dumpty". "Humpty Dumpty".


text:
package com.intellij.semantic;

import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author peter
 */
public abstract class SemService {

  public static SemService getSemService(Project p) {
    return ServiceManager.getService(p, SemService.class);
  }

  @Nullable
  public <T extends SemElement> T getSemElement(SemKey<T> key, @NotNull PsiElement psi) {
    final List<T> list = getSemElements(key, psi);
    if (list.isEmpty()) return null;
    return list.get(0);
  }

  public abstract <T extends SemElement> List<T> getSemElements(SemKey<T> key, @NotNull PsiElement psi);

  @Nullable
  public abstract <T extends SemElement> List<T> getCachedSemElements(SemKey<T> key, @NotNull PsiElement psi);

  public abstract <T extends SemElement> void setCachedSemElement(SemKey<T> key, @NotNull PsiElement psi, @Nullable T semElement);

  public abstract void clearCachedSemElements(@NotNull PsiElement psi);

  public abstract void clearCache();

  /**
   * Caches won't be cleared on PSI changes inside this action
   * @param change the action
   */
  public abstract void performAtomicChange(@NotNull Runnable change);

  public abstract boolean isInsideAtomicChange();
}


text:
"""Installer for the bfa.sitecontent package."""

from setuptools import find_packages
from setuptools import setup

import os

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

long_description = read('README.rst')

setup(
    name='bfa.sitecontent',
    version='1.0.0',
    description="Sitecontent package containing folderish content pages",
    long_description=long_description,
    # Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        "Framework :: Plone",
        "Programming Language :: Python",
    ],
    keywords='Plone Dexterity',
    author='Serge Davidov',
    author_email='sd@kreativkombinat.de',
    url='http://pypi.python.org/pypi/bfa.sitecontent',
    license='BSD',
    packages=find_packages(exclude=['ez_setup']),
    namespace_packages=['bfa'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'plone.api',
        'plone.app.dexterity [relations]',
    ],
    extras_require={
        'test': [
            'mock',
            'plone.app.testing',
            'unittest2',
        ],
        'develop': [
            'coverage',
            'flake8',
            'jarn.mkrelease',
            'plone.app.debugtoolbar',
            'plone.reload',
            'Products.Clouseau',
            'Products.DocFinderTab',
            'Products.PDBDebugMode',
            'Products.PrintingMailHost',
            'Sphinx',
            'zest.releaser',
            'zptlint',
        ],
    },
    entry_points="""
    [z3c.autoinclude.plugin]
    target = plone
    """,
)


text:
package com.gs.fw.common.mithra.test.domain;

import com.gs.fw.common.mithra.finder.Operation;

public class MithraTestSequenceForIntSourceList extends MithraTestSequenceForIntSourceListAbstract
{

    public MithraTestSequenceForIntSourceList()
    {
        super();
    }

    public MithraTestSequenceForIntSourceList(Operation operation)
    {
        super(operation);
    }
}


text:
<?php
/**
 * @author Honza Cerny (http://honzacerny.com)
 */

namespace App\AdminModule\Components;

use Nette\Application\UI\Control;
use Nextras\Application\UI\SecuredLinksControlTrait;

class ConfirmButton extends Control
{
	use SecuredLinksControlTrait;

	/** @var callable */
	private $onConfirm;

	public function __construct(
		callable $onConfirm
	) {
		$this->onConfirm = $onConfirm;
	}

	/**
	 * @secured
	 */
	public function handleConfirm()
	{
		($this->onConfirm)($this);
	}

	public function render()
	{
		$this->template->render(__DIR__ . '/confirmButton.latte');
	}
}


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

<title>GNU Compiler Collection (GCC) Internals: Exception handling routines</title>

<meta name="description" content="GNU Compiler Collection (GCC) Internals: Exception handling routines">
<meta name="keywords" content="GNU Compiler Collection (GCC) Internals: Exception handling routines">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Libgcc.html#Libgcc" rel="up" title="Libgcc">
<link href="Miscellaneous-routines.html#Miscellaneous-routines" rel="next" title="Miscellaneous routines">
<link href="Fixed_002dpoint-fractional-library-routines.html#Fixed_002dpoint-fractional-library-routines" rel="prev" title="Fixed-point fractional library routines">

Next: Miscellaneous routines, Previous: Fixed-point fractional library routines, Up: Libgcc   [Contents][Index]

4.5 Language-independent routines for exception handling

document me!

  _Unwind_DeleteException
  _Unwind_Find_FDE
  _Unwind_ForcedUnwind
  _Unwind_GetGR
  _Unwind_GetIP
  _Unwind_GetLanguageSpecificData
  _Unwind_GetRegionStart
  _Unwind_GetTextRelBase
  _Unwind_GetDataRelBase
  _Unwind_RaiseException
  _Unwind_Resume
  _Unwind_SetGR
  _Unwind_SetIP
  _Unwind_FindEnclosingFunction
  _Unwind_SjLj_Register
  _Unwind_SjLj_Unregister
  _Unwind_SjLj_RaiseException
  _Unwind_SjLj_ForcedUnwind
  _Unwind_SjLj_Resume
  __deregister_frame
  __deregister_frame_info
  __deregister_frame_info_bases
  __register_frame
  __register_frame_info
  __register_frame_info_bases
  __register_frame_info_table
  __register_frame_info_table_bases
  __register_frame_table


text:
package com.intel.analytics.bigdl.keras.nn

import com.intel.analytics.bigdl.keras.KerasBaseSpec
import com.intel.analytics.bigdl.nn.keras.{Sequential => KSequential}
import com.intel.analytics.bigdl.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.nn.keras.Dense
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.Shape
import com.intel.analytics.bigdl.utils.serializer.ModuleSerializationTest

import scala.util.Random

class DenseSpec extends KerasBaseSpec {

  def weightConverter(in: Array[Tensor[Float]]): Array[Tensor[Float]] = Array(in(0).t(), in(1))

  "Dense" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[3])
        |input = np.random.uniform(0, 1, [1, 3])
        |output_tensor = Dense(2, activation="relu")(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = KSequential[Float]()
    val dense = Dense[Float](2, activation = "relu", inputShape = Shape(3))
    seq.add(dense)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 2))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

  "Dense nD input" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[10, 5, 7])
        |input = np.random.uniform(0, 1, [2, 10, 5, 7])
        |output_tensor = \
        |Dense(2, init='one', input_shape=(10, 5, 7))(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = KSequential[Float]()
    val dense = Dense[Float](2, init = "one", inputShape = Shape(10, 5, 7))
    seq.add(dense)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 10, 5, 2))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter, precision = 1e-4)
  }

}

class DenseSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val dense = Dense[Float](10, inputShape = Shape(20))
    dense.build(Shape(2, 20))
    val input = Tensor[Float](2, 20).apply1(_ => Random.nextFloat())
    runSerializationTest(dense, input)
  }
}


text:
module ElasticSchema::Schema

  class Migration

    BULK_SIZE = 1000

    attr_reader :schema_files, :client, :actual_schemas, :timestamp, :analysis_files,
                :bulk_size

    def initialize(options)
      @client         = options[:client]
      @analysis_files = options[:analysis_files]
      @schema_files   = options[:schema_files]
      @bulk_size      = (options[:bulk_size] || BULK_SIZE).to_i
      @actual_schemas = {}
      @timestamp      = Time.new.to_i
    end

    def load_definitions
      analysis_files.each { |schema_file| require schema_file }
      schema_files.each { |schema_file| require schema_file }
      self
    end

    def run
      schemas_to_update = types_to_update
      total_schemas     = schemas.size
      needs_update      = schemas_to_update.size

      if total_schemas > 0
        if needs_update < 1
          puts "Woo-hoo! Everything is already up-to-date!"
        else
          puts "Initiating schema updates: #{needs_update} out of #{total_schemas} will be updated."
        end
      else
        puts "There are no schemas to be processed in the provided directory."
      end

      create_or_update_indices(schemas_to_update)
    end

    private

    def create_or_update_indices(selected_schemas)
      selected_schemas.each do |index_name, schema|
        index_body = schema.index.to_hash.values.first

        if index_exists?(index_name)
          if must_create_new_index?(schema, index_name)
            migrate_data(index_name, index_body)
          else
            types = updatable_or_creatable_types(schema, index_name)
            create_or_update_types(schema, types)
          end
        else
          new_index = new_index_name(index_name)
          create_index(new_index, index_body)
          alias_index(new_index, index_name)
        end
      end
    end

    def create_or_update_types(schema, types)
      mappings = schema.index.mappings.to_hash['mappings']

      types.each do |type|
        mapping = mappings[type]
        put_mapping(schema.index.name, type, { type => mapping })
      end
    end

    # Migrates data from index/type to a new index/type and create an alias to it
    def migrate_data(index_name, index_body)
      new_index = new_index_name(index_name)
      create_index(new_index, index_body)
      copy_all_documents_between_indices(index_name, new_index)
      delete_index_with_same_name_as_alias(index_name)
      alias_index(new_index, index_name)
      delete_older_indices(index_name)
    end

    def alias_index(index, alias_name)
      puts "Creating alias '#{alias_name}' to index '#{index}'"
      client.indices.put_alias(index: index, name: alias_name)
    end

    def delete_older_indices(alias_name)
      older_indices = indices_from_alias(alias_name).keys - [new_index_name(alias_name)]
      older_indices.each { |index| delete_index(index) if index_exists?(index) }
    end

    def delete_index_with_same_name_as_alias(alias_name)
      delete_index(alias_name) if !alias_exists?(alias_name) && index_exists?(alias_name)
    end

    def copy_all_documents_between_indices(old_index, new_index)
      types = actual_schemas[old_index].values.first['mappings'].keys
      types.each { |type| copy_documents_for_type(type, old_index, new_index) }
    end

    def copy_documents_for_type(type, old_index, new_index)
      return unless (doc_count = documents_count(old_index, type)) > 0

      puts "Migrating #{doc_count} documents from type '#{type}' in index '#{old_index}' to index '#{new_index}'"

      result         = client.search index: old_index, type: type, search_type: 'scan', scroll: '1m', size: bulk_size
      alias_name     = new_index.split("_")[0..-2].join("_")
      fields_filter  = fields_whilelist(alias_name, type)

      while (result = client.scroll(scroll_id: result['_scroll_id'], scroll: '1m')) && (docs = result['hits']['hits']).any?
        body = docs.map do |document|
                 bulk_item = { index: { _index: new_index, _type: type } }
                 source    = document['_source'].deep_slice(*fields_filter)
                 bulk_item[:index].update(_id: document['_id'], data: source)
                 bulk_item
               end
        client.bulk(body: body)
      end
    end

    def fields_whilelist(alias_name, type)
      mapping = schemas[alias_name].to_hash.values.first['mappings'][type]['properties']
      extract_field_names(mapping).map { |f| f.include?('.') ? f.split('.') : f }
    end

    def updatable_or_creatable_types(schema, index_name)
      old_mappings = actual_schemas[index_name].values.first['mappings']
      new_mappings = schema.index.mappings.to_hash['mappings']

      new_mappings.keys.select do |type|
        old_fields         = old_mappings[type]['properties'] rescue {}
        new_fields         = new_mappings[type]['properties']
        old_mapping_fields = extract_field_names(old_fields)
        new_mapping_fields = extract_field_names(new_fields)

        (new_mapping_fields - old_mapping_fields).any?
      end
    end

    def must_create_new_index?(schema, index)
      has_diverging_settings?(schema, index) || has_conflicting_mappings?(schema, index)
    end

    def has_conflicting_mappings?(schema, index)
      old_mappings = actual_schemas[index].values.first['mappings']
      new_mappings = schema.index.mappings.to_hash['mappings']

      old_mappings.each do |type, old_mapping|
        old_fields = old_mapping['properties']
        new_fields = new_mappings[type]['properties'] rescue nil

        next if new_fields.nil?

        old_mapping_fields = extract_field_names(old_fields)
        new_mapping_fields = extract_field_names(new_fields)
        shared_fields      = old_mapping_fields & new_mapping_fields

        return true if shared_fields != old_mapping_fields

        old_mapping_fields = old_mapping_fields.map do |full_name|
          full_name = full_name.split('.').join('.properties.').split('.')
          full_name.size == 1 ? full_name.first : full_name
        end
        new_mapping_fields = new_mapping_fields.map do |full_name|
          full_name = full_name.split('.').join('.properties.').split('.')
          full_name.size == 1 ? full_name.first : full_name
        end

        return true if old_fields.deep_slice(*old_mapping_fields) != new_fields.deep_slice(*new_mapping_fields)
      end

      return false
    end

    # For now we're only comparing analysis settings
    def has_diverging_settings?(schema, index)
      old_settings = actual_schemas[index].values.first['settings']['index']['analysis'] rescue {}
      new_settings = schema.index.settings.to_hash['settings']['index']['analysis'] rescue {}
      new_settings != old_settings
    end

    def extract_field_names(mapping, name = '')
      mapping.inject([]) do |names, (key, value)|
        full_name = name.empty? ? key : "#{name}.#{key}"

        if value.is_a?(Hash)
          full_name = name if key == 'properties'
          expanded_names = extract_field_names(value, full_name)
        else
          expanded_names = name
        end

        names.concat(Array(expanded_names))
      end.uniq.sort
    end

    def documents_count(index, type)
      client.count(index: index, type: type)['count']
    end

    def indices_from_alias(alias_name)
      client.indices.get_alias(name: alias_name)
    end

    def delete_index(index)
      puts "Deleting index '#{index}'"
      client.indices.delete(index: index)
    end

    def create_index(index, body)
      puts "Creating index '#{index}'"

      types = body["mappings"].keys rescue []
      types.each { |type| puts "Creating type '#{type}' in index '#{index}'" }

      client.indices.create(index: index, body: body)
    end

    def alias_exists?(alias_name)
      client.indices.exists_alias(name: alias_name)
    end

    def index_exists?(index)
      client.indices.exists(index: index)
    end

    def put_mapping(index, type, mapping)
      puts "Creating/updating type '#{type}' in index '#{index}'"
      client.indices.put_mapping(index: index, type: type, body: mapping)
    end

    def new_index_name(index)
      "#{index}_v#{timestamp}"
    end

    # Get all the index/type in ES that diverge from the definitions
    def types_to_update
      schemas.select do |index_name, schema|
        current_schema              = fetch_index(index_name)
        @actual_schemas[index_name] = current_schema
        !has_same_index_structures?(current_schema.values.first || {}, schema.to_hash.values.first)
      end
    end

    def has_same_index_structures?(old_index_body, new_index_body)
      old_index_body = old_index_body.deep_slice('mappings', %w(settings index analysis)) rescue {}
      new_index_body = new_index_body.deep_slice('mappings', %w(settings index analysis)) rescue {}
      old_index_body == new_index_body
    end

    def fetch_index(index)
      begin
        client.indices.get(index: index)
      rescue Elasticsearch::Transport::Transport::Errors::NotFound
        {}
      end
    end

    def schemas
      @schemas ||= ElasticSchema::Schema::Definition.definitions
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Prooph\ProophessorDo\Projection\Todo;

use Doctrine\DBAL\Connection;
use Prooph\ProophessorDo\Model\Todo\TodoReminderStatus;
use Prooph\ProophessorDo\Projection\Table;

class TodoReminderFinder
{
    /**
     * @var Connection
     */
    private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
        $this->connection->setFetchMode(\PDO::FETCH_OBJ);
    }

    public function findOpen(): array
    {
        $stmt = $this->connection->prepare(
            sprintf(
                "SELECT * FROM %s where reminder < NOW() AND status = '%s'",
                Table::TODO_REMINDER,
                TodoReminderStatus::OPEN
            )
        );
        $stmt->execute();

        return $stmt->fetchAll();
    }
}


text:
namespace uScheduler.Models.Enums {
    public enum Frequency {
        Single,
        Hourly,
        Daily,
        Weekly,
        Fortnightly,
        Monthly,
        Quarterly
    }
}


text:
package programming.icpc2013.probf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.logging.Logger;

public class LowPowerOutputCalculator {

	private final static Logger log = Logger.getLogger(LowPowerOutputCalculator.class.getName());

	/**
	 * Read two lines from standard input and write back out a result
	 */
	private static void processFromPrompt() throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String nandkString;
		String sbatts;
		int n, k;
		InventoryCalc invC = new InventoryCalc();

		// make prompts optional, as problem description does not call for them
		boolean showPrompts = true;
		log.fine("Starting command prompt processing");

		if (showPrompts) {
			System.out.println("Please enter number of machines and number of batteries per machine (ie \"2 4\"):");
		}

		while ((nandkString = in.readLine()) != null) {
			nandkString = nandkString.trim();
			if (nandkString.isEmpty() || nandkString.equals("quit")) {
				log.info("All Done.");
				break;
			}

			// try something new in Java 8.  Might be picky about input format...
			int[] nkarr = Arrays.stream( nandkString.split(" ") ).mapToInt(Integer::parseInt).toArray();
			n = nkarr[0];
			k = nkarr[1];  //TODO: unnecessary assignment if just passing to a method

			// TODO: input validation, 2nk < 10^6
			if (n <= 0 || k <= 0) {
				throw new IllegalArgumentException("Cannot take values <= 0");
			}

			if (showPrompts) {
				System.out.println("Please enter battery output values (ie \"1 2 3 4 5 6 7 8\"):");
			}
			sbatts = in.readLine().trim();
			// TODO: input validation, 1 <= p <= 10^9

			// could easily add a .sorted() here, but want to keep all the functionality in the InventoryCalc class
			int[] battsarr = Arrays.stream(sbatts.split(" ")).mapToInt(Integer::parseInt).toArray();
			// and considered passing the IntStream, but want to keep a simple-to-test interface

			// do the real work, from n and k and list of batts
			System.out.println(invC.calculateLowPower(nkarr[0], nkarr[1], battsarr));

			// prompt for next loop
			if (showPrompts) {
				System.out.println("\nPlease enter number of machines and number of batteries per machine (ie \"2 4\"):");
			}
		}

	}

	public static void main(String[] args) throws IOException {
		// either read the values from a file, or from the command prompt

		// processFromFiles(".");
		// OR
		processFromPrompt();
	}

}


text:
namespace cistft {
namespace stft {

ClientStorage::ClientStorage(const Client::Format& fmt, AppGlobals* const globals)
	: mFftSize(fmt.getFftSize())
	, mWindowType(fmt.getWindowType())
	, mWindowSize(fmt.getWindowSize())
	, mChannelSize(fmt.getChannelSize())
	, mSmoothingFactor(0.5f)
{
	// This makes sure that we are zero padding
	mFftSize = globals->getAppConfig().getCalculatedFftSize();

	// The actual FFT processor instance
	mFft = std::make_unique<ci::audio::dsp::Fft>(mFftSize);

	// The FFT buffer, the one that will be filled AFTER FFT is performed on data
	mFftBuffer = ci::audio::Buffer(mFftSize, mChannelSize);

	// Copied buffer. the one that will be filled by raw audio chunks BEFORE FFT
	mCopiedBuffer = ci::audio::Buffer(mFftSize, mChannelSize);

	// Intermediate buffer passed to FFT processor
	mBufferSpectral = ci::audio::BufferSpectral(mFftSize);

	// The floating point array that contains all the FFT data, will be passed to renderer
	mMagSpectrum.resize(mFftSize / 2);

	// Window table.
	mWindowingTable = ci::audio::makeAlignedArray<float>(mWindowSize);
	generateWindow(mWindowType, mWindowingTable.get(), mWindowSize);

	// MISC.
	mMagnitudeScale = 1.0f / mFft->getSize();
	mChannelScale	= 1.0f / mChannelSize;
}

}} //!cistft::stft


text:
"use strict";

// expect.addSnapshotSerializer(require("./serialize-git-sha"));
module.exports = {
  serialize(str) {
    return (
      str
        // short SHA tends to be in the path diff comparisons
        .replace(/\b[0-9a-f]{7,8}\b/g, "SHA")
        // full SHA corresponds to gitHead property in package.json files
        .replace(/\b[0-9a-f]{40}\b/g, "GIT_HEAD")
    );
  },
  test(val) {
    return val != null && typeof val === "string" && /[0-9a-f]{7,40}/.test(val);
  },
};


text:
CXXFLAGS=-O3 -Wall -Werror -pedantic -std=c++11

ringbuffer: ringbuffer.cc

clean:
	rm -f ringbuffer


text:
module Database
    ( createTableIfMissing
    , savePasteToDb
    , getPasteFromDb
    , getAllPastes
    , getAllUsedLanguages
    , getPastesForLang
    ) where

import           Control.Monad (unless)
import           Control.Monad.Trans(MonadIO, liftIO)
import           Data.Maybe (listToMaybe)
import           Data.Time.Clock(getCurrentTime)
import           Database.HDBC
import           Types
import           Paste

createTableIfMissing ::  (IConnection conn) => conn -> IO ()
createTableIfMissing db = do
    tables <- handleSqlError $ getTables db
    unless ("pastes" `elem` tables) $ handleSqlError $ do
        run db ("CREATE TABLE pastes (id INTEGER PRIMARY KEY AUTOINCREMENT," ++
            " title TEXT, timestamp DATE, syntax VARCHAR(20), contents TEXT)") []
        commit db

savePasteToDb :: (IConnection conn, MonadIO m) => conn -> Paste -> m Integer
savePasteToDb db paste = do
    let query = "INSERT INTO pastes(title, timestamp, syntax, contents)" ++
                "VALUES(?,?,?,?)"
    t <- liftIO getCurrentTime
    let vals = [toSql (pasteTitle paste), toSql t, toSql (pasteSyntax paste),
                toSql (pasteContents paste)]
    liftIO $ withTransaction db $ \d -> run d query vals
    [[uid]] <- liftIO $ quickQuery db "SELECT last_insert_rowid()" []
    return (fromSql uid)

getAllPastes :: (MonadIO m, IConnection conn) => conn -> m [Paste]
getAllPastes db = pastesFromQuery db "SELECT * FROM pastes ORDER BY title" []

getPasteFromDb :: (Functor m, MonadIO m, IConnection conn) => conn -> Integer -> m (Maybe Paste)
getPasteFromDb db uid =
    pasteFromQuery db "SELECT * FROM pastes WHERE id = ?" [toSql uid]

getAllUsedLanguages :: (MonadIO m, IConnection conn) => conn -> m [String]
getAllUsedLanguages db = do
    langs <- handleSqlError' $
               quickQuery db "SELECT DISTINCT syntax FROM pastes WHERE syntax != \"\" ORDER BY syntax" []
    return $ map (fromSql . (!! 0)) langs

getPastesForLang :: (MonadIO m, IConnection conn) => conn -> String -> m [Paste]
getPastesForLang db lang =
    pastesFromQuery db "SELECT * FROM pastes WHERE syntax = ? ORDER BY title" [toSql lang]

pasteFromQuery :: (Functor m, MonadIO m, IConnection conn) => conn -> String -> [SqlValue] -> m (Maybe Paste)
pasteFromQuery db sqlString sqlArgs = do
    pastes <- pastesFromQuery db sqlString sqlArgs
    return $ listToMaybe pastes

pastesFromQuery :: (MonadIO m, IConnection conn) => conn -> String -> [SqlValue] -> m [Paste]
pastesFromQuery db sqlString sqlArgs = do
    pastes <- handleSqlError' $ quickQuery db sqlString sqlArgs
    return $ map makePaste pastes
  where
    makePaste ::  [SqlValue] -> Paste
    makePaste [pid, tit, ts, synt, cont] = Paste { pasteId = fromSql pid
                                                 , pasteTitle = fromSql tit
                                                 , pasteTimestamp = fromSql ts
                                                 , pasteSyntax = fromSql synt
                                                 , pasteContents = fromSql cont }
    makePaste _                          = nullPaste

handleSqlError' ::  (MonadIO m) => IO a -> m a
handleSqlError' = liftIO . handleSqlError


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace SourceCode.Chasm
{
    [DebuggerDisplay("{ToString(),nq,ac}")]
    public struct TreeNodeList : IReadOnlyDictionary<string, TreeNode>, IReadOnlyList<TreeNode>, IEquatable<TreeNodeList>
    {
        #region Constants

        /// <summary>
        /// A singleton representing an empty <see cref="TreeNodeList"/> value.
        /// </summary>
        /// <value>
        /// The empty.
        /// </value>
        public static TreeNodeList Empty { get; }

        #endregion

        #region Fields

        internal readonly ReadOnlyMemory<TreeNode> _nodes;

        #endregion

        #region Properties

        public int Count => _nodes.Length;

        public TreeNode this[int index]
        {
            get
            {
                if (_nodes.IsEmpty)
                    return Array.Empty<TreeNode>()[index]; // Throw underlying exception

                var span = _nodes.Span;

                return span[index];
            }
        }

        public TreeNode this[string key]
        {
            get
            {
                if (!TryGetValue(key, out var node))
                    throw new KeyNotFoundException(nameof(key));

                return node;
            }
        }

        #endregion

        #region Constructors

        public TreeNodeList(params TreeNode[] nodes)
        {
            // We choose to coerce empty & null, so de/serialization round-trips with fidelity
            if (nodes == null || nodes.Length == 0)
            {
                _nodes = default; // ie, same as default struct ctor
                return;
            }

            // Sort & de-duplicate
            _nodes = DistinctSort(nodes, false);
        }

        public TreeNodeList(ICollection<TreeNode> nodes)
        {
            // We choose to coerce empty & null, so de/serialization round-trips with fidelity
            if (nodes == null || nodes.Count == 0)
            {
                _nodes = default; // ie, same as default struct ctor
                return;
            }

            // Copy
            var array = new TreeNode[nodes.Count];
            nodes.CopyTo(array, 0);

            // Sort & de-duplicate
            _nodes = DistinctSort(array, true);
        }

        #endregion

        #region Methods

        private static TreeNode[] Merge(TreeNodeList first, TreeNodeList second)
        {
            var newArray = new TreeNode[first.Count + second.Count];

            var i = 0;
            var aIndex = 0;
            var bIndex = 0;
            for (; aIndex < first.Count || bIndex < second.Count; i++)
            {
                if (aIndex >= first.Count)
                {
                    newArray[i] = second[bIndex++];
                }
                else if (bIndex >= second.Count)
                {
                    newArray[i] = first[aIndex++];
                }
                else
                {
                    var a = first[aIndex];
                    var b = second[bIndex];
                    var cmp = string.CompareOrdinal(a.Name, b.Name);

                    if (cmp == 0)
                    {
                        newArray[i] = b;
                        ++bIndex;
                        ++aIndex;
                    }
                    else if (cmp < 0)
                    {
                        newArray[i] = a;
                        ++aIndex;
                    }
                    else
                    {
                        newArray[i] = b;
                        ++bIndex;
                    }
                }
            }

            Array.Resize(ref newArray, i);
            return newArray;
        }

        public TreeNodeList Merge(TreeNode node)
        {
            if (_nodes.IsEmpty) return new TreeNodeList(node);

            var index = IndexOf(node.Name);

            var span = _nodes.Span;

            TreeNode[] array;
            if (index >= 0)
            {
                array = new TreeNode[_nodes.Length];
                span.CopyTo(array);
                array[index] = node;
            }
            else
            {
                index = ~index;
                array = new TreeNode[_nodes.Length + 1];

                var j = 0;
                for (var i = 0; i < array.Length; i++)
                    array[i] = i == index ? node : span[j++];
            }

            return new TreeNodeList(array);
        }

        public TreeNodeList Merge(TreeNodeList nodes)
        {
            if (nodes == default || nodes.Count == 0)
                return this;

            if (_nodes.IsEmpty || _nodes.Length == 0)
                return nodes;

            var set = Merge(this, nodes);

            var tree = new TreeNodeList(set);
            return tree;
        }

        public TreeNodeList Merge(ICollection<TreeNode> nodes)
        {
            if (nodes == null || nodes.Count == 0)
                return this;

            if (_nodes.IsEmpty)
                return new TreeNodeList(nodes);

            var set = Merge(this, new TreeNodeList(nodes));
            var tree = new TreeNodeList(set);
            return tree;
        }

        public int IndexOf(string key)
        {
            if (_nodes.IsEmpty || key == null) return -1;

            var l = 0;
            var r = _nodes.Length - 1;
            var i = r / 2;
            var ks = key;

            var span = _nodes.Span;

            while (r >= l)
            {
                var cmp = string.CompareOrdinal(span[i].Name, ks);
                if (cmp == 0) return i;
                else if (cmp > 0) r = i - 1;
                else l = i + 1;

                i = l + (r - l) / 2;
            }

            return ~i;
        }

        public bool ContainsKey(string key) => IndexOf(key) >= 0;

        public bool TryGetValue(string key, out TreeNode value)
        {
            value = default;

            if (_nodes.IsEmpty || key == null)
                return false;

            var l = 0;
            var r = _nodes.Length - 1;
            var i = r / 2;
            var ks = key;

            var span = _nodes.Span;

            while (r >= l)
            {
                value = span[i];

                var cmp = string.CompareOrdinal(value.Name, ks);
                if (cmp == 0) return true;

                if (cmp > 0) r = i - 1;
                else l = i + 1;

                i = l + (r - l) / 2;
            }

            value = default;
            return false;
        }

        public bool TryGetValue(string key, NodeKind kind, out TreeNode value)
        {
            value = default;

            if (!TryGetValue(key, out var node))
                return false;

            if (node.Kind != kind)
                return false;

            value = node;
            return true;
        }

        #endregion

        #region Helpers

        private static ReadOnlyMemory<TreeNode> DistinctSort(TreeNode[] array, bool alreadyCopied)
        {
            Debug.Assert(array != null); // Already checked at callsites

            // Optimize for common cases 0, 1, 2, N
            switch (array.Length)
            {
                case 1:
                    // Always copy. The callsite may change the array after creating the TreeNodeList.
                    return new TreeNode[1] { array[0] };

                case 2:
                    {
                        // If the Name (alone) is duplicated
                        if (StringComparer.Ordinal.Equals(array[0].Name, array[1].Name))
                        {
                            // If it's a complete duplicate, silently skip
                            if (TreeNodeComparer.Default.Equals(array[0], array[1]))
                                return new TreeNode[1] { array[0] };

                            // Else throw
                            throw CreateDuplicateException(array[0]);
                        }

                        // Sort
                        if (TreeNodeComparer.Default.Compare(array[0], array[1]) < 0)
                            return new TreeNode[2] { array[0], array[1] };

                        return new TreeNode[2] { array[1], array[0] };
                    }

                default:
                    {
                        // If callsite did not already copy, do so before mutating
                        var nodes = array;
                        if (!alreadyCopied)
                        {
                            nodes = new TreeNode[array.Length];
                            array.CopyTo(nodes, 0);
                        }

                        // Sort: Delegate dispatch faster than interface (https://github.com/dotnet/coreclr/pull/8504)
                        Array.Sort(nodes, TreeNodeComparer.Default.Compare);

                        // Distinct
                        var j = 1;
                        for (var i = 1; i < nodes.Length; i++)
                        {
                            // If the Name (alone) is duplicated
                            if (StringComparer.Ordinal.Equals(nodes[i - 1].Name, nodes[i].Name))
                            {
                                // If it's a complete duplicate, silently skip
                                if (TreeNodeComparer.Default.Equals(nodes[i - 1], nodes[i]))
                                    continue;

                                // Else throw
                                throw CreateDuplicateException(nodes[0]);
                            }

                            nodes[j++] = nodes[i]; // Increment target index iff distinct
                        }

                        // Assign
                        var span = new ReadOnlyMemory<TreeNode>(nodes, 0, j);
                        return span;
                    }
            }

            // Local functions
            ArgumentException CreateDuplicateException(TreeNode node)
                => new ArgumentException($"Duplicate {nameof(TreeNode)} arguments passed to {nameof(TreeNodeList)}: ({node})");
        }

        #endregion

        #region IEnumerable

        public IEnumerable<string> Keys
        {
            get
            {
                if (_nodes.IsEmpty)
                    yield break;

                // TODO: Is Span safe under yield?
                var span = _nodes.Span;

                for (var i = 0; i < _nodes.Length; i++)
                    yield return span[i].Name;
            }
        }

        public IEnumerable<TreeNode> Values
        {
            get
            {
                if (_nodes.IsEmpty)
                    yield break;

                // TODO: Is Span safe under yield?
                var span = _nodes.Span;

                for (var i = 0; i < _nodes.Length; i++)
                    yield return span[i];
            }
        }

        public IEnumerator<TreeNode> GetEnumerator() => Values.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

        IEnumerator<KeyValuePair<string, TreeNode>> IEnumerable<KeyValuePair<string, TreeNode>>.GetEnumerator()
        {
            if (_nodes.IsEmpty)
                yield break;

            // TODO: Is Span safe under yield?
            var span = _nodes.Span;

            for (var i = 0; i < _nodes.Length; i++)
                yield return new KeyValuePair<string, TreeNode>(span[i].Name, span[i]);
        }

        #endregion

        #region IEquatable

        public bool Equals(TreeNodeList other) => TreeNodeListComparer.Default.Equals(this, other);

        public override bool Equals(object obj)
            => obj is TreeNodeList tree
            && TreeNodeListComparer.Default.Equals(this, tree);

        public override int GetHashCode() => TreeNodeListComparer.Default.GetHashCode(this);

        #endregion

        #region Operators

        public static bool operator ==(TreeNodeList x, TreeNodeList y) => TreeNodeListComparer.Default.Equals(x, y);

        public static bool operator !=(TreeNodeList x, TreeNodeList y) => !(x == y);

        public override string ToString() => $"{nameof(Count)}: {_nodes.Length}";

        #endregion
    }
}


text:
use clap::{App, Arg, ArgMatches, SubCommand};
use reproto_core::errors::Result;
use reproto_core::Filesystem;
use std::path::Path;

pub fn options<'a>() -> App<'a> {
    let out = SubCommand::with_name("init").about("Initialize a new project");

    let out = out.arg(
        Arg::with_name("path")
            .long("path")
            .takes_value(true)
            .help("Path to initialize the new project in. Defaults to current."),
    );

    out
}

pub fn entry(fs: &dyn Filesystem, matches: &ArgMatches) -> Result<()> {
    let path = if let Ok(Some(path)) = matches.try_get_one::<String>("path") {
        Path::new(path).to_owned()
    } else {
        ::std::env::current_dir()?
    };

    let handle = fs.open_root(Some(&path))?;
    env::initialize(handle.as_ref())?;
    Ok(())
}