hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
4f1ee99281ef141d42a038f41cd1ddb9cc86f312
26,803
cpp
C++
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
#include "Variant.hpp" #include <gdnative/variant.h> #include "CoreTypes.hpp" #include "Defs.hpp" #include "GodotGlobal.hpp" #include "Object.hpp" #include <iostream> #include <stdexcept> #ifndef NO_IMPORT_ARRAY #define NO_IMPORT_ARRAY #endif #include "PythonGlobal.hpp" #include <_lib/godot/core/types.hpp> namespace godot { Variant::Variant() { godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); } Variant::Variant(bool p_bool) { godot::api->godot_variant_new_bool(&_godot_variant, p_bool); } Variant::Variant(signed int p_int) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_int); } Variant::Variant(unsigned int p_int) { godot::api->godot_variant_new_uint(&_godot_variant, p_int); } Variant::Variant(signed short p_short) // real one { godot::api->godot_variant_new_int(&_godot_variant, (int)p_short); } Variant::Variant(int64_t p_char) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_char); } Variant::Variant(uint64_t p_char) { godot::api->godot_variant_new_uint(&_godot_variant, p_char); } Variant::Variant(float p_float) { godot::api->godot_variant_new_real(&_godot_variant, p_float); } Variant::Variant(double p_double) { godot::api->godot_variant_new_real(&_godot_variant, p_double); } Variant::Variant(const String &p_string) { godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&p_string); } Variant::Variant(const char *const p_cstring) { String s = String(p_cstring); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const wchar_t *p_wstring) { String s = p_wstring; godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const Vector2 &p_vector2) { godot::api->godot_variant_new_vector2(&_godot_variant, (godot_vector2 *)&p_vector2); } Variant::Variant(const Rect2 &p_rect2) { godot::api->godot_variant_new_rect2(&_godot_variant, (godot_rect2 *)&p_rect2); } Variant::Variant(const Vector3 &p_vector3) { godot::api->godot_variant_new_vector3(&_godot_variant, (godot_vector3 *)&p_vector3); } Variant::Variant(const Plane &p_plane) { godot::api->godot_variant_new_plane(&_godot_variant, (godot_plane *)&p_plane); } Variant::Variant(const AABB &p_aabb) { godot::api->godot_variant_new_aabb(&_godot_variant, (godot_aabb *)&p_aabb); } Variant::Variant(const Quat &p_quat) { godot::api->godot_variant_new_quat(&_godot_variant, (godot_quat *)&p_quat); } Variant::Variant(const Basis &p_transform) { godot::api->godot_variant_new_basis(&_godot_variant, (godot_basis *)&p_transform); } Variant::Variant(const Transform2D &p_transform) { godot::api->godot_variant_new_transform2d(&_godot_variant, (godot_transform2d *)&p_transform); } Variant::Variant(const Transform &p_transform) { godot::api->godot_variant_new_transform(&_godot_variant, (godot_transform *)&p_transform); } Variant::Variant(const Color &p_color) { godot::api->godot_variant_new_color(&_godot_variant, (godot_color *)&p_color); } Variant::Variant(const NodePath &p_path) { godot::api->godot_variant_new_node_path(&_godot_variant, (godot_node_path *)&p_path); } Variant::Variant(const RID &p_rid) { godot::api->godot_variant_new_rid(&_godot_variant, (godot_rid *)&p_rid); } Variant::Variant(const Object *p_object) { if (p_object) godot::api->godot_variant_new_object(&_godot_variant, p_object->_owner); else godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Dictionary &p_dictionary) { godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&p_dictionary); } Variant::Variant(const Array &p_array) { godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&p_array); } Variant::Variant(const PoolByteArray &p_raw_array) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&p_raw_array); } Variant::Variant(const PoolIntArray &p_int_array) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&p_int_array); } Variant::Variant(const PoolRealArray &p_real_array) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&p_real_array); } Variant::Variant(const PoolStringArray &p_string_array) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&p_string_array); } Variant::Variant(const PoolVector2Array &p_vector2_array) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&p_vector2_array); } Variant::Variant(const PoolVector3Array &p_vector3_array) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&p_vector3_array); } Variant::Variant(const PoolColorArray &p_color_array) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&p_color_array); } Variant::Variant(const PyObject *p_python_object) { if (p_python_object == Py_None) { // Py_XDECREF(p_python_object); // XXX godot::api->godot_variant_new_nil(&_godot_variant); } else if (PyBool_Check(p_python_object)) { godot::api->godot_variant_new_bool(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyLong_Check(p_python_object)) { godot::api->godot_variant_new_int(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyFloat_Check(p_python_object)) { const double p_double = PyFloat_AsDouble((PyObject *)p_python_object); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyUnicode_Check(p_python_object) || PyBytes_Check(p_python_object)) { String s = String(p_python_object); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } else if (PyByteArray_Check(p_python_object)) { godot_pool_byte_array *p; godot::api->godot_pool_byte_array_new(p); godot::api->godot_pool_byte_array_resize(p, PyByteArray_GET_SIZE(p_python_object)); godot_pool_byte_array_write_access *_write_access = godot::api->godot_pool_byte_array_write(p); const uint8_t *ptr = godot::api->godot_pool_byte_array_write_access_ptr(_write_access); memcpy((void *)ptr, (void *)PyByteArray_AS_STRING(p_python_object), PyByteArray_GET_SIZE(p_python_object)); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); godot::api->godot_pool_byte_array_write_access_destroy(_write_access); godot::api->godot_pool_byte_array_destroy(p); } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_AABB) { godot_aabb *p = _python_wrapper_to_aabb((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_aabb(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Array) { godot_array *p = _python_wrapper_to_godot_array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_array(&_godot_variant, p); } else { godot::api->godot_variant_new_nil(&_godot_variant); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Basis) { godot_basis *p = _python_wrapper_to_basis((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_basis(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Color) { godot_color *p = _python_wrapper_to_color((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_color(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Dictionary) { godot_dictionary *p = _python_wrapper_to_godot_dictionary((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_dictionary(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_NodePath) { godot_node_path *p = _python_wrapper_to_nodepath((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_node_path(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Plane) { godot_plane *p = _python_wrapper_to_plane((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_plane(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolByteArray) { godot_pool_byte_array *p = _python_wrapper_to_poolbytearray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolIntArray) { godot_pool_int_array *p = _python_wrapper_to_poolintarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolRealArray) { godot_pool_real_array *p = _python_wrapper_to_poolrealarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolStringArray) { godot_pool_string_array *p = _python_wrapper_to_poolstringarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector2Array) { godot_pool_vector2_array *p = _python_wrapper_to_poolvector2array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector3Array) { godot_pool_vector3_array *p = _python_wrapper_to_poolvector3array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolColorArray) { godot_pool_color_array *p = _python_wrapper_to_poolcolorarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Quat) { godot_quat *p = _python_wrapper_to_quat((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_quat(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Rect2) { godot_rect2 *p = _python_wrapper_to_rect2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rect2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_RID) { godot_rid *p = _python_wrapper_to_rid((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rid(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_String) { godot_string *p = _python_wrapper_to_godot_string((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_string(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform) { godot_transform *p = _python_wrapper_to_transform((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform2D) { godot_transform2d *p = _python_wrapper_to_transform2d((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform2d(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector2) { godot_vector2 *p = _python_wrapper_to_vector2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector3) { godot_vector3 *p = _python_wrapper_to_vector3((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector3(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (PyObject_IsInstance((PyObject *)p_python_object, (PyObject *)PyGodotType__Wrapped)) { godot_object *p = _cython_binding_to_godot_object((PyObject *)p_python_object); godot::api->godot_variant_new_object(&_godot_variant, p); // TODO: dict -> Dictionary, other iterables -> Array, array.Array -> PoolArray*, numpy.array -> PoolArray* } else if (PyArray_Check((PyObject *)p_python_object)) { PyArrayObject *arr = (PyArrayObject *)p_python_object; if (PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_UINT8) { PoolByteArray _arr = PoolByteArray(arr); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISINTEGER(arr)) { PoolIntArray _arr(arr); godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISFLOAT(arr)) { PoolRealArray _arr(arr); godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISSTRING(arr)) { PoolStringArray _arr(arr); godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&_arr); } else if (PyArray_NDIM(arr) == 1) { Array _arr; for (int idx = 0; idx < PyArray_SIZE(arr); idx++) { PyObject *item = PyArray_GETITEM(arr, (const char *)PyArray_GETPTR1(arr, idx)); // TODO: Check NULL pointer _arr.append(Variant(item)); } godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 2) { PoolVector2Array _arr = PoolVector2Array(arr); godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 3) { PoolVector3Array _arr = PoolVector3Array(arr); godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 4) { PoolColorArray _arr = PoolColorArray(arr); godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&_arr); } else { throw std::invalid_argument("could not convert NumPy array"); } } else if (PySequence_Check((PyObject *)p_python_object)) { Array arr = Array(p_python_object); godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&arr); } else if (PyMapping_Check((PyObject *)p_python_object)) { Dictionary dict = Dictionary(p_python_object); godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&dict); } else if (PyIndex_Check((PyObject *)p_python_object)) { const Py_ssize_t p_num = PyNumber_AsSsize_t((PyObject *)p_python_object, NULL); godot::api->godot_variant_new_int(&_godot_variant, p_num); } else if (PyNumber_Check((PyObject *)p_python_object)) { PyObject *p_num = PyNumber_Float((PyObject *)p_python_object); const double p_double = PyFloat_AsDouble((PyObject *)p_num); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyObject_CheckBuffer((PyObject *)p_python_object)) { throw std::invalid_argument("generic Python buffer support is not implemented yet"); } else { // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } } Variant &Variant::operator=(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); return *this; } Variant::operator bool() const { return booleanize(); } Variant::operator signed int() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned int() const // this is the real one { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed short() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned short() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed char() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned char() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator int64_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator uint64_t() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator wchar_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator float() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator double() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator String() const { String ret; *(godot_string *)&ret = godot::api->godot_variant_as_string(&_godot_variant); return ret; } Variant::operator Vector2() const { godot_vector2 s = godot::api->godot_variant_as_vector2(&_godot_variant); return *(Vector2 *)&s; } Variant::operator Rect2() const { godot_rect2 s = godot::api->godot_variant_as_rect2(&_godot_variant); return *(Rect2 *)&s; } Variant::operator Vector3() const { godot_vector3 s = godot::api->godot_variant_as_vector3(&_godot_variant); return *(Vector3 *)&s; } Variant::operator Plane() const { godot_plane s = godot::api->godot_variant_as_plane(&_godot_variant); return *(Plane *)&s; } Variant::operator AABB() const { godot_aabb s = godot::api->godot_variant_as_aabb(&_godot_variant); return *(AABB *)&s; } Variant::operator Quat() const { godot_quat s = godot::api->godot_variant_as_quat(&_godot_variant); return *(Quat *)&s; } Variant::operator Basis() const { godot_basis s = godot::api->godot_variant_as_basis(&_godot_variant); return *(Basis *)&s; } Variant::operator Transform() const { godot_transform s = godot::api->godot_variant_as_transform(&_godot_variant); return *(Transform *)&s; } Variant::operator Transform2D() const { godot_transform2d s = godot::api->godot_variant_as_transform2d(&_godot_variant); return *(Transform2D *)&s; } Variant::operator Color() const { godot_color s = godot::api->godot_variant_as_color(&_godot_variant); return *(Color *)&s; } Variant::operator NodePath() const { NodePath ret; *(godot_node_path *)&ret = godot::api->godot_variant_as_node_path(&_godot_variant); return ret; } Variant::operator RID() const { godot_rid s = godot::api->godot_variant_as_rid(&_godot_variant); return *(RID *)&s; } Variant::operator Dictionary() const { Dictionary ret; *(godot_dictionary *)&ret = godot::api->godot_variant_as_dictionary(&_godot_variant); return ret; } Variant::operator Array() const { Array ret; *(godot_array *)&ret = godot::api->godot_variant_as_array(&_godot_variant); return ret; } Variant::operator PoolByteArray() const { PoolByteArray ret; *(godot_pool_byte_array *)&ret = godot::api->godot_variant_as_pool_byte_array(&_godot_variant); return ret; } Variant::operator PoolIntArray() const { PoolIntArray ret; *(godot_pool_int_array *)&ret = godot::api->godot_variant_as_pool_int_array(&_godot_variant); return ret; } Variant::operator PoolRealArray() const { PoolRealArray ret; *(godot_pool_real_array *)&ret = godot::api->godot_variant_as_pool_real_array(&_godot_variant); return ret; } Variant::operator PoolStringArray() const { PoolStringArray ret; *(godot_pool_string_array *)&ret = godot::api->godot_variant_as_pool_string_array(&_godot_variant); return ret; } Variant::operator PoolVector2Array() const { PoolVector2Array ret; *(godot_pool_vector2_array *)&ret = godot::api->godot_variant_as_pool_vector2_array(&_godot_variant); return ret; } Variant::operator PoolVector3Array() const { PoolVector3Array ret; *(godot_pool_vector3_array *)&ret = godot::api->godot_variant_as_pool_vector3_array(&_godot_variant); return ret; } Variant::operator PoolColorArray() const { PoolColorArray ret; *(godot_pool_color_array *)&ret = godot::api->godot_variant_as_pool_color_array(&_godot_variant); return ret; } Variant::operator godot_object *() const { return godot::api->godot_variant_as_object(&_godot_variant); } Variant::operator PyObject *() const { PyObject *obj; switch (get_type()) { case NIL: obj = Py_None; break; case BOOL: obj = booleanize() ? Py_True : Py_False; break; case INT: obj = PyLong_FromSsize_t(godot::api->godot_variant_as_int(&_godot_variant)); break; case REAL: obj = PyFloat_FromDouble(godot::api->godot_variant_as_real(&_godot_variant)); break; case STRING: { String s = *this; obj = PyUnicode_FromWideChar(s.unicode_str(), s.length()); break; } case VECTOR2: { Vector2 cpp_obj = *this; return _vector2_to_python_wrapper(cpp_obj); } case RECT2: { Rect2 cpp_obj = *this; return _rect2_to_python_wrapper(cpp_obj); } case VECTOR3: { Vector3 cpp_obj = *this; return _vector3_to_python_wrapper(cpp_obj); } case TRANSFORM2D: { Transform2D cpp_obj = *this; return _transform2d_to_python_wrapper(cpp_obj); } case PLANE: { Plane cpp_obj = *this; return _plane_to_python_wrapper(cpp_obj); } case QUAT: { Quat cpp_obj = *this; return _quat_to_python_wrapper(cpp_obj); } case RECT3: { AABB cpp_obj = *this; return _aabb_to_python_wrapper(cpp_obj); } case BASIS: { Basis cpp_obj = *this; return _basis_to_python_wrapper(cpp_obj); } case TRANSFORM: { Transform cpp_obj = *this; return _transform_to_python_wrapper(cpp_obj); } case COLOR: { Color cpp_obj = *this; return _color_to_python_wrapper(cpp_obj); } case NODE_PATH: { NodePath cpp_obj = *this; return _nodepath_to_python_wrapper(cpp_obj); } case _RID: { RID cpp_obj = *this; return _rid_to_python_wrapper(cpp_obj); } case OBJECT: { godot_object *c_obj = godot::api->godot_variant_as_object(&_godot_variant); return _godot_object_to_python_binding(c_obj); } case DICTIONARY: { const Dictionary dict = *this; const Array keys = dict.keys(); obj = PyDict_New(); for (int i = 0; i < keys.size(); i++) { Variant _key = keys[i]; PyObject *key = _key; PyObject *val = dict[_key]; // TODO: Check unlikely NULL pointers PyDict_SetItem(obj, key, val); } break; } case ARRAY: { const Array arr = *this; obj = PyTuple_New(arr.size()); for (int i = 0; i < arr.size(); i++) { PyObject *item = arr[i]; // TODO: Check unlikely NULL pointers PyTuple_SET_ITEM(obj, i, item); } break; } case POOL_BYTE_ARRAY: { PoolByteArray cpp_obj = *this; return _poolbytearray_to_python_wrapper(cpp_obj); } case POOL_INT_ARRAY: { PoolIntArray cpp_obj = *this; return _poolintarray_to_python_wrapper(cpp_obj); } case POOL_REAL_ARRAY: { PoolRealArray cpp_obj = *this; return _poolrealarray_to_python_wrapper(cpp_obj); } case POOL_STRING_ARRAY: { PoolStringArray cpp_obj = *this; return _poolstringarray_to_numpy(cpp_obj); } case POOL_VECTOR2_ARRAY: { PoolVector2Array cpp_obj = *this; return _poolvector2array_to_python_wrapper(cpp_obj); } case POOL_VECTOR3_ARRAY: { PoolVector3Array cpp_obj = *this; return _poolvector3array_to_python_wrapper(cpp_obj); } case POOL_COLOR_ARRAY: { PoolColorArray cpp_obj = *this; return _poolcolorarray_to_python_wrapper(cpp_obj); } default: // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } Py_XINCREF(obj); return obj; } Variant::Type Variant::get_type() const { return (Type)godot::api->godot_variant_get_type(&_godot_variant); } Variant Variant::call(const String &method, const Variant **args, const int arg_count) { Variant v; *(godot_variant *)&v = godot::api->godot_variant_call(&_godot_variant, (godot_string *)&method, (const godot_variant **)args, arg_count, nullptr); return v; } bool Variant::has_method(const String &method) { return godot::api->godot_variant_has_method(&_godot_variant, (godot_string *)&method); } bool Variant::operator==(const Variant &b) const { return godot::api->godot_variant_operator_equal(&_godot_variant, &b._godot_variant); } bool Variant::operator!=(const Variant &b) const { return !(*this == b); } bool Variant::operator<(const Variant &b) const { return godot::api->godot_variant_operator_less(&_godot_variant, &b._godot_variant); } bool Variant::operator<=(const Variant &b) const { return (*this < b) || (*this == b); } bool Variant::operator>(const Variant &b) const { return !(*this <= b); } bool Variant::operator>=(const Variant &b) const { return !(*this < b); } bool Variant::hash_compare(const Variant &b) const { return godot::api->godot_variant_hash_compare(&_godot_variant, &b._godot_variant); } bool Variant::booleanize() const { return godot::api->godot_variant_booleanize(&_godot_variant); } Variant::~Variant() { godot::api->godot_variant_destroy(&_godot_variant); } } // namespace godot
32.607056
147
0.745066
WilliamTambellini
4f203c48428c692de98f2b0fdd812268d388a572
2,114
cc
C++
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
3
2020-06-09T02:31:43.000Z
2021-03-30T09:14:33.000Z
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
/// Copyright (c) 2020 xiw /// /// MIT License /// \author Wang Xi #include "logging/log_stream.h" #include <thread> #include <sstream> namespace logging { void LogStream::buf(char** p_buf, size_t* size) { *p_buf = buf_; *size = buf_pointer_; } LogStream &LogStream::operator<<(bool arg) { if(arg) append("true"); else append("false"); return *this; } LogStream &LogStream::operator<<(char arg) { char str[2] = {arg,'\0'}; append(str); return *this; } LogStream &LogStream::operator<<(int16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(float arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(double arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(const char *arg) { append(arg); return *this; } LogStream &LogStream::operator<<(const string &arg) { append(arg.c_str()); return *this; } void LogStream::append(const char *s) { auto buf_left = buf_size_ - buf_pointer_ > 0 ? buf_size_ - buf_pointer_ : 0; buf_pointer_ += ::snprintf(buf_ + buf_pointer_, buf_left, "%s", s); } /// global output std::function<void(const char*, size_t)> g_out = [](const char* buf, size_t size){ ::fwrite(buf, 1, size, ::stdout); }; /// global flush std::function<void()> g_flush = [](){ ::fflush(::stdout); }; } // namespace logging
17.048387
82
0.644276
xiw2-0
4f2070c48921f7111b5e881d6412c44aa0dddea4
8,179
cpp
C++
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
2
2021-04-18T06:47:05.000Z
2021-06-16T09:52:44.000Z
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
#include "LFFD_ncnn.h" LFFD::LFFD(int scale_num, int num_thread_) { num_output_scales = scale_num; num_thread = num_thread_; if (num_output_scales == 5) { param_file_name = "symbol_10_320_20L_5scales_v2_deploy.param"; bin_file_name = "train_10_320_20L_5scales_v2_iter_1000000.bin"; receptive_field_list = { 20, 40, 80, 160, 320 }; receptive_field_stride = { 4, 8, 16, 32, 64 }; bbox_small_list = { 10, 20, 40, 80, 160 }; bbox_large_list = { 20, 40, 80, 160, 320 }; receptive_field_center_start = { 3, 7, 15, 31, 63 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names = { "softmax0","conv8_3_bbox", "softmax1","conv11_3_bbox", "softmax2","conv14_3_bbox", "softmax3","conv17_3_bbox", "softmax4","conv20_3_bbox" }; } else if (num_output_scales == 8) { param_file_name = "symbol_10_560_25L_8scales_v1_deploy.param"; bin_file_name = "train_10_560_25L_8scales_v1_iter_1400000.bin"; receptive_field_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_stride = { 4, 4, 8, 8, 16, 32, 32, 32 }; bbox_small_list = { 10, 15, 20, 40, 70, 110, 250, 400 }; bbox_large_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_center_start = { 3, 3, 7, 7, 15, 31, 31, 31 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names={ "softmax0","conv8_3_bbox", "softmax1","conv10_3_bbox", "softmax2","conv13_3_bbox", "softmax3","conv15_3_bbox", "softmax4","conv18_3_bbox", "softmax5","conv21_3_bbox", "softmax6","conv23_3_bbox", "softmax7","conv25_3_bbox" }; } lffd.load_param(param_file_name.data()); lffd.load_model(bin_file_name.data()); } LFFD::~LFFD() { lffd.clear(); } int LFFD::detect(ncnn::Mat& img, std::vector<FaceInfo>& face_list, int resize_h, int resize_w, float score_threshold, float nms_threshold, int top_k, std::vector<int> skip_scale_branch_list) { if (img.empty()) { std::cout << "image is empty ,please check!" << std::endl; return -1; } image_h = img.h; image_w = img.w; ncnn::Mat in; ncnn::resize_bilinear(img,in,resize_w,resize_h); float ratio_w=(float)image_w/in.w; float ratio_h=(float)image_h/in.h; ncnn::Mat ncnn_img = in; ncnn_img.substract_mean_normalize(mean_vals, norm_vals); std::vector<FaceInfo> bbox_collection; ncnn::Extractor ex = lffd.create_extractor(); ex.set_num_threads(num_thread); ex.input("data", ncnn_img); for (int i = 0; i <num_output_scales; i++) { ncnn::Mat conf; ncnn::Mat reg; ex.extract(output_blob_names[2*i].c_str(), conf); ex.extract(output_blob_names[2 * i+1].c_str(), reg); generateBBox(bbox_collection, conf, reg, score_threshold, conf.w, conf.h, in.w, in.h, i); } std::vector<FaceInfo> valid_input; get_topk_bbox(bbox_collection, valid_input, top_k); nms(valid_input, face_list, nms_threshold); for(size_t i=0;i<face_list.size();i++){ face_list[i].x1*=ratio_w; face_list[i].y1*=ratio_h; face_list[i].x2*=ratio_w; face_list[i].y2*=ratio_h; float w,h,maxSize; float cenx,ceny; w=face_list[i].x2-face_list[i].x1; h=face_list[i].y2-face_list[i].y1; maxSize = w > h ? w : h; cenx=face_list[i].x1+w/2; ceny=face_list[i].y1+h/2; face_list[i].x1=cenx-maxSize/2>0? cenx - maxSize / 2:0; face_list[i].y1=ceny-maxSize/2>0? ceny - maxSize / 2:0; face_list[i].x2=cenx+maxSize/2>image_w? image_w-1: cenx + maxSize / 2; face_list[i].y2=ceny+maxSize/2> image_h? image_h-1: ceny + maxSize / 2; } return 0; } void LFFD::generateBBox(std::vector<FaceInfo>& bbox_collection, ncnn::Mat score_map, ncnn::Mat box_map, float score_threshold, int fea_w, int fea_h, int cols, int rows, int scale_id) { float* RF_center_Xs = new float[fea_w]; float* RF_center_Xs_mat = new float[fea_w * fea_h]; float* RF_center_Ys = new float[fea_h]; float* RF_center_Ys_mat = new float[fea_h * fea_w]; for (int x = 0; x < fea_w; x++) { RF_center_Xs[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; } for (int x = 0; x < fea_h; x++) { for (int y = 0; y < fea_w; y++) { RF_center_Xs_mat[x * fea_w + y] = RF_center_Xs[y]; } } for (int x = 0; x < fea_h; x++) { RF_center_Ys[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; for (int y = 0; y < fea_w; y++) { RF_center_Ys_mat[x * fea_w + y] = RF_center_Ys[x]; } } float* x_lt_mat = new float[fea_h * fea_w]; float* y_lt_mat = new float[fea_h * fea_w]; float* x_rb_mat = new float[fea_h * fea_w]; float* y_rb_mat = new float[fea_h * fea_w]; //x-left-top float mid_value = 0; for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(0)[j] * constant[scale_id]; x_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //y-left-top for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(1)[j] * constant[scale_id]; y_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //x-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(2)[j] * constant[scale_id]; x_rb_mat[j] = mid_value > cols - 1 ? cols - 1 : mid_value; } //y-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(3)[j] * constant[scale_id]; y_rb_mat[j] = mid_value > rows - 1 ? rows - 1 : mid_value; } for (int k = 0; k < fea_h * fea_w; k++) { if (score_map.channel(0)[k] > score_threshold) { FaceInfo faceinfo; faceinfo.x1 = x_lt_mat[k]; faceinfo.y1 = y_lt_mat[k]; faceinfo.x2 = x_rb_mat[k]; faceinfo.y2 = y_rb_mat[k]; faceinfo.score = score_map[k]; faceinfo.area = (faceinfo.x2 - faceinfo.x1) * (faceinfo.y2 - faceinfo.y1); bbox_collection.push_back(faceinfo); } } delete[] RF_center_Xs; RF_center_Xs = NULL; delete[] RF_center_Ys; RF_center_Ys = NULL; delete[] RF_center_Xs_mat; RF_center_Xs_mat = NULL; delete[] RF_center_Ys_mat; RF_center_Ys_mat = NULL; delete[] x_lt_mat; x_lt_mat = NULL; delete[] y_lt_mat; y_lt_mat = NULL; delete[] x_rb_mat; x_rb_mat = NULL; delete[] y_rb_mat; y_rb_mat = NULL; } void LFFD::get_topk_bbox(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, int top_k) { std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); if (input.size() > size_t(top_k)) { for (int k = 0; k < top_k; k++) { output.push_back(input[k]); } } else { output = input; } } void LFFD::nms(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, float threshold, int type) { if(input.empty()) return; std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); int box_num = input.size(); std::vector<int> merged(box_num, 0); for (int i = 0; i < box_num; i++) { if (merged[i]) continue; output.push_back(input[i]); for (int j = i + 1; j < box_num; j++) { if (merged[j]) continue; float inner_x0 = input[i].x1 > input[j].x1 ? input[i].x1 : input[j].x1;//std::max(input[i].x1, input[j].x1); float inner_y0 = input[i].y1 > input[j].y1 ? input[i].y1 : input[j].y1; float inner_x1 = input[i].x2 < input[j].x2 ? input[i].x2 : input[j].x2; //bug fixed ,sorry float inner_y1 = input[i].y2 < input[j].y2 ? input[i].y2 : input[j].y2; float inner_h = inner_y1 - inner_y0 + 1; float inner_w = inner_x1 - inner_x0 + 1; if (inner_h <= 0 || inner_w <= 0) continue; float inner_area = inner_h * inner_w; float h1 = input[j].y2 - input[j].y1 + 1; float w1 = input[j].x2 - input[j].x1 + 1; float area1 = h1 * w1; float score= inner_area/area1; if (score > threshold) merged[j] = 1; } } }
30.981061
182
0.627461
Qengineering
4f21000a633dbc7b4704b27b1a2782af1fbd7e35
3,686
cpp
C++
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
/* #include<stdio.h> #include<assert.h> #include<iostream> #include<typeinfo> #include "Create.h" #include "Read.h" */ #include "core/Pipeline.h" //#include "TransformEvaluator.h" //#include "TransformEvaluate.h" #include "Source/UnboundedInMemEvaluator_Join.h" //#include "SimpleMapperEvaluator.h" #include "Join/JoinEvaluator1.h" #include "Sink/RecordBitmapBundleSinkEvaluator.h" #include <tuple> #include "test-common.h" /* * +--- SimpleMapper -- (KVPair)--\ * Unbound -(long)-> + Join --> (KVPai * +--- SimpleMapper -- (KVPair)--/ * */ /* template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; } */ template<class T> using BundleT = RecordBitmapBundle<T>; #ifdef DEBUG pipeline_config config = { .records_per_interval = 1000 * 1000, .target_tput = (1000 * 500), .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #else pipeline_config config = { .records_per_interval = 1000 * 1000, //.target_tput = (10 * 1000 * 1000), .target_tput = 2000 * 1000, //k2: 2000 should be fine .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #endif int main(int ac, char *av[]) { parse_options(ac, av, &config); print_config(); // create a new Bounded transform //UnboundedInMem<long, BundleT> unbound ("[unbounded]", 50, 0); //UnboundedInMem_Join<long, BundleT> unbound ("[unbounded]", UnboundedInMem_Join unbound ("[unbounded]", config.input_file.c_str(), config.records_per_interval , /* records per wm interval */ config.target_tput, /* target tput (rec/sec) */ config.record_size, 0 //XXX session_gap_ms = ???? ); // create a new pipeline Pipeline* p = Pipeline::create(NULL); /* vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); connect_transform(unbound, mapper0); connect_transform(unbound, mapper1); */ /* old design vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); auto c11 = dynamic_cast<PCollection *>(o2[0]->apply1(&mapper0)); c11->_name = "mapper0_out"; mapper0.set_side_info(1); //left side SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); auto c12 = dynamic_cast<PCollection *>(o2[1]->apply1(&mapper1)); c12->_name = "mapper1_out"; mapper1.set_side_info(2); //right side */ PCollection *unbound_output = dynamic_cast<PCollection *>(p->apply1(&unbound)); unbound_output->_name = "unbound_output"; Join<pair<long,long>> join("[join]", seconds(1)); auto c2 = dynamic_cast<PCollection *>(unbound_output->apply1(&join)); //auto c3 = dynamic_cast<PCollection *>(c12->apply1(&join)); ///c2 = c2; //assert(c2 == c3); // same output. join.set_side_info(3); RecordBitmapBundleSink<pair<long, vector<long>>> sink("[sink]"); auto c4 = dynamic_cast<PCollection *>(c2->apply1(&sink)); c4 = c4; assert(c4); //just for fixing warning sink.set_side_info(4); RecordBitmapBundleSink<pair<long, vector<long>>> sink1("[sink1]"); auto c5 = dynamic_cast<PCollection *>(c4->apply1(&sink1)); c5 = c5; assert(c5); //just for fixing warning //assert(false && "set RecordBitmapBundleSink side_info to 4!!"); sink1.set_side_info(5); EvaluationBundleContext eval(1, config.cores); //XXX target_wm_delta_secs?? eval.runSimple(p); return 0; }
29.253968
80
0.663049
chenzongxiong
4f23b6cc5bc4a79d61a90b2c317d723d6fb33dfb
444
cpp
C++
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
1
2021-02-23T05:58:24.000Z
2021-02-23T05:58:24.000Z
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "RandomUtils.hpp" using namespace poplar; namespace poprand { class SetSeedSupervisor : public SupervisorVertexIf<ASM_CODELETS_ENABLED> { public: SetSeedSupervisor(); Input<Vector<unsigned, ONE_PTR, 8>> seed; const uint32_t seedModifierUser; const uint32_t seedModifierHw; IS_EXTERNAL_CODELET(true); bool compute() { return true; } }; } // namespace poprand
20.181818
75
0.756757
giantchen2012
4f23d25e3dd58ad9ec5517f35b4fd0e826371bd6
24,265
cpp
C++
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
76
2019-07-03T06:43:37.000Z
2020-05-08T20:23:08.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
15
2020-01-12T23:37:09.000Z
2020-05-01T04:44:14.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
2
2020-01-18T14:13:14.000Z
2020-04-05T14:17:07.000Z
// FileDialog.cpp // // Dialog that allows selection of a file or directory. May be used for opening a file/directory or saving to a file. // // Copyright (c) 2021, 2022 Tristan Grimmer. // 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. #include <Math/tVector2.h> #include <System/tTime.h> #include "imgui.h" #include "FileDialog.h" #include "TacentView.h" #include "Image.h" using namespace tStd; using namespace tMath; using namespace tSystem; using namespace tImage; using namespace tInterface; namespace tInterface { // Content items are containers used to store information about a piece of information in a file dialog. It stores // the stuff you see in the right-hand panel. Namely the information displayed in a table row about a file or // directory, as well as if it is selected or not. struct ContentItem : tLink<ContentItem> { ContentItem(const tString& dirName); ContentItem(const tSystem::tFileInfo& fileInfo); bool Selected; // Each field (column) gets its own ID. This is needed so when sorting, we know what information to use in the // sorting function. We tell ImGui about the ID, and it passes that along when it tells us to sort. enum class FieldID { Invalid = -1, Name, ModTime, FileType, FileSize }; struct CompareFunctionObject { CompareFunctionObject(ImGuiTableSortSpecs* specs) : SortSpecs(specs) { } ImGuiTableSortSpecs* SortSpecs; bool operator() (const ContentItem& a, const ContentItem& b) const; }; // Name field. tString Name; bool IsDir; // These are not valid for directories. Note that we store field data redundantly in some cases since we need to be // able to sort based on a key decoupled from the display string. For example, sorting by date should be done with // an integer, not the string representation. Same with filesizes, we may want them displayed in KB or MB is they // get large, but want to sort on num-bytes. We store the string reps because it's more efficient to cache them // rather than regenerate them every time. // Modification time (last) field. int64 ModTime; // In posix epoch. tString ModTimeString; // Displayed. // File type field. tSystem::tFileType FileType; tString FileTypeString; // Displayed. // File size field. int64 FileSize; tString FileSizeString; // Displayed. }; // Tree nodes are displayed directly in the left panel and their contained Contents list in the right. TreeNodes // represent directories and other containers like favourites and network shares. A TreeNode has children TreeNodes. class TreeNode { public: TreeNode() : Name(), Parent(nullptr) { } TreeNode(const tString& name, FileDialog* dialog, TreeNode* parent = nullptr) : Name(name), Dialog(dialog), Parent(parent) { } void AppendChild(TreeNode* treeNode) { Children.Append(treeNode); } // For windows these do a case-insensitive compare. For case sensitive filesystems like Linux uses // these to a case-sensitive compare. TreeNode* Find(const tString& name) const; bool Contains(const tString& name) const { return Find(name) ? true : false; } int Depth() const; bool IsNetworkLocation() const; ContentItem* FindSelectedItem() const; tString Name; FileDialog* Dialog; bool ChildrenPopulated = false; TreeNode* Parent; tItList<TreeNode> Children; bool NextOpen = false; // Is the Contents list below populated and valid. It is slightly different than having an empty Contents list // because a leaf empty directory may have no contents, but it HAS read the filesystem so is populated. bool ContentsPopulated = false; tList<ContentItem> Contents; }; } ContentItem::ContentItem(const tString& dirName) : Selected(false), IsDir(true) { Name = dirName; ModTime = 0; ModTimeString.Clear(); FileType = tSystem::tFileType::Invalid; FileSize = 0; FileSizeString.Clear(); } ContentItem::ContentItem(const tSystem::tFileInfo& fileInfo) : Selected(false) { // Name field. Name = tSystem::tGetFileName(fileInfo.FileName); IsDir = fileInfo.Directory; // Modification time field. Choose greater of mod and creation time. ModTime = tMath::tMax(fileInfo.ModificationTime, fileInfo.CreationTime); tsPrintf(ModTimeString, "%s", tSystem::tConvertTimeToString(tSystem::tConvertTimeToLocal(ModTime)).Chars()); // File type field. FileType = tSystem::tGetFileType(Name); FileTypeString.Set(tSystem::tGetFileTypeName(FileType)); // File size field. FileSize = fileInfo.FileSize; if (FileSize < 10000) tsPrintf(FileSizeString, "%'d B", FileSize); else if (FileSize < 10000000) tsPrintf(FileSizeString, "%'d KB", FileSize/1024); else if (FileSize < 10000000000) tsPrintf(FileSizeString, "%'d MB", FileSize/(1024*1024)); else tsPrintf(FileSizeString, "%'d GB", FileSize/(1024*1024*1024)); } bool ContentItem::CompareFunctionObject::operator() (const ContentItem& a, const ContentItem& b) const { tAssert(SortSpecs); // We always put directories at the top regardless of field contents and sorting order. if (a.IsDir && !b.IsDir) return true; // This makes both the directories (that come first) as well as the files (that come after) sort correctly. // That is, do the sorting if we're comparing file-to-file or dir-to-dir. if (a.IsDir == b.IsDir) { // NumSpecs will be > 1 if more than one column is selected for sorting. The order is important. int numSpecs = SortSpecs->SpecsCount; for (int s = 0; s < numSpecs; s++) { const ImGuiTableColumnSortSpecs& colSortSpec = SortSpecs->Specs[s]; FieldID field = FieldID(colSortSpec.ColumnUserID); int64 delta = 0; switch (field) { case FieldID::Name: delta = tStd::tStricmp(a.Name.Chars(), b.Name.Chars()); break; case FieldID::ModTime: delta = a.ModTime - b.ModTime; break; case FieldID::FileType: delta = tStd::tStricmp(a.FileTypeString.Chars(), b.FileTypeString.Chars()); break; case FieldID::FileSize: delta = a.FileSize - b.FileSize; break; } if ((delta < 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Ascending)) return true; else if ((delta > 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Descending)) return true; } } return false; } TreeNode* TreeNode::Find(const tString& name) const { for (tItList<TreeNode>::Iter child = Children.First(); child; child++) { #ifdef PLATFORM_WINDOWS if (child->Name.IsEqualCI(name)) #else if (child->Name == name) #endif return child; } return nullptr; } int TreeNode::Depth() const { int depth = 0; TreeNode* parent = Parent; while (parent) { depth++; parent = parent->Parent; } return depth; } ContentItem* TreeNode::FindSelectedItem() const { for (ContentItem* item = Contents.First(); item; item = item->Next()) if (item->Selected) return item; return nullptr; } bool TreeNode::IsNetworkLocation() const { bool isNet = false; const TreeNode* curr = this; while (curr) { if ((curr->Depth() == 0) && (curr->Name == "Network")) isNet = true; curr = curr->Parent; } return isNet; } FileDialog::FileDialog(DialogMode mode, const tSystem::tFileTypes& fileTypes) : Mode(mode), FileTypes(fileTypes) { BookmarkTreeNode = new TreeNode("Bookmarks", this); LocalTreeNode = new TreeNode("Local", this); #ifdef PLATFORM_WINDOWS NetworkTreeNode = new TreeNode("Network", this); #endif // @wip Bookmarks is disabled until I implement it fully. PopulateBookmarks(); PopulateLocal(); #ifdef PLATFORM_WINDOWS PopulateNetwork(); #endif } void FileDialog::OpenPopup() { //ImGui::SetNextWindowSize(tVector2(640.0f, 400.0f), ImGuiCond_FirstUseEver); switch (Mode) { case DialogMode::OpenDir: ImGui::OpenPopup("Open Directory"); break; case DialogMode::OpenFile: ImGui::OpenPopup("Open File"); break; case DialogMode::SaveFile: ImGui::OpenPopup("Save File"); break; } } void FileDialog::PopulateBookmarks() { #if defined(PLATFORM_LINUX) // All linux platforms get a 'home' bookmark. #endif #if defined(PLATFORM_WINDOWS) // All windows platforms get a 'user' bookmark. TreeNode* user = new TreeNode("User", this, BookmarkTreeNode); BookmarkTreeNode->AppendChild(user); #endif } void FileDialog::PopulateLocal() { #if defined(PLATFORM_WINDOWS) tList<tStringItem> drives; tSystem::tGetDrives(drives); for (tStringItem* drive = drives.First(); drive; drive = drive->Next()) { TreeNode* driveNode = new TreeNode(*drive, this, LocalTreeNode); LocalTreeNode->AppendChild(driveNode); } #elif defined(PLATFORM_LINUX) TreeNode* rootNode = new TreeNode("/", this, LocalTreeNode); LocalTreeNode->AppendChild(rootNode); #endif } #ifdef PLATFORM_WINDOWS void FileDialog::RequestNetworkSharesThread() { tSystem::tGetNetworkShares(NetworkShareResults); } void FileDialog::PopulateNetwork() { // Start the request on a different thread. std::thread threadGetShares(&FileDialog::RequestNetworkSharesThread, this); threadGetShares.detach(); } void FileDialog::ProcessShareResults() { // Most of time this will be empty since we remove the items when they are available, just like a message queue. tStringItem* share = NetworkShareResults.ShareNames.Remove(); if (share) { tList<tStringItem> exploded; tExplodeShareName(exploded, *share); tString machName = *exploded.First(); if (!NetworkTreeNode->Contains(machName)) { TreeNode* machine = new TreeNode(machName.Text(), this, NetworkTreeNode); NetworkTreeNode->AppendChild(machine); } TreeNode* machNode = NetworkTreeNode->Find(machName); tAssert(machNode); tStringItem* shareName = (exploded.GetNumItems() == 2) ? exploded.Last() : nullptr; if (shareName && !machNode->Contains(*shareName)) { TreeNode* shareNode = new TreeNode(shareName->Text(), this, machNode); machNode->AppendChild(shareNode); } delete share; } } #endif void FileDialog::TreeNodeRecursive(TreeNode* node) { int flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen | ((node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0) | ((SelectedNode == node) ? ImGuiTreeNodeFlags_Selected : 0); bool populate = false; // This is the magic that's needed if you select from the right-hand panel. if (node->NextOpen) { ImGui::SetNextTreeNodeOpen(true); node->NextOpen = false; populate = true; } bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isClicked) { SelectedNode = node; populate = true; } // We only bother populating children if we need to. if (populate && !node->ChildrenPopulated) { #ifdef PLATFORM_WINDOWS if (!ProcessingNetworkPath || (node->Depth() >= 2)) #endif { // Need to be careful here. tFindDirs would (reasonably?) use the current working dir if we passed in an empty string. tString currDir = GetSelectedDir(); tList<tStringItem> foundDirs; if (!currDir.IsEmpty()) tSystem::tFindDirs(foundDirs, currDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { tString relDir = tSystem::tGetRelativePath(currDir, *dir); relDir.ExtractLeft("./"); relDir.ExtractRight("/"); TreeNode* child = new TreeNode(relDir, this, node); node->AppendChild(child); } node->ChildrenPopulated = true; } } if (isOpen) { // Recurse children. for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) TreeNodeRecursive(child.GetObject()); ImGui::TreePop(); } } void FileDialog::InvalidateAllNodeContent() { #ifdef PLATFORM_WINDOWS InvalidateAllNodeContentRecursive(NetworkTreeNode); #endif InvalidateAllNodeContentRecursive(LocalTreeNode); } void FileDialog::InvalidateAllNodeContentRecursive(TreeNode* node) { node->Contents.Empty(); node->ContentsPopulated = false; for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) InvalidateAllNodeContentRecursive(child.GetObject()); } void FileDialog::DoSelectable(ContentItem* item) { tString label = item->Name; if (ImGui::Selectable(label, &item->Selected, ImGuiSelectableFlags_SpanAllColumns)) { // This block enforces single selection. if (Mode != DialogMode::OpenFiles) { if (item->Selected) { // Only allowed one selected max. Clear the others. for (ContentItem* i = SelectedNode->Contents.First(); i; i = i->Next()) { if (i == item) continue; i->Selected = false; } } // Do not allow deselection of the single item. item->Selected = true; } // If a directory is selected in the right panel, we support updating the current selected TreeNode. if (item->IsDir) { SelectedNode->NextOpen = true; TreeNode* node = SelectedNode->Find(item->Name); if (!node) { // Need to create a new one and connect it up. node = new TreeNode(item->Name, this, SelectedNode); SelectedNode->AppendChild(node); tAssert(node->ChildrenPopulated == false); } SelectedNode = node; } } } void FileDialog::TreeNodeFlat(TreeNode* node) { int flags = (node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0; if (SelectedNode == node) flags |= ImGuiTreeNodeFlags_Selected; flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isOpen) { // Recurse children. // for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) // FavouritesTreeNodeFlat(child.GetObject()); ImGui::TreePop(); } } FileDialog::DialogResult FileDialog::DoPopup() { // The unused isOpen bool is just so we get a close button in ImGui. bool isOpen = true; const char* label = nullptr; switch (Mode) { case DialogMode::OpenFile: label = "Open File"; break; case DialogMode::OpenFiles: label = "Open Files"; break; case DialogMode::OpenDir: label = "Open Directory"; break; case DialogMode::SaveFile: label = "Save File"; break; } ImGui::SetNextWindowSize(tVector2(660.0f, 400.0f), ImGuiCond_Appearing); if (!ImGui::BeginPopupModal(label, &isOpen, 0)) return DialogResult::Closed; DialogResult result = DialogResult::Open; Result.Clear(); // The left and right panels are cells in a 1 row, 2 column table. float bottomBarHeight = 20.0f + 28.0f; ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.50f, 0.50f, 0.54f, 1.00f)); if (ImGui::BeginTable("FileDialogTable", 2, ImGuiTableFlags_Resizable, tVector2(0.0f, -bottomBarHeight))) { ImGui::TableSetupColumn("LeftTreeColumn", ImGuiTableColumnFlags_WidthFixed, 160.0f); ImGui::TableSetupColumn("RightContentColumn", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); // Left tree panel. ImGui::TableSetColumnIndex(0); ImGui::BeginChild("LeftTreePanel", tVector2(0.0f, -bottomBarHeight), false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, tVector2(0.0f, 3.0f)); // This block is the workhorse of the dialog. // @wip Bookmarks are disabled until implemented fully. TreeNodeFlat(BookmarkTreeNode); TreeNodeRecursive(LocalTreeNode); #ifdef PLATFORM_WINDOWS ProcessShareResults(); ProcessingNetworkPath = true; TreeNodeRecursive(NetworkTreeNode); ProcessingNetworkPath = false; #endif ImGui::PopStyleVar(); ImGui::EndChild(); // Right content panel. ImGui::TableSetColumnIndex(1); ImGui::BeginChild("RightContentPanel", tVector2(0.0f, -bottomBarHeight)); if (SelectedNode) { if (!SelectedNode->ContentsPopulated) { tString selDir = GetSelectedDir(); // Directories. tList<tStringItem> foundDirs; if (!selDir.IsEmpty()) tSystem::tFindDirs(foundDirs, selDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { (*dir)[dir->Length()-1] = '\0'; // Remove slash. ContentItem* contentItem = new ContentItem(tSystem::tGetFileName(*dir)); SelectedNode->Contents.Append(contentItem); } // Files. tList<tFileInfo> foundFiles; if (!selDir.IsEmpty()) { tSystem::tFileTypes selectedTypes; selectedTypes.AddSelected(FileTypes, true); tSystem::tExtensions extensions(selectedTypes); tSystem::tFindFilesFast(foundFiles, selDir, extensions); } for (tFileInfo* fileInfo = foundFiles.First(); fileInfo; fileInfo = fileInfo->Next()) { ContentItem* contentItem = new ContentItem(*fileInfo); SelectedNode->Contents.Append(contentItem); } SelectedNode->ContentsPopulated = true; } int tableFlags = ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Reorderable | // Drag columns to an order you like. ImGuiTableFlags_Hideable | // Hide individual columns. ImGuiTableFlags_Sortable | // Sort by column. // ImGuiTableFlags_SortTristate // Ascending, Descending, None. May get 0 sort specs. ImGuiTableFlags_SortMulti | // Allow sorting multiple columns by shift-selecting them. May get > 1 sort specs. //ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY; // This is needed so the table itself has a scroll bar that respects the top-row freeze. ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.25f, 0.25f, 0.28f, 1.00f)); if (ImGui::BeginTable("ContentItems", 5, tableFlags)) { // The columns. Each one gets its own unique ID. int iconFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoSort; int nameFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_NoReorder; int propFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_PreferSortAscending; ImGui::TableSetupColumn("Icon", iconFlags, 24.0f, uint32(ContentItem::FieldID::Invalid) ); ImGui::TableSetupColumn("Name", nameFlags, 190.0f, uint32(ContentItem::FieldID::Name) ); ImGui::TableSetupColumn("Modified", propFlags, 120.0f, uint32(ContentItem::FieldID::ModTime) ); ImGui::TableSetupColumn("Type", propFlags, 36.0f, uint32(ContentItem::FieldID::FileType) ); ImGui::TableSetupColumn("Size", propFlags, 0.0f, uint32(ContentItem::FieldID::FileSize) ); ImGui::TableSetupScrollFreeze(0, 1); // Make this row always visible. ImGui::TableHeadersRow(); // Sort the rows. ImGuiTableSortSpecs* sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs && (sortSpecs->SpecsDirty) && (sortSpecs->SpecsCount > 0)) { ContentItem::CompareFunctionObject compare(sortSpecs); SelectedNode->Contents.Sort(compare); sortSpecs->SpecsDirty = false; } // Do the content rows. We could use ImGuiListClipper here but so far, even with thousands of files in // the Contents list, it is very responsive. Also, since it's a list rather than an array, we'd still // need a 'Next' loop to get to the right clipper starting point (clipper.DisplayStart). for (ContentItem* item = SelectedNode->Contents.First(); item; item = item->Next()) { ImGui::TableNextRow(); ImGui::TableNextColumn(); uint64 imgID = item->IsDir ? Viewer::FolderImage.Bind() : Viewer::FileImage.Bind(); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+4.0f); ImGui::Image(ImTextureID(imgID), tVector2(16, 16), tVector2(0, 1), tVector2(1, 0), Viewer::ColourEnabledTint); // The name column selectable spans all columns. ImGui::TableNextColumn(); DoSelectable(item); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->ModTimeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileTypeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileSizeString.Text()); } ImGui::EndTable(); } ImGui::PopStyleColor(); } ImGui::EndChild(); ImGui::EndTable(); } ImGui::PopStyleColor(); ContentItem* selItem = SelectedNode ? SelectedNode->FindSelectedItem() : nullptr; bool resultAvail = false; if (selItem) { resultAvail = ( ((Mode == DialogMode::OpenFile) && !selItem->IsDir) || ((Mode == DialogMode::SaveFile) && !selItem->IsDir) || ((Mode == DialogMode::OpenDir) && selItem->IsDir) // @todo multiple files. ); } if (!resultAvail && (Mode == DialogMode::OpenDir) && SelectedNode) { // OK to select dir in left-hand pane. int depth = SelectedNode->Depth(); resultAvail = ( (depth > 1) || (!SelectedNode->IsNetworkLocation() && (depth > 0)) ); } // For file modes, display the filename and types combo. if (Mode != DialogMode::OpenDir) { int flags = ImGuiInputTextFlags_ReadOnly; ImGui::SetNextItemWidth( ImGui::GetWindowContentRegionMax().x / 2.0f ); if (!resultAvail) ImGui::PushStyleColor(ImGuiCol_Text, tVector4(0.5f, 0.5f, 0.52f, 1.0f) ); tString fname = resultAvail ? selItem->Name : "File Name"; ImGui::InputText("##File Name", fname.Text(), fname.Length()+1, flags); if (!resultAvail) ImGui::PopStyleColor(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); // Nothing selected means all types used. bool allTypes = !FileTypes.AnySelected(); tString currChosen = allTypes ? "All Image Types" : FileTypes.GetSelectedString(tSystem::tFileTypes::Separator::CommaSpace, 4); if (ImGui::BeginCombo("##TypeFilter", currChosen.Chars())) //, ImGuiComboFlags_NoArrowButton)) { if (ImGui::Selectable("All Image Types", allTypes)) { FileTypes.ClearSelected(); InvalidateAllNodeContent(); } for (tFileTypes::tFileTypeItem* typeItem = FileTypes.First(); typeItem; typeItem = typeItem->Next()) { tFileType fileType = typeItem->FileType; const char* fileTypeName = tSystem::tGetFileTypeName(fileType); if (!fileTypeName) continue; if (ImGui::Selectable(fileTypeName, typeItem->Selected)) { typeItem->Selected = !typeItem->Selected; InvalidateAllNodeContent(); } if (typeItem->Selected) ImGui::SetItemDefaultFocus(); } // Update the filters. ImGui::EndCombo(); } } // Cancel and OK buttons. ImGui::SetCursorPosY(ImGui::GetWindowContentRegionMax().y - 20.0f); if (resultAvail) { ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); if (ImGui::Button("Open", tVector2(70.0f, 0.0f))) { Result = GetSelectedDir(); if ((Mode == DialogMode::OpenFile) && selItem) Result += selItem->Name; result = DialogResult::OK; } ImGui::SameLine(); } ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 70.0f); if (ImGui::Button("Cancel", tVector2(70.0f, 0.0f))) result = DialogResult::Cancel; if (result != DialogResult::Open) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); return result; } tString FileDialog::GetResult() { return Result; } tString FileDialog::GetSelectedDir() { if (!SelectedNode) return tString(); bool isNetworkLoc = SelectedNode->IsNetworkLocation(); tString dir; TreeNode* curr = SelectedNode; while (curr) { if (!curr->Name.IsEmpty() && (curr->Depth() > 0)) { if (isNetworkLoc && (curr->Depth() == 1)) dir = curr->Name + "\\" + dir; else dir = curr->Name + "/" + dir; } curr = curr->Parent; } if (isNetworkLoc) dir = tString("\\\\") + dir; return dir; }
30.068154
242
0.705131
bluescan
4f2605188c3c8162aa30dfb72b435008f808b798
24,573
cpp
C++
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
111
2015-01-13T18:14:31.000Z
2022-02-20T14:26:55.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
54
2015-02-23T16:57:41.000Z
2021-02-19T08:16:27.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
26
2015-01-17T13:07:56.000Z
2021-12-02T07:43:29.000Z
// ========================================================== // Multi-Page functions // // Design and implementation by // - Floris van den Berg (flvdberg@wxs.nl) // - Laurent Rocher (rocherl@club-internet.fr) // - Steve Johnson (steve@parisgroup.net) // - Petr Pytelka (pyta@lightcomp.com) // - Hervé Drolon (drolon@infonie.fr) // - Vadim Alexandrov (vadimalexandrov@users.sourceforge.net // - Martin Dyring-Andersen (mda@spamfighter.com) // - Volodymyr Goncharov (volodymyr.goncharov@gmail.com) // - Mihail Naydenov (mnaydenov@users.sourceforge.net) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #ifdef _MSC_VER #pragma warning (disable : 4786) // identifier was truncated to 'number' characters #endif #include "CacheFile.h" #include "FreeImageIO.h" #include "Plugin.h" #include "Utilities.h" #include "FreeImage.h" namespace { // ---------------------------------------------------------- enum BlockType { BLOCK_CONTINUEUS, BLOCK_REFERENCE }; // ---------------------------------------------------------- class PageBlock { union { struct { int m_start; int m_end; }; struct { int m_reference; int m_size; }; }; public: BlockType m_type; PageBlock(BlockType type = BLOCK_CONTINUEUS, int val1 = -1, int val2 = -1) : m_type(type) { if(m_type == BLOCK_CONTINUEUS) { m_start = val1; m_end = val2; } else { m_reference = val1; m_size = val2; } } bool isValid() const { return !(m_type == BLOCK_CONTINUEUS && m_start == -1 && m_end == -1); } /*explicit*/ operator bool() const { return isValid(); } int getStart() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_start; } int getEnd() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_end; } bool isSinglePage() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_start == m_end) : true; } int getPageCount() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_end - m_start + 1) : 1;} int getReference() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_reference; } int getSize() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_size; } }; // ---------------------------------------------------------- typedef std::list<PageBlock> BlockList; typedef BlockList::iterator BlockListIterator; // ---------------------------------------------------------- struct MULTIBITMAPHEADER { MULTIBITMAPHEADER() : node(NULL) , fif(FIF_UNKNOWN) , handle(NULL) , changed(FALSE) , page_count(0) , read_only(TRUE) , cache_fif(fif) , load_flags(0) { SetDefaultIO(&io); } PluginNode *node; FREE_IMAGE_FORMAT fif; FreeImageIO io; fi_handle handle; CacheFile m_cachefile; std::map<FIBITMAP *, int> locked_pages; BOOL changed; int page_count; BlockList m_blocks; std::string m_filename; BOOL read_only; FREE_IMAGE_FORMAT cache_fif; int load_flags; }; // ===================================================================== // Helper functions // ===================================================================== inline void ReplaceExtension(std::string& dst_filename, const std::string& src_filename, const std::string& dst_extension) { size_t lastDot = src_filename.find_last_of('.'); if (lastDot == std::string::npos) { dst_filename = src_filename; dst_filename += "."; dst_filename += dst_extension; } else { dst_filename = src_filename.substr(0, lastDot + 1); dst_filename += dst_extension; } } } //< ns // ===================================================================== // Internal Multipage functions // ===================================================================== inline MULTIBITMAPHEADER * FreeImage_GetMultiBitmapHeader(FIMULTIBITMAP *bitmap) { return (MULTIBITMAPHEADER *)bitmap->data; } static BlockListIterator DLL_CALLCONV FreeImage_FindBlock(FIMULTIBITMAP *bitmap, int position) { assert(NULL != bitmap); MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // step 1: find the block that matches the given position int prev_count = 0; int count = 0; BlockListIterator i; for (i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { prev_count = count; count += i->getPageCount(); if (count > position) { break; } } // step 2: make sure we found the node. from here it gets a little complicated: // * if the block is single page, just return it // * if the block is a span of pages, split it in 3 new blocks // and return the middle block, which is now a single page if ((i != header->m_blocks.end()) && (count > position)) { if (i->isSinglePage()) { return i; } const int item = i->getStart() + (position - prev_count); // left part if (item != i->getStart()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, i->getStart(), item - 1)); } // middle part BlockListIterator block_target = header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item, item)); // right part if (item != i->getEnd()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item + 1, i->getEnd())); } // remove the old block that was just splitted header->m_blocks.erase(i); // return the splitted block return block_target; } // we should never go here ... assert(false); return header->m_blocks.end(); } int DLL_CALLCONV FreeImage_InternalGetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { if (((MULTIBITMAPHEADER *)bitmap->data)->handle) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); int page_count = (header->node->m_plugin->pagecount_proc != NULL) ? header->node->m_plugin->pagecount_proc(&header->io, header->handle, data) : 1; FreeImage_Close(header->node, &header->io, header->handle, data); return page_count; } } return 0; } // ===================================================================== // Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmap(FREE_IMAGE_FORMAT fif, const char *filename, BOOL create_new, BOOL read_only, BOOL keep_cache_in_memory, int flags) { FILE *handle = NULL; try { // sanity check on the parameters if (create_new) { read_only = FALSE; } // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { if (!create_new) { handle = fopen(filename, "rb"); if (handle == NULL) { return NULL; } } std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->m_filename = filename; // io is default header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap if (!create_new) { header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); } // set up the cache if (!read_only) { std::string cache_name; ReplaceExtension(cache_name, filename, "ficache"); if (!header->m_cachefile.open(cache_name, keep_cache_in_memory)) { // an error occured ... fclose(handle); return NULL; } } // return the multibitmap // std::bad_alloc won't be thrown from here on header.release(); // now owned by bitmap return bitmap.release(); // now owned by caller } } } catch (std::bad_alloc &) { /** @todo report error */ } if (handle) { fclose(handle); } return NULL; } FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmapFromHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flags) { try { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache if (io && handle) { // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->io = *io; header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default header.release(); return bitmap.release(); } } } } catch (std::bad_alloc &) { /** @todo report error */ } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToHandle(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FreeImageIO *io, fi_handle handle, int flags) { if(!bitmap || !bitmap->data || !io || !handle) { return FALSE; } BOOL success = TRUE; // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if(node) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // dst data void *data = FreeImage_Open(node, io, handle, FALSE); // src data void *data_read = NULL; if(header->handle) { // open src header->io.seek_proc(header->handle, 0, SEEK_SET); data_read = FreeImage_Open(header->node, &header->io, header->handle, TRUE); } // write all the pages to the file using handle and io int count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); i++) { if (success) { switch(i->m_type) { case BLOCK_CONTINUEUS: { for (int j = i->getStart(); j <= i->getEnd(); j++) { // load the original source data FIBITMAP *dib = header->node->m_plugin->load_proc(&header->io, header->handle, j, header->load_flags, data_read); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; FreeImage_Unload(dib); } break; } case BLOCK_REFERENCE: { // read the compressed data BYTE *compressed_data = (BYTE*)malloc(i->getSize() * sizeof(BYTE)); header->m_cachefile.readFile((BYTE *)compressed_data, i->getReference(), i->getSize()); // uncompress the data FIMEMORY *hmem = FreeImage_OpenMemory(compressed_data, i->getSize()); FIBITMAP *dib = FreeImage_LoadFromMemory(header->cache_fif, hmem, 0); FreeImage_CloseMemory(hmem); // get rid of the buffer free(compressed_data); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; // unload the dib FreeImage_Unload(dib); break; } } } else { break; } } // close the files FreeImage_Close(header->node, &header->io, header->handle, data_read); FreeImage_Close(node, io, handle, data); return success; } } return FALSE; } BOOL DLL_CALLCONV FreeImage_CloseMultiBitmap(FIMULTIBITMAP *bitmap, int flags) { if (bitmap) { BOOL success = TRUE; if (bitmap->data) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // saves changes only of images loaded directly from a file if (header->changed && !header->m_filename.empty()) { try { // open a temp file std::string spool_name; ReplaceExtension(spool_name, header->m_filename, "fispool"); // open the spool file and the source file FILE *f = fopen(spool_name.c_str(), "w+b"); // saves changes if (f == NULL) { FreeImage_OutputMessageProc(header->fif, "Failed to open %s, %s", spool_name.c_str(), strerror(errno)); success = FALSE; } else { success = FreeImage_SaveMultiBitmapToHandle(header->fif, bitmap, &header->io, (fi_handle)f, flags); // close the files if (fclose(f) != 0) { success = FALSE; FreeImage_OutputMessageProc(header->fif, "Failed to close %s, %s", spool_name.c_str(), strerror(errno)); } } if (header->handle) { fclose((FILE *)header->handle); } // applies changes to the destination file if (success) { remove(header->m_filename.c_str()); success = (rename(spool_name.c_str(), header->m_filename.c_str()) == 0) ? TRUE:FALSE; if(!success) { FreeImage_OutputMessageProc(header->fif, "Failed to rename %s to %s", spool_name.c_str(), header->m_filename.c_str()); } } else { remove(spool_name.c_str()); } } catch (std::bad_alloc &) { success = FALSE; } } else { if (header->handle && !header->m_filename.empty()) { fclose((FILE *)header->handle); } } // delete the last open bitmaps while (!header->locked_pages.empty()) { FreeImage_Unload(header->locked_pages.begin()->first); header->locked_pages.erase(header->locked_pages.begin()->first); } // delete the FIMULTIBITMAPHEADER delete header; } delete bitmap; return success; } return FALSE; } int DLL_CALLCONV FreeImage_GetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if (header->page_count == -1) { header->page_count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { header->page_count += i->getPageCount(); } } return header->page_count; } return 0; } static PageBlock FreeImage_SavePageToBlock(MULTIBITMAPHEADER *header, FIBITMAP *data) { PageBlock res; if (header->read_only || !header->locked_pages.empty()) { return res; } DWORD compressed_size = 0; BYTE *compressed_data = NULL; // compress the bitmap data // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); if(hmem==NULL) { return res; } // save the file to memory if(!FreeImage_SaveToMemory(header->cache_fif, data, hmem, 0)) { FreeImage_CloseMemory(hmem); return res; } // get the buffer from the memory stream if(!FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size)) { FreeImage_CloseMemory(hmem); return res; } // write the compressed data to the cache int ref = header->m_cachefile.writeFile(compressed_data, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); res = PageBlock(BLOCK_REFERENCE, ref, compressed_size); return res; } void DLL_CALLCONV FreeImage_AppendPage(FIMULTIBITMAP *bitmap, FIBITMAP *data) { if (!bitmap || !data) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add the block header->m_blocks.push_back(block); header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_InsertPage(FIMULTIBITMAP *bitmap, int page, FIBITMAP *data) { if (!bitmap || !data) { return; } if (page >= FreeImage_GetPageCount(bitmap)) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add a block if (page > 0) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, page); header->m_blocks.insert(block_source, block); } else { header->m_blocks.push_front(block); } header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_DeletePage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if (FreeImage_GetPageCount(bitmap) > 1) { BlockListIterator i = FreeImage_FindBlock(bitmap, page); if (i != header->m_blocks.end()) { switch(i->m_type) { case BLOCK_CONTINUEUS : header->m_blocks.erase(i); break; case BLOCK_REFERENCE : header->m_cachefile.deleteFile(i->getReference()); header->m_blocks.erase(i); break; } header->changed = TRUE; header->page_count = -1; } } } } } FIBITMAP * DLL_CALLCONV FreeImage_LockPage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // only lock if the page wasn't locked before... for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { if (i->second == page) { return NULL; } } // open the bitmap header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); // load the bitmap data if (data != NULL) { FIBITMAP *dib = (header->node->m_plugin->load_proc != NULL) ? header->node->m_plugin->load_proc(&header->io, header->handle, page, header->load_flags, data) : NULL; // close the file FreeImage_Close(header->node, &header->io, header->handle, data); // if there was still another bitmap open, get rid of it if (dib) { header->locked_pages[dib] = page; return dib; } return NULL; } } return NULL; } void DLL_CALLCONV FreeImage_UnlockPage(FIMULTIBITMAP *bitmap, FIBITMAP *page, BOOL changed) { if ((bitmap) && (page)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // find out if the page we try to unlock is actually locked... if (header->locked_pages.find(page) != header->locked_pages.end()) { // store the bitmap compressed in the cache for later writing if (changed && !header->read_only) { header->changed = TRUE; // cut loose the block from the rest BlockListIterator i = FreeImage_FindBlock(bitmap, header->locked_pages[page]); // compress the data DWORD compressed_size = 0; BYTE *compressed_data = NULL; // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); // save the page to memory FreeImage_SaveToMemory(header->cache_fif, page, hmem, 0); // get the buffer from the memory stream FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size); // write the data to the cache if (i->m_type == BLOCK_REFERENCE) { header->m_cachefile.deleteFile(i->getReference()); } int iPage = header->m_cachefile.writeFile(compressed_data, compressed_size); *i = PageBlock(BLOCK_REFERENCE, iPage, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); } // reset the locked page so that another page can be locked FreeImage_Unload(page); header->locked_pages.erase(page); } } } BOOL DLL_CALLCONV FreeImage_MovePage(FIMULTIBITMAP *bitmap, int target, int source) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if ((target != source) && ((target >= 0) && (target < FreeImage_GetPageCount(bitmap))) && ((source >= 0) && (source < FreeImage_GetPageCount(bitmap)))) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, target); BlockListIterator block_target = FreeImage_FindBlock(bitmap, source); header->m_blocks.insert(block_target, *block_source); header->m_blocks.erase(block_source); header->changed = TRUE; return TRUE; } } } return FALSE; } BOOL DLL_CALLCONV FreeImage_GetLockedPageNumbers(FIMULTIBITMAP *bitmap, int *pages, int *count) { if ((bitmap) && (count)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((pages == NULL) || (*count == 0)) { *count = (int)header->locked_pages.size(); } else { int c = 0; for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { pages[c] = i->second; c++; if (c == *count) { break; } } } return TRUE; } return FALSE; } // ===================================================================== // Memory IO Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_LoadMultiBitmapFromMemory(FREE_IMAGE_FORMAT fif, FIMEMORY *stream, int flags) { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { FIMULTIBITMAP *bitmap = new(std::nothrow) FIMULTIBITMAP; if (bitmap) { MULTIBITMAPHEADER *header = new(std::nothrow) MULTIBITMAPHEADER; if (header) { header->node = node; header->fif = fif; SetMemoryIO(&header->io); header->handle = (fi_handle)stream; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header; // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default return bitmap; } delete bitmap; } } } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToMemory(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FIMEMORY *stream, int flags) { if (stream && stream->data) { FreeImageIO io; SetMemoryIO(&io); return FreeImage_SaveMultiBitmapToHandle(fif, bitmap, &io, (fi_handle)stream, flags); } return FALSE; }
27.364143
168
0.613722
aws4y
4f261cdeb0b5320194a0a3c3fa545dbdb6fcccbb
1,582
hpp
C++
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
#ifndef CLI_ARGS_HPP #define CLI_ARGS_HPP #include "connection.hpp" #include "routing.hpp" #include <optional> #include <string> /** * These are the program arguments. In this single class we store all * information passed at the command line. */ struct cli_args { /// ----------------------------------------------------------------- /// The network and routing options /// ----------------------------------------------------------------- /// The network file name. std::string net; /// The number of units. int units; // Use the generic Dijkstra search. bool gd = false; // Use the brute force search. bool bf = false; // Use the edge exclusion search. bool ee = false; /// ----------------------------------------------------------------- /// The traffic options /// ----------------------------------------------------------------- /// The mean client arrival time. double mcat; /// The offered load. double ol; /// The mean holding time. double mht; /// The mean number of units. double mnu; /// ----------------------------------------------------------------- /// The simulation options /// ----------------------------------------------------------------- /// The seed int seed; /// The population name. std::string population; /// The kickoff time for stats. double kickoff; /// The limit on the simulation time. double sim_time; }; /** * This function parses the command-line arguments. */ cli_args process_cli_args(int argc, const char* argv[]); #endif /* CLI_ARGS_HPP */
21.093333
71
0.484829
iszczesniak
4f26672294b4cc622c3bd4f079929719d6af4fc7
7,896
cpp
C++
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
21
2017-10-06T05:05:05.000Z
2022-03-13T15:39:20.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
1
2017-03-23T00:27:24.000Z
2017-03-23T00:27:24.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
4
2018-01-09T15:49:58.000Z
2022-03-13T15:39:27.000Z
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2013 @author Azzam Haidar @generated from zgetrs_nopiv_batched.cpp normal z -> d, Fri Jan 30 19:00:19 2015 */ #include "common_magma.h" #include "batched_kernel_param.h" /** Purpose ------- Solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by DGETRF_GPU. Arguments --------- @param[in] trans magma_trans_t Specifies the form of the system of equations: - = MagmaNoTrans: A * X = B (No transpose) - = MagmaTrans: A**T * X = B (Transpose) - = MagmaConjTrans: A**H * X = B (Conjugate transpose) @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in] nrhs INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. @param[in] dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by DGETRF_GPU. @param[in] ldda INTEGER The leading dimension of the array A. LDA >= max(1,N). @param[in] ipiv INTEGER array, dimension (N) The pivot indices from DGETRF; for 1 <= i <= N, row i of the matrix was interchanged with row IPIV(i). @param[in,out] dB DOUBLE_PRECISION array on the GPU, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. @param[in] lddb INTEGER The leading dimension of the array B. LDB >= max(1,N). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value @ingroup magma_dgesv_comp ********************************************************************/ extern "C" magma_int_t magma_dgetrs_nopiv_batched( magma_trans_t trans, magma_int_t n, magma_int_t nrhs, double **dA_array, magma_int_t ldda, double **dB_array, magma_int_t lddb, magma_int_t *info_array, magma_int_t batchCount, magma_queue_t queue) { /* Local variables */ magma_int_t notran = (trans == MagmaNoTrans); magma_int_t info = 0; if ( (! notran) && (trans != MagmaTrans) && (trans != MagmaConjTrans) ) { info = -1; } else if (n < 0) { info = -2; } else if (nrhs < 0) { info = -3; } else if (ldda < max(1,n)) { info = -5; } else if (lddb < max(1,n)) { info = -8; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* Quick return if possible */ if (n == 0 || nrhs == 0) { return info; } double **dA_displ = NULL; double **dB_displ = NULL; double **dW1_displ = NULL; double **dW2_displ = NULL; double **dW3_displ = NULL; double **dW4_displ = NULL; double **dinvA_array = NULL; double **dwork_array = NULL; magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ)); magma_malloc((void**)&dB_displ, batchCount * sizeof(*dB_displ)); magma_malloc((void**)&dW1_displ, batchCount * sizeof(*dW1_displ)); magma_malloc((void**)&dW2_displ, batchCount * sizeof(*dW2_displ)); magma_malloc((void**)&dW3_displ, batchCount * sizeof(*dW3_displ)); magma_malloc((void**)&dW4_displ, batchCount * sizeof(*dW4_displ)); magma_malloc((void**)&dinvA_array, batchCount * sizeof(*dinvA_array)); magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array)); magma_int_t invA_msize = ((n+TRI_NB-1)/TRI_NB)*TRI_NB*TRI_NB; magma_int_t dwork_msize = n*nrhs; double* dinvA = NULL; double* dwork = NULL;// dinvA and dwork are workspace in dtrsm magma_dmalloc( &dinvA, invA_msize * batchCount); magma_dmalloc( &dwork, dwork_msize * batchCount ); /* check allocation */ if ( dW1_displ == NULL || dW2_displ == NULL || dW3_displ == NULL || dW4_displ == NULL || dinvA_array == NULL || dwork_array == NULL || dinvA == NULL || dwork == NULL || dA_displ == NULL || dB_displ == NULL ) { magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla( __func__, -(info) ); return info; } magmablas_dlaset_q(MagmaFull, invA_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dinvA, invA_msize, queue); magmablas_dlaset_q(MagmaFull, dwork_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dwork, dwork_msize, queue); dset_pointer(dwork_array, dwork, n, 0, 0, dwork_msize, batchCount, queue); dset_pointer(dinvA_array, dinvA, TRI_NB, 0, 0, invA_msize, batchCount, queue); magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount, queue); magma_ddisplace_pointers(dB_displ, dB_array, lddb, 0, 0, batchCount, queue); magma_queue_t cstream; magmablasGetKernelStream(&cstream); //printf(" I am after malloc getri\n"); if (notran) { // solve dwork = L^-1 * NRHS magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve X = U^-1 * dwork magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } else{ /* Solve A**T * X = B or A**H * X = B. */ // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, trans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, trans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } magma_queue_sync(cstream); magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); return info; }
33.457627
114
0.556864
shengren
4f272caf25db73404a223d05b9618e45e9ad4f6c
983
cpp
C++
src/point.cpp
ASjet/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
1
2020-05-30T07:15:18.000Z
2020-05-30T07:15:18.000Z
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "point.h" #include "cursor.h" //////////////////////////////////////////////////////////////////////////////// Point Point::setPos(int px, int py) { x = px; y = py; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::print(string str) const { SetCursorPosition(x, y); std::cout << str; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::clear(void) const { SetCursorPosition(x, y); std::cout << " "; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::setCursorHere(void) const { SetCursorPosition(x, y); return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::move(int movement_x, int movement_y) { x += movement_x; y += movement_y; return *this; }
25.868421
80
0.364191
ASjet
4f2acf2ee7baf76ba9ec40965975179cc65cc4c0
14,878
cpp
C++
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "InstructionWalker.h" #include "BasicBlock.h" #include "CompilationError.h" #include "Method.h" #include "analysis/ControlFlowGraph.h" using namespace vc4c; const InstructionWalker tombstone_traits<InstructionWalker>::tombstone; bool InstructionVisitor::visit(const InstructionWalker& start) const { InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(followJumps && it.get<intermediate::Branch>()) { intermediate::Branch* jump = it.get<intermediate::Branch>(); auto jumpIt = it; for(auto target : jump->getTargetLabels()) { if(auto nextBlock = it.getBasicBlock()->method.findBasicBlock(target)) { bool cont = visit(nextBlock->walk()); if(!cont) return false; } } if(jump->isUnconditional()) // the control-flow always jumps, destination is already processed return true; // handle either-or-jumps, check previous instruction intermediate::Branch* prevJump = it.copy().previousInBlock().get<intermediate::Branch>(); auto prevJumpIt = it; if(prevJump != nullptr && jump->branchCondition.isInversionOf(prevJump->branchCondition)) { auto lastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(jumpIt); auto secondLastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(prevJumpIt); if(lastBranchCond == secondLastBranchCond) // the branches are only guaranteed to cover all cases if they refer to the same branch // condition return true; } } if(stopAtBlock) { it.nextInBlock(); if(it.isEndOfBlock()) return true; continue; } else { it.nextInMethod(); if(it.isEndOfMethod()) return true; continue; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } bool InstructionVisitor::visitReverse(const InstructionWalker& start, analysis::ControlFlowGraph* blockGraph) const { // FIXME has problems with instructionwalkers freed in Method::cleanEmptyInstructions() (e.g. TestEmulator) InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(!it.isStartOfBlock()) { it.previousInBlock(); continue; } else if(stopAtBlock) { return true; } else if(!followJumps) { it.previousInMethod(); continue; } else // start of block and follow jumps -> follow jumps backwards { bool continueBranches = true; if(blockGraph != nullptr) { // use pre-calculated graph of basic blocks blockGraph->assertNode(it.getBasicBlock()) .forAllIncomingEdges([&continueBranches, this, blockGraph]( const analysis::CFGNode& node, const analysis::CFGEdge& edge) -> bool { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(edge.data.getPredecessor(node.key), blockGraph); return true; }); } else { // re-calculate predecessor blocks it.getBasicBlock()->forPredecessors([&continueBranches, this](InstructionWalker it) -> void { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(it); }); } return continueBranches; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } InstructionWalker::InstructionWalker() : basicBlock(nullptr), pos(nullptr) {} InstructionWalker::InstructionWalker(BasicBlock* basicBlock, intermediate::InstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } BasicBlock* InstructionWalker::getBasicBlock() { return basicBlock; } const BasicBlock* InstructionWalker::getBasicBlock() const { return basicBlock; } InstructionWalker& InstructionWalker::nextInBlock() { ++pos; return *this; } InstructionWalker& InstructionWalker::previousInBlock() { --pos; return *this; } InstructionWalker& InstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } InstructionWalker& InstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } InstructionWalker InstructionWalker::copy() const { return InstructionWalker(basicBlock, pos); } bool InstructionWalker::operator==(const InstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool InstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; if(!isEndOfBlock()) return false; const auto& lastBlock = *(--basicBlock->method.end()); return &lastBlock == basicBlock; } bool InstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool InstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool InstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } static inline void throwOnEnd(bool isEnd) { if(isEnd) throw CompilationError(CompilationStep::GENERAL, "End of method or block reached!"); } intermediate::IntermediateInstruction* InstructionWalker::get() { throwOnEnd(isEndOfBlock()); return (*pos).get(); } const intermediate::IntermediateInstruction* InstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); } intermediate::IntermediateInstruction* InstructionWalker::release() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); return tmp.release(); } return (*pos).release(); } InstructionWalker& InstructionWalker::reset(intermediate::IntermediateInstruction* instr) { throwOnEnd(isEndOfBlock()); if(dynamic_cast<intermediate::BranchLabel*>(instr) != dynamic_cast<intermediate::BranchLabel*>((*pos).get())) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); // if we reset the label with another label, the CFG dos not change if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } (*pos).reset(instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } InstructionWalker& InstructionWalker::erase() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } pos = basicBlock->instructions.erase(pos); return *this; } InstructionWalker& InstructionWalker::safeErase() { if(!isEndOfBlock() && get() && get()->hasDecoration(intermediate::InstructionDecorations::MANDATORY_DELAY)) { reset((new intermediate::Nop(intermediate::DelayType::WAIT_REGISTER)) ->addDecorations(intermediate::InstructionDecorations::MANDATORY_DELAY)); return nextInBlock(); } return erase(); } InstructionWalker& InstructionWalker::emplace(intermediate::IntermediateInstruction* instr) { if(isStartOfBlock()) throw CompilationError( CompilationStep::GENERAL, "Can't emplace at the start of a basic block", instr->to_string()); if(basicBlock == nullptr) throw CompilationError( CompilationStep::GENERAL, "Can't emplace into an iterator which is not associated with a basic block"); if(dynamic_cast<intermediate::BranchLabel*>(instr) != nullptr) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); pos = basicBlock->instructions.emplace(pos, instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } ConstInstructionWalker::ConstInstructionWalker() : basicBlock(nullptr), pos(nullptr) {} ConstInstructionWalker::ConstInstructionWalker(InstructionWalker it) : basicBlock(it.basicBlock), pos(it.pos) {} ConstInstructionWalker::ConstInstructionWalker( const BasicBlock* basicBlock, intermediate::ConstInstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } const BasicBlock* ConstInstructionWalker::getBasicBlock() const { return basicBlock; } ConstInstructionWalker& ConstInstructionWalker::nextInBlock() { ++pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::previousInBlock() { --pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } bool InstructionWalker::replaceValueInBlock( const Value& oldValue, const Value& newValue, LocalUse::Type type, bool forward, bool stopWhenWritten) { bool replaced = false; auto it = copy(); if(forward) { it.nextInBlock(); while(!it.isEndOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.nextInBlock(); } } else { it.previousInBlock(); while(!it.isStartOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.previousInBlock(); } } return replaced; } ConstInstructionWalker& ConstInstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } ConstInstructionWalker ConstInstructionWalker::copy() const { return ConstInstructionWalker(basicBlock, pos); } bool ConstInstructionWalker::operator==(const ConstInstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool ConstInstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; const auto& lastBlock = *(--basicBlock->method.end()); return isEndOfBlock() && &lastBlock == basicBlock; } bool ConstInstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool ConstInstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool ConstInstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } const intermediate::IntermediateInstruction* ConstInstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); }
31.190776
120
0.617556
Mookel
4f2c7c45a4c6a2a344655c2da31ef6e080d04499
2,810
hpp
C++
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
82
2015-01-04T21:11:35.000Z
2015-06-08T17:53:49.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
428
2015-01-01T18:42:04.000Z
2015-06-08T16:08:08.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
53
2015-01-05T02:31:30.000Z
2015-06-05T18:50:57.000Z
#pragma once #include <bts/blockchain/graphene.hpp> #include <bts/blockchain/types.hpp> #include <fc/time.hpp> namespace bts { namespace blockchain { struct snapshot_summary { uint64_t num_balance_owners = 0; uint64_t num_asset_balances = 0; uint64_t num_vesting_balances = 0; uint64_t num_canceled_asks = 0; uint64_t num_canceled_bids = 0; uint64_t num_canceled_shorts = 0; uint64_t num_account_names = 0; uint64_t num_witnesses = 0; uint64_t num_workers = 0; uint64_t num_mias = 0; uint64_t num_collateral_positions = 0; uint64_t num_uias = 0; }; struct snapshot_vesting_balance { time_point_sec start_time; uint32_t duration_seconds = 0; share_type original_balance = 0; share_type current_balance = 0; }; struct snapshot_balance { map<string, share_type> assets; optional<snapshot_vesting_balance> vesting; }; struct snapshot_account { uint32_t id; time_point_sec timestamp; public_key_type owner_key; public_key_type active_key; optional<public_key_type> signing_key; optional<share_type> daily_pay; }; struct snapshot_debt { share_type collateral = 0; share_type debt = 0; }; struct snapshot_asset { uint32_t id; string owner; string description; uint64_t precision = 1; share_type max_supply = 0; share_type collected_fees = 0; map<address, snapshot_debt> debts; }; struct snapshot_state { signed_block_header head_block; share_type max_core_supply = 0; snapshot_summary summary; map<address, snapshot_balance> balances; map<string, snapshot_account> accounts; map<string, snapshot_asset> assets; }; } } // bts::blockchain FC_REFLECT( bts::blockchain::snapshot_summary, (num_balance_owners)(num_asset_balances)(num_vesting_balances) (num_canceled_asks)(num_canceled_bids)(num_canceled_shorts) (num_account_names)(num_witnesses)(num_workers) (num_mias)(num_collateral_positions)(num_uias)) FC_REFLECT( bts::blockchain::snapshot_vesting_balance, (start_time)(duration_seconds)(original_balance)(current_balance) ) FC_REFLECT( bts::blockchain::snapshot_balance, (assets)(vesting) ) FC_REFLECT( bts::blockchain::snapshot_account, (id)(timestamp)(owner_key)(active_key)(signing_key)(daily_pay) ) FC_REFLECT( bts::blockchain::snapshot_debt, (collateral)(debt) ) FC_REFLECT( bts::blockchain::snapshot_asset, (id)(owner)(description)(precision)(max_supply)(collected_fees)(debts) ) FC_REFLECT( bts::blockchain::snapshot_state, (head_block)(max_core_supply)(summary)(balances)(accounts)(assets) )
29.893617
122
0.690036
jasonqin
4f2d49c583b36f4b94fc624a8c5079ed09d03b47
1,030
cpp
C++
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:27:10.000Z
2020-05-06T16:27:14.000Z
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
null
null
null
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:12:41.000Z
2021-01-20T15:52:52.000Z
#include <iostream> #include <windows.h> #include <vector> #include <string> using namespace std; bool pentagonal_get(int num,vector<int> &vect) { int fx_i; if (num<=0 || num>1024) { return false; } else { for (int i = 1; i <= num; i++) { fx_i = i*(i*3-1)/2; vect.push_back(fx_i); } } return true; } bool vect_printf(vector<int> &vects,string type_str) { cout<<"The type "<<type_str<<" and the pentagonal is:"<<endl; for (int i = 0; i < vects.size(); i++) { cout<<vects[i]<<" "; } cout<<endl<<endl; return true; } int main(void) { vector<int> vect; bool res; int num; cout<<"please enter num"<<endl<<endl; while (cin>>num) { res = pentagonal_get(num,vect); if (res == false) { cout<<"overflow"<<endl; } else { vect_printf(vect,"int"); } vector<int>().swap(vect); } return 0; }
16.349206
65
0.484466
Helio452b
4f303e8177e6e2c2ab36a9127a8c223d00524ef3
1,038
cpp
C++
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
755
2019-07-10T01:26:39.000Z
2022-03-31T12:43:19.000Z
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
111
2020-02-28T23:30:10.000Z
2022-01-18T13:57:30.000Z
Sources/Overload/OvCore/src/OvCore/ECS/Components/CDirectionalLight.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
97
2019-11-06T15:19:56.000Z
2022-03-25T08:40:04.000Z
/** * @project: Overload * @author: Overload Tech. * @licence: MIT */ #include <OvUI/Widgets/Texts/Text.h> #include <OvUI/Widgets/Drags/DragFloat.h> #include <OvUI/Widgets/Selection/ColorEdit.h> #include "OvCore/ECS/Actor.h" #include "OvCore/ECS/Components/CDirectionalLight.h" OvCore::ECS::Components::CDirectionalLight::CDirectionalLight(ECS::Actor & p_owner) : CLight(p_owner) { m_data.type = static_cast<float>(OvRendering::Entities::Light::Type::DIRECTIONAL); } std::string OvCore::ECS::Components::CDirectionalLight::GetName() { return "Directional Light"; } void OvCore::ECS::Components::CDirectionalLight::OnSerialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node) { CLight::OnSerialize(p_doc, p_node); } void OvCore::ECS::Components::CDirectionalLight::OnDeserialize(tinyxml2::XMLDocument & p_doc, tinyxml2::XMLNode * p_node) { CLight::OnDeserialize(p_doc, p_node); } void OvCore::ECS::Components::CDirectionalLight::OnInspector(OvUI::Internal::WidgetContainer& p_root) { CLight::OnInspector(p_root); }
25.95
121
0.757225
kmqwerty
4f32cec6c164bf925e351ea56d5c1a7e66213368
7,791
cpp
C++
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
clients/common/rocsparse_matrix_factory_laplace3d.cpp
xupinjie/rocSPARSE
5583492046ece092900f815d76fe98dd32cb8d36
[ "MIT" ]
null
null
null
/*! \file */ /* ************************************************************************ * Copyright (c) 2021 Advanced Micro Devices, Inc. * * 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. * * ************************************************************************ */ #include "rocsparse_init.hpp" #include "rocsparse_matrix_utils.hpp" #include "rocsparse_matrix_factory_laplace3d.hpp" template <typename T, typename I, typename J> rocsparse_matrix_factory_laplace3d<T, I, J>::rocsparse_matrix_factory_laplace3d(J dimx, J dimy, J dimz) : m_dimx(dimx) , m_dimy(dimy) , m_dimz(dimz){}; template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_csr(std::vector<I>& csr_row_ptr, std::vector<J>& csr_col_ind, std::vector<T>& csr_val, J& M, J& N, I& nnz, rocsparse_index_base base, rocsparse_matrix_type matrix_type, rocsparse_fill_mode uplo) { switch(matrix_type) { case rocsparse_matrix_type_symmetric: case rocsparse_matrix_type_hermitian: case rocsparse_matrix_type_triangular: { std::vector<I> ptr; std::vector<J> ind; std::vector<T> val; rocsparse_init_csr_laplace3d( ptr, ind, val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); rocsparse_matrix_utils::host_csrtri(ptr.data(), ind.data(), val.data(), csr_row_ptr, csr_col_ind, csr_val, M, N, nnz, base, uplo); break; } case rocsparse_matrix_type_general: { rocsparse_init_csr_laplace3d(csr_row_ptr, csr_col_ind, csr_val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); break; } } } template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_coo(std::vector<I>& coo_row_ind, std::vector<I>& coo_col_ind, std::vector<T>& coo_val, I& M, I& N, I& nnz, rocsparse_index_base base) { rocsparse_init_coo_laplace3d(coo_row_ind, coo_col_ind, coo_val, this->m_dimx, this->m_dimy, this->m_dimz, M, N, nnz, base); } template <typename T, typename I, typename J> void rocsparse_matrix_factory_laplace3d<T, I, J>::init_gebsr(std::vector<I>& bsr_row_ptr, std::vector<J>& bsr_col_ind, std::vector<T>& bsr_val, rocsparse_direction dirb, J& Mb, J& Nb, I& nnzb, J& row_block_dim, J& col_block_dim, rocsparse_index_base base) { rocsparse_init_gebsr_laplace3d(bsr_row_ptr, bsr_col_ind, bsr_val, this->m_dimx, this->m_dimy, this->m_dimz, Mb, Nb, nnzb, row_block_dim, col_block_dim, base); } template struct rocsparse_matrix_factory_laplace3d<float, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<float, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<float, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<double, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<double, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<double, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_float_complex, int64_t, int64_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int32_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int64_t, int32_t>; template struct rocsparse_matrix_factory_laplace3d<rocsparse_double_complex, int64_t, int64_t>;
50.590909
96
0.432294
xupinjie
4f3391c9e7767dbe626123133097b4296537b3e0
5,335
cpp
C++
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/builder/rnn.cpp
tzerrell/ngraph
b02b0812745ca1cb5f73d426ae9e0ad729eb0bbd
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 "ngraph/runtime/cpu/op/rnn.hpp" #include "ngraph/runtime/cpu/cpu_builder.hpp" #include "ngraph/runtime/cpu/mkldnn_invoke.hpp" #include "ngraph/runtime/cpu/mkldnn_utils.hpp" using namespace std; using namespace ngraph; namespace ngraph { namespace runtime { namespace cpu { template <> void Builder::BUILDER_DECL(ngraph::op::Rnn) { if (!runtime::cpu::mkldnn_utils::use_mkldnn_kernel(node)) { throw ngraph_error( "Rnn is supported only through MKLDNN and doesnt have reference " "INTERPRETER implementation"); } auto& functors = external_function->get_functors(); auto src_layer_buffer_index = external_function->get_buffer_index(args[0].get_name()); auto src_iter_buffer_index = external_function->get_buffer_index(args[1].get_name()); auto weights_layer_buffer_index = external_function->get_buffer_index(args[2].get_name()); auto weights_iter_buffer_index = external_function->get_buffer_index(args[3].get_name()); auto bias_buffer_index = external_function->get_buffer_index(args[4].get_name()); auto dst_layer_buffer_index = external_function->get_buffer_index(out[0].get_name()); auto dst_iter_buffer_index = external_function->get_buffer_index(out[1].get_name()); auto& mkldnn_emitter = external_function->get_mkldnn_emitter(); auto rnn_desc = mkldnn_emitter->get_rnn_forward_desc<ngraph::op::Rnn>(node, args, out); // Rnn needs 9 primitives: src_layer, src_iter, weights_layer, weights_iter, bias, // dst_layer, dst_iter, workspace, and rnn_forward. // It needs a new workspace. auto rnn_index = mkldnn_emitter->reserve_primitive_space(9, true /* new workspace */); auto& deps = mkldnn_emitter->get_primitive_deps(rnn_index); auto functor = [&, rnn_desc, rnn_index, src_layer_buffer_index, src_iter_buffer_index, weights_layer_buffer_index, weights_iter_buffer_index, bias_buffer_index, dst_layer_buffer_index, dst_iter_buffer_index](CPURuntimeContext* ctx, CPUExecutionContext* ectx) { if (ctx->first_iteration) { mkldnn_emitter->build_rnn_forward(ctx->mkldnn_primitives, ctx->mkldnn_workspaces, rnn_desc, deps, rnn_index); } cpu::mkldnn_utils::set_memory_ptr( ctx, deps[0], ctx->buffer_data[src_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[1], ctx->buffer_data[src_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[2], ctx->buffer_data[weights_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[3], ctx->buffer_data[weights_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[4], ctx->buffer_data[bias_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[5], ctx->buffer_data[dst_layer_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[6], ctx->buffer_data[dst_iter_buffer_index]); cpu::mkldnn_utils::set_memory_ptr( ctx, deps[7], ctx->mkldnn_workspaces[deps[8]]); cpu::mkldnn_utils::mkldnn_invoke_primitive(ctx, rnn_index); }; functors.emplace_back(functor); } REGISTER_OP_BUILDER(Rnn); } } }
48.944954
100
0.519213
tzerrell
4f3478b4fdaa44bc561c7d3648dc2ad4f6e3f4e4
5,354
cc
C++
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
source/common/http/filter/ratelimit.cc
vanillahsu/envoy
49dc064843035ff980e1ed1d1a7f1574b66f7305
[ "Apache-2.0" ]
null
null
null
#include "common/http/filter/ratelimit.h" #include "envoy/http/codes.h" #include "common/common/assert.h" #include "common/common/empty_string.h" #include "common/common/enum_to_int.h" #include "common/http/codes.h" #include "common/router/config_impl.h" namespace Http { namespace RateLimit { namespace { static const Http::HeaderMap* getTooManyRequestsHeader() { static const Http::HeaderMap* header_map = new Http::HeaderMapImpl{ {Http::Headers::get().Status, std::to_string(enumToInt(Code::TooManyRequests))}}; return header_map; } } // namespace; void Filter::initiateCall(const HeaderMap& headers) { bool is_internal_request = headers.EnvoyInternalRequest() && (headers.EnvoyInternalRequest()->value() == "true"); if ((is_internal_request && config_->requestType() == FilterRequestType::External) || (!is_internal_request && config_->requestType() == FilterRequestType::Internal)) { return; } Router::RouteConstSharedPtr route = callbacks_->route(); if (!route || !route->routeEntry()) { return; } const Router::RouteEntry* route_entry = route->routeEntry(); Upstream::ThreadLocalCluster* cluster = config_->cm().get(route_entry->clusterName()); if (!cluster) { return; } cluster_ = cluster->info(); std::vector<::RateLimit::Descriptor> descriptors; // Get all applicable rate limit policy entries for the route. populateRateLimitDescriptors(route_entry->rateLimitPolicy(), descriptors, route_entry, headers); // Get all applicable rate limit policy entries for the virtual host. populateRateLimitDescriptors(route_entry->virtualHost().rateLimitPolicy(), descriptors, route_entry, headers); if (!descriptors.empty()) { state_ = State::Calling; initiating_call_ = true; client_->limit( *this, config_->domain(), descriptors, {headers.RequestId() ? headers.RequestId()->value().c_str() : EMPTY_STRING, headers.OtSpanContext() ? headers.OtSpanContext()->value().c_str() : EMPTY_STRING}); initiating_call_ = false; } } FilterHeadersStatus Filter::decodeHeaders(HeaderMap& headers, bool) { if (!config_->runtime().snapshot().featureEnabled("ratelimit.http_filter_enabled", 100)) { return FilterHeadersStatus::Continue; } initiateCall(headers); return (state_ == State::Calling || state_ == State::Responded) ? FilterHeadersStatus::StopIteration : FilterHeadersStatus::Continue; } FilterDataStatus Filter::decodeData(Buffer::Instance&, bool) { ASSERT(state_ != State::Responded); return state_ == State::Calling ? FilterDataStatus::StopIterationAndBuffer : FilterDataStatus::Continue; } FilterTrailersStatus Filter::decodeTrailers(HeaderMap&) { ASSERT(state_ != State::Responded); return state_ == State::Calling ? FilterTrailersStatus::StopIteration : FilterTrailersStatus::Continue; } void Filter::setDecoderFilterCallbacks(StreamDecoderFilterCallbacks& callbacks) { callbacks_ = &callbacks; callbacks.addResetStreamCallback([this]() -> void { if (state_ == State::Calling) { client_->cancel(); } }); } void Filter::complete(::RateLimit::LimitStatus status) { state_ = State::Complete; switch (status) { case ::RateLimit::LimitStatus::OK: cluster_->statsScope().counter("ratelimit.ok").inc(); break; case ::RateLimit::LimitStatus::Error: cluster_->statsScope().counter("ratelimit.error").inc(); break; case ::RateLimit::LimitStatus::OverLimit: cluster_->statsScope().counter("ratelimit.over_limit").inc(); Http::CodeUtility::ResponseStatInfo info{ config_->globalStore(), cluster_->statsScope(), EMPTY_STRING, *getTooManyRequestsHeader(), true, EMPTY_STRING, EMPTY_STRING, EMPTY_STRING, EMPTY_STRING, false}; Http::CodeUtility::chargeResponseStat(info); break; } if (status == ::RateLimit::LimitStatus::OverLimit && config_->runtime().snapshot().featureEnabled("ratelimit.http_filter_enforcing", 100)) { state_ = State::Responded; Http::HeaderMapPtr response_headers{new HeaderMapImpl(*getTooManyRequestsHeader())}; callbacks_->encodeHeaders(std::move(response_headers), true); callbacks_->requestInfo().setResponseFlag(Http::AccessLog::ResponseFlag::RateLimited); } else if (!initiating_call_) { callbacks_->continueDecoding(); } } void Filter::populateRateLimitDescriptors(const Router::RateLimitPolicy& rate_limit_policy, std::vector<::RateLimit::Descriptor>& descriptors, const Router::RouteEntry* route_entry, const HeaderMap& headers) const { for (const Router::RateLimitPolicyEntry& rate_limit : rate_limit_policy.getApplicableRateLimit(config_->stage())) { const std::string& disable_key = rate_limit.disableKey(); if (!disable_key.empty() && !config_->runtime().snapshot().featureEnabled( fmt::format("ratelimit.{}.http_filter_enabled", disable_key), 100)) { continue; } rate_limit.populateDescriptors(*route_entry, descriptors, config_->localInfo().clusterName(), headers, callbacks_->downstreamAddress()); } } } // RateLimit } // Http
36.671233
98
0.683227
vanillahsu
4f34b190fc49b969608edc1c87f78451d9d24a15
319
cpp
C++
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Booking/bookingTest.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> class Test; class Test { public: static std::vector<const Test*> allData; Test() : data(3) { allData.push_back(this); } int data; }; int main() { Test test; std::cout << Test::allData.at(0)->data << std::endl; return 0; }
9.114286
54
0.54232
taku-xhift
4f387b63cad2886f2805f3d81d50cd69ff85cde2
9,276
cpp
C++
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
src/demos/vehicle/demo_DeformableSoil/demo_VEH_DeformableSoil.cpp
bluescarni/chrono
5804345dc23733196c6740afbc0c1432553dfb1d
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Demo code (advanced), about // // - using the SCM semi-empirical model for deformable soil // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/geometry/ChTriangleMeshConnected.h" #include "chrono/physics/ChLoadContainer.h" #include "chrono/physics/ChSystemSMC.h" #include "chrono/solver/ChSolverMINRES.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/SCMDeformableTerrain.h" using namespace chrono; using namespace chrono::irrlicht; using namespace irr; bool output = false; const std::string out_dir = GetChronoOutputPath() + "SCM_DEF_SOIL"; int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Global parameter for tire: double tire_rad = 0.8; double tire_vel_z0 = -3; ChVector<> tire_center(0, 0.02 + tire_rad, 0); double tire_w0 = tire_vel_z0 / tire_rad; // Create a Chrono::Engine physical system ChSystemSMC my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Deformable soil", core::dimension2d<u32>(1280, 720), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(1.0f, 1.4f, -1.2f), core::vector3df(0, (f32)tire_rad, 0)); application.AddLightWithShadow(core::vector3df(1.5f, 5.5f, -2.5f), core::vector3df(0, 0, 0), 3, 2.2, 7.2, 40, 512, video::SColorf(0.8f, 0.8f, 1.0f)); std::shared_ptr<ChBody> mtruss(new ChBody); mtruss->SetBodyFixed(true); my_system.Add(mtruss); // Initialize output if (output) { if (ChFileutils::MakeDirectory(out_dir.c_str()) < 0) { std::cout << "Error creating directory " << out_dir << std::endl; return 1; } } utils::CSV_writer csv(" "); // // CREATE A RIGID BODY WITH A MESH // std::shared_ptr<ChBody> mrigidbody(new ChBody); my_system.Add(mrigidbody); mrigidbody->SetMass(500); mrigidbody->SetInertiaXX(ChVector<>(20, 20, 20)); mrigidbody->SetPos(tire_center + ChVector<>(0, 0.3, 0)); auto trimesh = std::make_shared<geometry::ChTriangleMeshConnected>(); trimesh->LoadWavefrontMesh(GetChronoDataFile("tractor_wheel.obj")); std::shared_ptr<ChTriangleMeshShape> mrigidmesh(new ChTriangleMeshShape); mrigidmesh->SetMesh(trimesh); mrigidbody->AddAsset(mrigidmesh); mrigidbody->GetCollisionModel()->ClearModel(); mrigidbody->GetCollisionModel()->AddTriangleMesh(trimesh, false, false, VNULL, ChMatrix33<>(1), 0.01); mrigidbody->GetCollisionModel()->BuildModel(); mrigidbody->SetCollide(true); std::shared_ptr<ChColorAsset> mcol(new ChColorAsset); mcol->SetColor(ChColor(0.3f, 0.3f, 0.3f)); mrigidbody->AddAsset(mcol); std::shared_ptr<ChLinkEngine> myengine(new ChLinkEngine); myengine->Set_shaft_mode(ChLinkEngine::ENG_SHAFT_OLDHAM); myengine->Set_eng_mode(ChLinkEngine::ENG_MODE_ROTATION); myengine->Set_rot_funct(std::make_shared<ChFunction_Ramp>(0, CH_C_PI / 4.0)); // phase, speed myengine->Initialize(mrigidbody, mtruss, ChCoordsys<>(tire_center, Q_from_AngAxis(CH_C_PI_2, VECT_Y))); my_system.Add(myengine); // // THE DEFORMABLE TERRAIN // // Create the 'deformable terrain' object vehicle::SCMDeformableTerrain mterrain(&my_system); // Optionally, displace/tilt/rotate the terrain reference plane: mterrain.SetPlane(ChCoordsys<>(ChVector<>(0, 0, 0.5))); // Initialize the geometry of the soil: use either a regular grid: mterrain.Initialize(0.2, 1.5, 5, 20, 60); // or use a height map: ////mterrain.Initialize(vehicle::GetDataFile("terrain/height_maps/test64.bmp"), "test64", 1.6, 1.6, 0, 0.3); // Set the soil terramechanical parameters: mterrain.SetSoilParametersSCM(0.2e6, // Bekker Kphi 0, // Bekker Kc 1.1, // Bekker n exponent 0, // Mohr cohesive limit (Pa) 30, // Mohr friction limit (degrees) 0.01, // Janosi shear coefficient (m) 4e7, // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ); // LETE sand parameters ////mterrain.SetSoilParametersSCM(5301e3, // Bekker Kphi //// 102e3, // Bekker Kc //// 0.793, // Bekker n exponent //// 1.3e3, // Mohr cohesive limit (Pa) //// 31.1, // Mohr friction limit (degrees) //// 1.2e-2, // Janosi shear coefficient (m) //// 4e8, // Elastic stiffness (Pa/m), before plastic yield, must be > Kphi //// 3e4 // Damping (Pa s/m), proportional to negative vertical speed (optional) ////); mterrain.SetBulldozingFlow(true); // inflate soil at the border of the rut mterrain.SetBulldozingParameters( 55, // angle of friction for erosion of displaced material at the border of the rut 1, // displaced material vs downward pressed material. 5, // number of erosion refinements per timestep 10); // number of concentric vertex selections subject to erosion // Turn on the automatic level of detail refinement, so a coarse terrain mesh // is automatically improved by adding more points under the wheel contact patch: mterrain.SetAutomaticRefinement(true); mterrain.SetAutomaticRefinementResolution(0.04); // Set some visualization parameters: either with a texture, or with falsecolor plot, etc. ////mterrain.SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16); mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE, 0, 30000.2); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_PRESSURE_YELD, 0, 30000.2); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE, 0, 0.15); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_PLASTIC, 0, 0.15); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_SINKAGE_ELASTIC, 0, 0.05); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_STEP_PLASTIC_FLOW, 0, 0.0001); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_ISLAND_ID, 0, 8); ////mterrain.SetPlotType(vehicle::SCMDeformableTerrain::PLOT_IS_TOUCHED, 0, 8); mterrain.GetMesh()->SetWireframe(true); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets application.AssetUpdateAll(); // Use shadows in realtime view application.AddShadowAll(); // ==IMPORTANT!== Mark completion of system construction my_system.SetupInitial(); // // THE SOFT-REAL-TIME CYCLE // /* // Change the timestepper to HHT: my_system.SetTimestepperType(ChTimestepper::Type::HHT); auto integrator = std::static_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper()); integrator->SetAlpha(-0.2); integrator->SetMaxiters(8); integrator->SetAbsTolerances(1e-05, 1.8e00); integrator->SetMode(ChTimestepperHHT::POSITION); integrator->SetModifiedNewton(true); integrator->SetScaling(true); integrator->SetVerbose(true); */ /* my_system.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT); */ application.SetTimestep(0.002); while (application.GetDevice()->run()) { if (output) { vehicle::TerrainForce frc = mterrain.GetContactForce(mrigidbody); csv << my_system.GetChTime() << frc.force << frc.moment << frc.point << std::endl; } application.BeginScene(); application.DrawAll(); application.DoStep(); ChIrrTools::drawColorbar(0, 30000, "Pressure yield [Pa]", application.GetDevice(), 1180); application.EndScene(); } if (output) { csv.write_to_file(out_dir + "/output.dat"); } return 0; }
41.596413
118
0.631738
bluescarni
4f3911284077eaa525ae693c116101bee6ac505a
2,675
cpp
C++
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
zhangning737/ogs
53a892f4ce2f133e4d00534d33ad4329e5c0ccb2
[ "BSD-4-Clause" ]
1
2021-06-25T13:43:06.000Z
2021-06-25T13:43:06.000Z
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
boyanmeng/ogs
8172d20e61ae6dad076b3cc064846db7ef622020
[ "BSD-4-Clause" ]
1
2019-08-09T12:13:22.000Z
2019-08-09T12:13:22.000Z
ProcessLib/SurfaceFlux/SurfaceFlux.cpp
zhangning737/ogs
53a892f4ce2f133e4d00534d33ad4329e5c0ccb2
[ "BSD-4-Clause" ]
null
null
null
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "SurfaceFlux.h" #include <cassert> #include "ProcessLib/Utils/CreateLocalAssemblers.h" namespace ProcessLib { SurfaceFlux::SurfaceFlux( MeshLib::Mesh& boundary_mesh, std::size_t bulk_property_number_of_components, unsigned const integration_order) { DBUG("Create local balance assemblers."); // Populate the vector of local assemblers. _local_assemblers.resize(boundary_mesh.getElements().size()); // needed to create dof table auto mesh_subset_all_nodes = std::make_unique<MeshLib::MeshSubset>( boundary_mesh, boundary_mesh.getNodes()); // Collect the mesh subsets in a vector. std::vector<MeshLib::MeshSubset> all_mesh_subsets; std::generate_n(std::back_inserter(all_mesh_subsets), bulk_property_number_of_components, [&]() { return *mesh_subset_all_nodes; }); // needed for creation of local assemblers auto dof_table = std::make_unique<NumLib::LocalToGlobalIndexMap const>( std::move(all_mesh_subsets), NumLib::ComponentOrder::BY_LOCATION); auto const bulk_element_ids = boundary_mesh.getProperties().template getPropertyVector<std::size_t>( "bulk_element_ids", MeshLib::MeshItemType::Cell, 1); auto const bulk_face_ids = boundary_mesh.getProperties().template getPropertyVector<std::size_t>( "bulk_face_ids", MeshLib::MeshItemType::Cell, 1); ProcessLib::createLocalAssemblers<SurfaceFluxLocalAssembler>( boundary_mesh.getDimension() + 1, // or bulk_mesh.getDimension()? boundary_mesh.getElements(), *dof_table, 1, _local_assemblers, boundary_mesh.isAxiallySymmetric(), integration_order, *bulk_element_ids, *bulk_face_ids); } void SurfaceFlux::integrate( std::vector<GlobalVector*> const& x, MeshLib::PropertyVector<double>& balance, double const t, MeshLib::Mesh const& bulk_mesh, std::vector<std::size_t> const& active_element_ids, std::function<Eigen::Vector3d( std::size_t const, MathLib::Point3d const&, double const, std::vector<GlobalVector*> const&)> const& getFlux) { DBUG("Integrate SurfaceFlux."); GlobalExecutor::executeSelectedMemberOnDereferenced( &SurfaceFluxLocalAssemblerInterface::integrate, _local_assemblers, active_element_ids, x, balance, t, bulk_mesh, getFlux); } } // namespace ProcessLib
36.148649
82
0.702804
zhangning737
4f396e14fec3b619ea47854dd842c7f67199e950
4,346
cc
C++
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
93
2016-09-28T12:32:05.000Z
2022-03-25T03:29:21.000Z
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
3
2016-08-30T04:15:23.000Z
2021-03-26T05:33:24.000Z
src/libdeltafs/mds_srv_test.cc
chuckcranor/deltafs
34c6b60e225c19b363aaafa7c755fd9ffea4ffba
[ "Xnet", "X11" ]
12
2016-10-24T20:03:08.000Z
2022-03-30T14:12:51.000Z
/* * Copyright (c) 2019 Carnegie Mellon University, * Copyright (c) 2019 Triad National Security, LLC, as operator of * Los Alamos National Laboratory. * * All rights reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. See the AUTHORS file for names of contributors. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include "mds_srv.h" #include "pdlfs-common/testharness.h" #include "pdlfs-common/testutil.h" namespace pdlfs { class ServerTest { private: std::string dbname_; MDSEnv mds_env_; MDS* mds_; MDB* mdb_; DB* db_; public: ServerTest() { Env* env = Env::Default(); dbname_ = test::PrepareTmpDir("mds_srv_test", env); DBOptions dbopts; dbopts.env = env; DestroyDB(dbname_, dbopts); dbopts.create_if_missing = true; ASSERT_OK(DB::Open(dbopts, dbname_, &db_)); MDBOptions mdbopts; mdbopts.db = db_; mdb_ = new MDB(mdbopts); mds_env_.env = env; MDSOptions mdsopts; mdsopts.mds_env = &mds_env_; mdsopts.mdb = mdb_; mds_ = MDS::Open(mdsopts); } ~ServerTest() { delete mds_; delete mdb_; delete db_; } static std::string NodeName(int i) { char tmp[50]; snprintf(tmp, sizeof(tmp), "node%d", i); return tmp; } // Return the ino of the node being searched, or "-err_code" on errors. int Fstat(int dir_ino, int nod_no) { MDS::FstatOptions options; options.dir_id = DirId(0, 0, dir_ino); std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::FstatRet ret; Status s = mds_->Fstat(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } // Return the ino of the newly created file, or "-err_code" on errors. int Mknod(int dir_ino, int nod_no) { MDS::FcreatOptions options; options.dir_id = DirId(0, 0, dir_ino); options.flags = O_EXCL; options.mode = ACCESSPERMS; options.uid = 0; options.gid = 0; std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::FcreatRet ret; Status s = mds_->Fcreat(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } int Mkdir(int dir_ino, int nod_no) { MDS::MkdirOptions options; options.dir_id = DirId(0, 0, dir_ino); options.flags = O_EXCL; options.mode = ACCESSPERMS; options.uid = 0; options.gid = 0; std::string name = NodeName(nod_no); options.name = name; std::string name_hash; DirIndex::PutHash(&name_hash, name); options.name_hash = name_hash; MDS::MkdirRet ret; Status s = mds_->Mkdir(options, &ret); if (s.ok()) { return static_cast<int>(ret.stat.InodeNo()); } else { return -1 * s.err_code(); } } int Listdir(int dir_ino) { MDS::ListdirOptions options; options.dir_id = DirId(0, 0, dir_ino); std::vector<std::string> names; MDS::ListdirRet ret; ret.names = &names; Status s = mds_->Listdir(options, &ret); if (s.ok()) { return names.size(); } else { return -1 * s.err_code(); } } }; TEST(ServerTest, StartStop) { // empty } TEST(ServerTest, Files) { int r1 = Fstat(0, 1); ASSERT_TRUE(r1 == -1 * Status::kNotFound); int r2 = Mknod(0, 1); ASSERT_TRUE(r2 > 0); int r3 = Fstat(0, 1); ASSERT_TRUE(r3 == r2); int r4 = Mknod(0, 1); ASSERT_TRUE(r4 == -1 * Status::kAlreadyExists); } TEST(ServerTest, Dirs) { int r1 = Fstat(0, 1); ASSERT_TRUE(r1 == -1 * Status::kNotFound); int r2 = Mkdir(0, 1); ASSERT_TRUE(r2 > 0); int r3 = Fstat(0, 1); ASSERT_TRUE(r3 == r2); int r4 = Mkdir(0, 1); ASSERT_TRUE(r4 == -1 * Status::kAlreadyExists); } TEST(ServerTest, Scan) { Mknod(0, 1); Mknod(0, 2); Mknod(0, 3); Mknod(0, 4); Mknod(0, 5); Mkdir(0, 6); Mkdir(0, 7); Mkdir(0, 8); Mkdir(0, 9); int r = Listdir(0); ASSERT_TRUE(r == 9); } } // namespace pdlfs int main(int argc, char* argv[]) { return ::pdlfs::test::RunAllTests(&argc, &argv); }
23.748634
77
0.617809
chuckcranor
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
53
Edit dataset card