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 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | 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 listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
562b25a64afde4a9b394ceca85f455b4793da1de | 24,899 | cpp | C++ | pmdb_python_interface.cpp | mariusei/pmdb | eeb56311765dee83bf49c99d5921e83f3f177ab8 | [
"BSD-3-Clause"
] | null | null | null | pmdb_python_interface.cpp | mariusei/pmdb | eeb56311765dee83bf49c99d5921e83f3f177ab8 | [
"BSD-3-Clause"
] | null | null | null | pmdb_python_interface.cpp | mariusei/pmdb | eeb56311765dee83bf49c99d5921e83f3f177ab8 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2015-2017, Intel Corporation
* Copyright 2018, Marius Berge Eide
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "pmdb_core.hpp"
using pmem::obj::pool;
/////// PYTHON EXTENSION ////////
/********************************************
*
* INIT_POP
* initializer
*
*******************************************/
bool init_pop(char* path, pool<pmem_queue> *pop)
{
// Database storage
if (file_exists(path) != 0) {
std::cerr << "File out not found, creating it... " << path << std::endl;
pop[0] = pool<pmem_queue>::create(
//path, "queue", PMEMOBJ_MIN_POOL, CREATE_MODE_RW);
path, "queue", 3*1024*1024*1024, CREATE_MODE_RW);
return true;
} else {
pop[0] = pool<pmem_queue>::open(path, "queue");
return false;
}
}
/********************************************
*
* INIT_PMDB
* dbinitializer
*
*******************************************/
PyObject* init_pmdb(PyObject *self, PyObject* args, PyObject *kwords)
{
// Input/save file name for database
static char *kwlist[] = {"path_in", "n_max", NULL};
std::cout << "init_pmdb" << std::endl;
PyObject *path_in_py;
char* path_in;
//PyObject *n_objects_in_py = nullptr;
int64_t n_objects_in = 0;
int64_t n_objects_found;
char* res_back;
PyObject *out;
pool<pmem_queue> pop;
PyArg_ParseTupleAndKeywords(args, kwords,
"s|l:init_pmdb", kwlist,
&path_in,
&n_objects_in
);
std::cout << "Path in was: " << path_in << std::endl;
std::cout << "Will now check if n elements in exist: " << n_objects_in << std::endl;
if(init_pop(path_in, &pop)) {
res_back = "STATUS_EMPTY";
} else {
res_back = "STATUS_OPEN_POTENTIALLY_FILLED";
}
// Now check the number of elements
n_objects_found = 0;
std::cout << "counting objects in list... from " << n_objects_found << std::endl;
auto q = pop.get_root();
n_objects_found = q->count();
std::cout << "found n objects: " << n_objects_found << " in total" << std::endl;
if (n_objects_found == 0) {
res_back = "STATUS_EMPTY";
} else if (n_objects_found < n_objects_in || n_objects_in == 0) {
res_back = "STATUS_NOT_FULL";
} else {
res_back = "STATUS_FULL";
}
// NOW: return a list!
//
//path_back_py = Py_BuildValue("s", res_back);
out = PyList_New(2);
PyList_SetItem(out, 0, PyLong_FromLong(n_objects_found));
PyList_SetItem(out, 1, Py_BuildValue("s", res_back));
pop.close();
return out;
error:
pop.close();
return Py_BuildValue("");
}
/********************************************
*
* INSERT
* inserter
*
*******************************************/
PyObject* insert(PyObject *self, PyObject *args, PyObject *kwords)
{
/* Inserts potentially a list of elements into the database
*/
static char *kwlist[] = {"path_in", "n_max",
"jobid", "job", "jobstage", "jobpath", "jobdatecommitted",
"jobtagged", NULL};
std::cout << "pmdb::insert" << std::endl;
// Input
char* path_in;
int64_t n_max = -1;
int64_t n_objects_found;
// Will be inserted in DB:
//int64_t jobid;
//char* job;
//int64_t jobstage;
//char* jobpath;
//char* jobdatecommitted;
// Accessing the elements of the Python lists instead
PyObject *jobid = nullptr;
PyObject *job = nullptr;
PyObject *jobstage = nullptr;
PyObject *jobpath = nullptr;
PyObject *jobdatecommitted = nullptr;
PyObject *jobtagged = nullptr;
char* status_out;
PyObject *status_out_py;
std::cerr << "\t Initialized " << std::endl;
PyArg_ParseTupleAndKeywords(args, kwords,
"sl|OOOOOO:insert", kwlist,
&path_in,
&n_max,
&jobid,
&job,
&jobstage,
&jobpath,
&jobdatecommitted,
&jobtagged
);
std::cerr << "\t Parsed input tuples " << std::endl;
//std::cout << "\t Found jobid: " << PyLong_AsLong(jobid) << " and date: " << PyBytes_AsString(jobdatecommitted) << std::endl;
if (jobpath) {
std::cerr << "\t Is jobjobpath not null? " << jobpath << std::endl;
}
if (jobdatecommitted) {
std::cerr << "\t Is jobdatecommitted null? " << jobdatecommitted << std::endl;
}
if (jobtagged) {
std::cerr << "\t Is jobtagged null? " << jobtagged << std::endl;
}
if (n_max < 0) {
return PyErr_Format(PyExc_AttributeError, "STATUS_FAILED_N_MAX_NOT_SPECIFIED");
} else if (!jobid && !job && !jobstage && !jobpath && !jobdatecommitted && !jobtagged) {
return PyErr_Format(PyExc_AttributeError, "STATUS_FAILED_SPECIFY_AT_LEAST_INPUT_FIELD");
}
std::cerr << "\t Connecting to pool " << std::endl;
pool<pmem_queue> pop;
if(init_pop(path_in, &pop)) {
status_out = "STATUS_EMPTY";
} else {
status_out = "STATUS_OPEN_POTENTIALLY_FILLED";
}
std::cerr << "\t Opened PM file " << std::endl;
if (status_out == "STATUS_EMPTY") {
// The database should have been initialized
status_out = "STATUS_FAILED_NOT_INITIALIZED";
status_out_py = Py_BuildValue("s", status_out);
return status_out_py;
}
std::cerr << "\t Checked status of file " << std::endl;
auto q = pop.get_root();
std::cerr << "\t Found root node " << std::endl;
n_objects_found = q->count();
std::cerr << "\t Found n objects " << n_objects_found << std::endl;
std::cerr << "\t Will add until " << n_max << std::endl;
// reset q
q = pop.get_root();
int64_t jobid_i;
char* job_i;
int64_t jobstage_i;
char* jobpath_i;
char* jobdatecommitted_i;
int64_t jobtagged_i;
// Insert all at once
if (n_objects_found < n_max) {
// All is set, push to list
std::cerr << "\t Pushing jobs..." << std::endl;
for (int i = 0; i < n_max-n_objects_found; i++) {
//if (i%(n_max/100) == 0) {
// std::cerr << i << std::endl;
//}
//std::cerr << i << std::endl;
if (jobid) {
//std::cerr << "jobid" << std::endl;
jobid_i = PyLong_AsLong(PyList_GetItem(jobid, i));
} else {
//std::cerr << "no jobid" << std::endl;
jobid_i = i;
}
if (job) {
//std::cerr << "job" << std::endl;
job_i = PyBytes_AsString(PyList_GetItem(job, i));
//std::cerr << "job ok" << std::endl;
} else {
//std::cerr << "no job" << std::endl;
jobid_i = NULL;
}
if (jobstage) {
//std::cerr << "jobstage" << std::endl;
jobstage_i = PyLong_AsLong(PyList_GetItem(jobstage, i));
//std::cerr << "jobstage ok" << std::endl;
} else {
//std::cerr << "no jobstage" << std::endl;
jobid_i = NULL;
}
if (jobpath) {
//std::cerr << "jobpath" << std::endl;
jobpath_i = PyBytes_AsString(PyList_GetItem(jobpath, i));
} else {
//std::cerr << "no jobpath" << std::endl;
jobid_i = NULL;
}
if (jobdatecommitted) {
//std::cerr << "datecommitted" << std::endl;
jobdatecommitted_i = PyBytes_AsString(PyList_GetItem(jobdatecommitted, i));
} else {
//std::cerr << "no datecommitted" << std::endl;
jobid_i = NULL;
}
if (jobtagged) {
//std::cerr << "datetagged" << std::endl;
jobtagged_i = PyLong_AsLong(PyList_GetItem(jobtagged, i));
} else {
//std::cerr << "no datetagged" << std::endl;
jobid_i = NULL;
}
//std::cerr << "\t Parsed data, sending to pmdb..." << std::endl;
q->push(pop,
jobid_i,
job_i,
jobstage_i,
jobpath_i,
jobdatecommitted_i,
jobtagged_i
// PyLong_AsLong(PyList_GetItem(jobid, i)),
// PyBytes_AsString(PyList_GetItem(job, i)),
// PyLong_AsLong(PyList_GetItem(jobstage, i)),
// PyBytes_AsString(PyList_GetItem(jobpath, i)),
// PyBytes_AsString(PyList_GetItem(jobdatecommitted, i))
);
}
status_out = "STATUS_INSERTED";
} else {
status_out = "STATUS_FAILED_TOO_MANY";
}
pop.close();
std::cerr << "\t Pushed data to list " << std::endl;
status_out_py = Py_BuildValue("s", status_out);
std::cerr << "\t Done with code " << status_out << std::endl;
error:
// Cleanup
Py_XDECREF(jobid);
Py_XDECREF(job);
Py_XDECREF(jobstage);
Py_XDECREF(jobpath);
Py_XDECREF(jobdatecommitted);
Py_XDECREF(jobtagged);
return status_out_py;
}
/********************************************
*
* GET
* getter
*
*******************************************/
PyObject* get(PyObject *self, PyObject *args)
{
/* Gets a single object,
* returns it as a Python list
*/
std::cout << "pmdb::get" << std::endl;
// Input
char* path_in;
int64_t n_max, index;
// These objects will be set and stored in a list
PyObject *jobid, *job, *jobstage, *jobpath, *jobdatecommitted;
PyObject *outlist = PyList_New(6);
char* status_out;
// Parse inputs
if (!PyArg_ParseTuple(args, "sll",
&path_in,
&n_max,
&index
)) {
return Py_BuildValue("");
// status_out = "STATUS_FAILED_INTERPRETATION";
}
pool<pmem_queue> pop;
if(init_pop(path_in, &pop)) {
status_out = "STATUS_EMPTY";
} else {
status_out = "STATUS_OPEN_POTENTIALLY_FILLED";
}
std::cout << "\t Opened PM file " << std::endl;
// reset q
auto q = pop.get_root();
// Retrieved object is a struct
entry_shared data = q->get(index);
std::cout << "\t Retrieved data, e.g. jobix " << data.jobid << " jobstage " << data.jobstage << " and job " << data.job << " ok." << std::endl;
// whose elements can be converted
// to populate our list
PyList_SetItem(outlist, 0, PyLong_FromLong(data.jobid));
PyList_SetItem(outlist, 1, PyBytes_FromString(data.job));
PyList_SetItem(outlist, 2, PyLong_FromLong(data.jobstage));
PyList_SetItem(outlist, 3, PyBytes_FromString(data.savepath));
PyList_SetItem(outlist, 4, PyBytes_FromString(data.datecommitted));
PyList_SetItem(outlist, 5, PyLong_FromLong(data.jobtagged));
pop.close();
std::cout << "\t Converted data" << std::endl;
return outlist;
}
PyObject* set_pyerr(const char* errstring, PyObject* element=NULL)
{
/* Raises exception with error string `errstring`,
* of type `exception` (e.g. PyValueError) and
* optionally returns a Python object `element`.
*/
PyObject* out = PyList_New(2);
PyObject* out1 = PyBytes_FromString(errstring);
PyList_SetItem(out, 0, out1 );
if (element) {
PyList_SetItem(out, 1, element);
} else {
PyObject* out2 = PyLong_FromLong(0);
PyList_SetItem(out, 1, out2);
}
return out;
}
/********************************************
*
* SET
* setter
*
*******************************************/
PyObject* set(PyObject *self, PyObject *args, PyObject *kwords)
{
/* Sets values to a single entry in the database
* returns status code
*/
std::cout << "pmdb::set" << std::endl;
// Input
char* path_in;
int64_t n_max, index;
// Potential input objects, read in as keywords
PyObject *jobid = nullptr; // this one must be set
PyObject *job = nullptr;
//PyObject *jobstage = nullptr;
PyObject *jobpath = nullptr;
PyObject *jobdatecommitted = nullptr;
//PyObject *jobtagged = nullptr;
static char *kwlist[] = {
"path_in", "n_max", "jobid", "job", "jobstage", "jobpath", "jobdatecommitted", "jobtagged", NULL};
// Will be parsed into these:
int64_t jobid_loc = NULL;
char* job_loc = nullptr;
int64_t jobstage_loc = -1;
char* jobpath_loc = nullptr;
char* jobdatecommitted_loc = nullptr;
int64_t jobtagged_loc = -1;
char* status_out;
PyObject *status_out_py;
std::cout << "\t Initialized " << std::endl;
PyArg_ParseTupleAndKeywords(args, kwords,
"sll|OlOOl:set", kwlist,
&path_in,
&n_max,
&jobid_loc,
&job,
&jobstage_loc,
&jobpath,
&jobdatecommitted,
&jobtagged_loc
);
// Exit if we failed:
if (jobid_loc < 0) {
std::cerr << "fail: jobid: " << jobid_loc << std::endl;
status_out = "STATUS_FAILED_SPECIFIY_JOBID";
return PyErr_Format(PyExc_AttributeError, status_out);
} else if (job == Py_None
&& jobstage_loc == -1
&& jobpath == Py_None
&& jobdatecommitted == Py_None
&& jobtagged_loc == -1
) {
status_out = "STATUS_FAILED_SPECIFY_ONE_OR_MORE_FIELDS";
return PyErr_Format(PyExc_ValueError, status_out);
//} else if (PyLong_AsLong(jobid) > n_max) {
}
//else if (jobid > n_max) {
// status_out == "STATUS_INDEX_OUT_OF_BOUNDS";
// return PyErr_Format(PyExc_IndexError, status_out);
//}
// Connect to persistent memory
pool<pmem_queue> pop;
if(init_pop(path_in, &pop)) {
status_out = "STATUS_EMPTY";
} else {
status_out = "STATUS_OPEN_POTENTIALLY_FILLED";
}
//std::cerr << "\t Opened PM file " << std::endl;
// reset q
auto q = pop.get_root();
//std::cerr << "\t GOT ROOT" << std::endl;
// Set the entries of the index that are not null
//jobid_loc = PyLong_AsLong(jobid);
if (job != Py_None) {
//std::cerr << "\t job" << std::endl;
job_loc = PyBytes_AsString(job);
} else {
job_loc = NULL;
}
//if (jobstage != Py_None) {
// std::cerr << "\t jobstage" << std::endl;
// jobstage_loc = PyLong_AsLong(jobstage);
//} else {
// jobstage_loc = NULL;
//}
if (jobpath != Py_None) {
//std::cerr << "\t jobpath" << std::endl;
jobpath_loc = PyBytes_AsString(jobpath);
} else {
jobpath_loc = NULL;
}
if (jobdatecommitted != Py_None) {
//std::cerr << "\t jobdatecommitted" << std::endl;
jobdatecommitted_loc = PyBytes_AsString(jobdatecommitted);
} else {
jobdatecommitted_loc = NULL;
}
//if (jobtagged != Py_None) {
// std::cerr << "\t jobtagged" << std::endl;
// jobtagged_loc = PyLong_AsLong(jobtagged);
//} else {
// jobtagged_loc = NULL;
//}
std::cerr << "\t READY TO SET" << std::endl;
if (!q->set(pop,
jobid_loc,
job_loc,
jobstage_loc,
jobpath_loc,
jobdatecommitted_loc,
jobtagged_loc
)) {
pop.close();
status_out = "STATUS_FAILED_SETTING_VALUES";
return PyErr_Format(PyExc_AttributeError, status_out);
} else {
pop.close();
status_out = "STATUS_SUCCCESS";
}
return Py_BuildValue("s", status_out);
}
/********************************************
*
* SEARCH
* searcher
*
*******************************************/
PyObject* search(PyObject *self, PyObject *args, PyObject *kwords)
{
/* Search database for objects fulfilling criteria,
* returns index list specifying which indices fulfil these
* which then can be used to get/set values.
*
* Use `only_first=True` to abort and return the first found element.
*/
std::cerr << "pmdb::search" << std::endl;
// Input
char* path_in;
// Potential search objects, read in as keywords
PyObject *jobid = nullptr;
PyObject *job = nullptr;
PyObject *jobstage = nullptr;
PyObject *jobpath = nullptr;
PyObject *jobdatecommitted = nullptr;
PyObject *jobtagged = nullptr;
static char *kwlist[] = {"path_in", "n_max",
"jobid", "job", "jobstage", "jobpath",
"jobdatecommitted", "jobtagged", "only_first", NULL};
// Will be parsed into these:
int64_t n_max = -1;
int64_t jobid_loc;
char* job_loc;
int64_t jobstage_loc;
char* jobpath_loc;
char* jobdatecommitted_loc;
bool only_first = false; // returns only first element?
char* status_out;
int64_t* query_is_true;
PyObject *result_list;
int64_t result_list_size, result_list_ix;
//std::cerr << "\t Initialized " << std::endl;
PyArg_ParseTupleAndKeywords(args, kwords,
"sl|OOOOOOp:search", kwlist,
&path_in,
&n_max,
&jobid,
&job,
&jobstage,
&jobpath,
&jobdatecommitted,
&jobtagged,
&only_first
);
//std::cerr<< " \t Path in is: " << path_in << " ok" <<std::endl;
// Exit if we failed:
if (!path_in) {
status_out = "STATUS_FAILED_SPECIFY_PATH_IN";
return PyErr_Format(PyExc_ValueError, status_out);
} else if (n_max < 0) {
status_out = "STATUS_FAILED_SPECIFY_N_MAX";
return PyErr_Format(PyExc_ValueError, status_out);
} else if (!jobid && !job && !jobstage && !jobpath && !jobdatecommitted && !jobtagged) {
status_out = "STATUS_FAILED_SPECIFY_ONE_OR_MORE_FIELDS";
return PyErr_Format(PyExc_ValueError, status_out);
}
// Each query is a tuple of an operator and a statement,
// ie jobid=('>', 3)
// will return all jobids greater than 3.
int64_t q_status;
char* oper_jobid = nullptr;
char* oper_job = nullptr;
char* oper_jobstage = nullptr;
char* oper_jobpath = nullptr;
char* oper_datecommitted = nullptr;
char* oper_jobtagged = nullptr;
int64_t jobid_q = -1;
char* job_q = nullptr;
int64_t jobstage_q = -1;
char* jobpath_q = nullptr;
char* datecommitted_q = nullptr;
int64_t jobtagged_q = -1;
if (jobid) {
oper_jobid = new char[8];
PyArg_ParseTuple(jobid, "sl", &oper_jobid, &jobid_q);
}
if (job) {
oper_job = new char[8];
PyArg_ParseTuple(job, "ss", &oper_job, &job_q);
}
if (jobstage) {
oper_jobstage = new char[8];
PyArg_ParseTuple(jobstage, "sl", &oper_jobstage, &jobstage_q);
}
if (jobpath) {
oper_jobpath = new char[8];
PyArg_ParseTuple(jobpath, "ss", &oper_jobpath, &jobpath_q);
}
if (jobdatecommitted) {
oper_datecommitted = new char[8];
PyArg_ParseTuple(jobdatecommitted, "ss", &oper_datecommitted, &datecommitted_q);
}
if (jobtagged) {
oper_jobtagged = new char[8];
PyArg_ParseTuple(jobtagged, "sl", &oper_jobtagged, &jobtagged_q);
}
//std::cerr << "Found operator of jobstage: " << oper_jobstage << std::endl;
// Connect to persistent memory
pool<pmem_queue> pop;
if(init_pop(path_in, &pop)) {
status_out = "STATUS_EMPTY";
} else {
status_out = "STATUS_OPEN_POTENTIALLY_FILLED";
}
//std::cerr << "\t Opened PM file " << std::endl;
// reset q
auto q = pop.get_root();
if (!q) {
return PyErr_Format(PyExc_AttributeError, "STATUS_FAILED_DATABASE_Q_OR_POP_NULL");
goto error;
}
// Go through all the elements and return the indices where they are true
// Will interface with the search function, each index has an entry
query_is_true = new int64_t[n_max];
//std::cerr << "\t generated: query is true array " << std::endl;
// The search function loops over the data and sets the values of query_is_true
q_status = q->search_all(
query_is_true, n_max,
oper_jobid, jobid_q,
oper_job, job_q,
oper_jobstage, jobstage_q,
oper_jobpath, jobpath_q,
oper_datecommitted, datecommitted_q,
oper_jobtagged, jobtagged_q,
only_first);
pop.close();
std::cerr << "\t searched " << std::endl;
// Generate result list for Python, returning only indices
// First, find size of it:
result_list_size = 0;
if (!only_first) {
for (int ii=0; ii < n_max; ii++) {
if (query_is_true[ii] != 0) {
result_list_size += 1;
}
}
} else {
if (q_status < n_max) {
result_list_size = 1;
} else {
result_list_size = 0;
}
}
//std::cerr << "\t found size of result list " << result_list_size << std::endl;
//std::cerr << " and nmax: " << n_max << " and q_status (job id) " << q_status << std::endl;
// Make it
result_list = PyList_New(result_list_size);
// Insert indices:
result_list_ix = 0;
if (!only_first) {
for (int ii=0; ii < n_max; ii++) {
if (query_is_true[ii] != 0) {
PyList_SetItem(result_list, result_list_ix, PyLong_FromLong(ii));
result_list_ix += 1;
}
}
} else {
// Sets the first element to the first index of occurrence
// given from the q_status output
if (n_max > 0) {
if (q_status < n_max) {
PyList_SetItem(result_list, 0, PyLong_FromLong(q_status));
}
}
}
std::cout << "\t populated result list " << std::endl;
error:
// Cleanup, will always occurr
std::cout << "\t CLEANUP " << std::endl;
delete query_is_true;
//if (oper_jobid) {
// //Py_XDECREF(jobid);
// delete oper_jobid;
//}
//if (oper_job) {
// //Py_XDECREF(job);
// delete oper_job;
//}
//if (oper_jobstage) {
// //Py_XDECREF(jobstage);
// delete oper_jobstage;
//}
//if (oper_jobpath) {
// //Py_XDECREF(jobpath);
// delete oper_jobpath;
//}
//if (oper_datecommitted) {
// //Py_XDECREF(jobdatecommitted);
// delete oper_datecommitted;
//}
//if (oper_jobtagged) {
// //Py_XDECREF(jobtagged);
// delete oper_jobtagged;
//}
return result_list;
}
/********************************************
*
* COUNT
* counter
*
*******************************************/
PyObject* count(PyObject *self, PyObject *args, PyObject *kwords)
{
/* counts number of jobs
*/
std::cout << "pmdb::count" << std::endl;
// Input
char* path_in;
char* status_out;
int64_t n_el;
PyObject *out;
PyObject *n_el_py;
PyArg_ParseTuple(args,
"s:count",
&path_in
);
// Exit if we failed:
if (!path_in) {
return PyErr_Format(PyExc_AttributeError, "STATUS_FAILED_PATH_NOT_SPECIFIED");
}
// Else, count
//
// Connect to persistent memory
pool<pmem_queue> pop;
if(init_pop(path_in, &pop)) {
status_out = "STATUS_EMPTY";
} else {
status_out = "STATUS_OPEN_POTENTIALLY_FILLED";
}
auto q = pop.get_root();
n_el = q->count();
std::cout << "COUNTED " << n_el << " elements!" << std::endl;
pop.close();
out = PyList_New(1);
n_el_py = PyLong_FromLong(n_el);
PyList_SetItem(out, 0, n_el_py );
return out;
}
static PyMethodDef pmdb_methods[] = {
{ "init_pmdb", (PyCFunction)init_pmdb, METH_VARARGS|METH_KEYWORDS, nullptr },
{ "insert", (PyCFunction)insert, METH_VARARGS|METH_KEYWORDS, nullptr },
{ "get", (PyCFunction)get, METH_VARARGS, nullptr },
{ "set", (PyCFunction)set, METH_VARARGS|METH_KEYWORDS, nullptr },
{ "search", (PyCFunction)search, METH_VARARGS|METH_KEYWORDS, nullptr },
{ "count", (PyCFunction)count, METH_VARARGS, nullptr },
// Terminate the array with an object containing nulls.
{ nullptr, nullptr, 0, nullptr }
};
static PyModuleDef pmdb_module = {
PyModuleDef_HEAD_INIT,
"pmdb", // Module name to use with Python import statements
"Permament Memory Database Python bindings", // Module description
0,
pmdb_methods // Structure that defines the methods of the module
};
PyMODINIT_FUNC PyInit_pmdb()
{
return PyModule_Create(&pmdb_module);
}
/////// END PYTHON EXTENSION ////////
| 27.271632 | 145 | 0.59412 |
562dd6271c974c01c0876e325eb533931807e451 | 159 | cpp | C++ | CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp | GUNU-GO/SNUPI | a73137699d9fc6ae8fa3d1522f341c04d8d43052 | [
"MIT"
] | null | null | null | CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp | GUNU-GO/SNUPI | a73137699d9fc6ae8fa3d1522f341c04d8d43052 | [
"MIT"
] | null | null | null | CPP_Projects/Studying/ConsoleApplication1/ConsoleApplication1/pr1.cpp | GUNU-GO/SNUPI | a73137699d9fc6ae8fa3d1522f341c04d8d43052 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main() {
int num;
scanf_s("%d", &num);
for(int i = 1; i <= num; i++) {
if (num % i == 0) {
printf("%d, ",i);
}
}
}W | 9.9375 | 32 | 0.415094 |
562f2b292e7b632be0821c80de2481a80dc30153 | 3,701 | hpp | C++ | include/haz/Tools/EnumFlag.hpp | Hazurl/Framework-haz | 370348801cd969ce8521264653069923a255e0b0 | [
"MIT"
] | null | null | null | include/haz/Tools/EnumFlag.hpp | Hazurl/Framework-haz | 370348801cd969ce8521264653069923a255e0b0 | [
"MIT"
] | null | null | null | include/haz/Tools/EnumFlag.hpp | Hazurl/Framework-haz | 370348801cd969ce8521264653069923a255e0b0 | [
"MIT"
] | null | null | null | #ifndef __HAZ_ENUM_FLAG
#define __HAZ_ENUM_FLAG
#include <haz/Tools/Macro.hpp>
#include <type_traits>
#define ENUM_FLAG(name, bloc_enum...)\
BEG_NAMESPACE_HAZ_HIDDEN namespace enumFlagNamespace { \
enum class UNIQUE_NAME(name) \
bloc_enum; \
} END_NAMESPACE_HAZ_HIDDEN \
typedef haz::__hide::enumFlagNamespace::UNIQUE_NAME(name) name
#define ENUM_FLAG_NESTED(beg_ns, end_ns, name, bloc_enum...)\
BEG_NAMESPACE_HAZ_HIDDEN namespace enumFlagNamespace { \
enum class UNIQUE_NAME(name) \
bloc_enum; \
} END_NAMESPACE_HAZ_HIDDEN \
beg_ns typedef haz::__hide::enumFlagNamespace::UNIQUE_NAME(name) name; end_ns
BEG_NAMESPACE_HAZ_HIDDEN
namespace enumFlagNamespace {
#define TEMPLATE_RESTRICTIONS(T) typename = typename std::enable_if<std::is_enum<T>::value, T>::type
#define CAST_UNDER_TYPE(T) static_cast<typename std::underlying_type<T>::type>
template<typename T, TEMPLATE_RESTRICTIONS(T)>
class auto_bool
{
T value;
public:
constexpr auto_bool(T value) : value(value) {}
constexpr operator T() const { return value; }
constexpr operator bool() const
{
return CAST_UNDER_TYPE(T)(value) != 0;
}
};
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr auto_bool<T> operator&(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) & CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator|(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) | CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator^(T lhs, T rhs) {
return static_cast<T>(CAST_UNDER_TYPE(T)(lhs) ^ CAST_UNDER_TYPE(T)(rhs));
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator|=(T& lhs, T rhs) {
return lhs = (lhs | rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator&=(T& lhs, T rhs) {
return lhs = (lhs & rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T& operator^=(T& lhs, T rhs) {
return lhs = (lhs ^ rhs);
}
template<typename T, TEMPLATE_RESTRICTIONS(T)>
constexpr T operator~(T t) {
return static_cast<T>(~ CAST_UNDER_TYPE(T)(t));
}
}
#define IMPLM_ENUM_FLAP_OP(name) \
inline constexpr ::haz::__hide::enumFlagNamespace::auto_bool<name> operator & (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
& static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name operator | (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
| static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name operator ^ (name lhs, name rhs) { \
return static_cast<name>( \
static_cast<typename std::underlying_type<name>::type>(lhs) \
^ static_cast<typename std::underlying_type<name>::type>(rhs) \
); \
} \
inline constexpr name& operator &= (name& lhs, name rhs) { \
return lhs = (lhs & rhs); \
} \
inline constexpr name& operator |= (name& lhs, name rhs) { \
return lhs = (lhs | rhs); \
} \
inline constexpr name& operator ^= (name& lhs, name rhs) { \
return lhs = (lhs ^ rhs); \
} \
inline constexpr name operator ~ (name lhs) { \
return static_cast<name>( \
~ static_cast<typename std::underlying_type<name>::type>(lhs) \
); \
}
#undef TEMPLATE_RESTRICTIONS
#undef CAST_UNDER_TYPE
END_NAMESPACE_HAZ_HIDDEN
#endif | 31.905172 | 102 | 0.663334 |
5631846960b9848c74957911364c8b9b629890bf | 13,072 | cc | C++ | google/cloud/apigateway/api_gateway_client.cc | jmouradi-google/google-cloud-cpp | 7bd738251a80e9520d7a7de4cc14558f161c8edc | [
"Apache-2.0"
] | null | null | null | google/cloud/apigateway/api_gateway_client.cc | jmouradi-google/google-cloud-cpp | 7bd738251a80e9520d7a7de4cc14558f161c8edc | [
"Apache-2.0"
] | null | null | null | google/cloud/apigateway/api_gateway_client.cc | jmouradi-google/google-cloud-cpp | 7bd738251a80e9520d7a7de4cc14558f161c8edc | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/apigateway/v1/apigateway_service.proto
#include "google/cloud/apigateway/api_gateway_client.h"
#include "google/cloud/apigateway/internal/api_gateway_option_defaults.h"
#include <memory>
namespace google {
namespace cloud {
namespace apigateway {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
ApiGatewayServiceClient::ApiGatewayServiceClient(
std::shared_ptr<ApiGatewayServiceConnection> connection, Options options)
: connection_(std::move(connection)),
options_(internal::MergeOptions(
std::move(options),
apigateway_internal::ApiGatewayServiceDefaultOptions(
connection_->options()))) {}
ApiGatewayServiceClient::~ApiGatewayServiceClient() = default;
StreamRange<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::ListGateways(std::string const& parent,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListGatewaysRequest request;
request.set_parent(parent);
return connection_->ListGateways(request);
}
StreamRange<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::ListGateways(
google::cloud::apigateway::v1::ListGatewaysRequest request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListGateways(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::GetGateway(std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetGatewayRequest request;
request.set_name(name);
return connection_->GetGateway(request);
}
StatusOr<google::cloud::apigateway::v1::Gateway>
ApiGatewayServiceClient::GetGateway(
google::cloud::apigateway::v1::GetGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::CreateGateway(
std::string const& parent,
google::cloud::apigateway::v1::Gateway const& gateway,
std::string const& gateway_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateGatewayRequest request;
request.set_parent(parent);
*request.mutable_gateway() = gateway;
request.set_gateway_id(gateway_id);
return connection_->CreateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::CreateGateway(
google::cloud::apigateway::v1::CreateGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::UpdateGateway(
google::cloud::apigateway::v1::Gateway const& gateway,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateGatewayRequest request;
*request.mutable_gateway() = gateway;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::Gateway>>
ApiGatewayServiceClient::UpdateGateway(
google::cloud::apigateway::v1::UpdateGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteGateway(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteGatewayRequest request;
request.set_name(name);
return connection_->DeleteGateway(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteGateway(
google::cloud::apigateway::v1::DeleteGatewayRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteGateway(request);
}
StreamRange<google::cloud::apigateway::v1::Api>
ApiGatewayServiceClient::ListApis(std::string const& parent, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListApisRequest request;
request.set_parent(parent);
return connection_->ListApis(request);
}
StreamRange<google::cloud::apigateway::v1::Api>
ApiGatewayServiceClient::ListApis(
google::cloud::apigateway::v1::ListApisRequest request, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListApis(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::Api> ApiGatewayServiceClient::GetApi(
std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetApiRequest request;
request.set_name(name);
return connection_->GetApi(request);
}
StatusOr<google::cloud::apigateway::v1::Api> ApiGatewayServiceClient::GetApi(
google::cloud::apigateway::v1::GetApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::CreateApi(
std::string const& parent, google::cloud::apigateway::v1::Api const& api,
std::string const& api_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateApiRequest request;
request.set_parent(parent);
*request.mutable_api() = api;
request.set_api_id(api_id);
return connection_->CreateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::CreateApi(
google::cloud::apigateway::v1::CreateApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::UpdateApi(
google::cloud::apigateway::v1::Api const& api,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateApiRequest request;
*request.mutable_api() = api;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::Api>>
ApiGatewayServiceClient::UpdateApi(
google::cloud::apigateway::v1::UpdateApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApi(std::string const& name, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteApiRequest request;
request.set_name(name);
return connection_->DeleteApi(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApi(
google::cloud::apigateway::v1::DeleteApiRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteApi(request);
}
StreamRange<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::ListApiConfigs(std::string const& parent,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::ListApiConfigsRequest request;
request.set_parent(parent);
return connection_->ListApiConfigs(request);
}
StreamRange<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::ListApiConfigs(
google::cloud::apigateway::v1::ListApiConfigsRequest request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->ListApiConfigs(std::move(request));
}
StatusOr<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::GetApiConfig(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::GetApiConfigRequest request;
request.set_name(name);
return connection_->GetApiConfig(request);
}
StatusOr<google::cloud::apigateway::v1::ApiConfig>
ApiGatewayServiceClient::GetApiConfig(
google::cloud::apigateway::v1::GetApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->GetApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::CreateApiConfig(
std::string const& parent,
google::cloud::apigateway::v1::ApiConfig const& api_config,
std::string const& api_config_id, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::CreateApiConfigRequest request;
request.set_parent(parent);
*request.mutable_api_config() = api_config;
request.set_api_config_id(api_config_id);
return connection_->CreateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::CreateApiConfig(
google::cloud::apigateway::v1::CreateApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->CreateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::UpdateApiConfig(
google::cloud::apigateway::v1::ApiConfig const& api_config,
google::protobuf::FieldMask const& update_mask, Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::UpdateApiConfigRequest request;
*request.mutable_api_config() = api_config;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::ApiConfig>>
ApiGatewayServiceClient::UpdateApiConfig(
google::cloud::apigateway::v1::UpdateApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->UpdateApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApiConfig(std::string const& name,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
google::cloud::apigateway::v1::DeleteApiConfigRequest request;
request.set_name(name);
return connection_->DeleteApiConfig(request);
}
future<StatusOr<google::cloud::apigateway::v1::OperationMetadata>>
ApiGatewayServiceClient::DeleteApiConfig(
google::cloud::apigateway::v1::DeleteApiConfigRequest const& request,
Options options) {
internal::OptionsSpan span(
internal::MergeOptions(std::move(options), options_));
return connection_->DeleteApiConfig(request);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace apigateway
} // namespace cloud
} // namespace google
| 38.789318 | 79 | 0.746558 |
56323b24a47b69b41fa0fd4d8431e279aaebc438 | 6,614 | hpp | C++ | OcularCore/include/Math/Bounds/BoundsOBB.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 8 | 2017-01-27T01:06:06.000Z | 2020-11-05T20:23:19.000Z | OcularCore/include/Math/Bounds/BoundsOBB.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 39 | 2016-06-03T02:00:36.000Z | 2017-03-19T17:47:39.000Z | OcularCore/include/Math/Bounds/BoundsOBB.hpp | ssell/OcularEngine | c80cc4fcdb7dd7ce48d3af330bd33d05312076b1 | [
"Apache-2.0"
] | 4 | 2019-05-22T09:13:36.000Z | 2020-12-01T03:17:45.000Z | /**
* Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com)
*
* 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.
*/
#pragma once
#ifndef __H__OCULAR_MATH_BOUNDS_OBB__H__
#define __H__OCULAR_MATH_BOUNDS_OBB__H__
#include "Math/Bounds/Bounds.hpp"
#include "Math/Vector3.hpp"
//------------------------------------------------------------------------------------------
/**
* \addtogroup Ocular
* @{
*/
namespace Ocular
{
/**
* \addtogroup Math
* @{
*/
namespace Math
{
class Ray;
class BoundsSphere;
class BoundsAABB;
class Plane;
/**
* \class BoundsOBB
*
* Implementation of an Oriented Bounding Box.
*
* Essentially an OBB is an AABB that can be arbitrarily rotated.
* They are more expensive to create and their intersection tests
* are more complicated, but have the benefit of not needing to
* be recalculated every time their contents are rotated.
*
* Additionally, in most cases an OBB will also provide a tighter
* fit than an AABB.
*/
class BoundsOBB : public Bounds
{
public:
BoundsOBB(Vector3f const& center, Vector3f const& extents, Vector3f const& xDir, Vector3f const& yDir, Vector3f const& zDir);
BoundsOBB();
~BoundsOBB();
/**
* Returns the center of the bounding box.
*/
Vector3f const& getCenter() const;
/**
* /param[in] center
*/
void setCenter(Vector3f const& center);
/**
* Returns the positive half-lengths of the box.
* These are the distances along each local axis to the box edge.
*/
Vector3f const& getExtents() const;
/**
* /param[in] extents
*/
void setExtents(Vector3f const& extents);
/**
* Returns the normalized direction of the x-axis of the bounding box.
*/
Vector3f const& getDirectionX() const;
/**
* /param[in] dirX
*/
void setDirectionX(Vector3f const& dirX);
/**
* Returns the normalized direction of the y-axis of the bounding box.
*/
Vector3f const& getDirectionY() const;
/**
* /param[in] dirY
*/
void setDirectionY(Vector3f const& dirY);
/**
* Returns the normalized direction of the z-axis of the bounding box.
*/
Vector3f const& getDirectionZ() const;
/**
* /param[in] dirZ
*/
void setDirectionZ(Vector3f const& dirZ);
//------------------------------------------------------------------------------
// Intersection and Containment Testing
//------------------------------------------------------------------------------
/**
* Performs an intersection test on a ray and OBB.
*
* \param[in] ray
* \return TRUE if the ray and OBB intersect.
*/
bool intersects(Ray const& ray) const;
/**
* Performs an intersection test on a bounding sphere and OBB.
*
* \param[in] bounds
* \return TRUE if the bounding sphere and OBB intersect.
*/
bool intersects(BoundsSphere const& bounds) const;
/**
* Performs an intersection test on a AABB and OBB.
*
* \param[in] bounds
* \return TRUE if the AABB and OBB intersect.
*/
bool intersects(BoundsAABB const& bounds) const;
/**
* Performs an intersection test on two OBBs.
*
* \param[in] bounds
* \return TRUE if the two OBBs intersect.
*/
bool intersects(BoundsOBB const& bounds) const;
/**
* Performs an intersection test on a plane and OBB.
*
* If the result is Inside, then the OBB is located entirely within the plane's positive half space. <br/>
* If the result is Outside, then the OBB is located entirely outside the plane's positive half space.
*
* The positive half space of the plane is the direction that the plane is facing, as described by it's normal.
*
* As an example, say we have the plane defined as:
*
* Point: (0.0, 0.0, 0.0)
* Normal: (0.0, 1.0, 0.0)
*
* The plane is 'facing up' along the world origin.
*
* If the intersection test returns Outside, then the AABB is entirely in the +y world space. <br/>
* If the intersection test returns Inside, then the AABB is entirely in the -y world space.
*
* \param[in] plane
* \param[out] result Detailed intersection result.
*
* \return TRUE if the plane and OBB intersects, otherwise FALSE.
*/
bool intersects(Plane const& plane, IntersectionType* result = nullptr) const;
protected:
private:
Vector3f m_Center; ///< Center point of the box
Vector3f m_Extents; ///< Positive half-lengths
Vector3f m_DirectionX; ///< Normalized direction of the X side direction
Vector3f m_DirectionY; ///< Normalized direction of the Y side direction
Vector3f m_DirectionZ; ///< Normalized direction of the Z side direction
};
}
/**
* @} End of Doxygen Groups
*/
}
/**
* @} End of Doxygen Groups
*/
//------------------------------------------------------------------------------------------
#endif | 33.40404 | 137 | 0.508164 |
563304c25502d7cd748cd4959b1f93f90fe0b31d | 2,867 | cpp | C++ | src/common/file-lock.cpp | Samsung/security-manager | 10b062f317d5d5a7b88ed13242540e9034fd019f | [
"Apache-2.0"
] | 14 | 2015-09-17T19:30:34.000Z | 2021-11-11T14:10:43.000Z | src/common/file-lock.cpp | Samsung/security-manager | 10b062f317d5d5a7b88ed13242540e9034fd019f | [
"Apache-2.0"
] | 5 | 2015-09-17T13:33:39.000Z | 2015-11-12T21:37:09.000Z | src/common/file-lock.cpp | Samsung/security-manager | 10b062f317d5d5a7b88ed13242540e9034fd019f | [
"Apache-2.0"
] | 14 | 2015-06-08T07:40:24.000Z | 2020-01-20T18:58:13.000Z | /*
* Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Rafal Krypa <r.krypa@samsung.com>
*
* 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
*/
/*
* @file file-lock.cpp
* @author Sebastian Grabowski (s.grabowski@samsung.com)
* @version 1.0
* @brief Implementation of simple file locking for a service
*/
/* vim: set ts=4 et sw=4 tw=78 : */
#include <fstream>
#include "dpl/log/log.h"
#include "tzplatform-config.h"
#include "file-lock.h"
namespace SecurityManager {
const std::string SERVICE_LOCK_FILE = TizenPlatformConfig::makePath(
TZ_SYS_RUN, "lock", "security-manager.lock");
FileLocker::FileLocker(const std::string &lockFile, bool blocking)
{
if (lockFile.empty()) {
LogError("File name can not be empty.");
ThrowMsg(FileLocker::Exception::LockFailed,
"File name can not be empty.");
}
m_locked = false;
m_blocking = blocking;
m_lockFile = lockFile;
Lock();
}
FileLocker::~FileLocker()
{
try {
Unlock();
} catch (...) {
LogError("~FileLocker() threw an exception");
}
}
bool FileLocker::Locked()
{
return m_locked;
}
void FileLocker::Lock()
{
if (m_locked)
return;
try {
std::ofstream tmpf(m_lockFile);
tmpf.close();
m_flock = boost::interprocess::file_lock(m_lockFile.c_str());
if (m_blocking) {
m_flock.lock();
m_locked = true;
} else
m_locked = m_flock.try_lock();
} catch (const std::exception &e) {
LogError("Error while locking a file: " << e.what());
ThrowMsg(FileLocker::Exception::LockFailed,
"Error while locking a file: " << e.what());
}
if (m_locked)
LogDebug("We have a lock on " << m_lockFile << " file.");
else
LogDebug("Impossible to lock a file now.");
}
void FileLocker::Unlock()
{
if (m_locked) {
try {
m_flock.unlock();
} catch (const std::exception &e) {
LogError("Error while unlocking a file: " << e.what());
ThrowMsg(FileLocker::Exception::UnlockFailed,
"Error while unlocking a file: " << e.what());
}
m_locked = false;
LogDebug("Lock released.");
}
}
} // namespace SecurityManager
| 26.063636 | 78 | 0.611789 |
5635d1b5960254c4c718c1bc639529e28924c81b | 4,878 | cpp | C++ | system/apps/test45_simcom/main.cpp | tomwei7/LA104 | fdf04061f37693d37e2812ed6074348e65d7e5f9 | [
"MIT"
] | 336 | 2018-11-23T23:54:15.000Z | 2022-03-21T03:47:05.000Z | system/apps/test45_simcom/main.cpp | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 56 | 2019-02-01T05:01:07.000Z | 2022-03-26T16:00:24.000Z | system/apps/test45_simcom/main.cpp | 203Null/LA104 | b8ae9413d01ea24eafb9fdb420c97511287cbd99 | [
"MIT"
] | 52 | 2019-02-06T17:05:04.000Z | 2022-03-04T12:30:53.000Z | #include <library.h>
#include "../../os_host/source/framework/Console.h"
using namespace BIOS;
#include "simcom.h"
// https://dweet.io/follow/la104simcom900
// https://dweet.io/dweet/for/la104simcom900?counter=10123
// https://dweet.io/get/latest/dweet/for/la104simcom900
int gReset = 0;
class CMyHttpReceiver : public CHttpResponse
{
bool mFirstLine{true};
public:
virtual void OnHttpCode(int code) override
{
if (code != 200)
{
CONSOLE::Color(RGB565(ff00ff));
CONSOLE::Print("HTTP Error: %d\n", code);
}
}
virtual void OnBody(char* body, int length) override
{
if (!mFirstLine)
return;
mFirstLine = false;
if (length > 31)
strcpy(body+31-3, "...");
CONSOLE::Color(RGB565(b0b0b0));
CONSOLE::Print("Resp: ");
CONSOLE::Color(RGB565(ffffff));
CONSOLE::Print(body);
CONSOLE::Print("\n");
}
virtual void OnFinished() override
{
mFirstLine = true;
}
};
class CMyHttpRequest : public CHttpRequest
{
char mArguments[RequestArgumentsLength];
public:
CMyHttpRequest(const char* host, const char* path)
{
mProtocol = "TCP";
mHost = host;
mPath = path;
mPort = 80;
strcpy(mArguments, "");
}
virtual CAtStream& Request(CAtStream& s)
{
CAtStreamCounter counter;
GetArguments(counter);
s << "POST " << mPath << " HTTP/1.0\r\n"
<< "Host: " << mHost << "\r\n"
<< "User-Agent: sim800L on LA104 by valky.eu\r\n"
<< "content-type: application/x-www-form-urlencoded\r\n"
<< "content-length: " << counter.Count() << "\r\n"
<< "\r\n";
GetArguments(s);
s << "\r\n";
return s;
}
void SetArguments(char *args)
{
_ASSERT(strlen(args) < sizeof(mArguments)-1);
strcpy(mArguments, args);
}
virtual void GetArguments(CAtStream& s)
{
s << mArguments;
}
};
class CClientApp
{
static CClientApp* pInstance;
CGprs mGprs;
CHttpRequestPost mRequest{"dweet.io", "/dweet/for/la104simcom"};
CMyHttpReceiver mResponse;
bool shouldProcess{false};
int mCounter{0};
public:
void Init()
{
BIOS::GPIO::PinMode(BIOS::GPIO::P3, BIOS::GPIO::Output);
// io pins before special io
BIOS::GPIO::PinMode(BIOS::GPIO::P1, BIOS::GPIO::Uart);
BIOS::GPIO::PinMode(BIOS::GPIO::P2, BIOS::GPIO::Uart);
GPIO::UART::Setup(115200, GPIO::UART::EConfig::length8);
//gprs.SetApn("o2internet"); //O2
mGprs.SetApn("internet"); // 4ka
mGprs.SetReceiver(&mResponse);
mGprs.AttachPrint([](char c){ GPIO::UART::Write(c); });
mGprs.AttachPower([](bool value){ gReset++;
BIOS::GPIO::DigitalWrite(BIOS::GPIO::P3, 1-value); });
}
void comm_yield()
{
while (GPIO::UART::Available())
{
char c = GPIO::UART::Read();
mGprs << c;
if (c == '\n')
shouldProcess = true;
}
}
void gprs_yield()
{
static long last = 0;
long now = millis();
if (shouldProcess || now > last + 500)
{
shouldProcess = false;
last = now;
mGprs();
}
}
void Do()
{
comm_yield();
gprs_yield();
if (mGprs.isReady())
{
mResponse.Reset();
char request[128];
sprintf(request, "time=%d&reset=%d&counter=%d", BIOS::SYS::GetTick(), gReset, mCounter++);
mRequest.SetArguments(request);
mGprs.request(mRequest);
}
}
CClientApp()
{
pInstance = this;
}
};
CClientApp* CClientApp::pInstance = nullptr;
CClientApp app;
#ifdef _ARM
__attribute__((__section__(".entry")))
#endif
int _main(void)
{
CRect rcClient(0, 0, LCD::Width, LCD::Height);
LCD::Bar(rcClient, RGB565(0000b0));
CRect rc1(rcClient);
rc1.bottom = 14;
GUI::Background(rc1, RGB565(4040b0), RGB565(404040));
BIOS::LCD::Print(8, rc1.top, RGB565(ffffff), RGBTRANS, "SIMCOM web client & dweet.io");
CRect rc2(rcClient);
rc2.top = rc2.bottom-14;
GUI::Background(rc2, RGB565(404040), RGB565(202020));
BIOS::LCD::Print(8, rc2.top, RGB565(808080), RGBTRANS, "https://dweet.io/follow/la104simcom");
app.Init();
BIOS::KEY::EKey key;
while ((key = KEY::GetKey()) != KEY::EKey::Escape)
{
app.Do();
}
return 0;
}
void _HandleAssertion(const char* file, int line, const char* cond)
{
CONSOLE::Color(RGB565(ffff00));
CONSOLE::Print("Assertion failed in ");
CONSOLE::Print(file);
CONSOLE::Print(" [%d]: %s\n", line, cond);
#ifdef __APPLE__
//kill(getpid(), SIGSTOP);
#endif
while (1);
}
| 23.118483 | 102 | 0.555351 |
563b8cea31f72e9688e73cb8ae99652284e35afc | 8,870 | hpp | C++ | roller_eye/test/bist/BistNode.hpp | lorenzo-bianchi/Scout-open-source | ca20d3112388f47a36a245de5de1a35673afd260 | [
"MIT"
] | 35 | 2022-03-12T01:36:17.000Z | 2022-03-28T14:56:13.000Z | roller_eye/test/bist/BistNode.hpp | lorenzo-bianchi/Scout-open-source | ca20d3112388f47a36a245de5de1a35673afd260 | [
"MIT"
] | null | null | null | roller_eye/test/bist/BistNode.hpp | lorenzo-bianchi/Scout-open-source | ca20d3112388f47a36a245de5de1a35673afd260 | [
"MIT"
] | 9 | 2022-03-12T01:39:43.000Z | 2022-03-31T20:54:19.000Z | #include <iostream>
#include <cstdlib>
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
#include <linux/input.h>
#include "zlog.h"
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "roller_eye/ros_tools.h"
#include "roller_eye/motor.h"
#include "roller_eye/plt_assert.h"
#include <iostream>
#include <fstream>
#include "roller_eye/camera_handle.hpp"
#include "roller_eye/algo_utils.h"
#include "roller_eye/status_publisher.h"
#include "roller_eye/cv_img_stream.h"
#include "roller_eye/SensorBase.h"
#include "roller_eye/plt_tools.h"
#include "roller_eye/plt_config.h"
#include "roller_eye/wifi_ops.h"
#include "sensor_msgs/Illuminance.h"
#include "roller_eye/cv_img_stream.h"
#include "std_msgs/Int32.h"
#include "roller_eye/track_trace.h"
#include "roller_eye/recorder_mgr.h"
#include <roller_eye/wifi_ops.h>
#include "roller_eye/sound_effects_mgr.h"
#include "roller_eye/start_bist.h"
#include "roller_eye/get_bist_result.h"
#include <opencv2/opencv.hpp>
#include <opencv2/core/eigen.hpp>
#include <opencv2/core/core.hpp>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include <cv_bridge/cv_bridge.h>
using namespace roller_eye;
#define DETECT_ROLL_SPEED (1.5)
#define BIST_BOOT_ERROR 1
#define BIST_WFI_ERROR 2
#define BIST_KEY_PRESSING_ERROR 3
#define BIST_LIGHT_SENSOR_ERROR 4
#define BIST_SOUND_ERROR 5
#define BIST_TOF_ERROR 6
#define BIST_IMU_ERROR 7
#define BIST_MOTOR_WHEELS_ERROR 8
#define BIST_CAMERA_RESOLUTION_ERROR 9
#define BIST_CAMERA_DISTORTION_ERROR 10
#define BIST_BATTERY_ERROR 11
#define BIST_IRLIGHT_ERROR 12
#define BIST_BATTERY_WIFIANTENNA_ERROR 13
#define BIST_MEMERY_ERROR 14
#define BIST_DISK_ERROR 15
#define RESET_KEY_LONG_PRESS_TIME (500)
#define WIFI_KEY_LONG_PRESS_TIME (500)
#define POWER_KEY_LONGPRESS_TIME (500)
#define BIST_DETECT_W 640
#define BIST_DETECT_H 480
#define BIST_DETECT "/var/roller_eye/devAudio/got_new_instruction/got_new_instrction.wav"
#define NAV_OUT_SPEED 0.4
#define BIST_MOVE_DIST 0.5
#define CHESSBAORD_ROW 5
#define CHESSBAORD_COL 5
#define CHESSBAORD_SIZE 0.0065
#define CAM_K_FX 720.5631606
#define CAM_K_FY 723.6323653
#define CAM_K_CX 659.39411452
#define CAM_K_CY 369.00731648
#define DISTRO_K1 -0.36906219
#define DISTRO_K2 0.16914887
#define DISTRO_P1 -0.00147033
#define DISTRO_P2 -0.00345135
#define CAR_LENGTH (0.1)
#define ALIGN_DISTANCE 0.16
#define MEM_SIZE 900000
#define DISK_SIZE 7.0 //GB
class CompGreater
{
public:
bool operator ()(const WiFiInFo& info1, const WiFiInFo& info2)
{
return info1.signal > info2.signal;
}
};
class BistNode{
public:
BistNode();
~BistNode();
private:
void MotorWheelCB(const detectConstPtr& obj);
void tofDataCB(const sensor_msgs::RangeConstPtr &r);
void odomRelativeCB(const nav_msgs::Odometry::ConstPtr& msg);
void BatteryStatusCB(const statusConstPtr &s);
void IlluminanceCB(const sensor_msgs::IlluminanceConstPtr& ptr);
void IRLightCB(const sensor_msgs::IlluminanceConstPtr& ptr);
void imuCB(const sensor_msgs::Imu::ConstPtr& msg);
void VideoDataCB(roller_eye::frameConstPtr frame);
void calDistanceAndAngle(Eigen::Quaterniond& q,Eigen::Vector3d& pos,Eigen::Vector3d &goal,double &angle,double &distance);
void LEDControl(int id,int flag)
{
static const char* ids[]={"gpio02_","gpio03_","gpio04_","gpio05_"};
static const char* flags[]={"0", "1"};
char buff[16];
//PLOG_INFO("bist","LEDControl %d",id);
snprintf(buff,sizeof(buff),"%s%s\n",ids[id],flags[flag]);
ofstream of(LED_PATH);
if(!of){
PLOG_ERROR("bist","can't not open %s\n",LED_PATH.c_str());
return;
}
of<<buff<<std::flush;
}
void logInit(){
log_t arg = {
confpath: "/var/roller_eye/config/log/bist.cfg",
levelpath: "/var/roller_eye/config/log/bist.level",
logpath: "/var/log/node/bistNode.log",
cname: "bist"
};
int ret = dzlogInit(&arg,2);
system("echo 20 > /var/roller_eye/config/log/bist.level");
printf("dzlogInit:%d\r\n",ret);
zlog_category_t *zc = zlog_get_category("bist");
zlog_level_switch(zc,20);
}
void LEDProcess(int flag);
void LEDStatus(int flag);
void LEDAllON();
void LEDAllOFF();
void IrLightOn();
void IrLightOff();
void PCMAnalysis(int type = 0);
void PCMgeneration();
float ImagArticulation(const cv::Mat &image);
int pcm2wave(const char *pcmpath, int channels, int sample_rate, const char *wavepath);
void BistSaveImage();
void JpgCallback(roller_eye::frameConstPtr frame);
void getPose(float &lastX,float &lastY,float &angle);
//void GreyImagCallback(const sensor_msgs::ImageConstPtr& msg);
void BistVideoDetect();
void BistTofDetect();
void BistSpeakerMicrophoneDetect();
void BistKeyDetect();
void BistWIFIDetect();
void BistBatteryDetect();
void BistLightDetect();
void BistIMUDetect();
void BistMotorWheelsDetect();
void BistIRLightDetect();
void BistWIFIAntennaDetect();
void BistMemDetect();
void BistDiskDetect();
void BistDriveMotor();
void BistPCBIMUDetect();
void BistPCBTofDetect();
void BistMicrophoneDetect();
void BistPCBVideoDetect();
AlgoUtils mAlgo;
float mRange = 0.0;
float mPCBRange = 0.0;
double mDistance = 0.0;
double mAngle = 0.0;
int mCharging = -1;
double mArticulation = 0.0;
//mutex mBistMutex;
std::mutex mtx;
std::condition_variable cv;
const string LED_PATH="/proc/driver/gpioctl";
const string LOG_CFG="/var/roller_eye/config/log.conf";
const string LOG_LEVEL="/var/roller_eye/config/log.level";
const string PCMFILE="/tmp/test.pcm";
const string PCM2WAVFILE="/tmp/pcm2wav.wav";
const string WAVFILE="/tmp/test.wav";
const string BistImage="/userdata/Bist.jpg";
int mPcmHzs[3] = {0};
bool mIllumMin = false;
bool mIllumMax = false;
//ir light off
int mIRLightOffValu = 0;
int mIRLightOffCount = 0;
bool mIrLightOff = false;
//ir light on
int mIRLightOnValu = 0;
int mIRLightOnCount = 0;
bool mIrLightOn = false;
//key
int mWiFiFD;
int mResetFD;
int mPowerFD;
int IllumCount;
const string WIFI_KEY_TYPE="rk29-keypad";
const string RESET_KEY_TYPE = "adc-keys";
const string POWER_KEY_TYPE = "rk8xx_pwrkey";
struct timeval mLastResetTime;
struct timeval mLastWifiTime;
struct timeval mLastPowerTime;
bool mWiFiKey = false;
bool mResetKey = false;
bool mPowerKey = false;
void processResetKey();
void processWiFiKey();
void processPowerKey();
void KeyStatusLoop();
void BistLoop();
void BistReset();
void BistStatus();
void scanWiFilist(vector<WiFiInFo>& wifis );
void scanWiFiQuality(vector<WiFiInFo>& wifis );
void BistGreyImage();
void BistMatImage();
void JpgMatCb(roller_eye::frameConstPtr frame);
bool start(roller_eye::start_bistRequest &req, roller_eye::start_bistResponse &resp);
bool getResult(roller_eye::get_bist_resultRequest &req, roller_eye::get_bist_resultResponse &resp);
int mBistType;
bool mBistStartDetct = false;
bool mBistAllPassed = false;
bool mBistVideoRes = false;
bool mBistVideoDis = false;
bool mBistVideoJpg = false;
bool mBistTof = false;
bool mSpeakerMicrophone = false;
bool mKey = false;
bool mWifi = false;
bool mWIFIAntenna = false;
bool mBattery = false;
bool mLight = false;
bool mIRLight = false;
bool mIMU = false;
bool mMotorWheel = false;
bool mMemery = false;
bool mDisk = false;
bool mDetectRunning = false;
Eigen::Quaterniond mCurPose;
Eigen::Vector3d mCurPostion;
//CVGreyImageStream mGreyStream;
ros::Subscriber m_subJPG;
ros::Subscriber m_BistJPG;
ros::Subscriber m_subGrey;
cv::Mat m_BistGrey;
vector<uint8_t> mGreyData;
ros::Subscriber mTof;
ros::Subscriber mVideo;
ros::Subscriber mOdomRelative;
ros::Subscriber mBatteryStatus;
ros::Subscriber mScrLight;
ros::Subscriber mScrIMU;
ros::ServiceClient mImuClient;
shared_ptr<ros::NodeHandle> mGlobal;
ros::Publisher mSysEvtPub;
ros::Publisher mPub;
ros::Publisher mCmdVel;
ros::NodeHandle mGlobal2;
ros::Subscriber mSwitch;
ros::Publisher mCmdVel3;
ros::ServiceServer mStartBistSrv;
ros::ServiceServer mGetBistResSrv;
//ros::NodeHandle mGlobal1;
};
| 29.177632 | 123 | 0.700225 |
563bce5a28baa6518a4d23f7c19f34b17e37eea5 | 1,843 | cpp | C++ | src/arduino_signalbox.cpp | dniklaus/arduino-signalbox | 8c4a2be46b69cb1d74278f8c76690a531fec4776 | [
"MIT"
] | null | null | null | src/arduino_signalbox.cpp | dniklaus/arduino-signalbox | 8c4a2be46b69cb1d74278f8c76690a531fec4776 | [
"MIT"
] | null | null | null | src/arduino_signalbox.cpp | dniklaus/arduino-signalbox | 8c4a2be46b69cb1d74278f8c76690a531fec4776 | [
"MIT"
] | null | null | null | // Do not remove the include below
#include "arduino_signalbox.h"
#include "Timer.h" // https://github.com/dniklaus/arduino-utils-timer
#include "ToggleButton.h" // https://github.com/dniklaus/arduino-toggle-button
#include "Blanking.h" // https://github.com/dniklaus/arduino-utils-blanking
#include "Point.h"
const int cPt05BtnDev = 32;
const int cPt05BtnStr = 33;
const int cPt05IndDev = 34;
const int cPt05IndStr = 35;
const int cPt20BtnDev = 44;
const int cPt20BtnStr = 45;
const int cPt20IndDev = 46;
const int cPt20IndStr = 47;
const int cPt21BtnDev = 40;
const int cPt21BtnStr = 41;
const int cPt21IndDev = 42;
const int cPt21IndStr = 43;
const int cPt22BtnDev = 36;
const int cPt22BtnStr = 37;
const int cPt22IndDev = 38;
const int cPt22IndStr = 39;
const int cPt23BtnDev = 22;
const int cPt23BtnStr = 23;
const int cPt23Ind1 = 27;
const int cPt23Ind2 = 26;
const int cPt23Ind3 = 24;
const int cPt23Ind4 = 25;
const int cPt24BtnDev = 28;
const int cPt24BtnStr = 29;
const int cPt24IndDev = 30;
const int cPt24IndStr = 31;
class Point* pt05;
class Point* pt20;
class Point* pt21;
class Point* pt22;
class Point* pt23;
class Point* pt24;
//-----------------------------------------------------------------------------
void setup()
{
Serial.begin(115200);
Serial.println(F("Hello from Signal Box Arduino Application!\n"));
pt05 = new Point(cPt05BtnDev, cPt05BtnStr, cPt05IndDev, cPt05IndStr);
pt20 = new Point(cPt20BtnDev, cPt20BtnStr, cPt20IndDev, cPt20IndStr);
pt21 = new Point(cPt21BtnDev, cPt21BtnStr, cPt21IndDev, cPt21IndStr);
pt22 = new Point(cPt22BtnDev, cPt22BtnStr, cPt22IndDev, cPt22IndStr);
pt23 = new Crossing(cPt23BtnDev, cPt23BtnStr, cPt23Ind1, cPt23Ind2, cPt23Ind3, cPt23Ind4);
pt24 = new Point(cPt24BtnDev, cPt24BtnStr, cPt24IndDev, cPt24IndStr);
}
void loop()
{
yield();
}
| 27.507463 | 92 | 0.705372 |
563fb5522362017893114feea9c10dd8d3558c7b | 999 | hpp | C++ | src/image.hpp | robotjandal/image_processor | 02eb861082212249e958acf0dbd2ac0144cac458 | [
"BSD-3-Clause"
] | null | null | null | src/image.hpp | robotjandal/image_processor | 02eb861082212249e958acf0dbd2ac0144cac458 | [
"BSD-3-Clause"
] | null | null | null | src/image.hpp | robotjandal/image_processor | 02eb861082212249e958acf0dbd2ac0144cac458 | [
"BSD-3-Clause"
] | null | null | null | #ifndef CMAKE_IMAGE_H
#define CMAKE_IMAGE_H
#include <string>
#include <opencv4/opencv2/opencv.hpp>
#include <boost/filesystem.hpp>
namespace ImageProcessor {
struct Image {
Image(){};
Image(cv::Mat const image, std::string const filename,
std::string const output_folder)
: image_{image}, filename_{boost::filesystem::path{filename}},
output_folder_{output_folder} {};
Image(cv::Mat const image, boost::filesystem::path const filename,
std::string const output_folder)
: image_{image}, filename_{filename}, output_folder_{output_folder} {};
bool operator==(const Image &other) const;
bool image_exists() const;
std::string get_filename() const { return filename_.filename().string(); };
std::string get_stem() const { return filename_.stem().string(); };
std::string get_extension() const { return filename_.extension().string(); };
cv::Mat image_;
boost::filesystem::path filename_;
std::string output_folder_{"output"};
};
}
#endif | 30.272727 | 79 | 0.707708 |
5641c03f6019abd5d472656ac044d16f49b21347 | 252 | cpp | C++ | tests/main.cpp | mincardona/cppscratch | 159e3757bc373245defc77c34930c0d7b1d925de | [
"MIT"
] | null | null | null | tests/main.cpp | mincardona/cppscratch | 159e3757bc373245defc77c34930c0d7b1d925de | [
"MIT"
] | null | null | null | tests/main.cpp | mincardona/cppscratch | 159e3757bc373245defc77c34930c0d7b1d925de | [
"MIT"
] | null | null | null | #include <iostream>
#include <mji/algorithm.hpp>
#include <mji/math.hpp>
#include <mji/memory.hpp>
#include <mji/xplat.hpp>
int main(int argc, char** argv) {
(void)argc;
(void)argv;
std::cout << "tests passed!" << '\n';
return 0;
}
| 15.75 | 41 | 0.615079 |
5641da34fc830fd337d475424076c9acdb665662 | 708 | cpp | C++ | main.cpp | Qanora/mstack-cpp | a1b6de6983404558e46b87d0e81da715fcdccd55 | [
"MIT"
] | 15 | 2020-07-20T12:32:38.000Z | 2022-03-24T19:24:02.000Z | main.cpp | Qanora/mstack-cpp | a1b6de6983404558e46b87d0e81da715fcdccd55 | [
"MIT"
] | null | null | null | main.cpp | Qanora/mstack-cpp | a1b6de6983404558e46b87d0e81da715fcdccd55 | [
"MIT"
] | 5 | 2020-07-20T12:42:58.000Z | 2021-01-16T10:13:39.000Z | #include <future>
#include <iostream>
#include "api.hpp"
int main(int argc, char* argv[]) {
auto stack = std::async(std::launch::async, mstack::init_stack, argc, argv);
int fd = mstack::socket(0x06, mstack::ipv4_addr_t("192.168.1.1"), 30000);
mstack::listen(fd);
char buf[2000];
int size = 2000;
int cfd = mstack::accept(fd);
while (true) {
size = 2000;
mstack::read(cfd, buf, size);
std::cout << "read size: " << size << std::endl;
for (int i = 0; i < size; i++) {
std::cout << buf[i];
}
std::cout << std::endl;
}
} | 33.714286 | 85 | 0.461864 |
564274f3fdb5851743ed4756bdc8bf7224735d77 | 63 | cpp | C++ | src/Utility_Test.cpp | AlbertoLeonardi/Open_SXD_Absorption | 3d0353676dada2e6826de583355c5e35a93fa791 | [
"BSD-3-Clause"
] | null | null | null | src/Utility_Test.cpp | AlbertoLeonardi/Open_SXD_Absorption | 3d0353676dada2e6826de583355c5e35a93fa791 | [
"BSD-3-Clause"
] | null | null | null | src/Utility_Test.cpp | AlbertoLeonardi/Open_SXD_Absorption | 3d0353676dada2e6826de583355c5e35a93fa791 | [
"BSD-3-Clause"
] | null | null | null | // Utility Functions :: Test
//
#include "Utility_Test.h"
| 12.6 | 29 | 0.634921 |
5643c15740cf50743bd304baf9cba340d7f98edd | 3,656 | cpp | C++ | beerocks/bwl/dummy/base_wlan_hal_dummy.cpp | prplfoundation/prplMesh-common | 96574a27695d2b6d3d610e680d8faaa52f0635d7 | [
"BSD-2-Clause-Patent"
] | 1 | 2019-05-01T14:45:31.000Z | 2019-05-01T14:45:31.000Z | beerocks/bwl/dummy/base_wlan_hal_dummy.cpp | prplfoundation/prplMesh-common | 96574a27695d2b6d3d610e680d8faaa52f0635d7 | [
"BSD-2-Clause-Patent"
] | 2 | 2019-05-22T15:32:59.000Z | 2019-05-27T14:15:55.000Z | beerocks/bwl/dummy/base_wlan_hal_dummy.cpp | prplfoundation/prplMesh-common | 96574a27695d2b6d3d610e680d8faaa52f0635d7 | [
"BSD-2-Clause-Patent"
] | 1 | 2019-05-13T09:51:20.000Z | 2019-05-13T09:51:20.000Z | /* SPDX-License-Identifier: BSD-2-Clause-Patent
*
* Copyright (c) 2016-2019 Intel Corporation
*
* This code is subject to the terms of the BSD+Patent license.
* See LICENSE file for more details.
*/
#include "base_wlan_hal_dummy.h"
#include <beerocks/bcl/beerocks_string_utils.h>
#include <beerocks/bcl/beerocks_utils.h>
#include <beerocks/bcl/network/network_utils.h>
#include <beerocks/bcl/son/son_wireless_utils.h>
#include <easylogging++.h>
#include <sys/eventfd.h>
#define UNHANDLED_EVENTS_LOGS 20
namespace bwl {
namespace dummy {
//////////////////////////////////////////////////////////////////////////////
////////////////////////// Local Module Functions ////////////////////////////
//////////////////////////////////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &out, const dummy_fsm_state &value)
{
switch (value) {
case dummy_fsm_state::Delay:
out << "Delay";
break;
case dummy_fsm_state::Init:
out << "Init";
break;
case dummy_fsm_state::GetRadioInfo:
out << "GetRadioInfo";
break;
case dummy_fsm_state::Attach:
out << "Attach";
break;
case dummy_fsm_state::Operational:
out << "Operational";
break;
case dummy_fsm_state::Detach:
out << "Detach";
break;
}
return out;
}
std::ostream &operator<<(std::ostream &out, const dummy_fsm_event &value)
{
switch (value) {
case dummy_fsm_event::Attach:
out << "Attach";
break;
case dummy_fsm_event::Detach:
out << "Detach";
break;
}
return out;
}
//////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Implementation ///////////////////////////////
//////////////////////////////////////////////////////////////////////////////
base_wlan_hal_dummy::base_wlan_hal_dummy(HALType type, std::string iface_name, bool acs_enabled,
hal_event_cb_t callback, int wpa_ctrl_buffer_size)
: base_wlan_hal(type, iface_name, IfaceType::Intel, acs_enabled, callback),
beerocks::beerocks_fsm<dummy_fsm_state, dummy_fsm_event>(dummy_fsm_state::Delay),
m_wpa_ctrl_buffer_size(wpa_ctrl_buffer_size)
{
// Allocate wpa_ctrl buffer
if (m_wpa_ctrl_buffer_size) {
m_wpa_ctrl_buffer = std::shared_ptr<char>(new char[m_wpa_ctrl_buffer_size], [](char *obj) {
if (obj)
delete[] obj;
});
}
// Set up dummy external events fd
if ((m_fd_ext_events = eventfd(0, EFD_SEMAPHORE)) < 0) {
LOG(FATAL) << "Failed creating eventfd: " << strerror(errno);
}
// Initialize the FSM
fsm_setup();
}
base_wlan_hal_dummy::~base_wlan_hal_dummy() { detach(); }
bool base_wlan_hal_dummy::fsm_setup() { return true; }
HALState base_wlan_hal_dummy::attach(bool block) { return (m_hal_state = HALState::Operational); }
bool base_wlan_hal_dummy::detach() { return true; }
bool base_wlan_hal_dummy::ping() { return true; }
bool base_wlan_hal_dummy::dummy_send_cmd(const std::string &cmd) { return false; }
bool base_wlan_hal_dummy::dummy_send_cmd(const std::string &cmd, char **reply) { return false; }
bool base_wlan_hal_dummy::refresh_radio_info() { return true; }
bool base_wlan_hal_dummy::refresh_vap_info(int vap_id) { return true; }
bool base_wlan_hal_dummy::refresh_vaps_info(int id) { return true; }
bool base_wlan_hal_dummy::process_ext_events() { return true; }
std::string base_wlan_hal_dummy::get_radio_mac() { return std::string("DE:AD:BE:EF:DE:AD"); }
} // namespace dummy
} // namespace bwl
| 30.466667 | 99 | 0.596827 |
56462c507604830c90548b7dd8baeb644686fd66 | 6,490 | cpp | C++ | Core/STL/OS/Posix/PosixSyncPrimitives.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | Core/STL/OS/Posix/PosixSyncPrimitives.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | Core/STL/OS/Posix/PosixSyncPrimitives.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt'
#include "Core/STL/Common/Platforms.h"
#if defined( PLATFORM_BASE_POSIX ) and defined( GX_USE_NATIVE_API )
#include "Core/STL/OS/Posix/SyncPrimitives.h"
namespace GX_STL
{
namespace OS
{
/*
=================================================
constructor
=================================================
*/
Mutex::Mutex ()
{
static const pthread_mutex_t tmp = PTHREAD_MUTEX_INITIALIZER;
_mutex = tmp;
# if 1
::pthread_mutex_init( OUT &_mutex, null ) == 0;
# else
pthread_mutexattr_t attr;
::pthread_mutexattr_init( &attr );
::pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
::pthread_mutex_init( &_mutex, &attr ) == 0;
# endif
}
/*
=================================================
destructor
=================================================
*/
Mutex::~Mutex ()
{
::pthread_mutex_destroy( &_mutex );
}
/*
=================================================
Lock
=================================================
*/
void Mutex::Lock ()
{
bool res = ::pthread_mutex_lock( &_mutex ) == 0;
ASSERT( res );
}
/*
=================================================
TryLock
=================================================
*/
bool Mutex::TryLock ()
{
return ::pthread_mutex_trylock( &_mutex ) == 0;
}
/*
=================================================
Unlock
=================================================
*/
void Mutex::Unlock ()
{
bool res = ::pthread_mutex_unlock( &_mutex ) == 0;
ASSERT( res );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
ReadWriteSync::ReadWriteSync ()
{
::pthread_rwlock_init( OUT &_rwlock, null );
}
/*
=================================================
destructor
=================================================
*/
ReadWriteSync::~ReadWriteSync ()
{
::pthread_rwlock_destroy( &_rwlock );
}
/*
=================================================
LockWrite
=================================================
*/
void ReadWriteSync::LockWrite ()
{
bool res = ::pthread_rwlock_wrlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
TryLockWrite
=================================================
*/
bool ReadWriteSync::TryLockWrite ()
{
return ::pthread_rwlock_trywrlock( &_rwlock ) == 0;
}
/*
=================================================
UnlockWrite
=================================================
*/
void ReadWriteSync::UnlockWrite ()
{
bool res = ::pthread_rwlock_unlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
LockRead
=================================================
*/
void ReadWriteSync::LockRead ()
{
bool res = ::pthread_rwlock_rdlock( &_rwlock ) == 0;
ASSERT( res );
}
/*
=================================================
TryLockRead
=================================================
*/
bool ReadWriteSync::TryLockRead ()
{
return ::pthread_rwlock_tryrdlock( &_rwlock ) == 0;
}
/*
=================================================
UnlockRead
=================================================
*/
void ReadWriteSync::UnlockRead ()
{
bool res = ::pthread_rwlock_unlock( &_rwlock ) == 0;
ASSERT( res );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
ConditionVariable::ConditionVariable ()
{
::pthread_cond_init( OUT &_cv, null );
}
/*
=================================================
destructor
=================================================
*/
ConditionVariable::~ConditionVariable ()
{
::pthread_cond_destroy( &_cv );
}
/*
=================================================
Signal
=================================================
*/
void ConditionVariable::Signal ()
{
bool res = ::pthread_cond_signal( &_cv ) == 0;
ASSERT( res );
}
/*
=================================================
Broadcast
=================================================
*/
void ConditionVariable::Broadcast ()
{
bool res = ::pthread_cond_broadcast( &_cv ) == 0;
ASSERT( res );
}
/*
=================================================
Wait
=================================================
*/
bool ConditionVariable::Wait (Mutex &cs)
{
return ::pthread_cond_wait( &_cv, &cs._mutex ) == 0;
}
/*
=================================================
Wait
=================================================
*/
bool ConditionVariable::Wait (Mutex &cs, TimeL time)
{
struct timespec currTime;
::clock_gettime( CLOCK_REALTIME, OUT &currTime );
// TODO: check
currTime.tv_nsec += time.MilliSeconds() * 1000;
currTime.tv_sec += currTime.tv_nsec / 1000000000;
return ::pthread_cond_timedwait( &_cv, &cs._mutex, &currTime );
}
//-----------------------------------------------------------------------------
/*
=================================================
constructor
=================================================
*/
Semaphore::Semaphore (GXTypes::uint initialValue)
{
::sem_init( OUT &_sem, 0, initialValue );
}
/*
=================================================
destructor
=================================================
*/
Semaphore::~Semaphore ()
{
::sem_destroy( &_sem );
}
/*
=================================================
Lock
=================================================
*/
void Semaphore::Lock ()
{
int result = ::sem_wait( &_sem );
ASSERT( result == 0 );
}
/*
=================================================
TryLock
=================================================
*/
bool Semaphore::TryLock ()
{
int result = ::sem_trywait( &_sem );
return result == 0;
}
/*
=================================================
Unlock
=================================================
*/
void Semaphore::Unlock ()
{
int result = ::sem_post( &_sem );
ASSERT( result == 0 );
}
/*
=================================================
GetValue
=================================================
*/
GXTypes::uint Semaphore::GetValue ()
{
int value = 0;
int result = ::sem_getvalue( &_sem, &value );
ASSERT( result == 0 );
return value;
}
} // OS
} // GX_STL
#endif // PLATFORM_BASE_POSIX and GX_USE_NATIVE_API
| 20.868167 | 79 | 0.362096 |
5646b3b326d2c2b9566bf4b7824be6668dd58e77 | 1,078 | cpp | C++ | examples/tutorial/hello_job_world.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | examples/tutorial/hello_job_world.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | examples/tutorial/hello_job_world.cpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | // Copyright (c) 2011 Ole Weidner, Louisiana State University
//
// This is part of the code examples on the SAGA website:
// http://saga-project.org/documentation/tutorials/job-api
#include <saga/saga.hpp>
int main(int argc, char* argv[])
{
try
{
// create an "echo 'hello, world' job"
saga::job::description jd;
jd.set_attribute("Interactive", "True");
jd.set_attribute("Executable", "/bin/echo");
std::vector<std::string> args;
args.push_back("Hello, World!");
jd.set_vector_attribute("Arguments", args);
// connect to the local job service
saga::job::service js("fork://localhost");
// submit the job
saga::job::job job = js.create_job(jd);
job.run();
//wait for the job to complete
job.wait(-1);
// print the job's output
saga::job::istream output = job.get_stdout();
std::string line;
while ( ! std::getline (output, line).eof () )
{
std::cout << line << std::endl;
}
}
catch(saga::exception const & e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| 24.5 | 62 | 0.611317 |
56498b71024b3b090fb1cdb71ccf3e66e649ba7a | 19,728 | cpp | C++ | src/mongo/db/query/cursor_response_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/cursor_response_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/query/cursor_response_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/cursor_response.h"
#include "mongo/rpc/op_msg_rpc_impls.h"
#include "mongo/db/pipeline/resume_token.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
namespace {
TEST(CursorResponseTest, parseFromBSONFirstBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONNextBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONCursorIdZero) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(0) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(0));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
}
TEST(CursorResponseTest, parseFromBSONEmptyBatch) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSONArrayBuilder().arr())
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 0U);
}
TEST(CursorResponseTest, parseFromBSONMissingCursorField) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON("ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONCursorFieldWrongType) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << 3 << "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNsFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "firstBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNsFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns" << 456 << "firstBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONIdFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONIdFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id"
<< "123"
<< "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONBatchFieldMissing) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll")
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONFirstBatchFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON("_id" << 1))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONNextBatchFieldWrongType) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON("_id" << 1))
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONOkFieldMissing) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONPartialResultsReturnedField) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << true)
<< "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_EQ(response.getPartialResultsReturned(), true);
}
TEST(CursorResponseTest, parseFromBSONPartialResultsReturnedFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << 1)
<< "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONVarsFieldCorrect) {
BSONObj varsContents = BSON("randomVar" << 7);
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << varsContents << "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_TRUE(response.getVarsField());
ASSERT_BSONOBJ_EQ(response.getVarsField().get(), varsContents);
}
TEST(CursorResponseTest, parseFromBSONVarsFieldWrongType) {
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << 2 << "ok" << 1));
ASSERT_NOT_OK(result.getStatus());
}
TEST(CursorResponseTest, parseFromBSONMultipleVars) {
BSONObj varsContents = BSON("randomVar" << 7 << "otherVar" << BSON("nested" << 2));
StatusWith<CursorResponse> result = CursorResponse::parseFromBSON(BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "vars" << varsContents << "ok" << 1));
ASSERT_OK(result.getStatus());
CursorResponse response = std::move(result.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], BSON("_id" << 1));
ASSERT_BSONOBJ_EQ(response.getBatch()[1], BSON("_id" << 2));
ASSERT_TRUE(response.getVarsField());
ASSERT_BSONOBJ_EQ(response.getVarsField().get(), varsContents);
}
TEST(CursorResponseTest, roundTripThroughCursorResponseBuilderWithPartialResultsReturned) {
CursorResponseBuilder::Options options;
options.isInitialResponse = true;
rpc::OpMsgReplyBuilder builder;
BSONObj okStatus = BSON("ok" << 1);
BSONObj testDoc = BSON("_id" << 1);
BSONObj expectedBody =
BSON("cursor" << BSON("firstBatch" << BSON_ARRAY(testDoc) << "partialResultsReturned"
<< true << "id" << CursorId(123) << "ns"
<< "db.coll"));
// Use CursorResponseBuilder to serialize the cursor response to OpMsgReplyBuilder.
CursorResponseBuilder crb(&builder, options);
crb.append(testDoc);
crb.setPartialResultsReturned(true);
crb.done(CursorId(123), "db.coll");
// Confirm that the resulting BSONObj response matches the expected body.
auto msg = builder.done();
auto opMsg = OpMsg::parse(msg);
ASSERT_BSONOBJ_EQ(expectedBody, opMsg.body);
// Append {"ok": 1} to the opMsg body so that it can be parsed by CursorResponse.
auto swCursorResponse = CursorResponse::parseFromBSON(opMsg.body.addField(okStatus["ok"]));
ASSERT_OK(swCursorResponse.getStatus());
// Confirm the CursorReponse parsed from CursorResponseBuilder output has the correct content.
CursorResponse response = std::move(swCursorResponse.getValue());
ASSERT_EQ(response.getCursorId(), CursorId(123));
ASSERT_EQ(response.getNSS().ns(), "db.coll");
ASSERT_EQ(response.getBatch().size(), 1U);
ASSERT_BSONOBJ_EQ(response.getBatch()[0], testDoc);
ASSERT_EQ(response.getPartialResultsReturned(), true);
// Re-serialize a BSONObj response from the CursorResponse.
auto cursorResBSON = response.toBSONAsInitialResponse();
// Confirm that the BSON serialized by the CursorResponse is the same as that serialized by the
// CursorResponseBuilder. Field ordering differs between the two, so compare per-element.
BSONObjIteratorSorted cursorResIt(cursorResBSON["cursor"].Obj());
BSONObjIteratorSorted cursorBuilderIt(opMsg.body["cursor"].Obj());
while (cursorResIt.more()) {
ASSERT(cursorBuilderIt.more());
ASSERT_EQ(cursorResIt.next().woCompare(cursorBuilderIt.next()), 0);
}
ASSERT(!cursorBuilderIt.more());
}
TEST(CursorResponseTest, parseFromBSONHandleErrorResponse) {
StatusWith<CursorResponse> result =
CursorResponse::parseFromBSON(BSON("ok" << 0 << "code" << 123 << "errmsg"
<< "does not work"));
ASSERT_NOT_OK(result.getStatus());
ASSERT_EQ(result.getStatus().code(), 123);
ASSERT_EQ(result.getStatus().reason(), "does not work");
}
TEST(CursorResponseTest, toBSONInitialResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::InitialResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, toBSONSubsequentResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::SubsequentResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, toBSONPartialResultsReturned) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"),
CursorId(123),
batch,
boost::none,
boost::none,
boost::none,
boost::none,
boost::none,
true);
BSONObj responseObj = response.toBSON(CursorResponse::ResponseType::InitialResponse);
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "partialResultsReturned" << true)
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, addToBSONInitialResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObjBuilder builder;
response.addToBSON(CursorResponse::ResponseType::InitialResponse, &builder);
BSONObj responseObj = builder.obj();
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "firstBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, addToBSONSubsequentResponse) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
CursorResponse response(NamespaceString("testdb.testcoll"), CursorId(123), batch);
BSONObjBuilder builder;
response.addToBSON(CursorResponse::ResponseType::SubsequentResponse, &builder);
BSONObj responseObj = builder.obj();
BSONObj expectedResponse = BSON(
"cursor" << BSON("id" << CursorId(123) << "ns"
<< "testdb.testcoll"
<< "nextBatch" << BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2)))
<< "ok" << 1.0);
ASSERT_BSONOBJ_EQ(responseObj, expectedResponse);
}
TEST(CursorResponseTest, serializePostBatchResumeToken) {
std::vector<BSONObj> batch = {BSON("_id" << 1), BSON("_id" << 2)};
auto postBatchResumeToken =
ResumeToken::makeHighWaterMarkToken(Timestamp(1, 2), ResumeTokenData::kDefaultTokenVersion)
.toDocument()
.toBson();
CursorResponse response(
NamespaceString("db.coll"), CursorId(123), batch, boost::none, postBatchResumeToken);
auto serialized = response.toBSON(CursorResponse::ResponseType::SubsequentResponse);
ASSERT_BSONOBJ_EQ(serialized,
BSON("cursor" << BSON("id" << CursorId(123) << "ns"
<< "db.coll"
<< "nextBatch"
<< BSON_ARRAY(BSON("_id" << 1) << BSON("_id" << 2))
<< "postBatchResumeToken" << postBatchResumeToken)
<< "ok" << 1));
auto reparsed = CursorResponse::parseFromBSON(serialized);
ASSERT_OK(reparsed.getStatus());
CursorResponse reparsedResponse = std::move(reparsed.getValue());
ASSERT_EQ(reparsedResponse.getCursorId(), CursorId(123));
ASSERT_EQ(reparsedResponse.getNSS().ns(), "db.coll");
ASSERT_EQ(reparsedResponse.getBatch().size(), 2U);
ASSERT_BSONOBJ_EQ(*reparsedResponse.getPostBatchResumeToken(), postBatchResumeToken);
}
} // namespace
} // namespace mongo
| 46.748815 | 100 | 0.589822 |
5649ef306425c4e66478968eedf4b5296864a7e2 | 8,692 | cpp | C++ | src/lock_free_set.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | src/lock_free_set.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | src/lock_free_set.cpp | cconklin/nonblocking-tables | 82acacbb16342ad36156931b9969674d85114d21 | [
"MIT"
] | null | null | null | #include <lock_free_set.hpp>
namespace nonblocking
{
template<> versioned<lock_free_set::bucket_state>::versioned(unsigned int version, lock_free_set::bucket_state value) : _version{version}
{
switch (value)
{
case lock_free_set::bucket_state::empty: _value = 0; break;
case lock_free_set::bucket_state::busy: _value = 1; break;
case lock_free_set::bucket_state::collided: _value = 2; break;
case lock_free_set::bucket_state::visible: _value = 3; break;
case lock_free_set::bucket_state::inserting: _value = 4; break;
case lock_free_set::bucket_state::member: _value = 5; break;
}
}
template<> versioned<lock_free_set::bucket_state>::versioned() noexcept : _version{0}, _value{0} {}
template<> bool versioned<lock_free_set::bucket_state>::operator==(versioned<lock_free_set::bucket_state> other)
{
return (_version == other._version) && (_value == other._value);
}
template<> lock_free_set::bucket_state versioned<lock_free_set::bucket_state>::value()
{
switch (_value)
{
case 0: return lock_free_set::bucket_state::empty;
case 1: return lock_free_set::bucket_state::busy;
case 2: return lock_free_set::bucket_state::collided;
case 3: return lock_free_set::bucket_state::visible;
case 4: return lock_free_set::bucket_state::inserting;
case 5: return lock_free_set::bucket_state::member;
default: return lock_free_set::bucket_state::busy;
}
}
template<> unsigned int versioned<lock_free_set::bucket_state>::version()
{
return _version;
}
lock_free_set::bucket::bucket(unsigned int key, unsigned int version, lock_free_set::bucket_state state) : key{key}, vs(versioned<lock_free_set::bucket_state>(version, state)) {}
lock_free_set::bucket::bucket() : key{0}, vs(versioned<lock_free_set::bucket_state>()) {}
lock_free_set::bucket* lock_free_set::bucket_at(unsigned int h, int index)
{
return &buckets[(h+index*(index+1)/2)%size];
}
bool lock_free_set::does_bucket_contain_collision(unsigned int h, int index)
{
auto state = bucket_at(h, index)->vs.load(std::memory_order_acquire);
if ((state.value() == visible) || (state.value() == inserting) || (state.value() == member))
{
if (hash(bucket_at(h, index)->key.load(std::memory_order_acquire)) == h)
{
auto state2 = bucket_at(h, index)->vs.load(std::memory_order_relaxed);
if ((state2.value() == visible) || (state2.value() == inserting) || (state2.value() == member))
{
if (state2.version() == state.version())
{
return true;
}
}
}
}
return false;
}
lock_free_set::lock_free_set(unsigned int size) : base(size)
{
buckets = new bucket[size];
std::atomic_thread_fence(std::memory_order_release);
}
bool lock_free_set::lookup(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
auto state = bucket_at(h, i)->vs.load(std::memory_order_acquire);
if ((state.value() == member) && (bucket_at(h, i)->key.load(std::memory_order_acquire) == key))
{
auto state2 = bucket_at(h, i)->vs.load(std::memory_order_relaxed);
if (state == state2)
{
return true;
}
}
}
return false;
}
bool lock_free_set::erase(unsigned int key)
{
unsigned int h = hash(key);
auto max = get_probe_bound(h);
for (unsigned int i = 0; i <= max; ++i)
{
auto* bucket = bucket_at(h, i);
auto state = bucket->vs.load(std::memory_order_acquire);
if ((state.value() == member) && (bucket->key.load(std::memory_order_acquire) == key))
{
if (std::atomic_compare_exchange_strong_explicit(&bucket->vs, &state, versioned<bucket_state>(state.version(), busy), std::memory_order_release, std::memory_order_relaxed))
{
conditionally_lower_bound(h, i);
bucket->vs.store(versioned<bucket_state>(state.version() + 1, empty), std::memory_order_release);
return true;
}
}
}
return false;
}
bool lock_free_set::insert(unsigned int key)
{
unsigned int h = hash(key);
int i = -1;
unsigned int version;
versioned<bucket_state> old_vs;
versioned<bucket_state> new_vs;
do
{
if (++i >= size)
{
throw "Table full";
}
version = bucket_at(h, i)->vs.load(std::memory_order_acquire).version();
old_vs = versioned<bucket_state>(version, empty);
new_vs = versioned<bucket_state>(version, busy);
}
while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, new_vs, std::memory_order_release, std::memory_order_relaxed));
bucket_at(h, i)->key.store(key, std::memory_order_relaxed);
while (true)
{
bucket_at(h, i)->vs.store(versioned<bucket_state>(version, visible), std::memory_order_release);
conditionally_raise_bound(h, i);
bucket_at(h, i)->vs.store(versioned<bucket_state>(version, inserting), std::memory_order_release);
auto r = assist(key, h, i, version);
if (!(bucket_at(h, i)->vs.load(std::memory_order_acquire) == versioned<bucket_state>(version, collided)))
{
return true;
}
if (!r)
{
conditionally_lower_bound(h, i);
bucket_at(h, i)->vs.store(versioned<bucket_state>(version+1, empty), std::memory_order_release);
return false;
}
version++;
}
}
bool lock_free_set::assist(unsigned int key, unsigned int h, int i, unsigned int ver_i)
{
auto max = get_probe_bound(h);
versioned<bucket_state> old_vs(ver_i, inserting);
for (unsigned int j = 0; j <= max; j++)
{
if (i != j)
{
auto* bkt_at = bucket_at(h, j);
auto state = bkt_at->vs.load(std::memory_order_acquire);
if ((state.value() == inserting) && (bkt_at->key.load(std::memory_order_acquire) == key))
{
if (j < i)
{
auto j_state = bkt_at->vs.load(std::memory_order_relaxed);
if (j_state == state)
{
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, collided), std::memory_order_relaxed, std::memory_order_relaxed);
return assist(key, h, j, state.version());
}
}
else
{
auto i_state = bucket_at(h, i)->vs.load(std::memory_order_acquire);
if (i_state == versioned<bucket_state>(ver_i, inserting))
{
std::atomic_compare_exchange_strong_explicit(&bkt_at->vs, &state, versioned<bucket_state>(state.version(), collided), std::memory_order_relaxed, std::memory_order_relaxed);
}
}
}
auto new_state = bkt_at->vs.load(std::memory_order_acquire);
if ((new_state.value() == member) && (bkt_at->key.load(std::memory_order_acquire) == key))
{
if (bkt_at->vs.load(std::memory_order_relaxed) == new_state)
{
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, collided), std::memory_order_relaxed, std::memory_order_relaxed);
return false;
}
}
}
}
std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->vs, &old_vs, versioned<bucket_state>(ver_i, member), std::memory_order_release, std::memory_order_relaxed);
return true;
}
lock_free_set::~lock_free_set()
{
delete buckets;
}
}
| 41.788462 | 200 | 0.554648 |
5649f39794bcb8d696576f12970d330136ab6d9e | 955 | cpp | C++ | src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp | Thisisderpys/my-little-investigations | 0689f2ca3e808ba39864f024280abd2e77f8ad20 | [
"MIT"
] | 41 | 2015-01-24T17:33:16.000Z | 2022-01-08T19:36:40.000Z | src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp | Thisisderpys/my-little-investigations | 0689f2ca3e808ba39864f024280abd2e77f8ad20 | [
"MIT"
] | 15 | 2015-01-05T21:00:41.000Z | 2016-10-18T14:37:03.000Z | src/CaseCreator/UIComponents/CharacterTab/CharacterDialogSpritesPage.cpp | Thisisderpys/my-little-investigations | 0689f2ca3e808ba39864f024280abd2e77f8ad20 | [
"MIT"
] | 6 | 2016-01-14T21:07:22.000Z | 2020-11-28T09:51:15.000Z | #include "CharacterDialogSpritesPage.h"
#include <QVBoxLayout>
CharacterDialogSpritesPage::CharacterDialogSpritesPage(QWidget *parent) :
Page<Character>(parent)
{
isActive = false;
QVBoxLayout *pMainLayout = new QVBoxLayout();
pEmotionManipulator = new ListManipulator<Character::DialogEmotion>();
pMainLayout->addWidget(pEmotionManipulator);
setLayout(pMainLayout);
}
void CharacterDialogSpritesPage::Init(Character *pObject)
{
if (pObject == NULL)
{
return;
}
Page<Character>::Init(pObject);
pEmotionManipulator->SetParentObject(pObject);
}
void CharacterDialogSpritesPage::Reset()
{
pEmotionManipulator->Reset();
}
bool CharacterDialogSpritesPage::GetIsActive()
{
return isActive;
}
void CharacterDialogSpritesPage::SetIsActive(bool isActive)
{
if (this->isActive != isActive)
{
this->isActive = isActive;
pEmotionManipulator->SetIsActive(isActive);
}
}
| 20.319149 | 74 | 0.71623 |
871cfb6e6280a3cc476906643eb4d3e0a1ce5d5a | 36,782 | cxx | C++ | libbuild2/cc/module.cxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 422 | 2018-05-30T12:00:00.000Z | 2022-03-29T07:29:56.000Z | libbuild2/cc/module.cxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 183 | 2018-07-02T20:38:30.000Z | 2022-03-31T09:54:35.000Z | libbuild2/cc/module.cxx | build2/build2 | af662849b756ef2ff0f3d5148a6771acab78fd80 | [
"MIT"
] | 14 | 2019-01-09T12:34:02.000Z | 2021-03-16T09:10:53.000Z | // file : libbuild2/cc/module.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <libbuild2/cc/module.hxx>
#include <iomanip> // left, setw()
#include <libbuild2/scope.hxx>
#include <libbuild2/function.hxx>
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/bin/target.hxx>
#include <libbuild2/cc/target.hxx> // pc*
#include <libbuild2/config/utility.hxx>
#include <libbuild2/install/utility.hxx>
#include <libbuild2/cc/guess.hxx>
using namespace std;
using namespace butl;
namespace build2
{
namespace cc
{
void config_module::
guess (scope& rs, const location& loc, const variable_map&)
{
tracer trace (x, "guess_init");
bool cc_loaded (cast_false<bool> (rs["cc.core.guess.loaded"]));
// Adjust module priority (compiler). Also order cc module before us
// (we don't want to use priorities for that in case someone manages
// to slot in-between).
//
if (!cc_loaded)
config::save_module (rs, "cc", 250);
config::save_module (rs, x, 250);
auto& vp (rs.var_pool ());
// Must already exist.
//
const variable& config_c_poptions (vp["config.cc.poptions"]);
const variable& config_c_coptions (vp["config.cc.coptions"]);
const variable& config_c_loptions (vp["config.cc.loptions"]);
// Configuration.
//
using config::lookup_config;
// config.x
//
strings mode;
{
// Normally we will have a persistent configuration and computing the
// default value every time will be a waste. So try without a default
// first.
//
lookup l (lookup_config (new_config, rs, config_x));
if (!l)
{
// If there is a config.x value for one of the modules that can hint
// us the toolchain, load it's .guess module. This makes sure that
// the order in which we load the modules is unimportant and that
// the user can specify the toolchain using any of the config.x
// values.
//
if (!cc_loaded)
{
for (const char* const* pm (x_hinters); *pm != nullptr; ++pm)
{
string m (*pm);
// Must be the same as in module's init().
//
const variable& v (vp.insert<strings> ("config." + m));
if (rs[v].defined ())
{
init_module (rs, rs, m + ".guess", loc);
cc_loaded = true;
break;
}
}
}
// If cc.core.guess is already loaded then use its toolchain id,
// (optional) pattern, and mode to guess an appropriate default
// (e.g., for {gcc, *-4.9 -m64} we will get g++-4.9 -m64).
//
strings d;
if (cc_loaded)
d = guess_default (x_lang,
cast<string> (rs["cc.id"]),
cast<string> (rs["cc.pattern"]),
cast<strings> (rs["cc.mode"]));
else
{
// Note that we don't have the default mode: it doesn't feel
// correct to default to, say, -m64 simply because that's how
// build2 was built.
//
d.push_back (x_default);
if (d.front ().empty ())
fail << "not built with default " << x_lang << " compiler" <<
info << "use " << config_x << " to specify";
}
// If this value was hinted, save it as commented out so that if the
// user changes the source of the pattern/mode, this one will get
// updated as well.
//
l = lookup_config (new_config,
rs,
config_x,
move (d),
cc_loaded ? config::save_default_commented : 0);
}
// Split the value into the compiler path and mode.
//
const strings& v (cast<strings> (l));
path xc;
{
const string& s (v.empty () ? empty_string : v.front ());
try { xc = path (s); } catch (const invalid_path&) {}
if (xc.empty ())
fail << "invalid path '" << s << "' in " << config_x;
}
mode.assign (++v.begin (), v.end ());
// Save original path/mode in *.config.path/mode.
//
rs.assign (x_c_path) = xc;
rs.assign (x_c_mode) = mode;
// Figure out which compiler we are dealing with, its target, etc.
//
// Note that we could allow guess() to modify mode to support
// imaginary options (such as /MACHINE for cl.exe). Though it's not
// clear what cc.mode would contain (original or modified). Note that
// we are now folding *.std options into mode options.
//
x_info = &build2::cc::guess (
x, x_lang,
rs.root_extra->environment_checksum,
move (xc),
cast_null<string> (lookup_config (rs, config_x_id)),
cast_null<string> (lookup_config (rs, config_x_version)),
cast_null<string> (lookup_config (rs, config_x_target)),
mode,
cast_null<strings> (rs[config_c_poptions]),
cast_null<strings> (rs[config_x_poptions]),
cast_null<strings> (rs[config_c_coptions]),
cast_null<strings> (rs[config_x_coptions]),
cast_null<strings> (rs[config_c_loptions]),
cast_null<strings> (rs[config_x_loptions]));
}
const compiler_info& xi (*x_info);
// Split/canonicalize the target. First see if the user asked us to use
// config.sub.
//
target_triplet tt;
{
string ct;
if (config_sub)
{
ct = run<string> (3,
*config_sub,
xi.target.c_str (),
[] (string& l, bool) {return move (l);});
l5 ([&]{trace << "config.sub target: '" << ct << "'";});
}
try
{
tt = target_triplet (ct.empty () ? xi.target : ct);
l5 ([&]{trace << "canonical target: '" << tt.string () << "'; "
<< "class: " << tt.class_;});
}
catch (const invalid_argument& e)
{
// This is where we suggest that the user specifies --config-sub to
// help us out.
//
fail << "unable to parse " << x_lang << " compiler target '"
<< xi.target << "': " << e <<
info << "consider using the --config-sub option";
}
}
// Hash the environment (used for change detection).
//
// Note that for simplicity we use the combined checksum for both
// compilation and linking (which may compile, think LTO).
//
{
sha256 cs;
hash_environment (cs, xi.compiler_environment);
hash_environment (cs, xi.platform_environment);
env_checksum = cs.string ();
}
// Assign values to variables that describe the compiler.
//
rs.assign (x_path) = process_path_ex (
xi.path, x_name, xi.checksum, env_checksum);
const strings& xm (cast<strings> (rs.assign (x_mode) = move (mode)));
rs.assign (x_id) = xi.id.string ();
rs.assign (x_id_type) = to_string (xi.id.type);
rs.assign (x_id_variant) = xi.id.variant;
rs.assign (x_class) = to_string (xi.class_);
auto assign_version = [&rs] (const variable** vars,
const compiler_version* v)
{
rs.assign (vars[0]) = v != nullptr ? value (v->string) : value ();
rs.assign (vars[1]) = v != nullptr ? value (v->major) : value ();
rs.assign (vars[2]) = v != nullptr ? value (v->minor) : value ();
rs.assign (vars[3]) = v != nullptr ? value (v->patch) : value ();
rs.assign (vars[4]) = v != nullptr ? value (v->build) : value ();
};
assign_version (&x_version, &xi.version);
assign_version (&x_variant_version,
xi.variant_version ? &*xi.variant_version : nullptr);
rs.assign (x_signature) = xi.signature;
rs.assign (x_checksum) = xi.checksum;
// Also enter as x.target.{cpu,vendor,system,version,class} for
// convenience of access.
//
rs.assign (x_target_cpu) = tt.cpu;
rs.assign (x_target_vendor) = tt.vendor;
rs.assign (x_target_system) = tt.system;
rs.assign (x_target_version) = tt.version;
rs.assign (x_target_class) = tt.class_;
rs.assign (x_target) = move (tt);
rs.assign (x_pattern) = xi.pattern;
if (!x_stdlib.alias (c_stdlib))
rs.assign (x_stdlib) = xi.x_stdlib;
// Load cc.core.guess.
//
if (!cc_loaded)
{
// Prepare configuration hints.
//
variable_map h (rs.ctx);
// Note that all these variables have already been registered.
//
h.assign ("config.cc.id") = cast<string> (rs[x_id]);
h.assign ("config.cc.hinter") = string (x);
h.assign ("config.cc.target") = cast<target_triplet> (rs[x_target]);
if (!xi.pattern.empty ())
h.assign ("config.cc.pattern") = xi.pattern;
if (!xm.empty ())
h.assign ("config.cc.mode") = xm;
h.assign (c_runtime) = xi.runtime;
h.assign (c_stdlib) = xi.c_stdlib;
init_module (rs, rs, "cc.core.guess", loc, false, h);
}
else
{
// If cc.core.guess is already loaded, verify its configuration
// matched ours since it could have been loaded by another c-family
// module.
//
const auto& h (cast<string> (rs["cc.hinter"]));
auto check = [&loc, &h, this] (const auto& cv,
const auto& xv,
const char* what,
bool error = true)
{
if (cv != xv)
{
diag_record dr (error ? fail (loc) : warn (loc));
dr << h << " and " << x << " module " << what << " mismatch" <<
info << h << " is '" << cv << "'" <<
info << x << " is '" << xv << "'" <<
info << "consider explicitly specifying config." << h
<< " and config." << x;
}
};
check (cast<string> (rs["cc.id"]),
cast<string> (rs[x_id]),
"toolchain");
// We used to not require that patterns match assuming that if the
// toolchain id and target are the same, then where exactly the tools
// come from doesn't really matter. But in most cases it will be the
// g++-7 vs gcc kind of mistakes. So now we warn since even if
// intentional, it is still probably a bad idea.
//
// Note also that it feels right to allow different modes (think
// -fexceptions for C or -fno-rtti for C++).
//
check (cast<string> (rs["cc.pattern"]),
cast<string> (rs[x_pattern]),
"toolchain pattern",
false);
check (cast<target_triplet> (rs["cc.target"]),
cast<target_triplet> (rs[x_target]),
"target");
check (cast<string> (rs["cc.runtime"]),
xi.runtime,
"runtime");
check (cast<string> (rs["cc.stdlib"]),
xi.c_stdlib,
"c standard library");
}
}
#ifndef _WIN32
static const dir_path usr_inc ("/usr/include");
static const dir_path usr_loc_lib ("/usr/local/lib");
static const dir_path usr_loc_inc ("/usr/local/include");
# ifdef __APPLE__
static const dir_path a_usr_inc (
"/Library/Developer/CommandLineTools/SDKs/MacOSX*.sdk/usr/include");
# endif
#endif
// Extracting search dirs can be expensive (we may need to run the
// compiler several times) so we cache the result.
//
struct search_dirs
{
pair<dir_paths, size_t> lib;
pair<dir_paths, size_t> hdr;
};
static global_cache<search_dirs> dirs_cache;
void config_module::
init (scope& rs, const location& loc, const variable_map&)
{
tracer trace (x, "config_init");
const compiler_info& xi (*x_info);
const target_triplet& tt (cast<target_triplet> (rs[x_target]));
// Load cc.core.config.
//
if (!cast_false<bool> (rs["cc.core.config.loaded"]))
{
variable_map h (rs.ctx);
if (!xi.bin_pattern.empty ())
h.assign ("config.bin.pattern") = xi.bin_pattern;
init_module (rs, rs, "cc.core.config", loc, false, h);
}
// Configuration.
//
using config::lookup_config;
// config.x.{p,c,l}options
// config.x.libs
//
// These are optional. We also merge them into the corresponding
// x.* variables.
//
// The merging part gets a bit tricky if this module has already
// been loaded in one of the outer scopes. By doing the straight
// append we would just be repeating the same options over and
// over. So what we are going to do is only append to a value if
// it came from this scope. Then the usage for merging becomes:
//
// @@ There are actually two cases to this issue:
//
// 1. The module is loaded in the outer project (e.g., tests inside a
// project). It feels like this should be handled with project
// variable visibility. And now it is with the project being the
// default. Note that this is the reason we don't need any of this
// for the project configuration: there the config.* variables are
// always set on the project root.
//
// 2. The module is loaded in the outer scope within the same
// project. We are currently thinking whether we should even
// support loading of modules in non-root scopes.
//
// x.coptions = <overridable options> # Note: '='.
// using x
// x.coptions += <overriding options> # Note: '+='.
//
rs.assign (x_poptions) += cast_null<strings> (
lookup_config (rs, config_x_poptions, nullptr));
rs.assign (x_coptions) += cast_null<strings> (
lookup_config (rs, config_x_coptions, nullptr));
rs.assign (x_loptions) += cast_null<strings> (
lookup_config (rs, config_x_loptions, nullptr));
rs.assign (x_aoptions) += cast_null<strings> (
lookup_config (rs, config_x_aoptions, nullptr));
rs.assign (x_libs) += cast_null<strings> (
lookup_config (rs, config_x_libs, nullptr));
// config.x.std overrides x.std
//
strings& mode (cast<strings> (rs.assign (x_mode))); // Set by guess.
{
lookup l (lookup_config (rs, config_x_std));
const string* v;
if (l.defined ())
{
v = cast_null<string> (l);
rs.assign (x_std) = v;
}
else
v = cast_null<string> (rs[x_std]);
// Translate x_std value (if any) to the compiler option(s) (if any)
// and fold them into the compiler mode.
//
translate_std (xi, tt, rs, mode, v);
}
// config.x.internal.scope
//
// Note: save omitted.
//
// The effective internal_scope value is chosen based on the following
// priority list:
//
// 1. config.x.internal.scope
//
// 2. config.cc.internal.scope
//
// 3. effective value from bundle amalgamation
//
// 4. x.internal.scope
//
// 5. cc.internal.scope
//
// Note also that we only update x.internal.scope (and not cc.*) to
// reflect the effective value.
//
const string* iscope_str (nullptr);
{
if (lookup l = lookup_config (rs, config_x_internal_scope)) // 1
{
iscope_str = &cast<string> (l);
if (*iscope_str == "current")
fail << "'current' value in " << config_x_internal_scope;
}
else if (lookup l = rs["config.cc.internal.scope"]) // 2
{
iscope_str = &cast<string> (l);
}
else // 3
{
const scope& as (*rs.bundle_scope ());
if (as != rs)
{
// Only use the value if the corresponding module is loaded.
//
bool xl (cast_false<bool> (as[string (x) + ".config.loaded"]));
if (xl)
iscope_str = cast_null<string> (as[x_internal_scope]);
if (iscope_str == nullptr)
{
if (xl || cast_false<bool> (as["cc.core.config.loaded"]))
iscope_str = cast_null<string> (as["cc.internal.scope"]);
}
if (iscope_str != nullptr && *iscope_str == "current")
iscope_current = &as;
}
}
lookup l;
if (iscope_str == nullptr)
{
iscope_str = cast_null<string> (l = rs[x_internal_scope]); // 4
if (iscope_str == nullptr)
iscope_str = cast_null<string> (rs["cc.internal.scope"]); // 5
}
if (iscope_str != nullptr)
{
const string& s (*iscope_str);
// Assign effective.
//
if (!l)
rs.assign (x_internal_scope) = s;
if (s == "current")
{
iscope = internal_scope::current;
if (iscope_current == nullptr)
iscope_current = &rs;
}
else if (s == "base") iscope = internal_scope::base;
else if (s == "root") iscope = internal_scope::root;
else if (s == "bundle") iscope = internal_scope::bundle;
else if (s == "strong") iscope = internal_scope::strong;
else if (s == "weak") iscope = internal_scope::weak;
else if (s == "global")
; // Nothing to translate;
else
fail << "invalid " << x_internal_scope << " value '" << s << "'";
}
}
// config.x.translate_include
//
// It's still fuzzy whether specifying (or maybe tweaking) this list in
// the configuration will be a common thing to do so for now we use
// omitted.
//
if (x_translate_include != nullptr)
{
if (lookup l = lookup_config (rs, *config_x_translate_include))
{
// @@ MODHDR: if(modules) ? Yes.
//
rs.assign (x_translate_include).prepend (
cast<translatable_headers> (l));
}
}
// Extract system header/library search paths from the compiler and
// determine if we need any additional search paths.
//
// Note that for now module search paths only come from compiler_info.
//
pair<dir_paths, size_t> lib_dirs;
pair<dir_paths, size_t> hdr_dirs;
const optional<pair<dir_paths, size_t>>& mod_dirs (xi.sys_mod_dirs);
if (xi.sys_lib_dirs && xi.sys_hdr_dirs)
{
lib_dirs = *xi.sys_lib_dirs;
hdr_dirs = *xi.sys_hdr_dirs;
}
else
{
string key;
{
sha256 cs;
cs.append (static_cast<size_t> (x_lang));
cs.append (xi.path.effect_string ());
append_options (cs, mode);
key = cs.string ();
}
// Because the compiler info (xi) is also cached, we can assume that
// if dirs come from there, then they do so consistently.
//
const search_dirs* sd (dirs_cache.find (key));
if (xi.sys_lib_dirs)
lib_dirs = *xi.sys_lib_dirs;
else if (sd != nullptr)
lib_dirs = sd->lib;
else
{
switch (xi.class_)
{
case compiler_class::gcc:
lib_dirs = gcc_library_search_dirs (xi.path, rs);
break;
case compiler_class::msvc:
lib_dirs = msvc_library_search_dirs (xi.path, rs);
break;
}
}
if (xi.sys_hdr_dirs)
hdr_dirs = *xi.sys_hdr_dirs;
else if (sd != nullptr)
hdr_dirs = sd->hdr;
else
{
switch (xi.class_)
{
case compiler_class::gcc:
hdr_dirs = gcc_header_search_dirs (xi.path, rs);
break;
case compiler_class::msvc:
hdr_dirs = msvc_header_search_dirs (xi.path, rs);
break;
}
}
if (sd == nullptr)
{
search_dirs sd;
if (!xi.sys_lib_dirs) sd.lib = lib_dirs;
if (!xi.sys_hdr_dirs) sd.hdr = hdr_dirs;
dirs_cache.insert (move (key), move (sd));
}
}
sys_lib_dirs_mode = lib_dirs.second;
sys_hdr_dirs_mode = hdr_dirs.second;
sys_mod_dirs_mode = mod_dirs ? mod_dirs->second : 0;
sys_lib_dirs_extra = lib_dirs.first.size ();
sys_hdr_dirs_extra = hdr_dirs.first.size ();
#ifndef _WIN32
// Add /usr/local/{include,lib}. We definitely shouldn't do this if we
// are cross-compiling. But even if the build and target are the same,
// it's possible the compiler uses some carefully crafted sysroot and by
// adding /usr/local/* we will just mess things up. So the heuristics
// that we will use is this: if the compiler's system include directories
// contain /usr[/local]/include then we add /usr/local/*.
//
// Note that similar to GCC we also check for the directory existence.
// Failed that, we can end up with some bizarre yo-yo'ing cases where
// uninstall removes the directories which in turn triggers a rebuild
// on the next invocation.
//
{
auto& is (hdr_dirs.first);
auto& ls (lib_dirs.first);
bool ui (find (is.begin (), is.end (), usr_inc) != is.end ());
bool uli (find (is.begin (), is.end (), usr_loc_inc) != is.end ());
#ifdef __APPLE__
// On Mac OS starting from 10.14 there is no longer /usr/include.
// Instead we get the following:
//
// Homebrew GCC 9:
//
// /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include
//
// Apple Clang 10.0.1:
//
// /Library/Developer/CommandLineTools/usr/include
// /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include
//
// What exactly all this means is anyone's guess, of course (see
// homebrew-core issue #46393 for some background). So for now we
// will assume that anything that matches this pattern:
//
// /Library/Developer/CommandLineTools/SDKs/MacOSX*.sdk/usr/include
//
// Is Apple's /usr/include.
//
if (!ui && !uli)
{
for (const dir_path& d: is)
{
if (path_match (d, a_usr_inc))
{
ui = true;
break;
}
}
}
#endif
if (ui || uli)
{
bool ull (find (ls.begin (), ls.end (), usr_loc_lib) != ls.end ());
// Many platforms don't search in /usr/local/lib by default (but do
// for headers in /usr/local/include). So add it as the last option.
//
if (!ull && exists (usr_loc_lib, true /* ignore_error */))
ls.push_back (usr_loc_lib);
// FreeBSD is at least consistent: it searches in neither. Quoting
// its wiki: "FreeBSD can't even find libraries that it installed."
// So let's help it a bit.
//
if (!uli && exists (usr_loc_inc, true /* ignore_error */))
is.push_back (usr_loc_inc);
}
}
#endif
// If this is a configuration with new values, then print the report
// at verbosity level 2 and up (-v).
//
if (verb >= (new_config ? 2 : 3))
{
diag_record dr (text);
{
dr << x << ' ' << project (rs) << '@' << rs << '\n'
<< " " << left << setw (11) << x << xi.path << '\n';
}
if (!mode.empty ())
{
dr << " mode "; // One space short.
for (const string& o: mode)
dr << ' ' << o;
dr << '\n';
}
{
dr << " id " << xi.id << '\n'
<< " version " << xi.version.string << '\n'
<< " major " << xi.version.major << '\n'
<< " minor " << xi.version.minor << '\n'
<< " patch " << xi.version.patch << '\n';
}
if (!xi.version.build.empty ())
{
dr << " build " << xi.version.build << '\n';
}
if (xi.variant_version)
{
dr << " variant:" << '\n'
<< " version " << xi.variant_version->string << '\n'
<< " major " << xi.variant_version->major << '\n'
<< " minor " << xi.variant_version->minor << '\n'
<< " patch " << xi.variant_version->patch << '\n';
}
if (xi.variant_version && !xi.variant_version->build.empty ())
{
dr << " build " << xi.variant_version->build << '\n';
}
{
const string& ct (tt.string ()); // Canonical target.
dr << " signature " << xi.signature << '\n'
<< " checksum " << xi.checksum << '\n'
<< " target " << ct;
if (ct != xi.original_target)
dr << " (" << xi.original_target << ")";
dr << "\n runtime " << xi.runtime
<< "\n stdlib " << xi.x_stdlib;
if (!x_stdlib.alias (c_stdlib))
dr << "\n c stdlib " << xi.c_stdlib;
}
if (!xi.pattern.empty ()) // Note: bin_pattern printed by bin
{
dr << "\n pattern " << xi.pattern;
}
auto& mods (mod_dirs ? mod_dirs->first : dir_paths ());
auto& incs (hdr_dirs.first);
auto& libs (lib_dirs.first);
if (verb >= 3 && iscope)
{
dr << "\n int scope ";
if (*iscope == internal_scope::current)
dr << iscope_current->out_path ();
else
dr << *iscope_str;
}
if (verb >= 3 && !mods.empty ())
{
dr << "\n mod dirs";
for (const dir_path& d: mods)
{
dr << "\n " << d;
}
}
if (verb >= 3 && !incs.empty ())
{
dr << "\n hdr dirs";
for (size_t i (0); i != incs.size (); ++i)
{
if (i == sys_hdr_dirs_extra)
dr << "\n --";
dr << "\n " << incs[i];
}
}
if (verb >= 3 && !libs.empty ())
{
dr << "\n lib dirs";
for (size_t i (0); i != libs.size (); ++i)
{
if (i == sys_lib_dirs_extra)
dr << "\n --";
dr << "\n " << libs[i];
}
}
}
rs.assign (x_sys_lib_dirs) = move (lib_dirs.first);
rs.assign (x_sys_hdr_dirs) = move (hdr_dirs.first);
config::save_environment (rs, xi.compiler_environment);
config::save_environment (rs, xi.platform_environment);
}
// Global cache of ad hoc importable headers.
//
// The key is a hash of the system header search directories
// (sys_hdr_dirs) where we search for the headers.
//
static map<string, importable_headers> importable_headers_cache;
static mutex importable_headers_mutex;
void module::
init (scope& rs,
const location& loc,
const variable_map&,
const compiler_info& xi)
{
tracer trace (x, "init");
context& ctx (rs.ctx);
// Register the module function family if this is the first instance of
// this modules.
//
if (!function_family::defined (ctx.functions, x))
{
function_family f (ctx.functions, x);
compile_rule::functions (f, x);
link_rule::functions (f, x);
}
// Load cc.core. Besides other things, this will load bin (core) plus
// extra bin.* modules we may need.
//
load_module (rs, rs, "cc.core", loc);
// Search include translation headers and groups.
//
if (modules)
{
{
sha256 k;
for (const dir_path& d: sys_hdr_dirs)
k.append (d.string ());
mlock l (importable_headers_mutex);
importable_headers = &importable_headers_cache[k.string ()];
}
auto& hs (*importable_headers);
ulock ul (hs.mutex);
if (hs.group_map.find (header_group_std) == hs.group_map.end ())
guess_std_importable_headers (xi, sys_hdr_dirs, hs);
// Process x.translate_include.
//
const variable& var (*x_translate_include);
if (auto* v = cast_null<translatable_headers> (rs[var]))
{
for (const auto& p: *v)
{
const string& k (p.first);
if (k.front () == '<' && k.back () == '>')
{
if (path_pattern (k))
{
size_t n (hs.insert_angle_pattern (sys_hdr_dirs, k));
l5 ([&]{trace << "pattern " << k << " searched to " << n
<< " headers";});
}
else
{
// What should we do if not found? While we can fail, this
// could be too drastic if, for example, the header is
// "optional" and may or may not be present/used. So for now
// let's ignore (we could have also removed it from the map as
// an indication).
//
const auto* r (hs.insert_angle (sys_hdr_dirs, k));
l5 ([&]{trace << "header " << k << " searched to "
<< (r ? r->first.string ().c_str () : "<none>");});
}
}
else if (path_traits::find_separator (k) == string::npos)
{
// Group name.
//
if (k != header_group_all_importable &&
k != header_group_std_importable &&
k != header_group_all &&
k != header_group_std)
fail (loc) << "unknown header group '" << k << "' in " << var;
}
else
{
// Absolute and normalized header path.
//
if (!path_traits::absolute (k))
fail (loc) << "relative header path '" << k << "' in " << var;
}
}
}
}
// Register target types and configure their "installability".
//
bool install_loaded (cast_false<bool> (rs["install.loaded"]));
{
using namespace install;
rs.insert_target_type (x_src);
auto insert_hdr = [&rs, install_loaded] (const target_type& tt)
{
rs.insert_target_type (tt);
// Install headers into install.include.
//
if (install_loaded)
install_path (rs, tt, dir_path ("include"));
};
// Note: module (x_mod) is in x_hdr.
//
for (const target_type* const* ht (x_hdr); *ht != nullptr; ++ht)
insert_hdr (**ht);
// Also register the C header for C-derived languages.
//
if (*x_hdr != &h::static_type)
insert_hdr (h::static_type);
rs.insert_target_type<pc> ();
rs.insert_target_type<pca> ();
rs.insert_target_type<pcs> ();
if (install_loaded)
install_path<pc> (rs, dir_path ("pkgconfig"));
}
// Register rules.
//
{
using namespace bin;
// If the target doesn't support shared libraries, then don't register
// the corresponding rules.
//
bool s (tsys != "emscripten");
auto& r (rs.rules);
const compile_rule& cr (*this);
const link_rule& lr (*this);
// We register for configure so that we detect unresolved imports
// during configuration rather that later, e.g., during update.
//
r.insert<obje> (perform_update_id, x_compile, cr);
r.insert<obje> (perform_clean_id, x_compile, cr);
r.insert<obje> (configure_update_id, x_compile, cr);
r.insert<obja> (perform_update_id, x_compile, cr);
r.insert<obja> (perform_clean_id, x_compile, cr);
r.insert<obja> (configure_update_id, x_compile, cr);
if (s)
{
r.insert<objs> (perform_update_id, x_compile, cr);
r.insert<objs> (perform_clean_id, x_compile, cr);
r.insert<objs> (configure_update_id, x_compile, cr);
}
if (modules)
{
r.insert<bmie> (perform_update_id, x_compile, cr);
r.insert<bmie> (perform_clean_id, x_compile, cr);
r.insert<bmie> (configure_update_id, x_compile, cr);
r.insert<hbmie> (perform_update_id, x_compile, cr);
r.insert<hbmie> (perform_clean_id, x_compile, cr);
r.insert<hbmie> (configure_update_id, x_compile, cr);
r.insert<bmia> (perform_update_id, x_compile, cr);
r.insert<bmia> (perform_clean_id, x_compile, cr);
r.insert<bmia> (configure_update_id, x_compile, cr);
r.insert<hbmia> (perform_update_id, x_compile, cr);
r.insert<hbmia> (perform_clean_id, x_compile, cr);
r.insert<hbmia> (configure_update_id, x_compile, cr);
if (s)
{
r.insert<bmis> (perform_update_id, x_compile, cr);
r.insert<bmis> (perform_clean_id, x_compile, cr);
r.insert<bmis> (configure_update_id, x_compile, cr);
r.insert<hbmis> (perform_update_id, x_compile, cr);
r.insert<hbmis> (perform_clean_id, x_compile, cr);
r.insert<hbmis> (configure_update_id, x_compile, cr);
}
}
r.insert<libue> (perform_update_id, x_link, lr);
r.insert<libue> (perform_clean_id, x_link, lr);
r.insert<libue> (configure_update_id, x_link, lr);
r.insert<libua> (perform_update_id, x_link, lr);
r.insert<libua> (perform_clean_id, x_link, lr);
r.insert<libua> (configure_update_id, x_link, lr);
if (s)
{
r.insert<libus> (perform_update_id, x_link, lr);
r.insert<libus> (perform_clean_id, x_link, lr);
r.insert<libus> (configure_update_id, x_link, lr);
}
r.insert<exe> (perform_update_id, x_link, lr);
r.insert<exe> (perform_clean_id, x_link, lr);
r.insert<exe> (configure_update_id, x_link, lr);
r.insert<liba> (perform_update_id, x_link, lr);
r.insert<liba> (perform_clean_id, x_link, lr);
r.insert<liba> (configure_update_id, x_link, lr);
if (s)
{
r.insert<libs> (perform_update_id, x_link, lr);
r.insert<libs> (perform_clean_id, x_link, lr);
r.insert<libs> (configure_update_id, x_link, lr);
}
// Note that while libu*{} are not installable, we need to see through
// them in case they depend on stuff that we need to install (see the
// install rule implementations for details).
//
if (install_loaded)
{
const install_rule& ir (*this);
r.insert<exe> (perform_install_id, x_install, ir);
r.insert<exe> (perform_uninstall_id, x_uninstall, ir);
r.insert<liba> (perform_install_id, x_install, ir);
r.insert<liba> (perform_uninstall_id, x_uninstall, ir);
if (s)
{
r.insert<libs> (perform_install_id, x_install, ir);
r.insert<libs> (perform_uninstall_id, x_uninstall, ir);
}
const libux_install_rule& lr (*this);
r.insert<libue> (perform_install_id, x_install, lr);
r.insert<libue> (perform_uninstall_id, x_uninstall, lr);
r.insert<libua> (perform_install_id, x_install, lr);
r.insert<libua> (perform_uninstall_id, x_uninstall, lr);
if (s)
{
r.insert<libus> (perform_install_id, x_install, lr);
r.insert<libus> (perform_uninstall_id, x_uninstall, lr);
}
}
}
}
}
}
| 32.958781 | 81 | 0.520635 |
8721d1a22273035cf5721033a04becee7caa421b | 1,068 | cc | C++ | libs/crypto/legacy-test-pkcs5.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/crypto/legacy-test-pkcs5.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/crypto/legacy-test-pkcs5.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | //==========================================================================
// ObTools::Crypto: test-pkcs5.cc
//
// Test harness for Crypto library PKCS5 padding functions
//
// Copyright (c) 2006 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-crypto.h"
#include "ot-misc.h"
#include <iostream>
using namespace std;
using namespace ObTools;
//--------------------------------------------------------------------------
// Main
int main(int argc, char **argv)
{
Misc::Dumper dumper(cout, 16, 4, true);
const char *s = (argc>1)?argv[1]:"ABCD";
int length = strlen(s);
unsigned char *ps = Crypto::PKCS5::pad(
reinterpret_cast<const unsigned char *>(s),
length, 8);
cout << "Padded:\n";
dumper.dump(ps, length);
cout << "Original length is " << Crypto::PKCS5::original_length(ps, length)
<< endl;
free(ps);
return 0;
}
| 24.837209 | 77 | 0.481273 |
87232c2882af6dadaade39d821c6436e24b74a84 | 577 | cpp | C++ | cap03/cap03-01-01-test_search_value.cpp | ggaaaff/think_like_a_programmer--test_code | fb081d24d70db6dd503608562625b84607c7a3ab | [
"MIT"
] | 1 | 2020-12-08T10:54:39.000Z | 2020-12-08T10:54:39.000Z | cap03/cap03-01-01-test_search_value.cpp | ggaaaff/think_like_a_programmer--test_code | fb081d24d70db6dd503608562625b84607c7a3ab | [
"MIT"
] | null | null | null | cap03/cap03-01-01-test_search_value.cpp | ggaaaff/think_like_a_programmer--test_code | fb081d24d70db6dd503608562625b84607c7a3ab | [
"MIT"
] | null | null | null | //2014.02.09 Gustaf - CTG.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "TEST Searching for a Specific Value \n";
const int ARRAY_SIZE = 10;
int intArray[ARRAY_SIZE] = {4, 5, 9, 12, -4, 0, -57, 30987, -287, 1};
int targetValue = 12;
int targetPos = 0;
while ((intArray[targetPos] != targetValue) && (targetPos < ARRAY_SIZE))
targetPos++;
if (targetPos < ARRAY_SIZE)
{
cout << targetValue << " Target Value Finded \n";
}
else
{
cout << targetValue << " Target Value NOT Finded \n";
}
return 0;
}
| 17.484848 | 74 | 0.613518 |
872b2005306393fab82c78a2703a3027748461a7 | 2,358 | cpp | C++ | tutorial/test_async_stop_token.cpp | tearshark/librf | 4299e2ff264aac9bcd9e4788e528de80044252c8 | [
"Apache-2.0"
] | 434 | 2017-09-24T06:41:06.000Z | 2022-03-29T10:24:14.000Z | tutorial/test_async_stop_token.cpp | tearshark/librf | 4299e2ff264aac9bcd9e4788e528de80044252c8 | [
"Apache-2.0"
] | 7 | 2017-12-06T13:08:33.000Z | 2021-12-01T07:46:12.000Z | tutorial/test_async_stop_token.cpp | tearshark/librf | 4299e2ff264aac9bcd9e4788e528de80044252c8 | [
"Apache-2.0"
] | 95 | 2017-09-24T06:14:04.000Z | 2022-03-22T06:23:14.000Z | #include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "librf.h"
using namespace resumef;
using namespace std::chrono;
//_Ctype签名:void(bool, int64_t)
template<class _Ctype, typename=std::enable_if_t<std::is_invocable_v<_Ctype, bool, int64_t>>>
static void callback_get_long_with_stop(stop_token token, int64_t val, _Ctype&& cb)
{
std::thread([val, token = std::move(token), cb = std::forward<_Ctype>(cb)]
{
for (int i = 0; i < 10; ++i)
{
if (token.stop_requested())
{
cb(false, 0);
return;
}
std::this_thread::sleep_for(10ms);
}
//有可能未检测到token的停止要求
//如果使用stop_callback来停止,则务必保证检测到的退出要求是唯一的,且线程安全的
//否则,多次调用cb,会导致协程在半退出状态下,外部的awaitable_t管理的state获取跟root出现错误。
cb(true, val * val);
}).detach();
}
//token触发后,设置canceled_exception异常。
static future_t<int64_t> async_get_long_with_stop(stop_token token, int64_t val)
{
awaitable_t<int64_t> awaitable;
//在这里通过stop_callback来处理退出,并将退出转化为error_code::stop_requested异常。
//则必然会存在线程竞争问题,导致协程提前于callback_get_long_with_stop的回调之前而退出。
//同时,callback_get_long_with_stop还未必一定能检测到退出要求----毕竟只是一个要求,而不是强制。
callback_get_long_with_stop(token, val, [awaitable](bool ok, int64_t val)
{
if (ok)
awaitable.set_value(val);
else
awaitable.throw_exception(canceled_exception{error_code::stop_requested});
});
return awaitable.get_future();
}
//如果关联的协程被取消了,则触发canceled_exception异常。
static future_t<int64_t> async_get_long_with_stop(int64_t val)
{
task_t* task = current_task();
co_return co_await async_get_long_with_stop(task->get_stop_token(), val);
}
//测试取消协程
static void test_get_long_with_stop(int64_t val)
{
//异步获取值的协程
task_t* task = GO
{
try
{
int64_t result = co_await async_get_long_with_stop(val);
std::cout << result << std::endl;
}
catch (const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
};
//task的生命周期只在task代表的协程生存期间存在。
//但通过复制与其关联的stop_source,生存期可以超过task的生存期。
stop_source stops = task->get_stop_source();
//取消上一个协程的延迟协程
GO
{
co_await sleep_for(1ms * (rand() % 300));
stops.request_stop();
};
this_scheduler()->run_until_notask();
}
void resumable_main_stop_token()
{
srand((int)time(nullptr));
for (int i = 0; i < 10; ++i)
test_get_long_with_stop(i);
std::cout << "OK - stop_token!" << std::endl;
}
int main()
{
resumable_main_stop_token();
return 0;
}
| 22.673077 | 93 | 0.719254 |
872bcde54549bdee3ba77e4d5909035efc2bb063 | 34,879 | cpp | C++ | PVPersonal.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | PVPersonal.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | PVPersonal.cpp | nardinan/vulture | d4be5b028d9fab4c0d23797ceb95d22f5a33cb75 | [
"FTL"
] | null | null | null | /* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net
* Project: Vulture(c)
* Author : Andrea Nardinocchi
* eMail : andrea@nardinan.it
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PVPersonal.h"
int PVpersonal::login(void) {
FILE *configurationfile = NULL;
char *pathname = NULL;
int length = 0;
int times = 0;
if (infos.player->logics.hasvalue("STATUS", "Account") == 0) {
if ((pathname = (char *) pvmalloc(length = (sizeof (_PVFILES "players/") + strlen(infos.message) + sizeof (".dp") + 1)))) {
snprintf(pathname, (length), _PVFILES "players/%s.dp", infos.message);
if ((configurationfile = fopen(pathname, "r"))) {
if (!(pvulture.characters.gamecharacters.getaccount(infos.message))) {
if (infos.player->load(configurationfile, pvulture.objects.gameobjects, pvulture.map.gamemap) > 0) return 1;
else {
if (infos.player->setaccount(infos.message) > 0) return 1;
if (infos.player->opvsend(pvulture.server, "[reset][bold][green]Account esistente![n]Password:[hide]") > 0) return 1;
if (infos.player->logics.delvalue("STATUS", "Account") > 0) LOG_ERROR("Unable to find STATUS->Account Logic");
if (infos.player->logics.addvalue("STATUS", "Password", 1) > 0) LOG_ERROR("Unable to add STATUS->Password Logic");
}
} else if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Account gia' in uso![n]Account:") > 0) return 1;
fclose(configurationfile);
} else {
if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Account non esistente![n]") > 0) return 1;
times = getvalue("TIMES", "Account", infos.player->logics, 0);
if (++times >= logintries) {
if (infos.player->opvsend(pvulture.server, "[reset][red]hai sbagliato account per %d volte![n]", logintries) > 0) return 1;
if (pathname) {
pvfree(pathname);
pathname = NULL;
}
return -1;
} else {
infos.player->logics.addvalue("TIMES", "Account", times);
if (infos.player->opvsend(pvulture.server, "Account:") > 0) return 1;
}
}
} else return 1;
if (pathname) {
pvfree(pathname);
pathname = NULL;
}
} else if (infos.player->logics.hasvalue("STATUS", "Password") == 0) {
if (compare.vcmpcase(infos.message, LSTRSIZE(infos.player->getpassword())) == 0) {
if (infos.player->opvsend(pvulture.server, "[reset][bold][green]Password corretta![n]") > 0) return 1;
if (infos.player->logics.delvalue("STATUS", "Password") > 0) LOG_ERROR("Unable to delete STATUS->Password Logic");
if (infos.player->logics.addvalue("STATUS", "Online", pvulture.stopwatch.pause()) > 0) LOG_ERROR("Unable to add STATUS->Online Logic");
if (!infos.player->position) {
if (!(infos.player->position = pvulture.map.gamemap.gettilesroot()->tile)) return 1;
}
infos.player->setonline();
if (infos.player->setlogging(true) > 0) LOG_ERROR("Unable to run SETLOGGING()");
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name entra in gioco[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
}
if (environmentcommands.lookenvironment() > 0) return 1;
if (players.hasvalue(infos.player->getID()) != 0) {
if (players.addvalue(pvulture.characters.getsimplename(infos.player), infos.player->getID()) > 0) return 1;
else if (infos.player->pvsend(pvulture.server, "[reset][green]sei stato aggiunto alla lista utenti di gioco![n]") > 0) return 1;
}
if (infos.player->logics.hascategory("GROUP") == 0) {
if (groups.hasvalue(infos.player->logics.getvalue("GROUP", 3)) != 0) {
if (infos.player->logics.delcategory("GROUP") > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][red]il tuo gruppo si e' sciolto![n]") > 0) return 1;
}
}
if (infos.player->spvsend(pvulture.server, sshell) > 0) return 1;
} else {
if (infos.player->opvsend(pvulture.server, "[reset][bold][red]Password Errata![n]") > 0) return 1;
times = getvalue("TIMES", "Password", infos.player->logics, 0);
if (++times >= logintries) {
if (infos.player->opvsend(pvulture.server, "[reset][red]hai sbagliato password per %d volte![n]", logintries) > 0) return 1;
return -1;
} else {
infos.player->logics.addvalue("TIMES", "Password", times);
if (infos.player->opvsend(pvulture.server, "Password:[hide]") > 0) return 1;
}
}
}
return 0;
}
int PVpersonal::logout(bool message) {
if (compare.vcmpcase(infos.player->getaccount(), CSTRSIZE("###")) != 0) {
infos.player->logics.delvalue("STATUS", "Online");
infos.player->logics.delvalue("STATUS", "Last");
if (infos.player->logics.hascategory("FIGHT") == 0)
if (infos.player->logics.delcategory("FIGHT") > 0) LOG_ERROR("Unable to delete FIGHT Category");
if (infos.player->logics.hascategory("TIMES") == 0)
if (infos.player->logics.delcategory("TIMES") > 0) LOG_ERROR("Unable to delete TIMES Category");
if (infos.player->logics.hascategory("FOLLOW") == 0)
if (infos.player->logics.delcategory("FOLLOW") > 0) LOG_ERROR("Unable to delete FOLLOW Category");
if (pvulture.characters.gamecharacters.saveplayer(infos.player->getID(), _PVFILES "players/", pvulture.objects.gameobjects) > 0) return 1;
if (infos.player->position) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (message) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name esce dal gioco[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
}
}
if (pvulture.server.unload(infos.player->getsocketID()) > 0) return 1;
if (pvulture.characters.gamecharacters.delplayer(infos.player->getID()) > 0) return 1;
infos.player = NULL;
return 0;
}
int PVpersonal::status(void) {
char *command = NULL;
char *message = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) &&
((!message) || ((infos.player->logics.hasvalue("RANK", "Admin") != 0) &&
(infos.player->logics.hasvalue("RANK", "Moderator") != 0)))) {
value = status(infos.player);
} else {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = status(player);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = status(mob);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome![n]") > 0) return 1;
}
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return value;
}
int PVpersonal::status(Cplayer *player) {
char *charactername = NULL;
char *backup = NULL;
int index = 0;
if (infos.player->getID() != player->getID()) {
if (infos.player->pvsend(pvulture.server, "Lo status di %s e' il seguente:[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
}
if (infos.player->pvsend(pvulture.server, "Livello Vita %s[n]", (backup = funny.vbar(getvalue("STATS", "LPoints", player->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Stamina %s[n]", (backup = funny.vbar(getvalue("STATS", "SPoints", player->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "[reset][n][bold]ABILITA':[n]") > 0) return 1;
while (compare.vcmpcase(chacharas[index].representation, CSTRSIZE("NULL")) != 0) {
if ((backup = pvulture.characters.getability(player, chacharas[index].representation))) {
if (infos.player->pvsend(pvulture.server, backup) > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
}
index++;
}
return 0;
}
int PVpersonal::status(Cmob *mob) {
char *charactername = NULL;
char *backup = NULL;
int index = 0;
if (infos.player->pvsend(pvulture.server, "Lo status di %s e' il seguente:[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Vita %s[n]", (backup = funny.vbar(getvalue("STATS", "LPoints", mob->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "Livello Stamina %s[n]", (backup = funny.vbar(getvalue("STATS", "SPoints", mob->logics, 0), 100)) ? backup : "") > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
if (infos.player->pvsend(pvulture.server, "[reset][n][bold]ABILITA':[n]") > 0) return 1;
while (compare.vcmpcase(chacharas[index].representation, CSTRSIZE("NULL")) != 0) {
if ((backup = pvulture.characters.getability(mob, chacharas[index].representation))) {
if (infos.player->pvsend(pvulture.server, backup) > 0) return 1;
if (backup) {
pvfree(backup);
backup = NULL;
}
}
index++;
}
return 0;
}
int PVpersonal::position(void) {
if (compare.vcmpcase(infos.message, CSTRSIZE("alza")) == 0) {
if (getvalue("STATS", "Legs", infos.player->logics, 0) > 0) {
if ((infos.player->logics.hasvalue("STATUS", "Seated") == 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") == 0)) {
infos.player->logics.delvalue("STATUS", "Seated");
infos.player->logics.delvalue("STATUS", "Stretched");
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti alzi in piedi[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si alza in piedi[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' in piedi![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]hai le gambe distrutte! non riesci a muoverti![n]") > 0) return 1;
} else if (compare.vcmpcase(infos.message, CSTRSIZE("siedi")) == 0) {
if ((infos.player->logics.hasvalue("STATUS", "Seated") != 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") == 0)) {
infos.player->logics.addvalue("STATUS", "Seated", 1);
infos.player->logics.delvalue("STATUS", "Stretched");
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti metti a sedere[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si siede a terra[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' sedut%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
} else {
if ((infos.player->logics.hasvalue("STATUS", "Seated") == 0) ||
(infos.player->logics.hasvalue("STATUS", "Stretched") != 0)) {
infos.player->logics.delvalue("STATUS", "Seated");
infos.player->logics.addvalue("STATUS", "Stretched", 1);
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti sdrai a terra[n]") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name si sdraia a terra[n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
}
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]sei gia' sdraiat%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
}
return 0;
}
int PVpersonal::inventory(void) {
char *message = NULL;
char *command = NULL;
char *backup = NULL;
char *charactername = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) &&
((!message) || ((infos.player->logics.hasvalue("RANK", "Admin") != 0) &&
(infos.player->logics.hasvalue("RANK", "Moderator") != 0)))) {
if (!(backup = pvulture.objects.getinventory(infos.player)))
return 1;
} else {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
if (!(backup = pvulture.objects.getinventory(player)))
return 1;
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
if (!(backup = pvulture.objects.getinventory(mob)))
return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome![n]") > 0)
return 1;
}
}
if (backup) {
if (mob) {
if (infos.player->pvsend(pvulture.server, "%s sta' portando:[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0)
return 1;
} else if (player) {
if (player->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "%s sta' portando:[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0)
return 1;
} else
if (infos.player->pvsend(pvulture.server, "stai portando:[n]") > 0)
return 1;
} else
if (infos.player->pvsend(pvulture.server, "stai portando:[n]") > 0)
return 1;
if (infos.player->pvsend(pvulture.server, backup) > 0)
return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
pvfree(backup);
backup = NULL;
}
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return 0;
}
int PVpersonal::points(void) {
char *command = NULL;
char *message = NULL;
char *text = NULL;
char *pointer = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if ((command = strings.vpop(&message)) && (message)) {
if ((pointer = strchr(message, ':'))) {
for (text = pointer + 1; *text == ' '; text++);
do {
*pointer-- = '\0';
} while ((pointer > message) && (*pointer == ' '));
if (strlen(text) > 0) {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = points(player, text);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = points(mob, text);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare una categoria e un punteggio[n]") > 0) return 1;
} else {
value = points(infos.player, message);
}
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare una categoria e un punteggio[n]") > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else return 1;
if (command) {
pvfree(command);
command = NULL;
}
if (message) {
pvfree(message);
message = NULL;
}
return 0;
}
int PVpersonal::points(Cplayer *player, char *message) {
char *charactername = NULL;
char *category = NULL;
char *key = NULL;
int value = 0;
if ((strings.vsscanf(message, '.', "ssd", &category, &key, &value) == 0) &&
(player->logics.hasvalue(category, key) == 0)) {
if (player->logics.delvalue(category, key) > 0) LOG_ERROR("Unable to delete %s->%s Logic", category, key);
else if (player->logics.addvalue(category, key, value) > 0) LOG_ERROR("Unable to add %s->%s Logic", category, key);
else if (player->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il valore di %s.%s di %s in %d[n]", category, key, charactername = pvulture.characters.gettargetname(player, infos.player), value) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo valore di %s.%s in %d[n]", category, key, value) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non esiste una simile categoria/chiave nella logica[n]") > 0) return 1;
if (key) {
pvfree(key);
key = NULL;
}
if (category) {
pvfree(category);
category = NULL;
}
return 0;
}
int PVpersonal::points(Cmob *mob, char *message) {
char *charactername = NULL;
char *category = NULL;
char *key = NULL;
int value = 0;
if ((strings.vsscanf(message, '.', "ssd", &category, &key, &value) == 0) &&
(mob->logics.hasvalue(category, key) == 0)) {
if (mob->logics.delvalue(category, key) > 0) LOG_ERROR("Unable to delete %s->%s Logic", category, key);
else if (mob->logics.addvalue(category, key, value) > 0) LOG_ERROR("Unable to add %s->%s Logic", category, key);
else if (mob->getID() != infos.player->getID()) {
if (infos.player->pvsend(pvulture.server, "[reset]hai modificato il valore di %s.%s di %s in %d[n]", category, key, charactername = pvulture.characters.gettargetname(mob, infos.player), value) > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo valore di %s.%s in %d[n]", category, key, value) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]non esiste una simile categoria/chiave nella logica[n]") > 0) return 1;
if (key) {
pvfree(key);
key = NULL;
}
if (category) {
pvfree(category);
category = NULL;
}
return 0;
}
int PVpersonal::password(void) {
char *message = NULL;
char *command = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
if (infos.player->setpassword(message) > 0) {
if (infos.player->pvsend(pvulture.server, "[reset]la password e' troppo corta![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset][green]hai cambiato la password![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare la nuova password![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return 0;
}
int PVpersonal::appearance(void) {
int position = 0;
char *message = NULL;
char *command = NULL;
char *completename = NULL;
char *smalldescription = NULL;
char *largedescription = NULL;
char *race = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
position = getvalue("SYSTEM", "Position", infos.player->logics, 0);
if (strings.vsscanf(message, ':', "ssss", &completename, &smalldescription, &largedescription, &race) == 0) {
if (infos.player->logics.hasvalue("RACE", 0) == 0) {
if (infos.player->logics.delvalue("RACE", 0) > 0) LOG_ERROR("Unable to delete RACE->%s Logic", race);
}
if (infos.player->logics.addvalue("RACE", race, 0) > 0) LOG_ERROR("Unable to add RACE->%s Logic", race);
if (infos.player->descriptions.deldescription(position) == 0) {
infos.player->descriptions.adddescription(position, completename, smalldescription, largedescription);
if (infos.player->pvsend(pvulture.server, "[reset][green]hai cambiato il tuo aspetto e la tua razza![n]") > 0) return 1;
} else return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un nuovo aspetto per il tuo personaggio![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un nuovo aspetto per il tuo personaggio![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
if (completename) {
pvfree(completename);
completename = NULL;
}
if (smalldescription) {
pvfree(smalldescription);
smalldescription = NULL;
}
if (largedescription) {
pvfree(largedescription);
largedescription = NULL;
}
if (race) {
pvfree(race);
race = NULL;
}
return 0;
}
int PVpersonal::emoticon(void) {
char *message = NULL;
char *text = NULL;
char *emoticon = NULL;
char *buffer = NULL;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
emoticon = getemoticon(&message);
for (text = message + 1; *text == ' '; text++);
if (strlen(text) > 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][green]ti vedi mentre il tuo [bold]'io'[reset][green], %s %s[n]", text, (emoticon) ? emoticon : "") > 0) return 1;
if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) {
if (spvsend(pvulture.server, infos.player->position, (buffer = allocate.vsalloc("[n][yellow]$name %s %s[n]", text, (emoticon) ? emoticon : "")), (Ccharacter *) infos.player) > 0) return 1;
}
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
} else if (infos.player->pvsend(pvulture.server, "[reset]devi specificare un'azione![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (emoticon) {
pvfree(emoticon);
emoticon = NULL;
}
if (buffer) {
pvfree(buffer);
buffer = NULL;
}
return 0;
}
int PVpersonal::meet(void) {
char *command = NULL;
char *message = NULL;
Cplayer *player = NULL;
Cmob *mob = NULL;
int value = 0;
if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) {
strcpy(message, infos.message);
message[strlen(infos.message)] = '\0';
if ((command = strings.vpop(&message)) && (message)) {
if ((player = pvulture.characters.getplayer(message, infos.player->position))) {
value = meet(player);
} else if ((mob = pvulture.characters.getmob(message, infos.player->position))) {
value = meet(mob);
} else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1;
} else return 1;
if (message) {
pvfree(message);
message = NULL;
}
if (command) {
pvfree(command);
command = NULL;
}
return value;
}
int PVpersonal::meet(Cplayer *player) {
char *charactername = NULL;
if (player->getID() != infos.player->getID()) {
if (!(player->getcharacter(infos.player->getID(), PLAYER))) {
if (player->addcharacter(infos.player->getID(), PLAYER) > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti presenti a %s[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1;
if (player->pvsend(pvulture.server, "[reset][n][yellow]%s ti si presenta[n]", pvulture.characters.getsimplename(infos.player)) > 0) return 1;
if (player->spvsend(pvulture.server, sshell) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]da quel che sembra, lui ti conosce di gia'![n]") > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
return 0;
}
int PVpersonal::meet(Cmob *mob) {
char *charactername = NULL;
if (!(mob->getcharacter(infos.player->getID(), PLAYER))) {
if (mob->addcharacter(infos.player->getID(), PLAYER) > 0) return 1;
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti presenti a %s[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1;
if (intelligenceevents.meet(mob, infos.player) > 0) return 1;
} else if (infos.player->pvsend(pvulture.server, "[reset]da quel che sembra, lui ti conosce di gia'![n]") > 0) return 1;
if (charactername) {
pvfree(charactername);
charactername = NULL;
}
return 0;
}
int PVpersonal::hide(void) {
if (infos.player->logics.hasvalue("STATUS", "Hide") == 0) {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][yellow]spunti fuori dall'ombra![n]") > 0) return 1;
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name appare da una nuvola di fumo![n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
if (infos.player->logics.delvalue("STATUS", "Hide") > 0) LOG_ERROR("Unable to delete STATUS->Hide Logic");
} else {
if (infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1;
}
if (infos.player->pvsend(pvulture.server, "[reset][yellow]ti nascondi nell'ombra![n]") > 0) return 1;
if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo![n]", (Ccharacter *) infos.player) > 0) return 1;
if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1;
if (!infos.player->position->getplayer(infos.player->getID())) {
if (infos.player->position->addplayer(infos.player) > 0) return 1;
}
if (infos.player->logics.addvalue("STATUS", "Hide", 1) > 0) LOG_ERROR("Unable to add STATUS->Hide Logic");
}
return 0;
}
PVpersonal personalcommands;
int personal(void) {
if (compare.vcmpcase(infos.message, CSTRSIZE("status")) == 0) {
if (personalcommands.status() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.STATUS()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("inventario")) == 0) {
if (personalcommands.inventory() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.INVENTORY()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("passwd")) == 0) {
if (personalcommands.password() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.PASSWORD()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("alza")) == 0) ||
(compare.vcmpcase(infos.message, CSTRSIZE("siedi")) == 0) ||
(compare.vcmpcase(infos.message, CSTRSIZE("sdraia")) == 0)) {
if (personalcommands.position() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.POSITION()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("aspetto")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.appearance() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.APPEARANCE()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("valore")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.points() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.POINTS()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE(":")) == 0) {
if (personalcommands.emoticon() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.EMOTICON()");
} else if (compare.vcmpcase(infos.message, CSTRSIZE("presenta")) == 0) {
if (personalcommands.meet() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.MEET()");
} else if ((compare.vcmpcase(infos.message, CSTRSIZE("nascondi")) == 0) &&
((infos.player->logics.hasvalue("RANK", "Admin") == 0) ||
(infos.player->logics.hasvalue("RANK", "Moderator") == 0))) {
if (personalcommands.hide() > 0) LOG_ERROR("Unable to run PERSONALCOMMANDS.HIDE()");
} else if (infos.player->pvsend(pvulture.server, "[reset]prego?[n]") > 0) return 1;
return 0;
}
| 50.918248 | 229 | 0.579718 |
872d353085923567ca1f97e3c39511c08b594fde | 5,076 | cpp | C++ | csapex_sample_consensus/src/nodes/ransac.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 2 | 2016-09-02T15:33:22.000Z | 2019-05-06T22:09:33.000Z | csapex_sample_consensus/src/nodes/ransac.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 1 | 2021-02-14T19:53:30.000Z | 2021-02-14T19:53:30.000Z | csapex_sample_consensus/src/nodes/ransac.cpp | AdrianZw/csapex_core_plugins | 1b23c90af7e552c3fc37c7dda589d751d2aae97f | [
"BSD-3-Clause"
] | 6 | 2016-10-12T00:55:23.000Z | 2021-02-10T17:49:25.000Z | /// PROJECT
#include "sample_consensus.hpp"
namespace csapex
{
using namespace connection_types;
class Ransac : public SampleConsensus
{
public:
Ransac() = default;
void setupParameters(Parameterizable& parameters) override
{
SampleConsensus::setupParameters(parameters);
parameters.addParameter(param::factory::declareBool("use outlier probability", false), ransac_parameters_.use_outlier_probability);
parameters.addConditionalParameter(param::factory::declareRange("outlier probability", 0.01, 1.0, 0.9, 0.01), [this]() { return ransac_parameters_.use_outlier_probability; },
ransac_parameters_.outlier_probability);
parameters.addParameter(param::factory::declareValue("random seed", -1), std::bind(&Ransac::setupRandomGenerator, this));
parameters.addParameter(param::factory::declareRange("maximum sampling retries", 1, 1000, 100, 1), ransac_parameters_.maximum_sampling_retries);
}
virtual void process() override
{
PointCloudMessage::ConstPtr msg(msg::getMessage<PointCloudMessage>(in_cloud_));
boost::apply_visitor(PointCloudMessage::Dispatch<Ransac>(this, msg), msg->value);
}
template <class PointT>
void inputCloud(typename pcl::PointCloud<PointT>::ConstPtr cloud)
{
std::shared_ptr<std::vector<pcl::PointIndices>> out_inliers(new std::vector<pcl::PointIndices>);
std::shared_ptr<std::vector<pcl::PointIndices>> out_outliers(new std::vector<pcl::PointIndices>);
std::shared_ptr<std::vector<ModelMessage>> out_models(new std::vector<ModelMessage>);
/// retrieve the model to use
auto model = getModel<PointT>(cloud);
/// get indices of points to use
std::vector<int> prior_inlier;
std::vector<int> prior_outlier;
getInidicesFromInput(prior_inlier);
if (prior_inlier.empty()) {
if (keep_invalid_as_outlier_)
getIndices<PointT>(cloud, prior_inlier, prior_outlier);
else
getIndices<PointT>(cloud, prior_inlier);
}
/// prepare algorithm
ransac_parameters_.assign(sac_parameters_);
typename csapex_sample_consensus::Ransac<PointT>::Ptr sac(new csapex_sample_consensus::Ransac<PointT>(prior_inlier, ransac_parameters_, rng_));
pcl::PointIndices outliers;
pcl::PointIndices inliers;
inliers.header = cloud->header;
outliers.header = cloud->header;
if (fit_multiple_models_) {
outliers.indices = sac->getIndices();
int model_searches = 0;
while ((int)outliers.indices.size() >= minimum_residual_cloud_size_) {
auto working_model = model->clone();
sac->computeModel(working_model);
if (working_model) {
inliers.indices.clear();
outliers.indices.clear();
working_model->getInliersAndOutliers(ransac_parameters_.model_search_distance, inliers.indices, outliers.indices);
if ((int)inliers.indices.size() > minimum_model_cloud_size_)
out_inliers->emplace_back(inliers);
else
out_outliers->emplace_back(inliers);
sac->setIndices(outliers.indices);
}
++model_searches;
if (maximum_model_count_ != -1 && model_searches >= maximum_model_count_)
break;
}
out_outliers->emplace_back(outliers);
} else {
sac->computeModel(model);
if (model) {
model->getInliersAndOutliers(prior_inlier, ransac_parameters_.model_search_distance, inliers.indices, outliers.indices);
if ((int)inliers.indices.size() > minimum_model_cloud_size_) {
out_inliers->emplace_back(inliers);
} else {
out_outliers->emplace_back(inliers);
}
outliers.indices.insert(outliers.indices.end(), prior_outlier.begin(), prior_outlier.end());
out_outliers->emplace_back(outliers);
}
}
msg::publish<GenericVectorMessage, pcl::PointIndices>(out_inlier_indices_, out_inliers);
msg::publish<GenericVectorMessage, pcl::PointIndices>(out_outlier_indices_, out_outliers);
msg::publish<GenericVectorMessage, ModelMessage>(out_models_, out_models);
}
protected:
csapex_sample_consensus::RansacParameters ransac_parameters_;
std::default_random_engine rng_; /// keep the random engine alive for better number generation
inline void setupRandomGenerator()
{
int seed = readParameter<int>("random seed");
if (seed >= 0) {
rng_ = std::default_random_engine(seed);
} else {
std::random_device rd;
rng_ = std::default_random_engine(rd());
}
}
};
} // namespace csapex
CSAPEX_REGISTER_CLASS(csapex::Ransac, csapex::Node)
| 40.608 | 182 | 0.635737 |
873048c42c07552f2c28839f97f603836ea52a78 | 1,362 | cc | C++ | chromecast/android/cast_jni_registrar.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromecast/android/cast_jni_registrar.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromecast/android/cast_jni_registrar.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/android/cast_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "base/macros.h"
#include "chromecast/base/android/system_time_change_notifier_android.h"
#include "chromecast/base/chromecast_config_android.h"
#include "chromecast/chromecast_features.h"
#if BUILDFLAG(IS_CAST_USING_CMA_BACKEND)
#include "chromecast/media/cma/backend/android/audio_sink_android_audiotrack_impl.h"
#include "chromecast/media/cma/backend/android/volume_control_android.h"
#endif
namespace chromecast {
namespace android {
namespace {
static base::android::RegistrationMethod kMethods[] = {
{"ChromecastConfigAndroid", ChromecastConfigAndroid::RegisterJni},
{"SystemTimeChangeNotifierAndroid",
SystemTimeChangeNotifierAndroid::RegisterJni},
#if BUILDFLAG(IS_CAST_USING_CMA_BACKEND)
{"AudioSinkAudioTrackImpl",
media::AudioSinkAndroidAudioTrackImpl::RegisterJni},
{"VolumeControlAndroid", media::VolumeControlAndroid::RegisterJni},
#endif
};
} // namespace
bool RegisterJni(JNIEnv* env) {
return RegisterNativeMethods(env, kMethods, arraysize(kMethods));
}
} // namespace android
} // namespace chromecast
| 31.674419 | 84 | 0.792217 |
8730b3d7ae083b97f36ae568df4cb7d400b15331 | 6,147 | cpp | C++ | src/sylvaneth/DrychaHamadreth.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 5 | 2019-02-01T01:41:19.000Z | 2021-06-17T02:16:13.000Z | src/sylvaneth/DrychaHamadreth.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 2 | 2020-01-14T16:57:42.000Z | 2021-04-01T00:53:18.000Z | src/sylvaneth/DrychaHamadreth.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 1 | 2019-03-02T20:03:51.000Z | 2019-03-02T20:03:51.000Z | /*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <algorithm>
#include <sylvaneth/DrychaHamadreth.h>
#include <UnitFactory.h>
#include <spells/MysticShield.h>
#include <sylvaneth/SylvanethSpells.h>
#include "SylvanethPrivate.h"
namespace Sylvaneth {
static const int g_basesize = 105; // x70 oval
static const int g_wounds = 10;
static const int g_pointsPerUnit = 330;
bool DrychaHamadreth::s_registered = false;
struct TableEntry {
int m_flitterfuriesRange;
int m_squirmlingsHit;
int m_talonAttacks;
};
const size_t g_numTableEntries = 5;
const int g_woundThresholds[g_numTableEntries] = {2, 4, 6, 8, g_wounds};
const TableEntry g_damageTable[g_numTableEntries] =
{
{18, 3, 6},
{15, 4, 5},
{12, 4, 4},
{9, 5, 3},
{6, 5, 2}
};
DrychaHamadreth::DrychaHamadreth(Glade glade, Lore lore, bool isGeneral) :
SylvanethBase("Drycha Hamadreth", 9, g_wounds, 8, 3, false, g_pointsPerUnit),
m_colonyOfFlitterfuries(Weapon::Type::Missile, "Colony of Flitterfuries", 18, 10, 4, 3, -1, 1),
m_swarmOfSquirmlings(Weapon::Type::Missile, "Swarm of Squirmlings", 2, 10, 3, 4, 0, 1),
m_slashingTalons(Weapon::Type::Melee, "Slashing Talons", 2, 6, 4, 3, -2, 2) {
m_keywords = {ORDER, SYLVANETH, OUTCASTS, MONSTER, HERO, WIZARD, DRYCHA_HAMADRETH};
m_weapons = {&m_colonyOfFlitterfuries, &m_swarmOfSquirmlings, &m_slashingTalons};
m_battleFieldRole = Role::Leader_Behemoth;
m_totalUnbinds = 1;
m_totalSpells = 1;
s_globalToWoundReroll.connect(this, &DrychaHamadreth::songOfSpiteToWoundRerolls, &m_songSlot);
setGlade(glade);
setGeneral(isGeneral);
auto model = new Model(g_basesize, wounds());
model->addMissileWeapon(&m_colonyOfFlitterfuries);
model->addMissileWeapon(&m_swarmOfSquirmlings);
model->addMeleeWeapon(&m_slashingTalons);
model->addMeleeWeapon(&m_thornedSlendervines);
addModel(model);
m_knownSpells.push_back(std::unique_ptr<Spell>(CreatePrimalTerror(this)));
m_knownSpells.push_back(std::unique_ptr<Spell>(CreateLore(lore, this)));
m_knownSpells.push_back(std::unique_ptr<Spell>(CreateArcaneBolt(this)));
m_knownSpells.push_back(std::make_unique<MysticShield>(this));
m_points = g_pointsPerUnit;
}
DrychaHamadreth::~DrychaHamadreth() {
m_songSlot.disconnect();
}
void DrychaHamadreth::onWounded() {
SylvanethBase::onWounded();
const auto damageIndex = getDamageTableIndex();
m_colonyOfFlitterfuries.setRange(g_damageTable[damageIndex].m_flitterfuriesRange);
m_swarmOfSquirmlings.setToHit(g_damageTable[damageIndex].m_squirmlingsHit);
m_slashingTalons.setAttacks(g_damageTable[damageIndex].m_talonAttacks);
}
size_t DrychaHamadreth::getDamageTableIndex() const {
auto woundsInflicted = wounds() - remainingWounds();
for (auto i = 0u; i < g_numTableEntries; i++) {
if (woundsInflicted < g_woundThresholds[i]) {
return i;
}
}
return 0;
}
Unit *DrychaHamadreth::Create(const ParameterList ¶meters) {
auto glade = (Glade) GetEnumParam("Glade", parameters, g_glade[0]);
auto lore = (Lore) GetEnumParam("Lore", parameters, g_loreOfTheDeepwood[0]);
auto general = GetBoolParam("General", parameters, false);
return new DrychaHamadreth(glade, lore, general);
}
void DrychaHamadreth::Init() {
if (!s_registered) {
static FactoryMethod factoryMethod = {
DrychaHamadreth::Create,
SylvanethBase::ValueToString,
SylvanethBase::EnumStringToInt,
DrychaHamadreth::ComputePoints,
{
EnumParameter("Glade", g_glade[0], g_glade),
EnumParameter("Lore", g_loreOfTheDeepwood[0], g_loreOfTheDeepwood),
BoolParameter("General")
},
ORDER,
{SYLVANETH}
};
s_registered = UnitFactory::Register("Drycha Hamadreth", factoryMethod);
}
}
Wounds DrychaHamadreth::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const {
// Deadly Infestation
if (((weapon->name() == m_colonyOfFlitterfuries.name()) || weapon->name() == m_swarmOfSquirmlings.name()) &&
(woundRoll == 6)) {
return {0, 1};
}
return SylvanethBase::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll);
}
void DrychaHamadreth::onBeginRound(int battleRound) {
// Mercurial Aspect
m_enraged = (m_meleeTarget == nullptr);
SylvanethBase::onBeginRound(battleRound);
}
int DrychaHamadreth::extraAttacks(const Model *attackingModel, const Weapon *weapon, const Unit *target) const {
auto extra = SylvanethBase::extraAttacks(attackingModel, weapon, target);
// Mecurial Aspect
if (weapon->name() == m_colonyOfFlitterfuries.name() && m_enraged) {
extra += 10;
}
if (weapon->name() == m_swarmOfSquirmlings.name() && !m_enraged) {
extra += 10;
}
return extra;
}
int DrychaHamadreth::ComputePoints(const ParameterList& /*parameters*/) {
return g_pointsPerUnit;
}
Rerolls DrychaHamadreth::songOfSpiteToWoundRerolls(const Unit *attacker, const Weapon *weapon, const Unit *target) {
if (isFriendly(attacker) && attacker->hasKeyword(SPITE_REVENANTS) && (distanceTo(attacker) < 16.0))
return Rerolls::Ones;
return Rerolls::None;
}
} // namespace Sylvaneth
| 38.660377 | 147 | 0.626647 |
873294da4f704846cd5adfaf011522e881ea2829 | 4,418 | cpp | C++ | pymaplib_cpp/src/pixelbuf.cpp | Grk0/MapsEvolved | e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de | [
"PSF-2.0"
] | 3 | 2015-06-09T10:41:15.000Z | 2021-05-22T07:42:19.000Z | pymaplib_cpp/src/pixelbuf.cpp | Grk0/MapsEvolved | e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de | [
"PSF-2.0"
] | null | null | null | pymaplib_cpp/src/pixelbuf.cpp | Grk0/MapsEvolved | e058a324e7d3c9b4c9b7e00d65b6f9da029fc7de | [
"PSF-2.0"
] | null | null | null | #include "pixelbuf.h"
#include <assert.h>
#include "util.h"
#include "coordinates.h"
PixelBuf::PixelBuf(int width, int height)
// Zero-initialize the memory block (notice the parentheses).
: m_data(std::shared_ptr<unsigned int>(new unsigned int[width*height](),
ArrayDeleter<unsigned int>())),
m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
}
PixelBuf::PixelBuf(int width, int height, unsigned int value)
: m_data(std::shared_ptr<unsigned int>(new unsigned int[width*height],
ArrayDeleter<unsigned int>())),
m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
auto buf = m_data.get();
for (int i=0; i < width*height; i++) {
buf[i] = value;
}
}
PixelBuf::PixelBuf(const std::shared_ptr<unsigned int> &data,
int width, int height)
: m_data(data), m_width(width), m_height(height)
{
if (width < 0 || height < 0) {
throw std::runtime_error(
"PixelBuf width and height must be positive.");
}
}
void PixelBuf::Insert(const PixelBufCoord &pos, const PixelBuf &source) {
int x_dst_start = std::max(pos.x, 0);
int y_dst_start = std::max(pos.y, 0);
int x_src_offset = x_dst_start - pos.x;
int y_src_offset = y_dst_start - pos.y;
int x_dst_end = std::min(pos.x + source.GetWidth(), m_width);
int y_dst_end = std::min(pos.y + source.GetHeight(), m_height);
int x_delta = x_dst_end - x_dst_start;
int y_delta = y_dst_end - y_dst_start;
if (x_delta <= 0 || y_delta <= 0) {
return;
}
for (int y = 0; y < y_delta; ++y) {
auto dest = GetPixelPtr(x_dst_start, y + y_dst_start);
auto src = source.GetPixelPtr(x_src_offset, y + y_src_offset);
assert(dest >= GetRawData());
assert(dest + x_delta <= &GetRawData()[m_width*m_height]);
memcpy(dest, src, x_delta * sizeof(*dest));
}
}
void PixelBuf::SetPixel(const PixelBufCoord &pos, unsigned int val) {
// We ensure (int)m_width/(int)m_height >= 0 in the c'tors.
if (pos.x >= 0 && pos.x < static_cast<int>(m_width) &&
pos.y >= 0 && pos.y < static_cast<int>(m_height))
{
GetRawData()[pos.x + (m_height - pos.y - 1) * m_width] = val;
}
}
void PixelBuf::Line(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int color)
{
Line(start, end, 1, color);
}
void PixelBuf::Line(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int width,
const unsigned int color)
{
int x1 = start.x;
int x2 = end.x;
int y1 = start.y;
int y2 = end.y;
// Bresenham's line algorithm
const bool is_steep = (abs(y2 - y1) > abs(x2 - x1));
if (is_steep) {
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2) {
std::swap(x1, x2);
std::swap(y1, y2);
}
const int dx = x2 - x1;
const int dy = abs(y2 - y1);
int error = dx;
const int ystep = (y1 < y2) ? 1 : -1;
int y = y1;
for (int x = x1; x < x2; x++) {
if (is_steep) {
Rect(PixelBufCoord(y, x), width, color);
} else {
Rect(PixelBufCoord(x, y), width, color);
}
error -= 2 * dy;
if (error < 0) {
y += ystep;
error += 2 * dx;
}
}
}
void PixelBuf::Rect(const PixelBufCoord &start,
const PixelBufCoord &end,
const unsigned int color)
{
for (int y = start.y; y < end.y; y++) {
for (int x = start.x; x < end.x; x++) {
SetPixel(PixelBufCoord(x, y), color);
}
}
}
void PixelBuf::Rect(const class PixelBufCoord ¢er,
const unsigned int side_length,
const unsigned int color)
{
if (side_length == 0) {
return;
}
unsigned int size = (side_length - 1) / 2;
unsigned int offset = (side_length - 1) % 2;
Rect(center - PixelBufDelta(size, size),
center + PixelBufDelta(size + offset + 1, size + offset + 1),
color);
}
| 29.651007 | 76 | 0.549796 |
87333c57e10f31f952c2db09e68af7fde29094ba | 1,514 | hpp | C++ | commands.hpp | openbmc/google-ipmi-sys | f647e99165065feabb35aa744059cf6a2af46f1e | [
"Apache-2.0"
] | 2 | 2020-01-16T02:04:13.000Z | 2021-01-13T21:47:30.000Z | commands.hpp | openbmc/google-ipmi-sys | f647e99165065feabb35aa744059cf6a2af46f1e | [
"Apache-2.0"
] | null | null | null | commands.hpp | openbmc/google-ipmi-sys | f647e99165065feabb35aa744059cf6a2af46f1e | [
"Apache-2.0"
] | 3 | 2019-12-10T21:56:33.000Z | 2021-03-02T23:56:06.000Z | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
#pragma once
namespace google
{
namespace ipmi
{
enum SysOEMCommands
{
// The Sys cable check command.
SysCableCheck = 0,
// The Sys cpld version over ipmi command.
SysCpldVersion = 1,
// The Sys get eth device command.
SysGetEthDevice = 2,
// The Sys psu hard reset command.
SysPsuHardReset = 3,
// The Sys pcie slot count command.
SysPcieSlotCount = 4,
// The Sys pcie slot to i2c bus mapping command.
SysPcieSlotI2cBusMapping = 5,
// The Sys "entity id:entity instance" to entity name mapping command.
SysEntityName = 6,
// Returns the machine name of the image
SysMachineName = 7,
// Arm for psu reset on host shutdown
SysPsuHardResetOnShutdown = 8,
// The Sys get flash size command
SysGetFlashSize = 9,
// The Sys Host Power Off with disabled fallback watchdog
SysHostPowerOff = 10,
};
} // namespace ipmi
} // namespace google
| 30.28 | 75 | 0.702774 |
873b2b9ba23dd7eaec97f9dbf040f79215dfd8a4 | 3,904 | hpp | C++ | kernel/integration/x64/amd/arch_support.hpp | lusceu/hypervisor | 012a2d16f96dcfc256a3cac9aa22e238c8160a0c | [
"MIT"
] | null | null | null | kernel/integration/x64/amd/arch_support.hpp | lusceu/hypervisor | 012a2d16f96dcfc256a3cac9aa22e238c8160a0c | [
"MIT"
] | null | null | null | kernel/integration/x64/amd/arch_support.hpp | lusceu/hypervisor | 012a2d16f96dcfc256a3cac9aa22e238c8160a0c | [
"MIT"
] | null | null | null | /// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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.
#ifndef ARCH_SUPPORT_HPP
#define ARCH_SUPPORT_HPP
#include <mk_interface.hpp>
#include <bsl/convert.hpp>
#include <bsl/debug.hpp>
#include <bsl/discard.hpp>
#include <bsl/errc_type.hpp>
#include <bsl/safe_integral.hpp>
#include <bsl/unlikely.hpp>
namespace integration
{
/// <!-- description -->
/// @brief Initializes a VPS with architecture specific stuff.
///
/// <!-- inputs/outputs -->
/// @param handle the handle to use
/// @param vpsid the VPS being intialized
/// @return Returns bsl::errc_success on success and bsl::errc_failure
/// on failure.
///
[[nodiscard]] constexpr auto
init_vps(syscall::bf_handle_t &handle, bsl::safe_uint16 const &vpsid) noexcept -> bsl::errc_type
{
bsl::errc_type ret{};
/// NOTE:
/// - Set up ASID
///
constexpr bsl::safe_uint64 guest_asid_idx{bsl::to_u64(0x0058U)};
constexpr bsl::safe_uint32 guest_asid_val{bsl::to_u32(0x1U)};
ret = syscall::bf_vps_op_write32(handle, vpsid, guest_asid_idx, guest_asid_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
/// NOTE:
/// - Set up intercept controls. On AMD, we need to intercept
/// VMRun, and CPUID if we plan to support reporting and stopping.
///
constexpr bsl::safe_uint64 intercept_instruction1_idx{bsl::to_u64(0x000CU)};
constexpr bsl::safe_uint32 intercept_instruction1_val{bsl::to_u32(0x00040000U)};
constexpr bsl::safe_uint64 intercept_instruction2_idx{bsl::to_u64(0x0010U)};
constexpr bsl::safe_uint32 intercept_instruction2_val{bsl::to_u32(0x00000001U)};
ret = syscall::bf_vps_op_write32(
handle, vpsid, intercept_instruction1_idx, intercept_instruction1_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
ret = syscall::bf_vps_op_write32(
handle, vpsid, intercept_instruction2_idx, intercept_instruction2_val);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
/// NOTE:
/// - Report success. Specifically, when we return to the root OS,
/// setting RAX tells the loader that the hypervisor was successfully
/// set up.
///
ret = syscall::bf_vps_op_write_reg(
handle, vpsid, syscall::bf_reg_t::bf_reg_t_rax, bsl::ZERO_UMAX);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
return ret;
}
}
#endif
| 36.148148 | 100 | 0.649078 |
873caa37bbce2f14d1786d96714d740dd2881fc6 | 3,233 | cpp | C++ | Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp | avramidis/leetcode-problems | 66bf8eecdebe8d2b6bb45a23897a0c1938725116 | [
"BSL-1.0"
] | null | null | null | Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp | avramidis/leetcode-problems | 66bf8eecdebe8d2b6bb45a23897a0c1938725116 | [
"BSL-1.0"
] | null | null | null | Problems/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp | avramidis/leetcode-problems | 66bf8eecdebe8d2b6bb45a23897a0c1938725116 | [
"BSL-1.0"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include <iostream>
#include "catch.hpp"
class Solution {
public:
bool uniquestring(std::string s, int start, int end) {
for (int i = start; i < end; i++) {
for (int j = i + 1; j <= end; j++) {
if (s[i] == s[j]) {
return false;
}
}
}
return true;
}
int lengthOfLongestSubstring(std::string s) {
if (s.size() == 0)
{
return 0;
}
if (s.size() == 1)
{
return 1;
}
int result = 1;
for (size_t i = 0; i < s.size(); i++) {
for (size_t j = i + result; j < s.size(); j++) {
if (uniquestring(s, i, j)) {
if (j - i + 1 > result) {
result = j - i + 1;
}
}
}
}
return result;
}
};
TEST_CASE("Unique characters in string")
{
Solution solution;
SECTION("Input set 1") {
std::string input = "abcabcbb";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 7);
}
REQUIRE(result == false);
}
SECTION("Input set 2") {
std::string input = "a";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 0);
}
REQUIRE(result == true);
}
SECTION("Input set 3") {
std::string input = "au";
bool result = false;
BENCHMARK("Check if the string is made of unique characters")
{
result = solution.uniquestring(input, 0, 1);
}
REQUIRE(result == true);
}
}
TEST_CASE("Longest Substring Without Repeating Characters")
{
Solution solution;
SECTION("Input set 1") {
std::string input = "abcabcbb";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
SECTION("Input set 2") {
std::string input = "bbbbb";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 1);
}
SECTION("Input set 3") {
std::string input = "pwwkew";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
SECTION("Input set 4") {
std::string input = "c";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 1);
}
SECTION("Input set 5") {
std::string input = "au";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 2);
}
SECTION("Input set 6") {
std::string input = "";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 0);
}
SECTION("Input set 6") {
std::string input = "dvdf";
int result = 0;
BENCHMARK("Calculate length of the longest substring with unique characters")
{
result = solution.lengthOfLongestSubstring(input);
}
REQUIRE(result == 3);
}
} | 20.993506 | 79 | 0.63656 |
873d5ba06c2499a76b4caaa26d68da4ab04e88e0 | 4,161 | cxx | C++ | Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx | eile/ITK | 2f09e6e2f9e0a4a7269ac83c597f97b04f915dc1 | [
"Apache-2.0"
] | 4 | 2015-05-22T03:47:43.000Z | 2016-06-16T20:57:21.000Z | Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | null | null | null | Modules/Nonunit/Review/test/itkValuedRegionalMinimaImageFilterTest.cxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | 9 | 2016-06-23T16:03:12.000Z | 2022-03-31T09:25:08.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
// a test routine for regional extrema using flooding
#include "itkValuedRegionalMinimaImageFilter.h"
#include "itkMaximumImageFilter.h"
#include "itkHConcaveImageFilter.h"
#include "itkInvertIntensityImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkAndImageFilter.h"
#include "itkSimpleFilterWatcher.h"
int itkValuedRegionalMinimaImageFilterTest(int argc, char * argv[])
{
const int dim = 2;
if( argc < 5 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage OutputImageFile1 OutputImageFile2 "
<< "OutputImageFile3" << std::endl;
return EXIT_FAILURE;
}
typedef unsigned char PixelType;
typedef itk::Image< PixelType, dim > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
typedef itk::ValuedRegionalMinimaImageFilter< ImageType, ImageType >
FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetFullyConnected( atoi(argv[1]) );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[3] );
writer->Update();
// produce the same output with other filters
typedef itk::HConcaveImageFilter< ImageType, ImageType > ConcaveType;
ConcaveType::Pointer concave = ConcaveType::New();
concave->SetInput( reader->GetOutput() );
concave->SetFullyConnected( atoi(argv[1]) );
concave->SetHeight( 1 );
// concave gives minima with value=1 and others with value=0
// rescale the image so we have minima=255 other=0
typedef itk::RescaleIntensityImageFilter< ImageType, ImageType > RescaleType;
RescaleType::Pointer rescale = RescaleType::New();
rescale->SetInput( concave->GetOutput() );
rescale->SetOutputMaximum( 255 );
rescale->SetOutputMinimum( 0 );
// in the input image, select the values of the pixel at the minima
typedef itk::AndImageFilter< ImageType, ImageType, ImageType > AndType;
AndType::Pointer a = AndType::New();
a->SetInput(0, rescale->GetOutput() );
a->SetInput(1, reader->GetOutput() );
// all pixel which are not minima must have value=255.
// get the non minima pixel by inverting the rescaled image
// we will have minima value=0 and non minima value=255
typedef itk::InvertIntensityImageFilter< ImageType, ImageType > InvertType;
InvertType::Pointer invert = InvertType::New();
invert->SetInput( rescale->GetOutput() );
// get the highest value from "a" and from invert. The minima have
// value>=0 in "a" image and the non minima have a value=0. In invert,
// the non minima have a value=255 and the minima a value=0
typedef itk::MaximumImageFilter< ImageType, ImageType, ImageType > MaxType;
MaxType::Pointer max = MaxType::New();
max->SetInput(0, invert->GetOutput() );
max->SetInput(1, a->GetOutput() );
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( max->GetOutput() );
writer2->SetFileName( argv[4] );
writer2->Update();
return EXIT_SUCCESS;
}
| 39.628571 | 79 | 0.681086 |
8741c16bd32064b343cce9ecb937c002335fe039 | 10,584 | cpp | C++ | src/GCloudIoTMqtt.cpp | ferlipaz/google-cloud-iot-arduino | 5693e520a6331e52c3ef654fc8ebca0c4179bcb2 | [
"Apache-2.0"
] | null | null | null | src/GCloudIoTMqtt.cpp | ferlipaz/google-cloud-iot-arduino | 5693e520a6331e52c3ef654fc8ebca0c4179bcb2 | [
"Apache-2.0"
] | null | null | null | src/GCloudIoTMqtt.cpp | ferlipaz/google-cloud-iot-arduino | 5693e520a6331e52c3ef654fc8ebca0c4179bcb2 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2019 Google
* 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 "GCloudIoTMqtt.h"
#include "CloudIoTCore.h"
#ifdef ESP8266
#include <ESP8266WiFi.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#endif
// connection exponential backoff settings
// see: https://cloud.google.com/iot/docs/how-tos/exponential-backoff
#define EXP_BACKOFF_FACTOR 2
#define EXP_BACKOFF_MIN_MS 1000
#define EXP_BACKOFF_MAX_MS 32000
#define EXP_BACKOFF_JITTER_MS 500
// Certificates for SSL on the Google Cloud IOT LTS server
const char* gciot_primary_ca = CLOUD_IOT_CORE_LTS_PRIMARY_CA;
const char* gciot_backup_ca = CLOUD_IOT_CORE_LTS_BACKUP_CA;
class MQTTClientWithCookie : public MQTTClient {
public:
MQTTClientWithCookie(int bufSize, void * cookie)
: MQTTClient(bufSize) { _cookie_ = cookie; }
void * _cookie_;
};
void gciot_onMessageAdv(MQTTClient *client, char topic[], char bytes[], int length) {
GCloudIoTMqtt * gcmqtt = (GCloudIoTMqtt*)((MQTTClientWithCookie *)client)->_cookie_;
String topic_str = String(topic);
String payload_str = String((const char *)bytes);
if (gcmqtt != NULL) {
gcmqtt->onMessageReceived(topic_str, payload_str);
}
}
///////////////////////////////
// MQTT common functions
///////////////////////////////
GCloudIoTMqtt::GCloudIoTMqtt(CloudIoTCoreDevice * device)
{
this->device = device;
}
GCloudIoTMqtt::~GCloudIoTMqtt()
{
cleanup();
}
bool GCloudIoTMqtt::setup(int bufsize, int keepAlive_sec, int timeout_ms)
{
// ESP8266 WiFi setup
this->netClient = new BearSSL::WiFiClientSecure();
this->certList = new BearSSL::X509List();
// ESP8266 WiFi secure initialization
// Set CA cert on wifi client
this->certList->append(gciot_primary_ca);
this->certList->append(gciot_backup_ca);
this->netClient->setTrustAnchors(this->certList);
this->mqttClient = new MQTTClientWithCookie(bufsize, this);
this->mqttClient->setOptions(keepAlive_sec, true, timeout_ms);
this->backoff_until_millis = 0;
this->backoff_ms = 0;
this->useLts = true;
if (this->useLts) {
this->mqttClient->begin(CLOUD_IOT_CORE_MQTT_HOST_LTS, CLOUD_IOT_CORE_MQTT_PORT, *netClient);
} else {
this->mqttClient->begin(CLOUD_IOT_CORE_MQTT_HOST, CLOUD_IOT_CORE_MQTT_PORT, *netClient);
}
this->mqttClient->onMessageAdvanced(gciot_onMessageAdv);
return true;
}
void GCloudIoTMqtt::cleanup() {
if (this->mqttClient != NULL) {
this->mqttClient->disconnect();
delete this->mqttClient;
this->mqttClient = NULL;
}
if (this->netClient != NULL) {
delete this->netClient;
this->netClient = NULL;
}
if (this->certList != NULL) {
delete this->certList;
this->certList = NULL;
}
}
bool GCloudIoTMqtt::connect(bool auto_reconnect, bool skip) {
this->autoReconnect = true;
// regenerate JWT if expiring
if ((millis() + 60000) > device->getExpMillis()) {
// reconnecting before JWT expiration
GCIOT_DEBUG_LOG("cloudiotmqtt: JWT expired, regenerating...\n");
device->createJWT(); // Regenerate JWT using device function
}
bool result =
this->mqttClient->connect(
device->getClientId().c_str(),
"unused",
device->getJWT().c_str(),
skip);
GCIOT_DEBUG_LOG("cloudiotmqtt: connect rc=%s [%d], errcode=%s [%d]\n",
getLastConnectReturnCodeAsString().c_str(), mqttClient->returnCode(),
getLastErrorCodeAsString().c_str(), getLastErrorCode());
if (result && this->mqttClient->connected()) {
this->backoff_ms = 0;
// Set QoS to 1 (ack) for configuration messages
this->mqttClient->subscribe(device->getConfigTopic(), 1);
// QoS 0 (no ack) for commands
this->mqttClient->subscribe(device->getCommandsTopic(), 0);
onConnect();
return true;
}
switch(mqttClient->returnCode()) {
case (LWMQTT_BAD_USERNAME_OR_PASSWORD):
case (LWMQTT_NOT_AUTHORIZED):
GCIOT_DEBUG_LOG("cloudiotmqtt: auth failed: regenerating JWT token\n");
device->createJWT(); // Regenerate JWT using device function
default:
break;
}
// See https://cloud.google.com/iot/docs/how-tos/exponential-backoff
if (this->backoff_ms < EXP_BACKOFF_MIN_MS) {
this->backoff_ms = EXP_BACKOFF_MIN_MS + random(EXP_BACKOFF_JITTER_MS);
} else if (this->backoff_ms < EXP_BACKOFF_MAX_MS) {
this->backoff_ms = this->backoff_ms * EXP_BACKOFF_FACTOR + random(EXP_BACKOFF_JITTER_MS);
}
this->backoff_until_millis = millis() + this->backoff_ms;
return false;
}
bool GCloudIoTMqtt::connected()
{
return this->mqttClient->connected();
}
bool GCloudIoTMqtt::disconnect()
{
this->autoReconnect = false;
return mqttClient->disconnect();
}
void GCloudIoTMqtt::loop() {
if (mqttClient->connected() && (millis() + 60000) > device->getExpMillis()) {
// reconnecting before JWT expiration
GCIOT_DEBUG_LOG("cloudiotmqtt: JWT expiring, disconnecting to regenerate...\n");
mqttClient->disconnect();
connect(autoReconnect, false); // TODO: should we skip closing connection
} else if (autoReconnect && !mqttClient->connected() && millis() > this->backoff_until_millis) {
if (isNetworkConnected()) {
// attempt to reconnect only if network is connected
GCIOT_DEBUG_LOG("cloudiotmqtt: reconnecting...\n");
connect(true);
}
}
this->mqttClient->loop();
}
bool GCloudIoTMqtt::publishTelemetry(String data) {
return this->mqttClient->publish(device->getEventsTopic(), data);
}
bool GCloudIoTMqtt::publishTelemetry(String data, int qos) {
return this->mqttClient->publish(device->getEventsTopic(), data, false, qos);
}
bool GCloudIoTMqtt::publishTelemetry(const char* data, int length) {
return this->mqttClient->publish(device->getEventsTopic().c_str(), data, length);
}
bool GCloudIoTMqtt::publishTelemetry(String subtopic, String data) {
return this->mqttClient->publish(device->getEventsTopic() + subtopic, data);
}
bool GCloudIoTMqtt::publishTelemetry(String subtopic, String data, int qos) {
return this->mqttClient->publish(device->getEventsTopic() + subtopic, data, false, qos);
}
bool GCloudIoTMqtt::publishTelemetry(String subtopic, const char* data, int length) {
return this->mqttClient->publish(String(device->getEventsTopic() + subtopic).c_str(), data, length);
}
// Helper that just sends default sensor
bool GCloudIoTMqtt::publishState(String data) {
return this->mqttClient->publish(device->getStateTopic(), data);
}
bool GCloudIoTMqtt::publishState(const char* data, int length) {
return this->mqttClient->publish(device->getStateTopic().c_str(), data, length);
}
void GCloudIoTMqtt::onConnect() {
if (logConnect) {
publishState("connected");
publishTelemetry("/events", device->getDeviceId() + String("-connected"));
}
}
void GCloudIoTMqtt::onMessageReceived(String &topic, String &payload) {
if (device->getCommandsTopic().startsWith(topic)) {
if (commandCB != NULL)
commandCB(topic, payload);
} else if (device->getConfigTopic().startsWith(topic)) {
if (configCB != NULL)
configCB(topic, payload);
} else if (messageCB != NULL) {
messageCB(topic, payload);
}
}
bool GCloudIoTMqtt::isNetworkConnected() {
return WiFi.status() == WL_CONNECTED;
}
void GCloudIoTMqtt::setLogConnect(bool enabled) {
this->logConnect = enabled;
}
void GCloudIoTMqtt::setUseLts(bool enabled) {
this->useLts = enabled;
}
void GCloudIoTMqtt::setCommandCallback(MQTTClientCallbackSimple cb) {
this->commandCB = cb;
}
void GCloudIoTMqtt::setConfigCallback(MQTTClientCallbackSimple cb) {
this->configCB = cb;
}
void GCloudIoTMqtt::setMessageCallback(MQTTClientCallbackSimple cb) {
this->messageCB = cb;
}
int GCloudIoTMqtt::getLastErrorCode()
{
return this->mqttClient->lastError();
}
String GCloudIoTMqtt::getLastErrorCodeAsString()
{
switch(mqttClient->lastError()) {
case (LWMQTT_BUFFER_TOO_SHORT):
return String("LWMQTT_BUFFER_TOO_SHORT");
case (LWMQTT_VARNUM_OVERFLOW):
return String("LWMQTT_VARNUM_OVERFLOW");
case (LWMQTT_NETWORK_FAILED_CONNECT):
return String("LWMQTT_NETWORK_FAILED_CONNECT");
case (LWMQTT_NETWORK_TIMEOUT):
return String("LWMQTT_NETWORK_TIMEOUT");
case (LWMQTT_NETWORK_FAILED_READ):
return String("LWMQTT_NETWORK_FAILED_READ");
case (LWMQTT_NETWORK_FAILED_WRITE):
return String("LWMQTT_NETWORK_FAILED_WRITE");
case (LWMQTT_REMAINING_LENGTH_OVERFLOW):
return String("LWMQTT_REMAINING_LENGTH_OVERFLOW");
case (LWMQTT_REMAINING_LENGTH_MISMATCH):
return String("LWMQTT_REMAINING_LENGTH_MISMATCH");
case (LWMQTT_MISSING_OR_WRONG_PACKET):
return String("LWMQTT_MISSING_OR_WRONG_PACKET");
case (LWMQTT_CONNECTION_DENIED):
return String("LWMQTT_CONNECTION_DENIED");
case (LWMQTT_FAILED_SUBSCRIPTION):
return String("LWMQTT_FAILED_SUBSCRIPTION");
case (LWMQTT_SUBACK_ARRAY_OVERFLOW):
return String("LWMQTT_SUBACK_ARRAY_OVERFLOW");
case (LWMQTT_PONG_TIMEOUT):
return String("LWMQTT_PONG_TIMEOUT");
default:
return String("Unknown error");
}
}
int GCloudIoTMqtt::getLastConnectReturnCode()
{
return this->mqttClient->returnCode();
}
String GCloudIoTMqtt::getLastConnectReturnCodeAsString()
{
switch(mqttClient->returnCode()) {
case (LWMQTT_CONNECTION_ACCEPTED):
return String("OK");
case (LWMQTT_UNACCEPTABLE_PROTOCOL):
return String("LWMQTT_UNACCEPTABLE_PROTOCOLL");
case (LWMQTT_IDENTIFIER_REJECTED):
return String("LWMQTT_IDENTIFIER_REJECTED");
case (LWMQTT_SERVER_UNAVAILABLE):
return String("LWMQTT_SERVER_UNAVAILABLE");
case (LWMQTT_BAD_USERNAME_OR_PASSWORD):
return String("LWMQTT_BAD_USERNAME_OR_PASSWORD");
case (LWMQTT_NOT_AUTHORIZED):
return String("LWMQTT_NOT_AUTHORIZED");
case (LWMQTT_UNKNOWN_RETURN_CODE):
return String("LWMQTT_UNKNOWN_RETURN_CODE");
default:
return String("Unknown return code.");
}
}
| 30.326648 | 102 | 0.705593 |
874365d921d57769ce83eae4b8a2a5f3cfdd58e2 | 763 | cpp | C++ | src/Boring32/src/Guid/Guid.cpp | yottaawesome/boring32 | ecf843c200b133a4fad711dcf52419c0c88af49c | [
"MIT"
] | 3 | 2021-11-25T13:44:57.000Z | 2022-02-22T05:50:34.000Z | src/Boring32/src/Guid/Guid.cpp | yottaawesome/boring32 | ecf843c200b133a4fad711dcf52419c0c88af49c | [
"MIT"
] | 3 | 2021-10-13T10:58:30.000Z | 2021-12-21T05:46:41.000Z | src/Boring32/src/Guid/Guid.cpp | yottaawesome/boring32 | ecf843c200b133a4fad711dcf52419c0c88af49c | [
"MIT"
] | null | null | null | #include "pch.hpp"
#include "Objbase.h"
#include "include/Error/Error.hpp"
#include "include/Guid/Guid.hpp"
namespace Boring32::Guid
{
// Adapted from https://stackoverflow.com/a/19941516/7448661
std::wstring GetGuidAsWString(const GUID& guid)
{
wchar_t rawGuid[64] = { 0 };
HRESULT result = StringFromGUID2(guid, rawGuid, 64);
if (StringFromGUID2(guid, rawGuid, 64) == 0)
throw std::runtime_error("GetGuidAsWString(): StringFromGUID2() failed");
return rawGuid;
}
std::wstring GetGuidAsWString()
{
GUID guidReference;
HRESULT result = CoCreateGuid(&guidReference);
if (FAILED(result))
throw Error::ComError("GetGuidAsWString(): CoCreateGuid() failed", result);
return GetGuidAsWString(guidReference);
}
}
| 28.259259 | 79 | 0.70249 |
87448d25f36aecf10d18da35b06ac2ad09acc6df | 6,583 | cc | C++ | StRoot/StTrsMaker/src/StTpcDbElectronics.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StTrsMaker/src/StTpcDbElectronics.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StTrsMaker/src/StTpcDbElectronics.cc | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /*****************************************************************
*
* $Id: StTpcDbElectronics.cc,v 1.7 2008/08/02 14:33:09 fisyak Exp $
*
* Author: Manuel Calderon de la Barca Sanchez & Brian Lasiuk Sept 13, 1999
*
*****************************************************************
* Description: Electronics parameters for TRS taken from DB for
* the STAR Main TPC
*
*****************************************************************
*
* $Log: StTpcDbElectronics.cc,v $
* Revision 1.7 2008/08/02 14:33:09 fisyak
* new interface to tpcT0
*
* Revision 1.6 2008/06/20 15:01:12 fisyak
* move from StTrsData to StTpcRawData
*
* Revision 1.5 2000/03/15 17:39:48 calderon
* Remove beeps
*
* Revision 1.4 2000/02/10 01:21:49 calderon
* Switch to use StTpcDb.
* Coordinates checked for consistency.
* Fixed problems with StTrsIstream & StTrsOstream.
*
* Revision 1.3 2000/01/10 23:14:29 lasiuk
* Include MACROS for compatiblity with SUN CC5
*
* Revision 1.2 1999/12/08 02:10:41 calderon
* Modified to eliminate warnings on Linux.
*
* Revision 1.1 1999/10/11 23:55:20 calderon
* Version with Database Access and persistent file.
* Not fully tested due to problems with cons, it
* doesn't find the local files at compile time.
* Yuri suggests forcing commit to work directly with
* files in repository.
*
******************************************************************/
#include "SystemOfUnits.h"
#include "StTpcDbElectronics.hh"
//#include "StUtilities/StMessMgr.h"
#include "StTpcDb/StTpcDb.h"
#ifndef ST_NO_EXCEPTIONS
# include <stdexcept>
# if !defined(ST_NO_NAMESPACES)
using std::invalid_argument;
# endif
#endif
StTpcElectronics* StTpcDbElectronics::mInstance = 0; // static data member
StTpcDbElectronics::StTpcDbElectronics() { /* nopt */ }
StTpcDbElectronics::StTpcDbElectronics(StTpcDb* globalDbPointer)
{
gTpcDbPtr = globalDbPointer;
mNominalGain = gTpcDbPtr->Electronics()->nominalGain();
mSamplingFrequency = gTpcDbPtr->Electronics()->samplingFrequency();
mTZero = gTpcDbPtr->Electronics()->tZero();
mAdcConversion = gTpcDbPtr->Electronics()->adcConversion();
mAdcConversionCharge = gTpcDbPtr->Electronics()->adcCharge();
mNumberOfTimeBins = gTpcDbPtr->Electronics()->numberOfTimeBins();
mAveragePedestal = static_cast<int>(gTpcDbPtr->Electronics()->averagePedestal());
mShapingTime = gTpcDbPtr->Electronics()->shapingTime();
mTau = gTpcDbPtr->Electronics()->tau();
#ifndef ST_NO_NAMESPACES
using namespace units;
#endif
//Units Integrity
mNominalGain *= (millivolt)/(coulomb*1.e-15); // mV/fC
mSamplingFrequency *= MHz;
mTZero *= microsecond;
mAdcConversion *= (millivolt);
mAdcConversionCharge *= (coulomb*1.e-15);
mShapingTime *= nanosecond;
mTau *= nanosecond;
}
StTpcElectronics*
StTpcDbElectronics::instance()
{
if (!mInstance) {
#ifndef ST_NO_EXCEPTIONS
throw invalid_argument("StTpcDbElectronics::getInstance(): Argument Missing!");
#else
cerr << "StTpcDbElectronics::getInstance(): Argument Missing!" << endl;
cerr << "No arguments for instantiantion" << endl;
cerr << "Exiting..." << endl;
#endif
}
return mInstance;
}
StTpcElectronics*
StTpcDbElectronics::instance(StTpcDb* gTpcDbPtr)
{
if (!mInstance) {
mInstance = new StTpcDbElectronics(gTpcDbPtr);
}
else {
cerr << "StTpcDbElectronics::instance()" << endl;
cerr << "\tWARNING:" << endl;
cerr << "\tSingleton class is already instantiated" << endl;
cerr << "\tArgument ignored!!" << endl;
cerr << "\tContinuing..." << endl;
}
return mInstance;
}
double StTpcDbElectronics::channelGain(int sector, int row, int pad) const
{
// This should be where channel by channel gains are looked up
// Note: the DB has getGain(), getOnlineGain(), getNominalGain(), and
// getRelativeGain(). We use Nominal gain I believe.
return 1.;//gTpcDbPtr->Gain(sector)->getNominalGain(row,pad);
}
double StTpcDbElectronics::channelGain(StTpcPadCoordinate& coord) const
{
return channelGain(coord.sector(), coord.row(), (Int_t) coord.pad());
}
int StTpcDbElectronics::pedestal(int sector, int row, int pad, int timeB) const
{
return averagePedestal();
}
int StTpcDbElectronics::pedestal(StTpcPadCoordinate& coord) const
{
return pedestal(coord.sector(), coord.row(), (Int_t) coord.pad(), (Int_t) coord.timeBucket());
}
double StTpcDbElectronics::tZero(int sector, int row, int pad) const
{
return gTpcDbPtr->tpcT0()->T0(sector,row,pad);
}
double StTpcDbElectronics::tZero(StTpcPadCoordinate& coord) const
{
return tZero(coord.sector(), coord.row(), (Int_t) coord.pad());
}
void StTpcDbElectronics::print(ostream& os) const
{
#ifndef ST_NO_NAMESPACES
using namespace units;
#endif
os << "Electronics Data Base Parameters" << endl;
os << "=======================================" << endl;
os << "Analog:" << endl;
os << "nominalGain: " << mNominalGain/((volt*.001)/(coulomb*1.e-15)) << " mV/fC" << endl;
os << "samplingFrequency: " << mSamplingFrequency/MHz << " MHz" << endl;
os << "tZero: " << mTZero/microsecond << " us" << endl;
os << "shapingTime: " << mShapingTime/nanosecond << " ns" << endl;
os << "shapingTime2: " << mTau/nanosecond << " ns" << endl;
os << "\nDigital:" << endl;
os << "adcConversion: " << mAdcConversion/(volt*.001) << " mV/channel" << endl;
os << "adcConversionCharge: " << mAdcConversionCharge/(coulomb*1.e-15) << " mV/fC" << endl;
os << "numberOfTimeBins: " << mNumberOfTimeBins << endl;
os << "averagePedestal: " << mAveragePedestal << " channels" << endl;
os << endl;
// os << "Example of Gain per pad for Sector 1, Row 1" << endl;
// os << " Row Pad Gain for this Pad" << endl;
// os << "==========================================" << endl;
// for(int i=0; i<gTpcDbPtr->PadPlaneGeometry()->numberOfPadsAtRow(1); i++) {
// os.width(3);
// os.setf(ios::right,ios::adjustfield);
// os << 1;
// os.width(9);
// os << i+1;
// os.width(15);
// os << channelGain(1,1,i+1) << endl;
// }
// os << endl;
}
| 36.572222 | 108 | 0.588789 |
87457da4b1247ff3584eeeccebd30216871749ea | 1,586 | cpp | C++ | tests/unit/countersignature.cpp | LaudateCorpus1/authenticode-parser | 7653bb1c60b9eed74613dceb84b61ddd7b5127a1 | [
"MIT"
] | 4 | 2022-01-10T09:44:47.000Z | 2022-03-15T11:50:46.000Z | tests/unit/countersignature.cpp | LaudateCorpus1/authenticode-parser | 7653bb1c60b9eed74613dceb84b61ddd7b5127a1 | [
"MIT"
] | 1 | 2022-01-20T04:14:24.000Z | 2022-01-22T16:51:07.000Z | tests/unit/countersignature.cpp | LaudateCorpus1/authenticode-parser | 7653bb1c60b9eed74613dceb84b61ddd7b5127a1 | [
"MIT"
] | 2 | 2022-02-02T13:36:09.000Z | 2022-03-15T11:50:48.000Z | #include "../../src/countersignature.h"
#include <cstdint>
#include <cstring>
#include <gtest/gtest.h>
TEST(CountersignatureModule, countersignature_array_insert)
{
CountersignatureArray array;
array.counters = nullptr;
array.count = 0;
Countersignature countersig1 = {};
int res = countersignature_array_insert(&array, &countersig1);
EXPECT_EQ(res, 0);
ASSERT_EQ(array.count, 1);
ASSERT_TRUE(array.counters);
EXPECT_EQ(array.counters[0], &countersig1);
Countersignature countersig2;
res = countersignature_array_insert(&array, &countersig2);
EXPECT_EQ(res, 0);
ASSERT_EQ(array.count, 2);
ASSERT_TRUE(array.counters);
EXPECT_EQ(array.counters[1], &countersig2);
free(array.counters);
}
TEST(CountersignatureModule, countersignature_array_move)
{
CountersignatureArray array1;
array1.counters = nullptr;
array1.count = 0;
CountersignatureArray array2;
array2.counters = nullptr;
array2.count = 0;
Countersignature countersig1;
Countersignature countersig2;
int res = countersignature_array_insert(&array2, &countersig1);
EXPECT_EQ(res, 0);
res = countersignature_array_insert(&array2, &countersig2);
EXPECT_EQ(res, 0);
res = countersignature_array_move(&array1, &array2);
EXPECT_EQ(res, 0);
ASSERT_TRUE(array1.counters);
ASSERT_EQ(array1.count, 2);
EXPECT_EQ(array1.counters[0], &countersig1);
EXPECT_EQ(array1.counters[1], &countersig2);
EXPECT_EQ(array2.count, 0);
EXPECT_FALSE(array2.counters);
free(array1.counters);
} | 24.78125 | 67 | 0.710593 |
8750c0266c8d52d61c41c50a4592b2709ca57cc0 | 27,434 | cpp | C++ | experiment.cpp | ChristophKuhfuss/stneatexperiment | ca754fb679658072f4dacc4354a319db3faf660b | [
"BSD-3-Clause"
] | null | null | null | experiment.cpp | ChristophKuhfuss/stneatexperiment | ca754fb679658072f4dacc4354a319db3faf660b | [
"BSD-3-Clause"
] | null | null | null | experiment.cpp | ChristophKuhfuss/stneatexperiment | ca754fb679658072f4dacc4354a319db3faf660b | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <string.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <sstream>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <string>
#include <math.h>
#include <chrono>
#include <sys/stat.h>
#include <sqlite3.h>
#include "experiment.hpp"
#include <signal.h>
string Experiment::temp_pop_filename = "temp_pop";
string Experiment::db_filename = "neat.db";
int Experiment::max_db_retry = 100;
int Experiment::db_sleeptime = 50;
string Experiment::path_to_supertux_executable = "./bin/build/supertux2";
int Experiment::cur_gen = 0;
bool Experiment::new_top = true;
int Experiment::top_genome_gen_id = 0;
int Experiment::top_genome_id = 0;
double Experiment::top_fitness = 0;
int Experiment::num_winner_genomes = 0;
float Experiment::fitness_sum = 0;
float Experiment::airtime_sum = 0;
float Experiment::groundtime_sum = 0;
int Experiment::jump_sum = 0;
double Experiment::evaluation_time = 0;
Parameters Experiment::params;
vector<Genome*> Experiment::genomes;
vector<PhenotypeBehavior> Experiment::archive;
int main(int argc, char **argv) {
std::cout << "SuperTux + NEAT interface and experiment code by Christoph Kuhfuss 2018" << std::endl;
std::cout << "Using the original SuperTux source and the MultiNEAT framework by Peter Chervenski (https://github.com/peter-ch/MultiNEAT)" << std::endl;
Experiment::parse_commandline_arguments(argc, argv);
Experiment::fix_filenames();
Experiment::parse_experiment_parameters();
Experiment::params = Experiment::init_params();
Experiment experiment;
experiment.run_evolution();
return 0;
}
Experiment::Experiment() :
start_genome(0, ExperimentParameters::AMOUNT_RANGE_SENSORS + ExperimentParameters::AMOUNT_DEPTH_SENSORS + ExperimentParameters::AMOUNT_PIESLICE_SENSORS * 2 + 1, ExperimentParameters::num_hidden_start_neurons,
6, false, UNSIGNED_SIGMOID, UNSIGNED_SIGMOID, 1, params),
pop(strcmp(ExperimentParameters::pop_filename.c_str(), "") ?
Population(ExperimentParameters::pop_filename.c_str()) : Population(start_genome, params, true, 2.0, (ExperimentParameters::using_seed ? ExperimentParameters::seed : (int) time(0)))),
total_gen_time(0)
{
if (ExperimentParameters::hyperneat)
{
generate_substrate();
}
}
Experiment::~Experiment()
{
}
void Experiment::run_evolution() {
std::remove(db_filename.c_str());
init_db();
for (int i = 1; i <= ExperimentParameters::max_gens; i++) {
std::cout << "Working on generation #" << i << "..." << std::endl;
Experiment::new_top = false;
num_winner_genomes = 0;
fitness_sum = 0;
airtime_sum = 0;
groundtime_sum = 0;
jump_sum = 0;
evaluation_time = 0;
cur_gen = i;
refresh_genome_list();
if (ExperimentParameters::novelty_search) {
std::vector<PhenotypeBehavior>* behaviors = new std::vector<PhenotypeBehavior>();
for (int i = 0; i < genomes.size(); i++)
behaviors->push_back(Behavior());
pop.InitPhenotypeBehaviorData(behaviors, &archive);
}
// Prepare db file...
update_db();
// Run supertux processes...
start_processes();
// ... and get the fitness values from the db file
// Also update info about the generation
set_fitness_values();
update_gen_info();
std::cout << "Done. Top fitness: " << top_fitness << " by individual #" << top_genome_id << ", generation #" << top_genome_gen_id << std::endl;
std::cout << "Evaluation time: " << (int) (evaluation_time / 60) << "min" << (int) evaluation_time % 60 << "sec" << std::endl;
std::cout << num_winner_genomes << " genome(s) out of " << genomes.size() << " finished the level (" << num_winner_genomes / (double) genomes.size() * 100 << "%)" << std::endl;
if (ExperimentParameters::autosave_best && Experiment::new_top) {
std::ostringstream ss;
ss << "./neat_gen" << cur_gen;
save_pop(ss.str().c_str());
}
else if (!ExperimentParameters::autosave_best && i % ExperimentParameters::autosave_interval == 0) {
std::ostringstream ss;
ss << "./neat_gen" << cur_gen;
save_pop(ss.str().c_str());
}
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
pop.Epoch();
std::chrono::time_point<std::chrono::high_resolution_clock> finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
total_gen_time += elapsed.count();
}
}
void Experiment::start_processes()
{
// Save pop to single file for all child processes to read
pop.Save(temp_pop_filename.c_str());
// Distribute genomes as evenly as possible
int remaining_genome_count = genomes.size();
int cores_left = ExperimentParameters::num_cores;
std::vector<int> startindices;
std::vector<int> endindices;
int curindex = 0;
for (int j = 0; j < ExperimentParameters::num_cores; j++) {
startindices.push_back(++curindex - 1);
int single_genome_count = remaining_genome_count / cores_left;
if (remaining_genome_count % cores_left)
single_genome_count++;
remaining_genome_count -= single_genome_count;
cores_left--;
curindex += single_genome_count - 1;
endindices.push_back(curindex - 1);
}
// Build the GNU parallel command, include all parameter files and the levelfile
std::stringstream ss;
ss << "parallel --no-notice --xapply ";
ss << path_to_supertux_executable;
ss << " --neat";
// if (Experiment::novelty_search) ss << " --noveltysearch";
if (ExperimentParameters::hyperneat) ss << " --hyperneat";
// All child processes read from the same population file
ss << " --popfile " << boost::filesystem::canonical(temp_pop_filename);
// Only add experiment and MultiNEAT param files if they're configured...
if (strcmp(ExperimentParameters::experimentparam_filename.c_str(), "")) ss << " --experimentparamfile " << ExperimentParameters::experimentparam_filename;
if (strcmp(ExperimentParameters::param_filename.c_str(), "")) ss << " --paramfile " << ExperimentParameters::param_filename;
ss << " --dbfile " << boost::filesystem::canonical(db_filename);
ss << " --curgen " << cur_gen;
ss << " --fromtogenome ::: ";
for (std::vector<int>::iterator it = startindices.begin(); it != startindices.end(); ++it) {
ss << *it << " ";
}
ss << "::: ";
for (std::vector<int>::iterator it = endindices.begin(); it != endindices.end(); ++it) {
ss << *it << " ";
}
ss << "::: '";
ss << ExperimentParameters::path_to_level;
ss << "'";
// std::cout << ss.str() << std::endl;
// Ready to rumble, don't forget to measure the time
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
std::system(ss.str().c_str());
std::chrono::time_point<std::chrono::high_resolution_clock> finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
evaluation_time = elapsed.count();
// Remove temporary population file. If we have to, we'll make a new one
std::remove(temp_pop_filename.c_str());
}
void Experiment::init_db()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "CREATE TABLE RUN_INFO (id INT PRIMARY KEY NOT NULL, num_genomes INT, avg_fitness REAL, time REAL, avg_airtime REAL, avg_groundtime REAL, avg_jumps REAL, top_fitness REAL, amt_winners INT);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
sqlite3_close(db);
}
void Experiment::update_db()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss.str("");
ss << "CREATE TABLE GEN" << cur_gen << "(id INT PRIMARY KEY NOT NULL, fitness REAL, airtime REAL, groundtime REAL, num_jumps INT, qLeft REAL, qRight REAL, qUp REAL, qDown REAL, qJump REAL, qAction REAL, won INT);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
for(std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
ss.str("");
// Negative fitness if not evaluated yet. If fitness values stay negative, NEAT might just break
// Last values are for ns behavior
ss << "INSERT INTO GEN" << cur_gen << " VALUES(" << (*it)->GetID() << ", -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
}
sqlite3_close(db);
}
void Experiment::set_fitness_values()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "SELECT * FROM gen" << cur_gen << ";";
sqlite3_exec(db, ss.str().c_str(), (ExperimentParameters::novelty_search ? select_handler_ns : select_handler), 0, &err);
if (ExperimentParameters::novelty_search) {
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->m_PhenotypeBehavior->m_Data[0].size() == 0) {
std::cout << "ERROR OCCURED WITH GENOME #" << (*it)->GetID() << std::endl;
}
}
update_sparsenesses();
}
sqlite3_close(db);
}
void Experiment::update_gen_info()
{
sqlite3* db;
sqlite3_open("neat.db", &db);
sqlite3_busy_handler(db, busy_handler, (void*) nullptr);
char* err;
std::stringstream ss;
ss << "INSERT INTO RUN_INFO VALUES(" << cur_gen << ", " << genomes.size() << ", " << fitness_sum / genomes.size() << ", " << evaluation_time << ", " << (airtime_sum / (double) genomes.size()) << ", " << (groundtime_sum / (double) genomes.size()) << ", " << ((double) jump_sum) / genomes.size() << ", " << top_fitness << ", " << num_winner_genomes << ");";
sqlite3_exec(db, ss.str().c_str(), 0, 0, &err);
sqlite3_close(db);
}
void Experiment::refresh_genome_list()
{
genomes.clear();
for (unsigned int i = 0; i < pop.m_Species.size(); i++) {
Species* cur = &pop.m_Species[i];
// std::cout << "Species #" << cur->ID() << " has " << cur->m_Individuals.size() << " individuals" << std::endl;
for (unsigned int j = 0; j < cur->m_Individuals.size(); j++) {
cur->m_Individuals[j].m_PhenotypeBehavior = new Behavior();
genomes.push_back(&cur->m_Individuals[j]);
}
// Probably unneccessary
sort(genomes.begin(), genomes.end(), [ ](const Genome* lhs, const Genome* rhs)
{
return lhs->GetID() < rhs->GetID();
});
}
}
double Experiment::sparseness(Genome* g)
{
std::vector<double> distances;
double sum = 0;
int amt = 0;
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
//std::cout << "Calculating distance between genomes #" << g->GetID() << " and #" << (*it)->GetID() << std::endl;
amt++;
distances.push_back(g->m_PhenotypeBehavior->Distance_To((*it)->m_PhenotypeBehavior));
}
for (std::vector<PhenotypeBehavior>::iterator it = archive.begin(); it != archive.end(); ++it) {
amt++;
distances.push_back(g->m_PhenotypeBehavior->Distance_To(&(*it)));
}
sort(distances.begin(), distances.end(), [ ](const double lhs, const double rhs)
{
return lhs < rhs;
});
for (int i = 0; i < params.NoveltySearch_K; i++) {
sum += distances[i];
}
// std::cout << "Sparseness for genome #" << g->GetID() << " is " << sum / amt << std::endl;
if (amt > 0) {
double sparseness = sum / amt;
if (sparseness > params.NoveltySearch_P_min) {
archive.push_back(*(g->m_PhenotypeBehavior));
}
return sum / amt;
}
else
return 0;
}
void Experiment::update_sparsenesses()
{
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it)
{
(*it)->SetFitness(pop.ComputeSparseness(*(*it)));
(*it)->SetEvaluated();
}
}
void Experiment::generate_substrate()
{
SensorManager sm;
sm.initSensors();
std::vector<std::vector<double>> input_coords;
std::vector<std::vector<double>> hidden_coords; // TODO: Add support for hidden neurons (third dimension, arrange in a circle)
std::vector<std::vector<double>> output_coords;
std::vector<std::shared_ptr<RangeFinderSensor>>* rfsensors = sm.get_cur_rangefinder_sensors();
std::vector<std::shared_ptr<DepthFinderSensor>>* dfsensors = sm.get_cur_depthfinder_sensors();
std::vector<std::shared_ptr<PieSliceSensor>>* pssensors = sm.get_cur_pieslice_sensors();
double inputZ = -1;
double outputZ = 1;
double hiddenZ = 0;
// First, calculate maximum x and y coordinates so we can normalize substrate coordinates to (-1, 1)
int maxX = 0;
int maxY = 0;
if (ExperimentParameters::num_hidden_start_neurons > 0) {
std::vector<double> coords;
if (ExperimentParameters::num_hidden_start_neurons == 1) {
// If there is only one hidden start neuron, place it in the center and be done with it
coords.push_back(0);
coords.push_back(0);
coords.push_back(hiddenZ);
hidden_coords.push_back(coords);
} else {
// If there are more than one, arrange in a circle
coords.push_back(1);
coords.push_back(0);
coords.push_back(hiddenZ);
double cur_angle = 0;
// How many neurons per full rotation?
double angle_step = 2 * M_PI / ExperimentParameters::num_hidden_start_neurons;
for (int i = 0; i < ExperimentParameters::num_hidden_start_neurons - 1; i++) {
// Push back coordinates, rotate by the angle step each iteration
hidden_coords.push_back(coords);
std::vector<double> coords_new;
coords_new.push_back(coords.at(0) * cos(angle_step) + coords.at(1) * sin(angle_step));
coords_new.push_back(coords.at(1) * cos(angle_step) - coords.at(0) * sin(angle_step));
coords_new.push_back(hiddenZ);
coords = coords_new;
}
}
}
for (std::vector<std::shared_ptr<RangeFinderSensor>>::iterator it = rfsensors->begin(); it != rfsensors->end(); ++it)
{
Vector v = (*it)->get_offset();
// Get middle point of the RangeFinderSensor
int x = abs(v.x / 2.0);
int y = abs(v.y);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<DepthFinderSensor>>::iterator it = dfsensors->begin(); it != dfsensors->end(); ++it)
{
Vector v = (*it)->get_offset();
// Get middle point of the DepthFinderSensor
int x = abs(v.x);
int y = abs(v.y / 2.0);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<PieSliceSensor>>::iterator it = pssensors->begin(); it != pssensors->end(); ++it)
{
Vector v1 = (*it)->get_offset();
Vector v2 = (*it)->get_offset2();
// Get middle point of the PieSliceSensor
// Divide by three because both vectors form a triangle with (0, 0) as the third point
int x = abs((v1.x + v2.x) / 3.0);
int y = abs((v1.y + v2.y) / 3.0);
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
}
for (std::vector<std::shared_ptr<RangeFinderSensor>>::iterator it = rfsensors->begin(); it != rfsensors->end(); ++it)
{
std::vector<double> coords;
Vector v = (*it)->get_offset();
// Normalize between (0, 1) and then between (-1, 1)
coords.push_back(v.x / (double) maxX);
coords.push_back(v.y / (double) maxY);
coords.push_back(v.x);
coords.push_back(v.y);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
for (std::vector<std::shared_ptr<DepthFinderSensor>>::iterator it = dfsensors->begin(); it != dfsensors->end(); ++it)
{
std::vector<double> coords;
Vector v = (*it)->get_offset();
coords.push_back((v.x / (double) maxX));
coords.push_back((v.y / (double) maxY));
coords.push_back(v.x);
coords.push_back(v.y);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
for (std::vector<std::shared_ptr<PieSliceSensor>>::iterator it = pssensors->begin(); it != pssensors->end(); ++it)
{
std::vector<double> coords;
Vector v1 = (*it)->get_offset();
Vector v2 = (*it)->get_offset2();
// Same procedure as above, third point is (0, 0)
coords.push_back(((v1.x + v2.x) / 3.0) / (double) maxX);
coords.push_back(((v1.y + v2.y) / 3.0) / (double) maxY);
if (ExperimentParameters::num_hidden_start_neurons > 0) coords.push_back(inputZ);
input_coords.push_back(coords);
}
std::vector<double> bias;
bias.push_back(0);
bias.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) bias.push_back(inputZ);
input_coords.push_back(bias);
std::vector<double> output;
// Arrange output substrate coordinates around Tux
// UP should be above Tux, DOWN below, etc. with Tux "being" at (0, 0)
// UP
output.push_back(0);
output.push_back(1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// DOWN
output.push_back(0);
output.push_back(-1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// LEFT
output.push_back(-1);
output.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// RIGHT
output.push_back(1);
output.push_back(0);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// JUMP
output.push_back(0);
output.push_back(0.8);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
output.clear();
// ACTION
output.push_back(0);
output.push_back(0.1);
if (ExperimentParameters::num_hidden_start_neurons > 0) output.push_back(outputZ);
output_coords.push_back(output);
// Parameters taken from MultiNEAT's HyperNEAT example
substrate = Substrate(input_coords, hidden_coords, output_coords);
substrate.m_allow_hidden_hidden_links = false;
substrate.m_allow_hidden_output_links = true;
substrate.m_allow_input_hidden_links = true;
substrate.m_allow_input_output_links = true;
substrate.m_allow_looped_hidden_links = false;
substrate.m_allow_looped_output_links = false;
substrate.m_allow_output_hidden_links = false;
substrate.m_allow_output_output_links = false;
substrate.m_query_weights_only = true;
substrate.m_max_weight_and_bias = 8;
substrate.m_hidden_nodes_activation = ActivationFunction::SIGNED_SIGMOID;
substrate.m_output_nodes_activation = ActivationFunction::UNSIGNED_SIGMOID;
start_genome = Genome(0, substrate.GetMinCPPNInputs(), ExperimentParameters::num_hidden_start_neurons_cppn,
substrate.GetMinCPPNOutputs(), false, TANH, TANH, 0, params);
pop = strcmp(ExperimentParameters::pop_filename.c_str(), "") ? Population(ExperimentParameters::pop_filename.c_str()) : Population(start_genome, params, true, 1.0, (ExperimentParameters::using_seed ? ExperimentParameters::seed : (int) time(0)));
}
int Experiment::select_handler(void* data, int argc, char** argv, char** colNames)
{
int id = std::stoi(argv[0]);
double fitness = std::stod(argv[1]);
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->GetID() == id) {
(*it)->SetFitness((ExperimentParameters::novelty_search) ? sparseness(*it) : fitness);
(*it)->SetEvaluated();
if (fitness > top_fitness) {
new_top = true;
top_fitness = fitness;
top_genome_id = id;
top_genome_gen_id = cur_gen;
}
break;
}
}
fitness_sum += std::stod(argv[1]);
airtime_sum += std::stod(argv[2]);
groundtime_sum += std::stod(argv[3]);
jump_sum += std::stoi(argv[4]);
if (std::stod(argv[11]) > 0) num_winner_genomes++;
return 0;
}
int Experiment::select_handler_ns(void* data, int argc, char** argv, char** colNames)
{
int id = std::stoi(argv[0]);
double fitness = std::stod(argv[1]);
for (std::vector<Genome*>::iterator it = genomes.begin(); it != genomes.end(); ++it) {
if ((*it)->GetID() == id) {
for (int i = 5; i < 11; i++) {
(*it)->m_PhenotypeBehavior->m_Data[0][i - 5] = std::stod(argv[i]);
}
if (fitness > top_fitness) {
new_top = true;
top_fitness = fitness;
top_genome_id = id;
top_genome_gen_id = cur_gen;
}
break;
}
}
fitness_sum += std::stod(argv[1]);
airtime_sum += std::stod(argv[2]);
groundtime_sum += std::stod(argv[3]);
jump_sum += std::stoi(argv[4]);
if (std::stod(argv[11]) > 0) num_winner_genomes++;
return 0;
}
void Experiment::parse_commandline_arguments(int argc, char** argv)
{
for (int i = 0; i < argc; i++) {
string arg = argv[i];
if (arg == "--help")
{
print_usage();
exit(0);
}
else if (arg == "--experimentparamfile")
{
if (i + 1 < argc)
{
ExperimentParameters::experimentparam_filename = argv[++i];
}
else
{
std::cout << "Please specify path to experiment parameter file after using --experimentparamfile" << std::endl;
}
}
else if (arg == "--paramfile")
{
if (i + 1 < argc)
{
ExperimentParameters::param_filename = argv[++i];
}
else
{
std::cout << "Please specify path to MultiNEAT parameter file after using --paramfile" << std::endl;
}
}
else if (arg == "--popfile")
{
if (i + 1 < argc)
{
ExperimentParameters::pop_filename = argv[++i];
}
else
{
std::cout << "Please specify path to population file after using --popfile" << std::endl;
}
}
// We'll take seeds as a console argument for convenience,
// i.e. start multiple experiments via shellscript
else if (arg == "--seed")
{
int seed = 0;
if (i + 1 < argc && sscanf(argv[i + 1], "%d", &seed) == 1) {
ExperimentParameters::using_seed = true;
} else {
std::cout << "Please specify a proper seed after '--seed'" << std::endl;
}
}
else if (arg == "--noveltysearch")
{
ExperimentParameters::novelty_search = true;
}
else if (arg == "--hyperneat")
{
ExperimentParameters::hyperneat = true;
}
else if (i > 0 && arg[0] != '-')
{
ExperimentParameters::path_to_level = arg;
}
}
}
Parameters Experiment::init_params()
{
Parameters res;
if (strcmp(ExperimentParameters::param_filename.c_str(), "") != 0) {
res.Load(ExperimentParameters::param_filename.c_str());
}
return res;
}
void Experiment::parse_experiment_parameters()
{
string line, s;
double d;
std::ifstream stream(ExperimentParameters::experimentparam_filename);
while (std::getline(stream, line)) {
stringstream ss;
ss << line;
if (!(ss >> s >> d)) continue;
if (s == "maxgens") ExperimentParameters::max_gens = (int) d;
else if (s == "numcores") ExperimentParameters::num_cores = (int) d;
else if (s == "randseed") {
ExperimentParameters::using_seed = true;
ExperimentParameters::seed = (int) d;
}
else if (s == "autosaveinterval")
if ((int) d == 0) ExperimentParameters::autosave_best = true;
else ExperimentParameters::autosave_interval = (int) d;
else if (s == "numrangesensors") ExperimentParameters::AMOUNT_RANGE_SENSORS = (int) d;
else if (s == "numdepthsensors") ExperimentParameters::AMOUNT_DEPTH_SENSORS = (int) d;
else if (s == "numpiesensors") ExperimentParameters::AMOUNT_PIESLICE_SENSORS = (int) d;
else if (s == "spacingdepthsensors") ExperimentParameters::SPACING_DEPTH_SENSORS = (int) d;
else if (s == "radiuspiesensors") ExperimentParameters::RADIUS_PIESLICE_SENSORS = (int) d;
else if (s == "numhiddenstartneurons") ExperimentParameters::num_hidden_start_neurons = (int) d;
else if (s == "numhiddenstartneuronscppn") ExperimentParameters::num_hidden_start_neurons_cppn = (int) d;
else if (s == "noveltysearch" && (int) d) ExperimentParameters::novelty_search = true;
else if (s == "hyperneat" && (int) d) ExperimentParameters::hyperneat = true;
}
}
void Experiment::save_pop(string filename)
{
mkdir("popfiles", S_IRWXU);
std::stringstream ss = std::stringstream();
ss << "popfiles/";
ss << filename;
pop.Save(ss.str().c_str());
}
void Experiment::fix_filenames()
{
try {
ExperimentParameters::path_to_level = boost::filesystem::canonical(ExperimentParameters::path_to_level).string();
} catch (const std::exception& e) {
std::cerr << "Bad level file specified" << std::endl;
exit(-1);
}
if (strcmp(ExperimentParameters::pop_filename.c_str(), "")) {
try {
ExperimentParameters::pop_filename = boost::filesystem::canonical(ExperimentParameters::pop_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad population file specified" << std::endl;
exit(-1);
}
}
if (strcmp(ExperimentParameters::param_filename.c_str(), "")) {
try {
ExperimentParameters::param_filename = boost::filesystem::canonical(ExperimentParameters::param_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad parameter file specified" << std::endl;
exit(-1);
}
}
if (strcmp(ExperimentParameters::experimentparam_filename.c_str(), "")) {
try {
ExperimentParameters::experimentparam_filename = boost::filesystem::canonical(ExperimentParameters::experimentparam_filename).string();
} catch (const std::exception& e) {
std::cerr << "Bad experiment parameter file specified" << std::endl;
exit(-1);
}
}
}
int Experiment::busy_handler(void *data, int retry)
{
std::cout << "Busy handler";
if (retry < max_db_retry) {
std::cout << ", try #" << retry << std::endl;
sqlite3_sleep(db_sleeptime);
return 1;
} else {
return 0;
}
}
void Experiment::print_usage()
{
stringstream ss;
ss << std::endl;
ss << "====================================================" << std::endl;
ss << "== Help for SuperTux + NEAT experiment executable ==" << std::endl;
ss << "== Available arguments: ==" << std::endl;
ss << "====================================================" << std::endl;
ss << "--paramfile\t\tMultiNEAT parameter file" << std::endl;
ss << "--experimentparamfile\tCustom experiment parameter file. Check README for usage" << std::endl;
ss << std::endl;
ss << "The following arguments can be overriden by the experiment parameter file:" << std::endl;
ss << "--seed\t\t\tSeed for MultiNEAT" << std::endl;
ss << "--noveltysearch\t\tUse Novelty Search instead of objective-based fitness for evolution" << std::endl;
std::cout << ss.str();
} | 30.516129 | 357 | 0.640082 |
875281638813f52013ee2ac0ad9bab0cc0c37e9e | 10,910 | cpp | C++ | src/core/Film.cpp | IDragnev/pbrt | 0eef2a23fb840a73d70c888b4eb2ad5caa278d63 | [
"MIT"
] | null | null | null | src/core/Film.cpp | IDragnev/pbrt | 0eef2a23fb840a73d70c888b4eb2ad5caa278d63 | [
"MIT"
] | null | null | null | src/core/Film.cpp | IDragnev/pbrt | 0eef2a23fb840a73d70c888b4eb2ad5caa278d63 | [
"MIT"
] | null | null | null | #include "pbrt/core/Film.hpp"
#include "pbrt/core/geometry/Utility.hpp"
#include "pbrt/memory/Memory.hpp"
namespace idragnev::pbrt {
Film::Film(const Point2i& resolution,
const Bounds2f& cropWindow,
std::unique_ptr<const Filter> filt,
Float diagonal,
const std::string& filename,
Float scale,
Float maxSampleLuminance)
: fullResolution(resolution)
, diagonal(Float(diagonal * 0.001))
, filter(std::move(filt))
, filename(filename)
// clang-format off
, croppedPixelBounds(Bounds2i(
Point2i(static_cast<int>(std::ceil(fullResolution.x * cropWindow.min.x)),
static_cast<int>(std::ceil(fullResolution.y * cropWindow.min.y))),
Point2i(static_cast<int>(std::ceil(fullResolution.x * cropWindow.max.x)),
static_cast<int>(std::ceil(fullResolution.y * cropWindow.max.y)))))
// clang-format on
, pixels(new Pixel[croppedPixelBounds.area()])
, scale(scale)
, maxSampleLuminance(maxSampleLuminance) {
/*TODO: log resolution, crop window and cropped bounds */
const Float invTableExt = 1.f / static_cast<Float>(FILTER_TABLE_EXTENT);
std::size_t offset = 0;
for (int y = 0; y < FILTER_TABLE_EXTENT; ++y) {
for (int x = 0; x < FILTER_TABLE_EXTENT; ++x) {
// clang-format off
Point2f p;
p.x = (static_cast<Float>(x) + 0.5f) * invTableExt * filter->radius.x;
p.y = (static_cast<Float>(y) + 0.5f) * invTableExt * filter->radius.y;
// clang-format on
filterTable[offset++] = filter->eval(p);
}
}
}
Film::Pixel& Film::getPixel(const Point2i& p) {
assert(insideExclusive(p, croppedPixelBounds));
const int width = croppedPixelBounds.max.x - croppedPixelBounds.min.x;
const int offset = (p.x - croppedPixelBounds.min.x) +
(p.y - croppedPixelBounds.min.y) * width;
return pixels[offset];
}
Bounds2i Film::getSampleBounds() const {
Point2i min(math::floor(Point2f(croppedPixelBounds.min) +
Vector2f(0.5f, 0.5f) - filter->radius));
Point2i max(math::ceil(Point2f(croppedPixelBounds.max) -
Vector2f(0.5f, 0.5f) + filter->radius));
Bounds2i bounds;
bounds.min = min;
bounds.max = max;
return bounds;
}
Bounds2f Film::getPhysicalExtent() const {
const Float aspect = static_cast<Float>(fullResolution.y) /
static_cast<Float>(fullResolution.x);
const Float x =
std::sqrt(diagonal * diagonal / (1.f + aspect * aspect));
const Float y = aspect * x;
return Bounds2f{Point2f(-x / 2.f, -y / 2.f), Point2f(x / 2.f, y / 2.f)};
}
std::unique_ptr<FilmTile> Film::getFilmTile(const Bounds2i& sampleBounds) {
const Bounds2f floatBounds{sampleBounds};
const Point2i p0{
math::ceil(toDiscrete(floatBounds.min) - filter->radius)};
const Point2i p1 =
Point2i{math::floor(toDiscrete(floatBounds.max) + filter->radius)} +
Vector2i(1, 1);
Bounds2i tilePixelBounds =
intersectionOf(Bounds2i(p0, p1), croppedPixelBounds);
return std::unique_ptr<FilmTile>(new FilmTile(
tilePixelBounds,
filter->radius,
std::span<const Float>(filterTable,
FILTER_TABLE_EXTENT * FILTER_TABLE_EXTENT),
FILTER_TABLE_EXTENT,
maxSampleLuminance));
}
void Film::mergeFilmTile(std::unique_ptr<FilmTile> tile) {
// TODO: Log tile->pixelBounds ...
std::lock_guard<std::mutex> lock(mutex);
for (const Point2i pixel : tile->getPixelBounds()) {
const FilmTilePixel& tilePixel = tile->getPixel(pixel);
const std::array<Float, 3> xyz = tilePixel.contribSum.toXYZ();
Pixel& filmPixel = this->getPixel(pixel);
for (std::size_t i = 0; i < 3; ++i) {
filmPixel.xyz[i] += xyz[i];
}
filmPixel.filterWeightSum += tilePixel.filterWeightSum;
}
}
void Film::setImage(const std::span<Spectrum> imagePixels) const {
if (const int filmPixels = croppedPixelBounds.area();
filmPixels == static_cast<int>(imagePixels.size()))
{
const std::size_t nPixels = imagePixels.size();
for (std::size_t i = 0; i < nPixels; ++i) {
const std::array xyz = imagePixels[i].toXYZ();
Pixel& filmPixel = this->pixels[i];
filmPixel.xyz[0] = xyz[0];
filmPixel.xyz[1] = xyz[1];
filmPixel.xyz[2] = xyz[2];
filmPixel.filterWeightSum = 1.f;
filmPixel.splatXYZ[0] = 0.f;
filmPixel.splatXYZ[1] = 0.f;
filmPixel.splatXYZ[2] = 0.f;
}
}
else {
// TODO : Log ...
assert(false);
}
}
void Film::clear() {
for (const Point2i p : croppedPixelBounds) {
Pixel& filmPixel = getPixel(p);
filmPixel.xyz[0] = 0.f;
filmPixel.xyz[1] = 0.f;
filmPixel.xyz[2] = 0.f;
filmPixel.filterWeightSum = 0.f;
filmPixel.splatXYZ[0] = 0.f;
filmPixel.splatXYZ[1] = 0.f;
filmPixel.splatXYZ[2] = 0.f;
}
}
void
FilmTile::addSample(Point2f pFilm, Spectrum L, const Float sampleWeight) {
if (L.y() > maxSampleLuminance) {
L *= maxSampleLuminance / L.y();
}
pFilm = toDiscrete(pFilm);
auto p0 = Point2i{math::ceil(pFilm - filterRadius)};
auto p1 = Point2i{math::floor(pFilm + filterRadius)} + Vector2i(1, 1);
p0 = math::max(p0, pixelBounds.min);
p1 = math::min(p1, pixelBounds.max);
std::size_t* const filterXOffsets =
PBRT_ALLOCA(std::size_t, std::max(p1.x - p0.x, 1));
for (int x = p0.x; x < p1.x; ++x) {
const Float fx = std::abs((x - pFilm.x) * invFilterRadius.x *
static_cast<Float>(filterTableExtent));
filterXOffsets[x - p0.x] =
std::min(static_cast<std::size_t>(std::floor(fx)),
filterTableExtent - 1);
}
std::size_t* const filterYOffsets =
PBRT_ALLOCA(std::size_t, std::max(p1.y - p0.y, 1));
for (int y = p0.y; y < p1.y; ++y) {
const Float fy = std::abs((y - pFilm.y) * invFilterRadius.y *
static_cast<Float>(filterTableExtent));
filterYOffsets[y - p0.y] =
std::min(static_cast<std::size_t>(std::floor(fy)),
filterTableExtent - 1);
}
for (int y = p0.y; y < p1.y; ++y) {
for (int x = p0.x; x < p1.x; ++x) {
std::size_t offset =
filterYOffsets[y - p0.y] * filterTableExtent +
filterXOffsets[x - p0.x];
const Float filterWeight = filterTable[offset];
FilmTilePixel& pixel = getPixel(Point2i(x, y));
pixel.contribSum += L * sampleWeight * filterWeight;
pixel.filterWeightSum += filterWeight;
}
}
}
void Film::addSplat(const Point2f& p, Spectrum v) {
if (v.hasNaNs()) {
// TODO: log nans
return;
}
else if (v.y() < Float(0)) {
// log negative luminace
return;
}
else if (std::isinf(v.y())) {
// log inf luminace
return;
}
const Point2i pi(math::floor(p));
if (insideExclusive(pi, croppedPixelBounds)) {
if (v.y() > maxSampleLuminance) {
v *= maxSampleLuminance / v.y();
}
const std::array xyz = v.toXYZ();
Pixel& pixel = getPixel(pi);
pixel.splatXYZ[0].add(xyz[0]);
pixel.splatXYZ[1].add(xyz[1]);
pixel.splatXYZ[2].add(xyz[2]);
}
}
void Film::writeImage(const Float splatScale) {
// TODO: Log info: "Converting image to RGB and computing final weighted pixel values..."
const int nPixels = croppedPixelBounds.area();
std::unique_ptr<Float[]> imageRGB(new Float[3 * nPixels]);
for (std::size_t pixelIndex = 0; const Point2i p : croppedPixelBounds) {
const std::span<Float, 3> pixelRGB{&(imageRGB[3 * pixelIndex]), 3};
Pixel& pixel = getPixel(p);
const std::array arrRGB =
XYZToRGB(std::span<const Float, 3>{pixel.xyz});
pixelRGB[0] = arrRGB[0];
pixelRGB[1] = arrRGB[1];
pixelRGB[2] = arrRGB[2];
// normalize pixel with weight sum
if (pixel.filterWeightSum != 0.f) {
const Float invWt = Float(1) / pixel.filterWeightSum;
pixelRGB[0] = std::max(Float(0), pixelRGB[0] * invWt);
pixelRGB[1] = std::max(Float(0), pixelRGB[1] * invWt);
pixelRGB[2] = std::max(Float(0), pixelRGB[2] * invWt);
}
const Float splatXYZ[3] = {pixel.splatXYZ[0],
pixel.splatXYZ[1],
pixel.splatXYZ[2]};
const std::array splatRGB = XYZToRGB(splatXYZ);
pixelRGB[0] += splatScale * splatRGB[0];
pixelRGB[1] += splatScale * splatRGB[1];
pixelRGB[2] += splatScale * splatRGB[2];
pixelRGB[0] *= scale;
pixelRGB[1] *= scale;
pixelRGB[2] *= scale;
++pixelIndex;
}
// TODO: log_info("Writing image to {}. bounds = {}, scale = {}, splatScale = {}",
// filename, croppedPixelBounds, scale, splatScale)
// pbrt::writeImage(filename, &imageRGB[0], croppedPixelBounds, fullResolution);
}
FilmTilePixel& FilmTile::getPixel(const Point2i& p) {
assert(insideExclusive(p, pixelBounds));
int width = pixelBounds.max.x - pixelBounds.min.x;
int offset = (p.y - pixelBounds.min.y) * width +
(p.x - pixelBounds.min.x);
return pixels[offset];
}
const FilmTilePixel& FilmTile::getPixel(const Point2i& p) const {
assert(insideExclusive(p, pixelBounds));
int width = pixelBounds.max.x - pixelBounds.min.x;
int offset = (p.y - pixelBounds.min.y) * width +
(p.x - pixelBounds.min.x);
return pixels[offset];
}
} // namespace idragnev::pbrt | 36.366667 | 97 | 0.528323 |
875325064a37bb256fef9507b5a7598a2bfe6fe6 | 2,824 | cc | C++ | UX/src/LogView.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | null | null | null | UX/src/LogView.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | null | null | null | UX/src/LogView.cc | frankencode/CoreComponents | 4c66d7ff9fc5be19222906ba89ba0e98951179de | [
"Zlib"
] | null | null | null | /*
* Copyright (C) 2022 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/LogView>
#include <cc/Text>
#include <cc/LineSource>
#include <cc/Format>
namespace cc {
struct LogView::State final: public ListView::State
{
State()
{
font([this]{ return style().defaultFont(); });
margin([this]{
double m = style().flickableIndicatorThickness();
return Size{m, m};
});
leadSpace([this]{ return margin()[1]; });
tailSpace([this]{ return margin()[1]; });
font.onChanged([this]{ reload(); });
}
void reload()
{
ListView::State::deplete();
for (const String &line: lines_) {
appendLine(line);
}
}
void appendText(const String &text)
{
bool carrierAtEnd =
carrier().height() <= height() ||
carrier().pos()[1] <= height() - carrier().height() + sp(42);
for (const String &line: LineSource{text}) {
appendLine(line);
}
if (carrierAtEnd && height() < carrier().height()) {
if (carrier().moving()) carrierStop();
carrier().pos(Point{0, height() - carrier().height()});
}
}
void appendLine(const String &line)
{
carrier().add(
Text{line, font()}
.margin([this]{ return Size{margin()[0], 0}; })
.maxWidth([this]{ return width(); })
);
}
void clearText()
{
ListView::State::deplete();
lines_.deplete();
}
Property<Font> font;
Property<Size> margin;
List<String> lines_;
};
LogView::LogView():
ListView{onDemand<State>}
{}
LogView::LogView(double width, double height):
ListView{new State}
{
size(width, height);
}
LogView &LogView::associate(Out<LogView> self)
{
return View::associate<LogView>(self);
}
Font LogView::font() const
{
return me().font();
}
LogView &LogView::font(Font newValue)
{
me().font(newValue);
return *this;
}
LogView &LogView::font(Definition<Font> &&f)
{
me().font(move(f));
return *this;
}
Size LogView::margin() const
{
return me().margin();
}
LogView &LogView::margin(Size newValue)
{
me().margin(newValue);
return *this;
}
LogView &LogView::margin(Definition<Size> &&f)
{
me().margin(move(f));
return *this;
}
LogView &LogView::appendText(const String &text)
{
me().appendText(text);
return *this;
}
void LogView::clearText()
{
me().clearText();
}
List<String> LogView::textLines() const
{
return me().lines_;
}
LogView::State &LogView::me()
{
return Object::me.as<State>();
}
const LogView::State &LogView::me() const
{
return Object::me.as<State>();
}
} // namespace cc
| 18.337662 | 73 | 0.56551 |
8755e97bf465d7b049f60568f861e6be78a58164 | 5,944 | cc | C++ | src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_bus.h"
#include <zircon/errors.h>
#include <algorithm>
#include <string>
#include <ddk/metadata.h>
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/core.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/debug.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/device.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/firmware.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_buscore.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/pcie/pcie_firmware.h"
namespace wlan {
namespace brcmfmac {
PcieBus::PcieBus() = default;
PcieBus::~PcieBus() {
if (device_ != nullptr) {
if (device_->drvr()->settings == brcmf_mp_device_.get()) {
device_->drvr()->settings = nullptr;
}
if (device_->drvr()->bus_if == brcmf_bus_.get()) {
device_->drvr()->bus_if = nullptr;
}
device_ = nullptr;
}
}
// static
zx_status_t PcieBus::Create(Device* device, std::unique_ptr<PcieBus>* bus_out) {
zx_status_t status = ZX_OK;
auto pcie_bus = std::make_unique<PcieBus>();
std::unique_ptr<PcieBuscore> pcie_buscore;
if ((status = PcieBuscore::Create(device->parent(), &pcie_buscore)) != ZX_OK) {
return status;
}
std::unique_ptr<PcieFirmware> pcie_firmware;
if ((status = PcieFirmware::Create(device, pcie_buscore.get(), &pcie_firmware)) != ZX_OK) {
return status;
}
auto bus = std::make_unique<brcmf_bus>();
bus->bus_priv.pcie = pcie_bus.get();
bus->ops = PcieBus::GetBusOps();
auto mp_device = std::make_unique<brcmf_mp_device>();
brcmf_get_module_param(brcmf_bus_type::BRCMF_BUS_TYPE_PCIE, pcie_buscore->chip()->chip,
pcie_buscore->chip()->chiprev, mp_device.get());
device->drvr()->bus_if = bus.get();
device->drvr()->settings = mp_device.get();
pcie_bus->device_ = device;
pcie_bus->pcie_buscore_ = std::move(pcie_buscore);
pcie_bus->pcie_firmware_ = std::move(pcie_firmware);
pcie_bus->brcmf_bus_ = std::move(bus);
pcie_bus->brcmf_mp_device_ = std::move(mp_device);
*bus_out = std::move(pcie_bus);
return ZX_OK;
}
// static
const brcmf_bus_ops* PcieBus::GetBusOps() {
static constexpr brcmf_bus_ops bus_ops = {
.get_bus_type = []() { return PcieBus::GetBusType(); },
.stop = [](brcmf_bus* bus) { return bus->bus_priv.pcie->Stop(); },
.txdata = [](brcmf_bus* bus,
brcmf_netbuf* netbuf) { return bus->bus_priv.pcie->TxData(netbuf); },
.txctl = [](brcmf_bus* bus, unsigned char* msg,
uint len) { return bus->bus_priv.pcie->TxCtl(msg, len); },
.rxctl = [](brcmf_bus* bus, unsigned char* msg, uint len,
int* rxlen_out) { return bus->bus_priv.pcie->RxCtl(msg, len, rxlen_out); },
.wowl_config = [](brcmf_bus* bus,
bool enabled) { return bus->bus_priv.pcie->WowlConfig(enabled); },
.get_ramsize = [](brcmf_bus* bus) { return bus->bus_priv.pcie->GetRamsize(); },
.get_memdump = [](brcmf_bus* bus, void* data,
size_t len) { return bus->bus_priv.pcie->GetMemdump(data, len); },
.get_fwname =
[](brcmf_bus* bus, uint chip, uint chiprev, unsigned char* fw_name,
size_t* fw_name_size) {
return bus->bus_priv.pcie->GetFwname(chip, chiprev, fw_name, fw_name_size);
},
.get_bootloader_macaddr =
[](brcmf_bus* bus, uint8_t* mac_addr) {
return bus->bus_priv.pcie->GetBootloaderMacaddr(mac_addr);
},
.get_wifi_metadata =
[](brcmf_bus* bus, void* config, size_t exp_size, size_t* actual) {
return bus->bus_priv.pcie->GetWifiMetadata(config, exp_size, actual);
},
};
return &bus_ops;
}
// static
brcmf_bus_type PcieBus::GetBusType() { return BRCMF_BUS_TYPE_PCIE; }
void PcieBus::Stop() {}
zx_status_t PcieBus::TxData(brcmf_netbuf* netbuf) { return ZX_OK; }
zx_status_t PcieBus::TxCtl(unsigned char* msg, uint len) { return ZX_OK; }
zx_status_t PcieBus::RxCtl(unsigned char* msg, uint len, int* rxlen_out) {
if (rxlen_out != nullptr) {
*rxlen_out = 0;
}
return ZX_OK;
}
void PcieBus::WowlConfig(bool enabled) { BRCMF_ERR("PcieBus::WowlConfig unimplemented\n"); }
size_t PcieBus::GetRamsize() {
return pcie_buscore_->chip()->ramsize - pcie_buscore_->chip()->srsize;
}
zx_status_t PcieBus::GetMemdump(void* data, size_t len) {
pcie_buscore_->RamRead(0, data, len);
return ZX_OK;
}
zx_status_t PcieBus::GetFwname(uint chip, uint chiprev, unsigned char* fw_name,
size_t* fw_name_size) {
zx_status_t status = ZX_OK;
if (fw_name == nullptr || fw_name_size == nullptr || *fw_name_size == 0) {
return ZX_ERR_INVALID_ARGS;
}
std::string_view firmware_name;
if ((status = GetFirmwareName(brcmf_bus_type::BRCMF_BUS_TYPE_PCIE, pcie_buscore_->chip()->chip,
pcie_buscore_->chip()->chiprev, &firmware_name)) != ZX_OK) {
return status;
}
// Almost, but not quite, entirely unlike strlcpy().
const size_t copy_size = std::min<size_t>(*fw_name_size - 1, firmware_name.size());
std::copy(firmware_name.begin(), firmware_name.begin() + copy_size, fw_name);
fw_name[copy_size] = '\0';
return ZX_OK;
}
zx_status_t PcieBus::GetBootloaderMacaddr(uint8_t* mac_addr) {
BRCMF_ERR("PcieBus::GetBootloaderMacaddr unimplemented\n");
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t PcieBus::GetWifiMetadata(void* config, size_t exp_size, size_t* actual) {
return device_->DeviceGetMetadata(DEVICE_METADATA_WIFI_CONFIG, config, exp_size, actual);
}
} // namespace brcmfmac
} // namespace wlan
| 36.024242 | 100 | 0.677995 |
875bdcc9c2e25b38fd819a6bff10e7a0970c52a1 | 10,674 | cpp | C++ | src/libc9/loader.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | 1 | 2015-02-13T02:03:29.000Z | 2015-02-13T02:03:29.000Z | src/libc9/loader.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | src/libc9/loader.cpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | #include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "json/json.h"
#include "json/reader.h"
#include "c9/loader.hpp"
#include "c9/script.hpp"
#include "c9/istream.hpp"
#include "c9/variable_frame.hpp"
#include "c9/context.hpp"
namespace Channel9
{
class NothingChannel : public CallableContext
{
public:
NothingChannel(){}
~NothingChannel(){}
void send(Environment *env, const Value &val, const Value &ret)
{
}
std::string inspect() const
{
return "Nothing Channel";
}
};
NothingChannel *nothing_channel = new NothingChannel;
template <typename tRight>
loader_error operator<<(const loader_error &left, const tRight &right)
{
std::stringstream stream;
stream << left.reason;
stream << right;
return loader_error(stream.str());
}
Value convert_json(const Json::Value &val);
Value convert_json_array(const Json::Value &arr)
{
std::vector<Value> vals(arr.size());
std::vector<Value>::iterator oiter = vals.begin();
Json::Value::const_iterator iiter = arr.begin();
while (iiter != arr.end())
*oiter++ = convert_json(*iiter++);
return value(new_tuple(vals.begin(), vals.end()));
}
Value convert_json_complex(const Json::Value &obj)
{
if (!obj["undef"].isNull())
{
return Undef;
} else if (obj["message_id"].isString()) {
return value((int64_t)make_message_id(obj["message_id"].asString()));
} else if (obj["protocol_id"].isString()) {
return value((int64_t)make_protocol_id(obj["protocol_id"].asString()));
}
throw loader_error("Unknown complex object ") << obj.toStyledString();
}
Value convert_json(const Json::Value &val)
{
using namespace Json;
switch (val.type())
{
case nullValue:
return Nil;
case intValue:
return value(val.asInt64());
case uintValue:
return value((int64_t)val.asUInt64());
case realValue:
return value(val.asDouble());
case stringValue:
return value(val.asString());
case booleanValue:
return bvalue(val.asBool());
case arrayValue:
return convert_json_array(val);
case objectValue:
return convert_json_complex(val);
default:
throw loader_error("Invalid value encountered while parsing json");
}
}
GCRef<RunnableContext*> load_program(Environment *env, const Json::Value &code)
{
using namespace Channel9;
GCRef<IStream*> istream = new IStream;
int num = 0;
for (Json::Value::const_iterator it = code.begin(); it != code.end(); it++, num++)
{
const Json::Value &line = *it;
if (!line.isArray() || line.size() < 1)
{
throw loader_error("Malformed line ") << num << ": not an array or not enough elements";
}
const Json::Value &ival = line[0];
if (!ival.isString())
{
throw loader_error("Instruction on line ") << num << " was not a string (" << ival.toStyledString() << ")";
}
const std::string &instruction = ival.asString();
if (instruction == "line")
{
if (line.size() > 1)
{
std::string file = "(unknown)", extra;
uint64_t lineno = 0, linepos = 0;
file = line[1].asString();
if (line.size() > 2)
lineno = line[2].asUInt64();
if (line.size() > 3)
linepos = line[3].asUInt64();
if (line.size() > 4)
extra = line[4].asString();
(*istream)->set_source_pos(SourcePos(file, lineno, linepos, extra));
}
} else if (instruction == "set_label") {
if (line.size() != 2 || !line[1].isString())
{
throw loader_error("Invalid set_label line at ") << num;
}
(*istream)->set_label(line[1].asString());
} else {
INUM insnum = inum(instruction);
if (insnum == INUM_INVALID)
{
throw loader_error("Invalid instruction ") << instruction << " at " << num;
}
Instruction ins = {insnum};
InstructionInfo info = iinfo(ins);
if (line.size() - 1 < info.argc)
{
throw loader_error("Instruction ") << instruction << " takes "
<< info.argc << "arguments, but was given " << line.size() - 1
<< " at line " << num;
}
if (info.argc > 0)
ins.arg1 = convert_json(line[1]);
if (info.argc > 1)
ins.arg2 = convert_json(line[2]);
if (info.argc > 2)
ins.arg3 = convert_json(line[3]);
(*istream)->add(ins);
}
}
(*istream)->normalize();
GCRef<VariableFrame*> frame = new_variable_frame(*istream);
GCRef<RunnableContext*> ctx = new_context(*istream, *frame);
return ctx;
}
GCRef<RunnableContext*> load_bytecode(Environment *env, const std::string &filename)
{
std::ifstream file(filename.c_str());
if (file.is_open())
{
Json::Reader reader;
Json::Value body;
if (reader.parse(file, body, false))
{
Json::Value code = body["code"];
if (!code.isArray())
{
throw loader_error("No code block in ") << filename;
}
return load_program(env, code);
} else {
throw loader_error("Failed to parse json in ") << filename << ":\n"
<< reader.getFormattedErrorMessages();
}
} else {
throw loader_error("Could not open file ") << filename;
}
}
GCRef<RunnableContext*> load_bytecode(Environment *env, const std::string &filename, const std::string &str)
{
Json::Reader reader;
Json::Value body;
if (reader.parse(str, body, false))
{
Json::Value code = body["code"];
if (!code.isArray())
{
throw loader_error("No code block in ") << filename;
}
return load_program(env, code);
} else {
throw loader_error("Failed to parse json in ") << filename << ":\n"
<< reader.getFormattedErrorMessages();
}
}
int run_bytecode(Environment *env, const std::string &filename)
{
GCRef<RunnableContext*> ctx = load_bytecode(env, filename);
channel_send(env, value(*ctx), Nil, value(nothing_channel));
return 0;
}
GCRef<RunnableContext*> load_c9script(Environment *env, const std::string &filename)
{
GCRef<IStream*> istream = new IStream;
script::compile_file(filename, **istream);
(*istream)->normalize();
GCRef<VariableFrame*> frame = new_variable_frame(*istream);
GCRef<RunnableContext*> ctx = new_context(*istream, *frame);
return ctx;
}
int run_c9script(Environment *env, const std::string &filename)
{
GCRef<RunnableContext*> ctx = load_c9script(env, filename);
channel_send(env, value(*ctx), Nil, value(nothing_channel));
return 0;
}
int run_list(Environment *env, const std::string &filename)
{
std::ifstream file(filename.c_str());
if (file.is_open())
{
while (!file.eof())
{
std::string line;
std::getline(file, line);
if (line.size() > 0)
{
if (line[0] != '/')
{
// if the path is not absolute it's relative
// to the c9l file.
size_t last_slash_pos = filename.rfind('/');
if (last_slash_pos == std::string::npos)
run_file(env, line);
else
run_file(env, filename.substr(0, last_slash_pos+1) + line);
}
} else {
break;
}
}
return 0;
} else {
throw loader_error("Could not open file ") << filename << ".";
}
}
typedef int (*entry_point)(Environment*, const std::string&);
int run_shared_object(Environment *env, std::string filename)
{
#ifdef __APPLE__
// on macs change the .so to .dylib
filename.replace(filename.length()-3, std::string::npos, ".dylib");
#endif
void *shobj = dlopen(filename.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!shobj)
{
throw loader_error("Could not load shared object ") << filename;
}
entry_point shobj_entry = (entry_point)dlsym(shobj, "Channel9_environment_initialize");
if (!shobj_entry)
{
throw loader_error("Could not load entry point to shared object ") << filename;
}
return shobj_entry(env, filename);
}
void set_argv(Environment *env, int argc, const char **argv)
{
std::vector<Channel9::Value> args;
for (int i = 0; i < argc; i++)
{
args.push_back(Channel9::value(Channel9::new_string(argv[i])));
}
env->set_special_channel("argv", Channel9::value(Channel9::new_tuple(args.begin(), args.end())));
}
int load_environment_and_run(Environment *env, std::string program, int argc, const char **argv, bool trace_loaded)
{
// let the program invocation override the filename (ie. c9.rb always runs ruby)
// but if the exe doesn't match the exact expectation, use the first argument's
// extension to decide what to do.
size_t slash_pos = program.rfind('/');
if (slash_pos != std::string::npos)
program = program.substr(slash_pos + 1, std::string::npos);
if (program.length() < 3 || !std::equal(program.begin(), program.begin()+3, "c9."))
{
if (argc < 1)
throw loader_error("No program file specified.");
program = argv[0];
}
std::string ext = "";
size_t ext_pos = program.rfind('.');
if (ext_pos != std::string::npos)
ext = program.substr(ext_pos);
if (ext == "")
throw loader_error("Can't discover environment for file with no extension.");
if (ext == ".c9s" || ext == ".c9b" || ext == ".c9l" || ext == ".so")
{
// chop off the c9x file so it doesn't try to load itself.
set_argv(env, argc-1, argv+1);
return run_file(env, program);
} else {
// get the path of libc9.so. We expect c9 environments to be near it.
// They'll be at dirname(libc9.so)/c9-env/ext/ext.c9l.
Dl_info fninfo;
dladdr((void*)load_environment_and_run, &fninfo);
std::string search_path = std::string(fninfo.dli_fname);
search_path = search_path.substr(0, search_path.find_last_of('/') + 1);
search_path += "c9-env/";
std::string extname = ext.substr(1, std::string::npos);
search_path += extname + "/" + extname + ".c9l";
// find a matching module
struct stat match = {0};
if (stat(search_path.c_str(), &match) != 0)
throw loader_error("Could not find c9-env loader at ") << search_path;
// include the program name argument so it knows what to load.
set_argv(env, argc, argv);
env->set_special_channel("trace_loaded", bvalue(trace_loaded));
return run_file(env, search_path);
}
return 1;
}
int run_file(Environment *env, const std::string &filename)
{
// find the extension
std::string ext = "";
size_t ext_pos = filename.rfind('.');
if (ext_pos != std::string::npos)
ext = filename.substr(ext_pos);
if (ext == ".c9s")
{
return run_c9script(env, filename);
} else if (ext == ".c9b")
{
return run_bytecode(env, filename);
} else if (ext == ".c9l") {
return run_list(env, filename);
} else if (ext == ".so") {
return run_shared_object(env, filename);
} else if (ext == "") {
throw loader_error("Don't know what to do with no extension.");
} else {
throw loader_error("Don't know what to do with extension `") << ext << "`";
}
}
}
| 28.089474 | 116 | 0.643152 |
875d513837ce2208a4dbad201f5696b50d67f6b7 | 2,279 | hpp | C++ | library/L1_Peripheral/lpc17xx/i2c.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | 1 | 2020-02-22T20:26:41.000Z | 2020-02-22T20:26:41.000Z | library/L1_Peripheral/lpc17xx/i2c.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | null | null | null | library/L1_Peripheral/lpc17xx/i2c.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | 4 | 2019-10-17T03:42:03.000Z | 2020-05-23T20:32:03.000Z | #pragma once
#include "L1_Peripheral/lpc17xx/pin.hpp"
#include "L1_Peripheral/lpc17xx/system_controller.hpp"
#include "L1_Peripheral/lpc40xx/i2c.hpp"
namespace sjsu
{
namespace lpc17xx
{
// Bring in and using the LPC40xx driver as it is compatible with the lpc17xx
// peripheral.
using ::sjsu::lpc40xx::I2c;
/// Structure used as a namespace for predefined I2C Bus definitions.
struct I2cBus // NOLINT
{
private:
inline static lpc17xx::Pin i2c0_sda_pin = lpc17xx::Pin(0, 27);
inline static lpc17xx::Pin i2c0_scl_pin = lpc17xx::Pin(0, 28);
inline static lpc17xx::Pin i2c1_sda_pin = lpc17xx::Pin(0, 0);
inline static lpc17xx::Pin i2c1_scl_pin = lpc17xx::Pin(0, 1);
inline static lpc17xx::Pin i2c2_sda_pin = lpc17xx::Pin(0, 10);
inline static lpc17xx::Pin i2c2_scl_pin = lpc17xx::Pin(0, 11);
inline static I2c::Transaction_t transaction_i2c0;
inline static I2c::Transaction_t transaction_i2c1;
inline static I2c::Transaction_t transaction_i2c2;
public:
// Definition for I2C bus 0 for LPC17xx.
/// NOTE: I2C0 is not available for the 80-pin package.
inline static const lpc40xx::I2c::Bus_t kI2c0 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C0),
.id = SystemController::Peripherals::kI2c0,
.irq_number = I2C0_IRQn,
.transaction = transaction_i2c0,
.sda_pin = i2c0_sda_pin,
.scl_pin = i2c0_scl_pin,
.pin_function = 0b01,
};
/// Definition for I2C bus 1 for LPC17xx.
inline static const lpc40xx::I2c::Bus_t kI2c1 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C1),
.id = SystemController::Peripherals::kI2c1,
.irq_number = I2C1_IRQn,
.transaction = transaction_i2c1,
.sda_pin = i2c1_sda_pin,
.scl_pin = i2c1_scl_pin,
.pin_function = 0b11,
};
/// Definition for I2C bus 2 for LPC17xx.
inline static const lpc40xx::I2c::Bus_t kI2c2 = {
.registers = reinterpret_cast<lpc40xx::LPC_I2C_TypeDef *>(LPC_I2C2),
.id = SystemController::Peripherals::kI2c2,
.irq_number = I2C2_IRQn,
.transaction = transaction_i2c2,
.sda_pin = i2c2_sda_pin,
.scl_pin = i2c2_scl_pin,
.pin_function = 0b10,
};
};
} // namespace lpc17xx
} // namespace sjsu
| 33.028986 | 77 | 0.69197 |
876034cd377244f6c74963ed63ac430e03463d8b | 477 | cpp | C++ | src/exchange/offer.cpp | cvauclair/marketsim | 3ce669716a7c061fe05a6e4765c07808f4a89138 | [
"MIT"
] | null | null | null | src/exchange/offer.cpp | cvauclair/marketsim | 3ce669716a7c061fe05a6e4765c07808f4a89138 | [
"MIT"
] | 1 | 2021-02-10T14:12:34.000Z | 2021-02-10T22:42:57.000Z | src/exchange/offer.cpp | cvauclair/marketsim | 3ce669716a7c061fe05a6e4765c07808f4a89138 | [
"MIT"
] | null | null | null | #include "offer.h"
unsigned int Offer::offerCounter = 0;
Offer::Offer(OfferType type, const std::string &symbol, unsigned int quantity, float price, unsigned int accountId)
{
this->offerId = ++offerCounter;
this->symbol_ = symbol;
this->quantity = quantity;
this->price = Offer::round(price);
this->accountId_ = accountId;
this->status_ = Offer::PENDING;
this->type_ = type;
}
float Offer::round(float price)
{
return std::floor(1000.0f * price + 0.5f)/1000.0f;
}
| 21.681818 | 115 | 0.704403 |
8761aee44c3de02b1b13cbb08869509837aaaf6d | 435 | hpp | C++ | Quasar/src/Quasar/Renderer/Camera.hpp | rvillegasm/Quasar | 69a3e518030b52502bd1bf700cd6a44dc104d697 | [
"Apache-2.0"
] | null | null | null | Quasar/src/Quasar/Renderer/Camera.hpp | rvillegasm/Quasar | 69a3e518030b52502bd1bf700cd6a44dc104d697 | [
"Apache-2.0"
] | null | null | null | Quasar/src/Quasar/Renderer/Camera.hpp | rvillegasm/Quasar | 69a3e518030b52502bd1bf700cd6a44dc104d697 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
namespace Quasar
{
class Camera
{
protected:
glm::mat4 m_Projection = glm::mat4(1.0f);
public:
Camera() = default;
Camera(const glm::mat4 &projection)
: m_Projection(projection)
{
}
virtual ~Camera() = default;
const glm::mat4 &getProjection() const { return m_Projection; }
};
} // namespace Quasar
| 16.730769 | 71 | 0.556322 |
876250b484f53bcb46a7ba99c24475a765debd41 | 6,897 | cpp | C++ | data/haptic_teleoperation/src/robotteleop_keyboard.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/haptic_teleoperation/src/robotteleop_keyboard.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/haptic_teleoperation/src/robotteleop_keyboard.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <std_msgs/Bool.h>
#include <signal.h>
#include <termios.h>
#include <stdio.h>
#include "boost/thread/mutex.hpp"
#include "boost/thread/thread.hpp"
#include <geometry_msgs/PoseStamped.h>
#include <tf/transform_broadcaster.h>
#include <Eigen/Eigen>
#define KEYCODE_R 0x43
#define KEYCODE_L 0x44
#define KEYCODE_U 0x41
#define KEYCODE_D 0x42
#define KEYCODE_Q 0x71
class RobotTeleop
{
public:
RobotTeleop();
void keyLoop();
void watchdog();
private:
ros::NodeHandle nh_,ph_;
double linear_x, linear_y, angular_z ;
ros::Time first_publish_;
ros::Time last_publish_;
double l_scale_, a_scale_;
ros::Publisher vel_pub_;
ros::Subscriber pose_sub_, collision_flag ;
double robot_ox;
double robot_oz;
double robot_oy;
void publish(double, double, double);
void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg);
double roll, pitch, yaw;
boost::mutex publish_mutex_;
// bool inCollision ;
};
RobotTeleop::RobotTeleop():
ph_("~"),
linear_x(0),
linear_y(0),
angular_z(0),
l_scale_(1.0),
a_scale_(1.0)
{
ph_.param("scale_angular", a_scale_, a_scale_);
ph_.param("scale_linear", l_scale_, l_scale_);
vel_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("/uav/cmd_vel", 1);
pose_sub_ = nh_.subscribe("/mavros/vision_pose/pose" ,1, &RobotTeleop::poseCallback, this );
// collision_flag = nh_.subscribe<std_msgs::Bool>("/collision_flag" , 1, &SlaveController::get_inCollision , this);
}
void RobotTeleop::poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
tf::Quaternion q( msg->pose.orientation.x,msg->pose.orientation.y,msg->pose.orientation.z,msg->pose.orientation.w);
tf::Matrix3x3(q).getRPY(roll, pitch, yaw);
std::cout << "pitch" << pitch << std::endl ;
std::cout << "roll" << roll << std::endl ;
std::cout << "yaw" << yaw << std::endl ;
std::cout << "yaw in degrees: " << yaw * 180 / 3.14 << std::endl ;
}
int kfd = 0;
struct termios cooked, raw;
void quit(int sig)
{
tcsetattr(kfd, TCSANOW, &cooked);
ros::shutdown();
exit(0);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "turtlebot_teleop");
RobotTeleop turtlebot_teleop;
ros::NodeHandle n;
signal(SIGINT,quit);
boost::thread my_thread(boost::bind(&RobotTeleop::keyLoop, &turtlebot_teleop));
ros::Timer timer = n.createTimer(ros::Duration(10.0), boost::bind(&RobotTeleop::watchdog, &turtlebot_teleop));
ros::spin();
my_thread.interrupt() ;
my_thread.join() ;
return(0);
}
void RobotTeleop::watchdog()
{
boost::mutex::scoped_lock lock(publish_mutex_);
if ((ros::Time::now() > last_publish_ + ros::Duration(10.0)) &&
(ros::Time::now() > first_publish_ + ros::Duration(10.0)))
publish(0, 0, 0);
}
void RobotTeleop::keyLoop()
{
char c;
// get the console in raw mode
tcgetattr(kfd, &cooked);
memcpy(&raw, &cooked, sizeof(struct termios));
raw.c_lflag &=~ (ICANON | ECHO);
// Setting a new line, then end of file
raw.c_cc[VEOL] = 1;
raw.c_cc[VEOF] = 2;
tcsetattr(kfd, TCSANOW, &raw);
puts("Reading from keyboard");
puts("---------------------------");
puts("Use arrow keys to move the quadrotor.");
while (ros::ok())
{
// get the next event from the keyboard
if(read(kfd, &c, 1) < 0)
{
perror("read():");
exit(-1);
}
linear_x=linear_y=0;
ROS_DEBUG("value: 0x%02X\n", c);
switch(c)
{
case KEYCODE_L:
ROS_DEBUG("LEFT");
angular_z = 0.0;
linear_x = 0.0;
linear_y = 0.1;
break;
case KEYCODE_R:
ROS_DEBUG("RIGHT");
angular_z = 0.0;
linear_x = 0.0;
linear_y = -0.1;
break;
case KEYCODE_U:
ROS_DEBUG("UP");
linear_y = 0.0;
angular_z = 0.0;
linear_x = 0.1;
break;
case KEYCODE_D:
ROS_DEBUG("DOWN");
linear_x = -0.1;
linear_y = 0.0;
angular_z = 0.0;
break;
case KEYCODE_Q:
ROS_DEBUG("Emergancy");
linear_x = 0.0;
linear_y = 0.0;
angular_z = 0.0;
break;
}
boost::mutex::scoped_lock lock(publish_mutex_);
if (ros::Time::now() > last_publish_ + ros::Duration(1.0)) {
first_publish_ = ros::Time::now();
}
last_publish_ = ros::Time::now();
publish(linear_y, linear_x, angular_z);
}
return;
}
void RobotTeleop::publish(double linear_y, double linear_x , double angular_z)
{
geometry_msgs::TwistStamped vel;
vel.twist.linear.x = linear_x*cos(yaw ) - linear_y * sin(yaw) ;
vel.twist.linear.y = linear_x*sin (yaw) + linear_y * cos(yaw) ;
std::cout << "vel.twist.linear.x" << vel.twist.linear.x << std::endl ;
std::cout << "vel.twist.linear.y" << vel.twist.linear.y<< std::endl ;
vel.twist.angular.z = angular_z;
vel_pub_.publish(vel);
return;
}
| 29.101266 | 119 | 0.627954 |
87688dec8b9c4eeed4df313af29a91625230542b | 5,642 | cpp | C++ | cpp/Combinatorial-search/TSP-branch-and-bound.cpp | fossabot/a-grim-loth | a6c8d549289a39ec981c1e0d0c754bb2708dfff9 | [
"MIT"
] | 4 | 2021-06-26T17:18:47.000Z | 2022-02-02T15:02:27.000Z | cpp/Combinatorial-search/TSP-branch-and-bound.cpp | fossabot/a-grim-loth | a6c8d549289a39ec981c1e0d0c754bb2708dfff9 | [
"MIT"
] | 8 | 2021-06-29T07:00:32.000Z | 2021-12-01T11:26:22.000Z | cpp/Combinatorial-search/TSP-branch-and-bound.cpp | fossabot/a-grim-loth | a6c8d549289a39ec981c1e0d0c754bb2708dfff9 | [
"MIT"
] | 3 | 2021-07-14T14:42:08.000Z | 2021-12-07T19:36:53.000Z | /**
* @file travelling-salesman-problem.cpp
* @author prakash (prakashsellathurai@gmail.com)
* @brief travelling-salesman-problem using branch and bound
* @version 0.1
* @date 2021-08-01
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class TSP {
public:
int n;
int final_res = INT_MAX;
vector<int> final_path;
vector<bool> visited;
vector<vector<int>> graph;
TSP(vector<vector<int>> input_, int n_) {
graph = input_;
n = n_;
visited.resize(n, false);
final_path.resize(n + 1, 0);
}
// implement travelling salesman problem
void solve(int p) {
int curr_path[n + 1];
// Calculate initial lower bound for the root node
// using the formula 1/2 * (sum of first min +
// second min) for all edges.
// Also initialize the curr_path and visited array
int curr_bound = 0;
memset(curr_path, -1, sizeof(curr_path));
visited.resize(sizeof(curr_path), false);
// Compute initial bound
for (int i = 0; i < n; i++)
curr_bound += (firstMin(graph, i) + secondMin(graph, i));
// Rounding off the lower bound to an integer
curr_bound = (curr_bound & 1) ? curr_bound / 2 + 1 : curr_bound / 2;
// We start at vertex 1 so the first vertex
// in curr_path[] is 0
visited[0] = true;
curr_path[0] = 0;
TSP_Recursive(graph, curr_bound, 0, 1, curr_path);
}
// function that takes as arguments:
// curr_bound -> lower bound of the root node
// curr_weight-> stores the weight of the path so far
// level-> current level while moving in the search
// space tree
// curr_path[] -> where the solution is being stored which
// would later be copied to final_path[]
void TSP_Recursive(vector<vector<int>> adj, int curr_bound, int curr_weight,
int level, int curr_path[]) {
// base case is when we have reached level N which
// means we have covered all the nodes once
if (level == n) {
// check if there is an edge from last vertex in
// path back to the first vertex
if (adj[curr_path[level - 1]][curr_path[0]] != 0) {
// curr_res has the total weight of the
// solution we got
int curr_res = curr_weight + adj[curr_path[level - 1]][curr_path[0]];
// Update final result and final path if
// current result is better.
if (curr_res < final_res) {
copyToFinal(curr_path);
final_res = curr_res;
}
}
return;
}
// for any other level iterate for all vertices to
// build the search space tree recursively
for (int i = 0; i < n; i++) {
// Consider next vertex if it is not same (diagonal
// entry in adjacency matrix and not visited
// already)
if (adj[curr_path[level - 1]][i] != 0 && visited[i] == false) {
int temp = curr_bound;
curr_weight += adj[curr_path[level - 1]][i];
// different computation of curr_bound for
// level 2 from the other levels
if (level == 1)
curr_bound -=
((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2);
else
curr_bound -=
((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2);
// curr_bound + curr_weight is the actual lower bound
// for the node that we have arrived on
// If current lower bound < final_res, we need to explore
// the node further
if (curr_bound + curr_weight < final_res) {
curr_path[level] = i;
visited[i] = true;
// call TSP_Recursive for the next level
TSP_Recursive(adj, curr_bound, curr_weight, level + 1, curr_path);
}
// Else we have to prune the node by resetting
// all changes to curr_weight and curr_bound
curr_weight -= adj[curr_path[level - 1]][i];
curr_bound = temp;
// Also reset the visited array
visited.resize(visited.size(), false);
for (int j = 0; j <= level - 1; j++)
visited[curr_path[j]] = true;
}
}
}
// Function to copy temporary solution to
// the final solution
void copyToFinal(int curr_path[]) {
for (int i = 0; i < n; i++)
final_path[i] = curr_path[i];
final_path[n] = curr_path[0];
}
// print result
void print_result() {
cout << "Minimum Cost : " << final_res << endl;
std::cout << "Path taken :" << std::endl;
for (int i = 0; i < n; i++) {
std::cout << final_path[i] << " ";
}
std::cout << std::endl;
}
// Function to find the minimum edge cost
// having an end at the vertex i
int firstMin(vector<vector<int>> graph, int i) {
int min = INT_MAX;
for (int k = 0; k < n; k++)
if (graph[i][k] < min && i != k)
min = graph[i][k];
return min;
}
// function to find the second minimum edge cost
// having an end at the vertex i
int secondMin(vector<vector<int>> graph, int i) {
int first = INT_MAX, second = INT_MAX;
for (int j = 0; j < n; j++) {
if (i == j)
continue;
if (graph[i][j] <= first) {
second = first;
first = graph[i][j];
} else if (graph[i][j] <= second && graph[i][j] != first)
second = graph[i][j];
}
return second;
}
};
int main(int argc, const char **argv) {
vector<vector<int>> graph = {
{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}};
int n = graph.size();
int s = 0; /* source vertex*/
TSP tsp(graph, n);
tsp.solve(s);
tsp.print_result();
return 0;
} | 30.010638 | 78 | 0.584722 |
876d9e91896597ba1c37b8d358f5bb55e9636321 | 421 | cpp | C++ | intersection_of_sorted_arrays.cpp | muskanverma/coding-problems-solved | 3df460e79ed7fb8044fb3ef4b6fe84ef5444dd20 | [
"MIT"
] | null | null | null | intersection_of_sorted_arrays.cpp | muskanverma/coding-problems-solved | 3df460e79ed7fb8044fb3ef4b6fe84ef5444dd20 | [
"MIT"
] | null | null | null | intersection_of_sorted_arrays.cpp | muskanverma/coding-problems-solved | 3df460e79ed7fb8044fb3ef4b6fe84ef5444dd20 | [
"MIT"
] | null | null | null | vector<int> Solution::intersect(const vector<int> &a, const vector<int> &b) {
int i = 0, j = 0;
vector<int>c;
int x = a.size();
int y = b.size();
while(i<x && j<y){
if(a[i]<b[j]){
i++;
}
else if(b[j]<a[i]){
j++;
}
else{
c.push_back(a[i]);
i++;
j++;
}
}
return c;
}
| 20.047619 | 78 | 0.339667 |
876e12e9bc37d8d8578cac74f6219d8163bd2b5e | 398 | cpp | C++ | Firmware/AnalogInput.cpp | RauBurger/SuperSled | e2f8a1e4c5d3a001a613a83f495e8c9289601dc4 | [
"MIT"
] | null | null | null | Firmware/AnalogInput.cpp | RauBurger/SuperSled | e2f8a1e4c5d3a001a613a83f495e8c9289601dc4 | [
"MIT"
] | null | null | null | Firmware/AnalogInput.cpp | RauBurger/SuperSled | e2f8a1e4c5d3a001a613a83f495e8c9289601dc4 | [
"MIT"
] | null | null | null | #include "AnalogInput.h"
#include "Debug.h"
AnalogInput::AnalogInput(uint32_t instance, uint32_t channelGroup, adc16_chn_config_t channelConfig) :
mInstance(instance),
mChannelConfig(channelConfig),
mChannelGroup(channelGroup)
{
ADC16_DRV_ConfigConvChn(mInstance, mChannelGroup, &mChannelConfig);
}
uint16_t AnalogInput::Read()
{
return ADC16_DRV_GetConvValueRAW(mInstance, mChannelGroup);
} | 26.533333 | 102 | 0.816583 |
87722eeb4905a7d547f6a2faaecd8eb968ada488 | 1,281 | cc | C++ | leetcode/1300-critical-connections-in-a-network.cc | Magic07/online-judge-solutions | 02a289dd7eb52d7eafabc97bd1a043213b65f70a | [
"MIT"
] | null | null | null | leetcode/1300-critical-connections-in-a-network.cc | Magic07/online-judge-solutions | 02a289dd7eb52d7eafabc97bd1a043213b65f70a | [
"MIT"
] | null | null | null | leetcode/1300-critical-connections-in-a-network.cc | Magic07/online-judge-solutions | 02a289dd7eb52d7eafabc97bd1a043213b65f70a | [
"MIT"
] | null | null | null | #include <vector>
class Solution {
public:
int currentDfn;
vector<vector<int>> answer;
void dfs(int start,
const vector<vector<int>>& graph,
vector<int>& dfn,
vector<int>& low,
int parent) {
for (const auto& v : graph[start]) {
if (v == parent) {
continue;
}
if (dfn[v] == -1) {
low[v] = currentDfn;
dfn[v] = currentDfn++;
dfs(v, graph, dfn, low, start);
low[start] = min(low[start], low[v]);
if (low[v] > dfn[start]) {
answer.push_back({start, v});
}
} else {
low[start] = min(low[start], dfn[v]);
}
}
}
void resizeAndFill(vector<int>& v, int n) {
v.resize(n);
fill(v.begin(), v.end(), -1);
}
vector<vector<int>> criticalConnections(int n,
vector<vector<int>>& connections) {
vector<vector<int>> graph;
vector<int> dfn, low;
graph.resize(n);
resizeAndFill(dfn, n);
resizeAndFill(low, n);
currentDfn = 0;
for (const auto& con : connections) {
graph[con[0]].push_back(con[1]);
graph[con[1]].push_back(con[0]);
}
dfs(0, graph, dfn, low, 0);
return answer;
}
}; | 26.6875 | 78 | 0.489461 |
87736715930f209007aa2a51c75f7a44eba804d7 | 7,927 | cc | C++ | components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/page_load_metrics/browser/responsiveness_metrics_normalization_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/page_load_metrics/browser/responsiveness_metrics_normalization.h"
#include "base/test/scoped_feature_list.h"
#include "components/page_load_metrics/common/page_load_metrics.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
using UserInteractionLatenciesPtr =
page_load_metrics::mojom::UserInteractionLatenciesPtr;
using UserInteractionLatencies =
page_load_metrics::mojom::UserInteractionLatencies;
using UserInteractionLatency = page_load_metrics::mojom::UserInteractionLatency;
using UserInteractionType = page_load_metrics::mojom::UserInteractionType;
class ResponsivenessMetricsNormalizationTest : public testing::Test {
public:
ResponsivenessMetricsNormalizationTest() = default;
void AddNewUserInteractions(uint64_t num_new_interactions,
UserInteractionLatencies& max_event_durations,
UserInteractionLatencies& total_event_durations) {
responsiveness_metrics_normalization_.AddNewUserInteractionLatencies(
num_new_interactions, max_event_durations, total_event_durations);
}
const page_load_metrics::NormalizedResponsivenessMetrics&
normalized_responsiveness_metrics() const {
return responsiveness_metrics_normalization_
.GetNormalizedResponsivenessMetrics();
}
private:
page_load_metrics::ResponsivenessMetricsNormalization
responsiveness_metrics_normalization_;
};
TEST_F(ResponsivenessMetricsNormalizationTest, OnlySendWorstInteractions) {
UserInteractionLatenciesPtr max_event_duration1 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(120));
UserInteractionLatenciesPtr total_event_durations1 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(140));
AddNewUserInteractions(1, *max_event_duration1, *total_event_durations1);
UserInteractionLatenciesPtr max_event_duration2 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(200));
UserInteractionLatenciesPtr total_event_durations2 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(250));
AddNewUserInteractions(2, *max_event_duration2, *total_event_durations2);
UserInteractionLatenciesPtr max_event_duration3 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(70));
UserInteractionLatenciesPtr total_event_durations3 =
UserInteractionLatencies::NewWorstInteractionLatency(
base::Milliseconds(70));
AddNewUserInteractions(3, *max_event_duration3, *total_event_durations3);
EXPECT_EQ(normalized_responsiveness_metrics().num_user_interactions, 6u);
// When the flag is disabled, only worst_latency has a meaningful value and
// other metrics should have default values.
auto& normalized_max_event_durations =
normalized_responsiveness_metrics().normalized_max_event_durations;
EXPECT_EQ(normalized_max_event_durations.worst_latency,
base::Milliseconds(200));
EXPECT_EQ(normalized_max_event_durations.worst_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(normalized_max_event_durations.sum_of_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(
normalized_max_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
auto& normalized_total_event_durations =
normalized_responsiveness_metrics().normalized_total_event_durations;
EXPECT_EQ(normalized_total_event_durations.worst_latency,
base::Milliseconds(250));
EXPECT_EQ(normalized_total_event_durations.worst_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(normalized_total_event_durations.sum_of_latency_over_budget,
base::Milliseconds(0));
EXPECT_EQ(
normalized_total_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
}
TEST_F(ResponsivenessMetricsNormalizationTest, SendAllInteractions) {
// Flip the flag to send all user interaction latencies to browser.
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeature(
blink::features::kSendAllUserInteractionLatencies);
UserInteractionLatenciesPtr max_event_durations =
UserInteractionLatencies::NewUserInteractionLatencies({});
auto& user_interaction_latencies1 =
max_event_durations->get_user_interaction_latencies();
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(50), UserInteractionType::kKeyboard));
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(100), UserInteractionType::kTapOrClick));
user_interaction_latencies1.emplace_back(UserInteractionLatency::New(
base::Milliseconds(150), UserInteractionType::kDrag));
UserInteractionLatenciesPtr total_event_durations =
UserInteractionLatencies::NewUserInteractionLatencies({});
auto& user_interaction_latencies2 =
total_event_durations->get_user_interaction_latencies();
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(55), UserInteractionType::kKeyboard));
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(105), UserInteractionType::kTapOrClick));
user_interaction_latencies2.emplace_back(UserInteractionLatency::New(
base::Milliseconds(155), UserInteractionType::kDrag));
AddNewUserInteractions(3, *max_event_durations, *total_event_durations);
auto worst_ten_max_event_durations =
normalized_responsiveness_metrics()
.normalized_max_event_durations.worst_ten_latencies_over_budget;
EXPECT_EQ(worst_ten_max_event_durations.size(), 3u);
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(0));
worst_ten_max_event_durations.pop();
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(0));
worst_ten_max_event_durations.pop();
EXPECT_EQ(worst_ten_max_event_durations.top(), base::Milliseconds(50));
auto worst_ten_total_event_durations =
normalized_responsiveness_metrics()
.normalized_total_event_durations.worst_ten_latencies_over_budget;
EXPECT_EQ(worst_ten_total_event_durations.size(), 3u);
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(5));
worst_ten_total_event_durations.pop();
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(5));
worst_ten_total_event_durations.pop();
EXPECT_EQ(worst_ten_total_event_durations.top(), base::Milliseconds(55));
EXPECT_EQ(normalized_responsiveness_metrics().num_user_interactions, 3u);
auto& normalized_max_event_durations =
normalized_responsiveness_metrics().normalized_max_event_durations;
EXPECT_EQ(normalized_max_event_durations.worst_latency,
base::Milliseconds(150));
EXPECT_EQ(normalized_max_event_durations.worst_latency_over_budget,
base::Milliseconds(50));
EXPECT_EQ(normalized_max_event_durations.sum_of_latency_over_budget,
base::Milliseconds(50));
EXPECT_EQ(
normalized_max_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(0));
auto& normalized_total_event_durations =
normalized_responsiveness_metrics().normalized_total_event_durations;
EXPECT_EQ(normalized_total_event_durations.worst_latency,
base::Milliseconds(155));
EXPECT_EQ(normalized_total_event_durations.worst_latency_over_budget,
base::Milliseconds(55));
EXPECT_EQ(normalized_total_event_durations.sum_of_latency_over_budget,
base::Milliseconds(65));
EXPECT_EQ(
normalized_total_event_durations.pseudo_second_worst_latency_over_budget,
base::Milliseconds(5));
} | 48.042424 | 86 | 0.799167 |
8776383a5697804b88328a7a61733778662837a1 | 1,400 | hpp | C++ | src/cf_libs/dskcf/ScaleChangeObserver.hpp | liguanqun/Test_code | 523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b | [
"Apache-2.0"
] | null | null | null | src/cf_libs/dskcf/ScaleChangeObserver.hpp | liguanqun/Test_code | 523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b | [
"Apache-2.0"
] | null | null | null | src/cf_libs/dskcf/ScaleChangeObserver.hpp | liguanqun/Test_code | 523f4ed4c29b2b2092b40a8c9c3ce1ddbcf0737b | [
"Apache-2.0"
] | null | null | null | #ifndef _SCALECHANGEOBSERVER_HPP_
#define _SCALECHANGEOBSERVER_HPP_
/*
This class represents a C++ implementation of the DS-KCF Tracker [1]. In particular
the scaling system presented in [1] is implemented within this class
References:
[1] S. Hannuna, M. Camplani, J. Hall, M. Mirmehdi, D. Damen, T. Burghardt, A. Paiement, L. Tao,
DS-KCF: A ~real-time tracker for RGB-D data, Journal of Real-Time Image Processing
*/
#include "Typedefs.hpp"
/**
* ScaleChangeObserver is an abstract class.
* This class is designed to be derived by any class which needs to observe
* a ScaleAnalyser. An instance of ScaleChangeObserver should only be
* registered to observe a single ScaleAnalyser.
*/
class ScaleChangeObserver
{
public:
/**
* onScaleChange is called whenever a scale change has been detected.
* @param targetSize The new size of the target object's bounding box.
* @param windowSize The new padded size of the bounding box around the target.
* @param yf The new gaussian shaped labels for this scale.
* @param cosineWindow The new cosine window for this scale.
*
* @warning If an instance of this class is registered to observe multiple
* ScaleAnalyser, then this method will likely cause a crash.
*/
virtual void onScaleChange(const Size & targetSize, const Size & windowSize, const cv::Mat2d & yf, const cv::Mat1d & cosineWindow) = 0;
};
#endif
| 36.842105 | 137 | 0.738571 |
8778b21cc3238d4b53bd280e8c3e1765e1cd28c2 | 1,879 | cpp | C++ | src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | 2 | 2016-03-21T10:48:34.000Z | 2017-03-17T19:50:34.000Z | src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | null | null | null | src/tools/dnd/targets/ContainerFileTransitiveDataTarget.cpp | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | null | null | null | /***************************************************************
* Name: ContainerFileTransitiveDataTarget.cpp
* Purpose: Code for Fu(X) 2.0
* Author: David Lecoconnier (david.lecoconnier@free.fr)
* Created: 2015-06-26
* Copyright: David Lecoconnier (http://www.getfux.fr)
* License:
**************************************************************/
#include "tools/dnd/targets/ContainerFileTransitiveDataTarget.h"
#include "explorer/state/FileDriveManagerState.h"
#include "tools/dnd/dataObjects/ContainerFileTransitiveData.h"
#include <algorithm>
using namespace dragAndDrop;
/** @brief Constructor.
*/
ContainerFileTransitiveDataTarget::ContainerFileTransitiveDataTarget(DroppedMarkedLineListCtrl& source, explorer::FileDriveManagerState& managerState) :
TransitiveDataTarget(source),
m_managerState(managerState)
{
}
/** @brief Destructor.
*/
ContainerFileTransitiveDataTarget::~ContainerFileTransitiveDataTarget()
{
}
bool ContainerFileTransitiveDataTarget::isSameKind() const
{
if (m_data == NULL)
return false;
return m_data->isContainerFileKind();
}
void ContainerFileTransitiveDataTarget::doCopyProcessing(const wxArrayString& data, const long position)
{
m_managerState.insertElements(data, position);
}
void ContainerFileTransitiveDataTarget::doCutProcessing(TransitiveData& transitiveData, const long position)
{
ContainerFileTransitiveData& fileTransitiveData = static_cast<ContainerFileTransitiveData&>(transitiveData);
const unsigned long pos = position;
const std::vector<unsigned long>& items = fileTransitiveData.getItems();
std::vector<unsigned long>::const_iterator iter = std::find(items.begin(), items.end(), pos);
if (iter == items.end())
return;
m_managerState.insertElements(fileTransitiveData.getFilenames(), position);
fileTransitiveData.deleteFromSource();
}
| 33.553571 | 152 | 0.717935 |
877bdeb46a7ef2936fac4605fbf5b303b6eb9e14 | 1,734 | hpp | C++ | headers/lagrangian.hpp | bluemner/scientific_computing | db7c2d2372e7b493feece406de21f091369bbc0b | [
"MIT"
] | null | null | null | headers/lagrangian.hpp | bluemner/scientific_computing | db7c2d2372e7b493feece406de21f091369bbc0b | [
"MIT"
] | null | null | null | headers/lagrangian.hpp | bluemner/scientific_computing | db7c2d2372e7b493feece406de21f091369bbc0b | [
"MIT"
] | null | null | null | /** MIT License
Copyright (c) 2017 Brandon Bluemner
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.
*/
#ifndef _BETACORE_LAGRANGIAN_H_
#define _BETACORE_LAGRANGIAN_H_
namespace betacore {
template <typename T>
class Lagrangian{
template <size_t size>
static T Polynomial( T x, size_t point, T (&points)[size] ){
size_t i;
T h=1;
for(i=0; i<size; i++){
if(i != point){
h = h * (x - points[i]) / (points[point] - points[i]);
}
return h;
}
}
template <size_t size>
static T Interpolant( T x, T (&points)[size], T (&values)[size] ){
size_t i;
T sum = (T) 0; // cast needed
for( i = 0; i < size; i++){
sum = sum + values[i] * Polynomial(x, i, points);
}
return sum;
}
};
}
#endif | 33.346154 | 79 | 0.711649 |
877e5cb185a7fc44f80c03ed816965492643bb6a | 3,555 | hpp | C++ | frame/object.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/object.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/object.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | // frame/object.hpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#ifndef SOLID_FRAME_OBJECT_HPP
#define SOLID_FRAME_OBJECT_HPP
#include "system/timespec.hpp"
#include "frame/common.hpp"
#include "utility/dynamictype.hpp"
#include "utility/dynamicpointer.hpp"
#include <boost/concept_check.hpp>
#ifdef HAS_STDATOMIC
#include <atomic>
#else
#include "boost/atomic.hpp"
#endif
namespace solid{
class Mutex;
namespace frame{
class Manager;
class Service;
class ObjectPointerBase;
class Message;
class SelectorBase;
class Object;
class Object: public Dynamic<Object, DynamicShared<> >{
public:
struct ExecuteContext{
enum RetValE{
WaitRequest,
WaitUntilRequest,
RescheduleRequest,
CloseRequest,
LeaveRequest,
};
size_t eventMask()const{
return evsmsk;
}
const TimeSpec& currentTime()const{
return rcrttm;
}
void reschedule();
void close();
void leave();
void wait();
void waitUntil(const TimeSpec &_rtm);
void waitFor(const TimeSpec &_rtm);
protected:
ExecuteContext(
const size_t _evsmsk,
const TimeSpec &_rcrttm
): evsmsk(_evsmsk), rcrttm(_rcrttm), retval(WaitRequest){}
size_t evsmsk;
const TimeSpec &rcrttm;
RetValE retval;
TimeSpec waittm;
};
struct ExecuteController: ExecuteContext{
ExecuteController(
const size_t _evsmsk,
const TimeSpec &_rcrttm
): ExecuteContext(_evsmsk, _rcrttm){}
const RetValE returnValue()const{
return this->retval;
}
const TimeSpec& waitTime()const{
return this->waittm;
}
};
static const TimeSpec& currentTime();
//!Get the object associated to the current thread
/*!
\see Object::associateToCurrentThread
*/
static Object& specific();
//! Returns true if the object is signaled
bool notified() const;
bool notified(size_t _s) const;
//! Get the id of the object
IndexT id() const;
/**
* Returns true if the signal should raise the object ASAP
* \param _smask The signal bitmask
*/
bool notify(size_t _smask);
//! Signal the object with a signal
virtual bool notify(DynamicPointer<Message> &_rmsgptr);
protected:
friend class Service;
friend class Manager;
friend class SelectorBase;
//! Constructor
Object();
//! Grab the signal mask eventually leaving some bits set- CALL this inside lock!!
size_t grabSignalMask(size_t _leave = 0);
//! Virtual destructor
virtual ~Object();//only objptr base can destroy an object
void unregister();
bool isRegistered()const;
virtual void doStop();
private:
static void doSetCurrentTime(const TimeSpec *_pcrtts);
//! Set the id
void id(const IndexT &_fullid);
//! Gets the id of the thread the object resides in
IndexT threadId()const;
//! Assigns the object to the current thread
/*!
This is usualy called by the pool's Selector.
*/
void associateToCurrentThread();
//! Executes the objects
/*!
This method is calle by selectpools with support for
events and timeouts
*/
virtual void execute(ExecuteContext &_rexectx);
void stop();
//! Set the thread id
void threadId(const IndexT &_thrid);
private:
IndexT fullid;
ATOMIC_NS::atomic<size_t> smask;
ATOMIC_NS::atomic<IndexT> thrid;
};
inline IndexT Object::id() const {
return fullid;
}
#ifndef NINLINES
#include "frame/object.ipp"
#endif
}//namespace frame
}//namespace solid
#endif
| 20.084746 | 89 | 0.719269 |
8781a3e7aec776a34a38c7f30aac146996651ab0 | 53 | cpp | C++ | xperf/vc_parallel_compiles/Group1_A.cpp | ariccio/main | c1dce7b2f4b2682a984894cce995fadee0fe717a | [
"MIT"
] | 17 | 2015-03-02T18:19:24.000Z | 2021-07-26T11:20:24.000Z | xperf/vc_parallel_compiles/Group1_A.cpp | ariccio/main | c1dce7b2f4b2682a984894cce995fadee0fe717a | [
"MIT"
] | 3 | 2015-03-02T04:14:25.000Z | 2015-09-05T23:04:42.000Z | xperf/vc_parallel_compiles/Group1_B.cpp | randomascii/main | e5c3a1f84922b912edc1f859c455e1f80a9b0f83 | [
"MIT"
] | 6 | 2015-02-08T04:19:57.000Z | 2016-04-22T11:34:26.000Z | #include "stdafx.h"
static int s_value = CALC_FIB1;
| 13.25 | 31 | 0.735849 |
8781f7120eeb763696c4e9a344e0b5c1ec458bba | 12,049 | cpp | C++ | MediaCodecRT/DllLoader.cpp | gaobowen/MediaCodecRT | 8c0136eaf9c6cec50c9e4106d60988bdd0957e59 | [
"MIT"
] | 2 | 2019-02-18T09:25:46.000Z | 2019-04-19T08:05:58.000Z | MediaCodecRT/DllLoader.cpp | gaobowen/MediaCodecRT | 8c0136eaf9c6cec50c9e4106d60988bdd0957e59 | [
"MIT"
] | null | null | null | MediaCodecRT/DllLoader.cpp | gaobowen/MediaCodecRT | 8c0136eaf9c6cec50c9e4106d60988bdd0957e59 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "DllLoader.h"
using namespace MediaCodecRT;
HMODULE avutil_55_mod;
HMODULE avcodec_57_mod;
HMODULE avformat_57_mod;
HMODULE swscale_4_mod;
HMODULE swresample_2_mod;
HMODULE avdevice_57_mod;
HMODULE avfilter_6_mod;
HMODULE kernelAddr;
def_av_register_all * m_av_register_all;
def_av_malloc* m_av_malloc;
def_avio_alloc_context* m_avio_alloc_context;
def_avformat_alloc_context* m_avformat_alloc_context;
def_avformat_open_input* m_avformat_open_input;
def_av_dict_free* m_av_dict_free;
def_avformat_find_stream_info* m_avformat_find_stream_info;
def_av_find_best_stream* m_av_find_best_stream;
def_avcodec_alloc_context3* m_avcodec_alloc_context3;
//def_avcodec_parameters_to_context* m_avcodec_parameters_to_context;
def_avcodec_open2* m_avcodec_open2;
def_av_frame_free* m_av_frame_free;
def_av_frame_alloc* m_av_frame_alloc;
def_av_image_get_buffer_size* m_av_image_get_buffer_size;
def_av_image_fill_arrays* m_av_image_fill_arrays;
def_sws_getContext* m_sws_getContext;
def_av_seek_frame* m_av_seek_frame;
def_avcodec_flush_buffers* m_avcodec_flush_buffers;
def_av_read_frame* m_av_read_frame;
def_av_packet_unref* m_av_packet_unref;
def_avcodec_decode_video2* m_avcodec_decode_video2;
def_sws_scale* m_sws_scale;
def_avcodec_close* m_avcodec_close;
def_avformat_close_input* m_avformat_close_input;
def_av_free* m_av_free;
def_avcodec_free_context* m_avcodec_free_context;
def_avcodec_find_decoder* m_avcodec_find_decoder;
def_avcodec_find_decoder_by_name* m_avcodec_find_decoder_by_name;
def_av_guess_format* m_av_guess_format;
def_avformat_alloc_output_context2* m_avformat_alloc_output_context2;
def_avformat_new_stream* m_avformat_new_stream;
def_avcodec_encode_video2* m_avcodec_encode_video2;
def_av_write_frame* m_av_write_frame;;
def_av_write_trailer* m_av_write_trailer;
def_avio_close* m_avio_close;
def_avformat_free_context* m_avformat_free_context;
def_avformat_write_header* m_avformat_write_header;
def_av_new_packet* m_av_new_packet;
def_avcodec_find_encoder* m_avcodec_find_encoder;
def_avcodec_find_encoder_by_name* m_avcodec_find_encoder_by_name;
def_avcodec_register_all* m_avcodec_register_all;
def_av_codec_next* m_av_codec_next;
//def_avio_alloc_context* m_static_avio_alloc_context;
//def_avformat_alloc_context* m_static_avformat_alloc_context;
//def_avcodec_open2* m_static_avcodec_open2;
//def_av_guess_format* m_static_av_guess_format;
//def_avformat_alloc_output_context2* m_static_avformat_alloc_output_context2;
//def_avformat_new_stream* m_static_avformat_new_stream;
//def_avcodec_encode_video2* m_static_avcodec_encode_video2;
//def_av_write_frame* m_static_av_write_frame;
//def_av_write_trailer* m_static_av_write_trailer;
//def_avio_close* m_static_avio_close;
//def_avformat_free_context* m_static_avformat_free_context;
//def_avformat_write_header* m_static_avformat_write_header;
//def_avcodec_find_encoder* m_static_avcodec_find_encoder;
//def_avcodec_find_encoder_by_name* m_static_avcodec_find_encoder_by_name;
//def_av_malloc* m_static_av_malloc;
//def_av_frame_alloc* m_static_av_frame_alloc;
//def_av_new_packet* m_static_av_new_packet;
//def_av_packet_unref * m_static_av_packet_unref;
//def_avcodec_close* m_static_avcodec_close;
//def_av_free* m_static_av_free;
//def_av_register_all * my_static_av_register_all;
DllLoader::DllLoader()
{
}
bool MediaCodecRT::DllLoader::LoadAll()
{
MEMORY_BASIC_INFORMATION info = {};
if (VirtualQuery(VirtualQuery, &info, sizeof(info)))
{
kernelAddr = (HMODULE)info.AllocationBase;
auto loadlibraryPtr = (int64_t)GetProcAddress(kernelAddr, "LoadLibraryExW");
auto loadLibrary = (LoadLibraryExWPtr*)loadlibraryPtr;
auto user32_mod = loadLibrary(L"user32.dll", nullptr, 0);
//auto kernel32Addr = loadLibrary(L"kernel32.dll", nullptr, 0);
//auto allfmpeg = loadLibrary(L"ffmpeg.adll", nullptr, 0);
//m_av_malloc/av_frame_free/av_frame_alloc/av_image_get_buffer_size/av_image_fill_arrays/
avutil_55_mod = loadLibrary(L"avutil-55.dll", nullptr, 0);
//avutil_55_mod = allfmpeg;
m_av_malloc = (def_av_malloc*)GetProcAddress(avutil_55_mod, "av_malloc");
m_av_frame_free = (def_av_frame_free*)GetProcAddress(avutil_55_mod, "av_frame_free");
m_av_frame_alloc = (def_av_frame_alloc*)GetProcAddress(avutil_55_mod, "av_frame_alloc");
m_av_image_get_buffer_size = (def_av_image_get_buffer_size*)GetProcAddress(avutil_55_mod, "av_image_get_buffer_size");
m_av_image_fill_arrays = (def_av_image_fill_arrays*)GetProcAddress(avutil_55_mod, "av_image_fill_arrays");
m_av_free = (def_av_free*)GetProcAddress(avutil_55_mod, "av_free");
m_av_dict_free = (def_av_dict_free*)GetProcAddress(avutil_55_mod, "av_dict_free");
//avcodec_alloc_context3/avcodec_find_decoder/avcodec_open2/avcodec_flush_buffers/av_packet_unref/avcodec_decode_video2
avcodec_57_mod = loadLibrary(L"avcodec-57.dll", nullptr, 0);
//avcodec_57_mod = allfmpeg;
m_avcodec_alloc_context3 = (def_avcodec_alloc_context3*)GetProcAddress(avcodec_57_mod, "avcodec_alloc_context3");
m_avcodec_find_decoder = (def_avcodec_find_decoder*)GetProcAddress(avcodec_57_mod, "avcodec_find_decoder");
m_avcodec_open2 = (def_avcodec_open2*)GetProcAddress(avcodec_57_mod, "avcodec_open2");
m_avcodec_flush_buffers = (def_avcodec_flush_buffers*)GetProcAddress(avcodec_57_mod, "avcodec_flush_buffers");
m_av_packet_unref = (def_av_packet_unref*)GetProcAddress(avcodec_57_mod, "av_packet_unref");
m_avcodec_decode_video2 = (def_avcodec_decode_video2*)GetProcAddress(avcodec_57_mod, "avcodec_decode_video2");
//m_avcodec_parameters_to_context = (def_avcodec_parameters_to_context*)GetProcAddress(avcodec_57_mod, "avcodec_parameters_to_context");
m_avcodec_free_context = (def_avcodec_free_context*)GetProcAddress(avcodec_57_mod, "avcodec_free_context");
m_avcodec_find_decoder_by_name = (def_avcodec_find_decoder_by_name*)GetProcAddress(avcodec_57_mod, "avcodec_find_decoder_by_name");
m_avcodec_close = (def_avcodec_close*)GetProcAddress(avcodec_57_mod, "avcodec_close");
m_avcodec_find_encoder = (def_avcodec_find_encoder*)GetProcAddress(avcodec_57_mod, "avcodec_find_encoder");
m_avcodec_encode_video2 = (def_avcodec_encode_video2*)GetProcAddress(avcodec_57_mod, "avcodec_encode_video2");
m_av_new_packet = (def_av_new_packet*)GetProcAddress(avcodec_57_mod, "av_new_packet");
m_avcodec_find_encoder_by_name = (def_avcodec_find_encoder_by_name*)GetProcAddress(avcodec_57_mod, "avcodec_find_encoder_by_name");
m_avcodec_register_all = (def_avcodec_register_all*)GetProcAddress(avcodec_57_mod, "avcodec_register_all");
m_av_codec_next = (def_av_codec_next*)GetProcAddress(avcodec_57_mod, "av_codec_next");
//m_av_register_all/avio_alloc_context/avformat_alloc_context/avformat_open_input/avformat_find_stream_info/av_find_best_stream
//av_seek_frame/av_read_frame
avformat_57_mod = loadLibrary(L"avformat-57.dll", nullptr, 0);
//avformat_57_mod = allfmpeg;
m_av_register_all = (def_av_register_all*)GetProcAddress(avformat_57_mod, "av_register_all");
m_avio_alloc_context = (def_avio_alloc_context*)GetProcAddress(avformat_57_mod, "avio_alloc_context");
m_avformat_alloc_context = (def_avformat_alloc_context*)GetProcAddress(avformat_57_mod, "avformat_alloc_context");
m_avformat_open_input = (def_avformat_open_input*)GetProcAddress(avformat_57_mod, "avformat_open_input");
m_avformat_find_stream_info = (def_avformat_find_stream_info*)GetProcAddress(avformat_57_mod, "avformat_find_stream_info");
m_av_find_best_stream = (def_av_find_best_stream*)GetProcAddress(avformat_57_mod, "av_find_best_stream");
m_av_seek_frame = (def_av_seek_frame*)GetProcAddress(avformat_57_mod, "av_seek_frame");
m_av_read_frame = (def_av_read_frame*)GetProcAddress(avformat_57_mod, "av_read_frame");
m_avformat_close_input = (def_avformat_close_input*)GetProcAddress(avformat_57_mod, "avformat_close_input");
m_av_guess_format = (def_av_guess_format*)GetProcAddress(avformat_57_mod, "av_guess_format");
m_avformat_alloc_output_context2 = (def_avformat_alloc_output_context2*)GetProcAddress(avformat_57_mod, "avformat_alloc_output_context2");
m_avformat_new_stream = (def_avformat_new_stream*)GetProcAddress(avformat_57_mod, "avformat_new_stream");
m_avio_close = (def_avio_close*)GetProcAddress(avformat_57_mod, "avio_close");
m_avformat_free_context = (def_avformat_free_context*)GetProcAddress(avformat_57_mod, "avformat_free_context");
m_avformat_write_header = (def_avformat_write_header*)GetProcAddress(avformat_57_mod, "avformat_write_header");
m_av_write_frame = (def_av_write_frame*)GetProcAddress(avformat_57_mod, "av_write_frame");
m_av_write_trailer = (def_av_write_trailer*)GetProcAddress(avformat_57_mod, "av_write_trailer");
//sws_getContext/sws_scale
swscale_4_mod = loadLibrary(L"swscale-4.dll", nullptr, 0);
//swscale_4_mod = allfmpeg;
m_sws_getContext = (def_sws_getContext*)GetProcAddress(swscale_4_mod, "sws_getContext");
m_sws_scale = (def_sws_scale*)GetProcAddress(swscale_4_mod, "sws_scale");
//swresample_2_mod = loadLibrary(L"swresample-2.dll", nullptr, 0);
//avdevice_57_mod = loadLibrary(L"avdevice-57.dll", nullptr, 0);
//avfilter_6_mod = loadLibrary(L"avfilter-6.dll", nullptr, 0);
if (avutil_55_mod != nullptr && avcodec_57_mod != nullptr&& avformat_57_mod != nullptr&& swscale_4_mod != nullptr)
{
m_avcodec_register_all();
//AVCodec *c = m_av_codec_next(NULL);
//AVCodec* bbb = m_avcodec_find_encoder_by_name("mjpeg");
//decodec->
//if (encodec == NULL)
//{
// return false;
//}
//auto allfmpeg = loadLibrary(L"ffmpeg.txt", nullptr, 0);
//if (allfmpeg != NULL)
//{
// my_static_av_register_all = (def_av_register_all*)GetProcAddress(allfmpeg, "av_register_all");
// m_static_avio_alloc_context = (def_avio_alloc_context*)GetProcAddress(allfmpeg, "avio_alloc_context");
// m_static_avformat_alloc_context = (def_avformat_alloc_context*)GetProcAddress(allfmpeg, "avformat_alloc_context");
// m_static_avcodec_open2 = (def_avcodec_open2*)GetProcAddress(allfmpeg, "avcodec_open2");
// m_static_av_guess_format = (def_av_guess_format*)GetProcAddress(allfmpeg, "av_guess_format");
// m_static_avformat_alloc_output_context2 = (def_avformat_alloc_output_context2*)GetProcAddress(allfmpeg, "avformat_alloc_output_context2");
// m_static_avformat_new_stream = (def_avformat_new_stream*)GetProcAddress(allfmpeg, "avformat_new_stream");
// m_static_avcodec_encode_video2 = (def_avcodec_encode_video2*)GetProcAddress(allfmpeg, "avcodec_encode_video2");
// m_static_av_write_frame = (def_av_write_frame*)GetProcAddress(allfmpeg, "av_write_frame");
// m_static_av_write_trailer = (def_av_write_trailer*)GetProcAddress(allfmpeg, "av_write_trailer");
// m_static_avio_close = (def_avio_close*)GetProcAddress(allfmpeg, "avio_close");
// m_static_avformat_free_context = (def_avformat_free_context*)GetProcAddress(allfmpeg, "avformat_free_context");
// m_static_avformat_write_header = (def_avformat_write_header*)GetProcAddress(allfmpeg, "avformat_write_header");
// m_static_avcodec_find_encoder = (def_avcodec_find_encoder*)GetProcAddress(allfmpeg, "avcodec_find_encoder");
// m_static_avcodec_find_encoder_by_name = (def_avcodec_find_encoder_by_name*)GetProcAddress(allfmpeg, "avcodec_find_encoder_by_name");
// m_static_av_malloc = (def_av_malloc*)GetProcAddress(allfmpeg, "av_malloc");
// m_static_av_frame_alloc = (def_av_frame_alloc*)GetProcAddress(allfmpeg, "av_frame_alloc");
// m_static_av_new_packet = (def_av_new_packet*)GetProcAddress(allfmpeg, "av_new_packet");
// m_static_av_packet_unref = (def_av_packet_unref*)GetProcAddress(allfmpeg, "av_packet_unref");
// m_static_avcodec_close = (def_avcodec_close*)GetProcAddress(allfmpeg, "avcodec_close");
// m_static_av_free = (def_av_free*)GetProcAddress(allfmpeg, "av_free");
//}
return true;
}
}
return false;
}
DllLoader::~DllLoader()
{
}
| 54.768182 | 144 | 0.822226 |
8784146ac13d6b974322b8364facab1e6964f0b1 | 2,947 | cpp | C++ | actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp | gsosad/Programacion-I | 16bba6989fa09f6c9801a1092cf4ab4a2833876e | [
"MIT"
] | 1 | 2019-01-12T18:13:54.000Z | 2019-01-12T18:13:54.000Z | actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp | gsosad/Programacion-I | 16bba6989fa09f6c9801a1092cf4ab4a2833876e | [
"MIT"
] | 1 | 2018-10-14T18:12:28.000Z | 2018-10-14T18:12:28.000Z | actividades/sesion4/OSalvador/Actividad1/Vectores final.cpp | gsosad/Programacion-I | 16bba6989fa09f6c9801a1092cf4ab4a2833876e | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
using namespace std;
class Vector3D{
private:
float x,y,z;
float a,b,c;
public:
Vector3D(float _x, float _y, float _z){
x = _x;
y = _y;
z = _z;
}
void getCoordinates(float &a, float &b, float &c){
a = x;
b = y;
c = z;
}
//no dar valores de las coordenadas, llamar al vector
void scalarMultiplyBy(float num){
//x* = num es un atajo de x = x * num
x*= num;
y*= num;
z*= num;
}
//no estoy seguro de que el resultado del modulo sea correcto, pero la formula parece estar bien
float module(){
return sqrt(pow(x,2)+pow(y,2)+pow(z,2));
}
void add (Vector3D a ){
x = x + a.x;
y = y + a.y;
z = z + a.z;
}
void vectorMultiplyBy (Vector3D a ){
x = x * a.x;
y = y * a.y;
z = z * a.z;
}
};
int main(){
//declaracion de vectores y modulo
float x,y,z;
cout << "Introduce las coordenadas un primer vector: " << endl;
cin >> x >> y >> z;
Vector3D VectorUno(x,y,z);
VectorUno.getCoordinates(x,y,z);
cout << "El primer vector tiene coordenadas "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del vector vale: " << VectorUno.module() << endl;
float operador;
cout << "Por que numero quieres multiplicar tu vector?" << endl;
cin >> operador;
cout << "El resultado es: " << endl;
VectorUno.scalarMultiplyBy(operador);
//getCoordinates lo que hace es sobreescribir los valores de x,y,z con los x,y,z del vector
VectorUno.getCoordinates(x,y,z);
cout << "x: " << x << ", y: " << y << ", z: " << z << endl << endl;
cout << "Introduce las coordernadas de un segundo vector por el que multiplicar al primero: " << endl;
cin >> x >> y >> z;
Vector3D VectorDos(x,y,z);
VectorDos.getCoordinates(x,y,z);
cout << "Las coordenadas del segundo vector valen "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del segundo vector vale: " << VectorDos.module() << endl;
cout << "Introduce las coordernadas de un tercer vector que suma al segundo: " << endl;
cin >> x >> y >> z;
Vector3D VectorTres(x,y,z);
VectorTres.getCoordinates(x,y,z);
cout << "Las coordenadas del tercer vector valen "<< "x: " << x << ", y: " << y << ", z: " << z << endl;
cout << "El modulo del tercer vector vale: " << VectorTres.module() << endl;
//operaciones de vectores
VectorUno.vectorMultiplyBy(VectorDos);
VectorUno.getCoordinates(x,y,z);
cout << "El producto del primer y segundo vectores es el vector de coordenadas x: " << x << ", y:" << y << ", z:" << z << endl;
VectorDos.add(VectorTres);
VectorDos.getCoordinates(x,y,z);
cout << "La suma del segundo y tercer vectores es el vector de coordenadas x: " << x << ", y: " << y << ", z: " << z << endl;
return 0;
}
| 27.287037 | 130 | 0.556159 |
8784aced478528d638b9691c26e77057c0b11a1f | 10,048 | cpp | C++ | editor/src/window/window.cpp | TSAVideoGame/Skidibidipop | 62a8f949266df13cd759e3b98e36e16e05aabd11 | [
"Zlib"
] | 1 | 2020-12-26T21:52:59.000Z | 2020-12-26T21:52:59.000Z | editor/src/window/window.cpp | TSAVideoGame/Skidibidipop | 62a8f949266df13cd759e3b98e36e16e05aabd11 | [
"Zlib"
] | 2 | 2021-01-15T04:05:00.000Z | 2021-03-03T18:37:08.000Z | editor/src/window/window.cpp | TSAVideoGame/Skidibidipop | 62a8f949266df13cd759e3b98e36e16e05aabd11 | [
"Zlib"
] | null | null | null | #include "window.h"
#include "constants.h"
#include <ctime>
#include <SDL2/SDL_ttf.h>
bool Editor::Window::running = true;
SDLW::Window* Editor::Window::window;
SDLW::Renderer* Editor::Window::renderer;
Editor::Inputs Editor::Window::inputs;
Editor::Tool::Manager* Editor::Window::tool_manager;
std::string Editor::Window::current_file;
SDLW::Texture* Editor::Window::current_file_tex;
std::string Editor::Window::queue_file;
std::uint16_t Editor::Window::current_section = 0;
std::uint16_t Editor::Window::queue_section = current_section;
unsigned int Editor::Window::current_zoom = 1;
Data::Save::Data Editor::Window::data = Data::Save::load("res/default.sbbd");
SDLW::Texture* Editor::Window::spritesheet;
size_t Editor::Window::firstTile; // Top-left most tile
Editor::Tool::Base* Editor::Window::selected_tool = nullptr;
void Editor::Window::init()
{
SDL_Init(SDL_INIT_EVERYTHING);
TTF_Init();
window = new SDLW::Window("SBB Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Constants::Window.width, Constants::Window.height, 0);
renderer = new SDLW::Renderer(window);
inputs = {false, false, 0, 0, 0, 0, 0, 0, 0};
spritesheet = new SDLW::Texture("res/spritesheet.png", renderer);
// The default file name is SBBD_time.sbbd
char timeNameBuffer[20];
std::time_t rawtime;
time(&rawtime);
std::tm* timeinfo = localtime(&rawtime);
strftime(timeNameBuffer, sizeof(timeNameBuffer), "%Y_%m_%d_%T", timeinfo);
current_file = "SBBD_";
current_file.append(timeNameBuffer);
current_file += ".sbbd";
current_file_tex = nullptr;
create_current_file_texture();
queue_file = current_file;
firstTile = 0;
tool_manager = new Tool::Manager(renderer);
}
void Editor::Window::close()
{
delete spritesheet;
delete current_file_tex;
delete tool_manager;
delete renderer;
delete window;
TTF_Quit();
SDL_Quit();
}
void Editor::Window::input()
{
inputs.oldMouseDown = inputs.mouseDown;
inputs.oldMouseX = inputs.mouseX;
inputs.oldMouseY = inputs.mouseY;
inputs.mouseWheelY = 0;
SDL_Event e;
while(SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_QUIT:
{
running = false;
break;
}
case SDL_MOUSEBUTTONDOWN:
{
switch (e.button.button)
{
case SDL_BUTTON_LEFT:
{
inputs.mouseDown = true;
if (!inputs.oldMouseDown)
SDL_GetMouseState(&inputs.clickMouseX, &inputs.clickMouseY);
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP:
{
switch (e.button.button)
{
case SDL_BUTTON_LEFT:
{
inputs.mouseDown = false;
break;
}
}
break;
}
case SDL_MOUSEWHEEL:
{
inputs.mouseWheelY = e.wheel.y;
break;
}
case SDL_WINDOWEVENT:
{
if (SDL_GetWindowID(window->get_SDL()) != e.window.windowID)
{
inputs.mouseDown = false;
}
break;
}
}
}
SDL_GetMouseState(&inputs.mouseX, &inputs.mouseY);
}
void Editor::Window::update()
{
if (queue_file != current_file)
{
update_current_file();
}
if (queue_section != current_section)
{
update_current_section();
}
static unsigned int tempFirstTile = firstTile, tempViewX = firstTile % data.map.sections[current_section].size.x, tempViewY = firstTile / data.map.sections[current_section].size.y;
tool_manager->update(MouseState::HOVER);
if (inputs.mouseDown)
{
if (!inputs.oldMouseDown) // Click
{
tool_manager->update(MouseState::CLICK);
}
// Drag
if (selected_tool != nullptr)
{
tool_manager->update(MouseState::DRAG);
}
// This camera movement is all broken
else
{
int maxDrag = 29; // This will help in solving overflow messes
int y = -((inputs.mouseY - inputs.clickMouseY) / Constants::Grid.size);
int x = ((inputs.mouseX - inputs.clickMouseX) / Constants::Grid.size);
// Make y within bounds
if (tempFirstTile / data.map.sections[current_section].size.x < maxDrag && static_cast<int>(tempFirstTile / data.map.sections[current_section].size.x) + y < 0)
y = -(tempFirstTile / data.map.sections[current_section].size.x);
else if (tempFirstTile / data.map.sections[current_section].size.x + y >= data.map.sections[current_section].size.y)
y = (data.map.sections[current_section].size.y - 1) - (tempFirstTile / data.map.sections[current_section].size.x);
// Make x within bounds
if (tempFirstTile % data.map.sections[current_section].size.x < maxDrag && static_cast<int>(tempFirstTile % data.map.sections[current_section].size.x) + x < 0)
x = -(tempFirstTile % data.map.sections[current_section].size.x);
else if (tempFirstTile % data.map.sections[current_section].size.x + x >= data.map.sections[current_section].size.x)
x = (data.map.sections[current_section].size.x - 1) - (tempFirstTile % data.map.sections[current_section].size.x);
// Change firstTile
firstTile = tempFirstTile + data.map.sections[current_section].size.x * y + x;
}
}
// Release
if (!inputs.mouseDown && inputs.oldMouseDown)
{
if (selected_tool == nullptr)
{
tempFirstTile = firstTile;
tempViewX = firstTile % data.map.sections[current_section].size.x;
tempViewY = firstTile / data.map.sections[current_section].size.y;
}
}
// Scroll
if (std::abs(inputs.mouseWheelY) > 0)
{
if (inputs.mouseWheelY > 0) // Decrease zoom
{
if (current_zoom > 0)
--current_zoom;
}
else // Increase zoom
{
if (current_zoom < 4)
++current_zoom;
}
}
}
static void drawGrid(SDL_Renderer* renderer)
{
int size = 32;
SDL_SetRenderDrawColor(renderer, 36, 82, 94, 255);
// Draw vertical lines
for (int i = 1; i < Editor::Constants::Window.width / size; i++)
SDL_RenderDrawLine(renderer, i * size, 0, i * size, Editor::Constants::Window.height);
// Draw horizontal lines
for (int i = 1; i < Editor::Constants::Window.height / size; i++)
SDL_RenderDrawLine(renderer, 0, i * size, Editor::Constants::Window.width, i * size);
}
void Editor::Window::draw_tiles()
{
int size = Constants::Grid.size / std::pow(2, current_zoom);
SDL_Rect dRect = {0, 0, size, size};
SDL_Rect sRect = {0, 0, 32, 32};
unsigned int windowXTiles = Constants::Window.width / size;
unsigned int maxXTiles = data.map.sections[current_section].size.x - (firstTile % data.map.sections[current_section].size.x) < windowXTiles ? data.map.sections[current_section].size.x - (firstTile % data.map.sections[current_section].size.x) : windowXTiles;
unsigned int windowYTiles = (Constants::Window.height - Constants::Window.toolBarHeight) / size;
unsigned int maxYTiles = data.map.sections[current_section].size.y - (firstTile / data.map.sections[current_section].size.x) < windowYTiles ? data.map.sections[current_section].size.y - (firstTile / data.map.sections[current_section].size.x) : windowYTiles;
for (unsigned int row = 0; row < maxYTiles; ++row)
{
for (unsigned int col = 0; col < maxXTiles; ++col)
{
// Draw tile (id)
sRect.x = data.map.sections[current_section].tiles[firstTile + (row * data.map.sections[current_section].size.x) + col].id * 32;
sRect.y = 0;
renderer->copy(spritesheet, &sRect, &dRect);
// Draw tile objects (state)
sRect.x = data.map.sections[current_section].tiles[firstTile + (row * data.map.sections[current_section].size.x) + col].state * 32;
sRect.y = 32;
renderer->copy(spritesheet, &sRect, &dRect);
// Increment dRect
dRect.x += size;
}
dRect.x = 0;
dRect.y += size;
}
}
void Editor::Window::draw()
{
renderer->set_draw_color(10, 56, 69, 255);
renderer->clear();
// Draw map stuff
drawGrid(renderer->get_SDL());
draw_tiles();
// Draw tool stuff
// Draw the toolbar
SDL_Color c = tool_manager->getColor();
renderer->set_draw_color(c.r, c.g, c.b, 255);
SDL_Rect toolbar = {0, Constants::Window.height - Constants::Window.toolBarHeight, Constants::Window.width, Constants::Window.toolBarHeight};
SDL_RenderFillRect(renderer->get_SDL(), &toolbar);
tool_manager->draw();
// Draw the current file
SDL_Rect dRect = {4, Constants::Window.height - 24, 0, 0};
SDL_QueryTexture(current_file_tex->get_SDL(), 0, 0, &dRect.w, &dRect.h);
renderer->copy(current_file_tex, 0, &dRect);
renderer->present();
}
void Editor::Window::create_current_file_texture()
{
std::string displayText = "File: " + current_file;
TTF_Font* font = TTF_OpenFont("res/fonts/open-sans/OpenSans-Regular.ttf", 16);
SDL_Surface* txtSurface = TTF_RenderText_Blended(font, displayText.c_str(), {255, 255, 255});
if (current_file_tex != nullptr)
delete current_file_tex;
current_file_tex = new SDLW::Texture(SDL_CreateTextureFromSurface(renderer->get_SDL(), txtSurface));
SDL_FreeSurface(txtSurface);
TTF_CloseFont(font);
}
void Editor::Window::update_current_file()
{
current_file = queue_file;
create_current_file_texture();
data = Data::Save::load(current_file);
}
void Editor::Window::update_current_section()
{
if (queue_section < 0 || queue_section > data.map.sections.size() - 1)
{
queue_section = current_section;
return; // Queue is invalid
}
current_section = queue_section;
}
void Editor::Window::set_current_file(const std::string& new_file)
{
queue_file = new_file;
}
void Editor::Window::set_current_section(std::uint16_t new_section)
{
queue_section = new_section;
}
bool Editor::Window::is_running() { return running; }
Editor::Inputs Editor::Window::get_inputs() { return inputs; }
std::string Editor::Window::get_current_file() { return current_file; };
size_t Editor::Window::get_first_tile() { return firstTile; };
std::uint16_t Editor::Window::get_current_section() { return current_section; }
unsigned int Editor::Window::get_current_zoom() { return current_zoom; }
| 31.012346 | 259 | 0.670681 |
8788aefd5cb7545ca8a430ef9120d41c793624b2 | 13,725 | cpp | C++ | groups/bdl/bdlb/bdlb_indexspanutil.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 1 | 2020-02-03T17:15:53.000Z | 2020-02-03T17:15:53.000Z | groups/bdl/bdlb/bdlb_indexspanutil.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 2 | 2020-11-05T15:20:55.000Z | 2021-01-05T19:38:43.000Z | groups/bdl/bdlb/bdlb_indexspanutil.t.cpp | seanbaxter/bde-1 | 149176ebc2ae49c3b563895a7332fe638a760782 | [
"Apache-2.0"
] | 2 | 2020-01-16T17:58:12.000Z | 2020-08-11T20:59:30.000Z | // bdlb_indexspanutil.t.cpp -*-C++-*-
#include <bdlb_indexspanutil.h>
#include <bdlb_indexspan.h>
#include <bslim_testutil.h>
#include <bsls_asserttest.h>
#include <bsls_buildtarget.h>
#include <bsl_cstdlib.h>
#include <bsl_cstring.h>
#include <bsl_iostream.h>
#include <bsl_string.h> // For the usage example
using namespace BloombergLP;
using namespace bsl;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// This component is a utility operating on 'bldb::IndexSpan' objects.
// ----------------------------------------------------------------------------
// CLASS METHODS
// [2] IndexSpan shrink(original, shrinkBegin, shrinkEnd);
// ----------------------------------------------------------------------------
// [1] BREATHING TEST
// [3] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
//=============================================================================
// TYPE DEFINITIONS
//-----------------------------------------------------------------------------
typedef bdlb::IndexSpanUtil Util;
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example1: Taking a IPv6 address out of a URI
/// - - - - - - - - - - - - - - - - - - - - - -
// Suppose we a class that stores a parsed URL using a string to store the full
// URL and 'IndexSpan' objects to describe the individual parts of the URL and.
// we want to add accessors that handle the case when the host part of the URL
// is an IPv6 address, such as "http://[ff:fe:9]/index.html". As observed, an
// IPv6 address is indicated by the '[' and ']' characters (the URL is ill
// formed if the closing ']' is not present). We want to implement two
// methods, one to query if the host part of the URL is IPv6 ('isIPv6Host') and
// another to get the IPv6 address (the part without the square brackets) if
// the host is actually an IPv6 address ('getIPv6Host').
//
// First let us create a 'ParsedUrl' class. For brevity, the class has only
// those parts that are needed to implement 'isIPv6Host' and 'getIPv6Host'.
//..
class ParsedUrl {
private:
// DATA
bsl::string d_url;
bdlb::IndexSpan d_host;
public:
// CREATORS
ParsedUrl(const bslstl::StringRef& url, bdlb::IndexSpan host)
// Create a 'ParsedUrl' from the specified 'url', and 'host'.
: d_url(url)
, d_host(host)
{
}
// ACCESSORS
bool isIPv6Host() const;
// Return 'true' if the host part represents an IPv6 address and
// 'false' otherwise.
bslstl::StringRef getIPv6Host() const;
// Return a string reference to the IPv6 address in the host part
// of this URL. The behavior is undefined unless
// 'isIPv6Host() == true' for this object.
};
//..
// Next, we implement 'isIPv6Host'.
//..
bool ParsedUrl::isIPv6Host() const
{
return !d_host.isEmpty() && '[' == d_url[d_host.position()];
}
//..
// Then, to make the accessors simple (and readable), we implement a helper
// function that creates a 'StringRef' from a 'StringRef' and an 'IndexSpan'.
// (Don't do this in real code, use 'IndexSpanStringUtil::bind' that is
// levelized above this component - so we cannot use it here.)
//..
bslstl::StringRef bindSpan(const bslstl::StringRef& full,
const bdlb::IndexSpan& part)
// Return a string reference to the substring of the specified 'full'
// thing defined by the specified 'part'.
{
BSLS_ASSERT(part.position() <= full.length());
BSLS_ASSERT(part.position() + part.length() <= full.length());
return bslstl::StringRef(full.data() + part.position(), part.length());
}
//..
// Next, we implement 'getIPv6Host' using 'bdlb::IndexSpanUtil::shrink'.
//..
bslstl::StringRef ParsedUrl::getIPv6Host() const
{
BSLS_ASSERT(isIPv6Host());
return bindSpan(d_url, bdlb::IndexSpanUtil::shrink(d_host, 1, 1));
}
//..
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
bool veryVeryVerbose = argc > 4; (void)veryVeryVerbose;
cout << "TEST " << __FILE__ << " CASE " << test << endl;;
switch (test) { case 0:
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
// Extracted from component header file.
//
// Concerns:
//: 1 The usage example provided in the component header file compiles,
//: links, and runs as shown.
//
// Plan:
//: 1 Incorporate usage example from header into test driver, replace
//: leading comment characters with spaces, replace 'assert' with
//: 'ASSERT', and insert 'if (veryVerbose)' before all output
//: operations. (C-1)
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nUSAGE EXAMPLE"
"\n=============\n";
// See the rest of the code just before the 'main' function.
//
// Finally, we verify the two methods with URLs.
//..
ParsedUrl pu1("https://host/path/", bdlb::IndexSpan(8, 4));
ASSERT(false == pu1.isIPv6Host());
ParsedUrl pu2("https://[12:3:fe:9]/path/", bdlb::IndexSpan(8, 11));
ASSERT(true == pu2.isIPv6Host());
ASSERT("12:3:fe:9" == pu2.getIPv6Host());
//..
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING SHRINK
//
// Concerns:
//: 1 Shrinking from the beginning increases position and decreases
//: length.
//:
//: 2 Shrinking from the end decreases length only.
//:
//: 2 Shrinking beyond the size 'BSLS_ASSERT's.
//
// Plan:
//: 1 Table based testing.
//
// Testing:
// IndexSpan shrink(original, shrinkBegin, shrinkEnd);
// --------------------------------------------------------------------
if (verbose) cout << "\nTESTING SHRINK"
"\n==============\n";
static struct TestData {
long long d_line;
bsl::size_t d_pos;
bsl::size_t d_len;
bsl::size_t d_beginShrink;
bsl::size_t d_endShrink;
char d_bad; // 'X' if the shrink is too big
bsl::size_t d_expectedPos;
bsl::size_t d_expectedLen;
} k_DATA[] = {
// pos len beg end bad pos len
// --- --- --- --- ---- --- ---
{ L_, 0, 0, 0, 0, ' ', 0, 0 },
{ L_, 0, 0, 1, 0, 'X', 0, 0 },
{ L_, 0, 0, 0, 1, 'X', 0, 0 },
{ L_, 0, 0, 1, 1, 'X', 0, 0 },
{ L_, 0, 1, 1, 0, ' ', 1, 0 },
{ L_, 0, 1, 0, 1, ' ', 0, 0 },
{ L_, 0, 2, 1, 0, ' ', 1, 1 },
{ L_, 0, 2, 0, 1, ' ', 0, 1 },
{ L_, 1, 1, 1, 0, ' ', 2, 0 },
{ L_, 1, 1, 0, 1, ' ', 1, 0 },
};
static const bsl::size_t k_NUM_TESTS = sizeof k_DATA / sizeof *k_DATA;
for (bsl::size_t i = 0; i < k_NUM_TESTS; ++i) {
const TestData& k_TEST = k_DATA[i];
const long long k_LINE = k_TEST.d_line;
const bsl::size_t k_POS = k_TEST.d_pos;
const bsl::size_t k_LEN = k_TEST.d_len;
const bsl::size_t k_BEGIN_SHRINK = k_TEST.d_beginShrink;
const bsl::size_t k_END_SHRINK = k_TEST.d_endShrink;
const char k_BAD = k_TEST.d_bad;
const bsl::size_t k_EXPECTED_POS = k_TEST.d_expectedPos;
const bsl::size_t k_EXPECTED_LEN = k_TEST.d_expectedLen;
if (veryVerbose) {
P_(k_LINE) P_(k_POS) P_(k_LEN)
P_(k_BEGIN_SHRINK) P(k_END_SHRINK)
}
if ('X' != k_BAD) {
const bdlb::IndexSpan X(k_POS, k_LEN);
const bdlb::IndexSpan R = Util::shrink(X,
k_BEGIN_SHRINK,
k_END_SHRINK);
ASSERTV(k_LINE, R.position(), k_EXPECTED_POS,
k_EXPECTED_POS == R.position());
ASSERTV(k_LINE, R.length(), k_EXPECTED_LEN,
k_EXPECTED_LEN == R.length());
}
else {
#ifdef BDE_BUILD_TARGET_EXC
bsls::AssertTestHandlerGuard g; (void)g;
const bdlb::IndexSpan X(k_POS, k_LEN);
ASSERT_FAIL(Util::shrink(X, k_BEGIN_SHRINK, k_END_SHRINK));
#endif
}
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//: 1 Call the utility functions to verify their existence and basics.
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) cout << "\nBREATHING TEST"
"\n==============\n";
const bdlb::IndexSpan span(1, 2);
ASSERT(bdlb::IndexSpan(2, 0) == Util::shrink(span, 1, 1));
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
} break;
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 38.771186 | 79 | 0.485173 |
8789af36f68930966569f8a4ba7668be18f31c53 | 1,601 | cpp | C++ | src/main.cpp | JOwens-RTT/Teensy_Debugger | c7ced1f70913be8ea379740de78d9d6e29df9590 | [
"MIT"
] | null | null | null | src/main.cpp | JOwens-RTT/Teensy_Debugger | c7ced1f70913be8ea379740de78d9d6e29df9590 | [
"MIT"
] | null | null | null | src/main.cpp | JOwens-RTT/Teensy_Debugger | c7ced1f70913be8ea379740de78d9d6e29df9590 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <string>
#include <Metro.h>
//#define DEBUG
#define LED_PIN 13
#define COMPUTER Serial
#define DUT Serial7
//Metro dutTimeout(100);
//Metro compTimeout(100);
Metro ledTimer(250);
bool ledEnable = false;
bool ledStatus = true;
#if defined(DEBUG)
void debugPrintout();
Metro debugTimer(100);
#endif
void setup() {
COMPUTER.begin(115200);
DUT.begin(115200);
delay(200);
COMPUTER.println(" --- DEBUG START --- ");
pinMode(LED_PIN, OUTPUT);
delay(200);
digitalWrite(LED_PIN, LOW);
}
void loop() {
//COMPUTER.println("IN MAIN LOOP.");
// Transfer DUT msg to COMPUTER
if(DUT.available() > 0){
// enable LED Blink
ledEnable = true;
// read the string
char msg = DUT.read();
// pass on the msg
COMPUTER.print((char)F(msg));
}
if(COMPUTER.available() > 0){
// enable LED Blink
ledEnable = true;
// read the string
char msg = COMPUTER.read();
// pass on the msg
DUT.print((char)F(msg));
}
ledStatus = true;
if(ledTimer.check() && ledEnable){
//COMPUTER.println("BLINKING LED");
ledStatus = digitalRead(LED_PIN);
digitalWrite(LED_PIN, !ledStatus);
ledEnable = false;
}
ledEnable = ledEnable || !ledStatus;
#if defined(DEBUG)
if(debugTimer.check()) debugPrintout();
#endif
}
#if defined(DEBUG)
void debugPrintout() {
COMPUTER.println("\n\n=== DEBUG ===\n");
COMPUTER.print("LED Blink Enable: ");
COMPUTER.println(ledEnable);
COMPUTER.print("LED STATUS: ");
COMPUTER.println(ledStatus);
COMPUTER.println("\n === END DEBUG === \n");
}
#endif | 18.616279 | 46 | 0.640225 |
878a5b9179b13aeab45163038d767f436d87e349 | 2,140 | cpp | C++ | Algorithms Design and Analysis II/knapsack.cpp | cbrghostrider/Coursera | 0b509adb57f2e96e0d7b4119d50cdf2e555abafe | [
"MIT"
] | null | null | null | Algorithms Design and Analysis II/knapsack.cpp | cbrghostrider/Coursera | 0b509adb57f2e96e0d7b4119d50cdf2e555abafe | [
"MIT"
] | null | null | null | Algorithms Design and Analysis II/knapsack.cpp | cbrghostrider/Coursera | 0b509adb57f2e96e0d7b4119d50cdf2e555abafe | [
"MIT"
] | null | null | null | // -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
#include <iostream>
#include <cstdio>
#include <vector>
struct Item {
unsigned long long value;
unsigned long long weight;
Item (unsigned long long v, unsigned long long w) : value(v), weight(w) {}
};
void readProblem (std::vector<Item>& items, unsigned long long& wt)
{
unsigned int number;
std::cin >> wt >> number;
for (unsigned int i=0;i<number; i++) {
unsigned long long value=0, weight=0;
std::cin >> value >> weight;
items.push_back(Item(value, weight));
}
}
unsigned long long solveProblem (const std::vector<Item>& items, unsigned long long weight)
{
unsigned long long ** arr = new unsigned long long*[2];
arr[0] = new unsigned long long[weight];
arr[1] = new unsigned long long[weight];
for (unsigned int w=0; w<weight+1; w++) {
arr[0][w] = 0;
}
unsigned int last_iter = 0;
unsigned int this_iter = 1;
for (unsigned int i=1; i<items.size()+1; i++) {
for (unsigned int w=0; w<weight+1; w++) {
unsigned int ci = i-1;
unsigned long long opt1 = arr[last_iter][w];
unsigned long long opt2 = (w < items[ci].weight ) ? 0 : arr[last_iter][w-items[ci].weight] + items[ci].value;
arr[this_iter][w] = opt1 > opt2 ? opt1 : opt2;
}
last_iter = 1 - last_iter;
this_iter = 1 - this_iter;
}
unsigned long long ret = arr[last_iter][weight];
delete [] arr[1];
delete [] arr[0];
delete [] arr;
return ret;
}
int main()
{
std::vector<Item> items;
unsigned long long weight=0;
readProblem(items, weight);
unsigned long long answer = solveProblem(items, weight);
std::cout << "Answer = " << answer << std::endl;
}
| 30.571429 | 121 | 0.55 |
878abcf148a3850557bb810a51b4c8dc7ddef060 | 2,372 | cpp | C++ | src/main.cpp | mystery124/MilestoneRoomController | 1101c110f25d1cc348cf7da304dd9fe5d33a5876 | [
"MIT"
] | null | null | null | src/main.cpp | mystery124/MilestoneRoomController | 1101c110f25d1cc348cf7da304dd9fe5d33a5876 | [
"MIT"
] | 7 | 2020-03-23T17:48:57.000Z | 2020-04-21T19:48:20.000Z | src/main.cpp | mystery124/MilestoneRoomController | 1101c110f25d1cc348cf7da304dd9fe5d33a5876 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <Ticker.h>
#define LOGGING_SERIAL
#include "Logger.h"
#include "WifiManager.h"
#include "BME280Sensor.h"
/*
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
//local
#include <OTAHandler.h>
#define SEALEVELPRESSURE_HPA (1013.25)
OTAHandler otaHandler;
ESP8266WebServer server(80);
Adafruit_BME280 bme;
// hold uploaded file
File fsUploadFile;
void handleFileUpload(){
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START)
{
String filename = upload.filename;
if(!filename.startsWith("/"))
filename = "/d/"+filename;
Serial.print("handleFileUpload Name: "); Serial.println(filename);
fsUploadFile = SPIFFS.open(filename, "w+");
} else if(upload.status == UPLOAD_FILE_WRITE)
{
if(fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END)
{
if(fsUploadFile)
fsUploadFile.close();
Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
}
}
*/
void pinOn();
void readSensorAndPrint();
void goToSleep();
WiFiManagment::WifiManager wifiService;
Sensors::BME280Sensor bmeSensor;
bool sendFlag = false;
Ticker tick;
void setup(){
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
LOGGER
bmeSensor.init();
LOG("Start WIFI");
wifiService.attachConnectionHandler(pinOn);
wifiService.attachConnectionHandler(readSensorAndPrint);
wifiService.startWifi();
LOG("config WIFI done");
tick.attach(30, goToSleep);
}
void loop(){
wifiService.handleClient();
//otaHandler.handleOTA();
//server.handleClient();
LOGGER;
if(sendFlag){
goToSleep();
}
}
void goToSleep(){
int val = 60;
LOG("Going Sleep");
ESP.deepSleep(val*1000*1000);
}
void readSensorAndPrint(){
LOGGER;
bmeSensor.setMode(Adafruit_BME280::MODE_NORMAL);
Sensors::BME20SensorData data = bmeSensor.read();
bmeSensor.setMode(Adafruit_BME280::MODE_SLEEP);
LOG("Temp: ");
LOG(data.temperature);
LOG("Humidity: ");
LOG(data.humidity);
LOG("Pressure: ");
LOG(data.pressure);
sendFlag = true;
};
void pinOn(){
digitalWrite(LED_BUILTIN, LOW);
}; | 20.448276 | 82 | 0.673693 |
878dfa2d8a0a9c3551d0a33681169ff2e5e67e79 | 311 | cpp | C++ | solutions/1550. Three Consecutive Odds.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | 1 | 2020-09-27T17:36:58.000Z | 2020-09-27T17:36:58.000Z | solutions/1550. Three Consecutive Odds.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | null | null | null | solutions/1550. Three Consecutive Odds.cpp | MayThirtyOne/Practice-Problems | fe945742d6bc785fffcb29ce011251406ba7c695 | [
"MIT"
] | 1 | 2020-09-21T15:16:24.000Z | 2020-09-21T15:16:24.000Z | class Solution {
public:
bool threeConsecutiveOdds(vector<int>& arr) {
if(arr.size()<3) return false;
for(int i=0;i<arr.size()-2;i++){
if(arr[i]%2==1 && arr[i+1]%2==1 && arr[i+2]%2==1){
return true;
}
}
return false;
}
};
| 22.214286 | 62 | 0.440514 |
878e3776a8d736c0b3088de2e71b503a645511ae | 1,652 | cpp | C++ | examples/matrices/Walsh.cpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 473 | 2015-01-11T03:22:11.000Z | 2022-03-31T05:28:39.000Z | examples/matrices/Walsh.cpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 205 | 2015-01-10T20:33:45.000Z | 2021-07-25T14:53:25.000Z | examples/matrices/Walsh.cpp | pjt1988/Elemental | 71d3e2b98829594e9f52980a8b1ef7c1e99c724b | [
"Apache-2.0"
] | 109 | 2015-02-16T14:06:42.000Z | 2022-03-23T21:34:26.000Z | /*
Copyright (c) 2009-2016, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include <El.hpp>
int
main( int argc, char* argv[] )
{
El::Environment env( argc, argv );
El::mpi::Comm comm = El::mpi::COMM_WORLD;
try
{
const El::Int k = El::Input("--order","generate 2^k x 2^k matrix",4);
const bool binary = El::Input("--binary","binary data?",false);
const bool display = El::Input("--display","display matrix?",false);
const bool print = El::Input("--print","print matrix?",true);
El::ProcessInput();
El::PrintInputReport();
const El::Grid grid( comm );
// Generate a Walsh matrix of order k (a 2^k x 2^k matrix)
El::DistMatrix<double> W(grid);
El::Walsh( W, k, binary );
if( display )
El::Display( W, "Walsh matrix" );
if( print )
El::Print( W, "W(2^k)");
if( !binary )
{
El::LDL( W, true );
auto d = El::GetDiagonal(W);
El::MakeTrapezoidal( El::LOWER, W );
El::FillDiagonal( W, 1. );
if( display )
{
El::Display( W, "Lower factor" );
El::Display( d, "Diagonal factor" );
}
if( print )
{
El::Print( W, "L" );
El::Print( d, "d" );
}
}
}
catch( std::exception& e ) { El::ReportException(e); }
return 0;
}
| 28 | 77 | 0.502421 |
8791dc97f1c0913b534a4bd6811d48e963ade9d0 | 264 | cc | C++ | construct-the-rectangle.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | construct-the-rectangle.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | construct-the-rectangle.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <vector>
#include <cmath>
class Solution
{
public:
std::vector<int> constructRectangle(int area)
{
for (int i = std::sqrt(area); i >= 1; i--)
if (area % i == 0)
return {area / i, i};
return {};
}
}; | 18.857143 | 50 | 0.484848 |
8795e7062a08e8ba4e21ec9886cc1e776040e0b9 | 6,251 | cpp | C++ | unzipdirs.cpp | yk-szk/szkzip | 042227351539fc6d2c1937cc97cb3177c659dbd0 | [
"MIT"
] | null | null | null | unzipdirs.cpp | yk-szk/szkzip | 042227351539fc6d2c1937cc97cb3177c659dbd0 | [
"MIT"
] | 1 | 2022-01-20T01:23:39.000Z | 2022-01-20T01:23:39.000Z | unzipdirs.cpp | yk-szk/szkzip | 042227351539fc6d2c1937cc97cb3177c659dbd0 | [
"MIT"
] | null | null | null | #include <filesystem>
#include <iostream>
#include <vector>
#include <numeric>
#include <thread>
#include <exception>
#include <mz.h>
#include <mz_os.h>
#include <mz_strm.h>
#include <mz_strm_os.h>
#include <mz_zip.h>
#include <mz_zip_rw.h>
#include <tclap/CmdLine.h>
#include <indicators/progress_bar.hpp>
#include <config.h>
#include "szkarc.h"
namespace fs = std::filesystem;
using std::cout;
using std::cerr;
using std::endl;
using std::flush;
void unzip(const fs::path& input, const fs::path& output)
{
void* zip_reader;
void* file_stream;
mz_zip_reader_create(&zip_reader);
mz_stream_os_create(&file_stream);
int32_t err = stream_os_open(file_stream, input, MZ_OPEN_MODE_READ);
if (err != MZ_OK) {
throw std::runtime_error("Failed to open a zip file:" + input.string());
}
err = mz_zip_reader_open(zip_reader, file_stream);
if (err != MZ_OK) {
throw std::runtime_error("Failed to open a zip file:" + input.string());
}
#ifdef _WIN32
auto utf8 = wstr2utf8(output.wstring());
mz_zip_reader_save_all(zip_reader, utf8.c_str());
#else
mz_zip_reader_save_all(zip_reader, output.c_str());
#endif
err = mz_zip_reader_close(zip_reader);
if (err != MZ_OK) {
throw std::runtime_error("Failed to close a zip file:" + input.string());
}
err = mz_stream_os_close(file_stream);
if (err != MZ_OK) {
throw std::runtime_error("Failed to close a zip file:" + input.string());
}
mz_stream_os_delete(&file_stream);
mz_zip_reader_delete(&zip_reader);
}
using PathList = std::vector<fs::path>;
PathList list_zipfiles(const fs::path& indir, int depth) {
PathList list;
if (depth > 0) {
for (const auto& ent : fs::directory_iterator(indir)) {
if (ent.is_directory()) {
list.emplace_back(ent.path());
}
}
std::sort(list.begin(), list.end());
std::vector<PathList> nested;
std::transform(list.cbegin(), list.cend(), std::back_inserter(nested), [depth](const fs::path& p) {
return list_zipfiles(p, depth - 1);
});
auto flat = flatten_nested(nested);
return flat;
}
else {
for (const auto& ent : fs::directory_iterator(indir)) {
if (ent.path().extension()==".zip") {
list.emplace_back(ent.path());
}
}
std::sort(list.begin(), list.end());
return list;
}
}
fs::path input2output(const fs::path &input_dir, const fs::path &output_dir, const fs::path &input) {
auto relative = input.lexically_relative(input_dir);
return (output_dir / relative.replace_extension("")).string();
}
int main(int argc, char* argv[])
{
try {
TCLAP::CmdLine cmd("Unzip all zip files in the input directory. version: " PROJECT_VERSION, ' ', PROJECT_VERSION);
TCLAP::UnlabeledValueArg<std::string> a_input("input", "Input directory", true, "", "input", cmd);
TCLAP::UnlabeledValueArg<std::string> a_output("output", "(optional) Output directory. <input> is used as <output> by default.", false, "", "output", cmd);
TCLAP::ValueArg<int> a_depth("d", "depth", "(optional) Depth of the subdirectories.", false, 0, "int", cmd);
TCLAP::ValueArg<int> a_jobs("j", "jobs", "(optional) Number of simultaneous jobs.", false, 0, "int", cmd);
TCLAP::SwitchArg a_skip_exists("", "skip_existing", "Dont't unzip when the output directory exists.", cmd);
TCLAP::SwitchArg a_dryrun("", "dryrun", "List zip files to unzip and exit.", cmd);
cmd.parse(argc, argv);
auto input_dir = fs::path(a_input.getValue());
auto output_dir = fs::path(a_output.isSet() ? a_output.getValue() : a_input.getValue());
auto depth = a_depth.getValue();
auto jobs = a_jobs.getValue();
auto zipfiles = list_zipfiles(input_dir, depth);
if (a_skip_exists.isSet()) {
auto result = std::remove_if(zipfiles.begin(), zipfiles.end(), [&input_dir, &output_dir](auto& zf) {
auto output = input2output(input_dir, output_dir, zf);
return fs::exists(output);
});
auto orig_size = zipfiles.size();
zipfiles.erase(result, zipfiles.end());
cout << "Skip " << orig_size - zipfiles.size() << " existing entries." << endl;
}
if (zipfiles.empty()) {
cout << "There is nothing to decompress." << endl;
return 0;
}
if (a_dryrun.isSet()) {
for (const auto& zf : zipfiles) {
auto output = input2output(input_dir, output_dir, zf);
cout << zf.string() << " -> " << output << '\n';
}
cout << flush;
return 0;
}
using namespace indicators;
ProgressBar bar{
option::BarWidth{30},
option::MaxProgress(zipfiles.size()),
option::Start{"["},
option::Fill{"="},
option::Lead{">"},
option::Remainder{" "},
option::End{"]"},
option::PrefixText{"Decompressing"},
option::ShowElapsedTime{true},
option::ShowRemainingTime{true},
};
if (jobs <= 0) {
jobs = get_physical_core_counts();
cout << "Using " << jobs << " CPU cores." << endl;
}
std::exception_ptr ep;
std::mutex mtx_mkdir;
std::vector<std::thread> threads;
threads.reserve(jobs);
for (int job_id = 0; job_id < jobs; ++job_id) {
threads.emplace_back([job_id, jobs, &zipfiles, &input_dir, &output_dir, &bar, &mtx_mkdir, &ep]() {
for (int i = job_id; i < zipfiles.size(); i += jobs) {
const auto& zipfile = zipfiles[i];
auto output = input2output(input_dir, output_dir, zipfile);
{
std::lock_guard<std::mutex> lock(mtx_mkdir);
if (!fs::exists(output.parent_path())) {
fs::create_directories(output.parent_path());
}
}
try {
unzip(zipfile, output);
}
catch (...) {
ep = std::current_exception();
break;
}
bar.tick();
}
});
}
for (auto& t : threads) {
t.join();
}
if (ep) {
std::rethrow_exception(ep);
}
}
catch (TCLAP::ArgException& e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
catch (std::exception& e) {
cerr << e.what() << endl;
return 1;
}
catch (const std::string& e) {
cerr << e << endl;
return 1;
}
return 0;
}
| 31.892857 | 159 | 0.610622 |
87999efbe681268cd7a72ca49fd41f6ead2cd9e6 | 2,542 | cxx | C++ | Modules/ThirdParty/GDCM/src/gdcm/Source/MediaStorageAndFileFormat/gdcmUUIDGenerator.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 3 | 2018-10-01T20:46:17.000Z | 2019-12-17T19:39:50.000Z | Modules/ThirdParty/GDCM/src/gdcm/Source/MediaStorageAndFileFormat/gdcmUUIDGenerator.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/GDCM/src/gdcm/Source/MediaStorageAndFileFormat/gdcmUUIDGenerator.cxx | nalinimsingh/ITK_4D | 95a2eacaeaffe572889832ef0894239f89e3f303 | [
"Apache-2.0"
] | 4 | 2018-05-17T16:34:54.000Z | 2020-09-24T02:12:40.000Z | /*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 Mathieu Malaterre
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "gdcmUUIDGenerator.h"
#include "gdcmTrace.h"
#include "gdcmSystem.h"
#include <cstring> // memcpy
// FIXME...
#if defined(_WIN32) || defined(__CYGWIN__)
#define HAVE_UUIDCREATE
#else
#define HAVE_UUID_GENERATE
#endif
#ifdef HAVE_UUID_GENERATE
#include "gdcm_uuid.h"
#endif
#ifdef GDCM_HAVE_RPC_H
#include <rpc.h>
#endif
namespace gdcm
{
const char* UUIDGenerator::Generate()
{
Unique.resize( 36 );
char *uuid_data = &Unique[0];
#if defined(HAVE_UUID_GENERATE)
assert( sizeof(uuid_t) == 16 );
uuid_t g;
uuid_generate(g);
uuid_unparse(g, uuid_data);
#elif defined(HAVE_UUID_CREATE)
uint32_t rv;
uuid_t g;
uuid_create(&g, &rv);
if (rv != uuid_s_ok) return NULL;
uuid_to_string(&g, &uuid_data, &rv);
if (rv != uuid_s_ok) return NULL;
#elif defined(HAVE_UUIDCREATE)
UUID uuid;
UuidCreate(&uuid);
BYTE * str = 0;
UuidToString(&uuid, &str);
Unique = (char*)str;
RpcStringFree(&str);
#else
#error should not happen
#endif
assert( IsValid( Unique.c_str() ) );
return Unique.c_str();
}
bool UUIDGenerator::IsValid(const char *suid)
{
if( !suid ) return false;
#if defined(HAVE_UUID_GENERATE)
uuid_t uu;
// technically the specification wants char* input not const char*:
// this makes compilation fails otherwise on OpenIndiana:
int res = uuid_parse((char*)suid, uu);
if( res ) return false;
#elif defined(HAVE_UUID_CREATE)
// http://www.freebsd.org/cgi/man.cgi?query=uuid_create
uint32_t status;
uuid_t uuid;
uuid_from_string(suid, &uuid, &status);
if( status != uuid_s_ok ) return false;
#elif defined(HAVE_UUIDCREATE)
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379336(v=vs.85).aspx
UUID uuid;
if (FAILED(UuidFromString((unsigned char*)suid, &uuid)))
{
return false;
}
#else
#error should not happen
#endif
// no error found !
return true;
}
} // end namespace gdcm
| 25.42 | 84 | 0.643588 |
879b1cf03bb04a7572a7dc1a8fdf103e28db55be | 16,426 | cpp | C++ | src/xmol/io/pdb/BundledPDBRecordTypesBaseInit.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 4 | 2020-06-24T11:07:57.000Z | 2022-01-15T23:00:30.000Z | src/xmol/io/pdb/BundledPDBRecordTypesBaseInit.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 84 | 2018-04-22T12:29:31.000Z | 2020-06-17T15:03:37.000Z | src/xmol/io/pdb/BundledPDBRecordTypesBaseInit.cpp | sizmailov/pyxmolpp2 | 9395ba1b1ddc957e0b33dc6decccdb711e720764 | [
"MIT"
] | 6 | 2018-06-04T09:16:26.000Z | 2022-03-12T11:05:54.000Z | #include "xmol/io/pdb/PdbRecord.h"
using namespace xmol::io::pdb;
std::map<RecordName,PdbRecordType> detail::get_bundled_records() {
auto as_field = [](const std::string& fieldName, std::vector<int> colons){
auto shortend = fieldName.substr(0,std::min(size_t(FieldName::max_length),fieldName.size()));
return std::make_pair(FieldName(shortend),std::move(colons));
};
auto as_record = [](const char* recordName, std::map<FieldName,std::vector<int>> fields){
return std::pair<RecordName,PdbRecordType>(RecordName(recordName),PdbRecordType(std::move(fields)));
};
std::map<RecordName,PdbRecordType> result {
as_record("ANISOU",{
as_field("serial",{7,11}),
as_field("name",{13,16}),
as_field("altLoc",{17,17}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
as_field("u[0][0]",{29,35}),
as_field("u[1][1]",{36,42}),
as_field("u[2][2]",{43,49}),
as_field("u[0][1]",{50,56}),
as_field("u[0][2]",{57,63}),
as_field("u[1][2]",{64,70}),
as_field("element",{77,78}),
as_field("charge",{79,80}),
}), // ANISOU
as_record("ATOM",{
as_field("serial",{7,11}),
as_field("name",{13,16}),
as_field("altLoc",{17,17}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
as_field("x",{31,38}),
as_field("y",{39,46}),
as_field("z",{47,54}),
as_field("occupancy",{55,60}),
as_field("tempFactor",{61,66}),
as_field("element",{77,78}),
as_field("charge",{79,80}),
}), // ATOM
as_record("AUTHOR",{
as_field("continuation",{9,10}),
as_field("authorList",{11,79}),
}), // AUTHOR
as_record("CAVEAT",{
as_field("continuation",{9,10}),
as_field("idCode",{12,15}),
as_field("comment",{20,79}),
}), // CAVEAT
as_record("CISPEP",{
as_field("serNum",{8,10}),
as_field("pep1",{12,14}),
as_field("chainID1",{16,16}),
as_field("seqNum1",{18,21}),
as_field("icode1",{22,22}),
as_field("pep2",{26,28}),
as_field("chainID2",{30,30}),
as_field("seqNum2",{32,35}),
as_field("icode2",{36,36}),
as_field("modNum",{44,46}),
as_field("measure",{54,59}),
}), // CISPEP
as_record("COMPND",{
as_field("continuation",{8,10}),
as_field("compound",{11,80}),
}), // COMPND
as_record("CONECT",{
as_field("serial",{7,11,12,16,17,21,22,26,27,31}),
}), // CONECT
as_record("CRYST1",{
as_field("a",{7,15}),
as_field("b",{16,24}),
as_field("c",{25,33}),
as_field("alpha",{34,40}),
as_field("beta",{41,47}),
as_field("gamma",{48,54}),
as_field("sGroup",{56,66}),
as_field("z",{67,70}),
}), // CRYST1
as_record("DBREF",{
as_field("idCode",{8,11}),
as_field("chainID",{13,13}),
as_field("seqBegin",{15,18}),
as_field("insertBegin",{19,19}),
as_field("seqEnd",{21,24}),
as_field("insertEnd",{25,25}),
as_field("database",{27,32}),
as_field("dbAccession",{34,41}),
as_field("dbIdCode",{43,54}),
as_field("dbseqBegin",{56,60}),
as_field("idbnsBeg",{61,61}),
as_field("dbseqEnd",{63,67}),
as_field("dbinsEnd",{68,68}),
}), // DBREF
as_record("DBREF1",{
as_field("idCode",{8,11}),
as_field("chainID",{13,13}),
as_field("seqBegin",{15,18}),
as_field("insertBegin",{19,19}),
as_field("seqEnd",{21,24}),
as_field("insertEnd",{25,25}),
as_field("database",{27,32}),
as_field("dbIdCode",{48,67}),
}), // DBREF1
as_record("DBREF2",{
as_field("idCode",{8,11}),
as_field("chainID",{13,13}),
as_field("dbAccession",{19,40}),
as_field("seqBegin",{46,55}),
as_field("seqEnd",{58,67}),
}), // DBREF2
as_record("END",{
}), // END
as_record("ENDMDL",{
}), // ENDMDL
as_record("EXPDTA",{
as_field("continuation",{9,10}),
as_field("technique",{11,79}),
}), // EXPDTA
as_record("FORMUL",{
as_field("compNum",{9,10}),
as_field("hetID",{13,15}),
as_field("continuation",{17,18}),
as_field("asterisk",{19,19}),
as_field("text",{20,70}),
}), // FORMUL
as_record("HEADER",{
as_field("classification",{11,50}),
as_field("depDate",{51,59}),
as_field("idCode",{63,66}),
}), // HEADER
as_record("HELIX",{
as_field("serNum",{8,10}),
as_field("helixID",{12,14}),
as_field("initResName",{16,18}),
as_field("initChainID",{20,20}),
as_field("initSeqNum",{22,25}),
as_field("initICode",{26,26}),
as_field("endResName",{28,30}),
as_field("endChainID",{32,32}),
as_field("endSeqNum",{34,37}),
as_field("endICode",{38,38}),
as_field("helixClass",{39,40}),
as_field("comment",{41,70}),
as_field("length",{72,76}),
}), // HELIX
as_record("HET",{
as_field("hetID",{8,10}),
as_field("ChainID",{13,13}),
as_field("seqNum",{14,17}),
as_field("iCode",{18,18}),
as_field("numHetAtoms",{21,25}),
as_field("text",{31,70}),
}), // HET
as_record("HETATM",{
as_field("serial",{7,11}),
as_field("name",{13,16}),
as_field("altLoc",{17,17}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
as_field("x",{31,38}),
as_field("y",{39,46}),
as_field("z",{47,54}),
as_field("occupancy",{55,60}),
as_field("tempFactor",{61,66}),
as_field("element",{77,78}),
as_field("charge",{79,80}),
}), // HETATM
as_record("HETNAM",{
as_field("continuation",{9,10}),
as_field("hetID",{12,14}),
as_field("text",{16,70}),
}), // HETNAM
as_record("HETSYN",{
as_field("continuation",{9,10}),
as_field("hetID",{12,14}),
as_field("hetSynonyms",{16,70}),
}), // HETSYN
as_record("JRNL",{
as_field("text",{13,79}),
}), // JRNL
as_record("KEYWDS",{
as_field("continuation",{9,10}),
as_field("keywds",{11,79}),
}), // KEYWDS
as_record("LINK",{
as_field("name1",{13,16}),
as_field("altLoc1",{17,17}),
as_field("resName1",{18,20}),
as_field("chainID1",{22,22}),
as_field("resSeq1",{23,26}),
as_field("iCode1",{27,27}),
as_field("name2",{43,46}),
as_field("altLoc2",{47,47}),
as_field("resName2",{48,50}),
as_field("chainID2",{52,52}),
as_field("resSeq2",{53,56}),
as_field("iCode2",{57,57}),
as_field("sym1",{60,65}),
as_field("sym2",{67,72}),
as_field("Length",{74,78}),
}), // LINK
as_record("MASTER",{
as_field("numRemark",{11,15}),
as_field("0",{16,20}),
as_field("numHet",{21,25}),
as_field("numHelix",{26,30}),
as_field("numSheet",{31,35}),
as_field("numTurn",{36,40}),
as_field("numSite",{41,45}),
as_field("numXform",{46,50}),
as_field("numCoord",{51,55}),
as_field("numTer",{56,60}),
as_field("numConect",{61,65}),
as_field("numSeq",{66,70}),
}), // MASTER
as_record("MDLTYP",{
as_field("continuation",{9,10}),
as_field("comment",{11,80}),
}), // MDLTYP
as_record("MODEL",{
as_field("serial",{11,14}),
}), // MODEL
as_record("MODRES",{
as_field("idCode",{8,11}),
as_field("resName",{13,15}),
as_field("chainID",{17,17}),
as_field("seqNum",{19,22}),
as_field("iCode",{23,23}),
as_field("stdRes",{25,27}),
as_field("comment",{30,70}),
}), // MODRES
as_record("MTRIX1",{
as_field("serial",{8,10}),
as_field("m[1][1]",{11,20}),
as_field("m[1][2]",{21,30}),
as_field("m[1][3]",{31,40}),
as_field("v[1]",{46,55}),
as_field("iGiven",{60,60}),
}), // MTRIX1
as_record("MTRIX2",{
as_field("serial",{8,10}),
as_field("m[2][1]",{11,20}),
as_field("m[2][2]",{21,30}),
as_field("m[2][3]",{31,40}),
as_field("v[2]",{46,55}),
as_field("iGiven",{60,60}),
}), // MTRIX2
as_record("MTRIX3",{
as_field("serial",{8,10}),
as_field("m[3][1]",{11,20}),
as_field("m[3][2]",{21,30}),
as_field("m[3][3]",{31,40}),
as_field("v[3]",{46,55}),
as_field("iGiven",{60,60}),
}), // MTRIX3
as_record("NUMMDL",{
as_field("modelNumber",{11,14}),
}), // NUMMDL
as_record("OBSLTE",{
as_field("continuation",{9,10}),
as_field("repDate",{12,20}),
as_field("idCode",{22,25}),
as_field("rIdCode",{32,35,37,40,42,45,47,50,52,55,57,60,62,65,67,70,72,75}),
}), // OBSLTE
as_record("ORIGX1",{
as_field("o[1][1]",{11,20}),
as_field("o[1][2]",{21,30}),
as_field("o[1][3]",{31,40}),
as_field("t[1]",{46,55}),
}), // ORIGX1
as_record("ORIGX2",{
as_field("o[2][1]",{11,20}),
as_field("o[2][2]",{21,30}),
as_field("o[2][3]",{31,40}),
as_field("t[2]",{46,55}),
}), // ORIGX2
as_record("ORIGX3",{
as_field("o[3][1]",{11,20}),
as_field("o[3][2]",{21,30}),
as_field("o[3][3]",{31,40}),
as_field("t[3]",{46,55}),
}), // ORIGX3
as_record("REMARK",{
as_field("remarkNum",{8,10}),
as_field("empty",{12,79}),
}), // REMARK
as_record("REVDAT",{
as_field("modNum",{8,10}),
as_field("continuation",{11,12}),
as_field("modDate",{14,22}),
as_field("modId",{24,27}),
as_field("modType",{32,32}),
as_field("record",{40,45,47,52,54,59,61,66}),
}), // REVDAT
as_record("SCALE1",{
as_field("s[1][1]",{11,20}),
as_field("s[1][2]",{21,30}),
as_field("s[1][3]",{31,40}),
as_field("u[1]",{46,55}),
}), // SCALE1
as_record("SCALE2",{
as_field("s[2][1]",{11,20}),
as_field("s[2][2]",{21,30}),
as_field("s[2][3]",{31,40}),
as_field("u[2]",{46,55}),
}), // SCALE2
as_record("SCALE3",{
as_field("s[3][1]",{11,20}),
as_field("s[3][2]",{21,30}),
as_field("s[3][3]",{31,40}),
as_field("u[3]",{46,55}),
}), // SCALE3
as_record("SEQADV",{
as_field("idCode",{8,11}),
as_field("resName",{13,15}),
as_field("chainID",{17,17}),
as_field("seqNum",{19,22}),
as_field("iCode",{23,23}),
as_field("database",{25,28}),
as_field("dbAccession",{30,38}),
as_field("dbRes",{40,42}),
as_field("dbSeq",{44,48}),
as_field("conflict",{50,70}),
}), // SEQADV
as_record("SEQRES",{
as_field("serNum",{8,10}),
as_field("chainID",{12,12}),
as_field("numRes",{14,17}),
as_field("resName",{20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70}),
}), // SEQRES
as_record("SHEET",{
as_field("strand",{8,10}),
as_field("sheetID",{12,14}),
as_field("numStrands",{15,16}),
as_field("initResName",{18,20}),
as_field("initChainID",{22,22}),
as_field("initSeqNum",{23,26}),
as_field("initICode",{27,27}),
as_field("endResName",{29,31}),
as_field("endChainID",{33,33}),
as_field("endSeqNum",{34,37}),
as_field("endICode",{38,38}),
as_field("sense",{39,40}),
as_field("curAtom",{42,45}),
as_field("curResName",{46,48}),
as_field("curChainId",{50,50}),
as_field("curResSeq",{51,54}),
as_field("curICode",{55,55}),
as_field("prevAtom",{57,60}),
as_field("prevResName",{61,63}),
as_field("prevChainId",{65,65}),
as_field("prevResSeq",{66,69}),
as_field("prevICode",{70,70}),
}), // SHEET
as_record("SIGATM",{
as_field("serial",{7,11}),
as_field("name",{13,16}),
as_field("altLoc",{17,17}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
as_field("sigX",{31,38}),
as_field("sigY",{39,46}),
as_field("sigZ",{47,54}),
as_field("sigOcc",{55,60}),
as_field("sigTemp",{61,66}),
as_field("element",{77,78}),
as_field("charge",{79,80}),
}), // SIGATM
as_record("SIGUIJ",{
as_field("serial",{7,11}),
as_field("name",{13,16}),
as_field("altLoc",{17,17}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
as_field("sig[0][0]",{29,35}),
as_field("sig[1][1]",{36,42}),
as_field("sig[2][2]",{43,49}),
as_field("sig[0][1]",{50,56}),
as_field("sig[0][2]",{57,63}),
as_field("sig[1][2]",{64,70}),
as_field("element",{77,78}),
as_field("charge",{79,80}),
}), // SIGUIJ
as_record("SITE",{
as_field("seqNum",{8,10}),
as_field("siteID",{12,14}),
as_field("numRes",{16,17}),
as_field("resName1",{19,21}),
as_field("chainID1",{23,23}),
as_field("seq1",{24,27}),
as_field("iCode1",{28,28}),
as_field("resName2",{30,32}),
as_field("chainID2",{34,34}),
as_field("seq2",{35,38}),
as_field("iCode2",{39,39}),
as_field("resName3",{41,43}),
as_field("chainID3",{45,45}),
as_field("seq3",{46,49}),
as_field("iCode3",{50,50}),
as_field("resName4",{52,54}),
as_field("chainID4",{56,56}),
as_field("seq4",{57,60}),
as_field("iCode4",{61,61}),
}), // SITE
as_record("SOURCE",{
as_field("continuation",{8,10}),
as_field("srcName",{11,79}),
}), // SOURCE
as_record("SPLIT",{
as_field("continuation",{9,10}),
as_field("idCode",{12,15,17,20,22,25,27,30,32,35,37,40,42,45,47,50,52,55,57,60,62,65,67,70,72,75,77,80}),
}), // SPLIT
as_record("SPRSDE",{
as_field("continuation",{9,10}),
as_field("sprsdeDate",{12,20}),
as_field("idCode",{22,25}),
as_field("sIdCode",{32,35,37,40,42,45,47,50,52,55,57,60,62,65,67,70,72,75}),
}), // SPRSDE
as_record("SSBOND",{
as_field("serNum",{8,10}),
as_field("CYS",{26,28}),
as_field("chainID1",{16,16}),
as_field("seqNum1",{18,21}),
as_field("icode1",{22,22}),
as_field("chainID2",{30,30}),
as_field("seqNum2",{32,35}),
as_field("icode2",{36,36}),
as_field("sym1",{60,65}),
as_field("sym2",{67,72}),
as_field("Length",{74,78}),
}), // SSBOND
as_record("TER",{
as_field("serial",{7,11}),
as_field("resName",{18,20}),
as_field("chainID",{22,22}),
as_field("resSeq",{23,26}),
as_field("iCode",{27,27}),
}), // TER
as_record("TITLE",{
as_field("continuation",{9,10}),
as_field("title",{11,80}),
}), // TITLE
};
return result;
}
| 35.708696 | 115 | 0.479362 |
879c83b5fd1a9a0bb93c7d4ff07905c6adc1dcd2 | 672 | cpp | C++ | marsyas-vamp/marsyas/src/qt5apps/common/realvec_table_widget.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/qt5apps/common/realvec_table_widget.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/qt5apps/common/realvec_table_widget.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | #include "realvec_table_widget.h"
#include <QtAlgorithms>
#include <QKeyEvent>
#include <QApplication>
#include <QClipboard>
namespace MarsyasQt {
void RealvecTableWidget::keyPressEvent(QKeyEvent *event)
{
if (event == QKeySequence::Copy)
{
QModelIndexList selection = selectedIndexes();
qSort(selection);
QStringList strings;
foreach ( const QModelIndex & index, selection )
{
strings << model()->data(index, Qt::DisplayRole).toString();
}
QString text = strings.join(", ");
QApplication::clipboard()->setText(text);
return;
}
QTableView::keyPressEvent(event);
}
}
| 21.677419 | 72 | 0.635417 |
879f573b97bc57846b43a90f84ea7574c8208275 | 561 | cpp | C++ | codeforces/1385C.cpp | mhilmyh/algo-data-struct | 6a9b1e5220e3c4e4a41200a09cb27f3f55560693 | [
"MIT"
] | null | null | null | codeforces/1385C.cpp | mhilmyh/algo-data-struct | 6a9b1e5220e3c4e4a41200a09cb27f3f55560693 | [
"MIT"
] | null | null | null | codeforces/1385C.cpp | mhilmyh/algo-data-struct | 6a9b1e5220e3c4e4a41200a09cb27f3f55560693 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int solve(int n, vector<int> &a)
{
if (n == 1)
return 0;
bool asc = true;
int i;
for (i = n - 1; i > 0; i--)
{
if (asc && a[i] > a[i - 1])
asc = false;
else if (!asc && a[i] < a[i - 1])
break;
}
return i;
};
int main()
{
int t, n;
cin >> t;
while (t--)
{
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
cout << solve(n, a) << "\n";
}
return 0;
} | 15.583333 | 41 | 0.367201 |
87a4484cf38bc3b272462cb5a146491658546250 | 1,971 | hpp | C++ | board.hpp | Zilleplus/Cpp8Queen | 52adc77f6e657881eb1b9360c235b677b263dcfa | [
"MIT"
] | null | null | null | board.hpp | Zilleplus/Cpp8Queen | 52adc77f6e657881eb1b9360c235b677b263dcfa | [
"MIT"
] | null | null | null | board.hpp | Zilleplus/Cpp8Queen | 52adc77f6e657881eb1b9360c235b677b263dcfa | [
"MIT"
] | null | null | null | struct Queen {
int x;
int y;
};
bool hasHorizonalClash(const Queen& q1, const Queen& q2) {
return q1.y == q2.y;
}
bool hasVerticalClash(const Queen& q1, const Queen& q2) { return q1.x == q2.x; }
bool hasDiagonalClash(const Queen& q1, const Queen& q2) {
return (q1.x - q1.y) == (q1.x - q1.y) || (q1.x + q1.y) == (q1.x + q1.y);
}
int numberOfClashes(const Queen& q1, const Queen& q2) {
int numberOfClashes = 0;
if (hasHorizonalClash(q1, q2)) {
numberOfClashes++;
}
if (hasVerticalClash(q1, q2)) {
numberOfClashes++;
}
if (hasDiagonalClash(q1, q2)) {
numberOfClashes++;
}
return numberOfClashes;
}
template <typename TBoard, int size = TBoard::size>
int cost(TBoard& board) {
if (size < 2) return 0;
int cost = 0;
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
cost += numberOfClashes(board[i], board[j]);
}
}
return cost;
}
template <typename TBoard,
int sizeBoard = std::remove_reference_t<TBoard>::size>
bool hasQueen(TBoard&& board, int x, int y) {
for (int i = 0; i < sizeBoard; ++i) {
if (board[i].x == x && board[i].y == y) {
return true;
}
}
return false;
}
template <int sizeBoard>
class Board {
private:
Queen* queens;
public:
static constexpr int size = sizeBoard;
template <typename... Queens>
Board(Queens... qs) : queens{new Queen[]{qs...}} {
static_assert(sizeof...(Queens) == sizeBoard,
"Invalid number of queens in constructor");
}
Queen operator[](int index) const { return queens[index]; }
~Board() {
if (queens != nullptr) {
delete queens;
}
}
Board(Board&& b) : queens(b.queens) { b.queens = nullptr; }
void setQueen(int queenIndex, int newX, int newY) {
queens[queenIndex].x = newX;
queens[queenIndex].y = newY;
}
};
| 23.746988 | 80 | 0.559107 |
87a449e86ce31e79d5d47b50629b9ec2f6f62f4d | 4,934 | cpp | C++ | src/main.cpp | jonco3/dynamic | 76d10b012a7860595c7d9abbdf542c7d8f2a4d53 | [
"MIT"
] | 1 | 2020-11-26T23:37:19.000Z | 2020-11-26T23:37:19.000Z | src/main.cpp | jonco3/dynamic | 76d10b012a7860595c7d9abbdf542c7d8f2a4d53 | [
"MIT"
] | null | null | null | src/main.cpp | jonco3/dynamic | 76d10b012a7860595c7d9abbdf542c7d8f2a4d53 | [
"MIT"
] | null | null | null | #include "common.h"
#include "block.h"
#include "builtin.h"
#include "compiler.h"
#include "dict.h"
#include "interp.h"
#include "input.h"
#include "list.h"
#include "module.h"
#include "string.h"
#include "sysexits.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#define Function Readline_Function
#include <readline/readline.h>
#include <readline/history.h>
#undef Function
static char *lineRead = (char *)NULL;
char *readOneLine()
{
if (lineRead) {
free(lineRead);
lineRead = (char *)NULL;
}
lineRead = readline("> ");
if (lineRead && *lineRead)
add_history(lineRead);
return lineRead;
}
void maybeAbortTests(string what)
{}
static int runRepl()
{
char* line;
Stack<Env*> topLevel(createTopLevel());
while (line = readOneLine(), line != NULL) {
Stack<Value> result;
bool ok = execModule(line, "<none>", topLevel, result);
if (ok)
cout << result << endl;
else
printException(result);
}
cout << endl;
return EX_OK;
}
static int runProgram(const char* filename, int arg_count, const char* args[])
{
Stack<Env*> topLevel(createTopLevel());
RootVector<Value> argStrings(arg_count);
for (int i = 0 ; i < arg_count ; ++i)
argStrings[i] = gc.create<String>(args[i]);
Stack<Value> argv(gc.create<List>(argStrings));
Module::Sys->setAttr(Names::argv, argv);
Stack<Value> main(gc.create<String>("__main__"));
topLevel->setAttr(Names::__name__, main);
if (!execModule(readFile(filename), filename, topLevel))
return EX_SOFTWARE;
return EX_OK;
}
static int runModule(const char* name, int arg_count, const char* args[])
{
Stack<String*> nameStr(gc.create<String>(name));
Stack<Value> result;
bool ok = interp->call(LoadModule, nameStr, result);
if (!ok) {
printException(result);
return EX_SOFTWARE;
}
if (result.isNone()) {
cerr << "Module not found: " << name << endl;
return EX_SOFTWARE;
}
return EX_OK;
}
static int runExprs(int count, const char* args[])
{
Stack<Env*> globals;
for (int i = 0 ; i < count ; ++i) {
// todo: should probably parse thse as expressions
if (!execModule(args[i], "<none>", globals))
return EX_SOFTWARE;
}
return EX_OK;
}
const char* usageMessage =
"usage:\n"
" dynamic -- enter the REPL\n"
" dynamic FILE ARG* -- run script from file\n"
" dynamic -e EXPRS -- execute expressions from commandline\n"
"options:\n"
" -m MODULENAME -- locate and execute module\n"
" -i INTERNALSDIR -- set directory to load internals from\n"
#ifdef LOG_EXECUTION
" -le -- log interpreter execution\n"
" -lf -- log interpreter frames only\n"
#endif
#ifdef DEBUG
" -lg -- log GC activity\n"
" -lc -- log compiled bytecode\n"
" -lb -- log big integer arithmetic\n"
" -z N -- perform GC every N allocations\n"
#endif
" -sg -- print GC stats\n"
#ifdef DEBUG
" -si -- print instruction count stats\n"
#endif
;
static void badUsage()
{
cerr << usageMessage;
exit(EX_USAGE);
}
int main(int argc, const char* argv[])
{
int r = 0;
int pos = 1;
bool expr = false;
const char* moduleName = nullptr;
const char* internalsDir = "internals";
while (pos != argc && argv[pos][0] == '-') {
const char* opt = argv[pos++];
if (strcmp("-e", opt) == 0 && !moduleName)
expr = true;
else if (strcmp("-m", opt) == 0 && pos != argc && !expr)
moduleName = argv[pos++];
else if (strcmp("-i", opt) == 0 && pos != argc)
internalsDir = argv[pos++];
#ifdef LOG_EXECUTION
else if (strcmp("-le", opt) == 0)
logFrames = logExecution = true;
else if (strcmp("-lf", opt) == 0)
logFrames = true;
#endif
#ifdef DEBUG
else if (strcmp("-lg", opt) == 0)
logGC = true;
else if (strcmp("-lc", opt) == 0)
logCompile = true;
else if (strcmp("-lb", opt) == 0)
logBigInt = true;
else if (strcmp("-z", opt) == 0)
gcZealPeriod = atol(argv[pos++]);
#endif
else if (strcmp("-sg", opt) == 0)
logGCStats = true;
#ifdef DEBUG
else if (strcmp("-si", opt) == 0)
logInstrCounts = true;
#endif
else
badUsage();
}
init1();
init2(internalsDir);
if (moduleName)
r = runModule(moduleName, argc - pos, &argv[pos]);
else if (expr)
r = runExprs(argc - pos, &argv[pos]);
else if ((argc - pos) == 0)
r = runRepl();
else
r = runProgram(argv[pos], argc - pos, &argv[pos]);
final();
return r;
}
| 25.045685 | 78 | 0.556749 |
87a4b78e9d2044e990eec03989d946dad3d6c1eb | 312 | cpp | C++ | homework6/merge_sort/readFile.cpp | mxprshn/homework | 809635858a5bf01af7f63f398fe47fba7c688ecc | [
"Apache-2.0"
] | null | null | null | homework6/merge_sort/readFile.cpp | mxprshn/homework | 809635858a5bf01af7f63f398fe47fba7c688ecc | [
"Apache-2.0"
] | null | null | null | homework6/merge_sort/readFile.cpp | mxprshn/homework | 809635858a5bf01af7f63f398fe47fba7c688ecc | [
"Apache-2.0"
] | 2 | 2018-11-06T19:31:20.000Z | 2018-12-17T19:39:07.000Z | #include "list.h"
#include <fstream>
#include <string>
bool readFile(std::ifstream &file, List *list)
{
if (!file.is_open())
{
return false;
}
while (!file.eof())
{
std::string name;
std::string number;
getline(file, name);
getline(file, number);
add(list, name, number);
}
return true;
} | 13 | 46 | 0.63141 |
87a5035a692af7645d12a631dbfcea1fd8c2ebbb | 1,086 | hpp | C++ | .sandbox/hybrid-daes/dae-drumboiler/src/discrete_system.hpp | vacary/siconos-tutorials | 93c0158321077a313692ed52fed69ff3c256ae32 | [
"Apache-2.0"
] | 6 | 2017-01-12T23:09:28.000Z | 2021-03-20T17:03:58.000Z | .sandbox/hybrid-daes/dae-drumboiler/src/discrete_system.hpp | vacary/siconos-tutorials | 93c0158321077a313692ed52fed69ff3c256ae32 | [
"Apache-2.0"
] | 3 | 2019-01-14T13:44:51.000Z | 2021-05-17T13:57:27.000Z | .sandbox/hybrid-daes/dae-drumboiler/src/discrete_system.hpp | vacary/siconos-tutorials | 93c0158321077a313692ed52fed69ff3c256ae32 | [
"Apache-2.0"
] | 2 | 2019-10-22T13:30:39.000Z | 2020-10-06T10:19:57.000Z | #ifndef DISCRETE_SYSTEM_HPP
#define DISCRETE_SYSTEM_HPP
#include "model_common.hpp"
#include "model.hpp"
/* Information needed for the numerical simulation*/
typedef struct
{
int nb_eqs; // square system assumed
int nb_diff_eqs;
int nb_compl_eqs;
// TODO extended to double** (NumericsMatrix**) in case of theta/multistep methods (or use c++ std::array<T>)
double* system_rhs;
double* system_lhs;
NumericsMatrix* system_rhs_jac;
NumericsMatrix* system_lhs_jac;
double* z_prev;
// time step
double h;
double Tfinal;
}NumericalSimuInfo;
double finiteDifference(void* env, double z_i, int i);
double finiteDifferenceDz(void* env, double z_i, int i);
void implicitEulerDiscr(void* env, int size, double *z, double * system);
void implicitEulerDiscrJac(void* env, int size, double *z, NumericsMatrix * jacobian);
void initialize_simu(NumericalSimuInfo* simu_info, const double &P0, const double &M10, const double &x10, const double &T10, const double &M20, const double &x20, const double &T20);
#endif // DISCRETE_SYSTEM_HPP | 31.028571 | 183 | 0.732965 |
87a6137215523a94877098b08bedb8addcdd866b | 1,086 | hpp | C++ | bg/curves/euriborcurve.hpp | bondgeek/pybg | 046a25074b78409c6d29302177aeac581ade90d1 | [
"Unlicense",
"MIT"
] | 1 | 2017-03-14T05:39:15.000Z | 2017-03-14T05:39:15.000Z | bg/curves/euriborcurve.hpp | bondgeek/pybg | 046a25074b78409c6d29302177aeac581ade90d1 | [
"Unlicense",
"MIT"
] | null | null | null | bg/curves/euriborcurve.hpp | bondgeek/pybg | 046a25074b78409c6d29302177aeac581ade90d1 | [
"Unlicense",
"MIT"
] | null | null | null | /*
* euriborcurve.hpp
* pybg
*
* Created by Bart Mosley on 7/2/12.
* Copyright 2012 BG Research LLC. All rights reserved.
*
*/
#ifndef EURIBORCURVE_HPP
#define EURIBORCURVE_HPP
#include <bg/curvebase.hpp>
#include <bg/date_utilities.hpp>
using namespace QuantLib;
namespace bondgeek {
class EURiborCurve : public CurveBase {
protected:
public:
EURiborCurve():
CurveBase(boost::shared_ptr<IborIndex>(new Euribor(Period(6, Months))),
2,
Annual,
Unadjusted,
Thirty360(Thirty360::European),
ActualActual(ActualActual::ISDA)
)
{}
EURiborCurve(string tenor, Frequency fixedFrequency=Annual):
CurveBase(boost::shared_ptr<IborIndex>(new Euribor( Tenor(tenor) )),
2,
fixedFrequency,
Unadjusted,
Thirty360(Thirty360::European),
ActualActual(ActualActual::ISDA)
)
{
}
};
}
#endif | 24.133333 | 79 | 0.54512 |
87a79139386d672e8b4c8a45dbdb6efffa951bca | 3,398 | cpp | C++ | RUNETag/hirestimer.cpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 31 | 2017-12-29T16:39:07.000Z | 2022-03-25T03:26:29.000Z | RUNETag/hirestimer.cpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 7 | 2018-06-29T07:30:14.000Z | 2021-02-16T23:19:20.000Z | RUNETag/hirestimer.cpp | GeReV/RUNEtag | e8319a132e325d73cdd7759a0d8a5f45f26dd129 | [
"MIT"
] | 13 | 2018-09-27T13:19:12.000Z | 2022-03-02T08:48:42.000Z | /**
* RUNETag fiducial markers library
*
* -----------------------------------------------------------------------------
* The MIT License (MIT)
*
* Copyright (c) 2015 Filippo Bergamasco
*
* 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 "hirestimer.hpp"
HiresTimer::HiresTimer(void)
{
started = false;
stopped = true;
}
HiresTimer::~HiresTimer(void)
{
}
#ifdef WIN32
/*
* Win32 Hi-res timer code
*/
double LI1D(LARGE_INTEGER *i) {
return(i->LowPart+(i->HighPart*4294967296.0));
}
void HiresTimer::start() {
started = true;
stopped = false;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start_time);
}
double HiresTimer::elapsed() {
if( !started )
return 0.0;
if( !stopped ) {
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
elapsed_time = (LI1D(&end_time) - LI1D(&start_time)) / LI1D(&frequency);
}
return elapsed_time;
}
void HiresTimer::stop() {
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
elapsed_time = (LI1D(&end_time) - LI1D(&start_time)) / LI1D(&frequency);
stopped = true;
}
void HiresTimer::reset() {
started = false;
stopped = false;
}
#else
#ifdef UNIX
/*
* Unix Hi-res timer code
*/
void HiresTimer::start() {
started = true;
stopped = false;
start_time = 0.0;
struct timeval start_timeval;
gettimeofday( &start_timeval, NULL );
start_time = (double)start_timeval.tv_sec + (double)start_timeval.tv_usec/1000000.0;
}
double HiresTimer::elapsed() {
if( !started )
return 0.0;
if( !stopped ) {
struct timeval end_timeval;
gettimeofday( &end_timeval, NULL );
double tnow = (double)end_timeval.tv_sec + (double)end_timeval.tv_usec/1000000.0;
elapsed_time = tnow-start_time;
}
return elapsed_time;
}
void HiresTimer::stop() {
struct timeval end_timeval;
gettimeofday( &end_timeval, NULL );
double tnow = (double)end_timeval.tv_sec + (double)end_timeval.tv_usec/1000000.0;
elapsed_time = tnow-start_time;
stopped = true;
}
void HiresTimer::reset() {
started = false;
stopped = false;
}
#else
/*
* Standard timer (NOT yet implemented)
*/
//#error Default standard timer not yet implemented. You see this error probably because you are trying to compile against an unsupported platform
#endif
#endif
| 24.985294 | 147 | 0.685992 |
87a95e3db8fcbb1816a328097c375065212d8b99 | 24,965 | cpp | C++ | api/src/SAM_Windpower.cpp | nickdiorio/SAM | 4288d4261f4f88f44106867b561b81c2ba480c85 | [
"BSD-3-Clause"
] | null | null | null | api/src/SAM_Windpower.cpp | nickdiorio/SAM | 4288d4261f4f88f44106867b561b81c2ba480c85 | [
"BSD-3-Clause"
] | null | null | null | api/src/SAM_Windpower.cpp | nickdiorio/SAM | 4288d4261f4f88f44106867b561b81c2ba480c85 | [
"BSD-3-Clause"
] | null | null | null | #include <string>
#include <utility>
#include <vector>
#include <memory>
#include <iostream>
#include <ssc/sscapi.h>
#include "SAM_api.h"
#include "ErrorHandler.h"
#include "SAM_Windpower.h"
SAM_EXPORT SAM_Windpower SAM_Windpower_construct(const char* def, SAM_error* err){
SAM_Windpower result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_create();
});
return result;
}
SAM_EXPORT int SAM_Windpower_execute(SAM_Windpower data, int verbosity, SAM_error* err){
int n_err = 0;
translateExceptions(err, [&]{
n_err += SAM_module_exec("windpower", data, verbosity, err);
});
return n_err;
}
SAM_EXPORT void SAM_Windpower_destruct(SAM_Windpower system)
{
ssc_data_free(system);
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_k_factor_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_k_factor", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_reference_height_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_reference_height", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_weibull_wind_speed_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "weibull_wind_speed", number);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_data_tset(SAM_Windpower ptr, SAM_table tab, SAM_error *err){
SAM_table_set_table(ptr, "wind_resource_data", tab, err);
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_distribution_mset(SAM_Windpower ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "wind_resource_distribution", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_filename_sset(SAM_Windpower ptr, const char* str, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_string(ptr, "wind_resource_filename", str);
});
}
SAM_EXPORT void SAM_Windpower_Resource_wind_resource_model_choice_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_model_choice", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_resource_shear_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_shear", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_hub_ht_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_hub_ht", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_max_cp_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_max_cp", number);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_powercurve_powerout_aset(SAM_Windpower ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_turbine_powercurve_powerout", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_powercurve_windspeeds_aset(SAM_Windpower ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_turbine_powercurve_windspeeds", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Turbine_wind_turbine_rotor_diameter_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_turbine_rotor_diameter", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_system_capacity_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "system_capacity", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_wake_model_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_farm_wake_model", number);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_xCoordinates_aset(SAM_Windpower ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_farm_xCoordinates", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_farm_yCoordinates_aset(SAM_Windpower ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wind_farm_yCoordinates", arr, length);
});
}
SAM_EXPORT void SAM_Windpower_Farm_wind_resource_turbulence_coeff_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_resource_turbulence_coeff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_bop_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_bop_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_grid_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_grid_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_avail_turb_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "avail_turb_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_elec_eff_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "elec_eff_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_en_icing_cutoff_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "en_icing_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_en_low_temp_cutoff_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "en_low_temp_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_degrad_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_degrad_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_exposure_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_exposure_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_ext_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_ext_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_env_icing_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "env_icing_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_icing_cutoff_rh_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "icing_cutoff_rh", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_icing_cutoff_temp_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "icing_cutoff_temp", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_low_temp_cutoff_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "low_temp_cutoff", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_env_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_env_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_grid_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_grid_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_load_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_load_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_ops_strategies_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ops_strategies_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_generic_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_generic_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_hysteresis_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_hysteresis_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_perf_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_perf_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_turb_specific_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "turb_specific_loss", number);
});
}
SAM_EXPORT void SAM_Windpower_Losses_wake_loss_nset(SAM_Windpower ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wake_loss", number);
});
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_k_factor_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_k_factor", &result))
make_access_error("SAM_Windpower", "weibull_k_factor");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_reference_height_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_reference_height", &result))
make_access_error("SAM_Windpower", "weibull_reference_height");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_weibull_wind_speed_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "weibull_wind_speed", &result))
make_access_error("SAM_Windpower", "weibull_wind_speed");
});
return result;
}
SAM_EXPORT SAM_table SAM_Windpower_Resource_wind_resource_data_tget(SAM_Windpower ptr, SAM_error *err){
SAM_table result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_table(ptr, "wind_resource_data");
if (!result)
make_access_error("SAM_Windpower", "wind_resource_data");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Resource_wind_resource_distribution_mget(SAM_Windpower ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "wind_resource_distribution", nrows, ncols);
if (!result)
make_access_error("SAM_Windpower", "wind_resource_distribution");
});
return result;
}
SAM_EXPORT const char* SAM_Windpower_Resource_wind_resource_filename_sget(SAM_Windpower ptr, SAM_error *err){
const char* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_string(ptr, "wind_resource_filename");
if (!result)
make_access_error("SAM_Windpower", "wind_resource_filename");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Resource_wind_resource_model_choice_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_model_choice", &result))
make_access_error("SAM_Windpower", "wind_resource_model_choice");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_resource_shear_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_shear", &result))
make_access_error("SAM_Windpower", "wind_resource_shear");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_hub_ht_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_hub_ht", &result))
make_access_error("SAM_Windpower", "wind_turbine_hub_ht");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_max_cp_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_max_cp", &result))
make_access_error("SAM_Windpower", "wind_turbine_max_cp");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Turbine_wind_turbine_powercurve_powerout_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_turbine_powercurve_powerout", length);
if (!result)
make_access_error("SAM_Windpower", "wind_turbine_powercurve_powerout");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Turbine_wind_turbine_powercurve_windspeeds_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_turbine_powercurve_windspeeds", length);
if (!result)
make_access_error("SAM_Windpower", "wind_turbine_powercurve_windspeeds");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Turbine_wind_turbine_rotor_diameter_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_turbine_rotor_diameter", &result))
make_access_error("SAM_Windpower", "wind_turbine_rotor_diameter");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_system_capacity_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "system_capacity", &result))
make_access_error("SAM_Windpower", "system_capacity");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_wind_farm_wake_model_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_farm_wake_model", &result))
make_access_error("SAM_Windpower", "wind_farm_wake_model");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Farm_wind_farm_xCoordinates_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_farm_xCoordinates", length);
if (!result)
make_access_error("SAM_Windpower", "wind_farm_xCoordinates");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Farm_wind_farm_yCoordinates_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_farm_yCoordinates", length);
if (!result)
make_access_error("SAM_Windpower", "wind_farm_yCoordinates");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Farm_wind_resource_turbulence_coeff_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_resource_turbulence_coeff", &result))
make_access_error("SAM_Windpower", "wind_resource_turbulence_coeff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_bop_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_bop_loss", &result))
make_access_error("SAM_Windpower", "avail_bop_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_grid_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_grid_loss", &result))
make_access_error("SAM_Windpower", "avail_grid_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_avail_turb_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "avail_turb_loss", &result))
make_access_error("SAM_Windpower", "avail_turb_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_elec_eff_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "elec_eff_loss", &result))
make_access_error("SAM_Windpower", "elec_eff_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_en_icing_cutoff_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "en_icing_cutoff", &result))
make_access_error("SAM_Windpower", "en_icing_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_en_low_temp_cutoff_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "en_low_temp_cutoff", &result))
make_access_error("SAM_Windpower", "en_low_temp_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_degrad_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_degrad_loss", &result))
make_access_error("SAM_Windpower", "env_degrad_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_exposure_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_exposure_loss", &result))
make_access_error("SAM_Windpower", "env_exposure_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_ext_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_ext_loss", &result))
make_access_error("SAM_Windpower", "env_ext_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_env_icing_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "env_icing_loss", &result))
make_access_error("SAM_Windpower", "env_icing_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_icing_cutoff_rh_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "icing_cutoff_rh", &result))
make_access_error("SAM_Windpower", "icing_cutoff_rh");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_icing_cutoff_temp_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "icing_cutoff_temp", &result))
make_access_error("SAM_Windpower", "icing_cutoff_temp");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_low_temp_cutoff_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "low_temp_cutoff", &result))
make_access_error("SAM_Windpower", "low_temp_cutoff");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_env_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_env_loss", &result))
make_access_error("SAM_Windpower", "ops_env_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_grid_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_grid_loss", &result))
make_access_error("SAM_Windpower", "ops_grid_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_load_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_load_loss", &result))
make_access_error("SAM_Windpower", "ops_load_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_ops_strategies_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ops_strategies_loss", &result))
make_access_error("SAM_Windpower", "ops_strategies_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_generic_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_generic_loss", &result))
make_access_error("SAM_Windpower", "turb_generic_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_hysteresis_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_hysteresis_loss", &result))
make_access_error("SAM_Windpower", "turb_hysteresis_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_perf_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_perf_loss", &result))
make_access_error("SAM_Windpower", "turb_perf_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_turb_specific_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "turb_specific_loss", &result))
make_access_error("SAM_Windpower", "turb_specific_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Losses_wake_loss_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wake_loss", &result))
make_access_error("SAM_Windpower", "wake_loss");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_energy_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy", &result))
make_access_error("SAM_Windpower", "annual_energy");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_annual_gross_energy_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_gross_energy", &result))
make_access_error("SAM_Windpower", "annual_gross_energy");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_capacity_factor_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "capacity_factor", &result))
make_access_error("SAM_Windpower", "capacity_factor");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_cutoff_losses_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "cutoff_losses", &result))
make_access_error("SAM_Windpower", "cutoff_losses");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_gen_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "gen", length);
if (!result)
make_access_error("SAM_Windpower", "gen");
});
return result;
}
SAM_EXPORT double SAM_Windpower_Outputs_kwh_per_kw_nget(SAM_Windpower ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "kwh_per_kw", &result))
make_access_error("SAM_Windpower", "kwh_per_kw");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_monthly_energy_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "monthly_energy", length);
if (!result)
make_access_error("SAM_Windpower", "monthly_energy");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_pressure_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "pressure", length);
if (!result)
make_access_error("SAM_Windpower", "pressure");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_temp_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "temp", length);
if (!result)
make_access_error("SAM_Windpower", "temp");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_turbine_output_by_windspeed_bin_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "turbine_output_by_windspeed_bin", length);
if (!result)
make_access_error("SAM_Windpower", "turbine_output_by_windspeed_bin");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_wind_direction_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_direction", length);
if (!result)
make_access_error("SAM_Windpower", "wind_direction");
});
return result;
}
SAM_EXPORT double* SAM_Windpower_Outputs_wind_speed_aget(SAM_Windpower ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wind_speed", length);
if (!result)
make_access_error("SAM_Windpower", "wind_speed");
});
return result;
}
| 28.995354 | 141 | 0.779852 |
87ab8ec991ad3bfaf9c59a402180820e98d05ecc | 5,853 | hpp | C++ | Include/FishEngine/Serialization/CloneArchive.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-12-20T02:38:44.000Z | 2018-12-20T02:38:44.000Z | Include/FishEngine/Serialization/CloneArchive.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | null | null | null | Include/FishEngine/Serialization/CloneArchive.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-10-25T19:40:22.000Z | 2018-10-25T19:40:22.000Z | #pragma once
#include <FishEngine/Serialization/Archive.hpp>
#include <set>
#include <vector>
#include <FishEngine/Prefab.hpp>
namespace FishEngine
{
class CollectObjectsArchive : public OutputArchive
{
public:
void Collect(Object* obj)
{
if (obj->Is<Prefab>())
return;
this->SerializeObject(obj);
}
void CollectPrefab(Prefab* prefab)
{
prefab->Serialize(*this);
}
protected:
virtual void Serialize(short t) override {}
virtual void Serialize(unsigned short t) override {}
virtual void Serialize(int t) override {}
virtual void Serialize(unsigned int t) override {}
virtual void Serialize(long t) override {}
virtual void Serialize(unsigned long t) override {}
virtual void Serialize(long long t) override {}
virtual void Serialize(unsigned long long t) override {}
virtual void Serialize(float t) override {}
virtual void Serialize(double t) override {}
virtual void Serialize(bool t) override {}
virtual void Serialize(std::string const & t) override {}
virtual void SerializeNullPtr() override {} // nullptr
void SerializeObject(Object* t) override
{
auto it = m_Objects.find(t);
if (it == m_Objects.end())
{
m_Objects.insert(t);
t->Serialize(*this);
}
}
void MapKey(const char* name) override {}
public:
std::set<Object*> m_Objects;
};
class CloneOutputArchive : public OutputArchive
{
public:
void AssertEmpty()
{
assert(m_IntValues.empty());
assert(m_UIntValues.empty());
assert(m_FloatValues.empty());
assert(m_StringValues.empty());
assert(m_ObjectValues.empty());
assert(m_MapKeys.empty());
}
protected:
virtual void Serialize(short t) override { m_IntValues.push_back(t); }
virtual void Serialize(unsigned short t) override { m_UIntValues.push_back(t); }
virtual void Serialize(int t) override { m_IntValues.push_back(t); }
virtual void Serialize(unsigned int t) override { m_UIntValues.push_back(t); }
virtual void Serialize(long t) override { m_IntValues.push_back(t); }
virtual void Serialize(unsigned long t) override { m_UIntValues.push_back(t); }
virtual void Serialize(long long t) override { m_IntValues.push_back(t); }
virtual void Serialize(unsigned long long t) override { m_UIntValues.push_back(t); }
virtual void Serialize(float t) override { m_FloatValues.push_back(t); }
virtual void Serialize(double t) override { m_FloatValues.push_back(t); }
virtual void Serialize(bool t) override { m_IntValues.push_back(t ? 1 : 0); }
virtual void Serialize(std::string const & t) override { m_StringValues.push_back(t); }
virtual void SerializeNullPtr() override { m_ObjectValues.push_back(nullptr); } // nullptr
virtual void SerializeObject(Object* t) override { m_ObjectValues.push_back(t); };
void MapKey(const char* name) override
{
m_MapKeys.push_back(name);
}
//// Map
//virtual void AfterValue() {}
//// Sequence
virtual void BeginSequence(int size) override
{
m_SequenceSize.push_back(size);
}
//virtual void BeforeSequenceItem() {}
//virtual void AfterSequenceItem() {}
//virtual void EndSequence() {}
public:
std::deque<int64_t> m_IntValues;
std::deque<uint64_t> m_UIntValues;
std::deque<double> m_FloatValues;
std::deque<std::string> m_StringValues;
std::deque<Object*> m_ObjectValues;
std::deque<const char*> m_MapKeys;
std::deque<int> m_SequenceSize;
};
class CloneInputArchive : public InputArchive
{
public:
CloneOutputArchive & values;
std::map<Object*, Object*> & objectMemo;
CloneInputArchive(CloneOutputArchive& values, std::map<Object*, Object*>& objectMemo)
: values(values), objectMemo(objectMemo)
{
}
protected:
virtual void Deserialize(short & t) override { t = values.m_IntValues.front(); values.m_IntValues.pop_front(); }
virtual void Deserialize(unsigned short & t) override { t = values.m_UIntValues.front(); values.m_UIntValues.pop_front(); }
virtual void Deserialize(int & t) override { t = values.m_IntValues.front(); values.m_IntValues.pop_front(); }
virtual void Deserialize(unsigned int & t) override { t = values.m_UIntValues.front(); values.m_UIntValues.pop_front(); }
virtual void Deserialize(long & t) override { t = values.m_IntValues.front(); values.m_IntValues.pop_front(); }
virtual void Deserialize(unsigned long & t) override { t = values.m_UIntValues.front(); values.m_UIntValues.pop_front(); }
virtual void Deserialize(long long & t) override { t = values.m_IntValues.front(); values.m_IntValues.pop_front(); }
virtual void Deserialize(unsigned long long & t) override { t = values.m_UIntValues.front(); values.m_UIntValues.pop_front(); }
virtual void Deserialize(float & t) override { t = values.m_FloatValues.front(); values.m_FloatValues.pop_front(); }
virtual void Deserialize(double & t) override { t = values.m_FloatValues.front(); values.m_FloatValues.pop_front(); }
virtual void Deserialize(bool & t) override { t = values.m_IntValues.front(); values.m_IntValues.pop_front(); }
virtual void Deserialize(std::string & t) override { t = values.m_StringValues.front(); values.m_StringValues.pop_front(); }
virtual Object* DeserializeObject() override
{
auto obj = values.m_ObjectValues.front();
values.m_ObjectValues.pop_front();
if (obj != nullptr)
{
obj = this->objectMemo[obj];
}
return obj;
}
// Map
virtual bool MapKey(const char* name) override {
assert(values.m_MapKeys.front() == std::string(name));
values.m_MapKeys.pop_front();
return true;
}
virtual void AfterValue() override {}
// Sequence
virtual int BeginSequence() override {
int size = values.m_SequenceSize.front();
values.m_SequenceSize.pop_front();
return size;
}
virtual void BeginSequenceItem() override {}
virtual void AfterSequenceItem() override {}
virtual void EndSequence() override {}
};
}
| 34.429412 | 129 | 0.718606 |
87b089091f45aaf7a85fa23dfb980553b5aeff5b | 1,138 | cpp | C++ | UVA/10189.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | UVA/10189.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | UVA/10189.cpp | DT3264/ProgrammingContestsSolutions | a297f2da654c2ca2815b9aa375c2b4ca0052269d | [
"MIT"
] | null | null | null | #include<stdio.h>
int x, y;
int i, j;
char t;
char arr[100][100];
int prob[100][100];
void mine(){
if(i-1>=0 && j-1>=0) prob[i-1][j-1]++;
if(i-1>=0) prob[i-1][j]++;
if(i-1>=0 && j+1<y) prob[i-1][j+1]++;
///
if(j-1>=0) prob[i][j-1]++;
if(j+1<y) prob[i][j+1]++;
///
if(i+1<x && j-1>=0) prob[i+1][j-1]++;
if(i+1<x) prob[i+1][j]++;
if(i+1<x && j+1<y) prob[i+1][j+1]++;
}
void printPath(){
int i, j;
for(i=0; i<x; i++){
for(j=0; j<y; j++){
if(arr[i][j]=='*') printf("*");
else printf("%d", prob[i][j]);
}
printf("\n");
}
}
int main(){
int cont=1;
while(scanf("%d %d", &x, &y) && x!=0 && y!=0){
if(cont>1) printf("\n");
for(i=0; i<x; i++){
for(j=0; j<y; j++){
prob[i][j]=0;
}
}
printf("Field #%d:\n", cont++);
for(i=0; i<x; i++){
for(j=0; j<y; j++){
scanf(" %c", &arr[i][j]);
if(arr[i][j]=='*'){
mine();
}
}
}
printPath();
}
return 0;
}
| 21.074074 | 50 | 0.339192 |
87b235e46241c19f5544be53b2589737713ffef8 | 1,403 | cpp | C++ | friend.cpp | OmairK/OOP_LAB | 2cf73a7764529a68e210f2f8c9b65c441577a670 | [
"MIT"
] | null | null | null | friend.cpp | OmairK/OOP_LAB | 2cf73a7764529a68e210f2f8c9b65c441577a670 | [
"MIT"
] | null | null | null | friend.cpp | OmairK/OOP_LAB | 2cf73a7764529a68e210f2f8c9b65c441577a670 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
using namespace std;
void readName(string filename){
ifstream file;
file.open(filename, ios::in);
string line;
if (file.is_open())
{
while (getline(file, line))
{
cout << line << endl;
}
}
file.close();
}
class Box{
public:
float length,breadth,height;
Box(){}
Box(float l,float b,float h):length(l),breadth(b),height(h){}
friend double Volume(Box box);
friend double SurfaceArea(Box box);
inline void display();
};
inline void Box::display(){
cout<<"\n Dimensions \n Height: "<<height<<"\n Length: "<<length<<"\n Breadth: "<<breadth<<endl;
}
double volume(Box box){
return(box.length*box.height*box.breadth);
}
double surfaceArea(Box box){
return(2*(box.length*box.height + box.breadth*box.height + box.length*box.breadth));
}
int main(){
float len,bre,hei;
cout<<"Enter the dimensions of the box"<<endl;
cout<<"Enter the length"<<endl;
cin>>len;
cout<<"Enter the breadth"<<endl;
cin>>bre;
cout<<"Enter the height"<<endl;
cin>>hei;
Box box = Box(len,bre,hei);
box.display();
cout<<"The surface area is "<<surfaceArea(box)<<endl;
cout<<"The volume is "<<volume(box)<<endl;
readName("name.txt");
return 1;
} | 21.257576 | 118 | 0.568068 |
87b455f92a2a238c2f2a245f15e6126c6553e68b | 18,473 | cpp | C++ | LibCarla/source/carla/trafficmanager/CollisionStage.cpp | pirate-lofy/carla | b46117685e2e037dd6c0e6246998e5988bdc2bfb | [
"MIT"
] | 1 | 2019-12-17T12:28:57.000Z | 2019-12-17T12:28:57.000Z | LibCarla/source/carla/trafficmanager/CollisionStage.cpp | Tarfand123/carla | b46117685e2e037dd6c0e6246998e5988bdc2bfb | [
"MIT"
] | null | null | null | LibCarla/source/carla/trafficmanager/CollisionStage.cpp | Tarfand123/carla | b46117685e2e037dd6c0e6246998e5988bdc2bfb | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "CollisionStage.h"
namespace carla {
namespace traffic_manager {
namespace CollisionStageConstants {
static const float VERTICAL_OVERLAP_THRESHOLD = 2.0f;
static const float BOUNDARY_EXTENSION_MINIMUM = 2.0f;
static const float EXTENSION_SQUARE_POINT = 7.5f;
static const float TIME_HORIZON = 0.5f;
static const float HIGHWAY_SPEED = 50.0f / 3.6f;
static const float HIGHWAY_TIME_HORIZON = 5.0f;
static const float CRAWL_SPEED = 10.0f / 3.6f;
static const float BOUNDARY_EDGE_LENGTH = 2.0f;
static const float MAX_COLLISION_RADIUS = 100.0f;
} // namespace CollisionStageConstants
using namespace CollisionStageConstants;
CollisionStage::CollisionStage(
std::string stage_name,
std::shared_ptr<LocalizationToCollisionMessenger> localization_messenger,
std::shared_ptr<CollisionToPlannerMessenger> planner_messenger,
cc::World &world,
Parameters ¶meters,
cc::DebugHelper &debug_helper)
: PipelineStage(stage_name),
localization_messenger(localization_messenger),
planner_messenger(planner_messenger),
world(world),
parameters(parameters),
debug_helper(debug_helper){
// Initializing clock for checking unregistered actors periodically.
last_world_actors_pass_instance = chr::system_clock::now();
// Initializing output array selector.
frame_selector = true;
// Initializing messenger states.
localization_messenger_state = localization_messenger->GetState();
// Initializing this messenger to preemptively write since it precedes
// motion planner stage.
planner_messenger_state = planner_messenger->GetState() - 1;
// Initializing the number of vehicles to zero in the beginning.
number_of_vehicles = 0u;
}
CollisionStage::~CollisionStage() {}
void CollisionStage::Action() {
const auto current_planner_frame = frame_selector ? planner_frame_a : planner_frame_b;
// Handle vehicles not spawned by TrafficManager.
const auto current_time = chr::system_clock::now();
const chr::duration<double> diff = current_time - last_world_actors_pass_instance;
// Periodically check for actors not spawned by TrafficManager.
if (diff.count() > 1.0f) {
const auto world_actors = world.GetActors()->Filter("vehicle.*");
const auto world_walker = world.GetActors()->Filter("walker.*");
// Scanning for vehicles.
for (auto actor: *world_actors.get()) {
const auto unregistered_id = actor->GetId();
if (vehicle_id_to_index.find(unregistered_id) == vehicle_id_to_index.end() &&
unregistered_actors.find(unregistered_id) == unregistered_actors.end()) {
unregistered_actors.insert({unregistered_id, actor});
}
}
// Scanning for pedestrians.
for (auto walker: *world_walker.get()) {
const auto unregistered_id = walker->GetId();
if (unregistered_actors.find(unregistered_id) == unregistered_actors.end()) {
unregistered_actors.insert({unregistered_id, walker});
}
}
// Regularly update unregistered actors.
std::vector<ActorId> actor_ids_to_erase;
for (auto actor_info: unregistered_actors) {
if (actor_info.second->IsAlive()) {
vicinity_grid.UpdateGrid(actor_info.second);
} else {
vicinity_grid.EraseActor(actor_info.first);
actor_ids_to_erase.push_back(actor_info.first);
}
}
for (auto actor_id: actor_ids_to_erase) {
unregistered_actors.erase(actor_id);
}
last_world_actors_pass_instance = current_time;
}
// Looping over registered actors.
for (uint64_t i = 0u; i < number_of_vehicles; ++i) {
const LocalizationToCollisionData &data = localization_frame->at(i);
const Actor ego_actor = data.actor;
const ActorId ego_actor_id = ego_actor->GetId();
// Retrieve actors around the path of the ego vehicle.
std::unordered_set<ActorId> actor_id_list = GetPotentialVehicleObstacles(ego_actor);
bool collision_hazard = false;
// Generate number between 0 and 100
const int r = rand() % 101;
// Continue only if random number is lower than our %, default is 0.
if (parameters.GetPercentageIgnoreActors(boost::shared_ptr<cc::Actor>(ego_actor)) <= r) {
// Check every actor in the vicinity if it poses a collision hazard.
for (auto j = actor_id_list.begin(); (j != actor_id_list.end()) && !collision_hazard; ++j) {
const ActorId actor_id = *j;
try {
Actor actor = nullptr;
if (vehicle_id_to_index.find(actor_id) != vehicle_id_to_index.end()) {
actor = localization_frame->at(vehicle_id_to_index.at(actor_id)).actor;
} else if (unregistered_actors.find(actor_id) != unregistered_actors.end()) {
actor = unregistered_actors.at(actor_id);
}
const cg::Location ego_location = ego_actor->GetLocation();
const cg::Location other_location = actor->GetLocation();
if (actor_id != ego_actor_id &&
(cg::Math::DistanceSquared(ego_location, other_location)
< std::pow(MAX_COLLISION_RADIUS, 2)) &&
(std::abs(ego_location.z - other_location.z) < VERTICAL_OVERLAP_THRESHOLD)) {
if (parameters.GetCollisionDetection(ego_actor, actor) &&
NegotiateCollision(ego_actor, actor)) {
collision_hazard = true;
}
}
} catch (const std::exception &e) {
carla::log_warning("Encountered problem while determining collision \n");
carla::log_info("Actor might not be alive \n");
}
}
}
CollisionToPlannerData &message = current_planner_frame->at(i);
message.hazard = collision_hazard;
}
}
void CollisionStage::DataReceiver() {
const auto packet = localization_messenger->ReceiveData(localization_messenger_state);
localization_frame = packet.data;
localization_messenger_state = packet.id;
if (localization_frame != nullptr) {
// Connecting actor ids to their position indices on data arrays.
// This map also provides us the additional benefit of being able to
// quickly identify
// if a vehicle id is registered with the traffic manager or not.
uint64_t index = 0u;
for (auto &element: *localization_frame.get()) {
vehicle_id_to_index.insert({element.actor->GetId(), index++});
}
// Allocating new containers for the changed number of registered
// vehicles.
if (number_of_vehicles != (*localization_frame.get()).size()) {
number_of_vehicles = static_cast<uint>((*localization_frame.get()).size());
// Allocating output arrays to be shared with motion planner stage.
planner_frame_a = std::make_shared<CollisionToPlannerFrame>(number_of_vehicles);
planner_frame_b = std::make_shared<CollisionToPlannerFrame>(number_of_vehicles);
}
}
}
void CollisionStage::DataSender() {
const DataPacket<std::shared_ptr<CollisionToPlannerFrame>> packet{
planner_messenger_state,
frame_selector ? planner_frame_a : planner_frame_b
};
frame_selector = !frame_selector;
planner_messenger_state = planner_messenger->SendData(packet);
}
bool CollisionStage::NegotiateCollision(const Actor &reference_vehicle, const Actor &other_vehicle) const {
bool hazard = false;
auto& data_packet = localization_frame->at(vehicle_id_to_index.at(reference_vehicle->GetId()));
Buffer& waypoint_buffer = data_packet.buffer;
auto& other_packet = localization_frame->at(vehicle_id_to_index.at(other_vehicle->GetId()));
Buffer& other_buffer = other_packet.buffer;
const cg::Location reference_location = reference_vehicle->GetLocation();
const cg::Location other_location = other_vehicle->GetLocation();
const cg::Vector3D reference_heading = reference_vehicle->GetTransform().GetForwardVector();
cg::Vector3D reference_to_other = other_location - reference_location;
reference_to_other = reference_to_other.MakeUnitVector();
const auto reference_vehicle_ptr = boost::static_pointer_cast<cc::Vehicle>(reference_vehicle);
const auto other_vehicle_ptr = boost::static_pointer_cast<cc::Vehicle>(other_vehicle);
if (waypoint_buffer.front()->CheckJunction() &&
other_buffer.front()->CheckJunction()) {
const Polygon reference_geodesic_polygon = GetPolygon(GetGeodesicBoundary(reference_vehicle));
const Polygon other_geodesic_polygon = GetPolygon(GetGeodesicBoundary(other_vehicle));
const Polygon reference_polygon = GetPolygon(GetBoundary(reference_vehicle));
const Polygon other_polygon = GetPolygon(GetBoundary(other_vehicle));
const double reference_vehicle_to_other_geodesic = bg::distance(reference_polygon, other_geodesic_polygon);
const double other_vehicle_to_reference_geodesic = bg::distance(other_polygon, reference_geodesic_polygon);
const auto inter_geodesic_distance = bg::distance(reference_geodesic_polygon, other_geodesic_polygon);
const auto inter_bbox_distance = bg::distance(reference_polygon, other_polygon);
const cg::Vector3D other_heading = other_vehicle->GetTransform().GetForwardVector();
cg::Vector3D other_to_reference = reference_vehicle->GetLocation() - other_vehicle->GetLocation();
other_to_reference = other_to_reference.MakeUnitVector();
// Whichever vehicle's path is farthest away from the other vehicle gets
// priority to move.
if (inter_geodesic_distance < 0.1 &&
((
inter_bbox_distance > 0.1 &&
reference_vehicle_to_other_geodesic > other_vehicle_to_reference_geodesic
) || (
inter_bbox_distance < 0.1 &&
cg::Math::Dot(reference_heading, reference_to_other) > cg::Math::Dot(other_heading, other_to_reference)
)) ) {
hazard = true;
}
} else if (!waypoint_buffer.front()->CheckJunction()) {
const float reference_vehicle_length = reference_vehicle_ptr->GetBoundingBox().extent.x;
const float other_vehicle_length = other_vehicle_ptr->GetBoundingBox().extent.x;
const float vehicle_length_sum = reference_vehicle_length + other_vehicle_length;
const float bbox_extension_length = GetBoundingBoxExtention(reference_vehicle);
if ((cg::Math::Dot(reference_heading, reference_to_other) > 0.0f) &&
(cg::Math::DistanceSquared(reference_location, other_location) <
std::pow(bbox_extension_length+vehicle_length_sum, 2))) {
hazard = true;
}
}
return hazard;
}
traffic_manager::Polygon CollisionStage::GetPolygon(const LocationList &boundary) const {
std::string boundary_polygon_wkt;
for (const cg::Location &location: boundary) {
boundary_polygon_wkt += std::to_string(location.x) + " " + std::to_string(location.y) + ",";
}
boundary_polygon_wkt += std::to_string(boundary[0].x) + " " + std::to_string(boundary[0].y);
traffic_manager::Polygon boundary_polygon;
bg::read_wkt("POLYGON((" + boundary_polygon_wkt + "))", boundary_polygon);
return boundary_polygon;
}
LocationList CollisionStage::GetGeodesicBoundary(const Actor &actor) const {
const LocationList bbox = GetBoundary(actor);
if (vehicle_id_to_index.find(actor->GetId()) != vehicle_id_to_index.end()) {
const cg::Location vehicle_location = actor->GetLocation();
float bbox_extension = GetBoundingBoxExtention(actor);
const float specific_distance_margin = parameters.GetDistanceToLeadingVehicle(actor);
if (specific_distance_margin > 0.0f) {
bbox_extension = std::max(specific_distance_margin, bbox_extension);
}
const auto &waypoint_buffer = localization_frame->at(vehicle_id_to_index.at(actor->GetId())).buffer;
LocationList left_boundary;
LocationList right_boundary;
const auto vehicle = boost::static_pointer_cast<cc::Vehicle>(actor);
const float width = vehicle->GetBoundingBox().extent.y;
const float length = vehicle->GetBoundingBox().extent.x;
SimpleWaypointPtr boundary_start = waypoint_buffer.front();
uint64_t boundary_start_index = 0u;
while (boundary_start->DistanceSquared(vehicle_location) < std::pow(length, 2) &&
boundary_start_index < waypoint_buffer.size() -1) {
boundary_start = waypoint_buffer.at(boundary_start_index);
++boundary_start_index;
}
SimpleWaypointPtr boundary_end = nullptr;
SimpleWaypointPtr current_point = waypoint_buffer.at(boundary_start_index);
const auto vehicle_reference = boost::static_pointer_cast<cc::Vehicle>(actor);
// At non-signalized junctions, we extend the boundary across the junction
// and in all other situations, boundary length is velocity-dependent.
bool reached_distance = false;
for (uint64_t j = boundary_start_index; !reached_distance && (j < waypoint_buffer.size()); ++j) {
if (boundary_start->DistanceSquared(current_point) > std::pow(bbox_extension, 2)) {
reached_distance = true;
}
if (boundary_end == nullptr ||
boundary_end->DistanceSquared(current_point) > std::pow(BOUNDARY_EDGE_LENGTH, 2) ||
reached_distance) {
const cg::Vector3D heading_vector = current_point->GetForwardVector();
const cg::Location location = current_point->GetLocation();
cg::Vector3D perpendicular_vector = cg::Vector3D(-heading_vector.y, heading_vector.x, 0.0f);
perpendicular_vector = perpendicular_vector.MakeUnitVector();
// Direction determined for the left-handed system.
const cg::Vector3D scaled_perpendicular = perpendicular_vector * width;
left_boundary.push_back(location + cg::Location(scaled_perpendicular));
right_boundary.push_back(location + cg::Location(-1.0f * scaled_perpendicular));
boundary_end = current_point;
}
current_point = waypoint_buffer.at(j);
}
// Connecting the geodesic path boundary with the vehicle bounding box.
LocationList geodesic_boundary;
// Reversing right boundary to construct clockwise (left-hand system)
// boundary. This is so because both left and right boundary vectors have
// the closest point to the vehicle at their starting index for the right
// boundary,
// we want to begin at the farthest point to have a clockwise trace.
std::reverse(right_boundary.begin(), right_boundary.end());
geodesic_boundary.insert(geodesic_boundary.end(), right_boundary.begin(), right_boundary.end());
geodesic_boundary.insert(geodesic_boundary.end(), bbox.begin(), bbox.end());
geodesic_boundary.insert(geodesic_boundary.end(), left_boundary.begin(), left_boundary.end());
return geodesic_boundary;
} else {
return bbox;
}
}
float CollisionStage::GetBoundingBoxExtention(const Actor &actor) const {
const float velocity = actor->GetVelocity().Length();
float bbox_extension = BOUNDARY_EXTENSION_MINIMUM;
if (velocity > HIGHWAY_SPEED) {
bbox_extension = HIGHWAY_TIME_HORIZON * velocity;
} else if (velocity < CRAWL_SPEED) {
bbox_extension = BOUNDARY_EXTENSION_MINIMUM;
} else {
bbox_extension = std::sqrt(
EXTENSION_SQUARE_POINT * velocity) +
velocity * TIME_HORIZON +
BOUNDARY_EXTENSION_MINIMUM;
}
return bbox_extension;
}
std::unordered_set<ActorId> CollisionStage::GetPotentialVehicleObstacles(const Actor &ego_vehicle) {
vicinity_grid.UpdateGrid(ego_vehicle);
const auto& data_packet = localization_frame->at(vehicle_id_to_index.at(ego_vehicle->GetId()));
const Buffer &waypoint_buffer = data_packet.buffer;
const float velocity = ego_vehicle->GetVelocity().Length();
std::unordered_set<ActorId> actor_id_list = data_packet.overlapping_actors;
if (waypoint_buffer.front()->CheckJunction() && velocity < HIGHWAY_SPEED) {
actor_id_list = vicinity_grid.GetActors(ego_vehicle);
} else {
actor_id_list = data_packet.overlapping_actors;
}
return actor_id_list;
}
LocationList CollisionStage::GetBoundary(const Actor &actor) const {
const auto actor_type = actor->GetTypeId();
cg::BoundingBox bbox;
cg::Location location;
cg::Vector3D heading_vector;
if (actor_type[0] == 'v') {
const auto vehicle = boost::static_pointer_cast<cc::Vehicle>(actor);
bbox = vehicle->GetBoundingBox();
location = vehicle->GetLocation();
heading_vector = vehicle->GetTransform().GetForwardVector();
} else if (actor_type[0] == 'w') {
const auto walker = boost::static_pointer_cast<cc::Walker>(actor);
bbox = walker->GetBoundingBox();
location = walker->GetLocation();
heading_vector = walker->GetTransform().GetForwardVector();
}
const cg::Vector3D extent = bbox.extent;
heading_vector.z = 0.0f;
const cg::Vector3D perpendicular_vector = cg::Vector3D(-heading_vector.y, heading_vector.x, 0.0f);
// Four corners of the vehicle in top view clockwise order (left-handed
// system).
const cg::Vector3D x_boundary_vector = heading_vector * extent.x;
const cg::Vector3D y_boundary_vector = perpendicular_vector * extent.y;
return {
location + cg::Location(x_boundary_vector - y_boundary_vector),
location + cg::Location(-1.0f * x_boundary_vector - y_boundary_vector),
location + cg::Location(-1.0f * x_boundary_vector + y_boundary_vector),
location + cg::Location(x_boundary_vector + y_boundary_vector),
};
}
void CollisionStage::DrawBoundary(const LocationList &boundary) const {
for (uint64_t i = 0u; i < boundary.size(); ++i) {
debug_helper.DrawLine(
boundary[i] + cg::Location(0.0f, 0.0f, 1.0f),
boundary[(i + 1) % boundary.size()] + cg::Location(0.0f, 0.0f, 1.0f),
0.1f, {255u, 0u, 0u}, 0.1f);
}
}
} // namespace traffic_manager
} // namespace carla
| 41.419283 | 115 | 0.69469 |
87b4ac8c46deb92a0c290e44da493eee0e0aee0d | 2,633 | hpp | C++ | src/base/LifeCycleComponent.hpp | inexorgame/entity-system | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 19 | 2018-10-11T09:19:48.000Z | 2020-04-19T16:36:58.000Z | src/base/LifeCycleComponent.hpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 132 | 2018-07-28T12:30:54.000Z | 2020-04-25T23:05:33.000Z | src/base/LifeCycleComponent.hpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 3 | 2019-03-02T16:19:23.000Z | 2020-02-18T05:15:29.000Z | #pragma once
#include <cstdint>
#include <memory>
#include <tuple>
#include <vector>
#include <boost/range/adaptor/reversed.hpp>
#include <spdlog/spdlog.h>
namespace inexor {
/**
* Derived classes profits from automatic initialization and destruction
* of the sub components.
*/
class LifeCycleComponent
{
protected:
/// @brief Constructor.
template <class... LifeCycleComponents>
LifeCycleComponent(LifeCycleComponents... _sub_components) : sub_components{_sub_components...} {};
/// @brief Destructor.
~LifeCycleComponent() = default;
public:
virtual void pre_init() {}
void pre_init_components()
{
// Pre-Initialize before sub components are constructed
pre_init();
spdlog::trace("Pre-Initializing {} sub components of {}", sub_components.size(), this->get_component_name());
for (const std::shared_ptr<LifeCycleComponent> &sub_component : sub_components)
{
sub_component->pre_init_components();
}
}
virtual void init() {}
void init_components()
{
// Initialize before sub components are constructed
init();
spdlog::trace("Initializing {} sub components of {}", sub_components.size(), this->get_component_name());
for (const std::shared_ptr<LifeCycleComponent> &sub_component : sub_components)
{
sub_component->init_components();
}
}
virtual void destroy() {}
void destroy_components()
{
spdlog::trace("Destroying {} sub components of {}", sub_components.size(), this->get_component_name());
// Destruction in reverse order
for (const std::shared_ptr<LifeCycleComponent> &sub_component : boost::adaptors::reverse(sub_components))
{
sub_component->destroy_components();
}
// Destruction after sub components are destructed
destroy();
}
virtual void post_destroy() {}
void post_destroy_components()
{
spdlog::trace("Post-Destroying {} sub components of {}", sub_components.size(), this->get_component_name());
// Destruction in reverse order
for (const std::shared_ptr<LifeCycleComponent> &sub_component : boost::adaptors::reverse(sub_components))
{
sub_component->post_destroy_components();
}
// Destruction after sub components are destructed
post_destroy();
}
virtual std::string get_component_name()
{
return typeid(this).name();
}
private:
std::vector<std::shared_ptr<LifeCycleComponent>> sub_components;
};
} // namespace inexor
| 28.010638 | 117 | 0.651348 |
87b4fff92f1e8214a275f1a0536a306b57c090b5 | 796 | cpp | C++ | Array/Move_Even_Odd_Numbers.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 19 | 2018-12-02T05:59:44.000Z | 2021-07-24T14:11:54.000Z | Array/Move_Even_Odd_Numbers.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | null | null | null | Array/Move_Even_Odd_Numbers.cpp | susantabiswas/placementPrep | 22a7574206ddc63eba89517f7b68a3d2f4d467f5 | [
"MIT"
] | 13 | 2019-04-25T16:20:00.000Z | 2021-09-06T19:50:04.000Z | //given an array.Arrange the elements st even nos. are at the begining and
//the odd nos. are the end
#include<iostream>
#include<vector>
using namespace std;
//moves the even and odd nums
void moveEvenOddNums(vector<int> &arr){
int i = 0; //this is for keeping track of even numbers
int j = arr.size()-1; //for keeping track of odd numbers
int temp = 0 ;//for swapping
while(i<j){
//when the num. is odd,move it to the odd number position
if(arr[i]%2 != 0){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
--j;
}
else
++i;
}
}
//for displaying the numbers
void disp(vector<int> &arr){
for (int i = 0; i < arr.size(); ++i)
{
cout<<arr[i]<<" ";
}
}
int main(){
vector<int> arr = {12,33,14,12411,23,134,443,77};
moveEvenOddNums(arr);
disp(arr);
return 0;
}
| 20.410256 | 74 | 0.626884 |
87b695cf0ca441f75eb5d6ab731d9e0eed4e9e06 | 3,886 | cc | C++ | src/audio/synthesizer.cc | stanford-stagecast/pancake | e9cfd547edf2dd797f324b159252757190211ff2 | [
"Apache-2.0"
] | 2 | 2022-01-05T08:58:11.000Z | 2022-01-06T05:33:14.000Z | src/audio/synthesizer.cc | stanford-stagecast/pancake | e9cfd547edf2dd797f324b159252757190211ff2 | [
"Apache-2.0"
] | null | null | null | src/audio/synthesizer.cc | stanford-stagecast/pancake | e9cfd547edf2dd797f324b159252757190211ff2 | [
"Apache-2.0"
] | null | null | null | #include "synthesizer.hh"
#include <cmath>
#include <iostream>
constexpr unsigned int NUM_KEYS = 88;
constexpr unsigned int KEY_OFFSET = 21;
constexpr unsigned int KEY_DOWN = 144;
constexpr unsigned int KEY_UP = 128;
constexpr unsigned int SUSTAIN = 176;
using namespace std;
Synthesizer::Synthesizer( const string& sample_directory )
: note_repo( sample_directory )
{
for ( size_t i = 0; i < NUM_KEYS; i++ ) {
keys.push_back( { {}, {} } );
}
}
void Synthesizer::process_new_data( uint8_t event_type, uint8_t event_note, uint8_t event_velocity )
{
if ( event_type == SUSTAIN ) {
// std::cerr << (size_t) midi_processor.get_event_type() << " " << (size_t) event_note << " " <<
// (size_t)event_velocity << "\n";
if ( event_velocity == 127 )
sustain_down = true;
else
sustain_down = false;
} else if ( event_type == KEY_DOWN || event_type == KEY_UP ) {
bool direction = event_type == KEY_DOWN ? true : false;
auto& k = keys.at( event_note - KEY_OFFSET );
if ( !direction ) {
k.releases.push_back( { 0, event_velocity, 1.0, false } );
k.presses.back().released = true;
} else {
k.presses.push_back( { 0, event_velocity, 1.0, false } );
}
}
}
wav_frame_t Synthesizer::calculate_curr_sample() const
{
std::pair<float, float> total_sample = { 0, 0 };
for ( size_t i = 0; i < NUM_KEYS; i++ ) {
auto& k = keys.at( i );
size_t active_presses = k.presses.size();
size_t active_releases = k.releases.size();
for ( size_t j = 0; j < active_presses; j++ ) {
// auto t1 = high_resolution_clock::now();
float amplitude_multiplier = k.presses.at( j ).vol_ratio * 0.2; /* to avoid clipping */
const std::pair<float, float> curr_sample
= note_repo.get_sample( true, i, k.presses.at( j ).velocity, k.presses.at( j ).offset );
total_sample.first += curr_sample.first * amplitude_multiplier;
total_sample.second += curr_sample.second * amplitude_multiplier;
// auto t2 = high_resolution_clock::now();
// if (frames_processed % 50000 == 0) std::cerr << "Time to get one key press sample: " << duration_cast<nanoseconds>(t2 - t1).count() << "\n";
}
for ( size_t j = 0; j < active_releases; j++ ) {
//auto t1 = high_resolution_clock::now();
float amplitude_multiplier = exp10( -37 / 20.0 ) * 0.2; /* to avoid clipping */
const std::pair<float, float> curr_sample
= note_repo.get_sample( false, i, k.releases.at( j ).velocity, k.releases.at( j ).offset );
total_sample.first += curr_sample.first * amplitude_multiplier;
total_sample.second += curr_sample.second * amplitude_multiplier;
//auto t2 = high_resolution_clock::now();
//if (frames_processed % 50000 == 0) std::cerr << "Time to get one key release sample: " << duration_cast<nanoseconds>(t2 - t1).count() << "\n";
}
}
return total_sample;
}
void Synthesizer::advance_sample()
{
frames_processed++;
for ( size_t i = 0; i < NUM_KEYS; i++ ) {
auto& k = keys.at( i );
size_t active_presses = k.presses.size();
size_t active_releases = k.releases.size();
for ( size_t j = 0; j < active_presses; j++ ) {
k.presses.at( j ).offset++;
if ( note_repo.note_finished( true, i, k.presses.at( j ).velocity, k.presses.at( j ).offset ) ) {
k.presses.erase( k.presses.begin() );
j--;
active_presses--;
} else if ( ( k.presses.at( j ).released && !sustain_down ) & ( k.presses.at( j ).vol_ratio > 0 ) ) {
k.presses.at( j ).vol_ratio -= 0.0001;
}
}
for ( size_t j = 0; j < active_releases; j++ ) {
k.releases.at( j ).offset++;
if ( note_repo.note_finished( false, i, k.releases.at( j ).velocity, k.releases.at( j ).offset ) ) {
k.releases.erase( k.releases.begin() );
j--;
active_releases--;
}
}
}
}
| 33.791304 | 150 | 0.617859 |
87b870a79ffa203ac6f3a4eeceb49a047389ebab | 56,469 | cc | C++ | src/client/client.cc | Caesar-github/rkmedia | 953f22f7a5965a04ca2688d251ccce9683ce993c | [
"BSD-3-Clause"
] | 2 | 2021-07-01T00:51:48.000Z | 2022-03-01T23:46:02.000Z | src/client/client.cc | Caesar-github/rkmedia | 953f22f7a5965a04ca2688d251ccce9683ce993c | [
"BSD-3-Clause"
] | 2 | 2021-02-03T12:47:35.000Z | 2021-12-12T13:30:00.000Z | src/client/client.cc | Caesar-github/rkmedia | 953f22f7a5965a04ca2688d251ccce9683ce993c | [
"BSD-3-Clause"
] | 2 | 2020-11-02T09:13:23.000Z | 2021-07-07T11:29:24.000Z | #include <assert.h>
#include <drm_fourcc.h>
#include <fcntl.h>
#include <malloc.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <xf86drm.h>
#include "../socket/socket.h"
#include "rkmedia_api.h"
#define CONST_STRING_NUM 256
const char *const_string[CONST_STRING_NUM] = {NULL};
typedef enum rkCB_TYPE { CB_TYPE_EVENT = 0, CB_TYPE_OUT } CB_TYPE_E;
typedef struct EVENT_CALL_LIST {
int id;
MPP_CHN_S stChn;
void *cb;
RK_VOID *pHandle;
CB_TYPE_E type;
struct EVENT_CALL_LIST *next;
} EVENT_CALL_LIST_S;
typedef struct MB_LIST {
MEDIA_BUFFER mb;
void *ptr;
int devfd;
int fd;
int handle;
int size;
struct MB_LIST *next;
} MB_LIST_S;
static EVENT_CALL_LIST_S *event_cb_list = NULL;
static pthread_mutex_t event_mutex = PTHREAD_MUTEX_INITIALIZER;
static MB_LIST_S *mb_list = NULL;
static pthread_mutex_t mb_mutex = PTHREAD_MUTEX_INITIALIZER;
MB_LIST_S *mb_list_add(MEDIA_BUFFER mb, void *ptr, int devfd, int fd,
int handle, int size) {
MB_LIST_S *ret = NULL;
MB_LIST_S *tmp = NULL;
pthread_mutex_lock(&mb_mutex);
if (mb_list) {
tmp = mb_list;
while (tmp) {
if (tmp->mb == mb) {
ret = tmp;
break;
}
tmp = tmp->next;
}
}
if (ret == NULL) {
tmp = (MB_LIST_S *)malloc(sizeof(MB_LIST_S));
tmp->next = mb_list;
tmp->mb = mb;
tmp->ptr = ptr;
tmp->devfd = devfd;
tmp->fd = fd;
tmp->handle = handle;
tmp->size = size;
mb_list = tmp;
ret = mb_list;
}
pthread_mutex_unlock(&mb_mutex);
return ret;
}
int mb_list_update(MEDIA_BUFFER mb, MB_LIST_S *info) {
int ret = -1;
MB_LIST_S *tmp = NULL;
pthread_mutex_lock(&mb_mutex);
if (mb_list) {
tmp = mb_list;
while (tmp) {
if (tmp->mb == mb) {
break;
}
tmp = tmp->next;
}
}
if (tmp) {
ret = 0;
tmp->ptr = info->ptr;
tmp->devfd = info->devfd;
tmp->fd = info->fd;
tmp->handle = info->handle;
tmp->size = info->size;
}
pthread_mutex_unlock(&mb_mutex);
return ret;
}
int mb_list_get(MEDIA_BUFFER mb, MB_LIST_S *info) {
int ret = -1;
MB_LIST_S *tmp = NULL;
pthread_mutex_lock(&mb_mutex);
if (mb_list) {
tmp = mb_list;
while (tmp) {
if (tmp->mb == mb) {
break;
}
tmp = tmp->next;
}
}
if (tmp) {
ret = 0;
memcpy(info, tmp, sizeof(MB_LIST_S));
}
pthread_mutex_unlock(&mb_mutex);
return ret;
}
void del_list_del(MEDIA_BUFFER mb) {
pthread_mutex_lock(&mb_mutex);
again:
if (mb_list) {
MB_LIST_S *tmp = mb_list;
MB_LIST_S *next = tmp->next;
if (tmp->mb == mb) {
mb_list = tmp->next;
free(tmp);
goto again;
}
while (next) {
if (next->mb == mb) {
tmp->next = next->next;
free(next);
}
tmp = next;
next = tmp->next;
}
}
pthread_mutex_unlock(&mb_mutex);
}
void *MbMap(int devfd, int handle, int size) {
struct drm_mode_map_dumb dmmd;
memset(&dmmd, 0, sizeof(dmmd));
dmmd.handle = handle;
if (drmIoctl(devfd, DRM_IOCTL_MODE_MAP_DUMB, &dmmd))
printf("Failed to map dumb\n");
return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, devfd,
dmmd.offset);
}
int MbHandleToFD(int devfd, int handle) {
int fd;
drmPrimeHandleToFD(devfd, handle, DRM_CLOEXEC, &fd);
return fd;
}
EVENT_CALL_LIST_S *event_list_add(const MPP_CHN_S *pstChn, RK_VOID *pHandle,
void *cb, CB_TYPE_E type) {
EVENT_CALL_LIST_S *ret = NULL;
EVENT_CALL_LIST_S *tmp = NULL;
int id = (pstChn->enModId << 16) + pstChn->s32ChnId;
pthread_mutex_lock(&event_mutex);
if (event_cb_list) {
tmp = event_cb_list;
while (tmp) {
if (tmp->id == id && tmp->cb == cb) {
ret = tmp;
break;
}
tmp = tmp->next;
}
}
if (ret == NULL) {
tmp = (EVENT_CALL_LIST_S *)malloc(sizeof(EVENT_CALL_LIST_S));
memcpy(&tmp->stChn, pstChn, sizeof(MPP_CHN_S));
tmp->next = event_cb_list;
tmp->id = id;
tmp->pHandle = pHandle;
tmp->cb = cb;
tmp->type = type;
event_cb_list = tmp;
ret = event_cb_list;
}
pthread_mutex_unlock(&event_mutex);
return ret;
}
void *event_server_run(void *arg) {
int fd;
EVENT_CALL_LIST_S *node = (EVENT_CALL_LIST_S *)arg;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &node->stChn, sizeof(MPP_CHN_S));
sock_write(fd, &node->type, sizeof(CB_TYPE_E));
while (1) {
if (node->cb) {
if (node->type == CB_TYPE_EVENT) {
int len;
RK_VOID *data = NULL;
if (sock_read(fd, &len, sizeof(int)) <= 0)
break;
data = (RK_VOID *)malloc(len);
if (sock_read(fd, data, len) <= 0)
break;
EventCbFunc cb = (EventCbFunc)node->cb;
cb(node->pHandle, data);
if (data)
free(data);
} else if (node->type == CB_TYPE_OUT) {
MEDIA_BUFFER mb;
if (sock_read(fd, &mb, sizeof(MEDIA_BUFFER)) <= 0)
break;
OutCbFunc cb = (OutCbFunc)node->cb;
cb(mb);
}
}
}
/* End transmission parameters */
cli_end(fd);
pthread_exit(NULL);
return 0;
}
void example_0(void) {
int fd;
printf("%s, in\n", __func__);
fd = cli_begin((char *)__func__);
/* Transmission parameters */
/* End transmission parameters */
cli_end(fd);
printf("%s, out\n", __func__);
}
int example_1(int a, int b, int *c) {
int fd;
int ret = 0;
printf("%s, in\n", __func__);
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &a, sizeof(int));
sock_write(fd, &b, sizeof(int));
sock_read(fd, c, sizeof(int));
sock_read(fd, &ret, sizeof(int));
printf("%s, a = %d, b = %d, c = %d, ret = %d\n", __func__, a, b, *c, ret);
/* End transmission parameters */
cli_end(fd);
printf("%s, out\n", __func__);
return ret;
}
#if 0
_CAPI RK_S32 SAMPLE_COMM_ISP_Init(RK_S32 CamId, rk_aiq_working_mode_t WDRMode,
RK_BOOL MultiCam, const char *iq_file_dir)
{
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &CamId, sizeof(RK_S32));
sock_write(fd, &WDRMode, sizeof(rk_aiq_working_mode_t));
sock_write(fd, &MultiCam, sizeof(RK_BOOL));
len = strlen(iq_file_dir) + 1;
sock_write(fd, &len, sizeof(int));
sock_write(fd, iq_file_dir, len);
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 SAMPLE_COMM_ISP_Stop(RK_S32 CamId)
{
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &CamId, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 SAMPLE_COMM_ISP_Run(RK_S32 CamId)
{
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &CamId, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 SAMPLE_COMM_ISP_SetFrameRate(RK_S32 CamId, RK_U32 uFps)
{
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &CamId, sizeof(RK_S32));
sock_write(fd, &uFps, sizeof(RK_U32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 ISP_RUN(int s32CamId, int fps)
{
int fd;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &s32CamId, sizeof(int));
sock_write(fd, &fps, sizeof(int));
/* End transmission parameters */
cli_end(fd);
return RK_ERR_SYS_OK;
}
_CAPI RK_S32 ISP_STOP(int s32CamId)
{
int fd;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &s32CamId, sizeof(int));
/* End transmission parameters */
cli_end(fd);
return RK_ERR_SYS_OK;
}
#endif
_CAPI RK_S32 RK_MPI_SYS_Init() {
int fd;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
/* End transmission parameters */
cli_end(fd);
return RK_ERR_SYS_OK;
}
_CAPI RK_S32 RK_MPI_SYS_Bind(const MPP_CHN_S *pstSrcChn,
const MPP_CHN_S *pstDestChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, pstSrcChn, sizeof(MPP_CHN_S));
sock_write(fd, pstDestChn, sizeof(MPP_CHN_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_SYS_UnBind(const MPP_CHN_S *pstSrcChn,
const MPP_CHN_S *pstDestChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, pstSrcChn, sizeof(MPP_CHN_S));
sock_write(fd, pstDestChn, sizeof(MPP_CHN_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_SetChnAttr(VI_PIPE ViPipe, VI_CHN ViChn,
const VI_CHN_ATTR_S *pstChnAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_write(fd, pstChnAttr, sizeof(VI_CHN_ATTR_S));
len = strlen(pstChnAttr->pcVideoNode) + 1;
sock_write(fd, &len, sizeof(int));
if (len)
sock_write(fd, pstChnAttr->pcVideoNode, len);
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_EnableChn(VI_PIPE ViPipe, VI_CHN ViChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_DisableChn(VI_PIPE ViPipe, VI_CHN ViChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_StartRegionLuma(VI_CHN ViChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_StopRegionLuma(VI_CHN ViChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_GetChnRegionLuma(
VI_PIPE ViPipe, VI_CHN ViChn, const VIDEO_REGION_INFO_S *pstRegionInfo,
RK_U64 *pu64LumaData, RK_S32 s32MilliSec) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_write(fd, pstRegionInfo, sizeof(VIDEO_REGION_INFO_S));
sock_write(fd, &s32MilliSec, sizeof(RK_S32));
sock_read(fd, pu64LumaData, sizeof(RK_U64) * 2);
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_RGN_SetCover(VI_PIPE ViPipe, VI_CHN ViChn,
const OSD_REGION_INFO_S *pstRgnInfo,
const COVER_INFO_S *pstCoverInfo) {
int fd;
RK_S32 ret = 0;
int haveinfo = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_write(fd, pstRgnInfo, sizeof(OSD_REGION_INFO_S));
if (pstCoverInfo) {
haveinfo = 1;
sock_write(fd, &haveinfo, sizeof(int));
sock_write(fd, pstCoverInfo, sizeof(COVER_INFO_S));
} else {
sock_write(fd, &haveinfo, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VI_StartStream(VI_PIPE ViPipe, VI_CHN ViChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &ViPipe, sizeof(VI_PIPE));
sock_write(fd, &ViChn, sizeof(VI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_RGA_CreateChn(RGA_CHN RgaChn, RGA_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &RgaChn, sizeof(RGA_CHN));
sock_write(fd, pstAttr, sizeof(RGA_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_RGA_DestroyChn(RGA_CHN RgaChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &RgaChn, sizeof(RGA_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_RGA_GetChnAttr(RGA_CHN RgaChn, RGA_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &RgaChn, sizeof(RGA_CHN));
sock_read(fd, pstAttr, sizeof(RGA_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_RGA_SetChnAttr(RGA_CHN RgaChn, const RGA_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &RgaChn, sizeof(RGA_CHN));
sock_write(fd, pstAttr, sizeof(RGA_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VO_CreateChn(VO_CHN VoChn, const VO_CHN_ATTR_S *pstAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VoChn, sizeof(VO_CHN));
sock_write(fd, pstAttr, sizeof(VO_CHN_ATTR_S));
if (pstAttr->pcDevNode) {
len = strlen(pstAttr->pcDevNode) + 1;
sock_write(fd, &len, sizeof(int));
sock_write(fd, pstAttr->pcDevNode, len);
} else {
len = 0;
sock_write(fd, &len, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VO_GetChnAttr(VO_CHN VoChn, VO_CHN_ATTR_S *pstAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
char *pcDevNode = NULL;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VoChn, sizeof(VO_CHN));
if (sock_read(fd, pstAttr, sizeof(VO_CHN_ATTR_S)) == SOCKERR_CLOSED) {
ret = -1;
goto out;
}
if (sock_read(fd, &len, sizeof(int)) == SOCKERR_CLOSED) {
ret = -1;
goto out;
}
if (len) {
pcDevNode = (char *)malloc(len);
if (sock_read(fd, pcDevNode, len) == SOCKERR_CLOSED) {
ret = -1;
free(pcDevNode);
goto out;
}
for (unsigned int i = 0; i < CONST_STRING_NUM; i++) {
if (const_string[i]) {
if (strcmp(pcDevNode, const_string[i]) == 0) {
pstAttr->pcDevNode = const_string[i];
free(pcDevNode);
break;
}
} else {
const_string[i] = pcDevNode;
pstAttr->pcDevNode = const_string[i];
break;
}
}
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
out:
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VO_SetChnAttr(VO_CHN VoChn, const VO_CHN_ATTR_S *pstAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VoChn, sizeof(VO_CHN));
sock_write(fd, pstAttr, sizeof(VO_CHN_ATTR_S));
if (pstAttr->pcDevNode) {
len = strlen(pstAttr->pcDevNode) + 1;
sock_write(fd, &len, sizeof(int));
sock_write(fd, pstAttr->pcDevNode, len);
} else {
len = 0;
sock_write(fd, &len, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VO_DestroyChn(VO_CHN VoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VoChn, sizeof(VO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_MD_CreateChn(ALGO_MD_CHN MdChn,
const ALGO_MD_ATTR_S *pstChnAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &MdChn, sizeof(ALGO_MD_CHN));
sock_write(fd, pstChnAttr, sizeof(ALGO_MD_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_MD_DestroyChn(ALGO_MD_CHN MdChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &MdChn, sizeof(ALGO_MD_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_MD_EnableSwitch(ALGO_MD_CHN MdChn, RK_BOOL bEnable) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &MdChn, sizeof(ALGO_MD_CHN));
sock_write(fd, &bEnable, sizeof(RK_BOOL));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_OD_CreateChn(ALGO_OD_CHN OdChn,
const ALGO_OD_ATTR_S *pstChnAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &OdChn, sizeof(ALGO_OD_CHN));
sock_write(fd, pstChnAttr, sizeof(ALGO_OD_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_OD_DestroyChn(ALGO_OD_CHN OdChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &OdChn, sizeof(ALGO_OD_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ALGO_OD_EnableSwitch(ALGO_OD_CHN OdChn, RK_BOOL bEnable) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &OdChn, sizeof(ALGO_OD_CHN));
sock_write(fd, &bEnable, sizeof(RK_BOOL));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ADEC_CreateChn(ADEC_CHN AdecChn,
const ADEC_CHN_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AdecChn, sizeof(ADEC_CHN));
sock_write(fd, pstAttr, sizeof(ADEC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_ADEC_DestroyChn(ADEC_CHN AdecChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AdecChn, sizeof(ADEC_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_SYS_RegisterEventCb(const MPP_CHN_S *pstChn,
RK_VOID *pHandle, EventCbFunc cb) {
printf("%s 1\n", __func__);
EVENT_CALL_LIST_S *node =
event_list_add(pstChn, pHandle, (void *)cb, CB_TYPE_EVENT);
printf("%s 2\n", __func__);
if (node) {
pthread_t tid = 0;
printf("%s 3\n", __func__);
pthread_create(&tid, NULL, event_server_run, (void *)node);
}
printf("%s 4\n", __func__);
return 0;
}
_CAPI RK_S32 RK_MPI_SYS_RegisterOutCb(const MPP_CHN_S *pstChn, OutCbFunc cb) {
EVENT_CALL_LIST_S *node =
event_list_add(pstChn, NULL, (void *)cb, CB_TYPE_OUT);
if (node) {
pthread_t tid = 0;
pthread_create(&tid, NULL, event_server_run, (void *)node);
}
return 0;
}
_CAPI RK_S32 RK_MPI_SYS_SendMediaBuffer(MOD_ID_E enModID, RK_S32 s32ChnID,
MEDIA_BUFFER buffer) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &enModID, sizeof(MOD_ID_E));
sock_write(fd, &s32ChnID, sizeof(RK_S32));
sock_write(fd, &buffer, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_SYS_GetMediaBuffer(MOD_ID_E enModID, RK_S32 s32ChnID,
RK_S32 s32MilliSec) {
int fd;
MEDIA_BUFFER mb;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &enModID, sizeof(MOD_ID_E));
sock_write(fd, &s32ChnID, sizeof(RK_S32));
sock_write(fd, &s32MilliSec, sizeof(RK_S32));
sock_read(fd, &mb, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return mb;
}
_CAPI RK_S32 RK_MPI_MB_ReleaseBuffer(MEDIA_BUFFER mb) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
MB_LIST_S info;
if (mb_list_get(mb, &info) == 0) {
del_list_del(mb);
if (info.ptr)
munmap(info.ptr, info.size);
close(info.fd);
close(info.devfd);
}
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI void *RK_MPI_MB_GetPtr(MEDIA_BUFFER mb) {
int fd;
int handle = 0;
int size = 0;
int mbfd = 0;
void *ptr = NULL;
MB_LIST_S info;
int devfd;
if (mb_list_get(mb, &info) == 0) {
if (info.ptr == NULL) {
info.ptr = MbMap(info.devfd, info.handle, info.size);
mb_list_update(mb, &info);
}
printf("%s 1 ptr = %p\n", __func__, info.ptr);
return info.ptr;
}
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_recv_devfd(fd, &devfd);
sock_read(fd, &handle, sizeof(int));
sock_read(fd, &size, sizeof(int));
/* End transmission parameters */
cli_end(fd);
ptr = MbMap(devfd, handle, size);
mbfd = MbHandleToFD(devfd, handle);
mb_list_add(mb, ptr, devfd, mbfd, handle, size);
printf("%s 2 ptr = %p, handle = %d, mbfd = %d\n", __func__, ptr, handle,
mbfd);
return ptr;
}
_CAPI int RK_MPI_MB_GetFD(MEDIA_BUFFER mb) {
int fd;
int handle = 0;
int size = 0;
int mbfd = 0;
MB_LIST_S info;
int devfd;
if (mb_list_get(mb, &info) == 0) {
return info.fd;
}
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_recv_devfd(fd, &devfd);
sock_read(fd, &handle, sizeof(int));
sock_read(fd, &size, sizeof(int));
/* End transmission parameters */
cli_end(fd);
mbfd = MbHandleToFD(devfd, handle);
mb_list_add(mb, NULL, devfd, mbfd, handle, size);
return mbfd;
}
_CAPI RK_S32 RK_MPI_MB_GetImageInfo(MEDIA_BUFFER mb,
MB_IMAGE_INFO_S *pstImageInfo) {
int fd;
int ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, pstImageInfo, sizeof(MB_IMAGE_INFO_S));
sock_read(fd, &ret, sizeof(int));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI size_t RK_MPI_MB_GetSize(MEDIA_BUFFER mb) {
int fd;
size_t ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(size_t));
/* End transmission parameters */
cli_end(fd);
printf("%s size = %d\n", __func__, ret);
return ret;
}
_CAPI MOD_ID_E RK_MPI_MB_GetModeID(MEDIA_BUFFER mb) {
int fd;
MOD_ID_E ret;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(MOD_ID_E));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S16 RK_MPI_MB_GetChannelID(MEDIA_BUFFER mb) {
int fd;
RK_S16 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S16));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_U64 RK_MPI_MB_GetTimestamp(MEDIA_BUFFER mb) {
int fd;
RK_U64 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_U64));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_SetTimestamp(MEDIA_BUFFER mb, RK_U64 timestamp) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_write(fd, ×tamp, sizeof(RK_U64));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_SetSize(MEDIA_BUFFER mb, RK_U32 size) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_write(fd, &size, sizeof(RK_U32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_MB_CreateBuffer(RK_U32 u32Size, RK_BOOL boolHardWare,
RK_U8 u8Flag) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &u32Size, sizeof(RK_U32));
sock_write(fd, &boolHardWare, sizeof(RK_BOOL));
sock_write(fd, &u8Flag, sizeof(RK_U8));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_MB_CreateImageBuffer(MB_IMAGE_INFO_S *pstImageInfo,
RK_BOOL boolHardWare,
RK_U8 u8Flag) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, pstImageInfo, sizeof(MB_IMAGE_INFO_S));
sock_write(fd, &boolHardWare, sizeof(RK_BOOL));
sock_write(fd, &u8Flag, sizeof(RK_U8));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_MB_CreateAudioBuffer(RK_U32 u32BufferSize,
RK_BOOL boolHardWare) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &u32BufferSize, sizeof(RK_U32));
sock_write(fd, &boolHardWare, sizeof(RK_BOOL));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER_POOL RK_MPI_MB_POOL_Create(MB_POOL_PARAM_S *pstPoolParam) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, pstPoolParam, sizeof(MB_POOL_PARAM_S));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_POOL_Destroy(MEDIA_BUFFER_POOL MBPHandle) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &MBPHandle, sizeof(MEDIA_BUFFER_POOL));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_MB_POOL_GetBuffer(MEDIA_BUFFER_POOL MBPHandle,
RK_BOOL bIsBlock) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &MBPHandle, sizeof(MEDIA_BUFFER_POOL));
sock_write(fd, &bIsBlock, sizeof(RK_BOOL));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI MEDIA_BUFFER RK_MPI_MB_ConvertToImgBuffer(MEDIA_BUFFER mb,
MB_IMAGE_INFO_S *pstImageInfo) {
int fd;
MEDIA_BUFFER ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_write(fd, pstImageInfo, sizeof(MB_IMAGE_INFO_S));
sock_read(fd, &ret, sizeof(MEDIA_BUFFER));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_GetFlag(MEDIA_BUFFER mb) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_GetTsvcLevel(MEDIA_BUFFER mb) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_BOOL RK_MPI_MB_IsViFrame(MEDIA_BUFFER mb) {
int fd;
RK_BOOL ret;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_BOOL));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_MB_TsNodeDump(MEDIA_BUFFER mb) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &mb, sizeof(MEDIA_BUFFER));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VDEC_CreateChn(VDEC_CHN VdChn,
const VDEC_CHN_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VdChn, sizeof(VDEC_CHN));
sock_write(fd, pstAttr, sizeof(VDEC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VDEC_DestroyChn(VDEC_CHN VdChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VdChn, sizeof(VDEC_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_CreateChn(VENC_CHN VencChn,
VENC_CHN_ATTR_S *stVencChnAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, stVencChnAttr, sizeof(VENC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_DestroyChn(VENC_CHN VencChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_CreateJpegLightChn(VENC_CHN VencChn,
VENC_CHN_ATTR_S *stVencChnAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, stVencChnAttr, sizeof(VENC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_GetVencChnAttr(VENC_CHN VencChn,
VENC_CHN_ATTR_S *stVencChnAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_read(fd, stVencChnAttr, sizeof(VENC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetVencChnAttr(VENC_CHN VencChn,
VENC_CHN_ATTR_S *stVencChnAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, stVencChnAttr, sizeof(VENC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_GetRcParam(VENC_CHN VencChn,
VENC_RC_PARAM_S *pstRcParam) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_read(fd, pstRcParam, sizeof(VENC_RC_PARAM_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetRcParam(VENC_CHN VencChn,
const VENC_RC_PARAM_S *pstRcParam) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRcParam, sizeof(VENC_RC_PARAM_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetJpegParam(VENC_CHN VencChn,
const VENC_JPEG_PARAM_S *pstJpegParam) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstJpegParam, sizeof(VENC_JPEG_PARAM_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_RGN_Init(VENC_CHN VencChn,
VENC_COLOR_TBL_S *stColorTbl) {
int fd;
RK_S32 ret = 0;
int havetbl = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
if (stColorTbl) {
havetbl = 1;
sock_write(fd, &havetbl, sizeof(int));
sock_write(fd, stColorTbl, sizeof(VENC_COLOR_TBL_S));
} else {
sock_write(fd, &havetbl, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_RGN_SetBitMap(VENC_CHN VencChn,
const OSD_REGION_INFO_S *pstRgnInfo,
const BITMAP_S *pstBitmap) {
int fd;
RK_S32 ret = 0;
int len = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRgnInfo, sizeof(OSD_REGION_INFO_S));
sock_write(fd, pstBitmap, sizeof(BITMAP_S));
if (pstBitmap->pData) {
if (pstBitmap->enPixelFormat == PIXEL_FORMAT_ARGB_8888)
len = pstBitmap->u32Width * pstBitmap->u32Height * 4;
// len = malloc_usable_size(pstBitmap->pData) - 4;
printf("%s %d, %d\n", __func__, len,
malloc_usable_size(pstBitmap->pData) - 4);
}
sock_write(fd, &len, sizeof(int));
if (len > 0) {
sock_write(fd, pstBitmap->pData, len);
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_StartRecvFrame(
VENC_CHN VencChn, const VENC_RECV_PIC_PARAM_S *pstRecvParam) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRecvParam, sizeof(VENC_RECV_PIC_PARAM_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_RGN_SetCover(VENC_CHN VencChn,
const OSD_REGION_INFO_S *pstRgnInfo,
const COVER_INFO_S *pstCoverInfo) {
int fd;
RK_S32 ret = 0;
int haveinfo = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRgnInfo, sizeof(OSD_REGION_INFO_S));
if (pstCoverInfo) {
haveinfo = 1;
sock_write(fd, &haveinfo, sizeof(int));
sock_write(fd, pstCoverInfo, sizeof(COVER_INFO_S));
} else {
sock_write(fd, &haveinfo, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_RGN_SetCoverEx(VENC_CHN VencChn,
const OSD_REGION_INFO_S *pstRgnInfo,
const COVER_INFO_S *pstCoverInfo) {
int fd;
RK_S32 ret = 0;
int haveinfo = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRgnInfo, sizeof(OSD_REGION_INFO_S));
if (pstCoverInfo) {
haveinfo = 1;
sock_write(fd, &haveinfo, sizeof(int));
sock_write(fd, pstCoverInfo, sizeof(COVER_INFO_S));
} else {
sock_write(fd, &haveinfo, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetGopMode(VENC_CHN VencChn,
VENC_GOP_ATTR_S *pstGopModeAttr) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstGopModeAttr, sizeof(VENC_GOP_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_GetRoiAttr(VENC_CHN VencChn,
VENC_ROI_ATTR_S *pstRoiAttr,
RK_S32 roi_index) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, &roi_index, sizeof(RK_S32));
sock_read(fd, pstRoiAttr, sizeof(VENC_ROI_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetRoiAttr(VENC_CHN VencChn,
const VENC_ROI_ATTR_S *pstRoiAttr,
RK_S32 region_cnt) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, pstRoiAttr, sizeof(VENC_ROI_ATTR_S));
sock_write(fd, ®ion_cnt, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VENC_SetResolution(
VENC_CHN VencChn, VENC_RESOLUTION_PARAM_S stResolutionParam) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VencChn, sizeof(VENC_CHN));
sock_write(fd, &stResolutionParam, sizeof(VENC_RESOLUTION_PARAM_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_CreateDev(VMIX_DEV VmDev,
VMIX_DEV_INFO_S *pstDevInfo) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, pstDevInfo, sizeof(VMIX_DEV_INFO_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_DestroyDev(VMIX_DEV VmDev) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_EnableChn(VMIX_DEV VmDev, VMIX_CHN VmChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_DisableChn(VMIX_DEV VmDev, VMIX_CHN VmChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_SetLineInfo(VMIX_DEV VmDev, VMIX_CHN VmChn,
VMIX_LINE_INFO_S VmLine) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_write(fd, &VmLine, sizeof(VMIX_LINE_INFO_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_ShowChn(VMIX_DEV VmDev, VMIX_CHN VmChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_HideChn(VMIX_DEV VmDev, VMIX_CHN VmChn) {
int fd;
RK_S32 ret = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_GetChnRegionLuma(
VMIX_DEV VmDev, VMIX_CHN VmChn, const VIDEO_REGION_INFO_S *pstRegionInfo,
RK_U64 *pu64LumaData, RK_S32 s32MilliSec) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_write(fd, pstRegionInfo, sizeof(VIDEO_REGION_INFO_S));
sock_write(fd, &s32MilliSec, sizeof(RK_S32));
sock_read(fd, pu64LumaData, sizeof(RK_U64) * 2);
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_VMIX_RGN_SetCover(VMIX_DEV VmDev, VMIX_CHN VmChn,
const OSD_REGION_INFO_S *pstRgnInfo,
const COVER_INFO_S *pstCoverInfo) {
int fd;
RK_S32 ret = 0;
int haveinfo = 0;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &VmDev, sizeof(VMIX_DEV));
sock_write(fd, &VmChn, sizeof(VMIX_CHN));
sock_write(fd, pstRgnInfo, sizeof(OSD_REGION_INFO_S));
if (pstCoverInfo) {
haveinfo = 1;
sock_write(fd, &haveinfo, sizeof(int));
sock_write(fd, pstCoverInfo, sizeof(COVER_INFO_S));
} else {
sock_write(fd, &haveinfo, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_SetChnAttr(AO_CHN AoChn, const AO_CHN_ATTR_S *pstAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_write(fd, pstAttr, sizeof(AO_CHN_ATTR_S));
if (pstAttr->pcAudioNode) {
len = strlen(pstAttr->pcAudioNode) + 1;
sock_write(fd, &len, sizeof(int));
sock_write(fd, pstAttr->pcAudioNode, len);
} else {
len = 0;
sock_write(fd, &len, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_EnableChn(AO_CHN AoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_DisableChn(AO_CHN AoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_SetVolume(AO_CHN AoChn, RK_S32 s32Volume) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_write(fd, &s32Volume, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_GetVolume(AO_CHN AoChn, RK_S32 *ps32Volume) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, ps32Volume, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_SetVqeAttr(AO_CHN AoChn, AO_VQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_write(fd, pstVqeConfig, sizeof(AO_VQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_GetVqeAttr(AO_CHN AoChn, AO_VQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, pstVqeConfig, sizeof(AO_VQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_EnableVqe(AO_CHN AoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_DisableVqe(AO_CHN AoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_QueryChnStat(AO_CHN AoChn, AO_CHN_STATE_S *pstStatus) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, pstStatus, sizeof(AO_CHN_STATE_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AO_ClearChnBuf(AO_CHN AoChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AoChn, sizeof(AO_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AENC_CreateChn(AENC_CHN AencChn,
const AENC_CHN_ATTR_S *pstAttr) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AencChn, sizeof(AENC_CHN));
sock_write(fd, pstAttr, sizeof(AENC_CHN_ATTR_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AENC_DestroyChn(AENC_CHN AencChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AencChn, sizeof(AENC_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_SetChnAttr(VENC_CHN AiChn,
const AI_CHN_ATTR_S *pstAttr) {
int fd;
int len;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(VENC_CHN));
sock_write(fd, pstAttr, sizeof(AI_CHN_ATTR_S));
if (pstAttr->pcAudioNode) {
len = strlen(pstAttr->pcAudioNode) + 1;
sock_write(fd, &len, sizeof(int));
sock_write(fd, pstAttr->pcAudioNode, len);
} else {
len = 0;
sock_write(fd, &len, sizeof(int));
}
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_EnableChn(AI_CHN AiChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_DisableChn(AI_CHN AiChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_SetVolume(AI_CHN AiChn, RK_S32 s32Volume) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_write(fd, &s32Volume, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_GetVolume(AI_CHN AiChn, RK_S32 *ps32Volume) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, ps32Volume, sizeof(RK_S32));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_SetTalkVqeAttr(AI_CHN AiChn,
AI_TALKVQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_write(fd, pstVqeConfig, sizeof(AI_TALKVQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_GetTalkVqeAttr(AI_CHN AiChn,
AI_TALKVQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, pstVqeConfig, sizeof(AI_TALKVQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_SetRecordVqeAttr(AI_CHN AiChn,
AI_RECORDVQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_write(fd, pstVqeConfig, sizeof(AI_RECORDVQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_GetRecordVqeAttr(AI_CHN AiChn,
AI_RECORDVQE_CONFIG_S *pstVqeConfig) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, pstVqeConfig, sizeof(AI_RECORDVQE_CONFIG_S));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_EnableVqe(AI_CHN AiChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_StartStream(AI_CHN AiChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
}
_CAPI RK_S32 RK_MPI_AI_DisableVqe(AI_CHN AiChn) {
int fd;
RK_S32 ret = RK_ERR_SYS_OK;
fd = cli_begin((char *)__func__);
/* Transmission parameters */
sock_write(fd, &AiChn, sizeof(AI_CHN));
sock_read(fd, &ret, sizeof(RK_S32));
/* End transmission parameters */
cli_end(fd);
return ret;
} | 25.030585 | 81 | 0.630452 |
87b8a0aa6812d30e13c12400662c46eea59acae6 | 3,018 | cpp | C++ | Frameworks/Starboard/dlfcn.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | Frameworks/Starboard/dlfcn.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | Frameworks/Starboard/dlfcn.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | //******************************************************************************
//
// Copyright (c) 2016 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 <dlfcn.h>
#include <windows.h>
#include <memory>
#include <string>
#include <string.h>
/**
@Status Caveat
@Notes This function can only find libraries in the root of the current
package. The mode parameter is ignored. In addition, error information
is not available on failure.
*/
void* dlopen(const char* path, int mode) {
try {
// We can only load libraries from within our own package or any dependent
// packages, so absolute paths are not much use to us. From whatever path
// we're given, just strip off everything but the leaf file name and try
// to load that. This isn't always correct, but it is sometimes correct.
std::wstring widePath(path, path + strlen(path));
DWORD pathLength = GetFullPathNameW(widePath.c_str(), 0, nullptr, nullptr);
auto fullPath = std::make_unique<WCHAR[]>(pathLength);
LPWSTR fileName = nullptr;
GetFullPathNameW(widePath.c_str(), pathLength, fullPath.get(), &fileName);
return LoadPackagedLibrary(fileName, 0);
} catch (...) {
}
return NULL;
}
/**
@Status Caveat
@Notes Error information is not available on failure
*/
void* dlsym(void* handle, const char* symbol) {
HMODULE module = static_cast<HMODULE>(handle);
// This platform doesn't represent Objective-C class symbols in the same way as
// the reference platform, so some mapping of symbols is necessary
static const char OUR_CLASS_PREFIX[] = "_OBJC_CLASS_";
static const char THEIR_CLASS_PREFIX[] = "OBJC_CLASS_$_";
static const size_t THEIR_CLASS_PREFIX_LENGTH = sizeof(THEIR_CLASS_PREFIX) - 1;
try {
if (0 == strncmp(symbol, THEIR_CLASS_PREFIX, THEIR_CLASS_PREFIX_LENGTH)) {
std::string transformedSymbol(OUR_CLASS_PREFIX);
transformedSymbol.append(symbol + THEIR_CLASS_PREFIX_LENGTH);
return GetProcAddress(module, transformedSymbol.c_str());
}
} catch (...) {
return nullptr;
}
return GetProcAddress(module, symbol);
}
/**
@Status Caveat
@Notes Error information is not available on failure
*/
int dlclose(void* handle) {
HMODULE module = static_cast<HMODULE>(handle);
return !FreeLibrary(module);
}
| 34.295455 | 83 | 0.66004 |
87bddd84c173926dd88f416cdc59985934e6e6da | 906 | cpp | C++ | test/logger_test.cpp | OpenWinch/OpenWinch-C | efbce8f0c892927560f6b719d347578c85babade | [
"Apache-2.0"
] | 1 | 2020-11-23T23:52:19.000Z | 2020-11-23T23:52:19.000Z | test/logger_test.cpp | OpenWinch/OpenWinch-C | efbce8f0c892927560f6b719d347578c85babade | [
"Apache-2.0"
] | 3 | 2020-11-24T22:00:01.000Z | 2021-02-23T22:32:31.000Z | test/logger_test.cpp | OpenWinch/OpenWinch-C | efbce8f0c892927560f6b719d347578c85babade | [
"Apache-2.0"
] | null | null | null | /**
* @file logger_test.cpp
* @author Mickael GAILLARD (mick.gaillard@gmail.com)
* @brief OpenWinch Project
*
* @copyright Copyright © 2020-2021
*/
#include "logger.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class LoggerTest : public ::testing::Test {
protected:
Logger *logger = nullptr;
LoggerTest() { }
~LoggerTest() override { }
void SetUp() override {
this->logger = &Logger::get();
}
void TearDown() override { }
};
TEST_F(LoggerTest, MethodLive) {
this->logger->live("Log live.");
}
TEST_F(LoggerTest, MethodInfo) {
this->logger->info("Log info.");
}
TEST_F(LoggerTest, MethodDebug) {
this->logger->debug("Log debug.");
}
TEST_F(LoggerTest, MethodWarning) {
this->logger->warning("Log warning.");
}
TEST_F(LoggerTest, MethodError) {
this->logger->error("Log error.");
}
TEST_F(LoggerTest, MethodFatal) {
this->logger->fatal("Log fatal.");
}
| 18.489796 | 53 | 0.664459 |
87c3980da828df91b88b169e33fcd02054647039 | 1,061 | cpp | C++ | Stack/parenthesis_matching.cpp | ahanavish/DSA-using-CPP | cc96ae5cabef1dfa4ac183c1ea1510f74e3f42d9 | [
"MIT"
] | null | null | null | Stack/parenthesis_matching.cpp | ahanavish/DSA-using-CPP | cc96ae5cabef1dfa4ac183c1ea1510f74e3f42d9 | [
"MIT"
] | null | null | null | Stack/parenthesis_matching.cpp | ahanavish/DSA-using-CPP | cc96ae5cabef1dfa4ac183c1ea1510f74e3f42d9 | [
"MIT"
] | 1 | 2021-11-29T06:12:05.000Z | 2021-11-29T06:12:05.000Z | #include <iostream>
#include <string.h>
using namespace std;
class stack
{
int size;
int top;
char *sta;
char *str;
public:
stack(char *s)
{
str = s;
size = strlen(s);
top = -1;
sta = new char[size];
}
~stack()
{
delete []sta;
sta = 0;
}
bool balance()
{
int i=0;
while(str[i] != '\0')
{
if(str[i] == '(')
push(str[i]);
else if(str[i] == ')')
if(pop() == 0)
return false;
i++;
}
if(top == -1)
return true;
else
return false;
}
void push(int n)
{
top++;
sta[top] = n;
}
int pop()
{
if(top == -1)
return 0;
sta[top] = -10;
top--;
return 1;
}
};
int main()
{
char s[] = "(a+b)*(c/6)";
stack st(s);
if(st.balance() == true)
cout<<"-> Balanced";
else
cout<<"-> Not balanced";
} | 15.157143 | 34 | 0.356268 |
87cb31bab04de90272a7997507279300aa184c70 | 1,532 | cpp | C++ | Display.cpp | mmiecz/chip8 | 2e0710547ef44a04846db16c58930f64ec0777a0 | [
"MIT"
] | null | null | null | Display.cpp | mmiecz/chip8 | 2e0710547ef44a04846db16c58930f64ec0777a0 | [
"MIT"
] | null | null | null | Display.cpp | mmiecz/chip8 | 2e0710547ef44a04846db16c58930f64ec0777a0 | [
"MIT"
] | null | null | null | //
// Created by mhl on 19.10.16.
//
#include "Display.h"
#include <string>
#include <iostream>
#include <SDL2/SDL_ttf.h>
Display::Display()
: m_window(nullptr), m_surface(nullptr) {
}
bool Display::init(const std::string &title, int width, int height) {
if( SDL_Init( SDL_INIT_VIDEO) < 0 ) {
std::cerr << "Unable to initialize SDL\n";
return false;
}
SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &m_window, &m_renderer);
SDL_RenderPresent(m_renderer);
if(m_window == nullptr ) {
std::cerr << "Unable to create SDL Window";
return false;
}
m_surface = SDL_GetWindowSurface( m_window );
TTF_Init();
TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 24); //this opens a font style and sets a size
if(font == nullptr) {
std::cerr << "Cannot load ttf\n" << TTF_GetError();
}
SDL_Color font_color = {255, 255, 255};
auto surfaceMessage = TTF_RenderText_Solid(font, "Hello World", font_color);
SDL_Texture* message = SDL_CreateTextureFromSurface(m_renderer, surfaceMessage);
SDL_Rect message_rect; //create a rect
message_rect.x = 0; //controls the rect's x coordinate
message_rect.y = 0; // controls the rect's y coordinte
message_rect.w = 75; // controls the width of the rect
message_rect.h = 20; // controls the height of the rect
SDL_RenderCopy(m_renderer, message, NULL, &message_rect);
SDL_RenderPresent(m_renderer);
return true;
}
| 28.37037 | 135 | 0.671671 |
d7acb86feb64b28b4c6bd8012f4577137f0defb3 | 1,450 | hpp | C++ | test/timer/classes.hpp | smart-cloud/actor-zeta | 9597d6c21843a5e24a7998d09ff041d2f948cc63 | [
"BSD-3-Clause"
] | 20 | 2016-01-07T07:37:52.000Z | 2019-06-02T12:04:25.000Z | test/timer/classes.hpp | smart-cloud/actor-zeta | 9597d6c21843a5e24a7998d09ff041d2f948cc63 | [
"BSD-3-Clause"
] | 30 | 2017-03-10T14:47:46.000Z | 2019-05-09T19:23:25.000Z | test/timer/classes.hpp | jinncrafters/actor-zeta | 9597d6c21843a5e24a7998d09ff041d2f948cc63 | [
"BSD-3-Clause"
] | 6 | 2017-03-10T14:06:01.000Z | 2018-08-13T18:19:37.000Z | #pragma once
#include <cassert>
#include <chrono>
#include <memory>
#include <vector>
#include <actor-zeta.hpp>
#include <actor-zeta/detail/memory_resource.hpp>
#include "tooltestsuites/scheduler_test.hpp"
#include "tooltestsuites/clock_test.hpp"
static std::atomic<uint64_t> alarm_counter{0};
using actor_zeta::detail::pmr::memory_resource;
/// non thread safe
constexpr static auto alarm_id = actor_zeta::make_message_id(0);
class supervisor_lite final : public actor_zeta::cooperative_supervisor<supervisor_lite> {
public:
explicit supervisor_lite(memory_resource* ptr)
: cooperative_supervisor(ptr, "network")
, executor_(new actor_zeta::test::scheduler_test_t(1, 1)) {
add_handler(alarm_id, &supervisor_lite::alarm);
scheduler()->start();
}
auto clock() noexcept -> actor_zeta::test::clock_test& {
return executor_->clock();
}
~supervisor_lite() override = default;
void alarm() {
alarm_counter += 1;
}
protected:
auto scheduler_impl() noexcept -> actor_zeta::scheduler_abstract_t* final { return executor_.get(); }
auto enqueue_impl(actor_zeta::message_ptr msg, actor_zeta::execution_unit*) -> void final {
{
set_current_message(std::move(msg));
execute(this, current_message());
}
}
private:
std::unique_ptr<actor_zeta::test::scheduler_test_t> executor_;
std::vector<actor_zeta::actor> actors_;
}; | 29 | 105 | 0.696552 |
d7ad55b4b9ea461df80b04f74b7d2b28f7565485 | 2,185 | cpp | C++ | bcos-gateway/bcos-gateway/protocol/GatewayNodeStatus.cpp | contropist/FISCO-BCOS | 1605c371448b410674559bb1c9e98bab722f036b | [
"Apache-2.0"
] | null | null | null | bcos-gateway/bcos-gateway/protocol/GatewayNodeStatus.cpp | contropist/FISCO-BCOS | 1605c371448b410674559bb1c9e98bab722f036b | [
"Apache-2.0"
] | null | null | null | bcos-gateway/bcos-gateway/protocol/GatewayNodeStatus.cpp | contropist/FISCO-BCOS | 1605c371448b410674559bb1c9e98bab722f036b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @file GatewayNodeStatus.cpp
* @author: yujiechen
* @date 2021-12-31
*/
#include "GatewayNodeStatus.h"
#include <bcos-tars-protocol/Common.h>
#include <bcos-tars-protocol/protocol/GroupNodeInfoImpl.h>
using namespace bcos;
using namespace bcos::protocol;
using namespace bcos::gateway;
GatewayNodeStatus::GatewayNodeStatus()
: m_tarsStatus(std::make_shared<bcostars::GatewayNodeStatus>())
{}
bytesPointer GatewayNodeStatus::encode()
{
// append groupInfos to m_tarsStatus
m_tarsStatus->nodeList.clear();
for (auto const& it : m_groupNodeInfos)
{
auto groupNodeInfoImpl =
std::dynamic_pointer_cast<bcostars::protocol::GroupNodeInfoImpl>(it);
m_tarsStatus->nodeList.emplace_back(groupNodeInfoImpl->inner());
}
auto encodeData = std::make_shared<bytes>();
tars::TarsOutputStream<bcostars::protocol::BufferWriterByteVector> output;
m_tarsStatus->writeTo(output);
output.getByteBuffer().swap(*encodeData);
return encodeData;
}
void GatewayNodeStatus::decode(bytesConstRef _data)
{
tars::TarsInputStream<tars::BufferReader> input;
input.setBuffer((const char*)_data.data(), _data.size());
m_tarsStatus->readFrom(input);
// decode into m_groupNodeInfos
m_groupNodeInfos.clear();
for (auto& it : m_tarsStatus->nodeList)
{
auto groupNodeInfo = std::make_shared<bcostars::protocol::GroupNodeInfoImpl>(
[m_groupNodeInfo = it]() mutable { return &m_groupNodeInfo; });
m_groupNodeInfos.emplace_back(groupNodeInfo);
}
} | 35.819672 | 85 | 0.722197 |
d7afdb497afd4db9747e33ac791f78e58c0dcd1b | 77,409 | cpp | C++ | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32469I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/CarouselMenu/st_menu_button_pressed.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32469I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/CarouselMenu/st_menu_button_pressed.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32469I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/CarouselMenu/st_menu_button_pressed.cpp | hwiwonl/ACES | 9b9a6766a177c531384b863854459a7e016dbdcc | [
"NCSA"
] | null | null | null | // Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _st_menu_button_pressed[] LOCATION_EXTFLASH_ATTRIBUTE = { // 62x62 ARGB8888 pixels.
0x18,0x0c,0x00,0x00,0x18,0x0c,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x0c,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x20,0x10,0x00,0x00,0x20,0x14,0x00,0x00,0x18,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,
0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,
0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x20,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x18,0x0c,0x00,0x00,0x18,0x10,0x00,0x00,
0x18,0x0c,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x18,0x10,0x00,0x00,0x20,0x10,0x00,0x00,0x20,0x14,0x00,0x00,0x18,0x10,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,
0x28,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x08,0x28,0x1c,0x00,0x24,0x28,0x1c,0x00,0x3c,0x28,0x1c,0x00,0x55,0x28,0x1c,0x00,0x65,0x28,0x1c,0x00,0x71,0x28,0x1c,0x00,0x79,0x28,0x20,0x00,0x82,0x28,0x1c,0x00,0x82,0x28,0x1c,0x00,0x79,0x28,0x1c,0x00,0x71,
0x28,0x1c,0x00,0x65,0x28,0x1c,0x00,0x55,0x28,0x1c,0x00,0x3c,0x28,0x1c,0x00,0x24,0x28,0x1c,0x00,0x08,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x18,0x10,0x00,0x00,0x18,0x0c,0x00,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x28,0x1c,0x00,0x0c,0x28,0x1c,0x00,0x38,0x28,0x20,0x00,0x65,0x28,0x20,0x00,0x7d,0x28,0x20,0x00,0x82,0x28,0x20,0x00,0x82,0x28,0x20,0x00,0x82,0x30,0x20,0x00,0x82,0x30,0x20,0x00,0x7d,0x30,0x20,0x00,0x82,0x30,0x20,0x00,0x82,0x30,0x20,0x00,0x7d,0x30,0x20,0x00,0x82,0x28,0x20,0x00,0x82,0x30,0x20,0x00,0x82,0x28,0x20,0x00,0x82,
0x28,0x20,0x00,0x82,0x28,0x20,0x00,0x82,0x28,0x20,0x00,0x7d,0x28,0x20,0x00,0x61,0x28,0x1c,0x00,0x38,0x28,0x1c,0x00,0x10,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0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x96,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xd0,0xcc,0xb8,0xc7,0x60,0x4c,0x08,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,
0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x54,0x10,0x82,0x90,0x80,0x50,0x96,0xd0,0xd0,0xb8,0xcb,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0x78,0x70,0x50,0x9a,0x30,0x28,0x00,0x82,0x48,0x3c,0x20,0x28,0xf8,0xfc,0xf8,0x00,
0x30,0x20,0x00,0x00,0x58,0x50,0x38,0x4d,
0x38,0x28,0x00,0x82,0xb0,0xa8,0x98,0xb6,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xb0,0xa8,0x88,0xae,
0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x7d,0x60,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x4c,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,
0x58,0x4c,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0xb0,0xa4,0x80,0xaa,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xb0,0xac,0xa0,0xb6,0x38,0x28,0x00,0x82,0x58,0x50,0x30,0x4d,0xf8,0xfc,0xf8,0x00,
0x30,0x24,0x00,0x00,0x58,0x4c,0x30,0x65,0x38,0x28,0x00,0x82,0xd0,0xc8,0xc0,0xcb,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xb8,0xac,0x90,0xb2,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,
0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x60,0x4c,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x82,
0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x48,0x00,0x7d,0x58,0x48,0x00,0x82,0xd8,0xd0,0xc0,0xcb,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xd0,0xc8,0xc0,0xcb,0x38,0x28,0x00,0x7d,0x58,0x4c,0x28,0x65,0xf8,0xfc,0xf8,0x00,
0x30,0x24,0x00,0x00,0x50,0x44,0x20,0x75,0x38,0x2c,0x00,0x82,0xe0,0xe0,0xd8,0xdf,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xd0,0xcc,0xb8,0xcb,0x60,0x50,0x08,0x82,0x60,0x48,0x00,0x7d,0x58,0x48,0x00,0x82,
0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x58,0x4c,0x00,0x82,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x60,0x4c,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,
0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x90,0x84,0x50,0x96,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0x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,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,
0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x4c,0x00,0x7d,0x60,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0xd8,0xd0,0xc0,0xcb,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xf8,0xf8,0xf7,0x40,0x34,0x00,0x82,0x40,0x30,0x00,0x7d,
0xd0,0xd0,0xc8,0x24,0xf8,0xfc,0xf8,0x00,
0x30,0x24,0x00,0x00,0xf8,0xfc,0xf8,0x04,0x60,0x58,0x30,0x79,0x40,0x30,0x00,0x82,0xd8,0xd4,0xc8,0xd3,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x82,0x60,0x4c,0x00,0x7d,0x58,0x48,0x00,0x7d,
0x60,0x48,0x00,0x82,0x58,0x4c,0x00,0x82,0x58,0x48,0x00,0x7d,0x60,0x48,0x00,0x82,0x58,0x4c,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x7d,0xb0,0xa4,0x80,0xaa,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xd8,0xd4,0xc8,0xd3,0x40,0x30,0x00,0x82,0x60,0x54,0x30,0x79,0xf8,0xfc,0xf8,0x08,0xf8,0xfc,0xf8,0x00,
0x30,0x24,0x00,0x00,0x38,0x28,0x00,0x00,0x90,0x88,0x70,0x65,0x40,0x2c,0x00,0x82,0x98,0x90,0x78,0xa6,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0x98,0x90,0x60,0x9e,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x58,0x48,0x00,0x82,0x60,0x48,0x00,0x7d,0x58,0x4c,0x00,0x82,0x60,0x48,0x00,0x7d,
0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x58,0x48,0x00,0x7d,0x60,0x4c,0x00,0x82,0x60,0x48,0x00,0x82,0x58,0x48,0x00,0x7d,0x68,0x54,0x10,0x82,0x90,0x80,0x50,0x96,0xd0,0xd0,0xb8,0xcb,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,
0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0xf8,0xfc,0xf8,0xff,0x98,0x90,0x78,0xa6,0x40,0x2c,0x00,0x82,0x90,0x8c,0x70,0x65,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x30,0x24,0x00,0x00,0x38,0x28,0x00,0x00,
0xd8,0xd4,0xc8,0x34,0x40,0x30,0x08,0x7d,0x48,0x38,0x08,0x82,0xf8,0xf4,0xf8,0xf3,0x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38,0x00,0x82,0x48,0x38,0x00,0x82,
0x48,0x38,0x00,0x7d,0x68,0x5c,0x30,0x79,0xa0,0x98,0x80,0x75,0xe0,0xe4,0xd8,0x6d,0xf8,0xfc,0xf8,0x49,0xf8,0xfc,0xf8,0x18,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x18,0x10,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x1c,0x00,0x00,
0x28,0x1c,0x00,0x00,0x28,0x20,0x00,0x00,0x30,0x20,0x00,0x00,0x30,0x20,0x00,0x00,0x30,0x24,0x00,0x00,0x30,0x24,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x40,0x30,0x00,0x00,0xf8,0xfc,0xf8,0x0c,0xf8,0xfc,0xf8,0x30,0xf8,0xfc,0xf8,0x51,0xf0,0xf0,0xf0,0x69,
0xc0,0xbc,0xb0,0x71,0x98,0x94,0x78,0x75,0x78,0x70,0x48,0x75,0x68,0x58,0x30,0x79,0x58,0x4c,0x18,0x7d,0x50,0x40,0x10,0x7d,0x48,0x38,0x00,0x7d,0x48,0x38,0x08,0x7d,0x50,0x40,0x10,0x7d,0x58,0x4c,0x18,0x7d,0x68,0x58,0x30,0x79,0x78,0x70,0x48,0x79,0x98,0x94,0x78,0x75,0xc0,0xbc,0xb0,0x71,0xf0,0xf0,0xe8,0x69,0xf8,0xfc,0xf8,0x51,
0xf8,0xfc,0xf8,0x30,0xf8,0xfc,0xf8,0x0c,0x40,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x28,0x00,0x00,0x30,0x28,0x00,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0x18,0x10,0x00,0x00,0x18,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x14,0x00,0x00,0x20,0x18,0x00,0x00,0x20,0x18,0x00,0x00,0x28,0x18,0x00,0x00,0x28,0x1c,0x00,0x00,0x28,0x1c,0x00,0x00,
0x28,0x1c,0x00,0x00,0x28,0x20,0x00,0x00,0x30,0x20,0x00,0x00,0x30,0x24,0x00,0x00,0x30,0x24,0x00,0x00,0x30,0x28,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x30,0x00,0x00,0x40,0x30,0x00,0x00,0xf8,0xfc,0xf8,0x08,0xf8,0xfc,0xf8,0x1c,0xf8,0xfc,0xf8,0x34,
0xf8,0xfc,0xf8,0x45,0xf8,0xfc,0xf8,0x55,0xf8,0xfc,0xf8,0x5d,0xf8,0xfc,0xf8,0x65,0xf8,0xfc,0xf8,0x69,0xf8,0xfc,0xf8,0x69,0xf8,0xfc,0xf8,0x61,0xf8,0xfc,0xf8,0x5d,0xf8,0xfc,0xf8,0x55,0xf8,0xfc,0xf8,0x45,0xf8,0xfc,0xf8,0x34,0xf8,0xfc,0xf8,0x1c,0xf8,0xfc,0xf8,0x08,0x40,0x30,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,
0x38,0x2c,0x00,0x00,0x38,0x2c,0x00,0x00,0x38,0x28,0x00,0x00,0x38,0x28,0x00,0x00,0x30,0x24,0x00,0x00,0x30,0x24,0x00,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,
0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00,0xf8,0xfc,0xf8,0x00
};
| 254.634868 | 320 | 0.796949 |
d7b22815eee156cd9b13741615d7f4d43ffe1b30 | 7,417 | cpp | C++ | ds/adsi/oledsvw/qstatus.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/oledsvw/qstatus.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/oledsvw/qstatus.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // QueryStatus.cpp : implementation file
//
#include "stdafx.h"
#include "viewex.h"
#include "qstatus.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CQueryStatus dialog
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
CQueryStatus::CQueryStatus(CWnd* pParent /*=NULL*/)
: CDialog(CQueryStatus::IDD, pParent)
{
//{{AFX_DATA_INIT(CQueryStatus)
//}}AFX_DATA_INIT
m_nUser = 0;
m_nGroup = 0;
m_nService = 0;
m_nFileService = 0;
m_nPrintQueue = 0;
m_nToDisplay = 0;
m_nComputer = 0;
m_nOtherObjects = 0;
m_pbAbort = NULL;
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CQueryStatus::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CQueryStatus)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CQueryStatus, CDialog)
//{{AFX_MSG_MAP(CQueryStatus)
ON_BN_CLICKED(IDCANCEL, OnStop)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CQueryStatus message handlers
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CQueryStatus::IncrementType( DWORD dwType, BOOL bDisplay )
{
switch( dwType )
{
case USER:
m_nUser++;
break;
case GROUP:
m_nGroup++;
break;
case SERVICE:
m_nService++;
break;
case FILESERVICE:
m_nFileService++;
break;
case PRINTQUEUE:
m_nPrintQueue++;
break;
case COMPUTER:
m_nComputer++;
break;
default:
m_nOtherObjects++;
break;
}
if( bDisplay )
{
m_nToDisplay++;
}
DisplayStatistics( );
UpdateWindow( );
MSG aMsg;
while( PeekMessage( &aMsg, NULL, 0, 0, PM_REMOVE ) &&
!IsDialogMessage( &aMsg ) )
{
TranslateMessage( &aMsg );
DispatchMessage( &aMsg );
}
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CQueryStatus::DisplayStatistics( void )
{
SetDlgItemInt( IDS_USER, m_nUser );
SetDlgItemInt( IDS_GROUP, m_nGroup );
SetDlgItemInt( IDS_SERVICE, m_nService );
SetDlgItemInt( IDS_FILESERVICE, m_nFileService );
SetDlgItemInt( IDS_PRINTQUEUE, m_nPrintQueue );
SetDlgItemInt( IDS_OTHEROBJECTS, m_nOtherObjects );
SetDlgItemInt( IDS_COMPUTER, m_nComputer );
SetDlgItemInt( IDC_ITEMSTODISPLAY, m_nToDisplay );
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
BOOL CQueryStatus::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
DisplayStatistics( );
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CQueryStatus::SetAbortFlag( BOOL* pAbort )
{
m_pbAbort = pAbort;
*pAbort = FALSE;
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CQueryStatus::OnStop()
{
// TODO: Add your control notification handler code here
if( NULL != m_pbAbort )
{
*m_pbAbort = TRUE;
}
}
/////////////////////////////////////////////////////////////////////////////
// CDeleteStatus dialog
CDeleteStatus::CDeleteStatus(CWnd* pParent /*=NULL*/)
: CDialog(CDeleteStatus::IDD, pParent)
{
//{{AFX_DATA_INIT(CDeleteStatus)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_pbAbort = NULL;
}
void CDeleteStatus::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDeleteStatus)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDeleteStatus, CDialog)
//{{AFX_MSG_MAP(CDeleteStatus)
ON_BN_CLICKED(IDCANCEL, OnStop)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CDeleteStatus::SetAbortFlag( BOOL* pAbort )
{
m_pbAbort = pAbort;
*pAbort = FALSE;
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CDeleteStatus::SetCurrentObjectText ( TCHAR* szName )
{
SetDlgItemText( IDC_CURRENTDELETEOBJECT, szName );
UpdateWindow( );
MSG aMsg;
while( PeekMessage( &aMsg, NULL, 0, 0, PM_REMOVE ) &&
!IsDialogMessage( &aMsg ) )
{
TranslateMessage( &aMsg );
DispatchMessage( &aMsg );
}
}
/***********************************************************
Function:
Arguments:
Return:
Purpose:
Author(s):
Revision:
Date:
***********************************************************/
void CDeleteStatus::SetStatusText( TCHAR* szStatus )
{
//SetDlgItemText( IDC_DELETESTATUS, szStatus );
GetDlgItem( IDC_DELETESTATUS )->ShowWindow( SW_HIDE );
//UpdateWindow( );
/*MSG aMsg;
while( PeekMessage( &aMsg, NULL, 0, 0, PM_REMOVE ) &&
!IsDialogMessage( &aMsg ) )
{
TranslateMessage( &aMsg );
DispatchMessage( &aMsg );
}*/
}
/////////////////////////////////////////////////////////////////////////////
// CDeleteStatus message handlers
void CDeleteStatus::OnStop()
{
// TODO: Add your control notification handler code here
if( NULL != m_pbAbort )
{
*m_pbAbort = TRUE;
}
}
| 23.178125 | 78 | 0.443171 |
d7b77646f63e6a8074b6bf09160e7b8297afa4d4 | 1,376 | cpp | C++ | src/semana-10/Range-Minimum-Query.cpp | RicardoLopes1/desafios-prog-2021-1 | 1e698f0696b5636fa5608d669dd58d170f8049ea | [
"MIT"
] | null | null | null | src/semana-10/Range-Minimum-Query.cpp | RicardoLopes1/desafios-prog-2021-1 | 1e698f0696b5636fa5608d669dd58d170f8049ea | [
"MIT"
] | null | null | null | src/semana-10/Range-Minimum-Query.cpp | RicardoLopes1/desafios-prog-2021-1 | 1e698f0696b5636fa5608d669dd58d170f8049ea | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// https://practice.geeksforgeeks.org/problems/range-minimum-query/1/
// Range Minimum Query
// Not completed
class SegmentTree{
private:
int n, t[4*10000];
map <string, int> rmq;
public:
SegmentTree( int * arr, int sz){
n = sz;
build(arr, 1, 0, n-1);
}
void build( int * arr, int idx, int tl, int tr){
if( tl == tr ){
t[idx] = arr[tl];
}else{
int tm = (tl+tr)/2;
build(arr, idx << 1, tl, tm);
build(arr, idx << 1 | 1 , tm+1, tr);
t[idx] = min(t[idx << 1], t[idx << 1 | 1]);
}
//printf("min(%d, %d) = %d\n", tl, tr, t[idx]);
rmq[to_string(tl) + to_string(tr)] = t[idx];
}
int searchRMQ(int l, int r){
if(l == r){
return rmq[to_string(l) + to_string(l)];
}else if(rmq[to_string(l) + to_string(r)] == 0){
int mid = (l + r)/2;
//cout << l << " - " << mid << endl;
int resl = searchRMQ(l, mid);
//cout << mid+1 << " - " << r << endl;
int resr = searchRMQ(mid+1, r);
return min(resl, resr);
}
return rmq[to_string(l) + to_string(r)];
}
};
int main(){
int arr[] = {3,2,4,2,4,3,7,1};
int n = sizeof(arr)/sizeof(int);
SegmentTree st(arr, n);
cout << "minimu between 0 and 4: " << st.searchRMQ(0, 4) << endl;
return 0;
} | 23.724138 | 69 | 0.494913 |
d7b806c937b4cbda5936c0e2d330a4a136c7d835 | 1,647 | cpp | C++ | Assignments/homework_03/main.cpp | Landon-Brown1/1063-DS-Brown | 64220948fbc69f7bfbd1ab234fe22da5de97fa6e | [
"MIT"
] | 1 | 2019-12-23T16:26:20.000Z | 2019-12-23T16:26:20.000Z | Assignments/homework_03/main.cpp | Landon-Brown1/1063-DS-Brown | 64220948fbc69f7bfbd1ab234fe22da5de97fa6e | [
"MIT"
] | null | null | null | Assignments/homework_03/main.cpp | Landon-Brown1/1063-DS-Brown | 64220948fbc69f7bfbd1ab234fe22da5de97fa6e | [
"MIT"
] | null | null | null | /*AUTHOR: Landon M. Brown
*ASSIGNMENT TITLE: homework_03
*ASSIGNMENT DESCRIPTION: Edit the ListStack and main so that the
* overloaded constructor is used instead of the default one.
*DUE DATE: 10/15/2019
*DATE CREATED: 10/12/2019
*DATE LAST MODIFIED: 10/12/2019
*/
#include <iostream>
#include <fstream>
#include "ListStack.h"
using namespace std;
int main(){
ifstream inFile; // input file of animal info
inFile.open("animals.txt");
ofstream outFile; // output results of main functions
outFile.open("output_file.dat");
Animal *a; // animal pointer used to hold popped animals
ListStack s; // List based stack object
while (!inFile.eof()) {
inFile >> a->name >> a->weight >> a->scary; // load animal with file data
Animal *b = new Animal(a->name, a->weight, a->scary); // allocate memory for an animal
s.Push(b);
}
inFile.close();
outFile << "INITIAL LIST:" << endl;
s.Print(outFile); // Print the stack
outFile << endl; // ummm
a = s.Pop(); // get animal off top of stack
outFile << "Pop -> " << a << endl; // print animal (cout operator overloaded)
a = s.Pop(); // get animal off top of stack again
outFile << "Pop -> " << a << endl; // print animal (cout operator overloaded)
outFile << endl; // ummm
outFile << "ENDING LIST:" << endl;
s.Print(outFile); // print the stack
outFile.close();
return 0;
} | 31.673077 | 97 | 0.549484 |
d7b9aadbf4f61c98406583b50fd3f0881c6aeaf5 | 37,820 | cpp | C++ | framegraph/Vulkan/CommandBuffer/VCmdBatch.cpp | zann1x/FrameGraph | ea06e28147a51f6d7cab219b4d8f30428a539faa | [
"BSD-2-Clause"
] | null | null | null | framegraph/Vulkan/CommandBuffer/VCmdBatch.cpp | zann1x/FrameGraph | ea06e28147a51f6d7cab219b4d8f30428a539faa | [
"BSD-2-Clause"
] | null | null | null | framegraph/Vulkan/CommandBuffer/VCmdBatch.cpp | zann1x/FrameGraph | ea06e28147a51f6d7cab219b4d8f30428a539faa | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2018-2019, Zhirnov Andrey. For more information see 'LICENSE'
#include "VCmdBatch.h"
#include "VFrameGraph.h"
namespace FG
{
/*
=================================================
constructor
=================================================
*/
VCmdBatch::VCmdBatch (VFrameGraph &fg, uint indexInPool) :
_state{ EState::Initial }, _frameGraph{ fg },
_indexInPool{ indexInPool }
{
STATIC_ASSERT( decltype(_state)::is_always_lock_free );
_counter.store( 0 );
_shaderDebugger.bufferAlign = BytesU{fg.GetDevice().GetDeviceLimits().minStorageBufferOffsetAlignment};
if ( FG_EnableShaderDebugging ) {
CHECK( fg.GetDevice().GetDeviceLimits().maxBoundDescriptorSets > FG_DebugDescriptorSet );
}
}
/*
=================================================
destructor
=================================================
*/
VCmdBatch::~VCmdBatch ()
{
EXLOCK( _drCheck );
CHECK( _counter.load( memory_order_relaxed ) == 0 );
}
/*
=================================================
Initialize
=================================================
*/
void VCmdBatch::Initialize (EQueueType type, ArrayView<CommandBuffer> dependsOn)
{
EXLOCK( _drCheck );
ASSERT( _dependencies.empty() );
ASSERT( _batch.commands.empty() );
ASSERT( _batch.signalSemaphores.empty() );
ASSERT( _batch.waitSemaphores.empty() );
ASSERT( _staging.hostToDevice.empty() );
ASSERT( _staging.deviceToHost.empty() );
ASSERT( _staging.onBufferLoadedEvents.empty() );
ASSERT( _staging.onImageLoadedEvents.empty() );
ASSERT( _resourcesToRelease.empty() );
ASSERT( _swapchains.empty() );
ASSERT( _shaderDebugger.buffers.empty() );
ASSERT( _shaderDebugger.modes.empty() );
ASSERT( _submitted == null );
ASSERT( _counter.load( memory_order_relaxed ) == 0 );
_queueType = type;
_state.store( EState::Initial, memory_order_relaxed );
for (auto& dep : dependsOn)
{
if ( auto* batch = Cast<VCmdBatch>(dep.GetBatch()) )
_dependencies.push_back( batch );
}
}
/*
=================================================
Release
=================================================
*/
void VCmdBatch::Release ()
{
EXLOCK( _drCheck );
CHECK( GetState() == EState::Complete );
ASSERT( _counter.load( memory_order_relaxed ) == 0 );
_frameGraph.RecycleBatch( this );
}
/*
=================================================
SignalSemaphore
=================================================
*/
void VCmdBatch::SignalSemaphore (VkSemaphore sem)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Submitted );
CHECK_ERR( _batch.signalSemaphores.size() < _batch.signalSemaphores.capacity(), void());
_batch.signalSemaphores.push_back( sem );
}
/*
=================================================
WaitSemaphore
=================================================
*/
void VCmdBatch::WaitSemaphore (VkSemaphore sem, VkPipelineStageFlags stage)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Submitted );
CHECK_ERR( _batch.waitSemaphores.size() < _batch.waitSemaphores.capacity(), void());
_batch.waitSemaphores.push_back( sem, stage );
}
/*
=================================================
PushFrontCommandBuffer / PushBackCommandBuffer
=================================================
*/
void VCmdBatch::PushFrontCommandBuffer (VkCommandBuffer cmd, const VCommandPool *pool)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Submitted );
CHECK_ERR( _batch.commands.size() < _batch.commands.capacity(), void());
_batch.commands.insert( 0, cmd, pool );
}
void VCmdBatch::PushBackCommandBuffer (VkCommandBuffer cmd, const VCommandPool *pool)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Submitted );
CHECK_ERR( _batch.commands.size() < _batch.commands.capacity(), void());
_batch.commands.push_back( cmd, pool );
}
/*
=================================================
AddDependency
=================================================
*/
void VCmdBatch::AddDependency (VCmdBatch *batch)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Backed );
CHECK_ERR( _dependencies.size() < _dependencies.capacity(), void());
_dependencies.push_back( batch );
}
/*
=================================================
DestroyPostponed
=================================================
*/
void VCmdBatch::DestroyPostponed (VkObjectType type, uint64_t handle)
{
EXLOCK( _drCheck );
ASSERT( GetState() < EState::Backed );
_readyToDelete.push_back({ type, handle });
}
/*
=================================================
_SetState
=================================================
*/
void VCmdBatch::_SetState (EState newState)
{
EXLOCK( _drCheck );
ASSERT( uint(newState) > uint(GetState()) );
_state.store( newState, memory_order_relaxed );
}
/*
=================================================
OnBegin
=================================================
*/
bool VCmdBatch::OnBegin (const CommandBufferDesc &desc)
{
EXLOCK( _drCheck );
_SetState( EState::Recording );
//_submitImmediatly = // TODO
_staging.hostWritableBufferSize = desc.hostWritableBufferSize;
_staging.hostReadableBufferSize = desc.hostWritableBufferSize;
_staging.hostWritebleBufferUsage = desc.hostWritebleBufferUsage | EBufferUsage::TransferSrc;
_statistic = Default;
return true;
}
/*
=================================================
OnBeginRecording
=================================================
*/
void VCmdBatch::OnBeginRecording (VkCommandBuffer cmd)
{
EXLOCK( _drCheck );
CHECK( GetState() == EState::Recording );
VDevice const& dev = _frameGraph.GetDevice();
VkQueryPool pool = _frameGraph.GetQueryPool();
dev.vkCmdWriteTimestamp( cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, pool, _indexInPool*2 );
_BeginShaderDebugger( cmd );
}
/*
=================================================
OnEndRecording
=================================================
*/
void VCmdBatch::OnEndRecording (VkCommandBuffer cmd)
{
EXLOCK( _drCheck );
CHECK( GetState() == EState::Recording );
_EndShaderDebugger( cmd );
VDevice const& dev = _frameGraph.GetDevice();
VkQueryPool pool = _frameGraph.GetQueryPool();
dev.vkCmdWriteTimestamp( cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, pool, _indexInPool*2 + 1 );
}
/*
=================================================
OnBaked
=================================================
*/
bool VCmdBatch::OnBaked (INOUT ResourceMap_t &resources)
{
EXLOCK( _drCheck );
_SetState( EState::Backed );
std::swap( _resourcesToRelease, resources );
return true;
}
/*
=================================================
OnReadyToSubmit
=================================================
*/
bool VCmdBatch::OnReadyToSubmit ()
{
EXLOCK( _drCheck );
_SetState( EState::Ready );
return true;
}
/*
=================================================
BeforeSubmit
=================================================
*/
bool VCmdBatch::BeforeSubmit (OUT VkSubmitInfo &submitInfo)
{
EXLOCK( _drCheck );
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.pNext = null;
submitInfo.pCommandBuffers = _batch.commands.get<0>().data();
submitInfo.commandBufferCount = uint(_batch.commands.size());
submitInfo.pSignalSemaphores = _batch.signalSemaphores.data();
submitInfo.signalSemaphoreCount = uint(_batch.signalSemaphores.size());
submitInfo.pWaitSemaphores = _batch.waitSemaphores.get<0>().data();
submitInfo.pWaitDstStageMask = _batch.waitSemaphores.get<1>().data();
submitInfo.waitSemaphoreCount = uint(_batch.waitSemaphores.size());
return true;
}
/*
=================================================
AfterSubmit
=================================================
*/
bool VCmdBatch::AfterSubmit (OUT Appendable<VSwapchain const*> swapchains, VSubmitted *ptr)
{
EXLOCK( _drCheck );
_SetState( EState::Submitted );
for (auto& sw : _swapchains) {
swapchains.push_back( sw );
}
_swapchains.clear();
_dependencies.clear();
_submitted = ptr;
return true;
}
/*
=================================================
OnComplete
=================================================
*/
bool VCmdBatch::OnComplete (VDebugger &debugger, const ShaderDebugCallback_t &shaderDbgCallback, INOUT Statistic_t &outStatistic)
{
EXLOCK( _drCheck );
ASSERT( _submitted );
_SetState( EState::Complete );
_FinalizeCommands();
_ParseDebugOutput( shaderDbgCallback );
_FinalizeStagingBuffers();
_ReleaseResources();
_ReleaseVkObjects();
debugger.AddBatchDump( std::move(_debugDump) );
debugger.AddBatchGraph( std::move(_debugGraph) );
_debugDump.clear();
_debugGraph = Default;
// read frame time
{
VDevice const& dev = _frameGraph.GetDevice();
VkQueryPool pool = _frameGraph.GetQueryPool();
uint64_t query_results[2];
VK_CALL( dev.vkGetQueryPoolResults( dev.GetVkDevice(), pool, _indexInPool*2, uint(CountOf(query_results)),
sizeof(query_results), OUT query_results,
sizeof(query_results[0]), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT ));
_statistic.renderer.gpuTime += Nanoseconds{query_results[1] - query_results[0]};
}
outStatistic.Merge( _statistic );
_submitted = null;
return true;
}
/*
=================================================
_FinalizeCommands
=================================================
*/
void VCmdBatch::_FinalizeCommands ()
{
for (size_t i = 0; i < _batch.commands.size(); ++i)
{
if ( auto* pool = _batch.commands.get<1>()[i] )
pool->RecyclePrimary( _batch.commands.get<0>()[i] );
}
_batch.commands.clear();
_batch.signalSemaphores.clear();
_batch.waitSemaphores.clear();
}
/*
=================================================
_FinalizeStagingBuffers
=================================================
*/
void VCmdBatch::_FinalizeStagingBuffers ()
{
using T = BufferView::value_type;
// map device-to-host staging buffers
for (auto& buf : _staging.deviceToHost)
{
// buffer may be recreated on defragmentation pass, so we need to obtain actual pointer every frame
CHECK( _MapMemory( INOUT buf ));
}
// trigger buffer events
for (auto& ev : _staging.onBufferLoadedEvents)
{
FixedArray< ArrayView<T>, MaxBufferParts > data_parts;
BytesU total_size;
for (auto& part : ev.parts)
{
ArrayView<T> view{ Cast<T>(part.buffer->mappedPtr + part.offset), size_t(part.size) };
data_parts.push_back( view );
total_size += part.size;
}
ASSERT( total_size == ev.totalSize );
ev.callback( BufferView{data_parts} );
}
_staging.onBufferLoadedEvents.clear();
// trigger image events
for (auto& ev : _staging.onImageLoadedEvents)
{
FixedArray< ArrayView<T>, MaxImageParts > data_parts;
BytesU total_size;
for (auto& part : ev.parts)
{
ArrayView<T> view{ Cast<T>(part.buffer->mappedPtr + part.offset), size_t(part.size) };
data_parts.push_back( view );
total_size += part.size;
}
ASSERT( total_size == ev.totalSize );
ev.callback( ImageView{ data_parts, ev.imageSize, ev.rowPitch, ev.slicePitch, ev.format, ev.aspect });
}
_staging.onImageLoadedEvents.clear();
// release resources
{
auto& rm = _frameGraph.GetResourceManager();
for (auto& sb : _staging.hostToDevice) {
rm.ReleaseResource( sb.bufferId.Release() );
}
_staging.hostToDevice.clear();
for (auto& sb : _staging.deviceToHost) {
rm.ReleaseResource( sb.bufferId.Release() );
}
_staging.deviceToHost.clear();
}
}
/*
=================================================
_ParseDebugOutput
=================================================
*/
void VCmdBatch::_ParseDebugOutput (const ShaderDebugCallback_t &cb)
{
if ( _shaderDebugger.buffers.empty() )
return;
ASSERT( cb );
auto& dev = _frameGraph.GetDevice();
auto& rm = _frameGraph.GetResourceManager();
VK_CHECK( dev.vkDeviceWaitIdle( dev.GetVkDevice() ), void());
// release descriptor sets
for (auto& ds : _shaderDebugger.descCache) {
rm.GetDescriptorManager().DeallocDescriptorSet( ds.second );
}
_shaderDebugger.descCache.clear();
// process shader debug output
if ( cb )
{
Array<String> temp_strings;
for (auto& dbg : _shaderDebugger.modes) {
_ParseDebugOutput2( cb, dbg, temp_strings );
}
}
_shaderDebugger.modes.clear();
// release storage buffers
for (auto& sb : _shaderDebugger.buffers)
{
rm.ReleaseResource( sb.shaderTraceBuffer.Release() );
rm.ReleaseResource( sb.readBackBuffer.Release() );
}
_shaderDebugger.buffers.clear();
}
/*
=================================================
_ParseDebugOutput2
=================================================
*/
bool VCmdBatch::_ParseDebugOutput2 (const ShaderDebugCallback_t &cb, const DebugMode &dbg, Array<String> &tempStrings) const
{
CHECK_ERR( dbg.modules.size() );
auto& rm = _frameGraph.GetResourceManager();
auto read_back_buf = _shaderDebugger.buffers[ dbg.sbIndex ].readBackBuffer.Get();
VBuffer const* buf = rm.GetResource( read_back_buf );
CHECK_ERR( buf );
VMemoryObj const* mem = rm.GetResource( buf->GetMemoryID() );
CHECK_ERR( mem );
VMemoryObj::MemoryInfo info;
CHECK_ERR( mem->GetInfo( rm.GetMemoryManager(), OUT info ));
CHECK_ERR( info.mappedPtr );
for (auto& shader : dbg.modules)
{
CHECK_ERR( shader->ParseDebugOutput( dbg.mode, ArrayView<uint8_t>{ Cast<uint8_t>(info.mappedPtr + dbg.offset), size_t(dbg.size) }, OUT tempStrings ));
cb( dbg.taskName, shader->GetDebugName(), dbg.shaderStages, tempStrings );
}
return true;
}
//-----------------------------------------------------------------------------
/*
=================================================
_MapMemory
=================================================
*/
bool VCmdBatch::_MapMemory (INOUT StagingBuffer &buf) const
{
VMemoryObj::MemoryInfo info;
auto& rm = _frameGraph.GetResourceManager();
if ( rm.GetResource( buf.memoryId )->GetInfo( rm.GetMemoryManager(),OUT info ) )
{
buf.mappedPtr = info.mappedPtr;
buf.memOffset = info.offset;
buf.mem = info.mem;
buf.isCoherent = EnumEq( info.flags, VK_MEMORY_PROPERTY_HOST_COHERENT_BIT );
return true;
}
return false;
}
/*
=================================================
_ReleaseResources
=================================================
*/
void VCmdBatch::_ReleaseResources ()
{
auto& rm = _frameGraph.GetResourceManager();
for (auto[res, count] : _resourcesToRelease)
{
switch ( res.GetUID() )
{
case RawBufferID::GetUID() : rm.ReleaseResource( RawBufferID{ res.Index(), res.InstanceID() }, count ); break;
case RawImageID::GetUID() : rm.ReleaseResource( RawImageID{ res.Index(), res.InstanceID() }, count ); break;
case RawGPipelineID::GetUID() : rm.ReleaseResource( RawGPipelineID{ res.Index(), res.InstanceID() }, count ); break;
case RawMPipelineID::GetUID() : rm.ReleaseResource( RawMPipelineID{ res.Index(), res.InstanceID() }, count ); break;
case RawCPipelineID::GetUID() : rm.ReleaseResource( RawCPipelineID{ res.Index(), res.InstanceID() }, count ); break;
case RawRTPipelineID::GetUID() : rm.ReleaseResource( RawRTPipelineID{ res.Index(), res.InstanceID() }, count ); break;
case RawSamplerID::GetUID() : rm.ReleaseResource( RawSamplerID{ res.Index(), res.InstanceID() }, count ); break;
case RawDescriptorSetLayoutID::GetUID():rm.ReleaseResource( RawDescriptorSetLayoutID{ res.Index(), res.InstanceID() }, count ); break;
case RawPipelineResourcesID::GetUID() : rm.ReleaseResource( RawPipelineResourcesID{ res.Index(), res.InstanceID() }, count ); break;
case RawRTSceneID::GetUID() : rm.ReleaseResource( RawRTSceneID{ res.Index(), res.InstanceID() }, count ); break;
case RawRTGeometryID::GetUID() : rm.ReleaseResource( RawRTGeometryID{ res.Index(), res.InstanceID() }, count ); break;
case RawRTShaderTableID::GetUID() : rm.ReleaseResource( RawRTShaderTableID{ res.Index(), res.InstanceID() }, count ); break;
case RawSwapchainID::GetUID() : rm.ReleaseResource( RawSwapchainID{ res.Index(), res.InstanceID() }, count ); break;
case RawMemoryID::GetUID() : rm.ReleaseResource( RawMemoryID{ res.Index(), res.InstanceID() }, count ); break;
case RawPipelineLayoutID::GetUID() : rm.ReleaseResource( RawPipelineLayoutID{ res.Index(), res.InstanceID() }, count ); break;
case RawRenderPassID::GetUID() : rm.ReleaseResource( RawRenderPassID{ res.Index(), res.InstanceID() }, count ); break;
case RawFramebufferID::GetUID() : rm.ReleaseResource( RawFramebufferID{ res.Index(), res.InstanceID() }, count ); break;
default : CHECK( !"not supported" ); break;
}
}
_resourcesToRelease.clear();
}
/*
=================================================
_ReleaseVkObjects
=================================================
*/
void VCmdBatch::_ReleaseVkObjects ()
{
VDevice const& dev = _frameGraph.GetDevice();
VkDevice vdev = dev.GetVkDevice();
for (auto& pair : _readyToDelete)
{
switch ( pair.first )
{
case VK_OBJECT_TYPE_SEMAPHORE :
dev.vkDestroySemaphore( vdev, VkSemaphore(pair.second), null );
break;
case VK_OBJECT_TYPE_FENCE :
dev.vkDestroyFence( vdev, VkFence(pair.second), null );
break;
case VK_OBJECT_TYPE_DEVICE_MEMORY :
dev.vkFreeMemory( vdev, VkDeviceMemory(pair.second), null );
break;
case VK_OBJECT_TYPE_IMAGE :
dev.vkDestroyImage( vdev, VkImage(pair.second), null );
break;
case VK_OBJECT_TYPE_EVENT :
dev.vkDestroyEvent( vdev, VkEvent(pair.second), null );
break;
case VK_OBJECT_TYPE_QUERY_POOL :
dev.vkDestroyQueryPool( vdev, VkQueryPool(pair.second), null );
break;
case VK_OBJECT_TYPE_BUFFER :
dev.vkDestroyBuffer( vdev, VkBuffer(pair.second), null );
break;
case VK_OBJECT_TYPE_BUFFER_VIEW :
dev.vkDestroyBufferView( vdev, VkBufferView(pair.second), null );
break;
case VK_OBJECT_TYPE_IMAGE_VIEW :
dev.vkDestroyImageView( vdev, VkImageView(pair.second), null );
break;
case VK_OBJECT_TYPE_PIPELINE_LAYOUT :
dev.vkDestroyPipelineLayout( vdev, VkPipelineLayout(pair.second), null );
break;
case VK_OBJECT_TYPE_RENDER_PASS :
dev.vkDestroyRenderPass( vdev, VkRenderPass(pair.second), null );
break;
case VK_OBJECT_TYPE_PIPELINE :
dev.vkDestroyPipeline( vdev, VkPipeline(pair.second), null );
break;
case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT :
dev.vkDestroyDescriptorSetLayout( vdev, VkDescriptorSetLayout(pair.second), null );
break;
case VK_OBJECT_TYPE_SAMPLER :
dev.vkDestroySampler( vdev, VkSampler(pair.second), null );
break;
case VK_OBJECT_TYPE_DESCRIPTOR_POOL :
dev.vkDestroyDescriptorPool( vdev, VkDescriptorPool(pair.second), null );
break;
case VK_OBJECT_TYPE_FRAMEBUFFER :
dev.vkDestroyFramebuffer( vdev, VkFramebuffer(pair.second), null );
break;
case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION :
dev.vkDestroySamplerYcbcrConversion( vdev, VkSamplerYcbcrConversion(pair.second), null );
break;
case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE :
dev.vkDestroyDescriptorUpdateTemplate( vdev, VkDescriptorUpdateTemplate(pair.second), null );
break;
case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV :
dev.vkDestroyAccelerationStructureNV( vdev, VkAccelerationStructureNV(pair.second), null );
break;
default :
FG_LOGE( "resource type is not supported" );
break;
}
}
_readyToDelete.clear();
}
/*
=================================================
_GetWritable
=================================================
*/
bool VCmdBatch::GetWritable (const BytesU srcRequiredSize, const BytesU blockAlign, const BytesU offsetAlign, const BytesU dstMinSize,
OUT RawBufferID &dstBuffer, OUT BytesU &dstOffset, OUT BytesU &outSize, OUT void* &mappedPtr)
{
EXLOCK( _drCheck );
ASSERT( blockAlign > 0_b and offsetAlign > 0_b );
ASSERT( dstMinSize == AlignToSmaller( dstMinSize, blockAlign ));
auto& staging_buffers = _staging.hostToDevice;
// search in existing
StagingBuffer* suitable = null;
StagingBuffer* max_available = null;
BytesU max_size;
for (auto& buf : staging_buffers)
{
const BytesU off = AlignToLarger( buf.size, offsetAlign );
const BytesU av = AlignToSmaller( buf.capacity - off, blockAlign );
if ( av >= srcRequiredSize )
{
suitable = &buf;
break;
}
if ( not max_available or av > max_size )
{
max_available = &buf;
max_size = av;
}
}
// no suitable space, try to use max available block
if ( not suitable and max_available and max_size >= dstMinSize )
{
suitable = max_available;
}
// allocate new buffer
if ( not suitable )
{
ASSERT( dstMinSize < _staging.hostWritableBufferSize );
CHECK_ERR( staging_buffers.size() < staging_buffers.capacity() );
BufferID buf_id = _frameGraph.CreateBuffer( BufferDesc{ _staging.hostWritableBufferSize, _staging.hostWritebleBufferUsage },
MemoryDesc{ EMemoryType::HostWrite }, "HostWriteBuffer" );
CHECK_ERR( buf_id );
RawMemoryID mem_id = _frameGraph.GetResourceManager().GetResource( buf_id.Get() )->GetMemoryID();
CHECK_ERR( mem_id );
staging_buffers.push_back({ std::move(buf_id), mem_id, _staging.hostWritableBufferSize });
suitable = &staging_buffers.back();
CHECK( _MapMemory( *suitable ));
}
// write data to buffer
dstOffset = AlignToLarger( suitable->size, offsetAlign );
outSize = Min( AlignToSmaller( suitable->capacity - dstOffset, blockAlign ), srcRequiredSize );
dstBuffer = suitable->bufferId.Get();
mappedPtr = suitable->mappedPtr + dstOffset;
suitable->size = dstOffset + outSize;
return true;
}
/*
=================================================
_AddPendingLoad
=================================================
*/
bool VCmdBatch::_AddPendingLoad (const BytesU srcRequiredSize, const BytesU blockAlign, const BytesU offsetAlign, const BytesU dstMinSize,
OUT RawBufferID &dstBuffer, OUT OnBufferDataLoadedEvent::Range &range)
{
ASSERT( blockAlign > 0_b and offsetAlign > 0_b );
ASSERT( dstMinSize == AlignToSmaller( dstMinSize, blockAlign ));
auto& staging_buffers = _staging.deviceToHost;
// search in existing
StagingBuffer* suitable = null;
StagingBuffer* max_available = null;
BytesU max_size;
for (auto& buf : staging_buffers)
{
const BytesU off = AlignToLarger( buf.size, offsetAlign );
const BytesU av = AlignToSmaller( buf.capacity - off, blockAlign );
if ( av >= srcRequiredSize )
{
suitable = &buf;
break;
}
if ( not max_available or av > max_size )
{
max_available = &buf;
max_size = av;
}
}
// no suitable space, try to use max available block
if ( not suitable and max_available and max_size >= dstMinSize )
{
suitable = max_available;
}
// allocate new buffer
if ( not suitable )
{
ASSERT( dstMinSize < _staging.hostReadableBufferSize );
CHECK_ERR( staging_buffers.size() < staging_buffers.capacity() );
BufferID buf_id = _frameGraph.CreateBuffer( BufferDesc{ _staging.hostReadableBufferSize, EBufferUsage::TransferDst },
MemoryDesc{ EMemoryType::HostRead }, "HostReadBuffer" );
CHECK_ERR( buf_id );
RawMemoryID mem_id = _frameGraph.GetResourceManager().GetResource( buf_id.Get() )->GetMemoryID();
CHECK_ERR( mem_id );
// TODO: make immutable because read after write happens after waiting for fences and it implicitly make changes visible to the host
staging_buffers.push_back({ std::move(buf_id), mem_id, _staging.hostReadableBufferSize });
suitable = &staging_buffers.back();
CHECK( _MapMemory( *suitable ));
}
// write data to buffer
range.buffer = suitable;
range.offset = AlignToLarger( suitable->size, offsetAlign );
range.size = Min( AlignToSmaller( suitable->capacity - range.offset, blockAlign ), srcRequiredSize );
dstBuffer = suitable->bufferId.Get();
suitable->size = range.offset + range.size;
return true;
}
/*
=================================================
AddPendingLoad
=================================================
*/
bool VCmdBatch::AddPendingLoad (const BytesU srcOffset, const BytesU srcTotalSize,
OUT RawBufferID &dstBuffer, OUT OnBufferDataLoadedEvent::Range &range)
{
EXLOCK( _drCheck );
// skip blocks less than 1/N of data size
const BytesU min_size = (srcTotalSize + MaxBufferParts-1) / MaxBufferParts;
return _AddPendingLoad( srcTotalSize - srcOffset, 1_b, 16_b, min_size, OUT dstBuffer, OUT range );
}
/*
=================================================
AddDataLoadedEvent
=================================================
*/
bool VCmdBatch::AddDataLoadedEvent (OnBufferDataLoadedEvent &&ev)
{
EXLOCK( _drCheck );
CHECK_ERR( ev.callback and not ev.parts.empty() );
_staging.onBufferLoadedEvents.push_back( std::move(ev) );
return true;
}
/*
=================================================
AddPendingLoad
=================================================
*/
bool VCmdBatch::AddPendingLoad (const BytesU srcOffset, const BytesU srcTotalSize, const BytesU srcPitch,
OUT RawBufferID &dstBuffer, OUT OnImageDataLoadedEvent::Range &range)
{
EXLOCK( _drCheck );
// skip blocks less than 1/N of total data size
const BytesU min_size = Max( (srcTotalSize + MaxImageParts-1) / MaxImageParts, srcPitch );
return _AddPendingLoad( srcTotalSize - srcOffset, srcPitch, 16_b, min_size, OUT dstBuffer, OUT range );
}
/*
=================================================
AddDataLoadedEvent
=================================================
*/
bool VCmdBatch::AddDataLoadedEvent (OnImageDataLoadedEvent &&ev)
{
EXLOCK( _drCheck );
CHECK_ERR( ev.callback and not ev.parts.empty() );
_staging.onImageLoadedEvents.push_back( std::move(ev) );
return true;
}
//-----------------------------------------------------------------------------
/*
=================================================
_BeginShaderDebugger
=================================================
*/
void VCmdBatch::_BeginShaderDebugger (VkCommandBuffer cmd)
{
if ( _shaderDebugger.buffers.empty() )
return;
auto& dev = _frameGraph.GetDevice();
auto& rm = _frameGraph.GetResourceManager();
// copy data
for (auto& dbg : _shaderDebugger.modes)
{
auto buf = rm.GetResource( _shaderDebugger.buffers[dbg.sbIndex].shaderTraceBuffer.Get() )->Handle();
BytesU size = rm.GetDebugShaderStorageSize( dbg.shaderStages ) + SizeOf<uint>; // per shader data + position
ASSERT( size <= BytesU::SizeOf(dbg.data) );
dev.vkCmdUpdateBuffer( cmd, buf, VkDeviceSize(dbg.offset), VkDeviceSize(size), dbg.data );
}
// add pipeline barriers
FixedArray< VkBufferMemoryBarrier, 16 > barriers;
VkPipelineStageFlags dst_stage_flags = 0;
for (auto& sb : _shaderDebugger.buffers)
{
VkBufferMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
barrier.buffer = rm.GetResource( sb.shaderTraceBuffer.Get() )->Handle();
barrier.offset = 0;
barrier.size = VkDeviceSize(sb.size);
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
dst_stage_flags |= sb.stages;
barriers.push_back( barrier );
if ( barriers.size() == barriers.capacity() )
{
dev.vkCmdPipelineBarrier( cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_flags, 0, 0, null, uint(barriers.size()), barriers.data(), 0, null );
barriers.clear();
}
}
if ( barriers.size() ) {
dev.vkCmdPipelineBarrier( cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_flags, 0, 0, null, uint(barriers.size()), barriers.data(), 0, null );
}
}
/*
=================================================
_EndShaderDebugger
=================================================
*/
void VCmdBatch::_EndShaderDebugger (VkCommandBuffer cmd)
{
if ( _shaderDebugger.buffers.empty() )
return;
auto& dev = _frameGraph.GetDevice();
auto& rm = _frameGraph.GetResourceManager();
// copy to staging buffer
for (auto& sb : _shaderDebugger.buffers)
{
VkBuffer src_buf = rm.GetResource( sb.shaderTraceBuffer.Get() )->Handle();
VkBuffer dst_buf = rm.GetResource( sb.readBackBuffer.Get() )->Handle();
VkBufferMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.buffer = src_buf;
barrier.offset = 0;
barrier.size = VkDeviceSize(sb.size);
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
dev.vkCmdPipelineBarrier( cmd, sb.stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, null, 1, &barrier, 0, null );
VkBufferCopy region = {};
region.size = VkDeviceSize(sb.size);
dev.vkCmdCopyBuffer( cmd, src_buf, dst_buf, 1, ®ion );
}
}
/*
=================================================
SetShaderModule
=================================================
*/
bool VCmdBatch::SetShaderModule (ShaderDbgIndex id, const SharedShaderPtr &module)
{
EXLOCK( _drCheck );
CHECK_ERR( uint(id) < _shaderDebugger.modes.size() );
auto& dbg = _shaderDebugger.modes[ uint(id) ];
dbg.modules.emplace_back( module );
return true;
}
/*
=================================================
GetDebugModeInfo
=================================================
*/
bool VCmdBatch::GetDebugModeInfo (ShaderDbgIndex id, OUT EShaderDebugMode &mode, OUT EShaderStages &stages) const
{
EXLOCK( _drCheck );
CHECK_ERR( uint(id) < _shaderDebugger.modes.size() );
auto& dbg = _shaderDebugger.modes[ uint(id) ];
mode = dbg.mode;
stages = dbg.shaderStages;
return true;
}
/*
=================================================
GetDescriptotSet
=================================================
*/
bool VCmdBatch::GetDescriptotSet (ShaderDbgIndex id, OUT uint &binding, OUT VkDescriptorSet &descSet, OUT uint &dynamicOffset) const
{
EXLOCK( _drCheck );
CHECK_ERR( uint(id) < _shaderDebugger.modes.size() );
auto& dbg = _shaderDebugger.modes[ uint(id) ];
binding = FG_DebugDescriptorSet;
descSet = dbg.descriptorSet;
dynamicOffset = uint(dbg.offset);
return true;
}
/*
=================================================
AppendShader
=================================================
*/
ShaderDbgIndex VCmdBatch::AppendShader (INOUT ArrayView<RectI> &, const TaskName_t &name, const _fg_hidden_::GraphicsShaderDebugMode &mode, BytesU size)
{
EXLOCK( _drCheck );
CHECK_ERR( FG_EnableShaderDebugging );
DebugMode dbg_mode;
dbg_mode.taskName = name;
dbg_mode.mode = mode.mode;
dbg_mode.shaderStages = mode.stages;
CHECK_ERR( _AllocStorage( INOUT dbg_mode, size ));
dbg_mode.data[0] = mode.fragCoord.x;
dbg_mode.data[1] = mode.fragCoord.y;
dbg_mode.data[2] = 0;
dbg_mode.data[3] = 0;
_shaderDebugger.modes.push_back( std::move(dbg_mode) );
return ShaderDbgIndex(_shaderDebugger.modes.size() - 1);
}
/*
=================================================
AppendShader
=================================================
*/
ShaderDbgIndex VCmdBatch::AppendShader (const TaskName_t &name, const _fg_hidden_::ComputeShaderDebugMode &mode, BytesU size)
{
EXLOCK( _drCheck );
CHECK_ERR( FG_EnableShaderDebugging );
DebugMode dbg_mode;
dbg_mode.taskName = name;
dbg_mode.mode = mode.mode;
dbg_mode.shaderStages = EShaderStages::Compute;
CHECK_ERR( _AllocStorage( INOUT dbg_mode, size ));
MemCopy( OUT dbg_mode.data, mode.globalID );
dbg_mode.data[3] = 0;
_shaderDebugger.modes.push_back( std::move(dbg_mode) );
return ShaderDbgIndex(_shaderDebugger.modes.size() - 1);
}
/*
=================================================
AppendShader
=================================================
*/
ShaderDbgIndex VCmdBatch::AppendShader (const TaskName_t &name, const _fg_hidden_::RayTracingShaderDebugMode &mode, BytesU size)
{
EXLOCK( _drCheck );
CHECK_ERR( FG_EnableShaderDebugging );
DebugMode dbg_mode;
dbg_mode.taskName = name;
dbg_mode.mode = mode.mode;
dbg_mode.shaderStages = EShaderStages::AllRayTracing;
CHECK_ERR( _AllocStorage( INOUT dbg_mode, size ));
MemCopy( OUT dbg_mode.data, mode.launchID );
dbg_mode.data[3] = 0;
_shaderDebugger.modes.push_back( std::move(dbg_mode) );
return ShaderDbgIndex(_shaderDebugger.modes.size() - 1);
}
/*
=================================================
_AllocStorage
=================================================
*/
bool VCmdBatch::_AllocStorage (INOUT DebugMode &dbgMode, const BytesU size)
{
VkPipelineStageFlags stage = 0;
for (EShaderStages s = EShaderStages(1); s <= dbgMode.shaderStages; s = EShaderStages(uint(s) << 1))
{
if ( not EnumEq( dbgMode.shaderStages, s ) )
continue;
ENABLE_ENUM_CHECKS();
switch ( s )
{
case EShaderStages::Vertex : stage = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; break;
case EShaderStages::TessControl : stage = VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT; break;
case EShaderStages::TessEvaluation: stage = VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; break;
case EShaderStages::Geometry : stage = VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT; break;
case EShaderStages::Fragment : stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; break;
case EShaderStages::Compute : stage = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; break;
case EShaderStages::MeshTask : stage = VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV; break;
case EShaderStages::Mesh : stage = VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV; break;
case EShaderStages::RayGen :
case EShaderStages::RayAnyHit :
case EShaderStages::RayClosestHit :
case EShaderStages::RayMiss :
case EShaderStages::RayIntersection:
case EShaderStages::RayCallable : stage = VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV; break;
case EShaderStages::_Last :
case EShaderStages::Unknown :
case EShaderStages::AllGraphics :
case EShaderStages::AllRayTracing :
case EShaderStages::All : // to shutup warnings
default : RETURN_ERR( "unknown shader type" );
}
DISABLE_ENUM_CHECKS();
}
dbgMode.size = Min( size, _shaderDebugger.bufferSize );
// find place in existing storage buffers
for (auto& sb : _shaderDebugger.buffers)
{
dbgMode.offset = AlignToLarger( sb.size, _shaderDebugger.bufferAlign );
if ( dbgMode.size <= (sb.capacity - dbgMode.offset) )
{
dbgMode.sbIndex = uint(Distance( _shaderDebugger.buffers.data(), &sb ));
sb.size = dbgMode.offset + size;
sb.stages |= stage;
break;
}
}
// create new storage buffer
if ( dbgMode.sbIndex == UMax )
{
StorageBuffer sb;
sb.capacity = _shaderDebugger.bufferSize * (1 + _shaderDebugger.buffers.size() / 2);
sb.shaderTraceBuffer = _frameGraph.CreateBuffer( BufferDesc{ sb.capacity, EBufferUsage::Storage | EBufferUsage::Transfer },
Default, "DebugOutputStorage" );
sb.readBackBuffer = _frameGraph.CreateBuffer( BufferDesc{ sb.capacity, EBufferUsage::TransferDst },
MemoryDesc{EMemoryType::HostRead}, "ReadBackDebugOutput" );
CHECK_ERR( sb.shaderTraceBuffer and sb.readBackBuffer );
dbgMode.sbIndex = uint(_shaderDebugger.buffers.size());
dbgMode.offset = 0_b;
sb.size = dbgMode.offset + size;
sb.stages |= stage;
_shaderDebugger.buffers.push_back( std::move(sb) );
}
CHECK_ERR( _AllocDescriptorSet( dbgMode.mode, dbgMode.shaderStages,
_shaderDebugger.buffers[dbgMode.sbIndex].shaderTraceBuffer.Get(),
dbgMode.size, OUT dbgMode.descriptorSet ));
return true;
}
/*
=================================================
_AllocDescriptorSet
=================================================
*/
bool VCmdBatch::_AllocDescriptorSet (EShaderDebugMode debugMode, EShaderStages stages, RawBufferID storageBuffer, BytesU size, OUT VkDescriptorSet &descSet)
{
auto& dev = _frameGraph.GetDevice();
auto& rm = _frameGraph.GetResourceManager();
auto layout_id = rm.GetDescriptorSetLayout( debugMode, stages );
auto* layout = rm.GetResource( layout_id );
auto* buffer = rm.GetResource( storageBuffer );
CHECK_ERR( layout and buffer );
// find descriptor set in cache
auto iter = _shaderDebugger.descCache.find({ storageBuffer, layout_id });
if ( iter != _shaderDebugger.descCache.end() )
{
descSet = iter->second.first;
return true;
}
// allocate descriptor set
{
VDescriptorSetLayout::DescriptorSet ds;
CHECK_ERR( rm.GetDescriptorManager().AllocDescriptorSet( layout->Handle(), OUT ds ));
descSet = ds.first;
_shaderDebugger.descCache.insert_or_assign( {storageBuffer, layout_id}, ds );
}
// update descriptor set
{
VkDescriptorBufferInfo buffer_desc = {};
buffer_desc.buffer = buffer->Handle();
buffer_desc.offset = 0;
buffer_desc.range = VkDeviceSize(size);
VkWriteDescriptorSet write = {};
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = descSet;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;
write.pBufferInfo = &buffer_desc;
dev.vkUpdateDescriptorSets( dev.GetVkDevice(), 1, &write, 0, null );
}
return true;
}
} // FG
| 30.722989 | 158 | 0.6266 |
d7b9c3af34674fcfe0367e66b87fbf1bd1209ed3 | 939 | cpp | C++ | leetcode-cn/cpp/Decode String.cpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | 2 | 2019-01-27T14:16:09.000Z | 2019-05-25T10:05:24.000Z | leetcode-cn/cpp/Decode String.cpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | null | null | null | leetcode-cn/cpp/Decode String.cpp | MU001999/codeex | 23e300f9121a8d6bf4f4c9ec103510193808e9ba | [
"MIT"
] | 1 | 2020-11-05T05:17:28.000Z | 2020-11-05T05:17:28.000Z | /*
Q-URL: https://leetcode-cn.com/problems/decode-string/
# BEATS 100%
*/
class Solution {
private:
string helper(string &s, string::iterator &it)
{
if (it == s.end()) return "";
string pre1, pre2, res, ens;
while (isalpha(*it)) pre1 += *it++;
if (it == s.end()) return pre1;
while (isdigit(*it)) pre2 += *it++;
if (pre2.empty()) return pre1;
++it;
while (*it != ']')
{
if (isdigit(*it)) ens += helper(s, it);
else ens += *it++;
}
++it;
auto k = stoi(pre2);
while (k--) res += ens;
return pre1 + res;
}
public:
string decodeString(string s) {
string res;
auto it = s.begin();
while (it != s.end()) res += helper(s, it);
return res;
}
};
| 19.5625 | 54 | 0.407881 |
d7ba6a5cc53bc9abc7ffa4a01147e332e4679947 | 973 | cpp | C++ | Volume102/10281 - Average Speed/10281.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | 1 | 2017-01-25T18:07:49.000Z | 2017-01-25T18:07:49.000Z | Volume102/10281 - Average Speed/10281.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | Volume102/10281 - Average Speed/10281.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | // Author: Stancioiu Nicu Razvan
// Problem: http://uva.onlinejudge.org/external/102/10281.html
#include <string>
#include <iostream>
#include <sstream>
#include <cstdio>
using namespace std;
int main()
{
int speed,currentSpeed=0;
int hour,min,sec;
int currentHour=0;
int prevHour=0;
string s;
double km=0;
while(getline(cin,s))
{
istringstream iss(s);
iss>>s;
int i=0;
hour=min=sec=0;
while(s[i]>='0' && s[i]<='9')
{
hour*=10;
hour+=s[i]-'0';
i++;
}
i++;
while(s[i]>='0' && s[i]<='9')
{
min*=10;
min+=s[i]-'0';
i++;
}
i++;
while(s[i]>='0' && s[i]<='9')
{
sec=sec*10 + s[i]-'0';
i++;
}
currentHour=hour*3600+min*60+sec;
if(!(iss>>speed))
{
km+=(double)(currentHour-prevHour)/3600*currentSpeed;
prevHour=currentHour;
printf("%s %.2f km\n",s.c_str(),km);
}
else
{
km+=(double)(currentHour-prevHour)/3600*currentSpeed;
prevHour=currentHour;
currentSpeed=speed;
}
}
return 0;
} | 16.775862 | 62 | 0.579651 |
d7bad70d390416bbdc5854f14fe5275cebb5a585 | 2,089 | cpp | C++ | Raven.CppClient.Tests/PutDocumentCommandTest.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-04-24T02:34:53.000Z | 2019-08-01T08:22:26.000Z | Raven.CppClient.Tests/PutDocumentCommandTest.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 2 | 2019-03-21T09:00:02.000Z | 2021-02-28T23:49:26.000Z | Raven.CppClient.Tests/PutDocumentCommandTest.cpp | mlawsonca/ravendb-cpp-client | c3a3d4960c8b810156547f62fa7aeb14a121bf74 | [
"MIT"
] | 3 | 2019-03-04T11:58:54.000Z | 2021-03-01T00:25:49.000Z | #include "pch.h"
#include "RavenTestDriver.h"
#include "raven_test_definitions.h"
#include "DocumentSession.h"
#include "AdvancedSessionOperations.h"
#include "RequestExecutor.h"
#include "User.h"
#include "PutDocumentCommand.h"
namespace ravendb::client::tests::client::documents::commands
{
class PutDocumentCommandTest : public driver::RavenTestDriver
{
protected:
void customise_store(std::shared_ptr<ravendb::client::documents::DocumentStore> store) override
{
//store->set_before_perform(infrastructure::set_for_fiddler);
}
};
TEST_F(PutDocumentCommandTest, CanPutDocumentUsingCommand)
{
auto store = get_document_store(TEST_NAME);
auto user = std::make_shared<infrastructure::entities::User>();
user->name = "Alexander";
user->age = 38;
nlohmann::json json = *user;
auto command = ravendb::client::documents::commands::PutDocumentCommand("users/1", {}, json);
store->get_request_executor()->execute(command);
auto res = command.get_result();
ASSERT_EQ("users/1", res->id);
ASSERT_FALSE(res->change_vector.empty());
{
auto session = store->open_session();
auto loaded_user = session.load<infrastructure::entities::User>("users/1");
ASSERT_EQ("Alexander", loaded_user->name);
}
}
TEST_F(PutDocumentCommandTest, CanPutLargeDocumentUsingCommand)
{
auto store = get_document_store(TEST_NAME);
auto user = std::make_shared<infrastructure::entities::User>();
constexpr std::size_t LARGE_STRING_SIZE{ 1024 * 1024 };
user->name.reserve(LARGE_STRING_SIZE);
for(std::size_t i = 0; i < LARGE_STRING_SIZE/4; ++i)
{
user->name.append("AbCd");
}
nlohmann::json json = *user;
auto command = ravendb::client::documents::commands::PutDocumentCommand("users/1", {}, json);
store->get_request_executor()->execute(command);
auto res = command.get_result();
ASSERT_EQ("users/1", res->id);
ASSERT_FALSE(res->change_vector.empty());
{
auto session = store->open_session();
auto loaded_user = session.load<infrastructure::entities::User>("users/1");
ASSERT_EQ(user->name, loaded_user->name);
}
}
}
| 27.853333 | 97 | 0.721398 |
d7bd45c05e0eec748467f5543c97fbf349a019c8 | 3,375 | hpp | C++ | examples/CBuilder/Compound/Locking/Server/comserv.hpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 121 | 2020-09-22T10:46:20.000Z | 2021-11-17T12:33:35.000Z | examples/CBuilder/Compound/Locking/Server/comserv.hpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 8 | 2020-09-23T12:32:23.000Z | 2021-07-28T07:01:26.000Z | examples/CBuilder/Compound/Locking/Server/comserv.hpp | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 42 | 2020-09-22T14:37:20.000Z | 2021-10-04T10:24:12.000Z | // Borland C++ Builder
// Copyright (c) 1995, 1999 by Borland International
// All rights reserved
// (DO NOT EDIT: machine generated header) 'ComServ.pas' rev: 5.00
#ifndef ComServHPP
#define ComServHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <ComObj.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <ActiveX.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Comserv
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TStartMode { smStandalone, smAutomation, smRegServer, smUnregServer };
#pragma option pop
typedef void __fastcall (__closure *TLastReleaseEvent)(bool &Shutdown);
class DELPHICLASS TComServer;
class PASCALIMPLEMENTATION TComServer : public Comobj::TComServerObject
{
typedef Comobj::TComServerObject inherited;
private:
int FObjectCount;
int FFactoryCount;
_di_ITypeLib FTypeLib;
AnsiString FServerName;
AnsiString FHelpFileName;
bool FIsInprocServer;
TStartMode FStartMode;
bool FStartSuspended;
bool FRegister;
bool FUIInteractive;
TLastReleaseEvent FOnLastRelease;
void __fastcall FactoryFree(TComObjectFactory* Factory);
void __fastcall FactoryRegisterClassObject(TComObjectFactory* Factory);
void __fastcall FactoryUpdateRegistry(TComObjectFactory* Factory);
void __fastcall LastReleased(void);
protected:
virtual int __fastcall CountObject(bool Created);
virtual int __fastcall CountFactory(bool Created);
virtual AnsiString __fastcall GetHelpFileName();
virtual AnsiString __fastcall GetServerFileName();
virtual AnsiString __fastcall GetServerKey();
virtual AnsiString __fastcall GetServerName();
virtual bool __fastcall GetStartSuspended(void);
virtual _di_ITypeLib __fastcall GetTypeLib();
virtual void __fastcall SetHelpFileName(const AnsiString Value);
public:
__fastcall TComServer(void);
__fastcall virtual ~TComServer(void);
void __fastcall Initialize(void);
void __fastcall LoadTypeLib(void);
void __fastcall SetServerName(const AnsiString Name);
void __fastcall UpdateRegistry(bool Register);
__property bool IsInprocServer = {read=FIsInprocServer, write=FIsInprocServer, nodefault};
__property int ObjectCount = {read=FObjectCount, nodefault};
__property TStartMode StartMode = {read=FStartMode, nodefault};
__property bool UIInteractive = {read=FUIInteractive, write=FUIInteractive, nodefault};
__property TLastReleaseEvent OnLastRelease = {read=FOnLastRelease, write=FOnLastRelease};
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE TComServer* ComServer;
extern PACKAGE HRESULT __stdcall DllGetClassObject(const GUID &CLSID, const GUID &IID, void *Obj);
extern PACKAGE HRESULT __stdcall DllCanUnloadNow(void);
extern PACKAGE HRESULT __stdcall DllRegisterServer(void);
extern PACKAGE HRESULT __stdcall DllUnregisterServer(void);
} /* namespace Comserv */
#if !defined(NO_IMPLICIT_NAMESPACE_USE)
using namespace Comserv;
#endif
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // ComServ
| 34.793814 | 98 | 0.740741 |