text:
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>

#include <platform/ConnectivityManager.h>

#include <platform/internal/GenericConnectivityManagerImpl_UDP.ipp>

#if INET_CONFIG_ENABLE_TCP_ENDPOINT
#include <platform/internal/GenericConnectivityManagerImpl_TCP.ipp>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <platform/internal/GenericConnectivityManagerImpl_BLE.ipp>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <platform/internal/GenericConnectivityManagerImpl_Thread.ipp>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
#include <platform/internal/GenericConnectivityManagerImpl_WiFi.ipp>
#endif

#include <platform/internal/BLEManager.h>
#include <support/CHIPMemString.h>
#include <support/CodeUtils.h>
#include <support/logging/CHIPLogging.h>

#include <lwip/dns.h>
#include <lwip/ip_addr.h>
#include <lwip/nd6.h>
#include <lwip/netif.h>

#include "NetworkCommissioningDriver.h"

#include "matter_pal.h"
#include <components/netif.h>

using namespace ::chip;
using namespace ::chip::Inet;
using namespace ::chip::TLV;
using namespace ::chip::DeviceLayer::Internal;

namespace chip {
namespace DeviceLayer {

ConnectivityManagerImpl ConnectivityManagerImpl::sInstance;
NetworkCommissioning::BekenWiFiDriver::WiFiNetwork mWifiNetconf;

// ==================== ConnectivityManager Platform Internal Methods ====================

CHIP_ERROR ConnectivityManagerImpl::_Init()
{
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
    mLastStationConnectFailTime   = System::Clock::kZero;
    mLastAPDemandTime             = System::Clock::kZero;
    mWiFiStationMode              = kWiFiStationMode_Disabled;
    mWiFiStationState             = kWiFiStationState_NotConnected;
    mWiFiAPMode                   = kWiFiAPMode_Disabled;
    mWiFiAPState                  = kWiFiAPState_NotActive;
    mWiFiStationReconnectInterval = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_WIFI_STATION_RECONNECT_INTERVAL);
    mWiFiAPIdleTimeout            = System::Clock::Milliseconds32(CHIP_DEVICE_CONFIG_WIFI_AP_IDLE_TIMEOUT);
    mFlags.SetRaw(0);

    memset(&mWifiNetconf, 0x0, sizeof(mWifiNetconf));
    // If there is no persistent station provision...
    if (!IsWiFiStationProvisioned())
    {
        // If the code has been compiled with a default WiFi station provision, configure that now.
#if !defined(CONFIG_DEFAULT_WIFI_SSID)
        printf("%s %d pls define CONFIG_DEFAULT_WIFI_SSID\r\n", __func__, __LINE__);
#else
        if (CONFIG_DEFAULT_WIFI_SSID[0] != 0)
        {
            ChipLogProgress(DeviceLayer, "Setting default WiFi station configuration (SSID: %s)", CONFIG_DEFAULT_WIFI_SSID);

            // Set a default station configuration.
            rtw_wifi_setting_t wifiConfig;

            // Set the wifi configuration
            memset(&wifiConfig, 0, sizeof(wifiConfig));
            memcpy(wifiConfig.ssid, CONFIG_DEFAULT_WIFI_SSID, strlen(CONFIG_DEFAULT_WIFI_SSID) + 1);
            memcpy(wifiConfig.password, CONFIG_DEFAULT_WIFI_PASSWORD, strlen(CONFIG_DEFAULT_WIFI_PASSWORD) + 1);
            wifiConfig.mode = RTW_MODE_STA;

            // Configure the WiFi interface.
            int err = CHIP_SetWiFiConfig(&wifiConfig);
            if (err != 0)
            {
                ChipLogError(DeviceLayer, "_Init _SetWiFiConfig() failed: %d", err);
            }

            // Enable WiFi station mode.
            ReturnErrorOnFailure(SetWiFiStationMode(kWiFiStationMode_Enabled));
        }

        // Otherwise, ensure WiFi station mode is disabled.
        else
        {
            ReturnErrorOnFailure(SetWiFiStationMode(kWiFiStationMode_Disabled));
        }
#endif
    }

    // Force AP mode off for now.

    // Queue work items to bootstrap the AP and station state machines once the Chip event loop is running.
    ReturnErrorOnFailure(DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL));
    ReturnErrorOnFailure(DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL));

#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI

    return CHIP_NO_ERROR;
}

void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event)
{
    // Forward the event to the generic base classes as needed.
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
    GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>::_OnPlatformEvent(event);
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
    if (event->Type == DeviceEventType::kRtkWiFiStationConnectedEvent)
    {
        ChipLogProgress(DeviceLayer, "_OnPlatformEvent WIFI_EVENT_STA_CONNECTED");
        if (mWiFiStationState == kWiFiStationState_Connecting)
        {
            NetworkCommissioning::BekenWiFiDriver::GetInstance().OnConnectWiFiNetwork();
            ChangeWiFiStationState(kWiFiStationState_Connecting_Succeeded);
        }
        DriveStationState();
    }
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
}

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMode(void)
{
    // Enabled when platform instance initilazed
    return kWiFiStationMode_Enabled;
}

bool ConnectivityManagerImpl::_IsWiFiStationEnabled(void)
{
    return GetWiFiStationMode() == kWiFiStationMode_Enabled;
}

CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    VerifyOrExit(val != kWiFiStationMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT);

    if (mWiFiStationMode == kWiFiStationMode_Disabled && val == kWiFiStationMode_Enabled)
    {
        BK_LOG_ON_ERR(bk_event_register_cb(EVENT_MOD_WIFI, EVENT_ID_ALL, ConnectivityManagerImpl().wlan_event_cb, NULL));
        BK_LOG_ON_ERR(bk_event_register_cb(EVENT_MOD_NETIF, EVENT_ID_ALL, ConnectivityManagerImpl().netif_event_cb, NULL));
        ChangeWiFiStationState(kWiFiStationState_Connecting);
    }

    if (val != kWiFiStationMode_ApplicationControlled)
    {
        DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL);
    }

    if (mWiFiStationMode != val)
    {
        ChipLogProgress(DeviceLayer, "WiFi station mode change: %s -> %s", WiFiStationModeToStr(mWiFiStationMode),
                        WiFiStationModeToStr(val));
    }

    mWiFiStationMode = val;

exit:
    return err;
}

bool ConnectivityManagerImpl::_IsWiFiStationProvisioned(void)
{
    if (mWifiNetconf.ssidLen == 0)
        NetworkCommissioning::BekenWiFiDriver::GetInstance().GetSavedNetWorkConfig(&mWifiNetconf);
    ChipLogError(DeviceLayer, "wifi ssid:%s\r\n", mWifiNetconf.ssid);
    return (mWifiNetconf.ssidLen != 0) ? true : false;
}

void ConnectivityManagerImpl::_ClearWiFiStationProvision(void)
{
    // TBD
}

CHIP_ERROR ConnectivityManagerImpl::_SetWiFiAPMode(WiFiAPMode val)
{
    CHIP_ERROR err = CHIP_NO_ERROR;

    VerifyOrExit(val != kWiFiAPMode_NotSupported, err = CHIP_ERROR_INVALID_ARGUMENT);

    if (mWiFiAPMode != val)
    {
        ChipLogProgress(DeviceLayer, "WiFi AP mode change: %s -> %s", WiFiAPModeToStr(mWiFiAPMode), WiFiAPModeToStr(val));
    }

    mWiFiAPMode = val;

    DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL);

exit:
    return err;
}

void ConnectivityManagerImpl::_DemandStartWiFiAP(void)
{
    if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision)
    {
        mLastAPDemandTime = System::SystemClock().GetMonotonicTimestamp();
        DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL);
    }
}

void ConnectivityManagerImpl::_StopOnDemandWiFiAP(void)
{
    if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision)
    {
        mLastAPDemandTime = System::Clock::kZero;
        DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL);
    }
}

void ConnectivityManagerImpl::_MaintainOnDemandWiFiAP(void)
{
    if (mWiFiAPMode == kWiFiAPMode_OnDemand || mWiFiAPMode == kWiFiAPMode_OnDemand_NoStationProvision)
    {
        if (mWiFiAPState == kWiFiAPState_Activating || mWiFiAPState == kWiFiAPState_Active)
        {
            mLastAPDemandTime = System::SystemClock().GetMonotonicTimestamp();
        }
    }
}

void ConnectivityManagerImpl::_SetWiFiAPIdleTimeout(System::Clock::Timeout val)
{
    mWiFiAPIdleTimeout = val;
    DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL);
}

CHIP_ERROR ConnectivityManagerImpl::_GetAndLogWifiStatsCounters(void)
{
    return CHIP_NO_ERROR;
}

void ConnectivityManagerImpl::_OnWiFiScanDone()
{
    // Schedule a call to DriveStationState method in case a station connect attempt was
    // deferred because the scan was in progress.
    DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL);
}

void ConnectivityManagerImpl::_OnWiFiStationProvisionChange()
{
    // Schedule a call to the DriveStationState method to adjust the station state as needed.
    DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL);
}

// ==================== ConnectivityManager Private Methods ====================
void ConnectivityManagerImpl::WiFiStationConnectedHandler()
{
    ChipDeviceEvent event;
    memset(&event, 0, sizeof(event));
    event.Type = DeviceEventType::kRtkWiFiStationConnectedEvent;
    PlatformMgr().PostEventOrDie(&event);
}

static bool stationConnected = false;

int ConnectivityManagerImpl::netif_event_cb(void * arg, event_module_t event_module, int event_id, void * event_data)
{
    ssid_key_save_t wpa_save = { { 0 } };
    switch (event_id)
    {
    case EVENT_NETIF_GOT_IP4:
        stationConnected = true;
        WiFiStationConnectedHandler();
        ChipLogProgress(DeviceLayer, "netif_event_cb EVENT_NETIF_GOT_IP4");
        break;
    default:
        ChipLogProgress(DeviceLayer, "unSupported netif status:%d", event_id);
        break;
    }

    return BK_OK;
}

int ConnectivityManagerImpl::wlan_event_cb(void * arg, event_module_t event_module, int event_id, void * event_data)
{
    switch (event_id)
    {
    case EVENT_WIFI_STA_CONNECTED:
        ChipLogProgress(DeviceLayer, "wlan_event_cb EVENT_WIFI_STA_CONNECTED");
        break;
    case EVENT_WIFI_STA_DISCONNECTED:
        stationConnected = false;
        ChipLogProgress(DeviceLayer, "wlan_event_cb EVENT_WIFI_STA_DISCONNECTED");
        wifi_event_sta_disconnected_t * sta_disconnected;
        sta_disconnected = (wifi_event_sta_disconnected_t *) event_data;
        ChipDeviceEvent myevent;
        myevent.Platform.BKSystemEvent.Data.WiFiStaDisconnected = sta_disconnected->disconnect_reason;
        NetworkCommissioning::BekenWiFiDriver::GetInstance().SetLastDisconnectReason(&myevent);
        break;
    default:
        ChipLogProgress(DeviceLayer, "unSupported wifi status:%d", event_id);
        break;
    }
    return BK_OK;
}

void ConnectivityManagerImpl::DriveStationState()
{
    mWiFiStationMode = GetWiFiStationMode();
    ChipLogProgress(DeviceLayer, "wifi station state:%d, mWiFiStationState:%d", stationConnected, mWiFiStationState);
    // If the station interface is currently connected ...
    if (stationConnected)
    {
        // Advance the station state to Connected if it was previously NotConnected or
        // a previously initiated connect attempt succeeded.
        if (mWiFiStationState == kWiFiStationState_NotConnected || mWiFiStationState == kWiFiStationState_Connecting_Succeeded)
        {
            ChangeWiFiStationState(kWiFiStationState_Connected);
            ChipLogProgress(DeviceLayer, "WiFi station interface connected");
            mLastStationConnectFailTime = System::Clock::kZero;
            OnStationConnected();
            IpConnectedEventNotify();
        }
    }

    // Otherwise the station interface is NOT connected to an AP, so...
    else
    {
        System::Clock::Timestamp now = System::SystemClock().GetMonotonicTimestamp();

        // Advance the station state to NotConnected if it was previously Connected or Disconnecting,
        // or if a previous initiated connect attempt failed.
        if (mWiFiStationState == kWiFiStationState_Connected || mWiFiStationState == kWiFiStationState_Disconnecting ||
            mWiFiStationState == kWiFiStationState_Connecting_Failed)
        {
            WiFiStationState prevState = mWiFiStationState;
            ChangeWiFiStationState(kWiFiStationState_NotConnected);
            if (prevState != kWiFiStationState_Connecting_Failed)
            {
                ChipLogProgress(DeviceLayer, "WiFi station interface disconnected");
                mLastStationConnectFailTime = System::Clock::kZero;
                OnStationDisconnected();
            }
            else
            {
                mLastStationConnectFailTime = now;
            }
        }
        // If the WiFi station interface is now enabled and provisioned (and by implication,
        // not presently under application control), AND the system is not in the process of
        // scanning, then...
        ChipLogProgress(DeviceLayer, "mWiFiStationMode:%d, IsWiFiStationProvisioned:%d", mWiFiStationMode,
                        IsWiFiStationProvisioned());
        if (mWiFiStationMode == kWiFiStationMode_Enabled && IsWiFiStationProvisioned() &&
            mWiFiStationState != kWiFiStationState_Connecting)
        {
            // Initiate a connection to the AP if we haven't done so before, or if enough
            // time has passed since the last attempt.
            if (mLastStationConnectFailTime == System::Clock::kZero ||
                now >= mLastStationConnectFailTime + mWiFiStationReconnectInterval)
            {
                ChipLogProgress(DeviceLayer, "try to connect wifi");
                wifi_sta_config_t sta_config;

                memset(&sta_config, 0x0, sizeof(sta_config));
                sta_config.security = WIFI_SECURITY_AUTO; // can't use WIFI_DEFAULT_STA_CONFIG because of C99 designator error
                Platform::CopyString(sta_config.ssid, mWifiNetconf.ssidLen, mWifiNetconf.ssid);
                Platform::CopyString(sta_config.password, mWifiNetconf.credentialsLen, mWifiNetconf.credentials);
                BK_LOG_ON_ERR(bk_wifi_sta_set_config(&sta_config));
                BK_LOG_ON_ERR(bk_wifi_sta_start());
                BK_LOG_ON_ERR(bk_event_register_cb(EVENT_MOD_WIFI, EVENT_ID_ALL, ConnectivityManagerImpl().wlan_event_cb, NULL));
                BK_LOG_ON_ERR(bk_event_register_cb(EVENT_MOD_NETIF, EVENT_ID_ALL, ConnectivityManagerImpl().netif_event_cb, NULL));
                BK_LOG_ON_ERR(bk_wifi_sta_connect());
                ChangeWiFiStationState(kWiFiStationState_Connecting);
            }

            // Otherwise arrange another connection attempt at a suitable point in the future.
            else
            {
                System::Clock::Timeout timeToNextConnect = (mLastStationConnectFailTime + mWiFiStationReconnectInterval) - now;

                ChipLogProgress(DeviceLayer, "Next WiFi station reconnect in %" PRIu32 " ms",
                                System::Clock::Milliseconds32(timeToNextConnect).count());

                ReturnOnFailure(DeviceLayer::SystemLayer().StartTimer(timeToNextConnect, DriveStationState, nullptr));
            }
        }
    }
    ChipLogProgress(DeviceLayer, "Done driving station state, nothing else to do...");
    // Kick-off any pending network scan that might have been deferred due to the activity
    // of the WiFi station.
}

void ConnectivityManagerImpl::OnStationConnected()
{
    // Alert other components of the new state.
    ChipDeviceEvent event;
    event.Type                          = DeviceEventType::kWiFiConnectivityChange;
    event.WiFiConnectivityChange.Result = kConnectivity_Established;
    PlatformMgr().PostEventOrDie(&event);

    UpdateInternetConnectivityState();
}

void ConnectivityManagerImpl::OnStationDisconnected()
{
    // Alert other components of the new state.
    ChipDeviceEvent event;
    event.Type                          = DeviceEventType::kWiFiConnectivityChange;
    event.WiFiConnectivityChange.Result = kConnectivity_Lost;
    PlatformMgr().PostEventOrDie(&event);

    UpdateInternetConnectivityState();
}

void ConnectivityManagerImpl::ChangeWiFiStationState(WiFiStationState newState)
{
    if (mWiFiStationState != newState)
    {
        ChipLogProgress(DeviceLayer, "WiFi station state change: %s -> %s", WiFiStationStateToStr(mWiFiStationState),
                        WiFiStationStateToStr(newState));
        mWiFiStationState = newState;
        SystemLayer().ScheduleLambda([]() { NetworkCommissioning::BekenWiFiDriver::GetInstance().OnNetworkStatusChange(); });
    }
}

void ConnectivityManagerImpl::DriveStationState(::chip::System::Layer * aLayer, void * aAppState)
{
    sInstance.DriveStationState();
}

void ConnectivityManagerImpl::DriveAPState()
{
    ChipLogProgress(DeviceLayer, "WiFi ConnectivityManagerImpl::DriveAPState, do nothing!");
    CHIP_ERROR err = CHIP_NO_ERROR;
}

CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP()
{
    return CHIP_NO_ERROR;
}

void ConnectivityManagerImpl::ChangeWiFiAPState(WiFiAPState newState)
{
    if (mWiFiAPState != newState)
    {
        ChipLogProgress(DeviceLayer, "WiFi AP state change: %s -> %s", WiFiAPStateToStr(mWiFiAPState), WiFiAPStateToStr(newState));
        mWiFiAPState = newState;
    }
}

void ConnectivityManagerImpl::DriveAPState(::chip::System::Layer * aLayer, void * aAppState)
{
    sInstance.DriveAPState();
}

void ConnectivityManagerImpl::UpdateInternetConnectivityState(void)
{
    bool haveIPv4Conn      = false;
    bool haveIPv6Conn      = false;
    const bool hadIPv4Conn = mFlags.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity);
    const bool hadIPv6Conn = mFlags.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity);
    IPAddress addr;

    // If the WiFi station is currently in the connected state...
    if (mWiFiStationState == kWiFiStationState_Connected)
    {
        // Get the LwIP netif for the WiFi station interface.
        struct netif * netif = netif_list;

        // If the WiFi station interface is up...
        if (netif != NULL && netif_is_up(netif) && netif_is_link_up(netif))
        {
            // Check if a DNS server is currently configured.  If so...
            ip_addr_t dnsServerAddr = *dns_getserver(0);
            if (!ip_addr_isany_val(dnsServerAddr))
            {
                // If the station interface has been assigned an IPv4 address, and has
                // an IPv4 gateway, then presume that the device has IPv4 Internet
                // connectivity.
                if (!ip4_addr_isany_val(*netif_ip4_addr(netif)) && !ip4_addr_isany_val(*netif_ip4_gw(netif)))
                {
                    haveIPv4Conn = true;
                    // char addrStr[INET_ADDRSTRLEN];
                    // ip4addr_ntoa_r((const ip4_addr_t *) LwIP_GetIP(&xnetif[0]), addrStr, sizeof(addrStr));
                    // IPAddress::FromString(addrStr, addr);
                }

                // Search among the IPv6 addresses assigned to the interface for a Global Unicast
                // address (2000::/3) that is in the valid state.  If such an address is found...
                for (uint8_t i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++)
                {
                    if (ip6_addr_isglobal(netif_ip6_addr(netif, i)) && ip6_addr_isvalid(netif_ip6_addr_state(netif, i)))
                    {
                        // Determine if there is a default IPv6 router that is currently reachable
                        // via the station interface.  If so, presume for now that the device has
                        // IPv6 connectivity.
                        struct netif * found_if = nd6_find_route(IP6_ADDR_ANY6);
                        if (found_if && netif->num == found_if->num)
                        {
                            haveIPv6Conn = true;
                        }
                    }
                }
            }
        }
    }

    // If the internet connectivity state has changed...
    if (haveIPv4Conn != hadIPv4Conn || haveIPv6Conn != hadIPv6Conn)
    {
        // Update the current state.
        mFlags.Set(ConnectivityFlags::kHaveIPv4InternetConnectivity, haveIPv4Conn)
            .Set(ConnectivityFlags::kHaveIPv6InternetConnectivity, haveIPv6Conn);

        // Alert other components of the state change.
        ChipDeviceEvent event;
        event.Type                            = DeviceEventType::kInternetConnectivityChange;
        event.InternetConnectivityChange.IPv4 = GetConnectivityChange(hadIPv4Conn, haveIPv4Conn);
        event.InternetConnectivityChange.IPv6 = GetConnectivityChange(hadIPv6Conn, haveIPv6Conn);
        // addr.ToString(event.InternetConnectivityChange.address);
        PlatformMgr().PostEventOrDie(&event);

        if (haveIPv4Conn != hadIPv4Conn)
        {
            ChipLogProgress(DeviceLayer, "%s Internet connectivity %s", "IPv4", (haveIPv4Conn) ? "ESTABLISHED" : "LOST");
        }

        if (haveIPv6Conn != hadIPv6Conn)
        {
            ChipLogProgress(DeviceLayer, "%s Internet connectivity %s", "IPv6", (haveIPv6Conn) ? "ESTABLISHED" : "LOST");
        }
    }
}

void ConnectivityManagerImpl::OnStationIPv4AddressAvailable(void)
{
#if 0
    uint8_t * ip  = LwIP_GetIP(&xnetif[0]);
    uint8_t * gw  = LwIP_GetGW(&xnetif[0]);
    uint8_t * msk = LwIP_GetMASK(&xnetif[0]);
#if CHIP_PROGRESS_LOGGING
    {
        ChipLogProgress(DeviceLayer, "\n\r\tIP              => %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
        ChipLogProgress(DeviceLayer, "\n\r\tGW              => %d.%d.%d.%d\n\r", gw[0], gw[1], gw[2], gw[3]);
        ChipLogProgress(DeviceLayer, "\n\r\tmsk             => %d.%d.%d.%d\n\r", msk[0], msk[1], msk[2], msk[3]);
    }
#endif // CHIP_PROGRESS_LOGGING
#endif

    UpdateInternetConnectivityState();
    ChipLogProgress(DeviceLayer, "IPv4 address available on WiFi station interface");
    ChipDeviceEvent event;
    event.Type                           = DeviceEventType::kInterfaceIpAddressChanged;
    event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV4_Assigned;
    PlatformMgr().PostEventOrDie(&event);
}

void ConnectivityManagerImpl::OnStationIPv4AddressLost(void)
{
    ChipLogProgress(DeviceLayer, "IPv4 address lost on WiFi station interface");

    UpdateInternetConnectivityState();

    ChipDeviceEvent event;
    event.Type                           = DeviceEventType::kInterfaceIpAddressChanged;
    event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV4_Lost;
    PlatformMgr().PostEventOrDie(&event);
}

void ConnectivityManagerImpl::OnIPv6AddressAvailable(void)
{
#if 0
#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 1
#if LWIP_IPV6
    uint8_t * ipv6_0 = LwIP_GetIPv6_linklocal(&xnetif[0]);
    uint8_t * ipv6_1 = LwIP_GetIPv6_global(&xnetif[0]);
#endif
#endif
#if CHIP_PROGRESS_LOGGING
    {
#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 1
#if LWIP_IPV6
        ChipLogProgress(DeviceLayer,
                        "\n\r\tLink-local IPV6 => %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
                        ipv6_0[0], ipv6_0[1], ipv6_0[2], ipv6_0[3], ipv6_0[4], ipv6_0[5], ipv6_0[6], ipv6_0[7], ipv6_0[8],
                        ipv6_0[9], ipv6_0[10], ipv6_0[11], ipv6_0[12], ipv6_0[13], ipv6_0[14], ipv6_0[15]);
        ChipLogProgress(DeviceLayer,
                        "\n\r\tIPV6            => %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
                        ipv6_1[0], ipv6_1[1], ipv6_1[2], ipv6_1[3], ipv6_1[4], ipv6_1[5], ipv6_1[6], ipv6_1[7], ipv6_1[8],
                        ipv6_1[9], ipv6_1[10], ipv6_1[11], ipv6_1[12], ipv6_1[13], ipv6_1[14], ipv6_1[15]);
#endif
#endif
    }
#endif // CHIP_PROGRESS_LOGGING
#endif

    UpdateInternetConnectivityState();
    ChipLogProgress(DeviceLayer, "IPv6 address available on WiFi station interface");
    ChipDeviceEvent event;
    event.Type                           = DeviceEventType::kInterfaceIpAddressChanged;
    event.InterfaceIpAddressChanged.Type = InterfaceIpChangeType::kIpV6_Assigned;
    PlatformMgr().PostEventOrDie(&event);
}

void ConnectivityManagerImpl::IpConnectedEventNotify()
{
    const bool hadIPv4Conn = mFlags.Has(ConnectivityFlags::kHaveIPv4InternetConnectivity);
    const bool hadIPv6Conn = mFlags.Has(ConnectivityFlags::kHaveIPv6InternetConnectivity);

    if (hadIPv4Conn)
    {
        sInstance.OnStationIPv4AddressAvailable();
    }
    if (hadIPv6Conn)
    {
        sInstance.OnIPv6AddressAvailable();
    }
}

#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI

} // namespace DeviceLayer
} // namespace chip


text:
import React from 'react';
import { shallow } from 'enzyme';
import AreaSeries from '../../../src/components/AreaSeries/AreaSeries';
import Series from '../../../src/components/Series';

describe('<AreaSeries />', function ()  {
  it('renders a <Series />', function ()  {
    const wrapper = shallow(<AreaSeries id="mySeries" />);
    expect(wrapper).to.have.type(Series);
  });

  it('renders a <Series type="area" />', function () {
    const wrapper = shallow(<AreaSeries id="mySeries" />);
    expect(wrapper).to.have.prop('type').equal('area');
  });

  it('passes other props through to <Series />', function () {
    const wrapper = shallow(<AreaSeries id="myOtherSeries" data={[1, 2, 3, 4]} />);
    expect(wrapper).to.have.prop('data').eql([1, 2, 3, 4]);
  });
});

redpajama_set_name: RedPajamaGithub


text:
package com.socrata.pg.server

class SoQLStringFunctionsTest extends SoQLTest {

  test("select *") {
    compareSoqlResult("select make, name order by make, name", "result.json")
  }

  test("c < x") {
    compareSoqlResult("select make, name where name < 'Buzz' order by name", "where-str-lt.json")
  }

  test("c <= x") {
    compareSoqlResult("select make, name where name <= 'Buzz' order by name", "where-str-le.json")
  }

  test("c = x") {
    compareSoqlResult("select make, name where make = 'APCO' order by name", "where-str-eq.json")
  }

  test("c != x") {
    compareSoqlResult("select make, name where make != 'APCO' order by name", "where-str-ne.json")
  }

  test("c > x") {
    compareSoqlResult("select make, name where name > 'Sprint Evo' order by name", "where-str-gt.json")
  }

  test("c >= x") {
    compareSoqlResult("select make, name where name >= 'Sprint Evo' order by name", "where-str-ge.json")
  }

  test("lower(c)") {
    compareSoqlResult("select make, lower(name) where name = 'Atlas'", "where-str-lower.json")
  }

  test("upper(c)") {
    compareSoqlResult("select make, upper(name) where name = 'Atlas'", "where-str-upper.json")
  }

  test("starts_with(c, x)") {
    compareSoqlResult("select make, name where starts_with(make, 'Skyw') order by name", "where-str-starts_with.json")
  }

  test("contains(c, x)") {
    compareSoqlResult("select make, name where contains(name, 'arm') order by name", "where-str-contains.json")
  }

  test("substring, length, split_part") {
    compareSoqlResult("select make, name, substring(make, 3, 2) as substr, length(make) as len, split_part(name, ' ', 2) as split_part, length(make)=4 as len_eq_4 where len >=4 order by make, name limit 5",
        "substring.json")
  }
}


text:
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Benchmarking
{
    using System;

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public sealed class BenchmarkAttribute : Attribute
    {
        public string DisplayName { get; set; }
    }
}


text:
#include "AccelerationMotion.h"

#include <SimTKsimbody.h>

using namespace OpenSim;

class PrescribedAccelerationMotionImplementation
        : public SimTK::Motion::Custom::Implementation {
public:
    PrescribedAccelerationMotionImplementation(
            const SimTK::MobilizedBodyIndex& mobodIdx,
            const AccelerationMotion& accel)
            : m_mobodIdx(mobodIdx), m_accel(accel) {}
    SimTK::Motion::Level getLevel(const SimTK::State&) const override {
        return SimTK::Motion::Level::Acceleration;
    }
    void calcPrescribedAcceleration(
            const SimTK::State& s, int nu, SimTK::Real* udot) const override {
        std::copy_n(m_accel.getUDot(s, m_mobodIdx).getContiguousScalarData(),
                nu, udot);
    }

private:
    SimTK::MobilizedBodyIndex m_mobodIdx;
    const AccelerationMotion& m_accel;
};

class PrescribedAccelerationMotion : public SimTK::Motion::Custom {
public:
    PrescribedAccelerationMotion(
            const AccelerationMotion& accel, SimTK::MobilizedBody& mobod)
            : Motion::Custom(
                      mobod, new PrescribedAccelerationMotionImplementation(
                                     mobod, accel)) {}
};

void AccelerationMotion::setUDot(
        SimTK::State& state, const SimTK::Vector& fullUDot) const {

    OPENSIM_THROW_IF(fullUDot.size() != state.getNU(), Exception,
            "Incorrect size for fullUDot.");

    const auto& matter = getSystem().getMatterSubsystem();
    const auto& defaultSub = getSystem().getDefaultSubsystem();
    int offset = 0;
    for (int i = 0; i < matter.getNumBodies(); ++i) {
        auto& mobod = matter.getMobilizedBody(SimTK::MobilizedBodyIndex(i));
        int nu = mobod.getNumU(state);
        auto& value = defaultSub.updDiscreteVariable(state, m_dvIndices[i]);
        value.updValue<SimTK::Vector>() = fullUDot(offset, nu);
        offset += nu;
    }
}

const SimTK::Vector& AccelerationMotion::getUDot(
        const SimTK::State& state, SimTK::MobilizedBodyIndex mobodIdx) const {
    return getSystem()
            .getDefaultSubsystem()
            .getDiscreteVariable(state, m_dvIndices[mobodIdx])
            .getValue<SimTK::Vector>();
}

void AccelerationMotion::setEnabled(
        SimTK::State& state, bool enabled) const {
    for (auto& motion : m_motions) {
        if (enabled) {
            motion.enable(state);
        } else {
            motion.disable(state);
        }
    }
}

void AccelerationMotion::extendAddToSystem(
        SimTK::MultibodySystem& system) const {
    Super::extendAddToSystem(system);
    m_motions.clear();
    auto& matter = system.updMatterSubsystem();
    for (int i = 0; i < matter.getNumBodies(); ++i) {
        auto& mobod = matter.updMobilizedBody(SimTK::MobilizedBodyIndex(i));
        m_motions.push_back(PrescribedAccelerationMotion(*this, mobod));
        m_motions.back().setDisabledByDefault(true);
    }
}

void AccelerationMotion::extendRealizeTopology(SimTK::State& state) const {
    Super::extendRealizeTopology(state);
    const auto& matter = getSystem().getMatterSubsystem();
    const auto& defaultSub = getSystem().getDefaultSubsystem();
    for (int i = 0; i < matter.getNumBodies(); ++i) {
        m_dvIndices.push_back(defaultSub.allocateDiscreteVariable(state,
                SimTK::Stage::Acceleration, new SimTK::Value<SimTK::Vector>()));
    }
}


text:
using System.Runtime.InteropServices;

namespace TerraFX.Graphics.Advanced;

/// The options used when creating a graphics pipeline signature.
[StructLayout(LayoutKind.Auto)]
public unsafe struct GraphicsPipelineSignatureCreateOptions
{
    /// The pipeline inputs for the pipeline signature.
    public UnmanagedArray<GraphicsPipelineInput> Inputs;

    /// The pipeline resources for the pipeline signature.
    public UnmanagedArray<GraphicsPipelineResource> Resources;

    /// <c>true</c> if the graphics pipeline signature should take ownership of <see cref="Inputs" />; otherwise, <c>false</c>.
    public bool TakeInputsOwnership;

    /// <c>true</c> if the graphics pipeline signature should take ownership of <see cref="Resources" />; otherwise, <c>false</c>.
    public bool TakeResourcesOwnership;
}


text:
package com.google.security.zynamics.binnavi.Gui.GraphWindows.Undo;

import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;
import com.google.security.zynamics.zylib.general.Pair;
import com.google.security.zynamics.zylib.gui.jtree.IconNode;

import java.util.ArrayList;

import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 * Node class for representing selection state snapshots in the selection history chooser tree.
 *
 * TODO: Separate root node from real snapshot nodes.
 */
public final class CSelectionHistoryTreeNode extends IconNode {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = -7628040230460801915L;

  /**
   * Icon shown for root nodes.
   */
  private static final ImageIcon ICON_ROOT =
      new ImageIcon(CMain.class.getResource("data/undoselectionchoosericons/root.png"));

  /**
   * Icon shown if none of the nodes of the represented selection state are selected.
   */
  private static final ImageIcon ICON_ALL_UNSELECTED_GRAPHNODES = new ImageIcon(CMain.class
      .getResource("data/undoselectionchoosericons/graph_selection_folder_all_unselected.png"));

  /**
   * Icon shown if all nodes of the represented selection state are selected.
   */
  private static final ImageIcon ICON_ALL_SELECTED_GRAPHNODES = new ImageIcon(CMain.class
      .getResource("data/undoselectionchoosericons/graph_selection_folder_open.png"));

  /**
   * Icon shown if all nodes of the represented selection state are invisible.
   */
  private static final
      ImageIcon ICON_ALL_INVISIBLE_GRAPHNODES = new ImageIcon(CMain.class.getResource(
          "data/undoselectionchoosericons/graph_selection_folder_all_unselected_gray.png"));

  /**
   * Icon shown if all nodes of the represented selection are unselected but some are invisible.
   */
  private static final ImageIcon ICON_ALL_UNSELECTED_SOME_VISIBLE_SOME_INVISIBLE_GRAPHNODES =
      new ImageIcon(CMain.class.getResource(
          "data/undoselectionchoosericons/graph_selection_folder_all_unselected_halfgray.png"));

  /**
   * Icon shown if all nodes of the represented selection are visible but only some are selected.
   */
  private static final ImageIcon ICON_ALL_VISIBLE_SOME_SELECTED_SOME_UNSELECTED_GRAPHNODES =
      new ImageIcon(CMain.class.getResource(
          "data/undoselectionchoosericons/graph_selection_folder_some_unselected.png"));

  /**
   * Icon shown if some nodes of the represented selection are visible and some are selected.
   */
  private static final ImageIcon ICON_SOME_SELECTED_SOME_VISIBLE_SOME_INVISIBLE_GRAPHNODES =
      new ImageIcon(CMain.class.getResource(
          "data/undoselectionchoosericons/graph_selection_folder_some_unselected_halfgray.png"));

  /**
   * Icon shown for selection states without nodes.
   */
  private static final ImageIcon ICON_EMPTY_FOLDER = new ImageIcon(CMain.class.getResource(
      "data/undoselectionchoosericons/graph_selection_folder_empty.png"));

  /**
   * Icon shown if no other icon criterium matches.
   */
  private static final ImageIcon ICON_DUMMY = new ImageIcon(CMain.class.getResource(
      "data/undoselectionchoosericons/graph_selection_folder_closed.png"));

  /**
   * Selection snapshot represented by this node.
   */
  private final CSelectionSnapshot m_snapshot;

  /**
   * True, if the node is a root node. False, otherwise.
   */
  private final boolean m_root;

  /**
   * Creates a new node that represents a snapshot.
   *
   * @param snapshot Snapshot represented by the node.
   * @param stateIndex Index of the snapshot.
   */
  public CSelectionHistoryTreeNode(final CSelectionSnapshot snapshot, final int stateIndex) {
    super(new CSelectionHistoryNodeWrapper(snapshot, stateIndex));

    m_snapshot = snapshot;
    m_root = false;
  }

  /**
   * Creates a new root node.
   *
   * @param name Text shown in the root node.
   */
  public CSelectionHistoryTreeNode(final String name) {
    super(name);

    m_snapshot = new CSelectionSnapshot(new ArrayList<NaviNode>());
    m_root = true;
  }

  /**
   * Returns an icon depending on the selection and visibility state of the nodes in a selection.
   *
   * @param countAll Number of nodes.
   * @param selected Number of selected nodes.
   * @param unselected Number of unselected nodes.
   * @param invisible Number of invisible nodes.
   *
   * @return The appropriate icon.
   */
  private static Icon getIcon(
      final int countAll, final int selected, final int unselected, final int invisible) {
    if (countAll == 0) {
      return ICON_EMPTY_FOLDER;
    } else if (invisible == countAll) {
      return ICON_ALL_INVISIBLE_GRAPHNODES;
    } else if (selected == countAll) {
      return ICON_ALL_SELECTED_GRAPHNODES;
    } else if (unselected == countAll && invisible == 0) {
      return ICON_ALL_UNSELECTED_GRAPHNODES;
    } else if (selected == 0) {
      return ICON_ALL_UNSELECTED_SOME_VISIBLE_SOME_INVISIBLE_GRAPHNODES;
    } else if (invisible == 0) {
      return ICON_ALL_VISIBLE_SOME_SELECTED_SOME_UNSELECTED_GRAPHNODES;
    } else if (invisible != 0 && selected != 0) {
      return ICON_SOME_SELECTED_SOME_VISIBLE_SOME_INVISIBLE_GRAPHNODES;
    }

    return ICON_DUMMY;
  }

  @Override
  public Icon getIcon() {
    if (m_root) {
      return ICON_ROOT;
    }

    final Pair<Integer, Integer> result = CNodeTypeCounter.count(m_snapshot.getSelection());

    final int countAll = m_snapshot.getSelection().size();
    final int selected = result.first();
    final int unselected = countAll - selected;
    final int invisible = result.second();

    return getIcon(countAll, selected, unselected, invisible);
  }

  /**
   * Returns the snapshot represented by the node.
   *
   * @return The snapshot represented by the node.
   */
  public CSelectionSnapshot getSnapshot() {
    return m_snapshot;
  }
}


text:
class GlobalProjectsController < ApplicationController
  layout 'global_projects'

  def index
    q = params[:q]
    published_projects = Project.published.includes(:figures, :owner, recipe: :states, note: :note_cards)

    if q.present?
      query = q.force_encoding 'utf-8'
      @projects = published_projects.ransack(draft_cont_all: query.split(/\p{space}+/)).result.page(params[:page])
      @is_searching = true
      @query = query

    elsif !q.nil?
      @projects = published_projects.page(params[:page]).order('updated_at DESC')
      @is_searching = true

    else
      @projects = published_projects.page(params[:page]).order('updated_at DESC')
      @featured_project_groups = Feature.projects.length >= 3 ? view_context.featured_project_groups : []
      @featured_groups = Group.includes(:members, :projects).order(projects_count: :desc).limit(3)
      @is_searching = false
    end

    selected_tags_length = 30
    @all_tags = Tag.where(taggable_type: 'Project').where.not(name: '').group(:name).order('COUNT(id) DESC').pluck(:name)
    @selected_tags = view_context.selected_tags @all_tags, selected_tags_length

    @selected_tools = view_context.selected_tools
    @selected_materials = view_context.selected_materials
  end
end


text:
{#
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
 #
 # http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-#}
{% extends "manage_organization_base.html" %}

{% set user = request.user %}
{% set title = gettext("Organization projects") %}

{% set active_tab = 'projects' %}

{% block title %}{% trans organization_name=organization.name %}Manage '{{ organization_name }}' projects{% endtrans %}{% endblock %}

{% block main %}

{% trans project_count=active_projects|length %}Projects ({{ project_count }}){% endtrans %}

    {% set user_has_two_factor = request.user.has_two_factor %}
    {% for project in active_projects %}
    {% set release = project.releases[0] if project.releases else None %}

{{ project.name }}
            {% if project.organization %}

              {{ project.organization.name }}

            {% endif %}
            {% if (
              request.registry.settings["warehouse.two_factor_requirement.enabled"]
              and project.owners_require_2fa
            ) %}

              {% trans %}2FA Required{% endtrans %}

            {% elif (
              request.registry.settings["warehouse.two_factor_mandate.enabled"]
              and project.pypi_mandates_2fa
            ) %}

              {% trans %}Critical Project{% endtrans %}

              {% trans %}2FA Mandated{% endtrans %}

            {% elif (
              request.registry.settings["warehouse.two_factor_mandate.available"]
              and project.pypi_mandates_2fa
            ) %}

              {% trans %}Critical Project{% endtrans %}

            {% endif %}
            {% if project.name in projects_sole_owned %}
            {% trans %}Sole owner{% endtrans %}
            {% endif %}

          {% if release %}

            {% trans release_date=humanize(release.created) %}Last released {{ release_date }}{% endtrans %}

            {{ release.summary }}

          {% else %}

            {% trans creation_date=humanize(project.created) %}Created {{ creation_date }}{% endtrans %}

          {% endif %}

          {% if project.name in projects_owned %}
            {% if (
              not user_has_two_factor
              and project.name in projects_requiring_2fa
              and project.pypi_mandates_2fa
              and request.registry.settings["warehouse.two_factor_mandate.enabled"]
            ) %}
            {# Show 2FA mandated button #}
            {% trans %}2FA Mandated{% endtrans %}
            {% elif (
              not user_has_two_factor
              and project.name in projects_requiring_2fa
              and project.owners_require_2fa
              and request.registry.settings["warehouse.two_factor_requirement.enabled"]
            ) %}
            {# Show 2FA required button #}
            {% trans %}2FA Required{% endtrans %}
            {% else %}
            {# Show manage button #}
            {% trans %}Manage{% endtrans %}
            {% endif %}
          {% else %}
          {# Show disabled button #}
          <button class="button button--primary" disabled title="{% trans %}You are not an owner of this project{% endtrans %}">
            {% trans %}Manage{% endtrans %}
          </button>
          {% endif %}
          {% if project.releases %}
          {% trans %}View{% endtrans %}
          {% else %}
          <button class="button" disabled title="{% trans %}This project has no releases{% endtrans %}" >
            {% trans %}View{% endtrans %}
          </button>
          {% endif %}

    {% else %}

{% trans href='https://packaging.python.org/' %}You have not added any projects to your organization, yet. Get started by adding a project that you own using the form below. To learn how to create a new project, visit the Python Packaging User Guide{% endtrans %}

    {% endfor %}

  {% if request.has_permission("manage:organization") %}

  {{ form_error_anchor(add_organization_project_form) }}

{% trans %}Add project to organization{% endtrans %}

    <form class="radio-toggle-form" method="POST">
      <input name="csrf_token" type="hidden" value="{{ request.session.get_csrf_token() }}">
      {{ form_errors(add_organization_project_form) }}
      {# New or existing? radio buttons should be siblings of div.form-group below. #}

          {% trans %}New or existing project?{% endtrans %}

        {% for subfield in add_organization_project_form.add_existing_project %}
        {{ subfield(**{"data-target": ".radio-toggle-" + loop.index|string}) }}
        {{ subfield.label }}
        {% endfor %}

          {{ field_errors(add_organization_project_form.add_existing_project) }}

          {% trans %}Transfer an existing project that you own, or create and add a new project to the organization.{% endtrans %}

      {# end radio buttons #}

          {% trans %}Name of existing project{% endtrans %}
          {% trans %}(required){% endtrans %}

        {% set no_existing_projects = add_organization_project_form.existing_project_name.choices|length <= 1 %}
        {{ add_organization_project_form.existing_project_name(class_="form-group__field", disabled=no_existing_projects, title=gettext("You do not own any projects that you can add to this organization.") if no_existing_projects else "", **{"aria-describedby":"existing-project-name-errors"}) }}

          {{ field_errors(add_organization_project_form.existing_project_name) }}

          {% trans trimmed %}
          Owners of this organization can transfer a project that they own to this organization if the project has not been added to another organization. A project that has been added to another organization can be transferred from the project settings page.
          {% endtrans %}

      <input value="{% trans %}Transfer existing project{% endtrans %}" class="button button--primary radio-toggle radio-toggle-1" type="submit">

          {% trans %}Name of new project{% endtrans %}
          {% trans %}(required){% endtrans %}

        {{ add_organization_project_form.new_project_name(class_="form-group__field", **{"aria-describedby":"new-project-name-errors"}) }}

          {{ field_errors(add_organization_project_form.new_project_name) }}

          {% trans trimmed %}
          Owners of this organization can create an empty project and add it to the organization.
          {% endtrans %}

      <input value="{% trans %}Create and add new project{% endtrans %}" class="button button--primary radio-toggle radio-toggle-2" type="submit">
    </form>

  {% endif %}
{% endblock %}


text:
Create cli utility for node.js easily, including:
 - Full command/argument parser
 - Consistant inputs and arguments
 - Auto help generator
 - Progress and table generators

## Getting Started
Install the module with: `npm install clifier`

```javascript
var cli = require('clifier');

cli
    .name('testcommand')
    .version('0.0.1')
    .description('Hello command !');

cli
    .command('testcommand', 'description')
    .input('name', '[a-z]+')
    .argument('-a1, --arg1', 'foo', 'defaultValue', function(value){
        return "filtered value: " + value;
    })
    .argument('-a2, --arg2', 'bar')
    .action((name, arg1, arg2) => {
        cli.log(arg1);
        cli.success('Hello '+name);
        cli.warning("What is that?");
        cli.error(arg2);

        cli.table(['header', 1, 2], [['Content', 1, 2]]);

        var progress = cli.progress("Installing something", 100),
            i        = 0,
            interval = function () {
                i++;
                progress.tick(1);

                if (i == 100) {
                    progress.stop();
                    cli.end();
                } else {
                    setTimeout(interval, 10);
                }
            }

        interval();
    });

cli.run();
```

## API

#### `require('clifier')`

return a `Cli` instance.

### Cli API

#### `.version(string) : Cli`

Set the version of your cli utility

#### `.name(string) : Cli`

Set the name of your cli utility

#### `.description(string) : Cli`

Set the description of your cli utility

#### `.write(string)`

Write something on the stdout

#### `.style(content, style)`

Transform content with asked style. Need to be send to `write`.

#### `.success(string)`

Write a success text on the stdout

#### `.warning(string)`

Write a warning text on the stdout

#### `.error(string)`

Write an error text on the stderr

#### `.log(string)`

Write a log text on the stdout if verbose enabled

#### `.command(name, description) : Command`

Create a new command with name and description.

### Command API

#### `.input(name, validator) : Command`

Add an input to the command.
- **name** (string) : name of the input
- **validator** (string) : RegExp to validate the input

#### `.argument(name, description, defaultValue, filter) : Command`

Add an argument to the command.
- **name** (string) : name of the argument *(--arg, -arg)*
- **description** (string) : description of the argument
- **defaultValue** (mixed) : default value of the argument if empty
- **filter** (function) : filter function for the argument

#### `.action(function(...inputs, ...arguments)) : Command`

Action of the command when executed. Function will receive all inputs and arguments in define orders as parameters.

## License

See `LICENSE` file


text:
package com.primalpond.hunt;

import org.json.JSONException;
import org.json.JSONObject;

public interface JSONable {
	public JSONObject toJSON() throws JSONException;
}


text:
require 'volt/page/bindings/base_binding'
require 'volt/page/template_renderer'
require 'volt/page/bindings/view_binding/grouped_controllers'
require 'volt/page/bindings/view_binding/view_lookup_for_path'
require 'volt/page/bindings/view_binding/controller_handler'

module Volt
  class ViewBinding < BaseBinding
    # @param [String]     binding_in_path is the path this binding was rendered from.  Used to
    #                     lookup paths in ViewLookupForPath
    # @param [String|nil] content_template_path is the path to the template for the content
    #                     provided in the tag.
    def initialize(volt_app, target, context, binding_name, binding_in_path, getter, content_template_path = nil)
      super(volt_app, target, context, binding_name)

      @content_template_path = content_template_path

      # Setup the view lookup helper
      @view_lookup = Volt::ViewLookupForPath.new(page, binding_in_path)

      @current_template = nil

      # Run the initial render
      @computation      = lambda do
        # Don't try to render if this has been removed
        if @context
          # Render
          update(*@context.instance_eval(&getter))
        end
      end.watch!
    end

    # update is called when the path string changes.
    def update(path, section_or_arguments = nil, options = {})
      Computation.run_without_tracking do
        @options = options

        # A blank path needs to load a missing template, otherwise it tries to load
        # the same template.
        path     = path.blank? ? '---missing---' : path

        section    = nil
        @arguments = nil

        if section_or_arguments.is_a?(String)
          # Render this as a section
          section = section_or_arguments
        else
          # Use the value passed in as the default arguments
          @arguments = section_or_arguments

          # Include content_template_path in attrs
          if @content_template_path
            @arguments ||= {}
            @arguments[:content_template_path] = @content_template_path
            @arguments[:content_controller] = @context
          end
        end

        # Sometimes we want multiple template bindings to share the same controller (usually
        # when displaying a :Title and a :Body), this instance tracks those.
        if @options && (controller_group = @options[:controller_group])
          # Setup the grouped controller for the first time.
          @grouped_controller = GroupedControllers.new(controller_group)
        end

        # If a controller is already starting, but not yet started, then remove it.
        remove_starting_controller

        full_path, controller_path = @view_lookup.path_for_template(path, section)

        unless full_path
          # if we don't have a full path, then we have a missing template
          render_next_template(full_path, path)
          return
        end

        @starting_controller_handler, generated_new, chain_stopped = create_controller_handler(full_path, controller_path)

        # Check if chain was stopped when the action ran
        if chain_stopped
          # An action stopped the chain.  When this happens, we stop running here.
          remove_starting_controller
        else
          # None of the actions stopped the chain
          # Wait until the controller is loaded before we actually render.
          @waiting_for_load = -> { @starting_controller_handler.controller.loaded? }.watch_until!(true) do
            render_next_template(full_path, path)
          end

          queue_clear_grouped_controller
        end
      end
    end

    # Called when the next template is ready to render
    def render_next_template(full_path, path)
      remove_current_controller_and_template

      # Switch the current template
      @current_controller_handler = @starting_controller_handler
      @starting_controller_handler = nil

      # Also track the current controller directly
      @controller = @current_controller_handler.controller if full_path

      render_template(full_path || path)
    rescue => e
      Volt.logger.error("Error during render of template at #{path}: #{e.inspect}")
      Volt.logger.error(e.backtrace)
    end

    def stop_waiting_for_load
      if @waiting_for_load
        @waiting_for_load.stop
        @waiting_for_load = nil
      end
    end

    # On the next tick, we clear the grouped controller so that any changes to template paths
    # will create a new controller and trigger the action.
    def queue_clear_grouped_controller
      if Volt.in_browser?
        # In the browser, we want to keep a grouped controller around during a single run
        # of the event loop.  To make that happen, we clear it on the next tick.
        `setImmediate(function() {`
        clear_grouped_controller
        `});`
      else
        # For the backend, clear it immediately
        clear_grouped_controller
      end
    end

    def clear_grouped_controller
      if @grouped_controller
        @grouped_controller.clear
        @grouped_controller = nil
      end
    end

    def remove_current_controller_and_template
      # Remove existing controller and template and call _removed
      if @current_controller_handler
        @current_controller_handler.call_action('before', 'remove')
      end

      if @current_template
        @current_template.remove
        @current_template = nil
      end

      if @current_controller_handler
        @current_controller_handler.call_action('after', 'remove')
      end

      if @grouped_controller && @current_controller_handler
        # Remove a reference for the controller in the group.
        @grouped_controller.remove(@current_controller_handler.controller.class)
      end

      @controller = nil
      @current_controller_handler = nil
    end

    def remove_starting_controller
      # Clear any previously running wait for loads.  This is for when the path changes
      # before the view actually renders.
      stop_waiting_for_load

      if @starting_controller_handler
        # Only call the after_..._removed because the dom never loaded.
        @starting_controller_handler.call_action('after', 'removed')
        @starting_controller_handler = nil
      end
    end

    # Create controller handler loads up a controller inside of the controller handler for the paths
    def create_controller_handler(full_path, controller_path)
      # If arguments is nil, then an blank SubContext will be created
      args = [SubContext.new(@arguments, nil, true)]

      # get the controller class and action
      controller_class, action = ControllerHandler.get_controller_and_action(controller_path)

      generated_new = false
      new_controller = proc do
        # Mark that we needed to generate a new controller instance (not reused
        # from the group)
        generated_new = true
        # Setup the controller
        controller_class.new(@volt_app, *args)
      end

      # Fetch grouped controllers if we're grouping
      if @grouped_controller
        # Find the controller in the group, or create it
        controller = @grouped_controller.lookup_or_create(controller_class, &new_controller)
      else
        # Just create the controller
        controller = new_controller.call
      end

      handler = ControllerHandler.fetch(controller, action)

      if generated_new
        # Call the action
        stopped = handler.call_action

        controller.instance_variable_set('@chain_stopped', true) if stopped
      else
        stopped = controller.instance_variable_get('@chain_stopped')
      end

      [handler, generated_new, stopped]
    end

    # The context for templates can be either a controller, or the original context.
    def render_template(full_path, path)
      @current_template = TemplateRenderer.new(@volt_app, @target, @controller, @binding_name, full_path, path)

      call_ready
    end

    def call_ready
      if @controller
        # Set the current section on the controller if it wants so it can manipulate
        # the dom if needed.
        # Only assign sections for action's, so we don't get AttributeSections bound
        # also.
        if @controller.respond_to?(:section=)
          dom_section = @current_template.dom_section

          # Only assign dom sections that can be manipulated via the dom (so not the title for example)
          @controller.section = dom_section unless dom_section.is_a?(Volt::AttributeSection)
        end

        # Call the ready callback on the controller
        @current_controller_handler.call_action(nil, 'ready')
      end
    end

    # Called when the binding is removed from the page
    def remove
      # Cleanup any starting controller
      remove_starting_controller

      @computation.stop
      @computation = nil

      remove_current_controller_and_template

      super
    end
  end
end


text:
<Type Name="NodeBeginContact2DEventArgs" FullName="Urho.NodeBeginContact2DEventArgs">
  <TypeSignature Language="C#" Value="public struct NodeBeginContact2DEventArgs" />
  <TypeSignature Language="ILAsm" Value=".class public sequential ansi sealed beforefieldinit NodeBeginContact2DEventArgs extends System.ValueType" />
  <AssemblyInfo>
    <AssemblyName>Urho</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.ValueType</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="Body">
      <MemberSignature Language="C#" Value="public Urho.Urho2D.RigidBody2D Body { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Urho.Urho2D.RigidBody2D Body" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.Urho2D.RigidBody2D</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Contact">
      <MemberSignature Language="C#" Value="public IntPtr Contact { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance native int Contact" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.IntPtr</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OtherBody">
      <MemberSignature Language="C#" Value="public Urho.Urho2D.RigidBody2D OtherBody { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Urho.Urho2D.RigidBody2D OtherBody" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.Urho2D.RigidBody2D</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OtherNode">
      <MemberSignature Language="C#" Value="public Urho.Node OtherNode { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Urho.Node OtherNode" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Urho.Node</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
#ifndef __GBSIM_USB_H
#define __GBSIM_USB_H

#include <usbg/usbg.h>

int gadget_create(usbg_state **, usbg_gadget **);
int gadget_enable(usbg_gadget *);
void gadget_cleanup(usbg_state *, usbg_gadget *);

int functionfs_init(void);
int functionfs_loop(void);
int functionfs_cleanup(void);
void cleanup_endpoint(int, char *);

int gbsim_usb_init(void);
void gbsim_usb_cleanup(void);

#endif


text:
#include "../../tests.h"
#include "runnable/CustomAttribute.h"

class CustomAttributeTests : public cTestObject
{
public:
    virtual void test();
    virtual cString getName() { return __FILE__; }

private:
    void create_custom_attrib_with_args(void);
};

// Instance test object
CustomAttributeTests g_global;

void CustomAttributeTests::create_custom_attrib_with_args(void)
{
    cString caName = "CallingConvention";
    CustomAttribute cattrib = CustomAttribute(caName);
    ASSERT(caName == cattrib.getName());

    cString caStringName =  "my_string";
    cString caStringValue = "This is my string";
    CustomAttributeArgumentPtr caStringPtr = cattrib.addArgument(caStringName, caStringValue);
    ASSERT(caStringValue == caStringPtr->getStringValue());

    cString caSignedIntegerName =  "my_signed_int";
    int caSignedIntegerValue = -5;
    CustomAttributeArgumentPtr caSignedIntegerPtr = cattrib.addArgument(caSignedIntegerName, caSignedIntegerValue);
    ASSERT(caSignedIntegerValue == caSignedIntegerPtr->getSignedIntegerValue());

    cString caUnsignedIntegerName =  "my_unsigned_int";
    unsigned int caUnsignedIntegerValue = 5;
    CustomAttributeArgumentPtr caUnsignedIntegerPtr = cattrib.addArgument(caUnsignedIntegerName, caUnsignedIntegerValue);
    ASSERT(caUnsignedIntegerValue == caUnsignedIntegerPtr->getUnsignedIntegerValue());

    cString caBoolName =  "my_bool";
    bool caBoolValue = true;
    CustomAttributeArgumentPtr caBoolPtr = cattrib.addArgument(caBoolName, caBoolValue);
    ASSERT(caBoolValue == caBoolPtr->getBoolValue());

    TESTS_LOG(cattrib << endl);
}

void CustomAttributeTests::test(void)
{
    create_custom_attrib_with_args();
}


text:
package edu.teco.dnd.blocks;

import java.io.Serializable;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *

 * An Output for a {@link FunctionBlock}. A {@link FunctionBlock} can use this to provide data for other FunctionBlock's
 * {@link Input}s. To define an Output simply define a non-static field of this type. It will be initialized by the
 * wrapper code, so you should never assign the field directly. You should also never call
 * {@link #setTarget(OutputTarget)} manually.
 *

 *
 *

 * To send a value simply call {@link #setValue(Serializable)} with the value.
 *

 *
 *

 * Output is thread-safe.
 *

 */
public class Output<T extends Serializable> implements Serializable {
	private static final Logger LOGGER = LogManager.getLogger(Output.class);

	private static final long serialVersionUID = 8652366978996728530L;

	private OutputTarget<? super T> target = null;

	/**
	 * Sends a value using this output.
	 *
	 * @param value
	 *            the value to send
	 */
	public void setValue(final T value) {
		if (target == null) {
			LOGGER.warn("called setValue before any targets were set up.");
		} else {
			target.setValue(value);
		}
	}

	/**
	 * Sets the target for this Output. The target can only be set once.
	 *
	 * @param target
	 *            the new target for this Output
	 * @return true if the target was set successfully, false otherwise
	 */
	public synchronized boolean setTarget(final OutputTarget<? super T> target) {
		if (this.target != null) {
			return false;
		}
		this.target = target;
		return true;
	}
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Drawing;
using System.IO;

namespace Wexflow.NetCore.Tests
{
    [TestClass]
    public class ImagesCropper
    {
        private static readonly string Dest1 = @"C:\WexflowTesting\ImagesCropperDest\image1.jpg";
        private static readonly string Dest2 = @"C:\WexflowTesting\ImagesCropperDest\image2.jpg";
        private static readonly string Dest3 = @"C:\WexflowTesting\ImagesCropperDest\image3.jpg";

        [TestInitialize]
        public void TestInitialize()
        {
            if(File.Exists(Dest1)) File.Delete(Dest1);
            if (File.Exists(Dest2)) File.Delete(Dest2);
            if (File.Exists(Dest3)) File.Delete(Dest3);
        }

        [TestCleanup]
        public void TestCleanup()
        {
            if (File.Exists(Dest1)) File.Delete(Dest1);
            if (File.Exists(Dest2)) File.Delete(Dest2);
            if (File.Exists(Dest3)) File.Delete(Dest3);
        }

        [TestMethod]
        public void ImagesCropperTest()
        {
            Assert.AreEqual(false, File.Exists(Dest1));
            Assert.AreEqual(false, File.Exists(Dest2));
            Assert.AreEqual(false, File.Exists(Dest3));
            Helper.StartWorkflow(74);
            Assert.AreEqual(true, File.Exists(Dest1));
            Assert.AreEqual(true, File.Exists(Dest2));
            Assert.AreEqual(true, File.Exists(Dest3));

            // Checking the image size
            CheckImageSize(Dest1);
            CheckImageSize(Dest2);
            CheckImageSize(Dest3);
        }

        private void CheckImageSize(string path)
        {
            using (Image image = Image.FromFile(path))
            {
                Assert.AreEqual(512, image.Width);
                Assert.AreEqual(384, image.Height);
            }
        }

    }
}


text:
package com.sissi.pipeline.in.presence.init;

import com.sissi.context.JID;
import com.sissi.context.JIDContext;
import com.sissi.pipeline.in.ProxyProcessor;
import com.sissi.protocol.Protocol;
import com.sissi.protocol.presence.Presence;

/**
 * 当前JID被订阅者(To)所有资源出席通知
 *
 * @author kim 2014年1月21日
 */
public class PresenceInit4SelfsProcessor extends ProxyProcessor {

	@Override
	public boolean input(JIDContext context, Protocol protocol) {
		return this.writePresence(protocol.cast(Presence.class).clone(), context);
	}

	private boolean writePresence(Presence presence, JIDContext context) {
		for (JID resource : super.resources(context.jid())) {
			context.write(new Presence().setFrom(resource).clauses(super.findOne(resource, true).status().clauses()), true);
		}
		return true;
	}
}


text:
package org.apache.syncope.core.persistence.beans;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.apache.syncope.common.to.RoleTO;
import org.apache.syncope.common.to.UserTO;
import org.apache.syncope.core.persistence.validation.entity.SyncTaskCheck;
import org.apache.syncope.core.util.XMLSerializer;

@Entity
@SyncTaskCheck
public class SyncTask extends SchedTask {

    private static final long serialVersionUID = -4141057723006682562L;

    /**
     * ExternalResource to which the sync happens.
     */
    @ManyToOne
    private ExternalResource resource;

    @Lob
    private String userTemplate;

    @Lob
    private String roleTemplate;

    @Basic
    @Min(0)
    @Max(1)
    private Integer performCreate;

    @Basic
    @Min(0)
    @Max(1)
    private Integer performUpdate;

    @Basic
    @Min(0)
    @Max(1)
    private Integer performDelete;

    @Basic
    @Min(0)
    @Max(1)
    private Integer syncStatus;

    @Basic
    @Min(0)
    @Max(1)
    private Integer fullReconciliation;

    private String actionsClassName;

    /**
     * Default constructor.
     */
    public SyncTask() {
        super();

        super.setJobClassName("org.apache.syncope.core.sync.impl.SyncJob");
    }

    @Override
    public void setJobClassName(final String jobClassName) {
        // fixed to SyncJob, cannot be changed
    }

    public ExternalResource getResource() {
        return resource;
    }

    public void setResource(ExternalResource resource) {
        this.resource = resource;
    }

    public UserTO getUserTemplate() {
        return userTemplate == null
                ? new UserTO()
                : XMLSerializer.<UserTO>deserialize(userTemplate);
    }

    public void setUserTemplate(final UserTO userTemplate) {
        this.userTemplate = XMLSerializer.serialize(userTemplate);
    }

    public RoleTO getRoleTemplate() {
        return userTemplate == null
                ? new RoleTO()
                : XMLSerializer.<RoleTO>deserialize(roleTemplate);
    }

    public void setRoleTemplate(final RoleTO roleTemplate) {
        this.roleTemplate = XMLSerializer.serialize(roleTemplate);
    }

    public boolean isPerformCreate() {
        return isBooleanAsInteger(performCreate);
    }

    public void setPerformCreate(final boolean performCreate) {
        this.performCreate = getBooleanAsInteger(performCreate);
    }

    public boolean isPerformUpdate() {
        return isBooleanAsInteger(performUpdate);
    }

    public void setPerformUpdate(final boolean performUpdate) {
        this.performUpdate = getBooleanAsInteger(performUpdate);
    }

    public boolean isPerformDelete() {
        return isBooleanAsInteger(performDelete);
    }

    public void setPerformDelete(boolean performDelete) {
        this.performDelete = getBooleanAsInteger(performDelete);
    }

    public boolean isSyncStatus() {
        return isBooleanAsInteger(syncStatus);
    }

    public void setSyncStatus(final boolean syncStatus) {
        this.syncStatus = getBooleanAsInteger(syncStatus);
    }

    public boolean isFullReconciliation() {
        return isBooleanAsInteger(fullReconciliation);
    }

    public void setFullReconciliation(final boolean fullReconciliation) {
        this.fullReconciliation = getBooleanAsInteger(fullReconciliation);
    }

    public String getActionsClassName() {
        return actionsClassName;
    }

    public void setActionsClassName(String actionsClassName) {
        this.actionsClassName = actionsClassName;
    }
}


text:
.. _whatsnew_0252:

What's new in 0.25.2 (October 15, 2019)
---------------------------------------

These are the changes in pandas 0.25.2. See :ref:`release` for a full changelog
including other versions of pandas.

.. note::

    pandas 0.25.2 adds compatibility for Python 3.8 (:issue:`28147`).

.. _whatsnew_0252.bug_fixes:

Bug fixes
~~~~~~~~~

Indexing
^^^^^^^^

- Fix regression in :meth:`DataFrame.reindex` not following the ``limit`` argument (:issue:`28631`).
- Fix regression in :meth:`RangeIndex.get_indexer` for decreasing :class:`RangeIndex` where target values may be improperly identified as missing/present (:issue:`28678`)

IO
^^

- Fix regression in notebook display where ``<th>`` tags were missing for :attr:`DataFrame.index` values (:issue:`28204`).
- Regression in :meth:`~DataFrame.to_csv` where writing a :class:`Series` or :class:`DataFrame` indexed by an :class:`IntervalIndex` would incorrectly raise a ``TypeError`` (:issue:`28210`)
- Fix :meth:`~DataFrame.to_csv` with ``ExtensionArray`` with list-like values (:issue:`28840`).

GroupBy/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^

- Bug incorrectly raising an ``IndexError`` when passing a list of quantiles to :meth:`pandas.core.groupby.DataFrameGroupBy.quantile` (:issue:`28113`).
- Bug in :meth:`pandas.core.groupby.GroupBy.shift`, :meth:`pandas.core.groupby.GroupBy.bfill` and :meth:`pandas.core.groupby.GroupBy.ffill` where timezone information would be dropped (:issue:`19995`, :issue:`27992`)

Other
^^^^^

- Compatibility with Python 3.8 in :meth:`DataFrame.query` (:issue:`27261`)
- Fix to ensure that tab-completion in an IPython console does not raise
  warnings for deprecated attributes (:issue:`27900`).

.. _whatsnew_0.252.contributors:

Contributors
~~~~~~~~~~~~

.. contributors:: v0.25.1..v0.25.2


text:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;

namespace OMF
{
    public class SurfaceElement : ContentModel, IObject
    {
        public SurfaceElement()
        {
            subtype = "surface";
        }
        public SurfaceElement(List<double[]> vertices, List<int[]> faces) : this()
        {
            Surface = new SurfaceGeometry(vertices, faces);
        }
        public int[] color { get; set; }
        public string subtype { get; set; }
        public string geometry { get; set; }

        [JsonIgnore]
        public SurfaceGeometry Surface { get; set; }

        [JsonIgnore]
        public string[] data { get; set; }

        public void Deserialize(Dictionary<string, object> json, BinaryReader br)
        {
            Surface = (SurfaceGeometry)ObjectFactory.GetObjectFromGuid(json, br, geometry);
        }

        public void Serialize(Dictionary<string, object> json, BinaryWriter bw)
        {
            geometry = ObjectFactory.SerializeObject(Surface, json, bw);

            ObjectFactory.GetObjectToData(json, this, uid.ToString());
        }
    }
}


text:
namespace axl {
namespace io {

//..............................................................................

inline
void
registerSslErrorProvider() {
	cry::registerCryptoErrorProviders();
	::ERR_load_SSL_strings();
}

//..............................................................................

} // namespace io
} // namespace axl


text:
package org.apache.pig.experimental.logical.relational;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.pig.experimental.plan.BaseOperatorPlan;
import org.apache.pig.experimental.plan.OperatorPlan;

/**
 * LogicalPlan is the logical view of relational operations Pig will execute
 * for a given script.  Note that it contains only relational operations.
 * All expressions will be contained in LogicalExpressionPlans inside
 * each relational operator.
 */
public class LogicalPlan extends BaseOperatorPlan {

    /**
     * Equality is checked by calling equals on every leaf in the plan.  This
     * assumes that plans are always connected graphs.  It is somewhat
     * inefficient since every leaf will test equality all the way to
     * every root.  But it is only intended for use in testing, so that
     * should be ok.  Checking predecessors (as opposed to successors) was
     * chosen because splits (which have multiple successors) do not depend
     * on order of outputs for correctness, whereas joins (with multiple
     * predecessors) do.  That is, reversing the outputs of split in the
     * graph has no correctness implications, whereas reversing the inputs
     * of join can.  This method of doing equals will detect predecessors
     * in different orders but not successors in different orders.
     */
    @Override
    public boolean isEqual(OperatorPlan other) {
        if (other == null || !(other instanceof LogicalPlan)) {
            return false;
        }

        return super.isEqual(other);
    }
}


text:
interface IAndroidResourcesMigrationService {
  canMigrate(platformString: string): boolean;
  hasMigrated(appResourcesDir: string): boolean;
  migrate(appResourcesDir: string): Promise<void>;
}

interface ILogger {
  initialize(opts?: any): void;
  initializeCliLogger(): void;
  getLevel(): string;
  fatal(formatStr?: any, ...args: any[]): void;
  error(formatStr?: any, ...args: any[]): void;
  warn(formatStr?: any, ...args: any[]): void;
  info(formatStr?: any, ...args: any[]): void;
  debug(formatStr?: any, ...args: any[]): void;
  trace(formatStr?: any, ...args: any[]): void;
  printMarkdown(...args: any[]): void;
  prepare(item: any): string;
  isVerbose(): boolean;
}

interface IPlatformData {
  frameworkPackageName: string;
  platformProjectService: IPlatformProjectService;
  projectRoot: string;
  normalizedPlatformName: string;
  platformNameLowerCase: string;
  appDestinationDirectoryPath: string;
  frameworkFilesExtensions: string[];
  frameworkDirectoriesExtensions?: string[];
  frameworkDirectoriesNames?: string[];
  targetedOS?: string[];
  configurationFileName?: string;
  configurationFilePath?: string;
  relativeToFrameworkConfigurationFilePath: string;
  fastLivesyncFileExtensions: string[];
}

interface IPlatformsData {
  availablePlatforms: any;
  platformsNames: string[];
  getPlatformData(platform: string, projectData: IProjectData): IPlatformData;
}

interface IPlatformProjectService {
  getAppResourcesDestinationDirectoryPath(projectData: IProjectData): string;
}

interface IProjectData {
  projectDir: string;
  projectName: string;
  platformsDir: string;
  projectFilePath: string;
  projectId?: string;
  dependencies: any;
  appDirectoryPath: string;
  appResourcesDirectoryPath: string;
  projectType: string;
  nsConfig: any;
  androidManifestPath: string;
  appGradlePath: string;
  gradleFilesDirectoryPath: string;
  infoPlistPath: string;
  buildXcconfigPath: string;
  getAppDirectoryPath(projectDir?: string): string;
  getAppDirectoryRelativePath(): string;
  getAppResourcesDirectoryPath(projectDir?: string): string;
  getAppResourcesRelativeDirectoryPath(): string;
}

interface IPlatformsDataService {
  getPlatformData(platform: string, projectData: IProjectData): IPlatformData;
}

interface IInjector {
  resolve<T>(name: string, ctorArguments?: any): any;
}


text:
package br.com.eng3.principal;

import br.com.eng3.tipo.Acidente;
import br.com.eng3.tipo.Auto;
import br.com.eng3.tipo.Caminhao;
import br.com.eng3.tipo.Ciclista;
import br.com.eng3.tipo.Moto;
import br.com.eng3.tipo.Onibus;
import br.com.eng3.tipo.Outros;
import br.com.eng3.tipo.Pedestre;
import br.com.eng3.tipo.Tipo;

public class Teste {

	public static void main(String[] args) {

		Facade facade = new Facade();
		facade.criarMVCAcidente();

		facade.criarMVCPais();

		facade.inicializar();
		facade.inicializarPais();

	}

}


text:
package za.org.grassroot.webapp.controller.ussd;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import za.org.grassroot.core.domain.Group;
import za.org.grassroot.core.domain.Meeting;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.Vote;
import za.org.grassroot.core.enums.EventRSVPResponse;
import za.org.grassroot.core.enums.EventType;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Created by luke on 2015/11/20.
 */
public class USSDHomeControllerTest extends USSDAbstractUnitTest {

    // private static final Logger log = LoggerFactory.getLogger(USSDHomeControllerTest.class);

    private static final String phoneForTests = "27810001111";
    private static final String baseForOthers = "2781000111";
    private static final String testUserName = "Test User";
    private static final String testGroupName = "Test Group";

    private static final String openingMenu = "/ussd/start";
    private static final String phoneParameter = "msisdn";

    private User testUser = new User(phoneForTests, testUserName);

    private User testUserZu = new User(baseForOthers + "2");
    private User testUserTs = new User(baseForOthers + "3");
    private User testUserNso = new User(baseForOthers + "4");
    private User testUserSt = new User(baseForOthers + "5");

    private List<User> languageUsers;

    @InjectMocks
    private USSDHomeController ussdHomeController;

    @Before
    public void setUp() {

        mockMvc = MockMvcBuilders.standaloneSetup(ussdHomeController)
                .setHandlerExceptionResolvers(exceptionResolver())
                .setValidator(validator())
                .setViewResolvers(viewResolver())
                .build();

        wireUpMessageSourceAndGroupUtil(ussdHomeController);
        // todo : extend this parrent into method above, to remove public setters
        ReflectionTestUtils.setField(ussdHomeController, "safetyCode", "911");
        ReflectionTestUtils.setField(ussdHomeController, "livewireSuffix", "411");
        ReflectionTestUtils.setField(ussdHomeController, "sendMeLink", "123");
        ReflectionTestUtils.setField(ussdHomeController, "hashPosition", 9);
        ReflectionTestUtils.setField(ussdHomeController, "promotionSuffix", "44");

        /* We use these quite often */
        testUserZu.setLanguageCode("zu");
        testUserTs.setLanguageCode("ts");
        testUserNso.setLanguageCode("nso");
        testUserSt.setLanguageCode("st");

        languageUsers = Arrays.asList(testUserNso, testUserSt, testUserTs, testUserZu);
    }

    @Test
    public void testQuestion() throws Exception {
        mockMvc.perform(get("/ussd/test_question")).andExpect(status().isOk());
    }

    @Test
    @Rollback
    public void welcomeMenuShouldWork() throws Exception {

        testUser.setHasInitiatedSession(false);
        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);

        // todo: check a lot more than this
        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).andExpect(status().isOk());

        verify(userManagementServiceMock, times(1)).loadOrCreateUser(phoneForTests);
        // verifyNoMoreInteractions(userManagementServiceMock); // todo: work out if should shift other calls to user entity itself
    }

    @Test
    public void welcomeMenuAfterChoosingLanguageShouldWork() throws Exception {
        testUser.setHasInitiatedSession(true);
        testUser.setLanguageCode("zu");
        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).andExpect(status().isOk());
    }

    @Test
    public void welcomeMenuLocaleShouldWorkWithNoName() throws Exception {

        testUser.setDisplayName("");
        testUser.setHasInitiatedSession(false);
        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);

        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).andExpect(status().isOk());
        testUser.setLanguageCode("ts");
        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).
                andExpect(status().isOk());

        // no longer done here -- check via language menu
        // verify(userManagementServiceMock, times(1)).updateUserLanguage(testUser.getUid(), new Locale("ts"));
        testUser.setDisplayName(testUserName);
    }

    @Test
    public void forcedStartMenuShouldWork() throws Exception {

        testUser.setHasInitiatedSession(true);
        // switch the next thing to cache manager
        // testUser.setLastUssdMenu("/ussd/mtg/start"); // irrelevant if this is well formed or not, just testing if it asks

        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);

        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).andExpect(status().isOk());
        mockMvc.perform(get(openingMenu + "_force").param(phoneParameter, phoneForTests)).andExpect(status().isOk());

    }

    @Test
    public void groupJoinTokenShouldWorkInAllLanguages() throws Exception {

        testUser.setDisplayName("");
        testUser.setHasInitiatedSession(false);

        Group testGroup = new Group(testGroupName, new User("27601110000"));

        testGroup.setGroupTokenCode("111");
        testGroup.setTokenExpiryDateTime(Instant.now().plus(7, ChronoUnit.DAYS));

        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        when(groupQueryBrokerMock.findGroupFromJoinCode("111")).thenReturn(Optional.of(testGroup));

        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests).param("request", "*134*1994*111#")).
                andExpect(status().isOk());

        for (User user : languageUsers) {
            when(userManagementServiceMock.loadOrCreateUser(user.getPhoneNumber())).thenReturn(user);
            mockMvc.perform(get(openingMenu).param(phoneParameter, user.getPhoneNumber()).param("request", "*134*1994*111#")).
                    andExpect(status().isOk());
        }
    }

    @Test
    public void voteRequestScreenShouldWorkInAllLanguages() throws Exception {

        testUser.setDisplayName(testUserName);
        testUser.setLanguageCode("en");
        Group testGroup = new Group(testGroupName, testUser);

//        Event vote = new Event(testUser, EventType.VOTE, true);
        Vote vote = new Vote("are unit tests working?", Instant.now().plus(1, ChronoUnit.HOURS), testUser, testGroup);

        List<User> votingUsers = new ArrayList<>(languageUsers);
        votingUsers.add(testUser);

        for (User user : votingUsers) {

            testGroup.addMember(user); // this may be redundant
            user.setHasInitiatedSession(false);

            when(userManagementServiceMock.loadOrCreateUser(user.getPhoneNumber())).thenReturn(user);
            when(userManagementServiceMock.findByInputNumber(user.getPhoneNumber())).thenReturn(user);
            when(eventBrokerMock.userHasResponsesOutstanding(user, EventType.VOTE)).thenReturn(true);
            when(eventBrokerMock.getOutstandingResponseForUser(user, EventType.VOTE)).thenReturn(Collections.singletonList(vote));
            when(eventBrokerMock.load(vote.getUid())).thenReturn(vote);

            mockMvc.perform(get(openingMenu).param(phoneParameter, user.getPhoneNumber())).andExpect(status().isOk());
            verify(eventBrokerMock, times(1)).userHasResponsesOutstanding(user, EventType.VOTE);
            verify(eventBrokerMock, times(1)).getOutstandingResponseForUser(user, EventType.VOTE);

            // note: the fact that message source accessor is not wired up may mean this is not actually testing
            mockMvc.perform(get("/ussd/start").param(phoneParameter, user.getPhoneNumber()));
            mockMvc.perform(get("/ussd/vote").param(phoneParameter, user.getPhoneNumber()).
                    param("entityUid", "" + vote.getUid()).
                    param("response", "yes")).andExpect(status().isOk());

            verify(eventLogBrokerMock, times(1)).rsvpForEvent(vote.getUid(), user.getUid(),
                                                                         EventRSVPResponse.YES);
        }
    }

    @Test
    public void meetingRsvpShouldWorkInAllLanguages() throws Exception {

        resetTestUser();
        Group testGroup = new Group(testGroupName, testUser);

        Meeting meeting = new Meeting("Meeting about testing", Instant.now(), testUser, testGroup, "someLocation");

        List<User> groupMembers = new ArrayList<>(languageUsers);
        groupMembers.add(testUser);

        for (User user: groupMembers) {

            user.setHasInitiatedSession(false);

            when(userManagementServiceMock.loadOrCreateUser(user.getPhoneNumber())).thenReturn(user);
            when(userManagementServiceMock.findByInputNumber(user.getPhoneNumber())).thenReturn(user);
            when(eventBrokerMock.userHasResponsesOutstanding(user, EventType.MEETING)).thenReturn(true);
            when(eventBrokerMock.getOutstandingResponseForUser(user, EventType.MEETING)).thenReturn(Collections.singletonList(meeting));
            when(eventBrokerMock.loadMeeting(meeting.getUid())).thenReturn(meeting);

            mockMvc.perform(get(openingMenu).param(phoneParameter, user.getPhoneNumber())).andExpect(status().isOk());
            verify(eventBrokerMock, times(1)).getOutstandingResponseForUser(user, EventType.MEETING);

            mockMvc.perform(get("/ussd/start").param(phoneParameter, user.getPhoneNumber())
                    .param("entityUid", "" + meeting.getUid())
                    .param("confirmed", "yes")).andExpect(status().isOk());

            verify(eventLogBrokerMock, times(1)).rsvpForEvent(meeting.getUid(), user.getUid(), EventRSVPResponse.YES);
        }
    }

    @Test
    public void shouldAssembleLiveWire() throws Exception {
             Group group = new Group(testGroupName, testUser);
             Meeting meeting = new Meeting("",Instant.now().plus(1,ChronoUnit.HOURS)
                    ,testUser,group,"");

             List<Meeting> newMeeting  = Arrays.asList(meeting);

             when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
             when(liveWireBrokerMock.countGroupsForInstantAlert(testUser.getUid())).
                thenReturn(0L);

              mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)
                     .param("request", "*134*1994*411#")).
                andExpect(status().isOk());

              verify(userManagementServiceMock,times(1)).
                loadOrCreateUser(phoneForTests);
              verify(liveWireBrokerMock,times(1)).
                      meetingsForAlert(testUser.getUid());
              verify(liveWireBrokerMock, times(1))
                .countGroupsForInstantAlert(testUser.getUid());

              when(liveWireBrokerMock.countGroupsForInstantAlert(testUser.getUid()))
                      .thenReturn(2L);

               mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)
                .param("request", "*134*1994*411#")).
                       andExpect(status().isOk());

              when(liveWireBrokerMock.meetingsForAlert(testUser.getUid())).
                      thenReturn(newMeeting);
              mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)
                .param("request", "*134*1994*411#").
                              param("page","1")).
                andExpect(status().isOk());
    }

    /*
    Make sure groupRename works properly
     */
    @Test
    public void groupRenameShouldWork() throws Exception {

        resetTestUser();
        testUser.setHasInitiatedSession(true);
        Group testGroup = new Group("", testUser);

        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.fetchGroupUserMustRename(testUser)).thenReturn(testGroup);

        // todo: work out how to verify that it actually returned the prompt to rename the testGroup
        mockMvc.perform(get(openingMenu).param(phoneParameter, testUser.getPhoneNumber())).
                andExpect(status().isOk());

        mockMvc.perform(get("/ussd/group-start").
                param(phoneParameter, phoneForTests).
                param("groupUid", "" + testGroup.getUid()).
                param("request", testGroupName)).andExpect(status().isOk());

        verify(userManagementServiceMock, times(1)).loadOrCreateUser(phoneForTests);
        verify(userManagementServiceMock, times(1)).findByInputNumber(phoneForTests);
        verify(groupBrokerMock, times(1)).updateName(testUser.getUid(), testGroup.getUid(), testGroupName);
        verify(userManagementServiceMock, times(2)).fetchGroupUserMustRename(testUser);
    }

    /*
    User rename should work properly
     */
    @Test
    public void userRenamePromptShouldWork() throws Exception {

        resetTestUser();
        testUser.setHasInitiatedSession(true);
        testUser.setDisplayName("");

        when(userManagementServiceMock.loadOrCreateUser(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);
        when(userManagementServiceMock.needsToRenameSelf(testUser)).thenReturn(true);

        // todo: as above, work how to verify what it returned (once / if this is re-enabled
        mockMvc.perform(get(openingMenu).param(phoneParameter, phoneForTests)).
                andExpect(status().isOk());

        testUser.setDisplayName(testUserName); // necessary else when/then doesn't work within controller

        mockMvc.perform(get("/ussd/rename-start").param(phoneParameter, phoneForTests).param("request", testUserName)).
                andExpect(status().isOk());

        verify(userManagementServiceMock, times(1)).loadOrCreateUser(phoneForTests);
        verify(userManagementServiceMock, times(1)).findByInputNumber(phoneForTests);
        verify(userManagementServiceMock, times(1)).updateDisplayName(testUser.getUid(), testUserName);

    }

    /*
    Make sure testGroup pagination works
     */
    @Test
    public void groupSecondPageShouldWork() throws Exception {

        resetTestUser();

        List<Group> testGroups = Arrays.asList(new Group("gc1", testUser),
                                               new Group("gc2", testUser),
                                               new Group("gc3", testUser),
                                               new Group("gc4", testUser));

        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);
        when(permissionBrokerMock.countActiveGroupsWithPermission(testUser, null)).thenReturn(4);
        when(permissionBrokerMock.getPageOfGroups(testUser, null, 1, 3)).thenReturn(testGroups);

        mockMvc.perform(get("/ussd/group_page").param(phoneParameter, phoneForTests).param("prompt", "Look at pages").
                param("page", "1").param("existingUri", "/ussd/blank").param("newUri", "/ussd/blank2")).
                andExpect(status().isOk());

        verify(userManagementServiceMock, times(1)).findByInputNumber(phoneForTests);
        verify(permissionBrokerMock, times(1)).countActiveGroupsWithPermission(testUser, null);
        verify(permissionBrokerMock, times(1)).getPageOfGroups(testUser, null, 1, 3);
        verifyNoMoreInteractions(userManagementServiceMock);
        verifyNoMoreInteractions(permissionBrokerMock);
    }

    /*
    Make sure that exit page works properly
     */
    @Test
    public void errorPagesShouldBeWellFormed() throws Exception {
        resetTestUser();
        when(userManagementServiceMock.findByInputNumber(phoneForTests)).thenReturn(testUser);
        mockMvc.perform(get("/ussd/error")
                .param(phoneParameter, phoneForTests))
                .andExpect(status().isOk());
        verify(userManagementServiceMock, times(1)).findByInputNumber(phoneForTests);
        verifyNoMoreInteractions(userManagementServiceMock);

    }

    /*
    Small helper method to reset testUser between tests
     */

    private void resetTestUser() {

        testUser.setDisplayName(testUserName);
        testUser.setLanguageCode("en");

    }

}