hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
468a87ea5be096f236c2d431ed9fe681337e902d | 493 | h | C | OXGame/Interface/UIMessageBox.h | kreuwont/OXGame | 6de134161f2bb67c09c99f52b2ec966c31aed4fd | [
"MIT"
] | null | null | null | OXGame/Interface/UIMessageBox.h | kreuwont/OXGame | 6de134161f2bb67c09c99f52b2ec966c31aed4fd | [
"MIT"
] | null | null | null | OXGame/Interface/UIMessageBox.h | kreuwont/OXGame | 6de134161f2bb67c09c99f52b2ec966c31aed4fd | [
"MIT"
] | null | null | null | #ifndef _UI_MESSAGE_BOX_H_
#define _UI_MESSAGE_BOX_H_
class UIBase;
class UIMessageBox : public UIBase
{
public:
UIMessageBox(int realX, int realY, int realWidth, int realHeigth, UIBase* pParent);
~UIMessageBox();
void Render();
void setText(std::string text) { m_uiText.setText(text); }
std::string getText() const { return m_uiText.getText(); }
bool OnLeftButtonClick(int x, int y);
private:
UIText m_uiText;
UIText m_uiClose;
int m_nFixedX;
};
#endif // !_UI_MESSAGE_BOX_H_
| 18.961538 | 84 | 0.744422 | [
"render"
] |
468c498628979206f7c86ff6c3d6dfda473535a2 | 23,510 | c | C | subsys/net/lib/lwm2m/lwm2m_rw_json.c | MartinFletzer/zephyr | 2a175b6abdd47c85345029b19c358a3dd8c611aa | [
"Apache-2.0"
] | 1 | 2022-03-21T12:50:43.000Z | 2022-03-21T12:50:43.000Z | subsys/net/lib/lwm2m/lwm2m_rw_json.c | thulithwilfred/zephyr | 0e4d7055e70b752c1dbc5bc3de8f0399dac76fe9 | [
"Apache-2.0"
] | 3 | 2021-10-14T04:32:03.000Z | 2021-11-12T09:02:16.000Z | subsys/net/lib/lwm2m/lwm2m_rw_json.c | thulithwilfred/zephyr | 0e4d7055e70b752c1dbc5bc3de8f0399dac76fe9 | [
"Apache-2.0"
] | 1 | 2022-02-20T21:00:33.000Z | 2022-02-20T21:00:33.000Z | /*
* Copyright (c) 2017 Linaro Limited
* Copyright (c) 2018-2019 Foundries.io
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Copyright (c) 2016, Eistec AB.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Original Authors:
* Joakim Nohlgård <joakim.nohlgard@eistec.se>
* Joakim Eriksson <joakime@sics.se> added JSON reader parts
*/
/*
* Zephyr Contribution by Michael Scott <michael.scott@linaro.org>
* - Zephyr code style changes / code cleanup
* - Move to Zephyr APIs where possible
* - Convert to Zephyr int/uint types
* - Remove engine dependency (replace with writer/reader context)
* - Add write / read int64 functions
*/
/*
* TODO:
* - Debug formatting errors in Leshan
* - Replace magic #'s with defines
*/
#define LOG_MODULE_NAME net_lwm2m_json
#define LOG_LEVEL CONFIG_LWM2M_LOG_LEVEL
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(LOG_MODULE_NAME);
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <inttypes.h>
#include <ctype.h>
#include <zephyr/data/json.h>
#include "lwm2m_object.h"
#include "lwm2m_rw_json.h"
#include "lwm2m_engine.h"
#include "lwm2m_util.h"
struct json_string_payload {
const char *name;
const char *val_string;
};
struct json_boolean_payload {
const char *name;
bool val_bool;
};
struct json_float_payload {
const char *name;
struct json_obj_token val_float;
};
struct json_array_object {
union {
struct json_float_payload float_obj;
struct json_boolean_payload boolean_obj;
struct json_string_payload string_obj;
} obj;
};
/* Decode payload structure */
struct json_context {
const char *base_name;
struct json_obj_token obj_array;
};
/* Decode description structure for parsing LwM2m JSON main object*/
static const struct json_obj_descr json_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_context, "bn",
base_name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_context, "e",
obj_array, JSON_TOK_OBJ_ARRAY),
};
#define JSON_BN_TYPE 1
#define JSON_E_TYPE 2
/* Decode payload structure */
struct json_obj_struct {
const char *name;
char *val_object_link;
const char *val_string;
struct json_obj_token val_float;
bool val_bool;
};
/* Decode description structure for parsing LwM2m JSON Arrary object*/
static const struct json_obj_descr json_obj_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_obj_struct, "n",
name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_obj_struct, "v",
val_float, JSON_TOK_FLOAT),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_obj_struct, "bv",
val_bool, JSON_TOK_TRUE),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_obj_struct, "ov",
val_object_link, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_obj_struct, "sv",
val_string, JSON_TOK_STRING),
};
#define JSON_N_TYPE 1
#define JSON_V_TYPE 2
#define JSON_BV_TYPE 4
#define JSON_OV_TYPE 8
#define JSON_SV_TYPE 16
#define JSON_NAME_MASK (JSON_N_TYPE)
#define JSON_VAL_MASK (JSON_V_TYPE + JSON_BV_TYPE + JSON_OV_TYPE + JSON_SV_TYPE)
static const struct json_obj_descr json_float_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_float_payload, "n",
name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_float_payload, "v",
val_float, JSON_TOK_FLOAT),
};
static const struct json_obj_descr json_boolean_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_boolean_payload, "n",
name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_boolean_payload, "bv",
val_bool, JSON_TOK_TRUE),
};
static const struct json_obj_descr json_obj_lnk_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_string_payload, "n",
name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_string_payload, "ov",
val_string, JSON_TOK_STRING),
};
static const struct json_obj_descr json_string_descr[] = {
JSON_OBJ_DESCR_PRIM_NAMED(struct json_string_payload, "n",
name, JSON_TOK_STRING),
JSON_OBJ_DESCR_PRIM_NAMED(struct json_string_payload, "sv",
val_string, JSON_TOK_STRING),
};
struct json_out_formatter_data {
uint8_t writer_flags;
char name_string[sizeof("/65535/65535/") + 1];
struct json_array_object json;
struct lwm2m_output_context *out;
};
struct json_in_formatter_data {
uint8_t json_flags;
int object_bit_field;
struct json_obj_struct array_object;
};
/* some temporary buffer space for format conversions */
static char pt_buffer[42];
static int init_object_name_parameters(struct json_out_formatter_data *fd,
struct lwm2m_obj_path *path)
{
int ret;
/* Init Name string */
if (fd->writer_flags & WRITER_RESOURCE_INSTANCE) {
ret = snprintk(fd->name_string, sizeof(fd->name_string), "%u/%u", path->res_id,
path->res_inst_id);
} else {
ret = snprintk(fd->name_string, sizeof(fd->name_string), "%u", path->res_id);
}
if (ret < 0) {
return ret;
}
return 0;
}
static int number_to_string(const char *format, ...)
{
va_list vargs;
int n;
va_start(vargs, format);
n = vsnprintk(pt_buffer, sizeof(pt_buffer), format, vargs);
va_end(vargs);
if (n < 0 || n >= sizeof(pt_buffer)) {
return -EINVAL;
}
return n;
}
static int float_to_string(double *value)
{
int len;
len = lwm2m_ftoa(value, pt_buffer, sizeof(pt_buffer), 15);
if (len < 0 || len >= sizeof(pt_buffer)) {
LOG_ERR("Failed to encode float value");
return -EINVAL;
}
return len;
}
static int objlnk_to_string(struct lwm2m_objlnk *value)
{
return snprintk(pt_buffer, sizeof(pt_buffer), "%u:%u", value->obj_id, value->obj_inst);
}
static int json_add_separator(struct lwm2m_output_context *out, struct json_out_formatter_data *fd)
{
int len = 0;
if (fd->writer_flags & WRITER_OUTPUT_VALUE) {
/* Add separator */
char separator = ',';
len = buf_append(CPKT_BUF_WRITE(out->out_cpkt), &separator, sizeof(separator));
if (len < 0) {
return -ENOMEM;
}
}
return len;
}
static void json_postprefix(struct json_out_formatter_data *fd)
{
fd->writer_flags |= WRITER_OUTPUT_VALUE;
}
static int json_float_object_write(struct lwm2m_output_context *out,
struct json_out_formatter_data *fd, int float_string_length)
{
int res, len;
ssize_t o_len;
const struct json_obj_descr *descr;
size_t descr_len;
void *obj_payload;
len = json_add_separator(out, fd);
if (len < 0) {
return len;
}
descr = json_float_descr;
descr_len = ARRAY_SIZE(json_float_descr);
obj_payload = &fd->json.obj.float_obj;
fd->json.obj.float_obj.name = fd->name_string;
fd->json.obj.float_obj.val_float.start = pt_buffer;
fd->json.obj.float_obj.val_float.length = float_string_length;
/* Calculate length */
o_len = json_calc_encoded_len(descr, descr_len, obj_payload);
if (o_len < 0) {
return -EINVAL;
}
/* Encode */
res = json_obj_encode_buf(descr, descr_len, obj_payload,
CPKT_BUF_W_REGION(out->out_cpkt));
if (res < 0) {
return -ENOMEM;
}
len += o_len;
out->out_cpkt->offset += len;
json_postprefix(fd);
return len;
}
static int json_string_object_write(struct lwm2m_output_context *out,
struct json_out_formatter_data *fd, char *buf)
{
int res, len;
ssize_t o_len;
const struct json_obj_descr *descr;
size_t descr_len;
void *obj_payload;
len = json_add_separator(out, fd);
if (len < 0) {
return len;
}
descr = json_string_descr;
descr_len = ARRAY_SIZE(json_string_descr);
obj_payload = &fd->json.obj.string_obj;
fd->json.obj.string_obj.name = fd->name_string;
fd->json.obj.string_obj.val_string = buf;
/* Calculate length */
o_len = json_calc_encoded_len(descr, descr_len, obj_payload);
if (o_len < 0) {
return -EINVAL;
}
/* Encode */
res = json_obj_encode_buf(descr, descr_len, obj_payload,
CPKT_BUF_W_REGION(out->out_cpkt));
if (res < 0) {
return -ENOMEM;
}
len += o_len;
out->out_cpkt->offset += len;
json_postprefix(fd);
return len;
}
static int json_boolean_object_write(struct lwm2m_output_context *out,
struct json_out_formatter_data *fd, bool value)
{
int res, len;
ssize_t o_len;
const struct json_obj_descr *descr;
size_t descr_len;
void *obj_payload;
len = json_add_separator(out, fd);
if (len < 0) {
return len;
}
descr = json_boolean_descr;
descr_len = ARRAY_SIZE(json_boolean_descr);
obj_payload = &fd->json.obj.boolean_obj;
fd->json.obj.boolean_obj.name = fd->name_string;
fd->json.obj.boolean_obj.val_bool = value;
/* Calculate length */
o_len = json_calc_encoded_len(descr, descr_len, obj_payload);
if (o_len < 0) {
return -EINVAL;
}
/* Encode */
res = json_obj_encode_buf(descr, descr_len, obj_payload,
CPKT_BUF_W_REGION(out->out_cpkt));
if (res < 0) {
return -ENOMEM;
}
len += o_len;
out->out_cpkt->offset += len;
json_postprefix(fd);
return len;
}
static int json_objlnk_object_write(struct lwm2m_output_context *out,
struct json_out_formatter_data *fd)
{
int res, len;
ssize_t o_len;
const struct json_obj_descr *descr;
size_t descr_len;
void *obj_payload;
len = json_add_separator(out, fd);
if (len < 0) {
return len;
}
descr = json_obj_lnk_descr;
descr_len = ARRAY_SIZE(json_obj_lnk_descr);
obj_payload = &fd->json.obj.string_obj;
fd->json.obj.string_obj.name = fd->name_string;
fd->json.obj.string_obj.val_string = pt_buffer;
/* Calculate length */
o_len = json_calc_encoded_len(descr, descr_len, obj_payload);
if (o_len < 0) {
return -EINVAL;
}
/* Encode */
res = json_obj_encode_buf(descr, descr_len, obj_payload,
CPKT_BUF_W_REGION(out->out_cpkt));
if (res < 0) {
return -ENOMEM;
}
len += o_len;
out->out_cpkt->offset += len;
json_postprefix(fd);
return len;
}
static int put_begin(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path)
{
int len = -1, res;
if (path->level >= 2U) {
len = snprintk(pt_buffer, sizeof(pt_buffer),
"{\"bn\":\"/%u/%u/\",\"e\":[",
path->obj_id, path->obj_inst_id);
} else {
len = snprintk(pt_buffer, sizeof(pt_buffer),
"{\"bn\":\"/%u/\",\"e\":[",
path->obj_id);
}
if (len < 0) {
return len;
}
res = buf_append(CPKT_BUF_WRITE(out->out_cpkt), pt_buffer, len);
if (res < 0) {
return res;
}
return len;
}
static int put_end(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path)
{
int res;
res = buf_append(CPKT_BUF_WRITE(out->out_cpkt), "]}", 2);
if (res < 0) {
return res;
}
return 2;
}
static int put_begin_ri(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path)
{
struct json_out_formatter_data *fd;
fd = engine_get_out_user_data(out);
if (!fd) {
return -EINVAL;
}
fd->writer_flags |= WRITER_RESOURCE_INSTANCE;
return 0;
}
static int put_end_ri(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path)
{
struct json_out_formatter_data *fd;
fd = engine_get_out_user_data(out);
if (!fd) {
return -EINVAL;
}
fd->writer_flags &= ~WRITER_RESOURCE_INSTANCE;
return 0;
}
static int put_s32(struct lwm2m_output_context *out, struct lwm2m_obj_path *path, int32_t value)
{
struct json_out_formatter_data *fd;
int len = 0;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
len = number_to_string("%d", value);
if (len < 0) {
return len;
}
return json_float_object_write(out, fd, len);
}
static int put_s16(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, int16_t value)
{
return put_s32(out, path, (int32_t)value);
}
static int put_s8(struct lwm2m_output_context *out, struct lwm2m_obj_path *path,
int8_t value)
{
return put_s32(out, path, (int32_t)value);
}
static int put_s64(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, int64_t value)
{
struct json_out_formatter_data *fd;
int len;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
len = number_to_string("%lld", value);
if (len < 0) {
return len;
}
return json_float_object_write(out, fd, len);
}
static int put_string(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, char *buf, size_t buflen)
{
struct json_out_formatter_data *fd;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
return json_string_object_write(out, fd, buf);
}
static int put_float(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, double *value)
{
struct json_out_formatter_data *fd;
int len;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
len = float_to_string(value);
if (len < 0) {
return len;
}
return json_float_object_write(out, fd, len);
}
static int put_bool(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, bool value)
{
struct json_out_formatter_data *fd;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
return json_boolean_object_write(out, fd, value);
}
static int put_objlnk(struct lwm2m_output_context *out,
struct lwm2m_obj_path *path, struct lwm2m_objlnk *value)
{
struct json_out_formatter_data *fd;
fd = engine_get_out_user_data(out);
if (!out->out_cpkt || !fd) {
return -EINVAL;
}
if (init_object_name_parameters(fd, path)) {
return -EINVAL;
}
if (objlnk_to_string(value) < 0) {
return -EINVAL;
}
return json_objlnk_object_write(out, fd);
}
static int read_int(struct lwm2m_input_context *in, int64_t *value,
bool accept_sign)
{
struct json_in_formatter_data *fd;
uint8_t *buf;
int i = 0;
bool neg = false;
char c;
/* initialize values to 0 */
*value = 0;
fd = engine_get_in_user_data(in);
if (!fd || (fd->object_bit_field & JSON_V_TYPE) == 0) {
return -EINVAL;
}
if (fd->array_object.val_float.length == 0) {
return -ENODATA;
}
buf = fd->array_object.val_float.start;
while (*(buf + i) && i < fd->array_object.val_float.length) {
c = *(buf + i);
if (c == '-' && accept_sign && i == 0) {
neg = true;
} else if (isdigit(c)) {
*value = *value * 10 + (c - '0');
} else {
/* anything else stop reading */
break;
}
i++;
}
if (neg) {
*value = -*value;
}
return i;
}
static int get_s64(struct lwm2m_input_context *in, int64_t *value)
{
return read_int(in, value, true);
}
static int get_s32(struct lwm2m_input_context *in, int32_t *value)
{
int64_t tmp = 0;
int len = 0;
len = read_int(in, &tmp, true);
if (len > 0) {
*value = (int32_t)tmp;
}
return len;
}
static int get_string(struct lwm2m_input_context *in, uint8_t *buf,
size_t buflen)
{
struct json_in_formatter_data *fd;
size_t string_length;
fd = engine_get_in_user_data(in);
if (!fd || (fd->object_bit_field & JSON_SV_TYPE) == 0) {
return -EINVAL;
}
string_length = strlen(fd->array_object.val_string);
if (string_length > buflen) {
LOG_WRN("Buffer too small to accommodate string, truncating");
string_length = buflen - 1;
}
memcpy(buf, fd->array_object.val_string, string_length);
/* add NULL */
buf[string_length] = '\0';
return string_length;
}
static int get_float(struct lwm2m_input_context *in, double *value)
{
struct json_in_formatter_data *fd;
int i = 0, len = 0;
bool has_dot = false;
uint8_t tmp, buf[24];
uint8_t *json_buf;
fd = engine_get_in_user_data(in);
if (!fd || (fd->object_bit_field & JSON_V_TYPE) == 0) {
return -EINVAL;
}
size_t value_length = fd->array_object.val_float.length;
if (value_length == 0) {
return -ENODATA;
}
json_buf = fd->array_object.val_float.start;
while (*(json_buf + len) && len < value_length) {
tmp = *(json_buf + len);
if ((tmp == '-' && i == 0) || (tmp == '.' && !has_dot) ||
isdigit(tmp)) {
len++;
/* Copy only if it fits into provided buffer - we won't
* get better precision anyway.
*/
if (i < sizeof(buf) - 1) {
buf[i++] = tmp;
}
if (tmp == '.') {
has_dot = true;
}
} else {
break;
}
}
buf[i] = '\0';
if (lwm2m_atof(buf, value) != 0) {
LOG_ERR("Failed to parse float value");
return -EBADMSG;
}
return len;
}
static int get_bool(struct lwm2m_input_context *in, bool *value)
{
struct json_in_formatter_data *fd;
fd = engine_get_in_user_data(in);
if (!fd || (fd->object_bit_field & JSON_BV_TYPE) == 0) {
return -EINVAL;
}
*value = fd->array_object.val_bool;
return 1;
}
static int get_opaque(struct lwm2m_input_context *in, uint8_t *value,
size_t buflen, struct lwm2m_opaque_context *opaque,
bool *last_block)
{
/* TODO */
return -EOPNOTSUPP;
}
static int get_objlnk(struct lwm2m_input_context *in,
struct lwm2m_objlnk *value)
{
int64_t tmp;
int len, total_len;
struct json_in_formatter_data *fd;
char *demiliter_pos;
fd = engine_get_in_user_data(in);
if (!fd || (fd->object_bit_field & JSON_OV_TYPE) == 0) {
return -EINVAL;
}
demiliter_pos = strchr(fd->array_object.val_object_link, ':');
if (!demiliter_pos) {
return -ENODATA;
}
fd->object_bit_field |= JSON_V_TYPE;
fd->array_object.val_float.start = fd->array_object.val_object_link;
fd->array_object.val_float.length = strlen(fd->array_object.val_object_link);
/* Set String end for first item */
*demiliter_pos = '\0';
len = read_int(in, &tmp, false);
if (len <= 0) {
return -ENODATA;
}
total_len = len;
value->obj_id = (uint16_t)tmp;
len++; /* +1 for ':' delimiter. */
demiliter_pos++;
fd->array_object.val_float.start = demiliter_pos;
fd->array_object.val_float.length = strlen(demiliter_pos);
len = read_int(in, &tmp, false);
if (len <= 0) {
return -ENODATA;
}
total_len += len;
value->obj_inst = (uint16_t)tmp;
return total_len;
}
const struct lwm2m_writer json_writer = {
.put_begin = put_begin,
.put_end = put_end,
.put_begin_ri = put_begin_ri,
.put_end_ri = put_end_ri,
.put_s8 = put_s8,
.put_s16 = put_s16,
.put_s32 = put_s32,
.put_s64 = put_s64,
.put_string = put_string,
.put_float = put_float,
.put_time = put_s64,
.put_bool = put_bool,
.put_objlnk = put_objlnk,
};
const struct lwm2m_reader json_reader = {
.get_s32 = get_s32,
.get_s64 = get_s64,
.get_string = get_string,
.get_time = get_s64,
.get_float = get_float,
.get_bool = get_bool,
.get_opaque = get_opaque,
.get_objlnk = get_objlnk,
};
int do_read_op_json(struct lwm2m_message *msg, int content_format)
{
struct json_out_formatter_data fd;
int ret;
(void)memset(&fd, 0, sizeof(fd));
engine_set_out_user_data(&msg->out, &fd);
ret = lwm2m_perform_read_op(msg, content_format);
engine_clear_out_user_data(&msg->out);
return ret;
}
int do_write_op_json(struct lwm2m_message *msg)
{
struct lwm2m_engine_obj_field *obj_field = NULL;
struct lwm2m_engine_obj_inst *obj_inst = NULL;
struct lwm2m_engine_res *res = NULL;
struct lwm2m_engine_res_inst *res_inst = NULL;
struct lwm2m_obj_path orig_path;
struct json_in_formatter_data fd;
struct json_obj json_object;
struct json_context main_object;
char *data_ptr;
const char *base_name_ptr = NULL;
uint16_t in_len;
int ret = 0, obj_bit_field;
uint8_t full_name[MAX_RESOURCE_LEN + 1] = {0};
uint8_t created;
(void)memset(&fd, 0, sizeof(fd));
(void)memset(&main_object, 0, sizeof(main_object));
engine_set_in_user_data(&msg->in, &fd);
data_ptr = (char *)coap_packet_get_payload(msg->in.in_cpkt, &in_len);
obj_bit_field =
json_obj_parse(data_ptr, in_len, json_descr, ARRAY_SIZE(json_descr), &main_object);
if (obj_bit_field < 0 || (obj_bit_field & 2) == 0 || main_object.obj_array.length == 0) {
LOG_ERR("JSON object bits not valid %d", obj_bit_field);
ret = -EINVAL;
goto end_of_operation;
}
if (obj_bit_field & 1) {
base_name_ptr = main_object.base_name;
}
/* store a copy of the original path */
memcpy(&orig_path, &msg->path, sizeof(msg->path));
/* When No blockwise do Normal Init */
if (json_arr_separate_object_parse_init(&json_object, main_object.obj_array.start,
main_object.obj_array.length)) {
ret = -EINVAL;
goto end_of_operation;
}
while (1) {
(void)memset(&fd.array_object, 0, sizeof(fd.array_object));
fd.object_bit_field = json_arr_separate_parse_object(
&json_object, json_obj_descr, ARRAY_SIZE(json_obj_descr), &fd.array_object);
if (fd.object_bit_field == 0) {
/* End of */
break;
} else if (fd.object_bit_field < 0 ||
((fd.object_bit_field & JSON_VAL_MASK) == 0)) {
LOG_ERR("Json Write Parse object fail %d", fd.object_bit_field);
ret = -EINVAL;
goto end_of_operation;
}
/* Create object resource path */
if (base_name_ptr) {
if (fd.object_bit_field & JSON_N_TYPE) {
ret = snprintk(full_name, sizeof(full_name), "%s%s", base_name_ptr,
fd.array_object.name);
} else {
ret = snprintk(full_name, sizeof(full_name), "%s", base_name_ptr);
}
} else {
if ((fd.object_bit_field & JSON_N_TYPE) == 0) {
ret = -EINVAL;
goto end_of_operation;
}
ret = snprintk(full_name, sizeof(full_name), "%s", fd.array_object.name);
}
if (ret >= MAX_RESOURCE_LEN) {
ret = -EINVAL;
goto end_of_operation;
}
/* handle resource value */
/* reset values */
created = 0U;
/* parse full_name into path */
ret = lwm2m_string_to_path(full_name, &msg->path, '/');
if (ret < 0) {
LOG_ERR("Relative name too long");
ret = -EINVAL;
goto end_of_operation;
}
ret = lwm2m_get_or_create_engine_obj(msg, &obj_inst, &created);
if (ret < 0) {
break;
}
ret = lwm2m_engine_validate_write_access(msg, obj_inst, &obj_field);
if (ret < 0) {
return ret;
}
ret = lwm2m_engine_get_create_res_inst(&msg->path, &res, &res_inst);
if (ret < 0) {
return -ENOENT;
}
/* Write the resource value */
ret = lwm2m_write_handler(obj_inst, res, res_inst, obj_field, msg);
if (orig_path.level >= 3U && ret < 0) {
/* return errors on a single write */
break;
}
}
end_of_operation:
engine_clear_in_user_data(&msg->in);
return ret;
}
| 23.369781 | 99 | 0.704551 | [
"object"
] |
46a080e07ceae271b6a868f1f544348bf87c5d35 | 2,380 | h | C | suif/include/transform/lptrans.h | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | 5 | 2020-04-11T21:30:19.000Z | 2021-12-04T16:16:09.000Z | suif/include/transform/lptrans.h | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | null | null | null | suif/include/transform/lptrans.h | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | null | null | null | /* file "lptrans.h" */
/* Copyright (c) 1994 Stanford University
All rights reserved.
This software is provided under the terms described in
the "suif_copyright.h" include file. */
#include <suif_copyright.h>
/* Unimodular loop transformations and tiling */
#ifndef LPTRANS_H
#define LPTRANS_H
#pragma interface
#include <suif1.h>
#include <suifmath.h>
#include "bexpr.h"
RCS_HEADER(lptrans_h, "$Id$")
//
// Annotations
//
extern const char *k_doall;
extern const char *k_fpinner;
extern const char *k_tiled;
extern const char *k_tiledc;
struct tiled_annote
{
int depth;
boolean *doall_loops;
};
//
// Loop Transformations
//
class loop_transform {
friend boolean transform_body_src(instruction *i, operand *r, void *x);
friend void transform_body_tree(tree_node *tn, void *x);
private:
int depth;
tree_for **loops;
bizarre_bounds_info *binfo;
boolean *doall_loops;
boolean already_tiled;
void generate_bounds();
// Unimodular transformations
//
integer_matrix utrans;
integer_matrix utrans_inv;
void utransform();
void generate_inequality(access_vector *av, tree_for *tf);
int find_index(operand r);
boolean new_access(operand r, access_vector *access_vec);
void transform_body(instruction *ins);
void transform_body(tree_node_list *l);
// Tile transformations
//
int num_regions; // number of tiling regions
boolean *coalesce_region; // coalesce the given region?
int *trip_size; // trip size for *loop* (not the region)
int *first_loop; // number of the first loop in region.
// must have first_loop[num_regions] = depth
void tile_loops();
void tile_region(int region_num, int firsts, int last,
var_sym **outer_indices);
public:
loop_transform(int d, tree_for **tfs, boolean *doalls = NULL);
~loop_transform();
tree_for *get_loop(int i)
{ assert(i >= 0 && i < depth);
return (loops[i]); }
void annotate_doalls();
boolean unimodular_transform(integer_matrix &m);
boolean tile_transform(int *trip, int nregions, boolean *coalesce,
int *first);
};
extern boolean bounds_ok(tree_for *tf); // Are the bounds such that we can
// transform the loop nest?
#endif
| 22.45283 | 79 | 0.659664 | [
"transform"
] |
f219eb010a75f377e07b0e5a60f70c4f77556af1 | 876 | h | C | NewLLDebugTool/Components/Other/Function/LLBugReportSettingModel.h | didiaodanding/TestPods | f894a1633933f4ccf0ead56e78a296117037c82e | [
"MIT"
] | 1 | 2020-05-28T03:28:06.000Z | 2020-05-28T03:28:06.000Z | NewLLDebugTool/Components/Other/Function/LLBugReportSettingModel.h | didiaodanding/TestPods | f894a1633933f4ccf0ead56e78a296117037c82e | [
"MIT"
] | null | null | null | NewLLDebugTool/Components/Other/Function/LLBugReportSettingModel.h | didiaodanding/TestPods | f894a1633933f4ccf0ead56e78a296117037c82e | [
"MIT"
] | null | null | null | //
// LLBugReportSettingModel.h
// LLDebugToolDemo
//
// Created by apple on 2019/8/3.
// Copyright © 2019 li. All rights reserved.
//
#import "LLStorageModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface LLBugReportSettingModel : LLStorageModel
/**
* workspace_id
*/
@property (copy , nonatomic , nonnull) NSString *workspaceId;
/**
* crash owner
*/
@property (copy , nonatomic , nonnull) NSString *crashOwner;
/**
* js exception owner
*/
@property (copy , nonatomic , nonnull) NSString *JSExceptionOwner;
/**
* version
*/
@property (copy , nonatomic , nonnull) NSString *version;
/**
* creator
*/
@property (copy , nonatomic , nonnull) NSString *creator;
/**
Model identity.
*/
@property (nonatomic , copy , readonly , nonnull) NSString *identity;
- (instancetype _Nonnull)initWithIdentity:(NSString *_Nullable)identity ;
@end
NS_ASSUME_NONNULL_END
| 17.52 | 73 | 0.703196 | [
"model"
] |
f241cf4357c53e9178fdf8514d65ed0feebecc70 | 1,775 | h | C | PlanetSystem.h | simeonradivoev/PlanetarySystem | 08fbb9c86f6a591590a60be3d14e2c2c1aa09212 | [
"MIT"
] | 12 | 2015-07-07T21:53:14.000Z | 2022-01-04T01:49:18.000Z | PlanetSystem.h | simeonradivoev/PlanetarySystem | 08fbb9c86f6a591590a60be3d14e2c2c1aa09212 | [
"MIT"
] | null | null | null | PlanetSystem.h | simeonradivoev/PlanetarySystem | 08fbb9c86f6a591590a60be3d14e2c2c1aa09212 | [
"MIT"
] | 5 | 2016-08-03T22:49:27.000Z | 2021-08-30T12:33:11.000Z | #pragma once
#ifndef PLANET_SYSTEM_H
#define PLANET_SYSTEM_H
#include "Scene.h"
#include "texture2D.h"
#include "gui.h"
#include <list>
#include <glm\glm.hpp>
#include <glm\gtx\quaternion.hpp>
#include <queue>
#define GRID_CELLS_COUNT 256
#define ORBIT_PREDITION_STEPS 512
#define ORBIT_PREDITION_STEP_SIZE 0.2
#define MAX_PLANET_INTERACTION 16
class Material;
class Planet;
class LightPass;
class Canvas;
class Shader;
class PlanetSystem: public Scene
{
public:
PlanetSystem();
~PlanetSystem();
void FixedUpdate() override;
void Update() override;
void AddPlanet(Planet* planet);
void GeometryPass(Camera& cam) override;
void AtmospherePass(Camera& cam);
void TransperentPass(Camera& cam) override;
void LightingPass(Camera& cam,LightPass* lightPass) override;
void GUI(Canvas* canvas, Camera& camera) override;
void SelectedPlanetOptionsWindow(Canvas* canvas, GUI::Rect rect);
void CreateRandomPlanet();
void Create() override;
static const double G;
private:
std::list<Planet*> m_planets;
void MovePlanet(Planet* planet);
glm::dvec3 CalculateVelocity(Planet* planet, double timeStep);
void DrawGrid(Camera& camera);
void DrawPlanetPlace(Camera& camera);
void DrawPlanetPlaceHelpers(Camera& camera);
void PredictOrbit(Planet* planet);
void ManagePlanetPlace(Canvas* canvas);
double ForceBetween(Planet* a, Planet* b);
double round(double f, double prec);
double m_speed = 0.2;
Material* m_orbitMaterial;
Material* m_gridMaterial;
Transform m_gridTransform;
Planet* m_selectedPlanet = nullptr;
std::queue<Planet*> m_planetQueue;
Planet* m_planetToBePlaced = nullptr;
Texture2D m_earthTexture;
Texture2D m_sunTexture;
Texture2D m_jupiterTexture;
};
#endif //PLANET_SYSTEM_H | 27.734375 | 67 | 0.753803 | [
"transform"
] |
f2451d8191b9d926bebb29f455d6cc36c06b2122 | 5,270 | h | C | filedistribution/src/vespa/filedistribution/model/zkfacade.h | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | filedistribution/src/vespa/filedistribution/model/zkfacade.h | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | filedistribution/src/vespa/filedistribution/model/zkfacade.h | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <string>
#include <vector>
#include <map>
#include <mutex>
#include <vespa/filedistribution/common/buffer.h>
#include <vespa/filedistribution/common/exception.h>
#include <vespa/vespalib/util/exception.h>
struct _zhandle;
typedef _zhandle zhandle_t;
namespace filedistribution {
class ZKException : public vespalib::Exception {
protected:
using vespalib::Exception::Exception;
};
VESPA_DEFINE_EXCEPTION(ZKNodeDoesNotExistsException, ZKException);
VESPA_DEFINE_EXCEPTION(ZKConnectionLossException, ZKException);
VESPA_DEFINE_EXCEPTION(ZKNodeExistsException, ZKException);
VESPA_DEFINE_EXCEPTION(ZKFailedConnecting, ZKException);
VESPA_DEFINE_EXCEPTION(ZKOperationTimeoutException, ZKException);
VESPA_DEFINE_EXCEPTION(ZKSessionExpired, ZKException);
class ZKGenericException : public ZKException {
public:
ZKGenericException(int zkStatus, const vespalib::stringref &msg, const vespalib::stringref &location = "", int skipStack = 0) :
ZKException(msg, location, skipStack),
_zkStatus(zkStatus)
{ }
ZKGenericException(int zkStatus, const vespalib::Exception &cause, const vespalib::stringref &msg = "",
const vespalib::stringref &location = "", int skipStack = 0) :
ZKException(msg, cause, location, skipStack),
_zkStatus(zkStatus)
{ }
VESPA_DEFINE_EXCEPTION_SPINE(ZKGenericException);
private:
const int _zkStatus;
};
class ZKFacade : public std::enable_shared_from_this<ZKFacade> {
volatile bool _retriesEnabled;
volatile bool _watchersEnabled;
zhandle_t* _zhandle;
const static int _zkSessionTimeOut = 30 * 1000;
const static size_t _maxDataSize = 1024 * 1024;
class ZKWatcher;
static void stateWatchingFun(zhandle_t*, int type, int state, const char* path, void* context);
public:
typedef std::shared_ptr<ZKFacade> SP;
/* Lifetime is managed by ZKFacade.
Derived classes should only contain weak_ptrs to other objects
to avoid linking their lifetime to the ZKFacade lifetime.
*/
class NodeChangedWatcher {
public:
NodeChangedWatcher(const NodeChangedWatcher &) = delete;
NodeChangedWatcher & operator = (const NodeChangedWatcher &) = delete;
NodeChangedWatcher() = default;
virtual ~NodeChangedWatcher() {};
virtual void operator()() = 0;
};
typedef std::shared_ptr<NodeChangedWatcher> NodeChangedWatcherSP;
ZKFacade(const ZKFacade &) = delete;
ZKFacade & operator = (const ZKFacade &) = delete;
ZKFacade(const std::string& zkservers, bool allowDNSFailure);
~ZKFacade();
bool hasNode(const Path&);
bool hasNode(const Path&, const NodeChangedWatcherSP&);
const std::string getString(const Path&);
Buffer getData(const Path&); //throws ZKNodeDoesNotExistsException
//if watcher is specified, it will be set even if the node does not exists
Buffer getData(const Path&, const NodeChangedWatcherSP&); //throws ZKNodeDoesNotExistsException
//Parent path must exist
void setData(const Path&, const Buffer& buffer, bool mustExist = false);
void setData(const Path&, const char* buffer, size_t length, bool mustExist = false);
const Path createSequenceNode(const Path&, const char* buffer, size_t length);
void remove(const Path&); //throws ZKNodeDoesNotExistsException
void removeIfExists(const Path&);
void retainOnly(const Path&, const std::vector<std::string>& children);
void addEphemeralNode(const Path& path);
std::vector<std::string> getChildren(const Path& path);
std::vector<std::string> getChildren(const Path& path, const NodeChangedWatcherSP&); //throws ZKNodeDoesNotExistsException
//only for use by shutdown code.
void disableRetries();
bool retriesEnabled() {
return _retriesEnabled;
}
static std::string getValidZKServers(const std::string &input, bool ignoreDNSFailure);
private:
class RegistrationGuard {
public:
RegistrationGuard & operator = (const RegistrationGuard &) = delete;
RegistrationGuard(const RegistrationGuard &) = delete;
RegistrationGuard(ZKFacade & zk, const NodeChangedWatcherSP & watcher) : _zk(zk), _watcherContext(_zk.registerWatcher(watcher)) { }
~RegistrationGuard() {
if (_watcherContext) {
_zk.unregisterWatcher(_watcherContext);
}
}
void * get() { return _watcherContext; }
void release() { _watcherContext = nullptr; }
private:
ZKFacade & _zk;
void * _watcherContext;
};
void* registerWatcher(const NodeChangedWatcherSP &); //returns watcherContext
std::shared_ptr<ZKWatcher> unregisterWatcher(void* watcherContext);
void invokeWatcher(void* watcherContext);
std::mutex _watchersMutex;
typedef std::map<void*, std::shared_ptr<ZKWatcher> > WatchersMap;
WatchersMap _watchers;
};
class ZKLogging {
public:
ZKLogging();
~ZKLogging();
ZKLogging(const ZKLogging &) = delete;
ZKLogging & operator = (const ZKLogging &) = delete;
private:
FILE * _file;
};
} //namespace filedistribution
| 35.608108 | 139 | 0.714801 | [
"vector"
] |
f245811580f6145222defda7ed4b26c4f4c444e6 | 9,679 | h | C | ds/security/base/lsa/server/lsads.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/base/lsa/server/lsads.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/base/lsa/server/lsads.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
lsads.h
Abstract:
Private macros/definitions/prototypes for implementing portions of the LSA store
in the DS and in the registry, simultaneously
Author:
Mac McLain (MacM) Jan 17, 1997
Environment:
User Mode
Revision History:
--*/
#ifndef __LSADS_H__
#define __LSADS_H__
#include <ntdsa.h>
#include <dsysdbg.h>
#include <safelock.h>
#if DBG == 1
#ifdef ASSERT
#undef ASSERT
#endif
#define ASSERT DsysAssert
#define DEB_UPGRADE 0x10
#define DEB_POLICY 0x20
#define DEB_FIXUP 0x80
#define DEB_NOTIFY 0x100
#define DEB_DSNOTIFY 0x200
#define DEB_FTRACE 0x400
#define DEB_LOOKUP 0x800
#define DEB_HANDLE 0x1000
#define DEB_FTINFO 0x2000
#define DEB_SIDFILTER 0x4000
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
DECLARE_DEBUG2( LsaDs )
#ifdef __cplusplus
}
#endif // __cplusplus
#define LsapDsDebugOut( args ) LsaDsDebugPrint args
#define LsapEnterFunc( x ) \
LsaDsDebugPrint( DEB_FTRACE, "0x%lx: Entering %s\n", GetCurrentThreadId(), x );
#define LsapExitFunc( x, y ) \
LsaDsDebugPrint( DEB_FTRACE, "0x%lx: Leaving %s: 0x%lx\n", GetCurrentThreadId(), x, y );
#else
#define LsapDsDebugOut(args)
#define LsapEnterFunc( x )
#define LsapExitFunc( x, y )
#endif // DBG
//
// These function prototypes control how the Ds transactioning is done. In
// the Ds case, the pointers are initialized to routines that actually do
// transactioning. In the non-Ds case, they point to dummy rountines that
// do nothing.
//
typedef NTSTATUS ( *pfDsOpenTransaction ) ( ULONG );
typedef NTSTATUS ( *pfDsApplyTransaction ) ( ULONG );
typedef NTSTATUS ( *pfDsAbortTransaction ) ( ULONG );
//
// Ds functions that behave differently for the Ds and non-Ds case exist
// in this function table.
//
typedef struct _LSADS_DS_FUNC_TABLE {
pfDsOpenTransaction pOpenTransaction;
pfDsApplyTransaction pApplyTransaction;
pfDsAbortTransaction pAbortTransaction;
} LSADS_DS_FUNC_TABLE, *PLSADS_DS_FUNC_TABLE;
typedef struct _LSADS_DS_SYSTEM_CONTAINER_ITEMS {
PDSNAME TrustedDomainObject;
PDSNAME SecretObject;
} LSADS_DS_SYSTEM_CONTAINER_ITEMS, *PLSADS_DS_SYSTEM_CONTAINER_ITEMS;
//
// Basic LsaDs information structure
//
typedef struct _LSADS_DS_STATE_INFO {
PDSNAME DsRoot; // DSNAME of the root of the Ds
PDSNAME DsPartitionsContainer; // DSNAME of the partitions container
PDSNAME DsSystemContainer; // DSNAME of the system container
PDSNAME DsConfigurationContainer; // DSNAME of the configuration container
ULONG DsDomainHandle; // DS Handle of the domain
LSADS_DS_FUNC_TABLE DsFuncTable; // Function table for Ds specific
// functions
LSADS_DS_SYSTEM_CONTAINER_ITEMS SystemContainerItems;
PVOID SavedThreadState; // Results from THSave
BOOLEAN DsTransactionSave;
BOOLEAN DsTHStateSave;
BOOLEAN DsOperationSave;
BOOLEAN WriteLocal; // Can we write to the registry?
BOOLEAN UseDs; // Is the Ds active?
BOOLEAN FunctionTableInitialized; // Is the function table initialized
BOOLEAN DsInitializedAndRunning; // Has the Ds started
BOOLEAN Nt4UpgradeInProgress; // Is this the case of an upgrade from NT4
} LSADS_DS_STATE_INFO, *PLSADS_DS_STATE_INFO;
typedef struct _LSADS_PER_THREAD_INFO {
BOOLEAN SavedTransactionValid;
ULONG UseCount;
ULONG DsThreadStateUseCount;
ULONG DsTransUseCount;
ULONG DsOperationCount;
PVOID SavedThreadState;
PVOID InitialThreadState;
ULONG OldTrustDirection;
ULONG OldTrustType;
} LSADS_PER_THREAD_INFO, *PLSADS_PER_THREAD_INFO;
#if DBG
typedef struct _LSADS_THREAD_INFO_NODE {
PLSADS_PER_THREAD_INFO ThreadInfo;
ULONG ThreadId;
} LSADS_THREAD_INFO_NODE, *PLSADS_THREAD_INFO_NODE;
#define LSAP_THREAD_INFO_LIST_MAX 15
extern LSADS_THREAD_INFO_NODE LsapDsThreadInfoList[ LSAP_THREAD_INFO_LIST_MAX ];
extern SAFE_RESOURCE LsapDsThreadInfoListResource;
#endif
//
// Extern definitions
//
extern LSADS_DS_STATE_INFO LsaDsStateInfo;
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
extern DWORD LsapDsThreadState;
#ifdef __cplusplus
}
#endif // __cplusplus
//
// Implemented as a macro for performance reasons
//
// PLSADS_PER_THREAD_INFO
// LsapQueryThreadInfo(
// VOID
// );
#define LsapQueryThreadInfo( ) TlsGetValue( LsapDsThreadState )
VOID
LsapDsDebugInitialize(
VOID
);
//
// Registry specific functions
//
NTSTATUS
LsapRegReadObjectSD(
IN LSAPR_HANDLE ObjectHandle,
OUT PSECURITY_DESCRIPTOR *ppSD
);
NTSTATUS
LsapRegGetPhysicalObjectName(
IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
IN PUNICODE_STRING LogicalNameU,
OUT OPTIONAL PUNICODE_STRING PhysicalNameU
);
NTSTATUS
LsapRegOpenObject(
IN LSAP_DB_HANDLE ObjectHandle,
IN ULONG OpenMode,
OUT PVOID *pvKey
);
NTSTATUS
LsapRegOpenTransaction(
);
NTSTATUS
LsapRegApplyTransaction(
);
NTSTATUS
LsapRegAbortTransaction(
);
NTSTATUS
LsapRegCreateObject(
IN PUNICODE_STRING ObjectPath,
IN LSAP_DB_OBJECT_TYPE_ID ObjectType
);
NTSTATUS
LsapRegDeleteObject(
IN PUNICODE_STRING ObjectPath
);
NTSTATUS
LsapRegWriteAttribute(
IN PUNICODE_STRING AttributePath,
IN PVOID pvAttribute,
IN ULONG AttributeLength
);
NTSTATUS
LsapRegDeleteAttribute(
IN PUNICODE_STRING AttributePath,
IN BOOLEAN DeleteSecurely,
IN ULONG AttributeLength
);
NTSTATUS
LsapRegReadAttribute(
IN LSAPR_HANDLE ObjectHandle,
IN PUNICODE_STRING AttributeName,
IN OPTIONAL PVOID AttributeValue,
IN OUT PULONG AttributeValueLength
);
//
// Counterpart Ds functions
//
NTSTATUS
LsapDsReadObjectSD(
IN LSAPR_HANDLE ObjectHandle,
OUT PSECURITY_DESCRIPTOR *ppSD
);
NTSTATUS
LsapDsGetPhysicalObjectName(
IN PLSAP_DB_OBJECT_INFORMATION ObjectInformation,
IN BOOLEAN DefaultName,
IN PUNICODE_STRING LogicalNameU,
OUT OPTIONAL PUNICODE_STRING PhysicalNameU
);
NTSTATUS
LsapDsOpenObject(
IN LSAP_DB_HANDLE ObjectHandle,
IN ULONG OpenMode,
OUT PVOID *pvKey
);
NTSTATUS
LsapDsVerifyObjectExistenceByDsName(
IN PDSNAME DsName
);
NTSTATUS
LsapDsOpenTransaction(
IN ULONG Options
);
//
// Assert that there is a DS transaction open
//
#define LsapAssertDsTransactionOpen() \
{ \
PLSADS_PER_THREAD_INFO CurrentThreadInfo; \
CurrentThreadInfo = LsapQueryThreadInfo(); \
\
ASSERT( CurrentThreadInfo != NULL ); \
if ( CurrentThreadInfo != NULL ) { \
ASSERT( CurrentThreadInfo->DsTransUseCount > 0 ); \
} \
}
NTSTATUS
LsapDsOpenTransactionDummy(
IN ULONG Options
);
NTSTATUS
LsapDsApplyTransaction(
IN ULONG Options
);
NTSTATUS
LsapDsApplyTransactionDummy(
IN ULONG Options
);
NTSTATUS
LsapDsAbortTransaction(
IN ULONG Options
);
NTSTATUS
LsapDsAbortTransactionDummy(
IN ULONG Options
);
NTSTATUS
LsapDsCreateObject(
IN PUNICODE_STRING ObjectPath,
IN ULONG Flags,
IN LSAP_DB_OBJECT_TYPE_ID ObjectType
);
NTSTATUS
LsapDsDeleteObject(
IN PUNICODE_STRING ObjectPath
);
NTSTATUS
LsapDsWriteAttributes(
IN PUNICODE_STRING ObjectPath,
IN PLSAP_DB_ATTRIBUTE Attributes,
IN ULONG AttributeCount,
IN ULONG Options
);
NTSTATUS
LsapDsWriteAttributesByDsName(
IN PDSNAME ObjectPath,
IN PLSAP_DB_ATTRIBUTE Attributes,
IN ULONG AttributeCount,
IN ULONG Options
);
NTSTATUS
LsapDsReadAttributes(
IN PUNICODE_STRING ObjectPath,
IN ULONG Options,
IN OUT PLSAP_DB_ATTRIBUTE Attributes,
IN ULONG AttributeCount
);
NTSTATUS
LsapDsReadAttributesByDsName(
IN PDSNAME ObjectPath,
IN ULONG Options,
IN OUT PLSAP_DB_ATTRIBUTE Attributes,
IN ULONG AttributeCount
);
NTSTATUS
LsapDsRenameObject(
IN PDSNAME OldObject,
IN PDSNAME NewParent,
IN ULONG AttrType,
IN PUNICODE_STRING NewObject
);
NTSTATUS
LsapDsDeleteAttributes(
IN PUNICODE_STRING ObjectPath,
IN OUT PLSAP_DB_ATTRIBUTE Attributes,
IN ULONG AttributeCount
);
//
// Interesting or global functions
//
PVOID
LsapDsAlloc(
IN DWORD dwLen
);
VOID
LsapDsFree(
IN PVOID pvMemory
);
NTSTATUS
LsapDsInitializePromoteInterface(
VOID
);
BOOLEAN
LsapDsIsValidSid(
IN PSID Sid,
IN BOOLEAN DsSid
);
NTSTATUS
LsapDsTruncateNameToFitCN(
IN PUNICODE_STRING OriginalName,
OUT PUNICODE_STRING TruncatedName
);
BOOLEAN
LsapDsIsNtStatusResourceError(
NTSTATUS NtStatus
);
NTSTATUS
LsapDsReadObjectSDByDsName(
IN DSNAME* Object,
OUT PSECURITY_DESCRIPTOR *pSD
);
NTSTATUS
LsapDsGetDefaultSecurityDescriptor(
IN ULONG ClassId,
OUT PSECURITY_DESCRIPTOR *ppSD,
OUT ULONG *cbSD
);
#endif
| 22.047836 | 93 | 0.673107 | [
"object"
] |
f245b591170bdcf21bd7e23e927c435d6e0a638e | 404 | h | C | Textures/include/GameApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | Textures/include/GameApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | Textures/include/GameApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | #pragma once
#include <gl_core_4_4.h>
#include <GLFW\glfw3.h>
#include <aie\Gizmos.h>
#include <glm\glm.hpp>
#include <glm\ext.hpp>
#include <glm\gtx\transform.hpp>
#include "Timer.h"
#include "Camera.h"
class GameApp
{
public:
virtual bool StartUp() = 0;
virtual void ShutDown() = 0;
virtual bool Update() = 0;
virtual void Draw() = 0;
GLFWwindow* mWindow = nullptr;
Timer timer = Timer();
}; | 17.565217 | 32 | 0.685644 | [
"transform"
] |
f2466fa900e6c54bbc658b1753c6fa5430313743 | 25,942 | h | C | PiDashboardBackend/src/manager/db_manager.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | PiDashboardBackend/src/manager/db_manager.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | PiDashboardBackend/src/manager/db_manager.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | #pragma once
#include "../dto/sensor_dto.h"
#include "../dto/extremas_dto.h"
#include "../dto/query_object.h"
#include "../utils/time_converter.h"
#include <limits>
#include <map>
#include <mysql/mysql.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
namespace manager
{
static constexpr int8_t TRUE = 1;
static constexpr int8_t FALSE = 0;
static constexpr int8_t NULL_PTR = -2;
static constexpr int8_t QUERY_ERROR = -1;
//! Class that manages all database operations.
/*!
* This class implements various functions manipulate the underlying MySQL database.
*/
class db_manager
{
public:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// db_manager_table_management.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! Default constructor.
/*!
* Initializes the database connection by performing the following steps:
* - Check if a anonymous connection can be established.
* - Try to connect to the projects database.
* - Create the database if it does not exist yet and use it afterwards.
* - Check if the tables are existing and create them if needed.
*
* Closes database connection in case of an error and throws an exception.
*
* \param host[in]: ip (or localhost) of the pc where the database is located.
* \param user[in]: the database user to use for all operations (needs select, insert, update, delete, create, drop rights).
* \param password[in]: the password of the user account.
* \param database[in]: the name of the database where all tables are located in.
*/
db_manager(std::string host, std::string user, std::string password, std::string database);
//! Default destructor.
~db_manager();
//! Creates a new table.
/*!
* Creates a new table by executing the given create table statement. Closes database connection in case of an error
* and throws an exception.
*
* \param statement[in]: the create table statement that is used to create the new table.
*/
void create_table(std::string statement);
//! Creates a new table.
/*!
* Creates a new table by building a create table statement from the given parameters. Closes database connection in case of an error
* and throws an exception.
*
* \param table[in]: the name of the new table.
* \param column_definitions[in]: a list of column definitions (name + data type + special settings (e.g. autoincrement, primary key, ...)).
*/
void create_table(std::string table, std::vector<std::string> column_definitions);
//! Creates a new database.
/*!
* Creates a new database with the given name. Closes database connection in case of an error
* and throws an exception.
*
* \param database[in]: the name of the new database.
*/
void create_database(std::string database);
//! Calls the use statement on the given database.
/*!
* Calls the use statement on the given database. Closes database connection in case of an error
* and throws an exception.
*
* \param database[in]: the name of the database to use.
*/
void use_database(std::string database);
//! Deletes a table.
/*!
* Deletes the table with the given name. Does not close database connection in case of an error.
*
* \param table[in]: the name of the table to delete.
* \return 1 (true) is deleting succeeded, -2 (query error) if an error occured.
*/
int8_t delete_table(std::string table);
//! Deletes a database.
/*!
* Deletes the database with the given name. Does not close database connection in case of an error.
*
* \param database[in]: the name of the database to delete.
* \return 1 (true) is deleting succeeded, -2 (query error) if an error occured.
*/
int8_t delete_database(std::string database);
//! Checks if a table exists.
/*!
* Checks if the table with the given name exists inside the given database.
* Does not close database connection in case of an error.
*
* \param database[in]: the name of the database in which the table should be found.
* \param table[in]: the name of the table to lookup.
* \return 1 (true) if the table exists, 0 if it doesn't and -2 (query error) if an error occured.
*/
int8_t check_if_table_exists(std::string database, std::string table);
//! Checks if a database exists.
/*!
* Checks if the database with the given name exists. Does not close database connection
* in case of an error.
*
* \param database[in]: the name of the database to lookup.
* \return 1 (true) if the table exists, 0 if it doesn't and -2 (query error) if an error occured.
*/
int8_t check_if_database_exists(std::string database);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// db_manager_sensors.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! Adds a new entry to the sensor database.
/*!
* Adds a new entry to the sensor database. Does not close database connection in case of an error.
*
* \param new_value[in]: a dto object with the values to add.
* \return 1 (true) if adding the entry succeeded and -1 (null ptr error) or -2 (query error) if an error occured.
*/
int8_t add_sensor_entry(std::shared_ptr<dto::sensor_dto> new_value);
//! Deletes a entry from the sensor database.
/*!
* Deletes the entry the given dto represents from the sensor database. Does not close database connection in case of an error.
*
* \param value[in]: the entry to delete.
* \return 1 (true) if removing the entry succeeded and -1 (null ptr error) or -2 (query error) if an error occured.
*/
int8_t delete_sensor_entry(std::shared_ptr<dto::sensor_dto> value);
//! Deletes a entry from the sensor database.
/*!
* Deletes the entry that matches the given names and timestamp from the sensor database.
* Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to delete.
* \param individual_name[in]: the individual name in the row to delete.
* \param timestamp[in]: the timestamp name in the row to delete.
* \return 1 (true) if removing the entry succeeded and -2 (query error) if an error occured.
*/
int8_t delete_sensor_entry(std::string sensor_type_name, std::string individual_name, std::chrono::time_point<std::chrono::system_clock> timestamp);
//! Deletes multiple entries from the sensor database.
/*!
* Deletes all entries that match the given names from the sensor database. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the rows to delete.
* \param individual_name[in]: the individual name in the rows to delete.
* \return 1 (true) if removing the entry succeeded and -2 (query error) if an error occured.
*/
int8_t delete_sensor_entries(std::string sensor_type_name, std::string individual_name);
//! Deletes multiple entries from the sensor database.
/*!
* Deletes all entries that match the given names from the sensor database. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the rows to delete.
* \param individual_name[in]: the individual name in the rows to delete.
* \param timestamp[in]: the timestamp threshold.
* \param delete_older[in]: true to delete values older than timestamp, false to delete newer ones.
* \return 1 (true) if removing the entry succeeded and -2 (query error) if an error occured.
*/
int8_t delete_sensor_entries(std::string sensor_type_name, std::string individual_name, std::chrono::time_point<std::chrono::system_clock> timestamp, bool delete_older = true);
//! Updates an entry.
/*!
* Updates an entry that matches the given names and value. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the rows to update.
* \param column[in]: the name of the column to update.
* \param old_value[in]: the current value that should be replaced by the new one.
* \param new_value[in]: the new value to insert into the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_entry(std::string sensor_type_name, std::string individual_name, std::string column, std::string old_value, std::string new_value);
//! Updates an entry.
/*!
* Updates an entry that matches the given names and value. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the rows to update.
* \param column[in]: the name of the column to update.
* \param old_value[in]: the current value that should be replaced by the new one.
* \param new_value[in]: the new value to insert into the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_entry(std::string sensor_type_name, std::string individual_name, std::string column, int old_value, int new_value);
//! Updates an entry.
/*!
* Updates an entry that matches the given names and value. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the rows to update.
* \param column[in]: the name of the column to update.
* \param old_value[in]: the current value that should be replaced by the new one.
* \param new_value[in]: the new value to insert into the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_entry(std::string sensor_type_name, std::string individual_name, std::string column, float old_value, float new_value);
//! Updates an entry.
/*!
* Updates an entry that matches the given names and value. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the rows to update.
* \param column[in]: the name of the column to update.
* \param old_value[in]: the current value that should be replaced by the new one.
* \param new_value[in]: the new value to insert into the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_entry(std::string sensor_type_name, std::string individual_name, std::string column, double old_value, double new_value);
//! Updates an entry.
/*!
* Updates an entry that matches the given names and value. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the rows to update.
* \param column[in]: the name of the column to update.
* \param old_value[in]: the current value that should be replaced by the new one.
* \param new_value[in]: the new value to insert into the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_entry(std::string sensor_type_name, std::string individual_name, std::string column, bool old_value, bool new_value);
//! Returns a single sensor entry.
/*!
* Returns the sensor entry that matches the names and timestamp in the given dto. Does not close database connection in case of an error.
*
* \param result[out]: the desired row or an empty dto if the input param did not match any row (check if names are "")
* \param value[in]: the dto used to find the desired sensor row.
* \return 1 (true) if getting the entry succeeded and -1 (null ptr error) or -2 (query error) if an error occured.
*/
int8_t get_sensor_entry(std::shared_ptr<dto::sensor_dto>& result, std::shared_ptr<dto::sensor_dto> value);
//! Returns a single sensor entry.
/*!
* Returns the sensor entry that matches the given names and timestamp. Does not close database connection in case of an error.
*
* \param result[out]: the desired row or an empty dto if the input params did not match any row (check if names are "")
* \param sensor_type_name[in]: the type name in the row to return.
* \param individual_name[in]: the individual name in the rows to return.
* \param timestamp[in]: the timestamp in the rows to return.
* \return 1 (true) if getting the entry succeeded and -2 (query error) if an error occured.
*/
int8_t get_sensor_entry(std::shared_ptr<dto::sensor_dto>& result, std::string sensor_type_name, std::string individual_name, std::chrono::time_point<std::chrono::system_clock> timestamp);
//! Returns multiple sensor entries.
/*!
* Returns all entries from the sensor table. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given name. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given names. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \param individual_name[in]: the individual name in the rows to return.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name, std::string individual_name);
//! Returns multiple sensor entries.
/*!
* Returns all entries that are older or newer than the given timestamp. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param timestamp[in]: the timestamp threshold.
* \param older_entries[in]: true to return all values older than the given timestamp, false to return newer values.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::chrono::time_point<std::chrono::system_clock> timestamp, bool older_entries = false);
//! Returns multiple sensor entries.
/*!
* Returns all entries that are located between both input timestamps. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param start_timestamp[in]: the earliest timestamp to return.
* \param end_timestamp[in]: the latest timestamp to return.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::chrono::time_point<std::chrono::system_clock> start_timestamp, std::chrono::time_point<std::chrono::system_clock> end_timestamp);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given name and timestamp. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \param timestamp[in]: the timestamp threshold.
* \param older_entries[in]: true to return all values older than the given timestamp, false to return newer values.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name, std::chrono::time_point<std::chrono::system_clock> timestamp, bool older_entries = false);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given name and are located between both input timestamps. Does not close database
* connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \param start_timestamp[in]: the earliest timestamp to return.
* \param end_timestamp[in]: the latest timestamp to return.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name, std::chrono::time_point<std::chrono::system_clock> start_timestamp, std::chrono::time_point<std::chrono::system_clock> end_timestamp);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given names and timestamp. Does not close database connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \param individual_name[in]: the individual name in the rows to return.
* \param timestamp[in]: the timestamp threshold.
* \param older_entries[in]: true to return all values older than the given timestamp, false to return newer values.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name, std::string individual_name, std::chrono::time_point<std::chrono::system_clock> timestamp, bool older_entries = false);
//! Returns multiple sensor entries.
/*!
* Returns all entries that match the given names and are located between both input timestamps. Does not close database
* connection in case of an error.
*
* \param result[out]: a list of all values in the sensor table that match the input params.
* \param sensor_type_name[in]: the type name in the rows to return.
* \param individual_name[in]: the individual name in the rows to return.
* \param start_timestamp[in]: the earliest timestamp to return.
* \param end_timestamp[in]: the latest timestamp to return.
* \return 1 (true) if getting the entries succeeded and -2 (query error) if an error occured.
*/
int8_t get_all_sensor_entries(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string sensor_type_name, std::string individual_name, std::chrono::time_point<std::chrono::system_clock> start_timestamp, std::chrono::time_point<std::chrono::system_clock> end_timestamp);
//! Returns the first entry from the sensor table.
/*!
* Returns the first entry from the sensor table. Does not close database connection in case of an error.
*
* \param result[out]: the first entry from the sensor table.
* \return 1 (true) if getting the entry succeeded and -2 (query error) if an error occured.
*/
int8_t get_first_sensor_entry(std::shared_ptr<dto::sensor_dto>& result);
//! Returns the last entry from the sensor table.
/*!
* Returns the last entry from the sensor table. Does not close database connection in case of an error.
*
* \param result[out] the last entry from the sensor table.
* \return 1 (true) if getting the entry succeeded and -2 (query error) if an error occured.
*/
int8_t get_last_sensor_entry(std::shared_ptr<dto::sensor_dto>& result);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// db_manager_extremas.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! Adds a new extremum to the extremas table.
/*!
* Adds a new extremum to the extremas table. Does not close database connection in case of an error.
*
* \param new_value[in]: a dto containing the values to add to the table.
* \return 1 (true) if adding the entry succeeded and -1 (null ptr error) or -2 (query error) if an error occured.
*/
int8_t add_extremum(std::shared_ptr<dto::extremas_dto> new_value);
//! Deletes a extremum from the extremas table.
/*!
* Deletes the extremum with the given names from the extremas table. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to delete.
* \param individual_name[in]: the individual name in the row to delete.
* \return 1 (true) if deleting the entry succeeded and -2 (query error) if an error occured.
*/
int8_t delete_extremum(std::string sensor_type_name, std::string individual_name);
//! Returns a single extremum from the extremas table.
/*!
* Returns a single extremum that matches the given names. Does not close database connection in case of an error.
*
* \param result[out] the entry from the table.
* \param sensor_type_name[in]: the type name in the row to return.
* \param individual_name[in]: the individual name in the row to return.
* \return 1 (true) if getting the entry succeeded and -2 (query error) if an error occured.
*/
int8_t get_extremum(std::shared_ptr<dto::extremas_dto>& result, std::string sensor_type_name, std::string individual_name);
//! Updates an existing extremum in the extremas table.
/*!
* Updates an existing extremum in the extremas table with the given sensor dto object. Does not close database
* connection in case of an error.
*
* \param new_value[in]: dto containing the values that should be added to the table.
* \return 1 (true) if updating the entry succeeded and -1 (null ptr error) or -2 (query error) if an error occured.
*/
int8_t update_extremum(std::shared_ptr<dto::sensor_dto> new_value);
//! Updates an existing extremum in the extremas table.
/*!
* Updates an existing extremum in the extremas table with the given params. Does not close database connection in
* case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the row to update.
* \param count[in]: the new count to add to the row.
* \param sum[in]: the new sum to add to the row.
* \param max[in]: the new max to add to the row.
* \param min[in]: the new min to add to the row.
* \return 1 (true) if updating the entry succeeded and -2 (query error) if an error occured.
*/
int8_t update_extremum(std::string sensor_type_name, std::string individual_name, double count, double sum, double max, double min);
//! Recalculates the sum, count, max and min values of one row.
/*!
* Recalculates the sum, count, max and min values of one row in the extremas table by getting all
* sensor values from the sensors table. Does not close database connection in case of an error.
*
* \param sensor_type_name[in]: the type name in the row to update.
* \param individual_name[in]: the individual name in the row to update.
* \return 1 (true) if recalculating the entry succeeded, 0 (false) if no sensor values are available and -2 (query error) if an error occured.
*/
int8_t recalculate_extremum(std::string sensor_type_name, std::string individual_name);
private:
int8_t get_single_sensor_query_result(std::shared_ptr<dto::sensor_dto>& result, std::string statement);
int8_t get_multiple_sensor_query_results(std::vector<std::shared_ptr<dto::sensor_dto>>& result, std::string statement);
void handle_error(std::string method, std::string table, std::string statement, std::string error, bool close = false);
MYSQL* db_connection;
std::map<std::string, dto::query_object*> tables = {
{"extremas", new dto::query_object("extremas",
std::vector<dto::column*>{ new dto::column("id", "INT"),
new dto::column("sensor_type_name", "TEXT"),
new dto::column("individual_name", "TEXT"),
new dto::column("count", "DOUBLE"),
new dto::column("sum", "DOUBLE"),
new dto::column("max", "DOUBLE"),
new dto::column("min", "DOUBLE")},
"CREATE TABLE IF NOT EXISTS extremas(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, sensor_type_name TEXT NOT NULL, individual_name TEXT NOT NULL, count DOUBLE, sum DOUBLE, max DOUBLE, min DOUBLE);")
},
{"sensors", new dto::query_object("sensors",
std::vector<dto::column*>{ new dto::column("id", "INT"),
new dto::column("sensor_type_name", "TEXT"),
new dto::column("individual_name", "TEXT"),
new dto::column("timestamp", "TIMESTAMP"),
new dto::column("value", "DOUBLE")},
"CREATE TABLE IF NOT EXISTS sensors(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, sensor_type_name TEXT NOT NULL, individual_name TEXT NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, value DOUBLE);")
}
};
};
}
| 51.987976 | 280 | 0.698481 | [
"object",
"vector"
] |
f2637572730e03cd3cbb25f91c4ee83c02a9431b | 553 | h | C | OpenCVGraph/src/GraphEngine.h | WhiteMoll/OpenCVGraph | 6d5008250a880335e1a5a96fd556b50fed34bb19 | [
"MIT"
] | null | null | null | OpenCVGraph/src/GraphEngine.h | WhiteMoll/OpenCVGraph | 6d5008250a880335e1a5a96fd556b50fed34bb19 | [
"MIT"
] | 12 | 2016-07-10T21:29:34.000Z | 2016-07-31T17:09:24.000Z | OpenCVGraph/src/GraphEngine.h | WhiteMoll/OpenCVGraph | 6d5008250a880335e1a5a96fd556b50fed34bb19 | [
"MIT"
] | null | null | null | #ifndef _GRAPHENGINE_H_
#define _GRAPHENGINE_H_
#include <memory>
#include <vector>
#include "Node.h"
class GraphView;
class GraphEngine
{
private:
std::vector<std::shared_ptr<Node>> m_nodes;
GraphView* m_graphView;
bool OneShotRecursive(Node* node);
public:
GraphEngine(GraphView* parent);
~GraphEngine();
void Init();
void Stop();
// Run the graph from the entry point specified until the end and stops
void RunOneShot(Node* entryPoint);
void AddNode(std::shared_ptr<Node> node);
void DeleteNode(std::shared_ptr<Node> node);
};
#endif | 19.75 | 72 | 0.746835 | [
"vector"
] |
f27ab17f3fb12dceff7e89998f266dd012d42f8a | 5,050 | c | C | interfaces/dia/plug-ins/python/python.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:42.000Z | 2021-05-04T16:35:42.000Z | interfaces/dia/plug-ins/python/python.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | null | null | null | interfaces/dia/plug-ins/python/python.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:35.000Z | 2021-05-04T16:35:35.000Z | /* Python plug-in for dia
* Copyright (C) 1999 James Henstridge
* Copyright (C) 2000 Hans Breuer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <Python.h>
#include <stdio.h>
#include <glib.h>
#include "intl.h"
#include "plug-ins.h"
#include "dia_dirs.h"
#include "message.h"
#include "pydia-error.h"
DIA_PLUGIN_CHECK_INIT
void initdia(void);
static gboolean
on_error_report (void)
{
if (PyErr_Occurred()) {
#ifndef G_OS_WIN32
PyErr_Print();
#else
/* On Win32 there is not necessary a console attached to the
* program, so delegate the stack dump to the error object,
* which finally uses g_print()
*/
PyObject *exc, *v, *tb, *ef;
PyErr_Fetch (&exc, &v, &tb);
ef = PyDiaError_New ("Initialization Error:", FALSE);
PyFile_WriteObject (exc, ef, 0);
PyFile_WriteObject (v, ef, 0);
PyTraceBack_Print(tb, ef);
Py_DECREF (ef);
Py_XDECREF (exc);
Py_XDECREF (v);
Py_XDECREF (tb);
#endif
return TRUE;
}
else
return FALSE;
}
static gboolean
dia_py_plugin_can_unload (PluginInfo *info)
{
/* until we can properly clean up the python plugin, it is not safe to
* unload it from a dia */
return FALSE; /* TRUE */
}
static void
dia_py_plugin_unload (PluginInfo *info)
{
/* should call filter_unregister_export () */
Py_Finalize ();
}
PluginInitResult
dia_plugin_init(PluginInfo *info)
{
gchar *python_argv[] = { "dia-python", NULL };
gchar *startup_file;
FILE *fp;
PyObject *__main__, *__file__;
if (Py_IsInitialized ()) {
g_warning ("Dia's Python embedding is not designed for concurrency.");
return DIA_PLUGIN_INIT_ERROR;
}
if (!dia_plugin_info_init(info, "Python",
_("Python scripting support"),
dia_py_plugin_can_unload,
dia_py_plugin_unload))
return DIA_PLUGIN_INIT_ERROR;
Py_SetProgramName("dia");
Py_Initialize();
PySys_SetArgv(1, python_argv);
/* Sanitize sys.path */
PyRun_SimpleString("import sys; sys.path = filter(None, sys.path)");
if (on_error_report())
return DIA_PLUGIN_INIT_ERROR;
initdia();
if (on_error_report())
return DIA_PLUGIN_INIT_ERROR;
#ifdef G_OS_WIN32
PySys_SetObject("stderr", PyDiaError_New (NULL, TRUE));
#endif
if (g_getenv ("DIA_PYTHON_PATH")) {
startup_file = g_build_filename (g_getenv ("DIA_PYTHON_PATH"), "python-startup.py", NULL);
} else {
startup_file = dia_get_data_directory("python-startup.py");
}
if (!startup_file) {
g_warning("could not find python-startup.py");
return DIA_PLUGIN_INIT_ERROR;
}
/* set __file__ in __main__ so that python-startup.py knows where it is */
__main__ = PyImport_AddModule("__main__");
__file__ = PyString_FromString(startup_file);
PyObject_SetAttrString(__main__, "__file__", __file__);
Py_DECREF(__file__);
#if defined(G_OS_WIN32) && (PY_VERSION_HEX >= 0x02040000)
/* this code should work for every supported Python version, but it is needed
* on win32 since Python 2.4 due to mixed runtime issues, i.e.
* crashing in PyRun_SimpleFile for python2(5|6)/msvcr(71|90)
* It is not enabled by default yet, because I could not get PyGtk using
* plug-ins to work at all with 2.5/2.6 */
{
gchar *startup_string = NULL;
gsize i, length = 0;
GError *error = NULL;
if (!g_file_get_contents(startup_file, &startup_string, &length, &error)) {
g_warning("Python: Couldn't find startup file %s\n%s\n",
startup_file, error->message);
g_error_free(error);
g_free(startup_file);
return DIA_PLUGIN_INIT_ERROR;
}
/* PyRun_SimpleString does not like the windows format */
for (i = 0; i < length; ++i)
if (startup_string[i] == '\r')
startup_string[i] = '\n';
if (PyRun_SimpleString(startup_string) != 0) {
g_warning("Python: Couldn't run startup file %s\n", startup_file);
}
g_free(startup_string);
}
#else
fp = fopen(startup_file, "r");
if (!fp) {
g_warning("Python: Couldn't find startup file %s\n", startup_file);
g_free(startup_file);
return DIA_PLUGIN_INIT_ERROR;
}
PyRun_SimpleFile(fp, startup_file);
#endif
g_free(startup_file);
if (on_error_report())
return DIA_PLUGIN_INIT_ERROR;
return DIA_PLUGIN_INIT_OK;
}
| 28.693182 | 91 | 0.680198 | [
"object"
] |
f27e62e54dac3b3f3c50dd70bf5b75a9daa29b27 | 373 | h | C | HW10/src/shape.h | hsuan81/2020SPRING_OOP_NTUT | 670c24add9de18ff193adbb6c9358c550e767a56 | [
"MIT"
] | null | null | null | HW10/src/shape.h | hsuan81/2020SPRING_OOP_NTUT | 670c24add9de18ff193adbb6c9358c550e767a56 | [
"MIT"
] | null | null | null | HW10/src/shape.h | hsuan81/2020SPRING_OOP_NTUT | 670c24add9de18ff193adbb6c9358c550e767a56 | [
"MIT"
] | null | null | null | #ifndef SHAPE_H
#define SHAPE_H
class Shape{
protected:
Shape(std::string name){
_name = name;
}
public:
virtual double perimeter() const = 0;
virtual double area() const = 0;
virtual std::string toString() const = 0;
virtual ~Shape(){}
std::string name() const{
return _name;
}
private:
std::string _name;
};
#endif | 15.541667 | 45 | 0.605898 | [
"shape"
] |
f27f3af44c59c83789e83c9046e4b08b3c79bc0b | 469 | h | C | engine/modules/spline/editor/spline_control_point_editor.h | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | engine/modules/spline/editor/spline_control_point_editor.h | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | engine/modules/spline/editor/spline_control_point_editor.h | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | #pragma once
#include "../spline.h"
namespace Echo
{
#ifdef ECHO_EDITOR_MODE
class SplineControlPointEditor : public ObjectEditor
{
public:
SplineControlPointEditor(Object* object);
virtual ~SplineControlPointEditor();
// get thumbnail
virtual ImagePtr getThumbnail() const override;
// on editor select this node
virtual void onEditorSelectThisNode() override;
// update self
virtual void editor_update_self() override;
private:
};
#endif
}
| 17.37037 | 53 | 0.750533 | [
"object"
] |
f27f92eb2af216d60ab2a8fdb94cdcc6052b980a | 41,279 | c | C | raylib-image.c | joseph-montanez/raylib-php | 897df5e1ccc2a2ea854c518ab1001802250c4a7b | [
"Zlib"
] | 125 | 2018-12-08T05:47:51.000Z | 2022-03-29T08:55:27.000Z | raylib-image.c | robbierayas/raylib-php | 897df5e1ccc2a2ea854c518ab1001802250c4a7b | [
"Zlib"
] | 18 | 2020-03-31T00:00:54.000Z | 2022-03-15T05:13:37.000Z | raylib-image.c | robbierayas/raylib-php | 897df5e1ccc2a2ea854c518ab1001802250c4a7b | [
"Zlib"
] | 9 | 2020-04-04T21:13:59.000Z | 2021-12-18T14:09:33.000Z | /* If defined, the following flags inhibit definition of the indicated items.*/
#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_
#define NOVIRTUALKEYCODES // VK_*
#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_*
#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
#define NOSYSMETRICS // SM_*
#define NOMENUS // MF_*
#define NOICONS // IDI_*
#define NOKEYSTATES // MK_*
#define NOSYSCOMMANDS // SC_*
#define NORASTEROPS // Binary and Tertiary raster ops
#define NOSHOWWINDOW // SW_*
#define OEMRESOURCE // OEM Resource values
#define NOATOM // Atom Manager routines
#define NOCLIPBOARD // Clipboard routines
#define NOCOLOR // Screen colors
#define NOCTLMGR // Control and Dialog routines
#define NODRAWTEXT // DrawText() and DT_*
#define NOGDI // All GDI defines and routines
#define NOKERNEL // All KERNEL defines and routines
#define NOUSER // All USER defines and routines
/*#define NONLS // All NLS defines and routines*/
#define NOMB // MB_* and MessageBox()
#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines
#define NOMETAFILE // typedef METAFILEPICT
#define NOMINMAX // Macros min(a,b) and max(a,b)
#define NOMSG // typedef MSG and associated routines
#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_*
#define NOSCROLL // SB_* and scrolling routines
#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc.
#define NOSOUND // Sound driver routines
#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines
#define NOWH // SetWindowsHook and WH_*
#define NOWINOFFSETS // GWL_*, GCL_*, associated routines
#define NOCOMM // COMM driver routines
#define NOKANJI // Kanji support stuff.
#define NOHELP // Help engine interface.
#define NOPROFILER // Profiler interface.
#define NODEFERWINDOWPOS // DeferWindowPos routines
#define NOMCX // Modem Configuration Extensions
/* Type required before windows.h inclusion */
typedef struct tagMSG *LPMSG;
#include "php.h"
#undef LOG_INFO
#undef LOG_WARNING
#undef LOG_DEBUG
#include "raylib.h"
#include "raylib-image.h"
#include "raylib-rectangle.h"
#include "raylib-font.h"
#include "raylib-vector2.h"
#include "raylib-vector4.h"
#include "raylib-texture.h"
#include "raylib-color.h"
#include "raylib-utils.h"
//------------------------------------------------------------------------------------------------------
//-- raylib Image PHP Custom Object
//------------------------------------------------------------------------------------------------------
/* {{{ ZE2 OO definitions */
zend_object_handlers php_raylib_image_object_handlers;
static HashTable php_raylib_image_prop_handlers;
typedef int (*raylib_image_read_int_t)(struct Image *image);
typedef struct _raylib_image_prop_handler {
raylib_image_read_int_t read_int_func;
} raylib_image_prop_handler;
/* }}} */
static void php_raylib_image_register_prop_handler(HashTable *prop_handler, char *name, raylib_image_read_int_t read_int_func) /* {{{ */
{
raylib_image_prop_handler hnd;
hnd.read_int_func = read_int_func;
zend_hash_str_add_mem(prop_handler, name, strlen(name), &hnd, sizeof(raylib_image_prop_handler));
/* Register for reflection */
zend_declare_property_null(php_raylib_image_ce, name, strlen(name), ZEND_ACC_PUBLIC);
}
/* }}} */
static zval *php_raylib_image_property_reader(php_raylib_image_object *obj, raylib_image_prop_handler *hnd, zval *rv) /* {{{ */
{
int retint = 0;
if (obj != NULL && hnd->read_int_func) {
retint = hnd->read_int_func(&obj->image);
if (retint == -1) {
php_error_docref(NULL, E_WARNING, "Internal raylib image error returned");
return NULL;
}
}
ZVAL_LONG(rv, (long)retint);
return rv;
}
/* }}} */
static zval *php_raylib_image_get_property_ptr_ptr(zend_object *object, zend_string *name, int type, void **cache_slot) /* {{{ */
{
php_raylib_image_object *obj;
zval *retval = NULL;
raylib_image_prop_handler *hnd = NULL;
obj = php_raylib_image_fetch_object(object);
if (obj->prop_handler != NULL) {
hnd = zend_hash_find_ptr(obj->prop_handler, name);
}
if (hnd == NULL) {
retval = zend_std_get_property_ptr_ptr(object, name, type, cache_slot);
}
return retval;
}
/* }}} */
static zval *php_raylib_image_read_property(zend_object *object, zend_string *name, int type, void **cache_slot, zval *rv) /* {{{ */
{
php_raylib_image_object *obj;
zval *retval = NULL;
raylib_image_prop_handler *hnd = NULL;
obj = php_raylib_image_fetch_object(object);
if (obj->prop_handler != NULL) {
hnd = zend_hash_find_ptr(obj->prop_handler, name);
}
if (hnd) {
retval = php_raylib_image_property_reader(obj, hnd, rv);
} else {
retval = zend_std_read_property(object, name, type, cache_slot, rv);
}
return retval;
}
/* }}} */
static int php_raylib_image_has_property(zend_object *object, zend_string *name, int has_set_exists, void **cache_slot) /* {{{ */
{
php_raylib_image_object *obj;
raylib_image_prop_handler *hnd = NULL;
int ret = 0;
if ((hnd = zend_hash_find_ptr(obj->prop_handler, name)) != NULL) {
switch (has_set_exists) {
case ZEND_PROPERTY_EXISTS:
ret = 1;
break;
case ZEND_PROPERTY_NOT_EMPTY: {
zval rv;
zval *value = php_raylib_image_read_property(object, name, BP_VAR_IS, cache_slot, &rv);
if (value != &EG(uninitialized_zval)) {
convert_to_boolean(value);
ret = Z_TYPE_P(value) == IS_TRUE ? 1 : 0;
}
break;
}
case ZEND_PROPERTY_ISSET: {
zval rv;
zval *value = php_raylib_image_read_property(object, name, BP_VAR_IS, cache_slot, &rv);
if (value != &EG(uninitialized_zval)) {
ret = Z_TYPE_P(value) != IS_NULL? 1 : 0;
zval_ptr_dtor(value);
}
break;
}
EMPTY_SWITCH_DEFAULT_CASE();
}
} else {
ret = zend_std_has_property(object, name, has_set_exists, cache_slot);
}
return ret;
}
/* }}} */
static HashTable *php_raylib_image_get_gc(zend_object *object, zval **gc_data, int *gc_data_count) /* {{{ */
{
*gc_data = NULL;
*gc_data_count = 0;
return zend_std_get_properties(object);
}
/* }}} */
static HashTable *php_raylib_image_get_properties(zend_object *object)/* {{{ */
{
php_raylib_image_object *obj;
HashTable *props;
raylib_image_prop_handler *hnd;
zend_string *key;
obj = php_raylib_image_fetch_object(object);
props = zend_std_get_properties(object);
if (obj->prop_handler == NULL) {
return NULL;
}
ZEND_HASH_FOREACH_STR_KEY_PTR(obj->prop_handler, key, hnd) {
zval *ret, val;
ret = php_raylib_image_property_reader(obj, hnd, &val);
if (ret == NULL) {
ret = &EG(uninitialized_zval);
}
zend_hash_update(props, key, ret);
} ZEND_HASH_FOREACH_END();
return props;
}
/* }}} */
void php_raylib_image_free_storage(zend_object *object)
{
php_raylib_image_object *intern = php_raylib_image_fetch_object(object);
zend_object_std_dtor(&intern->std);
UnloadImage(intern->image);
}
zend_object * php_raylib_image_new_ex(zend_class_entry *ce, zend_object *orig)
{
php_raylib_image_object *intern;
intern = (php_raylib_image_object*) ecalloc(1, sizeof(php_raylib_image_object) + zend_object_properties_size(ce));
intern->prop_handler = &php_raylib_image_prop_handlers;
if (orig) {
php_raylib_image_object *other = php_raylib_image_fetch_object(orig);
intern->image = ImageCopy(other->image);
} else {
intern->image = (Image) {
.data = NULL,
.width = 0,
.height = 0,
.mipmaps = 0,
.format = 0,
};
}
zend_object_std_init(&intern->std, ce);
object_properties_init(&intern->std, ce);
intern->std.handlers = &php_raylib_image_object_handlers;
return &intern->std;
}
zend_object * php_raylib_image_new(zend_class_entry *ce)
{
return php_raylib_image_new_ex(ce, NULL);
}
// PHP property handling
static int php_raylib_image_width(struct Image *image) /* {{{ */
{
return image->width;
}
/* }}} */
static int php_raylib_image_height(struct Image *image) /* {{{ */
{
return image->height;
}
/* }}} */
static int php_raylib_image_mipmaps(struct Image *image) /* {{{ */
{
return image->mipmaps;
}
/* }}} */
static int php_raylib_image_format(struct Image *image) /* {{{ */
{
return image->format;
}
/* }}} */
// PHP object handling
ZEND_BEGIN_ARG_INFO_EX(arginfo_image__construct, 0, 0, 1)
ZEND_ARG_INFO(0, fileName)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, __construct)
{
zend_string *fileName;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(fileName)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
intern->image = LoadImage(fileName->val);
}
// Load image from Color array data (RGBA - 32bit)
// RLAPI Image LoadImageEx(Color *pixels, int width, int height);
//PHP_METHOD(Image, fromColors)
//{
// zval *pixels;
// zend_long width;
// zend_long height;
// HashTable *pixelsArr;
// zval *zv;
//
// ZEND_PARSE_PARAMETERS_START(3, 3)
// Z_PARAM_ARRAY(pixels)
// Z_PARAM_LONG(width)
// Z_PARAM_LONG(height)
// ZEND_PARSE_PARAMETERS_END();
//
// pixelsArr = Z_ARRVAL_P(pixels);
//
// // Count the number of elements in array
// int numPixels = zend_hash_num_elements(pixelsArr);
// Color *pixelsP = (Color *)safe_emalloc(numPixels, sizeof(Color), 0);
//
// // Load pixels from hash to an array
// int n = 0;
// ZEND_HASH_FOREACH_VAL(pixelsArr, zv) {
// if (Z_TYPE_P(zv) == IS_OBJECT) {
// php_raylib_color_object *obj = Z_COLOR_OBJ_P(zv);
// pixelsP[n] = obj->color;
// }
// n++;
// } ZEND_HASH_FOREACH_END();
//
// // Create Image Object
// object_init_ex(return_value, php_raylib_image_ce);
// zend_object *object = php_raylib_image_new(php_raylib_image_ce);
// php_raylib_image_object *internImage = php_raylib_image_fetch_object(object);
//
// // Load From Pixels
// internImage->image = LoadImageEx(pixelsP, (int) width, (int) height);
//
// ZVAL_OBJ(return_value, object);
//}
// Load image from RAW file data
// RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_fromRaw, 0, 0, 5)
ZEND_ARG_INFO(0, fileName)
ZEND_ARG_INFO(0, width)
ZEND_ARG_INFO(0, height)
ZEND_ARG_INFO(0, format)
ZEND_ARG_INFO(0, headerSize)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, fromRaw)
{
zend_string *fileName;
zend_long width;
zend_long height;
zend_long format;
zend_long headerSize;
ZEND_PARSE_PARAMETERS_START(5, 5)
Z_PARAM_STR(fileName)
Z_PARAM_LONG(width)
Z_PARAM_LONG(height)
Z_PARAM_LONG(format)
Z_PARAM_LONG(headerSize)
ZEND_PARSE_PARAMETERS_END();
// Create Image Object
object_init_ex(return_value, php_raylib_image_ce);
zend_object *object = php_raylib_image_new(php_raylib_image_ce);
php_raylib_image_object *internImage = php_raylib_image_fetch_object(object);
// Load From Pixels
internImage->image = LoadImageRaw(fileName->val, (int) width, (int) height, (int) format, (int) headerSize);
ZVAL_OBJ(return_value, object);
}
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_toTexture, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, toTexture)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
object_init_ex(return_value, php_raylib_texture_ce);
zend_object *object = php_raylib_texture_new(php_raylib_texture_ce);
php_raylib_texture_object *internTexture = php_raylib_texture_fetch_object(object);
internTexture->texture = LoadTextureFromImage(intern->image);
ZVAL_OBJ(return_value, object);
}
//Image ImageCopy(Image image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_copy, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, copy)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
object_init_ex(return_value, php_raylib_image_ce);
zend_object *object = php_raylib_image_new(php_raylib_image_ce);
php_raylib_image_object *internTexture = php_raylib_image_fetch_object(object);
internTexture->image = ImageCopy(intern->image);
ZVAL_OBJ(return_value, object);
}
//ImageToPOT(Image *image, Color fillColor);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_toPot, 0, 0, 1)
ZEND_ARG_INFO(0, fillColor)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, toPot)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
zval *fillColor;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(fillColor)
ZEND_PARSE_PARAMETERS_END();
php_raylib_color_object *phpFillColor = Z_COLOR_OBJ_P(fillColor);
ImageToPOT(&intern->image, phpFillColor->color);
}
// RLAPI void ExportImage(const char *fileName, Image image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_export, 0, 0, 1)
ZEND_ARG_INFO(0, fileName)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, export)
{
zend_string *fileName;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(fileName)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ExportImage(intern->image, fileName->val);
}
// RLAPI void ExportImageAsCode(Image image, const char *fileName);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_exportAsCode, 0, 0, 1)
ZEND_ARG_INFO(0, fileName)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, exportAsCode)
{
zend_string *fileName;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(fileName)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ExportImageAsCode(intern->image, fileName->val);
}
// Get pixel data from image as a Color struct array
// RLAPI Color *GetImageData(Image image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_getData, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, getData)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
int numOfPixels = intern->image.width * intern->image.height;
Color* colors = LoadImageColors(intern->image);
array_init_size(return_value, numOfPixels);
for (int i = 0; i < numOfPixels; i++) {
zval *color = malloc(sizeof(zval));
object_init_ex(color, php_raylib_color_ce);
php_raylib_color_object *result = Z_COLOR_OBJ_P(color);
result->color = colors[i];
add_index_zval(return_value, i, color);
}
}
// Draw a source image within a destination image (tint applied to source)
// RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_draw, 0, 0, 4)
ZEND_ARG_INFO(0, src)
ZEND_ARG_INFO(0, srcRec)
ZEND_ARG_INFO(0, dstRec)
ZEND_ARG_INFO(0, tint)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, draw)
{
zval *src;
zval *srcRec;
zval *dstRec;
zval *tint;
ZEND_PARSE_PARAMETERS_START(4, 4)
Z_PARAM_ZVAL(src)
Z_PARAM_ZVAL(srcRec)
Z_PARAM_ZVAL(dstRec)
Z_PARAM_ZVAL(tint)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_image_object *phpSrc = Z_IMAGE_OBJ_P(src);
php_raylib_rectangle_object *phpSrcRec = Z_RECTANGLE_OBJ_P(srcRec);
php_raylib_rectangle_object *phpDstRec = Z_RECTANGLE_OBJ_P(dstRec);
php_raylib_color_object *phpTint = Z_COLOR_OBJ_P(tint);
ImageDraw(
&intern->image,
phpSrc->image,
phpSrcRec->rectangle,
phpDstRec->rectangle,
phpTint->color
);
}
// Draw text (default font) within an image (destination)
// RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_drawText, 0, 0, 5)
ZEND_ARG_INFO(0, posX)
ZEND_ARG_INFO(0, posY)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, fontSize)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, drawText)
{
zend_long posX;
zend_long posY;
zend_string *text;
zend_long fontSize;
zval *color;
ZEND_PARSE_PARAMETERS_START(5, 5)
Z_PARAM_LONG(posX)
Z_PARAM_LONG(posY)
Z_PARAM_STR(text)
Z_PARAM_LONG(fontSize)
Z_PARAM_ZVAL(color)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageDrawText(&intern->image, text->val, (int) posX, (int) posY, (int) fontSize, phpColor->color);
}
// Draw text (custom sprite font) within an image (destination)
// RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_drawTextEx, 0, 0, 6)
ZEND_ARG_INFO(0, position)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, fontSize)
ZEND_ARG_INFO(0, spacing)
ZEND_ARG_INFO(0, tint)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, drawTextEx)
{
zval *position;
zval *font;
zend_string *text;
double fontSize;
double spacing;
zval *tint;
ZEND_PARSE_PARAMETERS_START(6, 6)
Z_PARAM_ZVAL(position)
Z_PARAM_ZVAL(font)
Z_PARAM_STR(text)
Z_PARAM_DOUBLE(fontSize)
Z_PARAM_DOUBLE(spacing)
Z_PARAM_ZVAL(tint)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_vector2_object *phpPosition = Z_VECTOR2_OBJ_P(position);
php_raylib_color_object *phpTint = Z_COLOR_OBJ_P(tint);
php_raylib_font_object *phpFont = Z_FONT_OBJ_P(font);
ImageDrawTextEx(&intern->image, phpFont->font, ZSTR_VAL(text), phpPosition->vector2, (float) fontSize, (float) spacing, phpTint->color);
}
// RLAPI Image ImageText(const char *text, int fontSize, Color color);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_fromDefaultFont, 0, 0, 3)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, fontSize)
ZEND_ARG_INFO(0, tint)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, fromDefaultFont)
{
zend_string *text;
zend_long fontSize;
zval *tint;
ZEND_PARSE_PARAMETERS_START(3, 3)
Z_PARAM_STR(text)
Z_PARAM_LONG(fontSize)
Z_PARAM_ZVAL(tint)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpTint = Z_COLOR_OBJ_P(tint);
zval *obj = malloc(sizeof(zval));
object_init_ex(obj, php_raylib_image_ce);
php_raylib_image_object *result = Z_IMAGE_OBJ_P(obj);
result->image = ImageText(text->val, (int) fontSize, phpTint->color);
RETURN_OBJ(&result->std);
}
// RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_fromFont, 0, 0, 5)
ZEND_ARG_INFO(0, font)
ZEND_ARG_INFO(0, text)
ZEND_ARG_INFO(0, fontSize)
ZEND_ARG_INFO(0, spacing)
ZEND_ARG_INFO(0, tint)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, fromFont)
{
zval *font;
zend_string *text;
double fontSize;
double spacing;
zval *tint;
ZEND_PARSE_PARAMETERS_START(5, 5)
Z_PARAM_ZVAL(font)
Z_PARAM_STR(text)
Z_PARAM_DOUBLE(fontSize)
Z_PARAM_DOUBLE(spacing)
Z_PARAM_ZVAL(tint)
ZEND_PARSE_PARAMETERS_END();
php_raylib_font_object *phpFont = Z_FONT_OBJ_P(font);
php_raylib_color_object *phpTint = Z_COLOR_OBJ_P(tint);
zval *obj = malloc(sizeof(zval));
object_init_ex(obj, php_raylib_image_ce);
php_raylib_image_object *result = Z_IMAGE_OBJ_P(obj);
result->image = ImageTextEx(phpFont->font, text->val, (float) fontSize, (float) spacing, phpTint->color);
RETURN_OBJ(&result->std);
}
// Create an image from another image piece
//RLAPI Image ImageFromImage(Image image, Rectangle rec);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_fromImage, 0, 0, 2)
ZEND_ARG_INFO(0, image)
ZEND_ARG_INFO(0, rec)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, fromImage)
{
zval *image;
zval *rec;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(image)
Z_PARAM_ZVAL(rec)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *phpImage = Z_IMAGE_OBJ_P(image);
php_raylib_rectangle_object *phpRec = Z_RECTANGLE_OBJ_P(rec);
//-- Create Image Object
zval *obj = malloc(sizeof(zval));
object_init_ex(obj, php_raylib_image_ce);
php_raylib_image_object *result = Z_IMAGE_OBJ_P(obj);
//-- Assign new image struct to image object
result->image = ImageFromImage(phpImage->image, phpRec->rectangle);
RETURN_OBJ(&result->std);
}
// Create an image from an animated image, currently only GIF is supported
//RLAPI Image LoadImageAnim(const char *fileName, int *frames);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_fromAnim, 0, 0, 2)
ZEND_ARG_INFO(0, fileName)
ZEND_ARG_INFO(1, frames)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, fromAnim)
{
zend_string *fileName;
zval *frames;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STR(fileName)
Z_PARAM_ZVAL(frames)
ZEND_PARSE_PARAMETERS_END();
int framesOut;
zend_object *phpImage = php_raylib_image_new(php_raylib_image_ce);
php_raylib_image_object *result = php_raylib_image_fetch_object(phpImage);
//-- Assign new image struct to image object
result->image = LoadImageAnim(fileName->val, &framesOut);
//-- Assign frames to the output variable
ZVAL_DEREF(frames);
if (Z_TYPE_P(frames) == IS_LONG) {
Z_LVAL_P(frames) = framesOut;
} else if (Z_TYPE_P(frames) == IS_DOUBLE) {
Z_DVAL_P(frames) = framesOut;
} else {
php_error_docref(NULL, E_WARNING, "unexpected argument type, $frames must be an int or float.");
}
RETURN_OBJ(&result->std);
}
// Convert image data to desired format
// RLAPI void ImageFormat(Image *image, int newFormat);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_format, 0, 0, 1)
ZEND_ARG_INFO(0, newFormat)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, format)
{
zend_long newFormat;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(newFormat)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageFormat(&intern->image, (int) newFormat);
}
// Apply alpha mask to image
// RLAPI void ImageAlphaMask(Image *image, Image alphaMask);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_alphaMask, 0, 0, 2)
ZEND_ARG_INFO(0, color)
ZEND_ARG_INFO(0, threshold)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, alphaMask)
{
zval *alphaMask;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(alphaMask)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_image_object *phpAlphaMask = Z_IMAGE_OBJ_P(alphaMask);
ImageAlphaMask(&intern->image, phpAlphaMask->image);
}
// Clear alpha channel to desired color
// RLAPI void ImageAlphaClear(Image *image, Color color, float threshold);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_alphaClear, 0, 0, 2)
ZEND_ARG_INFO(0, color)
ZEND_ARG_INFO(0, threshold)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, alphaClear)
{
zval *color;
double threshold;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(color)
Z_PARAM_DOUBLE(threshold)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageAlphaClear(&intern->image, phpColor->color, (float) threshold);
}
// Crop image depending on alpha value
// RLAPI void ImageAlphaCrop(Image *image, float threshold);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_alphaCrop, 0, 0, 2)
ZEND_ARG_INFO(0, color)
ZEND_ARG_INFO(0, threshold)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, alphaCrop)
{
zval *color;
double threshold;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(color)
Z_PARAM_DOUBLE(threshold)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageAlphaClear(&intern->image, phpColor->color, (float) threshold);
}
// Premultiply alpha channel
// RLAPI void ImageAlphaPremultiply(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_alphaPremultiply, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, alphaPremultiply)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageAlphaPremultiply(&intern->image);
}
// Crop an image to a defined rectangle
// RLAPI void ImageCrop(Image *image, Rectangle crop);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_crop, 0, 0, 1)
ZEND_ARG_INFO(0, crop)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, crop)
{
zval *crop;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(crop)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_rectangle_object *phpCrop = Z_RECTANGLE_OBJ_P(crop);
ImageCrop(&intern->image, phpCrop->rectangle);
}
// Resize image (Bicubic scaling algorithm)
// RLAPI void ImageResize(Image *image, int newWidth, int newHeight);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_resize, 0, 0, 2)
ZEND_ARG_INFO(0, newWidth)
ZEND_ARG_INFO(0, newHeight)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, resize)
{
zend_long newWidth;
zend_long newHeight;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_LONG(newWidth)
Z_PARAM_LONG(newHeight)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageResize(&intern->image, (int) newWidth, (int) newHeight);
}
// Resize image (Nearest-Neighbor scaling algorithm)
// RLAPI void ImageResizeNN(Image *image, int newWidth, int newHeight);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_resizeNearestNeighbor, 0, 0, 2)
ZEND_ARG_INFO(0, newWidth)
ZEND_ARG_INFO(0, newHeight)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, resizeNearestNeighbor)
{
zend_long newWidth;
zend_long newHeight;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_LONG(newWidth)
Z_PARAM_LONG(newHeight)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageResizeNN(&intern->image, (int) newWidth, (int) newHeight);
}
// Resize canvas and fill with color
// RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color color);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_resizeCanvas, 0, 0, 5)
ZEND_ARG_INFO(0, newWidth)
ZEND_ARG_INFO(0, newHeight)
ZEND_ARG_INFO(0, offsetX)
ZEND_ARG_INFO(0, offsetY)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, resizeCanvas)
{
zend_long newWidth;
zend_long newHeight;
zend_long offsetX;
zend_long offsetY;
zval *color;
ZEND_PARSE_PARAMETERS_START(5, 5)
Z_PARAM_LONG(newWidth)
Z_PARAM_LONG(newHeight)
Z_PARAM_LONG(offsetX)
Z_PARAM_LONG(offsetY)
Z_PARAM_ZVAL(color)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageResizeCanvas(&intern->image, (int) newWidth, (int) newHeight, (int) offsetX, (int) offsetY, phpColor->color);
}
// Generate all mipmap levels for a provided image
// RLAPI void ImageMipmaps(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_genMipmaps, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, genMipmaps)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageMipmaps(&intern->image);
}
// Dither image data to 16bpp or lower (Floyd-Steinberg dithering)
// RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_dither, 0, 0, 1)
ZEND_ARG_INFO(0, fileName)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, dither)
{
zend_long rBpp;
zend_long gBpp;
zend_long bBpp;
zend_long aBpp;
ZEND_PARSE_PARAMETERS_START(4, 4)
Z_PARAM_LONG(rBpp)
Z_PARAM_LONG(gBpp)
Z_PARAM_LONG(bBpp)
Z_PARAM_LONG(aBpp)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageDither(&intern->image, (int) rBpp, (int) gBpp, (int) bBpp, (int) aBpp);
}
// Flip image vertically
// RLAPI void ImageFlipVertical(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_flipVertical, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, flipVertical)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageFlipVertical(&intern->image);
}
// Flip image horizontally
// RLAPI void ImageFlipHorizontal(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_flipHorizontal, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, flipHorizontal)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageFlipHorizontal(&intern->image);
}
// Rotate image clockwise 90deg
// RLAPI void ImageRotateCW(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_rotateClockwise, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, rotateClockwise)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageRotateCW(&intern->image);
}
// Rotate image counter-clockwise 90deg
// RLAPI void ImageRotateCCW(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_rotateCounterClockwise, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, rotateCounterClockwise)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageRotateCCW(&intern->image);
}
// Modify image color: tint
// RLAPI void ImageColorTint(Image *image, Color color);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorTint, 0, 0, 1)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorTint)
{
zval *color;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(color)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageColorTint(&intern->image, phpColor->color);
}
// Modify image color: invert
// RLAPI void ImageColorInvert(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorInvert, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorInvert)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageColorInvert(&intern->image);
}
// Modify image color: grayscale
// RLAPI void ImageColorGrayscale(Image *image);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorGrayscale, 0, 0, 0)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorGrayscale)
{
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageColorGrayscale(&intern->image);
}
// Modify image color: contrast (-100 to 100)
// RLAPI void ImageColorContrast(Image *image, float contrast);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorContrast, 0, 0, 1)
ZEND_ARG_INFO(0, contrast)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorContrast)
{
double contrast;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_DOUBLE(contrast)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageColorContrast(&intern->image, (float) contrast);
}
// Modify image color: brightness (-255 to 255)
// RLAPI void ImageColorBrightness(Image *image, int brightness);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorBrightness, 0, 0, 1)
ZEND_ARG_INFO(0, brightness)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorBrightness) // new ImageColorBrightness
{
zend_long brightness;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(brightness)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
ImageColorBrightness(&intern->image, (int) brightness);
}
// Modify image color: replace color
// RLAPI void ImageColorReplace(Image *image, Color color, Color replace);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_colorReplace, 0, 0, 2)
ZEND_ARG_INFO(0, color)
ZEND_ARG_INFO(0, replace)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, colorReplace) // new ImageColorReplace
{
zval *color;
zval *replace;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(color)
Z_PARAM_ZVAL(replace)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
php_raylib_color_object *phpReplace = Z_COLOR_OBJ_P(replace);
ImageColorReplace(&intern->image, phpColor->color, phpReplace->color);
}
// Load colors palette from image as a Color array (RGBA - 32bit)
// RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorsCount);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_loadPalette, 0, 0, 2)
ZEND_ARG_INFO(0, maxPaletteSize)
ZEND_ARG_INFO(0, z_extractCount)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, loadPalette)
{
double maxPaletteSize;
zval *z_extractCount;
int extractCount;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_DOUBLE(maxPaletteSize)
Z_PARAM_ZVAL(z_extractCount)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
extractCount = (int) zval_get_long(z_extractCount);
Color *colors = LoadImagePalette(intern->image, (int) maxPaletteSize, &extractCount);
ZEND_TRY_ASSIGN_REF_LONG(z_extractCount, extractCount);
array_init_size(return_value, extractCount);
for (int i = 0; i < extractCount; i++) {
zval *color = malloc(sizeof(zval));
object_init_ex(color, php_raylib_color_ce);
php_raylib_color_object *result = Z_COLOR_OBJ_P(color);
result->color = colors[i];
add_index_zval(return_value, i, color);
}
}
// Get image alpha border rectangle
// RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_getAlphaBorder, 0, 0, 1)
ZEND_ARG_INFO(0, threshold)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, getAlphaBorder)
{
double threshold;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_DOUBLE(threshold)
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
zval *obj = malloc(sizeof(zval));
object_init_ex(obj, php_raylib_rectangle_ce);
php_raylib_rectangle_object *result = Z_RECTANGLE_OBJ_P(obj);
result->rectangle = GetImageAlphaBorder(intern->image, (float) threshold);
RETURN_OBJ(&result->std);
}
// Draw rectangle within an image
// RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color);
ZEND_BEGIN_ARG_INFO_EX(arginfo_image_drawRectangleRec, 0, 0, 2)
ZEND_ARG_INFO(0, rec)
ZEND_ARG_INFO(0, color)
ZEND_END_ARG_INFO()
PHP_METHOD(Image, drawRectangleRec)
{
zval *rec;
zval *color;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(rec);
Z_PARAM_ZVAL(color);
ZEND_PARSE_PARAMETERS_END();
php_raylib_image_object *intern = Z_IMAGE_OBJ_P(ZEND_THIS);
php_raylib_rectangle_object *phpRec = Z_RECTANGLE_OBJ_P(rec);
php_raylib_color_object *phpColor = Z_COLOR_OBJ_P(color);
ImageDrawRectangleRec(
&intern->image,
phpRec->rectangle,
phpColor->color
);
}
const zend_function_entry php_raylib_image_methods[] = {
// PHP_ME(Image, fromColors, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Image, __construct , arginfo_image__construct, ZEND_ACC_PUBLIC)
PHP_ME(Image, fromDefaultFont , arginfo_image_fromDefaultFont, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Image, fromFont , arginfo_image_fromFont, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Image, fromImage , arginfo_image_fromImage, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Image, fromAnim , arginfo_image_fromAnim, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(Image, fromRaw , arginfo_image_fromRaw, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) // RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize);
PHP_ME(Image, toTexture , arginfo_image_toTexture, ZEND_ACC_PUBLIC)
PHP_ME(Image, getData , arginfo_image_getData, ZEND_ACC_PUBLIC) // RLAPI Color *GetImageData(Image image);
PHP_ME(Image, copy , arginfo_image_copy, ZEND_ACC_PUBLIC)
PHP_ME(Image, toPot , arginfo_image_toPot, ZEND_ACC_PUBLIC)
PHP_ME(Image, export , arginfo_image_export, ZEND_ACC_PUBLIC)
PHP_ME(Image, exportAsCode , arginfo_image_exportAsCode, ZEND_ACC_PUBLIC)
PHP_ME(Image, draw , arginfo_image_draw, ZEND_ACC_PUBLIC)
PHP_ME(Image, drawText , arginfo_image_drawText, ZEND_ACC_PUBLIC)
PHP_ME(Image, drawTextEx , arginfo_image_drawTextEx,ZEND_ACC_PUBLIC)
PHP_ME(Image, drawRectangleRec , arginfo_image_drawRectangleRec, ZEND_ACC_PUBLIC)
PHP_ME(Image, alphaMask , arginfo_image_alphaMask, ZEND_ACC_PUBLIC)
PHP_ME(Image, alphaClear , arginfo_image_alphaClear, ZEND_ACC_PUBLIC)
PHP_ME(Image, alphaCrop , arginfo_image_alphaCrop, ZEND_ACC_PUBLIC)
PHP_ME(Image, alphaPremultiply , arginfo_image_alphaPremultiply, ZEND_ACC_PUBLIC)
PHP_ME(Image, crop , arginfo_image_crop, ZEND_ACC_PUBLIC)
PHP_ME(Image, resize , arginfo_image_resize, ZEND_ACC_PUBLIC)
PHP_ME(Image, resizeNearestNeighbor , arginfo_image_resizeNearestNeighbor, ZEND_ACC_PUBLIC)
PHP_ME(Image, resizeCanvas , arginfo_image_resizeCanvas, ZEND_ACC_PUBLIC)
PHP_ME(Image, genMipmaps , arginfo_image_genMipmaps, ZEND_ACC_PUBLIC)
PHP_ME(Image, dither , arginfo_image_dither, ZEND_ACC_PUBLIC)
PHP_ME(Image, flipVertical , arginfo_image_flipVertical, ZEND_ACC_PUBLIC)
PHP_ME(Image, flipHorizontal , arginfo_image_flipHorizontal, ZEND_ACC_PUBLIC)
PHP_ME(Image, rotateClockwise , arginfo_image_rotateClockwise, ZEND_ACC_PUBLIC)
PHP_ME(Image, rotateCounterClockwise, arginfo_image_rotateCounterClockwise, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorTint , arginfo_image_colorTint, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorInvert , arginfo_image_colorInvert, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorGrayscale , arginfo_image_colorGrayscale, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorContrast , arginfo_image_colorContrast, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorBrightness , arginfo_image_colorBrightness, ZEND_ACC_PUBLIC)
PHP_ME(Image, colorReplace , arginfo_image_colorReplace, ZEND_ACC_PUBLIC)
PHP_ME(Image, loadPalette , arginfo_image_loadPalette, ZEND_ACC_PUBLIC)
PHP_ME(Image, getAlphaBorder , arginfo_image_getAlphaBorder, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static void php_raylib_image_free_prop_handler(zval *el) /* {{{ */ {
pefree(Z_PTR_P(el), 1);
} /* }}} */
// Extension class startup
void php_raylib_image_startup(INIT_FUNC_ARGS)
{
zend_class_entry ce;
//-- Object handlers
memcpy(&php_raylib_image_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
php_raylib_image_object_handlers.offset = XtOffsetOf(php_raylib_image_object, std);
php_raylib_image_object_handlers.free_obj = &php_raylib_image_free_storage;
php_raylib_image_object_handlers.clone_obj = NULL;
// Props
php_raylib_image_object_handlers.get_property_ptr_ptr = php_raylib_image_get_property_ptr_ptr;
php_raylib_image_object_handlers.get_gc = php_raylib_image_get_gc;
php_raylib_image_object_handlers.get_properties = php_raylib_image_get_properties;
php_raylib_image_object_handlers.read_property = php_raylib_image_read_property;
php_raylib_image_object_handlers.has_property = php_raylib_image_has_property;
//-- Class Methods
INIT_NS_CLASS_ENTRY(ce, "raylib", "Image", php_raylib_image_methods);
php_raylib_image_ce = zend_register_internal_class(&ce);
php_raylib_image_ce->create_object = php_raylib_image_new;
zend_hash_init(&php_raylib_image_prop_handlers, 0, NULL, php_raylib_image_free_prop_handler, 1);
php_raylib_image_register_prop_handler(&php_raylib_image_prop_handlers, "width", php_raylib_image_width);
php_raylib_image_register_prop_handler(&php_raylib_image_prop_handlers, "height", php_raylib_image_height);
php_raylib_image_register_prop_handler(&php_raylib_image_prop_handlers, "mipmaps", php_raylib_image_mipmaps);
php_raylib_image_register_prop_handler(&php_raylib_image_prop_handlers, "height", php_raylib_image_format);
} | 32.683294 | 203 | 0.707842 | [
"object"
] |
f287c6b7ede6b1420e2241ed58f836e13337525f | 6,656 | h | C | FDTD/operations/JMPML.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | FDTD/operations/JMPML.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | FDTD/operations/JMPML.h | plisdku/trogdor6 | d77eb137dd0c03635c0016801ada54117697e521 | [
"MIT"
] | null | null | null | /*
* UpdateJPML.h
* Trogdor6
*
* Created by Paul Hansen on 6/28/10.
* Copyright 2010 Stanford University. All rights reserved.
*
* This file is covered by the MIT license. See LICENSE.txt.
*/
#ifndef _UPDATEJPML_
#define _UPDATEJPML_
#include "../PhysicalConstants.h"
#include "../FieldEnum.h"
#include "../GridFields.h"
#include "../Operation.h"
#include <vector>
struct RunlineJMPML
{
RunlineJMPML() {}
RunlineJMPML(long current, long fieldHigh, long fieldLow, long inAux,
long inConsts, long inStride, long length) :
mCurrent(current),
mFieldHigh(fieldHigh),
mFieldLow(fieldLow),
mAux(inAux),
mConsts(inConsts),
mStride(inStride),
mLength(length)
{
assert(length > 0);
}
long length() const { return mLength; }
long mCurrent;
long mFieldHigh;
long mFieldLow;
long mAux;
long mConsts;
long mStride;
long mLength;
};
inline std::ostream & operator<<(std::ostream & str, const RunlineJMPML & rl)
{
str << "[curr " << rl.mCurrent << " fields " << rl.mFieldLow << ", "
<< rl.mFieldHigh << " aux " << rl.mAux << " consts " << rl.mConsts
<< "x" << rl.mStride << " length "
<< rl.mLength << "]";
return str;
}
class UpdateJMPML : public Operation
{
public:
UpdateJMPML()
{
}
UpdateJMPML(Field current, Field neighborField,
Precision::Float leadingSign, const std::vector<RunlineJMPML> & runlines,
const std::vector<PMLParameters> & params,
Precision::Float dt, Precision::Float dxyz) :
mFieldCurrent(current),
mFieldNeighbor(neighborField),
mRunlines(runlines),
m_c_hj(params.size()),
m_c_phij(params.size()),
m_c_hphi(params.size()),
m_c_jphi(params.size()),
mSign(leadingSign)
{
for (int nn = 0; nn < params.size(); nn++)
{
Precision::Float alpha = params[nn].alpha();
Precision::Float kappa = params[nn].kappa();
Precision::Float sigma = params[nn].sigma();
m_c_hj[nn] = ((2*Constants::eps0 + dt*alpha)/
(2*Constants::eps0*kappa + dt*(alpha*kappa + sigma)) - 1.0)
/ dxyz; // ALERT: the 1/dx went here!
m_c_phij[nn] = 2*Constants::eps0*kappa / (
2*Constants::eps0*kappa + dt*(alpha*kappa+sigma));
m_c_hphi[nn] = dt*(alpha - alpha*kappa - sigma) /
(Constants::eps0*kappa) / dxyz; // ALERT: the 1/dx went here!
m_c_jphi[nn] = dt*(alpha*kappa + sigma) /
(Constants::eps0*kappa);
// std::cerr << "nn " << nn << " hj " << m_c_hj[nn]
// << " phij " << m_c_phij[nn]
// << " hphi " << m_c_hphi[nn]
// << " jphi " << m_c_jphi[nn]
// << "\n";
}
name("JMPML");
}
void setPointers(GridFields & currentGridFields,
std::map<int, Pointer<GridFields> > & allGridFields)
{
mHeadCurrent = currentGridFields.field(mFieldCurrent);
mHeadNeighborField = currentGridFields.field(mFieldNeighbor);
}
void allocate()
{
long totalLength = 0;
for (int nn = 0; nn < mRunlines.size(); nn++)
totalLength += mRunlines[nn].length();
mPhi = std::vector<Precision::Float>(totalLength, 0.0);
// LOG << "allocated.\n";
}
unsigned long bytes() const
{
long totalBytes = 0;
totalBytes += mRunlines.size()*sizeof(RunlineJMPML);
totalBytes += sizeof(Precision::Float)*m_c_hj.size();
totalBytes += sizeof(Precision::Float)*m_c_phij.size();
totalBytes += sizeof(Precision::Float)*m_c_hphi.size();
totalBytes += sizeof(Precision::Float)*m_c_jphi.size();
totalBytes += sizeof(Precision::Float)*mPhi.size();
return totalBytes;
}
void apply(long timestep, Precision::Float dt)
{
for (int rr = 0; rr < mRunlines.size(); rr++)
{
Precision::Float* jm = mHeadCurrent + mRunlines[rr].mCurrent;
Precision::Float* phi = &(mPhi.at(mRunlines[rr].mAux));
const Precision::Float* ehLow = mHeadNeighborField + mRunlines[rr].mFieldLow;
const Precision::Float* ehHigh = mHeadNeighborField + mRunlines[rr].mFieldHigh;
const Precision::Float* c_hj = &(m_c_hj.at(mRunlines[rr].mConsts));
const Precision::Float* c_phij = &(m_c_phij.at(mRunlines[rr].mConsts));
const Precision::Float* c_hphi = &(m_c_hphi.at(mRunlines[rr].mConsts));
const Precision::Float* c_jphi = &(m_c_jphi.at(mRunlines[rr].mConsts));
unsigned long stride = mRunlines[rr].mStride;
const Precision::Float sign = mSign;
for (int ll = 0; ll < mRunlines[rr].length(); ll++)
{
Precision::Float diffEH = *ehHigh - *ehLow;
Precision::Float curr = *c_hj * diffEH +
*c_phij * (*phi);
// if (diffEH != 0)
// {
// std::cerr << "chj " << *c_hj << " diffEH " << diffEH
// << " c_phij " << *c_phij << " phi " << *phi << " curr "
// << sign*curr << "\n";
// std::cerr << " adding " << sign*curr << "\n";
// }
*jm += sign*curr;
*phi += *c_hphi * diffEH - *c_jphi * curr;
jm++;
phi++;
ehLow++;
ehHigh++;
c_hj += stride;
c_phij += stride;
c_hphi += stride;
c_jphi += stride;
}
}
}
void printRunlines(std::ostream & str) const
{
for (int nn = 0; nn < mRunlines.size(); nn++)
str << mRunlines[nn] << "\n";
}
long numCells() const
{
long cells = 0;
for (int nn = 0; nn < mRunlines.size(); nn++)
cells += mRunlines[nn].length();
return cells;
}
private:
Field mFieldCurrent, mFieldNeighbor;
std::vector<RunlineJMPML> mRunlines;
std::vector<Precision::Float> m_c_hj;
std::vector<Precision::Float> m_c_phij;
std::vector<Precision::Float> m_c_hphi;
std::vector<Precision::Float> m_c_jphi;
std::vector<Precision::Float> mPhi;
Precision::Float mSign;
Precision::Float* mHeadCurrent;
Precision::Float* mHeadNeighborField;
};
#endif
| 31.102804 | 91 | 0.526593 | [
"vector"
] |
f2a9b3ae191944d4c3def711b9daa59eb86df658 | 1,843 | c | C | d/shadow/room/deep_echos/mon/rogue.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/shadow/room/deep_echos/mon/rogue.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/shadow/room/deep_echos/mon/rogue.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | // rogue stuck in cave in
// has key for door in room 44
#include <std.h>
inherit "/std/monster";
create() {
object metal;
int x;
::create();
set_name("rogue");
set_id(({"dwarf","rogue dwarf","rogue"}));
set_gender("male");
set_race("dwarf");
set_short("dirty sneaky dwarf");
set_long("This stout dwarf looks terrible. "+
" He has been stuck down here for a while. "+
" His beard is stained and he is covered in mud."+
" He wears a simple mining cap. He is stuck"+
" under a rock perhaps you could _pull rock_ "+
"to free him.");
set_body_type("human");
set_alignment(2);
set_hd(6,2);
set_stats("strength",16);
set("aggressive",0);
set_stats("intelligence", 6);
set_stats("wisdom", 10);
set_stats("charisma",10);
set_stats("dexterity",10);
set_size(2);
set_property("swarm",0);
set_wielding_limbs(({"right hand","left hand"}));
set_overall_ac(10);
set_hp(random(50));
set_max_level(5);
for(x=0;x<7;x++)
new("/d/common/obj/misc/gem")->move(TO);
metal = new("/std/obj/metal.c");
metal->set_metal_quality(random(6)+5);
metal->move(TO);
key();
force_me("pose stuck under a rock");
}
void poof(){
if(!TP) return;
force_me("emote lets out a sigh of relief.");
force_me("say Thank gods, been stuck down here,"+
" seems like fer-ever. Take the loot,"+
" I'm done with dis place.");
force_me("emote heads out with a grunt.");
force_me("drop all");
force_me("west");
TO->move("/d/shadowgate/void");
}
void key(){
object ob;
ob = new ("/std/Object");
ob->set_name("iron key");
ob->set_short("A small iron key");
ob->set_id(({"key","iron key"}));
ob->set_long("This is a small iron key. "+
"It has an simple head. It's obviously meant"+
" for a simple lock.");
ob->set_weight(1);
ob->move(TO);
return ;
}
| 25.957746 | 54 | 0.62344 | [
"object"
] |
f2acab25aad8577d487c3aad6240a748d1442c0e | 1,312 | c | C | lib/wizards/moonstar/test/malys.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/moonstar/test/malys.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/moonstar/test/malys.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null |
inherit "obj/monster";
#define OWNER "Moonstar"
reset(arg) {
object armour;
::reset(arg);
if(arg) { return; }
set_level(100);
set_name("malystryx");
set_alias("dragon");
set_short("Malystryx, the huge red dragon is following "+OWNER);
set_long("Malystryx, the huge red dragon is following Moonstar.\n");
set_al(0);
set_exp(666666666);
set_aggressive(0);
}
heart_beat() {
object ob;
ob = find_player(lower_case(OWNER));
if(ob) {
if(environment(ob) != environment(this_object())) {
tell_room(environment(this_object()), "Malystryx follows "+OWNER+".\n");
move_object(this_object(), environment(ob));
tell_room(environment(this_object()),"Malystryx flies in after "+OWNER+".\n");
}
}
}
hit_player(int i) {
i = 0;
return ::hit_player(i);
}
void catch_tell(string str) {
string tmp, command, omistaja;
if(sscanf(str,"%s says 'Malystryx, %s'", omistaja, command) != 2) return;
if(omistaja != OWNER) return;
if(sscanf(command,"smile %s",tmp)) {
if(present(tmp,environment(this_object())))
say(query_name()+" smiles happily at "+capitalize(tmp)+".\n");
return;
}
if(sscanf(command,"hug %s",tmp)) {
if(present(tmp,environment(this_object())))
say(query_name()+" hugs "+capitalize(tmp)+" deeply.\n");
return;
}
}
| 23.854545 | 82 | 0.645579 | [
"object"
] |
f2ad541f5d86699cb65eb7c9b43c0af3ea660c9c | 8,014 | c | C | release/src-rt-6.x.4708/cfe/cfe/vendor/cfe_vendor_xreq.c | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src-rt-6.x.4708/cfe/cfe/vendor/cfe_vendor_xreq.c | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src-rt-6.x.4708/cfe/cfe/vendor/cfe_vendor_xreq.c | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /* *********************************************************************
* Broadcom Common Firmware Environment (CFE)
*
* IOCB dispatcher File: cfe_vendor_xreq.c
*
* This routine is the main API dispatch for CFE. User API
* calls, via the ROM entry point, get dispatched to routines
* in this module.
*
* This version of cfe_xreq is used for vendor extensions to
* CFE.
*
* This module looks similar to cfe_iocb_dispatch - it is different
* in that the data structure used, cfe_xiocb_t, uses fixed
* size field members (specifically, all 64-bits) no matter how
* the firmware is compiled. This ensures a consistent API
* interface on any implementation. When you call CFE
* from another program, the entry vector comes here first.
*
* Should the normal cfe_iocb interface change, this one should
* be kept the same for backward compatibility reasons.
*
* Author: Mitch Lichtenberg (mpl@broadcom.com)
*
*********************************************************************
*
* Copyright 2000,2001,2002,2003
* Broadcom Corporation. All rights reserved.
*
* This software is furnished under license and may be used and
* copied only in accordance with the following terms and
* conditions. Subject to these conditions, you may download,
* copy, install, use, modify and distribute modified or unmodified
* copies of this software in source and/or binary form. No title
* or ownership is transferred hereby.
*
* 1) Any source code used, modified or distributed must reproduce
* and retain this copyright notice and list of conditions
* as they appear in the source file.
*
* 2) No right is granted to use any trade name, trademark, or
* logo of Broadcom Corporation. The "Broadcom Corporation"
* name may not be used to endorse or promote products derived
* from this software without the prior written permission of
* Broadcom Corporation.
*
* 3) THIS SOFTWARE IS PROVIDED "AS-IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING BUT NOT LIMITED TO, ANY IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT
* SHALL BROADCOM BE LIABLE FOR ANY DAMAGES WHATSOEVER, AND IN
* PARTICULAR, BROADCOM SHALL NOT BE LIABLE FOR DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE), EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************* */
#include "lib_types.h"
#include "lib_malloc.h"
#include "lib_queue.h"
#include "lib_printf.h"
#include "lib_string.h"
#include "cfe_iocb.h"
#include "cfe_vendor_iocb.h"
#include "cfe_xiocb.h"
#include "cfe_vendor_xiocb.h"
#include "cfe_error.h"
#include "cfe_device.h"
#include "cfe_timer.h"
#include "cfe_mem.h"
#include "env_subr.h"
#include "cfe.h"
/* *********************************************************************
* Constants
********************************************************************* */
/* enum values for various plist types */
#define PLBUF 1 /* iocb_buffer_t */
/* *********************************************************************
* Structures
********************************************************************* */
struct cfe_vendor_xcmd_dispatch_s {
int xplistsize;
int iplistsize;
int plisttype;
};
/* *********************************************************************
* Command conversion table
* This table contains useful information for converting
* iocbs to xiocbs.
********************************************************************* */
const static struct cfe_vendor_xcmd_dispatch_s
cfe_vendor_xcmd_dispatch_table[CFE_CMD_VENDOR_MAX-CFE_CMD_VENDOR_USE] = {
{sizeof(xiocb_buffer_t), sizeof(iocb_buffer_t), PLBUF}, /* 0 : CFE_CMD_VENDOR_SAMPLE */
};
/* *********************************************************************
* Externs
********************************************************************* */
extern int cfe_vendor_iocb_dispatch(cfe_vendor_iocb_t *iocb);
extern cfe_int_t cfe_vendor_doxreq(cfe_vendor_xiocb_t *xiocb);
/* *********************************************************************
* cfe_vendor_doxreq(xiocb)
*
* Process an xiocb request. This routine converts an xiocb
* into an iocb, calls the IOCB dispatcher, converts the results
* back into the xiocb, and returns.
*
* Input parameters:
* xiocb - pointer to user xiocb
*
* Return value:
* command status, <0 if error occured
********************************************************************* */
cfe_int_t cfe_vendor_doxreq(cfe_vendor_xiocb_t *xiocb)
{
const struct cfe_vendor_xcmd_dispatch_s *disp;
cfe_vendor_iocb_t iiocb;
cfe_int_t res;
/*
* Check for commands codes out of range
*/
if ((xiocb->xiocb_fcode < CFE_CMD_VENDOR_USE) ||
(xiocb->xiocb_fcode >= CFE_CMD_VENDOR_MAX)) {
xiocb->xiocb_status = CFE_ERR_INV_COMMAND;
return xiocb->xiocb_status;
}
/*
* Check for command codes in range but invalid
*/
disp = &cfe_vendor_xcmd_dispatch_table[xiocb->xiocb_fcode - CFE_CMD_VENDOR_USE];
if (disp->xplistsize < 0) {
xiocb->xiocb_status = CFE_ERR_INV_COMMAND;
return xiocb->xiocb_status;
}
/*
* Check for invalid parameter list size
*/
if (disp->xplistsize != xiocb->xiocb_psize) {
xiocb->xiocb_status = CFE_ERR_INV_PARAM;
return xiocb->xiocb_status;
}
/*
* Okay, copy parameters into the internal IOCB.
* First, the fixed header.
*/
iiocb.iocb_fcode = (unsigned int) xiocb->xiocb_fcode;
iiocb.iocb_status = (int) xiocb->xiocb_status;
iiocb.iocb_handle = (int) xiocb->xiocb_handle;
iiocb.iocb_flags = (unsigned int) xiocb->xiocb_flags;
iiocb.iocb_psize = (unsigned int) disp->iplistsize;
/*
* Now the parameter list
*/
switch (disp->plisttype) {
case PLBUF:
iiocb.plist.iocb_buffer.buf_offset = (cfe_offset_t) xiocb->plist.xiocb_buffer.buf_offset;
iiocb.plist.iocb_buffer.buf_ptr = (unsigned char *) (uintptr_t) xiocb->plist.xiocb_buffer.buf_ptr;
iiocb.plist.iocb_buffer.buf_length = (unsigned int) xiocb->plist.xiocb_buffer.buf_length;
iiocb.plist.iocb_buffer.buf_retlen = (unsigned int) xiocb->plist.xiocb_buffer.buf_retlen;
iiocb.plist.iocb_buffer.buf_ioctlcmd = (unsigned int) xiocb->plist.xiocb_buffer.buf_ioctlcmd;
break;
}
/*
* Do the internal function dispatch
*/
res = (cfe_int_t) cfe_vendor_iocb_dispatch(&iiocb);
/*
* Now convert the parameter list members back
*/
switch (disp->plisttype) {
case PLBUF:
xiocb->plist.xiocb_buffer.buf_offset = (cfe_uint_t) iiocb.plist.iocb_buffer.buf_offset;
xiocb->plist.xiocb_buffer.buf_ptr = (cfe_xptr_t) (uintptr_t) iiocb.plist.iocb_buffer.buf_ptr;
xiocb->plist.xiocb_buffer.buf_length = (cfe_uint_t) iiocb.plist.iocb_buffer.buf_length;
xiocb->plist.xiocb_buffer.buf_retlen = (cfe_uint_t) iiocb.plist.iocb_buffer.buf_retlen;
xiocb->plist.xiocb_buffer.buf_ioctlcmd = (cfe_uint_t) iiocb.plist.iocb_buffer.buf_ioctlcmd;
break;
}
/*
* And the fixed header
*/
xiocb->xiocb_status = (cfe_int_t) iiocb.iocb_status;
xiocb->xiocb_handle = (cfe_int_t) iiocb.iocb_handle;
xiocb->xiocb_flags = (cfe_uint_t) iiocb.iocb_flags;
return xiocb->xiocb_status;
}
| 35.93722 | 103 | 0.604692 | [
"vector"
] |
f135efffa9a231ca54f4fd49ab0ea7bb18861ccf | 643 | h | C | DBCommunication/dbcommunicator.h | chaunnt/Qt-UI-Kits | d2832be43aa3910b7b1ba1c0aa21dc84230287cf | [
"MIT"
] | null | null | null | DBCommunication/dbcommunicator.h | chaunnt/Qt-UI-Kits | d2832be43aa3910b7b1ba1c0aa21dc84230287cf | [
"MIT"
] | null | null | null | DBCommunication/dbcommunicator.h | chaunnt/Qt-UI-Kits | d2832be43aa3910b7b1ba1c0aa21dc84230287cf | [
"MIT"
] | null | null | null | #ifndef DBCOMMUNICATOR_H
#define DBCOMMUNICATOR_H
#include <QObject>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QSqlResult>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include "globaldefine.h"
#include "Model/simpledata.h"
class DBCommunicator : public QObject
{
Q_OBJECT
QSqlDatabase m_dbBDSData;
public:
explicit DBCommunicator(QObject *parent = nullptr);
bool addRecord(QString strData);
bool updateRecord(QString strData);
QList<QObject*> loadAllData();
signals:
public slots:
};
#endif // DBCOMMUNICATOR_H
| 17.861111 | 55 | 0.752722 | [
"model"
] |
f136a06d629e1d583db75cf72e8a11e2d6290d56 | 2,284 | h | C | src/client_main/engine/entities/entity.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | src/client_main/engine/entities/entity.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | 7 | 2021-05-30T21:52:39.000Z | 2021-06-25T22:35:28.000Z | src/client_main/engine/entities/entity.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | #ifndef PROJECTFARM_ENTITY_H
#define PROJECTFARM_ENTITY_H
#include <cstdint>
#include <vector>
#include "entities/entity_types.h"
#include "graphics/renderable.h"
#include "time/consume_timer.h"
namespace projectfarm::engine::entities
{
class Entity : public graphics::Renderable,
public shared::time::ConsumeTimer
{
public:
Entity() = default;
~Entity() override = default;
void Tick() noexcept;
[[nodiscard]] virtual bool Load() noexcept = 0;
virtual void Shutdown() noexcept = 0;
virtual shared::entities::EntityTypes GetEntityType() const noexcept = 0;
[[nodiscard]] uint32_t GetEntityId() const noexcept
{
return this->_entityId;
}
void SetEntityId(uint32_t entityId) noexcept
{
this->_entityId = entityId;
}
[[nodiscard]] uint64_t GetLastUpdateTime() const noexcept
{
return this->_lastUpdateTime;
}
void SetLastUpdateTime(uint64_t lastUpdateTime) noexcept
{
this->_lastUpdateTime = lastUpdateTime;
}
virtual void SetData(const std::vector<std::byte>&) noexcept
{
}
[[nodiscard]] virtual std::vector<std::byte> GetEntityData() const noexcept
{
return {};
}
[[nodiscard]] bool ShouldBroadcastState() const noexcept
{
return this->_shouldBroadcastState &&
this->_currentBroadcastStateTime >= this->_broadcastStateTime;
}
void SetBroadcastStateTime(uint64_t milliseconds) noexcept
{
this->_broadcastStateTime = milliseconds * 1000;
}
void ResetBroadcastCounter() noexcept
{
this->_currentBroadcastStateTime = 0;
}
void SetShouldBroadcastState(bool shouldBroadcastState) noexcept
{
this->_shouldBroadcastState = shouldBroadcastState;
}
protected:
virtual void OnTick() noexcept = 0;
uint32_t _entityId {0};
uint64_t _lastUpdateTime {0};
bool _shouldBroadcastState {false};
uint64_t _broadcastStateTime {0};
uint64_t _currentBroadcastStateTime {0};
};
}
#endif
| 25.377778 | 83 | 0.605517 | [
"vector"
] |
f147b5e957f6126d237728d6dd6756f6813b9dec | 674 | h | C | OpenGL ES_Test/OpenGL ES Test/SceneModel.h | iOScontiue/OpenGL-ES-SkyboxEffect | dfc1352dd09665919577de1df87d5b16ddfc6354 | [
"MIT"
] | null | null | null | OpenGL ES_Test/OpenGL ES Test/SceneModel.h | iOScontiue/OpenGL-ES-SkyboxEffect | dfc1352dd09665919577de1df87d5b16ddfc6354 | [
"MIT"
] | null | null | null | OpenGL ES_Test/OpenGL ES Test/SceneModel.h | iOScontiue/OpenGL-ES-SkyboxEffect | dfc1352dd09665919577de1df87d5b16ddfc6354 | [
"MIT"
] | null | null | null | //
// SceneModel.h
// 01-Car
//
// Created by CC老师 on 2018/1/24.
// Copyright © 2018年 CC老师. All rights reserved.
//
#import <GLKit/GLKit.h>
@class AGLKVertexAttribArrayBuffer;
@class SceneMesh;
//现场包围盒
typedef struct
{
GLKVector3 min;
GLKVector3 max;
}SceneAxisAllignedBoundingBox;
@interface SceneModel : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)SceneAxisAllignedBoundingBox axisAlignedBoundingBox;
- (id)initWithName:(NSString *)aName mesh:(SceneMesh *)aMesh numberOfVertices:(GLsizei)aCount;
//绘制
- (void)draw;
//顶点数据改变后,重新计算边界
- (void)updateAlignedBoundingBoxForVertices:(float *)verts count:(int)aCount;
@end
| 18.722222 | 94 | 0.750742 | [
"mesh"
] |
f14b90a62f781c3ca5fc9fb31b842d1a5115d119 | 3,673 | h | C | RailUnitTests/TestUtils.h | CathalT/Rail | 4c5623c9c69eca67e46beb554bdfc71d44627f73 | [
"MIT"
] | null | null | null | RailUnitTests/TestUtils.h | CathalT/Rail | 4c5623c9c69eca67e46beb554bdfc71d44627f73 | [
"MIT"
] | 21 | 2018-03-08T12:17:34.000Z | 2018-07-18T21:11:33.000Z | RailUnitTests/TestUtils.h | CathalT/Rail | 4c5623c9c69eca67e46beb554bdfc71d44627f73 | [
"MIT"
] | null | null | null | #pragma once
namespace TestUtils
{
constexpr char TEST_PASSWORD[] = "test123";
constexpr char TEST_ADDRESS_ONE[] = "xrb_1oocugiybqxypp7f9qpt4d48dxbqtczhg68z5db17xr3sbosdq7bq8zufm9m";
constexpr char TEST_SEED_ONE[] = "FBE0A52D1A5A4FF9E2F0B5F716BE07FAEF5E21797FD60A2E3858001A3FCD54A3";
constexpr char TEST_ADDRESS_TWO[] = "xrb_1sjhm4guw13t6d5nynwqrd34eh7kwiatrh7jrihcsqizd683ghepxnomcemt";
constexpr char TEST_SEED_TWO[] = "34E41BE2C40454F4E853C6633243689068F95BDB03286A4283CC65C9C73A6F67";
constexpr std::array<std::byte, 32> TEST_SEED_ONE_BYTES =
{ std::byte(0xFB), std::byte(0xE0), std::byte(0xA5), std::byte(0x2D), std::byte(0x1A), std::byte(0x5A), std::byte(0x4F), std::byte(0xF9),
std::byte(0xE2), std::byte(0xF0), std::byte(0xB5), std::byte(0xF7), std::byte(0x16), std::byte(0xBE), std::byte(0x07), std::byte(0xFA),
std::byte(0xEF), std::byte(0x5E), std::byte(0x21), std::byte(0x79), std::byte(0x7F), std::byte(0xD6), std::byte(0x0A), std::byte(0x2E),
std::byte(0x38), std::byte(0x58), std::byte(0x00), std::byte(0x1A), std::byte(0x3F), std::byte(0xCD), std::byte(0x54), std::byte(0xA3) };
constexpr std::array<std::byte, 32> TEST_SEED_TWO_BYTES =
{ std::byte(0x34), std::byte(0xE4), std::byte(0x1B), std::byte(0xE2), std::byte(0xC4), std::byte(0x04), std::byte(0x54), std::byte(0xF4),
std::byte(0xE8), std::byte(0x53), std::byte(0xC6), std::byte(0x63), std::byte(0x32), std::byte(0x43), std::byte(0x68), std::byte(0x90),
std::byte(0x68), std::byte(0xF9), std::byte(0x5B), std::byte(0xDB), std::byte(0x03), std::byte(0x28), std::byte(0x6A), std::byte(0x42),
std::byte(0x83), std::byte(0xCC), std::byte(0x65), std::byte(0xC9), std::byte(0xC7), std::byte(0x3A), std::byte(0x6F), std::byte(0x67) };
constexpr std::array<std::byte, 32> TEST_PASS_KEY_SALT =
{ std::byte(0x8b), std::byte(0x46), std::byte(0xe4), std::byte(0xed), std::byte(0x51), std::byte(0xbd), std::byte(0x5b), std::byte(0x24),
std::byte(0xd0), std::byte(0x15), std::byte(0xd7), std::byte(0xf9), std::byte(0xf2), std::byte(0x2a), std::byte(0xb7), std::byte(0xc3),
std::byte(0xa9), std::byte(0xe7), std::byte(0xa6), std::byte(0x34), std::byte(0xdc), std::byte(0x46), std::byte(0xe3), std::byte(0x3b),
std::byte(0x08), std::byte(0x3f), std::byte(0xd2), std::byte(0xf9), std::byte(0x7d), std::byte(0x83), std::byte(0xc4), std::byte(0xb0) };
constexpr std::array<std::byte, 16> TEST_SEED_ONE_IV =
{ std::byte(0x02), std::byte(0xb0), std::byte(0x5f), std::byte(0x01), std::byte(0xa9), std::byte(0x77), std::byte(0x82), std::byte(0xe5),
std::byte(0x6c), std::byte(0x97), std::byte(0xf0), std::byte(0x2e), std::byte(0x60), std::byte(0x87), std::byte(0xcd), std::byte(0x34) };
const std::vector<std::byte> ENCRYPTED_SEED_ONE =
{ std::byte(0x31), std::byte(0xfb), std::byte(0xba), std::byte(0x8d), std::byte(0x9c), std::byte(0xb1), std::byte(0x7c), std::byte(0x89),
std::byte(0x8a), std::byte(0x6c), std::byte(0x73), std::byte(0xec), std::byte(0x5e), std::byte(0x6c), std::byte(0xb8), std::byte(0xde),
std::byte(0xdd), std::byte(0x89), std::byte(0x22), std::byte(0xe2), std::byte(0xd2), std::byte(0x35), std::byte(0x78), std::byte(0xdb),
std::byte(0xce), std::byte(0x02), std::byte(0x71), std::byte(0x41), std::byte(0xe5), std::byte(0xd1), std::byte(0x8d), std::byte(0x19),
std::byte(0x91), std::byte(0x6a), std::byte(0x2f), std::byte(0x90), std::byte(0x66), std::byte(0x82), std::byte(0x1d), std::byte(0xda),
std::byte(0x94), std::byte(0x77), std::byte(0xe0), std::byte(0x6c), std::byte(0x90), std::byte(0xcc), std::byte(0xdb), std::byte(0x77) };
} | 87.452381 | 143 | 0.653961 | [
"vector"
] |
f1545c6ccf6972f7a76881d887d59d1a8260e037 | 4,510 | h | C | source/Common.h | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | source/Common.h | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | source/Common.h | sormo/simpleSDL | 79a830a013f911c4670c86ccf68bd068a887670d | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include "glm/glm.hpp"
#if defined(ANDROID)
// Just rerouting printf to logcat on android (not a complete logging solution).
#include <android/log.h>
#define printf(...) __android_log_print(ANDROID_LOG_INFO, "SIMPLE_EXAMPLE", __VA_ARGS__)
#else
#include <cstdio>
#endif
class Camera;
#define COUNTOF(_ARR) ((uint32_t)(sizeof(_ARR)/sizeof(*_ARR)))
namespace Common
{
std::vector<uint8_t> ReadFile(const char * name);
std::string ReadFileToString(const char * name);
bool WriteFile(const char* name, const std::vector<uint8_t>& data);
bool AppendFile(const char* name, const std::vector<uint8_t>& data);
std::tuple<int32_t, int32_t> GetWindowSize();
int32_t GetWindowWidth();
int32_t GetWindowHeight();
// seconds since epoch
double GetCurrentTimeInSeconds();
// directory if not empty, will be delimited with '/'
std::string GetDirectoryFromFilePath(const std::string & filePath);
// reading integral types from buffer
template<class T>
T BufferRead(const std::vector<uint8_t> & data, uint32_t offset)
{
T value = 0;
memcpy(&value, &(data[offset]), sizeof(T));
return value;
}
std::vector<uint8_t> ConvertBGRToRGB(const uint8_t * data, uint32_t count);
std::vector<uint8_t> ConvertARGBToRGBA(const uint8_t * data, uint32_t count);
namespace Frame
{
void Signal();
float GetFPS();
}
// from depth value [0, 1] make distance [nearPlane, farPlane]
float LinearizeDepth(float depth, float nearPlane, float farPlane);
// from distance [nearPlane, farPlane] make depth [0, 1]
float MakeDepth(float distance, float nearPlane, float farPlane);
// from screen point ([0,0] in upper left) make point in world space with distance from camera (in [nearPlane, farPlane])
glm::vec3 GetPointWorldSpace(const glm::vec2 & position, float distance, const Camera & camera);
// TODO those two doesn't work correcly
glm::vec3 GetPointWorldSpaceManual(const glm::vec2 & position, float distance, const Camera & camera);
glm::vec3 GetPointWorldSpaceDirection(const glm::vec2 & position, float distance, const Camera & camera);
namespace Math
{
static const float DEFAULT_SIGMA = 0.01f;
bool IsPowerOfTwo(int32_t n);
bool IsNear(float a, float b, float sigma = DEFAULT_SIGMA);
struct Line
{
static Line CreateFromPoints(const glm::vec3 & p1, const glm::vec3 & p2);
// parameter t (of R)
// line: x = point.x + vector.x * t
// y = point.y + vector.y * t
// z = point.z + vector.z * t
glm::vec3 vector;
glm::vec3 point;
};
struct Plane
{
static Plane CreateFromPoints(const glm::vec3 & p1, const glm::vec3 & p2, const glm::vec3 & p3);
void Translate(const glm::vec3 & vector);
// rotation will "displace" plane,
void Rotate(const glm::vec3 & radians);
// move plane such point is contained within plane
void Position(const glm::vec3& point);
// plane: normal.x * x + normal.y * y + normal.z * z - value = 0;
glm::vec3 normal;
float value;
};
glm::vec3 GetIntersection(const Plane & plane, const Line & line);
glm::vec3 GetRotation(float radians, const glm::vec3 & axis);
glm::vec3 RotateRotation(const glm::vec3& rotation, float radians, const glm::vec3& axis);
glm::vec3 RotateVector(const glm::vec3& vector, const glm::vec3& rotation);
float GetAngle(const glm::vec3& p1, const glm::vec3& p2);
// signed angle according to plane normal
float GetAngle(const glm::vec3& p1, const glm::vec3& p2, const Plane & plane);
float GetDistance(const Plane& plane, const glm::vec3& p);
glm::vec3 GetClosestPointOnLine(const Line& line, const glm::vec3& p);
}
// get ray from camera going through position in screen coordinates
Math::Line GetRay(const glm::vec2 & position, const Camera & camera);
template<class T>
std::vector<T> MergeVectors(const std::vector<T> & v1, const std::vector<T> & v2)
{
std::vector<T> result;
result.reserve(v1.size() + v2.size());
result.insert(result.end(), v1.begin(), v1.end());
result.insert(result.end(), v2.begin(), v2.end());
return result;
}
}
| 35.511811 | 125 | 0.635033 | [
"vector"
] |
f15b7f27bdf6c8650a9358b08643b047302351a0 | 581 | h | C | include/ScreenOverlays/EnemyDefeatedScreenOverlay.h | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 279 | 2015-05-06T19:04:07.000Z | 2022-03-21T21:33:38.000Z | include/ScreenOverlays/EnemyDefeatedScreenOverlay.h | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 222 | 2016-10-26T15:56:25.000Z | 2021-10-03T15:30:18.000Z | include/ScreenOverlays/EnemyDefeatedScreenOverlay.h | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 49 | 2015-10-01T21:23:03.000Z | 2022-03-19T20:11:31.000Z | #pragma once
#include "ScreenOverlays/TextureScreenOverlay.h"
#include "GUI/BitmapText.h"
#include "GUI/InventorySlot.h"
class EnemyDefeatedScreenOverlay final : public TextureScreenOverlay {
public:
EnemyDefeatedScreenOverlay(const sf::Time& activeTime, const sf::Time& fadeTime = sf::Time::Zero);
~EnemyDefeatedScreenOverlay();
void update(const sf::Time& frameTime) override;
void render(sf::RenderTarget& target) override;
void setLoot(std::map<std::string, int>& items, int gold);
private:
std::vector<InventorySlot*> m_items;
std::vector<BitmapText*> m_texts;
};
| 27.666667 | 99 | 0.767642 | [
"render",
"vector"
] |
f165358e345d3a26ee841b8206cfc99ec8148ef0 | 9,706 | c | C | extern/gtk/demos/gtk-demo/gskshaderpaintable.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/demos/gtk-demo/gskshaderpaintable.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/demos/gtk-demo/gskshaderpaintable.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | /*
* Copyright © 2020 Red Hat, Inc
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Matthias Clasen <mclasen@redhat.com>
*/
#include "config.h"
#include <gtk/gtk.h>
#include "gskshaderpaintable.h"
/**
* GskShaderPaintable:
*
* `GskShaderPaintable` is an implementation of the `GdkPaintable` interface
* that uses a `GskGLShader` to create pixels.
*
* You can set the uniform data that the shader needs for rendering
* using gsk_shader_paintable_set_args(). This function can
* be called repeatedly to change the uniform data for the next
* snapshot.
*
* Commonly, time is passed to shaders as a float uniform containing
* the elapsed time in seconds. The convenience API
* gsk_shader_paintable_update_time() can be called from a `GtkTickCallback`
* to update the time based on the frame time of the frame clock.
*/
struct _GskShaderPaintable
{
GObject parent_instance;
GskGLShader *shader;
GBytes *args;
gint64 start_time;
};
struct _GskShaderPaintableClass
{
GObjectClass parent_class;
};
enum {
PROP_0,
PROP_SHADER,
PROP_ARGS,
N_PROPS,
};
static GParamSpec *properties[N_PROPS] = { NULL, };
static void
gsk_shader_paintable_paintable_snapshot (GdkPaintable *paintable,
GdkSnapshot *snapshot,
double width,
double height)
{
GskShaderPaintable *self = GSK_SHADER_PAINTABLE (paintable);
gtk_snapshot_push_gl_shader (snapshot, self->shader, &GRAPHENE_RECT_INIT(0, 0, width, height), g_bytes_ref (self->args));
gtk_snapshot_pop (snapshot);
}
static void
gsk_shader_paintable_paintable_init (GdkPaintableInterface *iface)
{
iface->snapshot = gsk_shader_paintable_paintable_snapshot;
}
G_DEFINE_TYPE_EXTENDED (GskShaderPaintable, gsk_shader_paintable, G_TYPE_OBJECT, 0,
G_IMPLEMENT_INTERFACE (GDK_TYPE_PAINTABLE,
gsk_shader_paintable_paintable_init))
static void
gsk_shader_paintable_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GskShaderPaintable *self = GSK_SHADER_PAINTABLE (object);
switch (prop_id)
{
case PROP_SHADER:
gsk_shader_paintable_set_shader (self, g_value_get_object (value));
break;
case PROP_ARGS:
gsk_shader_paintable_set_args (self, g_value_get_boxed (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsk_shader_paintable_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GskShaderPaintable *self = GSK_SHADER_PAINTABLE (object);
switch (prop_id)
{
case PROP_SHADER:
g_value_set_object (value, self->shader);
break;
case PROP_ARGS:
g_value_set_boxed (value, self->args);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsk_shader_paintable_finalize (GObject *object)
{
GskShaderPaintable *self = GSK_SHADER_PAINTABLE (object);
g_clear_pointer (&self->args, g_bytes_unref);
g_clear_object (&self->shader);
G_OBJECT_CLASS (gsk_shader_paintable_parent_class)->finalize (object);
}
static void
gsk_shader_paintable_class_init (GskShaderPaintableClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->get_property = gsk_shader_paintable_get_property;
gobject_class->set_property = gsk_shader_paintable_set_property;
gobject_class->finalize = gsk_shader_paintable_finalize;
properties[PROP_SHADER] =
g_param_spec_object ("shader", "Shader", "The shader",
GSK_TYPE_GL_SHADER,
G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);
properties[PROP_ARGS] =
g_param_spec_boxed ("args", "Arguments", "The uniform arguments",
G_TYPE_BYTES,
G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS);
g_object_class_install_properties (gobject_class, N_PROPS, properties);
}
static void
gsk_shader_paintable_init (GskShaderPaintable *self)
{
}
/**
* gsk_shader_paintable_new:
* @shader: (transfer full) (nullable): the shader to use
* @data: (transfer full) (nullable): uniform data
*
* Creates a paintable that uses the @shader to create
* pixels. The shader must not require input textures.
* If @data is %NULL, all uniform values are set to zero.
*
* Returns: (transfer full): a new `GskShaderPaintable`
*/
GdkPaintable *
gsk_shader_paintable_new (GskGLShader *shader,
GBytes *data)
{
GdkPaintable *ret;
g_return_val_if_fail (shader == NULL || GSK_IS_GL_SHADER (shader), NULL);
if (shader && !data)
{
int size = gsk_gl_shader_get_args_size (shader);
data = g_bytes_new_take (g_new0 (guchar, size), size);
}
ret = g_object_new (GSK_TYPE_SHADER_PAINTABLE,
"shader", shader,
"args", data,
NULL);
g_clear_object (&shader);
g_clear_pointer (&data, g_bytes_unref);
return ret;
}
/**
* gsk_shader_paintable_set_shader:
* @self: a `GskShaderPaintable`
* @shader: the `GskGLShader` to use
*
* Sets the shader that the paintable will use
* to create pixels. The shader must not require
* input textures.
*/
void
gsk_shader_paintable_set_shader (GskShaderPaintable *self,
GskGLShader *shader)
{
g_return_if_fail (GSK_IS_SHADER_PAINTABLE (self));
g_return_if_fail (shader == NULL || GSK_IS_GL_SHADER (shader));
g_return_if_fail (shader == NULL || gsk_gl_shader_get_n_textures (shader) == 0);
if (!g_set_object (&self->shader, shader))
return;
g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_SHADER]);
gdk_paintable_invalidate_contents (GDK_PAINTABLE (self));
g_clear_pointer (&self->args, g_bytes_unref);
}
/**
* gsk_shader_paintable_get_shader:
* @self: a `GskShaderPaintable`
*
* Returns the shader that the paintable is using.
*
* Returns: (transfer none): the `GskGLShader` that is used
*/
GskGLShader *
gsk_shader_paintable_get_shader (GskShaderPaintable *self)
{
g_return_val_if_fail (GSK_IS_SHADER_PAINTABLE (self), NULL);
return self->shader;
}
/**
* gsk_shader_paintable_set_args:
* @self: a `GskShaderPaintable`
* @data: Data block with uniform data for the shader
*
* Sets the uniform data that will be passed to the
* shader when rendering. The @data will typically
* be produced by a `GskUniformDataBuilder`.
*
* Note that the @data should be considered immutable
* after it has been passed to this function.
*/
void
gsk_shader_paintable_set_args (GskShaderPaintable *self,
GBytes *data)
{
g_return_if_fail (GSK_IS_SHADER_PAINTABLE (self));
g_return_if_fail (data == NULL || g_bytes_get_size (data) == gsk_gl_shader_get_args_size (self->shader));
g_clear_pointer (&self->args, g_bytes_unref);
if (data)
self->args = g_bytes_ref (data);
g_object_notify_by_pspec (G_OBJECT (self), properties[PROP_ARGS]);
gdk_paintable_invalidate_contents (GDK_PAINTABLE (self));
}
/**
* gsk_shader_paintable_get_args:
* @self: a `GskShaderPaintable`
*
* Returns the uniform data set with
* gsk_shader_paintable_get_args().
*
* Returns: (transfer none): the uniform data
*/
GBytes *
gsk_shader_paintable_get_args (GskShaderPaintable *self)
{
g_return_val_if_fail (GSK_IS_SHADER_PAINTABLE (self), NULL);
return self->args;
}
/**
* gsk_shader_paintable_update_time:
* @self: a `GskShaderPaintable`
* @time_idx: the index of the uniform for time in seconds as float
* @frame_time: the current frame time, as returned by `GdkFrameClock`
*
* This function is a convenience wrapper for
* gsk_shader_paintable_set_args() that leaves all
* uniform values unchanged, except for the uniform with
* index @time_idx, which will be set to the elapsed time
* in seconds, since the first call to this function.
*
* This function is usually called from a `GtkTickCallback`.
*/
void
gsk_shader_paintable_update_time (GskShaderPaintable *self,
int time_idx,
gint64 frame_time)
{
GskShaderArgsBuilder *builder;
GBytes *args;
float time;
if (self->start_time == 0)
self->start_time = frame_time;
time = (frame_time - self->start_time) / (float)G_TIME_SPAN_SECOND;
builder = gsk_shader_args_builder_new (self->shader, self->args);
gsk_shader_args_builder_set_float (builder, time_idx, time);
args = gsk_shader_args_builder_free_to_args (builder);
gsk_shader_paintable_set_args (self, args);
g_bytes_unref (args);
}
| 28.973134 | 123 | 0.68638 | [
"object"
] |
f165f7b57e30072fcc40f0675b051503ce38fb75 | 24,944 | h | C | src/traveller.h | Wjc1999/Data_structure_touring_simulator | a794518e33311563fc58df9f7f6c65e17ced5a2a | [
"MIT"
] | null | null | null | src/traveller.h | Wjc1999/Data_structure_touring_simulator | a794518e33311563fc58df9f7f6c65e17ced5a2a | [
"MIT"
] | 1 | 2019-03-30T10:50:48.000Z | 2019-03-30T10:50:48.000Z | src/traveller.h | L-Jay1999/Data_structure_touring_simulator | 0553338bc1c42732c3a8251f02d3c2ca6b159487 | [
"MIT"
] | null | null | null | #ifndef SRC_TRAVELLER
#define SRC_TRAVELLER
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdint>
#include <random>
#include <fstream>
#include <sstream>
#include <memory>
#include <initializer_list>
#include "user_type.h"
#include "path.h"
//#include "io.h"
#include "time_format.h"
#include "city_graph.h"
const int kMaxInt = INT32_MAX; // 0x7fffffff
const std::string save_path = "../data/traveller_data.txt";
const std::string name_path = "../data/namelist.txt";
const int SaveLines = 8;
#ifdef TEST_GET_PATH
extern int call_counter_time;
extern int call_counter_money;
extern int depth_counter;
#endif // TEST_GET_PATH
struct DFSLeastMoneyParWarp
{
int temp_price;
int path_price;
bool *isMeet;
int current;
int depth;
int min_price;
};
struct DFSLeastTimeParWarp
{
Time t;
City_id current;
bool *isMeet;
int depth;
std::vector<City_id> temp;
};
class Traveller // 旅行者
{
public:
Traveller() = default;
Traveller(std::string id) : id_(id){};
// 显示旅客id
void PrintID() const { std::cout << id_ << std::endl; }
const std::string &get_ID() const { return id_; }
void set_id(std::string name) { id_ = name; }
// 打印旅客路径
void ShowPath() const { touring_path_.Show(); }
const Path &get_path() const { return touring_path_; }
// 为旅客计划一条路径
Path SchedulePath(const CityGraph &graph, const std::vector<City_id> &plan, Strategy s, Time t = Time(), Time limit = Time());
Path SchedulePath(const CityGraph &graph, Strategy s, Time t = Time(), Time limit = Time())
{
return SchedulePath(graph, travelling_plan_, s, t, limit);
}
// 设置旅行路径
void set_path(Path &path)
{
touring_path_ = path;
position_pathnode_ = -1;
}
// 打印旅客计划
void PrintPlan() const
{
std::for_each(travelling_plan_.begin(), travelling_plan_.end(), [](City_id city) { std::cout << city << " "; });
std::cout << std::endl;
}
const std::vector<City_id> &get_plan() const { return travelling_plan_; }
void set_plan(const std::vector<City_id> &plan) { travelling_plan_ = plan; }
void set_plan(std::initializer_list<City_id> il) { travelling_plan_ = std::vector<City_id>(il); }
// 保存当前旅客信息
bool SaveData() const;
bool LoadData(int cnt, const CityGraph &graph);
void append_plan(City_id city) { travelling_plan_.push_back(city); }
int get_position() const { return position_pathnode_; }
int get_left_hour() const { return next_city_hour_left_; }
void InitState(const CityGraph &graph);
void UpdateState(const CityGraph &graph, Time now);
TravellerState get_state() const { return state_; }
void set_strategy(Strategy strategy) { strategy_ = strategy; }
bool set_strategy(int strategy)
{
switch (strategy)
{
case 0:
strategy_ = LEAST_MONEY;
break;
case 1:
strategy_ = LEAST_TIME;
break;
case 2:
strategy_ = LIMIT_TIME;
break;
default:
return false;
}
return true;
}
void set_init_time(const Time &t) { init_time_ = t; }
const Time &get_init_time() const { return init_time_; }
private:
std::string id_ = ""; // 旅客id
TravellerState state_ = STAY; // 旅客当前状态
Strategy strategy_ = LEAST_MONEY; // 旅行策略
std::vector<City_id> travelling_plan_; // 旅行计划 <起点>, <中继点>... , <终点>
Path touring_path_; // 旅行路径
int next_city_hour_left_ = 0; // 到下一个城市的剩余多少小时
int position_pathnode_ = -2; // 当前在第k个pathnode上, -2代表没有出行计划,-1代表有出行计划但没到出发时间
//std::vector<PathNode>::iterator next_city_; // 路径中的下一个城市
Time init_time_; // 最开始时的时间
Path GetPathLeastMoney(const CityGraph &graph, const std::vector<City_id> &plan);
Path GetPathLeastTime(const CityGraph &graph, const std::vector<City_id> &plan, Time now);
Path GetPathLTM(const CityGraph &graph, const std::vector<City_id> &plan, Time now, Time limit);
void DFSLeastTime(const CityGraph &graph, const std::vector<City_id> &plan, Path &path, Path &temp_path, DFSLeastTimeParWarp &par_warp);
void DFSLeastMoney(const std::vector<std::vector<int>> &price_matrix, std::vector<int> &path, std::vector<int> &temp_path, DFSLeastMoneyParWarp &par_warp);
void DFSLTM(const CityGraph &graph, const std::vector<City_id> &plan, Path &path, Path temp, int layer, int &least_money, const int limit);
};
void Traveller::DFSLeastMoney(const std::vector<std::vector<int>> &price_matrix, std::vector<int> &path, std::vector<int> &temp_path, DFSLeastMoneyParWarp &par_warp)
{
#ifdef TEST_GET_PATH
call_counter_money++;
#endif // TEST_GET_PATH
if (par_warp.current == price_matrix.size() - 1) // 到达终点时判断递归深度(路径长度)是否符合要求
{
if (par_warp.depth == price_matrix.size() - 1) // 路径长度是否符合要求
{
path = temp_path;
par_warp.path_price = par_warp.temp_price;
#ifdef TEST_GET_PATH
depth_counter++;
std::cout << par_warp.path_price << std::endl;
#endif // TEST_GET_PATH
}
else
return;
}
std::vector<int> path_save;
int current_save = par_warp.current;
for (int i = 0; i != price_matrix.size(); ++i)
{
if (i == par_warp.current || par_warp.isMeet[i])
continue;
else
{
par_warp.isMeet[i] = true;
path_save = temp_path;
par_warp.temp_price += price_matrix[par_warp.current][i];
if (par_warp.temp_price <= par_warp.path_price && (price_matrix.size() - 2 - par_warp.depth) * par_warp.min_price <= par_warp.path_price - par_warp.temp_price)
{
temp_path.push_back(i);
par_warp.depth++, par_warp.current = i; // 进入更深层的递归时保存当前的状态
DFSLeastMoney(price_matrix, path, temp_path, par_warp);
par_warp.depth--, par_warp.current = current_save; // 还原状态
}
par_warp.temp_price -= price_matrix[par_warp.current][i]; // 还原状态
par_warp.isMeet[i] = false;
temp_path = path_save;
}
}
}
void Traveller::DFSLeastTime(const CityGraph &graph, const std::vector<City_id> &plan, Path &path, Path &temp_path, DFSLeastTimeParWarp &par_warp)
{
#ifdef TEST_GET_PATH
call_counter_time++;
#endif // TEST_GET_PATH
if (par_warp.current == plan.size() - 1)
{
if (par_warp.depth == plan.size() - 1)
{
path = temp_path;
#ifdef TEST_GET_PATH
depth_counter++;
std::cout << path.GetTotalTime().to_hour() << std::endl;
#endif // TEST_GET_PATH
}
else
return;
}
int temp_current = par_warp.current;
Time temp_time;
Time time_save = par_warp.t;
Path path_save;
for (int i = 0; i < plan.size(); ++i)
{
if (i == par_warp.current || par_warp.isMeet[i])
continue;
else
{
par_warp.temp[0] = plan[par_warp.current], par_warp.temp[1] = plan[i];
temp_time = init_time_;
path_save = temp_path;
par_warp.isMeet[i] = true;
temp_path.Append(GetPathLeastTime(graph, par_warp.temp, par_warp.t));
temp_path.FixTotalTime(graph, init_time_);
if (temp_path.GetTotalTime().to_hour() < path.GetTotalTime().to_hour() && plan.size() - 1 - par_warp.depth < path.GetTotalTime().to_hour() - temp_path.GetTotalTime().to_hour())
{
par_warp.current = i, par_warp.depth++, par_warp.t = temp_time.add_time(temp_path.GetTotalTime());
DFSLeastTime(graph, plan, path, temp_path, par_warp);
par_warp.current = temp_current, par_warp.depth--, par_warp.t = time_save;
}
par_warp.isMeet[i] = false;
temp_path = path_save;
}
}
}
Path Traveller::SchedulePath(const CityGraph &graph, const std::vector<City_id> &plan, Strategy s, Time start_time, Time limit)
{
init_time_ = start_time;
strategy_ = s;
travelling_plan_ = plan;
if (plan.size() < 2)
throw plan.size();
if (s == LEAST_MONEY)
{
std::vector<std::vector<Path>> path_matrix;
std::vector<std::vector<int>> price_matrix;
std::vector<int> order_of_path, temp_path;
int min_price = kMaxInt;
Path res;
int path_price = GetPathLeastMoney(graph, plan).GetTotalPrice();
std::vector<City_id> temp_plan_shuffle = plan;
int temp_path_price;
std::random_device rd;
std::mt19937 g(rd());
for (int i = 0; i < 100; i++)
{
shuffle(temp_plan_shuffle.begin() + 1, temp_plan_shuffle.end() - 1, g);
temp_path_price = GetPathLeastMoney(graph, temp_plan_shuffle).GetTotalPrice();
if (temp_path_price < path_price)
path_price = temp_path_price;
}
size_t sz = plan.size();
bool *isMeet = new bool[sz]();
std::vector<City_id> temp_plan{0, 1};
for (int i = 0; i != sz; ++i)
{
isMeet[i] = false;
path_matrix.emplace_back();
for (int j = 0; j != sz; ++j)
{
if (i != j && i != sz - 1 && j)
{
temp_plan[0] = plan[i], temp_plan[1] = plan[j];
path_matrix[i].push_back(GetPathLeastMoney(graph, temp_plan));
}
else
{
path_matrix[i].emplace_back();
}
}
}
for (int i = 0; i != path_matrix.size(); ++i)
{
price_matrix.emplace_back();
for (int j = 0; j != path_matrix[i].size(); ++j)
{
price_matrix[i].push_back(path_matrix[i][j].GetTotalPrice());
if (price_matrix[i].back() && min_price > price_matrix[i].back())
min_price = price_matrix[i].back();
}
}
isMeet[0] = true;
DFSLeastMoneyParWarp par_warp = {0, path_price, isMeet, 0, 0, min_price};
order_of_path.push_back(0);
temp_path.push_back(0);
DFSLeastMoney(price_matrix, order_of_path, temp_path, par_warp);
for (int i = 1; i != order_of_path.size(); ++i)
res.Append(path_matrix[order_of_path[i - 1]][order_of_path[i]]);
res.FixTotalTime(graph, start_time);
delete isMeet;
return res;
// return GetPathLeastMoney(graph, plan);
}
else if (s == LEAST_TIME)
{
Path res = GetPathLeastTime(graph, plan, start_time);
res.FixTotalTime(graph, start_time);
int i = 0;
auto sz = plan.size();
if (plan.size() == 2)
return res;
else
{
bool *isMeet = new bool[sz]();
Path temp_path;
std::vector<City_id> buf;
for (i = 1; i != sz; ++i)
isMeet[i] = false;
std::vector<City_id> temp{0, 1};
DFSLeastTimeParWarp par_warp = {start_time, 0, isMeet, 0, temp};
DFSLeastTime(graph, plan, res, temp_path, par_warp);
delete isMeet;
}
return res;
}
else if (s == LIMIT_TIME)
{
Path a = GetPathLTM(graph, plan, start_time, limit);
if (a.GetLen() == 0)
{
std::cout << "未找到符合要求路线" << std::endl;
}
return a;
}
}
Path Traveller::GetPathLeastMoney(const CityGraph &graph, const std::vector<City_id> &plan)
{
City_id destination; // 终点
City_id origin; // 起点
Path path;
std::vector<int> find_min_cost;
// std::cout << plan[0] << plan[1] << std::endl;
for (int cnt = plan.size() - 1; cnt > 0; cnt--)
{
destination = plan[cnt];
origin = plan[cnt - 1];
int cost[kCityNum]; // 记录最小花费
int preway[kCityNum][2]; // preway[cityA][] = {CityB, transport_index_from_CityB_to_CityA}
bool is_count[kCityNum] = {false};
for (int j = 0; j < kCityNum; j++) //对数据进行初始化
{
if (j == origin)
continue;
for (int k = 0; k < graph.Getsize(origin, j); k++) // 将所有从origin到j的价格push到find_min_cost中
find_min_cost.push_back(graph.GetRoute(origin, j, k).price);
if (!find_min_cost.empty()) // 如果可以从origin到j
{
std::vector<int>::iterator min = min_element(find_min_cost.begin(), find_min_cost.end());
cost[j] = *min;
preway[j][0] = origin;
preway[j][1] = distance(find_min_cost.begin(), min);
find_min_cost.clear();
}
else // 不可达
{
cost[j] = kMaxInt;
preway[j][0] = -1;
preway[j][1] = -1;
}
}
cost[origin] = kMaxInt; // 去除origin
preway[origin][0] = -1;
preway[origin][1] = -1;
is_count[origin] = true;
while (!is_count[destination])
{
int temp = kMaxInt;
int city_temp = origin;
for (int i = 0; i < kCityNum; i++) //找到最小值
{
if (!is_count[i] && cost[i] < temp)
{
temp = cost[i];
city_temp = i;
}
}
is_count[city_temp] = true;
if (city_temp == destination)
break;
for (int j = 0; j < kCityNum; j++) //更新
{
if (is_count[j])
continue;
for (int k = 0; k < graph.Getsize(city_temp, j); k++)
find_min_cost.push_back(graph.GetRoute(city_temp, j, k).price);
if (!find_min_cost.empty())
{
std::vector<int>::iterator min = min_element(find_min_cost.begin(), find_min_cost.end());
int newcost = *min + cost[city_temp];
if (newcost < cost[j])
{
cost[j] = newcost;
preway[j][0] = city_temp;
preway[j][1] = distance(find_min_cost.begin(), min);
}
find_min_cost.clear();
}
}
}
for (int traceback = destination; traceback != origin; traceback = preway[traceback][0])
{
path.Append(graph, preway[traceback][0], traceback, preway[traceback][1]);
}
}
//path.Reverse();
//path.Show();
return path;
}
Path Traveller::GetPathLeastTime(const CityGraph &graph, const std::vector<City_id> &plan, Time now)
{
City_id destination; // 终点
City_id origin; // 起点
Path path;
std::vector<int> find_min_cost;
Time temp_now;
std::vector<int>::iterator min;
for (int cnt = plan.size() - 1; cnt > 0; cnt--)
{
destination = plan[cnt];
origin = plan[cnt - 1];
int cost[kCityNum]; // 记录最小花费
int preway[kCityNum][2]; // preway[cityA][] = {CityB, transport_index_from_CityB_to_CityA}
// Time pretime[kCityNum];
bool is_count[kCityNum] = {false};
for (int j = 0; j < kCityNum; j++) //对数据进行初始化
{
if (j == origin)
continue;
for (int k = 0; k < graph.Getsize(origin, j); k++) // 将所有从origin到j的价格push到find_min_cost中
{ //*****和LM的区别*****
const Route &route = graph.GetRoute(origin, j, k);
temp_now.set_hour(now.GetHour());
int wait_hour = route.start_time.hour_diff(temp_now); // 计算从当前时间开始需要等待的时间
if (wait_hour < 0) // 如果发车时间在now之前,想要搭乘这辆车就必须等候到其发车
wait_hour += 24;
int route_hour = route.end_time.hour_diff(route.start_time); // 路途上的时间
find_min_cost.push_back(wait_hour + route_hour);
}
if (!find_min_cost.empty()) // 如果可以从origin到j
{
min = min_element(find_min_cost.begin(), find_min_cost.end());
cost[j] = *min;
preway[j][0] = origin;
preway[j][1] = distance(find_min_cost.begin(), min);
// pretime[j] = now;
find_min_cost.clear();
}
else // 不可达
{
cost[j] = kMaxInt;
preway[j][0] = -1;
preway[j][1] = -1;
}
}
cost[origin] = kMaxInt; // 去除origin
preway[origin][0] = -1;
preway[origin][1] = -1;
is_count[origin] = true;
while (!is_count[destination])
{
int temp = kMaxInt;
int city_temp = origin;
for (int i = 0; i < kCityNum; i++) //找到最小值
{
if (!is_count[i] && cost[i] < temp)
{
temp = cost[i];
city_temp = i;
}
}
is_count[city_temp] = true;
if (city_temp == destination)
break;
//*****和LM的区别*****
// Route temp_route = graph.GetRoute(preway[city_temp][0], city_temp, preway[city_temp][1]);
// now.add_time(cost[city_temp]); // 此时的时间为之前的时间加上从前一个城市到city_temp的时间(包括等候时间)
now = graph.GetRoute(preway[city_temp][0], city_temp, preway[city_temp][1]).end_time;
temp_now.set_hour(now.GetHour()); // 只看到达时间,不看天数
// now = graph.GetRoute(preway[city_temp][0], city_temp, preway[city_temp][1]).end_time;
for (int j = 0; j < kCityNum; j++) //更新
{
if (is_count[j])
continue;
for (int k = 0; k < graph.Getsize(city_temp, j); k++)
{ //*****和LM的区别*****
const Route &route = graph.GetRoute(city_temp, j, k);
int wait_hour = route.start_time.hour_diff(temp_now); // 计算从当前时间开始需要等待的时间
if (wait_hour < 0) // 如果发车时间在now之前,想要搭乘这辆车就必须等候到其发车
wait_hour += 24;
int route_hour = route.end_time.hour_diff(route.start_time); // 路途上的时间
find_min_cost.push_back(wait_hour + route_hour);
}
if (!find_min_cost.empty())
{
min = min_element(find_min_cost.begin(), find_min_cost.end());
int newcost = *min + cost[city_temp];
if (newcost < cost[j])
{
cost[j] = newcost;
preway[j][0] = city_temp;
preway[j][1] = distance(find_min_cost.begin(), min);
// pretime[j] = now;
}
find_min_cost.clear();
}
}
}
for (int traceback = destination; traceback != origin; traceback = preway[traceback][0])
{
path.Append(graph, preway[traceback][0], traceback, preway[traceback][1]); //pretime[traceback]);
}
}
//path.Reverse();
//path.Show();
return path;
}
Path Traveller::GetPathLTM(const CityGraph &graph, const std::vector<City_id> &plan, Time start_time, Time limit_time)
{
int limit = limit_time.hour_diff(start_time);
Path path;
int least_money = kMaxInt;
Path temp;
auto temp_plan_shuffle = plan;
DFSLTM(graph, plan, path, temp, 0, least_money, limit);
std::random_device rd;
std::mt19937 g(rd());
if (plan.size() > 3)
for (int i = 0; i < 5; i++)
{
shuffle(temp_plan_shuffle.begin() + 1, temp_plan_shuffle.end() - 1, g);
while (std::equal(plan.begin(), plan.end(), temp_plan_shuffle.begin()))
shuffle(temp_plan_shuffle.begin() + 1, temp_plan_shuffle.end() - 1, g);
DFSLTM(graph, temp_plan_shuffle, path, temp, 0, least_money, limit);
}
return path;
}
void Traveller::DFSLTM(const CityGraph &graph, const std::vector<City_id> &plan, Path &path, Path temp, int layer, int &least_money, const int limit)
{
if (layer == plan.size() - 1)
{
path = temp;
least_money = path.GetTotalPrice();
return;
}
int i = plan.at(layer);
int j = plan.at(layer + 1);
for (int k = 0; k < graph.Getsize(i, j); k++)
{
temp.Append(graph, i, j, k, 1);
temp.FixTotalTime(graph, init_time_);
if (temp.GetTotalPrice() < least_money && temp.GetTotalTime().GetLength() <= limit && temp.GetTotalTime().GetLength() + plan.size() - layer - 1 <= limit)
DFSLTM(graph, plan, path, temp, layer + 1, least_money, limit);
temp.Remove(graph);
}
}
bool Traveller::SaveData() const
{
std::vector<std::string> lines;
std::string temp;
int start_index = 0;
std::ofstream create_name_flie(name_path, std::ofstream::app); // 防止文件不存在导致的打开失败
std::ofstream create_file(save_path, std::ofstream::app); // 防止文件不存在导致的打开失败
std::ifstream name_fis(name_path);
if (name_fis)
{
while (getline(name_fis, temp))
if (temp == id_)
break;
else
start_index++;
}
std::ifstream fis(save_path);
if (fis)
{
while (getline(fis, temp))
lines.push_back(temp);
start_index *= SaveLines;
if (start_index < lines.size())
{
int i = start_index + 1;
lines[i++] = std::to_string(state_);
lines[i++] = std::to_string(strategy_);
temp = "";
for (int j = 0; j < travelling_plan_.size(); j++)
temp += std::to_string(travelling_plan_.at(j)) + " ";
lines[i++] = temp;
temp = "";
for (auto j = touring_path_.cbegin(); j != touring_path_.cend(); j++)
temp += std::to_string((*j).former_city) + " " + std::to_string((*j).current_city) + " " + std::to_string((*j).kth_way) + " ";
lines[i++] = temp;
lines[i++] = std::to_string(next_city_hour_left_);
lines[i++] = std::to_string(position_pathnode_);
lines[i++] = std::to_string(init_time_.GetHour());
}
else
{
lines.push_back(id_);
lines.push_back(std::to_string(state_));
lines.push_back(std::to_string(strategy_));
temp = "";
for (int j = 0; j < travelling_plan_.size(); j++)
temp += std::to_string(travelling_plan_.at(j)) + " ";
lines.push_back(temp);
temp = "";
for (auto j = touring_path_.cbegin(); j != touring_path_.cend(); j++)
temp += std::to_string((*j).former_city) + " " + std::to_string((*j).current_city) + " " + std::to_string((*j).kth_way) + " ";
lines.push_back(temp);
lines.push_back(std::to_string(next_city_hour_left_));
lines.push_back(std::to_string(position_pathnode_));
lines.push_back(std::to_string(init_time_.GetHour()));
}
}
else
return false;
std::ofstream fos(save_path);
if (fos)
std::for_each(lines.begin(), lines.end(), [&fos](const std::string &line) { fos << line << std::endl; });
else
return false;
return true;
}
bool Traveller::LoadData(int cnt, const CityGraph &graph)
{
if (cnt == -1)
return false;
int state_temp;
int strategy_temp;
std::string temp;
std::ifstream in_stream(save_path);
if (in_stream.is_open())
{
for (int i = 0; i < cnt * SaveLines; i++)
getline(in_stream, temp); // 找位置
in_stream >> id_; // 第一行
in_stream >> state_temp; // 第二行
in_stream >> strategy_temp; // 第三行
if (state_temp == 0)
state_ = STAY;
else if (state_temp == 1)
state_ = OFF;
if (strategy_temp == 0)
strategy_ = LEAST_MONEY;
else if (strategy_temp == 1)
strategy_ = LEAST_TIME;
else if (strategy_temp == 2)
strategy_ = LIMIT_TIME;
getline(in_stream, temp); // 结束前一行
getline(in_stream, temp); // 第四行
std::istringstream sis(temp);
int plantemp;
while (sis >> plantemp)
{
// std::cout << plantemp << " "; ///////////
travelling_plan_.push_back(plantemp);
}
// std::cout << std::endl;
getline(in_stream, temp); // 第五行
sis.str(temp);
sis.clear();
City_id former_city, current_city, k;
while (sis >> former_city)
{
sis >> current_city;
sis >> k;
//std::cout << former_city << " " << current_city << " " << k << std::endl; ////////////
touring_path_.Append(graph, former_city, current_city, k, 1);
}
in_stream >> next_city_hour_left_;
//std::cout << next_city_hour_left_ << std::endl;///////////
in_stream >> position_pathnode_;
//std::cout << position_pathnode_ << std::endl;///////////
int hour;
in_stream >> hour;
init_time_.set_hour(hour);
touring_path_.FixTotalTime(graph, init_time_);
return true;
}
return false;
}
inline void Traveller::UpdateState(const CityGraph &graph, Time now)
{
if (state_ == OFF)
{
if (next_city_hour_left_ == 1)
{
if (position_pathnode_ == touring_path_.GetLen() - 1)
{
state_ = STAY;
position_pathnode_ = -1;
return;
}
else
{
position_pathnode_++;
PathNode node = touring_path_.GetNode(position_pathnode_);
Route route = graph.GetRoute(node.former_city, node.current_city, node.kth_way);
PathNode nodebefore = touring_path_.GetNode(position_pathnode_ - 1);
Route preroute = graph.GetRoute(nodebefore.former_city, nodebefore.current_city, nodebefore.kth_way);
int diff_hour = route.start_time.hour_diff(Time(1, preroute.end_time.GetHour()));
if (diff_hour < 0)
diff_hour += 24;
if (!diff_hour)
{
next_city_hour_left_ = route.end_time.hour_diff(route.start_time);
}
else
{
state_ = STAY;
next_city_hour_left_ = diff_hour;
}
}
}
else
next_city_hour_left_--;
}
else
{
if (position_pathnode_ != -1)
{
if (next_city_hour_left_ == 1)
{
int i = touring_path_.GetNode(position_pathnode_).former_city;
int j = touring_path_.GetNode(position_pathnode_).current_city;
int k = touring_path_.GetNode(position_pathnode_).kth_way;
state_ = OFF;
Route route = graph.GetRoute(i, j, k);
next_city_hour_left_ = route.end_time.hour_diff(route.start_time);
}
else
next_city_hour_left_--;
}
}
}
inline void Traveller::InitState(const CityGraph &graph)
{
if (position_pathnode_ == -2)
return;
auto path_begin = touring_path_.cbegin();
Route route = graph.GetRoute((*path_begin).former_city, (*path_begin).current_city, (*path_begin).kth_way);
int left_hour = route.start_time.hour_diff(init_time_);
position_pathnode_ = 0;
if (left_hour < 0)
left_hour += 24;
if (left_hour)
{
state_ = STAY;
next_city_hour_left_ = left_hour;
}
else
{
state_ = OFF;
next_city_hour_left_ = route.end_time.hour_diff(route.start_time);
}
}
#endif // SRC_TRAVELLER | 30.162031 | 182 | 0.606679 | [
"vector"
] |
f18fa11241933a5e22c90bdcb0545b1e66a1f382 | 10,302 | c | C | wireshark-2.0.13/ui/traffic_table_ui.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/ui/traffic_table_ui.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | wireshark-2.0.13/ui/traffic_table_ui.c | mahrukhfida/mi | 7187765aa225e71983969ef5285771ac77c8309a | [
"Apache-2.0"
] | null | null | null | /* traffic_table_ui.c
* Copied from gtk/conversations_table.c 2003 Ronnie Sahlberg
* Helper routines common to all conversations taps.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <glib.h>
#include "traffic_table_ui.h"
#include <wsutil/utf8_entities.h>
#ifdef HAVE_GEOIP
#include <GeoIP.h>
#include "epan/address.h"
#include "epan/addr_resolv.h"
#include "epan/geoip_db.h"
#include "epan/strutil.h"
#include "wsutil/pint.h"
#include "wsutil/str_util.h"
#include "epan/packet_info.h"
#include "epan/conversation_table.h"
#include <errno.h>
#include <stdio.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "wsutil/filesystem.h"
#include "wsutil/file_util.h"
#include "wsutil/tempfile.h"
#endif
const char *conv_column_titles[CONV_NUM_COLUMNS] = {
"Address A",
"Port A",
"Address B",
"Port B",
"Packets",
"Bytes",
"Packets A " UTF8_RIGHTWARDS_ARROW " B",
"Bytes A " UTF8_RIGHTWARDS_ARROW " B",
"Packets B " UTF8_RIGHTWARDS_ARROW " A",
"Bytes B " UTF8_RIGHTWARDS_ARROW " A",
"Rel Start",
"Duration",
"Bits/s A " UTF8_RIGHTWARDS_ARROW " B",
"Bits/s B " UTF8_RIGHTWARDS_ARROW " A"
};
const char *conv_conn_a_title = "Connection A";
const char *conv_conn_b_title = "Connection B";
const char *endp_column_titles[ENDP_NUM_COLUMNS] = {
"Address",
"Port",
"Packets",
"Bytes",
"Tx Packets",
"Tx Bytes",
"Rx Packets",
"Rx Bytes"
};
const char *endp_conn_title = "Connection";
#ifdef HAVE_GEOIP
#define MAX_TPL_LINE_LEN 4096
gchar *
create_endpoint_geoip_map(const GArray *endp_array, gchar **err_str) {
char *tpl_filename, *tpl_line;
FILE *tpl_file, *out_file;
char *map_path;
gchar *map_filename = NULL;
guint i;
GString *tpl_entry;
gchar *esc_entry;
int db_lon, db_lat, db_country4, db_country6, db_city4, db_city6, db_asn4, db_asn6;
guint cur_db;
const char *map_endpoint_opener = "{\n";
db_lon = db_lat = db_country4 = db_country6 = db_city4 = db_city6 = db_asn4 = db_asn6 = -1;
/* Create a location map HTML file from a template */
/* XXX - add error handling */
tpl_filename = get_datafile_path("ipmap.html");
tpl_file = ws_fopen(tpl_filename, "r");
if(tpl_file == NULL) {
if (err_str) {
GString *err_descr = g_string_new("");
g_string_printf(err_descr, file_open_error_message(errno, FALSE), tpl_filename);
*err_str = g_string_free(err_descr, FALSE);
}
g_free(tpl_filename);
return NULL;
}
g_free(tpl_filename);
#if 1
/* We should probably create a file with a temporary name and a .html extension instead */
if (! create_tempdir(&map_path, "Wireshark IP Map ")) {
if (err_str) {
GString *err_descr = g_string_new("");
g_string_printf(err_descr, "Could not create temporary directory\n%s",
map_path);
*err_str = g_string_free(err_descr, FALSE);
}
fclose(tpl_file);
return NULL;
}
#else
/* Debugging only */
map_path = "/tmp";
#endif
map_filename = g_strdup_printf("%s%cipmap.html", map_path, G_DIR_SEPARATOR);
out_file = ws_fopen(map_filename, "w");
if(out_file == NULL) {
if (err_str) {
GString *err_descr = g_string_new("");
g_string_printf(err_descr, file_open_error_message(errno, FALSE), map_filename);
*err_str = g_string_free(err_descr, FALSE);
}
g_free(map_filename);
fclose(tpl_file);
return NULL;
}
tpl_line = (char *)g_malloc(MAX_TPL_LINE_LEN);
while (fgets(tpl_line, MAX_TPL_LINE_LEN, tpl_file) != NULL) {
fputs(tpl_line, out_file);
/* MUST match ipmap.html */
if (strstr(tpl_line, "// Start endpoint list")) {
break;
}
}
for (cur_db = 0; cur_db < geoip_db_num_dbs(); cur_db++) {
switch (geoip_db_type(cur_db)) {
case WS_LON_FAKE_EDITION:
db_lon = cur_db;
break;
case WS_LAT_FAKE_EDITION:
db_lat = cur_db;
break;
case GEOIP_COUNTRY_EDITION:
db_country4 = cur_db;
break;
case GEOIP_COUNTRY_EDITION_V6:
db_country6 = cur_db;
break;
case GEOIP_CITY_EDITION_REV0:
case GEOIP_CITY_EDITION_REV1:
db_city4 = cur_db;
break;
case GEOIP_CITY_EDITION_REV0_V6:
case GEOIP_CITY_EDITION_REV1_V6:
db_city6 = cur_db;
break;
}
}
if(db_lon < 0 || db_lat < 0) {
if (err_str) {
*err_str = g_strdup("Unable to open GeoIP database");
}
/* We can't write the map file, so close it and get rid of it */
fclose(out_file);
ws_unlink(map_filename);
g_free(map_filename);
fclose(tpl_file);
return NULL;
}
/* Fill in our map data */
tpl_entry = g_string_new("");
for (i = 0; i < endp_array->len; i++) {
char *lat = NULL, *lon = NULL, *country = NULL, *city = NULL, *asn = NULL;
hostlist_talker_t *endp_item = &g_array_index(endp_array, hostlist_talker_t, i);
if (endp_item->myaddress.type == AT_IPv4) {
lon = geoip_db_lookup_ipv4(db_lon, pntoh32(endp_item->myaddress.data), NULL);
lat = geoip_db_lookup_ipv4(db_lat, pntoh32(endp_item->myaddress.data), NULL);
country = geoip_db_lookup_ipv4(db_country4, pntoh32(endp_item->myaddress.data), "-");
city = geoip_db_lookup_ipv4(db_city4, pntoh32(endp_item->myaddress.data), "-");
asn = geoip_db_lookup_ipv4(db_asn4, pntoh32(endp_item->myaddress.data), "-");
} else if (endp_item->myaddress.type == AT_IPv6) {
const struct e_in6_addr *addr = (const struct e_in6_addr *) endp_item->myaddress.data;
lon = geoip_db_lookup_ipv6(db_lon, *addr, NULL);
lat = geoip_db_lookup_ipv6(db_lat, *addr, NULL);
country = geoip_db_lookup_ipv6(db_country6, *addr, "-");
city = geoip_db_lookup_ipv6(db_city6, *addr, "-");
asn = geoip_db_lookup_ipv6(db_asn6, *addr, "-");
} else {
continue;
}
/*
{
'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-122.583889, 37.898889] },
'properties': { 'title': 'host.example.com', 'description': 'AS: AS12345 Ewok Holdings, Inc.<br/>Country: US<br/>City: Muir Woods, CA<br/>Packets: 6<br/>Bytes: 980' }
},
*/
if (lon && lat) {
char* addr_str;
g_string_printf(tpl_entry, "%s", map_endpoint_opener);
/* Longitude + latitude */
g_string_append_printf(tpl_entry, " 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [%s, %s] },\n", lon, lat);
/* Address */
addr_str = (char*)address_to_display(NULL, &endp_item->myaddress);
g_string_append_printf(tpl_entry, " 'properties': { 'title': '%s', ", addr_str);
wmem_free(NULL, addr_str);
/* Description */
/* City */
esc_entry = string_replace(city, "'", "'");
g_string_append_printf(tpl_entry, "'description': '<div class=\"geoip_property\">City: %s</div>", esc_entry);
g_free(esc_entry);
/* Country */
esc_entry = string_replace(country, "'", "'");
g_string_append_printf(tpl_entry, "<div class=\"geoip_property\">Country: %s</div>", esc_entry);
g_free(esc_entry);
/* Packets */
esc_entry = format_size(endp_item->tx_frames + endp_item->rx_frames,
(format_size_flags_e)(format_size_unit_none|format_size_prefix_si));
g_string_append_printf(tpl_entry, "<div class=\"geoip_property\">Packets: %s</div>", esc_entry);
g_free(esc_entry);
/* Bytes */
esc_entry = format_size(endp_item->tx_bytes + endp_item->rx_bytes,
(format_size_flags_e)(format_size_unit_none|format_size_prefix_si));
g_string_append_printf(tpl_entry, "<div class=\"geoip_property\">Bytes: %s</div>", esc_entry);
g_free(esc_entry);
/* ASN */
esc_entry = string_replace(asn, "'", "'");
g_string_append_printf(tpl_entry, "<div class=\"geoip_property\">AS Number: %s</div>", esc_entry);
g_free(esc_entry);
/* XXX - We could add specific icons, e.g. depending on the amount of packets or bytes */
g_string_append(tpl_entry, "' }\n");
g_string_append(tpl_entry, "}");
fputs(tpl_entry->str, out_file);
map_endpoint_opener = ",\n{\n";
}
wmem_free(NULL, lat);
wmem_free(NULL, lon);
wmem_free(NULL, country);
wmem_free(NULL, city);
wmem_free(NULL, asn);
/* XXX Display an error if we we have no entries */
}
while (fgets(tpl_line, MAX_TPL_LINE_LEN, tpl_file) != NULL) {
fputs(tpl_line, out_file);
}
g_free(tpl_line);
fclose(tpl_file);
fclose(out_file);
return map_filename;
}
#endif
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| 33.232258 | 176 | 0.610949 | [
"geometry"
] |
f195791d126a88b5c4e9eddabdb9fa8ab30062f6 | 3,376 | h | C | apps/AMR/heat.h | lightsighter/LegionOrigins | 0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7 | [
"Apache-2.0"
] | 2 | 2021-11-10T06:29:39.000Z | 2021-11-14T20:56:13.000Z | apps/AMR/heat.h | lightsighter/LegionOrigins | 0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7 | [
"Apache-2.0"
] | null | null | null | apps/AMR/heat.h | lightsighter/LegionOrigins | 0180bb3a8ee6efd0d2efdb743f75d3fba86f18f7 | [
"Apache-2.0"
] | null | null | null |
#ifndef __HEAT_SIM__
#define __HEAT_SIM__
#include "legion.h"
#define SIMULATION_DIM 2 // Number of dimensions in the simulation
#define POW2(dim) ((dim==1) ? 2 : (dim==2) ? 4 : 8)
#define COARSENING 16
using namespace RegionRuntime::HighLevel;
enum {
REGION_MAIN,
INIT_TASK,
INTERP_BOUNDARY,
CALC_FLUXES,
ADVANCE,
RESTRICT,
INTERP_BOUNDARY_NOP,
CALC_FLUXES_NOP,
ADVANCE_NOP,
RESTRICT_NOP,
};
enum {
REDUCE_ID = 1,
};
enum PointerLocation {
PVT = 0,
SHR = 1,
GHOST = 2,
BOUNDARY = 3,
};
struct Flux;
struct Cell {
public:
#ifdef COARSENING
float temperature[COARSENING][COARSENING]; // Current value of the solution at this cell
#else
float temperature;
#endif
#if SIMULATION_DIM==2
float position[2]; // (x,y)
ptr_t<Flux> inx,outx,iny,outy;
#else
float position[3]; // (x,y,z)
ptr_t<Flux> inx,outx,iny,outy,inz,outz;
#endif
// Where is this cell located (can only be one of pvt, shared, or boundary)
PointerLocation loc;
// If a cell is refined keep track of its pointers to
// the cells in the level below that are the aggregate. Similarly
// if it is a boundary cell remember the cells above it that are
// used to interpolate its value
unsigned num_below;
#if SIMULATION_DIM==2
// 0 = lower-left
// 1 = upper-left
// 2 = lower-right
// 3 = upper-right
// see fill_temps_and_center
ptr_t<Cell> across_cells[4];
unsigned across_index_loc[4];
#else
ptr_t<Cell> across_cells[8];
unsigned across_index_loc[8];
#endif
};
struct Flux {
public:
#ifdef COARSENING
float flux[COARSENING];
#else
float flux;
#endif
PointerLocation locations[2];
ptr_t<Cell> cell_ptrs[2];
};
struct Level {
public:
// The next three fields have to be first so
// they can be read out and passed as arguments to task calls
// The size of a face/edge for a given level
float dx;
// The size of the timestep
float dt;
// Diffusion coefficient
float coeff;
// The level of this level
int level;
// Divisions
int divisions;
// Number of fluxes in each grid at this level
int num_fluxes;
// Number of private cells
int num_private;
int num_shared;
int shared_offset;
// Offsets for computing global cell locations (same in all dimensions)
float offset;
// The Index Space for launching tasks
std::vector<Range> index_space;
// The size of a piece in one dimension
float px;
unsigned cells_per_piece_side;
unsigned pieces_per_dim;
unsigned num_pieces;
// Top level regions
LogicalRegion all_cells;
LogicalRegion all_fluxes;
// Aggregations of cells
LogicalRegion all_private;
LogicalRegion all_shared;
LogicalRegion all_boundary;
// Partitions for flux calculation and advance
Partition pvt_cells, shr_cells, ghost_cells, boundary_cells;
Partition pvt_fluxes;
// Partition of pvt, shared, and ghost that are sources for interpolation
// for the level below
Partition pvt_interp, shr_interp, ghost_interp;
std::vector<std::vector<RegionRequirement> > interp_boundary_regions;
std::vector<MappingTagID> interp_tags;
std::vector<RegionRequirement> calc_fluxes_regions;
std::vector<RegionRequirement> adv_time_step_regions;
std::vector<std::vector<RegionRequirement> > restrict_coarse_regions;
std::vector<MappingTagID> restrict_tags;
std::vector<TaskArgument> restrict_args;
};
#endif // __HEAT_SIM__
| 23.123288 | 91 | 0.723045 | [
"vector"
] |
f1a15efc1ca872c087a1f806ea131aeaecf5d116 | 42,477 | h | C | target_acquisition/mov/ImageParamsConfig.h | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | target_acquisition/mov/ImageParamsConfig.h | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | target_acquisition/mov/ImageParamsConfig.h | DeepBlue14/usar_system | a1b3d78a65f064be897f75dfc5f4dad4214f9d74 | [
"MIT"
] | null | null | null | //#line 2 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
// *********************************************************
//
// File autogenerated for the target_aquisition package
// by the dynamic_reconfigure package.
// Please do not edit.
//
// ********************************************************/
#ifndef __target_aquisition__IMAGEPARAMSCONFIG_H__
#define __target_aquisition__IMAGEPARAMSCONFIG_H__
#include <dynamic_reconfigure/config_tools.h>
#include <limits>
#include <ros/node_handle.h>
#include <dynamic_reconfigure/ConfigDescription.h>
#include <dynamic_reconfigure/ParamDescription.h>
#include <dynamic_reconfigure/Group.h>
#include <dynamic_reconfigure/config_init_mutex.h>
#include <boost/any.hpp>
namespace target_aquisition
{
class ImageParamsConfigStatics;
class ImageParamsConfig
{
public:
class AbstractParamDescription : public dynamic_reconfigure::ParamDescription
{
public:
AbstractParamDescription(std::string n, std::string t, uint32_t l,
std::string d, std::string e)
{
name = n;
type = t;
level = l;
description = d;
edit_method = e;
}
virtual void clamp(ImageParamsConfig &config, const ImageParamsConfig &max, const ImageParamsConfig &min) const = 0;
virtual void calcLevel(uint32_t &level, const ImageParamsConfig &config1, const ImageParamsConfig &config2) const = 0;
virtual void fromServer(const ros::NodeHandle &nh, ImageParamsConfig &config) const = 0;
virtual void toServer(const ros::NodeHandle &nh, const ImageParamsConfig &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, ImageParamsConfig &config) const = 0;
virtual void toMessage(dynamic_reconfigure::Config &msg, const ImageParamsConfig &config) const = 0;
virtual void getValue(const ImageParamsConfig &config, boost::any &val) const = 0;
};
typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr;
typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr;
template <class T>
class ParamDescription : public AbstractParamDescription
{
public:
ParamDescription(std::string name, std::string type, uint32_t level,
std::string description, std::string edit_method, T ImageParamsConfig::* f) :
AbstractParamDescription(name, type, level, description, edit_method),
field(f)
{}
T (ImageParamsConfig::* field);
virtual void clamp(ImageParamsConfig &config, const ImageParamsConfig &max, const ImageParamsConfig &min) const
{
if (config.*field > max.*field)
config.*field = max.*field;
if (config.*field < min.*field)
config.*field = min.*field;
}
virtual void calcLevel(uint32_t &comb_level, const ImageParamsConfig &config1, const ImageParamsConfig &config2) const
{
if (config1.*field != config2.*field)
comb_level |= level;
}
virtual void fromServer(const ros::NodeHandle &nh, ImageParamsConfig &config) const
{
nh.getParam(name, config.*field);
}
virtual void toServer(const ros::NodeHandle &nh, const ImageParamsConfig &config) const
{
nh.setParam(name, config.*field);
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, ImageParamsConfig &config) const
{
return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field);
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const ImageParamsConfig &config) const
{
dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field);
}
virtual void getValue(const ImageParamsConfig &config, boost::any &val) const
{
val = config.*field;
}
};
class AbstractGroupDescription : public dynamic_reconfigure::Group
{
public:
AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s)
{
name = n;
type = t;
parent = p;
state = s;
id = i;
}
std::vector<AbstractParamDescriptionConstPtr> abstract_parameters;
bool state;
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0;
virtual void updateParams(boost::any &cfg, ImageParamsConfig &top) const= 0;
virtual void setInitialState(boost::any &cfg) const = 0;
void convertParams()
{
for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i)
{
parameters.push_back(dynamic_reconfigure::ParamDescription(**i));
}
}
};
typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr;
typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr;
template<class T, class PT>
class GroupDescription : public AbstractGroupDescription
{
public:
GroupDescription(std::string name, std::string type, int parent, int id, bool s, T PT::* f) : AbstractGroupDescription(name, type, parent, id, s), field(f)
{
}
GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups)
{
parameters = g.parameters;
abstract_parameters = g.abstract_parameters;
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field))
return false;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
if(!(*i)->fromMessage(msg, n))
return false;
}
return true;
}
virtual void setInitialState(boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* group = &((*config).*field);
group->state = state;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = boost::any(&((*config).*field));
(*i)->setInitialState(n);
}
}
virtual void updateParams(boost::any &cfg, ImageParamsConfig &top) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* f = &((*config).*field);
f->setParams(top, abstract_parameters);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
(*i)->updateParams(n, top);
}
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const
{
const PT config = boost::any_cast<PT>(cfg);
dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
(*i)->toMessage(msg, config.*field);
}
}
T (PT::* field);
std::vector<ImageParamsConfig::AbstractGroupDescriptionConstPtr> groups;
};
class DEFAULT
{
public:
DEFAULT()
{
state = true;
name = "Default";
}
void setParams(ImageParamsConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params)
{
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator _i = params.begin(); _i != params.end(); ++_i)
{
boost::any val;
(*_i)->getValue(config, val);
if("Activate"==(*_i)->name){Activate = boost::any_cast<bool>(val);}
if("Red_Min"==(*_i)->name){Red_Min = boost::any_cast<int>(val);}
if("Green_Min"==(*_i)->name){Green_Min = boost::any_cast<int>(val);}
if("Blue_Min"==(*_i)->name){Blue_Min = boost::any_cast<int>(val);}
if("Red_Max"==(*_i)->name){Red_Max = boost::any_cast<int>(val);}
if("Green_Max"==(*_i)->name){Green_Max = boost::any_cast<int>(val);}
if("Blue_Max"==(*_i)->name){Blue_Max = boost::any_cast<int>(val);}
if("Motion_Sensitivity"==(*_i)->name){Motion_Sensitivity = boost::any_cast<int>(val);}
if("Motion_Blur"==(*_i)->name){Motion_Blur = boost::any_cast<int>(val);}
if("Shape_Sensitivity"==(*_i)->name){Shape_Sensitivity = boost::any_cast<int>(val);}
if("Shape_Blur"==(*_i)->name){Shape_Blur = boost::any_cast<int>(val);}
if("H_Min"==(*_i)->name){H_Min = boost::any_cast<int>(val);}
if("S_Min"==(*_i)->name){S_Min = boost::any_cast<int>(val);}
if("V_Min"==(*_i)->name){V_Min = boost::any_cast<int>(val);}
if("H_Max"==(*_i)->name){H_Max = boost::any_cast<int>(val);}
if("S_Max"==(*_i)->name){S_Max = boost::any_cast<int>(val);}
if("V_Max"==(*_i)->name){V_Max = boost::any_cast<int>(val);}
if("Sensitivity"==(*_i)->name){Sensitivity = boost::any_cast<int>(val);}
if("Blur"==(*_i)->name){Blur = boost::any_cast<int>(val);}
}
}
bool Activate;
int Red_Min;
int Green_Min;
int Blue_Min;
int Red_Max;
int Green_Max;
int Blue_Max;
int Motion_Sensitivity;
int Motion_Blur;
int Shape_Sensitivity;
int Shape_Blur;
int H_Min;
int S_Min;
int V_Min;
int H_Max;
int S_Max;
int V_Max;
int Sensitivity;
int Blur;
bool state;
std::string name;
}groups;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
bool Activate;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Red_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Green_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Blue_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Red_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Green_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Blue_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Motion_Sensitivity;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Motion_Blur;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Shape_Sensitivity;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Shape_Blur;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int H_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int S_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int V_Min;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int H_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int S_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int V_Max;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Sensitivity;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int Blur;
//#line 218 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
bool __fromMessage__(dynamic_reconfigure::Config &msg)
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
int count = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
if ((*i)->fromMessage(msg, *this))
count++;
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++)
{
if ((*i)->id == 0)
{
boost::any n = boost::any(this);
(*i)->updateParams(n, *this);
(*i)->fromMessage(msg, n);
}
}
if (count != dynamic_reconfigure::ConfigTools::size(msg))
{
ROS_ERROR("ImageParamsConfig::__fromMessage__ called with an unexpected parameter.");
ROS_ERROR("Booleans:");
for (unsigned int i = 0; i < msg.bools.size(); i++)
ROS_ERROR(" %s", msg.bools[i].name.c_str());
ROS_ERROR("Integers:");
for (unsigned int i = 0; i < msg.ints.size(); i++)
ROS_ERROR(" %s", msg.ints[i].name.c_str());
ROS_ERROR("Doubles:");
for (unsigned int i = 0; i < msg.doubles.size(); i++)
ROS_ERROR(" %s", msg.doubles[i].name.c_str());
ROS_ERROR("Strings:");
for (unsigned int i = 0; i < msg.strs.size(); i++)
ROS_ERROR(" %s", msg.strs[i].name.c_str());
// @todo Check that there are no duplicates. Make this error more
// explicit.
return false;
}
return true;
}
// This version of __toMessage__ is used during initialization of
// statics when __getParamDescriptions__ can't be called yet.
void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const
{
dynamic_reconfigure::ConfigTools::clear(msg);
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toMessage(msg, *this);
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
if((*i)->id == 0)
{
(*i)->toMessage(msg, *this);
}
}
}
void __toMessage__(dynamic_reconfigure::Config &msg) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
__toMessage__(msg, __param_descriptions__, __group_descriptions__);
}
void __toServer__(const ros::NodeHandle &nh) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toServer(nh, *this);
}
void __fromServer__(const ros::NodeHandle &nh)
{
static bool setup=false;
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->fromServer(nh, *this);
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){
if (!setup && (*i)->id == 0) {
setup = true;
boost::any n = boost::any(this);
(*i)->setInitialState(n);
}
}
}
void __clamp__()
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const ImageParamsConfig &__max__ = __getMax__();
const ImageParamsConfig &__min__ = __getMin__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->clamp(*this, __max__, __min__);
}
uint32_t __level__(const ImageParamsConfig &config) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
uint32_t level = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->calcLevel(level, config, *this);
return level;
}
static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__();
static const ImageParamsConfig &__getDefault__();
static const ImageParamsConfig &__getMax__();
static const ImageParamsConfig &__getMin__();
static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__();
static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__();
private:
static const ImageParamsConfigStatics *__get_statics__();
};
template <> // Max and min are ignored for strings.
inline void ImageParamsConfig::ParamDescription<std::string>::clamp(ImageParamsConfig &config, const ImageParamsConfig &max, const ImageParamsConfig &min) const
{
return;
}
class ImageParamsConfigStatics
{
friend class ImageParamsConfig;
ImageParamsConfigStatics()
{
ImageParamsConfig::GroupDescription<ImageParamsConfig::DEFAULT, ImageParamsConfig> Default("Default", "", 0, 0, true, &ImageParamsConfig::groups);
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Activate = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Activate = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Activate = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<bool>("Activate", "bool", 0, "Activate GUI", "", &ImageParamsConfig::Activate)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<bool>("Activate", "bool", 0, "Activate GUI", "", &ImageParamsConfig::Activate)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Red_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Red_Min = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Red_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Red_Min", "int", 0, "Minimum amount of red required", "", &ImageParamsConfig::Red_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Red_Min", "int", 0, "Minimum amount of red required", "", &ImageParamsConfig::Red_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Green_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Green_Min = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Green_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Green_Min", "int", 0, "Minimum amount of green required", "", &ImageParamsConfig::Green_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Green_Min", "int", 0, "Minimum amount of green required", "", &ImageParamsConfig::Green_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Blue_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Blue_Min = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Blue_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blue_Min", "int", 0, "Minumum amount of blue required", "", &ImageParamsConfig::Blue_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blue_Min", "int", 0, "Minumum amount of blue required", "", &ImageParamsConfig::Blue_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Red_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Red_Max = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Red_Max = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Red_Max", "int", 0, "Maximum amount of red required", "", &ImageParamsConfig::Red_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Red_Max", "int", 0, "Maximum amount of red required", "", &ImageParamsConfig::Red_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Green_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Green_Max = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Green_Max = 19;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Green_Max", "int", 0, "Maximum amount of green required", "", &ImageParamsConfig::Green_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Green_Max", "int", 0, "Maximum amount of green required", "", &ImageParamsConfig::Green_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Blue_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Blue_Max = 256;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Blue_Max = 141;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blue_Max", "int", 0, "Maximum amount of blue required", "", &ImageParamsConfig::Blue_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blue_Max", "int", 0, "Maximum amount of blue required", "", &ImageParamsConfig::Blue_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Motion_Sensitivity = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Motion_Sensitivity = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Motion_Sensitivity = 22;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Motion_Sensitivity", "int", 0, "Sensitivity value (for motion node)", "", &ImageParamsConfig::Motion_Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Motion_Sensitivity", "int", 0, "Sensitivity value (for motion node)", "", &ImageParamsConfig::Motion_Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Motion_Blur = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Motion_Blur = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Motion_Blur = 24;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Motion_Blur", "int", 0, "Blur value (for motion node)", "", &ImageParamsConfig::Motion_Blur)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Motion_Blur", "int", 0, "Blur value (for motion node)", "", &ImageParamsConfig::Motion_Blur)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Shape_Sensitivity = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Shape_Sensitivity = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Shape_Sensitivity = 20;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Shape_Sensitivity", "int", 0, "Sensitivity value (for shape node)", "", &ImageParamsConfig::Shape_Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Shape_Sensitivity", "int", 0, "Sensitivity value (for shape node)", "", &ImageParamsConfig::Shape_Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Shape_Blur = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Shape_Blur = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Shape_Blur = 25;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Shape_Blur", "int", 0, "Blur value (for shape node)", "", &ImageParamsConfig::Shape_Blur)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Shape_Blur", "int", 0, "Blur value (for shape node)", "", &ImageParamsConfig::Shape_Blur)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.H_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.H_Min = 181;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.H_Min = 115;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("H_Min", "int", 0, "Minimum amount of red required", "", &ImageParamsConfig::H_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("H_Min", "int", 0, "Minimum amount of red required", "", &ImageParamsConfig::H_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.S_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.S_Min = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.S_Min = 186;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("S_Min", "int", 0, "Minimum amount of green required", "", &ImageParamsConfig::S_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("S_Min", "int", 0, "Minimum amount of green required", "", &ImageParamsConfig::S_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.V_Min = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.V_Min = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.V_Min = 33;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("V_Min", "int", 0, "Minumum amount of blue required", "", &ImageParamsConfig::V_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("V_Min", "int", 0, "Minumum amount of blue required", "", &ImageParamsConfig::V_Min)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.H_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.H_Max = 181;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.H_Max = 181;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("H_Max", "int", 0, "Maximum amount of red required", "", &ImageParamsConfig::H_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("H_Max", "int", 0, "Maximum amount of red required", "", &ImageParamsConfig::H_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.S_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.S_Max = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.S_Max = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("S_Max", "int", 0, "Maximum amount of green required", "", &ImageParamsConfig::S_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("S_Max", "int", 0, "Maximum amount of green required", "", &ImageParamsConfig::S_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.V_Max = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.V_Max = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.V_Max = 361;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("V_Max", "int", 0, "Maximum amount of blue required", "", &ImageParamsConfig::V_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("V_Max", "int", 0, "Maximum amount of blue required", "", &ImageParamsConfig::V_Max)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Sensitivity = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Sensitivity = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Sensitivity = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Sensitivity", "int", 0, "Sensitivity value (for shape node)", "", &ImageParamsConfig::Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Sensitivity", "int", 0, "Sensitivity value (for shape node)", "", &ImageParamsConfig::Sensitivity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.Blur = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.Blur = 40;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.Blur = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blur", "int", 0, "Blur value (for shape node)", "", &ImageParamsConfig::Blur)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(ImageParamsConfig::AbstractParamDescriptionConstPtr(new ImageParamsConfig::ParamDescription<int>("Blur", "int", 0, "Blur value (for shape node)", "", &ImageParamsConfig::Blur)));
//#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.convertParams();
//#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__group_descriptions__.push_back(ImageParamsConfig::AbstractGroupDescriptionConstPtr(new ImageParamsConfig::GroupDescription<ImageParamsConfig::DEFAULT, ImageParamsConfig>(Default)));
//#line 353 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
for (std::vector<ImageParamsConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
__description_message__.groups.push_back(**i);
}
__max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__);
__min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__);
__default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__);
}
std::vector<ImageParamsConfig::AbstractParamDescriptionConstPtr> __param_descriptions__;
std::vector<ImageParamsConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__;
ImageParamsConfig __max__;
ImageParamsConfig __min__;
ImageParamsConfig __default__;
dynamic_reconfigure::ConfigDescription __description_message__;
static const ImageParamsConfigStatics *get_instance()
{
// Split this off in a separate function because I know that
// instance will get initialized the first time get_instance is
// called, and I am guaranteeing that get_instance gets called at
// most once.
static ImageParamsConfigStatics instance;
return &instance;
}
};
inline const dynamic_reconfigure::ConfigDescription &ImageParamsConfig::__getDescriptionMessage__()
{
return __get_statics__()->__description_message__;
}
inline const ImageParamsConfig &ImageParamsConfig::__getDefault__()
{
return __get_statics__()->__default__;
}
inline const ImageParamsConfig &ImageParamsConfig::__getMax__()
{
return __get_statics__()->__max__;
}
inline const ImageParamsConfig &ImageParamsConfig::__getMin__()
{
return __get_statics__()->__min__;
}
inline const std::vector<ImageParamsConfig::AbstractParamDescriptionConstPtr> &ImageParamsConfig::__getParamDescriptions__()
{
return __get_statics__()->__param_descriptions__;
}
inline const std::vector<ImageParamsConfig::AbstractGroupDescriptionConstPtr> &ImageParamsConfig::__getGroupDescriptions__()
{
return __get_statics__()->__group_descriptions__;
}
inline const ImageParamsConfigStatics *ImageParamsConfig::__get_statics__()
{
const static ImageParamsConfigStatics *statics;
if (statics) // Common case
return statics;
boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__);
if (statics) // In case we lost a race.
return statics;
statics = ImageParamsConfigStatics::get_instance();
return statics;
}
}
#endif // __IMAGEPARAMSRECONFIGURATOR_H__
| 58.588966 | 258 | 0.738305 | [
"shape",
"vector"
] |
f1bdcf0a305d3950d96711547706dfd31c63fbf4 | 240 | h | C | src/main/cpp/RLBotInterface/chip/cpp/inc/misc/convert.h | dvptl68/RLBot | e3cc4d2d7f04ec846b219e274e9633623859179b | [
"MIT"
] | 1 | 2020-01-21T15:38:18.000Z | 2020-01-21T15:38:18.000Z | src/main/cpp/RLBotInterface/chip/cpp/inc/misc/convert.h | dvptl68/RLBot | e3cc4d2d7f04ec846b219e274e9633623859179b | [
"MIT"
] | null | null | null | src/main/cpp/RLBotInterface/chip/cpp/inc/misc/convert.h | dvptl68/RLBot | e3cc4d2d7f04ec846b219e274e9633623859179b | [
"MIT"
] | null | null | null | #pragma once
#include "linear_algebra/math.h"
#ifdef GENERATE_PYTHON_BINDINGS
#include <pybind11/pybind11.h>
namespace convert {
vec3 vector3_to_vec3(pybind11::object vector3);
mat3 rotator_to_mat3(pybind11::object rotator);
}
#endif
| 20 | 49 | 0.791667 | [
"object"
] |
f1c230c1b094fbad0480eda24d933c499b1f8521 | 2,988 | c | C | 0500_Firmware/PongBoy.X/src/app/menu_ctrl.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | 0500_Firmware/PongBoy.X/src/app/menu_ctrl.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | 0500_Firmware/PongBoy.X/src/app/menu_ctrl.c | SamyFrancelet/PongBoy | 6d7ad913570d4de93b89088eaab1cd7b8ce86f85 | [
"MIT"
] | null | null | null | #include "menu_ctrl.h"
#include "pong_ctrl.h"
#include "../pongboy/pongboy.h"
#include "../display/display.h"
extern const FONT_INFO arialNarrow_12ptFontInfo;
/**
* Initialise the Menu controller
*
* @param me - Menu controller object
*
* @author Samy Francelet
*/
void Menu_init(Menu* me) {
me->state = Menu_main;
me->oldState = Menu_main;
LCD_ButtonCreate(20, 50, 80, 40, BG_COLOR, ITEM_COLOR,
"Play Pong", &arialNarrow_12ptFontInfo, NULL, NULL, NULL,
&(me->SinglePlayerBtn), 1);
LCD_ButtonCreate(20, 150, 80, 40, BG_COLOR, ITEM_COLOR,
"Settings", &arialNarrow_12ptFontInfo, NULL, NULL, NULL,
&(me->settingsBtn), 1);
LCD_SliderCreate(150, 60, 100, 20, BG_COLOR, ITEM_COLOR,
RED, 5, 100, NULL, &(me->backLightSlider));
me->backLightSlider.value = 100;
}
/**
* Starting behavior of the Menu state machine
*
* @param me - Menu controller object
*
* @author Samy Francelet
*/
void Menu_startBehavior(Menu* me) {
me->state = Menu_main;
me->oldState = Menu_main;
}
/**
* Update the Menu state machine
* accordingly to the event received
*
* @param me - Menu controller object
* @param ev - event to react
*
* @author Samy Francelet
*/
void Menu_SM(Menu* me, Event ev) {
me->oldState = me->state;
TSC* tsc;
switch(me->state) {
case Menu_main:
case Menu_settings:
if(ev == TSC_evTSC) {
tsc = PongBoy_getTSC();
checkClick(me, tsc->x, tsc->y);
} else if (ev == Pong_startGameEv) {
me->state = Menu_inGame;
}
break;
case Menu_inGame:
if(ev == Menu_evMenu) {
me->state = Menu_main;
}
break;
default:
break;
}
}
/**
* Check if the TouchScreen has clicked on an object
*
* @param me - Menu controller object
* @param posX - TouchScreen x position
* @param posY - TouchScreen y position
*
* @author Samy Francelet
*/
void checkClick(Menu* me, uint16_t posX, uint16_t posY) {
if (me->state == Menu_main) {
if (LCD_InButton(&(me->SinglePlayerBtn), posX, posY)) {
XF_pushEvent(Pong_startGameEv, false);
} else if (LCD_InButton(&(me->settingsBtn), posX, posY)) {
XF_pushEvent(Menu_redraw, false);
me->state = Menu_settings;
me->SinglePlayerBtn.text = "Back";
}
} else if (me->state == Menu_settings) {
if (LCD_InButton(&(me->SinglePlayerBtn), posX, posY)) {
XF_pushEvent(Menu_redraw, false);
me->state = Menu_main;
me->SinglePlayerBtn.text = "Play Pong";
} else if (LCD_InSlider(&(me->backLightSlider), posX, posY)) {
uint8_t value;
value = posX - me->backLightSlider.posX;
me->backLightSlider.value = value;
XF_pushEvent(Menu_refresh, false);
}
}
} | 27.666667 | 70 | 0.580991 | [
"object"
] |
0188ca0f452dbbc1ac43689332decd7e0446483e | 1,262 | h | C | scisim/ConstrainedMaps/FrictionMaps/LinearMDPOperatorQL.h | Lyestria/scisim | e2c2abc8d38ea9b07717841782c5c723fce37ce5 | [
"Apache-2.0"
] | null | null | null | scisim/ConstrainedMaps/FrictionMaps/LinearMDPOperatorQL.h | Lyestria/scisim | e2c2abc8d38ea9b07717841782c5c723fce37ce5 | [
"Apache-2.0"
] | null | null | null | scisim/ConstrainedMaps/FrictionMaps/LinearMDPOperatorQL.h | Lyestria/scisim | e2c2abc8d38ea9b07717841782c5c723fce37ce5 | [
"Apache-2.0"
] | null | null | null | // LinearMDPOperatorQL.h
//
// Breannan Smith
// Last updated: 09/21/2015
#ifndef LINEAR_MDP_OPERATOR_QL
#define LINEAR_MDP_OPERATOR_QL
#include "FrictionOperator.h"
// TODO: Move to unsigned when possible
class LinearMDPOperatorQL final : public FrictionOperator
{
public:
LinearMDPOperatorQL( const int disk_samples, const scalar& eps );
explicit LinearMDPOperatorQL( std::istream& input_stream );
virtual ~LinearMDPOperatorQL() override = default;
virtual void flow( const scalar& t, const SparseMatrixsc& Minv, const VectorXs& v0, const SparseMatrixsc& D, const SparseMatrixsc& Q, const VectorXs& gdotD, const VectorXs& mu, const VectorXs& alpha, VectorXs& beta, VectorXs& lambda ) override;
virtual int numFrictionImpulsesPerNormal() const override;
virtual void formGeneralizedFrictionBasis( const VectorXs& q, const VectorXs& v, const std::vector<std::unique_ptr<Constraint>>& K, SparseMatrixsc& D, VectorXs& drel ) override;
virtual std::string name() const override;
virtual std::unique_ptr<FrictionOperator> clone() const override;
virtual void serialize( std::ostream& output_stream ) const override;
virtual bool isLinearized() const override;
private:
const int m_disk_samples;
const scalar m_tol;
};
#endif
| 28.681818 | 246 | 0.770206 | [
"vector"
] |
018c2d87b37ce34c03e13ebeb3bbca5d6648acf8 | 4,163 | h | C | cmc/private/cmc/I3MetropolisHastings.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 1 | 2020-12-24T22:00:01.000Z | 2020-12-24T22:00:01.000Z | cmc/private/cmc/I3MetropolisHastings.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | null | null | null | cmc/private/cmc/I3MetropolisHastings.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 3 | 2020-07-17T09:20:29.000Z | 2021-03-30T16:44:18.000Z | /**
* A metropolis hasting sampler for bremsstrahlung and pair production cross sections
*
* copyright (C) 2007
* the icecube collaboration
*
* $Id: I3MetropolisHastings.h 143040 2016-03-11 17:35:25Z nega $
*
* @version $Revision: 143040 $
* @date $LastChangedDate: 2016-03-11 10:35:25 -0700 (Fri, 11 Mar 2016) $
* @author Bernhard Voigt <bernhard.voigt@desy.de> $LastChangedBy$
*/
#ifndef I3METROPOLISHASTINGS_h_
#define I3METROPOLISHASTINGS_h_
// icetray includes
#include "icetray/I3Logging.h"
#include "cmc/I3CascadeMCCommon.h"
// gsl includes
#include <gsl/gsl_rng.h>
// c++ includes
#include <string>
/**
* @brief This class implements a Metropolis Hastings sampler
*
* It uses a pdf and a proposal distribution to efficiently
* produce random samples from the pdf
*
* The proposal distribution used is a beta distribution, which
* matches almost the shape of the bremsstrahlung and pair production
* cross sections, using the right parameters. See I3CascadeSimulation
* for the usage.
*
* For details on the algorithm, take a look at :
* http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm
*/
class I3MetropolisHastings : public I3CascadeMCCommon::Sampler {
// set logging name for icetray
SET_LOGGER("I3MetropolisHastings");
public:
/**
* Default Constructor
*/
I3MetropolisHastings() {}
/**
* Constructor
*
* @param rng a gsl_random instance
* @param pdf a function with two parameters, ie. the energy and
* fractional energy of the cross section
* @param proposal a gsl random instance sampling from the proposal
* distribution which is a beta distribution
* @param proposalDistribution a beta function in x
* @param name name of this instance for logging purposes
*
* The proposal gsl random instance as well as the proposalDistribution are implemented
* in a struct beta_dist in the header file I3CascadeSimulation.h
*/
I3MetropolisHastings(I3RandomServicePtr rng,
double (*pdf)(const double&, const double&),
double (*proposal)(const gsl_rng*),
double (*proposalDistribution)(const double&),
std::string name);
/**
* Get the total sample loop count
*/
unsigned long GetCounter() {
return counter_;
}
/**
* Reset the total sample loop count
*/
void ResetCounter() {
counter_ = 0;
}
/**
* Get the number of returned samples
*/
unsigned long GetYield() {
return yield_;
}
/**
* Reset the number of returned samples
*/
void ResetYield() {
yield_ = 0;
}
/**
* Samples n times starting at start position
*
* Used to forget the initial state
*
* @param energy parameter of underlying pdf
* @param start starting position
* @param n number of samples
*/
void BurnIn(double energy, double start, unsigned int n=100);
/**
* Samples the underlying pdf in the given range
*
* @param energy parameter to the underlying pdf
* @param lower edge of sample range
* @param higher edge of sample range
* @return random number
*/
double Sample(double energy, double lower=0, double higher=1);
private:
/**
* @brief pdf, ie a cross section with energy and fractional energy parameters
*/
double (*pdf_)(const double&, const double&);
/**
* @brief a gls random instance drawing samples from the proposal distribution
*/
double (*proposal_)(const gsl_rng*);
/**
* @brief a proposal distribution, in this case a beta distribution in x
*/
double (*proposalDistribution_)(const double&);
/**
* @brief loop counter
*/
unsigned long counter_;
/**
* @brief counts how many successful attemps have been made to draw a new random number
*/
unsigned long yield_;
/**
* @brief name of this instance, for logging purpose
*/
std::string name_;
/**
* @brief last drawn sample
*/
double x_;
/**
* @brief last value of pdf(x)
*/
double y_;
/**
* @brief last value of proposalDist(x)
*/
double propDistY_;
};
#endif
| 23.653409 | 90 | 0.661302 | [
"shape"
] |
01969d801d8fbb9622e080a60cbd638abe80df83 | 12,097 | c | C | src/ast.c | keyehzy/calc | 954dc4e37aeff712ef89dd9d1a1f8dc99c5bbfbc | [
"MIT"
] | null | null | null | src/ast.c | keyehzy/calc | 954dc4e37aeff712ef89dd9d1a1f8dc99c5bbfbc | [
"MIT"
] | null | null | null | src/ast.c | keyehzy/calc | 954dc4e37aeff712ef89dd9d1a1f8dc99c5bbfbc | [
"MIT"
] | null | null | null | #include "calc/vector.h"
#include <calc/assert.h>
#include <calc/ast.h>
#include <calc/token.h>
#include <stdlib.h>
static AST *new_empty_ast();
static AST *new_ast(ast_kind, codeloc, operation);
static AST *parse_primary_expr(lexer *);
static AST *parse_rest_expr(lexer *, AST *, operation, int);
static void combine_tree(vector *, operation);
static operation operation_from_tk(token t, int context);
AST *child_0(AST *ast) {
CHECK(Size(&ast->children) > 0);
return GetVector(&ast->children, 0);
}
AST *child_1(AST *ast) {
CHECK(Size(&ast->children) > 1);
return GetVector(&ast->children, 1);
}
AST *child(AST *ast, int i) {
CHECK(Size(&ast->children) > i);
return GetVector(&ast->children, i);
}
void free_ast(AST *ast) { /* FIXME */
/* int n = Size(&ast->children); */
/* for (int i = 0; i < n; i++) { */
/* free_ast(GetVector(&ast->children, i)); */
/* } */
free(ast->children.items);
free(ast);
}
static AST *new_empty_ast() {
AST *ast = (AST *)malloc(sizeof(AST));
*ast = (AST) {0};
ast->children = NewVector();
return ast;
}
static AST *make_ast(ast_kind kind) {
AST *ast = (AST *)malloc(sizeof(AST));
*ast = (AST) {0};
ast->kind = kind;
ast->children = NewVector();
ast->var_declarations = NewVector();
ast->fn_declarations = NewVector();
return ast;
}
static AST *new_ast(ast_kind kind, codeloc loc, operation op) {
AST *ast = (AST *)malloc(sizeof(AST));
*ast = (AST) {0};
ast->kind = kind;
ast->loc = loc;
ast->op = op;
ast->children = NewVector();
return ast;
}
static AST *invalid_ast() {
AST *ast = (AST *)malloc(sizeof(AST));
*ast = (AST) {0};
ast->kind = ast_invalid;
return ast;
}
static operation operation_from_tk(token t, int context) {
char * name = normalized_name(t.loc);
operation op = (operation) {0};
if (context == 0) { /* binary operations */
switch (name[0]) {
case '+':
op = (operation){.kind = op_binary_plus,
.prec = prec_addsub,
.assoc = assoc_right};
break;
case '-':
op = (operation){.kind = op_binary_minus,
.prec = prec_addsub,
.assoc = assoc_right};
break;
case '*':
op = (operation){.kind = op_binary_times,
.prec = prec_multdiv,
.assoc = assoc_right};
break;
case '/':
op = (operation){.kind = op_binary_div,
.prec = prec_multdiv,
.assoc = assoc_right};
break;
case '^':
op = (operation){
.kind = op_binary_pow, .prec = prec_pow, .assoc = assoc_left};
break;
case ',':
op = (operation){
.kind = op_comma, .prec = prec_comma, .assoc = assoc_right};
break;
default:
emit_error(error_unexpected_operation, t.loc); /* error */
break;
}
} else { /* unary operation */
switch (name[0]) {
case '+':
op = (operation){
.kind = op_unary_plus, .prec = prec_unary, .assoc = assoc_left};
break;
case '-':
op = (operation){.kind = op_unary_minus,
.prec = prec_unary,
.assoc = assoc_left};
break;
default:
emit_error(error_unexpected_operation, t.loc); /* error */
break;
}
}
free(name);
return op;
}
static AST *parse_primary_expr(lexer *lex) {
switch (L_PEEK().type) {
case tk_identifier: {
codeloc identifier_span = L_PEEK().loc;
L_SKIP();
return new_ast(ast_variable, identifier_span, (operation){0});
}
case tk_number: {
codeloc number_span = L_PEEK().loc;
L_SKIP();
return new_ast(ast_number_literal, number_span, (operation){0});
}
case tk_left_paren: {
L_SKIP();
AST *paren_expr = parse_expr1(lex);
CHECK(L_PEEK().type == tk_right_paren);
L_SKIP();
AST *ast = new_ast(ast_paren_expr, paren_expr->loc,
(operation){.prec = prec_paren});
PushVector(&ast->children, paren_expr);
return ast;
}
case tk_left_curly: {
L_SKIP();
AST *curly_expr = parse_expr1(lex);
CHECK(L_PEEK().type == tk_right_curly);
L_SKIP();
AST *ast = new_ast(ast_curly_expr, curly_expr->loc,
(operation){.prec = prec_paren});
PushVector(&ast->children, curly_expr);
return ast;
}
case tk_operator: {
operation op = operation_from_tk(L_PEEK(), 1);
codeloc operator_span = L_PEEK().loc;
L_SKIP();
AST *ast = new_ast(ast_unary_expr, operator_span, op);
PushVector(&ast->children, parse_primary_expr(lex));
return ast;
}
#define PARSE_CONST(constant) \
case tk_##constant: { \
codeloc const_span = L_PEEK().loc; \
L_SKIP(); \
return new_ast(ast_const_##constant, const_span, (operation){0}); \
}
ENUMERATE_CONSTANTS(PARSE_CONST);
#undef PARSE_CONST
#define PARSE_FUNC(fn) \
case tk_##fn: { \
operation op = (operation){ \
.kind = op_##fn, .prec = prec_unary, .assoc = assoc_left}; \
codeloc operator_span = L_PEEK().loc; \
L_SKIP(); \
CHECK(L_PEEK().type == tk_left_paren); \
AST *ast = new_ast(ast_unary_expr, operator_span, op); \
PushVector(&ast->children, parse_primary_expr(lex)); \
return ast; \
}
ENUMERATE_FUNCTIONS(PARSE_FUNC);
#undef PARSE_FUNC
default:
return invalid_ast();
}
}
static AST *parse_rest_expr(lexer *lex, AST *lhs, operation o, int commas) {
vector tree = NewVector();
PushVector(&tree, lhs);
operation new_o = {0};
AST * res = NULL;
int comma_flag = /*false*/ 0;
while (1) {
switch (L_PEEK().type) {
case tk_comma: {
if (commas)
goto end;
comma_flag = /*true*/ 1;
new_o = operation_from_tk(L_PEEK(), 0);
codeloc commas_loc = L_PEEK().loc;
L_SKIP();
PushVector(&tree, parse_expr(lex, new_o, /*commas*/ 1));
if(AST_BACK(&tree)->kind == ast_invalid) {
emit_error(error_invalid_expression_in_commas,
new_loc(lhs->loc.begin, commas_loc.end));
}
continue;
}
case tk_operator: {
new_o = operation_from_tk(L_PEEK(), 0);
if (o.prec > new_o.prec ||
(o.prec == new_o.prec && new_o.assoc == assoc_right)) {
goto end;
}
codeloc token_loc = L_PEEK().loc;
L_SKIP();
PushVector(&tree, parse_expr(lex, new_o, commas));
if(AST_BACK(&tree)->kind == ast_invalid) {
emit_error(error_invalid_rhs_for_binary_expression,
new_loc(lhs->loc.begin, token_loc.end));
}
break;
}
case tk_equal: {
CHECK(lhs->kind == ast_variable);
codeloc equal_loc = L_PEEK().loc;
L_SKIP();
PushVector(&tree, parse_expr1(lex));
if(AST_BACK(&tree)->kind == ast_invalid) {
emit_error(error_invalid_assignee_for_assignment,
new_loc(lhs->loc.begin, equal_loc.end));
}
combine_tree(&tree, (operation){0});
AST_BACK(&tree)->kind = ast_assignment;
goto end;
}
default:
goto end;
}
combine_tree(&tree, new_o);
}
end:
combine_tree(&tree, new_o);
res = AST_BACK(&tree);
if (comma_flag) { /* HACK */
res->kind = ast_comma_expr;
}
free(tree.items);
return res;
}
static void combine_tree(vector *tree, operation o) {
if (Size(tree) > 1) {
AST *ast = new_empty_ast();
ast->kind = ast_binary_expr;
ast->op = o;
ast->loc =
new_loc(AST_GET(tree, 0)->loc.begin, AST_BACK(tree)->loc.end);
int SIZE = Size(tree);
for (int i = 0; i < SIZE; i++) {
PushVector(&ast->children, GetVector(tree, i));
}
for (int i = 0; i < SIZE; i++) {
PopVector(tree);
}
PushVector(tree, ast);
return;
} else if (Size(tree) == 1) {
return;
}
}
AST *parse_expr(lexer *lex, operation o, int commas) {
AST *ast = parse_primary_expr(lex);
if (L_PEEK().type == tk_comma)
return ast;
return parse_rest_expr(lex, ast, o, commas);
}
AST *parse_expr1(lexer *lex) {
AST *ast = parse_primary_expr(lex);
return parse_rest_expr(lex, ast, (operation){0}, /*commas*/ 0);
}
static AST *parse_let_statement(lexer *lex) {
const char *begin = L_PEEK().loc.begin;
L_SKIP(); /* skip 'let' */
if (L_PEEK().type == tk_identifier) {
AST *lhs = make_ast(ast_variable);
lhs->loc = L_PEEK().loc;
L_SKIP();
AST *rhs = parse_rest_expr(lex, lhs, (operation){0}, /*commas*/ 0);
AST *declaration = make_ast(ast_declaration);
declaration->loc = new_loc(begin, rhs->loc.end);
PushVector(&declaration->children, rhs);
/* push into current scope variable declarations */
AST *scope = (AST *)BackVector(&lex->scope);
PushVector(&scope->var_declarations, declaration);
L_SKIP_CHECKED(tk_semicolon);
return declaration;
}
emit_error(error_unexpected_token_after_let, L_PEEK().loc);
return invalid_ast();
}
static AST *parse_statement(lexer *lex) {
switch (L_PEEK().type) {
case tk_identifier: {
AST *identifier = make_ast(ast_variable);
identifier->loc = L_PEEK().loc;
L_SKIP();
if (L_PEEK().type == tk_semicolon) {
L_SKIP();
return identifier;
} else {
return parse_rest_expr(lex, identifier, (operation){0},
/*commas*/ 0);
}
}
case tk_let: {
AST *let_statement = parse_let_statement(lex);
return let_statement;
}
default:
return parse_expr1(lex); /* try to parse as a trailling
* expression */
}
}
AST *parse_program(lexer *lex) {
AST *module = make_ast(ast_module);
lex->scope = NewVector();
PushVector(&lex->scope, module); /* push global scope for declaring
* variables and functions */
while (1) {
AST *statement = parse_statement(lex);
if (statement->kind != ast_invalid) {
PushVector(&module->children, statement);
} else {
switch (L_PEEK().type) {
case tk_eof:
goto end;
case tk_semicolon:
L_SKIP();
break;
default:
emit_error(error_malformed_expression, statement->loc);
break;
}
}
}
end:
PopVector(&lex->scope);
return module;
}
| 29.577017 | 80 | 0.499297 | [
"vector"
] |
019ab49bb65315523fdf0371f4e212cdf45b0640 | 624 | h | C | Example/Pods/Headers/Public/BKMVVMKit/BKVMReusableViewModel.h | isingle/BKMVVMKit | f34a9630d840be525506d8ede5eaf7ed89a88b73 | [
"MIT"
] | 13 | 2019-11-27T07:59:21.000Z | 2021-06-29T08:09:07.000Z | Example/Pods/Headers/Public/BKMVVMKit/BKVMReusableViewModel.h | isingle/BKMVVMKit | f34a9630d840be525506d8ede5eaf7ed89a88b73 | [
"MIT"
] | 1 | 2020-05-29T06:06:29.000Z | 2020-05-29T06:06:29.000Z | Example/Pods/Headers/Public/BKMVVMKit/BKVMReusableViewModel.h | isingle/BKMVVMKit | f34a9630d840be525506d8ede5eaf7ed89a88b73 | [
"MIT"
] | null | null | null | //
// BKVMReusableViewModel.h
// Pods
//
// Created by lic on 2019/9/4.
//
#import "BKVMBaseViewModel.h"
#import "BKVMViewProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface BKVMReusableViewModel : BKVMBaseViewModel
//子类实现注册 reuse cell
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, strong) Class<BKVMViewProtocol> viewClass;
//
@property (nonatomic, assign, readonly) CGFloat viewHeight;
@property (nonatomic, assign, readonly) CGFloat viewWidth;
- (instancetype)initWithModel:(id)model identifier:(NSString *)identifier viewClass:(Class<BKVMViewProtocol>)viewClass;
@end
NS_ASSUME_NONNULL_END
| 24 | 119 | 0.782051 | [
"model"
] |
019ad669dfcaad9ffbddbf4261542e1ef0be0f59 | 5,502 | h | C | TDEngine2/include/core/memory/CBaseAllocator.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | TDEngine2/include/core/memory/CBaseAllocator.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | TDEngine2/include/core/memory/CBaseAllocator.h | bnoazx005/TDEngine2 | 93ebfecf8af791ff5ecd4f57525a6935e34cd05c | [
"Apache-2.0"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | /*!
\file CBaseAllocator.h
\date 31.10.2018
\authors Kasimov Ildar
*/
#pragma once
#include "../CBaseObject.h"
#include "IAllocator.h"
namespace TDEngine2
{
/*!
class CBaseAllocator
\brief The class implements a common functionality of all memory allocators that are
used in the engine
The allocator's implementation is based on following article:
https://www.gamedev.net/articles/programming/general-and-gameplay-programming/c-custom-memory-allocation-r3010/
*/
class CBaseAllocator : public CBaseObject, public IAllocator
{
public:
/*!
\brief The method initializes an internal state of an allocator
\param[in] totalMemorySize A value determines a size of a memory block
\param[in, out] pMemoryBlock A pointer to a memory block
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Init(U32 totalMemorySize, U8* pMemoryBlock) override;
/*!
\brief The method frees all memory occupied by the object
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Free() override;
/*!
\brief The method allocates a new piece of memory of specified size,
which is aligned by aligment's value
\param[in] size A size of an allocated memory
\param[in] alignment An alignment of a block
\return A pointer to the allocated block, returns nullptr if there is no free space
*/
TDE2_API virtual void* Allocate(U32 size, U8 alignment) = 0;
/*!
\brief The method deallocates memory in position specified with a given pointer
\param[in] pObjectPtr A pointer to piece of memory that should be freed
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API virtual E_RESULT_CODE Deallocate(void* pObjectPtr) = 0;
/*!
\brief The method clears up all used memory
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API virtual E_RESULT_CODE Clear() = 0;
#if TDE2_EDITORS_ENABLED
TDE2_API void SetBlockDebugName(const std::string& blockId) override;
#endif
/*!
\brief The method returns total size of available memory
\return The method returns total size of available memory
*/
TDE2_API U32 GetTotalMemorySize() const override;
/*!
\brief The method returns a size of used memory
\return The method returns a size of used memory
*/
TDE2_API U32 GetUsedMemorySize() const override;
/*!
\brief The methods returns total number of allocations
\return The methods returns total number of allocations
*/
TDE2_API U32 GetAllocationsCount() const override;
/*!
\brief The method returns an aligned address. If current address
is already aligned then it returns without any change. In other
case nearest forward address will be returned which is a multiple
of alignment value
\param[in] An input memory address
\param[in] An alignment value (should be power of 2)
\return An aligned value
*/
TDE2_API static void* GetAlignedAddress(void* pAddress, U8 alignment);
/*!
\brief The method returns a padding value that should be added to
current given address to make it aligned
\param[in] An input memory address
\param[in] An alignment value (should be power of 2)
\return The method returns a padding value that should be added to
current given address to make it aligned
*/
TDE2_API static U8 GetPadding(void* pAddress, U8 alignment);
/*!
\brief The method returns a padding value that should be added to
current given address to make it aligned
\param[in] An input memory address
\param[in] An alignment value (should be power of 2)
\return The method returns a padding value that should be added to
current given address to make it aligned
*/
TDE2_API static U8 GetPaddingWithHeader(void* pAddress, U8 alignment, U8 headerSize);
protected:
DECLARE_INTERFACE_IMPL_PROTECTED_MEMBERS(CBaseAllocator)
protected:
U32 mTotalMemorySize;
U32 mUsedMemorySize;
U32 mAllocationsCount;
U8* mpMemoryBlock;
#if TDE2_EDITORS_ENABLED
std::string mName;
#endif
};
/*!
\brief The function allocates a new chunk of aligned memory of given size
\param[in, out] pAllocator A pointer to an allocator's implementation
\param[in] size A memory's size
\param[in] alignment An alignment of a memory block
\return The method returns a pointer to an allocated memory block. If pAlignment equals to nullptr
or there is no free space within memory then nullptr will be returned
*/
TDE2_API void* AllocateMemory(IAllocator* pAllocator, U32 size, U32 alignment);
/*!
class CBaseAllocatorFactory
\brief The abstract class is used to derive new types of allocators' factories
*/
class CBaseAllocatorFactory : public CBaseObject, public IAllocatorFactory
{
public:
/*!
\brief The method initializes an internal state of an allocator factory
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Init() override;
/*!
\brief The method frees all memory occupied by the object
\return RC_OK if everything went ok, or some other code, which describes an error
*/
TDE2_API E_RESULT_CODE Free() override;
protected:
DECLARE_INTERFACE_IMPL_PROTECTED_MEMBERS(CBaseAllocatorFactory)
};
}
| 26.075829 | 113 | 0.726645 | [
"object"
] |
01a3a938dd85086f36290abc957c467109467739 | 2,287 | h | C | src/console.h | hmoraldo/randomediaGameJs | aa2c31e287f554423082660a51151643b8ed628c | [
"Zlib"
] | 2 | 2021-07-03T15:14:09.000Z | 2022-03-25T08:59:46.000Z | src/console.h | hmoraldo/randomediaGameJs | aa2c31e287f554423082660a51151643b8ed628c | [
"Zlib"
] | null | null | null | src/console.h | hmoraldo/randomediaGameJs | aa2c31e287f554423082660a51151643b8ed628c | [
"Zlib"
] | 1 | 2018-08-16T13:31:21.000Z | 2018-08-16T13:31:21.000Z | /*
Copyright (c) 2003 - 2014 Horacio Hernan Moraldo
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef FILE_CONSOLE_INCLUDED
#define FILE_CONSOLE_INCLUDED
#define FILE_CONSOLE_VERSION "10-6-2002-H"// last modification: dd/mm/yy
#include "scrolltext.h"
class consoleClass{
private:
// our scroll text object
scrollTextClass scroll;
bool initialized;
// console data
int maxChars;// max amount of chars + 1 for zero
char* lastLine;// where to place the typed string
int currentLetter;// pointer to the next byte to be written in lastLine
char* textParam;// where to copy the text params
int nextParam;// pointer to the next byte to be read
bool lastLineBuffered;// tells if lastLine contains the current or old typed text
// used when getting the params
bool skipSpaces();
public:
// some useful methods
bool init(int width, int height, int maxChars=200);
bool end();
bool clear();
bool keyUp(char key);
bool draw(ddSurfaceClass& srf, int x, int y);
bool writeLine(char* text);
bool getTextParam(char* ¶m);
bool getNoSpacedTextParam(char* ¶m);
bool getIntegerParam(int ¶m);
bool resetParamPointer();
// methods for dealing with lost surfaces
bool isLost(bool* errorCode=NULL);
bool restore();
// simple methods
bool isReady() {return initialized;}
// constructor / destructor
consoleClass():initialized(false) {}
~consoleClass() {end();}
};// consoleClass
#endif// FILE_CONSOLE_INCLUDED
| 29.701299 | 83 | 0.738085 | [
"object"
] |
01aa881707c97acf5fd07ae2cdda5d252e16c2fc | 3,280 | h | C | include/network/CNetBase.h | lirizhong/easygo | cd3a3656d94da0f915c67e871b85d40c9bc4aac0 | [
"Apache-2.0"
] | 1 | 2018-07-21T15:51:55.000Z | 2018-07-21T15:51:55.000Z | include/network/CNetBase.h | lirizhong/easygo | cd3a3656d94da0f915c67e871b85d40c9bc4aac0 | [
"Apache-2.0"
] | null | null | null | include/network/CNetBase.h | lirizhong/easygo | cd3a3656d94da0f915c67e871b85d40c9bc4aac0 | [
"Apache-2.0"
] | null | null | null | #ifndef EASYGO_NETWORK_CNETBASE_H
#define EASYGO_NETWORK_CNETBASE_H
#include <map>
#include <vector>
#include <set>
#include <atomic>
#include <mutex>
#include <queue>
#include <condition_variable>
#include "../include/network/NetType.h"
#include "../include/base/CCounter.h"
#include "../include/thread/CThread.h"
#include "../include/thread/CTaskThread.h"
#include "../include/thread/pool/CThreadPool.h"
#include "../include/network/CSocket.h"
#include "../include/declexport.h"
#include "../include/base/CBase.h"
#include "../include/network/CNetClock.h"
#include "../include/network/CTimer.h"
#ifndef EASYGO_NETWORK_DECL
# ifdef EASYGO_DYNAMIC_LINK
# if defined(EXPORT_NETWORK)
# define EASYGO_NETWORK_DECL EASYGO_DECL_EXPORT
# else
# define EASYGO_NETWORK_DECL EASYGO_DECL_IMPORT
# endif
# else
# define EASYGO_NETWORK_DECL
# endif
#endif
namespace easygo {
namespace network {
class CConnector;
typedef easygo::base::CBase<CConnector> PCConnector;
class CSocket;
typedef easygo::base::CBase<CSocket> PCSocket;
class CListener;
typedef easygo::base::CBase<CListener> PCListener;
class CNetClock;
typedef easygo::base::CBase<CNetClock> PCNetClock;
class CTimer;
typedef easygo::base::CBase<CTimer> PCTimer;
}
}
namespace easygo {
namespace thread {
class CThreadPool;
}
namespace network {
typedef enum NET_SOCK_EVENT
{
NET_SOCK_READ = 0x1,
NET_SOCK_WRITE = 0x2,
NET_SOCK_EXCEP = 0x4,
NET_SOCK_ALL = 0x7
} TNetSockEvent;
class EASYGO_NETWORK_DECL CNetBase : public easygo::thread::CThread
{
public:
CNetBase();
virtual ~CNetBase();
public:
bool Init();
bool UnInit();
bool Listen(PCListener listener);
bool Connect(PCConnector connector);
public:
virtual void Run();
void Start(int threadCount);
void Stop();
void Wait();
bool AddTimer(PCTimer timer);
bool RemoveTimer(PCTimer timer);
void PrepareTimer();
void ProcessTimer();
void AddEvent(PCSocket socket, int event);
void RemoveEvent(PCSocket socket, int event);
PCSocket FindBaseSocket(TNetScoket sockfd);
bool PushTask(easygo::base::CBase<easygo::thread::CTask> task);
bool NotifyAcceptor(easygo::base::CBase<easygo::thread::CTask> task);
public:
static void ProcSignal();
static bool Daemonize();
private:
int m_nThreadCount;
#ifdef WIN32
fd_set m_readSet;
fd_set m_writeSet;
fd_set m_excepSet;
#elif defined(__APPLE__) || defined(__FreeBSD__)
int m_kqfd;
#else
int m_epfd;
std::map<TNetScoket, uint32_t> m_addSet;
std::map<TNetScoket, uint32_t> m_modSet;
std::map<TNetScoket, uint32_t> m_delSet;
#endif
std::priority_queue<PCTimer, std::deque<PCTimer>, CTimerComparer> m_inactiveTimers;
std::priority_queue<PCTimer, std::deque<PCTimer>, CTimerComparer> m_activeTimers;
long long m_netTime;
PCNetClock m_netClock;
std::atomic<bool> m_bRunLoop;
std::atomic<bool> m_bInit;
std::map<TNetScoket, PCSocket> m_socketMap;
std::set<TNetScoket> m_closingSocks;
std::recursive_mutex m_netBaseMutex;
std::mutex m_mainThreadMutex;
std::condition_variable m_mainThreadCond;
easygo::base::CBase<easygo::thread::CThreadPool> m_threadPool;
};
} // namespace network
} // namespace easygo
#endif // EASYGO_NETWORK_CNETBASE_H
| 25.826772 | 86 | 0.733537 | [
"vector"
] |
01adc6d40f5fefa8f5fe86007286ec3d0fd62fae | 2,631 | h | C | src/gk_internal.h | amineas/libGK | 400cb6d16486848c121cfb1e8b99f5375de1c019 | [
"MIT"
] | 1 | 2017-12-15T14:05:59.000Z | 2017-12-15T14:05:59.000Z | src/gk_internal.h | amineas/libGK | 400cb6d16486848c121cfb1e8b99f5375de1c019 | [
"MIT"
] | null | null | null | src/gk_internal.h | amineas/libGK | 400cb6d16486848c121cfb1e8b99f5375de1c019 | [
"MIT"
] | null | null | null | /* Copyright (c) 2012 Toni Georgiev
*
* 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.
*/
/* THIS FILE IS BAD! */
#ifndef _GK_INTERNAL_H_
#define _GK_INTERNAL_H_
#ifdef __cplusplus
extern "C"{
#endif
extern uint64_t gkAppStartTime;
extern gkMouseState gkGlobalMouseState;
extern gkKeyboardState gkGlobalKeyboardState;
void gkProcessLayoutMainPanel(gkPanel* panel, float width, float height);
void gkProcessUpdatePanel(gkPanel* panel);
void gkProcessDrawPanel(gkPanel* panel);
void gkCheckFocusedPanel();
void gkUpdateMouseTarget(gkPanel* mainPanel);
void gkProcessMouseEvent(gkMouseEvent* mouseEvent);
GK_BOOL gkProcessKeyboardEvent(gkKeyboardEvent* keyboardEvent);
void gkResetTransform();
void gkResetColorFilter();
void gkUpdateTimers();
void gkUpdateTweens();
/* Some variables used in graphics.c */
typedef struct gkColorNodeStruct gkColorNode;
struct gkColorNodeStruct{
gkColor color;
gkColorNode* parent;
};
extern gkColorNode* gkColorFilterTop;
gkColor gkGetFilteredColor(gkColor c);
typedef struct gkTransformNodeStruct gkTransformNode;
struct gkTransformNodeStruct{
gkMatrix transform;
gkTransformNode *parent;
};
extern gkTransformNode* gkTransformTop;
/* Initializers and cleanups */
void gkInitImages();
void gkCleanupImages();
void gkInitFonts();
void gkCleanupFonts();
void gkInitTimers();
void gkCleanupTimers();
void gkInitTweens();
void gkCleanupTweens();
void gkInitDrawToImageBuffer(gkSize size);
void gkCleanupDrawToImageBuffer();
void gkInitJoystick();
void gkCleanupJoystick();
void gkInitAudio();
void gkCleanupAudio();
#ifdef __cplusplus
}
#endif
#endif
| 27.123711 | 80 | 0.789054 | [
"transform"
] |
01b4c73f2063d9d55c92ef354bffddba11b75c09 | 31,442 | c | C | deconv_moffat_dcv/dcv_1D_sub.c | jlprieur/deconv | 027324b50a152f201c4c2485648617cac9a53260 | [
"MIT"
] | null | null | null | deconv_moffat_dcv/dcv_1D_sub.c | jlprieur/deconv | 027324b50a152f201c4c2485648617cac9a53260 | [
"MIT"
] | null | null | null | deconv_moffat_dcv/dcv_1D_sub.c | jlprieur/deconv | 027324b50a152f201c4c2485648617cac9a53260 | [
"MIT"
] | null | null | null | /******************************************************************
* Module used by dcv_deconv_1D.f90
*
* spdiv => Direct spectral division
* wiene => Wiener filter
* tikho => Tikhonov regularisation
* maxen => Maximum Entropy method
*
* JLP
* Version 23/03/2001
*******************************************************************/
#include <jlp_dcv.h>
#include "jlp_fftw.h"
/* Public: */
double *yy, *yy0, *yyd, *w0, *w1;
/* Private: */
/*******************
* For dcv_1D_mod:
* ss2 is a parameter needed for convex sqrt regularization
*/
static double ss2;
static int nn1, nn, hh_nx;
static double *hh_re, *hh_im, *hht_re, *hht_im;
static double *xx1, *xx2, *w_re, *w_im;
static double *yy_re, *yy_im;
static double alpha;
/* Complex array (for fast FFT's) */
static FFTW_COMPLEX *cp0;
/* Public: (declared in jlp_dcv.h)
int dcv_1D_gmark(double alpha_0, double ftol, int *iter, int positive);
int dcv_1D_tikhonov(double alpha_0, double ftol, int *iter, int positive);
int dcv_1D_ggauss(double alpha_0, double ftol, int *iter, int positive);
int dcv_1D_sqrtrf(double alpha_0, double ss, double ftol, int *iter, int positive);
int dcv_1D_mem(double alpha_0, double ftol, int *iter, int positive);
int dcv_1D_spdiv();
int dcv_1D_wiener(double alpha_0);
int dcv_1D_banana(double ftol);
int dcv_1D_init(int nn1_0, int nn_0, int hh_nx_0);
void dcv_1D_free();
int dcv_1D_plot1(double *yy1, int nn, char *title);
int dcv_1D_plot1_log(double *yy1, int nn1, char *title);
int dcv_1D_plot2(double *yy1, double *yy2, int nn, char *title);
int dcv_1D_display_input(int nn);
int dcv_1D_transfert(double *hh);
*/
/* Private functions defined here: */
static int dcv_1D_check_grad(double *x1, double (*func)(double []),
void (*dfunc)(double[], double[]));
static int dcv_1D_conv_hh(double *xx, double *hh_re, double *hh_im, double *ww);
static double func_1D_gmark(double *xx);
static void dfunc_1D_gmark(double *xx, double *dx);
static double func_1D_mem(double *xx);
static void dfunc_1D_mem(double *xx, double *dx);
static double func_1D_tikho(double *xx);
static void dfunc_1D_tikho(double *xx, double *dx);
static double func_1D_ggauss(double *xx);
static void dfunc_1D_ggauss(double *xx, double *dx);
static double func_1D_sqrtrf(double *xx);
static void dfunc_1D_sqrtrf(double *xx, double *dx);
static double func_1D_banana(double *x);
static void dfunc_1D_banana(double *xx, double *dx);
/*************************************************************
* To display a curve (linear)
**************************************************************/
int dcv_1D_plot1(double *yy1, int nn, char *title)
{
register int i;
char xlabel[40], ylabel[40], plotdev[40];
/* X axis: */
for(i = 1; i <= nn; i++) xx1[i] = (double)i;
strcpy(xlabel," ");
strcpy(ylabel," ");
strcpy(plotdev,"xterm_s");
jlp_display1(xx1, yy1, 1, nn, xlabel, ylabel, title, plotdev);
return(0);
}
/*************************************************************
* To display a curve (semi-log)
**************************************************************/
int dcv_1D_plot1_log(double *yy1, int nn1, char *title)
{
register int i;
/* X axis: */
for(i = 1; i <= nn1; i++) xx1[i] = (double)(i - nn1/2)/ (double)nn1;
/* Y axis: */
for(i = 1; i <= nn1; i++) xx2[i] = MY_LOG10(yy1[i]);
jlp_display1(xx1, xx2, 1, nn1, " ", " ", title, "xterm_s");
return(0);
}
/*************************************************************
* To display two curves (linear)
**************************************************************/
int dcv_1D_plot2(double *yy1, double *yy2, int nn, char *title)
{
register int i;
/* X axis: */
for(i = 1; i <= nn; i++) xx1[i] = (double)i;
jlp_display2(xx1, yy1, 1, nn, xx1, yy2, 1, nn, " ", " ", title, "xterm_s",
"L0", "L1");
return(0);
}
/*************************************************************
* Deconvolution with Gauss-Markov regularisation
* Criterium to minimize is:
* || y - H x ||^2 + alpha Sigma_{k=1}^{k=N} x_k^2
*
* INPUT:
* ftol: tolerance
**************************************************************/
int dcv_1D_gmark(double alpha_0, double ftol, int *iter,
int positive)
{
double fret;
int iter_max = 2000, lbfgs = 0;
register int i;
alpha = alpha_0;
/* Check if gradient is OK */
dcv_1D_check_grad(yyd, func_1D_gmark, dfunc_1D_gmark);
/* Starting point: */
for(i = 1; i <= nn1; i++) yyd[i] = 0.;
jlp_minimize(yyd, nn, nn1, ftol, iter, iter_max, &fret,
func_1D_gmark, dfunc_1D_gmark, positive, lbfgs);
printf(" Number of iterations: %d \n",*iter);
printf(" Value of the minimum: %.5g\n",fret);
/* Pb with last point sometimes, so: */
yyd[nn] = yyd[nn-1];
return(0);
}
/**************************************************************
* Function E to be minimized for Gauss-Markov
* E : value of the criterium in X
* \--- 2
* E = |Y-Ax|^2+ alpha > | x - x |
* /___ i+1 i
* i
*
**************************************************************/
static double func_1D_gmark(double *xx)
{
double sum2_y, sum2_dx;
register int i;
/* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
sum2_y = 0.;
for(i = 1; i <= nn; i++) sum2_y += SQUARE(w0[i] - yy[i]);
/* Bauman & Sauer' function with p=2:
* _
* \ p
* phi = / | x - x |
* - i+1 i
* i
* (Smooth function, which reduces the variation between two successive pixels)
*/
sum2_dx = 0.;
for(i = 2; i <= nn; i++) sum2_dx += SQUARE(xx[i] - xx[i-1]);
return(sum2_y + alpha * sum2_dx);
}
/**************************************************************
* Gradient for Gauss-Markov
* grad_Er : value of the gradient of the criterium in X
* ( \---
* This function returns grad(E) =grad( |Y-Ax|^2+ alpha > phi(Xs-Xr)
* ( /___
* (s,r) in C
*
* d/dx (HX - Y)^T (HX - Y) = 2 H^T (HX - Y)
**************************************************************/
static void dfunc_1D_gmark(double *xx, double *dx)
{
register int i;
/* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
for(i = 1; i <= nn; i++) dx[i] = w0[i] - yy[i];
dcv_1D_conv_hh(dx, hht_re, hht_im, w0);
/* Shift hh_nx pixels to origin,
* since convolution by hht has shifted the input signal by that amount: */
for(i = 1; i <= nn; i++) w0[i] = w0[hh_nx + i - 1];
for(i = nn + 1; i <= nn1; i++) w0[i] = 0.;
/* Gradient of Bauman & Sauer' function with p=2:
* _
* \ 2
* phi = / | x - x |
* - i+1 i
* i
* (Smooth function, which reduces the variation between two successive pixels)
*/
dx[1] = 2. * w0[1] - 2. * alpha * (xx[2]-xx[1]);
for(i = 2; i <= nn - 1; i++)
dx[i] = 2. * w0[i] - 2. * alpha * (xx[i+1]-xx[i])
+ 2. * alpha * (xx[i]-xx[i-1]);
dx[nn] = 2. * w0[nn] + 2. * alpha*(xx[nn]-xx[nn-1]);
}
/**************************************************************
* Deconvolution with MEM
* Criterium to minimize is:
* || y - H x ||^2 + alpha Sigma_{k=1}^{k=N} x_k^2
**************************************************************/
int dcv_1D_mem(double alpha_0, double ftol, int *iter,
int positive)
{
double fret;
int iter_max = 2000, lbfgs = 0;
register int i;
alpha = alpha_0;
/* Check if gradient is OK */
dcv_1D_check_grad(yyd, func_1D_mem, dfunc_1D_mem);
/* Starting point: */
for(i = 1; i <= nn1; i++) yyd[i] = 0.;
jlp_minimize(yyd, nn, nn1, ftol, iter, iter_max, &fret,
func_1D_mem, dfunc_1D_mem, positive, lbfgs);
printf(" Number of iterations: %d \n",*iter);
printf(" Value of the minimum: %.5g\n",fret);
/* Pb with last point sometimes, so: */
yyd[nn] = yyd[nn-1];
return(0);
}
/**************************************************************
* Function E to be minimized for MEM
* E : value of the criterium in X
* \---
* This function returns E = |Y-Ax|^2+ alpha > phi(Xs-Xr)
* /___
* (s,r) in C
*
**************************************************************/
static double func_1D_mem(double *xx)
{
register int i;
double sum2_y, sum_x;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
sum2_y = 0.;
for(i = 1; i <= nn; i++) sum2_y += SQUARE(w0[i] - yy[i]);
/*
* Entropy potential function:
* _
* \
* phi = / x log(x )
* - i i
* i
*
* Penalty of 1000. if negative...
*/
sum_x = 0.;
for(i = 1; i <= nn; i++)
{
if(xx[i] > 0.)
sum_x += xx[i] * log(xx[i]);
else
sum_x += 1000.;
}
return(sum2_y + alpha * sum_x);
}
/**************************************************************
* Gradient for MEM
* grad_Er : value of the gradient of the criterium in X
* ( \---
* This function returns grad(E) =grad( |Y-Ax|^2+ alpha > phi(Xs-Xr)
* ( /___
* (s,r) in C
*
* d/dx (HX - Y)^T (HX - Y) = 2 H^T (HX - Y)
**************************************************************/
static void dfunc_1D_mem(double *xx, double *dx)
{
register int i;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
for(i = 1; i <= nn; i++) dx[i] = w0[i] - yy[i];
dcv_1D_conv_hh(dx, hht_re, hht_im, w0);
/* Shift hh_nx pixels to origin,
* since convolution by hht has shifted the input signal by that amount: */
for(i = 1; i <= nn; i++) w0[i] = w0[hh_nx + i - 1];
for(i = nn + 1; i <= nn1; i++) w0[i] = 0.;
/*
* Gradient de la fonction potentiel entropique
* _
* \
* phi = / x log(x )
* - i i
* => dphi = (1 + log(x)):
*/
for(i = 1; i <= nn; i++)
{
if(xx[i] > 0.)
w1[i] = 1. + log(xx[i]);
else
w1[i] = -1000.;
}
for(i = 1; i <= nn; i++) dx[i] = 2. * w0[i] + alpha * w1[i];
}
/**************************************************************
* Deconvolution by Tikhonov's regularisation
* Criterium to minimize is:
* || y - H x ||^2 + alpha Sigma_{k=1}^{k=N} x_k^2
* (Carfantan: grf)
**************************************************************/
int dcv_1D_tikhonov(double alpha_0, double ftol, int *iter,
int positive)
{
double fret;
int iter_max = 2000, lbfgs = 0;
register int i;
alpha = alpha_0;
/* Check if gradient is OK */
dcv_1D_check_grad(yyd, func_1D_tikho, dfunc_1D_tikho);
/* Starting point: */
for(i = 1; i <= nn; i++) yyd[i] = 0.;
jlp_minimize(yyd, nn, nn1, ftol, iter, iter_max, &fret,
func_1D_tikho, dfunc_1D_tikho, positive, lbfgs);
printf(" Number of iterations: %d \n",*iter);
printf(" Value of the minimum: %.5g\n",fret);
/* Pb with last point sometimes, so: */
yyd[nn] = yyd[nn-1];
return(0);
}
/**************************************************************
* Function E to be minimized for Tikhonov's regularisation:
* E : value of the criterium in X
* \---
* This funtion returns E = |Y-Ax|^2+ alpha > phi(Xs-Xr)
* /___
* (s,r) in C
*
**************************************************************/
static double func_1D_tikho(double *xx)
{
register int i;
double sum2_y, sum_x;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
sum2_y = 0.;
for(i = 1; i <= nn; i++) sum2_y += SQUARE(w0[i] - yy[i]);
/*
* Bauman & Sauer's potential function, with p=2
* _
* \ p
* phi = / | x |
* - i
* i
* phi = sum(abs(real(x(:))).^p);
* dphi = p*sign(x).*(abs(real(x)).^(p-1));
*/
sum_x = 0.;
for(i = 1; i <= nn; i++) sum_x += SQUARE(xx[i]);
return(sum2_y + alpha * sum_x);
}
/**************************************************************
* Gradient for Tikhonov's regularisation:
* grad_Er : value of the gradient of the criterium in X
* ( \---
* This funtion returns grad(E) =grad( |Y-Ax|^2+ alpha > phi(Xs-Xr)
* ( /___
* (s,r) in C
*
* d/dx (HX - Y)^T (HX - Y) = 2 H^T (HX - Y)
**************************************************************/
static void dfunc_1D_tikho(double *xx, double *dx)
{
register int i;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
for(i = 1; i <= nn; i++) dx[i] = w0[i] - yy[i];
dcv_1D_conv_hh(dx, hht_re, hht_im, w0);
/* Shift hh_nx pixels to origin,
* since convolution by hht has shifted the input signal by that amount: */
for(i = 1; i <= nn; i++) w0[i] = w0[hh_nx + i - 1];
for(i = nn + 1; i <= nn1; i++) w0[i] = 0.;
/*
* Bauman & Sauer's potential function, with p=2
* _
* \ p
* phi = / | x |
* - i
* i
* dphi = p*sign(x).*(abs(real(x)).^(p-1));
* here: dphi = 2 x
*/
for(i = 1; i <= nn; i++) dx[i] = 2. * w0[i] + 2. * alpha * xx[i];
}
/**************************************************************
* Deconvolution by generalized Gauss' regularisation
* Criterium to minimize is:
* || y - H x ||^2 + alpha Sigma_{k=1}^{k=N} x_k^p
* with p=1.1
* (Carfantan: ggrf)
**************************************************************/
int dcv_1D_ggauss(double alpha_0, double ftol, int *iter,
int positive)
{
double fret;
int iter_max = 2000, lbfgs = 0;
register int i;
alpha = alpha_0;
/* Check if gradient is OK */
dcv_1D_check_grad(yyd, func_1D_ggauss, dfunc_1D_ggauss);
/* Starting point: */
for(i = 1; i <= nn; i++) yyd[i] = 0.;
jlp_minimize(yyd, nn, nn1, ftol, iter, iter_max, &fret,
func_1D_ggauss, dfunc_1D_ggauss, positive, lbfgs);
printf(" Number of iterations: %d \n",*iter);
printf(" Value of the minimum: %.5g\n",fret);
/* Pb with last point sometimes, so: */
yyd[nn] = yyd[nn-1];
return(0);
}
/**************************************************************
* Function E to be minimized for generalized Gauss' regularisation:
* E : value of the criterium in X
* \---
* This function returns E = |Y-Ax|^2+ alpha > phi(Xs-Xr)
* /___
* (s,r) in C
*
**************************************************************/
static double func_1D_ggauss(double *xx)
{
register int i;
double sum2_y, sum_x;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
sum2_y = 0.;
for(i = 1; i <= nn; i++) sum2_y += SQUARE(w0[i] - yy[i]);
/*
* Bauman & Sauer's potential function, with p=1.1
* _
* \ p
* phi = / | x |
* - i
* i
* phi = sum(abs(real(x(:))).^p);
* dphi = p*sign(x).*(abs(real(x)).^(p-1));
*/
sum_x = 0.;
for(i = 1; i <= nn; i++) sum_x += pow(ABS(xx[i]),1.1);
return(sum2_y + alpha * sum_x);
}
/**************************************************************
* Gradient for generalized Gauss' regularisation:
* grad_Er : value of the gradient of the criterium in X
* ( \---
* This function returns grad(E) =grad( |Y-Ax|^2+ alpha > phi(Xs-Xr)
* ( /___
* (s,r) in C
*
* d/dx (HX - Y)^T (HX - Y) = 2 H^T (HX - Y)
**************************************************************/
static void dfunc_1D_ggauss(double *xx, double *dx)
{
register int i;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
for(i = 1; i <= nn; i++) dx[i] = w0[i] - yy[i];
dcv_1D_conv_hh(dx, hht_re, hht_im, w0);
/* Shift hh_nx pixels to origin,
* since convolution by hht has shifted the input signal by that amount: */
for(i = 1; i <= nn; i++) w0[i] = w0[hh_nx + i - 1];
for(i = nn + 1; i <= nn1; i++) w0[i] = 0.;
/*
* Bauman & Sauer's potential function, with p=1.1
* _
* \ p
* phi = / | x |
* - i
* i
* dphi = p*sign(x).*(abs(real(x)).^(p-1));
* here: dphi = 1.1 x**0.1
*/
for(i = 1; i <= nn; i++)
{
if(xx[i] > 0.)
w1[i] = pow(xx[i],0.1);
else
w1[i] = - pow(-xx[i],0.1);
}
for(i = 1; i <= nn; i++) dx[i] = 2. * w0[i] + 1.1 * alpha * w1[i];
}
/**************************************************************
* Deconvolution by generalized Gauss' regularisation
* Criterium to minimize is:
* || y - H x ||^2 + alpha phi
* with:
* _ __________
* \ / 2 2 |
* phi = / \ / ss + x
* - \/ i
* i
*
* ss is the level which is a kind of (intensity) threshold
* between "good signal" and "medium" or "bad" signal
* (penalty is less severe than tikhonov, for intensities > ss)
**************************************************************/
int dcv_1D_sqrtrf(double alpha_0, double ss, double ftol, int *iter,
int positive)
{
register int i;
int iter_max = 2000, lbfgs = 0;
double fret;
alpha = alpha_0;
/*
* Set ss2 (private parameter) to the value chosen when calling the routine:
*/
ss2 = ss*ss;
/* Check if gradient is OK */
dcv_1D_check_grad(yyd, func_1D_sqrtrf, dfunc_1D_sqrtrf);
/* Starting point: */
for(i = 1; i <= nn; i++) yyd[i] = 0.;
jlp_minimize(yyd, nn, nn1, ftol, iter, iter_max, &fret,
func_1D_sqrtrf, dfunc_1D_sqrtrf, positive, lbfgs);
printf(" Number of iterations: %d \n",*iter);
printf(" Value of the minimum: %.5g\n",fret);
/* Pb with last point sometimes, so: */
yyd[nn] = yyd[nn-1];
printf(" alpha=%f ss=%f \n",alpha_0, sqrt(ss2));
return(0);
}
/**************************************************************
* Function E to be minimized for convex sqrt(s^2+x^2) regularisation:
* E : value of the criterium in X
*
* This function returns E = |Y-Ax|^2+ alpha phi
*
* with:
* _ __________
* \ / 2 2 |
* phi = / \ / ss + x
* - \/ i
* i
* (Carfantan: sqrtrf, with ss=0.01 or ss=0.001)
**************************************************************/
static double func_1D_sqrtrf(double *xx)
{
double sum2_y, sum_x;
register int i;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
sum2_y = 0.;
for(i = 1; i <= nn; i++) sum2_y += SQUARE(w0[i] - yy[i]);
sum_x = 0.;
for(i = 1; i <= nn; i++) sum_x += sqrt(ss2 + SQUARE(xx[i]));
return(sum2_y + alpha * sum_x);
}
/**************************************************************
* Gradient for convex sqrt(s^2+x^2) regularisation:
* grad_Er : value of the gradient of the criterium in X
*
* This function returns grad(E) =grad( |Y-Ax|^2+ alpha phi )
*
* with:
* _ __________
* \ / 2 2 |
* phi = / \ / ss + x
* - \/ i
* i
* (Carfantan: sqrtrf, with ss=0.01 or ss=0.001)
*
* d/dx (HX - Y)^T (HX - Y) = 2 H^T (HX - Y)
**************************************************************/
static void dfunc_1D_sqrtrf(double *xx, double *dx)
{
register int i;
/*
* Convolution = product in Fourier domain:
* w0 = conv(xx,hh):
*/
dcv_1D_conv_hh(xx, hh_re, hh_im, w0);
for(i = 1; i <= nn; i++) dx[i] = w0[i] - yy[i];
dcv_1D_conv_hh(dx, hht_re, hht_im, w0);
/* Shift hh_nx pixels to origin,
* since convolution by hht has shifted the input signal by that amount: */
for(i = 1; i <= nn; i++) w0[i] = w0[hh_nx + i - 1];
for(i = nn + 1; i <= nn1; i++) w0[i] = 0.;
for(i = 1; i <= nn; i++)
dx[i] = 2. * w0[i] + alpha * xx[i] / sqrt(ss2 + xx[i]*xx[i]);
}
/**************************************************************
* Banana function : start at X=[-1.9;2]. minimum at X=[1;1] : f(X)=0;
* z = 100*(x(2)^2-x(1))^2 + (1-x(1))^2
* dx = [ -200*(x(2)^2 - x(1))-2*(1-x(1)) ]
[ 100*(4 * x(2)^3 - 4 x(1))*x(2) ]
*
**************************************************************/
int dcv_1D_banana(double ftol)
{
int n=2, iter;
int positive = 0;
int iter_max = 2000, lbfgs = 0;
double p[3], fret;
printf("Test with Banana function\n");
/* Starting point: */
p[1]= -1.9;
p[2]= 2.;
jlp_minimize(p, n, n, ftol, &iter, iter_max, &fret,
func_1D_banana, dfunc_1D_banana, positive, lbfgs);
printf(" Location of the minimum: %.3f %.3f\n", p[1], p[2]);
printf(" Number of iterations: %d\n",iter);
printf(" Value of the minimum: %.5e\n",fret);
return(0);
}
/**********************************************************
* Banana function:
* z = 100*(x(2)^2-x(1))^2 + (1-x(1))^2
**********************************************************/
static double func_1D_banana(double *x)
{
return(SQUARE(1. - x[1]) + 100. * SQUARE(SQUARE(x[2]) - x[1]));
}
/**********************************************************
* Banana function:
* dx = [ -200*(x(2)^2 - x(1))-2*(1-x(1)) ]
[ 100*(4 * x(2)^3 - 4 x(1))*x(2) ]
**********************************************************/
static void dfunc_1D_banana(double *x, double *dx)
{
dx[1] = -200. * (SQUARE(x[2]) - x[1]) - 2. * (1. - x[1]);
dx[2] = 400. * (x[2]*x[2]*x[2] - x[1] * x[2]);
}
/**************************************************************
* Deconvolution by Wiener filter
**************************************************************/
int dcv_1D_wiener(double alpha_0)
{
register int i;
alpha = alpha_0;
/* Compute FFT of signal: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = yy[i];
c_im(cp0[i]) = 0.;
}
fftw_fast(&cp0[1], nn1, 1, 1);
for(i = 1; i <= nn1; i++) {
yy_re[i] = c_re(cp0[i]);
yy_im[i] = c_im(cp0[i]);
}
/* Compute square modulus of transfer function: */
for(i = 1; i <= nn1; i++)
w0[i] = SQUARE(hh_re[i]) + SQUARE(hh_im[i]);
/****************************************
* 1/(a+ib) = (a-ib)/(a2+b2)
* Wiener filter = ((a2+b2) / ((a2+b2) + alpha)) / (a+ib)
* Hence: = (a-ib) / ((a2+b2) + alpha))
****************************************/
for(i = 1; i <= nn1; i++) {w_re[i] = 0.; w_im[i] = 0.;}
for(i = 1; i <= nn1; i++)
if((w0[i] + alpha) != 0.){
w_re[i] = hh_re[i] / (w0[i] + alpha);
w_im[i] = - hh_im[i] / (w0[i] + alpha);
}
/* Plot Wiener filter: */
if(0){
printf(" Display Wiener filter\n");
for(i = 1; i <= nn1; i++) w1[i] = SQUARE(w_re[i]) + SQUARE(w_im[i]);
dcv_1D_plot1_log(w1, nn1, "Wiener filter");
}
/* Deconvolution: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = w_re[i] * yy_re[i] - w_im[i] * yy_im[i];
c_im(cp0[i]) = w_re[i] * yy_im[i] + w_im[i] * yy_re[i];
}
fftw_fast(&cp0[1], nn1, 1, -1);
for(i = 1; i <= nn; i++) yyd[i] = c_re(cp0[i]);
for(i = nn+1; i <= nn1; i++) yyd[i] = 0.;
return(0);
}
/**************************************************************
* Deconvolution by spectral division
**************************************************************/
int dcv_1D_spdiv()
{
register int i;
/* Compute FFT of signal: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = yy[i];
c_im(cp0[i]) = 0.;
}
fftw_fast(&cp0[1], nn1, 1, 1);
for(i = 1; i <= nn1; i++) {
yy_re[i] = c_re(cp0[i]);
yy_im[i] = c_im(cp0[i]);
}
/* Compute square modulus of transfer function: */
for(i = 1; i <= nn1; i++)
w0[i] = SQUARE(hh_re[i]) + SQUARE(hh_im[i]);
/* 1/(a+ib) = (a-ib)/(a2+b2)
*/
for(i = 1; i <= nn1; i++) {w_re[i] = 0.; w_im[i] = 0.;}
for(i = 1; i <= nn1; i++)
if(w0[i] != 0.)
{
w_re[i] = hh_re[i] / w0[i];
w_im[i] = - hh_im[i] / w0[i];
}
/* Plot inverse filter: */
if(1){
printf(" Display inverse filter\n");
for(i = 1; i <= nn1; i++) w1[i] = SQUARE(w_re[i]) + SQUARE(w_im[i]);
dcv_1D_plot1_log(w1, nn1, "Inverse filter");
}
/* Deconvolution: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = w_re[i] * yy_re[i] - w_im[i] * yy_im[i];
c_im(cp0[i]) = w_re[i] * yy_im[i] + w_im[i] * yy_re[i];
}
fftw_fast(&cp0[1], nn1, 1, -1);
for(i = 1; i <= nn; i++) yyd[i] = c_re(cp0[i]);
for(i = nn+1; i <= nn1; i++) yyd[i] = 0.;
return(0);
}
/**************************************************************
* Display input files (to check if OK)
**************************************************************/
int dcv_1D_display_input(int nn)
{
INT4 nx, ny;
int display_all = 1;
register int i;
char title[40];
/* Display original signal: */
if(display_all){
printf("Display original signal:\n");
strcpy(title,"Original signal");
dcv_1D_plot1(yy0, nn, title);
}
/* Display noisy signal to deconvolve: */
if(display_all){
printf("Display noisy signal to deconvolve:\n");
strcpy(title,"Noisy signal to deconvolve");
dcv_1D_plot1(yy, nn, title);
}
/* Compute power spectrum of original signal: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = yy0[i];
c_im(cp0[i]) = 0.;
}
fftw_fast(&cp0[1], nn1, 1, 1);
for(i = 1; i <= nn1; i++) {
w0[i] = SQUARE(c_re(cp0[i])) + SQUARE(c_im(cp0[i]));
}
nx = nn1; ny = 1;
RECENT_FFT_1D_X(&w0[1], &w0[1], &nx, &ny, &nx);
printf("nn1 = %d\n", nn1);
/* Display power spectrum of original signal: */
if(display_all){
printf("Display power spectrum of original signal: \n");
strcpy(title,"Power spectrum of original signal");
dcv_1D_plot1_log(w0, nn1, title);
}
/* Compute square modulus of transfer function: */
for(i = 1; i <= nn1; i++)
w0[i] = SQUARE(hh_re[i]) + SQUARE(hh_im[i]);
nx = nn1; ny = 1;
RECENT_FFT_1D_X(&w0[1], &w0[1], &nx, &ny, &nx);
/* Display Transfer function: */
if(display_all){
printf("Frequency response of the filter:\n");
strcpy(title,"Frequency response of the filter");
dcv_1D_plot1_log(w0, nn1, title);
}
return(0);
}
/**************************************************************
* Convolution H*X : w0 = conv(xx,hh)
*
* IN:
* xx: function to be convolved by hh
* hh_re, hh_im: TF of hh
*
* OUT:
* ww = conv(hh,xx) WARNING: often ww=w0 in the calling program...
*
**************************************************************/
static int dcv_1D_conv_hh(double *xx, double *hh_re, double *hh_im, double *ww)
{
register int i;
/* Just in case: */
for(i = nn+1; i <= nn1; i++) xx[i] = 0.;
/* Compute FFT of xx: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = xx[i];
c_im(cp0[i]) = 0.;
}
fftw_fast(&cp0[1], nn1, 1, 1);
/* Product in Fourier domain: */
for(i = 1; i <= nn1; i++)
{
w_re[i] = c_re(cp0[i]) * hh_re[i] - c_im(cp0[i]) * hh_im[i];
w_im[i] = c_re(cp0[i]) * hh_im[i] + c_im(cp0[i]) * hh_re[i];
}
/* Back to direct space: */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = w_re[i];
c_im(cp0[i]) = w_im[i];
}
fftw_fast(&cp0[1], nn1, 1, -1);
for(i = 1; i <= nn1; i++) ww[i] = c_re(cp0[i]);
return(0);
}
/**************************************************************
* Check the validity of the gradient
* and compare f(x+dx)-f(x)/dx with grad_f(x)
*
* x1: work space of dimension nn
**************************************************************/
static int dcv_1D_check_grad(double *x1, double (*func)(double []),
void (*dfunc)(double[], double[]))
{
register int i, j;
double eps=1.e-4, tolerance=1.e-4;
double f_xx1,f_x1,error;
/* Generate random vector (between 0 and 1) */
for(i = 1; i <= nn1; i++) x1[i] = 0.;
for(i = 1; i <= nn; i++) x1[i] = (double)rand() / (double)RAND_MAX;
for(i = 1; i <= nn1; i++) xx1[i] = 0.;
f_x1 = (*func)(x1);
/* Loop on all components: */
for(i = 1; i <= nn; i++)
{
for(j = 1; j <= nn; j++) xx1[j] = x1[j];
/* Small variation of component #i: */
xx1[i] = x1[i] + eps;
f_xx1 = (*func)(xx1);
/* Gradient stored in xx2: */
(*dfunc)(xx1,xx2);
error = (f_xx1 - f_x1)/eps - xx2[i];
error = error / (ABS(f_xx1 - f_x1)/eps + 1.e-12);
#ifdef DEBUG
if(i < 10)
printf(" f_x1=%e f_xx1=%e (f_xx1-f_x1)/eps = %e dx[%d] = %e error=%e\n",
f_x1, f_xx1, (f_xx1 - f_x1)/eps, i, xx2[i], error);
#endif
if(error > tolerance) {
printf("dcv_1D_check_grad/Error! \n");
printf("component #i=%d: relative error =%.4e\n", i, error);
}
}
printf("dcv_1D_check_grad/End: gradient has been checked.\n");
return(0);
}
/***********************************************************************
* To initialize all static (private) arrays
*
* xx1, xx2: arrays used by dcv_1D_plot1, dcv_1D_plot_log, dcv_1D_plot2
* and check_grad
***********************************************************************/
int dcv_1D_init(int nn1_0, int nn_0, int hh_nx_0)
{
int idim;
/* Transfer to static variables: */
nn1 = nn1_0;
nn = nn_0;
hh_nx = hh_nx_0;
/* Allocation of memory space: */
idim = nn1+1;
if( (yy = (double *)malloc(idim * sizeof(double))) == NULL
|| (yy0 = (double *)malloc(idim * sizeof(double))) == NULL
|| (yyd = (double *)malloc(idim * sizeof(double))) == NULL
|| (yy_re = (double *)malloc(idim * sizeof(double))) == NULL
|| (yy_im = (double *)malloc(idim * sizeof(double))) == NULL
|| (hh_re = (double *)malloc(idim * sizeof(double))) == NULL
|| (hh_im = (double *)malloc(idim * sizeof(double))) == NULL
|| (hht_re = (double *)malloc(idim * sizeof(double))) == NULL
|| (hht_im = (double *)malloc(idim * sizeof(double))) == NULL
|| (w_re = (double *)malloc(idim * sizeof(double))) == NULL
|| (w_im = (double *)malloc(idim * sizeof(double))) == NULL
|| (xx1 = (double *)malloc(idim * sizeof(double))) == NULL
|| (xx2 = (double *)malloc(idim * sizeof(double))) == NULL
|| (w0 = (double *)malloc(idim * sizeof(double))) == NULL
|| (w1 = (double *)malloc(idim * sizeof(double))) == NULL
|| (cp0 = (FFTW_COMPLEX *) malloc(idim * sizeof(FFTW_COMPLEX))) == NULL)
{
printf("dcv_1D_init/Fatal error allocating memory space: idim=%d\n",idim);
exit(-1);
}
/* To prepare fast FFT's: */
printf(" fftw_setup with (%d,1)\n", nn1);
fftw_setup(nn1,1);
return(0);
}
/************************************************************
* To free memory
************************************************************/
void dcv_1D_free()
{
free(yy);
free(yy0);
free(yyd);
free(yy_re);
free(yy_im);
free(hh_re);
free(hh_im);
free(hht_re);
free(hht_im);
free(w_re);
free(w_im);
free(xx1);
free(xx2);
free(w0);
free(w1);
FFTW_SHUTDOWN();
return;
}
/*************************************************************
* Compute transfer function:
**************************************************************/
int dcv_1D_transfert(double *hh)
{
register int i;
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = hh[i];
c_im(cp0[i]) = 0.;
}
fftw_fast(&cp0[1], nn1, 1, 1);
for(i = 1; i <= nn1; i++) {
hh_re[i] = c_re(cp0[i]);
hh_im[i] = c_im(cp0[i]);
}
/* Compute FFT function of reversed PSF (i.e., PSF(-x)):
* Length of the support of hh is hh_nx */
for(i = 1; i <= nn1; i++) {
c_re(cp0[i]) = 0.;
c_im(cp0[i]) = 0.;
}
for(i = 1; i <= hh_nx; i++)
c_re(cp0[i]) = hh[hh_nx - i + 1];
fftw_fast(&cp0[1], nn1, 1, 1);
for(i = 1; i <= nn1; i++) {
hht_re[i] = c_re(cp0[i]);
hht_im[i] = c_im(cp0[i]);
}
return(0);
}
| 28.635701 | 83 | 0.479931 | [
"vector"
] |
01bddcec0906fcdc8d064635b080a237956057a3 | 6,309 | h | C | include/iris/sensor-api/iris/drivers/serial/SerialDriver.h | LESA-RPI/irma_ground_truth | 94037de5c7877544738d3569f11f900ba919227e | [
"BSL-1.0"
] | 1 | 2018-06-18T18:08:38.000Z | 2018-06-18T18:08:38.000Z | include/iris/sensor-api/iris/drivers/serial/SerialDriver.h | duffym4/tof_control | 418714fb29900ce7fdd4ba0bed9105b0c3d623a7 | [
"BSL-1.0"
] | null | null | null | include/iris/sensor-api/iris/drivers/serial/SerialDriver.h | duffym4/tof_control | 418714fb29900ce7fdd4ba0bed9105b0c3d623a7 | [
"BSL-1.0"
] | 2 | 2018-11-21T17:15:24.000Z | 2019-09-29T02:46:30.000Z | // ***************************************************************************
// * _ _ ____ _ ____ ___ *
// * (_)_ __(_)___ / ___| ___ _ __ ___ ___ _ __ / \ | _ \_ _| *
// * | | '__| / __| \___ \ / _ \ '_ \/ __|/ _ \| '__| / _ \ | |_) | | *
// * | | | | \__ \ ___) | __/ | | \__ \ (_) | | / ___ \| __/| | *
// * |_|_| |_|___/ |____/ \___|_| |_|___/\___/|_| /_/ \_\_| |___| *
// * *
// * Copyright (c) 2010 by iris-GmbH, Berlin All rights reserved *
// * *
// ***************************************************************************
// ---------------------------------------------------------------------------
// Please refer to LICENSE.TXT for more information on copyright and licensing
// terms with respect to this library and its source codes.
// ---------------------------------------------------------------------------
#ifndef DRIVERS_SERIAL_SERIALDRIVER_H
#define DRIVERS_SERIAL_SERIALDRIVER_H
// workaround for win32: needs to be first include
#if defined(__WIN32) || defined(_WIN32)
#include <winsock2.h>
#endif
// boost includes
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
// iris includes
#include "iris/drivers/Driver.h"
#include "iris/synchronization/Event.h"
#include "iris/synchronization/Mutex.h"
namespace iris {
namespace drivers {
namespace serial {
// internal class forward
class UipCommunicator;
class SENSORAPI SerialDriver: public iris::drivers::Driver {
public:
/**
* Holds the UIP communicator object
*/
UipCommunicator* communicator;
/**
* boost ioservice instance
*/
boost::asio::io_service *ios_;
/**
* boost port instance
*/
boost::asio::serial_port *port_;
/**
* boost deadline timer instance
*/
boost::asio::deadline_timer *dlt_;
/**
* Raw (bytes) reception buffer for serial datagrams
*/
char receiveBuffer[2000];
/**
* Variable holding the actual reception length
*/
int receiveLength;
/**
* Holds a list containing the scanned sensor addresses
*/
mutable AddressList scanList;
/**
* Defines a list of UIP addresses
*/
typedef std::list<unsigned char> UipAddressList;
/**
* Holds a list containing the scanned gateways' UIP addresses
*/
mutable UipAddressList gateways;
/**
* Holds a list of gateway UIP addresses to be tested during scan
*/
UipAddressList gatewaysOfInterest;
/**
* Flag indicating whether the gateway scan is stopped at the first
* unsuccessful address
*/
bool stopScanAtTimeout;
/**
* Holds the receive thread instance
*/
mutable boost::thread* t;
typedef std::list<boost::asio::ip::address_v4> BroadcastAddressList;
BroadcastAddressList broadcastAddresses;
iris::synchronization::Event* scanEvent;
unsigned char senderAddress;
public:
static const std::string PortNameOptionName;
static const std::string IbisSwitchOptionName;
static const std::string IbisSpeedOptionName;
static const std::string IbisBvgOptionName;
static const std::string Ibis8n1OptionName;
/**
* Constructor
*/
SerialDriver();
/**
* Destructor
*/
virtual ~SerialDriver();
/**
* Returns the list of all sensors addresses that can currently be found
*
* @return Address list (without URL prefix and :// separator)
*/
AddressList performAddressScan(void* userData = 0, SCAN_CALLBACK callback = 0) const;
/**
* Sends the given message
*
* @param level UIP level (0..2)
* @param addr Sensor address
* @param message Message to be sent
*/
void sendMessage(const int level, const std::string& addr,
const UipMessage* message) const;
/**
* Sends the given message in broadcast mode
*
* @param level UIP level (0..2)
* @param message Message to be sent
*/
void sendBroadcastMessage(const int level, const UipMessage* message) const;
/**
* Initiates a new receive process on the port
*/
void request_receive(void);
/**
* Callback method for successful or failed reception processes
*
* @param error Success/error code
* @param bytes_transferred Byte size of received packet
*/
void handle_receive(const boost::system::error_code& error,
std::size_t bytes_transferred);
/**
* Initializes the driver
*/
void startupDriver(void);
/**
* Deinitializes the driver
*/
void shutdownDriver(void);
/**
* Implements a reception thread
*/
class ReceiveThread {
/**
* Holds the corresponding SerialDriver instance
*/
SerialDriver* md;
public:
/**
* Constructor
*
* @param md Corresponding UdpDriver instance
*/
ReceiveThread(SerialDriver* md);
/**
* Execution method (boost functor)
*/
void operator()();
}; // class ReceiveThread
iris::synchronization::Mutex mutex;
iris::synchronization::Event started;
bool waitForStart(int timeoutMs);
void signalStart(void);
void sendIbisSwitch(unsigned char gwAddr) const;
/**
* Sets the UIP address of the sender.
*
* @param addr UIP address between 240 and 254.
*/
void setSenderAddress(unsigned char addr);
protected:
void messageCallback(int level, const std::string& addr, UipMessage* message);
friend class UipCommunicator;
static volatile bool finished;
bool supportsParallelAccess(void) const;
}; // class SerialDriver
} // namespace serial
} // namespace drivers
} // namespace iris
#endif // DRIVERS_SERIAL_SERIALDRIVER_H
| 25.337349 | 90 | 0.549215 | [
"object"
] |
01c18c73a821425567b9cfa26be95b653c83be06 | 1,171 | h | C | boxtarget.h | navinsoni/Contra_2D_Game_in_CPP_with_Design_Patterns | f7953b36c7d4ecb0d92c66ac24e8169df9e3e0ad | [
"MIT"
] | 2 | 2018-04-07T11:36:05.000Z | 2020-10-17T14:33:36.000Z | boxtarget.h | navinsoni/Contra_2D_Game_in_CPP_with_Design_Patterns | f7953b36c7d4ecb0d92c66ac24e8169df9e3e0ad | [
"MIT"
] | null | null | null | boxtarget.h | navinsoni/Contra_2D_Game_in_CPP_with_Design_Patterns | f7953b36c7d4ecb0d92c66ac24e8169df9e3e0ad | [
"MIT"
] | null | null | null | #ifndef BOXTARGET__H
#define BOXTARGET__H
#include <string>
#include <iostream>
#include "multiframesprite.h"
#include "frame.h"
#include "framefactory.h"
#include "bullets.h"
#include "bullet.h"
using std::string;
class BoxTarget : public MultiFrameSprite {
public:
BoxTarget(const string& n,const string& no);
BoxTarget(const BoxTarget& s);
virtual ~BoxTarget() { }
BoxTarget& operator=(const BoxTarget&);
virtual void update(Uint32 ticks);
void setUp(bool u) { upp = u; }
bool getUp() const { return upp; }
void setDown(bool d) { downn = d; }
bool getDown() const { return downn; }
private:
bool upp;
bool downn;
float dt;
int strength;
string power;
string offset;
Vector2f bulletDirection;
std::vector<Frame*> up;
std::vector<Frame*> rup30;
std::vector<Frame*> lup30;
std::vector<Frame*> rup60;
std::vector<Frame*> lup60;
std::vector<Frame*> rnormal;
std::vector<Frame*> lnormal;
std::vector<Frame*> rdown60;
std::vector<Frame*> ldown60;
std::vector<Frame*> rdown30;
std::vector<Frame*> ldown30;
std::vector<Frame*> down;
void normal(Uint32 ticks);
void fire(string& power,string& offset);
};
#endif
| 22.960784 | 46 | 0.690863 | [
"vector"
] |
01c3c4aa590b1feb80c3ef5b7f7b6f6a09e09e23 | 2,957 | c | C | C-Codes/FrictionLaws/Lib_NewmarkTS.c | Nicolucas/C-Scripts | 2608df5c2e635ad16f422877ff440af69f98f960 | [
"MIT"
] | 1 | 2020-02-25T08:05:13.000Z | 2020-02-25T08:05:13.000Z | C-Codes/FrictionLaws/Lib_NewmarkTS.c | Nicolucas/C-Scripts | 2608df5c2e635ad16f422877ff440af69f98f960 | [
"MIT"
] | null | null | null | C-Codes/FrictionLaws/Lib_NewmarkTS.c | Nicolucas/C-Scripts | 2608df5c2e635ad16f422877ff440af69f98f960 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include "Lib_SetOfFrictionLaws.h"
#include "Lib_NewmarkTS.h"
/**PartialUpScalar
* Partial update for half timestep of a Scalar variable
*/
void PartialUpScalar(double ScalarIn, double *ScalarHalf, double TimeStep, double ScalarDot)
{
ScalarHalf[0] = ScalarIn + 0.5*TimeStep*ScalarDot;
}
/**PartialUpVector
* Partial update for half timestep of a 2D vector variable
*/
void PartialUpVector(double VectIn[], double VectHalf[], double TimeStep, double VectDot[])
{
VectHalf[0] = VectIn[0] + 0.5*TimeStep*VectDot[0];
VectHalf[1] = VectIn[1] + 0.5*TimeStep*VectDot[1];
}
/**CalcSigmaComponent
* Calculate the 2D sigma component:
* Sigma_n1n2 = \sigma_ij * n1_ij * n2_ij
*/
void CalcSigmaComponent(double Sigma[],double n_i[], double n_j[], double *SigmaScalar)
{
SigmaScalar[0] = Sigma[0]*n_i[0]*n_j[0] + Sigma[1]*n_i[1]*n_j[1] + Sigma[2]*n_i[1]*n_j[0] + Sigma[2]*n_i[0]*n_j[1];
}
/**CompTauCritic
* Calculate the Critical Shear Stress from the normal component of the stress \sigma_n
* - Checks for positive SlipRate, Slip, and Theta, otherwise it throws an error
* - Checks for negative Sigma_N, if positive it leaves Tau_c = 0
*/
void GetFricValue(double Slip, double SlipDot, double Theta,\
double ListOfParameters[], int FricFuncNo, double *Friction)
{
if (FricFuncNo == 0) // 0 -> LSW
{
FricSW(Friction, ListOfParameters[5], ListOfParameters[6], ListOfParameters[7], Slip);
} else if (FricFuncNo == 1) { // 1 -> VW
printf("VW Not Implemented\n");
} else { // 2 -> RSF
FricRS(Friction, SlipDot, Theta, ListOfParameters);
}
}
void CompTauCritic(double Sigma[], double n[], double *TauC, double Friction)
{
double SigmaN;
CalcSigmaComponent(Sigma, n, n, &SigmaN);
TauC[0] = 0.0;
if(SigmaN < 0.0)
{
TauC[0] = - SigmaN * Friction;
}
}
/**GetFaultTraction
* Calculate the Fault traction component T and compare with the critical shear traction Tau_c.
* The comparison sets a boolean variable true in case of higher T than Tau_c.
*/
void GetFaultTraction(double Sigma[],double n_T[], double n[], double TauC, double *Traction, bool *UpStress)
{
CalcSigmaComponent(Sigma, n_T, n, &Traction[0]);
UpStress[0] = false;
if (fabs(Traction[0]) > fabs(TauC))
{
UpStress[0] = true;
}
}
/**GetSlipFromTraction
* Calculates a new Slip if a boolean is set to True
*/
void GetSlipFromTraction(double delta, double G, bool UpStress, double Traction, double TauC, double OldSlip, double *NewSlip)
{
if (UpStress)
{
NewSlip[0] = OldSlip + (Traction - TauC) * delta / G;
}
else
{
NewSlip[0] = OldSlip;
}
}
/** GetSlipRate
* Calculates a slip rate from a change in slip in a half timestep
*/
void GetSlipRate(double OldSlip, double Slip, double TimeStep, double *SlipRate)
{
SlipRate[0] = 2.0 * (Slip - OldSlip) / TimeStep;
}
| 29.57 | 126 | 0.668583 | [
"vector"
] |
01c5bf025b779e3a17c81cb74b601b432278dad9 | 1,804 | h | C | Portal Seekers Game Client/Network/TCPServerConnection.h | pedroalmeida-dev/Student-Projects | 476db403ec72a0dcde2e7061062f35ecf94a42ed | [
"MIT"
] | null | null | null | Portal Seekers Game Client/Network/TCPServerConnection.h | pedroalmeida-dev/Student-Projects | 476db403ec72a0dcde2e7061062f35ecf94a42ed | [
"MIT"
] | null | null | null | Portal Seekers Game Client/Network/TCPServerConnection.h | pedroalmeida-dev/Student-Projects | 476db403ec72a0dcde2e7061062f35ecf94a42ed | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#pragma comment(lib, "Ws2_32.lib")
#include<stdio.h>
#include <string>
#include <vector>
#include <winsock2.h>
#include <Ws2tcpip.h>
#define DEFAULT_BUFLEN 512
/**
* Responsible to create the connection with the server
* Uses the Winsock library
*/
class TCPServerConnection
{
public:
TCPServerConnection(char* _servername, int _serverPort, int _localPort);
~TCPServerConnection();
//Getter Method for the socket created that is used in the connection
SOCKET* GetSocket();
//Encapsulation of Winsock Receive method
int Receive(char** OutMessage);
//Encapsulation of Winsock Send method
int Send(char* Message);
//Initializes Winsock
char* InitializeWinsock();
//Create Socket
char* CreateSocket();
//Connect to server
char* Connect();
//Give the communication local port a static value (important for debug in the same computer)
int BindLocalPort();
//States if connection is established with the server
bool* IsConnected();
//Retrives all the local addresses that this client onws
char* GetLocalAddresses();
//Getter for the port number of this client
int GetLocalPort();
private:
//Shuts down the connection
void Shutdown();
//Referent to the socket used to communicate with the server
SOCKET conn_socket;
//Addresses
struct sockaddr_in serverAddress, localAddress;
//Name of the server
char* servername;
//Port of the Server to connect with
int serverPort;
//Local Port
int localPort;
//Option used in setsockopt()
int opt = 1;
//Buffer Lenght
int bufferLen = DEFAULT_BUFLEN;
//Char Buffer
char buffer[DEFAULT_BUFLEN];
//Error Code resulting from the winsock methods
int iResult = 0;
//States if the connection is active
bool m_isConnected = false;
};
| 26.529412 | 95 | 0.752772 | [
"vector"
] |
01ccff2376b14cb172cb7eee4984b57c01449a1f | 470 | h | C | atom/VectorStorage.h | pixelsquare/pacman | c679db752a68ef316c46946953dd9cea9524eb38 | [
"MIT"
] | null | null | null | atom/VectorStorage.h | pixelsquare/pacman | c679db752a68ef316c46946953dd9cea9524eb38 | [
"MIT"
] | null | null | null | atom/VectorStorage.h | pixelsquare/pacman | c679db752a68ef316c46946953dd9cea9524eb38 | [
"MIT"
] | null | null | null | #ifndef __ATOM_ENGINE_VECTOR_STORAGE_LIBRARY_H__
#define __ATOM_ENGINE_VECTOR_STORAGE_LIBRARY_H__
#include <vector>
#include "BasicPrimitives.h"
using namespace BasicPrimitivesLib::Library;
namespace VectorStorageLib {
namespace Library {
class VectorStorage {
public:
VectorStorage();
~VectorStorage();
void AddObject(Primitive obj);
void DeleteObject(Primitive obj);
private:
std::vector<Primitive> vecPrimitive;
protected:
};
}
}
#endif | 19.583333 | 48 | 0.770213 | [
"vector"
] |
cc08008ac05bb070dbe48133aa19d0d2a78af176 | 948 | h | C | KRender/Internal/Manager/KDynamicConstantBufferManager.h | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 13 | 2019-10-19T17:41:19.000Z | 2021-11-04T18:50:03.000Z | KRender/Internal/Manager/KDynamicConstantBufferManager.h | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 3 | 2019-12-09T06:22:43.000Z | 2020-05-28T09:33:44.000Z | KRender/Internal/Manager/KDynamicConstantBufferManager.h | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | null | null | null | #pragma once
#include "Interface/IKRenderDevice.h"
#include "Interface/IKBuffer.h"
#include <mutex>
class KDynamicConstantBufferManager
{
protected:
struct ConstantBlock
{
IKUniformBufferPtr buffer;
size_t useSize;
ConstantBlock()
{
buffer = nullptr;
useSize = 0;
}
};
struct FrameConstantBlock
{
size_t frameNum;
std::vector<ConstantBlock> blocks;
FrameConstantBlock()
{
frameNum = 0;
}
};
std::vector<FrameConstantBlock> m_ConstantBlocks;
std::mutex m_Lock;
IKRenderDevice* m_Device;
size_t m_BlockSize;
size_t m_Alignment;
bool InternalAlloc(size_t size,
size_t frameIndex, size_t frameNum,
IKUniformBufferPtr& buffer, size_t& offset);
public:
KDynamicConstantBufferManager();
~KDynamicConstantBufferManager();
bool Init(IKRenderDevice* device, size_t frameInFlight, size_t aligment, size_t blockSize);
bool UnInit();
bool Alloc(const void* data, KDynamicConstantBufferUsage& usage);
};
| 18.96 | 92 | 0.753165 | [
"vector"
] |
cc4a57f79478b83d3a1cc805090706f028ea04f6 | 395 | h | C | Motorola/iDEN/Inc/EnumDevices.h | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | 1 | 2021-06-26T17:08:24.000Z | 2021-06-26T17:08:24.000Z | Motorola/iDEN/Inc/EnumDevices.h | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null | Motorola/iDEN/Inc/EnumDevices.h | erithion/old_junk | b2dcaa23320824f8b2c17571f27826869ccd0d4b | [
"MIT"
] | null | null | null |
#include <vector>
#include <string>
namespace Port
{
enum DeviceType
{
TypeSerial,
TypeUsb
};
struct ConnectionInfo
{
DeviceType type_;
std::string name_;
std::string path_;
};
typedef std::vector<ConnectionInfo> ConnectionInfo_vt;
ConnectionInfo_vt GetDevices(const std::string& pattern);
}
| 17.173913 | 63 | 0.577215 | [
"vector"
] |
cc55b8c814a4bb0fa26cb75385446eff827748ef | 3,111 | h | C | include/MeadowsECS/World.h | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | 1 | 2017-11-22T11:39:25.000Z | 2017-11-22T11:39:25.000Z | include/MeadowsECS/World.h | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | null | null | null | include/MeadowsECS/World.h | Konijnendijk/Meadows-ECS | 5ee2619481086edaabcfa235e2455686cb854901 | [
"BSL-1.0",
"MIT"
] | null | null | null |
#ifndef MEADOWSGAMEOSG_WORLD_H
#define MEADOWSGAMEOSG_WORLD_H
#include <vector>
#include <list>
#include <type_traits>
#include "Entity.h"
#include "System.h"
namespace Meadows {
class World {
std::list<Entity*> entities;
std::vector<Entity*> entitiesToAdd;
std::vector<Entity*> entitiesToRemove;
std::vector<System*> systems;
// Counter for assigning ids to GameObjects
std::size_t nextGameObjectId;
public:
World();
~World();
/**
* @brief create an object of the given type using the constructor taking varArgs
*
* @return A pointer to the newly created entity, owned by this World
*/
template<class T, class... VarArgs>
T* createEntity(VarArgs... varArgs) {
static_assert(std::is_convertible<T, Entity>(), "T must be a subclass of Entity");
T* object = new T(varArgs...);
registerEntity(object);
return object;
}
/**
* @brief create a system of the given type using the constructor taking varArgs
*
* The system's System.registerObject(), System.removeObject() and System.tick() methods
* will start to be called the next time world.tick() is called.
*
* @return A pointer to the newly created system, owned by this World
*/
template <class T, class... VarArgs>
T* createSystem(VarArgs... varArgs) {
static_assert(std::is_convertible<T, System>(), "T must be a subclass of System");
T* system = new T(varArgs...);
registerSystem(system);
system->init();
return system;
};
/**
* @brief Remove a game object from the world.
*
* Removes the given Entity from the world. Next tick the System.objectRemoved() methods wil be called and
* all pointers to this object will be invalidated.
*
* @param object The object to remove
*/
void removeEntity(Entity *object);
/**
* @brief Retrieve a system given its type
*
* This can be a time-consuming operation since it will loop through all systems until the first system of the
* given type is found.
*
* @return The first registered system of the given type, or nullptr if no such system is present
*/
template<class T>
T* getSystem() {
static_assert(std::is_convertible<T, System>(), "T must be a subclass of System");
for (System* s : systems) {
T* result = dynamic_cast<T*>(s);
if (result != nullptr) {
return result;
}
}
}
/**
* @brief Tick all game objects and systems
*
* @param delta The delta time
*/
void tick(float delta);
private:
void registerEntity(Entity *object);
void registerSystem(System* system);
};
}
#endif //MEADOWSGAMEOSG_WORLD_H
| 29.913462 | 118 | 0.566056 | [
"object",
"vector"
] |
cc6156a94f486df7f88834222ad371d6d9e880bf | 1,795 | h | C | shaka/src/mapping/generic_converter.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 185 | 2018-11-06T06:04:44.000Z | 2022-03-02T22:20:39.000Z | shaka/src/mapping/generic_converter.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 211 | 2018-11-15T22:52:49.000Z | 2022-03-02T18:46:20.000Z | shaka/src/mapping/generic_converter.h | jgongo/shaka-player-embedded | e04f97b971c684ef18a370697584d5239fb711bd | [
"Apache-2.0",
"BSD-3-Clause"
] | 52 | 2018-12-12T11:00:46.000Z | 2022-02-23T17:35:02.000Z | // Copyright 2016 Google LLC
//
// 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
//
// https://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.
#ifndef SHAKA_EMBEDDED_MAPPING_GENERIC_CONVERTER_H_
#define SHAKA_EMBEDDED_MAPPING_GENERIC_CONVERTER_H_
#include "src/mapping/js_wrappers.h"
#include "src/memory/heap_tracer.h"
namespace shaka {
/**
* Defines a base class for types that do their own parsing. Objects like
* these allow generic parsing by the conversion framework. When trying to
* convert to the given type, a stack object of the type will be created and
* the TryConvert method will be called. If it returns true, then the object
* will be moved into the argument.
*
* Note these are NOT backing objects and will be created on the stack. This
* should only be used for simple objects as they are created and destroyed
* often.
*/
class GenericConverter {
public:
virtual ~GenericConverter() {}
/**
* Tries to convert the given value into the required type, populating
* the members of this object as needed.
* @return True on success, false on error.
*/
virtual bool TryConvert(Handle<JsValue> value) = 0;
/** Converts the current value into a JavaScript value. */
virtual ReturnVal<JsValue> ToJsValue() const = 0;
};
} // namespace shaka
#endif // SHAKA_EMBEDDED_MAPPING_GENERIC_CONVERTER_H_
| 35.196078 | 77 | 0.747632 | [
"object"
] |
acee77943308621af057169242d8c649c94fad97 | 10,694 | c | C | baclib/object/schedule.c | temcocontrols/Three-PhasePower-Meter | 518d49d4a0e5c472d9f380a1b19a2cf0571c0f36 | [
"MIT"
] | 8 | 2018-02-28T11:30:31.000Z | 2021-11-19T14:46:01.000Z | baclib/object/schedule.c | temcocontrols/Three-PhasePower-Meter | 518d49d4a0e5c472d9f380a1b19a2cf0571c0f36 | [
"MIT"
] | null | null | null | baclib/object/schedule.c | temcocontrols/Three-PhasePower-Meter | 518d49d4a0e5c472d9f380a1b19a2cf0571c0f36 | [
"MIT"
] | 4 | 2018-04-19T16:08:51.000Z | 2021-05-21T09:25:56.000Z |
/* Schedule Objects customize -- writen by chesea*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "bacnet.h"
#include "bacdef.h"
#include "bacdcode.h"
#include "bacenum.h"
#include "schedule.h"
#if BAC_SCHEDULE
/*
reliable have following property
-present_value
-description
-list_of_object_property_references
-weeky_schedule
-out_if_service
// to be added more
-status_flag
-effectieve_period
-exception_schedule
-schedule_default
-local_date
-local_time
-reliabiltity
-prioritoy_for_writing
*/
uint8_t SCHEDULES;
/* we simply have 0-n object instances. Yours might be */
/* more complex, and then you need validate that the */
/* given instance exists */
bool Schedule_Valid_Instance(uint32_t object_instance)
{
if (object_instance < MAX_SCHEDULES)
return true;
}
/* we simply have 0-n object instances. */
unsigned Schedule_Count(void)
{
return SCHEDULES;
}
/* we simply have 0-n object instances. */
uint32_t Schedule_Index_To_Instance(unsigned index)
{
return index;
}
/* we simply have 0-n object instances. */
unsigned Schedule_Instance_To_Index(
uint32_t object_instance)
{
return object_instance;
}
/* return apdu length, or -1 on error */
/* assumption - object has already exists */
// read
int Schedule_Encode_Property_APDU(
uint8_t * apdu,
uint32_t object_instance,
BACNET_PROPERTY_ID property,
uint32_t array_index,
BACNET_ERROR_CLASS * error_class,
BACNET_ERROR_CODE * error_code)
{
int apdu_len = 0; /* return value */
BACNET_BIT_STRING bit_string;
BACNET_CHARACTER_STRING char_string;
unsigned object_index;
int len = 0;
int far i;
int far day;
switch (property) {
case PROP_OBJECT_IDENTIFIER:
apdu_len =
encode_application_object_id(&apdu[0], OBJECT_SCHEDULE,
object_instance);
break;
/* note: Name and Description don't have to be the same.
You could make Description writable and different.
Note that Object-Name must be unique in this device */
case PROP_OBJECT_NAME:
characterstring_init_ansi(&char_string, get_label(SCHEDULE,object_instance));
apdu_len = encode_application_character_string(&apdu[0], &char_string);
break;
case PROP_DESCRIPTION:
characterstring_init_ansi(&char_string,get_description(SCHEDULE,object_instance));
apdu_len = encode_application_character_string(&apdu[0], &char_string);
break;
case PROP_OBJECT_TYPE:
apdu_len = encode_application_enumerated(&apdu[0], OBJECT_SCHEDULE);
break;
case PROP_PRESENT_VALUE:
object_index = Schedule_Instance_To_Index(object_instance);
apdu_len =
encode_application_unsigned(&apdu[0], Get_bacnet_value_from_buf(SCHEDULE,0,object_index)/*AI_Present_Value[object_index]*/);
break;
case PROP_EVENT_STATE:
apdu_len =
encode_application_enumerated(&apdu[0], EVENT_STATE_NORMAL);
break;
case PROP_OUT_OF_SERVICE:
object_index =
Schedule_Instance_To_Index( object_instance);
apdu_len = encode_application_boolean(&apdu[0], get_AM_Status(SCHEDULE,object_instance));
break;
apdu_len = encode_application_boolean(&apdu[0], false);
break;
case PROP_WEEKLY_SCHEDULE:
if (array_index == 0) /* count, always 7 */
{
apdu_len = encode_application_unsigned(&apdu[0], 7);
}
else if (array_index == BACNET_ARRAY_ALL) { /* full array */
object_index =
Schedule_Instance_To_Index(object_instance);
for (day = 0; day < 7; day++) {
apdu_len += encode_opening_tag(&apdu[apdu_len], 0);
for (i = 0; i < Get_TV_count(object_index,day); i++)
{
apdu_len +=
bacapp_encode_time_value(&apdu[apdu_len],
Get_Time_Value(object_index,day,i));
}
apdu_len += encode_closing_tag(&apdu[apdu_len], 0);
}
}
else if (array_index <= 7) { /* some array element */
int day = array_index - 1;
apdu_len += encode_opening_tag(&apdu[apdu_len], 0);
for (i = 0; i < Get_TV_count(object_index,day)/*CurrentSC->Weekly_Schedule[day].TV_Count*/; i++) {
apdu_len +=
bacapp_encode_time_value(&apdu[apdu_len],
Get_Time_Value(object_index,day,i)/*&CurrentSC->Weekly_Schedule[day].Time_Values[i]*/);
}
apdu_len += encode_closing_tag(&apdu[apdu_len], 0);
} else { /* out of bounds */
*error_class = ERROR_CLASS_PROPERTY;
*error_code = ERROR_CODE_INVALID_ARRAY_INDEX;
apdu_len = BACNET_STATUS_ERROR;
}
break;
case PROP_EFFECTIVE_PERIOD:
// apdu_len = encode_bacnet_date(&apdu[0], Get_Object_Property_References(0));
// apdu_len += encode_bacnet_date(&apdu[apdu_len], Get_Object_Property_References(0));
break;
case PROP_LIST_OF_OBJECT_PROPERTY_REFERENCES:
for (i = 0; i < 1; i++) {
apdu_len +=
bacapp_encode_device_obj_property_ref(&apdu[apdu_len],
Get_Object_Property_References(i));
}
break;
case PROP_STATUS_FLAGS:
bitstring_init(&bit_string);
bitstring_set_bit(&bit_string, STATUS_FLAG_IN_ALARM, false);
bitstring_set_bit(&bit_string, STATUS_FLAG_FAULT, false);
bitstring_set_bit(&bit_string, STATUS_FLAG_OVERRIDDEN, false);
bitstring_set_bit(&bit_string, STATUS_FLAG_OUT_OF_SERVICE, false);
apdu_len = encode_application_bitstring(&apdu[0], &bit_string);
break;
default:
*error_class = ERROR_CLASS_PROPERTY;
*error_code = ERROR_CODE_UNKNOWN_PROPERTY;
apdu_len = -1;
break;
}
/* only array properties can have array options */
if ((apdu_len >= 0) && (array_index != BACNET_ARRAY_ALL)) {
*error_class = ERROR_CLASS_PROPERTY;
*error_code = ERROR_CODE_PROPERTY_IS_NOT_AN_ARRAY;
apdu_len = -1;
}
return apdu_len;
}
/* returns true if successful */
// write
bool Schedule_Write_Property(
BACNET_WRITE_PROPERTY_DATA * wp_data)
{
bool status = false; /* return value */
unsigned int object_index = 0;
int far len = 0;
BACNET_APPLICATION_DATA_VALUE far value;
BACNET_TIME_VALUE far time_value;
/* decode the some of the request */
if(!IS_CONTEXT_SPECIFIC(*wp_data->application_data))
{
len =
bacapp_decode_application_data(wp_data->application_data,
wp_data->application_data_len, &value);
/* FIXME: len < application_data_len: more data? */
if (len < 0) {
/* error while decoding - a value larger than we can handle */
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_VALUE_OUT_OF_RANGE;
return false;
}
/* only array properties can have array options */
if ((wp_data->object_property != PROP_EVENT_TIME_STAMPS) &&
(wp_data->array_index != BACNET_ARRAY_ALL)) {
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_PROPERTY_IS_NOT_AN_ARRAY;
return false;
}
}
object_index = Schedule_Instance_To_Index(wp_data->object_instance);
switch ((int) wp_data->object_property) {
case PROP_PRESENT_VALUE:
if (value.tag == BACNET_APPLICATION_TAG_REAL) {
object_index =
Schedule_Instance_To_Index(wp_data->object_instance);
wirte_bacnet_value_to_buf(SCHEDULE,wp_data->priority,object_index,value.type.Boolean);
status = true;
} else {
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_INVALID_DATA_TYPE;
}
break;
// add it by chelsea
case PROP_WEEKLY_SCHEDULE:
{
char i;
char tv_count;
len = 1;
tv_count = (wp_data->application_data_len - 2) / 7;
for(i = 0;i < tv_count;i++)
{
bacapp_decode_time_value(&wp_data->application_data[len],&time_value);
write_Time_Value(object_index,wp_data->array_index - 1,i,time_value);
len += 7;
}
status = true;
}
break;
case PROP_OBJECT_NAME:
if (value.tag == BACNET_APPLICATION_TAG_CHARACTER_STRING) {
object_index =
Schedule_Instance_To_Index(wp_data->object_instance);
write_bacnet_name_to_buf(SCHEDULE,wp_data->priority,object_index,value.type.Character_String.value);
status = true;
} else {
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_INVALID_DATA_TYPE;
}
break;
case PROP_DESCRIPTION:
if (value.tag == BACNET_APPLICATION_TAG_CHARACTER_STRING) {
object_index =
Schedule_Instance_To_Index(wp_data->object_instance);
write_bacnet_description_to_buf(SCHEDULE,wp_data->priority,object_index,value.type.Character_String.value);
status = true;
} else {
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_INVALID_DATA_TYPE;
}
break;
case PROP_OUT_OF_SERVICE:
if (value.tag == BACNET_APPLICATION_TAG_BOOLEAN) {
object_index =
Schedule_Instance_To_Index(wp_data->object_instance);
write_bacent_AM_to_buf(SCHEDULE,object_index,value.type.Boolean);
status = true;
} else {
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_INVALID_DATA_TYPE;
}
break;
case PROP_OBJECT_IDENTIFIER:
case PROP_OBJECT_TYPE:
case PROP_STATUS_FLAGS:
case PROP_EVENT_STATE:
case PROP_RELIABILITY:
default:
wp_data->error_class = ERROR_CLASS_PROPERTY;
wp_data->error_code = ERROR_CODE_UNKNOWN_PROPERTY;
break;
}
return status;
}
#endif | 32.504559 | 140 | 0.618291 | [
"object"
] |
4a0b8fedda640a1837794e62628c6cf88be63be5 | 1,881 | h | C | include/brutils/TcpSocket/TcpSocket.h | brakulla/brutils | 086a9458ceeaa9d6ea007862533e11a97c6fcc7a | [
"MIT"
] | 7 | 2019-04-12T10:15:55.000Z | 2022-01-20T14:57:17.000Z | include/brutils/TcpSocket/TcpSocket.h | brakulla/brutils | 086a9458ceeaa9d6ea007862533e11a97c6fcc7a | [
"MIT"
] | 1 | 2021-06-02T13:45:32.000Z | 2021-06-03T08:10:46.000Z | include/brutils/TcpSocket/TcpSocket.h | brakulla/brutils | 086a9458ceeaa9d6ea007862533e11a97c6fcc7a | [
"MIT"
] | null | null | null |
#ifndef TCPSOCKET_TCPSOCKET_TCPSOCKET_H_
#define TCPSOCKET_TCPSOCKET_TCPSOCKET_H_
#include <string>
#include <mutex>
#include "brutils/br_object.h"
namespace brutils {
enum class ConnectionStatus
{
NOT_CONNECTED,
CONNECTED
};
enum TcpError_e
{
TCP_ERROR_NO_ERROR = 0,
TCP_ERROR_SYS_ERROR,
TCP_ERROR_NOT_ALLOWED_IN_CURRENT_STATE,
TCP_ERROR_NOT_ALLOWED_WHILE_BUFFER_IS_NOT_EMPTY,
TCP_ERROR_BAD_SOCKET_DESCRIPTOR
};
struct TcpError
{
TcpError_e errorCode;
std::string errorStr;
};
class TcpSocket : public br_object
{
public:
explicit TcpSocket(br_object *parent = nullptr);
explicit TcpSocket(uint64_t readBufferSize, br_object *parent = nullptr);
explicit TcpSocket(int socketDescriptor, ConnectionStatus status, br_object *parent = nullptr);
explicit TcpSocket(int socketDescriptor,
ConnectionStatus status,
uint64_t readBufferSize,
br_object *parent = nullptr);
~TcpSocket() override;
public: // signals:
signal<> connected;
signal<> disconnected;
signal<> dataReady;
signal<TcpError> errorOccurred;
signal<> destroyed;
public:
ConnectionStatus connectionStatus() const;
TcpError error() const;
std::string peerAddress();
uint16_t peerPort();
uint64_t readBufferSize() const;
bool setReadBufferSize(uint64_t readBufferSize);
int socketDescriptor() const;
bool setSocketDescriptor(int sd);
public:
bool connect(std::string address, uint16_t port);
bool disconnect();
std::vector<std::byte> read();
bool write(const std::vector<std::byte> &input);
bool readFromSocket();
private:
ConnectionStatus _connectionStatus;
TcpError _lastError;
uint64_t _readBufferSize;
std::vector<std::byte> _dataBuffer;
int _socketD;
mutable std::recursive_mutex _mutex;
};
} // namespace brutils
#endif //TCPSOCKET_TCPSOCKET_TCPSOCKET_H_
| 21.62069 | 97 | 0.74269 | [
"vector"
] |
4a1096775946d38f4be79c1d1218688fd9a3a19b | 1,406 | h | C | src/lib/Simplex.h | PearCoding/NumericSim | 66cf98f574a2f615817c9b5456975be69662acf6 | [
"MIT"
] | null | null | null | src/lib/Simplex.h | PearCoding/NumericSim | 66cf98f574a2f615817c9b5456975be69662acf6 | [
"MIT"
] | null | null | null | src/lib/Simplex.h | PearCoding/NumericSim | 66cf98f574a2f615817c9b5456975be69662acf6 | [
"MIT"
] | null | null | null | #pragma once
#include "Types.h"
#include "Vector.h"
#include "matrix/MatrixOperations.h"
#include "Normal.h"
NS_BEGIN_NAMESPACE
template<typename T, Dimension K>
class Simplex
{
public:
static constexpr Dimension Order = K;
static constexpr Dimension VertexCount = K+1;
typedef FixedVector<T,K> vertex_t;
typedef FixedMatrix<T,K,K> matrix_t;
Simplex();
Simplex(std::initializer_list<std::initializer_list<T> > list);
void prepare();
const vertex_t& operator[](Index i) const;
vertex_t& operator[](Index i);
static constexpr T unitVolume();
T volume() const;
vertex_t center() const;
// Radius of the circumscribed hypersphere
T outerRadius() const;
T diameter() const;
vertex_t toLocal(const vertex_t& global) const;
vertex_t toGlobal(const vertex_t& local) const;
vertex_t gradient(Index component) const;
vertex_t faceCenter(Index i) const;
vertex_t faceNormal(Index i) const;// Jump Vector
const matrix_t& matrix() const;
const matrix_t& inverseMatrix() const;
T determinant() const;
private:
vertex_t mVertices[K+1];
bool mPrepared;
matrix_t mMatrix;
matrix_t mInverseMatrix;
T mDeterminant;
};
// Typedefs
template<typename T>
using Line = Simplex<T, 1>;
template<typename T>
using Triangle = Simplex<T, 2>;
template<typename T>
using Tetrahedron = Simplex<T, 3>;
NS_END_NAMESPACE
#define _NS_SIMPLEX_INL
# include "Simplex.inl"
#undef _NS_SIMPLEX_INL | 19.802817 | 64 | 0.748933 | [
"vector"
] |
4a11a8def28b6646285dc4638c70b4216751343c | 3,091 | h | C | hprose/http/Header.h | adsfgfh4654/hprose-cpp1x | d37b3737bbf1836d68b32241c78f711051b1984c | [
"MIT"
] | 42 | 2016-10-10T02:36:54.000Z | 2022-02-05T13:47:45.000Z | hprose/http/Header.h | adsfgfh4654/hprose-cpp1x | d37b3737bbf1836d68b32241c78f711051b1984c | [
"MIT"
] | 5 | 2017-05-14T01:31:13.000Z | 2018-03-22T01:02:33.000Z | hprose/http/Header.h | adsfgfh4654/hprose-cpp1x | d37b3737bbf1836d68b32241c78f711051b1984c | [
"MIT"
] | 20 | 2016-10-20T01:51:39.000Z | 2022-02-05T13:48:16.000Z | /**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* hprose/http/Header.h *
* *
* hprose http header for cpp. *
* *
* LastModified: Nov 27, 2017 *
* Author: Chen fei <cf@hprose.com> *
* *
\**********************************************************/
#pragma once
#include <algorithm>
#include <locale>
#include <string>
#include <vector>
#include <unordered_map>
#include <set>
#include <ostream>
namespace hprose {
namespace http {
namespace internal {
struct UniHash {
size_t operator()(const std::string &str) const {
std::string lowerStr(str.size(), 0);
std::transform(str.begin(), str.end(), lowerStr.begin(), tolower);
std::hash<std::string> hash;
return hash(lowerStr);
}
};
struct UniEqual {
bool operator()(const std::string &left, const std::string &right) const {
return left.size() == right.size()
&& std::equal(left.begin(), left.end(), right.begin(),
[](char a, char b) {
return tolower(a) == tolower(b);
}
);
}
};
} // internal
class Header
: public std::unordered_map<std::string, std::vector<std::string>, internal::UniHash, internal::UniEqual> {
public:
void add(std::string key, std::string value) {
auto search = find(key);
if (search != end()) {
search->second.push_back(value);
} else {
set(key, value);
}
}
inline void set(std::string key, std::string value) {
(*this)[key] = {value};
}
std::string get(std::string key) const {
auto search = find(key);
if (search != end()) {
auto value = search->second;
if (value.size()) {
return value[0];
}
}
return "";
}
inline void del(std::string key) {
erase(key);
}
void writeSubset(std::ostream &ostream, const std::set<std::string> &exclude) const {
for (auto iter = cbegin(); iter != cend(); iter++) {
if (exclude.find(iter->first) == exclude.end()) {
ostream << iter->first << ": " << iter->second[0] << "\r\n";
}
}
}
};
}
} // hprose::http
| 30.60396 | 111 | 0.377871 | [
"vector",
"transform"
] |
4a215761926b0cc053be9edabcfde3a992d4fdec | 1,573 | h | C | include/o3d/engine/primitive/isosphere.h | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | include/o3d/engine/primitive/isosphere.h | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | include/o3d/engine/primitive/isosphere.h | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file isosphere.h
* @brief Definition of an iso-sphere primitive.
* @author Emmanuel RUFFIO (emmanuel.ruffio@gmail.com)
* @date 2008-11-10
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#ifndef _O3D_ISOSPHERE_H
#define _O3D_ISOSPHERE_H
#include "primitive.h"
namespace o3d {
/**
* @brief Iso-sphere geometry generator.
*/
class O3D_API IsoSphere : public Primitive
{
O3D_DECLARE_ABSTRACT_CLASS(IsoSphere)
public:
enum IsoSphereMode
{
HALF_SPHERE = 4,
};
//! Default constructor. Build an iso-sphere.
//! @param radius Radius of the iso-sphere
//! @param subDiv Specify how many times you want to subdivide the icosahedron
//! @param halfSphere True if you want only a half sphere
IsoSphere(Float radius, UInt32 subDiv, UInt32 flags = 0);
//! Is half sphere
Bool isHalfSphere() const { return (m_capacities & HALF_SPHERE) == HALF_SPHERE; }
protected:
//! Build a isosphere from a icosahedron subdivision
void buildIsoSphere();
/**
* @brief IN. the radius of the sphere
*/
Float m_radius;
/**
* @brief IN. specify how many times you want to subdivide the icosahedron.
* The vertex number is given by: V(subDiv) = V(n) = 2+10*2^(2*n) for a whole sphere
* V(n) = 1+5.2^(n-1)*(2^(n+1)+1) for a half sphere
*/
UInt32 m_subDiv;
/**
* @brief IN. true if you want only a half sphere
*/
Bool m_halfSphere;
/**
* @brief Not supported yet
*/
Bool m_optimize;
};
} // namespace o3d
#endif // _O3D_ISOSPHERE_H
| 22.15493 | 89 | 0.6637 | [
"geometry"
] |
4a2f31109c81b077293c42ecc16036f035b0a06b | 1,499 | h | C | HElib-api/flt2int_encode.h | bristolcrypto/HEAT | 3d96abb74c29e94b26010d17759875578e5c9f50 | [
"BSD-2-Clause"
] | 25 | 2017-02-21T20:57:45.000Z | 2021-06-30T05:56:34.000Z | HElib-api/flt2int_encode.h | bristolcrypto/HEAT | 3d96abb74c29e94b26010d17759875578e5c9f50 | [
"BSD-2-Clause"
] | 2 | 2017-03-21T09:21:30.000Z | 2017-09-05T11:35:59.000Z | HElib-api/flt2int_encode.h | bristolcrypto/HEAT | 3d96abb74c29e94b26010d17759875578e5c9f50 | [
"BSD-2-Clause"
] | 8 | 2016-08-27T20:35:43.000Z | 2021-09-23T17:51:44.000Z | #ifndef FIXEDPOINT_FLT2INT_ENCODE_H_
#define FIXEDPOINT_FLT2INT_ENCODE_H_
#include <NTL/ZZX.h>
#include <NTL/RR.h>
#include <NTL/mat_ZZ.h>
#include <NTL/LLL.h>
#include "FHE.h"
#include "timing.h"
#include <vector>
#include <cassert>
#include <cstdio>
#include <cmath>
#include <ctime>
#define _USE_MATH_DEFINES
/*If y<=2, then x = x%y, else x will be in (-y/2,...,y/2] */
#define BINT_REP(x,y){\
x %=(y);\
if((y)>2) if ((x)>((y)>>1)) x-=(y);\
}
/* Polynomial of type ZZX is converted to type ZZ_pX */
#define ZZX2PX(a,b,c) {\
a = ZZ_pX(0L);\
for(long def_i=0; def_i <= deg(b); def_i++)\
SetCoeff(a,def_i,coeff(b,def_i)%c);\
}
/* Polynomial of type ZZ_pX is converted to type ZZX */
#define ZZPX2X(a,b) {\
a = ZZX(0L);\
for(long def_i=0; def_i <= deg(b); def_i++)\
SetCoeff(a,def_i,rep(coeff(b,def_i)));\
}
void BbaseDigits(vector<long>& out, long in, long base);
void flt2plyEncode(ZZX& outply, long& fplvl, double& in_fin, double in, long preci, long PreciInt, long base, long dg, bool fracrep)
;
void ply2fltDecode(double& out, const ZZX& in, long fplvl, long base, long dg, long PrecBbase, bool fracrep);
long checkPreci(long preci, long PreciInt, double out, double in);
void Test_flt2plyEncode();
void LatfltEncode(long n, ZZX& outply, double inR, double inI, long preci, long dg);
void LatfltDecode(double& outR, double& outI, const ZZX& in, long dg);
void Test_LatfltEncode();
#endif /* FIXEDPOINT_FLT2INT_ENCODE_H_ */
| 26.767857 | 132 | 0.66511 | [
"vector"
] |
4a351facd3bebc46a26ba49404759027c9a1b640 | 1,286 | h | C | RPG-Code/Code/Source/Modules/Scenes/Gameloop/Configuration.h | Dani-24/RPG | b5621dd0134ca10d88eb861409a210999d804b9b | [
"MIT"
] | 1 | 2022-03-13T12:57:59.000Z | 2022-03-13T12:57:59.000Z | RPG-Code/Code/Source/Modules/Scenes/Gameloop/Configuration.h | Dani-24/Project-RPG | 775ccaf652f7680a70cf5668cf6efa272ee7e3f9 | [
"MIT"
] | null | null | null | RPG-Code/Code/Source/Modules/Scenes/Gameloop/Configuration.h | Dani-24/Project-RPG | 775ccaf652f7680a70cf5668cf6efa272ee7e3f9 | [
"MIT"
] | null | null | null | #ifndef __CONFIGURATION_H__
#define __CONFIGURATION_H__
#include "Module.h"
#include "Animation.h"
#include "GuiButton.h"
#include "App.h"
#include "SDL/include/SDL_rect.h"
struct SDL_Texture;
class Configuration : public Module
{
public:
Configuration(App* application, bool start_enabled = true);
// Destructor
virtual ~Configuration();
// Called before render is available
bool Awake(pugi::xml_node& config);
// Called before the first frame
bool Start();
// Called before all Updates
bool PreUpdate();
// Called each loop iteration
bool Update(float dt);
// Called before all Updates
bool PostUpdate();
// Called before quitting
bool CleanUp();
// Define multiple Gui Event methods
bool OnGuiMouseClickEvent(GuiControl* control);
private:
GuiButton* musp;//increse the music volume
GuiButton* musm;//decrese the music volume
GuiButton* FXp;//increse the FX volume
GuiButton* FXm;//decrese the FX volume
GuiButton* fullS;//Change fullscreen mode
GuiButton* Vsync;//active/deactive Vsync
//GuiButton* frcap30;//change frcap to 30fps
//GuiButton* frcap60;//change frcap to 60fps
GuiButton* back;//back to the last screen
int backFx, loadFx, saveFx, btnSelection;
public:
bool pause;
bool fulls;
SDL_Texture* background;
};
#endif | 18.637681 | 60 | 0.741058 | [
"render"
] |
4a482eea3e7c48d0cd45c9351be986d21b2d481e | 12,085 | c | C | benchmarks/nemo/nemolite2d/manual_versions/psykal_c_opencl/opencl_utils.c | stfc/PSycloneBench | f3c65c904eb286b4e3f63c43273a80d25e92cbe4 | [
"BSD-3-Clause"
] | 5 | 2018-03-30T23:33:23.000Z | 2022-03-21T13:32:01.000Z | benchmarks/nemo/nemolite2d/manual_versions/psykal_c_opencl/opencl_utils.c | stfc/PSycloneBench | f3c65c904eb286b4e3f63c43273a80d25e92cbe4 | [
"BSD-3-Clause"
] | 76 | 2018-01-31T14:16:03.000Z | 2022-03-25T13:56:17.000Z | benchmarks/nemo/nemolite2d/manual_versions/psykal_c_opencl/opencl_utils.c | stfc/PSycloneBench | f3c65c904eb286b4e3f63c43273a80d25e92cbe4 | [
"BSD-3-Clause"
] | 2 | 2019-08-01T10:23:02.000Z | 2021-09-28T13:23:01.000Z | #include "opencl_utils.h"
/** Maximum number of OpenCL devices we will query */
#define MAX_DEVICES 4
#define MAX_SOURCE_SIZE (0x100000)
#define VERBOSE 0
/** Query the available OpenCL devices and choose one */
void init_device(
int platform_selection,
cl_device_id *device,
char *version_str,
cl_context *context)
{
/** The version of OpenCL supported by the selected device */
cl_device_id device_ids[MAX_DEVICES];
cl_platform_id platform_ids[MAX_DEVICES];
cl_uint ret_num_devices;
cl_uint ret_num_platforms;
cl_int ret;
int idev;
/* Get Platform and Device Info */
ret = clGetPlatformIDs(MAX_DEVICES, platform_ids, &ret_num_platforms);
check_status("clGetPlatformIDs", ret);
fprintf(stdout, "Have %d platforms.\n", ret_num_platforms);
char result_str[128];
cl_device_fp_config fp_config;
cl_device_type device_type;
size_t result_len;
for(idev=0;idev<ret_num_platforms;idev++){
ret = clGetPlatformInfo(platform_ids[idev],
CL_PLATFORM_NAME,
(size_t)128, (void *)result_str, &result_len);
fprintf(stdout, "Platform %d (id=%ld) is: %s\n",
idev, (long)(platform_ids[idev]), result_str);
}
if (platform_selection < ret_num_platforms){
fprintf(stdout, "Selecting platform %d.\n", platform_selection);
}else{
fprintf(stderr, "Selected platform %d does not exist.\n", platform_selection);
exit(-1);
}
ret = clGetDeviceIDs(platform_ids[platform_selection], CL_DEVICE_TYPE_DEFAULT,
MAX_DEVICES, device_ids, &ret_num_devices);
check_status("clGetDeviceIDs", ret);
fprintf(stdout, "Have %d devices\n", ret_num_devices);
for (idev=0; idev<ret_num_devices; idev++){
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_NAME,
(size_t)128, result_str, &result_len);
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_TYPE,
(size_t)(sizeof(cl_device_type)), &device_type,
&result_len);
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_VERSION,
(size_t)128, version_str, &result_len);
#ifdef CL_DEVICE_DOUBLE_FP_CONFIG
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_DOUBLE_FP_CONFIG,
(size_t)(sizeof(cl_device_fp_config)),
&fp_config, &result_len);
#else
/* The Intel/Altera OpenCL SDK is only version 1.0 and that doesn't
have the CL_DEVICE_DOUBLE_FP_CONFIG property */
fp_config = 0;
#endif
size_t wg_size;
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_MAX_WORK_GROUP_SIZE,
(size_t)(sizeof(size_t)),
&wg_size, &result_len);
cl_uint ndims;
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
sizeof(cl_uint), &ndims, &result_len);
size_t *max_sizes;
max_sizes = (size_t*)malloc(ndims*sizeof(size_t));
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_MAX_WORK_ITEM_SIZES,
ndims*sizeof(size_t), max_sizes, &result_len);
cl_uint max_units;
ret = clGetDeviceInfo(device_ids[idev], CL_DEVICE_MAX_COMPUTE_UNITS,
sizeof(cl_uint), &max_units, &result_len);
fprintf(stdout, "Device %d is: %s, type=%d, version=%s\n",
idev, result_str, (int)(device_type), version_str);
if((int)fp_config == 0){
fprintf(stdout, " double precision NOT supported\n");
}
else{
fprintf(stdout, " double precision supported\n");
}
fprintf(stdout, " max work group size = %ld\n", (long)wg_size);
fprintf(stdout, " max size of each work item dimension: "
"%ld %ld\n", max_sizes[0], max_sizes[1]);
fprintf(stdout, " max compute units = %ld\n", (long)max_units);
free(max_sizes);
}
/* Choose device 0 */
idev = 0;
*device = device_ids[idev];
/* Create OpenCL context for just 1 device */
cl_context_properties cl_props[3];
/* The list of properties for this context is zero terminated */
cl_props[0] = CL_CONTEXT_PLATFORM;
cl_props[1] = (cl_context_properties)(platform_ids[platform_selection]);
cl_props[2] = 0;
*context = clCreateContext(cl_props, 1, device, NULL, NULL, &ret);
check_status("clCreateContext", ret);
}
const char* OCL_GetErrorString(cl_int error)
{
switch (error)
{
case CL_SUCCESS:
return "CL_SUCCESS";
case CL_DEVICE_NOT_FOUND:
return "CL_DEVICE_NOT_FOUND";
case CL_DEVICE_NOT_AVAILABLE:
return "CL_DEVICE_NOT_AVAILABLE";
case CL_COMPILER_NOT_AVAILABLE:
return "CL_COMPILER_NOT_AVAILABLE";
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
return "CL_MEM_OBJECT_ALLOCATION_FAILURE";
case CL_OUT_OF_RESOURCES:
return "CL_OUT_OF_RESOURCES";
case CL_OUT_OF_HOST_MEMORY:
return "CL_OUT_OF_HOST_MEMORY";
case CL_PROFILING_INFO_NOT_AVAILABLE:
return "CL_PROFILING_INFO_NOT_AVAILABLE";
case CL_MEM_COPY_OVERLAP:
return "CL_MEM_COPY_OVERLAP";
case CL_IMAGE_FORMAT_MISMATCH:
return "CL_IMAGE_FORMAT_MISMATCH";
case CL_IMAGE_FORMAT_NOT_SUPPORTED:
return "CL_IMAGE_FORMAT_NOT_SUPPORTED";
case CL_BUILD_PROGRAM_FAILURE:
return "CL_BUILD_PROGRAM_FAILURE";
case CL_MAP_FAILURE:
return "CL_MAP_FAILURE";
case CL_INVALID_VALUE:
return "CL_INVALID_VALUE";
case CL_INVALID_DEVICE_TYPE:
return "CL_INVALID_DEVICE_TYPE";
case CL_INVALID_PLATFORM:
return "CL_INVALID_PLATFORM";
case CL_INVALID_DEVICE:
return "CL_INVALID_DEVICE";
case CL_INVALID_CONTEXT:
return "CL_INVALID_CONTEXT";
case CL_INVALID_QUEUE_PROPERTIES:
return "CL_INVALID_QUEUE_PROPERTIES";
case CL_INVALID_COMMAND_QUEUE:
return "CL_INVALID_COMMAND_QUEUE";
case CL_INVALID_HOST_PTR:
return "CL_INVALID_HOST_PTR";
case CL_INVALID_MEM_OBJECT:
return "CL_INVALID_MEM_OBJECT";
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR";
case CL_INVALID_IMAGE_SIZE:
return "CL_INVALID_IMAGE_SIZE";
case CL_INVALID_SAMPLER:
return "CL_INVALID_SAMPLER";
case CL_INVALID_BINARY:
return "CL_INVALID_BINARY";
case CL_INVALID_BUILD_OPTIONS:
return "CL_INVALID_BUILD_OPTIONS";
case CL_INVALID_PROGRAM:
return "CL_INVALID_PROGRAM";
case CL_INVALID_PROGRAM_EXECUTABLE:
return "CL_INVALID_PROGRAM_EXECUTABLE";
case CL_INVALID_KERNEL_NAME:
return "CL_INVALID_KERNEL_NAME";
case CL_INVALID_KERNEL_DEFINITION:
return "CL_INVALID_KERNEL_DEFINITION";
case CL_INVALID_KERNEL:
return "CL_INVALID_KERNEL";
case CL_INVALID_ARG_INDEX:
return "CL_INVALID_ARG_INDEX";
case CL_INVALID_ARG_VALUE:
return "CL_INVALID_ARG_VALUE";
case CL_INVALID_ARG_SIZE:
return "CL_INVALID_ARG_SIZE";
case CL_INVALID_KERNEL_ARGS:
return "CL_INVALID_KERNEL_ARGS";
case CL_INVALID_WORK_DIMENSION:
return "CL_INVALID_WORK_DIMENSION";
case CL_INVALID_WORK_GROUP_SIZE:
return "CL_INVALID_WORK_GROUP_SIZE";
case CL_INVALID_WORK_ITEM_SIZE:
return "CL_INVALID_WORK_ITEM_SIZE";
case CL_INVALID_GLOBAL_OFFSET:
return "CL_INVALID_GLOBAL_OFFSET";
case CL_INVALID_EVENT_WAIT_LIST:
return "CL_INVALID_EVENT_WAIT_LIST";
case CL_INVALID_EVENT:
return "CL_INVALID_EVENT";
case CL_INVALID_OPERATION:
return "CL_INVALID_OPERATION";
case CL_INVALID_GL_OBJECT:
return "CL_INVALID_GL_OBJECT";
case CL_INVALID_BUFFER_SIZE:
return "CL_INVALID_BUFFER_SIZE";
case CL_INVALID_MIP_LEVEL:
return "CL_INVALID_MIP_LEVEL";
case CL_INVALID_GLOBAL_WORK_SIZE:
return "CL_INVALID_GLOBAL_WORK_SIZE";
// unknown
default:
return "unknown error code";
}
}
void check_status(const char *text, cl_int err){
if(err != CL_SUCCESS){
fprintf(stderr, "Hit error: %s: %s\n", text, OCL_GetErrorString(err));
exit(1);
}
if(VERBOSE){
fprintf(stdout, "Called %s OK\n", text);
}
}
cl_program get_program(cl_context context,
const cl_device_id *device,
int is_source_file,
const char *filename){
cl_program program;
if(!is_source_file){
program = get_binary_kernel(context, device, filename);
}
else{
program = get_source_kernel(context, device, filename);
}
return program;
}
/** Creates an OpenCL kernel by compiling it from the supplied source */
cl_program get_source_kernel(cl_context context,
const cl_device_id *device,
const char *filename){
FILE *fp;
char *source_str;
size_t source_size;
/* Holds return value of calls to OpenCL API */
cl_int ret;
/* Load the source code containing the kernel*/
fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "Failed to load kernel source: %s.\n", filename);
exit(1);
}
source_str = (char*)malloc(MAX_SOURCE_SIZE);
source_size = fread(source_str, 1, MAX_SOURCE_SIZE, fp);
fclose( fp );
/* Create Kernel Program from the source */
cl_program program = clCreateProgramWithSource(context, 1,
(const char **)&source_str,
(const size_t *)&source_size,
&ret);
check_status("clCreateProgramWithSource", ret);
/* Build Kernel Program */
char const *build_options = "-cl-mad-enable -cl-fast-relaxed-math";
ret = clBuildProgram(program, 1, device, build_options, NULL, NULL);
if(ret == CL_BUILD_PROGRAM_FAILURE){
char *build_log;
size_t log_size;
clGetProgramBuildInfo(program, *device, CL_PROGRAM_BUILD_LOG,
0, NULL, &log_size);
build_log = (char *)malloc(log_size+1);
clGetProgramBuildInfo(program, *device, CL_PROGRAM_BUILD_LOG,
log_size, build_log, NULL);
build_log[log_size] = '\0';
fprintf(stderr, "%s\n", build_log);
free(build_log);
exit(1);
}
check_status("clBuildProgram", ret);
/* Clean up */
free(source_str);
return program;
}
cl_program get_binary_kernel(cl_context context,
const cl_device_id *device,
const char *filename){
FILE *fp;
const int num_binaries = 1;
/** Array of pointers to buffers containing kernel binaries */
const unsigned char *binary_buffers[num_binaries];
size_t binary_sizes[num_binaries];
cl_int binary_status[num_binaries];
char *ptr;
/* Holds return value of calls to OpenCL API */
cl_int ret;
/* Open and read the file containing the pre-compiled kernel */
fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr,
"ERROR: get_binary_kernel: Failed to load pre-compiled kernel file: "
"%s.\n", filename);
exit(1);
}
fseek(fp, 0, SEEK_END);
binary_sizes[0] = ftell(fp);
binary_buffers[0] = (unsigned char*)malloc(
sizeof(unsigned char)*binary_sizes[0]);
rewind(fp);
fread(binary_buffers[0], binary_sizes[0], 1, fp);
fclose(fp);
fprintf(stdout, "Read %d bytes for binary %s\n", (int)binary_sizes[0], filename);
/* Create the program object from the loaded binary */
cl_program program = clCreateProgramWithBinary(context, (cl_uint)1,
device, binary_sizes, binary_buffers, binary_status, &ret);
check_status("clCreateProgramWithBinary", ret);
check_status("Loading binary", binary_status[0]);
// Build the program that was just created.
ret = clBuildProgram(program, 0, NULL, "", NULL, NULL);
check_status("clBuildProgram", ret);
// Clean up
for(int ibuf=0; ibuf<num_binaries; ibuf++){
free(binary_buffers[ibuf]);
}
return program;
}
/** Returns the duration of the supplied OpenCL event in nanoseconds.
Requires OpenCL profiling to have been enabled on the queue that performed
the operation to which the event corresponds. */
cl_ulong duration_ns(cl_event event){
cl_ulong start_time, end_time;
cl_int ret;
ret = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,
sizeof(cl_ulong), (void*)&start_time, NULL);
check_status("clGetEventProfilingInfo", ret);
ret = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,
sizeof(cl_ulong), (void*)&end_time, NULL);
check_status("clGetEventProfilingInfo", ret);
return (end_time - start_time);
}
| 33.569444 | 83 | 0.700869 | [
"object"
] |
4a5738876240fa000f999cf5646071ec203168e2 | 2,499 | h | C | compiler/enco/core/src/CppGen/Subnet.h | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compiler/enco/core/src/CppGen/Subnet.h | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compiler/enco/core/src/CppGen/Subnet.h | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
*
* 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.
*/
#ifndef __ENCO_CPP_GEN_SUBNET_H__
#define __ENCO_CPP_GEN_SUBNET_H__
#include "ANN/Binder.h"
#include "CppGen/MemoryContext.h"
#include <pp/MultiLineText.h>
#include <map>
#include <set>
namespace enco
{
/**
* @brief A C++ struct that provides Android NN model & compilation
*/
struct SubnetStruct
{
virtual ~SubnetStruct() = default;
/// @brief Return the field name of ANeuralNetworksModel value
virtual std::string model(void) const = 0;
/// @brief Return the field name of ANeuralNetworksCompilatoin value
virtual std::string compilation(void) const = 0;
virtual const pp::MultiLineText &def(void) const = 0;
virtual const pp::MultiLineText &ctor(void) const = 0;
virtual const pp::MultiLineText &dtor(void) const = 0;
};
class SubnetStructBuilder
{
public:
std::unique_ptr<SubnetStruct> build(const ANNBinder *binder) const;
public:
void expr(const ann::Operand *oper, const std::string &base, const std::string &size)
{
_weighted.insert(oper);
_base_exprs[oper] = base;
_size_exprs[oper] = size;
}
private:
std::set<const ann::Operand *> _weighted;
std::map<const ann::Operand *, std::string> _base_exprs;
std::map<const ann::Operand *, std::string> _size_exprs;
};
/**
* @brief Generate C++ code that invokes Android NN subnet
*/
class SubnetBlockCompiler
{
public:
SubnetBlockCompiler(const enco::MemoryContext &mem) : _mem(mem)
{
// DO NOTHING
}
public:
/// @brief Specify how to access ANeuralNetworksCompilation value (C expression)
void bind(const ANNBinder *binder, const std::string &exp) { _compilation_ctx[binder] = exp; }
public:
std::unique_ptr<pp::MultiLineText> compile(const ANNBinder *binder) const;
private:
const enco::MemoryContext &_mem;
std::map<const ANNBinder *, std::string> _compilation_ctx;
};
} // namespace enco
#endif // __ENCO_CPP_GEN_SUBNET_H__
| 27.163043 | 96 | 0.72589 | [
"model"
] |
4a70fd2c6bd2987079b57e7afa0e988c8ae2525f | 4,757 | h | C | src/saf.h | ccanel/saf | 5bc296e352419ae3688eb51dded72154f732127e | [
"Apache-2.0"
] | 28 | 2018-09-06T19:18:27.000Z | 2022-02-10T05:56:08.000Z | src/saf.h | ccanel/saf | 5bc296e352419ae3688eb51dded72154f732127e | [
"Apache-2.0"
] | 13 | 2018-09-13T13:41:53.000Z | 2021-05-12T01:18:36.000Z | src/saf.h | ccanel/saf | 5bc296e352419ae3688eb51dded72154f732127e | [
"Apache-2.0"
] | 14 | 2018-09-06T14:33:37.000Z | 2021-05-22T20:07:45.000Z | // Copyright 2018 The SAF Authors. All Rights Reserved.
//
// 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.
#ifndef SAF_SAF_H_
#define SAF_SAF_H_
#include "camera/camera.h"
#include "camera/camera_manager.h"
#include "camera/gst_camera.h"
#include "common/context.h"
#include "common/serialization.h"
#include "common/timer.h"
#include "common/types.h"
#include "model/model.h"
#include "model/model_manager.h"
#include "operator/binary_file_writer.h"
#include "operator/buffer.h"
#include "operator/compressor.h"
#include "operator/detectors/object_detector.h"
#include "operator/detectors/opencv_face_detector.h"
#include "operator/detectors/opencv_people_detector.h"
#include "operator/display.h"
#include "operator/extractors/feature_extractor.h"
#include "operator/face_tracker.h"
#include "operator/flow_control/flow_control_entrance.h"
#include "operator/flow_control/flow_control_exit.h"
#include "operator/frame_writer.h"
#include "operator/image_classifier.h"
#include "operator/image_segmenter.h"
#include "operator/image_transformer.h"
#include "operator/jpeg_writer.h"
#include "operator/matchers/euclidean_matcher.h"
#include "operator/matchers/object_matcher.h"
#include "operator/matchers/xqda_matcher.h"
#include "operator/neural_net_consumer.h"
#include "operator/neural_net_evaluator.h"
#include "operator/opencv_motion_detector.h"
#include "operator/opencv_optical_flow.h"
#include "operator/operator.h"
#include "operator/operator_factory.h"
#include "operator/pubsub/frame_publisher.h"
#include "operator/pubsub/frame_subscriber.h"
#include "operator/receivers/receiver.h"
#include "operator/rtsp_sender.h"
#include "operator/senders/sender.h"
#include "operator/strider.h"
#include "operator/temporal_region_selector.h"
#include "operator/throttler.h"
#include "operator/trackers/object_tracker.h"
#include "operator/writers/file_writer.h"
#include "operator/writers/writer.h"
#include "pipeline/pipeline.h"
#include "stream/frame.h"
#include "stream/stream.h"
#include "utils/cuda_utils.h"
#include "utils/cv_utils.h"
#include "utils/file_utils.h"
#include "utils/fp16.h"
#include "utils/gst_utils.h"
#include "utils/hash_utils.h"
#include "utils/image_utils.h"
#include "utils/math_utils.h"
#include "utils/output_tracker.h"
#include "utils/perf_utils.h"
#include "utils/string_utils.h"
#include "utils/time_utils.h"
#include "utils/utils.h"
#include "utils/yolo_utils.h"
#include "video/gst_video_capture.h"
#include "video/gst_video_encoder.h"
#ifdef USE_CAFFE
#include "model/caffe_model.h"
#include "operator/caffe_facenet.h"
#include "operator/detectors/caffe_mtcnn_face_detector.h"
#include "operator/detectors/caffe_yolo_detector.h"
#endif // USE_CAFFE
#ifdef HAVE_INTEL_CAFFE
#include "operator/detectors/caffe_yolo_v2_detector.h"
#include "operator/extractors/caffe_feature_extractor.h"
#ifdef USE_SSD
#include "operator/detectors/caffe_mobilenet_ssd_detector.h"
#include "operator/detectors/ssd_detector.h"
#endif // USE_SSD
#endif // HAVE_INTEL_CAFFE
#ifdef USE_CVSDK
#include "model/cvsdk_model.h"
#include "operator/extractors/cvsdk_feature_extractor.h"
#ifdef USE_SSD
#include "operator/detectors/cvsdk_ssd_detector.h"
#endif // USE_SSD
#endif // USE_CVSDK
#ifdef USE_DLIB
#include "operator/trackers/dlib_tracker.h"
#endif // USE_DLIB
#ifdef USE_FCRNN
#include "operator/detectors/frcnn_detector.h"
#endif // USE_FRCNN
#ifdef USE_KAFKA
#include "operator/receivers/kafka_receiver.h"
#include "operator/senders/kafka_sender.h"
#endif
#ifdef USE_MQTT
#include "operator/receivers/mqtt_receiver.h"
#include "operator/senders/mqtt_sender.h"
#endif // USE_MQTT
#ifdef USE_NCS
#include "ncs/ncs.h"
#include "ncs/ncs_manager.h"
#include "operator/detectors/ncs_yolo_detector.h"
#endif // USE_NCS
#ifdef USE_PTGRAY
#include "camera/pgr_camera.h"
#endif // USE_PTGRAY
#ifdef USE_RPC
#include "operator/rpc/frame_receiver.h"
#include "operator/rpc/frame_sender.h"
#endif // USE_RPC
#ifdef USE_TENSORFLOW
#include "model/tf_model.h"
#endif // USE_TENSORFLOW
#ifdef USE_VIMBA
#include "camera/vimba_camera.h"
#endif // USE_VIMBA
#ifdef USE_WEBSOCKET
#include "operator/receivers/websocket_receiver.h"
#include "operator/senders/websocket_sender.h"
#endif // USE_WEBSOCKET
#endif // SAF_SAF_H_
| 31.091503 | 75 | 0.789783 | [
"model"
] |
7d2b4b0364e7e8954eed5a9980147518728dd836 | 700 | h | C | SPHSimulation/src/Transform.h | bikush/simple-sph-simulation | 1ee208630181550180358f22f468fbf4f32149f5 | [
"Apache-2.0"
] | 5 | 2017-12-12T08:05:58.000Z | 2021-08-05T21:23:12.000Z | SPHSimulation/src/Transform.h | bikush/simple-sph-simulation | 1ee208630181550180358f22f468fbf4f32149f5 | [
"Apache-2.0"
] | null | null | null | SPHSimulation/src/Transform.h | bikush/simple-sph-simulation | 1ee208630181550180358f22f468fbf4f32149f5 | [
"Apache-2.0"
] | 2 | 2017-04-18T08:02:38.000Z | 2018-06-07T09:45:37.000Z | #pragma once
#include "GlmVec.h"
#include <glm\mat4x4.hpp>
class Transform
{
public:
Transform();
Transform( const glm::vec3& position, const glm::vec3& scale, const glm::vec3& axisAngles );
void setPosition(const glm::vec3& newPosition);
void setScale(const glm::vec3& newScale);
void setScale(const float newScale);
void setAngles(const float xAxis, const float yAxis, const float zAxis);
void setAngles(const glm::vec3& newAngles);
glm::vec3 getPosition() const;
glm::vec3 getScale() const;
glm::vec3 getAxisAngles() const;
const glm::mat4& getTransformMatrix();
private:
glm::vec3 position;
glm::vec3 scale;
glm::vec3 axisAngles;
bool recalculate;
glm::mat4 modelMatrix;
}; | 22.580645 | 93 | 0.734286 | [
"transform"
] |
7d2b60269e4aafd22e54946be77bf99920d7a08f | 9,301 | h | C | BeatDetektor.h | cjcliffe/CubicFX | 780f4e93ea261f878aa0e917a9f3e5ef4313759e | [
"MIT"
] | 1 | 2021-06-20T07:31:12.000Z | 2021-06-20T07:31:12.000Z | BeatDetektor.h | cjcliffe/CubicFX | 780f4e93ea261f878aa0e917a9f3e5ef4313759e | [
"MIT"
] | null | null | null | BeatDetektor.h | cjcliffe/CubicFX | 780f4e93ea261f878aa0e917a9f3e5ef4313759e | [
"MIT"
] | 2 | 2019-03-25T19:25:29.000Z | 2021-04-07T01:21:30.000Z | #pragma once
/*
* BeatDetektor.h
*
* BeatDetektor - CubicFX Visualizer Beat Detection & Analysis Algorithm
*
* Created by Charles J. Cliffe on 09-11-30.
* Copyright 2009 Charles J. Cliffe. All rights reserved.
*
* BeatDetektor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BeatDetektor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact cj@cubicproductions.com if you seek alternate
* licensing terms for your project.
*
*/
/*
BeatDetektor class
Theory:
Trigger detection is performed using a trail of moving averages,
The FFT input is broken up into 128 ranges and averaged, each range has two moving
averages that tail each other at a rate of (1.0 / BD_DETECTION_RATE) seconds.
Each time the moving average for a range exceeds it's own tailing average by:
(moving_average[range] * BD_DETECTION_FACTOR >= moving_average[range])
if this is true there's a rising edge and a detection is flagged for that range.
Next a trigger gap test is performed between rising edges and timestamp recorded.
If the gap is larger than our BPM window (in seconds) then we can discard it and
reset the timestamp for a new detection -- but only after checking to see if it's a
reasonable match for 2* the current detection in case it's only triggered every
other beat. Gaps that are lower than the BPM window are ignored and the last
timestamp will not be reset.
Gaps that are within a reasonable window are run through a quality stage to determine
how 'close' they are to that channel's current prediction and are incremented or
decremented by a weighted value depending on accuracy. Repeated hits of low accuracy
will still move a value towards erroneous detection but it's quality will be lowered
and will not be eligible for the gap time quality draft.
Once quality has been assigned ranges are reviewed for good match candidates and if
BD_MINIMUM_CONTRIBUTIONS or more ranges achieve a decent ratio (with a factor of
BD_QUALITY_TOLERANCE) of contribution to the overall quality we take them into the
contest round. Note that the contest round won't run on a given process() call if
the total quality achieved does not meet or exceed BD_QUALITY_TOLERANCE.
Each time through if a select draft of BPM ranges has achieved a reasonable quality
above others it's awarded a value in the BPM contest. The BPM contest is a hash
array indexed by an integer BPM value, each draft winner is awarded BD_QUALITY_REWARD.
Finally the BPM contest is examined to determine a leader and all contest entries
are normalized to a total value of BD_FINISH_LINE, whichever range is closest to
BD_FINISH_LINE at any given point is considered to be the best guess however waiting
until a minimum contest winning value of about 20.0-25.0 will provide more accurate
results. Note that the 20-25 rule may vary with lower and higher input ranges.
A winning value that exceeds 40 or hovers around 60 (the finish line) is pretty much
a guaranteed match.
Configuration Kernel Notes:
The majority of the ratios and values have been reverse-engineered from my own
observation and visualization of information from various aspects of the detection
triggers; so not all parameters have a perfect definition nor perhaps the best value yet.
However despite this it performs very well; I had expected several more layers
before a reasonable detection would be achieved. Comments for these parameters will be
updated as analysis of their direct effect is explored.
Input Restrictions:
bpm_maximum must be within the range of (bpm_minimum*2)-1
i.e. minimum of 50 must have a maximum of 99 because 50*2 = 100
*/
#include <map>
#include <vector>
#include <math.h>
/* Original recipe
#define BD_DETECTION_RANGES 128
#define BD_DETECTION_RATE 12.0
#define BD_DETECTION_FACTOR 0.925
#define BD_QUALITY_TOLERANCE 0.96
#define BD_QUALITY_DECAY 0.95
#define BD_QUALITY_REWARD 7.0
#define BD_QUALITY_STEP 0.1
#define BD_FINISH_LINE 60.0
#define BD_MINIMUM_CONTRIBUTIONS 6
*/
/*#define BD_DETECTION_RANGES 128
#define BD_DETECTION_RATE 6.0
#define BD_DETECTION_FACTOR 0.92
#define BD_QUALITY_TOLERANCE 0.95
#define BD_QUALITY_DECAY 0.95
#define BD_QUALITY_REWARD 20.0
#define BD_QUALITY_STEP 0.075
#define BD_FINISH_LINE 200.0
#define BD_MINIMUM_CONTRIBUTIONS 4
*/
#define BD_DETECTION_RANGES 128
#define BD_DETECTION_RATE 12.0
#define BD_DETECTION_FACTOR 0.925
#define BD_QUALITY_TOLERANCE 0.96
#define BD_QUALITY_DECAY 0.95
#define BD_QUALITY_REWARD 7.0
#define BD_QUALITY_STEP 0.1
#define BD_FINISH_LINE 60.0
#define BD_MINIMUM_CONTRIBUTIONS 6
class BeatDetektor
{
public:
float BPM_MIN;
float BPM_MAX;
BeatDetektor *src;
float current_bpm;
float bpm_predict;
bool is_erratic;
float bpm_offset;
float last_timer;
float last_update;
float total_time;
std::map<int,float> draft;
std::map<int,float> fract_draft;
float detection_factor;
// float quality_minimum,
float quality_reward,quality_decay,detection_rate;
int minimum_contributions;
float quality_total, quality_avg, ma_quality_lo, ma_quality_total, ma_quality_avg, maa_quality_avg;
// current average (this sample) for range n
float a_freq_range[BD_DETECTION_RANGES];
// moving average of frequency range n
float ma_freq_range[BD_DETECTION_RANGES];
// moving average of moving average of frequency range n
float maa_freq_range[BD_DETECTION_RANGES];
// timestamp of last detection for frequecy range n
float last_detection[BD_DETECTION_RANGES];
// moving average of gap lengths
float ma_bpm_range[BD_DETECTION_RANGES];
// moving average of moving average of gap lengths
float maa_bpm_range[BD_DETECTION_RANGES];
// range n quality attribute, good match = quality+, bad match = quality-, min = 0
float detection_quality[BD_DETECTION_RANGES];
// current trigger state for range n
bool detection[BD_DETECTION_RANGES];
#if DEVTEST_BUILD
bool debugmode;
std::map<int,int> contribution_counter;
#endif
BeatDetektor(float BPM_MIN_in=100.0,float BPM_MAX_in=200.0, BeatDetektor *link_src = NULL) :
current_bpm(0.0),
bpm_predict(0),
is_erratic(false),
bpm_offset(0.0),
last_timer(0.0),
last_update(0.0),
total_time(0.0),
src(link_src),
// quality_minimum(BD_QUALITY_MINIMUM),
quality_reward(BD_QUALITY_REWARD),
detection_rate(BD_DETECTION_RATE),
minimum_contributions(BD_MINIMUM_CONTRIBUTIONS),
detection_factor(BD_DETECTION_FACTOR),
quality_total(1.0),
quality_avg(1.0),
quality_decay(BD_QUALITY_DECAY),
ma_quality_avg(0.001),
ma_quality_lo(1.0),
ma_quality_total(1.0)
#if DEVTEST_BUILD
,debugmode(false)
#endif
{
BPM_MIN = BPM_MIN_in;
BPM_MAX = BPM_MAX_in;
reset();
}
void reset(bool reset_freq=true)
{
for (int i = 0; i < BD_DETECTION_RANGES; i++)
{
// ma_bpm_range[i] = maa_bpm_range[i] = 60.0/(float)(BPM_MIN + (1.0+sin(8.0*M_PI*((float)i/(float)BD_DETECTION_RANGES))/2.0)*((BPM_MAX-BPM_MIN)/2));
ma_bpm_range[i] = maa_bpm_range[i] = 60.0/(float)(BPM_MIN+5)+ ((60.0/(float)(BPM_MAX-5)-60.0/(float)(BPM_MIN+5)) * ((float)i/(float)BD_DETECTION_RANGES));
if (reset_freq)
{
a_freq_range[i] = ma_freq_range[i] = maa_freq_range[i] = 0;
}
last_detection[i] = 0;
detection_quality[i] = 0;
detection[i] = false;
}
total_time = 0;
maa_quality_avg = 500.0;
current_bpm = bpm_offset = last_update = last_timer = 0;
#if DEVTEST_BUILD
contribution_counter.clear();
#endif
}
void process(float timer_seconds, std::vector<float> &fft_data);
};
class BeatDetektorContest
{
public:
float winning_bpm;
float winning_bpm_lo;
float win_val;
int win_bpm_int;
float win_val_lo;
int win_bpm_int_lo;
bool no_contest_decay;
float bpm_timer;
int beat_counter;
int half_counter;
int quarter_counter;
float finish_line;
float last_timer;
float last_update;
bool has_current_bpm;
std::map<int,float> bpm_contest; // 1/10th
std::map<int,float> bpm_contest_lo; // 1/1
BeatDetektorContest() :
win_val(0.0),
win_bpm_int(0),
win_val_lo(0.0),
win_bpm_int_lo(0),
no_contest_decay(false),
bpm_timer(0.0),
beat_counter(0),
half_counter(0),
quarter_counter(0),
winning_bpm(0.0),
has_current_bpm(false),
finish_line(BD_FINISH_LINE)
{
reset();
}
void reset()
{
last_timer = last_update = win_val = win_bpm_int = winning_bpm = bpm_timer = 0;
bpm_contest.clear();
bpm_contest_lo.clear();
}
void process(float timer_seconds, BeatDetektor *bd);
void run();
};
class BeatDetektorVU
{
public:
std::vector<float> vu_levels;
BeatDetektorVU()
{
vu_levels.resize(BD_DETECTION_RANGES);
for (int i = 0; i < BD_DETECTION_RANGES; i++) vu_levels[i] = 0.0;
}
void process(BeatDetektor *detector, float last_update, float current_bpm);
};
| 29.248428 | 157 | 0.757875 | [
"vector"
] |
7d2cf31a72b2c681c7f3a289fbbb0a370be78734 | 7,889 | h | C | Engine/Camera/Public/Camera/Camera.h | heretique/Atlas | 0981e7941b570ecfda1febf71b4669338ab81921 | [
"MIT"
] | 6 | 2016-11-09T08:40:10.000Z | 2021-10-06T09:47:05.000Z | Engine/Camera/Public/Camera/Camera.h | heretique/Atlas | 0981e7941b570ecfda1febf71b4669338ab81921 | [
"MIT"
] | null | null | null | Engine/Camera/Public/Camera/Camera.h | heretique/Atlas | 0981e7941b570ecfda1febf71b4669338ab81921 | [
"MIT"
] | 3 | 2016-11-09T08:38:59.000Z | 2021-12-24T16:03:59.000Z | #pragma once
#include "Hq/Math/MathTypes.h"
namespace atlas
{
/**
* The type of camera.
*/
enum class CameraType
{
ePerspective = 1,
eOrthographic = 2
};
/**
* Defines a camera which acts as a view of a scene to be rendered.
*/
class Camera
{
public:
Camera();
/**
* Destructor.
*/
~Camera();
/**
* Creates a perspective camera.
*
* @param fieldOfView The field of view in degrees for the perspective camera (normally in the range of 40-60
* degrees).
* @param aspectRatio The aspect ratio of the camera (normally the width of the viewport divided by the height of
* the viewport).
* @param nearPlane The near plane distance.
* @param farPlane The far plane distance.
*/
void setPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane);
/**
* Creates an orthographic camera.
*
* @param zoomX The zoom factor along the X-axis of the orthographic projection (the width of the ortho projection).
* @param zoomY The zoom factor along the Y-axis of the orthographic projection (the height of the ortho
* projection).
* @param aspectRatio The aspect ratio of the orthographic projection.
* @param nearPlane The near plane distance.
* @param farPlane The far plane distance.
*/
void setOrthographic(float zoomX, float zoomY, float aspectRatio, float nearPlane, float farPlane);
void setTransform(const hq::math::Mat4x4& transform);
/**
* Gets the type of camera.
*
* @return The camera type.
*/
CameraType getCameraType() const;
/**
* Gets the field of view for a perspective camera.
*
* @return The field of view.
*/
float getFieldOfView() const;
/**
* Sets the field of view.
*
* @param fieldOfView The field of view.
*/
void setFieldOfView(float fieldOfView);
/**
* Gets the x-zoom (magnification) for an orthographic camera.
* Default is 1.0f.
*
* @return The magnification (zoom) for x.
*/
float getZoomX() const;
/**
* Sets the x-zoom (magnification) for a orthographic camera.
* Default is 1.0f.
*
* @param zoomX The magnification (zoom) for x.
*/
void setZoomX(float zoomX);
/**
* Gets the y-zoom (magnification) for a orthographic camera.
* Default is 1.0f.
*
* @return The magnification (zoom) for y.
*/
float getZoomY() const;
/**
* Sets the y-zoom (magnification) for a orthographic camera.
*
* @param zoomY The magnification (zoom) for y.
*/
void setZoomY(float zoomY);
/**
* Gets the aspect ratio.
*
* @return The aspect ratio.
*/
float getAspectRatio() const;
/**
* Sets the aspect ratio.
*
* @param aspectRatio The aspect ratio.
*/
void setAspectRatio(float aspectRatio);
/**
* Gets the near z clipping plane distance.
*
* @return The near z clipping plane distance.
*/
float getNearPlane() const;
/**
* Sets the near z clipping plane distance.
*
* @param nearPlane The near z clipping plane distance.
*/
void setNearPlane(float nearPlane);
/**
* Gets the far z clipping plane distance.
*
* @return The far z clipping plane distance.
*/
float getFarPlane() const;
/**
* Sets the far z clipping plane distance.
*
* @param farPlane The far z clipping plane distance.
*/
void setFarPlane(float farPlane);
/**
* Gets the camera's view matrix.
*
* @return The camera view matrix.
*/
const hq::math::Mat4x4& getViewMatrix() const;
/**
* Gets the camera's inverse view matrix.
*
* @return The camera inverse view matrix.
*/
const hq::math::Mat4x4& getInverseViewMatrix() const;
/**
* Gets the camera's projection matrix.
*
* @return The camera projection matrix.
*/
const hq::math::Mat4x4& getProjectionMatrix() const;
/**
* Resets the camera to use the internally computed projection matrix
* instead of any previously specified user-defined matrix.
*/
void resetProjectionMatrix();
/**
* Gets the camera's view * projection matrix.
*
* @return The camera view * projection matrix.
*/
const hq::math::Mat4x4& getViewProjectionMatrix() const;
/**
* Gets the camera's inverse view * projection matrix.
*
* @return The camera inverse view * projection matrix.
*/
const hq::math::Mat4x4& getInverseViewProjectionMatrix() const;
/**
* Gets the view bounding frustum.
*
* @return The viewing bounding frustum.
*/
const hq::math::Frustum& getFrustum() const;
/**
* Projects the specified world position into the viewport coordinates.
*
* @param viewport The viewport rectangle to use.
* @param position The world space position.
* @param x The returned viewport x coordinate.
* @param y The returned viewport y coordinate.
* @param depth The returned pixel depth (can be NULL).
*
* @script{ignore}
*/
void project(const hq::math::Rect& viewport, const hq::math::Vec3& position, float& x, float& y,
float& depth) const;
/**
* Projects the specified world position into the viewport coordinates.
*
* @param viewport The viewport rectangle to use.
* @param position The world space position.
* @param out Populated with the resulting screen-space position.
*/
void project(const hq::math::Rect& viewport, const hq::math::Vec3& position, hq::math::Vec2& out) const;
/**
* Projects the specified world position into the viewport coordinates.
*
* @param viewport The viewport rectangle to use.
* @param position The world space position.
* @param out Populated with the resulting screen-space position, with the pixel depth in the Z coordinate.
*/
void project(const hq::math::Rect& viewport, const hq::math::Vec3& position, hq::math::Vec3& out) const;
/**
* Converts a viewport-space coordinate to a world-space position for the given depth value.
*
* The depth parameter is a value ranging between 0 and 1, where 0 returns a point on the
* near clipping plane and 1 returns a point on the far clipping plane.
*
* @param viewport The viewport rectangle to use.
* @param x The viewport-space x coordinate.
* @param y The viewport-space y coordinate.
* @param depth The depth range.
* @param dst The world space position.
*/
void unproject(const hq::math::Rect& viewport, float x, float y, float depth, hq::math::Vec3& dst) const;
/**
* Picks a ray that can be used for picking given the specified viewport-space coordinates.
*
* @param viewport The viewport rectangle to use.
* @param x The viewport x-coordinate.
* @param y The viewport y-coordinate.
* @param dst The computed pick ray.
*/
void pickRay(const hq::math::Rect& viewport, float x, float y, hq::math::Ray3& dst) const;
protected:
void updateCamera(const hq::math::Mat4x4& transform = hq::math::Mat4x4::Identity);
private:
CameraType _cameraType {CameraType::ePerspective};
float _fieldOfView;
float _zoom[2];
float _aspectRatio;
float _nearPlane;
float _farPlane;
mutable hq::math::Mat4x4 _view{hq::math::Mat4x4::Identity};
mutable hq::math::Mat4x4 _projection;
mutable hq::math::Mat4x4 _viewProjection;
mutable hq::math::Mat4x4 _inverseView;
mutable hq::math::Mat4x4 _inverseViewProjection;
mutable hq::math::Frustum _bounds;
};
}
| 29.110701 | 120 | 0.626695 | [
"transform"
] |
7d38fe03b0aded13eeda18fc21325cf6e1e03943 | 3,041 | h | C | source/Irrlicht/CD3D9Texture.h | flaithbheartaigh/mirrlicht | ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b | [
"IJG"
] | null | null | null | source/Irrlicht/CD3D9Texture.h | flaithbheartaigh/mirrlicht | ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b | [
"IJG"
] | null | null | null | source/Irrlicht/CD3D9Texture.h | flaithbheartaigh/mirrlicht | ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b | [
"IJG"
] | null | null | null | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_DIRECTX9_TEXTURE_H_INCLUDED__
#define __C_DIRECTX9_TEXTURE_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_DIRECT3D_9_
#include "ITexture.h"
#include "IImage.h"
#include <d3d9.h>
namespace irr
{
namespace video
{
class CD3D9Driver;
/*!
interface for a Video Driver dependent Texture.
*/
class CD3D9Texture : public ITexture
{
public:
//! constructor
CD3D9Texture(IImage* image, CD3D9Driver* driver,
u32 flags, const char* name);
//! rendertarget constructor
CD3D9Texture(CD3D9Driver* driver, core::dimension2d<s32> size, const char* name);
//! destructor
virtual ~CD3D9Texture();
//! lock function
virtual void* lock();
//! unlock function
virtual void unlock();
//! Returns original size of the texture.
virtual const core::dimension2d<s32>& getOriginalSize();
//! Returns (=size) of the texture.
virtual const core::dimension2d<s32>& getSize();
//! returns driver type of texture (=the driver, who created the texture)
virtual E_DRIVER_TYPE getDriverType();
//! returns color format of texture
virtual ECOLOR_FORMAT getColorFormat() const;
//! returns pitch of texture (in bytes)
virtual u32 getPitch() const;
//! returns the DIRECT3D9 Texture
IDirect3DTexture9* getDX9Texture();
//! returns if texture has mipmap levels
bool hasMipMaps();
//! Regenerates the mip map levels of the texture. Useful after locking and
//! modifying the texture
virtual void regenerateMipMapLevels();
//! returns if it is a render target
bool isRenderTarget();
//! Returns pointer to the render target surface
IDirect3DSurface9* getRenderTargetSurface();
private:
void createRenderTarget();
//! returns the size of a texture which would be the optimize size for rendering it
inline s32 getTextureSizeFromImageSize(s32 size);
//! creates the hardware texture
void createTexture(u32 flags);
//! copies the image to the texture
bool copyTexture();
//! optimized for 16 bit to 16 copy.
bool copyTo16BitTexture();
//! copies texture to 32 bit hardware texture
bool copyTo32BitTexture();
bool createMipMaps(s32 level=1);
void copy16BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt);
void copy32BitMipMap(char* src, char* tgt,
s32 width, s32 height, s32 pitchsrc, s32 pitchtgt);
IImage* Image;
IDirect3DDevice9* Device;
IDirect3DTexture9* Texture;
IDirect3DSurface9* RTTSurface;
CD3D9Driver* Driver;
core::dimension2d<s32> TextureSize;
core::dimension2d<s32> ImageSize;
s32 Pitch;
ECOLOR_FORMAT ColorFormat;
bool HasMipMaps;
bool HardwareMipMaps;
bool IsRenderTarget;
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_DIRECT3D_9_
#endif // __C_DIRECTX9_TEXTURE_H_INCLUDED__
| 24.328 | 85 | 0.720816 | [
"render"
] |
7d3cec6f6470fda70a3a1513fbb3e0073757f513 | 2,824 | h | C | thirdparty/sfs2x/Util/CryptoInitializer.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2020-05-14T07:48:32.000Z | 2021-02-03T14:58:11.000Z | thirdparty/sfs2x/Util/CryptoInitializer.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 1 | 2020-05-28T16:39:20.000Z | 2020-05-28T16:39:20.000Z | thirdparty/sfs2x/Util/CryptoInitializer.h | godot-addons/godot-sfs2x | a8d52aa9d548f6d45bbb64bfdaacab0df10e67c1 | [
"MIT"
] | 2 | 2018-07-07T20:15:00.000Z | 2018-10-26T05:18:30.000Z | // ===================================================================
//
// Description
// Helper class for crypting
//
// Revision history
// Date Description
// 01-May-2015 First version
//
// ===================================================================
#ifndef __CryptoInitializer__
#define __CryptoInitializer__
#include "./Common.h"
#include "../SmartFox.h"
#include <boost/shared_ptr.hpp> // Boost Asio shared pointer
#if defined(_MSC_VER)
#pragma warning(disable:4786) // STL library: disable warning 4786; this warning is generated due to a Microsoft bug
#endif
#include <string> // STL library: string object
using namespace std; // STL library: declare the STL namespace
namespace Sfs2X {
namespace Util {
/// <summary>
/// Initializer for encryption
/// </summary>
class CryptoInitializer
{
public:
// -------------------------------------------------------------------
// Public methods
// -------------------------------------------------------------------
CryptoInitializer(boost::shared_ptr<SmartFox> sfs);
/// <summary>
/// Initialize encryption
/// </summary>
void Run();
// -------------------------------------------------------------------
// Public members
// -------------------------------------------------------------------
static boost::shared_ptr<string> KEY_SESSION_TOKEN;
static boost::shared_ptr<string> TARGET_SERVLET;
protected:
// -------------------------------------------------------------------
// Protected methods
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// Protected members
// -------------------------------------------------------------------
private:
// -------------------------------------------------------------------
// Private methods
// -------------------------------------------------------------------
void RunHelper();
bool RunHelperAsync();
bool RunHelperSSLAsync();
void OnHttpResponse(boost::shared_ptr<string> rawData);
void OnHttpError(boost::shared_ptr<string> errorMsg);
boost::shared_ptr<ByteArray> DecodeResponse (boost::shared_ptr<string> rawData);
// -------------------------------------------------------------------
// Private members
// -------------------------------------------------------------------
boost::shared_ptr<SmartFox> sfs;
boost::shared_ptr<string> key; // This is the session key retrieved by RunHelperAsync/RunHelperSSLAsync that for linux compatibility is stored as local variabile instead of returned from methods
boost::shared_ptr<string> errorMessage; // This is the error string if it exists
bool useHttps;
};
} // namespace Util
} // namespace Sfs2X
#endif
| 32.090909 | 198 | 0.453258 | [
"object"
] |
7d405521a52e36ad136b1c1dd47f12c40b285b1a | 800 | h | C | taichi/backends/cc/cc_program.h | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | taichi/backends/cc/cc_program.h | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | taichi/backends/cc/cc_program.h | inkydragon/taichi | b5f80c2771b578c2a32b9a024a351aafc8ca7a0b | [
"MIT"
] | null | null | null | #pragma once
#include "taichi/lang_util.h"
#include <vector>
#include <memory>
TI_NAMESPACE_BEGIN
class DynamicLoader;
TI_NAMESPACE_END
TLANG_NAMESPACE_BEGIN
namespace cccp {
class CCKernel;
class CCLayout;
class CCRuntime;
using CCFuncEntryType = void();
class CCProgram {
// Launch C compiler to compile generated source code, and run them
public:
CCProgram();
~CCProgram();
void add_kernel(std::unique_ptr<CCKernel> kernel);
CCFuncEntryType *load_kernel(std::string const &name);
void init_runtime();
void relink();
std::vector<std::unique_ptr<CCKernel>> kernels;
std::unique_ptr<CCRuntime> runtime;
std::unique_ptr<CCLayout> layout;
std::unique_ptr<DynamicLoader> dll;
std::string dll_path;
bool need_relink{true};
};
} // namespace cccp
TLANG_NAMESPACE_END
| 19.047619 | 69 | 0.75125 | [
"vector"
] |
7d423d4add1596eaf249ccdf3db9d71772543748 | 3,531 | h | C | common/inc/qcc/SecureAllocator.h | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | common/inc/qcc/SecureAllocator.h | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | common/inc/qcc/SecureAllocator.h | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /**
* @file
*
* Custom allocator for STL container that will securely delete
* contents on memory deletion.
*/
/******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
#ifndef _QCC_SECUREALLOCATOR_H
#define _QCC_SECUREALLOCATOR_H
#include <qcc/platform.h>
#include <cstddef>
#include <memory>
#include <qcc/Util.h>
namespace qcc {
/**
* This class is an allocator that may be used by any STL container where there
* is a need to ensure that the contained data is securely deleted when the
* memory gets deallocated.
*/
template <class T>
class SecureAllocator : public std::allocator<T> {
public:
typedef std::size_t size_type; ///< typedef conforming to STL usage
typedef T* pointer; ///< typedef conforming to STL usage
typedef const T* const_pointer; ///< typedef conforming to STL usage
/**
* A class that enables an allocator for objects of one type to create
* storage for another type.
*/
template <typename U>
struct rebind {
typedef SecureAllocator<U> other;
};
/** Constructor */
SecureAllocator() : std::allocator<T>() { }
/** Copy Constructor */
SecureAllocator(const SecureAllocator& a) : std::allocator<T>(a) { }
/** Copy Constructor */
template <typename U>
SecureAllocator(const SecureAllocator<U>& a) : std::allocator<T>(a) { }
/** Destructor */
virtual ~SecureAllocator() { }
/** Allocate memory */
virtual pointer allocate(size_type n, const_pointer hint = 0) {
return std::allocator<T>::allocate(n, hint);
}
/** Deallocate memory, but securely wipe it out first. */
virtual void deallocate(pointer p, size_type n) {
ClearMemory(p, n * sizeof(T));
std::allocator<T>::deallocate(p, n);
}
};
/**
* Append the contents of a string to a vector<uint8_t, SecureAllocator<uint8_t> >.
*
* @param str String to be added.
* @param v Vector to be added to.
*/
void AJ_CALL AppendStringToSecureVector(const qcc::String& str, std::vector<uint8_t, SecureAllocator<uint8_t> >& v);
}
#endif // _QCC_SECUREALLOCATOR_H
| 33.628571 | 116 | 0.657887 | [
"vector"
] |
7d49597c127ab09d2b4f8b4ee2b9dcd00b1b22ad | 1,272 | h | C | tests/libs/adios/src/core/transforms/plugindetect/detect_plugin_write_hook_reg.h | utdsimmons/ohpc | 70dc728926a835ba049ddd3f4627ef08db7c95a0 | [
"Apache-2.0"
] | 692 | 2015-11-12T13:56:43.000Z | 2022-03-30T03:45:59.000Z | tests/libs/adios/src/core/transforms/plugindetect/detect_plugin_write_hook_reg.h | utdsimmons/ohpc | 70dc728926a835ba049ddd3f4627ef08db7c95a0 | [
"Apache-2.0"
] | 1,096 | 2015-11-12T09:08:22.000Z | 2022-03-31T21:48:41.000Z | tests/libs/adios/src/core/transforms/plugindetect/detect_plugin_write_hook_reg.h | utdsimmons/ohpc | 70dc728926a835ba049ddd3f4627ef08db7c95a0 | [
"Apache-2.0"
] | 224 | 2015-11-12T21:17:03.000Z | 2022-03-30T00:57:48.000Z | /*
* detect_plugin_write_hooks.h
*
* Using the plugin registry, (src/transforms/transform_plugins.h), builds the
* table of transform plugin write-side hooks. This should be included
* inside a C file, as it defines a global table with memory.
*
* Created on: Apr 1, 2013
* Author: David A. Boyuka II
*/
#ifndef DETECT_PLUGIN_WRITE_HOOKS_H_
#define DETECT_PLUGIN_WRITE_HOOKS_H_
// INPUT MACRO: Plugins will be registered in the table TRANSFORM_WRITE_METHODS
// NOTE: Uses the adios_transform_write_method struct from this include
// NOTE: Uses the REGISTER_TRANSFORM_WRITE_METHOD_HOOKS macro from this include
#include "src/core/transforms/adios_transforms_hooks_write.h"
// SETUP - Set up detection macro
#define REGISTER_TRANSFORM_PLUGIN(TYPEID, XMLALIAS, UID, DESC) \
REGISTER_TRANSFORM_WRITE_METHOD_HOOKS(TRANSFORM_WRITE_METHODS, TYPEID, adios_transform_##TYPEID) // From adios_transforms_hooks_write.h
// DETECT
REGISTER_TRANSFORM_WRITE_METHOD_HOOKS(TRANSFORM_WRITE_METHODS, none, adios_transform_none); // Stub for "none" method
#include "transforms/transform_plugins.h" // Translate plugin register entries into function declarations
// CLEANUP - Clean up macro
#undef REGISTER_TRANSFORM_PLUGIN
#endif /* DETECT_PLUGIN_WRITE_HOOKS_H_ */
| 38.545455 | 139 | 0.798742 | [
"transform"
] |
7d73333b16c525dd5c0a769b9062acde10df0452 | 3,392 | c | C | src/common/modobject.c | kalyanam-FMTGA/ray-original | f4f57896015c1c29ca571069b007c409d74824e0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/common/modobject.c | kalyanam-FMTGA/ray-original | f4f57896015c1c29ca571069b007c409d74824e0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/common/modobject.c | kalyanam-FMTGA/ray-original | f4f57896015c1c29ca571069b007c409d74824e0 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #ifndef lint
static const char RCSid[] = "$Id: modobject.c,v 2.13 2013/03/09 18:53:05 greg Exp $";
#endif
/*
* Routines for tracking object modifiers
*
* External symbols declared in object.h
*/
#include "copyright.h"
#include "standard.h"
#include "object.h"
#include "otypes.h"
static struct ohtab {
int hsiz; /* current table size */
OBJECT *htab; /* table, if allocated */
} modtab = {100, NULL}, objtab = {1000, NULL}; /* modifiers and objects */
static int otndx(char *, struct ohtab *);
OBJECT
objndx( /* get object number from pointer */
OBJREC *op
)
{
int i, j;
for (i = nobjects>>OBJBLKSHFT; i >= 0; i--) {
j = op - objblock[i];
if ((j >= 0) & (j < OBJBLKSIZ))
return((i<<OBJBLKSHFT) + j);
}
return(OVOID);
}
OBJECT
lastmod( /* find modifier definition before obj */
OBJECT obj,
char *mname
)
{
OBJREC *op;
int i;
i = modifier(mname); /* try hash table first */
if ((obj == OVOID) | (i < obj))
return(i);
for (i = obj; i-- > 0; ) { /* need to search */
op = objptr(i);
if (ismodifier(op->otype) && op->oname[0] == mname[0] &&
!strcmp(op->oname, mname))
return(i);
}
return(OVOID);
}
OBJECT
modifier( /* get a modifier number from its name */
char *mname
)
{
int ndx;
ndx = otndx(mname, &modtab);
return(modtab.htab[ndx]);
}
#ifdef GETOBJ
OBJECT
object( /* get an object number from its name */
char *oname
)
{
int ndx;
ndx = otndx(oname, &objtab);
return(objtab.htab[ndx]);
}
#endif
void
insertobject( /* insert new object into our list */
OBJECT obj
)
{
int i;
if (ismodifier(objptr(obj)->otype)) {
i = otndx(objptr(obj)->oname, &modtab);
modtab.htab[i] = obj;
}
#ifdef GETOBJ
else {
i = otndx(objptr(obj)->oname, &objtab);
objtab.htab[i] = obj;
}
#endif
for (i = 0; addobjnotify[i] != NULL; i++)
(*addobjnotify[i])(obj);
}
void
clearobjndx(void) /* clear object hash tables */
{
if (modtab.htab != NULL) {
free((void *)modtab.htab);
modtab.htab = NULL;
modtab.hsiz = 100;
}
if (objtab.htab != NULL) {
free((void *)objtab.htab);
objtab.htab = NULL;
objtab.hsiz = 100;
}
}
static int
nexthsiz( /* return next hash table size */
int oldsiz
)
{
static int hsiztab[] = {
251, 509, 1021, 2039, 4093, 8191, 16381, 0
};
int *hsp;
for (hsp = hsiztab; *hsp; hsp++)
if (*hsp > oldsiz)
return(*hsp);
return(oldsiz*2 + 1); /* not always prime */
}
static int
otndx( /* get object table index for name */
char *name,
struct ohtab *tab
)
{
OBJECT *oldhtab;
int hval, i;
int ndx;
if (tab->htab == NULL) { /* new table */
tab->hsiz = nexthsiz(tab->hsiz);
tab->htab = (OBJECT *)malloc(tab->hsiz*sizeof(OBJECT));
if (tab->htab == NULL)
error(SYSTEM, "out of memory in otndx");
ndx = tab->hsiz;
while (ndx--) /* empty it */
tab->htab[ndx] = OVOID;
}
/* look up object */
hval = shash(name);
tryagain:
for (i = 0; i < tab->hsiz; i++) {
ndx = (hval + (unsigned long)i*i) % tab->hsiz;
if (tab->htab[ndx] == OVOID ||
!strcmp(objptr(tab->htab[ndx])->oname, name))
return(ndx);
}
/* table is full, reallocate */
oldhtab = tab->htab;
ndx = tab->hsiz;
tab->htab = NULL;
while (ndx--)
if (oldhtab[ndx] != OVOID) {
i = otndx(objptr(oldhtab[ndx])->oname, tab);
tab->htab[i] = oldhtab[ndx];
}
free((void *)oldhtab);
goto tryagain; /* should happen only once! */
}
| 18.236559 | 85 | 0.592276 | [
"object"
] |
7d812e8025bd07310ea37ad1e9598135a738ca65 | 5,731 | c | C | src/box/sql/attach.c | GreeD3X/tarantool | b51f698762844a591a49596c52222cfd179bfdf8 | [
"BSD-2-Clause"
] | null | null | null | src/box/sql/attach.c | GreeD3X/tarantool | b51f698762844a591a49596c52222cfd179bfdf8 | [
"BSD-2-Clause"
] | null | null | null | src/box/sql/attach.c | GreeD3X/tarantool | b51f698762844a591a49596c52222cfd179bfdf8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This file contains code used to implement the ATTACH and DETACH commands.
*/
#include "sqliteInt.h"
/*
* Initialize a DbFixer structure. This routine must be called prior
* to passing the structure to one of the sqliteFixAAAA() routines below.
*/
void
sqlite3FixInit(DbFixer * pFix, /* The fixer to be initialized */
Parse * pParse, /* Error messages will be written here */
const char *zType, /* "view", "trigger", or "index" */
const Token * pName /* Name of the view, trigger, or index */
)
{
sqlite3 *db;
db = pParse->db;
pFix->pParse = pParse;
pFix->pSchema = db->mdb.pSchema;
pFix->zType = zType;
pFix->pName = pName;
pFix->bVarOnly = 0;
}
/*
* The following set of routines walk through the parse tree and assign
* a specific database to all table references where the database name
* was left unspecified in the original SQL statement. The pFix structure
* must have been initialized by a prior call to sqlite3FixInit().
*
* These routines are used to make sure that an index, trigger, or
* view in one database does not refer to objects in a different database.
* (Exception: indices, triggers, and views in the TEMP database are
* allowed to refer to anything.) If a reference is explicitly made
* to an object in a different database, an error message is added to
* pParse->zErrMsg and these routines return non-zero. If everything
* checks out, these routines return 0.
*/
int
sqlite3FixSrcList(DbFixer * pFix, /* Context of the fixation */
SrcList * pList /* The Source list to check and modify */
)
{
int i;
struct SrcList_item *pItem;
if (NEVER(pList == 0))
return 0;
for (i = 0, pItem = pList->a; i < pList->nSrc; i++, pItem++) {
if (pFix->bVarOnly == 0) {
pItem->pSchema = pFix->pSchema;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
if (sqlite3FixSelect(pFix, pItem->pSelect))
return 1;
if (sqlite3FixExpr(pFix, pItem->pOn))
return 1;
#endif
}
return 0;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
int
sqlite3FixSelect(DbFixer * pFix, /* Context of the fixation */
Select * pSelect /* The SELECT statement to be fixed to one database */
)
{
while (pSelect) {
if (sqlite3FixExprList(pFix, pSelect->pEList)) {
return 1;
}
if (sqlite3FixSrcList(pFix, pSelect->pSrc)) {
return 1;
}
if (sqlite3FixExpr(pFix, pSelect->pWhere)) {
return 1;
}
if (sqlite3FixExprList(pFix, pSelect->pGroupBy)) {
return 1;
}
if (sqlite3FixExpr(pFix, pSelect->pHaving)) {
return 1;
}
if (sqlite3FixExprList(pFix, pSelect->pOrderBy)) {
return 1;
}
if (sqlite3FixExpr(pFix, pSelect->pLimit)) {
return 1;
}
if (sqlite3FixExpr(pFix, pSelect->pOffset)) {
return 1;
}
pSelect = pSelect->pPrior;
}
return 0;
}
int
sqlite3FixExpr(DbFixer * pFix, /* Context of the fixation */
Expr * pExpr /* The expression to be fixed to one database */
)
{
while (pExpr) {
if (pExpr->op == TK_VARIABLE) {
if (pFix->pParse->db->init.busy) {
pExpr->op = TK_NULL;
} else {
sqlite3ErrorMsg(pFix->pParse,
"%s cannot use variables",
pFix->zType);
return 1;
}
}
if (ExprHasProperty(pExpr, EP_TokenOnly | EP_Leaf))
break;
if (ExprHasProperty(pExpr, EP_xIsSelect)) {
if (sqlite3FixSelect(pFix, pExpr->x.pSelect))
return 1;
} else {
if (sqlite3FixExprList(pFix, pExpr->x.pList))
return 1;
}
if (sqlite3FixExpr(pFix, pExpr->pRight)) {
return 1;
}
pExpr = pExpr->pLeft;
}
return 0;
}
int
sqlite3FixExprList(DbFixer * pFix, /* Context of the fixation */
ExprList * pList /* The expression to be fixed to one database */
)
{
int i;
struct ExprList_item *pItem;
if (pList == 0)
return 0;
for (i = 0, pItem = pList->a; i < pList->nExpr; i++, pItem++) {
if (sqlite3FixExpr(pFix, pItem->pExpr)) {
return 1;
}
}
return 0;
}
#endif
#ifndef SQLITE_OMIT_TRIGGER
int
sqlite3FixTriggerStep(DbFixer * pFix, /* Context of the fixation */
TriggerStep * pStep /* The trigger step be fixed to one database */
)
{
while (pStep) {
if (sqlite3FixSelect(pFix, pStep->pSelect)) {
return 1;
}
if (sqlite3FixExpr(pFix, pStep->pWhere)) {
return 1;
}
if (sqlite3FixExprList(pFix, pStep->pExprList)) {
return 1;
}
pStep = pStep->pNext;
}
return 0;
}
#endif
| 28.093137 | 76 | 0.683476 | [
"object"
] |
7d85e3312505c570bec486b957f3a408e28ef3b5 | 28,708 | h | C | zdnn/zdnn_private.h | n-marion/zDNN | 5966eddb57292e1d794c07ec7f2b9a126e7d4022 | [
"Apache-2.0"
] | 10 | 2021-09-11T11:28:23.000Z | 2022-03-26T03:18:22.000Z | site/zDNN/zdnn/zdnn_private.h | IBM/ai-on-z-101 | f2271134b04a66627f324fd536de2a0cf5a7975b | [
"Apache-2.0"
] | 1 | 2022-03-03T19:16:03.000Z | 2022-03-03T19:16:03.000Z | site/zDNN/zdnn/zdnn_private.h | IBM/ai-on-z-101 | f2271134b04a66627f324fd536de2a0cf5a7975b | [
"Apache-2.0"
] | 3 | 2021-10-01T15:35:38.000Z | 2022-02-04T22:38:09.000Z | // SPDX-License-Identifier: Apache-2.0
/*
* Copyright IBM Corp. 2021
*
* 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.
*/
#ifndef ZDNN_ZDNN_PRIVATE_H_
#define ZDNN_ZDNN_PRIVATE_H_
#include <stdarg.h>
#include <stdio.h>
// -----------------------------------------------------------------------------
// convert_hw.c includes
// -----------------------------------------------------------------------------
#if defined(__MVS__) // If z/OS, use XL C include and typedef
#include <builtins.h> // needed for XL C vector ops
#else // If LoZ, use gcc include and typedef
#include <s390intrin.h> // needed for LoZ vector ops
#endif
#include "../config.h"
#define AIU_BYTES_PER_STICK 128
#define AIU_2BYTE_CELLS_PER_STICK 64
#define AIU_2BYTE_CELL_SIZE 2
#define AIU_STICKS_PER_PAGE 32
#define AIU_PAGESIZE_IN_BYTES 4096
#define ZDNN_MAX_DIMS 4 // number of dims in AIU's Tensor Descriptor
typedef enum log_levels {
LOGLEVEL_OFF,
LOGLEVEL_FATAL,
LOGLEVEL_ERROR,
LOGLEVEL_WARN,
LOGLEVEL_INFO,
LOGLEVEL_DEBUG,
LOGLEVEL_TRACE,
} log_levels;
typedef enum elements_mode {
ELEMENTS_AIU,
ELEMENTS_PRE,
ELEMENTS_PRE_SINGLE_GATE = ELEMENTS_PRE,
ELEMENTS_PRE_ALL_GATES
} elements_mode;
#define LOGMODULE_SIZE 1024
extern log_levels log_level;
extern bool precheck_enabled;
extern uint32_t status_diag;
extern char log_module[LOGMODULE_SIZE];
#define ENVVAR_LOGLEVEL "ZDNN_LOGLEVEL"
#define ENVVAR_ENABLE_PRECHECK "ZDNN_ENABLE_PRECHECK"
#define ENVVAR_STATUS_DIAG "ZDNN_STATUS_DIAG"
#define ENVVAR_LOGMODULE "ZDNN_LOGMODULE"
#define STATUS_DIAG_NOT_SET -1
#define DCL_EXTERN_STATUS_STR(a) extern const char *STATUS_STR_##a;
DCL_EXTERN_STATUS_STR(ZDNN_OK)
DCL_EXTERN_STATUS_STR(ZDNN_ELEMENT_RANGE_VIOLATION)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_SHAPE)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_LAYOUT)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_TYPE)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_FORMAT)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_DIRECTION)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_CONCAT_INFO)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_STRIDE_PADDING)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_STRIDES)
DCL_EXTERN_STATUS_STR(ZDNN_MISALIGNED_PARMBLOCK)
DCL_EXTERN_STATUS_STR(ZDNN_ALLOCATION_FAILURE)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_BUFFER)
DCL_EXTERN_STATUS_STR(ZDNN_CONVERT_FAILURE)
DCL_EXTERN_STATUS_STR(ZDNN_INVALID_STATE)
DCL_EXTERN_STATUS_STR(ZDNN_UNSUPPORTED_AIU_EXCEPTION)
DCL_EXTERN_STATUS_STR(ZDNN_UNSUPPORTED_PARMBLOCK)
DCL_EXTERN_STATUS_STR(ZDNN_UNAVAILABLE_FUNCTION)
DCL_EXTERN_STATUS_STR(ZDNN_UNSUPPORTED_FORMAT)
DCL_EXTERN_STATUS_STR(ZDNN_UNSUPPORTED_TYPE)
DCL_EXTERN_STATUS_STR(ZDNN_EXCEEDS_MDIS)
DCL_EXTERN_STATUS_STR(ZDNN_EXCEEDS_MTS)
DCL_EXTERN_STATUS_STR(ZDNN_MISALIGNED_TENSOR)
DCL_EXTERN_STATUS_STR(ZDNN_MISALIGNED_SAVEAREA)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F000)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F001)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F002)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F003)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F004)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F005)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F006)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F007)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F008)
DCL_EXTERN_STATUS_STR(ZDNN_FUNC_RC_F009)
#undef DCL_EXTERN_STATUS_STR
/*
* NNPA use of register 0
*/
typedef union nnpa_return {
uint64_t r0; // for reading from and writing to r0
struct fields {
uint16_t rc; // response code, bits [0-15]
uint8_t rsvd1; // reserved, bits [16-23]
uint8_t ef; // exception flags, bits [24-31]
uint8_t rsvd2[3]; // reserved, bits [32-55]
uint8_t fc; // function code, bits [56-63]
} fields;
} nnpa_return;
/*
* To interface to the zAIU through the NNPA instruction requires the following
* parameter blocks
*/
typedef
#ifdef __MVS__
_Packed
#endif
struct nnpa_tensor_descriptor {
uint8_t data_layout_format;
uint8_t data_type;
uint8_t reserve1[6];
uint32_t dim4_index_size;
uint32_t dim3_index_size;
uint32_t dim2_index_size;
uint32_t dim1_index_size;
uint64_t *tensor_data_addr;
}
#ifndef __MVS__
__attribute__((packed))
#endif
nnpa_tensor_descriptor;
// BIG ENDIAN 128-bits bits-field, most significant bit is bit 0
typedef
#ifdef __MVS__
_Packed
#endif
struct bit128_t {
uint64_t bits_0to63;
uint64_t bits_64to127;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bit128_t;
// BIG ENDIAN 256-bits bits-field, most significant bit is bit 0
typedef
#ifdef __MVS__
_Packed
#endif
struct bit256_t {
uint64_t bits_0to63;
uint64_t bits_64to127;
uint64_t bits_128to191;
uint64_t bits_192to255;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bit256_t;
typedef
#ifdef __MVS__
_Packed
#endif
struct nnpa_parameter_block {
uint16_t parm_block_version_number; // first 9 bits must be 0
uint8_t model_version_number; // Only set by hardware for continuation.
uint8_t reserved_for_ibm[3];
uint16_t reserved1; // 1 bit Continuation Flag at end
uint8_t reserved2[48];
uint64_t function_specific_save_area_address;
nnpa_tensor_descriptor output_tensor1;
nnpa_tensor_descriptor output_tensor2;
uint8_t reserved3[64];
nnpa_tensor_descriptor input_tensor1;
nnpa_tensor_descriptor input_tensor2;
nnpa_tensor_descriptor input_tensor3;
uint8_t reserved4[96];
uint32_t function_specific_parm1;
uint32_t function_specific_parm2;
uint32_t function_specific_parm3;
uint32_t function_specific_parm4;
uint32_t function_specific_parm5;
uint8_t reserved5[108];
uint8_t continuation_state_buffer[3584];
}
#ifndef __MVS__
__attribute__((packed, aligned(8)))
#endif
nnpa_parameter_block
#ifdef __MVS__
__attribute__((__aligned__(8)))
#endif
;
typedef
#ifdef __MVS__
_Packed
#endif
struct nnpa_qaf_parameter_block {
bit256_t installed_functions_vector; // bit set of installed operations
bit128_t
installed_parameter_block_formats; // bit set of installed block formats
uint16_t installed_data_types; // bit set of installed data types
uint8_t reserved1[2];
uint32_t installed_data_layout_formats; // bit set of supported data layouts
uint8_t reserved2[4];
uint32_t maximum_dimension_index_size; // maximum supported number of elements
// for any single tensor dimension
uint64_t maximum_tensor_size; // maximum supported tensor size (bytes) aka
// stick-area size
uint16_t installed_dt1_conversions_vector; // bit set of installed Data-Type-1
// conversions
uint8_t reserved3[182];
}
#ifndef __MVS__
__attribute__((packed, aligned(8)))
#endif
nnpa_qaf_parameter_block
#ifdef __MVS__
__attribute__((__aligned__(8)))
#endif
;
extern nnpa_qaf_parameter_block nnpa_query_result;
// -----------------------------------------------------------------------------
// Versioning
// -----------------------------------------------------------------------------
extern uint32_t aiu_lib_vernum;
void refresh_aiu_lib_vernum();
// -----------------------------------------------------------------------------
// Floating Point Format Conversion Functions
// -----------------------------------------------------------------------------
uint32_t convert_data_format(void *input_data, zdnn_data_types in_data_fmt,
void *output_data, zdnn_data_types out_data_fmt,
uint32_t num_fields);
uint32_t
convert_data_format_in_stride(void *input_data, zdnn_data_types in_data_fmt,
void *output_data, zdnn_data_types out_data_fmt,
uint32_t num_fields, uint32_t input_stride);
// -----------------------------------------------------------------------------
// Tensor Functions
// -----------------------------------------------------------------------------
void init_transformed_desc(zdnn_data_layouts layout, zdnn_data_types type,
zdnn_data_formats format,
zdnn_tensor_desc *tfrmd_desc, uint32_t dim4,
uint32_t dim3, uint32_t dim2, uint32_t dim1);
zdnn_status ztensor_slice_dim4(const zdnn_ztensor *input_ztensor,
uint32_t slice_idx, size_t slice_buffer_size,
zdnn_tensor_desc *output_pre_tfrmd_desc,
zdnn_tensor_desc *output_tfrmd_desc,
zdnn_ztensor *output_ztensor);
// -----------------------------------------------------------------------------
// NNPA Parm Block Functions
// -----------------------------------------------------------------------------
// Define NNPA_PARM_BLOCK_VERSION
// Notes:
// - The PBVN is not used on a Query NNPA
// - The PBVN is architected to be 9-15 of the first word of the
// NNPA parm block
// - Actual supported values are returned on the aforementioned
// Query NNPA in field IPBF
#define NNPA_PARM_BLOCK_VERSION 0
void populate_descriptor(nnpa_tensor_descriptor *descriptor,
const zdnn_ztensor *ztensor);
void populate_nnpa_parm_block(
nnpa_parameter_block *parm_block, const zdnn_ztensor *input_ztensor1,
const zdnn_ztensor *input_ztensor2, const zdnn_ztensor *input_ztensor3,
zdnn_ztensor *output_ztensor1, zdnn_ztensor *output_ztensor2,
void *func_sp_savearea_addr, uint32_t func_sp_parm1, uint32_t func_sp_parm2,
uint32_t func_sp_parm3, uint32_t func_sp_parm4, uint32_t func_sp_parm5);
// -----------------------------------------------------------------------------
// Malloc 4k
// -----------------------------------------------------------------------------
void *malloc_aligned_4k(size_t size);
void free_aligned_4k(void *aligned_ptr);
// -----------------------------------------------------------------------------
// NNPA Invoke Functions
// -----------------------------------------------------------------------------
zdnn_status invoke_nnpa(uint8_t function_code, char *parm_block,
uint8_t *exception_flags);
zdnn_status invoke_nnpa_query(nnpa_qaf_parameter_block *qpb);
// -----------------------------------------------------------------------------
// Internal Function for AIU Operations
// -----------------------------------------------------------------------------
zdnn_status aiu_ops(uint8_t function_code, const zdnn_ztensor *input1,
const zdnn_ztensor *input2, const zdnn_ztensor *input3,
zdnn_ztensor *output1, zdnn_ztensor *output2);
zdnn_status
aiu_ops_func_specific(uint8_t function_code, const zdnn_ztensor *input1,
const zdnn_ztensor *input2, const zdnn_ztensor *input3,
zdnn_ztensor *output1, zdnn_ztensor *output2,
uint64_t func_sp_savearea_addr, uint32_t func_sp_parm1,
uint32_t func_sp_parm2, uint32_t func_sp_parm3,
uint32_t func_sp_parm4, uint32_t func_sp_parm5);
zdnn_status aiu_lstm_gru(uint8_t function_code, const zdnn_ztensor *input,
const zdnn_ztensor *h0, const zdnn_ztensor *c0,
const zdnn_ztensor *weights,
const zdnn_ztensor *biases,
const zdnn_ztensor *hidden_weights,
const zdnn_ztensor *hidden_biases,
lstm_gru_direction direction, void *work_area,
zdnn_ztensor *hn_output, zdnn_ztensor *cf_output);
// -----------------------------------------------------------------------------
// Internal Tensor Compatibility Verification
// -----------------------------------------------------------------------------
zdnn_status verify_tensors(const zdnn_ztensor *input_a,
const zdnn_ztensor *input_b,
const zdnn_ztensor *input_c,
const zdnn_ztensor *output);
zdnn_status verify_zdnn_lstm_or_gru_tensors(
uint8_t function_code, const zdnn_ztensor *input, const zdnn_ztensor *h0,
const zdnn_ztensor *c0, const zdnn_ztensor *weights,
const zdnn_ztensor *biases, const zdnn_ztensor *hidden_weights,
const zdnn_ztensor *hidden_biases, lstm_gru_direction direction,
const zdnn_ztensor *hn_output, const zdnn_ztensor *cf_output);
zdnn_status verify_lstm_or_gru_act_tensors(uint8_t function_code,
const zdnn_ztensor *ts_fused,
const zdnn_ztensor *bias_add_rnn_op,
const zdnn_ztensor *prev_state,
const zdnn_ztensor *h_output,
const zdnn_ztensor *c_output);
zdnn_status verify_matmul_op_tensors(const zdnn_ztensor *input_a,
const zdnn_ztensor *input_b,
const zdnn_ztensor *input_c,
const zdnn_ztensor *output);
zdnn_status verify_matmul_bcast_op_tensors(const zdnn_ztensor *input_a,
const zdnn_ztensor *input_b,
const zdnn_ztensor *input_c,
const zdnn_ztensor *output);
zdnn_status verify_batchnorm_tensors(const zdnn_ztensor *input_a,
const zdnn_ztensor *input_b,
const zdnn_ztensor *input_c,
const zdnn_ztensor *output);
zdnn_status verify_pool_avg_max_tensors(
const zdnn_ztensor *input, zdnn_pool_padding padding_type,
uint32_t kernel_height, uint32_t kernel_width, uint32_t stride_height,
uint32_t stride_width, const zdnn_ztensor *output);
zdnn_status verify_conv2d_tensors(const zdnn_ztensor *input,
const zdnn_ztensor *kernel,
const zdnn_ztensor *bias, uint32_t pad_n_act,
uint32_t stride_height, uint32_t stride_width,
uint32_t reserved_n_clipping,
const zdnn_ztensor *output);
zdnn_status verify_relu_tensors(const zdnn_ztensor *input,
uint32_t reserved_n_clipping,
const zdnn_ztensor *output);
zdnn_status
verify_pre_transformed_descriptor(const zdnn_tensor_desc *pre_tfrmd_desc);
zdnn_status verify_transformed_descriptor(const zdnn_tensor_desc *tfrmd_desc);
// -----------------------------------------------------------------------------
// Stickify Related Functions
// -----------------------------------------------------------------------------
size_t get_stick_offset(uint32_t e4x, uint32_t e3x, uint32_t e2x, uint32_t e1x,
const zdnn_tensor_desc *pre_tfrmd_desc);
void setbit_128(bit128_t *field, uint8_t bit_pos);
bool is_bitset_128(bit128_t field, uint8_t bit_pos);
void setbit_256(bit256_t *field, uint16_t bit_pos);
bool is_bitset_256(bit256_t field, uint16_t bit_pos);
zdnn_status transform_fico_ztensor(zdnn_ztensor *fico_ztensor, void *fx_data,
void *ix_data, void *cx_data, void *ox_data);
zdnn_status transform_zrh_ztensor(zdnn_ztensor *zrh_ztensor, void *zx_data,
void *rx_data, void *hx_data);
// -----------------------------------------------------------------------------
// convert_hw.c wrapper Functions and types
// -----------------------------------------------------------------------------
typedef vector unsigned int vec_float32;
typedef vector unsigned short vec_int16;
typedef vector unsigned char vec_char8;
vec_int16 aiu_vec_round_from_fp32(vec_float32 a, vec_float32 b);
void aiu_vec_lengthen_to_fp32(vec_int16 a, vec_float32 *out1,
vec_float32 *out2);
vec_int16 aiu_vec_convert_from_fp16(vec_int16 a);
vec_int16 aiu_vec_convert_to_fp16(vec_int16 a);
// -----------------------------------------------------------------------------
// NNPA-MATMUL-OP function-specific-parameter-1 bitfields
// -----------------------------------------------------------------------------
// bits 0-23: reserved
// bits 24-31: operation
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm1_matmul_op {
uint32_t reserved1 : 24;
uint32_t operation : 8;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm1_matmul_op;
typedef union func_sp_parm1_matmul_op {
// for get/setting bitfield individually
bitfield_func_sp_parm1_matmul_op bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm1_matmul_op;
// -----------------------------------------------------------------------------
// NNPA-MATMUL-OP-BCAST23 function-specific-parameter-1 bitfields
// -----------------------------------------------------------------------------
// bits 0-23: reserved
// bits 24-31: operation
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm1_matmul_bcast_op {
uint32_t reserved1 : 24;
uint32_t operation : 8;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm1_matmul_bcast_op;
typedef union func_sp_parm1_matmul_bcast_op {
// for get/setting bitfield individually
bitfield_func_sp_parm1_matmul_bcast_op bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm1_matmul_bcast_op;
// -----------------------------------------------------------------------------
// NNPA-SOFTMAX function-specific-parameter-1 bitfields
// -----------------------------------------------------------------------------
// bits 0-28: reserved
// bits 28-31: activation func
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm1_softmax {
uint32_t reserved1 : 28;
uint32_t act : 4;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm1_softmax;
typedef union func_sp_parm1_softmax {
// for get/setting bitfield individually
bitfield_func_sp_parm1_softmax bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm1_softmax;
// -----------------------------------------------------------------------------
// NNPA-RELU function-specific-parameter-1 bitfields
// -----------------------------------------------------------------------------
// bits 0-15: reserved
// bits 16-31: clipping value
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm1_relu {
uint32_t reserved1 : 16;
uint32_t clipping_value : 16;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm1_relu;
typedef union func_sp_parm1_relu {
// for get/setting bitfield individually
bitfield_func_sp_parm1_relu bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm1_relu;
// -----------------------------------------------------------------------------
// NNPA-CONVOLUTION function-specific-parameter-1 bitfields
// -----------------------------------------------------------------------------
// bits 0-23: reserved
// bits 24-27: activation func
// bits 28: reserved
// bits 29-31: padding type
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm1_conv2d {
uint32_t reserved1 : 24;
uint32_t act : 4;
uint32_t reserved2 : 1;
uint32_t pad : 3;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm1_conv2d;
typedef union func_sp_parm1_conv2d {
// for get/setting bitfield individually
bitfield_func_sp_parm1_conv2d bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm1_conv2d;
// -----------------------------------------------------------------------------
// NNPA-CONVOLUTION function-specific-parameter-4 bitfields
// -----------------------------------------------------------------------------
// bits 0-15: reserved
// bits 16-31: clipping value
typedef
#ifdef __MVS__
_Packed
#endif
struct bitfield_func_sp_parm4_conv2d {
uint32_t reserved1 : 16;
uint32_t clipping_value : 16;
}
#ifndef __MVS__
__attribute__((packed))
#endif
bitfield_func_sp_parm4_conv2d;
typedef union func_sp_parm4_conv2d {
// for get/setting bitfield individually
bitfield_func_sp_parm4_conv2d bits;
// for as a whole. you must clear this before setting bits individual
uint32_t val;
} func_sp_parm4_conv2d;
// -----------------------------------------------------------------------------
// zDNN Logger Functions
// -----------------------------------------------------------------------------
bool logmodule_matches(const char *file_name);
void log_fatal(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_error(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_warn(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_info(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_debug(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_trace(const char *func_name, const char *file_name, int line_no,
char *format, ...);
void log_message(log_levels lvl, const char *func_name, const char *file_name,
int line_no, const char *format, va_list arg);
#ifndef ZDNN_CONFIG_DEBUG
// when ZDNN_CONFIG_DEBUG is off (i.e., production code):
//
// - no logmodule filtering
// - FATAL/ERROR: log the message, no loglevel check
// - WARN/INFO/DEBUG/TRACE: no-op
#define LOG_FATAL(format, ...) \
log_fatal(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_ERROR(format, ...) \
log_error(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_WARN(format, ...)
#define LOG_INFO(format, ...)
#define LOG_DEBUG(format, ...)
#define LOG_TRACE(format, ...)
#define BEGIN_BLOCK_IF_LOGLEVEL_FATAL
#define BEGIN_BLOCK_IF_LOGLEVEL_ERROR
#define BEGIN_BLOCK_IF_LOGLEVEL_WARN if (0)
#define BEGIN_BLOCK_IF_LOGLEVEL_INFO if (0)
#define BEGIN_BLOCK_IF_LOGLEVEL_DEBUG if (0)
#define BEGIN_BLOCK_IF_LOGLEVEL_TRACE if (0)
#else
// when ZDNN_CONFIG_DEBUG is on
//
// - fully utilize loglevel/logmodule functionalities
#define LOG_FATAL(format, ...) \
log_fatal(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_ERROR(format, ...) \
log_error(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_WARN(format, ...) \
log_warn(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_INFO(format, ...) \
log_info(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_DEBUG(format, ...) \
log_debug(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define LOG_TRACE(format, ...) \
log_trace(__func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define BEGIN_IF_LOGLEVEL(lvl, file_name) \
if ((log_level >= lvl) && logmodule_matches(file_name))
#define BEGIN_BLOCK_IF_LOGLEVEL_FATAL \
BEGIN_IF_LOGLEVEL(LOGLEVEL_FATAL, __FILE__)
#define BEGIN_BLOCK_IF_LOGLEVEL_ERROR \
BEGIN_IF_LOGLEVEL(LOGLEVEL_ERROR, __FILE__)
#define BEGIN_BLOCK_IF_LOGLEVEL_WARN BEGIN_IF_LOGLEVEL(LOGLEVEL_WARN, __FILE__)
#define BEGIN_BLOCK_IF_LOGLEVEL_INFO BEGIN_IF_LOGLEVEL(LOGLEVEL_INFO, __FILE__)
#define BEGIN_BLOCK_IF_LOGLEVEL_DEBUG \
BEGIN_IF_LOGLEVEL(LOGLEVEL_DEBUG, __FILE__)
#define BEGIN_BLOCK_IF_LOGLEVEL_TRACE \
BEGIN_IF_LOGLEVEL(LOGLEVEL_TRACE, __FILE__)
#endif
// -----------------------------------------------------------------------------
// zDNN Status Related Functions
// -----------------------------------------------------------------------------
zdnn_status set_zdnn_status(zdnn_status status, const char *func_name,
const char *file_name, int line_no,
const char *format, ...);
#define ZDNN_STATUS(status, format, ...) \
set_zdnn_status(status, __func__, __FILE__, __LINE__, format, __VA_ARGS__)
#define NO_ARG 0
#define ZDNN_STATUS_NO_MSG(status) ZDNN_STATUS(status, NULL, NO_ARG)
#ifndef ZDNN_CONFIG_DEBUG
#define ZDNN_STATUS_OK ZDNN_OK
#else
#define ZDNN_STATUS_OK ZDNN_STATUS_NO_MSG(ZDNN_OK)
#endif
// -----------------------------------------------------------------------------
// Misc get_*() Functions
// -----------------------------------------------------------------------------
short get_func_code_num_gates(nnpa_function_code func_code);
short get_data_layout_num_gates(zdnn_data_layouts layout);
short get_data_layout_dims(zdnn_data_layouts layout);
const char *get_data_layout_str(zdnn_data_layouts layout);
const char *get_data_format_str(zdnn_data_formats format);
short get_data_type_size(zdnn_data_types type);
const char *get_data_type_str(zdnn_data_types type);
const char *get_rnn_direction_str(lstm_gru_direction dir);
const char *get_softmax_act_str(zdnn_softmax_act func);
const char *get_matmul_op_str(zdnn_matmul_ops op);
const char *get_matmul_bcast_op_str(zdnn_matmul_bcast_ops op);
const char *get_pool_padding_str(zdnn_pool_padding pad);
const char *get_conv2d_act_str(zdnn_conv2d_act func);
uint64_t get_num_elements(const zdnn_ztensor *ztensor, elements_mode mode);
uint32_t get_rnn_concatenated_dim1(uint32_t val, zdnn_concat_info info);
uint32_t get_rnn_concatenated_dim2(uint32_t val, zdnn_concat_info info);
// -----------------------------------------------------------------------------
// Print Utilities
// -----------------------------------------------------------------------------
void print_bits(size_t const size, void const *const ptr);
void print_hex(size_t const size, void const *const ptr);
void print_dlf16_buffer(void *buffer, uint64_t buffer_size);
void print_desc(zdnn_tensor_desc *desc);
void print_ztensor(const zdnn_ztensor *ztensor, char *name, bool print_data);
typedef enum dump_mode { AS_HEX, AS_FLOAT } dump_mode;
void dumpdata_origtensor(const zdnn_tensor_desc *pre_tfrmd_desc,
void *tensor_data, dump_mode mode);
void dumpdata_ztensor(const zdnn_ztensor *ztensor, dump_mode mode,
bool print_all);
// -----------------------------------------------------------------------------
// Misc Macros
// -----------------------------------------------------------------------------
#define CEIL(a, b) (uint64_t)((a + b - 1) / b) // positive numbers only
#define MIN(a, b) ((a > b) ? b : a)
#define MAX(a, b) ((a < b) ? b : a)
#define BIT_SIZEOF(a) (sizeof(a) * 8)
// padded = next multiple of AIU_2BYTE_CELLS_PER_STICK
#define PADDED(x) \
((uint32_t)CEIL(x, AIU_2BYTE_CELLS_PER_STICK) * AIU_2BYTE_CELLS_PER_STICK)
// -----------------------------------------------------------------------------
// Private global variables
// -----------------------------------------------------------------------------
#define PRINT_DIMS(x) \
printf(#x " pre: %u %u %u %u\n", (x)->pre_transformed_desc->dim4, \
(x)->pre_transformed_desc->dim3, (x)->pre_transformed_desc->dim2, \
(x)->pre_transformed_desc->dim1); \
printf(#x ": %u %u %u %u\n", (x)->transformed_desc->dim4, \
(x)->transformed_desc->dim3, (x)->transformed_desc->dim2, \
(x)->transformed_desc->dim1);
#endif /* ZDNN_ZDNN_PRIVATE_H_ */
| 37.923382 | 80 | 0.614289 | [
"vector"
] |
043e1e9e3467ead535ffdcd5ff6c3315bf68eb37 | 1,998 | h | C | functions.h | materialsnexus/grain3d | a24fe509f885bd0d968d62db47365409c1c958c5 | [
"Apache-2.0"
] | 1 | 2022-01-11T19:34:15.000Z | 2022-01-11T19:34:15.000Z | functions.h | materialsnexus/grain3d | a24fe509f885bd0d968d62db47365409c1c958c5 | [
"Apache-2.0"
] | null | null | null | functions.h | materialsnexus/grain3d | a24fe509f885bd0d968d62db47365409c1c958c5 | [
"Apache-2.0"
] | null | null | null | #ifndef FUNCTIONS_H__
#define FUNCTIONS_H__
double det (CNode*, CNode*, CNode*, CNode*); // determinant of a matrix
double pdet (CNode*, CNode*, CNode*, CNode*); // determinant of a matrix
double length(CNode*, CNode*);
void calc_and_print_stats();
int count_bodies();
int count_vertices();
int count_faces();
int count_edges();
void calc_volumes();
void calc_areas();
void calc_motions();
double calc_avg_face_area();
double calc_avg_cell_area();
double calc_avg_cell_faces();
double calc_avg_face_sides();
bool is_neighbor (CBody*, CNode*);
bool are_neighbors(CNode*, CNode*);
bool are_neighbors(CBody*, CBody*);
bool compare (CNode* one, CNode* two);
bool bcompare (CBody* one, CBody* two);
CBody* identify_body(CNode*, CNode*);
CBody* identify_body(CNode*, CNode*, CNode*);
CNode* common_face (CBody*, CBody*, CNode*);
CNode* common_face (Vertex*, Vertex*, Vertex*);
bool common_face (Vertex*, Vertex*, Vertex*, Vertex*);
void merge_faces (CNode*, CNode*, CNode*, CNode*);
void determine_neighbors(void);
void determine_node_topologies();
void cluster_evolver_out(int pid);
CNode* remove_edge(CNode*, CNode*);
void remove_system_edge_nodes();
void remove_small_bodies();
void remove_small_faces ();
void remove_small_edges ();
void remove_node_from_face(CNode*, CNode*);
void initialize_variables();
void update_variables();
void compactify();
void compactify_bodies();
CNode* refine_edge(CNode*, CNode*);
void refine_edges();
void read_in_data(int argc, char *argv[]);
void print_out_data(void);
void evolver_out(int id);
int vector_search(std::vector<edge>& edges, CNode* one, CNode* two);
int g(int edge1[], int edge2[], int edge_id[], int one, int two, int size);
int f(int the_nodes[], int number, int size);
void crash();
double calc_echange(CNode*, CNode*);
void surface_evolver_system();
void fit_nodes_in_cube();
bool not_digon_neighbors(CNode* one, CNode* two);
void move_nodes();
#endif
| 26.289474 | 75 | 0.715215 | [
"vector"
] |
044150c047922b19e64b5537d5e39710a859f6d6 | 7,547 | h | C | GRIT/GRIT/include/mesh_operations/grit_vertex_split_operation.h | H2020-MSCA-ITN-rainbow/GRIT | 1bdfb0735515e9d462214f66b88a71aabf836d76 | [
"MIT"
] | 4 | 2018-05-28T19:59:05.000Z | 2021-04-23T19:57:26.000Z | GRIT/GRIT/include/mesh_operations/grit_vertex_split_operation.h | H2020-MSCA-ITN-rainbow/GRIT | 1bdfb0735515e9d462214f66b88a71aabf836d76 | [
"MIT"
] | 18 | 2018-05-06T21:08:19.000Z | 2018-06-11T17:59:00.000Z | GRIT/GRIT/include/mesh_operations/grit_vertex_split_operation.h | misztal/GRIT | 6850fec967c9de7c6c501f5067d021ef5288b88e | [
"MIT"
] | null | null | null | #ifndef GRIT_VERTEX_SPLIT_OPERATION_H
#define GRIT_VERTEX_SPLIT_OPERATION_H
#include <grit_interface_mesh_operation.h>
#include <grit_simplex_set.h>
#include <utilities/grit_extract_simplices.h>
namespace grit
{
namespace details
{
template< typename types>
class VertexSplitOperation
: public InterfaceMeshOperation< Simplex0, types>
{
protected:
typedef InterfaceMeshOperation<
Simplex0
, types
> base_class;
typedef typename types::real_type T;
typedef typename types::vector3_type V;
typedef typename types::math_types MT;
typedef typename types::attributes_type AT;
typedef typename types::param_type PT;
typedef typename V::value_traits VT;
typedef typename base_class::simplex1_lut_type simplex1_lut_type;
typedef typename base_class::simplex2_lut_type simplex2_lut_type;
protected:
std::string const & m_name; ///< Name used to retrieve parameters.
unsigned int const m_label; ///< Label of the phase on which operation is performed.
PT const & m_parameters; ///< Parameters container.
public:
VertexSplitOperation(
std::string const & name
, unsigned int const label
, PT const & parameters
)
: m_name(name)
, m_label(label)
, m_parameters(parameters)
{ }
public:
void init(
InterfaceMesh const & mesh
, AT & attributes
)
{ }
public:
bool update_local_attributes(
Simplex0 const & simplex
, InterfaceMesh const & mesh
, AT & attributes
)
{
return false;
}
public:
bool plan_local_connectivity_changes(
Simplex0 const & simplex
, InterfaceMesh & mesh
, AT const & attributes
, SimplexSet & new_simplices
, SimplexSet & old_simplices
, simplex1_lut_type & simplex1_lut
, simplex2_lut_type & simplex2_lut
)
{
util::Log log;
std::string const & newline = util::Log::newline();
//--- Vertex split is only performed on interface vertices which are not
//--- on submesh boundary.
if( IsSubmeshBoundary(mesh)(simplex) || !IsInterface(mesh)(simplex))
{
return false;
}
//--- Get all labels from the 1-ring of simplex.
std::vector<unsigned int> const & labels = attributes.get_simplex0_labels(simplex);
//--- Only one phase assigned (the other phase is ambient).
if( labels.size() < 2u)
{
return false;
}
SimplexSet const S = mesh.star(simplex);
//--- All edges in the 1-ring
SimplexSet const E = filter( S, IsDimension( mesh, 1u));
//--- All interface edges in the 1-ring, in phase specified by m_label
SimplexSet const PE = filter( E, InPhase( mesh, m_label) && IsInterface(mesh));
if( PE.size(1u) != 2u)
{
log << "plan_local_connectivity_changes(): non-manifold configuration detected, vertex split not performed" << newline;
return false;
}
//-- An object with phase m_label here detaches from the surrounding phases.
//-- @param simplex remains to be "attached" to all other phases than m_label.
//-- A new simplex0 is inserted, which will belong to phase m_label.
Simplex0 w = mesh.insert();
new_simplices.insert(w);
mesh.submesh_boundary(w) = false;
//--- We need it to fix the attributes for this vertex
new_simplices.insert(simplex);
SimplexSet::simplex1_const_iterator it=S.begin1();
for( ; it!=S.end1(); ++it)
{
Simplex1 const & e = *it;
if( InPhase( mesh, m_label)(e))
{
replace_edge( simplex, w, e, mesh, new_simplices, old_simplices, simplex1_lut);
}
}
Simplex1 const edge( w, simplex);
new_simplices.insert(edge);
for( SimplexSet::simplex2_const_iterator it=S.begin2(); it!=S.end2(); ++it)
{
Simplex2 const & t = *it;
if( InPhase(mesh, m_label)(t))
{
replace_triangle( simplex, w, t, mesh, new_simplices, old_simplices, simplex2_lut);
}
}
return true;
}
protected:
void replace_edge(
Simplex0 const & simplex
, Simplex0 const & w
, Simplex1 const & e
, InterfaceMesh & mesh
, SimplexSet & new_simplices
, SimplexSet & old_simplices
, simplex1_lut_type & simplex1_lut
)
{
Simplex0 v1, v2;
SimplexSet const C = mesh.closure(e);
extract_simplices(v1, v2, C);
Simplex0 const v = (v1==simplex)?(v2):(v1);
new_simplices.insert(Simplex1(v,w));
simplex1_lut[ Simplex1(v,w) ] = e;
if( IsInterface(mesh)(e))
{
Simplex2 const air(v1,v2,w);
new_simplices.insert( air );
//--- Leaving assignment empty, making sure that Mesh and AttributeAssignment can handle it
//--- We can't pick a parent for this Simplex2
//simplex2_lut[ air ] = ???
Simplex1 const edge(w,simplex);
new_simplices.insert( edge );
simplex1_lut[ edge ] = e;
}
else
{
old_simplices.insert( e );
}
}
protected:
void replace_triangle(
Simplex0 const & simplex
, Simplex0 const & w
, Simplex2 const & t
, InterfaceMesh & mesh
, SimplexSet & new_simplices
, SimplexSet & old_simplices
, simplex2_lut_type & simplex2_lut
)
{
Simplex0 v1, v2, v3;
SimplexSet const C = mesh.closure(t);
extract_simplices( v1, v2, v3, C);
if( v1 == simplex) v1 = w;
if( v2 == simplex) v2 = w;
if( v3 == simplex) v3 = w;
Simplex2 const n(v1, v2, v3);
old_simplices.insert(t);
new_simplices.insert(n);
simplex2_lut[ n ] = t;
}
}; // class VertexSplitOperation
} // namespace details
} // namespace grit
// GRIT_VERTEX_SPLIT_H
#endif
| 31.577406 | 129 | 0.480853 | [
"mesh",
"object",
"vector"
] |
044bbafa36d527d588d114e521a91d30a1597e22 | 6,439 | h | C | src/ip4.h | cyrex562/Net-Loom | df436c5b084722fb747283863fa8fbb8056e5c35 | [
"MIT"
] | null | null | null | src/ip4.h | cyrex562/Net-Loom | df436c5b084722fb747283863fa8fbb8056e5c35 | [
"MIT"
] | null | null | null | src/ip4.h | cyrex562/Net-Loom | df436c5b084722fb747283863fa8fbb8056e5c35 | [
"MIT"
] | null | null | null | #pragma once
#include <network_interface.h>
#include <packet_buffer.h>
#include <ip4_addr.h>
#include <lwip_status.h>
/** This is the packed version of Ip4Addr,
used in network headers that are itself packed */ // struct Ip4AddrPacked {
// uint32_t addr;
// } ;
// typedef struct Ip4AddrPacked Ip4AddrPT;
/* Size of the IPv4 header. Same as 'sizeof(struct Ip4Hdr)'. */
constexpr size_t IP4_HDR_LEN = 20; /* Maximum size of the IPv4 header with options. */
constexpr size_t IP4_HDR_LEN_MAX = 60;
constexpr uint16_t IP4_RES_FLAG = 0x8000U; /* reserved fragment flag */
constexpr uint16_t IP4_DF_FLAG = 0x4000U; /* don't fragment flag */
constexpr uint16_t IP4_MF_FLAG = 0x2000U; /* more fragments flag */
constexpr uint16_t IP4_OFF_MASK = 0x1fffU; /* mask for fragmenting bits */ /* The IPv4 header */
struct Ip4Hdr
{
/* version / header length */
uint8_t _v_hl; /* type of service */
uint8_t _tos; /* total length */
uint16_t _len; /* identification */
int16_t _id; /* fragment offset field */
uint16_t _offset; /* time to live */
uint8_t _ttl; /* protocol*/
uint8_t _proto; /* checksum */
uint16_t _chksum; /* source and destination IP addresses */
Ip4Addr src;
Ip4Addr dest;
};
/* Macros to get struct Ip4Hdr fields: */
inline uint8_t get_ip4_hdr_version(const Ip4Hdr& hdr)
{
return ((hdr)._v_hl >> 4);
}
inline uint8_t get_ip4_hdr_version2(const Ip4Hdr* hdr)
{
return ((hdr)->_v_hl >> 4);
}
inline uint8_t get_ip4_hdr_hdr_len(const Ip4Hdr& hdr)
{
return ((hdr)._v_hl & 0x0f);
}
inline uint8_t get_ip4_hdr_hdr_len2(const Ip4Hdr* hdr)
{
return ((hdr)->_v_hl & 0x0f);
}
inline uint8_t get_ip4_hdr_hdr_len_bytes(const Ip4Hdr& hdr)
{
return uint8_t(get_ip4_hdr_hdr_len(hdr) * 4);
}
inline uint8_t get_ip4_hdr_hdr_len_bytes2(const Ip4Hdr* hdr)
{
return uint8_t(get_ip4_hdr_hdr_len2(hdr) * 4);
}
inline uint8_t get_ip4_hdr_tos(const Ip4Hdr& hdr)
{
return ((hdr)._tos);
}
inline uint16_t get_ip4_hdr_len(const Ip4Hdr& hdr)
{
return hdr._len;
}
inline uint16_t get_ip4_hdr_len2(const Ip4Hdr* hdr)
{
return hdr->_len;
}
inline uint16_t get_ip4_hdr_id(const Ip4Hdr& hdr)
{
return ((hdr)._id);
}
inline uint16_t get_ip4_hdr_offset(const Ip4Hdr& hdr)
{
return ((hdr)._offset);
}
inline uint16_t get_ip4_hdr_offset_bytes(const Ip4Hdr& hdr)
{
return uint16_t((lwip_ntohs(get_ip4_hdr_offset(hdr)) & IP4_OFF_MASK) * 8U);
}
inline uint8_t get_ip4_hdr_ttl(const Ip4Hdr& hdr)
{
return ((hdr)._ttl);
}
inline uint8_t get_ip4_hdr_proto(const Ip4Hdr& hdr)
{
return ((hdr)._proto);
}
inline uint16_t get_ip4_hdr_checksum(const Ip4Hdr& hdr)
{
return ((hdr)._chksum);
} /* Macros to set struct Ip4Hdr fields: */
// ReSharper disable once CppInconsistentNaming
inline void set_ip4_hdr_vhl(Ip4Hdr& hdr, const uint8_t v, const uint8_t hl)
{
hdr._v_hl = uint8_t(v << 4 | hl);
}
inline void set_ip4_hdr_tos(Ip4Hdr& hdr, const uint8_t tos)
{
(hdr)._tos = (tos);
}
inline void set_ip4_hdr_len(Ip4Hdr& hdr, const uint16_t len)
{
(hdr)._len = (len);
}
inline void set_ip4_hdr_id(Ip4Hdr& hdr, const uint16_t id)
{
(hdr)._id = (id);
}
inline void set_ip4_hdr_offset(Ip4Hdr& hdr, const uint16_t off)
{
(hdr)._offset = (off);
}
inline void set_ip4_hdr_ttl(Ip4Hdr& hdr, const uint8_t ttl)
{
(hdr)._ttl = uint8_t(ttl);
}
inline void set_ip4_hdr_proto(Ip4Hdr& hdr, const uint8_t proto)
{
(hdr)._proto = uint8_t(proto);
}
inline void set_ip4_hdr_checksum(Ip4Hdr& hdr, const uint16_t chksum)
{
(hdr)._chksum = (chksum);
}
inline bool init_ip4_module()
{
return true;
}
LwipStatus
get_netif_for_dst_ip4_addr(const Ip4Addr& dst_addr,
const std::vector<NetworkInterface>& netifs_to_check,
NetworkInterface& found_netif);
LwipStatus
source_route_ip4_addr(const Ip4AddrInfo& src,
const Ip4AddrInfo& dest,
NetworkInterface& out_netif,
const std::vector<NetworkInterface>& netifs);
bool
ip4_input(PacketBuffer& pkt_buf, NetworkInterface& netif, std::vector<NetworkInterface>& interfaces);
LwipStatus ip4_output(PacketBuffer& p,
const Ip4AddrInfo& src,
const Ip4AddrInfo& dest,
uint8_t ttl,
uint8_t tos,
uint8_t proto);
LwipStatus ip4_output_if(PacketBuffer& p,
const Ip4AddrInfo& src,
const Ip4AddrInfo& dest,
uint8_t ttl,
uint8_t tos,
uint8_t proto,
NetworkInterface& netif);
LwipStatus ip4_output_if_src(PacketBuffer& p,
const Ip4AddrInfo& src,
const Ip4AddrInfo& dest,
uint8_t ttl,
uint8_t tos,
uint8_t proto,
NetworkInterface& netif);
// LwipStatus ip4_output_hinted(struct PacketBuffer *p,
// const Ip4Addr *src,
// const Ip4Addr *dest,
// uint8_t ttl,
// uint8_t tos,
// uint8_t proto,
// NetIfcHint* netif_hint);
LwipStatus ip4_output_if_opt(struct PacketBuffer* p,
const Ip4Addr* src,
const Ip4Addr* dest,
uint8_t ttl,
uint8_t tos,
uint8_t proto,
NetworkInterface* netif,
uint8_t* ip_options,
uint16_t optlen);
LwipStatus ip4_output_if_opt_src(struct PacketBuffer* p,
const Ip4Addr* src,
const Ip4Addr* dest,
uint8_t ttl,
uint8_t tos,
uint8_t proto,
NetworkInterface* netif,
uint8_t* ip_options,
uint16_t optlen);
void ip4_set_default_multicast_netif(NetworkInterface** default_multicast_netif);
bool
can_forward_ip4_pkt(PacketBuffer& pkt_buf);
//
// END OF FILE
//
| 27.635193 | 101 | 0.594036 | [
"vector"
] |
0451cefdc7ac971c53ec41957470f92707a8e59d | 10,514 | h | C | muparser3/muParser.h | beltoforion/math-parser-benchmark-project | dcdb8cf290d580c564c9e57d21c6c4454e702363 | [
"Apache-2.0",
"Zlib",
"MIT"
] | 1 | 2021-03-07T13:17:37.000Z | 2021-03-07T13:17:37.000Z | muparser3/muParser.h | beltoforion/math-parser-benchmark-project | dcdb8cf290d580c564c9e57d21c6c4454e702363 | [
"Apache-2.0",
"Zlib",
"MIT"
] | null | null | null | muparser3/muParser.h | beltoforion/math-parser-benchmark-project | dcdb8cf290d580c564c9e57d21c6c4454e702363 | [
"Apache-2.0",
"Zlib",
"MIT"
] | null | null | null | #ifndef MU_PARSER_H
#define MU_PARSER_H
//--- Standard includes ---------------------------------------------------------------------------
#include <vector>
#include <algorithm>
#include <numeric>
//--- Parser includes -----------------------------------------------------------------------------
#include "muParserBase.h"
#include "muParserMath.h"
#include "muParserDef.h"
MUP_NAMESPACE_START
//-----------------------------------------------------------------------------------------------
/** \brief Basic implementation of the parser.
*/
template<typename TValue, typename TString = std::string>
class Parser : public ParserBase<TValue, TString>
{
typedef typename ParserBase<TValue, TString>::stringstream_type stringstream_type;
public:
//---------------------------------------------------------------------------------------------
/** \brief Default constructor of the parser object.
Preconfigures the parser according to its underlying valuetype.
*/
Parser()
:ParserBase<TValue, TString>()
{
if (!details::value_traits<TValue>::IsInteger())
{
ParserBase<TValue, TString>::AddValIdent(IsFloatVal);
}
else
{
ParserBase<TValue, TString>::AddValIdent(IsIntVal); // lowest priority
ParserBase<TValue, TString>::AddValIdent(IsBinVal);
ParserBase<TValue, TString>::AddValIdent(IsHexVal); // highest priority
}
InitFun();
InitConst();
InitOprt();
}
private:
//---------------------------------------------------------------------------------------------
void InitFun()
{
if (!details::value_traits<TValue>::IsInteger())
{
// trigonometric functions
ParserBase<TValue, TString>::DefineFun( _SL("sin"), MathImpl<TValue, TString>::Sin, 1);
ParserBase<TValue, TString>::DefineFun( _SL("cos"), MathImpl<TValue, TString>::Cos, 1);
ParserBase<TValue, TString>::DefineFun( _SL("tan"), MathImpl<TValue, TString>::Tan, 1);
// arcus functions
ParserBase<TValue, TString>::DefineFun( _SL("asin"), MathImpl<TValue, TString>::ASin, 1);
ParserBase<TValue, TString>::DefineFun( _SL("acos"), MathImpl<TValue, TString>::ACos, 1);
ParserBase<TValue, TString>::DefineFun( _SL("atan"), MathImpl<TValue, TString>::ATan, 1);
ParserBase<TValue, TString>::DefineFun( _SL("atan2"), MathImpl<TValue, TString>::ATan2, 2);
// hyperbolic functions
ParserBase<TValue, TString>::DefineFun( _SL("sinh"), MathImpl<TValue, TString>::Sinh, 1);
ParserBase<TValue, TString>::DefineFun( _SL("cosh"), MathImpl<TValue, TString>::Cosh, 1);
ParserBase<TValue, TString>::DefineFun( _SL("tanh"), MathImpl<TValue, TString>::Tanh, 1);
// arcus hyperbolic functions
ParserBase<TValue, TString>::DefineFun( _SL("asinh"), MathImpl<TValue, TString>::ASinh, 1);
ParserBase<TValue, TString>::DefineFun( _SL("acosh"), MathImpl<TValue, TString>::ACosh, 1);
ParserBase<TValue, TString>::DefineFun( _SL("atanh"), MathImpl<TValue, TString>::ATanh, 1);
// Logarithm functions
ParserBase<TValue, TString>::DefineFun( _SL("log2"), MathImpl<TValue, TString>::Log2, 1);
ParserBase<TValue, TString>::DefineFun( _SL("log10"), MathImpl<TValue, TString>::Log10, 1);
ParserBase<TValue, TString>::DefineFun( _SL("log"), MathImpl<TValue, TString>::Log, 1);
ParserBase<TValue, TString>::DefineFun( _SL("ln"), MathImpl<TValue, TString>::Log, 1);
// misc
ParserBase<TValue, TString>::DefineFun( _SL("exp"), MathImpl<TValue, TString>::Exp, 1);
ParserBase<TValue, TString>::DefineFun( _SL("sqrt"), MathImpl<TValue, TString>::Sqrt, 1);
ParserBase<TValue, TString>::DefineFun( _SL("sign"), MathImpl<TValue, TString>::Sign, 1);
ParserBase<TValue, TString>::DefineFun( _SL("rint"), MathImpl<TValue, TString>::Rint, 1);
ParserBase<TValue, TString>::DefineFun( _SL("avg"), MathImpl<TValue, TString>::Avg, -1);
}
ParserBase<TValue, TString>::DefineFun( _SL("abs"), MathImpl<TValue, TString>::Abs, 1);
// Functions with variable number of arguments
ParserBase<TValue, TString>::DefineFun( _SL("sum"), MathImpl<TValue, TString>::Sum, -1);
ParserBase<TValue, TString>::DefineFun( _SL("min"), MathImpl<TValue, TString>::Min, -1);
ParserBase<TValue, TString>::DefineFun( _SL("max"), MathImpl<TValue, TString>::Max, -1);
}
//---------------------------------------------------------------------------------------------
void InitConst()
{
if (!details::value_traits<TValue>::IsInteger())
{
ParserBase<TValue, TString>::DefineConst( _SL("_pi"), MathImpl<TValue, TString>::c_pi);
ParserBase<TValue, TString>::DefineConst( _SL("_e"), MathImpl<TValue, TString>::c_e);
}
}
//---------------------------------------------------------------------------------------------
void InitOprt()
{
ParserBase<TValue, TString>::DefineInfixOprt( _SL("-"), MathImpl<TValue, TString>::UnaryMinus);
ParserBase<TValue, TString>::DefineInfixOprt( _SL("+"), MathImpl<TValue, TString>::UnaryPlus);
ParserBase<TValue, TString>::DefineOprt( _SL("&&"), MathImpl<TValue, TString>::And, prLOGIC);
ParserBase<TValue, TString>::DefineOprt( _SL("||"), MathImpl<TValue, TString>::Or, prLOGIC);
ParserBase<TValue, TString>::DefineOprt( _SL("<"), MathImpl<TValue, TString>::Less, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL(">"), MathImpl<TValue, TString>::Greater, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL("<="), MathImpl<TValue, TString>::LessEq, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL(">="), MathImpl<TValue, TString>::GreaterEq, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL("=="), MathImpl<TValue, TString>::Equal, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL("!="), MathImpl<TValue, TString>::NotEqual, prCMP);
ParserBase<TValue, TString>::DefineOprt( _SL("+"), MathImpl<TValue, TString>::Add, prADD_SUB);
ParserBase<TValue, TString>::DefineOprt( _SL("-"), MathImpl<TValue, TString>::Sub, prADD_SUB);
ParserBase<TValue, TString>::DefineOprt( _SL("*"), MathImpl<TValue, TString>::Mul, prMUL_DIV, oaRIGHT);
if (!details::value_traits<TValue>::IsInteger())
{
ParserBase<TValue, TString>::DefineOprt( _SL("/"), MathImpl<TValue, TString>::Div, prMUL_DIV);
ParserBase<TValue, TString>::DefineOprt( _SL("^"), MathImpl<TValue, TString>::Pow, prPOW, oaRIGHT);
}
}
protected:
//---------------------------------------------------------------------------
static int IsFloatVal(const typename TString::value_type* a_szExpr, int *a_iPos, TValue *a_fVal)
{
TValue fVal(0);
typename ParserBase<TValue, TString>::stringstream_type stream(a_szExpr);
stream.seekg(0);
stream >> fVal;
typename ParserBase<TValue, TString>::stringstream_type::pos_type iEnd = stream.tellg(); // Position after reading
if (iEnd==(typename ParserBase<TValue, TString>::stringstream_type::pos_type)-1)
return 0;
*a_iPos += (int)iEnd;
*a_fVal = fVal;
return 1;
}
//---------------------------------------------------------------------------------------------
/** \brief Check a given position in the expression for the presence of
an integer value.
\param a_szExpr Pointer to the expression string
\param [in/out] a_iPos Pointer to an interger value holding the current parsing
position in the expression.
\param [out] a_fVal Pointer to the position where the detected value shall be stored.
*/
static int IsIntVal(const typename TString::value_type* a_szExpr, int *a_iPos, TValue *a_fVal)
{
TString buf(a_szExpr);
std::size_t pos = buf.find_first_not_of(_SL("0123456789"));
if (pos==std::string::npos)
return 0;
stringstream_type stream( buf.substr(0, pos ) );
int iVal(0);
stream >> iVal;
if (stream.fail())
return 0;
typename stringstream_type::pos_type iEnd = stream.tellg(); // Position after reading
if (stream.fail())
iEnd = stream.str().length();
if (iEnd==(typename stringstream_type::pos_type)-1)
return 0;
*a_iPos += (int)iEnd;
*a_fVal = (TValue)iVal;
return 1;
}
//---------------------------------------------------------------------------------------------
/** \brief Check a given position in the expression for the presence of
a hex value.
\param a_szExpr Pointer to the expression string
\param [in/out] a_iPos Pointer to an interger value holding the current parsing
position in the expression.
\param [out] a_fVal Pointer to the position where the detected value shall be stored.
Hey values must be prefixed with "0x" in order to be detected properly.
*/
static int IsHexVal(const typename TString::value_type* a_szExpr, int *a_iPos, TValue *a_fVal)
{
if (a_szExpr[1]==0 || (a_szExpr[0]!='0' || a_szExpr[1]!='x') )
return 0;
unsigned iVal(0);
// New code based on streams for UNICODE compliance:
typename stringstream_type::pos_type nPos(0);
stringstream_type ss(a_szExpr + 2);
ss >> std::hex >> iVal;
nPos = ss.tellg();
if (nPos==(typename stringstream_type::pos_type)0)
return 1;
*a_iPos += (int)(2 + nPos);
*a_fVal = (TValue)iVal;
return 1;
}
//---------------------------------------------------------------------------------------------
static int IsBinVal(const typename TString::value_type* a_szExpr, int *a_iPos, TValue *a_fVal)
{
if (a_szExpr[0]!='#')
return 0;
unsigned iVal(0),
iBits(sizeof(iVal)*8),
i(0);
for (i=0; (a_szExpr[i+1]=='0' || a_szExpr[i+1]=='1') && i<iBits; ++i)
iVal |= (int)(a_szExpr[i+1]=='1') << ((iBits-1)-i);
if (i==0)
return 0;
if (i==iBits)
throw ParserError<TString>(_SL("Binary to integer conversion error (overflow)."));
*a_fVal = (unsigned)(iVal >> (iBits-i) );
*a_iPos += i+1;
return 1;
}
};
} // namespace mu
#endif
| 41.231373 | 120 | 0.565437 | [
"object",
"vector"
] |
04547d9ae5bf15005a29d684eeebb7c3561d13f5 | 1,696 | h | C | teaching/acm-computing-seminar/resources/langs/cpp/src/inheritance/operator-star/vectors.h | notmatthancock/notmatthancock.github.io | abcd91cc7c2653c5243fe96ba2fd681ec03930bb | [
"MIT"
] | null | null | null | teaching/acm-computing-seminar/resources/langs/cpp/src/inheritance/operator-star/vectors.h | notmatthancock/notmatthancock.github.io | abcd91cc7c2653c5243fe96ba2fd681ec03930bb | [
"MIT"
] | null | null | null | teaching/acm-computing-seminar/resources/langs/cpp/src/inheritance/operator-star/vectors.h | notmatthancock/notmatthancock.github.io | abcd91cc7c2653c5243fe96ba2fd681ec03930bb | [
"MIT"
] | null | null | null | #ifndef VECTORS_H
#define VECTORS_H
#include "matrix.h"
namespace vec {
// Row vector class inherits from the matrix class.
template<class T>
class rowvec : public mtx::matrix<T> {
public:
// Constructor.
rowvec(int n) : mtx::matrix<T>(1, n) {}
// A length function makes more sense for
// the vector class. Although `n_rows()` and
// `n_cols()` can still be called from `rowvec`
// instance.
int len() const { return this->n_cols(); }
// Accessor.
T & operator()(int i) const { return mtx::matrix<T>::operator()(0, i); }
// Add [] as a possibility, too.
T & operator[](int i) const { return (*this)(i); }
};
// Column vector class also inherits from the matrix class.
template<class T>
class colvec : public mtx::matrix<T> {
public:
// Constructor.
colvec(int n) : mtx::matrix<T>(n, 1) {}
// A length function.
int len() const { return this->n_rows(); }
// Accessor.
T & operator()(int i) const { return mtx::matrix<T>::operator()(i, 0); }
// Add [] as a possibility, too.
T & operator[](int i) const { return (*this)(i); }
};
// Overwrite the matrix inherited `operator*`
// so that a scalar is returned when a `rowvec` and
// `colvec` are multiplied.
template<class T>
T operator*(const rowvec<T> & x, const colvec<T> & y) {
// Use the inherited matrix operator defined in the `mtx` namespace.
mtx::matrix<T> a = mtx::operator*(x,y);
// Grab the only entry.
T z = a(0,0);
// And return it.
return z;
}
}
#endif
| 29.754386 | 80 | 0.553066 | [
"vector"
] |
045b2f969ce4d8f7df4b9736ec1eafaf4444faa0 | 1,365 | h | C | include/codes/strider/LayerSuperposition.h | yonch/wireless | 5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5 | [
"MIT"
] | 29 | 2015-03-11T04:54:01.000Z | 2021-09-20T06:07:59.000Z | include/codes/strider/LayerSuperposition.h | darksidelemm/wireless | 5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5 | [
"MIT"
] | null | null | null | include/codes/strider/LayerSuperposition.h | darksidelemm/wireless | 5e5a081fcf3cd49d901f25db6c4c1fabbfc921d5 | [
"MIT"
] | 16 | 2015-01-28T18:58:33.000Z | 2021-08-29T02:00:24.000Z | /*
* Copyright (c) 2012 Jonathan Perry
* This code is released under the MIT license (see LICENSE file).
*/
#pragma once
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
#include "../../CodeBench.h"
/**
* \ingroup strider
* \brief Composes linear combinations of layers using a given matrix, to produce symbols
*/
class LayerSuperposition {
public:
/**
* C'tor
*
* @param layerLength: number of symbols in each layer
* @param G: generator matrix for the code
*/
LayerSuperposition(unsigned int layerLength,
std::complex<double>* matrixG,
int rowsG,
int colsG);
/**
* Sets the packet to be encoded
*/
void setLayer(unsigned int layerInd,
const std::vector< ComplexSymbol >& layer);
/**
* Resets the encoder to start from the first symbol of first pass
*/
void reset();
/**
* Gets the next encoded symbol
*/
ComplexSymbol next();
private:
// The generator matrix, G
boost::numeric::ublas::matrix< ComplexSymbol,
boost::numeric::ublas::row_major > m_G;
// The layer symbols. Each layer is stored in a row.
boost::numeric::ublas::matrix< ComplexSymbol,
boost::numeric::ublas::column_major > m_layerSymbols;
// The next symbol to be output within current pass
unsigned int m_nextSymbol;
// The current pass that is output (which row of m_G)
unsigned int m_currentPass;
};
| 22.75 | 89 | 0.691575 | [
"vector"
] |
0474194a2a8fb5fc4b2c87ed3243583ea7f3cecb | 6,406 | c | C | library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slartg.c | ThalesGroup/WSQForAndroid | 411c76306eeee7e85dc9bc79b70bf379a8cd5529 | [
"BSD-2-Clause"
] | 6 | 2020-04-15T02:59:01.000Z | 2021-12-23T16:25:29.000Z | library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slartg.c | ThalesGroup/WSQForAndroid | 411c76306eeee7e85dc9bc79b70bf379a8cd5529 | [
"BSD-2-Clause"
] | null | null | null | library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slartg.c | ThalesGroup/WSQForAndroid | 411c76306eeee7e85dc9bc79b70bf379a8cd5529 | [
"BSD-2-Clause"
] | 6 | 2020-04-29T04:47:04.000Z | 2022-02-11T04:48:49.000Z | /*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slartg_(real *f, real *g, real *cs, real *sn, real *r)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SLARTG generate a plane rotation so that
[ CS SN ] . [ F ] = [ R ] where CS**2 + SN**2 = 1.
[ -SN CS ] [ G ] [ 0 ]
This is a slower, more accurate version of the BLAS1 routine SROTG,
with the following other differences:
F and G are unchanged on return.
If G=0, then CS=1 and SN=0.
If F=0 and (G .ne. 0), then CS=0 and SN=1 without doing any
floating point operations (saves work in SBDSQR when
there are zeros on the diagonal).
If F exceeds G in magnitude, CS will be positive.
Arguments
=========
F (input) REAL
The first component of vector to be rotated.
G (input) REAL
The second component of vector to be rotated.
CS (output) REAL
The cosine of the rotation.
SN (output) REAL
The sine of the rotation.
R (output) REAL
The nonzero component of the rotated vector.
=====================================================================
*/
/* Initialized data */
static logical first = TRUE_;
/* System generated locals */
int i__1;
real r__1, r__2;
/* Builtin functions */
double log(doublereal), pow_ri(real *, int *), sqrt(doublereal);
/* Local variables */
static int i;
static real scale;
static int count;
static real f1, g1, safmn2, safmx2;
extern doublereal slamch_(char *);
static real safmin, eps;
if (first) {
first = FALSE_;
safmin = slamch_("S");
eps = slamch_("E");
r__1 = slamch_("B");
i__1 = (int) (log(safmin / eps) / log(slamch_("B")) / 2.f);
safmn2 = pow_ri(&r__1, &i__1);
safmx2 = 1.f / safmn2;
}
if (*g == 0.f) {
*cs = 1.f;
*sn = 0.f;
*r = *f;
} else if (*f == 0.f) {
*cs = 0.f;
*sn = 1.f;
*r = *g;
} else {
f1 = *f;
g1 = *g;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale >= safmx2) {
count = 0;
L10:
++count;
f1 *= safmn2;
g1 *= safmn2;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale >= safmx2) {
goto L10;
}
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
i__1 = count;
for (i = 1; i <= count; ++i) {
*r *= safmx2;
/* L20: */
}
} else if (scale <= safmn2) {
count = 0;
L30:
++count;
f1 *= safmx2;
g1 *= safmx2;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale <= safmn2) {
goto L30;
}
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
i__1 = count;
for (i = 1; i <= count; ++i) {
*r *= safmn2;
/* L40: */
}
} else {
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
}
if (dabs(*f) > dabs(*g) && *cs < 0.f) {
*cs = -(doublereal)(*cs);
*sn = -(doublereal)(*sn);
*r = -(doublereal)(*r);
}
}
return 0;
/* End of SLARTG */
} /* slartg_ */
| 30.798077 | 80 | 0.588667 | [
"vector"
] |
04747c2b92b3a3f4bd3f5b6d4c4c4d56c7b8541b | 1,034 | h | C | modules/task_3/lukashuk_d_monte_carlo/monte_carlo.h | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/lukashuk_d_monte_carlo/monte_carlo.h | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/lukashuk_d_monte_carlo/monte_carlo.h | Gurgen-Arm/pp_2021_autumn | ad549e49d765612c4544f34b04c9eb9432ac0dc7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Lukashuk Diana
#ifndef MODULES_TASK_3_LUKASHUK_D_MONTE_CARLO_MONTE_CARLO_H_
#define MODULES_TASK_3_LUKASHUK_D_MONTE_CARLO_MONTE_CARLO_H_
#include <mpi.h>
#include <cmath>
#include <ctime>
#include <random>
#include <vector>
#include <iostream>
#include <functional>
#define function std::function<double(const std::vector<double>&)>
std::vector<double> getRandomNode(const std::vector<double>& lower,
const std::vector<double>& upper, int points);
std::vector<double> upperLower(const std::vector<double>& lower,
const std::vector<double>& upper);
double getSequential(const std::vector<double>& upper_lover,
const std::vector<double>& node, int points,
const function& func);
double getParallel(const std::vector<double>& upper_lover,
const std::vector<double>& node, int points,
const function& func);
#endif // MODULES_TASK_3_LUKASHUK_D_MONTE_CARLO_MONTE_CARLO_H_
| 39.769231 | 80 | 0.679884 | [
"vector"
] |
0b96d78b75987721cca021357c2df88b8ff33d49 | 3,577 | h | C | libwasmint/interpreter/ByteCode.h | lukewagner/wasmint | 2138579f5fed8b76221b9e580eeb2038239464da | [
"Apache-2.0"
] | 90 | 2015-10-29T20:23:29.000Z | 2021-12-21T11:35:18.000Z | libwasmint/interpreter/ByteCode.h | lukewagner/wasmint | 2138579f5fed8b76221b9e580eeb2038239464da | [
"Apache-2.0"
] | 13 | 2015-10-30T07:33:23.000Z | 2019-01-03T13:19:19.000Z | libwasmint/interpreter/ByteCode.h | lukewagner/wasmint | 2138579f5fed8b76221b9e580eeb2038239464da | [
"Apache-2.0"
] | 15 | 2015-10-30T01:14:27.000Z | 2021-09-06T05:33:34.000Z | /*
* Copyright 2015 WebAssembly Community Group
*
* 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.
*/
#ifndef WASMINT_BYTECODE_H
#define WASMINT_BYTECODE_H
#include <vector>
#include <cstdint>
#include "ByteOpcodes.h"
#include <interpreter/SafeAddition.h>
#include <stdexcept>
#include <cstring>
#include <iostream>
namespace wasmint {
class ByteCode {
std::size_t usedCodeSize_ = 0;
std::vector<uint32_t> byteCode_;
const uint8_t* data() const {
return (uint8_t *) byteCode_.data();
}
uint8_t* data() {
return (uint8_t *) byteCode_.data();
}
public:
ByteCode() {
}
template<typename T>
void get(T* target, std::size_t position) const {
std::size_t size = sizeof(T);
std::size_t unused;
if (safeSizeTAddition(position, size, &unused)) {
throw std::out_of_range("Can't call get on bytecode with length " + std::to_string(usedCodeSize_)
+ " with pos " + std::to_string(position) + " and size " + std::to_string(size));
}
std::memcpy(target, data() + position, size);
}
template<typename T>
T get(std::size_t position) const {
T target;
std::size_t size = sizeof(T);
std::size_t unused;
if (safeSizeTAddition(position, size, &unused)) {
throw std::out_of_range("Can't call get on bytecode with length " + std::to_string(usedCodeSize_)
+ " with pos " + std::to_string(position) + " and size " + std::to_string(size));
}
std::memcpy(&target, data() + position, size);
return target;
}
template<typename T>
void getUnsafe(T* target, std::size_t position) const {
(*target) = *((T*) (data() + position));
}
void appendOpcode(ByteOpcode opcode) {
append((uint32_t) opcode);
}
template<typename T>
void append(T value) {
usedCodeSize_ += sizeof value;
if (usedCodeSize_ > byteCode_.size() * 4) {
if (usedCodeSize_ % 4 == 0) {
byteCode_.resize(usedCodeSize_ / 4);
} else {
// round up to the next word
byteCode_.resize((usedCodeSize_ / 4 + 1) * 4);
}
}
memcpy(data() + (usedCodeSize_ - sizeof(value)), &value, sizeof(value));
}
template<typename T>
void write(std::size_t offset, T value) {
if (offset + sizeof(value) > usedCodeSize_) {
throw std::domain_error(std::to_string(offset) + " + " + std::to_string(sizeof(value)) + " <= " + std::to_string(usedCodeSize_) + " failed");
}
memcpy(data() + offset, &value, sizeof(value));
}
uint32_t size() const {
return (uint32_t) usedCodeSize_;
}
};
}
#endif //WASMINT_BYTECODE_H
| 31.9375 | 157 | 0.561923 | [
"vector"
] |
0b993734471b65b033751fdddcc4a9d2346e1d97 | 3,409 | h | C | Sources/system/SessionSink.h | facebookarchive/ie-toolbar | cfcc1a8ffd6d6c7d8b1e12c8317ff728d2173cac | [
"Apache-2.0"
] | 4 | 2016-05-12T23:53:32.000Z | 2021-10-31T15:18:19.000Z | Sources/system/SessionSink.h | facebookarchive/ie-toolbar | cfcc1a8ffd6d6c7d8b1e12c8317ff728d2173cac | [
"Apache-2.0"
] | null | null | null | Sources/system/SessionSink.h | facebookarchive/ie-toolbar | cfcc1a8ffd6d6c7d8b1e12c8317ff728d2173cac | [
"Apache-2.0"
] | 3 | 2015-01-10T18:23:22.000Z | 2021-10-31T15:18:10.000Z | /**
* Facebook Internet Explorer Toolbar Software License
* Copyright (c) 2009 Facebook, Inc.
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (which, together with any graphical images included with such
* software, are collectively referred to below as the "Software") to (a) use,
* reproduce, display, distribute, execute, and transmit the Software, (b)
* prepare derivative works of the Software (excluding any graphical images
* included with the Software, which may not be modified or altered), and (c)
* permit third-parties to whom the Software is furnished to do so, all
* subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* Facebook, Inc. retains ownership of the Software and all associated
* intellectual property rights. All rights not expressly granted in this
* license are reserved by Facebook, Inc.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#if !defined(AFX_TESTAPP_H__3D916FFB_17FD_424F_B91D_4CF63A10DF42__INCLUDED_)
#define AFX_TESTAPP_H__3D916FFB_17FD_424F_B91D_4CF63A10DF42__INCLUDED_
#include "ProtocolImpl.h"
#include "../util/StringUtils.h"
namespace facebook{
/**
* class SessionSink
*
* Used to handle protocol events and
* send notifications to the window
*/
class SessionSink :
public InternetProtocolSink<SessionSink>,
public IHttpNegotiate {
typedef InternetProtocolSink<SessionSink> BaseClass;
public:
BEGIN_COM_MAP(SessionSink)
COM_INTERFACE_ENTRY(IHttpNegotiate)
COM_INTERFACE_ENTRY_CHAIN(BaseClass)
END_COM_MAP()
BEGIN_SERVICE_MAP(SessionSink)
SERVICE_ENTRY(IID_IHttpNegotiate)
END_SERVICE_MAP()
STDMETHODIMP BeginningTransaction(
/* [in] */ LPCWSTR url,
/* [in] */ LPCWSTR headers,
/* [in] */ DWORD reserved,
/* [out] */ LPWSTR *additionalHeaders);
STDMETHODIMP OnResponse(
/* [in] */ DWORD responseCode,
/* [in] */ LPCWSTR responseHeaders,
/* [in] */ LPCWSTR requestHeaders,
/* [out] */ LPWSTR *additionalRequestHeaders);
STDMETHODIMP ReportProgress(
/* [in] */ ULONG statusCode,
/* [in] */ LPCWSTR statusText);
private:
/**
* Process the responce header data. If it containst cookie info -
* report this to the parent dialog
*
* @param header - HTTP header to process
*/
void STDMETHODCALLTYPE processHeader(String header);
};
typedef CustomSinkStartPolicy<SessionSink> SessionPolicy;
} // !namespace facebook
#endif // !defined(AFX_TESTAPP_H__3D916FFB_17FD_424F_B91D_4CF63A10DF42__INCLUDED_)
| 35.884211 | 82 | 0.758287 | [
"object"
] |
0b9e6d374fd6b0f7993b8b00f8712fdbeece7975 | 7,832 | h | C | cc3235sf/ti_sdk/simplelink_cc32xx_sdk_4_10_00_07/source/ti/display/DisplayUart2.h | lagerdata/unit-test_templates | 783b34fc1552c68afa28187a7b5343a384798bd8 | [
"MIT"
] | null | null | null | cc3235sf/ti_sdk/simplelink_cc32xx_sdk_4_10_00_07/source/ti/display/DisplayUart2.h | lagerdata/unit-test_templates | 783b34fc1552c68afa28187a7b5343a384798bd8 | [
"MIT"
] | null | null | null | cc3235sf/ti_sdk/simplelink_cc32xx_sdk_4_10_00_07/source/ti/display/DisplayUart2.h | lagerdata/unit-test_templates | 783b34fc1552c68afa28187a7b5343a384798bd8 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** ============================================================================
* @file DisplayUart2.h
*
* @brief Display.h implementation for UART output
*
* # DisplayUart2 specifics #
*
* DisplayUart2 has two sets of function pointer tables. One which adds some
* ANSI/VT100 codes to the output, for cursor placement etc, and a minimal
* implementation which basically is a wrapper for UART2_write.
* * DisplayUart2Ansi_fxnTable
* * DisplayUart2Min_fxnTable
*
*
* ## DisplayUart2Min #
*
* DisplayUart2Min simply formats and outputs the text over UART and adds a
* newline at the end of each statement.
*
* Calls to Display_clear, Display_clearLine(s), and the line and column
* specifiers in Display_printf(handle, line, col, fmt, ...) are ignored.
*
* ## DisplayUart2Ansi #
*
* DisplayUart2Ansi will send the following escape-strings to the UART when
* it is opened:
* * Reset terminal
* * Clear screen
* * Set scrolling region from line 10 (not inclusive)
* * Set cursor to line 11
*
* When Display_print(handle, line, col, fmt, ...) is called with a line number
* the following is sent:
* * Save cursor position
* * Set scroll region from line 10
* * Move cursor to line, column
* * String to be printed
* * Restore cursor position
*
* If Display_printf is called with the line "number" `DisplayUart2_SCROLLING`,
* the string to be printed is simply output at the current cursor location,
* without saving or restoring the position. If the terminal supports the
* scrolling region feature, as most do, then the terminal will ensure that
* the content output here will scroll up but not overwrite the text written
* outside the scroll region.
*
* In this manner it is possible to have two separate outputs, one with a
* log of events, and one with fixed positions as on an LCD. Unless the
* `DisplayUart_SCROLLING` line specifier is used, any line number can be used,
* also those nominally inside the scrolling region.
*
* There is also a helper file <ti/display/AnsiColor.h> with a macro to set the
* color and style of the text.
*
* # Usage Example #
*
* @code
* #include <ti/display/Display.h>
* #include <ti/display/DisplayUart2.h>
* #include <ti/display/AnsiColor.h>
*
* #define MAXPRINTLEN 128
*
* DisplayUart2_Object displayUart2Object;
* static char uartStringBuf[MAXPRINTLEN];
*
* const DisplayUart2_HWAttrs displayUart2HWAttrs = {
* .uartIdx = CONFIG_UART0,
* .baudRate = 115200,
* .mutexTimeout = BIOS_WAIT_FOREVER,
* .strBuf = uartStringBuf,
* .strBufLen = MAXPRINTLEN,
* };
*
* const Display_Config Display_config[] = {
* {
* .fxnTablePtr = &DisplayUart2Ansi_fxnTable,
* //.fxnTablePtr = &DisplayUart2Min_fxnTable,
* .object = &displayUartObject,
* .hwAttrs = &displayUartHWAttrs
* }
* };
*
* const uint8_t Display_count = sizeof(Display_config) / sizeof(Display_Config);
*
* void myTask(uintptr_t a0, uintptr_t a1)
* {
* Display_Handle handle = Display_open(Display_Type_UART);
* Display_printf(handle, 1, 0, "Hello");
* Display_printf(handle, 2, 6, ANSI_COLOR(FG_GREEN) "World!" ANSI_COLOR(ATTR_RESET));
* }
* @endcode
*
* ============================================================================
*/
#ifndef ti_display_DisplayUart2__include
#define ti_display_DisplayUart2__include
#include <ti/drivers/dpl/SemaphoreP.h>
#include <ti/drivers/UART2.h>
#include <ti/display/Display.h>
#include <stdint.h>
/* Line number that means 'put in scrolling section', if exists */
#define DisplayUart2_SCROLLING 0xFF
extern const Display_FxnTable DisplayUart2Min_fxnTable;
extern const Display_FxnTable DisplayUart2Ansi_fxnTable;
/*!
* @brief DisplayUart2 Attributes
*
* The DisplayUart2 driver uses a buffer for formatting messages, which
* is then passed to UART2_write(). The location and size of
* the buffer are specified in a DisplayUart2_HWAttrs structure.
* Access to the buffer is synchronized by a semaphore. The timeout
* for acquiring the semaphore is specified in the attributes.
*/
typedef struct {
/*! Index of uart in UART_config[] */
unsigned int uartIdx;
/*! Baud rate for uart */
unsigned int baudRate;
/*! Timeout for acquiring semaphore */
unsigned int mutexTimeout;
/*! Buffer for formatting messages */
char *strBuf;
/*! Size of buffer */
uint16_t strBufLen;
} DisplayUart2_HWAttrs;
/*!
* @brief DisplayUart2 Object
*
* The application must not access any member variables of this structure!
*/
typedef struct {
UART2_Handle hUart;
SemaphoreP_Handle mutex;
char *lineClearSeq;
} DisplayUart2_Object, *DisplayUart2_Handle;
void DisplayUart2Min_init(Display_Handle handle);
void DisplayUart2Ansi_init(Display_Handle handle);
Display_Handle DisplayUart2Min_open(Display_Handle, Display_Params * params);
Display_Handle DisplayUart2Ansi_open(Display_Handle, Display_Params * params);
void DisplayUart2Min_clear(Display_Handle handle);
void DisplayUart2Ansi_clear(Display_Handle handle);
void DisplayUart2Min_clearLines(Display_Handle handle,
uint8_t fromLine,
uint8_t toLine);
void DisplayUart2Ansi_clearLines(Display_Handle handle,
uint8_t fromLine,
uint8_t toLine);
void DisplayUart2Min_vprintf(Display_Handle handle, uint8_t line,
uint8_t column, const char *fmt, va_list va);
void DisplayUart2Ansi_vprintf(Display_Handle handle, uint8_t line,
uint8_t column, const char *fmt, va_list va);
void DisplayUart2Min_close(Display_Handle);
void DisplayUart2Ansi_close(Display_Handle);
int DisplayUart2Min_control(Display_Handle handle, unsigned int cmd, void *arg);
int DisplayUart2Ansi_control(Display_Handle handle, unsigned int cmd, void *arg);
unsigned int DisplayUart2Min_getType(void);
unsigned int DisplayUart2Ansi_getType(void);
#endif /* ti_display_DisplayUart2__include */
| 37.653846 | 89 | 0.699183 | [
"object"
] |
0baf864f6cc003fc241012e18ae77ab39d674386 | 15,512 | h | C | src/fastertransformer/th_op/t5/T5DecoderOp.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | src/fastertransformer/th_op/t5/T5DecoderOp.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | src/fastertransformer/th_op/t5/T5DecoderOp.h | hieuhoang/FasterTransformer | 440695ccac874574b1d2e1121788e8fa674b4381 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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.
*/
#include "src/fastertransformer/models/t5/T5Decoder.h"
#include "src/fastertransformer/th_op/th_utils.h"
#include "src/fastertransformer/utils/mpi_utils.h"
namespace ft = fastertransformer;
namespace th = torch;
namespace torch_ext {
class IFT5Decoder {
public:
virtual ~IFT5Decoder() {}
virtual void forward(size_t batch_size,
size_t step,
th::Tensor& from_tensor,
th::Tensor& memory_tensor,
th::Tensor& memory_sequence_length,
th::Tensor& sequence_length,
th::Tensor& output_tensor,
th::Tensor& self_cache_keys_tensor,
th::Tensor& self_cache_values_tensor,
th::Tensor& memory_cache_keys_tensor,
th::Tensor& memory_cache_values_tensor,
th::Tensor& relative_attention_bias_tensor) = 0;
};
template<typename T>
class FTT5Decoder: public IFT5Decoder {
public:
FTT5Decoder(int head_num,
int head_size,
int inter_size,
int d_model,
int layer_num,
int mem_d_model,
int tensor_para_size,
int pipeline_para_size,
const std::vector<th::Tensor>& w):
_head_num(head_num),
_head_size(head_size),
_inter_size(inter_size),
_d_model(d_model),
_weights(w),
_layer_num(layer_num),
_mem_d_model(mem_d_model)
{
tensor_para_.world_size_ = tensor_para_size;
pipeline_para_.world_size_ = pipeline_para_size;
init_nccl_comm();
int hidden_dim = _head_num * _head_size;
ft::check_cuda_error(cublasLtCreate(&_cublasltHandle));
cublas_algo_map_ = new ft::cublasAlgoMap("gemm_config.in");
cublas_wrapper_mutex_ = new std::mutex();
decoder_layer_weights.clear();
decoder_layer_weights.resize(_layer_num);
for (int i = 0; i < _layer_num; ++i) {
int local_num_layer = (int)(ceil(_layer_num * 1.0f / pipeline_para_.world_size_));
if (!(i < _layer_num && (i >= local_num_layer * pipeline_para_.rank_)
&& (i < local_num_layer * (pipeline_para_.rank_ + 1)))) {
continue;
}
const int first_layer_index = local_num_layer * pipeline_para_.rank_;
decoder_layer_weights[i]->pre_layernorm_weights.gamma =
get_ptr<T>(_weights[0]) + (i - first_layer_index) * _d_model;
decoder_layer_weights[i]->self_attention_weights.query_weight.kernel =
get_ptr<T>(_weights[1]) + (i - first_layer_index) * _d_model * 3 * hidden_dim;
decoder_layer_weights[i]->self_attention_weights.attention_output_weight.kernel =
get_ptr<T>(_weights[2]) + (i - first_layer_index) * hidden_dim * _d_model;
decoder_layer_weights[i]->self_attn_layernorm_weights.gamma =
get_ptr<T>(_weights[3]) + (i - first_layer_index) * _d_model;
decoder_layer_weights[i]->cross_attention_weights.query_weight.kernel =
get_ptr<T>(_weights[4]) + (i - first_layer_index) * _d_model * hidden_dim;
decoder_layer_weights[i]->cross_attention_weights.key_weight.kernel =
get_ptr<T>(_weights[5]) + (i - first_layer_index) * _mem_d_model * hidden_dim;
decoder_layer_weights[i]->cross_attention_weights.value_weight.kernel =
get_ptr<T>(_weights[6]) + (i - first_layer_index) * _mem_d_model * hidden_dim;
decoder_layer_weights[i]->cross_attention_weights.attention_output_weight.kernel =
get_ptr<T>(_weights[7]) + (i - first_layer_index) * hidden_dim * _d_model;
decoder_layer_weights[i]->cross_attn_layernorm_weights.gamma =
get_ptr<T>(_weights[8]) + (i - first_layer_index) * _d_model;
decoder_layer_weights[i]->ffn_weights.intermediate_weight.kernel =
get_ptr<T>(_weights[9]) + (i - first_layer_index) * _d_model * _inter_size;
decoder_layer_weights[i]->ffn_weights.output_weight.kernel =
get_ptr<T>(_weights[10]) + (i - first_layer_index) * _inter_size * _d_model;
}
}
void init_nccl_comm()
{
int mpi_initialized;
MPICHECK(MPI_Initialized(&mpi_initialized));
if (!mpi_initialized) {
printf("[INFO] MPI is not initialized! Skipped the NCCL communication initialization.\n");
if (tensor_para_.world_size_ != 1) {
printf("[FATAL] MPI initialization can only be skipped when tensor_para_size=1, but got %d!\n",
tensor_para_.world_size_);
}
if (pipeline_para_.world_size_ != 1) {
printf("[FATAL] MPI initialization can only be skipped when pipeline_para_size=1, but got %d!\n",
pipeline_para_.world_size_);
}
return;
}
int rank, world_size;
MPICHECK(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
MPICHECK(MPI_Comm_size(MPI_COMM_WORLD, &world_size));
tensor_para_.rank_ = rank % tensor_para_.world_size_;
pipeline_para_.rank_ = rank / tensor_para_.world_size_;
ncclUniqueId tensor_para_nccl_uid;
ncclUniqueId pipeline_para_nccl_uid;
// assume gpu_num = n * k,
// tensor parallelism group size is n
// pipeline parallelism group size is k
if (tensor_para_.rank_ == 0) {
// get the uid of each tensor parallelism group
// here, 0, 1, ..., n-1 are in group 0,
// n, ..., 2n - 1 are in group 1.
NCCLCHECK(ncclGetUniqueId(&tensor_para_nccl_uid));
for (int i = 1; i < (int)tensor_para_.world_size_; i++) {
FT_LOG_INFO("rank %d sends tensor_para_nccl_uid to rank %d \n", rank, rank + i);
MPICHECK(MPI_Send(
&tensor_para_nccl_uid, sizeof(tensor_para_nccl_uid), MPI_BYTE, rank + i, 0, MPI_COMM_WORLD));
}
}
else {
MPI_Status status;
FT_LOG_INFO("rank %d receives tensor_para_nccl_uid from rank %d \n", rank, rank - (int)tensor_para_.rank_);
MPICHECK(MPI_Recv(&tensor_para_nccl_uid,
sizeof(tensor_para_nccl_uid),
MPI_BYTE,
rank - tensor_para_.rank_,
0,
MPI_COMM_WORLD,
&status));
}
if (pipeline_para_.rank_ == 0) {
// get the uid of each pipeline parallelism group
// 0, k, 2k, are in group 0
// 1, k+1, 2k+1 are in group 1
NCCLCHECK(ncclGetUniqueId(&pipeline_para_nccl_uid));
for (int i = 1; i < (int)pipeline_para_.world_size_; i++) {
FT_LOG_INFO("rank %d sends pipeline_para_nccl_uid to rank %d \n",
rank,
rank + i * (int)tensor_para_.world_size_);
MPICHECK(MPI_Send(&pipeline_para_nccl_uid,
sizeof(pipeline_para_nccl_uid),
MPI_BYTE,
rank + i * tensor_para_.world_size_,
0,
MPI_COMM_WORLD));
}
}
else {
MPI_Status status;
FT_LOG_INFO(
"rank %d receives pipeline_para_nccl_uid from rank %d \n", rank, rank % (int)tensor_para_.world_size_);
MPICHECK(MPI_Recv(&pipeline_para_nccl_uid,
sizeof(pipeline_para_nccl_uid),
MPI_BYTE,
rank % tensor_para_.world_size_,
0,
MPI_COMM_WORLD,
&status));
}
NCCLCHECK(ncclCommInitRank(
&tensor_para_.nccl_comm_, tensor_para_.world_size_, tensor_para_nccl_uid, tensor_para_.rank_));
NCCLCHECK(ncclCommInitRank(
&pipeline_para_.nccl_comm_, pipeline_para_.world_size_, pipeline_para_nccl_uid, pipeline_para_.rank_));
}
~FTT5Decoder() override
{
cublasLtDestroy(_cublasltHandle);
delete cublas_algo_map_;
delete cublas_wrapper_mutex_;
}
void forward(size_t batch_size,
size_t step,
th::Tensor& from_tensor,
th::Tensor& memory_tensor,
th::Tensor& memory_sequence_length,
th::Tensor& sequence_length,
th::Tensor& output_tensor,
th::Tensor& self_cache_keys_tensor,
th::Tensor& self_cache_values_tensor,
th::Tensor& memory_cache_keys_tensor,
th::Tensor& memory_cache_values_tensor,
th::Tensor& relative_attention_bias_tensor) override
{
auto stream = at::cuda::getCurrentCUDAStream().stream();
cublasHandle_t _cublasHandle = at::cuda::getCurrentCUDABlasHandle();
cublasSetStream(_cublasHandle, stream);
fastertransformer::Allocator<ft::AllocatorType::TH>* allocator =
new fastertransformer::Allocator<ft::AllocatorType::TH>();
ft::cublasMMWrapper* cublas_wrapper = new ft::cublasMMWrapper(
_cublasHandle, _cublasltHandle, stream, cublas_algo_map_, cublas_wrapper_mutex_, allocator);
if (std::is_same<T, half>::value) {
cublas_wrapper->setFP16GemmConfig();
}
else if (std::is_same<T, float>::value) {
cublas_wrapper->setFP32GemmConfig();
}
ft::T5Decoder<T> decoder = ft::T5Decoder<T>(batch_size,
_head_num,
_head_size,
_inter_size,
_d_model,
_layer_num,
stream,
cublas_wrapper,
allocator,
true,
tensor_para_,
pipeline_para_,
ft::ActivationType::Relu);
int tmp_step = step + 1;
std::vector<ft::Tensor> input_tensors =
std::vector<ft::Tensor>{convert_tensor<T>(from_tensor),
convert_tensor<T>(memory_tensor),
convert_tensor<int>(memory_sequence_length),
ft::Tensor{ft::MEMORY_GPU, ft::TYPE_BOOL, {batch_size}, nullptr},
ft::Tensor{ft::MEMORY_CPU, ft::TYPE_INT32, {1}, &tmp_step},
convert_tensor<int>(sequence_length),
convert_tensor<T>(relative_attention_bias_tensor)};
std::vector<ft::Tensor> output_tensors = std::vector<ft::Tensor>{convert_tensor<T>(output_tensor),
convert_tensor<T>(self_cache_keys_tensor),
convert_tensor<T>(self_cache_values_tensor),
convert_tensor<T>(memory_cache_keys_tensor),
convert_tensor<T>(memory_cache_values_tensor)};
try {
decoder.forward(&output_tensors, &input_tensors, &decoder_layer_weights);
}
catch (std::runtime_error& error) {
std::cout << error.what();
exit(-1);
}
catch (...) {
std::cout << "Runtime error";
exit(-1);
}
delete cublas_wrapper;
delete allocator;
}
private:
const int _head_num;
const int _head_size;
const int _inter_size;
const int _d_model;
std::vector<th::Tensor> _weights;
const int _layer_num;
const int _mem_d_model;
cublasLtHandle_t _cublasltHandle;
std::mutex* cublas_wrapper_mutex_;
ft::cublasAlgoMap* cublas_algo_map_;
std::vector<ft::T5DecoderLayerWeight<T>*> decoder_layer_weights;
ft::NcclParam tensor_para_;
ft::NcclParam pipeline_para_;
};
class FasterTransformerT5Decoder: public th::jit::CustomClassHolder {
public:
FasterTransformerT5Decoder(th::Tensor self_layernorm_gamma,
th::Tensor self_kernel_q,
th::Tensor self_output_kernel,
th::Tensor cross_layernorm_gamma,
th::Tensor cross_kernel_q,
th::Tensor cross_kernel_k,
th::Tensor cross_kernel_v,
th::Tensor cross_output_kernel,
th::Tensor ffn_layernorm_gamma,
th::Tensor inter_kernel,
th::Tensor output_kernel,
int64_t head_num,
int64_t head_size,
int64_t inter_size,
int64_t d_model,
int64_t layer_num,
int64_t mem_d_model,
int64_t tensor_para_size,
int64_t pipeline_para_size);
~FasterTransformerT5Decoder();
std::vector<th::Tensor> forward(int64_t step,
th::Tensor from_tensor,
th::Tensor memory_tensor,
th::Tensor memory_sequence_length,
th::Tensor sequence_length,
th::Tensor self_cache_keys_tensor,
th::Tensor self_cache_values_tensor,
th::Tensor memory_cache_keys_tensor,
th::Tensor memory_cache_values_tensor,
th::Tensor relative_attention_bias_tensor);
std::vector<th::Tensor> get_pickle_info() const;
private:
const at::ScalarType _st;
IFT5Decoder* ftdecoder;
th::Tensor head_info;
std::vector<th::Tensor> weights;
};
} // namespace torch_ext
| 46.166667 | 120 | 0.537197 | [
"vector"
] |
0bb1515d764b746d90f2feff487abd20a9e64bb9 | 1,093 | h | C | merge-intervals.h | kiddliu/midnight-leetcode | 1c5638102111ff7509b1bc125ba66741ba6b149e | [
"MIT"
] | null | null | null | merge-intervals.h | kiddliu/midnight-leetcode | 1c5638102111ff7509b1bc125ba66741ba6b149e | [
"MIT"
] | null | null | null | merge-intervals.h | kiddliu/midnight-leetcode | 1c5638102111ff7509b1bc125ba66741ba6b149e | [
"MIT"
] | null | null | null | #ifndef MERGE_INTERVALS_H_
#define MERGE_INTERVALS_H_
#include <algorithm>
#include <deque>
#include <vector>
namespace solution {
std::vector<std::vector<int>> merge(std::vector<std::vector<int>>& intervals) {
// why Pochmann's mind is so neat?
// Runtime: 12 ms, faster than 98.58% of C++ online submissions for Merge Intervals.
// Memory Usage: 14.2 MB, less than 81.35% of C++ online submissions for Merge Intervals.
//
if (intervals.size() == 1) return intervals;
std::sort(
intervals.begin(), intervals.end(),
[](const std::vector<int>& first, const std::vector<int>& second) {
return first[0] != second[0] ? first[0] < second[0]
: first[1] < second[1];
});
std::vector<std::vector<int>> result;
for (auto& interval : intervals) {
if (!result.empty() && interval[0] <= result.back()[1]) {
result.back()[1] = std::max(interval[1], result.back()[1]);
} else {
result.push_back(interval);
}
}
return result;
}
} // namespace solution
#endif // MERGE_INTERVALS_H_
| 28.025641 | 91 | 0.610247 | [
"vector"
] |
0bbd8de266bd851ab71b6d96a533b98e1838614b | 11,014 | h | C | components/nvml.h | alex-courtis/slstatus | b2c6bed08626a370d00036ae845f5e8d15bcda11 | [
"0BSD"
] | null | null | null | components/nvml.h | alex-courtis/slstatus | b2c6bed08626a370d00036ae845f5e8d15bcda11 | [
"0BSD"
] | null | null | null | components/nvml.h | alex-courtis/slstatus | b2c6bed08626a370d00036ae845f5e8d15bcda11 | [
"0BSD"
] | null | null | null | /**
* For /usr/lib/libnvidia-ml.so
*
* Took used bits out of nvml.h from http://developer.download.nvidia.com/compute/cuda/7.5/Prod/gdk/gdk_linux_amd64_352_79_release.run
*/
typedef struct nvmlDevice_st* nvmlDevice_t;
/**
* Return values for NVML API calls.
*/
typedef enum nvmlReturn_enum
{
NVML_SUCCESS = 0, //!< The operation was successful
NVML_ERROR_UNINITIALIZED = 1, //!< NVML was not first initialized with nvmlInit()
NVML_ERROR_INVALID_ARGUMENT = 2, //!< A supplied argument is invalid
NVML_ERROR_NOT_SUPPORTED = 3, //!< The requested operation is not available on target device
NVML_ERROR_NO_PERMISSION = 4, //!< The current user does not have permission for operation
NVML_ERROR_ALREADY_INITIALIZED = 5, //!< Deprecated: Multiple initializations are now allowed through ref counting
NVML_ERROR_NOT_FOUND = 6, //!< A query to find an object was unsuccessful
NVML_ERROR_INSUFFICIENT_SIZE = 7, //!< An input argument is not large enough
NVML_ERROR_INSUFFICIENT_POWER = 8, //!< A device's external power cables are not properly attached
NVML_ERROR_DRIVER_NOT_LOADED = 9, //!< NVIDIA driver is not loaded
NVML_ERROR_TIMEOUT = 10, //!< User provided timeout passed
NVML_ERROR_IRQ_ISSUE = 11, //!< NVIDIA Kernel detected an interrupt issue with a GPU
NVML_ERROR_LIBRARY_NOT_FOUND = 12, //!< NVML Shared Library couldn't be found or loaded
NVML_ERROR_FUNCTION_NOT_FOUND = 13, //!< Local version of NVML doesn't implement this function
NVML_ERROR_CORRUPTED_INFOROM = 14, //!< infoROM is corrupted
NVML_ERROR_GPU_IS_LOST = 15, //!< The GPU has fallen off the bus or has otherwise become inaccessible
NVML_ERROR_RESET_REQUIRED = 16, //!< The GPU requires a reset before it can be used again
NVML_ERROR_OPERATING_SYSTEM = 17, //!< The GPU control device has been blocked by the operating system/cgroups
NVML_ERROR_UNKNOWN = 999 //!< An internal driver error occurred
} nvmlReturn_t;
/**
* Temperature sensors.
*/
typedef enum nvmlTemperatureSensors_enum
{
NVML_TEMPERATURE_GPU = 0, //!< Temperature sensor for the GPU die
// Keep this last
NVML_TEMPERATURE_COUNT
} nvmlTemperatureSensors_t;
/**
* Helper method for converting NVML error codes into readable strings.
*
* For all products.
*
* @param result NVML error code to convert
*
* @return String representation of the error.
*
*/
const char* nvmlErrorString(nvmlReturn_t result);
/**
* Initialize NVML, but don't initialize any GPUs yet.
*
* \note In NVML 5.319 new nvmlInit_v2 has replaced nvmlInit"_v1" (default in NVML 4.304 and older) that
* did initialize all GPU devices in the system.
*
* This allows NVML to communicate with a GPU
* when other GPUs in the system are unstable or in a bad state. When using this API, GPUs are
* discovered and initialized in nvmlDeviceGetHandleBy* functions instead.
*
* \note To contrast nvmlInit_v2 with nvmlInit"_v1", NVML 4.304 nvmlInit"_v1" will fail when any detected GPU is in
* a bad or unstable state.
*
* For all products.
*
* This method, should be called once before invoking any other methods in the library.
* A reference count of the number of initializations is maintained. Shutdown only occurs
* when the reference count reaches zero.
*
* @return
* - \ref NVML_SUCCESS if NVML has been properly initialized
* - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running
* - \ref NVML_ERROR_NO_PERMISSION if NVML does not have permission to talk to the driver
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t nvmlInit(void);
/***************************************************************************************************/
/**
* Retrieves the number of compute devices in the system. A compute device is a single GPU.
*
* For all products.
*
* Note: New nvmlDeviceGetCount_v2 (default in NVML 5.319) returns count of all devices in the system
* even if nvmlDeviceGetHandleByIndex_v2 returns NVML_ERROR_NO_PERMISSION for such device.
* Update your code to handle this error, or use NVML 4.304 or older nvml header file.
* For backward binary compatibility reasons _v1 version of the API is still present in the shared
* library.
* Old _v1 version of nvmlDeviceGetCount doesn't count devices that NVML has no permission to talk to.
*
* @param deviceCount Reference in which to return the number of accessible devices
*
* @return
* - \ref NVML_SUCCESS if \a deviceCount has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a deviceCount is NULL
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t nvmlDeviceGetCount(unsigned int *deviceCount);
/**
* Acquire the handle for a particular device, based on its index.
*
* For all products.
*
* Valid indices are derived from the \a accessibleDevices count returned by
* \ref nvmlDeviceGetCount(). For example, if \a accessibleDevices is 2 the valid indices
* are 0 and 1, corresponding to GPU 0 and GPU 1.
*
* The order in which NVML enumerates devices has no guarantees of consistency between reboots. For that reason it
* is recommended that devices be looked up by their PCI ids or UUID. See
* \ref nvmlDeviceGetHandleByUUID() and \ref nvmlDeviceGetHandleByPciBusId().
*
* Note: The NVML index may not correlate with other APIs, such as the CUDA device index.
*
* Starting from NVML 5, this API causes NVML to initialize the target GPU
* NVML may initialize additional GPUs if:
* - The target GPU is an SLI slave
*
* Note: New nvmlDeviceGetCount_v2 (default in NVML 5.319) returns count of all devices in the system
* even if nvmlDeviceGetHandleByIndex_v2 returns NVML_ERROR_NO_PERMISSION for such device.
* Update your code to handle this error, or use NVML 4.304 or older nvml header file.
* For backward binary compatibility reasons _v1 version of the API is still present in the shared
* library.
* Old _v1 version of nvmlDeviceGetCount doesn't count devices that NVML has no permission to talk to.
*
* This means that nvmlDeviceGetHandleByIndex_v2 and _v1 can return different devices for the same index.
* If you don't touch macros that map old (_v1) versions to _v2 versions at the top of the file you don't
* need to worry about that.
*
* @param index The index of the target GPU, >= 0 and < \a accessibleDevices
* @param device Reference in which to return the device handle
*
* @return
* - \ref NVML_SUCCESS if \a device has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a device is NULL
* - \ref NVML_ERROR_INSUFFICIENT_POWER if any attached devices have improperly attached external power cables
* - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to talk to this device
* - \ref NVML_ERROR_IRQ_ISSUE if NVIDIA kernel detected an interrupt issue with the attached GPUs
* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*
* @see nvmlDeviceGetIndex
* @see nvmlDeviceGetCount
*/
nvmlReturn_t nvmlDeviceGetHandleByIndex(unsigned int index, nvmlDevice_t *device);
/**
* Retrieves the current temperature readings for the device, in degrees C.
*
* For all products.
*
* See \ref nvmlTemperatureSensors_t for details on available temperature sensors.
*
* @param device The identifier of the target device
* @param sensorType Flag that indicates which sensor reading to retrieve
* @param temp Reference in which to return the temperature reading
*
* @return
* - \ref NVML_SUCCESS if \a temp has been set
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a sensorType is invalid or \a temp is NULL
* - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have the specified sensor
* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t nvmlDeviceGetTemperature(nvmlDevice_t device, nvmlTemperatureSensors_t sensorType, unsigned int *temp);
/**
* Retrieves power usage for this GPU in milliwatts and its associated circuitry (e.g. memory)
*
* For Fermi &tm; or newer fully supported devices.
*
* On Fermi and Kepler GPUs the reading is accurate to within +/- 5% of current power draw.
*
* It is only available if power management mode is supported. See \ref nvmlDeviceGetPowerManagementMode.
*
* @param device The identifier of the target device
* @param power Reference in which to return the power usage information
*
* @return
* - \ref NVML_SUCCESS if \a power has been populated
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a power is NULL
* - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support power readings
* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t nvmlDeviceGetPowerUsage(nvmlDevice_t device, unsigned int *power);
/**
* Shut down NVML by releasing all GPU resources previously allocated with \ref nvmlInit().
*
* For all products.
*
* This method should be called after NVML work is done, once for each call to \ref nvmlInit()
* A reference count of the number of initializations is maintained. Shutdown only occurs
* when the reference count reaches zero. For backwards compatibility, no error is reported if
* nvmlShutdown() is called more times than nvmlInit().
*
* @return
* - \ref NVML_SUCCESS if NVML has been properly shut down
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_UNKNOWN on any unexpected error
*/
nvmlReturn_t nvmlShutdown(void);
| 50.990741 | 134 | 0.687943 | [
"object"
] |
0bcc5879e192d28c57eb14d5e2e28fdf51fec8ab | 1,341 | h | C | three/core/geometry_group.h | Graphics-Physics-Libraries/three-cpp-works-imported | 9df305135187c5db9247a44537290e181350e26c | [
"MIT"
] | 4 | 2016-08-09T21:56:43.000Z | 2020-10-16T16:39:53.000Z | three/core/geometry_group.h | Graphics-Physics-Libraries/three-cpp-works-imported | 9df305135187c5db9247a44537290e181350e26c | [
"MIT"
] | 1 | 2017-03-25T08:41:05.000Z | 2017-03-25T08:41:05.000Z | three/core/geometry_group.h | Graphics-Physics-Libraries/three-cpp-works-imported | 9df305135187c5db9247a44537290e181350e26c | [
"MIT"
] | 1 | 2019-09-07T06:45:35.000Z | 2019-09-07T06:45:35.000Z | #ifndef THREE_GEOMETRY_GROUP_H
#define THREE_GEOMETRY_GROUP_H
#include <three/common.h>
#include <three/core/geometry_buffer.h>
#include <three/utils/memory.h>
#include <vector>
namespace three {
class GeometryGroup : public GeometryBuffer {
public:
typedef std::shared_ptr<GeometryGroup> Ptr;
static Ptr create( int materialIndex = -1, int numMorphTargets = 0, int numMorphNormals = 0 ) {
return three::make_shared<GeometryGroup>( materialIndex, numMorphTargets, numMorphNormals );
}
typedef GeometryBuffer::GLBuffer GLBuffer;
int id;
std::vector<std::vector<float>> __morphNormalsArrays;
std::vector<std::vector<float>> __morphTargetsArrays;
std::vector<int> faces3;
std::vector<int> offsets;
GLBuffer vertexColorBuffer;
GLBuffer vertexIndexBuffer;
GLBuffer vertexNormalBuffer;
GLBuffer vertexPositionBuffer;
GLBuffer vertexUvBuffer;
int vertices;
protected:
explicit GeometryGroup( int materialIndex = -1, int numMorphTargets = 0, int numMorphNormals = 0 )
: GeometryBuffer( numMorphTargets, numMorphNormals, materialIndex ),
id( -1 ),
vertexColorBuffer( 0 ),
vertexIndexBuffer( 0 ),
vertexNormalBuffer( 0 ),
vertexPositionBuffer( 0 ),
vertexUvBuffer( 0 ),
vertices( 0 ) { }
};
} // namespace three
#endif // THREE_GEOMETRY_GROUP_H | 23.526316 | 100 | 0.726324 | [
"vector"
] |
0bde9ca4834196635ee935f4fee34bf79768cc26 | 7,209 | h | C | fboss/agent/state/QcmConfig.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 834 | 2015-03-10T18:12:28.000Z | 2022-03-31T20:16:17.000Z | fboss/agent/state/QcmConfig.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 82 | 2015-04-07T08:48:29.000Z | 2022-03-11T21:56:58.000Z | fboss/agent/state/QcmConfig.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 296 | 2015-03-11T03:45:37.000Z | 2022-03-14T22:54:22.000Z | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <folly/IPAddress.h>
#include "fboss/agent/gen-cpp2/switch_config_constants.h"
#include "fboss/agent/gen-cpp2/switch_config_types.h"
#include "fboss/agent/state/NodeBase.h"
namespace facebook::fboss {
class SwitchState;
typedef boost::container::flat_map<int, int> WeightMap;
typedef std::map<int, std::set<int>> Port2QosQueueIdMap;
struct QcmCfgFields {
template <typename Fn>
void forEachChild(Fn /*fn*/) {}
folly::dynamic toFollyDynamic() const;
static QcmCfgFields fromFollyDynamic(const folly::dynamic& json);
uint32_t agingIntervalInMsecs{
cfg::switch_config_constants::DEFAULT_QCM_AGING_INTERVAL_MSECS()};
uint32_t numFlowSamplesPerView{
cfg::switch_config_constants::DEFAULT_QCM_FLOWS_PER_VIEW()};
uint32_t flowLimit{cfg::switch_config_constants::DEFAULT_QCM_FLOW_LIMIT()};
uint32_t numFlowsClear{
cfg::switch_config_constants::DEFAULT_QCM_NUM_FLOWS_TO_CLEAR()};
uint32_t scanIntervalInUsecs{
cfg::switch_config_constants::DEFAULT_QCM_SCAN_INTERVAL_USECS()};
uint32_t exportThreshold{
cfg::switch_config_constants::DEFAULT_QCM_EXPORT_THRESHOLD()};
bool monitorQcmCfgPortsOnly{false};
WeightMap flowWeights;
folly::CIDRNetwork collectorDstIp{std::make_pair(folly::IPAddress(), 0)};
folly::CIDRNetwork collectorSrcIp{std::make_pair(folly::IPAddress(), 0)};
uint32_t collectorSrcPort;
uint32_t collectorDstPort{
cfg::switch_config_constants::DEFAULT_QCM_COLLECTOR_DST_PORT()};
std::optional<uint32_t> collectorDscp{std::nullopt};
std::optional<uint32_t> ppsToQcm{std::nullopt};
std::vector<int32_t> monitorQcmPortList;
Port2QosQueueIdMap port2QosQueueIds;
};
class QcmCfg : public NodeBaseT<QcmCfg, QcmCfgFields> {
public:
static std::shared_ptr<QcmCfg> fromFollyDynamic(const folly::dynamic& json) {
const auto& fields = QcmCfgFields::fromFollyDynamic(json);
return std::make_shared<QcmCfg>(fields);
}
folly::dynamic toFollyDynamic() const override {
return getFields()->toFollyDynamic();
}
bool operator==(const QcmCfg& qcm) const {
auto origQcmMonitoredPorts{getFields()->monitorQcmPortList};
auto newQcmMonitoredPorts{qcm.getMonitorQcmPortList()};
sort(origQcmMonitoredPorts.begin(), origQcmMonitoredPorts.end());
sort(newQcmMonitoredPorts.begin(), newQcmMonitoredPorts.end());
bool qcmMonitoredPortsNotChanged =
(origQcmMonitoredPorts == newQcmMonitoredPorts);
return getFields()->agingIntervalInMsecs == qcm.getAgingInterval() &&
getFields()->numFlowSamplesPerView == qcm.getNumFlowSamplesPerView() &&
getFields()->flowLimit == qcm.getFlowLimit() &&
getFields()->numFlowsClear == qcm.getNumFlowsClear() &&
getFields()->scanIntervalInUsecs == qcm.getScanIntervalInUsecs() &&
getFields()->exportThreshold == qcm.getExportThreshold() &&
getFields()->collectorDstIp == qcm.getCollectorDstIp() &&
getFields()->collectorSrcIp == qcm.getCollectorSrcIp() &&
getFields()->collectorDstPort == qcm.getCollectorDstPort() &&
getFields()->collectorDscp == qcm.getCollectorDscp() &&
getFields()->ppsToQcm == qcm.getPpsToQcm() &&
getFields()->monitorQcmCfgPortsOnly ==
qcm.getMonitorQcmCfgPortsOnly() &&
getFields()->flowWeights == qcm.getFlowWeightMap() &&
getFields()->port2QosQueueIds == qcm.getPort2QosQueueIdMap() &&
qcmMonitoredPortsNotChanged;
}
bool operator!=(const QcmCfg& qcm) const {
return !operator==(qcm);
}
uint32_t getAgingInterval() const {
return getFields()->agingIntervalInMsecs;
}
void setAgingInterval(uint32_t agingInterval) {
writableFields()->agingIntervalInMsecs = agingInterval;
}
void setNumFlowSamplesPerView(uint32_t numFlowSamplesPerView) {
writableFields()->numFlowSamplesPerView = numFlowSamplesPerView;
}
uint32_t getNumFlowSamplesPerView() const {
return getFields()->numFlowSamplesPerView;
}
void setFlowLimit(uint32_t flowLimit) {
writableFields()->flowLimit = flowLimit;
}
uint32_t getFlowLimit() const {
return getFields()->flowLimit;
}
void setNumFlowsClear(uint32_t numFlowsClear) {
writableFields()->numFlowsClear = numFlowsClear;
}
uint32_t getNumFlowsClear() const {
return getFields()->numFlowsClear;
}
void setScanIntervalInUsecs(uint32_t scanInterval) {
writableFields()->scanIntervalInUsecs = scanInterval;
}
uint32_t getScanIntervalInUsecs() const {
return getFields()->scanIntervalInUsecs;
}
void setExportThreshold(uint32_t exportThreshold) {
writableFields()->exportThreshold = exportThreshold;
}
uint32_t getExportThreshold() const {
return getFields()->exportThreshold;
}
WeightMap getFlowWeightMap() const {
return getFields()->flowWeights;
}
void setFlowWeightMap(WeightMap map) {
writableFields()->flowWeights = map;
}
Port2QosQueueIdMap getPort2QosQueueIdMap() const {
return getFields()->port2QosQueueIds;
}
void setPort2QosQueueIdMap(Port2QosQueueIdMap& map) {
writableFields()->port2QosQueueIds = map;
}
folly::CIDRNetwork getCollectorDstIp() const {
return getFields()->collectorDstIp;
}
void setCollectorDstIp(const folly::CIDRNetwork& ip) {
writableFields()->collectorDstIp = ip;
}
folly::CIDRNetwork getCollectorSrcIp() const {
return getFields()->collectorSrcIp;
}
void setCollectorSrcIp(const folly::CIDRNetwork& ip) {
writableFields()->collectorSrcIp = ip;
}
uint32_t getCollectorSrcPort() const {
return getFields()->collectorSrcPort;
}
void setCollectorSrcPort(const uint32_t srcPort) {
writableFields()->collectorSrcPort = srcPort;
}
void setCollectorDstPort(const uint32_t dstPort) {
writableFields()->collectorDstPort = dstPort;
}
uint32_t getCollectorDstPort() const {
return getFields()->collectorDstPort;
}
std::optional<uint32_t> getCollectorDscp() const {
return getFields()->collectorDscp;
}
void setCollectorDscp(const uint32_t dscp) {
writableFields()->collectorDscp = dscp;
}
std::optional<uint32_t> getPpsToQcm() const {
return getFields()->ppsToQcm;
}
void setPpsToQcm(const uint32_t ppsToQcm) {
writableFields()->ppsToQcm = ppsToQcm;
}
const std::vector<int32_t>& getMonitorQcmPortList() const {
return getFields()->monitorQcmPortList;
}
void setMonitorQcmPortList(const std::vector<int32_t>& qcmPortList) {
writableFields()->monitorQcmPortList = qcmPortList;
}
bool getMonitorQcmCfgPortsOnly() const {
return getFields()->monitorQcmCfgPortsOnly;
}
void setMonitorQcmCfgPortsOnly(bool monitorQcmPortsOnly) {
writableFields()->monitorQcmCfgPortsOnly = monitorQcmPortsOnly;
}
private:
// Inherit the constructors required for clone()
using NodeBaseT::NodeBaseT;
friend class CloneAllocator;
};
} // namespace facebook::fboss
| 31.480349 | 79 | 0.732834 | [
"vector"
] |
0bf7f50df1e43dda7f21ca545903ccb3196633dc | 9,099 | c | C | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/hrmesp_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 6 | 2022-01-21T19:58:08.000Z | 2022-03-28T12:32:24.000Z | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/hrmesp_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | null | null | null | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/hrmesp_c.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 4 | 2022-02-12T10:01:40.000Z | 2022-03-28T14:28:52.000Z | /*
-Procedure hrmesp_c ( Hermite polynomial interpolation, equal spacing )
-Abstract
Evaluate, at a specified point, a Hermite interpolating polynomial
for a specified set of equally spaced abscissa values and
corresponding pairs of function and function derivative values.
-Disclaimer
THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
-Required_Reading
None.
-Keywords
INTERPOLATION
POLYNOMIAL
*/
#include <stddef.h>
#include "SpiceUsr.h"
#include "SpiceZfc.h"
#include "zzalloc.h"
void hrmesp_c ( SpiceInt n,
SpiceDouble first,
SpiceDouble step,
ConstSpiceDouble yvals [],
SpiceDouble x,
SpiceDouble * f,
SpiceDouble * df )
/*
-Brief_I/O
VARIABLE I/O DESCRIPTION
-------- --- --------------------------------------------------
n I Number of points defining the polynomial.
first I First abscissa value.
step I Step size.
yvals I Ordinate and derivative values.
x I Point at which to interpolate the polynomial.
f O Interpolated function value at `x'.
df O Interpolated function's derivative at `x'.
-Detailed_Input
n is the number of points defining the polynomial.
The array `yvals' contains 2*n elements.
first,
step are, respectively, a starting abscissa value and a
step size that define the set of abscissa values
first + i * step, i = 0, ..., n-1
`step' must be non-zero.
yvals is an array of length 2*n containing ordinate and
derivative values for each point in the domain
defined by `first', `step', and `n'. The elements
yvals[ 2*i ]
yvals[ 2*i + 1 ]
give the value and first derivative of the output
polynomial at the abscissa value
first + i * step
where `i' ranges from 0 to n-1.
x is the abscissa value at which the interpolating
polynomial and its derivative are to be evaluated.
-Detailed_Output
f,
df are the value and derivative at `x' of the unique
polynomial of degree 2*n-1 that fits the points and
derivatives defined by `first', `step', and `yvals'.
-Parameters
None.
-Exceptions
1) If `step' is zero, the error SPICE(INVALIDSTEPSIZE) is
signaled by a routine in the call tree of this routine.
2) If `n' is less than 1, the error SPICE(INVALIDSIZE) is
signaled.
3) This routine does not attempt to ward off or diagnose
arithmetic overflows.
4) If memory cannot be allocated to create the temporary variable
required for the execution of the underlying Fortran routine,
the error SPICE(MALLOCFAILED) is signaled.
-Files
None.
-Particulars
Users of this routine must choose the number of points to use
in their interpolation method. The authors of Reference [1] have
this to say on the topic:
Unless there is solid evidence that the interpolating function
is close in form to the true function f, it is a good idea to
be cautious about high-order interpolation. We
enthusiastically endorse interpolations with 3 or 4 points, we
are perhaps tolerant of 5 or 6; but we rarely go higher than
that unless there is quite rigorous monitoring of estimated
errors.
The same authors offer this warning on the use of the
interpolating function for extrapolation:
...the dangers of extrapolation cannot be overemphasized:
An interpolating function, which is perforce an extrapolating
function, will typically go berserk when the argument x is
outside the range of tabulated values by more than the typical
spacing of tabulated points.
-Examples
The numerical results shown for this example may differ across
platforms. The results depend on the SPICE kernels used as
input, the compiler and supporting libraries, and the machine
specific arithmetic implementation.
1) Fit a 7th degree polynomial through the points ( x, y, y' )
( -1, 6, 3 )
( 1, 8, 11 )
( 3, 2210, 5115 )
( 5, 78180, 109395 )
and evaluate this polynomial at x = 2.
The returned value of ANSWER should be 141.0, and the
returned derivative value should be 456.0, since the unique
7th degree polynomial that fits these constraints is
7 2
f(x) = x + 2x + 5
Example code begins here.
/.
Program hrmesp_ex1
./
#include <stdio.h>
#include "SpiceUsr.h"
int main( )
{
SpiceDouble answer;
SpiceDouble deriv;
SpiceDouble first;
SpiceDouble step;
SpiceDouble yvals [8];
SpiceInt n;
n = 4;
yvals[0] = 6.0;
yvals[1] = 3.0;
yvals[2] = 8.0;
yvals[3] = 11.0;
yvals[4] = 2210.0;
yvals[5] = 5115.0;
yvals[6] = 78180.0;
yvals[7] = 109395.0;
first = -1.0;
step = 2.0;
hrmesp_c ( n, first, step, yvals, 2.0, &answer, &deriv );
printf( "ANSWER = %f\n", answer );
printf( "DERIV = %f\n", deriv );
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, the output was:
ANSWER = 141.000000
DERIV = 456.000000
-Restrictions
None.
-Literature_References
[1] W. Press, B. Flannery, S. Teukolsky and W. Vetterling,
"Numerical Recipes -- The Art of Scientific Computing,"
chapters 3.0 and 3.1, Cambridge University Press, 1986.
[2] S. Conte and C. de Boor, "Elementary Numerical Analysis -- An
Algorithmic Approach," 3rd Edition, p 64, McGraw-Hill, 1980.
-Author_and_Institution
J. Diaz del Rio (ODC Space)
-Version
-CSPICE Version 1.0.0, 03-AUG-2021 (JDR)
-Index_Entries
interpolate function using Hermite polynomial
Hermite interpolation
-&
*/
{ /* Begin hrmesp_c */
/*
Local variables.
*/
SpiceInt nBytesWork;
doublereal * work;
/*
Participate in error tracing.
*/
chkin_c ( "hrmesp_c" );
/*
No data, no interpolation.
*/
if ( n < 1 )
{
setmsg_c ( "Array size must be positive; was #." );
errint_c ( "#", n );
sigerr_c ( "SPICE(INVALIDSIZE)" );
chkout_c ( "hrmesp_c" );
return;
}
/*
Allocate the workspace.
*/
nBytesWork = 4 * n * sizeof(SpiceDouble);
work = (doublereal *) alloc_SpiceMemory( (size_t)nBytesWork );
if ( work == NULL )
{
setmsg_c ( "Workspace allocation of # bytes failed due to "
"malloc failure." );
errint_c ( "#", nBytesWork );
sigerr_c ( "SPICE(MALLOCFAILED)" );
chkout_c ( "hrmesp_c" );
return;
}
/*
Call the f2c'd Fortran routine.
*/
hrmesp_ ( ( integer * ) &n,
( doublereal * ) &first,
( doublereal * ) &step,
( doublereal * ) yvals,
( doublereal * ) &x,
( doublereal * ) work,
( doublereal * ) f,
( doublereal * ) df );
/*
De-allocate the workspace.
*/
free_SpiceMemory( work );
ALLOC_CHECK;
chkout_c ( "hrmesp_c" );
} /* End hrmesp_c */
| 28.083333 | 71 | 0.590724 | [
"solid"
] |
0bfb7b8b5d1f7277616f78ec20ef013044a1375d | 648 | h | C | practicas/esfera.h | OswaldoHernandezEscobar/Proyecto__CGIH01 | 9d3c7a725d9afb90866e0ef12cb874baae7acc3c | [
"CC0-1.0"
] | null | null | null | practicas/esfera.h | OswaldoHernandezEscobar/Proyecto__CGIH01 | 9d3c7a725d9afb90866e0ef12cb874baae7acc3c | [
"CC0-1.0"
] | null | null | null | practicas/esfera.h | OswaldoHernandezEscobar/Proyecto__CGIH01 | 9d3c7a725d9afb90866e0ef12cb874baae7acc3c | [
"CC0-1.0"
] | null | null | null | #pragma once
#ifndef ESFERA_H_
#define ESFERA_H_
#include <glew.h>
#include <glfw3.h>
#include <stb_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <shader_m.h>
#include <iostream>
#define M_PI 3.14159265358979323846264338327950288
#define MERIDIANOS 16
#define PARALELOS 8
class Esfera
{
public:
Esfera(GLfloat radio);
void init();
//void load();
void render();
virtual ~Esfera();
private:
float radio;
GLuint esfera_VAO[4], esfera_VBO[4], esfera_index[MERIDIANOS*(PARALELOS - 1) * 6];
GLfloat esfera_pos[PARALELOS * MERIDIANOS * 3];
};
#endif // !ESFERA_H_ | 18.514286 | 84 | 0.722222 | [
"render"
] |
0bfda0712e2453bccbc6f8db3d459507c7f2bdff | 2,766 | h | C | src/common/Honey/Math/NumAnalysis/MinimizeN.h | Qarterd/Honeycomb | 9b7066529444cdd85d3e3467b02b72eea651853d | [
"CC0-1.0"
] | 33 | 2015-05-08T00:11:01.000Z | 2022-03-04T08:25:06.000Z | src/common/Honey/Math/NumAnalysis/MinimizeN.h | Qarterd/Honeycomb | 9b7066529444cdd85d3e3467b02b72eea651853d | [
"CC0-1.0"
] | null | null | null | src/common/Honey/Math/NumAnalysis/MinimizeN.h | Qarterd/Honeycomb | 9b7066529444cdd85d3e3467b02b72eea651853d | [
"CC0-1.0"
] | 6 | 2015-08-08T13:47:14.000Z | 2021-04-06T02:29:41.000Z | // Honeycomb, Copyright (C) 2015 NewGamePlus Inc. Distributed under the Boost Software License v1.0.
#pragma once
#include "Honey/Math/NumAnalysis/Minimize.h"
#include "Honey/Math/Alge/Vec/Vec4.h"
namespace honey
{
/// Find a local minimum of an n-dimensional function using "Powell's conjugate gradient descent method"
template<class Real, int Dim>
class MinimizeN
{
typedef typename Numeral<Real>::Real_ Real_;
typedef Alge_<Real> Alge;
public:
typedef Vec<Dim, Real> Vec;
typedef function<Real (Vec)> Func;
static const int dim = Dim;
/**
* \param tol find minimum to within tolerance
* \param iterMax max number of iterations for gradient descent method
* \param levelMax see Minimize
* \param bracketMax see Minimize
*/
MinimizeN(Real tol = Real_::zeroTol, int iterMax = 30, int levelMax = 30, int bracketMax = 30)
: _tol(tol), _iterMax(iterMax), _minimize(tol, levelMax, bracketMax) {}
/// Find the minimum of a function within bounds [min,max] using `init` as an initial guess
/**
* The algorithm starts at point `init` and searches for a minimum along each coordinate axis using the Minimize class.
* A "conjugate" vector is then created by adding the deltas along each axis.
* A new starting point is then found by taking the minimum along the conjugate vector.
* The most successful axis is then replaced with the conjugate to minimize linear dependency.
* The direction set is cycled and the algorithm repeats to `iterMax`.
*
* \param func
* \param min minimum lower bound
* \param max minimum upper bound
* \param init initial guess of minimum
* \retval argMin the function arg that results in the minimum
* \retval valMin the minimum
*/
tuple<Vec,Real> calc(const Func& func, const Vec& min, const Vec& max, const Vec& init);
private:
// Algorithm is adapted from the Wild Magic lib
/// Clips line `v + t*dir` against the Cartesian product domain `[min, max]`
/**
* \param v line point
* \param dir line direction
* \param min range lower bound
* \param max range upper bound
* \retval tuple the clipped t-interval
*/
static tuple<Real, Real> calcDomain(const Vec& v, const Vec& dir, const Vec& min, const Vec& max);
Real _tol;
int _iterMax;
Minimize<Real> _minimize;
};
extern template class MinimizeN<Float, 2>;
extern template class MinimizeN<Float, 3>;
extern template class MinimizeN<Double, 2>;
extern template class MinimizeN<Double, 3>;
}
| 37.378378 | 125 | 0.643529 | [
"vector"
] |
0bfe900441130e0dcb3cd58634798895c6b2290f | 579 | h | C | React3D/Core/src/Material.h | ankitpriyarup/React3D | a5874f3e600bef27c9ed7a346ed2ca0440dee5a5 | [
"MIT"
] | null | null | null | React3D/Core/src/Material.h | ankitpriyarup/React3D | a5874f3e600bef27c9ed7a346ed2ca0440dee5a5 | [
"MIT"
] | null | null | null | React3D/Core/src/Material.h | ankitpriyarup/React3D | a5874f3e600bef27c9ed7a346ed2ca0440dee5a5 | [
"MIT"
] | 1 | 2022-03-22T11:41:13.000Z | 2022-03-22T11:41:13.000Z | #pragma once
#include <iostream>
#include <fstream>
#include <regex>
#include <iterator>
#include <string.h>
#include <map>
#include "Texture.h"
#include "Uniform.h"
class Material
{
private:
std::string srcShader;
public:
std::vector<Texture*> textures;
std::unordered_map<std::string, Uniform*> defaultUniforms;
bool containsViewUniform = false;
Material(std::string _srcShader);
Material(std::string _srcShader, std::string _srcTex);
void assignAlbedo(std::string _srcTex);
void assignNormalMap(std::string _srcTex);
~Material();
std::string getShader() const;
}; | 21.444444 | 59 | 0.744387 | [
"vector"
] |
04055cd49790e0fd084683bfec57a4cc346d775e | 12,411 | c | C | engine/code/bspc/aas_areamerging.c | arbaazkhan2/act_unreal | 4f10e647bdb5dad36bec6a57d25a504d051e4817 | [
"CC-BY-4.0"
] | 7,407 | 2016-12-06T08:40:58.000Z | 2022-03-31T12:19:09.000Z | engine/code/bspc/aas_areamerging.c | arbaazkhan2/act_unreal | 4f10e647bdb5dad36bec6a57d25a504d051e4817 | [
"CC-BY-4.0"
] | 227 | 2016-12-06T22:05:33.000Z | 2022-03-29T09:47:06.000Z | engine/code/bspc/aas_areamerging.c | arbaazkhan2/act_unreal | 4f10e647bdb5dad36bec6a57d25a504d051e4817 | [
"CC-BY-4.0"
] | 1,594 | 2016-12-06T08:44:13.000Z | 2022-03-31T12:19:12.000Z | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Quake III Arena source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "qbsp.h"
#include "botlib/aasfile.h"
#include "aas_create.h"
#include "aas_store.h"
#define CONVEX_EPSILON 0.3
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
tmp_node_t *AAS_RefreshMergedTree_r(tmp_node_t *tmpnode)
{
tmp_area_t *tmparea;
//if this is a solid leaf
if (!tmpnode) return NULL;
//if this is an area leaf
if (tmpnode->tmparea)
{
tmparea = tmpnode->tmparea;
while(tmparea->mergedarea) tmparea = tmparea->mergedarea;
tmpnode->tmparea = tmparea;
return tmpnode;
} //end if
//do the children recursively
tmpnode->children[0] = AAS_RefreshMergedTree_r(tmpnode->children[0]);
tmpnode->children[1] = AAS_RefreshMergedTree_r(tmpnode->children[1]);
return tmpnode;
} //end of the function AAS_RefreshMergedTree_r
//===========================================================================
// returns true if the two given faces would create a non-convex area at
// the given sides, otherwise false is returned
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int NonConvex(tmp_face_t *face1, tmp_face_t *face2, int side1, int side2)
{
int i;
winding_t *w1, *w2;
plane_t *plane1, *plane2;
w1 = face1->winding;
w2 = face2->winding;
plane1 = &mapplanes[face1->planenum ^ side1];
plane2 = &mapplanes[face2->planenum ^ side2];
//check if one of the points of face1 is at the back of the plane of face2
for (i = 0; i < w1->numpoints; i++)
{
if (DotProduct(plane2->normal, w1->p[i]) - plane2->dist < -CONVEX_EPSILON) return true;
} //end for
//check if one of the points of face2 is at the back of the plane of face1
for (i = 0; i < w2->numpoints; i++)
{
if (DotProduct(plane1->normal, w2->p[i]) - plane1->dist < -CONVEX_EPSILON) return true;
} //end for
return false;
} //end of the function NonConvex
//===========================================================================
// try to merge the areas at both sides of the given face
//
// Parameter: seperatingface : face that seperates two areas
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_TryMergeFaceAreas(tmp_face_t *seperatingface)
{
int side1, side2, area1faceflags, area2faceflags;
tmp_area_t *tmparea1, *tmparea2, *newarea;
tmp_face_t *face1, *face2, *nextface1, *nextface2;
tmparea1 = seperatingface->frontarea;
tmparea2 = seperatingface->backarea;
//areas must have the same presence type
if (tmparea1->presencetype != tmparea2->presencetype) return false;
//areas must have the same area contents
if (tmparea1->contents != tmparea2->contents) return false;
//areas must have the same bsp model inside (or both none)
if (tmparea1->modelnum != tmparea2->modelnum) return false;
area1faceflags = 0;
area2faceflags = 0;
for (face1 = tmparea1->tmpfaces; face1; face1 = face1->next[side1])
{
side1 = (face1->frontarea != tmparea1);
//debug: check if the area belongs to the area
if (face1->frontarea != tmparea1 &&
face1->backarea != tmparea1) Error("face does not belong to area1");
//just continue if the face is seperating the two areas
//NOTE: a result of this is that ground and gap areas can
// be merged if the seperating face is the gap
if ((face1->frontarea == tmparea1 &&
face1->backarea == tmparea2) ||
(face1->frontarea == tmparea2 &&
face1->backarea == tmparea1)) continue;
//get area1 face flags
area1faceflags |= face1->faceflags;
if (AAS_GapFace(face1, side1)) area1faceflags |= FACE_GAP;
//
for (face2 = tmparea2->tmpfaces; face2; face2 = face2->next[side2])
{
side2 = (face2->frontarea != tmparea2);
//debug: check if the area belongs to the area
if (face2->frontarea != tmparea2 &&
face2->backarea != tmparea2) Error("face does not belong to area2");
//just continue if the face is seperating the two areas
//NOTE: a result of this is that ground and gap areas can
// be merged if the seperating face is the gap
if ((face2->frontarea == tmparea1 &&
face2->backarea == tmparea2) ||
(face2->frontarea == tmparea2 &&
face2->backarea == tmparea1)) continue;
//get area2 face flags
area2faceflags |= face2->faceflags;
if (AAS_GapFace(face2, side2)) area2faceflags |= FACE_GAP;
//if the two faces would create a non-convex area
if (NonConvex(face1, face2, side1, side2)) return false;
} //end for
} //end for
//if one area has gap faces (that aren't seperating the two areas)
//and the other has ground faces (that aren't seperating the two areas),
//the areas can't be merged
if (((area1faceflags & FACE_GROUND) && (area2faceflags & FACE_GAP)) ||
((area2faceflags & FACE_GROUND) && (area1faceflags & FACE_GAP)))
{
// Log_Print(" can't merge: ground/gap\n");
return false;
} //end if
// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum, numfaces);
// return false;
//
//AAS_CheckArea(tmparea1);
//AAS_CheckArea(tmparea2);
//create the new area
newarea = AAS_AllocTmpArea();
newarea->presencetype = tmparea1->presencetype;
newarea->contents = tmparea1->contents;
newarea->modelnum = tmparea1->modelnum;
newarea->tmpfaces = NULL;
//add all the faces (except the seperating ones) from the first area
//to the new area
for (face1 = tmparea1->tmpfaces; face1; face1 = nextface1)
{
side1 = (face1->frontarea != tmparea1);
nextface1 = face1->next[side1];
//don't add seperating faces
if ((face1->frontarea == tmparea1 &&
face1->backarea == tmparea2) ||
(face1->frontarea == tmparea2 &&
face1->backarea == tmparea1))
{
continue;
} //end if
//
AAS_RemoveFaceFromArea(face1, tmparea1);
AAS_AddFaceSideToArea(face1, side1, newarea);
} //end for
//add all the faces (except the seperating ones) from the second area
//to the new area
for (face2 = tmparea2->tmpfaces; face2; face2 = nextface2)
{
side2 = (face2->frontarea != tmparea2);
nextface2 = face2->next[side2];
//don't add seperating faces
if ((face2->frontarea == tmparea1 &&
face2->backarea == tmparea2) ||
(face2->frontarea == tmparea2 &&
face2->backarea == tmparea1))
{
continue;
} //end if
//
AAS_RemoveFaceFromArea(face2, tmparea2);
AAS_AddFaceSideToArea(face2, side2, newarea);
} //end for
//free all shared faces
for (face1 = tmparea1->tmpfaces; face1; face1 = nextface1)
{
side1 = (face1->frontarea != tmparea1);
nextface1 = face1->next[side1];
//
AAS_RemoveFaceFromArea(face1, face1->frontarea);
AAS_RemoveFaceFromArea(face1, face1->backarea);
AAS_FreeTmpFace(face1);
} //end for
//
tmparea1->mergedarea = newarea;
tmparea1->invalid = true;
tmparea2->mergedarea = newarea;
tmparea2->invalid = true;
//
AAS_CheckArea(newarea);
AAS_FlipAreaFaces(newarea);
// Log_Print("merged area %d & %d to %d with %d faces\n", tmparea1->areanum, tmparea2->areanum, newarea->areanum);
return true;
} //end of the function AAS_TryMergeFaceAreas
//===========================================================================
// try to merge areas
// merged areas are added to the end of the convex area list so merging
// will be tried for those areas as well
//
// Parameter: -
// Returns: -
// Changes Globals: tmpaasworld
//===========================================================================
/*
void AAS_MergeAreas(void)
{
int side, nummerges;
tmp_area_t *tmparea, *othertmparea;
tmp_face_t *face;
nummerges = 0;
Log_Write("AAS_MergeAreas\r\n");
qprintf("%6d areas merged", 1);
//first merge grounded areas only
//NOTE: this is useless because the area settings aren't available yet
for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
{
// Log_Print("checking area %d\n", i);
//if the area is invalid
if (tmparea->invalid)
{
// Log_Print(" area invalid\n");
continue;
} //end if
//
// if (!(tmparea->settings->areaflags & AREA_GROUNDED)) continue;
//
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
//if the face has both a front and back area
if (face->frontarea && face->backarea)
{
//
if (face->frontarea == tmparea) othertmparea = face->backarea;
else othertmparea = face->frontarea;
// if (!(othertmparea->settings->areaflags & AREA_GROUNDED)) continue;
// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
if (AAS_TryMergeFaceAreas(face))
{
qprintf("\r%6d", ++nummerges);
break;
} //end if
} //end if
} //end for
} //end for
//merge all areas
for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
{
// Log_Print("checking area %d\n", i);
//if the area is invalid
if (tmparea->invalid)
{
// Log_Print(" area invalid\n");
continue;
} //end if
//
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
//if the face has both a front and back area
if (face->frontarea && face->backarea)
{
// Log_Print(" checking area %d with %d\n", face->frontarea, face->backarea);
if (AAS_TryMergeFaceAreas(face))
{
qprintf("\r%6d", ++nummerges);
break;
} //end if
} //end if
} //end for
} //end for
Log_Print("\r%6d areas merged\n", nummerges);
//refresh the merged tree
AAS_RefreshMergedTree_r(tmpaasworld.nodes);
} //end of the function AAS_MergeAreas*/
int AAS_GroundArea(tmp_area_t *tmparea)
{
tmp_face_t *face;
int side;
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
if (face->faceflags & FACE_GROUND) return true;
} //end for
return false;
} //end of the function AAS_GroundArea
void AAS_MergeAreas(void)
{
int side, nummerges, merges, groundfirst;
tmp_area_t *tmparea, *othertmparea;
tmp_face_t *face;
nummerges = 0;
Log_Write("AAS_MergeAreas\r\n");
qprintf("%6d areas merged", 1);
//
groundfirst = true;
//for (i = 0; i < 4 || merges; i++)
while(1)
{
//if (i < 2) groundfirst = true;
//else groundfirst = false;
//
merges = 0;
//first merge grounded areas only
for (tmparea = tmpaasworld.areas; tmparea; tmparea = tmparea->l_next)
{
//if the area is invalid
if (tmparea->invalid)
{
continue;
} //end if
//
if (groundfirst)
{
if (!AAS_GroundArea(tmparea)) continue;
} //end if
//
for (face = tmparea->tmpfaces; face; face = face->next[side])
{
side = (face->frontarea != tmparea);
//if the face has both a front and back area
if (face->frontarea && face->backarea)
{
//
if (face->frontarea == tmparea) othertmparea = face->backarea;
else othertmparea = face->frontarea;
//
if (groundfirst)
{
if (!AAS_GroundArea(othertmparea)) continue;
} //end if
if (AAS_TryMergeFaceAreas(face))
{
qprintf("\r%6d", ++nummerges);
merges++;
break;
} //end if
} //end if
} //end for
} //end for
if (!merges)
{
if (groundfirst) groundfirst = false;
else break;
} //end if
} //end for
qprintf("\n");
Log_Write("%6d areas merged\r\n", nummerges);
//refresh the merged tree
AAS_RefreshMergedTree_r(tmpaasworld.nodes);
} //end of the function AAS_MergeAreas
| 31.741688 | 124 | 0.633309 | [
"model",
"solid"
] |
040a5e18a47e4705145ef535693d78a33487a338 | 432 | h | C | src/component/TextureCube.h | baislsl/CG-project | 66a56c337d9b8163e61e3e7d827004e573f3a321 | [
"MIT"
] | 1 | 2021-01-12T02:56:10.000Z | 2021-01-12T02:56:10.000Z | src/component/TextureCube.h | baislsl/CG-project | 66a56c337d9b8163e61e3e7d827004e573f3a321 | [
"MIT"
] | null | null | null | src/component/TextureCube.h | baislsl/CG-project | 66a56c337d9b8163e61e3e7d827004e573f3a321 | [
"MIT"
] | null | null | null | #ifndef CGPROJECT_TEXTURECUBE_H
#define CGPROJECT_TEXTURECUBE_H
#include "BaseShape.h"
class TextureCube : public BaseShape
{
public:
TextureCube(GLint top, GLuint bottom, GLuint left, GLuint right, GLuint front, GLuint back);
void render(const Shader &shader, const Camera &camera) override;
virtual ~TextureCube() = default;
protected:
GLuint top, bottom, left, right, front, back;
};
#endif //CGPROJECT_TEXTURECUBE_H
| 19.636364 | 93 | 0.768519 | [
"render"
] |
041183707f46330672e4a0dce1479631482929a6 | 2,162 | h | C | include/pr/common/observe.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 2 | 2020-11-11T16:19:04.000Z | 2021-01-19T01:53:29.000Z | include/pr/common/observe.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2020-07-27T09:00:21.000Z | 2020-07-27T10:58:10.000Z | include/pr/common/observe.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2021-04-04T01:39:55.000Z | 2021-04-04T01:39:55.000Z | //***********************************************************************************************
//
//***********************************************************************************************
// Usage:
// 1) Inherit Observee / Observer
// 2) Register the Observer with the Observee by passing an SObserver struct. e.g. SObserver(this, some_data)
// 3) The Observee calls NotifyObservers with the observer data (some_data) and data relevant to the notify (something's happen)
#pragma once
#ifndef PR_COMMON_OBSERVE_H
#define PR_COMMON_OBSERVE_H
#include <vector>
#include <algorithm>
#include "pr/common/assert.h"
namespace pr
{
struct IObserver
{
virtual void OnNotification(void* event_data, void* user_data) = 0;
};
namespace impl
{
struct ObserverData
{
IObserver* m_observer;
void* m_user_data;
static ObserverData make(IObserver* observer, void* user_data)
{
ObserverData obs;
obs.m_observer = observer;
obs.m_user_data = user_data;
return obs;
}
};
inline bool operator == (const ObserverData& lhs, const ObserverData& rhs) { return lhs.m_observer == rhs.m_observer; }
}
struct Observee
{
typedef std::vector<impl::ObserverData> TObserverContainer;
TObserverContainer m_observer; // Those watching us
// Register an observer
void RegisterObserver(IObserver* observer, void* user_data)
{
auto obs = impl::ObserverData::make(observer, user_data);
auto iter = std::find(begin(m_observer), end(m_observer), obs);
if (iter != m_observer.end()) iter->m_user_data = user_data;
else m_observer.push_back(obs);
}
// Unregister someone as an observer
void UnRegisterObserver(IObserver* observer)
{
auto obs = impl::ObserverData::make(observer, 0);
auto iter = std::find(begin(m_observer), end(m_observer), obs);
if (iter != end(m_observer)) m_observer.erase(iter);
}
// Send a message to observers
void NotifyObservers(void* event_data)
{
for (auto obs : m_observer)
obs.m_observer->OnNotification(event_data, obs.m_user_data);
}
};
}
#endif
| 29.616438 | 129 | 0.617484 | [
"vector"
] |
0415b7b6b84dedbbbfd7cf874c9874f5ad799127 | 351 | h | C | src/Tracker/trackers/custom_none.h | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | src/Tracker/trackers/custom_none.h | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | src/Tracker/trackers/custom_none.h | grzegorzmatczak/PostProcessingModules | bc815541453453f58fc40bd9c00bfc03be1fa3b5 | [
"MIT"
] | null | null | null | #ifndef TRACKERS_CUSTOM_NONE_H
#define TRACKERS_CUSTOM_NONE_H
#include "basetracker.h"
class QJsonObject;
namespace Trackers {
class None : public BaseTracker {
public:
None();
void process(std::vector<_postData> &_data);
void endProcess(std::vector<_postData> &_data);
private:
};
} // namespace Trackers
#endif // TRACKERS_CUSTOM_NONE_H
| 16.714286 | 49 | 0.757835 | [
"vector"
] |
0420a63278d68b2a6eafa9a0595ad84cb23c73e4 | 992 | h | C | source/agent/addons/audioRanker/AudioRankerWrapper.h | andreasunterhuber/owt-server | 128b83714361c0b543ec44fc841c9094f4267633 | [
"Apache-2.0"
] | 890 | 2019-03-08T08:04:10.000Z | 2022-03-30T03:07:44.000Z | source/agent/addons/audioRanker/AudioRankerWrapper.h | vgemv/owt-server | fa6070af33feeeb79a962de08307ac5092991cbf | [
"Apache-2.0"
] | 583 | 2019-03-11T10:27:42.000Z | 2022-03-29T01:41:28.000Z | source/agent/addons/audioRanker/AudioRankerWrapper.h | vgemv/owt-server | fa6070af33feeeb79a962de08307ac5092991cbf | [
"Apache-2.0"
] | 385 | 2019-03-08T07:50:13.000Z | 2022-03-29T06:36:28.000Z | // Copyright (C) <2019> Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
#ifndef AUDIORANKERWRAPPER_H
#define AUDIORANKERWRAPPER_H
#include <AudioRanker.h>
#include <nan.h>
/*
* Wrapper class of owt_base::AudioRanker
*/
class AudioRanker : public Nan::ObjectWrap,
public owt_base::AudioRanker::Visitor {
public:
static NAN_MODULE_INIT(Init);
owt_base::AudioRanker* me;
boost::mutex mutex;
std::queue<std::string> jsonChanges;
void onRankChange(
std::vector<std::pair<std::string, std::string>> updates) override;
private:
AudioRanker();
~AudioRanker();
Nan::Callback *callback_;
uv_async_t async_;
Nan::AsyncResource *asyncResource_;
static Nan::Persistent<v8::Function> constructor;
static NAN_METHOD(New);
static NAN_METHOD(close);
static NAN_METHOD(addOutput);
static NAN_METHOD(addInput);
static NAN_METHOD(removeInput);
static NAUV_WORK_CB(Callback);
};
#endif
| 19.076923 | 75 | 0.688508 | [
"vector"
] |
04278d7ce9f709080512e865af7fbc53aa657517 | 1,059 | h | C | Telegram-2.8/Telegraph/Telegraph/TGModernGalleryController.h | DZamataev/TelegramAppKit | 479db564f5c202e8af848dac39ec7f6fdd928dff | [
"MIT"
] | null | null | null | Telegram-2.8/Telegraph/Telegraph/TGModernGalleryController.h | DZamataev/TelegramAppKit | 479db564f5c202e8af848dac39ec7f6fdd928dff | [
"MIT"
] | null | null | null | Telegram-2.8/Telegraph/Telegraph/TGModernGalleryController.h | DZamataev/TelegramAppKit | 479db564f5c202e8af848dac39ec7f6fdd928dff | [
"MIT"
] | null | null | null | /*
* This is the source code of Telegram for iOS v. 1.1
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Peter Iakovlev, 2013.
*/
#import "TGOverlayController.h"
@class TGModernGalleryModel;
@protocol TGModernGalleryItem;
@class TGModernGalleryItemView;
@interface TGModernGalleryController : TGOverlayController
@property (nonatomic, strong) TGModernGalleryModel *model;
@property (nonatomic) bool animateTransition;
@property (nonatomic) bool showInterface;
@property (nonatomic, copy) void (^itemFocused)(id<TGModernGalleryItem>);
@property (nonatomic, copy) UIView *(^beginTransitionIn)(id<TGModernGalleryItem>, TGModernGalleryItemView *);
@property (nonatomic, copy) void (^finishedTransitionIn)(id<TGModernGalleryItem>, TGModernGalleryItemView *);
@property (nonatomic, copy) UIView *(^beginTransitionOut)(id<TGModernGalleryItem>);
@property (nonatomic, copy) void (^completedTransitionOut)();
- (void)dismissWhenReady;
- (bool)isFullyOpaque;
@end
| 33.09375 | 109 | 0.777148 | [
"model"
] |
042dcca65793f880a950b5f38b14255d9189e4de | 1,694 | h | C | Code/Framework/AzCore/AzCore/std/math.h | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Framework/AzCore/AzCore/std/math.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Framework/AzCore/AzCore/std/math.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <cmath>
namespace AZStd
{
using std::abs;
using std::acos;
using std::asin;
using std::atan;
using std::atan2;
using std::ceil;
using std::cos;
using std::exp2;
using std::floor;
using std::fmod;
using std::llround;
using std::lround;
using std::pow;
using std::round;
using std::sin;
using std::sqrt;
using std::tan;
using std::trunc;
} // namespace AZStd
// from c++20 standard
namespace AZStd::Internal
{
template<typename T>
constexpr T lerp(T a, T b, T t) noexcept
{
if ((a <= 0 && b >= 0) || (a >= 0 && b <= 0))
{
return t * b + (1 - t) * a;
}
if (t == 1)
{
return b;
}
const T x = a + t * (b - a);
if ((t > 1) == (b > a))
{
return b < x ? x : b;
}
else
{
return x < b ? x : b;
}
}
} // namespace AZStd::Internal
namespace AZStd
{
constexpr float lerp(float a, float b, float t) noexcept
{
return Internal::lerp(a, b, t);
}
constexpr double lerp(double a, double b, double t) noexcept
{
return Internal::lerp(a, b, t);
}
constexpr long double lerp(long double a, long double b, long double t) noexcept
{
return Internal::lerp(a, b, t);
}
} // namespace AZStd
| 21.443038 | 101 | 0.504723 | [
"3d"
] |
47fc7c75fc3288cc37d3f24fe5d35a2dadba3e5e | 14,977 | h | C | include/disir/context/convenience.h | mariuslundblad/disir-c | ae831250cfbf033a755c91e62e8af7d82135d0d8 | [
"Apache-2.0"
] | 4 | 2017-06-19T09:59:50.000Z | 2019-03-20T18:49:11.000Z | include/disir/context/convenience.h | mariuslundblad/disir-c | ae831250cfbf033a755c91e62e8af7d82135d0d8 | [
"Apache-2.0"
] | 18 | 2017-06-25T22:19:00.000Z | 2019-11-28T13:16:26.000Z | include/disir/context/convenience.h | mariuslundblad/disir-c | ae831250cfbf033a755c91e62e8af7d82135d0d8 | [
"Apache-2.0"
] | 2 | 2017-10-31T11:19:55.000Z | 2019-11-28T12:13:13.000Z | #ifndef _LIBDISIR_CONTEXT_CONVENIENCE_H
#define _LIBDISIR_CONTEXT_CONVENIENCE_H
#ifdef __cplusplus
extern "C"{
#endif // __cplusplus
#include <disir/disir.h>
//!
//! This file contains the high level context convenience functions.
//! These are all implemented on top of the low level API endpoints.
//!
//! \brief Add a documentation string to an entry.
//!
//! This will have the default introduced version.
//! This is a shortcut between opening a new context,
//! adding value before finalizing it.
//!
//! Supported contexts:
//! * KEYVAL
//! * GROUP
//! * CONFIG
//! * MOLD
//! * RESTRICTION
//!
//! \param context The input context to add documentation to.
//! \param doc The documentation string
//! \param doc_size The size of the `doc` string.
//!
//! \return DISIR_STATUS_WRONG_CONTEXT if an unsupported context is provided.
//! \return DISIR_STATUS_EXISTS if a documentation entry already exists.
//! \return DISIR_STATUS_OK on success.
//!
DISIR_EXPORT
enum disir_status
dc_add_documentation (struct disir_context *context, const char *doc, int32_t doc_size);
//! \brief Get the documentation entry for a given version on the context.
//!
//! NOTE: This is currently the only method for retrieving the documentation
//! of a context.
//!
//! Retrieve a specific documentation entry valid for the input version number
//! given. If version is NULL, the highest version is picked.
//! Supported context types are:
//! * DISIR_CONTEXT_SECTION
//! * DISIR_CONTEXT_KEYVAL
//! * DISIR_CONTEXT_CONFIG
//! * DISIR_CONTEXT_MOLD
//! * DISIR_CONTEXT_RESTRICTION
//!
//! \param[in] context Input context to retrieve documentation for.
//! \param[in] version Matching documentation entry covered by this verison number.
//! NULL indicates the greatest (version) documentation entry.
//! \param[out] doc Output pointer the documentation constant will be populated to.
//! \param[out] doc_size Size of the documentation string, in bytes. Optional; May be NULL
//!
//! \return DISIR_STATUS_INVALID_ARGUMENTS if context or doc are NULL
//! \return DISIR_STATUS_WRONG_CONTEXT if context is not of supported type.
//! \return DISIR_STATUS_OK if doc is popualted with documentation string of context.
//!
DISIR_EXPORT
enum disir_status
dc_get_documentation (struct disir_context *context, struct disir_version *version,
const char **doc, int32_t *doc_size);
//! \brief Shortcut to add a KEYVAL string entry to a parent context.
//!
//! Instead of beginning a context on a parent, setting the required name, type,
//! default, documentation fields, this function wraps all that logic into one
//! simple function call. If you require special restrictions and additional defaults,
//! you will need to go the long route through beginning and finalizing a context.
//!
//! \param[out] output Optional output context storage. If address is passed,
//! the output KEYVAL context is populated and reference increased.
//! Caller must take care to use dc_putcontext () when he is done.
//!
//! \return DISIR_STATUS_OK if the parent accepted the input keyval with 'name', at
//! the input version 'version'.
//! \return DISIR_STATUS_INVALID_ARGUMENT if either 'name', 'def' or 'doc' are NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if input 'parent' is of wrong context type.
//!
DISIR_EXPORT
enum disir_status
dc_add_keyval_string (struct disir_context *parent,
const char *name, const char *def,
const char *doc, struct disir_version *version,
struct disir_context **output);
//! \brief Shortcut to add a KEYVAL enum entry to a parent context.
//!
//! Instead of beginning a context on a parent, setting the required name, type,
//! default, documentation fields, this function wraps all that logic into one
//! simple function call. If you require special restrictions and additional defaults,
//! you will need to go the long route through beginning and finalizing a context.
//!
//! NOTE: The enum requires additional restrictions on it to mark valid enum values.
//! The context will be invalid after this call. One SHOULD catch the output context
//! and add the required restrictions
//!
//! \param[out] output Optional output context storage. If address is passed,
//! the output KEYVAL context is populated and reference increased.
//! Caller must take care to use dc_putcontext () when he is done.
//!
//! \return DISIR_STATUS_OK if the parent accepted the input keyval with 'name', at
//! the input version 'version'.
//! \return DISIR_STATUS_INVALID_ARGUMENT if either 'name', 'def' or 'doc' are NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if input 'parent' is of wrong context type.
//!
DISIR_EXPORT
enum disir_status
dc_add_keyval_enum (struct disir_context *parent,
const char *name, const char *def,
const char *doc, struct disir_version *version,
struct disir_context **output);
//! \brief Shortcut to add a KEYVAL integer entry to a parent context.
//!
//! Instead of beginning a context on a parent, setting the required name, type,
//! default, documentation fields, this function wraps all that logic into one
//! simple function call. If you require special restrictions and additional defaults,
//! you will need to go the long route through beginning and finalizing a context.
//!
//! \param[out] output Optional output context storage. If address is passed,
//! the output KEYVAL context is populated and reference increased.
//! Caller must take care to use dc_putcontext () when he is done.
//!
//! \return DISIR_STATUS_OK if the parent accepted the input keyval with 'name', at
//! the input version 'version'.
//! \return DISIR_STATUS_INVALID_ARGUMENT if either 'name', 'def' or 'doc' are NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if input 'parent' is of wrong context type.
//!
DISIR_EXPORT
enum disir_status
dc_add_keyval_integer (struct disir_context *parent,
const char *name, int64_t def,
const char *doc, struct disir_version *version,
struct disir_context **output);
//! \brief Shortcut to add a KEYVAL float entry to a parent context.
//!
//! Instead of beginning a context on a parent, setting the required name, type,
//! default, documentation fields, this function wraps all that logic into one
//! simple function call. If you require special restrictions and additional defaults,
//! you will need to go the long route through beginning and finalizing a context.
//!
//! \param[out] output Optional output context storage. If address is passed,
//! the output KEYVAL context is populated and reference increased.
//! Caller must take care to use dc_putcontext () when he is done.
//!
//! \return DISIR_STATUS_OK if the parent accepted the input keyval with 'name', at
//! the input version 'version'.
//! \return DISIR_STATUS_INVALID_ARGUMENT if either 'name', 'def' or 'doc' are NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if input 'parent' is of wrong context type.
//!
DISIR_EXPORT
enum disir_status
dc_add_keyval_float (struct disir_context *parent,
const char *name, double def,
const char *doc, struct disir_version *version,
struct disir_context **output);
//! \brief Shortcut to add a KEYVAL boolean entry to a parent context.
//!
//! Instead of beginning a context on a parent, setting the required name, type,
//! default, documentation fields, this function wraps all that logic into one
//! simple function call. If you require special restrictions and additional defaults,
//! you will need to go the long route through beginning and finalizing a context.
//!
//! \param[out] output Optional output context storage. If address is passed,
//! the output KEYVAL context is populated and reference increased.
//! Caller must take care to use dc_putcontext () when he is done.
//!
//! \return DISIR_STATUS_OK if the parent accepted the input keyval with 'name', at
//! the input version 'version'.
//! \return DISIR_STATUS_INVALID_ARGUMENT if either 'name', 'def' or 'doc' are NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if input 'parent' is of wrong context type.
//!
DISIR_EXPORT
enum disir_status
dc_add_keyval_boolean (struct disir_context *parent,
const char *name, uint8_t def,
const char *doc, struct disir_version *version,
struct disir_context **output);
//! \brief Add a default value to an entry, type inferred from the parent context
//!
//! Parse the input string to retrieve the value whose type is inferred from the
//! parent context. This function is merely a convenient wrapper around all
//! other dc_add_default_* functions.
//! The `value_size` parameter is only applicable for default entries whose
//! KEYVAL is STRING.
//!
//! \param context Parent context of which to add a new default entry
//! \param value String to parse the relevant value information from
//! \param value_size: Only applicable to string manipulating value types.
//! Size in bytes of the input string to copy.A
//! \param version Number this default entry is valid from. NULL indicates
//! the default version number.
//!
//! \return DISIR_STATUS_OK if a new default object was associated with the parent context
//!
DISIR_EXPORT
enum disir_status
dc_add_default (struct disir_context *context, const char *value,
int32_t value_size, struct disir_version *version);
//! \brief Add a default string value to the parent context.
//!
//! Type of parent must be DISIR_VALUE_TYPE_STRING. There must not be a default context
//! in parent with an equal version number.
//!
//! \param parent A DISIR_CONTEXT_KEYVAL context, whose toplevel context is a DISIR_CONTEXT_MOLD.
//! \param value Default string value to add.
//! \param value_size Size in bytes of the string to copy.
//! \param version Number this default entry is valid from. NULL indicates
//! the default version number.
//!
//! \return DISIR_STATUS_OK if the default string 'value' entry succesfully added
//! to the parent context.
//! \return DISIR_STATUS_CONFLICTING_SEMVER if there exists a default entry with equal 'version'.
//!
DISIR_EXPORT
enum disir_status
dc_add_default_string (struct disir_context *parent, const char *value,
int32_t value_size, struct disir_version *version);
//! \brief Add a default integer value to the parent context.
//!
//! Type of parent must be DISIR_VALUE_TYPE_INTEGER. There must not be a default context
//! in parent with an equal version number.
//!
//! \param parent A DISIR_CONTEXT_KEYVAL context, whose toplevel context is a DISIR_CONTEXT_MOLD.
//! \param value Default integer value to add.
//! \param version Number this default entry is valid from. NULL indicates
//! the default version number.
//!
//! \return DISIR_STATUS_OK if the default integer 'value' entry succesfully added
//! to the parent context.
//! \return DISIR_STATUS_CONFLICTING_SEMVER if there exists a default entry with equal 'version'.
//!
DISIR_EXPORT
enum disir_status
dc_add_default_integer (struct disir_context *parent, int64_t value,
struct disir_version *version);
//! \brief Add a default float value to the parent context.
//!
//! Type of parent must be DISIR_VALUE_TYPE_FLOAT. There must not be a default context
//! in parent with an equal version number.
//!
//! \param parent A DISIR_CONTEXT_KEYVAL context, whose toplevel context is a DISIR_CONTEXT_MOLD.
//! \param value Default float value to add.
//! \param version Number this default entry is valid from. NULL indicates
//! the default version number.
//! \return DISIR_STATUS_OK if the default float 'value' entry succesfully added
//! to the parent context.
//! \return DISIR_STATUS_CONFLICTING_SEMVER if there exists a default entry with equal 'version'.
//!
DISIR_EXPORT
enum disir_status
dc_add_default_float (struct disir_context *parent, double value,
struct disir_version *version);
//! \brief Add a default boolean value to the parent context.
//!
//! Type of parent must be DISIR_VALUE_TYPE_BOOLEAN. There must not be a default context
//! in parent with an equal version number.
//!
//! \param parent A DISIR_CONTEXT_KEYVAL context, whose toplevel context is a DISIR_CONTEXT_MOLD.
//! \param booelan Default bool value to add.
//! \param version Number this default entry is valid from. NULL indicates
//! the default version number.
//!
//! \return DISIR_STATUS_OK if the default 'boolean' entry succesfully added
//! to the parent context.
//! \return DISIR_STATUS_CONFLICTING_SEMVER if there exists a default entry with equal 'version'.
//!
DISIR_EXPORT
enum disir_status
dc_add_default_boolean (struct disir_context *parent, uint8_t boolean,
struct disir_version *version);
//! \brief Generate the contents of the input SECTION or CONFIG whose root is CONFIG.
//!
//! This function is used to make sure the input context has all its required children
//! present. This is useful when constructing a new SECTION on a finalized parent,
//! who cannot be finalized before all minimum occurrence children is also present.
//! We do NOT generate child elements whose minimum occurrence count is zero.
//!
//! \param context A DISIR_CONTEXT_SECTION or DISIR_CONTEXT_CONFIG whose root is CONFIG.
//!
//! \return DISIR_STATUS_INVALID_ARGUMENT if context is NULL or not a valid context.
//! \return DISIR_CONTEXT_WRONG_CONTEXT if the context is of incorrect type or root.
//! \return DISIR_STATUS_OK on success.
//!
DISIR_EXPORT
enum disir_status
dc_generate_from_config_root (struct disir_context *context);
//! \brief Set the CONFIG KEYVAL value to its default value.
//!
//! This function inspects the mold equivalent for for this CONFIG KEYVAL
//! and assigns the value to its default value, as requested by the optional
//! input version specifier. If no version is specified, the default value
//! available at the highest version is used.
//!
//! \param[in] keyval The CONFIG KEYVAL context to perform the operation on.
//! \param[in] version Optional version specification. If NULL is passed,
//! the highest available version is used.
//!
//! \return DISIR_STATUS_INVALID_ARGUMENT if keyval is NULL.
//! \return DISIR_STATUS_WRONG_CONTEXT if keyval is not of type KEYVAL,
//! or if the root context is not of type CONFIG.
//! \return DISIR_STATUS_MOLD_MISSING if no mold is associated with this CONFIG KEYVAL.
//! \return DISIR_STATUS_OK on success.
//!
DISIR_EXPORT
enum disir_status
dc_keyval_set_default (struct disir_context *keyval, struct disir_version *version);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // _LIBDISIR_CONTEXT_CONVENIENCE_H
| 45.111446 | 97 | 0.727449 | [
"object"
] |
47ff533cf8ebd54c3a71d7a591ed03a6f88dee65 | 6,878 | h | C | src/PixelBuffer.h | adamelliot/LightString | cca027cd788954543491702b41a0e1dc43ea72bf | [
"MIT"
] | 3 | 2015-10-21T20:41:32.000Z | 2017-03-27T19:23:33.000Z | src/PixelBuffer.h | adamelliot/LightString | cca027cd788954543491702b41a0e1dc43ea72bf | [
"MIT"
] | 1 | 2017-06-30T23:35:34.000Z | 2017-06-30T23:35:34.000Z | src/PixelBuffer.h | adamelliot/LightString | cca027cd788954543491702b41a0e1dc43ea72bf | [
"MIT"
] | null | null | null | #pragma once
#include <string.h>
#include <math.h>
#include <algorithm>
#include <typeindex>
#include "utils.h"
#include "types.h"
#include "geometry.h"
#include "colortypes.h"
#ifndef ARDUINO
using namespace std;
#endif
namespace LightString {
template <template <typename> class T, typename FORMAT = uint8_t>
class TPixelBuffer : public IPixelBuffer {
private:
T<FORMAT> *rawPixels = nullptr;
// Leave space before the actual pixels so things mapped to -1 are allowable
bool hasDummyPixel = false;
public:
T<FORMAT> *pixels = nullptr;
uint32_t length = 0;
bool shouldDelete = false;
TPixelBuffer() {}
/**
* Allow to allocate space externally for the buffer. If `hasDummyPixel` is enabled
* then length is assumed to include the `dummy pixel` thus the functional length
* will be `length - 1`
*/
TPixelBuffer(T<FORMAT> *pixels, uint32_t length, bool hasDummyPixel = false)
: hasDummyPixel(hasDummyPixel), pixels(pixels), length(length), shouldDelete(false)
{
rawPixels = pixels;
if (hasDummyPixel) {
this->length = length - 1;
this->pixels++;
}
}
TPixelBuffer(const uint32_t length, bool hasDummyPixel = false)
: hasDummyPixel(hasDummyPixel), length(length), shouldDelete(true)
{
auto len = length + (hasDummyPixel ? 1 : 0);
pixels = new T<FORMAT>[len];
rawPixels = pixels;
if (hasDummyPixel) {
this->pixels++;
}
}
virtual ~TPixelBuffer() {
if (shouldDelete && rawPixels) delete[] rawPixels;
}
virtual bool resize(uint32_t length) {
if (!shouldDelete && this->length > 0) {
#ifdef ARDUINO
Serial.println("ERROR: Cannot resize buffer that is not owned by pixel buffer.");
#else
fprintf(stderr, "ERROR: Cannot resize buffer that is not owned by pixel buffer.\n");
#endif
return false;
}
if (shouldDelete) {
delete[] rawPixels;
}
auto len = length + (hasDummyPixel ? 1 : 0);
this->length = length;
pixels = new T<FORMAT>[len];
rawPixels = pixels;
if (hasDummyPixel) {
pixels++;
}
return true;
}
void setPixelData(T<FORMAT> *pixels, uint32_t length, bool hasDummyPixel = false) {
if (shouldDelete && rawPixels) delete[] rawPixels;
shouldDelete = false;
rawPixels = pixels;
this->length = length;
this->pixels = this->rawPixels;
this->hasDummyPixel = hasDummyPixel;
if (hasDummyPixel) {
this->length = length - 1;
this->pixels++;
}
}
uint32_t getLength() const { return length; }
uint32_t getSize() const { return length; }
inline T<FORMAT>& operator[] (int index) __attribute__((always_inline)) {
return pixels[index];
}
inline void setPixel(int index, T<FORMAT> col) __attribute__((always_inline)) {
pixels[index] = col;
}
// FIXME: Alpha channel semantics should be reviewed
inline void setPixelAA(float index, T<FORMAT> col) __attribute__((always_inline)) {
auto base = (uint32_t)index;
uint8_t ratio = (uint8_t)(fmod(index, 1) * 255);
if (ratio == 0) {
setPixel(base, col);
return;
}
pixels[base] = pixels[base].lerp8(col, 255 - ratio);
if ((base + 1) < length) {
pixels[base + 1] = pixels[base + 1].lerp8(col, ratio);
}
}
inline void setPixels(int index, uint8_t length, T<FORMAT> col) __attribute__((always_inline)) {
for (auto i = index; i < index + length; i++) {
pixels[i] = col;
}
}
inline void setMirroredPixel(int index, T<FORMAT> col) __attribute__((always_inline)) {
pixels[index] = col;
pixels[length - index - 1] = col;
}
inline void clear() __attribute__((always_inline)) {
memset(pixels, 0, sizeof(T<FORMAT>) * length);
}
inline void fillColor(T<FORMAT> col) __attribute__((always_inline)) {
for (auto i = 0; i < length; i++) {
pixels[i] = col;
}
}
inline void fade(const FORMAT scale) {
for (auto i = 0; i < this->length; i++) {
pixels[i].fade(scale);
}
}
inline void alphaFade(const FORMAT scale) {
for (auto i = 0; i < this->length; i++) {
pixels[i].alphaFade(scale);
}
}
/*
// 2d stuff should be broken out into 2d buffer
inline void drawRect(int16_t x0, int16_t y0, int16_t x1, int16_t y1, CRGB col) {
::drawRect(pixels, x0, y0, x1, y1, col);
}
inline void drawRect(Point<float> pt, uint8_t size, CRGB col) {
::drawRect(pixels, pt.x, pt.y, pt.x + size, pt.y + size, col);
}
inline void lineTo(Point<float> pt1, Point<float> pt2, CRGB col) {
::lineTo(pixels, pt1.x, pt1.y, pt2.x, pt2.y, col);
}
inline void drawSolidCircle(int16_t x, int16_t y, uint8_t radius, CRGB col) {
::drawSolidCircle(pixels, x, y, radius, col);
}
inline void drawSolidCircle(Point<float> pt, uint8_t radius, CRGB col) {
::drawSolidCircle(pixels, pt.x, pt.y, radius, col);
}
*/
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendCOPY(TPixelBuffer<SRC_PIXEL, FORMAT> &src) {
auto len = min(this->length, src.length);
for (auto i = 0; i < len; i++) {
LightString::blendCOPY(this->pixels[i], src.pixels[i]);
}
return *this;
}
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendCOPY(TPixelBuffer<SRC_PIXEL, FORMAT> &src, FORMAT alpha) {
auto len = min(this->length, src.length);
for (auto i = 0; i < len; i++) {
SRC_PIXEL<FORMAT> srcPixel = src.pixels[i].fadeCopy(alpha);
LightString::blendCOPY(this->pixels[i], srcPixel);
}
return *this;
}
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendADD(TPixelBuffer<SRC_PIXEL, FORMAT> &src) {
auto len = min(this->length, src.length);
for (auto i = 0; i < len; i++) {
LightString::blendADD(this->pixels[i], src.pixels[i]);
}
return *this;
}
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendADD(TPixelBuffer<SRC_PIXEL, FORMAT> &src, FORMAT alpha) {
auto len = min(this->length, src.length);
for (auto i = 0; i < len; i++) {
SRC_PIXEL<FORMAT> srcPixel = src.pixels[i].fadeCopy(alpha);
LightString::blendADD(this->pixels[i], srcPixel);
}
return *this;
}
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendWith(TPixelBuffer<SRC_PIXEL, FORMAT> &src, EBlendMode blendMode) {
switch (blendMode) {
case BLEND_COPY: return blendCOPY(src);
case BLEND_ADD: return blendADD(src);
}
return *this;
}
template <template <typename> class SRC_PIXEL>
inline TPixelBuffer<T, FORMAT> &blendWith(TPixelBuffer<SRC_PIXEL, FORMAT> &src, EBlendMode blendMode, FORMAT alpha) {
switch (blendMode) {
case BLEND_COPY: return blendCOPY(src, alpha);
case BLEND_ADD: return blendADD(src, alpha);
}
return *this;
}
};
typedef TPixelBuffer<TRGB, uint8_t> RGBuBuffer;
typedef TPixelBuffer<TRGB, uint8_t> RGBBuffer;
typedef TPixelBuffer<TRGBA, uint8_t> RGBABuffer;
typedef TPixelBuffer<TRGBA, uint8_t> RGBAuBuffer;
};
#include "buffers/MappingPixelBuffer2d.h"
#include "buffers/PixelBuffer3d.h"
#include "buffers/MappingPixelBuffer.h"
| 26.05303 | 118 | 0.682611 | [
"geometry"
] |
9a0aea9c1d1a7057b276ef5266279c8851ce0c38 | 2,446 | h | C | include/zapriltag_ros/zapriltag.h | ZhouYixuanRobtic/zapriltag_ros | 85b584320a1cc839fe88381314f7cbe0ed425522 | [
"MIT"
] | 1 | 2020-08-06T06:32:01.000Z | 2020-08-06T06:32:01.000Z | include/zapriltag_ros/zapriltag.h | ZhouYixuanRobtic/zapriltag_ros | 85b584320a1cc839fe88381314f7cbe0ed425522 | [
"MIT"
] | null | null | null | include/zapriltag_ros/zapriltag.h | ZhouYixuanRobtic/zapriltag_ros | 85b584320a1cc839fe88381314f7cbe0ed425522 | [
"MIT"
] | null | null | null | //
// Created by xcy on 2020/8/5.
//
#ifndef ZAPRILTAG_H
#define ZAPRILTAG_H
#include <cstdint>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <string>
#include <cmath>
#include <ctime>
#include <utility>
#include "Eigen/Dense"
#include "Eigen/Geometry"
#include <Eigen/Core>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/ximgproc.hpp>
#include <opencv2/core/eigen.hpp>
#include "cv.h"
#include "highgui.h"
#include <boost/thread/thread.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
#include "tr1/memory"
#include <dirent.h>
extern "C" {
#include "apriltag.h"
#include "tag36h11.h"
#include "tag25h9.h"
#include "tag16h5.h"
#include "tagCircle21h7.h"
#include "tagCircle49h12.h"
#include "tagCustom48h12.h"
#include "tagStandard41h12.h"
#include "tagStandard52h13.h"
#include "common/getopt.h"
#include "apriltag_pose.h"
}
struct TagDetectInfo{
//the tag pose with respect to camera described as a homogeneous matrix
Eigen::Affine3d Trans_C2T;
//the tag id
int id;
//the coefficient unit meters per pixel
double PixelCoef;
//the pixel point of tag center
cv::Point2d Center;
};
typedef std::vector<TagDetectInfo> tag_detection_info_t;
class AprilTag{
private:
TagDetectInfo TagDetected_;
//tag family name
const std::string TAG_FAMILY_NAME_;
//april tag handle
apriltag_family_t *tf;
//apriltag detecter handle
apriltag_detector_t *td;
//apriltag detection handle
apriltag_detection_t *det;
//apriltag detection info handle;
apriltag_detection_info_t info;
//apriltag pose handle
apriltag_pose_t pose;
//april tag physic size unit meter
const double TAG_SIZE_ ;
public:
bool image_received;
AprilTag(std::string tag_family_name,double tag_size,const double* intrinsic_parameter,
const float* detector_parameter,bool refine_edges);
~AprilTag();
/*
* Function computes tag information of all tags detected
* @param UserImage [the image prepared to detect tag]
* fill a vector contains all tag information detected, empty when no tags detected
*/
tag_detection_info_t GetTargetPoseMatrix(cv::Mat & UserImage);
};
#endif //ZAPRILTAG_H | 22.859813 | 91 | 0.725675 | [
"geometry",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.