text:
/*
   To run: ./lwm2m-sample-client <client name> [-b] [-s SEC_MODE]
   If [-b] argument is not given:
   This LWM2M client sample will try to connect to a LWM2M server @ locahost:5683
   (or @ localhost:5684 if -s is given).
   If a location object is created by the LWM2M server, it will report its location
   every one second.

   If [-b] argument is given:
   This LWM2M client sample expect a server-initiated bootstrap.
   If it doesn't happen in 5s, it will try to connect to a LWM2M bootstrap server
   @ localhost:5783 and perform client-initiated bootstrap.
   If the bootstrap is successfull, it will try to connect and register with the
   server(s) received in the bootstrap information.
 */

#include "sol-lwm2m-client.h"
#include "sol-mainloop.h"
#include "sol-vector.h"
#include "sol-util.h"

#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>

#define LOCATION_OBJ_ID (6)
#define LOCATION_OBJ_LATITUDE_RES_ID (0)
#define LOCATION_OBJ_LONGITUDE_RES_ID (1)
#define LOCATION_OBJ_TIMESTAMP_RES_ID (5)

#define ONE_SECOND (1000)
#define LIFETIME (60)

#define SERVER_OBJ_ID (1)
#define SERVER_OBJ_SHORT_RES_ID (0)
#define SERVER_OBJ_LIFETIME_RES_ID (1)
#define SERVER_OBJ_BINDING_RES_ID (7)
#define SERVER_OBJ_REGISTRATION_UPDATE_RES_ID (8)

#define ACCESS_CONTROL_OBJ_ID (2)
#define ACCESS_CONTROL_OBJ_OBJECT_RES_ID (0)
#define ACCESS_CONTROL_OBJ_INSTANCE_RES_ID (1)
#define ACCESS_CONTROL_OBJ_ACL_RES_ID (2)
#define ACCESS_CONTROL_OBJ_OWNER_RES_ID (3)

#define SECURITY_OBJ_ID (0)
#define SECURITY_SERVER_URI_RES_ID (0)
#define SECURITY_IS_BOOTSTRAP_RES_ID (1)
#define SECURITY_SECURITY_MODE_RES_ID (2)
#define SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID (3)
#define SECURITY_SERVER_PUBLIC_KEY_RES_ID (4)
#define SECURITY_SECRET_KEY_RES_ID (5)
#define SECURITY_SERVER_ID_RES_ID (10)
#define SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID (11)
#define SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID (12)

#define PSK_KEY_LEN 16
#define RPK_PRIVATE_KEY_LEN 32
#define RPK_PUBLIC_KEY_LEN (2 * RPK_PRIVATE_KEY_LEN)

//FIXME: UNSEC: Hardcoded Crypto Keys
#define CLIENT_BS_PSK_ID ("cli1-bs")
#define CLIENT_BS_PSK_KEY ("FEDCBA9876543210")
#define CLIENT_SERVER_PSK_ID ("cli1")
#define CLIENT_SERVER_PSK_KEY ("0123456789ABCDEF")

#define CLIENT_PRIVATE_KEY ("D9E2707A72DA6A0504995C86EDDBE3EFC7F1CD74838F7570C8072D0A76261BD4")
#define CLIENT_PUBLIC_KEY ("D055EE14084D6E0615599DB583913E4A3E4526A2704D61F27A4CCFBA9758EF9A" \
    "B418B64AFE8030DA1DDCF4F42E2F2631D043B1FB03E22F4D17DE43F9F9ADEE70")
#define BS_SERVER_PUBLIC_KEY ("cd4110e97bbd6e7e5a800028079d02915c70b915ea4596402098deea585eb7ad" \
    "f3e080487327f70758b13bc0583f4293d13288a0164a8e324779aa4f7ada26c1")
#define SERVER_PUBLIC_KEY ("3b88c213ca5ccfd9c5a7f73715760d7d9a5220768f2992d2628ae1389cbca4c6" \
    "d1b73cc6d61ae58783135749fb03eaaa64a7a1adab8062ed5fc0d7b86ba2d5ca")

struct client_data_ctx {
    bool has_location_instance;
    bool is_bootstrap;
};

struct security_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    struct sol_blob *server_uri;
    bool is_bootstrap;
    int64_t security_mode;
    struct sol_blob *public_key_or_id;
    struct sol_blob *server_public_key;
    struct sol_blob *secret_key;
    int64_t server_id;
    int64_t client_hold_off_time;
    int64_t bootstrap_server_account_timeout;
};

struct server_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    struct sol_blob *binding;
    int64_t server_id;
    int64_t lifetime;
};

struct acl_instance {
    uint16_t key;
    int64_t value;
};

struct access_control_obj_instance_ctx {
    struct sol_lwm2m_client *client;
    int64_t owner_id;
    int64_t object_id;
    int64_t instance_id;
    struct sol_vector acl;
};

struct location_obj_instance_ctx {
    struct sol_timeout *timeout;
    struct sol_lwm2m_client *client;
    double latitude;
    double longitude;
    int64_t timestamp;
};

static struct sol_blob bootstrap_server_addr = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coaps://localhost:5783",
    .size = sizeof("coaps://localhost:5783") - 1,
    .refcnt = 1
};

static struct sol_blob server_addr_coap = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coap://localhost:5683",
    .size = sizeof("coap://localhost:5683") - 1,
    .refcnt = 1
};

static struct sol_blob server_addr_dtls = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"coaps://localhost:5684",
    .size = sizeof("coaps://localhost:5684") - 1,
    .refcnt = 1
};

static struct sol_blob binding = {
    .type = &SOL_BLOB_TYPE_NO_FREE,
    .parent = NULL,
    .mem = (void *)"U",
    .size = sizeof("U") - 1,
    .refcnt = 1
};

static struct sol_blob *
coord_to_str(double d)
{
    int r;
    char *str;
    struct sol_blob *blob;

    r = asprintf(&str, "%g", d);
    if (r < 0) {
        fprintf(stderr, "Could not convert the latitude/longitude to string\n");
        return NULL;
    }

    blob = sol_blob_new(&SOL_BLOB_TYPE_DEFAULT, NULL, str, strlen(str));

    if (!blob) {
        fprintf(stderr, "Could not create a blob to store the latitude/longitude\n");
        free(str);
        return NULL;
    }
    return blob;
}

static bool
change_location(void *data)
{
    struct location_obj_instance_ctx *instance_ctx = data;
    int r = 0;
    static const char *paths[] = { "/6/0/0",
                                   "/6/0/1", "/6/0/5", NULL };

    instance_ctx->latitude = ((double)rand() / (double)RAND_MAX);
    instance_ctx->longitude = ((double)rand() / (double)RAND_MAX);

    instance_ctx->timestamp = (int64_t)time(NULL);

    printf("New latitude: %g - New longitude: %g\n", instance_ctx->latitude,
        instance_ctx->longitude);

    r = sol_lwm2m_client_notify(instance_ctx->client, paths);

    if (r < 0) {
        fprintf(stderr, "Could not notify the observers\n");
    } else
        printf("Sending new location coordinates to the observers\n");

    return true;
}

static int
create_location_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data, struct sol_lwm2m_payload payload)
{
    struct location_obj_instance_ctx *instance_ctx;
    struct client_data_ctx *data_ctx = user_data;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    //Only one location object is allowed
    if (data_ctx->has_location_instance) {
        fprintf(stderr, "Only one location object instance is allowed\n");
        return -EINVAL;
    }

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct location_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for location object context\n");
        return -ENOMEM;
    }

    instance_ctx->timeout = sol_timeout_add(ONE_SECOND, change_location,
        instance_ctx);
    if (!instance_ctx->timeout) {
        fprintf(stderr, "Could not create the client timer\n");
        r = -ENOMEM;
        goto err_free_instance;
    }

    if (payload.payload.tlv_content.len != 3) {
        r = -EINVAL;
        fprintf(stderr, "Missing mandatory fields.\n");
        goto err_free_timeout;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 32);
        double *prop = NULL;

        if (tlv->id == LOCATION_OBJ_LATITUDE_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            prop = &instance_ctx->latitude;
        } else if (tlv->id == LOCATION_OBJ_LONGITUDE_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            prop = &instance_ctx->longitude;
        } else
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->timestamp);

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_timeout;
        }

        if (buf.used) {
            char *endptr = NULL;

            *prop = sol_util_strtod_n(buf.data, &endptr, buf.used, false);

            if (errno != 0 || endptr == buf.data) {
                r = -EINVAL;
                fprintf(stderr, "Could not copy the longitude/latitude"
                    " property\n");
                goto err_free_timeout;
            }
        }
        sol_buffer_fini(&buf);
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    data_ctx->has_location_instance = true;
    printf("Location object created\n");

    return 0;

err_free_timeout:
    sol_timeout_del(instance_ctx->timeout);
err_free_instance:
    free(instance_ctx);
    return r;
}

static int
read_location_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id,
    uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct sol_blob *blob;
    struct location_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case LOCATION_OBJ_LATITUDE_RES_ID:
        blob = coord_to_str(ctx->latitude);
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, blob);
        sol_blob_unref(blob);
        break;
    case LOCATION_OBJ_LONGITUDE_RES_ID:
        blob = coord_to_str(ctx->longitude);
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, blob);
        sol_blob_unref(blob);
        break;
    case LOCATION_OBJ_TIMESTAMP_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_TIME, ctx->timestamp);
        break;
    default:
        if (res_id >= 2 && res_id <= 4)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
read_security_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct security_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case SECURITY_SERVER_URI_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->server_uri);
        break;
    case SECURITY_IS_BOOTSTRAP_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_BOOL, ctx->is_bootstrap);
        break;
    case SECURITY_SECURITY_MODE_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->security_mode);
        break;
    case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
        if (!ctx->public_key_or_id)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->public_key_or_id);
        break;
    case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
        if (!ctx->server_public_key)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->server_public_key);
        break;
    case SECURITY_SECRET_KEY_RES_ID:
        if (!ctx->secret_key)
            r = -ENOENT;
        else
            SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
                SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->secret_key);
        break;
    case SECURITY_SERVER_ID_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->server_id);
        break;
    case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->client_hold_off_time);
        break;
    case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->bootstrap_server_account_timeout);
        break;
    default:
        if (res_id >= 6 && res_id <= 9)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
write_security_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct security_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;

    switch (res->id) {
    case SECURITY_SERVER_URI_RES_ID:
        sol_blob_unref(instance_ctx->server_uri);
        instance_ctx->server_uri = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_IS_BOOTSTRAP_RES_ID:
        instance_ctx->is_bootstrap = res->data->content.b;
        break;
    case SECURITY_SECURITY_MODE_RES_ID:
        instance_ctx->security_mode = res->data->content.integer;
        break;
    case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
        sol_blob_unref(instance_ctx->public_key_or_id);
        instance_ctx->public_key_or_id = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
        sol_blob_unref(instance_ctx->server_public_key);
        instance_ctx->server_public_key = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SECRET_KEY_RES_ID:
        sol_blob_unref(instance_ctx->secret_key);
        instance_ctx->secret_key = sol_blob_ref(res->data->content.blob);
        break;
    case SECURITY_SERVER_ID_RES_ID:
        instance_ctx->server_id = res->data->content.integer;
        break;
    case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
        instance_ctx->client_hold_off_time = res->data->content.integer;
        break;
    case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
        instance_ctx->bootstrap_server_account_timeout = res->data->content.integer;
        break;
    default:
        if (res->id >= 6 && res->id <= 9)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Security object at /0/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);
    return r;
}

static int
write_security_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = 0;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct security_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        switch (tlv->id) {
        case SECURITY_SERVER_URI_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->server_uri);
            instance_ctx->server_uri = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_uri)
                return -EINVAL;
            break;
        case SECURITY_IS_BOOTSTRAP_RES_ID:
            r = sol_lwm2m_tlv_get_bool(tlv, &instance_ctx->is_bootstrap);
            if (r < 0)
                return r;
            break;
        case SECURITY_SECURITY_MODE_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->security_mode);
            if (r < 0)
                return r;
            break;
        case SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->public_key_or_id);
            instance_ctx->public_key_or_id = sol_buffer_to_blob(&buf);
            if (!instance_ctx->public_key_or_id)
                return -EINVAL;
            break;
        case SECURITY_SERVER_PUBLIC_KEY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->server_public_key);
            instance_ctx->server_public_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_public_key)
                return -EINVAL;
            break;
        case SECURITY_SECRET_KEY_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->secret_key);
            instance_ctx->secret_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->secret_key)
                return -EINVAL;
            break;
        case SECURITY_SERVER_ID_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
            if (r < 0)
                return r;
            break;
        case SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->client_hold_off_time);
            if (r < 0)
                return r;
            break;
        case SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->bootstrap_server_account_timeout);
            if (r < 0)
                return r;
            break;
        default:
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Security Server Object at /0/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Security object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Security object at /1/%" PRIu16 "\n", instance_id);

    return r;
}

static int
create_security_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct security_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct security_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for security object context\n");
        return -ENOMEM;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        if (tlv->id == SECURITY_SERVER_URI_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->server_uri = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_uri) {
                fprintf(stderr, "Could not set server_uri resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_IS_BOOTSTRAP_RES_ID) {
            r = sol_lwm2m_tlv_get_bool(tlv, &instance_ctx->is_bootstrap);
        } else if (tlv->id == SECURITY_SECURITY_MODE_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->security_mode);
        } else if (tlv->id == SECURITY_PUBLIC_KEY_OR_IDENTITY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->public_key_or_id = sol_buffer_to_blob(&buf);
            if (!instance_ctx->public_key_or_id) {
                fprintf(stderr, "Could not set public_key_or_id resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SERVER_PUBLIC_KEY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->server_public_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->server_public_key) {
                fprintf(stderr, "Could not set server_public_key resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SECRET_KEY_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->secret_key = sol_buffer_to_blob(&buf);
            if (!instance_ctx->secret_key) {
                fprintf(stderr, "Could not set secret_key resource\n");
                goto err_free_instance;
            }
        } else if (tlv->id == SECURITY_SERVER_ID_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
        } else if (tlv->id == SECURITY_CLIENT_HOLD_OFF_TIME_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->client_hold_off_time);
        } else if (tlv->id == SECURITY_BOOTSTRAP_SERVER_ACCOUNT_TIMEOUT_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->bootstrap_server_account_timeout);
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_instance;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Security object created at /0/%" PRIu16 "\n", instance_id);

    return 0;

err_free_instance:
    sol_blob_unref(instance_ctx->server_uri);
    if (instance_ctx->public_key_or_id)
        sol_blob_unref(instance_ctx->public_key_or_id);
    if (instance_ctx->server_public_key)
        sol_blob_unref(instance_ctx->server_public_key);
    if (instance_ctx->secret_key)
        sol_blob_unref(instance_ctx->secret_key);
    free(instance_ctx);
    return r;
}

static int
del_security_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct security_obj_instance_ctx *instance_ctx = instance_data;

    sol_blob_unref(instance_ctx->server_uri);
    if (instance_ctx->public_key_or_id)
        sol_blob_unref(instance_ctx->public_key_or_id);
    if (instance_ctx->server_public_key)
        sol_blob_unref(instance_ctx->server_public_key);
    if (instance_ctx->secret_key)
        sol_blob_unref(instance_ctx->secret_key);
    free(instance_ctx);
    return 0;
}

static int
read_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct server_obj_instance_ctx *ctx = instance_data;
    int r;

    switch (res_id) {
    case SERVER_OBJ_SHORT_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->server_id);
        break;
    case SERVER_OBJ_LIFETIME_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->lifetime);
        break;
    case SERVER_OBJ_BINDING_RES_ID:
        SOL_LWM2M_RESOURCE_SINGLE_INIT(r, res, res_id,
            SOL_LWM2M_RESOURCE_DATA_TYPE_STRING, ctx->binding);
        break;
    default:
        if (res_id >= 2 && res_id <= 6)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    return r;
}

static int
write_server_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct server_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;

    switch (res->id) {
    case SERVER_OBJ_SHORT_RES_ID:
        instance_ctx->server_id = res->data->content.integer;
        break;
    case SERVER_OBJ_LIFETIME_RES_ID:
        instance_ctx->lifetime = res->data->content.integer;
        break;
    case SERVER_OBJ_BINDING_RES_ID:
        sol_blob_unref(instance_ctx->binding);
        instance_ctx->binding = sol_blob_ref(res->data->content.blob);
        break;
    default:
        if (res->id >= 2 && res->id <= 6)
            r = -ENOENT;
        else
            r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Server object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);
    return r;
}

static int
write_server_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = 0;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct server_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        switch (tlv->id) {
        case SERVER_OBJ_SHORT_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
            if (r < 0)
                return r;
            break;
        case SERVER_OBJ_LIFETIME_RES_ID:
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->lifetime);
            if (r < 0)
                return r;
            break;
        case SERVER_OBJ_BINDING_RES_ID:
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                return r;
            sol_blob_unref(instance_ctx->binding);
            instance_ctx->binding = sol_buffer_to_blob(&buf);
            if (!instance_ctx->binding)
                return -EINVAL;
            break;
        default:
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Server Object at /1/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Server object at /1/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Server object at /1/%" PRIu16 "\n", instance_id);

    return r;
}

static int
create_server_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct server_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct server_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for server object context\n");
        return -ENOMEM;
    }

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        SOL_BUFFER_DECLARE_STATIC(buf, 64);

        if (tlv->id == SERVER_OBJ_SHORT_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->server_id);
        } else if (tlv->id == SERVER_OBJ_LIFETIME_RES_ID) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->lifetime);
        } else if (tlv->id == SERVER_OBJ_BINDING_RES_ID) {
            r = sol_lwm2m_tlv_get_bytes(tlv, &buf);
            if (r < 0)
                goto err_free_instance;
            instance_ctx->binding = sol_buffer_to_blob(&buf);
            if (!instance_ctx->binding) {
                fprintf(stderr, "Could not set binding resource\n");
                goto err_free_instance;
            }
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_instance;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Server object created at /1/%" PRIu16 "\n", instance_id);

    return 0;

err_free_instance:
    free(instance_ctx);
    return r;
}

static int
execute_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id,
    uint16_t res_id, const struct sol_str_slice args)
{
    if (res_id != SERVER_OBJ_REGISTRATION_UPDATE_RES_ID)
        return -EINVAL;

    return sol_lwm2m_client_send_update(client);
}

static int
del_server_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct server_obj_instance_ctx *instance_ctx = instance_data;

    sol_blob_unref(instance_ctx->binding);
    free(instance_ctx);
    return 0;
}

static int
del_location_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct location_obj_instance_ctx *instance_ctx = instance_data;
    struct client_data_ctx *data_ctx = user_data;

    if (instance_ctx->timeout)
        sol_timeout_del(instance_ctx->timeout);
    free(instance_ctx);
    data_ctx->has_location_instance = false;
    return 0;
}

static int
read_access_control_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, struct sol_lwm2m_resource *res)
{
    struct access_control_obj_instance_ctx *ctx = instance_data;
    int r;

    if (res_id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->object_id);
    } else if (res_id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->instance_id);
    } else if (res_id == ACCESS_CONTROL_OBJ_ACL_RES_ID) {
        struct acl_instance *acl_item;
        uint16_t i;
        struct sol_vector acl_instances;
        struct sol_lwm2m_resource_data *res_data;

        if (ctx->acl.len == 0)
            return -ENOENT;

        sol_vector_init(&acl_instances, sizeof(struct sol_lwm2m_resource_data));

        SOL_VECTOR_FOREACH_IDX (&ctx->acl, acl_item, i) {
            res_data = sol_vector_append(&acl_instances);
            res_data->id = acl_item->key;
            res_data->content.integer = acl_item->value;
        }

        SOL_SET_API_VERSION(res->api_version = SOL_LWM2M_RESOURCE_API_VERSION; )
        r = sol_lwm2m_resource_init_vector(res, ACCESS_CONTROL_OBJ_ACL_RES_ID,
            SOL_LWM2M_RESOURCE_DATA_TYPE_INT, &acl_instances);

        sol_vector_clear(&acl_instances);
    } else if (res_id == ACCESS_CONTROL_OBJ_OWNER_RES_ID) {
        SOL_LWM2M_RESOURCE_SINGLE_INT_INIT(r, res, res_id, ctx->owner_id);
    } else {
        r = -EINVAL;
    }

    return r;
}

static int
write_access_control_res(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, uint16_t res_id, const struct sol_lwm2m_resource *res)
{
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;
    int r = 0;
    struct acl_instance *acl_item;
    uint16_t i;

    switch (res->id) {
    case ACCESS_CONTROL_OBJ_OBJECT_RES_ID:
        instance_ctx->object_id = res->data->content.integer;
        break;
    case ACCESS_CONTROL_OBJ_INSTANCE_RES_ID:
        instance_ctx->instance_id = res->data->content.integer;
        break;
    case ACCESS_CONTROL_OBJ_ACL_RES_ID:
        if (res->type == SOL_LWM2M_RESOURCE_TYPE_MULTIPLE) {
            sol_vector_clear(&instance_ctx->acl);

            for (i = 0; i < res->data_len; i++) {
                acl_item = sol_vector_append(&instance_ctx->acl);
                if (!acl_item) {
                    fprintf(stderr, "Could not alloc memory for access control list Resource Instance\n");
                    r = -ENOMEM;
                    goto err_free_acl;
                }

                acl_item->key = res->data[i].id;
                acl_item->value = res->data[i].content.integer;
                printf("<<[WRITE_RES]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
            }
        } else {
            r = -EINVAL;
        }
        break;
    case ACCESS_CONTROL_OBJ_OWNER_RES_ID:
        instance_ctx->owner_id = res->data->content.integer;
        break;
    default:
        r = -EINVAL;
    }

    if (r >= 0)
        printf("Resource written to Access Control object at /2/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, res->id);

    return r;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    return r;
}

static int
write_or_create_acl(struct sol_vector *acl,
    struct sol_vector *tlvs, uint16_t *j, bool is_create)
{
    struct acl_instance *acl_item;
    struct sol_lwm2m_tlv *res_tlv;
    int64_t res_val;
    int r;

    while ((res_tlv = sol_vector_get(tlvs, *j)) &&
        res_tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_INSTANCE) {
        r = sol_lwm2m_tlv_get_int(res_tlv, &res_val);
        if (r < 0)
            return r;

        acl_item = sol_vector_append(acl);
        if (!acl_item) {
            fprintf(stderr, "Could not alloc memory for access control list Resource Instance\n");
            return -ENOMEM;
        }

        acl_item->key = res_tlv->id;
        acl_item->value = res_val;
        if (is_create)
            printf("<<[CREATE]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
        else
            printf("<<[WRITE_TLV]<< acl[%" PRIu16 "]=%" PRId64 ">>>>\n", acl_item->key, acl_item->value);
        (*j)++;
    }

    return 0;
}

static int
write_access_control_tlv(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client,
    uint16_t instance_id, struct sol_vector *tlvs)
{
    int r = -EINVAL;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;

    SOL_VECTOR_FOREACH_IDX (tlvs, tlv, i) {
        if (tlv->id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->object_id);
            if (r < 0)
                return r;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->instance_id);
            if (r < 0)
                return r;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_ACL_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_MULTIPLE_RESOURCES) {
            uint16_t j = i + 1;

            sol_vector_clear(&instance_ctx->acl);

            r = write_or_create_acl(&instance_ctx->acl, tlvs, &j, false);
            if (r < 0)
                goto err_free_acl;

            i = j - 1;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_OWNER_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->owner_id);
            if (r < 0)
                return r;
        } else {
            fprintf(stderr, "tlv type: %u, ID: %" PRIu16 ", Size: %zu, Content: %.*s"
                " could not be written to Access Control Object at /2/%" PRIu16,
                tlv->type, tlv->id, tlv->content.used,
                SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&tlv->content)), instance_id);
            return -EINVAL;
        }
    }

    if (tlvs->len == 1 && r >= 0)
        printf("TLV written to Access Control object at /2/%" PRIu16 "/%" PRIu16 "\n",
            instance_id, tlv->id);
    else
        printf("TLV written to Access Control object at /2/%" PRIu16 "\n", instance_id);

    return r;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    return r;
}

static int
create_access_control_obj(void *user_data, struct sol_lwm2m_client *client,
    uint16_t instance_id, void **instance_data,
    struct sol_lwm2m_payload payload)
{
    struct access_control_obj_instance_ctx *instance_ctx;
    int r;
    uint16_t i;
    struct sol_lwm2m_tlv *tlv;

    if (payload.type != SOL_LWM2M_CONTENT_TYPE_TLV) {
        fprintf(stderr, "Content type is not in TLV format\n");
        return -EINVAL;
    }

    instance_ctx = calloc(1, sizeof(struct access_control_obj_instance_ctx));
    if (!instance_ctx) {
        fprintf(stderr, "Could not alloc memory for access control object context\n");
        return -ENOMEM;
    }

    sol_vector_init(&instance_ctx->acl, sizeof(struct acl_instance));

    SOL_VECTOR_FOREACH_IDX (&payload.payload.tlv_content, tlv, i) {
        if (tlv->id == ACCESS_CONTROL_OBJ_OBJECT_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->object_id);
        } else if (tlv->id == ACCESS_CONTROL_OBJ_INSTANCE_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->instance_id);
        } else if (tlv->id == ACCESS_CONTROL_OBJ_ACL_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_MULTIPLE_RESOURCES) {
            uint16_t j = i + 1;

            sol_vector_clear(&instance_ctx->acl);

            r = write_or_create_acl(&instance_ctx->acl, &payload.payload.tlv_content, &j, true);
            if (r < 0)
                goto err_free_acl;

            i = j - 1;
        } else if (tlv->id == ACCESS_CONTROL_OBJ_OWNER_RES_ID &&
            tlv->type == SOL_LWM2M_TLV_TYPE_RESOURCE_WITH_VALUE) {
            r = sol_lwm2m_tlv_get_int(tlv, &instance_ctx->owner_id);
        }

        if (r < 0) {
            fprintf(stderr, "Could not get the tlv value for resource %"
                PRIu16 "\n", tlv->id);
            goto err_free_acl;
        }
    }

    instance_ctx->client = client;
    *instance_data = instance_ctx;
    printf("Access Control object created at /2/%" PRIu16 "\n\n", instance_id);

    return 0;

err_free_acl:
    sol_vector_clear(&instance_ctx->acl);
    free(instance_ctx);
    return r;
}

static int
del_access_control_obj(void *instance_data, void *user_data,
    struct sol_lwm2m_client *client, uint16_t instance_id)
{
    struct access_control_obj_instance_ctx *instance_ctx = instance_data;

    sol_vector_clear(&instance_ctx->acl);
    free(instance_ctx);
    return 0;
}

static void
bootstrap_cb(void *data,
    struct sol_lwm2m_client *client,
    enum sol_lwm2m_bootstrap_event event)
{
    if (event == SOL_LWM2M_BOOTSTRAP_EVENT_FINISHED) {
        printf("...<Call local Bootstrap clean-up operations>...\n"
            "...<Now that it should have a Server, try to register again>\n");
        sol_lwm2m_client_start(client);
    } else if (event == SOL_LWM2M_BOOTSTRAP_EVENT_ERROR) {
        fprintf(stderr, "Bootstrap Request or Bootstrap Finish Failed!\n");
    }
}

static const struct sol_lwm2m_object location_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = LOCATION_OBJ_ID,
    .create = create_location_obj,
    .read = read_location_obj,
    .del = del_location_obj,
    .resources_count = 6
};

static const struct sol_lwm2m_object security_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = SECURITY_OBJ_ID,
    .resources_count = 12,
    .read = read_security_obj,
    .create = create_security_obj,
    .del = del_security_obj,
    .write_resource = write_security_res,
    .write_tlv = write_security_tlv
};

static const struct sol_lwm2m_object server_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = SERVER_OBJ_ID,
    .resources_count = 9,
    .read = read_server_obj,
    .create = create_server_obj,
    .del = del_server_obj,
    .write_resource = write_server_res,
    .write_tlv = write_server_tlv,
    .execute = execute_server_obj
};

static const struct sol_lwm2m_object access_control_object = {
    SOL_SET_API_VERSION(.api_version = SOL_LWM2M_OBJECT_API_VERSION, )
    .id = ACCESS_CONTROL_OBJ_ID,
    .resources_count = 4,
    .read = read_access_control_obj,
    .create = create_access_control_obj,
    .del = del_access_control_obj,
    .write_resource = write_access_control_res,
    .write_tlv = write_access_control_tlv,
};

int
main(int argc, char *argv[])
{
    struct sol_lwm2m_client *client;
    static const struct sol_lwm2m_object *objects[] =
    { &security_object, &server_object, &access_control_object, &location_object, NULL };
    struct client_data_ctx data_ctx = { 0 };
    struct security_obj_instance_ctx *security_data = NULL;
    struct server_obj_instance_ctx *server_data = NULL;
    int r;
    enum sol_lwm2m_security_mode sec_mode = SOL_LWM2M_SECURITY_MODE_NO_SEC;
    unsigned char buf_aux[RPK_PUBLIC_KEY_LEN];
    struct sol_blob *public_key_or_id, *server_public_key, *secret_key;
    char *cli_name = NULL;
    char usage[256];

    srand(time(NULL));

    snprintf(usage, sizeof(usage), "Usage: ./lwm2m-sample-client <client-name> [-b] [-s SEC_MODE]\n"
        "Where Factory Bootstrap is default and SEC_MODE is an integer as per:\n"
        "\tPRE_SHARED_KEY=%d\n"
        "\tRAW_PUBLIC_KEY=%d\n"
        "\tCERTIFICATE=%d\n"
        "\tNO_SEC=%d (default)\n",
        SOL_LWM2M_SECURITY_MODE_PRE_SHARED_KEY,
        SOL_LWM2M_SECURITY_MODE_RAW_PUBLIC_KEY,
        SOL_LWM2M_SECURITY_MODE_CERTIFICATE,
        SOL_LWM2M_SECURITY_MODE_NO_SEC);

    while ((r = getopt(argc, argv, "bs:")) != -1) {
        switch (r) {
        case 'b':
            data_ctx.is_bootstrap = true;
            break;
        case 's':
            sec_mode = atoi(optarg);
            if (sec_mode < 0 || sec_mode > 3) {
                fprintf(stderr, "%s", usage);
                return -1;
            }
            break;
        default:
            fprintf(stderr, "%s", usage);
            return -1;
        }
    }

    cli_name = argv[optind];
    if (!cli_name) {
        fprintf(stderr, "%s", usage);
        return -1;
    }

    if (data_ctx.is_bootstrap && (sec_mode == SOL_LWM2M_SECURITY_MODE_NO_SEC)) {
        fprintf(stderr, "Non-Factory Bootstrap Mode needs DTLS security enabled\n");
        return -1;
    }

    switch (sec_mode) {
    case SOL_LWM2M_SECURITY_MODE_PRE_SHARED_KEY:
        if (data_ctx.is_bootstrap) {
            public_key_or_id = sol_blob_new_dup(CLIENT_BS_PSK_ID,
                sizeof(CLIENT_BS_PSK_ID) - 1);
            secret_key = sol_blob_new_dup(CLIENT_BS_PSK_KEY, PSK_KEY_LEN);
        } else {
            public_key_or_id = sol_blob_new_dup(CLIENT_SERVER_PSK_ID,
                sizeof(CLIENT_SERVER_PSK_ID) - 1);
            secret_key = sol_blob_new_dup(CLIENT_SERVER_PSK_KEY, PSK_KEY_LEN);
        }
        server_public_key = NULL;
        break;
    case SOL_LWM2M_SECURITY_MODE_RAW_PUBLIC_KEY:
        r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
            sol_str_slice_from_str(CLIENT_PRIVATE_KEY), SOL_DECODE_BOTH);
        secret_key = sol_blob_new_dup(buf_aux, RPK_PRIVATE_KEY_LEN);
        r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
            sol_str_slice_from_str(CLIENT_PUBLIC_KEY), SOL_DECODE_BOTH);
        public_key_or_id = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);

        if (data_ctx.is_bootstrap) {
            r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
                sol_str_slice_from_str(BS_SERVER_PUBLIC_KEY), SOL_DECODE_BOTH);
            server_public_key = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);
        } else {
            r = sol_util_base16_decode(buf_aux, sizeof(buf_aux),
                sol_str_slice_from_str(SERVER_PUBLIC_KEY), SOL_DECODE_BOTH);
            server_public_key = sol_blob_new_dup(buf_aux, RPK_PUBLIC_KEY_LEN);
        }
        break;
    case SOL_LWM2M_SECURITY_MODE_CERTIFICATE:
        fprintf(stderr, "Certificate security mode is not supported yet.\n");
        return -1;
    case SOL_LWM2M_SECURITY_MODE_NO_SEC:
    default:
        public_key_or_id = NULL;
        server_public_key = NULL;
        secret_key = NULL;
        break;
    }

    sol_init();

    client = sol_lwm2m_client_new(cli_name, NULL, NULL, objects, &data_ctx);

    if (!client) {
        r = -1;
        fprintf(stderr, "Could not the create the LWM2M client\n");
        goto exit;
    }

    security_data = calloc(1, sizeof(struct security_obj_instance_ctx));
    if (!security_data) {
        fprintf(stderr, "Could not alloc memory for security object context\n");
        r = -ENOMEM;
        goto exit_del;
    }

    security_data->client = client;
    security_data->security_mode = sec_mode;
    security_data->public_key_or_id = public_key_or_id;
    security_data->server_public_key = server_public_key;
    security_data->secret_key = secret_key;

    if (!data_ctx.is_bootstrap) {
        server_data = calloc(1, sizeof(struct server_obj_instance_ctx));
        if (!server_data) {
            fprintf(stderr, "Could not alloc memory for server object context\n");
            r = -ENOMEM;
            goto exit_del;
        }

        server_data->client = client;
        server_data->binding = &binding;
        server_data->server_id = 101;
        server_data->lifetime = LIFETIME;

        r = sol_lwm2m_client_add_object_instance(client, &server_object, server_data);

        if (r < 0) {
            fprintf(stderr, "Could not add a server object instance\n");
            goto exit_del;
        }

        security_data->server_uri = (sec_mode == SOL_LWM2M_SECURITY_MODE_NO_SEC) ?
            &server_addr_coap : &server_addr_dtls;
        security_data->is_bootstrap = false;
        security_data->server_id = 101;
    } else {
        r = sol_lwm2m_client_add_bootstrap_finish_monitor(client, bootstrap_cb,
            NULL);

        if (r < 0) {
            fprintf(stderr, "Could not add a bootstrap monitor\n");
            goto exit_del;
        }

        security_data->server_uri = &bootstrap_server_addr;
        security_data->is_bootstrap = true;
        security_data->client_hold_off_time = 0;
        security_data->bootstrap_server_account_timeout = 0;
    }

    r = sol_lwm2m_client_add_object_instance(client, &security_object, security_data);

    if (r < 0) {
        fprintf(stderr, "Could not add a security object instance\n");
        goto exit_del;
    }

    sol_lwm2m_client_start(client);

    sol_run();
    r = 0;

    sol_lwm2m_client_stop(client);

exit_del:
    sol_lwm2m_client_del(client);
    free(security_data);
    free(server_data);
exit:
    sol_shutdown();
    return r;
}


text:
package io.cattle.platform.iaas.api.auth.integration.azure;

import io.github.ibuildthecloud.gdapi.annotation.Field;
import io.github.ibuildthecloud.gdapi.annotation.Type;

@Type(name = AzureConstants.CONFIG)
public class AzureConfig {
    private Boolean enabled;
    private String tenantId;
    private String clientId;
    private String accessMode;
    private String domain;
    private String adminAccountUsername;
    private String adminAccountPassword;

    public AzureConfig(Boolean enabled, String accessMode, String tenantId, String clientId,
            String domain, String adminAccountUsername, String adminAccountPassword) {
        this.enabled = enabled;
        this.tenantId = tenantId;
        this.clientId = clientId;
        this.accessMode = accessMode;
        this.domain = domain;
        this.adminAccountUsername = adminAccountUsername;
        this.adminAccountPassword = adminAccountPassword;
    }

    @Field(required = true, nullable = false, defaultValue = "unrestricted")
    public String getAccessMode() {
        return accessMode;
    }

    @Field(nullable = true)
    public Boolean getEnabled() {
        return enabled;
    }

    @Field(nullable = true)
    public String getClientId() {
        return clientId;
    }

    @Field(nullable = true)
    public String getTenantId() {
        return tenantId;
    }

    public String getName() {
        return AzureConstants.CONFIG;
    }

    @Field(nullable = true)
    public String getDomain() {
        return domain;
    }

    @Field(nullable = true, required = true, minLength = 1)
    public String getAdminAccountUsername() {
        return adminAccountUsername;
    }

    @Field(nullable = true, required = true, minLength = 1)
    public String getAdminAccountPassword() {
        return adminAccountPassword;
    }

}

redpajama_set_name: RedPajamaGithub


text:
![alt text](https://i.imgur.com/LQIY0HD.jpg)

## Synopsis

Milky Way Express is an project that utilizes no outside game engines for development; everything is made in Android Studio! The game is available on the Google Play Market and will be frequently updated alongside this Github repository.

## Installation

This game can be loaded into Android Studio and compiled by simply downloading this repository and opening it in Android Studio. Feel free to use and modify this code at your will, as long as it follows the included MIT license.


text:
HackerNode
==========

Hacker News Terminal Viewer.

Why?  Because I saw this [blog post](http://andrewvos.com/2013/08/02/hacker-news-in-the-terminal/) where someone did it in Ruby and said I want to do that in NodeJS.

![alt text](https://raw.github.com/TerryMooreII/HackerNode/master/imgs/hackerNode.jpg "HackerNode")


text:
using System;
using System.Collections.Generic;
using System.Text;
using DeployTool.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DeployTool.Configuration
{
    public class SshConfigurationConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(SshConfiguration);
        }

        public override bool CanRead => true;
        public override bool CanWrite => true;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            SshConfiguration item = new SshConfiguration();
            JObject jo = JObject.Load(reader);

            jo.TryRead<string>(serializer, "Host", x => item.Host = x, null);
            jo.TryRead<int>(serializer, "Port", x => item.Port = x, () => item.Port = 22);
            jo.TryRead<string>(serializer, "Username", x => item.Username = x);
            jo.TryRead<string>(serializer, "Password", x => item.Password = x);
            jo.TryRead<string>(serializer, "EncryptedPassword", x => item.EncryptedPassword = x);

            jo.TryRead<PrivateKeyData[]>(serializer, "PrivateKeys", x => item.PrivateKeys = x, () => item.PrivateKeys = new PrivateKeyData[0]);

            jo.TryRead<string>(serializer, "ProxyHost", x => item.ProxyHost = x, null);
            jo.TryRead<int>(serializer, "ProxyPort", x => item.ProxyPort = x, () => item.ProxyPort = 8080);
            jo.TryRead<string>(serializer, "ProxyUsername", x => item.ProxyUsername = x);
            jo.TryRead<string>(serializer, "ProxyPassword", x => item.ProxyPassword = x);
            jo.TryRead<string>(serializer, "EncryptedProxyPassword", x => item.EncryptedProxyPassword = x);

            return item;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var item = value as SshConfiguration;
            if (item == null)
            {
                return;
            }

            var jo = new JObject();
            jo.AddIfNotEqual(serializer, "Host", item.Host, null);
            if (item.Port != 22 && item.Port != 0)
            {
                jo.AddIfNotEqual(serializer, "Port", item.Port, 22);
            }

            jo.AddIfNotEqual(serializer, "Username", item.Username, null);
            jo.AddIfNotEqual(serializer, "Password", item.Password, null);
            jo.AddIfNotEqual(serializer, "EncryptedPassword", item.Password, null);

            jo.AddIfNotEqual(serializer, "PrivateKeys", item.PrivateKeys, null);

            if (item.ProxyHost != null && item.ProxyPort != 0)
            {
                jo.AddIfNotEqual(serializer, "ProxyHost", item.ProxyHost, null);
                jo.AddIfNotEqual(serializer, "ProxyPort", item.ProxyPort, 8080);
                jo.AddIfNotEqual(serializer, "ProxyUsername", item.ProxyUsername, null);
                jo.AddIfNotEqual(serializer, "ProxyPassword", item.ProxyPassword, null);
                jo.AddIfNotEqual(serializer, "EncryptedProxyPassword", item.ProxyPassword, null);
            }

            jo.WriteTo(writer);
        }

    }
}


text:
//a member variable/object to cache a pointer/object for the shared library function
ExodusFunctorBase efb_nextkey;

//a member function with the right arguments, returning a var or void
var nextkey(in mode, in previous=var(""))
{

 //first time link to the shared lib and create/cache an object from it
 //passing current standard variables in mv
 if (efb_nextkey.pmemberfunction_==NULL)
  efb_nextkey.init("nextkey","exodusprogrambasecreatedelete_",mv);

 //define a function type (pExodusProgramBaseMemberFunction)
 //that can call the shared library object member function
 //with the right arguments and returning a var or void
 typedef var (ExodusProgramBase::*pExodusProgramBaseMemberFunction)(in,in);

 //call the shared library object main function with the right args,
 // returning a var or void
 return CALLMEMBERFUNCTION(*(efb_nextkey.pobject_),
 ((pExodusProgramBaseMemberFunction) (efb_nextkey.pmemberfunction_)))
  (mode,previous);

}
//#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="IdProvider" IDEtalkID="73A313280B5F3203EA45B28B8FDEB644" />
  <component name="ProjectRootManager" version="2" languageLevel="JDK_12" default="false" project-jdk-name="12" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
+++
Categories = ["Development", "GoLang"]
Description = ""
Tags = ["Development", "golang"]
date = "2017-01-19T06:15:57+09:00"
menu = "main"
title = "Platform Types"

+++
Kotlin is nullsafe, but there are things to keep in mind when using Kotlin from Java.
Kotlin has an implementation that accepts it as `T!` Type called Platform types. For example, it is as follows.

```
fun getString(key:String, defValue:String) = sharedPref.getString(key:String, defValue:String) // platform types. return value is T!
fun getString(key:String, defValue:String): String? = sharedPref.getString(key:String, defValue:String) // Declare it to be nullable
```

The above is a simplified method of `SharedPreferences#getString`. but `SharedPreferences#getString` returns @Nullable String.
On the Kotlin side, since it is received as `String:T!`, there is a possibility of crashing at runtime.

By describing it as `@Nullable` on the Java side, platform types and warnings are displayed on the IDE side. in an environment where Kotlin and Java coexist,
it is necessary to understand platform types. Let's explicitly declare whether it is @Nullable in Java.


text:
package jp.co.ctc_g.jse.validation.showcase.presentation.resources;

import jp.co.ctc_g.jse.validation.showcase.business.domain.Message;
import jp.co.ctc_g.jse.validation.showcase.business.domain.Staff;

import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * このクラスは、親子関係バリデーションのREST APIを提供します。
 * </p>
 * @author ITOCHU Techno-Solutions Corporation.
 */
@RestController
@RequestMapping("/validation/staff")
public class StaffResource {

    /**
     * 親子関係バリデーションを実行するAPIを提供します。
     * @param staff スタッフ
     * @return メッセージ
     */
    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public Message create(@RequestBody @Validated Staff staff) {
        return new Message("I-VALIDATION#003", "親子関係バリデーションに成功しました。");
    }

}


text:
using namespace base;
using namespace generator;
using namespace routing;
using namespace feature;
using namespace std;

namespace
{
bool ParseMaxspeedAndWriteToStream(string const & maxspeed, SpeedInUnits & speed, ostringstream & ss)
{
  if (!ParseMaxspeedTag(maxspeed, speed))
    return false;

  ss << UnitsToString(speed.GetUnits()) << "," << strings::to_string(speed.GetSpeed());
  return true;
}
}  // namespace

namespace generator
{
MaxspeedsCollector::MaxspeedsCollector(string const & filename)
  : CollectorInterface(filename)
{
  m_stream.exceptions(fstream::failbit | fstream::badbit);
  m_stream.open(GetTmpFilename());
}

shared_ptr<CollectorInterface> MaxspeedsCollector::Clone(
    shared_ptr<cache::IntermediateDataReaderInterface> const &) const
{
  return make_shared<MaxspeedsCollector>(GetFilename());
}

void MaxspeedsCollector::CollectFeature(FeatureBuilder const &, OsmElement const & p)
{
  if (!p.IsWay())
    return;

  ostringstream ss;
  ss << p.m_id << ",";

  auto const & tags = p.Tags();
  string maxspeedForwardStr;
  string maxspeedBackwardStr;
  bool isReverse = false;

  for (auto const & t : tags)
  {
    if (t.m_key == "maxspeed")
    {
      SpeedInUnits dummySpeed;
      if (!ParseMaxspeedAndWriteToStream(t.m_value, dummySpeed, ss))
        return;
      m_stream << ss.str() << '\n';
      return;
    }

    if (t.m_key == "maxspeed:forward")
      maxspeedForwardStr = t.m_value;
    else if (t.m_key == "maxspeed:backward")
      maxspeedBackwardStr = t.m_value;
    else if (t.m_key == "oneway")
      isReverse = (t.m_value == "-1");
  }

  // Note 1. isReverse == true means feature |p| has tag "oneway" with value "-1". Now (10.2018)
  // no feature with a tag oneway==-1 and a tag maxspeed:forward/backward is found. But to
  // be on the safe side this case is handled.
  // Note 2. If oneway==-1 the order of points is changed while conversion to mwm. So it's
  // necessary to swap forward and backward as well.
  if (isReverse)
    maxspeedForwardStr.swap(maxspeedBackwardStr);

  if (maxspeedForwardStr.empty())
    return;

  SpeedInUnits maxspeedForward;
  if (!ParseMaxspeedAndWriteToStream(maxspeedForwardStr, maxspeedForward, ss))
    return;

  if (!maxspeedBackwardStr.empty())
  {
    SpeedInUnits maxspeedBackward;
    if (!ParseMaxspeedTag(maxspeedBackwardStr, maxspeedBackward))
      return;

    // Note. Keeping only maxspeed:forward and maxspeed:backward if they have the same units.
    // The exception is maxspeed:forward or maxspeed:backward have a special values
    // like "none" or "walk". In that case units mean nothing an the values should
    // be processed in a special way.
    if (!HaveSameUnits(maxspeedForward, maxspeedBackward))
      return;

    ss << "," << strings::to_string(maxspeedBackward.GetSpeed());
  }

  m_stream << ss.str() << '\n';
}

void MaxspeedsCollector::Finish()
{
  if (m_stream.is_open())
    m_stream.close();
}

void MaxspeedsCollector::Save()
{
  CHECK(!m_stream.is_open(), ("Finish() has not been called."));
  LOG(LINFO, ("Saving maxspeed tag values to", GetFilename()));
  if (Platform::IsFileExistsByFullPath(GetTmpFilename()))
    CHECK(CopyFileX(GetTmpFilename(), GetFilename()), ());
}

void MaxspeedsCollector::OrderCollectedData() { OrderTextFileByLine(GetFilename()); }

void MaxspeedsCollector::Merge(CollectorInterface const & collector)
{
  collector.MergeInto(*this);
}

void MaxspeedsCollector::MergeInto(MaxspeedsCollector & collector) const
{
  CHECK(!m_stream.is_open() || !collector.m_stream.is_open(), ("Finish() has not been called."));
  base::AppendFileToFile(GetTmpFilename(), collector.GetTmpFilename());
}
}  // namespace generator


text:
"""
The MIT License (MIT)

Copyright (c) Serenity Software, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from cahoots.confidence.normalizers.base import BaseNormalizer

class CharacterWithoutBoolean(BaseNormalizer):
    """If we get a character and not a boolean, we boost char confidence"""

    @staticmethod
    def test(types, _):
        """
        We want to normalize if there is a character and not a boolean

        :param types: list of result types
        :type types: list
        :param all_types: list of result types + subtypes
        :type all_types: list
        :return: if this normalizer should normalize this result set
        :rtype: bool
        """
        return 'Character' in types and 'Boolean' not in types

    @staticmethod
    def normalize(results):
        """
        setting char confidence to 100% if there's no boolean result

        :param results: list of results we want to normalize
        :type results: list
        :return: the normalized results
        :rtype: list
        """
        for result in [r for r in results if r.type == 'Character']:
            result.confidence = 100

        return results


text:
using System.Threading.Tasks;

using Moq;
using NUnit.Framework;

using SetLocale.Client.Web.Models;
using SetLocale.Client.Web.Services;
using SetLocale.Client.Web.Test.TestHelpers;
using SetLocale.Client.Web.Test.Builders;

namespace SetLocale.Client.Web.Test.Controllers
{
    [TestFixture]
    public class HomeControllerTests
    {
        [Test]
        public async void index_should_return_home_stats_model()
        {
            //arrange
            const string actionName = "Index";

            var reportService = new Mock<IReportService>();
            reportService.Setup(x => x.GetHomeStats()).Returns(() => Task.FromResult(new HomeStatsModel()));

            //act
            var sut = new HomeControllerBuilder().WithReportService(reportService.Object)
                                                 .Build();
            var view = await sut.Index();
            var model = view.Model as HomeStatsModel;

           //assert
            Assert.NotNull(view);
            Assert.NotNull(model);

            sut.AssertGetAttribute(actionName);
            sut.AssertAllowAnonymousAttribute(actionName);
        }
    }
}


text:
<?php
/** @noinspection PhpUnhandledExceptionInspection */
declare(strict_types=1);

/**
 * This file is part of me-cms.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright   Copyright (c) Mirko Pagliai
 * @link        https://github.com/mirko-pagliai/me-cms
 * @license     https://opensource.org/licenses/mit-license.php MIT License
 */

namespace MeCms\Test\TestCase\Controller\Admin;

use Cake\Cache\Cache;
use Cake\I18n\I18n;
use MeCms\Controller\Admin\SystemsController;
use MeCms\TestSuite\ControllerTestCase;
use Tools\Filesystem;

/**
 * SystemsControllerTest class
 */
class SystemsControllerTest extends ControllerTestCase
{
    /**
     * Asserts that the cache is empty.
     *
     * It uses the same cache keys used by `createSomeTemporaryData()`.
     * @see createSomeTemporaryData()
     * @return void
     */
    public function assertCacheIsEmpty(): void
    {
        array_map([$this, 'assertNull'], [Cache::read('value'), Cache::read('varFromGroup', 'posts')]);
    }

    /**
     * Internal method to create some temporary data (cache, assets, logs,
     *  sitemap, thumbnails)
     * @return array Files
     */
    protected function createSomeTemporaryData(): array
    {
        //Writes some cache data
        Cache::write('value', 'data');
        Cache::write('valueFromGroup', 'data', 'posts');

        $Filesystem = new Filesystem();

        $files = [
            'assets' => getConfigOrFail('Assets.target') . DS . 'asset_file',
            'assets2' => getConfigOrFail('Assets.target') . DS . 'asset_file2',
            'logs' => LOGS . 'log_file',
            'sitemap' => SITEMAP,
            'thumbs' => $Filesystem->addSlashTerm(THUMBER_TARGET) . md5('a') . '_' . md5('a') . '.jpg',
        ];

        array_walk($files, fn(string $file) => $Filesystem->createFile($file, str_repeat('a', 255)));

        return $files;
    }

    /**
     * Called after the last test of this test class is run
     * @return void
     */
    public static function tearDownAfterClass(): void
    {
        parent::tearDownAfterClass();

        I18n::setLocale('en_US');
        if (is_writable(SITEMAP)) {
            unlink(SITEMAP);
        }
    }

    /**
     * Called after every test method
     * @return void
     */
    protected function tearDown(): void
    {
        Cache::clearAll();

        array_map([Filesystem::instance(), 'unlinkRecursive'], [getConfigOrFail('Assets.target'), THUMBER_TARGET]);

        parent::tearDown();
    }

    /**
     * Tests for `isAuthorized()` method
     * @test
     */
    public function testIsAuthorized(): void
    {
        parent::testIsAuthorized();

        //With `tmpCleaner` action
        $this->assertGroupsAreAuthorized([
            'admin' => true,
            'manager' => true,
            'user' => false,
        ], 'tmpCleaner');

        foreach (['all', 'logs'] as $param) {
            $this->Controller->setRequest($this->Controller->getRequest()->withParam('pass.0', $param));
            $this->assertGroupsAreAuthorized([
                'admin' => true,
                'manager' => false,
                'user' => false,
            ]);
        }
    }

    /**
     * Tests for `browser()` method
     * @test
     */
    public function testBrowser(): void
    {
        $this->get($this->url + ['action' => 'browser']);
        $this->assertResponseOkAndNotEmpty();
        $this->assertTemplate('Admin' . DS . 'Systems' . DS . 'browser.php');
        $this->assertStringEndsWith('elfinder/elfinder.html', $this->viewVariable('explorer'));

        /** @var \MeCms\Controller\Admin\SystemsController&\PHPUnit\Framework\MockObject\MockObject $Controller */
        $Controller = $this->getMockForController(SystemsController::class, ['elFinderExists']);
        $Controller->method('elFinderExists')->willReturn(false);
        $this->_response = $Controller->browser();
        $this->assertRedirect(['_name' => 'dashboard']);
        $this->assertFlashMessage('ElFinder not available');
    }

    /**
     * Tests for `changelogs()` method
     * @test
     */
    public function testChangelogs(): void
    {
        $url = $this->url + ['action' => 'changelogs'];

        $this->get($url);
        $this->assertResponseOkAndNotEmpty();
        $this->assertTemplate('Admin' . DS . 'Systems' . DS . 'changelogs.php');
        $this->assertNotEmpty($this->viewVariable('files'));
        $this->assertIsArray($this->viewVariable('files'));
        $this->assertEmpty($this->viewVariable('changelog'));

        //GET request. Asks for a changelog file
        $this->get($url + ['?' => ['file' => 'mecms']]);
        $this->assertResponseOkAndNotEmpty();
        $this->assertTemplate('Admin' . DS . 'Systems' . DS . 'changelogs.php');
        $this->assertNotEmpty($this->viewVariable('changelog'));
        $this->assertTrue(is_html($this->viewVariable('changelog')));

        //With a no existing file
        $this->get($url + ['?' => ['file' => 'noExistingFile']]);
        $this->assertResponseFailure();
    }

    /**
     * Tests for `tmpCleaner()` method
     * @test
     */
    public function testTmpCleaner(): void
    {
        $url = $this->url + ['action' => 'tmpCleaner'];

        //POST request. Cleans all
        $files = $this->createSomeTemporaryData();
        $this->post($url + ['all']);
        $this->assertRedirect(['action' => 'tmpViewer']);
        $this->assertFlashMessage(I18N_OPERATION_OK);
        $this->assertCacheIsEmpty();
        array_map([$this, 'assertFileDoesNotExist'], $files);

        //POST request. Cleans the cache
        $files = $this->createSomeTemporaryData();
        $this->post($url + ['cache']);
        $this->assertRedirect(['action' => 'tmpViewer']);
        $this->assertFlashMessage(I18N_OPERATION_OK);
        $this->assertCacheIsEmpty();

        //POST request. Cleans assets, logs, sitemap and thumbs
        foreach (['assets', 'logs', 'sitemap', 'thumbs'] as $tmpName) {
            $this->post($url + [$tmpName]);
            $this->assertRedirect(['action' => 'tmpViewer']);
            $this->assertFlashMessage(I18N_OPERATION_OK);
            $this->assertFileDoesNotExist($files[$tmpName]);
        }

        //POST request. Invalid type
        $this->post($url + ['invalidType']);
        $this->assertRedirect(['action' => 'tmpViewer']);
        $this->assertFlashMessage(I18N_OPERATION_NOT_OK);

        //GET request
        $this->get($url + ['all']);
        $this->assertResponseError();
    }

    /**
     * Tests for `tmpViewer()` method
     * @test
     */
    public function testTmpViewer(): void
    {
        $expectedViewVars = [
            'assetsSize',
            'cacheSize',
            'logsSize',
            'sitemapSize',
            'thumbsSize',
            'totalSize',
            'cacheStatus',
        ];
        $this->createSomeTemporaryData();
        $this->get($this->url + ['action' => 'tmpViewer']);
        $this->assertResponseOkAndNotEmpty();
        $this->assertTemplate('Admin' . DS . 'Systems' . DS . 'tmp_viewer.php');
        array_map([$this, 'assertNotEmpty'], array_map([$this, 'viewVariable'], $expectedViewVars));
    }
}


text:
title: OpenStack India event report
date: 2013-10-10 09:10:48
author: rbowen
tags: india, meetup
---

Red Hat is proud to have been a sponsor of OpenStack India this year. Over 200 people attended the  event. Here's a writeup and some photos from the event: http://openstackindia.wordpress.com/2013/10/10/event-report-openstack-india-day-2013/


text:
package org.apache.flink.graph.asm.degree.annotate.undirected;

import org.apache.flink.api.common.operators.base.JoinOperatorBase.JoinHint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.Vertex;
import org.apache.flink.graph.asm.degree.annotate.DegreeAnnotationFunctions.JoinEdgeWithVertexDegree;
import org.apache.flink.graph.utils.proxy.GraphAlgorithmWrappingBase;
import org.apache.flink.graph.utils.proxy.GraphAlgorithmWrappingDataSet;
import org.apache.flink.graph.utils.proxy.OptionalBoolean;
import org.apache.flink.types.LongValue;
import org.apache.flink.util.Preconditions;

import static org.apache.flink.api.common.ExecutionConfig.PARALLELISM_DEFAULT;

/**
 * Annotates edges of an undirected graph with degree of the target vertex.
 *
 * @param <K> ID type
 * @param <VV> vertex value type
 * @param <EV> edge value type
 */
public class EdgeTargetDegree<K, VV, EV>
extends GraphAlgorithmWrappingDataSet<K, VV, EV, Edge<K, Tuple2<EV, LongValue>>> {

	// Optional configuration
	private OptionalBoolean reduceOnSourceId = new OptionalBoolean(false, false);

	private int parallelism = PARALLELISM_DEFAULT;

	/**
	 * The degree can be counted from either the edge source or target IDs.
	 * By default the target IDs are counted. Reducing on source IDs may
	 * optimize the algorithm if the input edge list is sorted by source ID.
	 *
	 * @param reduceOnSourceId set to {@code true} if the input edge list
	 *                         is sorted by target ID
	 * @return this
	 */
	public EdgeTargetDegree<K, VV, EV> setReduceOnSourceId(boolean reduceOnSourceId) {
		this.reduceOnSourceId.set(reduceOnSourceId);

		return this;
	}

	/**
	 * Override the operator parallelism.
	 *
	 * @param parallelism operator parallelism
	 * @return this
	 */
	public EdgeTargetDegree<K, VV, EV> setParallelism(int parallelism) {
		Preconditions.checkArgument(parallelism > 0 || parallelism == PARALLELISM_DEFAULT,
			"The parallelism must be greater than zero.");

		this.parallelism = parallelism;

		return this;
	}

	@Override
	protected boolean mergeConfiguration(GraphAlgorithmWrappingBase other) {
		Preconditions.checkNotNull(other);

		if (!EdgeSourceDegree.class.isAssignableFrom(other.getClass())) {
			return false;
		}

		EdgeTargetDegree rhs = (EdgeTargetDegree) other;

		reduceOnSourceId.mergeWith(rhs.reduceOnSourceId);
		parallelism = (parallelism == PARALLELISM_DEFAULT) ? rhs.parallelism :
			((rhs.parallelism == PARALLELISM_DEFAULT) ? parallelism : Math.min(parallelism, rhs.parallelism));

		return true;
	}

	@Override
	public DataSet<Edge<K, Tuple2<EV, LongValue>>> runInternal(Graph<K, VV, EV> input)
			throws Exception {
		// t, d(t)
		DataSet<Vertex<K, LongValue>> vertexDegrees = input
			.run(new VertexDegree<K, VV, EV>()
				.setReduceOnTargetId(!reduceOnSourceId.get())
				.setParallelism(parallelism));

		// s, t, d(t)
		return input.getEdges()
			.join(vertexDegrees, JoinHint.REPARTITION_HASH_SECOND)
			.where(1)
			.equalTo(0)
			.with(new JoinEdgeWithVertexDegree<K, EV, LongValue>())
				.setParallelism(parallelism)
				.name("Edge target degree");
	}
}


text:
class AuthenticationService;
class PrefService;

namespace signin {
class IdentityManager;
}

// Mediator for the Google services settings.
@interface SafeBrowsingStandardProtectionMediator
    : NSObject <SafeBrowsingStandardProtectionViewControllerDelegate>

// View controller.
@property(nonatomic, weak) id<SafeBrowsingStandardProtectionConsumer> consumer;

// Designated initializer. All the parameters should not be null.
// `userPrefService`: preference service from the browser state.
// `authService`: authentication service from browser state.
// `identityManager`: identity manager from browser state.
- (instancetype)initWithUserPrefService:(PrefService*)userPrefService
                            authService:(AuthenticationService*)authService
                        identityManager:
                            (signin::IdentityManager*)identityManager
    NS_DESIGNATED_INITIALIZER;

- (instancetype)init NS_UNAVAILABLE;

// Disconnects observers.
- (void)disconnect;

@end

#endif  // IOS_CHROME_BROWSER_UI_SETTINGS_PRIVACY_SAFE_BROWSING_SAFE_BROWSING_STANDARD_PROTECTION_MEDIATOR_H_


text:
				 nosotros
				acerca
				visión
				manifesto

				 ayuda
				api

				 contribuye
				comparte datos
				programa

				 social

			politiquer.io 2017. Solo tú puedes prevenir los fuegos forestales.


text:
package com.thedeanda.ajaxproxy.ui.help.update;

import static org.junit.Assert.*;

import org.junit.Test;

public class ReleaseVersionTest {

	@Test
	public void testParseSnapshot() {
		ReleaseVersion rv = new ReleaseVersion("1.24-SNAPSHOT");
		assertEquals(1, rv.getMajor());
		assertEquals(24, rv.getMinor());
		assertEquals(0, rv.getPatch());
	}

	@Test
	public void testParse0() {
		ReleaseVersion rv = new ReleaseVersion("23");
		assertEquals(23, rv.getMajor());
		assertEquals(0, rv.getMinor());
		assertEquals(0, rv.getPatch());
	}

	@Test
	public void testParse1() {
		ReleaseVersion rv = new ReleaseVersion("1.23");
		assertEquals(1, rv.getMajor());
		assertEquals(23, rv.getMinor());
		assertEquals(0, rv.getPatch());
	}

	@Test
	public void testParse2() {
		ReleaseVersion rv = new ReleaseVersion("1.23.4");
		assertEquals(1, rv.getMajor());
		assertEquals(23, rv.getMinor());
		assertEquals(4, rv.getPatch());
	}

	@Test
	public void testSimpleParse() {
		ReleaseVersion rv = new ReleaseVersion(1, 23, 4);
		assertEquals(1, rv.getMajor());
		assertEquals(23, rv.getMinor());
		assertEquals(4, rv.getPatch());
	}

	@Test
	public void testCompare1() {
		ReleaseVersion rv1 = new ReleaseVersion(1, 0, 0);
		ReleaseVersion rv2 = new ReleaseVersion(2, 0, 0);

		assertEquals(-1, rv1.compareTo(rv2));
		assertEquals(1, rv2.compareTo(rv1));
	}

	@Test
	public void testCompare2() {
		ReleaseVersion rv1 = new ReleaseVersion(1, 3, 0);
		ReleaseVersion rv2 = new ReleaseVersion(1, 4, 0);

		assertEquals(-1, rv1.compareTo(rv2));
		assertEquals(1, rv2.compareTo(rv1));
	}

	@Test
	public void testCompare3() {
		ReleaseVersion rv1 = new ReleaseVersion(1, 3, 5);
		ReleaseVersion rv2 = new ReleaseVersion(1, 4, 7);

		assertEquals(-1, rv1.compareTo(rv2));
		assertEquals(1, rv2.compareTo(rv1));
	}

	@Test
	public void testCompareEqual() {
		ReleaseVersion rv1 = new ReleaseVersion(1, 3, 5);
		ReleaseVersion rv2 = new ReleaseVersion(1, 3, 5);

		assertEquals(0, rv1.compareTo(rv2));
		assertEquals(0, rv2.compareTo(rv1));
	}
}


text:
package org.openspaces.admin.internal.alert;

import java.util.Map;

import org.openspaces.admin.Admin;
import org.openspaces.admin.alert.Alert;
import org.openspaces.admin.alert.AlertConfigurationException;
import org.openspaces.admin.alert.config.AlertConfiguration;
import org.openspaces.admin.alert.events.AlertTriggeredEventManager;
import org.openspaces.admin.bean.BeanConfig;
import org.openspaces.admin.bean.BeanConfigNotFoundException;
import org.openspaces.admin.bean.BeanConfigPropertiesManager;
import org.openspaces.admin.internal.alert.bean.AlertBean;
import org.openspaces.admin.internal.alert.events.DefaultAlertEventManager;
import org.openspaces.admin.internal.alert.events.InternalAlertTriggeredEventManager;
import org.openspaces.core.bean.DefaultBeanServer;

public class DefaultAlertManager implements InternalAlertManager {

    private final Admin admin;
    private final InternalAlertTriggeredEventManager alertEventManager;
    private final AlertRepository alertRepository;
    private final BeanConfigPropertiesManager beanConfigPropertiesManager;

    public DefaultAlertManager(Admin admin) {
        this.admin = admin;
        this.alertEventManager = new DefaultAlertEventManager(this);
        this.alertRepository = new DefaultAlertRepository();
        this.beanConfigPropertiesManager = new DefaultBeanServer<AlertBean>(admin);
    }

    @Override
    public AlertRepository getAlertRepository() {
        return alertRepository;
    }

    @Override
    public AlertTriggeredEventManager getAlertTriggered() {
        return alertEventManager;
    }

    @Override
    public void triggerAlert(Alert alert) {
        alertRepository.addAlert(alert);
        alertEventManager.alertTriggered(alert);
    }

    @Override
    public Admin getAdmin() {
        return admin;
    }

    @Override
    public BeanConfigPropertiesManager getBeanConfigPropertiesManager() {
        return beanConfigPropertiesManager;
    }

    @Override
    public void disableAlert(Class<? extends AlertConfiguration> clazz) throws AlertConfigurationException {
        try {
            BeanConfig configInstance = getConfigInstance(clazz);
            beanConfigPropertiesManager.disableBean(configInstance.getBeanClassName());
        }catch(Exception e) {
            throw new AlertConfigurationException("Failed to disable alert ["+clazz.getName()+"]", e);
        }
    }

    @Override
    public void enableAlert(Class<? extends AlertConfiguration> clazz) throws AlertConfigurationException {
        try {
            BeanConfig configInstance = getConfigInstance(clazz);
            beanConfigPropertiesManager.enableBean(configInstance.getBeanClassName());
        }catch(Exception e) {
            throw new AlertConfigurationException("Failed to enable alert ["+clazz.getName()+"]", e);
        }
    }

    @Override
    public <T extends AlertConfiguration> T getConfig(Class<T> clazz) throws AlertConfigurationException {
        try {
            T configInstance = getConfigInstance(clazz);
            Map<String, String> beanProperties = beanConfigPropertiesManager.getBeanConfig(configInstance.getBeanClassName());
            configInstance.setProperties(beanProperties);
            configInstance.setEnabled(beanConfigPropertiesManager.isBeanEnabled(configInstance.getBeanClassName()));
            return configInstance;
        }catch(Exception e) {
            throw new AlertConfigurationException("Failed to get alert configuration ["+clazz.getName()+"]", e);
        }
    }

    @Override
    public boolean removeConfig(Class<? extends AlertConfiguration> clazz) throws AlertConfigurationException {
        try {
            BeanConfig configInstance = getConfigInstance(clazz);
            return beanConfigPropertiesManager.removeBeanConfig(configInstance.getBeanClassName());
        } catch (Exception e) {
            throw new AlertConfigurationException("Failed to remove alert configuration [" + clazz.getName() + "]", e);
        }
    }

    @Override
    public void setConfig(AlertConfiguration config) throws AlertConfigurationException {
        try {
            beanConfigPropertiesManager.setBeanConfig(config.getBeanClassName(), config.getProperties());
        }catch(Exception e) {
            throw new AlertConfigurationException("Failed to set alert configuration [" + config.getClass().getName() + "]", e);
        }
    }

    @Override
    public boolean isAlertEnabled(Class<? extends AlertConfiguration> clazz) {
        try {
            BeanConfig configInstance = getConfigInstance(clazz);
            return beanConfigPropertiesManager.isBeanEnabled(configInstance.getBeanClassName());
        }catch(Exception e) {
            return false; //ignore
        }
    }

    @Override
    public void configure(AlertConfiguration... configurations) throws AlertConfigurationException {
        for (AlertConfiguration configuration : configurations) {
            try {
                disableAlert(configuration.getClass());
            }catch(AlertConfigurationException e) {
                //silently ignore if called to enable/disable a bean with no configuration
                if (!(e.getCause() instanceof BeanConfigNotFoundException)) {
                    throw e;
                }
            }
            setConfig(configuration);
            if (configuration.isEnabled()) {
                enableAlert(configuration.getClass());
            }
        }
    }

    private <T extends BeanConfig> T getConfigInstance(Class<T> clazz) {
        try {
            T newInstance = clazz.newInstance();
            return newInstance;
        } catch (Exception e) {
            throw new BeanConfigNotFoundException("Unable to extract bean name from " + clazz, e);
        }
    }
}


text:
The intent of the Flyweight Pattern is to use shared objects to support
large numbers of fine-grained objects efficiently.
A flyweight is a shared object that can be used in multiple contexts simultaneously.
The flyweight acts as an independent object in each context.
The shared object operates with 2 different types of state: internal and external.
Internal state is stored in the flyweight; it consists of information
that's independent of the flyweight's context, thereby making it sharable.
The external state depends on and varies with the flyweight's context
and therefore can't be shared.
Client objects are responsible for passing external state to the flyweight when it needs it.

## How it works?
In our example we use following classes. Check the `Code.java` - is used to set
the code done by the programmer in order to get it executed. A `Platform.java` - is an interface
is implemented by the language specific platform in order to execute the code.
It has one method, executes, which takes the `Code` object as its parameter.
A `PlatformFactory.java` - factory class which controls the creation of the Platform objects.
A method `getPlatformInstance` - a static method which has a `platformType` as its parameter.
This platformType is used as the key in the map, it first checks the map whether
a platform object having the key is already exists or not.
If no object found, the appropriate platform object gets created, it is put into the map
and then the method returns the object. There are a few implementations of `platform`
interface: `CPlatform.java`, `CPPPlatform.java`, `JavaPlatform.java`, `RubyPlatform.java`.
Now, run the `FlyweightExample.java` the output clearly shows that the platform objects created only the first time
they are requested for; on the next attempts the same object gets returned.
As a result we reduced the amount of instances of heavy-weight objects.

## When to use The Flyweight?
Effectiveness of this pattern depends heavily on how and where it's used.
So use it when:

1. Group of objects may be replaced by relatively few shared objects once external state is removed.
2. The application doesn't depend on object identity.
3. Storage costs are high because of the sheer quantity of objects.


text:
package Constants;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

public class Ressource {
	private static Ressource instance = null;
	protected Ressource() {

	}
	public static Ressource getInstance() {
		if (instance == null) {
			instance = new Ressource();
		}
		return instance;
	}

	private boolean imagesLoaded = false;

	public String getTitle(){
		return "title";
	}

	public Image getWallpaper(){
		return scale(Toolkit.getDefaultToolkit().getImage("image/wallpaper.jpg"), Layout.getInstance().getScreenWidth(), Layout.getInstance().getScreenHeight());
	}

	public Image getTileImage(TileType type, int digit) {
		switch (type){
		case BAMBOO:
			return scaleTile(Toolkit.getDefaultToolkit().getImage("image/bamboo/"+ digit + ".png"));
		case CIRCLE:
			return scaleTile(Toolkit.getDefaultToolkit().getImage("image/circle/"+ digit + ".png"));
		case CHARACTER:
			return scaleTile(Toolkit.getDefaultToolkit().getImage("image/character/"+ digit + ".png"));
		default:
			return scaleTile(Toolkit.getDefaultToolkit().getImage("image/face_down.png"));
		}
	}
	public Image getDeckImage() {
		return scale(Toolkit.getDefaultToolkit().getImage("image/face_down.png"), Layout.getInstance().getDeckSize(), Layout.getInstance().getDeckSize());
	}

	public Image getFocusTile() {
		return scaleTile(Toolkit.getDefaultToolkit().getImage("image/focus.png"));
	}

	public Image getFocusButton() {
		return scaleButton(Toolkit.getDefaultToolkit().getImage("image/focus.png"));
	}

	public Image getThrowButton() {
		return scaleButton(Toolkit.getDefaultToolkit().getImage("image/throw.png"));
	}

	public Image getPassButton() {
		return scaleButton(Toolkit.getDefaultToolkit().getImage("image/pass.png"));
	}

	public Image getTakeButton() {
		return scaleButton(Toolkit.getDefaultToolkit().getImage("image/take.png"));
	}

	public Image getCantTakeButton() {
		return scaleButton(Toolkit.getDefaultToolkit().getImage("image/cant_take.png"));
	}

	private Image scaleTile(Image source){
		return scale(source, Layout.getInstance().getTileImageSize(), Layout.getInstance().getTileImageSize());
	}

	private Image scaleButton(Image source){
		return scale(source, Layout.getInstance().getButtonSize(), Layout.getInstance().getButtonSize());
	}

	private Image scale(Image source, int width, int height) {
	    BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

	    Graphics2D g = buf.createGraphics();
	    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	    g.drawImage(source, 0, 0, width, height, null);
	    g.dispose();

	    return buf;
	}
	public String getFontStyle() {
		return "Impact";
	}
}


text:
// Main entry code OpenCV

#include <cv.h>
#include <highgui.h>
#include <cvaux.h>

#include "ocr.h"

#include <iostream>
#include <vector>

using namespace std;
using namespace cv;
OCR ocr;

void generateRandom(int n, int min, int max, vector<int>* samples) {
  int range = max - min;
  int r = rand() % range + min;
  if (samples->at(r) == 0) {
    samples->at(r) = 1;
    n++;
  }
  if (n < 100) {
    generateRandom(n, min, max, samples);
  }
}

float test(Mat samples, Mat classes) {
  float errors = 0;
  for (int i = 0; i < samples.rows; i++) {
    int result = ocr.classify(samples.row(i));

    if (result != classes.at<int>(i)) errors++;
  }
  return errors / samples.rows;
}

int main(int argc, char** argv) {
  int nh;
  char* data;
  // Check params
  if (argc >= 2) {
    nh = atoi(argv[1]);
    data = argv[2];
  } else {
    cout << "Usage:\n" << argv[0]
         << " <num hidden nodes> <data to load from xml>\n";
    return 0;
  }

  Mat classes;
  Mat trainingData;

  // Read file storage.
  FileStorage fs;
  fs.open("ocr.xml", FileStorage::READ);

  fs[data] >> trainingData;
  fs["classes"] >> classes;

  float result;

  // init random generator
  srand(time(NULL));
  // Create 100 random pos for samples
  std::vector<int> isSample(trainingData.rows, 0);
  generateRandom(0, 0, trainingData.rows - 1, &isSample);

  // Create sample data
  Mat train, trainClasses;
  Mat samples, samplesClasses;
  for (int i = 0; i < trainingData.rows; i++) {
    if (isSample[i] == 1) {
      samples.push_back(trainingData.row(i));
      samplesClasses.push_back(classes.row(i));
    } else {
      train.push_back(trainingData.row(i));
      trainClasses.push_back(classes.row(i));
    }
  }

  result = 0;

  ocr.train(train, trainClasses, nh);
  result = test(samples, samplesClasses);

  // cout << nh <<  "\t" << data << "\t"<< result <<"\n";
  cout << result;

  return 0;
}


text:
#ifndef JOINTMARKER_H_
#define JOINTMARKER_H_
// workaround for qt moc bug w.r.t. BOOST_JOIN macro
// see https://bugreports.qt.io/browse/QTBUG-22829
#ifndef Q_MOC_RUN
    #include <openrave/openrave.h>
#endif
#include <interactive_markers/interactive_marker_server.h>

namespace or_rviz {
namespace markers {

class JointMarker;
typedef boost::shared_ptr<JointMarker> JointMarkerPtr;

class JointMarker {
public:
    JointMarker(boost::shared_ptr<interactive_markers::InteractiveMarkerServer> server,
                OpenRAVE::KinBody::JointPtr joint);
    virtual ~JointMarker();

    std::string id() const;
    OpenRAVE::KinBody::JointPtr joint() const;

    void set_parent_frame(std::string const &frame_id);

    OpenRAVE::Transform pose() const;
    void set_pose(OpenRAVE::Transform const &pose);

    double angle() const;

    void set_joint_pose(OpenRAVE::Transform const &pose);

    virtual bool EnvironmentSync();

    static OpenRAVE::Transform GetJointPose(OpenRAVE::KinBody::JointPtr joint);

protected:
    boost::shared_ptr<interactive_markers::InteractiveMarkerServer> server_;
    visualization_msgs::InteractiveMarker marker_;
    visualization_msgs::InteractiveMarkerControl *joint_control_;

private:
    OpenRAVE::KinBody::JointWeakPtr joint_;
    OpenRAVE::Transform joint_pose_;
    double joint_initial_;
    double joint_delta_;
    bool created_;
    bool force_update_;
    bool active_;

    bool is_implemented_;  // does this marker do anything?

    void JointCallback(visualization_msgs::InteractiveMarkerFeedbackConstPtr const &feedback);
};

}
}

#endif