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
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 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
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3fe1e08052fbf04b08e0214547368e45b3804aa4
| 637
|
cpp
|
C++
|
YorozuyaGSLib/source/_pt_trans_votepaper_zocl.cpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
YorozuyaGSLib/source/_pt_trans_votepaper_zocl.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
YorozuyaGSLib/source/_pt_trans_votepaper_zocl.cpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
#include <_pt_trans_votepaper_zocl.hpp>
START_ATF_NAMESPACE
_pt_trans_votepaper_zocl::_pt_trans_votepaper_zocl()
{
using org_ptr = void (WINAPIV*)(struct _pt_trans_votepaper_zocl*);
(org_ptr(0x1402bfff0L))(this);
};
void _pt_trans_votepaper_zocl::ctor__pt_trans_votepaper_zocl()
{
using org_ptr = void (WINAPIV*)(struct _pt_trans_votepaper_zocl*);
(org_ptr(0x1402bfff0L))(this);
};
int _pt_trans_votepaper_zocl::size()
{
using org_ptr = int (WINAPIV*)(struct _pt_trans_votepaper_zocl*);
return (org_ptr(0x1402c0490L))(this);
};
END_ATF_NAMESPACE
| 28.954545
| 74
| 0.689168
|
lemkova
|
3fe76f19d28426a27e7fd1418b7032b118b02e00
| 745
|
cc
|
C++
|
src/Animation.cc
|
carolinavillam/Lucky-Monkey
|
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
|
[
"MIT"
] | null | null | null |
src/Animation.cc
|
carolinavillam/Lucky-Monkey
|
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
|
[
"MIT"
] | null | null | null |
src/Animation.cc
|
carolinavillam/Lucky-Monkey
|
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
|
[
"MIT"
] | null | null | null |
#include "Animation.hh"
Animation:: Animation(const char* animationUrl, Drawable*& drawable)
{
reader = new std::ifstream();
reader->open(animationUrl);
*reader >> delay;
*reader >> row;
*reader >> startFrame;
*reader >> endFrame;
reader->close();
currentFrame = startFrame;
this->drawable = drawable;
}
Animation::~Animation()
{
}
void Animation::Play(float& deltaTime)
{
timer += deltaTime;
if(timer >= delay)
{
drawable->RebindRect(currentFrame * drawable->GetWidth(), row * drawable->GetHeight(), drawable->GetWidth(), drawable->GetHeight());
//cambiar de frame
timer = 0.f;
if(currentFrame < endFrame)
{
currentFrame++;
}
else
{
currentFrame = startFrame;
}
}
}
| 19.102564
| 136
| 0.634899
|
carolinavillam
|
3fe8df62bca012d15b55803766329e5032619fe6
| 139
|
cpp
|
C++
|
src/grpc_server_lib/src/greeter_async_server.cpp
|
vladimir-voinea/cpp_grpc_template
|
8f79b0083ed387e6b3de3b48b7306f2cbba7bb28
|
[
"MIT"
] | null | null | null |
src/grpc_server_lib/src/greeter_async_server.cpp
|
vladimir-voinea/cpp_grpc_template
|
8f79b0083ed387e6b3de3b48b7306f2cbba7bb28
|
[
"MIT"
] | null | null | null |
src/grpc_server_lib/src/greeter_async_server.cpp
|
vladimir-voinea/cpp_grpc_template
|
8f79b0083ed387e6b3de3b48b7306f2cbba7bb28
|
[
"MIT"
] | null | null | null |
#include <grpc_server_lib/greeter_async_server.hpp>
int main(int argc, char** argv) {
ServerImpl server;
server.Run();
return 0;
}
| 15.444444
| 51
| 0.71223
|
vladimir-voinea
|
3fe9ec20f18230b54c45d6cbb395a2ff9ac65eea
| 539
|
cpp
|
C++
|
matex-k18-a-js/krazki.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | 2
|
2019-05-04T09:37:09.000Z
|
2019-05-22T18:07:28.000Z
|
matex-k18-a-js/krazki.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | null | null | null |
matex-k18-a-js/krazki.cpp
|
Aleshkev/algoritmika
|
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
typedef intmax_t I;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
I n, m;
cin >> n >> m;
vector<I> r(n);
for (I i = 0; i < n; ++i) {
cin >> r[i];
if (i > 0 && r[i] > r[i - 1]) r[i] = r[i - 1];
}
I l = n - 1;
for (I i = 0; i < m; ++i) {
I a;
cin >> a;
while (l >= 0 && r[l] < a) --l;
--l;
}
cout << max((I)0, l + 1 + 1) << '\n';
#ifdef UNITEST
cout.flush();
system("pause");
#endif
return 0;
}
| 14.567568
| 50
| 0.45269
|
Aleshkev
|
3feb165d280660848289bb4b2c35ed3da7efa381
| 12,127
|
hpp
|
C++
|
package/lib-nms-abp/inc/nms_abp.hpp
|
krai/ck-mlperf
|
8849c68662be2f9f7ea6d2520dba35d6a159e4b8
|
[
"BSD-3-Clause"
] | 2
|
2021-04-22T01:29:58.000Z
|
2021-12-13T14:29:35.000Z
|
package/lib-nms-abp/inc/nms_abp.hpp
|
krai/ck-mlperf
|
8849c68662be2f9f7ea6d2520dba35d6a159e4b8
|
[
"BSD-3-Clause"
] | 4
|
2021-06-27T22:33:19.000Z
|
2022-02-07T09:21:59.000Z
|
package/lib-nms-abp/inc/nms_abp.hpp
|
krai/ck-mlperf
|
8849c68662be2f9f7ea6d2520dba35d6a159e4b8
|
[
"BSD-3-Clause"
] | 5
|
2021-02-17T12:10:39.000Z
|
2022-02-17T18:19:16.000Z
|
// MIT License
//
// Copyright (c) 2021 Krai Ltd
//
// 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 <iostream>
#include <math.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <algorithm>
#include "fp16.h"
template <typename Loc, typename Conf, typename MParams>
class NMS_ABP {
std::string binPath;
public:
std::string priorName;
float *priorTensor;
MParams modelParams;
NMS_ABP() {
binPath = std::getenv("PRIOR_BIN_PATH");
if (binPath == "") binPath = ".";
readPriors();
}
~NMS_ABP() {
delete priorTensor;
};
float *read(std::string priorFilename, uint32_t tensorLength) {
std::ifstream fs(binPath + "/" + priorFilename, std::ifstream::binary);
fs.seekg(0, std::ios::end);
uint32_t fileSize = fs.tellg();
fs.seekg(0, std::ios::beg);
if (tensorLength != fileSize) {
std::cerr << "Invalid input: " << priorFilename << std::endl;
std::cerr << "Length mismatch: "
<< " Tensor Size: " << tensorLength
<< ",\t File Size: " << fileSize << std::endl;
std::exit(1);
}
float *priorData = new float[tensorLength];
fs.read((char *)priorData, tensorLength);
fs.close();
return priorData;
}
public:
void readPriors() {
priorTensor =
read(modelParams.priorName,
modelParams.TOTAL_NUM_BOXES * NUM_COORDINATES * sizeof(float));
}
void anchorBoxProcessing(const Loc *const locTensor,
const Conf *const confTensor,
std::vector<bbox> &selectedAll, const float idx) {
const Conf *confPtr = confTensor;
const Loc *locPtr = locTensor;
float const *priorPtr = priorTensor;
if (modelParams.BOXES_INDEX == 0) {
for (uint32_t ci = 1; ci < modelParams.NUM_CLASSES; ci++) {
uint32_t confItr = ci * modelParams.OFFSET_CONF;
std::vector<bbox> result;
std::vector<Conf> scores;
std::vector<bbox> selected;
confPtr = confTensor;
locPtr = locTensor;
priorPtr = priorTensor;
for (uint32_t bi = 0; bi < modelParams.TOTAL_NUM_BOXES;
++bi, confPtr++, locPtr++, priorPtr++) {
Conf confidence = confPtr[confItr];
if (!above_Class_Threshold(confidence)) continue;
bbox cBox = {get_Loc_Val(locPtr[modelParams.BOX_ITR_0]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_1]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_2]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_3])};
if (modelParams.variance.data() != NULL)
cBox = decodeLocationTensorWithVariance(
cBox, priorPtr, modelParams.variance.data());
else
cBox = decodeLocationTensor(cBox, priorPtr);
result.emplace_back(std::initializer_list<float>{
idx, cBox[1], cBox[0], cBox[3], cBox[2], 0, (float)ci});
scores.push_back(confidence);
}
if (result.size()) {
NMS(result, scores, modelParams.NMS_THRESHOLD,
modelParams.MAX_BOXES_PER_CLASS, selected, selectedAll,
modelParams.class_map);
}
}
} else {
std::vector<bbox> result[modelParams.NUM_CLASSES];
std::vector<bbox> selected[modelParams.NUM_CLASSES];
std::vector<Conf> scores[modelParams.NUM_CLASSES];
float const *priorPtr = priorTensor;
for (uint32_t bi = 0; bi < modelParams.TOTAL_NUM_BOXES;
bi++, locPtr += 4, priorPtr += 4) {
uint32_t confItr = bi * modelParams.NUM_CLASSES;
for (uint32_t ci = 1; ci < modelParams.NUM_CLASSES; ci++) {
Conf confidence = confPtr[confItr + ci];
if (!above_Class_Threshold(confidence)) continue;
bbox cBox = {get_Loc_Val(locPtr[modelParams.BOX_ITR_0]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_1]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_2]),
get_Loc_Val(locPtr[modelParams.BOX_ITR_3])};
if (modelParams.variance.data() != NULL)
cBox = decodeLocationTensorWithVariance(
cBox, priorPtr, modelParams.variance.data());
else
cBox = decodeLocationTensor(cBox, priorPtr);
result[ci].emplace_back(std::initializer_list<float>{
idx, cBox[1], cBox[0], cBox[3], cBox[2], 0, (float)ci});
scores[ci].push_back(confidence);
}
}
for (uint32_t ci = 1; ci < modelParams.NUM_CLASSES; ci++) {
if (result[ci].size()) {
NMS(result[ci], scores[ci], modelParams.NMS_THRESHOLD,
modelParams.MAX_BOXES_PER_CLASS, selected[ci], selectedAll,
modelParams.class_map);
}
}
}
int middle = selectedAll.size();
if (middle > modelParams.MAX_DETECTIONS_PER_IMAGE) {
middle = modelParams.MAX_DETECTIONS_PER_IMAGE;
}
std::partial_sort(selectedAll.begin(), selectedAll.begin() + middle,
selectedAll.end(), [](const bbox &a, const bbox &b) {
return a[SCORE_POSITION] > b[SCORE_POSITION];
});
}
inline Conf above_Class_Threshold(uint8_t score) {
return score > modelParams.CLASS_THRESHOLD_UINT8;
}
inline Conf above_Class_Threshold(uint16_t score) {
return score > modelParams.CLASS_THRESHOLD_FP16;
}
inline Conf above_Class_Threshold(float score) {
return score > modelParams.CLASS_THRESHOLD;
}
inline float get_Loc_Val(uint8_t x) {
return CONVERT_UINT8_FP32(x, modelParams.LOC_OFFSET,
modelParams.LOC_SCALE);
}
inline float get_Loc_Val(float x) { return x; }
inline float get_Score_Val(uint16_t x) { return fp16_ieee_to_fp32_value(x); }
inline float get_Score_Val(uint8_t x) {
return CONVERT_UINT8_FP32(x, modelParams.CONF_OFFSET,
modelParams.CONF_SCALE);
;
}
inline float get_Score_Val(float x) { return x; }
bbox decodeLocationTensorWithVariance(const bbox &loc,
const float *const prior,
const float *const var) {
float x = prior[modelParams.BOX_ITR_0] +
loc[0] * var[0] * prior[modelParams.BOX_ITR_2];
float y = prior[modelParams.BOX_ITR_1] +
loc[1] * var[0] * prior[modelParams.BOX_ITR_3];
float w = prior[modelParams.BOX_ITR_2] * expf(loc[2] * var[1]);
float h = prior[modelParams.BOX_ITR_3] * expf(loc[3] * var[1]);
x -= (w / 2.0f);
y -= (h / 2.0f);
w += x;
h += y;
return {x, y, w, h};
}
bbox decodeLocationTensor(const bbox &loc, const float *const prior) {
float box_x1 = prior[1];
float box_y1 = prior[0];
float box_x2 = prior[3];
float box_y2 = prior[2];
float dx = loc[1] / 10.0f;
float dy = loc[0] / 10.0f;
float dw = loc[3] / 5.0f;
float dh = loc[2] / 5.0f;
float w = box_x2 - box_x1;
float h = box_y2 - box_y1;
float cent_x = box_x1 + 0.5f * w;
float cent_y = box_y1 + 0.5f * h;
float pred_cent_x = dx * w + cent_x;
float pred_cent_y = dy * h + cent_y;
float pred_w = expf(dw) * w;
float pred_h = expf(dh) * h;
return {pred_cent_x - 0.5f * pred_w, pred_cent_y - 0.5f * pred_h,
pred_cent_x + 0.5f * pred_w, pred_cent_y + 0.5f * pred_h};
}
template <typename A, typename B>
void pack(const std::vector<A> &part1, const std::vector<B> &part2,
std::vector<std::pair<A, B> > &packed) {
assert(part1.size() == part2.size());
for (size_t i = 0; i < part1.size(); i++) {
packed.push_back(std::make_pair(part1[i], part2[i]));
}
}
template <typename A, typename B>
void unpack(const std::vector<std::pair<A, B> > &packed,
std::vector<A> &part1, std::vector<B> &part2) {
for (size_t i = 0; i < part1.size(); i++) {
part1[i] = packed[i].first;
part2[i] = packed[i].second;
}
}
#define AREA(y1, x1, y2, x2) ((y2 - y1) * (x2 - x1))
float computeIOU(const float *box1, const float *box2) {
float box1_y1 = box1[1], box1_x1 = box1[2], box1_y2 = box1[3],
box1_x2 = box1[4];
float box2_y1 = box2[1], box2_x1 = box2[2], box2_y2 = box2[3],
box2_x2 = box2[4];
assert(box1_y1 < box1_y2 && box1_x1 < box1_x2);
assert(box2_y1 < box2_y2 && box2_x1 < box2_x2);
float inter_y1 = std::max(box1_y1, box2_y1);
float inter_x1 = std::max(box1_x1, box2_x1);
float inter_y2 = std::min(box1_y2, box2_y2);
float inter_x2 = std::min(box1_x2, box2_x2);
float IOU = 0.0f;
if ((inter_y1 < inter_y2) &&
(inter_x1 < inter_x2)) // there is a valid intersection
{
float intersect = AREA(inter_y1, inter_x1, inter_y2, inter_x2);
float total = AREA(box1_y1, box1_x1, box1_y2, box1_x2) +
AREA(box2_y1, box2_x1, box2_y2, box2_x2) - intersect;
IOU = total > 0.0f ? (intersect / total) : 0.0f;
}
return IOU;
}
void insertSelected(std::vector<std::vector<float> > &selected,
std::vector<std::vector<float> > &selectedAll,
std::vector<float> &cand, const float &thres,
std::vector<Conf> &scores, int index,
std::vector<float> &classmap) {
for (int i = 0; i < selected.size(); i++) {
if (computeIOU(&cand[0], &selected[i][0]) > thres) {
return;
}
}
cand[SCORE_POSITION] = get_Score_Val(scores[index]);
if (modelParams.MAP_CLASSES)
cand[CLASS_POSITION] = classmap[cand[CLASS_POSITION]];
selected.push_back(cand);
selectedAll.push_back(cand);
}
void NMS(std::vector<std::vector<float> > &boxes, std::vector<Conf> &scores,
const float &thres, const int &max_output_size,
std::vector<std::vector<float> > &selected,
std::vector<std::vector<float> > &selectedAll,
std::vector<float> &classmap) {
std::vector<std::pair<std::vector<float>, Conf> > packed;
assert(boxes.size() == scores.size());
pack(boxes, scores, packed);
std::sort(
std::begin(packed), std::end(packed),
[&](const auto &a, const auto &b) { return (a.second > b.second); });
unpack(packed, boxes, scores);
for (int i = 0; (i < boxes.size()) && (selected.size() < max_output_size);
i++) {
insertSelected(selected, selectedAll, boxes[i], thres, scores, i,
classmap);
}
}
};
| 39.630719
| 80
| 0.579203
|
krai
|
3feb1bf4f05bea465c6fa1ce0b9e5f17b1afc165
| 294
|
cc
|
C++
|
StackOutBounds.cc
|
7andrew7/Bugorama
|
d0315083732f7724612963e98a7e89481f7acade
|
[
"MIT"
] | null | null | null |
StackOutBounds.cc
|
7andrew7/Bugorama
|
d0315083732f7724612963e98a7e89481f7acade
|
[
"MIT"
] | null | null | null |
StackOutBounds.cc
|
7andrew7/Bugorama
|
d0315083732f7724612963e98a7e89481f7acade
|
[
"MIT"
] | null | null | null |
#include <iostream>
// Reference out-of-bounds stack memory via a helper function
char BufferFetch(char *buffer, size_t index) {
return buffer[index];
}
int main(int argc, char **argv) {
char buffer[256] = {0};
char c = BufferFetch(buffer, 259);
std::cout << c << std::endl;
}
| 18.375
| 61
| 0.656463
|
7andrew7
|
684cafa346744b347917ad0cb40319d9f91ef922
| 588
|
cc
|
C++
|
ports/www/chromium-legacy/newport/files/patch-chrome_browser_download_download__shelf__context__menu.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 31
|
2015-02-06T17:06:37.000Z
|
2022-03-08T19:53:28.000Z
|
ports/www/chromium-legacy/newport/files/patch-chrome_browser_download_download__shelf__context__menu.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 236
|
2015-06-29T19:51:17.000Z
|
2021-12-16T22:46:38.000Z
|
ports/www/chromium-legacy/newport/files/patch-chrome_browser_download_download__shelf__context__menu.cc
|
liweitianux/DeltaPorts
|
b907de0ceb9c0e46ae8961896e97b361aa7c62c0
|
[
"BSD-2-Clause-FreeBSD"
] | 52
|
2015-02-06T17:05:36.000Z
|
2021-10-21T12:13:06.000Z
|
--- chrome/browser/download/download_shelf_context_menu.cc.orig 2020-11-13 06:36:36 UTC
+++ chrome/browser/download/download_shelf_context_menu.cc
@@ -146,7 +146,7 @@ base::string16 DownloadShelfContextMenu::GetLabelForCo
: IDS_DOWNLOAD_MENU_PLATFORM_OPEN_ALWAYS;
break;
}
-#elif defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS)
+#elif defined(OS_MAC) || defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
if (can_open_pdf_in_system_viewer) {
id = IDS_DOWNLOAD_MENU_PLATFORM_OPEN_ALWAYS;
break;
| 49
| 87
| 0.697279
|
liweitianux
|
684f3552f949e69f8353322b84d8b8e9c018909a
| 824
|
hpp
|
C++
|
src/utils/function.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 154
|
2020-01-03T02:51:51.000Z
|
2020-08-03T19:44:53.000Z
|
src/utils/function.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 22
|
2020-01-26T04:18:28.000Z
|
2020-07-04T06:38:28.000Z
|
src/utils/function.hpp
|
dynilath/cqcppsdk
|
8f14c2ed85b6d2917ad7aef149acdfb89512937f
|
[
"MIT"
] | 40
|
2020-01-06T11:17:25.000Z
|
2020-08-07T08:26:32.000Z
|
#pragma once
#include <functional>
namespace cq::utils {
template <typename ReturnType, typename... Params, typename... Args>
inline ReturnType call_if_valid(const std::function<ReturnType(Params...)> &func, Args &&... args) {
if (func) {
return func(std::forward<Args>(args)...);
}
return {};
}
template <typename... Params, typename... Args>
inline void call_if_valid(const std::function<void(Params...)> &func, Args &&... args) {
if (func) {
func(std::forward<Args>(args)...);
}
}
template <typename Cont, typename... Args>
inline void call_all(const Cont &funcs, Args &&... args) {
for (const auto &f : funcs) {
call_if_valid(f, std::forward<Args>(args)...);
}
}
} // namespace cq::utils
| 29.428571
| 104
| 0.569175
|
dynilath
|
684fc2132fae3647a2a82ab6f68778a29c42fb4d
| 10,012
|
hpp
|
C++
|
commune/kMeansLearner.hpp
|
fuchuanpu/Whisper
|
80622d6d30b59feab1312865b4395960b9b4d8ea
|
[
"MIT"
] | 25
|
2021-11-15T03:03:46.000Z
|
2022-03-23T03:39:06.000Z
|
commune/kMeansLearner.hpp
|
sljx/Whisper
|
80622d6d30b59feab1312865b4395960b9b4d8ea
|
[
"MIT"
] | 2
|
2021-12-22T13:16:53.000Z
|
2022-02-02T17:23:42.000Z
|
commune/kMeansLearner.hpp
|
sljx/Whisper
|
80622d6d30b59feab1312865b4395960b9b4d8ea
|
[
"MIT"
] | 11
|
2021-11-15T04:00:53.000Z
|
2022-03-07T04:31:18.000Z
|
#pragma once
#include "../common.hpp"
#include "./analyzerWorker.hpp"
#include "./deviceConfig.hpp"
#include <mlpack/core.hpp>
#include <mlpack/methods/kmeans/kmeans.hpp>
#include <time.h>
#include <unistd.h>
#include <semaphore.h>
namespace Whisper {
class AnalyzerWorkerThread;
class DeviceConfig;
struct LearnerConfigParam final {
// Number of required trainning data
size_t num_train_data = 2000;
// value of K for Kmeans.
size_t val_K = 10;
// Display the debuging information
bool verbose = true;
bool save_result = false;
string save_result_file = "";
bool load_result = false;
string load_result_file = "";
auto inline display_params() const -> void {
printf("[Whisper Leaner Configuration]\n");
printf("Record required for training: %ld, K value for Kmeans: %ld\n", num_train_data, val_K);
if (save_result) {
printf("Save training result to: %s\n", save_result_file.c_str());
}
if (load_result) {
printf("Load training result from: %s\n", load_result_file.c_str());
}
}
LearnerConfigParam() = default;
virtual ~LearnerConfigParam() {}
LearnerConfigParam & operator=(const LearnerConfigParam &) = delete;
LearnerConfigParam(const LearnerConfigParam &) = delete;
};
class KMeansLearner final {
friend class AnalyzerWorkerThread;
friend class DeviceConfig;
private:
using feature_t = vector<double_t>;
// Dataset collected from AnalyzeWorker
vector<vector<double_t> > train_set;
// Mutual exclution lock for trainSet
mutable sem_t data_sema;
void inline acquire_semaphore_data() const {
sem_wait(&data_sema);
}
void inline release_semaphore_data() const {
sem_post(&data_sema);
}
// Mutual exclution for training process (only one AnalyeWorker can start the trainning)
mutable sem_t learn_sema;
void inline acquire_semaphore_learn() const {
sem_wait(&learn_sema);
}
void inline release_semaphore_learn() const {
sem_post(&learn_sema);
}
// Clustering centers
vector<feature_t> train_result;
shared_ptr<LearnerConfigParam> p_learner_config;
auto save_result_file() const -> bool {
if (p_learner_config->verbose) {
LOGF("Save centers to file: %s.", p_learner_config->save_result_file.c_str());
}
assert(p_learner_config->save_result);
try {
ofstream fs(p_learner_config->load_result_file);
if (!fs.good()) {
throw logic_error("Open target file failed.");
}
json _j;
for (size_t i = 0; i < train_result.size(); i ++) {
json __j;
for (size_t j = 0; j < train_result[0].size(); j ++) {
__j.push_back(train_result[i][j]);
}
_j.push_back(__j);
}
fs << _j;
fs.close();
} catch (exception & e) {
WARN(e.what());
return false;
}
if (p_learner_config->verbose) {
LOGF("Save result to file success.");
}
return true;
}
auto load_result_file() -> bool {
if (p_learner_config->verbose) {
LOGF("Load centers form file: %s.", p_learner_config->load_result_file.c_str());
}
assert(p_learner_config->load_result);
try {
ifstream fs(p_learner_config->load_result_file);
if (!fs.good()) {
throw logic_error("Target load file not exist.");
}
json centers;
fs >> centers;
fs.close();
if (centers.size() != p_learner_config->val_K) {
throw logic_error("Cluster centers number mismatch.");
}
for (size_t i = 0; i < centers.size(); i ++) {
train_result.push_back({});
for (size_t j = 0; j < centers[0].size(); j ++) {
train_result[i].push_back(centers[i][j]);
}
}
} catch (exception & e) {
WARN(e.what());
return false;
}
if (p_learner_config->verbose) {
LOGF("Load result from file success.");
}
start_learn = true;
finish_learn = true;
return true;
}
public:
// Start the learning process
volatile bool start_learn = false;
// Finish the learning process
volatile bool finish_learn = false;
// Default constructor
KMeansLearner() {
sem_init(&data_sema, 0, 1);
sem_init(&learn_sema, 0, 1);
}
// Default deconstructor
~KMeansLearner() {}
KMeansLearner & operator=(const KMeansLearner &) const = delete;
KMeansLearner(const KMeansLearner &) = delete;
KMeansLearner(const decltype(p_learner_config) p_c):
p_learner_config(p_c) {
sem_init(&data_sema, 0, 1);
sem_init(&learn_sema, 0, 1);
}
// Add single recored to the training dataset
void add_train_data(feature_t & ve) {
train_set.push_back(ve);
}
// Add a batch of data to the training dataset
void add_train_data(vector<feature_t> & vve) {
train_set.insert(train_set.end(), vve.begin(), vve.end());
}
// Start the training process.
// The training process can be started by only one AnalyzeWorker.
void start_train() {
if (p_learner_config == nullptr) {
FATAL_ERROR("Configuration for learner not found.");
}
start_learn = true;
if(p_learner_config->verbose) {
if (!p_learner_config->load_result) {
LOGF("Learner: Start training, %ld records.", train_set.size());
}
}
if (p_learner_config->load_result) {
if (!load_result_file()) {
FATAL_ERROR("Learner Load result from file failed.");
} else {
return;
}
}
// Transform the std::vector representation to arma::matrix
size_t x_len = train_set.size();
size_t y_len = train_set[0].size();
arma::mat dataset(x_len, y_len, arma::fill::randu);
for (size_t i = 0; i < x_len; i ++) {
for (size_t j = 0; j < y_len; j ++) {
dataset(i, j) = train_set[i][j];
}
}
dataset = dataset.t();
// Call the mlpack KMeans implementation
arma::mat centroids;
arma::Row<size_t> assignments;
mlpack::kmeans::KMeans<> k;
k.Cluster(dataset, p_learner_config->val_K, assignments, centroids);
// Transform the arma::matrix to std::vector type
centroids = centroids.t();
for (size_t i = 0; i < centroids.n_rows; i ++) {
vector<double_t> ve;
for (size_t j = 0; j < centroids.n_cols; j ++) {
ve.push_back(centroids(i, j));
}
train_result.push_back(ve);
}
finish_learn = true;
if (p_learner_config->save_result) {
if (!save_result_file()) {
FATAL_ERROR("Learner save result to file failed.");
}
}
if(p_learner_config->verbose) {
LOGF("Learner: Finsih training");
}
}
// Training data is enough or not
auto inline reach_learn() const -> bool {
if (p_learner_config == nullptr) {
FATAL_ERROR("Configuration for learner not found.");
}
if (p_learner_config->load_result) {
return true;
}
return train_set.size() > p_learner_config->num_train_data;
}
// Getter of clustering center
auto inline get_K() const -> size_t {
return p_learner_config->val_K;
}
auto configure_via_json(const json & jin) -> bool {
if (p_learner_config != nullptr) {
WARN("Learner configuration overleap.");
}
p_learner_config = make_shared<LearnerConfigParam>();
if (p_learner_config == nullptr) {
WARNF("learner configuration: bad allocation.");
return false;
}
try {
if (jin.count("val_K")) {
p_learner_config->val_K =
static_cast<decltype(p_learner_config->val_K)>(jin["val_K"]);
}
if (jin.count("num_train_data")) {
p_learner_config->num_train_data =
static_cast<decltype(p_learner_config->num_train_data)>(jin["num_train_data"]);
}
if (jin.count("save_result")) {
p_learner_config->save_result =
static_cast<decltype(p_learner_config->save_result)>(jin["save_result"]);
if (jin.count("save_result_file")) {
p_learner_config->save_result_file =
static_cast<decltype(p_learner_config->save_result_file)>(jin["save_result_file"]);
}
}
if (jin.count("load_result")) {
p_learner_config->load_result =
static_cast<decltype(p_learner_config->load_result)>(jin["load_result"]);
if (jin.count("load_result_file")) {
p_learner_config->load_result_file =
static_cast<decltype(p_learner_config->load_result_file)>(jin["load_result_file"]);
}
}
if (jin.count("verbose")) {
p_learner_config->verbose =
static_cast<decltype(p_learner_config->verbose)>(jin["verbose"]);
}
if (p_learner_config->load_result && p_learner_config->save_result) {
throw logic_error("Can not save tarining result while load the result.");
}
} catch (exception & e) {
WARN(e.what());
return false;
}
return true;
}
};
}
| 30.431611
| 107
| 0.560727
|
fuchuanpu
|
68505f2e3f041ba73de3fd3302d0ae08f1230e6a
| 4,880
|
cpp
|
C++
|
src/atta/uiSystem/layers/editor/topBar/localWindows/repoWindow.cpp
|
brenocq/atta
|
dc0f3429c26be9b0a340e63076f00f996e9282cc
|
[
"MIT"
] | 5
|
2021-11-18T02:44:45.000Z
|
2021-12-21T17:46:10.000Z
|
src/atta/uiSystem/layers/editor/topBar/localWindows/repoWindow.cpp
|
Brenocq/RobotSimulator
|
dc0f3429c26be9b0a340e63076f00f996e9282cc
|
[
"MIT"
] | 1
|
2021-11-18T02:56:14.000Z
|
2021-12-04T15:09:16.000Z
|
src/atta/uiSystem/layers/editor/topBar/localWindows/repoWindow.cpp
|
Brenocq/RobotSimulator
|
dc0f3429c26be9b0a340e63076f00f996e9282cc
|
[
"MIT"
] | 3
|
2020-09-10T07:17:00.000Z
|
2020-11-05T10:24:41.000Z
|
//--------------------------------------------------
// Atta UI System
// repoWindow.cpp
// Date: 2021-12-26
// By Breno Cunha Queiroz
//--------------------------------------------------
#include <atta/uiSystem/layers/editor/topBar/localWindows/repoWindow.h>
#include <atta/fileSystem/fileManager.h>
#include <imgui.h>
namespace atta::ui
{
RepoWindow::RepoWindow(fs::path repoPath):
_repoPath(repoPath), _shouldClose(false)
{
_title = repoPath.filename();
_description = "Repository without description";
if(fs::exists(repoPath/"README.md"))
{
ReadmeMetadata meta = parseReadmeMetadata(repoPath/"README.md");
if(meta.title.size())
_title = meta.title;
if(meta.description.size())
_description = meta.description;
}
findProjects();
}
void RepoWindow::render()
{
bool open = !_shouldClose;
if(ImGui::Begin((_title+"###RepoWindow"+_repoPath.string()).c_str(), &open))
{
ImGui::Text(_title.c_str());
ImGui::Text(_description.c_str());
ImGui::Separator();
if(ImGui::BeginTable(("repoWindowTable###RepoWindowTable"+_repoPath.string()).c_str(), 2, ImGuiTableFlags_Borders))
{
ImGui::TableSetupColumn("description", ImGuiTableColumnFlags_WidthStretch, 300.0f);
ImGui::TableSetupColumn("open", ImGuiTableColumnFlags_WidthFixed, 40.0f);
for(ProjectInfo& project : _projects)
{
// Project info
ImGui::TableNextColumn();
ImGui::Text(project.metadata.title.c_str());
ImGui::Spacing();
ImGui::Text(project.metadata.description.c_str());
// Open project button
ImGui::TableNextColumn();
if(ImGui::Button(("Open###RepoWindowOpenButton"+project.attaFile.string()).c_str()))
FileManager::openProject(project.attaFile);
ImGui::TableNextRow();
}
ImGui::EndTable();
}
}
ImGui::End();
_shouldClose = !open;
}
void RepoWindow::findProjects()
{
for(auto& entry : fs::recursive_directory_iterator(_repoPath))
{
fs::path p = entry.path();
if(p.extension().string() == ".atta")
{
ProjectInfo pi;
pi.attaFile = p;
pi.metadata = parseReadmeMetadata(p.parent_path()/"README.md");
_projects.push_back(pi);
}
}
}
RepoWindow::ReadmeMetadata RepoWindow::parseReadmeMetadata(fs::path readme)
{
ReadmeMetadata meta {};
// Check if file is a README.md file
if(readme.filename().string() != "README.md")
{
LOG_WARN("RepoWindow", "(parseReadmeMetadata) Expected readme file, but got $0", readme.filename().string());
return meta;
}
// Read file
std::ifstream readmeFile(readme);
if(readmeFile.is_open())
{
std::stringstream buffer;
buffer << readmeFile.rdbuf();
std::string readmeStr = buffer.str();
// Parse metadata
if(readmeStr.substr(0,3) == "---")
{
int start = 4;
while(true)
{
size_t endMark = readmeStr.find(':', start);
size_t nl = readmeStr.find('\n', start);
size_t endMeta = readmeStr.find("---", start);
if(endMark == std::string::npos ||
nl == std::string::npos ||
endMeta == std::string::npos)// File not well formated
break;
if(endMeta < nl)// End of metadata
break;
std::string marker = readmeStr.substr(start, endMark-start);
std::string value = readmeStr.substr(endMark+1, nl-endMark-1l);
if(value[0] == ' ') value = value.substr(1, value.size()-1);
if(marker == "title")
meta.title = value;
else if(marker == "description")
meta.description = value;
else if(marker == "image")
meta.image = value;
start = nl+1;
}
}
readmeFile.close();
}
else
{
// Could no open file, return
LOG_WARN("RepoWindow", "(parseReadmeMetadata) Could not open $0", readme.string());
return meta;
}
return meta;
}
}
| 34.366197
| 127
| 0.483811
|
brenocq
|
68519e46e9b2173735930021186e07b0327d8b4c
| 1,740
|
hpp
|
C++
|
source/vaultserver/NPC.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 67
|
2015-01-08T10:40:31.000Z
|
2022-03-29T21:16:51.000Z
|
source/vaultserver/NPC.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 20
|
2015-01-05T21:04:05.000Z
|
2018-04-15T11:50:37.000Z
|
source/vaultserver/NPC.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 60
|
2015-02-17T00:12:11.000Z
|
2021-08-21T22:16:58.000Z
|
#ifndef NPCDB_H
#define NPCDB_H
#include "vaultserver.hpp"
#include "Expected.hpp"
#include "BaseContainer.hpp"
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <functional>
class sqlite3_stmt;
/**
* \brief Represents a NPC
*/
namespace DB
{
class NPC
{
private:
enum TplFlags : unsigned short
{
Traits = 0x0001,
Stats = 0x0002,
Factions = 0x0004,
Effects = 0x0008,
AIData = 0x0010,
AIPack = 0x0020,
Model = 0x0040,
Base = 0x0080,
Inventory = 0x0100,
Script = 0x0200,
};
static std::unordered_map<unsigned int, NPC*> npcs;
unsigned int baseID;
bool essential;
bool female;
unsigned int race;
unsigned int template_;
unsigned short flags;
unsigned int deathitem;
signed int new_female;
unsigned int new_race;
NPC(const NPC&) = delete;
NPC& operator=(const NPC&) = delete;
public:
static Expected<NPC*> Lookup(unsigned int baseID);
static Expected<NPC*> GetNPC(const std::function<bool(const NPC&)>& pred);
unsigned int GetBase() const;
bool IsEssential() const;
bool IsFemale() const;
bool IsOriginalFemale() const;
unsigned int GetRace() const;
unsigned int GetOriginalRace() const;
unsigned int GetTemplate() const;
unsigned short GetFlags() const;
unsigned int GetDeathItem() const;
const std::vector<BaseContainer*>& GetBaseContainer() const;
void SetRace(unsigned int race);
void SetFemale(bool female);
NPC(const std::string& table, sqlite3_stmt* stmt);
~NPC() = default;
// must never be called. only defined because vector requires it
NPC(NPC&&) { std::terminate(); }
NPC& operator=(NPC&&) = delete;
};
}
#endif
| 21.481481
| 77
| 0.666667
|
CyberSys
|
68580e87a44db7b56238a9c1767c6b110e281494
| 1,949
|
cpp
|
C++
|
graph/475b.cpp
|
SnowOnion/CodeForcesLee
|
c2e964432ce9c2f6ca0c9038934c10f1bf1268b3
|
[
"MIT"
] | null | null | null |
graph/475b.cpp
|
SnowOnion/CodeForcesLee
|
c2e964432ce9c2f6ca0c9038934c10f1bf1268b3
|
[
"MIT"
] | null | null | null |
graph/475b.cpp
|
SnowOnion/CodeForcesLee
|
c2e964432ce9c2f6ca0c9038934c10f1bf1268b3
|
[
"MIT"
] | null | null | null |
/**
WA at test 16!
http://codeforces.com/contest/475/submission/8223685
16 11
<<<<>><><<<<<><<
vv^v^vvvv^v
output YES
answer NO
*/
#include<cstdio>
/**Floyd 算法. A 权值, D最终是最短距离*/
int A[410][410],D[410][410];
const int inf=1000000;
int rowarr[30],colarr[30];// 1: > ^ ; -1: < v
int n,m;
/**safe assign something to A*/
void assa(int val,int i,int j){
if(0<=i && i<n*m && 0<=j && j<n*m){
A[i][j]=val;
/////////// copy to D
D[i][j]=val;
}
}
int main(){
scanf("%d%d",&n,&m);
char inp[30];
scanf("%s",inp); // %c sucks
for(int i=0;i<n;i++){
rowarr[i]=inp[i]=='>'?1:-1;
}
scanf("%s",inp);
for(int i=0;i<m;i++){
colarr[i]=inp[i]=='^'?1:-1;
}
// calc A[i][j], copy to D[i][j]
for(int i=0;i<n*m;i++){
int xarr = rowarr[i/m];
int yarr = colarr[i%m];
for(int j=0;j<n*m;j++){
if(i==j) assa(0,i,j);
else if(j==i-1) assa(xarr==1?inf:1,i,j);
else if(j==i+1) assa(xarr==1?1:inf,i,j);
else if(j==i-m) assa(yarr==1?1:inf,i,j);
else if(j==i+m) assa(yarr==1?inf:1,i,j);
else assa(inf,i,j);
}
}
for(int k=0;k<n*m;k++){
for(int i=0;i<n*m;i++){
for(int j=0;j<n*m;j++){
if(D[i][j]>D[i][k]+D[k][j]){
D[i][j]=D[i][k]+D[k][j];
}
}
}
}
/*
for(int i=0;i<n*m;i++){
printf("\n--%d--\n",i);
for(int j=0;j<n*m;j++){
if(!(j%m)) puts("");
printf("%d ",D[i][j]);
}
}
*/
int maxx=0,mi,mj;
for(int i=0;i<n*m;i++){
for(int j=0;j<n*m;j++){
if(D[i][j]>maxx) {maxx=D[i][j];mi=i;mj=j;}
/*
if(D[i][j]>=inf){
printf("NO\n");
return 0;
}*/
}
}
printf("%d %d %d\n",mi,mj,maxx);
printf("YES\n");
return 0;
}
| 19.686869
| 54
| 0.391483
|
SnowOnion
|
6859e8df87dd1f2873927e4b1146d37b4bf06da7
| 13,408
|
cpp
|
C++
|
src/Game.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 11
|
2015-09-30T12:14:59.000Z
|
2022-03-22T04:04:51.000Z
|
src/Game.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 2
|
2015-09-30T16:00:18.000Z
|
2016-12-29T10:51:14.000Z
|
src/Game.cpp
|
howprice/sdl2-tetris
|
8272994293c84b42450ef68bc92c73587f2429cd
|
[
"BSD-3-Clause"
] | 2
|
2021-12-23T04:20:12.000Z
|
2022-03-22T04:09:57.000Z
|
//--------------------------------------------------------------------------------------------------
/**
\file Game.cpp
**/
//--------------------------------------------------------------------------------------------------
#include "Game.h"
#include "Debug.h"
#include "Renderer.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static const unsigned int s_kFieldWidth = 10;
static const unsigned int s_kFieldHeight = 20;
//static const unsigned int s_kNumHiddenRows = 2; // TODO: Use this region to spawn tetrominoes out of sight (centred)
static const unsigned int s_initialFramesPerFallStep = 48;
static const int s_deltaFramesPerFallStepPerLevel = 2;
//--------------------------------------------------------------------------------------------------
// From Super Rotation System standard http://tetris.wikia.com/wiki/SRS
static const Tetromino s_tetrominos[kNumTetrominoTypes] =
{
// I
{
0, 1, 1, 1, 2, 1, 3, 1,
2, 0, 2, 1, 2, 2, 2, 3,
0, 2, 1, 2, 2, 2, 3, 2,
1, 0, 1, 1, 1, 2, 1, 3,
0x00ffffff,
},
// J
{
0, 0, 0, 1, 1, 1, 2, 1,
1, 0, 2, 0, 1, 1, 1, 2,
0, 1, 1, 1, 2, 1, 2, 2,
1, 0, 1, 1, 0, 2, 1, 2,
0x0000ffff,
},
// L
{
2, 0, 0, 1, 1, 1, 2, 1,
1, 0, 1, 1, 1, 2, 2, 2,
0, 1, 1, 1, 2, 1, 0, 2,
0, 0, 1, 0, 1, 1, 1, 2,
0xffaa00ff,
},
// O
{
1, 0, 2, 0, 1, 1, 2, 1,
1, 0, 2, 0, 1, 1, 2, 1,
1, 0, 2, 0, 1, 1, 2, 1,
1, 0, 2, 0, 1, 1, 2, 1,
0xffff00ff
},
// S
{
1, 0, 2, 0, 0, 1, 1, 1,
1, 0, 1, 1, 2, 1, 2, 2,
1, 1, 2, 1, 0, 2, 1, 2,
0, 0, 0, 1, 1, 1, 1, 2,
0x00ff00ff,
},
// T
{
1, 0, 0, 1, 1, 1, 2, 1,
1, 0, 1, 1, 2, 1, 1, 2,
0, 1, 1, 1, 2, 1, 1, 2,
1, 0, 0, 1, 1, 1, 1, 2,
0x9900ffff,
},
// Z
{
0, 0, 1, 0, 1, 1, 2, 1,
2, 0, 1, 1, 2, 1, 1, 2,
0, 1, 1, 1, 1, 2, 2, 2,
1, 0, 0, 1, 1, 1, 0, 2,
0xff0000ff,
}
};
//--------------------------------------------------------------------------------------------------
static bool IsOverlap( const TetrominoInstance& tetronimoInstance, const Field& field )
{
const Tetromino& tetronimo = s_tetrominos[tetronimoInstance.m_tetrominoType];
const Tetromino::BlockCoords& blockCoords = tetronimo.blockCoord[ tetronimoInstance.m_rotation ];
for( unsigned int i = 0; i < Tetromino::kNumBlocks; ++ i )
{
const int x = tetronimoInstance.m_pos.x + blockCoords[i].x;
const int y = tetronimoInstance.m_pos.y + blockCoords[i].y;
// Count going outside the field as an overlap
if( x < 0 || x >= (int)field.width || y < 0 || y >= (int)field.height )
return true;
if( field.staticBlocks[x + y * field.width] != -1 )
return true;
}
return false;
}
static void SetBlock( Field& field, unsigned int ix, unsigned int iy, unsigned int val )
{
HP_ASSERT( ix < field.width );
HP_ASSERT( iy < field.height );
field.staticBlocks[iy * field.width + ix] = val;
}
//--------------------------------------------------------------------------------------------------
Game::Game()
: m_deltaTimeSeconds( 0.0f )
, m_framesUntilFall( s_initialFramesPerFallStep )
, m_framesPerFallStep( s_initialFramesPerFallStep )
, m_numUserDropsForThisTetronimo( 0 )
, m_numLinesCleared( 0 )
, m_level( 0 )
, m_score( 0 )
, m_hiScore( 0 )
, m_gameState( kGameState_TitleScreen )
{
m_field.staticBlocks = nullptr;
}
Game::~Game()
{
}
bool Game::Init()
{
return true;
}
void Game::Shutdown()
{
delete [] m_field.staticBlocks;
m_field.staticBlocks = nullptr;
}
void Game::Reset()
{
}
// return true if there was room to spawn
bool Game::SpawnTetronimo()
{
m_activeTetromino.m_tetrominoType = (TetrominoType)( rand() % kNumTetrominoTypes );
m_activeTetromino.m_rotation = 0;
m_activeTetromino.m_pos.x = (m_field.width - 4) / 2; // tetronimo block width approx = 4
m_activeTetromino.m_pos.y = 0;
if( IsOverlap( m_activeTetromino, m_field ) )
{
return false;
}
m_framesUntilFall = s_initialFramesPerFallStep;
m_numUserDropsForThisTetronimo = 0;
return true;
}
void Game::Update( const GameInput& gameInput, float deltaTimeSeconds )
{
m_deltaTimeSeconds = deltaTimeSeconds;
switch( m_gameState )
{
case kGameState_TitleScreen:
if( gameInput.bStart )
{
InitPlaying();
m_gameState = kGameState_Playing;
}
break;
case kGameState_Playing:
UpdatePlaying( gameInput );
break;
case kGameState_GameOver:
if( gameInput.bStart )
{
m_gameState = kGameState_TitleScreen;
}
break;
default:
HP_FATAL_ERROR("Unhandled case");
}
}
void Game::InitPlaying()
{
m_field.width = s_kFieldWidth;
m_field.height = s_kFieldHeight;
delete [] m_field.staticBlocks;
m_field.staticBlocks = new int[m_field.width * m_field.height];
for( unsigned int iy = 0; iy < m_field.height; ++iy )
{
for( unsigned int ix = 0; ix < m_field.width; ++ix )
{
m_field.staticBlocks[iy * m_field.width + ix] = -1;
}
}
srand( (unsigned int)time( NULL ) );
SpawnTetronimo();
m_numLinesCleared = 0;
m_level = 0;
m_framesPerFallStep = s_initialFramesPerFallStep;
m_score = 0;
}
void Game::UpdatePlaying( const GameInput& gameInput )
{
#ifdef _DEBUG
if( gameInput.bDebugChangeTetromino )
{
m_activeTetromino.m_tetrominoType = (TetrominoType)( ( (unsigned int)m_activeTetromino.m_tetrominoType + 1 ) % (unsigned int)kNumTetrominoTypes );
}
if( gameInput.bDebugMoveLeft )
{
--m_activeTetromino.m_pos.x;
}
if( gameInput.bDebugMoveRight )
{
++m_activeTetromino.m_pos.x;
}
if( gameInput.bDebugMoveUp )
{
--m_activeTetromino.m_pos.y;
}
if( gameInput.bDebugMoveDown )
{
++m_activeTetromino.m_pos.y;
}
#endif
// move horizontally
if( gameInput.bMoveLeft )
{
// try move
TetrominoInstance testInstance = m_activeTetromino;
--testInstance.m_pos.x;
if( !IsOverlap(testInstance, m_field) )
m_activeTetromino.m_pos.x = testInstance.m_pos.x;
}
if( gameInput.bMoveRight )
{
// try move
TetrominoInstance testInstance = m_activeTetromino;
++testInstance.m_pos.x;
if( !IsOverlap( testInstance, m_field ) )
m_activeTetromino.m_pos.x = testInstance.m_pos.x;
}
// rotate
if( gameInput.bRotateClockwise )
{
TetrominoInstance testInstance = m_activeTetromino;
if( testInstance.m_rotation == 0 )
{
testInstance.m_rotation = 3;
}
else
{
--testInstance.m_rotation;
}
// check for overlaps
if( IsOverlap( testInstance, m_field ) )
{
// Simple wall kick, try 1 to the left and 1 to the right
// TODO: Need special case for the stick, which may need to be bumped by +/-2
testInstance.m_pos.x = m_activeTetromino.m_pos.x - 1;
if( !IsOverlap( testInstance, m_field ) )
{
m_activeTetromino = testInstance;
}
else
{
testInstance.m_pos.x = m_activeTetromino.m_pos.x + 1;
if( !IsOverlap( testInstance, m_field ) )
{
m_activeTetromino = testInstance;
}
}
}
else
{
// no overlap
m_activeTetromino = testInstance;
}
}
if( gameInput.bRotateAnticlockwise )
{
m_activeTetromino.m_rotation = ( m_activeTetromino.m_rotation + 1 ) % Tetromino::kNumRotations;
}
// fall
m_framesUntilFall -= 1;
if( m_framesUntilFall <= 0 )
{
m_framesUntilFall = m_framesPerFallStep;
// try move
TetrominoInstance testInstance = m_activeTetromino;
testInstance.m_pos.y += 1;
if( IsOverlap(testInstance, m_field) )
{
AddTetronimoToField( m_field, m_activeTetromino );
if( !SpawnTetronimo() )
m_gameState = kGameState_GameOver;
}
else
{
m_activeTetromino.m_pos.y = testInstance.m_pos.y;
}
}
// soft drop
if( gameInput.bSoftDrop )
{
// try move
TetrominoInstance testInstance = m_activeTetromino;
++testInstance.m_pos.y;
if( !IsOverlap( testInstance, m_field ) )
{
m_activeTetromino.m_pos.y = testInstance.m_pos.y;
++m_numUserDropsForThisTetronimo;
}
}
// hard drop
if( gameInput.bHardDrop )
{
TetrominoInstance testInstance = m_activeTetromino;
while( !IsOverlap( testInstance, m_field ) )
{
++testInstance.m_pos.y;
++m_numUserDropsForThisTetronimo;
}
--testInstance.m_pos.y; // back up one
--m_numUserDropsForThisTetronimo;
AddTetronimoToField( m_field, testInstance );
if( !SpawnTetronimo() )
m_gameState = kGameState_GameOver;
}
}
void Game::AddTetronimoToField( const Field& field, const TetrominoInstance& tetronimoInstance )
{
const Tetromino& tetronimo = s_tetrominos[tetronimoInstance.m_tetrominoType];
const Tetromino::BlockCoords& blockCoords = tetronimo.blockCoord[tetronimoInstance.m_rotation];
for( unsigned int i = 0; i < Tetromino::kNumBlocks; ++i )
{
const int x = tetronimoInstance.m_pos.x + blockCoords[i].x;
const int y = tetronimoInstance.m_pos.y + blockCoords[i].y;
// Count going outside the field as an overlap
HP_ASSERT( (x >= 0) && (x < (int)field.width) && (y >= 0) && (y < (int)field.height) )
field.staticBlocks[x + y * field.width] = (unsigned int)tetronimoInstance.m_tetrominoType;
}
// clear any full rows
unsigned int numLinesCleared = 0;
for( unsigned int y = 0; y < field.height; ++y )
{
bool bRowFull = true;
for( unsigned int x = 0; x < field.width; ++x )
{
if( field.staticBlocks[x + y * field.width] == -1 )
{
bRowFull = false;
break;
}
}
if( bRowFull )
{
++numLinesCleared;
// traverse backward back up to the top copying down the data
for( unsigned int yy = y; yy > 0; --yy )
{
for( unsigned int x = 0; x < field.width; ++x )
{
field.staticBlocks[x + yy * field.width] = field.staticBlocks[x + ( yy - 1 ) * field.width];
}
}
}
}
unsigned int previousLevel = m_numLinesCleared / 10;
m_numLinesCleared += numLinesCleared;
m_level = m_numLinesCleared / 10;
if( m_level != previousLevel )
{
// update speed
m_framesPerFallStep -= s_deltaFramesPerFallStepPerLevel;
if( m_framesPerFallStep < 1 )
{
m_framesPerFallStep = 1;
}
}
// score
if( numLinesCleared > 0 )
{
unsigned int multiplier = 0;
switch( numLinesCleared )
{
case 1:
multiplier = 40;
break;
case 2:
multiplier = 100;
break;
case 3:
multiplier = 300;
break;
case 4:
multiplier = 1200;
}
unsigned int score = multiplier * ( previousLevel + 1 );
score += m_numUserDropsForThisTetronimo;
m_score += score;
if( m_score > m_hiScore )
m_hiScore = m_score;
}
}
void Game::Draw( Renderer& renderer )
{
switch( m_gameState )
{
case kGameState_TitleScreen:
// TODO: GetTextRect
renderer.DrawText( "Press space to start", renderer.GetLogicalWidth()/2 - 100, renderer.GetLogicalHeight()/2, 0xffffffff );
break;
case kGameState_Playing:
DrawPlaying( renderer );
break;
case kGameState_GameOver:
DrawPlaying( renderer );
renderer.DrawText( "GAME OVER", renderer.GetLogicalWidth() / 2 - 100, renderer.GetLogicalHeight() / 2, 0xffffffff );
break;
default:
HP_FATAL_ERROR("Unhandled case");
}
//#ifdef _DEBUG
float fps = 1.0f / m_deltaTimeSeconds;
char text[128];
snprintf( text, sizeof(text), "FPS: %.1f", fps );
renderer.DrawText( text, 0, 0, 0x8080ffff );
//#endif
}
void Game::DrawPlaying( Renderer& renderer )
{
static unsigned int blockSizePixels = 32;
// Draw field
unsigned int fieldWidthPixels = m_field.width * blockSizePixels;
unsigned int fieldHeightPixels = m_field.height * blockSizePixels;
unsigned int fieldOffsetPixelsX = 0;
if( renderer.GetLogicalWidth() > fieldWidthPixels )
{
fieldOffsetPixelsX = ( renderer.GetLogicalWidth() - fieldWidthPixels ) / 2;
}
unsigned int fieldOffsetPixelsY = 0;
if( renderer.GetLogicalHeight() > fieldHeightPixels )
{
fieldOffsetPixelsY = ( renderer.GetLogicalHeight() - fieldHeightPixels ) / 2;
}
for( unsigned int iy = 0; iy < m_field.height; ++iy )
{
const unsigned int y = fieldOffsetPixelsY + iy * blockSizePixels;
for( unsigned int ix = 0; ix < m_field.width; ++ix )
{
const unsigned int x = fieldOffsetPixelsX + ix * blockSizePixels;
const int blockState = m_field.staticBlocks[iy * m_field.width + ix];
unsigned int blockRgba = 0x202020ff;
if( blockState != -1 )
{
HP_ASSERT( blockState < kNumTetrominoTypes );
blockRgba = s_tetrominos[blockState].rgba;
}
renderer.DrawSolidRect( x, y, blockSizePixels, blockSizePixels, blockRgba );
renderer.DrawRect( x, y, blockSizePixels, blockSizePixels, 0x404040ff );
}
}
// draw active tetromino
for( unsigned int i = 0; i < 4; ++i )
{
const Tetromino& tetromino = s_tetrominos[m_activeTetromino.m_tetrominoType];
const Tetromino::BlockCoords& blockCoords = tetromino.blockCoord[m_activeTetromino.m_rotation];
unsigned int tetrominoRgba = tetromino.rgba;
const unsigned int x = fieldOffsetPixelsX + ( m_activeTetromino.m_pos.x + blockCoords[i].x ) * blockSizePixels;
const unsigned int y = fieldOffsetPixelsY + ( m_activeTetromino.m_pos.y + blockCoords[i].y ) * blockSizePixels;
renderer.DrawSolidRect( x, y, blockSizePixels, blockSizePixels, tetrominoRgba );
}
char text[128];
snprintf( text, sizeof(text), "Lines: %u", m_numLinesCleared );
renderer.DrawText( text, 0, 100, 0xffffffff );
snprintf( text, sizeof(text), "Level: %u", m_level );
renderer.DrawText( text, 0, 140, 0xffffffff );
snprintf( text, sizeof(text), "Score: %u", m_score );
renderer.DrawText( text, 0, 180, 0xffffffff );
snprintf( text, sizeof(text), "High score: %u", m_hiScore );
renderer.DrawText( text, 0, 220, 0xffffffff );
#ifdef _DEBUG
snprintf( text, sizeof(text), "Frames per fall: %u", m_framesPerFallStep );
renderer.DrawText( text, 0, 400, 0x404040ff );
#endif
}
| 24.647059
| 148
| 0.648568
|
howprice
|
685c4977bbdb94cf8d969e524331334a16c37764
| 1,362
|
hpp
|
C++
|
_thirdparty/include/boost/process/detail/posix/search_path.hpp
|
joerghall/sourcesfs
|
29ed9675b18f16d869116ed5e5d5343241aa5335
|
[
"MIT"
] | 1
|
2017-07-27T19:32:29.000Z
|
2017-07-27T19:32:29.000Z
|
_thirdparty/include/boost/process/detail/posix/search_path.hpp
|
joerghall/sourcesfs
|
29ed9675b18f16d869116ed5e5d5343241aa5335
|
[
"MIT"
] | null | null | null |
_thirdparty/include/boost/process/detail/posix/search_path.hpp
|
joerghall/sourcesfs
|
29ed9675b18f16d869116ed5e5d5343241aa5335
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// 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 BOOST_PROCESS_POSIX_SEARCH_PATH_HPP
#define BOOST_PROCESS_POSIX_SEARCH_PATH_HPP
#include <boost/process/detail/config.hpp>
#include <boost/filesystem.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <stdexcept>
#include <stdlib.h>
#include <unistd.h>
namespace boost { namespace process { namespace detail { namespace posix {
inline boost::filesystem::path search_path(
const boost::filesystem::path &filename,
const std::string &path = ::getenv("PATH"))
{
std::string result;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(":");
tokenizer tok(path, sep);
for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it)
{
boost::filesystem::path p = *it;
p /= filename;
if (!::access(p.c_str(), X_OK))
{
result = p.string();
break;
}
}
return result;
}
}}}}
#endif
| 28.978723
| 79
| 0.671072
|
joerghall
|
685fc3c63da7cf6de89fb2f6fa9b3c99474a87d5
| 1,512
|
hpp
|
C++
|
include/lol/def/LolFeaturedModesQueue.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 1
|
2020-07-22T11:14:55.000Z
|
2020-07-22T11:14:55.000Z
|
include/lol/def/LolFeaturedModesQueue.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | null | null | null |
include/lol/def/LolFeaturedModesQueue.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 4
|
2018-12-01T22:48:21.000Z
|
2020-07-22T11:14:56.000Z
|
#pragma once
#include "../base_def.hpp"
#include "LolFeaturedModesQueueGameCategory.hpp"
#include "LolFeaturedModesQueueAvailability.hpp"
namespace lol {
struct LolFeaturedModesQueue {
int32_t id;
int32_t mapId;
std::string name;
std::string gameMode;
std::string gameMutator;
LolFeaturedModesQueueGameCategory category;
uint64_t lastToggledOffTime;
uint64_t lastToggledOnTime;
LolFeaturedModesQueueAvailability queueAvailability;
};
inline void to_json(json& j, const LolFeaturedModesQueue& v) {
j["id"] = v.id;
j["mapId"] = v.mapId;
j["name"] = v.name;
j["gameMode"] = v.gameMode;
j["gameMutator"] = v.gameMutator;
j["category"] = v.category;
j["lastToggledOffTime"] = v.lastToggledOffTime;
j["lastToggledOnTime"] = v.lastToggledOnTime;
j["queueAvailability"] = v.queueAvailability;
}
inline void from_json(const json& j, LolFeaturedModesQueue& v) {
v.id = j.at("id").get<int32_t>();
v.mapId = j.at("mapId").get<int32_t>();
v.name = j.at("name").get<std::string>();
v.gameMode = j.at("gameMode").get<std::string>();
v.gameMutator = j.at("gameMutator").get<std::string>();
v.category = j.at("category").get<LolFeaturedModesQueueGameCategory>();
v.lastToggledOffTime = j.at("lastToggledOffTime").get<uint64_t>();
v.lastToggledOnTime = j.at("lastToggledOnTime").get<uint64_t>();
v.queueAvailability = j.at("queueAvailability").get<LolFeaturedModesQueueAvailability>();
}
}
| 38.769231
| 94
| 0.681217
|
Maufeat
|
6868fd3637db09a89d57b5b02343391b87783b5c
| 2,159
|
cpp
|
C++
|
runtime/gmm_helper/gmm_types_converter.cpp
|
Unihedro/compute-runtime
|
cc46cdf46cb37eb7801918cd03c7fd3e06fd4068
|
[
"MIT"
] | null | null | null |
runtime/gmm_helper/gmm_types_converter.cpp
|
Unihedro/compute-runtime
|
cc46cdf46cb37eb7801918cd03c7fd3e06fd4068
|
[
"MIT"
] | null | null | null |
runtime/gmm_helper/gmm_types_converter.cpp
|
Unihedro/compute-runtime
|
cc46cdf46cb37eb7801918cd03c7fd3e06fd4068
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "runtime/gmm_helper/gmm_types_converter.h"
#include "core/memory_manager/graphics_allocation.h"
#include "runtime/helpers/get_info.h"
#include "runtime/helpers/surface_formats.h"
#include "GL/gl.h"
#include "GL/glext.h"
using namespace NEO;
void GmmTypesConverter::queryImgFromBufferParams(ImageInfo &imgInfo, GraphicsAllocation *gfxAlloc) {
// 1D or 2D from buffer
if (imgInfo.imgDesc->image_row_pitch > 0) {
imgInfo.rowPitch = imgInfo.imgDesc->image_row_pitch;
} else {
imgInfo.rowPitch = getValidParam(imgInfo.imgDesc->image_width) * imgInfo.surfaceFormat->ImageElementSizeInBytes;
}
imgInfo.slicePitch = imgInfo.rowPitch * getValidParam(imgInfo.imgDesc->image_height);
imgInfo.size = gfxAlloc->getUnderlyingBufferSize();
imgInfo.qPitch = 0;
}
uint32_t GmmTypesConverter::getRenderMultisamplesCount(uint32_t numSamples) {
if (numSamples == 2) {
return 1;
} else if (numSamples == 4) {
return 2;
} else if (numSamples == 8) {
return 3;
} else if (numSamples == 16) {
return 4;
}
return 0;
}
GMM_YUV_PLANE GmmTypesConverter::convertPlane(OCLPlane oclPlane) {
if (oclPlane == OCLPlane::PLANE_Y) {
return GMM_PLANE_Y;
} else if (oclPlane == OCLPlane::PLANE_U || oclPlane == OCLPlane::PLANE_UV) {
return GMM_PLANE_U;
} else if (oclPlane == OCLPlane::PLANE_V) {
return GMM_PLANE_V;
}
return GMM_NO_PLANE;
}
GMM_CUBE_FACE_ENUM GmmTypesConverter::getCubeFaceIndex(uint32_t target) {
switch (target) {
case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
return __GMM_CUBE_FACE_NEG_X;
case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
return __GMM_CUBE_FACE_POS_X;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
return __GMM_CUBE_FACE_NEG_Y;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
return __GMM_CUBE_FACE_POS_Y;
case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
return __GMM_CUBE_FACE_NEG_Z;
case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
return __GMM_CUBE_FACE_POS_Z;
}
return __GMM_NO_CUBE_MAP;
}
| 29.575342
| 120
| 0.708198
|
Unihedro
|
686ccbd7138830920135b815f363caccf1427ebe
| 3,451
|
hpp
|
C++
|
shared/include/small_function.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 13
|
2019-03-25T09:40:12.000Z
|
2022-03-13T16:12:39.000Z
|
shared/include/small_function.hpp
|
SleepKiller/shaderpatch
|
4bda848df0273993c96f1d20a2cf79161088a77d
|
[
"MIT"
] | 110
|
2018-10-16T09:05:43.000Z
|
2022-03-16T23:32:28.000Z
|
shared/include/small_function.hpp
|
SleepKiller/swbfii-shaderpatch
|
b49ce3349d4dd09b19237ff4766652166ba1ffd4
|
[
"MIT"
] | 1
|
2020-02-06T20:32:50.000Z
|
2020-02-06T20:32:50.000Z
|
#pragma once
#include <array>
#include <cstddef>
#include <functional>
#include <type_traits>
#include <utility>
namespace sp {
template<typename>
class Small_function;
template<typename Return, typename... Args>
class Small_function<Return(Args...) noexcept> {
public:
Small_function() = default;
Small_function(Small_function&& from) noexcept : Small_function{}
{
swap(from);
}
Small_function& operator=(Small_function&& from) noexcept
{
swap(from);
return *this;
}
template<typename Invocable>
Small_function(Invocable&& invocable) noexcept
{
static_assert(std::is_nothrow_invocable_r_v<Return, Invocable, Args...>,
"invocable's arguments or return type do not match");
create(std::forward<Invocable>(invocable));
}
template<typename Invocable>
Small_function& operator=(Invocable&& invocable) noexcept
{
static_assert(std::is_nothrow_invocable_r_v<Return, Invocable, Args...>,
"invocable's arguments or return type do not match");
cleanup();
create(std::forward<Invocable>(invocable));
return *this;
}
Small_function& operator=(std::nullptr_t) noexcept
{
cleanup();
return *this;
}
~Small_function()
{
cleanup();
}
Small_function(const Small_function&) noexcept = delete;
Small_function& operator=(const Small_function&) noexcept = delete;
auto operator()(Args... args) const noexcept -> Return
{
return _invoke(_invocable_storage.data(), std::forward<Args>(args)...);
}
explicit operator bool() const noexcept
{
return _invoke != nullptr;
}
void swap(Small_function& other) noexcept
{
using std::swap;
swap(this->_invoke, other._invoke);
swap(this->_destroy, other._destroy);
swap(this->_invocable_storage, other._invocable_storage);
}
private:
template<typename Invocable>
void create(Invocable&& invocable) noexcept
{
using Invocable_type = std::remove_reference_t<std::remove_cv_t<Invocable>>;
static_assert(sizeof(Invocable_type) <= sizeof(_invocable_storage),
"Invocable_type is too large!");
static_assert(alignof(Invocable_type) <= alignof(std::intptr_t),
"Invocable_type will be misaligned!");
new (_invocable_storage.data())
Invocable_type{std::forward<Invocable>(invocable)};
_invoke = [](const void* invocable_storage, Args... args) noexcept
{
const auto& invocable =
*static_cast<const Invocable_type*>(invocable_storage);
return std::invoke(invocable, std::forward<Args>(args)...);
};
_destroy = [](void* invocable_storage) noexcept
{
[[maybe_unused]] auto& invocable =
*static_cast<Invocable_type*>(invocable_storage);
if constexpr (!std::is_trivially_destructible_v<Invocable_type>) {
invocable.~Invocable_type();
}
};
}
void cleanup() noexcept
{
if (_invoke) _destroy(_invocable_storage.data());
_invoke = nullptr;
_destroy = nullptr;
}
using Invoke_fn = std::add_pointer_t<Return(const void*, Args...) noexcept>;
using Destory_fn = std::add_pointer_t<void(void*) noexcept>;
Invoke_fn _invoke = nullptr;
Destory_fn _destroy = nullptr;
alignas(std::intptr_t) std::array<std::byte, 32> _invocable_storage;
};
}
| 25.189781
| 82
| 0.651985
|
SleepKiller
|
686dc59f38054c90246c2f35f5cf440cde121bab
| 5,788
|
cc
|
C++
|
Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc
|
PKUfudawei/cmssw
|
8fbb5ce74398269c8a32956d7c7943766770c093
|
[
"Apache-2.0"
] | 2
|
2020-10-26T18:40:32.000Z
|
2021-04-10T16:33:25.000Z
|
Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc
|
gartung/cmssw
|
3072dde3ce94dcd1791d778988198a44cde02162
|
[
"Apache-2.0"
] | 30
|
2015-11-04T11:42:27.000Z
|
2021-12-01T07:56:34.000Z
|
Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc
|
gartung/cmssw
|
3072dde3ce94dcd1791d778988198a44cde02162
|
[
"Apache-2.0"
] | 8
|
2016-03-25T07:17:43.000Z
|
2021-07-08T17:11:21.000Z
|
// -*- C++ -*-
//
// Package: TestAccessGeom
// Class: TestAccessGeom
//
/**\class TestAccessGeom Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc
Description: <one line class summary>
Implementation:
Module accessing tracking geometries for tracker, DT and CSC
*/
//
// Original Author: Gero Flucke
// Created: Sat Feb 16 20:56:04 CET 2008
// $Id: TestAccessGeom.cc,v 1.2 2008/06/26 10:05:09 flucke Exp $
//
//
// system include files
#include <memory>
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "Geometry/DTGeometry/interface/DTGeometry.h"
#include "Geometry/CSCGeometry/interface/CSCGeometry.h"
#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include <vector>
#include <string>
#include "TString.h"
//
// class declaration
//
class TestAccessGeom : public edm::one::EDAnalyzer<> {
public:
explicit TestAccessGeom(const edm::ParameterSet&);
~TestAccessGeom() = default;
private:
virtual void analyze(const edm::Event&, const edm::EventSetup&);
// ----------member data ---------------------------
const std::vector<std::string> tkGeomLabels_;
const std::vector<std::string> dtGeomLabels_;
const std::vector<std::string> cscGeomLabels_;
std::vector<edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord>> tkGeoTokens_;
std::vector<edm::ESGetToken<DTGeometry, MuonGeometryRecord>> dtGeoTokens_;
std::vector<edm::ESGetToken<CSCGeometry, MuonGeometryRecord>> cscGeoTokens_;
};
//
// constructors and destructor
//
TestAccessGeom::TestAccessGeom(const edm::ParameterSet& iConfig)
: tkGeomLabels_(iConfig.getParameter<std::vector<std::string>>("TrackerGeomLabels")),
dtGeomLabels_(iConfig.getParameter<std::vector<std::string>>("DTGeomLabels")),
cscGeomLabels_(iConfig.getParameter<std::vector<std::string>>("CSCGeomLabels")) {
//now do what ever initialization is needed
for (std::vector<std::string>::const_iterator iL = tkGeomLabels_.begin(), iE = tkGeomLabels_.end(); iL != iE; ++iL) {
auto index = std::distance(tkGeomLabels_.begin(), iL);
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
tkGeoTokens_[index] = esConsumes(edm::ESInputTag("", label.Data()));
}
for (std::vector<std::string>::const_iterator iL = dtGeomLabels_.begin(), iE = dtGeomLabels_.end(); iL != iE; ++iL) {
auto index = std::distance(dtGeomLabels_.begin(), iL);
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
dtGeoTokens_[index] = esConsumes(edm::ESInputTag("", label.Data()));
}
for (std::vector<std::string>::const_iterator iL = cscGeomLabels_.begin(), iE = cscGeomLabels_.end(); iL != iE;
++iL) {
auto index = std::distance(cscGeomLabels_.begin(), iL);
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
cscGeoTokens_[index] = esConsumes(edm::ESInputTag("", label.Data()));
}
}
//
// member functions
//
// ------------ method called to for each event ------------
void TestAccessGeom::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
using std::string;
using std::vector;
edm::LogInfo("Test") << "@SUB=analyze"
<< "Try to access " << tkGeomLabels_.size() << " Tracker-, " << dtGeomLabels_.size()
<< " DT- and " << cscGeomLabels_.size() << " CSC-geometries.";
for (vector<string>::const_iterator iL = tkGeomLabels_.begin(), iE = tkGeomLabels_.end(); iL != iE; ++iL) {
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
edm::LogInfo("Test") << "Try access to tracker geometry with label '" << label << "'.";
auto idx = std::distance(tkGeomLabels_.begin(), iL);
//*iL << "'.";
edm::ESHandle<TrackerGeometry> tkGeomHandle = iSetup.getHandle(tkGeoTokens_[idx]);
edm::LogInfo("Test") << "TrackerGeometry pointer: " << tkGeomHandle.product();
}
for (vector<string>::const_iterator iL = dtGeomLabels_.begin(), iE = dtGeomLabels_.end(); iL != iE; ++iL) {
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
edm::LogInfo("Test") << "Try access to DT geometry with label '" << label << "'.";
auto idx = std::distance(dtGeomLabels_.begin(), iL);
//*iL << "'.";
edm::ESHandle<DTGeometry> dtGeomHandle = iSetup.getHandle(dtGeoTokens_[idx]);
edm::LogInfo("Test") << "DTGeometry pointer: " << dtGeomHandle.product();
}
for (vector<string>::const_iterator iL = cscGeomLabels_.begin(), iE = cscGeomLabels_.end(); iL != iE; ++iL) {
TString label(iL->c_str());
label.ReplaceAll(" ", ""); // fix for buggy framework
edm::LogInfo("Test") << "Try access to CSC geometry with label '" << label << "'.";
auto idx = std::distance(cscGeomLabels_.begin(), iL);
//*iL << "'.";
edm::ESHandle<CSCGeometry> cscGeomHandle = iSetup.getHandle(cscGeoTokens_[idx]);
edm::LogInfo("Test") << "CSCGeometry pointer: " << cscGeomHandle.product();
}
edm::LogInfo("Test") << "@SUB=analyze"
<< "Succesfully accessed " << tkGeomLabels_.size() << " Tracker-, " << dtGeomLabels_.size()
<< " DT- and " << cscGeomLabels_.size() << " CSC-geometries.";
}
//define this as a plug-in
DEFINE_FWK_MODULE(TestAccessGeom);
| 38.586667
| 119
| 0.666724
|
PKUfudawei
|
686e89928f2180b1131b2a5b1400265bf0917585
| 23,768
|
cpp
|
C++
|
tests/test_arrays.cpp
|
yangyha/ipic3d-klm
|
d91f8f7fe361f38ab00a3169e4a583e5713e1a9a
|
[
"Apache-2.0"
] | null | null | null |
tests/test_arrays.cpp
|
yangyha/ipic3d-klm
|
d91f8f7fe361f38ab00a3169e4a583e5713e1a9a
|
[
"Apache-2.0"
] | 1
|
2021-06-22T09:14:29.000Z
|
2021-06-22T13:18:14.000Z
|
tests/test_arrays.cpp
|
yangyha/ipic3d-klm
|
d91f8f7fe361f38ab00a3169e4a583e5713e1a9a
|
[
"Apache-2.0"
] | 4
|
2021-05-28T08:59:49.000Z
|
2021-07-08T07:55:48.000Z
|
/* iPIC3D was originally developed by Stefano Markidis and Giovanni Lapenta.
* This release was contributed by Alec Johnson and Ivy Bo Peng.
* Publications that use results from iPIC3D need to properly cite
* 'S. Markidis, G. Lapenta, and Rizwan-uddin. "Multi-scale simulations of
* plasma with iPIC3D." Mathematics and Computers in Simulation 80.7 (2010): 1509-1519.'
*
* Copyright 2015 KTH Royal Institute of Technology
* 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.
*/
/*
Reger Ferrer
Vicenç Beltran
Alec Johnson
*/
//#define CHAINED_ARRAYS
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include "stopwatch.h"
#include "arrays.h"
#include "Alloc.h"
#include "asserts.h"
#include "debug.h"
using namespace iPic3D;
/**** begin Jorge Amaya's array allocation methods ****/
/*! The allocator for 4D array */
template < class type > type **** newArray4_Amaya(int sz1, int sz2, int sz3, int sz4) {
type ****all_x;
type ***all_y;
type **all_z;
type *all_r;
all_x = new type ***[sz1];
all_y = new type **[sz1 * sz2];
all_z = new type *[sz1 * sz2 * sz3];
all_r = new type[sz1 * sz2 * sz3 * sz4];
type ****result = all_x;
for (int i = 0; i < sz1; i++, all_y += sz2) {
result[i] = all_y;
for (int j = 0; j < sz2; j++, all_z += sz3) {
result[i][j] = all_z;
for (int k = 0; k < sz3; k++, all_r += sz4) {
result[i][j][k] = all_r;
}
}
}
return result;
}
/*! Deallocator for 4D arrays */
template < class type > void delArr4_Amaya(type **** arr, int dummyx, int dummyy, int dummyz) {
delete[]arr[0][0][0];
delete[]arr[0][0];
delete[]arr[0];
delete[]arr;
}
/*! The allocator for 3D array */
template < class type > type *** newArray3_Amaya(int sz1, int sz2, int sz3) {
type ***all_x;
type **all_y;
type *all_z;
all_x = new type **[sz1];
all_y = new type *[sz1 * sz2];
all_z = new type[sz1 * sz2 * sz3];
type ***result = all_x;
for (int i = 0; i < sz1; i++, all_y += sz2) {
result[i] = all_y;
for (int j = 0; j < sz2; j++, all_z += sz3) {
result[i][j] = all_z;
}
}
return result;
}
/*! Deallocator for 3D arrays */
template < class type > void delArr3_Amaya(type *** arr, int dummyx, int dummyy) {
delete[]arr[0][0];
delete[]arr[0];
delete[]arr;
}
/*! The allocator for 2D array */
template < class type > type ** newArr2_Amaya(int sz1, int sz2) {
type **all_x;
type *all_y;
all_x = new type *[sz1];
all_y = new type[sz1 * sz2];
type **result = all_x;
for (int i = 0; i < sz1; i++, all_y += sz2) {
result[i] = all_y;
}
return result;
}
/*! Deallocator for 2D arrays */
template < class type > void delArr2_Amaya(type ** arr, int dummyx) {
delete[]arr[0];
delete[]arr;
}
#define newArr4_Amaya(type,sz1,sz2,sz3,sz4) newArray4_Amaya<type>((sz1),(sz2),(sz3),(sz4))
#define newArr3_Amaya(type,sz1,sz2,sz3) newArray3_Amaya<type>((sz1),(sz2),(sz3))
#define newArr2_Amaya(type,sz1,sz2) newArray2_Amaya<type>((sz1),(sz2))
/**** end Jorge Amaya's array allocation methods ****/
/****** begin (i,j) arrays from Reger Ferrer and Vicenç Beltran ******/
template <class type>
class Rank1
{
const size_t S1;
type * __restrict__ const arr;
public:
Rank1(size_t s1) : S1(s1), arr(AlignedAlloc(type, s1)) {}
//Rank1( const Rank1& other ) : S1( other.S1 ), arr( other.arr ) {}
type& operator()(size_t n1) const
{
ALIGNED(arr);
return arr[n1];
}
size_t dim1() const { return S1; }
~Rank1() { };
};
template <class type>
class Rank2
{
const size_t S1, S2;
type * __restrict__ const arr;
public:
Rank2(size_t s1, size_t s2) : S1(s1), S2(s2), arr(AlignedAlloc(type, s1*s2)) {}
//Rank2( const Rank2& other ) : S1( other.S1 ), S2( other.S2 ), arr( other.arr ) {}
type& operator()(size_t n1, size_t n2) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
ALIGNED(arr);
return arr[n2+S2*n1];
}
type& fetch(size_t n1,size_t n2) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
ALIGNED(arr);
return arr[n2+S2*n1];
}
size_t dim1() const { return S1; }
size_t dim2() const { return S2; }
void free() {
AlignedFree(arr);
}
~Rank2() { };
};
template <class type>
class Rank3
{
const size_t S1, S2, S3;
type * const __restrict__ arr;
public:
Rank3(size_t s1, size_t s2, size_t s3) : S1(s1), S2(s2), S3(s3),
arr(AlignedAlloc(type, s1*s2*s3)) {}
//Rank3( const Rank3& other ) : S1( other.S1 ), S2( other.S2 ), S3( other.S3 ),
//arr( other.arr ) {}
type& operator()(size_t n1, size_t n2, size_t n3) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
check_bounds(n3,S3);
ALIGNED(arr);
return arr[n3+S3*(n2+S2*n1)];
}
type& fetch(size_t n1, size_t n2, size_t n3) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
check_bounds(n3,S3);
ALIGNED(arr);
return arr[n3+S3*(n2+S2*n1)];
}
const type& get(size_t n1, size_t n2, size_t n3) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
check_bounds(n3,S3);
ALIGNED(arr);
return arr[n3+S3*(n2+S2*n1)];
}
~Rank3() { }
size_t dim1() const { return S1; }
size_t dim2() const { return S2; }
size_t dim3() const { return S3; }
void free() {
AlignedFree(arr);
}
};
template <class type>
class Rank4
{
const size_t S1, S2, S3, S4;
type* __restrict__ const arr;
public:
Rank4(size_t s1, size_t s2, size_t s3, size_t s4) : S1(s1), S2(s2), S3(s3), S4(s4),
arr(AlignedAlloc(type, s1*s2*s3*s4)) {}
//Rank4( const Rank4& other ) : S1( other.S1 ), S2( other.S2 ), S3( other.S3 ), S4( other.S4 ),
//arr( other.arr ) {}
type& operator()(size_t n1, size_t n2, size_t n3, size_t n4) const
{
check_bounds(n1,S1);
check_bounds(n2,S2);
check_bounds(n3,S3);
check_bounds(n4,S4);
ALIGNED(arr);
return arr[n4+S4*(n3+S3*(n2+S2*n1))];
}
~Rank4() { }
size_t dim1() const { return S1; }
size_t dim2() const { return S2; }
size_t dim3() const { return S3; }
size_t dim4() const { return S4; }
void free() { AlignedFree(arr); }
};
/******** end (i,j) arrays from Reger Ferrer and Vicenç Beltran ******/
/****** begin [i][j] arrays from Reger Ferrer and Vicenç Beltran ******/
template <class type>
class BracketRank1
{
const size_t S1;
type * __restrict__ const arr;
public:
BracketRank1(size_t s1, void * __restrict__ const storage) : S1(s1),
arr(reinterpret_cast<type * __restrict__ const>(storage)){}
BracketRank1(size_t s1) : S1(s1), arr(new type[s1]){}
type& operator[](size_t i) const
{
return arr[i];
}
};
template <class type>
class BracketRank2
{
const size_t S1, S2;
type * __restrict__ const arr;
public:
void free(){ delete[] arr; }
BracketRank2(size_t s1, size_t s2, void *storage) : S1(s1), S2(s2),
arr(reinterpret_cast<type * __restrict__ const>(storage)){}
BracketRank2(size_t s1, size_t s2) : S1(s1), S2(s2),
arr(new type[s1*s2]) {}
BracketRank1<type> operator[](size_t i) const
{
return BracketRank1<type>(S2, arr + i * S2);
}
type& operator()(size_t n1, size_t n2) const
{
ALIGNED(arr);
return arr[n2+S2*n1];
}
};
/******** end [i][j] arrays from Reger Ferrer and Vicenç Beltran ******/
using namespace std;
template <class type>
void testArr2_diagonal()
{
const int ITERS = 10000;
const size_t dim1 = 64;
const size_t dim2 = 64;
BracketRank2<type> Abra(dim1, dim2);
BracketRank2<type> Bbra(dim1, dim2);
BracketRank2<type> Cbra(dim1, dim2);
Rank2<type> Apar(dim1, dim2);
Rank2<type> Bpar(dim1, dim2);
Rank2<type> Cpar(dim1, dim2);
FixedArray2D<type, dim1, dim2> Afix ;
FixedArray2D<type, dim1, dim2> Bfix ;
FixedArray2D<type, dim1, dim2> Cfix ;
type** Aold = newArr2(type, dim1, dim2);
type** Bold = newArr2(type, dim1, dim2);
type** Cold = newArr2(type, dim1, dim2);
array_ref2<type> Aarr(dim1, dim2);
array_ref2<type> Barr(dim1, dim2);
array_ref2<type> Carr(dim1, dim2);
printf("Initializing data ...\n");
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
Bbra[i][j] = rand();
Cbra[i][j] = rand();
Bpar(i,j) = Bbra[i][j];
Cpar(i,j) = Cbra[i][j];
Bfix.fetch(i,j) = Bbra[i][j];
Cfix.fetch(i,j) = Cbra[i][j];
Bold[i][j] = Bbra[i][j];
Cold[i][j] = Cbra[i][j];
Barr.fetch(i,j) = Bbra[i][j];
Carr.fetch(i,j) = Cbra[i][j];
}
stopwatch(START);
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
Aold[i][j] = Bold[i][j] * Cold[i][j];
}
printf("%d ms = Total time [i][j] chained-pointer array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
//Afix.fetch(i,j) = Bfix.fetch(i,j) * Cfix.fetch(i,j);
Afix[i][j] = Bfix[i][j] * Cfix[i][j];
}
printf("%d ms = Total time [i][j] fixed-dimension array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
Abra[i][j] = Bbra[i][j] * Cbra[i][j];
}
printf("%d ms = Total time [i][j] Vicenc array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
Apar.fetch(i,j) = Bpar.fetch(i,j) * Cpar.fetch(i,j);
//Apar(i,j) = Bpar(i,j) * Cpar(i,j);
}
printf("%d ms = Total time (i,j) Vicenc array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
Aarr[i][j] = Barr[i][j] * Carr[i][j];
}
printf("%d ms = Total time [i][j] access of array_ref2\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
//Aarr(i,j) = Barr(i,j) * Carr(i,j);
Aarr.fetch(i,j) = Barr.fetch(i,j) * Carr.fetch(i,j);
}
printf("%d ms = Total time (i,j) access of array_ref2\n", tv_to_ms(stopwatch(LAP)));
for(size_t i=0; i<dim1; i++)
for(size_t j=i; j<dim2; j++)
{
assert(Afix.fetch(i,j) == Abra[i][j]);
assert(Aold[i][j] == Abra[i][j]);
assert(Aarr.get(i,j) == Abra[i][j]);
}
printf("Verification done!\n");
stopwatch(STOP);
delArr2(Aold,dim1);
delArr2(Bold,dim1);
delArr2(Cold,dim1);
}
template <class type>
void testArr2()
{
const int ITERS = 10000;
const size_t dim1 = 64;
const size_t dim2 = 64;
BracketRank2<type> Abra(dim1, dim2);
BracketRank2<type> Bbra(dim1, dim2);
BracketRank2<type> Cbra(dim1, dim2);
Rank2<type> Apar(dim1, dim2);
Rank2<type> Bpar(dim1, dim2);
Rank2<type> Cpar(dim1, dim2);
FixedArray2D<type, dim1, dim2> Afix ;
FixedArray2D<type, dim1, dim2> Bfix ;
FixedArray2D<type, dim1, dim2> Cfix ;
type** Aold = newArr2(type, dim1, dim2);
type** Bold = newArr2(type, dim1, dim2);
type** Cold = newArr2(type, dim1, dim2);
array_ref2<type> Aarr(dim1, dim2);
array_ref2<type> Barr(dim1, dim2);
array_ref2<type> Carr(dim1, dim2);
printf("Initializing data ...\n");
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Bbra[i][j] = rand();
Cbra[i][j] = rand();
Bpar(i,j) = Bbra[i][j];
Cpar(i,j) = Cbra[i][j];
Bfix.fetch(i,j) = Bbra[i][j];
Cfix.fetch(i,j) = Cbra[i][j];
Bold[i][j] = Bbra[i][j];
Cold[i][j] = Cbra[i][j];
Barr.fetch(i,j) = Bbra[i][j];
Carr.fetch(i,j) = Cbra[i][j];
}
stopwatch(START);
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Aold[i][j] = Bold[i][j] * Cold[i][j];
}
printf("%d ms = Total time [i][j] chained-pointer array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Afix.fetch(i,j) = Bfix.fetch(i,j) * Cfix.fetch(i,j);
}
printf("%d ms = Total time [i][j] fixed-dimension array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Abra[i][j] = Bbra[i][j] * Cbra[i][j];
}
printf("%d ms = Total time [i][j] Vicenc array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Apar(i,j) = Bpar(i,j) * Cpar(i,j);
}
printf("%d ms = Total time (i,j) Vicenc array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Aarr[i][j] = Barr[i][j] * Carr[i][j];
}
printf("%d ms = Total time [i][j] access of array_ref2\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
Aarr.fetch(i,j) = Barr.get(i,j) * Carr.get(i,j);
}
printf("%d ms = Total time (i,j) access of array_ref2\n", tv_to_ms(stopwatch(LAP)));
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
{
assert(Afix.fetch(i,j) == Abra[i][j]);
assert(Aold[i][j] == Abra[i][j]);
assert(Aarr.get(i,j) == Abra[i][j]);
}
printf("Verification done!\n");
stopwatch(STOP);
delArr2(Aold,dim1);
delArr2(Bold,dim1);
delArr2(Cold,dim1);
}
#define testArr3nestedFor(arg1, arg2) \
for(int t=0; t<ITERS; t++) \
for(size_t i=0; i<dim1; i++) \
for(size_t j=0; j<dim2; j++) \
for(size_t k=0; k<dim3; k++) \
{ \
#arg1; \
} \
printf("%d ms = Total time " #arg2 "\n", tv_to_ms(stopwatch(LAP)));
template <class type>
void set_prod3(array_ref3<type> Aarr,const_array_ref3<type> Barr,array_ref3<type> Carr,int ITERS, size_t dim1,size_t dim2,size_t dim3)
{
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
//Aarr[i][j][k] = Barr[i][j][k] * Carr[i][j][k];
Aarr.fetch(i,j,k) = Barr.get(i,j,k) * Carr.get(i,j,k);
}
printf("%d ms = Total time [i][j][k] access of array_ref3\n", tv_to_ms(stopwatch(LAP)));
}
template <class type>
void testArr3()
{
const int ITERS = 100;
const size_t dim1 = 64;
const size_t dim2 = 64;
const size_t dim3 = 64;
Rank3<type> Apar(dim1, dim2, dim3);
Rank3<type> Bpar(dim1, dim2, dim3);
Rank3<type> Cpar(dim1, dim2, dim3);
FixedArray3D<type, dim1, dim2, dim3> Afix ;
FixedArray3D<type, dim1, dim2, dim3> Bfix ;
FixedArray3D<type, dim1, dim2, dim3> Cfix ;
type*** Aold = newArr3(type, dim1, dim2, dim3);
type*** Bold = newArr3(type, dim1, dim2, dim3);
type*** Cold = newArr3(type, dim1, dim2, dim3);
//array3<type> Aarr(dim1, dim2, dim3);
//array3<type> Barr(dim1, dim2, dim3);
//array3<type> Carr(dim1, dim2, dim3);
array_ref3<type> Aarr(dim1, dim2, dim3);
array_ref3<type> Barr(dim1, dim2, dim3);
array_ref3<type> Carr(dim1, dim2, dim3);
printf("Initializing data ...\n");
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
Barr.fetch(i,j,k) = rand();
Carr.fetch(i,j,k) = rand();
Bpar.fetch(i,j,k) = Barr.get(i,j,k);
Cpar.fetch(i,j,k) = Carr.get(i,j,k);
Bfix.fetch(i,j,k) = Barr.get(i,j,k);
Cfix.fetch(i,j,k) = Carr.get(i,j,k);
Bold[i][j][k] = Barr.get(i,j,k);
Cold[i][j][k] = Carr.get(i,j,k);
}
stopwatch(START);
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
Aold[i][j][k] = Bold[i][j][k] * Cold[i][j][k];
}
printf("%d ms = Total time [i][j][k] chained-pointer array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
Afix[i][j][k] = Bfix[i][j][k] * Cfix[i][j][k];
//Afix.arr[i][j][k] = Bfix.arr[i][j][k] * Cfix.arr[i][j][k];
//Afix.fetch(i,j,k) = Bfix.fetch(i,j,k) * Cfix.fetch(i,j,k);
}
printf("%d ms = Total time [i][j][k] fixed-dimension array\n", tv_to_ms(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
Apar.fetch(i,j,k) = Bpar.fetch(i,j,k) * Cpar.fetch(i,j,k);
}
printf("%d ms = Total time (i,j,k) Vicenc array\n", tv_to_ms(stopwatch(LAP)));
set_prod3(Aarr,Barr,Carr,ITERS,dim1,dim2,dim3);
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
Aarr.fetch(i,j,k) = Barr.get(i,j,k) * Carr.get(i,j,k);
}
printf("%d ms = Total time (i,j,k) access of array_ref3\n", tv_to_ms(stopwatch(LAP)));
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
{
assert_eq(Aold[i][j][k], Aarr.get(i,j,k));
assert_eq(Apar.fetch(i,j,k), Aarr.get(i,j,k));
assert_eq(Afix.fetch(i,j,k), Aarr.get(i,j,k));
}
printf("Verification done!\n");
stopwatch(STOP);
// automatic destructor slows array access
// unless compiling with -fno-exceptions
//
Apar.free();
Bpar.free();
Cpar.free();
Aarr.free();
Barr.free();
Carr.free();
}
template <class type>
void testArr4()
{
// For some bizarre reason, if I comment out the code for the
// "fbr" and "fpa" arrays below then icpc on knc2 is somehow
// able to figure out that each iteration does the same thing
// in the case of array_ref4, but not in the case of the chained
// pointer or fixed-dimension arrays. Why not? And why
// does this optimization occur for four-dimensional arrays
// and not for 3- or 2-dimensional arrays? And why is this
// optimization no longer performed if "fbr" and "fpa" stuff
// is included? The times are baffling.
const int ITERS = 1;
const size_t dim1 = 16;
const size_t dim2 = 16;
const size_t dim3 = 16;
const size_t dim4 = 16;
FixedArray4D<type, dim1, dim2, dim3, dim4> Afix;
FixedArray4D<type, dim1, dim2, dim3, dim4> Bfix;
FixedArray4D<type, dim1, dim2, dim3, dim4> Cfix;
type**** Aold = newArr4(type, dim1, dim2, dim3, dim4);
type**** Bold = newArr4(type, dim1, dim2, dim3, dim4);
type**** Cold = newArr4(type, dim1, dim2, dim3, dim4);
//array4<type> Afbr(dim1, dim2, dim3, dim4);
//array4<type> Bfbr(dim1, dim2, dim3, dim4);
//array4<type> Cfbr(dim1, dim2, dim3, dim4);
//array4<type> Afpa(dim1, dim2, dim3, dim4);
//array4<type> Bfpa(dim1, dim2, dim3, dim4);
//array4<type> Cfpa(dim1, dim2, dim3, dim4);
array_ref4<type> Abra(dim1, dim2, dim3, dim4);
array_ref4<type> Bbra(dim1, dim2, dim3, dim4);
array_ref4<type> Cbra(dim1, dim2, dim3, dim4);
array_ref4<type> Apar(dim1, dim2, dim3, dim4);
array_ref4<type> Bpar(dim1, dim2, dim3, dim4);
array_ref4<type> Cpar(dim1, dim2, dim3, dim4);
printf("Initializing data ...\n");
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
Bbra.fetch(i,j,k,l) = rand();
Cbra.fetch(i,j,k,l) = rand();
Bpar.fetch(i,j,k,l) = Bbra.get(i,j,k,l);
Cpar.fetch(i,j,k,l) = Cbra.get(i,j,k,l);
//Bfbr.fetch(i,j,k,l) = Bbra.get(i,j,k,l);
//Cfbr.fetch(i,j,k,l) = Cbra.get(i,j,k,l);
//Bfpa.fetch(i,j,k,l) = Bbra.get(i,j,k,l);
//Cfpa.fetch(i,j,k,l) = Cbra.get(i,j,k,l);
Bfix.fetch(i,j,k,l) = Bbra.get(i,j,k,l);
Cfix.fetch(i,j,k,l) = Cbra.get(i,j,k,l);
Bold[i][j][k][l] = Bbra.get(i,j,k,l);
Cold[i][j][k][l] = Cbra.get(i,j,k,l);
}
stopwatch(START);
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
Aold[i][j][k][l] = Bold[i][j][k][l] * Cold[i][j][k][l];
}
printf("%d us = Total time [i][j][k][l] chained-pointer array\n", tv_to_us(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
Afix[i][j][k][l] = Bfix[i][j][k][l] * Cfix[i][j][k][l];
//Afix.arr[i][j][k][l] = Bfix.arr[i][j][k][l] * Cfix.arr[i][j][k][l];
//Afix.fetch(i,j,k,l) = Bfix.fetch(i,j,k,l) * Cfix.fetch(i,j,k,l);
}
printf("%d us = Total time [i][j][k][l] fixed-dimension array\n", tv_to_us(stopwatch(LAP)));
//for(int t=0; t<ITERS; t++)
//for(size_t i=0; i<dim1; i++)
//for(size_t j=0; j<dim2; j++)
//for(size_t k=0; k<dim3; k++)
//for(size_t l=0; l<dim4; l++)
//{
// Afbr.fetch(i,j,k,l) = Bfbr.get(i,j,k,l) * Cfbr.get(i,j,k,l);
//}
//printf("%d us = Total time (i,j,k,l) access of array4\n", tv_to_us(stopwatch(LAP)));
//for(int t=0; t<ITERS; t++)
//for(size_t i=0; i<dim1; i++)
//for(size_t j=0; j<dim2; j++)
//for(size_t k=0; k<dim3; k++)
//for(size_t l=0; l<dim4; l++)
//{
// Afpa.fetch(i,j,k,l) = Bfpa.get(i,j,k,l) * Cfpa.get(i,j,k,l);
//}
//printf("%d us = Total time (i,j,k,l) access of array4\n", tv_to_us(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
Abra[i][j][k][l] = Bbra[i][j][k][l] * Cbra[i][j][k][l];
}
printf("%d us = Total time [i][j][k][l] access of array_ref4\n", tv_to_us(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
Apar.fetch(i,j,k,l) = Bpar.get(i,j,k,l) * Cpar.get(i,j,k,l);
}
printf("%d us = Total time (i,j,k,l) access of array_ref4\n", tv_to_us(stopwatch(LAP)));
for(int t=0; t<ITERS; t++)
for(size_t i=0; i<dim1; i++)
for(size_t j=0; j<dim2; j++)
for(size_t k=0; k<dim3; k++)
for(size_t l=0; l<dim4; l++)
{
assert_eq(Aold[i][j][k][l], Abra.get(i,j,k,l));
assert_eq(Apar.fetch(i,j,k,l), Abra.get(i,j,k,l));
//assert_eq(Afbr[i][j][k][l], Abra.get(i,j,k,l));
//assert_eq(Afpa.fetch(i,j,k,l), Abra.get(i,j,k,l));
assert_eq(Afix.fetch(i,j,k,l), Abra.get(i,j,k,l));
}
printf("Verification done!\n");
stopwatch(STOP);
Apar.free();
Bpar.free();
Cpar.free();
Abra.free();
Bbra.free();
Cbra.free();
}
int main()
{
//printf("=== testing array_ref2<int> (diagonal) ===\n");
//testArr2_diagonal<int>();
//printf("=== testing array_ref2<double> (diagonal) ===\n");
//testArr2_diagonal<double>();
printf("=== testing array_ref2<int> ===\n");
testArr2<int>();
printf("=== testing array_ref2<double> ===\n");
testArr2<double>();
printf("=== testing array_ref3<int> ===\n");
testArr3<int>();
printf("=== testing array_ref3<double> ===\n");
testArr3<double>();
printf("=== testing array_ref4<int> ===\n");
testArr4<int>();
printf("=== testing array_ref4<double> ===\n");
testArr4<double>();
}
| 27.669383
| 134
| 0.575353
|
yangyha
|
68718219eda17a62176ed61329edcffd8ae22551
| 1,485
|
cpp
|
C++
|
leetcode/cpp/p2/p2.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | 1
|
2020-08-20T23:27:13.000Z
|
2020-08-20T23:27:13.000Z
|
leetcode/cpp/p2/p2.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | null | null | null |
leetcode/cpp/p2/p2.cpp
|
davidlunadeleon/leetcode
|
3a3d7d3ec9b708982658b154f8e551ae9a9fb8c1
|
[
"Unlicense"
] | null | null | null |
// Source: https://leetcode.com/problems/add-two-numbers/
// Date: 17.06.2020
// Solution by: David Luna
// Runtime: 44ms
// Memory usage: 71.2 MB
#include <iostream>
#include <vector>
#include "../lib/linkedListUtils/linkedListUtils.h"
#include "../lib/vectorUtils/vectorUtils.h"
// Leetcode solution starts
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *ans, *ptrAns;
int carry;
ans = new ListNode();
ptrAns = ans;
carry = 0;
while (l1 || l2) {
if (l1) {
carry += l1->val;
l1 = l1->next;
}
if (l2) {
carry += l2->val;
l2 = l2->next;
}
ans = (ans->next = new ListNode(carry % 10));
carry /= 10;
}
if (carry) {
ans->next = new ListNode(carry);
}
ans = ptrAns->next;
delete ptrAns;
return ans;
}
};
// Leetcode solution ends
void makeTest() {
ListNode *l1, *l2, *ans, *correctAns;
std::vector<int> l1vector, l2vector, correctAnsVector;
makeVectorT(l1vector);
makeVectorT(l2vector);
makeVectorT(correctAnsVector);
l1 = makeLinkedList(l1vector);
l2 = makeLinkedList(l2vector);
correctAns = makeLinkedList(correctAnsVector);
ans = Solution().addTwoNumbers(l1, l2);
std::cout << (compareLinkedLists(ans, correctAns) ? "pass\n" : "fail\n");
deleteLinkedList(ans);
deleteLinkedList(correctAns);
deleteLinkedList(l1);
deleteLinkedList(l2);
}
int main() {
int numTests;
std::cin >> numTests;
for (int i = 0; i < numTests; i++) {
makeTest();
}
return 0;
}
| 19.8
| 74
| 0.651178
|
davidlunadeleon
|
68725068ccbabe252b8e7038540bab47f6c4459a
| 1,122
|
cpp
|
C++
|
src/mxAUIContainer.cpp
|
stahta01/Zinjal
|
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
|
[
"OML"
] | 1
|
2019-03-24T00:58:59.000Z
|
2019-03-24T00:58:59.000Z
|
src/mxAUIContainer.cpp
|
stahta01/Zinjal
|
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
|
[
"OML"
] | null | null | null |
src/mxAUIContainer.cpp
|
stahta01/Zinjal
|
8d1e52c9eab5cde9f7cb96c99a0fbdf97904da42
|
[
"OML"
] | null | null | null |
#include "mxAUIContainer.h"
#include "mxMainWindow.h"
#include "mxAUI.h"
BEGIN_EVENT_TABLE(mxAUIContainer,wxAuiNotebook)
EVT_AUINOTEBOOK_PAGE_CHANGED(mxID_LEFT_PANELS, mxAUIContainer::OnPageChanged)
END_EVENT_TABLE()
mxAUIContainer::mxAUIContainer (wxWindow * parent, bool for_side_panel)
: wxAuiNotebook(parent, wxID_ANY, wxDefaultPosition, wxSize(200,400), wxAUI_NB_BOTTOM | wxNO_BORDER),
m_for_side_panel(for_side_panel)
{
}
void mxAUIContainer::Select (wxWindow * win) {
int i = GetPageIndex(win);
if (i!=wxNOT_FOUND)
SetSelection(i);
}
void mxAUIContainer::Detach (wxWindow *win) {
int i = GetPageIndex(win);
if (i!=wxNOT_FOUND)
RemovePage(i);
}
void mxAUIContainer::Add (PaneId::type id, wxWindow * win) {
win->Reparent(this);
PaneConfig &cfg = PaneConfig::Get(id);
AddPage(win,m_for_side_panel?cfg.GetVeryShortCaption():cfg.GetShortCaption(),true);
}
void mxAUIContainer::OnPageChanged (wxAuiNotebookEvent & evt) {
int i = this->GetSelection();
main_window->m_aui->GetPane(this).Caption(m_names[i]);
}
wxWindow * mxAUIContainer::GetCurrent ( ) {
return GetPage(GetSelection());
}
| 24.391304
| 102
| 0.753119
|
stahta01
|
6872aa2d719d1b24f647cb4e8ac2bad7c8b97096
| 1,454
|
cpp
|
C++
|
hr/hard/connectedSum.cpp
|
gnom1gnom/cpp-algorithms
|
e460c0d1720acf0e0548452dfba05651e4868120
|
[
"Unlicense"
] | null | null | null |
hr/hard/connectedSum.cpp
|
gnom1gnom/cpp-algorithms
|
e460c0d1720acf0e0548452dfba05651e4868120
|
[
"Unlicense"
] | null | null | null |
hr/hard/connectedSum.cpp
|
gnom1gnom/cpp-algorithms
|
e460c0d1720acf0e0548452dfba05651e4868120
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
map<int, vector<int>> v;
map<int, bool> visited;
int getConnectedComponentSize(int x)
{
stack<int> nodes;
nodes.push(x);
visited[x] = true;
int cnt = 0;
while (nodes.size() > 0)
{
int x = nodes.top();
nodes.pop();
cnt += 1;
for (int y : v[x])
{
if (visited[y] == false)
{
visited[y] = true;
nodes.push(y);
}
}
}
return cnt;
}
int connectedSum(int graph_nodes, vector<int> graph_from, vector<int> graph_to)
{
for (int i = 0; i < graph_from.size(); i++)
{
int x = graph_from[i];
int y = graph_to[i];
v[x].push_back(y);
v[y].push_back(x);
}
int ans = 0;
for (int i = 1; i < graph_nodes + 1; i++)
{
if (visited[i] == false)
{
if (v.find(i) != v.end()) // there is at least one connection from the node
{
int cnt = getConnectedComponentSize(i);
ans += ceil(sqrt(cnt));
}
else // this is an isolated node
ans++;
}
}
return ans;
}
int main(int argc, char const *argv[])
{
int graph_nodes = 10;
vector<int> graph_from = {1, 1, 2, 3, 7};
vector<int> graph_to = {2, 3, 4, 5, 8};
cout << connectedSum(graph_nodes, graph_from, graph_to) << endl;
return 0;
}
| 20.771429
| 87
| 0.47868
|
gnom1gnom
|
68744a3aa9788c1e7ff013c53b2ebc4b971848a2
| 1,451
|
cpp
|
C++
|
src/WidgetSprinkler.cpp
|
intoyuniot/WidgetSprinkler
|
10915dd4ea88ba3f2b8aa06feb3acc5b3162251b
|
[
"MIT"
] | null | null | null |
src/WidgetSprinkler.cpp
|
intoyuniot/WidgetSprinkler
|
10915dd4ea88ba3f2b8aa06feb3acc5b3162251b
|
[
"MIT"
] | null | null | null |
src/WidgetSprinkler.cpp
|
intoyuniot/WidgetSprinkler
|
10915dd4ea88ba3f2b8aa06feb3acc5b3162251b
|
[
"MIT"
] | null | null | null |
#include "WidgetSprinkler.h"
WidgetSprinkler::WidgetSprinkler(uint8_t ucItem)
{
_Item=ucItem;
memset(pDataStatusTopic,0,sizeof(pDataStatusTopic));
memset(pCmdWaterTopic,0,sizeof(pCmdWaterTopic));
memset(pDataSoilHumidityTopic,0,sizeof(pDataSoilHumidityTopic));
sprintf(pDataStatusTopic,"channel/sprinkler_%d/data/status",_Item);
sprintf(pCmdWaterTopic,"channel/sprinkler_%d/cmd/watering",_Item);
sprintf(pDataSoilHumidityTopic,"channel/sprinkler_%d/data/soilHumidity",_Item);
}
WidgetSprinkler::~WidgetSprinkler()
{
}
void WidgetSprinkler::begin(void (*UserCallBack)(void))
{
_EventCb=UserCallBack;
IntoRobot.subscribe(pCmdWaterTopic, NULL, this);
}
void WidgetSprinkler::displayWaterStatus(uint8_t status)
{
IntoRobot.publish(pDataStatusTopic,status);
}
void WidgetSprinkler::displaySoilHumidity(int soilHumidity)
{
IntoRobot.publish(pDataSoilHumidityTopic,soilHumidity);
}
uint8_t WidgetSprinkler::getWaterSwitch(void)
{
return _switchKey;
}
int WidgetSprinkler:: getWateringTime(void)
{
return _wateringTime;
}
void WidgetSprinkler::control(uint8_t pin,uint8_t status)
{
pinMode(pin,OUTPUT);
digitalWrite(pin,status);
displayWaterStatus(status);
}
void WidgetSprinkler::widgetBaseCallBack(uint8_t *payload, uint32_t len)
{
if(!jsonGetValue(payload, "status", _switchKey)) return;
if(!jsonGetValue(payload, "time", _wateringTime)) return;
_EventCb();
}
| 21.338235
| 83
| 0.760165
|
intoyuniot
|
6875392c133ac3c05480da694262bac3fc550ebd
| 1,005
|
hpp
|
C++
|
src/region_event_registry.hpp
|
gemfire/node-gemfire
|
51e55645e1b643046b47e8dc7d2144ae58688ed2
|
[
"BSD-2-Clause"
] | 8
|
2015-04-24T18:59:01.000Z
|
2019-07-05T14:24:22.000Z
|
src/region_event_registry.hpp
|
gemfire/node-gemfire
|
51e55645e1b643046b47e8dc7d2144ae58688ed2
|
[
"BSD-2-Clause"
] | 8
|
2015-06-30T20:48:34.000Z
|
2021-03-13T03:45:13.000Z
|
src/region_event_registry.hpp
|
gemfire/node-gemfire
|
51e55645e1b643046b47e8dc7d2144ae58688ed2
|
[
"BSD-2-Clause"
] | 13
|
2015-05-02T16:16:42.000Z
|
2021-05-25T05:50:03.000Z
|
#ifndef __REGION_EVENT_REGISTRY_HPP__
#define __REGION_EVENT_REGISTRY_HPP__
#include <geode/Region.hpp>
#include <geode/EntryEvent.hpp>
#include <string>
#include <set>
#include "region_event_listener.hpp"
#include "event_stream.hpp"
namespace node_gemfire {
class Region;
class RegionEventRegistry {
public:
RegionEventRegistry() :
listener(new RegionEventListener),
eventStream(new EventStream(this, (uv_async_cb) emitCallback)) {}
static void emitCallback(uv_async_t * async, int status);
void add(node_gemfire::Region * region);
void remove(node_gemfire::Region * region);
void emit(const std::string & eventName, const apache::geode::client::EntryEvent & event);
static RegionEventRegistry * getInstance();
private:
void publishEvents();
apache::geode::client::CacheListenerPtr listener;
static RegionEventRegistry instance;
std::set<node_gemfire::Region *> regionSet;
EventStream * eventStream;
};
} // namespace node_gemfire
#include "region.hpp"
#endif
| 23.928571
| 92
| 0.761194
|
gemfire
|
687672105e4f1408e5e225f7b52bd4e553c0c03c
| 4,079
|
cpp
|
C++
|
src/ComponentsFactory.cpp
|
valentingrigorean/Tanks-IP
|
24f7db59b009cf05b193bf0a2d46f68b71d0b399
|
[
"MIT"
] | null | null | null |
src/ComponentsFactory.cpp
|
valentingrigorean/Tanks-IP
|
24f7db59b009cf05b193bf0a2d46f68b71d0b399
|
[
"MIT"
] | null | null | null |
src/ComponentsFactory.cpp
|
valentingrigorean/Tanks-IP
|
24f7db59b009cf05b193bf0a2d46f68b71d0b399
|
[
"MIT"
] | null | null | null |
#include <tank/ComponentsFactory.h>
#include <tank/ObjectPool.h>
#include <tank/GameObject.h>
#include <tank/ResourceManager.h>
#include <tank/components/SpriteComponent.h>
#include <tank/components/TransformComponent.h>
#include <tank/components/HealthComponent.h>
#include <tank/components/TankComponent.h>
#include <tank/components/HealthComponent.h>
#include <tank/components/GunComponent.h>
#include <tank/components/BodyComponent.h>
#include <tank/components/BulletComponent.h>
#include <tank/components/AIComponent.h>
#include <tank/GConstants.h>
anax::Entity ComponentsFactory::CreateSprite(anax::World & world, Texture2D & texture, Point position, Size size,int zOrder)
{
auto& e = world.createEntity();
auto& spriteComp = e.addComponent<SpriteComponent>();
spriteComp.zOrder = zOrder;
spriteComp.sprite.SetTexture(texture);
auto& transform = e.addComponent<TransformComponent>().transform;
transform.SetPosition(position);
transform.SetSize(size);
e.activate();
return e;
}
b2Body * ComponentsFactory::AddBody(b2World & world, anax::Entity & entity, BodyConfig & config, void * userData, bool causeEvents)
{
auto& bodyComp = entity.addComponent<BodyComponent>();
bodyComp.causeEvents = causeEvents;
bodyComp.body = BodyFactory::CreateRect(world, config);
entity.activate();
bodyComp.body->SetUserData(userData);
return bodyComp.body;
}
void ComponentsFactory::AddTank(anax::Entity & entity, int health, int dmg, float speed)
{
auto& tankComp = entity.addComponent<TankComponent>();
tankComp.speed = speed;
auto& gunComp = entity.addComponent<GunComponent>();
gunComp.bulletDamage = dmg;
AddHealth(entity, health);
}
void ComponentsFactory::AddHealth(anax::Entity & entity, int health)
{
auto& healthComp = entity.addComponent<HealthComponent>();
healthComp.health = health;
entity.activate();
}
void ComponentsFactory::CreateBullet(anax::Entity & owner, GunComponent &gunComp)
{
auto& transform = owner.getComponent<TransformComponent>().transform;
auto bodyEntity = owner.getComponent<BodyComponent>().body;
auto world = bodyEntity->GetWorld();
Point pos;
Point offset;
Size size(10, 10);
b2Vec2 velocity;
auto offsetX = (transform.GetSize().width / 2.f) + (size.width / 2.f) + 1;
auto offsetY = (transform.GetSize().height / 2.f) + (size.height / 2.f) + 1;
offset.x = transform.GetSize().width / 2.f - size.width / 2.f;
offset.y = transform.GetSize().height / 2.f - size.height / 2.f;
switch (gunComp.direction)
{
case UP:
pos.x = transform.GetPosition().x;
pos.y = transform.GetPosition().y - offsetY;
velocity.x = 0;
velocity.y = 1;
offset.y = offsetY - size.height;
break;
case DOWN:
pos.x = transform.GetPosition().x;
pos.y = transform.GetPosition().y + offsetY;
velocity.x = 0;
velocity.y = -1;
offset.y = offsetY - size.height;
break;
case LEFT:
pos.x = transform.GetPosition().x - offsetX;
pos.y = transform.GetPosition().y;
velocity.x = -1;
velocity.y = 0;
offset.x = offsetX - size.width;
break;
case RIGHT:
pos.x = transform.GetPosition().x + offsetX;
pos.y = transform.GetPosition().y;
velocity.x = 1;
velocity.y = 0;
offset.x = offsetX - size.width;
break;
}
auto& bulletEntity = CreateSprite(owner.getWorld(), ResourceManager::GetTexture("bullet"), pos, size);
auto& tranEntity = bulletEntity.getComponent<TransformComponent>().transform;
tranEntity.SetOffset(offset);
auto& bulletComp = bulletEntity.addComponent<BulletComponent>();
auto obj = ObjectPool::GetObject();
obj->entity = bulletEntity;
bulletComp.owner = owner;
bulletComp.dmg = gunComp.bulletDamage;
auto mask = TILE_TYPE::DESTROYABLE | TILE_TYPE::DYNAMIC | TILE_TYPE::SOLID;
//auto mask = 0x1;
BodyConfig bodyConfig(pos, size, TILE_TYPE::DYNAMIC, mask);
bodyConfig.dynamic = true;
auto body = AddBody(*world, bulletEntity, bodyConfig, obj, true);
velocity.x *= gunComp.SPEED * P2M;
velocity.y *= gunComp.SPEED * P2M;
body->SetLinearVelocity(velocity);
}
void ComponentsFactory::AddAI(anax::Entity & entity)
{
entity.addComponent<AIComponent>();
entity.activate();
}
| 30.669173
| 131
| 0.730816
|
valentingrigorean
|
68772850ae773b62cebb839e75a1805617316515
| 1,041
|
cxx
|
C++
|
test/loopcompile4.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | 10
|
2018-03-26T07:41:44.000Z
|
2021-11-06T08:33:24.000Z
|
test/loopcompile4.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | null | null | null |
test/loopcompile4.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | 1
|
2020-11-17T03:17:00.000Z
|
2020-11-17T03:17:00.000Z
|
/* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include <stdio.h>
#define NUM 10
void test3()
{
int i=0;
float ary[NUM];
while(i<NUM){
ary[i] = i;
ary[i] = -i;
ary[i] = i*2;
++i;
}
}
void test2()
{
int i=0,j=0;
while(i<10 && j!=4) {
printf("i=%d j=%d\n",i,j);
i++; j++;
}
printf("i=%d j=%d\n",i,j);
while(i>0 || j==0) {
printf("i=%d j=%d\n",i,j);
i--;j--;
}
printf("i=%d j=%d\n",i,j);
}
void test1()
{
int i;
for(i=0;i<4;i++) {
if(((i==1)&&(2==2))||(2==3)) {
printf("true\n");
}
else {
printf("false\n");
}
if(((i==2)&&(2==2))||(2==3)) {
printf("true\n");
}
else {
printf("false\n");
}
if(((i==2)&&(2==2))||(3==3)) {
printf("true\n");
}
else {
printf("false\n");
}
}
}
int main()
{
test3();
test1();
test2();
return 0;
}
| 14.661972
| 74
| 0.387128
|
paulwratt
|
68778b1cfd5fe17c927fc3dca44b4671479ef2d4
| 11,100
|
cpp
|
C++
|
examples/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp
|
VXAPPS/cmake-sgx-template
|
01e75934253a63e2a8d371011d268da53833df72
|
[
"BSD-3-Clause"
] | null | null | null |
examples/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp
|
VXAPPS/cmake-sgx-template
|
01e75934253a63e2a8d371011d268da53833df72
|
[
"BSD-3-Clause"
] | null | null | null |
examples/Cxx14SGXDemo/Enclave/TrustedLibrary/Libcxx.cpp
|
VXAPPS/cmake-sgx-template
|
01e75934253a63e2a8d371011d268da53833df72
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2011-2021 Intel Corporation. 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 Intel Corporation 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 <algorithm>
#include <array>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "../Enclave.h"
#include "Enclave_t.h"
// Examples for the following new language and library features introduced by C++14:
// standard user-defined literals
// tuple addressing via type
// std::make_unique
// std::integral_constant
// std::integer_sequence
// std::cbegin/std::cend and std::crbegin/std::crend
// std::exchange
// std::is_final
// std::equal/std::mismatch/std::is_permutation new overloads
// heterogeneous lookup
// function return type deduction
// variable template
// binary literals
// digit separators
// generic lambdas
// lambda capture expressions
// attribute [[deprecated]]
// aggregate member initialization
// relaxed constexpr restrictions
// alternate type deduction on declaration
// std:quoted
using namespace std::literals;
class A {};
class B final {};
struct Vec {
int m_x = 0;
int m_y = 0;
Vec() = default;
Vec( int x, int y ) : m_x( x ), m_y( y ) {}
void dump() {
printf( "{%d, %d}", m_x, m_y );
}
};
struct R {
int x;
R( int i ) : x{i} { printf( "R{%d} ", i ); }
bool operator<( R const &r ) const { return x < r.x; }
};
bool operator<( R const &r, int i ) { return r.x < i; }
bool operator<( int i, R const &r ) { return i < r.x; }
// debugging aid
template<typename T, T... ints>
void print_sequence( std::integer_sequence<T, ints...> int_seq ) {
printf( "The sequence of size %lu: ", int_seq.size() );
( printf( "%lu ", ints ), ... );
printf( "\n" );
}
// convert array into a tuple
template<typename Array, std::size_t... I>
auto a2t_impl( const Array &a, std::index_sequence<I...> ) {
return std::make_tuple( a[I]... );
}
template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
auto a2t( const std::array<T, N> &a ) {
return a2t_impl( a, Indices{} );
}
// pretty-print a tuple
template<typename Tuple, std::size_t... Is>
void print_tuple_impl( const Tuple &t, std::index_sequence<Is...> ) {
( printf( "%s%d", Is == 0 ? "" : ", ", std::get<Is>( t ) ), ... );
}
template<typename... Args>
void dump_tuple( const std::tuple<Args...> &t ) {
printf( "(" );
print_tuple_impl( t, std::index_sequence_for<Args...> {} );
printf( ")" );
printf( "\n" );
}
//Function return type deduction
auto fibonacci( int n ) {
if ( n < 2 ) {
return 1;
}
return fibonacci( n - 1 ) + fibonacci( n - 2 );
}
// variable templates
template<typename T>
constexpr T pi = T( 3.141592653589793238462643383 );
template<>
constexpr const char *pi<const char *> = "pi";
template<typename T>
T circular_area( T r ) {
return pi<T> *r * r;
}
// attribute [[deprecated]]
[[deprecated]] int f_depre() {return 0;}
[[deprecated( "g_depre() is thread-unsafe. Use h() instead" )]]
void g_depre( int &x ) { (void)x; return;}
// aggregate member initialization
struct Aggr {
struct B {
int a = 21;
int b;
int c = 22;
int d;
int e = 23;
};
B b1 = {11, 12};
B b2 = {11, 12, 13};
int x;
};
// Relaxed constexpr restrictions
constexpr bool even( int x ) {
if ( x % 2 == 0 ) {
return true;
}
return false;
}
constexpr int while_loop( int x ) {
int i = 0;
do {
++i;
}
while ( i < x );
return i;
}
void ecall_cxx14_standard_user_defined_literals() {
auto str = "hello world"s;
printf( "%s\n", str.c_str() );
}
void ecall_cxx14_tuple_via_type() {
std::tuple<std::string, int, double> t( "foo", 99, 1.0 );
auto i = std::get<int>( t );
auto d = std::get<double>( t );
auto s = std::get<std::string>( t );
printf( "%d, %f, %s\n", i, d, s.c_str() );
}
void ecall_cxx14_make_unique() {
auto v1 = std::make_unique<Vec>();
auto v2 = std::make_unique<Vec>( 1, 2 );
auto v3 = std::make_unique<Vec[]>( 5 );
printf( "make_unique<Vec>(): " );
( *v1 ).dump();
printf( "\n" );
printf( "make_unique<Vec>(1, 2): " );
( *v2 ).dump();
printf( "\n" );
printf( "make_unique<Vec[]>(5): " );
printf( "\n" );
for ( int i = 0; i < 5; i++ ) {
printf( " " );
v3[i].dump();
printf( "\n" );
}
}
void ecall_cxx14_integral_constant() {
typedef std::integral_constant<int, 2> two_t;
typedef std::integral_constant<int, 4> four_t;
static_assert( two_t() * 2 == four_t(), "2*2 != 4" );
}
void ecall_cxx14_integer_sequence() {
print_sequence( std::integer_sequence<size_t, 9, 2, 5, 1> {} );
print_sequence( std::make_integer_sequence<size_t, 20> {} );
print_sequence( std::make_index_sequence<10> {} );
print_sequence( std::index_sequence_for<float, R, char> {} );
std::array<int, 4> array = {1, 2, 3, 4};
auto tuple = a2t( array );
static_assert( std::is_same<decltype( tuple ),
std::tuple<int, int, int, int>>::value, "" );
dump_tuple( tuple );
}
void ecall_cxx14_constant_begin_end() {
std::vector<int> v = {3, 1, 4};
if ( std::find( std::cbegin( v ), std::cend( v ), 3 ) != std::cend( v ) ) {
printf( "Forward search: found the target in vector v!\n" );
}
if ( std::find( std::crbegin( v ), std::crend( v ), 3 ) != std::crend( v ) ) {
printf( "Backward search: found the target in vector v!\n" );
}
}
void ecall_cxx14_exchage() {
std::vector<int> vexc;
std::exchange( vexc, {1, 2, 3, 4} );
for ( const auto &vi : vexc ) {
printf( "%d ", vi );
}
printf( "\n" );
}
void ecall_cxx14_is_final() {
printf( "A is final: %s\nB is final: %s\n",
std::is_final<A>() ? "True" : "False",
std::is_final<B>() ? "True" : "False" );
}
void ecall_cxx14_equal_mismatch_permutation_new_overloads() {
std::vector<int> veq1{1, 2, 3};
std::vector<int> veq2{1, 2, 3};
auto is_equal = std::equal( veq1.cbegin(), veq1.cend(),
veq2.cbegin(), veq2.cend() );
printf( "veq1 and veq2 is equal: %s\n", is_equal ? "True" : "False" );
std::vector<int> vmis{1, 3, 2};
auto diff_pair = std::mismatch( veq1.cbegin(), veq1.cend(),
vmis.cbegin(), vmis.cend() );
printf( "first pair of different values: (%d, %d)\n",
*diff_pair.first, *diff_pair.second );
const auto v_permu1 = {1, 2, 3, 4, 5};
const auto v_permu2 = {3, 5, 4, 1, 9};
printf( "v_permu1 and v_permu2 is_permutation: %s\n",
std::is_permutation( v_permu1.begin(), v_permu1.end(),
v_permu2.begin() ) ? "True" : "False" );
}
void ecall_cxx14_heterogeneous_lookup() {
std::set<R, std::less<>> r{3, 1, 4, 1, 5};
printf( ": %lu, %lu\n", r.count( 1 ), r.count( 2 ) );
}
void ecall_cxx14_function_return_type_deduction() {
auto fibo_ret = fibonacci( 10 );
printf( "The fibonacci number at index 10: %u\n", fibo_ret );
}
void ecall_cxx14_variable_template() {
printf( "pi as a const char: %s\n", pi<const char *> );
printf( "circular area (integer): %u\n", circular_area( 10 ) );
printf( "circular area (floating point): %f\n", circular_area( 10.0 ) );
}
void ecall_cxx14_binary_literals() {
printf( "The hex represented by '0b10100101' is: 0x%x\n", 0b10100101 );
}
void ecall_cxx14_digit_separators() {
printf( "digit separator for integer: %u\n", 1'000'000 );
printf( "digit separator for floating: %f\n", 0.001'015 );
printf( "digit separator for binary literal: 0x%x\n", 0b0100'1100'0110 );
}
void ecall_cxx14_generic_lambdas() {
auto lambda_sum = []( auto x, auto y ) {return x + y;};
printf( "lambda_sum for (10, 10): %u\n", lambda_sum( 10, 10 ) );
printf( "lambda_sum for (10, 10.0): %f\n", lambda_sum( 10, 10.0 ) );
}
void ecall_cxx14_lambda_capture_expression() {
auto ptr = std::make_unique<int>( 10 );
printf( "result from lambda capture: %d\n", [value = std::move( ptr )] {return *value;}() );
}
void ecall_cxx14_attribute_deprecated() {
auto depre = f_depre();
g_depre( depre );
}
void ecall_cxx14_aggregate_member_init() {
Aggr a = {{1, 2, 3, 4}, {1}, 5};
(void)a;
}
void ecall_cxx14_relaxed_constexpr() {
printf( "2 is an even number: %s\n", even( 2 ) ? "true" : "false" );
printf( "result from constexpr while_loop(10): %d\n", while_loop( 10 ) );
}
void ecall_cxx14_alternate_type_deduction() {
auto dedu_a = 1 + 2; // type of a : int
decltype( auto ) dedu_b1 = dedu_a; // type of b1: int
decltype( auto ) dedu_b2 = ( dedu_a ); // type of b2: int&
printf( "before modification: a: %d, b1: %d, b2: %d\n", dedu_a, dedu_b1, dedu_b2 );
++dedu_b2;
printf( "after modification: a: %d, b1: %d, b2: %d\n", dedu_a, dedu_b1, dedu_b2 );
}
void ecall_cxx14_quoted() {
std::stringstream ss;
std::string in = "String with spaces, and embedded \"quotes\" too";
std::string out;
auto show = [&]( const auto & what ) {
&what == &in
? printf( "read in [%s]\nstored as [%s]\n", in.c_str(), ss.str().c_str() )
: printf( "written out [%s]\n\n", out.c_str() );
};
ss << std::quoted( in );
show( in );
ss >> std::quoted( out );
show( out );
ss.str( "" );
in = "String with spaces, and embedded $quotes$ too";
const char delim {'$'};
const char escape {'%'};
ss << std::quoted( in, delim, escape );
show( in );
ss >> std::quoted( out, delim, escape );
show( out );
}
| 26.241135
| 94
| 0.627658
|
VXAPPS
|
6879bc324078290ca7f15bc3e932ed06efd6ea7f
| 1,827
|
hpp
|
C++
|
src/GLRenderer/Scene/Component.hpp
|
Thomas-Zorroche/GLRenderer
|
1e47a98d563a5c1df8c781826322325a1766bda5
|
[
"MIT"
] | null | null | null |
src/GLRenderer/Scene/Component.hpp
|
Thomas-Zorroche/GLRenderer
|
1e47a98d563a5c1df8c781826322325a1766bda5
|
[
"MIT"
] | null | null | null |
src/GLRenderer/Scene/Component.hpp
|
Thomas-Zorroche/GLRenderer
|
1e47a98d563a5c1df8c781826322325a1766bda5
|
[
"MIT"
] | null | null | null |
#pragma once
#include <glm/glm.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <memory>
#include <string>
#include "../Mesh.hpp"
#include "../Lighting/BaseLight.hpp"
#include "../Line.hpp"
namespace glrenderer {
struct TransformComponent
{
glm::vec3 location = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 rotation = glm::vec3(0.0f, 0.0f, 0.0f);
glm::vec3 scale = glm::vec3(1.0f, 1.0f, 1.0f);
TransformComponent() = default;
TransformComponent(const TransformComponent&) = default;
glm::mat4 getModelMatrix() const
{
glm::mat4 trans = glm::translate(glm::mat4(1.0f), location);
glm::mat4 rot = glm::rotate(glm::mat4(1.0f), glm::radians(rotation.z), glm::vec3(0, 0, 1));
rot = glm::rotate(rot, glm::radians(rotation.y), glm::vec3(0, 1, 0));
rot = glm::rotate(rot, glm::radians(rotation.x), glm::vec3(1, 0, 0));
glm::mat4 scl = glm::scale(glm::mat4(1.0f), scale);
return trans * rot * scl;
}
};
struct LabelComponent
{
std::string label = "Entity";
LabelComponent() = default;
LabelComponent(const LabelComponent&) = default;
LabelComponent(const std::string& label) : label(label) {}
};
struct MeshComponent
{
std::shared_ptr<Mesh> mesh = nullptr;
MeshComponent() = default;
MeshComponent(const MeshComponent&) = default;
MeshComponent(const std::shared_ptr<Mesh>& mesh)
: mesh(mesh) {};
};
struct LightComponent
{
std::shared_ptr<BaseLight> light = nullptr;
LightComponent() = default;
LightComponent(const LightComponent&) = default;
LightComponent(const std::shared_ptr<BaseLight>& light)
: light(light) {}
};
struct LineComponent
{
std::shared_ptr<Line> line = nullptr;
LineComponent() = default;
LineComponent(const LineComponent&) = default;
LineComponent(const std::shared_ptr<Line>& line)
: line(line) {}
};
}
| 23.423077
| 94
| 0.67214
|
Thomas-Zorroche
|
687b2189cd2243075b44d9182317150260ddea43
| 1,186
|
cpp
|
C++
|
examples/demo/state_world.cpp
|
HolyBlackCat/prototyping
|
0938ad889db0bfcc3b683beaa92eac81bf05bc76
|
[
"Zlib"
] | null | null | null |
examples/demo/state_world.cpp
|
HolyBlackCat/prototyping
|
0938ad889db0bfcc3b683beaa92eac81bf05bc76
|
[
"Zlib"
] | null | null | null |
examples/demo/state_world.cpp
|
HolyBlackCat/prototyping
|
0938ad889db0bfcc3b683beaa92eac81bf05bc76
|
[
"Zlib"
] | null | null | null |
#include "main.h"
namespace States
{
STRUCT( World EXTENDS StateBase )
{
MEMBERS()
float angle = 0;
void Tick(std::string &next_state) override
{
(void)next_state;
angle += 0.01;
ImGui::ShowDemoWindow();
if (mouse.right.pressed())
{
static Audio::Buffer buf = []{
int16_t array[10000];
for (size_t i = 0; i < std::size(array); i++)
array[i] = std::sin(i / 30.f) * 0x7fff;
return Audio::Sound(48000, Audio::mono, std::size(array), array);
}();
audio_controller.Add(buf)->play();
}
}
void Render() const override
{
Graphics::SetClearColor(fvec3(0));
Graphics::Clear();
r.BindShader();
r.iquad(mouse.pos(), ivec2(32)).center().rotate(angle).color(mouse.left.down() ? fvec3(1,0.5,0) : fvec3(0,0.5,1));
r.itext(mouse.pos(), Graphics::Text(Fonts::main, STR((audio_controller.ActiveSources())))).color(fvec3(1));
r.Finish();
}
};
}
| 26.954545
| 126
| 0.469646
|
HolyBlackCat
|
687c5cd7828c54a773742ec44899720ec6854062
| 12,860
|
cpp
|
C++
|
nightsky/configDlg.cpp
|
thurizas/nightSky
|
6924ef45c93b45bf0c47e0db2eef667d8255fb38
|
[
"Apache-2.0"
] | null | null | null |
nightsky/configDlg.cpp
|
thurizas/nightSky
|
6924ef45c93b45bf0c47e0db2eef667d8255fb38
|
[
"Apache-2.0"
] | null | null | null |
nightsky/configDlg.cpp
|
thurizas/nightSky
|
6924ef45c93b45bf0c47e0db2eef667d8255fb38
|
[
"Apache-2.0"
] | null | null | null |
#include <QString>
#include <QHBoxLayout>
#include <QLabel>
#include <QDebug>
#include "configDlg.h"
#include "nighsky.h"
/**********************************************************************************************************************************************************************************
* function : closeEvent
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
configDlg::configDlg(QWidget* p): QDialog(p), m_pParent(p)
{
setupUI();
updateValues();
}
/**********************************************************************************************************************************************************************************
* function : closeEvent
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
configDlg::~configDlg()
{
}
/**********************************************************************************************************************************************************************************
* function : closeEvent
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
void configDlg::setupUI()
{
QWidget* layoutWidget;
QHBoxLayout* hboxLayout;
QSpacerItem* spacerItem;
QFrame* line;
QFrame* line2;
QLabel* label;
QLabel* label1;
QLabel* label6;
QLabel* label7;
QLabel* label8;
QLabel* label9;
QLabel* label10;
// set up for for use with the dialog...
QFont font;
font.setFamily(QString::fromUtf8("Courier New"));
font.setPointSize(12);
if (this->objectName().isEmpty())
this->setObjectName(QString::fromUtf8("configDialog"));
this->setWindowTitle("Configuration Parameters");
this->resize(434, 392);
layoutWidget = new QWidget(this);
layoutWidget->setObjectName(QString::fromUtf8("layoutWidget"));
layoutWidget->setGeometry(QRect(70, 340, 351, 33));
line = new QFrame(this);
line->setObjectName(QString::fromUtf8("line"));
line->setGeometry(QRect(190, 15, 431, 20));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
// top divider....
label1 = new QLabel(this);
label1->setObjectName(QString::fromUtf8("label1"));
label1->setFont(font);
label1->setGeometry(QRect(9, 12, 191, 21));
label1->setText("Display Properties");
// controls for dealing with displaying grid ....
m_cbxGrid = new QCheckBox(this);
m_cbxGrid->setText("Display Grid");
m_cbxGrid->setObjectName(QString::fromUtf8("m_cbxGrid"));
m_cbxGrid->setGeometry(QRect(20, 40, 151, 21));
m_cbxGrid->setFont(font);
// ... set up labels for use with lat/long entry fields ...
for (int ndx = 0; ndx < 4; ndx++)
{
m_labels[ndx] = new QLabel(this);
m_labels[ndx]->setObjectName(QString("label%1").arg(ndx + 2));
m_labels[ndx]->setEnabled(false);
m_labels[ndx]->setFont(font);
}
m_labels[0]->setGeometry(QRect(40, 70, 171, 16));
m_labels[0]->setText("Latitude spacing");
m_labels[1]->setGeometry(QRect(40, 100, 171, 16));
m_labels[1]->setText("Longitude spacing");
m_labels[2]->setGeometry(QRect(270, 70, 71, 16));
m_labels[2]->setText("Degrees");
m_labels[3]->setGeometry(QRect(270, 100, 71, 16));
m_labels[2]->setText("Degrees");
// ... set up edit controls for data entry ...
m_txtLatSpace = new QLineEdit(this);
m_txtLatSpace->setObjectName(QString::fromUtf8("m_edtLatSpace"));
m_txtLatSpace->setEnabled(false);
m_txtLatSpace->setFont(font);
m_txtLatSpace->setGeometry(QRect(220, 70, 41, 20));
m_txtLonSpace = new QLineEdit(this);
m_txtLonSpace->setObjectName(QString::fromUtf8("m_ednLonSpace"));
m_txtLonSpace->setEnabled(false);
m_txtLonSpace->setFont(font);
m_txtLonSpace->setGeometry(QRect(220, 100, 41, 20));
// set up controls for getting projection to use....
label6 = new QLabel(this);
label6->setObjectName(QString::fromUtf8("label6"));
label6->setFont(font);
label6->setText("Projection Type:");
label6->setGeometry(QRect(20, 130, 181, 16));
m_cboProjection = new QComboBox(this);
m_cboProjection->setObjectName(QString::fromUtf8("m_cboProjection"));
m_cboProjection->setGeometry(QRect(20, 150, 271, 22));
m_cboProjection->setFont(font);
m_cboProjection->insertItem(0, "choose a projection");
m_cboProjection->insertItem(1, "Mollweide");
m_cboProjection->insertItem(2, "Orthrographic");
// set up controls for radius of projection...
label10 = new QLabel(this);
label10->setObjectName(QString::fromUtf8("label_2"));
label10->setText("Radius of Projection:");
label10->setGeometry(QRect(20, 190, 221, 16));
label10->setFont(font);
m_txtProjRadius = new QLineEdit(this);
m_txtProjRadius->setObjectName(QString::fromUtf8("m_nProjRadius"));
m_txtProjRadius->setGeometry(QRect(240, 190, 113, 20));
// second divider...now working with simulation properties.....
line2 = new QFrame(this);
line2->setObjectName(QString::fromUtf8("line_2"));
line2->setGeometry(QRect(230, 220, 431, 20));
line2->setFrameShape(QFrame::HLine);
line2->setFrameShadow(QFrame::Sunken);
label = new QLabel(this);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(9, 217, 221, 21));
label->setFont(font);
label->setText("Simulation Properties");
// set up stellar density control...
label8 = new QLabel(this);
label8->setObjectName(QString::fromUtf8("label8"));
label8->setGeometry(QRect(20, 250, 201, 16));
label8->setText("Stellar Density:");
label8->setFont(font);
m_txtDensity = new QLineEdit(this);
m_txtDensity->setObjectName(QString::fromUtf8("m_txtDensity"));
m_txtDensity->setGeometry(QRect(290, 250, 113, 20));
m_txtDensity->setFont(font);
// set up simulation radius control...
label9 = new QLabel(this);
label9->setObjectName(QString::fromUtf8("label9"));
label9->setGeometry(QRect(20, 280, 271, 16));
label9->setText("Radius of Space (parsecs):");
label9->setFont(font);
m_txtRadius = new QLineEdit(this);
m_txtRadius->setObjectName(QString::fromUtf8("m_txtRadius"));
m_txtRadius->setGeometry(QRect(290, 280, 113, 20));
m_txtRadius->setFont(font);
// set up number of stars generated control...
label7 = new QLabel(this);
label7->setObjectName(QString::fromUtf8("label7"));
label7->setGeometry(QRect(20, 310, 181, 16));
label7->setText("Number of Stars:");
label7->setFont(font);
m_txtStarCnt = new QLineEdit(this);
m_txtStarCnt->setObjectName(QString::fromUtf8("m_txtStarCnt"));
m_txtStarCnt->setGeometry(QRect(290, 310, 113, 20));
m_txtStarCnt->setFont(font);
m_txtStarCnt->setReadOnly(true);
// set up button box....
hboxLayout = new QHBoxLayout(layoutWidget);
hboxLayout->setSpacing(6);
hboxLayout->setObjectName(QString::fromUtf8("hboxLayout"));
hboxLayout->setContentsMargins(0, 0, 0, 0);
spacerItem = new QSpacerItem(131, 31, QSizePolicy::Expanding, QSizePolicy::Minimum);
m_btnAccept = new QPushButton(layoutWidget);
m_btnAccept->setObjectName(QString::fromUtf8("m_btnAccept"));
m_btnAccept->setText("Accept");
m_btnCancel = new QPushButton(layoutWidget);
m_btnCancel->setObjectName(QString::fromUtf8("m_btnCancel"));
m_btnCancel->setText("Cancel");
hboxLayout->addItem(spacerItem);
hboxLayout->addWidget(m_btnAccept);
hboxLayout->addWidget(m_btnCancel);
// set up signals/slots....
QObject::connect(m_btnAccept, SIGNAL(clicked()), this, SLOT(onAccept()));
QObject::connect(m_btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
QObject::connect(m_cbxGrid, SIGNAL(stateChanged(int)), this, SLOT(onGridChecked()));
QObject::connect(m_txtDensity, SIGNAL(textChanged(const QString&)), this, SLOT(calcNbrStar()));
QObject::connect(m_txtRadius, SIGNAL(textChanged(const QString&)), this, SLOT(calcNbrStar()));
}
/**********************************************************************************************************************************************************************************
* function :
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
void configDlg::updateValues()
{
bool bCheck = reinterpret_cast<nightSky*>(m_pParent)->getDisplayGrid();
Qt::CheckState checked = (bCheck ? Qt::Checked : Qt::Unchecked); // convert true/false into Qt::CheckState value.
m_cbxGrid->setCheckState(checked);
m_txtLatSpace->setText(QString("%1").arg(reinterpret_cast<nightSky*>(m_pParent)->getLatSpacing()));
m_txtLonSpace->setText(QString("%1").arg(reinterpret_cast<nightSky*>(m_pParent)->getLonSpacing()));
m_cboProjection->setCurrentIndex(reinterpret_cast<nightSky*>(m_pParent)->getProjType());
m_txtProjRadius->setText(QString("%1").arg(reinterpret_cast<nightSky*>(m_pParent)->getProjRadius()));
m_txtDensity->setText(QString("%1").arg(reinterpret_cast<nightSky*>(m_pParent)->getStellarDensity()));
m_txtRadius->setText(QString("%1").arg(reinterpret_cast<nightSky*>(m_pParent)->getSimRadius()));
m_txtStarCnt->setText(QString("%1").arg(m_cntStars));
}
/**********************************************************************************************************************************************************************************
* function :
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
void configDlg::onGridChecked()
{
bool checked = m_cbxGrid->isChecked();
for (int ndx = 0; ndx < 4; ndx++)
{
m_labels[ndx]->setEnabled(checked);
}
m_txtLatSpace->setEnabled(checked);
m_txtLonSpace->setEnabled(checked);
}
/**********************************************************************************************************************************************************************************
* function :
*
* abstract :
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
void configDlg::calcNbrStar()
{
float radius = reinterpret_cast<nightSky*>(m_pParent)->getSimRadius();
float density = reinterpret_cast<nightSky*>(m_pParent)->getStellarDensity();
m_cntStars = 4 * PI * radius * radius * radius * density / 3;
}
/**********************************************************************************************************************************************************************************
* function :
*
* abstract : gets the values from the controls and store in member variables.
*
* parameters:
*
* returns : void
*
* written : GKHuber Nov 2021
************************************************************************************************************************************************************************************/
void configDlg::onAccept()
{
m_bShowGrid = m_cbxGrid->isChecked();
m_nLatStep = m_txtLatSpace->text().toInt();
m_nLonStep = m_txtLonSpace->text().toInt();
m_nProj = m_cboProjection->currentIndex();
m_nProjRadius = m_txtProjRadius->text().toInt();
m_fRadius = m_txtRadius->text().toFloat();
m_fDensity = m_txtDensity->text().toFloat();
QDialog::accept();
}
| 37.16763
| 183
| 0.516096
|
thurizas
|
688371bb2e97c4f2146c8a233e532d0424e6db3e
| 9,590
|
cpp
|
C++
|
sqlite/src/ossimGpkgContentsRecord.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 12
|
2016-09-09T01:24:12.000Z
|
2022-01-09T21:45:58.000Z
|
sqlite/src/ossimGpkgContentsRecord.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 5
|
2016-02-04T16:10:40.000Z
|
2021-06-29T05:00:29.000Z
|
sqlite/src/ossimGpkgContentsRecord.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 20
|
2015-11-17T11:46:22.000Z
|
2021-11-12T19:23:54.000Z
|
//----------------------------------------------------------------------------
//
// File: ossimGpkgContentsRecord.cpp
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Description: Container class for gpkg_contents table.
//
//----------------------------------------------------------------------------
// $Id$
#include "ossimGpkgContentsRecord.h"
#include "ossimSqliteUtil.h"
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimNotify.h>
#include <sqlite3.h>
#include <iomanip>
static const std::string TABLE_NAME = "gpkg_contents";
ossimGpkgContentsRecord::ossimGpkgContentsRecord()
:
ossimGpkgDatabaseRecordBase(),
m_table_name(),
m_data_type(),
m_identifier(),
m_description(),
m_last_change(),
m_min_x(ossim::nan()),
m_min_y(ossim::nan()),
m_max_x(ossim::nan()),
m_max_y(ossim::nan()),
m_srs_id(0)
{
}
ossimGpkgContentsRecord::ossimGpkgContentsRecord(const ossimGpkgContentsRecord& obj)
:
ossimGpkgDatabaseRecordBase(),
m_table_name(obj.m_table_name),
m_data_type(obj.m_data_type),
m_identifier(obj.m_identifier),
m_description(obj.m_description),
m_last_change(obj.m_last_change),
m_min_x(obj.m_min_x),
m_min_y(obj.m_min_y),
m_max_x(obj.m_max_x),
m_max_y(obj.m_max_y),
m_srs_id(obj.m_srs_id)
{
}
const ossimGpkgContentsRecord& ossimGpkgContentsRecord::operator=(
const ossimGpkgContentsRecord& copy_this)
{
if ( this != ©_this )
{
m_table_name = copy_this.m_table_name;
m_data_type = copy_this.m_data_type;
m_identifier = copy_this.m_identifier;
m_description = copy_this.m_description;
m_last_change = copy_this.m_last_change;
m_min_x = copy_this.m_min_x;
m_min_y = copy_this.m_min_y;
m_max_x = copy_this.m_max_x;
m_max_y = copy_this.m_max_y;
m_srs_id = copy_this.m_srs_id;
}
return *this;
}
ossimGpkgContentsRecord::~ossimGpkgContentsRecord()
{
}
const std::string& ossimGpkgContentsRecord::getTableName()
{
return TABLE_NAME;
}
bool ossimGpkgContentsRecord::init( sqlite3_stmt* pStmt )
{
static const char M[] = "ossimGpkgContentsRecord::init";
bool status = false;
if ( pStmt )
{
const ossim_int32 EXPECTED_COLUMNS = 10;
ossim_int32 nCol = sqlite3_column_count( pStmt );
if ( nCol != EXPECTED_COLUMNS )
{
ossimNotify(ossimNotifyLevel_WARN)
<< M << " WARNING:\nUnexpected number of columns: " << nCol
<< "Expected column count: " << EXPECTED_COLUMNS
<< std::endl;
}
if ( nCol >= EXPECTED_COLUMNS )
{
ossim_int32 columnsFound = 0;
std::string colName;
const char* c = 0; // To catch null so not to pass to string.
for ( ossim_int32 i = 0; i < nCol; ++i )
{
colName = sqlite3_column_name(pStmt, i);
if ( colName.size() )
{
if ( colName == "table_name" )
{
c = (const char*)sqlite3_column_text(pStmt, i);
m_table_name = (c ? c : "");
++columnsFound;
}
else if ( colName == "data_type" )
{
c = (const char*)sqlite3_column_text(pStmt, i);
m_data_type = (c ? c : "");
++columnsFound;
}
else if ( colName == "identifier" )
{
c = (const char*)sqlite3_column_text(pStmt, i);
m_identifier = (c ? c : "");
++columnsFound;
}
else if ( colName == "description" )
{
c = (const char*)sqlite3_column_text(pStmt, i);
m_description = (c ? c : "");
++columnsFound;
}
else if ( colName == "last_change" )
{
c = (const char*)sqlite3_column_text(pStmt, i);
m_last_change = (c ? c : "");
++columnsFound;
}
else if ( colName == "min_x" )
{
m_min_x = sqlite3_column_double(pStmt, i);
++columnsFound;
}
else if ( colName == "min_y" )
{
m_min_y = sqlite3_column_double(pStmt, i);
++columnsFound;
}
else if ( colName == "max_x" )
{
m_max_x = sqlite3_column_double(pStmt, i);
++columnsFound;
}
else if ( colName == "max_y" )
{
m_max_y = sqlite3_column_double(pStmt, i);
++columnsFound;
}
else if ( colName == "srs_id" )
{
m_srs_id = sqlite3_column_int(pStmt, i);
++columnsFound;
}
else
{
ossimNotify(ossimNotifyLevel_WARN)
<< M << " Unhandled column name["
<< i << "]: " << colName << std::endl;
}
} // Matches: if ( colName.size() )
if ( columnsFound == EXPECTED_COLUMNS )
{
status = true;
break;
}
} // Matches: for ( ossim_int32 i = 0; i < nCol; ++i )
}
} // Matches: if ( pStmt )
return status;
} // End: ossimGpkgContentsRecord::init( sqlite3_stmt* pStmt )
bool ossimGpkgContentsRecord::init(
const std::string& tableName, ossim_int32 srs_id,
const ossimDpt& minPt, const ossimDpt& maxPt )
{
bool status = false;
if ( (minPt.hasNans() == false) && (maxPt.hasNans() == false) )
{
m_table_name = tableName;
m_data_type = "tiles";
m_identifier = "Raster Tiles for ";
m_identifier += tableName;
m_description = "Create by ossim gpkg writer.";
ossim_sqlite::getTime( m_last_change );
m_min_x = minPt.x;
m_min_y = minPt.y;
m_max_x = maxPt.x;
m_max_y = maxPt.y;
m_srs_id = srs_id;
status = true;
}
return status;
}
bool ossimGpkgContentsRecord::createTable( sqlite3* db )
{
bool status = false;
if ( db )
{
status = ossim_sqlite::tableExists( db, TABLE_NAME );
if ( !status )
{
std::ostringstream sql;
sql << "CREATE TABLE " << TABLE_NAME << " ( "
<< "table_name TEXT NOT NULL PRIMARY KEY, "
<< "data_type TEXT NOT NULL, "
<< "identifier TEXT UNIQUE, "
<< "description TEXT DEFAULT \"\", "
//---
// Requirement 13:
// Note: Spec changed to %fZ. No %f on linux but sqlite library handles.
// << "last_change DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')), "
//---
<< "last_change DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), "
<< "min_x DOUBLE, "
<< "min_y DOUBLE, "
<< "max_x DOUBLE, "
<< "max_y DOUBLE, "
<< "srs_id INTEGER, "
<< "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) "
<< "REFERENCES gpkg_spatial_ref_sys(srs_id)"
<< ")";
if ( ossim_sqlite::exec( db, sql.str() ) == SQLITE_DONE )
{
status = true;
}
}
}
return status;
}
bool ossimGpkgContentsRecord::insert( sqlite3* db )
{
bool status = false;
if ( db )
{
std::ostringstream sql;
sql << "INSERT INTO gpkg_contents VALUES ( "
<< "'" << m_table_name << "', "
<< "'" << m_data_type << "', "
<< "'" << m_identifier << "', "
<< "'" << m_description << "', "
<< "'" << m_last_change << "', "
<< std::setprecision(16)
<< m_min_x << ", "
<< m_min_y << ", "
<< m_max_x << ", "
<< m_max_y << ", "
<< m_srs_id
<< " )";
if ( ossim_sqlite::exec( db, sql.str() ) == SQLITE_DONE )
{
status = true;
}
}
return status;
}
void ossimGpkgContentsRecord::saveState( ossimKeywordlist& kwl,
const std::string& prefix ) const
{
std::string myPref = prefix.size() ? prefix : std::string("gpkg_contents.");
std::string value;
std::string key = "table_name";
kwl.addPair(myPref, key, m_table_name, true);
key = "data_type";
kwl.addPair(myPref, key, m_data_type, true);
key = "identifier";
kwl.addPair(myPref, key, m_identifier, true);
key = "description";
kwl.addPair(myPref, key, m_description, true);
key = "last_change";
kwl.addPair(myPref, key, m_last_change, true);
key = "min_x";
value = ossimString::toString(m_min_x, 15).string();
kwl.addPair(myPref, key, value, true);
key = "min_y";
value = ossimString::toString(m_min_y, 15).string();
kwl.addPair(myPref, key, value, true);
key = "max_x";
value = ossimString::toString(m_max_x, 15).string();
kwl.addPair(myPref, key, value, true);
key = "max_y";
value = ossimString::toString(m_max_y, 15).string();
kwl.addPair(myPref, key, value, true);
key = "srs_id";
value = ossimString::toString(m_srs_id).string();
kwl.addPair(myPref, key, value, true);
}
| 29.237805
| 98
| 0.517518
|
dardok
|
688536b49f91088c65f03ddfaee1716ac386734c
| 1,245
|
cpp
|
C++
|
GameFramework/Helper/HlTimer.cpp
|
GavWood/tutorials
|
d5140129b6acd6d61f6feedcd352c12e4ebabd40
|
[
"BSD-2-Clause"
] | 8
|
2017-10-26T14:26:55.000Z
|
2022-01-07T07:35:39.000Z
|
GameFramework/Helper/HlTimer.cpp
|
GavWood/tutorials
|
d5140129b6acd6d61f6feedcd352c12e4ebabd40
|
[
"BSD-2-Clause"
] | 1
|
2018-01-27T19:21:07.000Z
|
2018-01-31T13:55:09.000Z
|
GameFramework/Helper/HlTimer.cpp
|
GavWood/Game-Framework
|
d5140129b6acd6d61f6feedcd352c12e4ebabd40
|
[
"BSD-2-Clause"
] | 1
|
2021-07-21T17:37:33.000Z
|
2021-07-21T17:37:33.000Z
|
////////////////////////////////////////////////////////////////////////////////
// HlTimer
// Includes
#include "HlTimer.h"
#include "BtTime.h"
#include "BtString.h"
#include "ApConfig.h"
////////////////////////////////////////////////////////////////////////////////
// Constructor
HlTimer::HlTimer()
{
m_start = 0;
m_duration = 0;
}
////////////////////////////////////////////////////////////////////////////////
// IsReady
//static
BtBool HlTimer::IsReady()
{
BtFloat currentTime = BtTime::GetElapsedTimeInSeconds();
if( m_duration && (currentTime > m_start + m_duration) )
{
return BtTrue;
}
return BtFalse;
}
////////////////////////////////////////////////////////////////////////////////
// ResetTimer
void HlTimer::ResetTimer( BtFloat duration)
{
m_start = BtTime::GetElapsedTimeInSeconds();
m_duration = duration;
}
////////////////////////////////////////////////////////////////////////////////
// GetElapsedTime
//static
BtFloat HlTimer::GetElapsedTime()
{
BtFloat currentTime = BtTime::GetElapsedTimeInSeconds();
return currentTime - m_start;
}
////////////////////////////////////////////////////////////////////////////////
// GetStartTime
//static
BtFloat HlTimer::GetStartTime()
{
return m_start;
}
| 20.409836
| 80
| 0.434538
|
GavWood
|
68868c2d58a7267470ec9694c0eb658eb204202e
| 2,658
|
hpp
|
C++
|
inc/vpp/prediction.hpp
|
ezdayo/vpp
|
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
|
[
"MIT"
] | 1
|
2020-06-18T14:01:50.000Z
|
2020-06-18T14:01:50.000Z
|
inc/vpp/prediction.hpp
|
ezdayo/vpp
|
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
|
[
"MIT"
] | null | null | null |
inc/vpp/prediction.hpp
|
ezdayo/vpp
|
90d13ed9ab49ff0db7188ef72a89821f0c14a9bf
|
[
"MIT"
] | null | null | null |
/**
*
* @file vpp/prediction.hpp
*
* @brief This is the VPP prediction description file
*
* @details This file describes the structure of a prediction and adds a few
* methods to handle it. A prediction is basically a score, a list
* index and an object index within this list.
*
* This file is part of the VPP framework (see link).
*
* @author Olivier Stoltz-Douchet <ezdayo@gmail.com>
*
* @copyright (c) 2019-2020 Olivier Stoltz-Douchet
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/ezdayo/vpp
*
**/
#pragma once
#include <cstdint>
#include <set>
namespace VPP {
class Prediction final {
public:
Prediction() noexcept : score(-1), dataset(-1), id(-1) {}
Prediction(float score_, int16_t dataset_, int16_t id_) noexcept
: score(std::move(score_)), dataset(std::move(dataset_)),
id(std::move(id_)) {}
Prediction(int score_, int16_t dataset_, int16_t id_) noexcept
: score(static_cast<float>(score_)/100.0),
dataset(std::move(dataset_)), id(std::move(id_)) {}
static inline int32_t gid(int16_t dataset_, int16_t id_) {
return static_cast<int32_t>(dataset_)*65536 + id_;
}
inline int32_t gid() const noexcept {
return gid(dataset, id);
}
inline bool is_a(int16_t dataset_, int16_t id_) const noexcept {
return ((id_ == id) && (dataset_ == dataset));
}
inline bool is_in(const std::set<int32_t> &valid) const noexcept {
return (valid.find(gid()) != valid.end());
}
inline bool operator == (const Prediction &other) const noexcept {
return (score == other.score);
}
inline bool operator != (const Prediction &other) const noexcept {
return (score != other.score);
}
inline bool operator < (const Prediction &other) const noexcept {
return (score < other.score);
}
inline bool operator > (const Prediction &other) const noexcept {
return (score > other.score);
}
inline bool operator <= (const Prediction &other) const noexcept {
return (score <= other.score);
}
inline bool operator >= (const Prediction &other) const noexcept {
return (score >= other.score);
}
/**# Prediction score */
float score;
/**# Index of the dataset for the prediction */
int16_t dataset;
/**# Index in the dataset */
int16_t id;
};
} // namespace VPP
| 29.208791
| 78
| 0.582769
|
ezdayo
|
68881e7d66e313cd139022a82a3a89cbcf64aefe
| 2,911
|
cpp
|
C++
|
deps/vision/src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
|
MichaelJCaruso/vision-xa-nodejs-connect
|
ef13ccc2730bf1db07cb44106dfcfd020d843d82
|
[
"BSD-3-Clause"
] | 30
|
2016-10-07T15:23:35.000Z
|
2020-03-25T20:01:30.000Z
|
src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
|
MichaelJCaruso/vision-software-src-master
|
12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92
|
[
"BSD-3-Clause"
] | 30
|
2016-10-31T19:48:08.000Z
|
2021-04-28T01:31:53.000Z
|
software/src/master/src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
|
c-kuhlman/vision
|
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
|
[
"BSD-3-Clause"
] | 15
|
2016-10-07T16:44:13.000Z
|
2021-06-21T18:47:55.000Z
|
/***** Vca Sample Server *****/
/********************
***** System *****
********************/
#include "Vk.h"
/******************
***** Self *****
******************/
/************************
***** Supporting *****
************************/
#include "Vca_VOneAppMain_.h"
#include "Vca_VServerApplication.h"
#include "vca_samples_iechostring.h"
/*********************************
*********************************
***** *****
***** VcaSamples::ThisApp *****
***** *****
*********************************
*********************************/
namespace VcaSamples {
class ThisApp : public Vca::VServerApplication {
DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication);
// Construction
public:
ThisApp (Context *pContext);
// Destruction
private:
~ThisApp ();
// Roles
public:
using BaseClass::getRole;
//---> IEchoString Role
private:
Vca::VRole<ThisClass,IEchoString> m_pIEchoString;
public:
void getRole (IEchoString::Reference &rpRole) {
m_pIEchoString.getRole (rpRole);
}
// Role Callbacks
//---> IEchoString
public:
void Echo (
IEchoString *pRole, IVReceiver<VString const&> *pClient, VString const &rString
);
// Startup
private:
virtual bool start_() OVERRIDE;
};
}
/***************************
***************************
***** Run Time Type *****
***************************
***************************/
DEFINE_CONCRETE_RTT (VcaSamples::ThisApp);
/**************************
**************************
***** Construction *****
**************************
**************************/
VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIEchoString (this) {
}
/*************************
*************************
***** Destruction *****
*************************
*************************/
VcaSamples::ThisApp::~ThisApp () {
}
/***********************
***********************
***** Callbacks *****
***********************
***********************/
void VcaSamples::ThisApp::Echo (
IEchoString *pRole, IVReceiver<VString const&> *pClient, VString const &rString
) {
if (pClient)
pClient->OnData (rString);
}
/*********************
*********************
***** *****
***** Startup *****
***** *****
*********************
*********************/
bool VcaSamples::ThisApp::start_() {
if (BaseClass::start_() && !offerSelf ()) {
fprintf (stderr, "Usage: No address to offer object.\n");
setExitStatus (ErrorExitValue);
}
return isStarting ();
}
/**************************
**************************
***** Main Program *****
**************************
**************************/
int main (int argc, char *argv[]) {
Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv);
return iMain.processEvents ();
}
| 21.248175
| 96
| 0.40055
|
MichaelJCaruso
|
68899bb54200e7df5bcd9314f946c07d8e684b49
| 684
|
hpp
|
C++
|
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
|
NekoSilverFox/CPP
|
c6797264fceda4a65ac3452acca496e468d1365a
|
[
"Apache-2.0"
] | 5
|
2020-02-08T20:57:21.000Z
|
2021-12-23T06:24:41.000Z
|
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
|
NekoSilverFox/CPP
|
c6797264fceda4a65ac3452acca496e468d1365a
|
[
"Apache-2.0"
] | 2
|
2020-03-02T14:44:55.000Z
|
2020-11-11T16:25:33.000Z
|
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
|
NekoSilverFox/CPP
|
c6797264fceda4a65ac3452acca496e468d1365a
|
[
"Apache-2.0"
] | 4
|
2020-09-27T17:30:03.000Z
|
2022-02-16T09:48:23.000Z
|
#ifndef SHAPE_H
#define SHAPE_H
#include <memory>
namespace gadzhiev
{
struct point_t;
struct rectangle_t;
class Shape
{
public:
typedef std::shared_ptr<const Shape> ConstShapePtr;
typedef std::shared_ptr<Shape> ShapePtr;
virtual ~Shape() = default;
virtual double getArea() const = 0;
virtual rectangle_t getFrameRect() const = 0;
virtual void move(const point_t& point) = 0;
virtual void move(double dx, double dy) = 0;
virtual void scale(double coefficient) = 0;
virtual void rotate(double degrees) = 0;
virtual point_t getCenter() const = 0;
virtual void printNameAndParametersOfShape() const = 0;
};
}
#endif
| 21.375
| 59
| 0.685673
|
NekoSilverFox
|
688a49523e06e10ee9fc273c7239431b67069106
| 911
|
cpp
|
C++
|
Libraries/plist/Sources/Format/ABPCommon.cpp
|
kolinkrewinkel/xcbuild
|
05ac2e574d96a3edff08df4d87b49f39931043f1
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
Libraries/plist/Sources/Format/ABPCommon.cpp
|
kolinkrewinkel/xcbuild
|
05ac2e574d96a3edff08df4d87b49f39931043f1
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
Libraries/plist/Sources/Format/ABPCommon.cpp
|
kolinkrewinkel/xcbuild
|
05ac2e574d96a3edff08df4d87b49f39931043f1
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
/**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <plist/Format/ABPCoderPrivate.h>
#include <cstring>
size_t
ABPGetObjectsCount(ABPContext *context)
{
return (context != NULL ? context->trailer.objectsCount : 0);
}
void
_ABPContextFree(ABPContext *context)
{
if (context->objects != NULL) {
for (size_t n = 0; n < context->trailer.objectsCount; n++) {
if (context->objects[n] != NULL) {
context->objects[n]->release();
}
}
delete[] context->objects;
}
if (context->offsets != NULL) {
delete[] context->offsets;
}
memset(context, 0, sizeof(*context));
}
| 23.973684
| 76
| 0.641054
|
kolinkrewinkel
|
688bad96be36f936d263c3eba93553365283e53f
| 4,767
|
hpp
|
C++
|
src/controller/DualAdvancedRunner.hpp
|
psettle/podracing
|
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
|
[
"MIT"
] | 1
|
2021-09-25T18:18:14.000Z
|
2021-09-25T18:18:14.000Z
|
src/controller/DualAdvancedRunner.hpp
|
psettle/podracing
|
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
|
[
"MIT"
] | null | null | null |
src/controller/DualAdvancedRunner.hpp
|
psettle/podracing
|
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
|
[
"MIT"
] | null | null | null |
#ifndef DUALADVANCEDRUNNER_HPP
#define DUALADVANCEDRUNNER_HPP
#include <math.h>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include "GameIO.hpp"
#include "IPlayer.hpp"
#include "NeuralNetwork.hpp"
#include "Vec2.hpp"
class DualAdvancedRunner : public IPlayer {
public:
static unsigned int const kNextCheckpoints = 2;
struct PodTracker {
PodData input = PodData();
unsigned int last_checkpoint = 0;
unsigned int laps = 0;
};
struct InputCheckpoint {
double distance;
double direction;
};
struct InputVelocity {
double magnitude;
double direction;
};
struct InputOtherPod {
InputCheckpoint relative_position;
InputVelocity relative_velocity;
// InputCheckpoint next_checkpoints[kNextCheckpoints];
};
struct InputPod {
InputCheckpoint next_checkpoints[kNextCheckpoints];
InputVelocity velocity;
// InputOtherPod ally_pod;
// InputOtherPod leading_enemy_pod;
// InputOtherPod trailing_enemy_pod;
};
struct NetworkInput {
InputPod pod;
};
struct OutputPod {
double thrust;
double direction;
double should_shield;
double should_boost;
};
struct NetworkOutput {
OutputPod pod;
};
static unsigned int const kInputCount = sizeof(NetworkInput) / sizeof(double);
static unsigned int const kOutputCount = sizeof(NetworkOutput) / sizeof(double);
DualAdvancedRunner(NeuralNetwork& core) : boosts_left_(1), network_(core) {}
void SetStreams(std::istream& input, std::ostream& output) override {
input_ = &input;
output_ = &output;
};
void Setup() override { map_data_ = std::make_unique<MapData>(*input_); }
void Turn() override {
ReadInput();
std::vector<PodTracker const*> me = {&pods_[0], &pods_[1]};
std::vector<PodTracker const*> op = {&pods_[2], &pods_[3]};
unsigned int lead_op_pod = GetLeadPod(op);
PodTracker const& op_lead = lead_op_pod == 0 ? pods_[2] : pods_[3];
PodTracker const& op_trail = lead_op_pod == 1 ? pods_[2] : pods_[3];
NeuralNetwork::Activations in(kInputCount);
NetworkInput* input = reinterpret_cast<NetworkInput*>(in.data());
GetNetworkInput(*input, pods_[0].input, pods_[1].input, op_lead.input, op_trail.input);
network_.SetInput(in);
NeuralNetwork::Activations const* out0 = &network_.GetOutput();
NetworkOutput const* output = reinterpret_cast<NetworkOutput const*>(out0->data());
WriteNetworkOutput(*output, &me[0]->input);
input = reinterpret_cast<NetworkInput*>(in.data());
GetNetworkInput(*input, pods_[1].input, pods_[0].input, op_lead.input, op_trail.input);
network_.SetInput(in);
out0 = &network_.GetOutput();
output = reinterpret_cast<NetworkOutput const*>(out0->data());
WriteNetworkOutput(*output, &me[1]->input);
EndInput();
}
private:
void ReadInput() {
pods_[0].input = PodData(*input_, 0, Owner::Me);
pods_[1].input = PodData(*input_, 1, Owner::Me);
pods_[2].input = PodData(*input_, 0, Owner::Opponent);
pods_[3].input = PodData(*input_, 1, Owner::Opponent);
for (auto& pod : pods_) {
if (pod.input.next_checkpoint_id < static_cast<int>(pod.last_checkpoint)) {
pod.last_checkpoint++;
}
}
}
void EndInput() {
for (auto& pod : pods_) {
pod.last_checkpoint = pod.input.next_checkpoint_id;
}
first_turn_latch_ = false;
}
static double constexpr kMaxDistance = 16000.0;
static double constexpr kMaxSpeed = 1300.0;
void GetNetworkInput(NetworkInput& input, PodData const& pod, PodData const& ally,
PodData const& lead, PodData const& trail);
void GetPodInput(InputPod& input, PodData const& pod, PodData const& ally,
std::vector<PodData const*> const& op);
static double constexpr kAbilityThresh = 0.0;
void WriteNetworkOutput(NetworkOutput const& output, PodData const* pod);
void WritePodOutput(OutputPod const& output, PodData const& pod);
static double NormalizeAngle(double angle);
double PodAngle(PodData const& pod);
void GetNextCheckpoints(InputCheckpoint* checkpoints, PodData const& from,
PodData const& perspective);
void GetNextCheckpoint(InputCheckpoint& checkpoint, Vec2 const& next, PodData const& from);
void GetVelocity(InputVelocity& velocity, PodData const& of, Vec2 const& ref_velocity,
double ref_angle);
void GetOtherPod(InputOtherPod& output, PodData const& perspective, PodData const& other);
unsigned int GetLeadPod(std::vector<PodTracker const*> pods);
int boosts_left_;
bool first_turn_latch_ = true;
PodTracker pods_[4];
std::unique_ptr<MapData> map_data_;
std::istream* input_;
std::ostream* output_;
NeuralNetwork& network_;
};
#endif
| 32.428571
| 93
| 0.696665
|
psettle
|
68932b764c381906b5d31e306e63332ed7f38ca8
| 10,499
|
cpp
|
C++
|
drishti/camerapathnode.cpp
|
shouhengli/drishti
|
46558d12adcc1d365b7e2125d28190e3be2181c3
|
[
"MIT"
] | 118
|
2016-11-01T06:01:44.000Z
|
2022-03-30T05:20:19.000Z
|
drishti/camerapathnode.cpp
|
shouhengli/drishti
|
46558d12adcc1d365b7e2125d28190e3be2181c3
|
[
"MIT"
] | 56
|
2016-09-30T09:29:36.000Z
|
2022-03-31T17:15:32.000Z
|
drishti/camerapathnode.cpp
|
shouhengli/drishti
|
46558d12adcc1d365b7e2125d28190e3be2181c3
|
[
"MIT"
] | 28
|
2016-07-31T23:48:51.000Z
|
2021-05-25T05:32:47.000Z
|
#include "camerapathnode.h"
CameraPathNode::CameraPathNode(Vec pos, Quaternion rot)
{
m_mf = new ManipulatedFrame();
// disable camera manipulation by mouse
m_mf->removeFromMouseGrabberPool();
m_mf->setPosition(pos);
m_mf->setOrientation(rot);
m_constraints = new LocalConstraint();
m_constraints->setTranslationConstraintType(AxisPlaneConstraint::FREE);
m_mf->setConstraint(m_constraints);
m_markForDelete = false;
connect(m_mf, SIGNAL(modified()),
this, SLOT(nodeModified()));
}
void
CameraPathNode::nodeModified()
{
emit modified();
}
bool CameraPathNode::markedForDeletion() { return m_markForDelete; }
Vec CameraPathNode::position() { return m_mf->position(); }
void CameraPathNode::setPosition(Vec pos) { m_mf->setPosition(pos); }
Quaternion CameraPathNode::orientation() { return m_mf->orientation(); }
void CameraPathNode::setOrientation(Quaternion rot) { m_mf->setOrientation(rot); }
int
CameraPathNode::keyPressEvent(QKeyEvent *event, bool &lookFrom)
{
lookFrom = false;
if (m_mf->grabsMouse())
{
if (event->key() == Qt::Key_Space)
{
lookFrom = true;
return 1;
}
else if (event->modifiers() & Qt::ShiftModifier)
{ // set rotational constraints
if (event->key() == Qt::Key_X)
{
m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setRotationConstraintDirection(Vec(1,0,0));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_Y)
{
m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setRotationConstraintDirection(Vec(0,1,0));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_Z)
{
m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setRotationConstraintDirection(Vec(0,0,1));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_W)
{
m_constraints->setRotationConstraintType(AxisPlaneConstraint::FREE);
m_mf->setConstraint(m_constraints);
return 1;
}
}
else if (event->modifiers() == Qt::NoModifier)
{ // set translational constraints
if (event->key() == Qt::Key_Delete ||
event->key() == Qt::Key_Backspace ||
event->key() == Qt::Key_Backtab)
{
m_markForDelete = true;
}
else if (event->key() == Qt::Key_X)
{
m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setTranslationConstraintDirection(Vec(1,0,0));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_Y)
{
m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setTranslationConstraintDirection(Vec(0,1,0));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_Z)
{
m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS);
m_constraints->setTranslationConstraintDirection(Vec(0,0,1));
m_mf->setConstraint(m_constraints);
return 1;
}
else if (event->key() == Qt::Key_W)
{
m_constraints->setTranslationConstraintType(AxisPlaneConstraint::FREE);
m_mf->setConstraint(m_constraints);
return 1;
}
}
}
return 0;
}
void
CameraPathNode::draw(float widgetSize)
{
glPushMatrix();
glMultMatrixd(m_mf->matrix());
float scale = widgetSize;
if (m_mf->grabsMouse())
scale = widgetSize * 1.5;
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glLineWidth(1);
if (m_mf->grabsMouse())
glColor3f(1, 1, 0);
else
glColor3f(0.6f, 1, 1);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(-scale, -scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(-scale, scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(scale, scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(scale, -scale, -scale);
glEnd();
glBegin(GL_LINE_STRIP);
glVertex3f(-scale, -scale, -scale);
glVertex3f(-scale, scale, -scale);
glVertex3f(scale, scale, -scale);
glVertex3f(scale, -scale, -scale);
glVertex3f(-scale, -scale, -scale);
glEnd();
//glLineWidth(3);
if (m_mf->grabsMouse())
glColor3f(0.5, 1, 0.5f);
else
glColor3f(1, 1, 0.8f);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(-scale, -scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(-scale, scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(scale, scale, -scale);
glVertex3f(0, 0, 0);
glVertex3f(scale, -scale, -scale);
glEnd();
glBegin(GL_LINE_STRIP);
glVertex3f(-scale, -scale, -scale);
glVertex3f(-scale, scale, -scale);
glVertex3f(scale, scale, -scale);
glVertex3f(scale, -scale, -scale);
glVertex3f(-scale, -scale, -scale);
glEnd();
// draw lookup vector
float arrowscale = scale/3;
glBegin(GL_QUADS);
glVertex3f(-arrowscale/2, scale, -scale);
glVertex3f(-arrowscale/2, scale+arrowscale/2, -scale);
glVertex3f( arrowscale/2, scale+arrowscale/2, -scale);
glVertex3f( arrowscale/2, scale, -scale);
glEnd();
glBegin(GL_TRIANGLES);
glVertex3f(-arrowscale/2, scale+arrowscale/2, -scale);
glVertex3f( arrowscale/2, scale+arrowscale/2, -scale);
glVertex3f( 0, scale+arrowscale, -scale);
glEnd();
glEnable(GL_LIGHTING);
glColor3f(1.0f, 0.5f, 0.2f);
if (m_constraints->translationConstraintType() == AxisPlaneConstraint::AXIS)
{
Vec dir = m_constraints->translationConstraintDirection();
if (dir.norm() > 0)
dir.normalize();
if ((dir-Vec(0,0,1)).norm() < 0.001)
{
dir *= scale;
QGLViewer::drawArrow(Vec(0,0,-scale),
dir*0.5f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(Vec(0,0,-scale),
-dir*0.5f+Vec(0,0,-scale),
0.5f, 12);
}
else
{
dir *= scale;
QGLViewer::drawArrow(dir+Vec(0,0,-scale),
dir*1.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(-dir+Vec(0,0,-scale),
-dir*1.3f+Vec(0,0,-scale),
0.5f, 12);
}
}
else if (m_constraints->translationConstraintType() == AxisPlaneConstraint::FREE)
{
Vec Xaxis, Yaxis, Zaxis;
Xaxis = scale*Vec(1,0,0);
Yaxis = scale*Vec(0,1,0);
Zaxis = scale*Vec(0,0,1);
QGLViewer::drawArrow( Xaxis+Vec(0,0,-scale),
Xaxis*1.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(-Xaxis+Vec(0,0,-scale),
-Xaxis*1.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow( Yaxis+Vec(0,0,-scale),
Yaxis*1.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(-Yaxis+Vec(0,0,-scale),
-Yaxis*1.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(Vec(0,0,0)+Vec(0,0,-scale),
Zaxis*0.3f+Vec(0,0,-scale),
0.5f, 12);
QGLViewer::drawArrow(Vec(0,0,0)+Vec(0,0,-scale),
-Zaxis*0.3f+Vec(0,0,-scale),
0.5f, 12);
}
glDisable(GL_LIGHTING);
glColor3f(0.3f, 0.8f, 0.6f);
if (m_constraints->rotationConstraintType() == AxisPlaneConstraint::AXIS)
{
Vec a1, a2;
Vec dir = m_constraints->rotationConstraintDirection();
if (dir.norm() > 0)
dir.normalize();
a1 = dir.orthogonalVec();
a2 = dir^a1;
dir *= scale;
a1 *= 0.2f*scale;
a2 *= 0.2f*scale;
int nticks;
float angle, astep;
nticks = 50;
astep = 6.28f/nticks;
Vec vp[100];
angle = 0.0f;
for(int t=0; t<=nticks; t++)
{
vp[t] = a1*cos(angle) + a2*sin(angle);
angle += astep;
}
Vec shift = Vec(0,0,-scale);
shift += 0.2f*dir;
//----------------------------
glColor3f(1, 1, 1);
glLineWidth(1);
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
Vec v = vp[t] + shift;
glVertex3f(v.x, v.y, v.z);
}
glEnd();
glLineWidth(3);
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
float frc = (float)t/(float)nticks;
Vec v = vp[t] + shift;
glColor3f(1-frc, 0.5-0.5*frc, 1);
glVertex3f(v.x, v.y, v.z);
}
glEnd();
// draw arrows
glColor3f(0.9f, 0.8f, 0.6f);
Vec v0, v1, v2;
glBegin(GL_TRIANGLES);
for(int t=0; t<nticks-4; t+=5)
{
v0 = vp[t]+shift;
v1 = vp[t+2]+shift+0.02f*dir;
v2 = vp[t+2]+shift-0.02f*dir;
glVertex3f(v0.x, v0.y, v0.z);
glVertex3f(v1.x, v1.y, v1.z);
glVertex3f(v2.x, v2.y, v2.z);
}
glEnd();
//----------------------------
shift = Vec(0,0,-scale);
shift -= 0.2f*dir;
//----------------------------
glColor3f(1, 1, 1);
glLineWidth(1);
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
Vec v = vp[t] + shift;
glVertex3f(v.x, v.y, v.z);
}
glEnd();
glLineWidth(3);
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
float frc = (float)t/(float)nticks;
Vec v = vp[t] + shift;
glColor3f(1-frc, 0.5-0.5*frc, 1);
glVertex3f(v.x, v.y, v.z);
}
glEnd();
// draw arrows
glColor3f(0.9f, 0.8f, 0.6f);
glBegin(GL_TRIANGLES);
for(int t=0; t<nticks-4; t+=5)
{
v0 = vp[t+2]+shift;
v1 = vp[t]+shift+0.02f*dir;
v2 = vp[t]+shift-0.02f*dir;
glVertex3f(v0.x, v0.y, v0.z);
glVertex3f(v1.x, v1.y, v1.z);
glVertex3f(v2.x, v2.y, v2.z);
}
glEnd();
//----------------------------
}
else if (m_constraints->rotationConstraintType() == AxisPlaneConstraint::FREE)
{
int nticks;
float angle, astep;
nticks = 50;
astep = 6.28f/nticks;
angle = 0.0f;
glLineWidth(1);
glColor3f(0.7f, 0.7f, 0.7f);
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
float frc = (float)t/(float)nticks;
Vec v, v1, v2;
v = Vec(cos(angle),sin(angle), 0);
v *= 0.5f*scale;
angle += astep;
glVertex3f(v.x, v.y, v.z);
}
glEnd();
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
float frc = (float)t/(float)nticks;
Vec v, v1, v2;
v = Vec(cos(angle),sin(angle), 0);
v *= 0.5f*scale;
angle += astep;
glVertex3f(v.x, v.z, v.y);
}
glEnd();
glBegin(GL_LINE_STRIP);
for(int t=0; t<=nticks; t++)
{
float frc = (float)t/(float)nticks;
Vec v, v1, v2;
v = Vec(cos(angle),sin(angle), 0);
v *= 0.5f*scale;
angle += astep;
glVertex3f(v.z, v.x, v.y);
}
glEnd();
}
glLineWidth(1);
glPopMatrix();
}
| 25.057279
| 83
| 0.590151
|
shouhengli
|
689f57399ac5c28a6bed7bbb043bcacfc45adc8d
| 1,023
|
cpp
|
C++
|
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
|
alaxion/Learning
|
4b12b1603419252103cd933fdbfc4b2faffb6d00
|
[
"MIT"
] | null | null | null |
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
|
alaxion/Learning
|
4b12b1603419252103cd933fdbfc4b2faffb6d00
|
[
"MIT"
] | null | null | null |
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
|
alaxion/Learning
|
4b12b1603419252103cd933fdbfc4b2faffb6d00
|
[
"MIT"
] | null | null | null |
// Exercise3.36.cpp
// Ad
// Write a program to compare two arrays for equality, then write a similar to compare vectors.
#include <iostream>
#include <vector>
#include <iterator>
using std::cin;
using std::cout;
using std::endl;
int main()
{
// to compare two arrays
int arr1[10]{}, arr2[10]{};
int *pa1{arr1}, *pa2{arr2};
for (; pa1 != std::end(arr1) && pa2 != std::end(arr2); ++pa1, ++pa2)
{
if (*pa1 != *pa2)
break;
}
if (pa1 != std::end(arr1))
{
if (*pa1 > *pa2)
cout << "arr1 > arr2" << endl;
else
cout << "arr1 < arr2" << endl;
}
else
{
cout << "arr1 == arr2" << endl;
}
// to compare two vectors
std::vector<int> vec1{}, vec2{};
if (vec1 > vec2)
{
cout << "vec1 > vec2" << endl;
}
else if (vec1 < vec2)
{
cout << "vec1 < vec2" << endl;
}
else
{
cout << "vec1 == vec2" << endl;
}
// pause
cin.get();
return 0;
}
| 20.058824
| 96
| 0.475073
|
alaxion
|
68a223fcb0bad703e33b65855153863e1d03fe20
| 542
|
cpp
|
C++
|
test/main.cpp
|
chenxu2048/DockerClientpp
|
81792fb0d84028b059983e1a08f12edf6e8c6b32
|
[
"MIT"
] | 5
|
2017-05-23T16:32:15.000Z
|
2019-02-16T14:27:51.000Z
|
test/main.cpp
|
chenxu2048/DockerClientpp
|
81792fb0d84028b059983e1a08f12edf6e8c6b32
|
[
"MIT"
] | 5
|
2019-07-13T23:14:52.000Z
|
2019-07-16T20:46:53.000Z
|
test/main.cpp
|
fedemengo/DockerClientpp
|
a83a1a992f081b5d25dccc2b9530308105e5c9c4
|
[
"MIT"
] | 4
|
2017-11-14T14:00:58.000Z
|
2020-07-23T07:16:01.000Z
|
#include "gtest/gtest.h"
class GlobalEnv : public ::testing::Environment {
public:
virtual void SetUp() {
if (std::system("docker pull busybox:1.26")) {
throw std::runtime_error("Cannot pull busybox");
}
std::system("docker run -dt --name test busybox:1.26 > /dev/null 2>&1");
}
virtual void TearDown() {
std::system("docker rm -f test > /dev/null 2>&1");
}
};
int main(int argc, char *argv[]) {
AddGlobalTestEnvironment(new GlobalEnv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.809524
| 76
| 0.645756
|
chenxu2048
|
68a49f934efc4cfdc2f5e354471ec32d42b79391
| 10,418
|
cpp
|
C++
|
crud-example/request_processor.cpp
|
Stiffstream/restinio-crud-example
|
3e3e3a859b9743a870b20dda7da14360ccdae3ce
|
[
"BSD-3-Clause"
] | 4
|
2019-10-07T21:23:55.000Z
|
2020-02-05T16:10:57.000Z
|
crud-example/request_processor.cpp
|
Stiffstream/restinio-crud-example
|
3e3e3a859b9743a870b20dda7da14360ccdae3ce
|
[
"BSD-3-Clause"
] | 1
|
2020-02-04T05:14:23.000Z
|
2020-02-04T09:45:17.000Z
|
crud-example/request_processor.cpp
|
Stiffstream/restinio-crud-example
|
3e3e3a859b9743a870b20dda7da14360ccdae3ce
|
[
"BSD-3-Clause"
] | 1
|
2020-02-05T16:11:00.000Z
|
2020-02-05T16:11:00.000Z
|
#include "request_processor.hpp"
#include <restinio/helpers/http_field_parsers/content-type.hpp>
#include <restinio/helpers/file_upload.hpp>
#include <fmt/format.h>
#include <stdexcept>
namespace crud_example
{
namespace errors
{
const int unknow_error = -1;
const int json_dto_error = 1;
const int sqlite_error = 2;
const int invalid_pet_id = 3;
const int invalid_request = 4;
} /* namespace errors */
// Type of object to be returned in a HTTP-response for a failed request.
struct failure_description_t
{
int m_error_code;
std::string m_description;
template<typename Json_Io>
void json_io(Json_Io & io)
{
io & json_dto::mandatory("code", m_error_code)
& json_dto::mandatory("description", m_description);
}
};
// A type of exception to be thrown in the case of some failure
// during processing of a request.
//
// NOTE: this error is related to some business-logic problem.
class request_processing_failure_t : public std::runtime_error
{
restinio::http_status_line_t m_response_status;
failure_description_t m_failure_description;
public:
request_processing_failure_t(
restinio::http_status_line_t response_status,
failure_description_t failure_description)
: std::runtime_error("request processing failure")
, m_response_status{std::move(response_status)}
, m_failure_description{std::move(failure_description)}
{}
const auto &
response_status() const noexcept
{
return m_response_status;
}
const auto &
failure_description() const noexcept
{
return m_failure_description;
}
};
namespace
{
// Helper function for wrapping request processing routine and making
// the response in dependency of processing result.
template<typename F>
void
wrap_request_processing(
const restinio::request_handle_t & req,
F && functor)
{
std::string response_body;
auto response_status = restinio::status_ok();
try
{
response_body = json_dto::to_json(functor());
}
catch(const request_processing_failure_t & x)
{
response_status = x.response_status();
response_body = json_dto::to_json(x.failure_description());
}
catch(...)
{
response_status = restinio::status_internal_server_error();
response_body = json_dto::to_json(
failure_description_t{
errors::unknow_error,
"unexpected application failure"});
}
req->create_response(response_status)
.append_header_date_field()
.append_header(restinio::http_field::content_type, "application/json")
.set_body(response_body)
.done();
}
// Helper function for wrapping actual business-logic code and intercept
// errors related to JSON-processing, interactions with DB and so on.
// All such errors are converted into request_processing_failure_t.
template<typename F>
auto
wrap_business_logic_action(F && functor)
{
try
{
return functor();
}
catch(const json_dto::ex_t & x)
{
throw request_processing_failure_t(
restinio::status_bad_request(),
failure_description_t{
errors::json_dto_error,
fmt::format("json-related-error: {}", x.what())
});
}
catch(const SQLite::Exception & x)
{
throw request_processing_failure_t(
restinio::status_internal_server_error(),
failure_description_t{
errors::sqlite_error,
fmt::format("sqlite-related-error: error_code={}, "
"ext_error_code={}, desc='{}'",
x.getErrorCode(),
x.getExtendedErrorCode(),
x.getErrorStr())
});
}
}
enum class create_new_mode_t
{
single,
batch
};
restinio::expected_t<create_new_mode_t, request_processing_failure_t>
detect_create_new_mode(
const restinio::request_handle_t & req)
{
const auto unexpected = [](const char * msg) {
return restinio::make_unexpected(request_processing_failure_t{
restinio::status_bad_request(),
failure_description_t{errors::invalid_request, msg}
});
};
// Content-Type HTTP-field should be present.
const auto content_type_raw = req->header().opt_value_of(
restinio::http_field::content_type);
if(!content_type_raw)
return unexpected("Content-Type HTTP-field is absent");
// Content-Type should have right format.
namespace hfp = restinio::http_field_parsers;
const auto content_type = hfp::content_type_value_t::try_parse(*content_type_raw);
if(!content_type)
return unexpected("unable to parse Content-Type HTTP-field");
// If Content-Type is "application/json" then we assume that it is
// a request for addition of single pet.
if("application" == content_type->media_type.type &&
"json" == content_type->media_type.subtype)
return create_new_mode_t::single;
// If Content-Type if "multipart/form-data" then we assume that it is
// a request for batch addition of new pets.
if("multipart" == content_type->media_type.type &&
"form-data" == content_type->media_type.subtype)
return create_new_mode_t::batch;
return unexpected("unsupported value of Content-Type");
}
} /* namespace anonymous */
request_processor_t::request_processor_t(db_layer_t & db)
: m_db{db}
{
}
void
request_processor_t::on_create_new_pet(
const restinio::request_handle_t & req)
{
auto mode = detect_create_new_mode(req);
if(mode)
{
switch(*mode)
{
case create_new_mode_t::single:
wrap_request_processing(req, [&] { return create_new_pet(req); });
break;
case create_new_mode_t::batch:
wrap_request_processing(req, [&] { return batch_create_new_pets(req); });
break;
}
}
else
{
const auto & error = mode.error();
req->create_response(error.response_status())
.append_header_date_field()
.append_header(restinio::http_field::content_type, "application/json")
.set_body(json_dto::to_json(error.failure_description()))
.done();
}
}
void
request_processor_t::on_get_all_pets(
const restinio::request_handle_t & req)
{
wrap_request_processing(req, [&] { return get_all_pets(); });
}
void
request_processor_t::on_get_specific_pet(
const restinio::request_handle_t & req,
pet_id_t pet_id)
{
wrap_request_processing(req, [&] { return get_specific_pet(pet_id); });
}
void
request_processor_t::on_patch_specific_pet(
const restinio::request_handle_t & req,
pet_id_t pet_id)
{
wrap_request_processing(req, [&] { return patch_specific_pet(req, pet_id); });
}
void
request_processor_t::on_delete_specific_pet(
const restinio::request_handle_t & req,
pet_id_t pet_id)
{
wrap_request_processing(req, [&] { return delete_specific_pet(pet_id); });
}
void
request_processor_t::on_make_batch_upload_form(
const restinio::request_handle_t & req)
{
req->create_response()
.append_header_date_field()
.append_header(restinio::http_field::content_type, "text/html; charset=utf-8")
.set_body(
R"---(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select file with batch info of new pets</title>
</head>
<body>
<p>Please select file to be uploaded to server.</p>
<form method="post" action="http://localhost:8080/all/v1/pets" enctype="multipart/form-data">
<p><input type="file" name="file" id="file"></p>
<p><button type="submit">Submit</button></p>
</form>
</body>
</html>
)---"
)
.done();
}
model::pet_identity_t
request_processor_t::create_new_pet(
const restinio::request_handle_t & req)
{
return wrap_business_logic_action([&] {
return model::pet_identity_t{
m_db.create_new_pet(
json_dto::from_json<model::pet_without_id_t>(req->body()))
};
});
}
model::bunch_of_pet_ids_t
request_processor_t::batch_create_new_pets(
const restinio::request_handle_t & req)
{
using namespace restinio::file_upload;
return wrap_business_logic_action([&]() {
// Content of file with new pets should be found in
// the request's body.
//
// NOTE: it's safe to store reference to uploaded file's content
// as string_view because uploaded_content won't outlive the
// request object with the actual uploaded data.
//
restinio::string_view_t uploaded_content;
const auto result = enumerate_parts_with_files(*req,
[this, &uploaded_content](part_description_t part) {
if("file" == part.name)
{
uploaded_content = part.body;
return handling_result_t::stop_enumeration;
}
else
return handling_result_t::continue_enumeration;
});
if(!result || uploaded_content.empty())
// There is no uploaded file or request's body has invalid format.
throw request_processing_failure_t(
restinio::status_bad_request(),
failure_description_t{
errors::invalid_request,
"no file with new pets found"
});
// The content of uploaded file should be parsed.
const auto pets = json_dto::from_json<model::bunch_of_pets_without_id_t>(
json_dto::make_string_ref(
uploaded_content.data(), uploaded_content.size()));
return m_db.create_bunch_of_pets(pets);
});
}
model::all_pets_t
request_processor_t::get_all_pets()
{
return wrap_business_logic_action([&] {
return m_db.get_all_pets();
});
}
model::pet_with_id_t
request_processor_t::get_specific_pet(
pet_id_t pet_id)
{
return wrap_business_logic_action([&] {
auto pet = m_db.get_pet(pet_id);
if(!pet)
throw request_processing_failure_t(
restinio::status_not_found(),
failure_description_t{
errors::invalid_pet_id,
fmt::format("pet with this ID not found, ID={}", pet_id)
});
return std::move(*pet);
});
}
model::pet_identity_t
request_processor_t::patch_specific_pet(
const restinio::request_handle_t & req,
pet_id_t pet_id)
{
return wrap_business_logic_action([&] {
const auto update_result = m_db.update_pet(
pet_id,
json_dto::from_json<model::pet_without_id_t>(req->body()));
if(db_layer_t::update_result_t::updated != update_result)
throw request_processing_failure_t(
restinio::status_not_found(),
failure_description_t{
errors::invalid_pet_id,
fmt::format("pet with this ID not found, ID={}", pet_id)
});
return model::pet_identity_t{pet_id};
});
}
model::pet_identity_t
request_processor_t::delete_specific_pet(
pet_id_t pet_id)
{
return wrap_business_logic_action([&] {
const auto delete_result = m_db.delete_pet(pet_id);
if(db_layer_t::delete_result_t::deleted != delete_result)
throw request_processing_failure_t(
restinio::status_not_found(),
failure_description_t{
errors::invalid_pet_id,
fmt::format("pet with this ID not found, ID={}", pet_id)
});
return model::pet_identity_t{pet_id};
});
}
} /* namespace crud_example */
| 25.98005
| 93
| 0.727683
|
Stiffstream
|
68a4dc075d7caec1988290fd3a4cc07c184c3c83
| 862
|
cpp
|
C++
|
Regex/Problem27/main.cpp
|
akaseon/ModernCppChallengeStudy
|
1630f8cf5b3656171ee656738a908619cee6e718
|
[
"MIT"
] | null | null | null |
Regex/Problem27/main.cpp
|
akaseon/ModernCppChallengeStudy
|
1630f8cf5b3656171ee656738a908619cee6e718
|
[
"MIT"
] | null | null | null |
Regex/Problem27/main.cpp
|
akaseon/ModernCppChallengeStudy
|
1630f8cf5b3656171ee656738a908619cee6e718
|
[
"MIT"
] | null | null | null |
//#include <gsl/gsl>
#include <vector>
#include <string>
#include <iostream>
std::vector<std::string> splittingString( std::string aFrom,
std::string aDelimiter )
{
std::vector<std::string> sTo;
char * sToken = NULL;
sToken = std::strtok( const_cast<char*>( aFrom.c_str() ),
aDelimiter.c_str() );
while( sToken != NULL )
{
sTo.push_back( sToken );
sToken = std::strtok( NULL, aDelimiter.c_str() );
}
return sTo;
}
int main(int argc, char* argv[])
{
std::string sString( "this,is.a sample!!" );
std::string sDelimiter( ",.! ");
std::vector<std::string> sResult;
sResult = splittingString( sString, sDelimiter );
for( auto sToken: sResult )
std::cout << sToken << "\n";
return 0;
}
| 23.297297
| 68
| 0.533643
|
akaseon
|
68a4e871e0fe4dbd179de98e9eb77f3df31dcdd0
| 795
|
cpp
|
C++
|
Game/Sources/State/PausedState.cpp
|
YvesHenri/Chico
|
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
|
[
"MIT"
] | 6
|
2017-01-09T13:19:56.000Z
|
2021-11-15T11:18:35.000Z
|
Game/Sources/State/PausedState.cpp
|
YvesHenri/Chico
|
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
|
[
"MIT"
] | null | null | null |
Game/Sources/State/PausedState.cpp
|
YvesHenri/Chico
|
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
|
[
"MIT"
] | null | null | null |
#include "../../Includes/State/PausedState.h"
PausedState::PausedState()
{
overlap = sf::RectangleShape(sf::Vector2f(800.f, 600.f));
overlap.setFillColor(sf::Color(0, 0, 0, 185));
}
void PausedState::onEnter()
{
WARN("-----> Paused");
}
void PausedState::onLeave()
{
WARN("<----- Paused");
}
void PausedState::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
/*
// Draw the previous state first
if (m_previous) {
m_previous->draw(target, states);
}
*/
// The overlap rectangle has to be drawn using the fixed view
sf::View fixed = target.getDefaultView();
sf::View active = target.getView();
target.setView(fixed);
target.draw(overlap, states);
target.setView(active);
}
sts::StateResult PausedState::update(float dt)
{
return sts::StateResult::Running;
}
| 19.875
| 79
| 0.68805
|
YvesHenri
|
68ae2dba87fdef7d2b77799274d10e9e024b8dd3
| 1,280
|
cpp
|
C++
|
Onegin/sorting.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
Onegin/sorting.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
Onegin/sorting.cpp
|
Great1ng/Huawei_Tasks
|
21f855f30df9806f81d5cedf8cd314a633174be1
|
[
"CC0-1.0"
] | null | null | null |
#include "sorting.h"
void mergesort(void *base, size_t count, size_t type, comparator comp) {
if (count == 1) return;
char *bt_base = (char *) base;
size_t lcount = count / 2;
size_t rcount = count - lcount;
mergesort(bt_base, lcount, type, comp);
mergesort(bt_base + lcount * type, rcount, type, comp);
merge_arrays(base, lcount, bt_base + lcount * type, rcount, type, comp);
}
void merge_arrays(void *lbase, size_t lcnt, void *rbase, size_t rcnt, size_t type, comparator comp) {
char *tmp = (char *) calloc(lcnt + rcnt, type);
char *bt_lbase = (char *) lbase;
char *bt_rbase = (char *) rbase;
char *lptr = bt_lbase;
char *rptr = bt_rbase;
size_t sorted_cnt = 0;
while (lptr < bt_lbase + lcnt * type) {
while (rptr < bt_rbase + rcnt * type && comp(rptr, lptr) < 0) {
memcpy(tmp + sorted_cnt * type, rptr, type);
rptr += type;
sorted_cnt++;
}
memcpy(tmp + sorted_cnt * type, lptr, type);
lptr += type;
sorted_cnt++;
}
while (rptr < bt_rbase + rcnt * type) {
memcpy(tmp + sorted_cnt * type, rptr, type);
rptr += type;
sorted_cnt++;
}
memcpy(bt_lbase, tmp, (lcnt + rcnt) * type);
free(tmp);
}
| 26.122449
| 101
| 0.575781
|
Great1ng
|
68b7fb59d66d1da145b5b6fb694765973d6465ee
| 607
|
hpp
|
C++
|
src/Missile.hpp
|
michal-tangri/sgd-game
|
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
|
[
"MIT"
] | null | null | null |
src/Missile.hpp
|
michal-tangri/sgd-game
|
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
|
[
"MIT"
] | null | null | null |
src/Missile.hpp
|
michal-tangri/sgd-game
|
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
|
[
"MIT"
] | null | null | null |
#ifndef __MISSILE_CLASS_HPP__
#define __MISSILE_CLASS_HPP__
#include "GameObject.hpp"
#include "Tile.hpp"
#include <array>
class Missile : public GameObject {
public:
enum MissileOrigin {
MISSILE_ORIGIN_PLAYER,
MISSILE_ORIGIN_ENEMY
};
Missile(MissileOrigin origin);
void update(double dt, Tile level[24][30]);
void render(SDL_Renderer* r) override;
void initialize(double pos_x, double pos_y, double acceleration_x, SDL_Renderer* r);\
ObjectType type = ObjectType::LIGUNIA_MISSILE;
MissileOrigin origin;
private:
double acceleration_x;
};
#endif
| 19.580645
| 89
| 0.723229
|
michal-tangri
|
68ba56c90c62dc771c66c7fe4bfea2ed7d3a1b5a
| 8,576
|
cpp
|
C++
|
src/hyposystem.cpp
|
HypoModel/HypoModBase
|
29572f98202780c9a8b25cffe80761fedb35aa1a
|
[
"MIT"
] | null | null | null |
src/hyposystem.cpp
|
HypoModel/HypoModBase
|
29572f98202780c9a8b25cffe80761fedb35aa1a
|
[
"MIT"
] | null | null | null |
src/hyposystem.cpp
|
HypoModel/HypoModBase
|
29572f98202780c9a8b25cffe80761fedb35aa1a
|
[
"MIT"
] | null | null | null |
#include "hypomodel.h"
//#include "hypomain.h"
//#include "hypopanels.h"
OptionPanel::OptionPanel(HypoMain *main, const wxString & title)
: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(450, 450),
wxFRAME_FLOAT_ON_PARENT | wxFRAME_TOOL_WINDOW | wxCAPTION | wxSYSTEM_MENU | wxCLOSE_BOX | wxRESIZE_BORDER)
{
int i, modindex;
int nummods = 9;
mainwin = main;
ToolPanel *panel = new ToolPanel(this, wxDefaultPosition, wxDefaultSize);
wxRadioButton *modrad[20];
wxString text;
wxFont confont;
wxButton *button;
if(mainwin->ostype == Mac) confont = wxFont(wxFontInfo(11).FaceName("Tahoma"));
else confont = wxFont(wxFontInfo(8).FaceName("Tahoma"));
wxBoxSizer *mainbox = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *panelbox = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *panelhbox = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer *prefbox = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *pathbox = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *buttonbox = new wxBoxSizer(wxHORIZONTAL);
wxStaticBoxSizer *startbox = new wxStaticBoxSizer(wxVERTICAL, panel, "Start Model");
numdrawcon = new ParamNum(panel, "numdraw", "Num Draw", mainwin->numdraw);
viewheightcon = new ParamNum(panel, "viewheight", "View Height", mainwin->viewheight);
ylabelcon = new ParamNum(panel, "ylabels", "Y Labels", mainwin->ylabels);
datsamplecon = new ParamNum(panel, "datsample", "Data Sample Rate", mainwin->datsample);
// Project
wxBoxSizer *projectbox = new wxBoxSizer(wxHORIZONTAL);
projecttag = new TagBox(mainwin, panel, wxID_ANY, "", wxDefaultPosition, wxSize(200, 23), "projectbox", "");
projectbox->Add(projecttag, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxALL, 2);
//projecttag->SetLabel(mainwin->project->protag);
button = new wxButton(panel, ID_ProjectStore, "Store", wxDefaultPosition, wxSize(40, 25));
button->SetFont(confont);
projectbox->Add(button, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxTOP|wxBOTTOM);
projectbox->AddSpacer(2);
button = new wxButton(panel, ID_ProjectLoad, "Load", wxDefaultPosition, wxSize(40, 25));
button->SetFont(confont);
projectbox->Add(button, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxTOP|wxBOTTOM);
// Paths
datapathcon = new ParamText(panel, "datapath", "Data", mainwin->datapath, 30, 320);
datapathcon->AddButton("Path", ID_DataBrowse, 40);
outpathcon = new ParamText(panel, "outpath", "Out", mainwin->outpath, 30, 320);
outpathcon->AddButton("Path", ID_OutputBrowse, 40);
parampathcon = new ParamText(panel, "browsepath", "Param", mainwin->parampath, 30, 320);
parampathcon->AddButton("Path", ID_ParamBrowse, 40);
modpathcon = new ParamText(panel, "modpath", "Mod", mainwin->modpath, 30, 320);
modpathcon->AddButton("Path", ID_ModBrowse, 40);
//nummods = mainwin->moddex - 1;
nummods = mainwin->modset.modcount;
//modrad[0] = new wxRadioButton(panel, 0, "Blank", wxDefaultPosition, wxDefaultSize, wxRB_GROUP);
//startbox->Add(modrad[0], 1, wxTOP | wxBOTTOM, 3);
for(i=0; i<nummods; i++) {
modrad[i+1] = new wxRadioButton(panel, mainwin->modset.modeldat[i].index, mainwin->modset.modeldat[i].title);
mainwin->diagbox->Write(text.Format("button %d %s\n", mainwin->modset.modeldat[i].index, mainwin->modset.modeldat[i].title));
startbox->Add(modrad[i+1], 1, wxTOP | wxBOTTOM, 3);
}
modindex = mainwin->modset.GetDex(mainwin->startmod);
if(modindex != -1) modrad[modindex + 1]->SetValue(true);
mainwin->diagbox->Write(text.Format("startmod %d button %d\n", mainwin->startmod, mainwin->modset.GetDex(mainwin->startmod) + 1));
prefbox->AddSpacer(10);
prefbox->Add(numdrawcon, 1);
prefbox->Add(viewheightcon, 1);
prefbox->Add(ylabelcon, 1);
prefbox->Add(datsamplecon, 1);
panelhbox->Add(startbox, 0);
panelhbox->AddSpacer(20);
panelhbox->Add(prefbox, 0);
pathbox->Add(datapathcon, 1);
pathbox->Add(parampathcon, 1);
pathbox->Add(outpathcon, 1);
pathbox->Add(modpathcon, 1);
panelbox->Add(panelhbox, 0);
panelbox->AddStretchSpacer(5);
panelbox->Add(projectbox, 0, wxALIGN_CENTRE);
panelbox->AddStretchSpacer(5);
panelbox->Add(pathbox, 0);
panel->SetSizer(panelbox);
panel->Layout();
wxButton *okButton = new wxButton(this, wxID_OK, "Ok", wxDefaultPosition, wxSize(70, 30));
wxButton *closeButton = new wxButton(this, wxID_CANCEL, "Close", wxDefaultPosition, wxSize(70, 30));
buttonbox->Add(okButton, 1);
buttonbox->Add(closeButton, 1, wxLEFT, 5);
mainbox->Add(panel, 1, wxALL, 10);
mainbox->Add(buttonbox, 0, wxALIGN_CENTRE | wxTOP | wxBOTTOM, 10);
SetSizer(mainbox);
Layout();
Connect(wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler(OptionPanel::OnModRadio));
Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnOK));
Connect(wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(OptionPanel::OnEnter));
Connect(ID_DataBrowse, ID_ModBrowse, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnBrowse));
//Connect(ID_OutputBrowse, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnBrowse));
Connect(ID_ProjectStore, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnProjectStore));
Connect(ID_ProjectLoad, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnProjectLoad));
//ShowModal();
//Destroy();
}
void OptionPanel::OnProjectStore(wxCommandEvent& event)
{
wxString tag, filepath;
filepath = projecttag->StoreTag(mainwin->project->path, "-prefs.ini");
if(filepath.IsEmpty()) return;
tag = projecttag->GetValue();
mainwin->project->Init(tag);
mainwin->project->Store();
}
void OptionPanel::OnProjectLoad(wxCommandEvent& event)
{
wxString tag, filepath;
filepath = projecttag->LoadTag(mainwin->project->path, "-prefs.ini");
if(filepath.IsEmpty()) return;
projecttag->HistStore(); // store updated tag list before project load
tag = projecttag->GetValue();
mainwin->project->Init(tag);
mainwin->project->Load();
this->Raise();
}
void OptionPanel::OnModRadio(wxCommandEvent& event)
{
//if(event.GetId() == ID_BlankPanel) mainwin->startmod = 0;
//if(event.GetId() == ID_IGFPanel) mainwin->startmod = 1;
//if(event.GetId() == ID_VasoPanel) mainwin->startmod = 2;
//if(event.GetId() == ID_VMHPanel) mainwin->startmod = 3;
//if(event.GetId() == ID_CortPanel) mainwin->startmod = 4;
//if(event.GetId() == ID_OsmoPanel) mainwin->startmod = 5;
//if(event.GetId() == ID_HeatMod) mainwin->startmod = modHeat;
//if(event.GetId() == ID_GHMod) mainwin->startmod = modGH;
//if(event.GetId() == ID_LysisMod) mainwin->startmod = modLysis;
//if(event.GetId() == ID_AgentMod) mainwin->startmod = modAgent;
mainwin->startmod = event.GetId();
}
void OptionPanel::OnEnter(wxCommandEvent& event)
{
long stringnum;
wxString snum;
numdrawcon->numbox->GetValue().ToLong(&stringnum);
mainwin->numdraw_set = stringnum;
if(mainwin->mod) mainwin->mod->prefstore["numdraw"] = mainwin->numdraw_set;
viewheightcon->numbox->GetValue().ToLong(&stringnum);
mainwin->viewheight = stringnum;
ylabelcon->numbox->GetValue().ToLong(&stringnum);
mainwin->ylabels = stringnum;
datsamplecon->numbox->GetValue().ToLong(&stringnum);
mainwin->datsample = stringnum;
mainwin->parampath = parampathcon->GetValue();
mainwin->datapath = datapathcon->GetValue();
mainwin->outpath = outpathcon->GetValue();
mainwin->modpath = modpathcon->GetValue();
//snum.Printf("ok numdraw %d", mainwin->numdraw);
//mainwin->SetStatus(snum);
mainwin->GraphPanelsUpdate();
}
void OptionPanel::OnOK(wxCommandEvent& event)
{
OnEnter(event);
Close();
}
void OptionPanel::OnClose(wxCloseEvent& event)
{
mainwin->OptionStore();
Show(false);
}
void OptionPanel::OnBrowse(wxCommandEvent& event)
{
if(event.GetId() == ID_DataBrowse) {
wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->datapath, 0, wxDefaultPosition);
if(d->ShowModal() == wxID_OK) datapathcon->textbox->SetLabel(d->GetPath());
}
if(event.GetId() == ID_OutputBrowse) {
wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->outpath, 0, wxDefaultPosition);
if(d->ShowModal() == wxID_OK) outpathcon->textbox->SetLabel(d->GetPath());
}
if(event.GetId() == ID_ParamBrowse) {
wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->parampath, 0, wxDefaultPosition);
if(d->ShowModal() == wxID_OK) parampathcon->textbox->SetLabel(d->GetPath());
}
if(event.GetId() == ID_ModBrowse) {
wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->modpath, 0, wxDefaultPosition);
if(d->ShowModal() == wxID_OK) modpathcon->textbox->SetLabel(d->GetPath());
}
}
| 35.585062
| 131
| 0.731343
|
HypoModel
|
68be163aad621d1fd1d5c3538565f5f8d5c1430c
| 122,962
|
cpp
|
C++
|
CELLULARDlg.cpp
|
yantis/amps-cellular-interceptor
|
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
|
[
"MIT"
] | 4
|
2018-02-12T15:18:43.000Z
|
2021-03-08T21:35:31.000Z
|
CELLULARDlg.cpp
|
yantis/amps-cellular-interceptor
|
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
|
[
"MIT"
] | null | null | null |
CELLULARDlg.cpp
|
yantis/amps-cellular-interceptor
|
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
|
[
"MIT"
] | null | null | null |
// CELLULARDlg.cpp : implementation file
//
#include "stdafx.h"
#include "CELLULAR.h"
#include "CELLULARDlg.h"
#include <sys/types.h>
#include <sys/stat.h>
/*
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
*/
#include "supercom\supercom.h"
#include "area.h"
#include "phonelst.h"
#include "manufact.h"
#include "smrtheap.hpp"
#define OK 0
#define CLOSED 0
#define OPEN 1
// #define RECORD
///////////////////////////
int iCommPortOS456;
int iCommPortDDI;
long int iMaxCallTime;
bool bReverseChannel;
int iBufferCounter;
char dateis[15];
char timeis[15];
char d_timeis[12];
char chDDIdataBuffer[60];
char chPhoneNumber[15];
char chRegistration[2];
char chArea[38];
char chChannel[5];
char chGoFrequency[8];
char chAllRegistrations[4];
char chAllPaging[4];
char chRegistrationType[2];
char chAreaCode[4];
char chWhereErrorOccured[100];
int endnum;
int stanum;
bool bRegistration = false;
bool bDisconnect = false;
bool bPaging = false;
bool bReorder = false;
bool bLockOut = false;
bool bGoto = false;
bool bVoiceGoto = false;
bool bAllPaging = false;
bool bAllRegistration = false;
bool bNewTest;
bool bNewNumber;
bool bAmend;
char chChannelBand[2];
char chSCMstring[50];
////////////// ISAM
dfAREA areabase;
dfPHONELST phonelst;
dfMANUFACT manufact;
////////////////////
bool bCancelCall;
char chSignalStrength[100];
time_t start_time;
int squelch;
bool bHoldCall;
int iCallCounter_0;
int iCallCounter_1;
int iCallCounter_2;
int iCallCounter_3;
int iCallCounter_4;
int iCallCounter_5;
int iCallCounter_6;
int iCallCounter_7;
int iCallCounter_8;
int iCallCounter_9;
int iCallCounter_total;
int iCallCounter_record;
int iCallCounter_fax;
int iCallCounter_modem;
int iWaveFileNumber;
UINT wDeviceID;
bool bMonitor;
bool bAquire;
bool bGoReverseVoice;
bool bGoForwardVoice;
bool bVoiceForward;
char chChannelType[50];
char chFrequency[50];
char chReverseChannel[50];
char chForwardChannel[50];
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCELLULARDlg dialog
CCELLULARDlg::CCELLULARDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCELLULARDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CCELLULARDlg)
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCELLULARDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCELLULARDlg)
DDX_Control(pDX, IDC_PROGRESS_SIGNAL, m_ProgressSignal);
DDX_Control(pDX, IDC_BUTTON_CONTROL_TYPE, m_ButtonSwitchControlType);
DDX_Control(pDX, IDC_BUTTON_SWITCHVOICE, m_ButtonSwitchVoice);
DDX_Control(pDX, IDC_EDIT_CALLS, m_EditCallList);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL9, m_Text_CallsLevel9);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL8, m_Text_CallsLevel8);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL7, m_Text_CallsLevel7);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL6, m_Text_CallsLevel6);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL5, m_Text_CallsLevel5);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL4, m_Text_CallsLevel4);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL3, m_Text_CallsLevel3);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL2, m_Text_CallsLevel2);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL1, m_Text_CallsLevel1);
DDX_Control(pDX, IDC_TEXT_CALLSLEVEL0, m_Text_CallsLevel0);
DDX_Control(pDX, IDC_TEXT_TOTALCALL, m_Text_CallsTotal);
DDX_Control(pDX, IDC_TEXT_CALLSRECORD, m_Text_CallsRecorded);
DDX_Control(pDX, IDC_TEXT_CALLSMODEM, m_Text_CallsModem);
DDX_Control(pDX, IDC_TEXT_CALLSFAX, m_Text_CallsFax);
DDX_Control(pDX, IDC_EDIT_TOTALCALLS, m_Edit_TotalCalls);
DDX_Control(pDX, IDC_EDIT_SUBJECT, m_EditSubject);
DDX_Control(pDX, IDC_EDIT_SIGNALSTR, m_EditSignalStrength);
DDX_Control(pDX, IDC_EDIT_SCM, m_EditSCM);
DDX_Control(pDX, IDC_EDIT_RECORDCALL, m_EditRecordCall);
DDX_Control(pDX, IDC_EDIT_PHONETYPE, m_EditPhoneType);
DDX_Control(pDX, IDC_EDIT_PHONEMODEL, m_EditPhoneModel);
DDX_Control(pDX, IDC_EDIT_PHONE, m_EditPhone);
DDX_Control(pDX, IDC_EDIT_OCCUPATION, m_EditOccupation);
DDX_Control(pDX, IDC_EDIT_NAME2, m_EditName2);
DDX_Control(pDX, IDC_EDIT_NAME, m_EditName);
DDX_Control(pDX, IDC_EDIT_MODEMCALL, m_EditModemCalls);
DDX_Control(pDX, IDC_EDIT_LINKEDFILE, m_EditLinkedFile);
DDX_Control(pDX, IDC_EDIT_LASTCALL, m_EditLastCall);
DDX_Control(pDX, IDC_EDIT_LANGUAGE, m_EditLanguage);
DDX_Control(pDX, IDC_EDIT_INFO3, m_EditInfo3);
DDX_Control(pDX, IDC_EDIT_INFO2, m_EditInfo2);
DDX_Control(pDX, IDC_EDIT_INFO1, m_EditInfo1);
DDX_Control(pDX, IDC_EDIT_GENDER, m_EditGender);
DDX_Control(pDX, IDC_EDIT_FAXCALLS, m_EditFaxCalls);
DDX_Control(pDX, IDC_EDIT_ESN, m_EditESN);
DDX_Control(pDX, IDC_EDIT_DTMF, m_EditDtmf);
DDX_Control(pDX, IDC_EDIT_DIALEDNUMBER, m_EditDialedNumber);
DDX_Control(pDX, IDC_EDIT_CHANNELAB, m_EditChannelAB);
DDX_Control(pDX, IDC_EDIT_CALLTIME, m_EditCallTime);
DDX_Control(pDX, IDC_EDIT_CALLSTART, m_EditStart);
DDX_Control(pDX, IDC_EDIT_CALLEND, m_EditCallEnd);
DDX_Control(pDX, IDC_EDIT_AREA, m_EditArea);
DDX_Control(pDX, IDC_EDIT_ALERTLEVEL, m_EditAlertLevel);
DDX_Control(pDX, IDC_EDIT_STATUS, m_Edit_Status);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCELLULARDlg, CDialog)
//{{AFX_MSG_MAP(CCELLULARDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_EN_ERRSPACE(IDC_EDIT_STATUS, OnErrspaceEditStatus)
ON_BN_CLICKED(IDC_BUTTON_SKIPVOICECALL, OnButtonSkipvoicecall)
ON_BN_CLICKED(IDC_BUTTON_SAVE_DATA, OnButtonSaveData)
ON_BN_CLICKED(IDC_BUTTON_FIND_PHONE, OnButtonFindPhone)
ON_BN_CLICKED(IDC_CHECK_HOLDCALL, OnCheckHoldcall)
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_CHECK_AQUIRE, OnCheckAquire)
ON_BN_CLICKED(IDC_CHECK_MONITOR, OnCheckMonitor)
ON_BN_CLICKED(IDC_BUTTON_SWITCHVOICE, OnButtonSwitchvoice)
ON_BN_CLICKED(IDC_BUTTON_CONTROL_TYPE, OnButtonControlType)
ON_BN_CLICKED(IDC_BUTTON_CONTROLSCAN, OnButtonControlscan)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCELLULARDlg message handlers
BOOL CCELLULARDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
ReadIniFile();
phonelst.rew();
phonelst.clear_buf();
areabase.rew();
areabase.clear_buf();
manufact.rew();
manufact.clear_buf();
m_EditPhone.LimitText(14);
m_EditName.LimitText(30);
m_EditName2.LimitText(30);
m_EditArea.LimitText(30);
m_EditOccupation.LimitText(30);
m_EditSubject.LimitText(30);
m_EditLanguage.LimitText(10);
m_EditGender.LimitText(1);
m_EditInfo1.LimitText(30);
m_EditInfo2.LimitText(30);
m_EditInfo3.LimitText(30);
m_EditLinkedFile.LimitText(12);
m_EditModemCalls.LimitText(1);
m_EditFaxCalls.LimitText(1);
m_EditAlertLevel.LimitText(1);
m_EditRecordCall.LimitText(1);
m_EditDtmf.LimitText(30);
m_EditESN.LimitText(8);
m_EditSCM.LimitText(2);
bHoldCall = false;
iCallCounter_0 = 0;
iCallCounter_1 = 0;
iCallCounter_2 = 0;
iCallCounter_3 = 0;
iCallCounter_4 = 0;
iCallCounter_5 = 0;
iCallCounter_6 = 0;
iCallCounter_7 = 0;
iCallCounter_8 = 0;
iCallCounter_9 = 0;
iCallCounter_total = 0;
iCallCounter_record = 0;
iCallCounter_fax = 0;
iCallCounter_modem =0;
iWaveFileNumber = 0;
bMonitor = false;
bAquire = false;
bGoReverseVoice = false;
bGoForwardVoice = false;
bVoiceForward = true;
m_ProgressSignal.SetRange(0,25);
// m_ProgressSignal.SetStep(1);
m_Edit_Status.SetWindowText(" ");
which_channel();
bCancelThread=true;
bThreadClosed=true;
return TRUE; // return true unless you set the focus to a control
}
void CCELLULARDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CCELLULARDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CCELLULARDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CCELLULARDlg::WriteToStatusBox(char *pchString)
{
static int iCount = 0;
iCount ++;
char chTempString[50];
char *pchTempString = chTempString;
sprintf(pchTempString, "%d",iCount);
SetDlgItemText(IDC_STATUS_TEXT,pchTempString);
if(iCount >= 400)
{
iCount = 0;
m_Edit_Status.SetWindowText(" ");
m_Edit_Status.Clear();
}
m_Edit_Status.ReplaceSel(pchString,false);
char chNewLine[3];
chNewLine[0]= 0x0D;
chNewLine[1]= 0x0A;
chNewLine[2]= 0x00;
char *pchNewLine = chNewLine;
m_Edit_Status.ReplaceSel(pchNewLine,false);
}
void CCELLULARDlg::WriteToCallBox(char *pchString)
{
m_EditCallList.ReplaceSel(pchString,false);
char chNewLine[3];
chNewLine[0]= 0x0D;
chNewLine[1]= 0x0A;
chNewLine[2]= 0x00;
char *pchNewLine = chNewLine;
m_EditCallList.ReplaceSel(pchNewLine,false);
}
void CCELLULARDlg::MyError(char *s)
{
WriteDebugLog(s);
MessageBeep(MB_ICONEXCLAMATION);
MessageBox(s,"Program Error",MB_OK | MB_ICONHAND | MB_SETFOREGROUND);
}
void CCELLULARDlg::WriteDebugLog(char *chLogText)
{
FILE *log;
if((log=fopen("DEBUG.LOG","a+"))==NULL)
{
// Error("Error opening DEBUG.LOG"); (No Error or infinate loop ..)
return;
}
else
{
fprintf(log,"%s\n",chLogText);
fclose(log);
}
}
void CCELLULARDlg::OnOK()
{
CreateMyThread();
}
void CCELLULARDlg::InitalizeDDI(void)
{
WriteToStatusBox(" Initalizing DDI");
// Set to 9600 BPS and Send DDI command to switch to 19200
ComInit(iCommPortDDI);
if(ComValid(iCommPortDDI))
{
ComSetState(iCommPortDDI,9600,8,1,'N',SIGNAL_NONE);
ComBufClear(iCommPortDDI,DIR_INC);
ComBufClear(iCommPortDDI,DIR_OUT);
WriteToStatusBox(" DDI Comm Port Initalized @ 9600 BPS");
}
else
{
char chTempString[250];
char *pchTempString = chTempString;
sprintf(pchTempString,"Com Port %d is not available or is in use",iCommPortDDI+1);
MyError(pchTempString);
return;
}
ComDTROn(iCommPortDDI); // set DTR
ComRTSOn(iCommPortDDI); // set RTS
// Reset DDI
WriteToStatusBox(" Sending DDI Reset Command (1X)");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'Y');
// Reset DDI
WriteToStatusBox(" Sending DDI Reset Command (2X)");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'Y');
// Reset DDI
WriteToStatusBox(" Sending DDI Reset Command (3X)");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'Y');
// Switch DDI to 19200 bps
WriteToStatusBox(" Sending DDI Command to increase BPS to 19200");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'F');
WriteToStatusBox(" Switching DDI Comm Port to 19200 BPS");
ComSetBaudRate(iCommPortDDI, 19200);
// ComBufClear(iCommPortDDI,DIR_INC);
// ComBufClear(iCommPortDDI,DIR_OUT);
// WriteToStatusBox(" Sending DDI Command to display all control data");
// ComWrite(iCommPortDDI,'-');
// ComWrite(iCommPortDDI,'D'); // All Control Data
WriteToStatusBox(" Sending DDI Command to display all control data changes only");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'d'); // Changes only
WriteToStatusBox(" Sending DDI Command to show Channel on Goto");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'K');
SetDDItoControlChannel();
if(bReverseChannel == true)
{
SetDDItoReverse();
}
else
{
SetDDItoForward();
}
}
void CCELLULARDlg::OnCancel()
{
#ifdef RECORD
mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);
#endif
bCancelThread=true;
if(bThreadClosed==false)
{
SetDlgItemText(IDC_STATUS_TEXT,"Please wait while closing multithreaded engine.");
Sleep(3000);
}
if(bThreadClosed==false)
{
DWORD dwExitCode;
if(GetExitCodeThread(hThread,&dwExitCode)==false)
{
MyError("Error in GetExitCodeThread(hThread)");
}
else
{
TerminateThread(hThread,dwExitCode);
}
}
hThread = NULL;
ComReset(iCommPortDDI);
ComReset(iCommPortOS456);
CDialog::OnCancel();
}
void CCELLULARDlg::CreateMyThread(void)
{
#ifdef _DEBUG
TRACE("CreateMyThread START\n");
#endif
DWORD dwThreadId;
hThread = CreateThread((LPSECURITY_ATTRIBUTES) NULL, 0,
(LPTHREAD_START_ROUTINE) ThreadProc,this,0,&dwThreadId);
if(hThread == NULL)
{
char chTempString[75];
char *pchTempString = chTempString;
sprintf(pchTempString,"Error %ld Creating Thread",GetLastError());
MyError(pchTempString);
}
else
{
if(SetThreadPriority( hThread, THREAD_PRIORITY_NORMAL ) == 0)
{
MyError("Cound Not set thread to THREAD_PRIORITY_NORMAL");
}
}
#ifdef _DEBUG
TRACE("CreateMyThread END\n");
#endif
}
DWORD CCELLULARDlg::ThreadProc(CCELLULARDlg *s)
{
s->ProcessThread();
return 0;
}
void CCELLULARDlg::ProcessThread(void)
{
#ifdef _DEBUG
TRACE("ProcessThread START\n");
#endif
bCancelThread=false;
bThreadClosed=false;
InitalizeOS456();
InitalizeDDI();
start:
if(bCancelThread==true)
{
bThreadClosed=true;
return;
}
if(bHoldCall == false)
{
GetDDIdata();
}
goto start;
}
void CCELLULARDlg::whattime(void)
{
struct tm *today;
time_t timer;
timer = time(NULL);
today = localtime( &timer );
char timestatus[3]; // am/pm
int hour1;
if (today->tm_hour<12)
{
strcpy(timestatus,"am");
hour1=today->tm_hour;
if (today->tm_hour==0){hour1=12;}
}
if (today->tm_hour>=12)
{
strcpy(timestatus,"pm");
hour1=today->tm_hour - 12;
if (today->tm_hour==12){hour1=12;}
}
sprintf(timeis,"%02d:%02d:%02d%s",hour1,today->tm_min,today->tm_sec,timestatus);
sprintf(dateis,"%02d-%02d-%02d",today->tm_mon+1,today->tm_mday,today->tm_year);
sprintf(d_timeis,"%02d:%02d%c",hour1,today->tm_min,timestatus[0]);
}
void CCELLULARDlg::ZeroMemVariables(void)
{
::ZeroMemory (chDDIdataBuffer, sizeof (chDDIdataBuffer));
::ZeroMemory (chArea, sizeof (chArea));
}
void CCELLULARDlg::GetDDIdata(void)
{
char i;
if(ComRead(iCommPortDDI,&i)==TRUE)
{
if(i==0x0D)
{
char chTempBuffer[500];
char *pchTempBuffer = chTempBuffer;
iBufferCounter=-1;
whattime();
AnalyzeDDIdata();
if((chDDIdataBuffer[0]>=0x30) && (chDDIdataBuffer[0]<=0x39)) // Is first character a number ?
{
if((bRegistration==true) &&(bReverseChannel==false))
{
sprintf(pchTempBuffer," %s %s\tRegistration [%c]\t%s",timeis,chPhoneNumber,chRegistration[0],chArea);
WriteToStatusBox(pchTempBuffer);
/*
if(logit==true)
{
fprintf(log," %s %s Registration [%c] %s\n",timeis,chPhoneNumber,chRegistration[0],chArea);
}
*/
}
if(bDisconnect==true)
{
sprintf(pchTempBuffer," %s %s\tDisconnect\t%s",timeis,chPhoneNumber,chArea);
WriteToStatusBox(pchTempBuffer);
/*
if(logit==true)
{
fprintf(log," %s %s Disconnect %s\n",timeis,chPhoneNumber,chArea);
}
*/
}
if(bPaging==true)
{
sprintf(pchTempBuffer," %s %s\tPaging\t\t%s",timeis,chPhoneNumber,chArea);
WriteToStatusBox(pchTempBuffer);
/*
if(logit==true)
{
fprintf(log," %s %s Paging %s\n",timeis,chPhoneNumber,chArea);
}
*/
}
if((bReorder==true)&&(bLockOut==false))
{
sprintf(pchTempBuffer," %s %s\tReorder\t\t%s",timeis,chPhoneNumber,chArea);
WriteToStatusBox(pchTempBuffer);
/*
if(logit==true)
{
fprintf(log," %s %s Reorder System to busy - Try later.\n",timeis,chPhoneNumber);
}
*/
}
if((bGoto ==true)&&(bLockOut==true))
{
sprintf(pchTempBuffer," %s %s\tLocked Out Goto\t%s",timeis,chPhoneNumber,chArea);
WriteToStatusBox(pchTempBuffer);
}
if((bGoto ==true)&&(bLockOut==false))
{
sprintf(pchTempBuffer," %s %s\tGoto %s\t%s",timeis,chPhoneNumber,chGoFrequency,chArea);
WriteToStatusBox(pchTempBuffer);
switch_to_voice();
}
} // End if (is it a number ?)
if(((chDDIdataBuffer[0]<0x30)||(chDDIdataBuffer[0]>0x39)) || (bReverseChannel==true) ) // Is first character NOT a number ?
{
if((bAllPaging==false)&&(bAllRegistration==false)&&(chDDIdataBuffer[0] != 0x00)&&(chDDIdataBuffer[1] != 0x00)&&(chDDIdataBuffer[0] != 0x20))
{
sprintf(pchTempBuffer," %s",chDDIdataBuffer);
WriteToStatusBox(pchTempBuffer);
/*
if(logit==true)
{
fprintf(log," %s\n",chDDIdataBuffer);
}
*/
}
} // end if (if first character NOT a number?)
ZeroMemVariables();
} // End if (i>1)
if((i>=0x20) && (i <=0x7A))
{
iBufferCounter++;
chDDIdataBuffer[iBufferCounter] = (char) i;;
}
}
}
void CCELLULARDlg::AnalyzeDDIdata(void)
{
ossignalstr();
bRegistration = false; // reset registration flag
bDisconnect = false; // reset disconnect flag
bPaging = false; // reset paging flag
bGoto = false; // reset Goto flag
bVoiceGoto = false; // reset voice GoTo Flag
bReorder = false; // reset bReorder flag
bLockOut = false; // reset bLockOut flag
/* personal = false; // reset personal flag */
bAllRegistration = false; // reset all registration flag
bAllPaging = false; // reset all paging flag
char chTempBuffer[500];
char *pchTempBuffer = chTempBuffer;
if((chDDIdataBuffer[0]<0x30) || (chDDIdataBuffer[0]>0x39)) // Is first character NOT a number ?
{
// Check if Goto Command from Voice Channel(check for "GoT")
if ((chDDIdataBuffer[0]=='G')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='T') )
{
bVoiceGoto = true;
// Jump to which channel
chChannel[0] = chDDIdataBuffer[5];
chChannel[1] = chDDIdataBuffer[6];
chChannel[2] = chDDIdataBuffer[7];
chChannel[3] = chDDIdataBuffer[8];
// Jump to which frequency
chGoFrequency[0] = chDDIdataBuffer[10];// 8
chGoFrequency[1] = chDDIdataBuffer[11];// 8
chGoFrequency[2] = chDDIdataBuffer[12];// 0
chGoFrequency[3] = chDDIdataBuffer[13];// .
chGoFrequency[4] = chDDIdataBuffer[14];// 5
chGoFrequency[5] = chDDIdataBuffer[15];// 0
chGoFrequency[6] = chDDIdataBuffer[16];// 0
WriteToStatusBox(" At Goto2 Subroutine ");
/*
if(logit==true)
{
fprintf(log,"At Goto2 Subroutine \n");
}
*/
goto END;
}
// Check if "?" or ">"
if((chDDIdataBuffer[0]==0x3F)||(chDDIdataBuffer[0]==0x3E) )
{
ZeroMemVariables();
goto END;
}
// Check if Voice
if((chDDIdataBuffer[0]=='V')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='i') )
{
WriteToStatusBox(" DDI Successfully set to Voice Mode");
ZeroMemVariables();
goto END;
}
// Check if E1 thru EE but not E0 (Reserved, Ignore)
if((chDDIdataBuffer[0]=='E')&&(chDDIdataBuffer[1]!='0'))
{
ZeroMemVariables();
goto END;
}
// Check if F1 thru FF but not F0 (Reserved, Ignore)
if((chDDIdataBuffer[0]=='E')&&(chDDIdataBuffer[1]!='0'))
{
ZeroMemVariables();
goto END;
}
// Check if D2 thru DB but not any other Dx (Reserved, Ignore)
if((chDDIdataBuffer[0]=='D')&&(chDDIdataBuffer[1]=='2' || '3' || '4' || '5' || '6'|| '7' || '8' || '9' || 'A' || 'B'))
{
ZeroMemVariables();
goto END;
}
// Check if System Requested Registration
if((chDDIdataBuffer[6]=='R')&&(chDDIdataBuffer[7]=='e')&&(chDDIdataBuffer[8]=='g') )
{
bAllRegistration = true;
// All registration of Which area code
chAllRegistrations[0]=chDDIdataBuffer[1];
chAllRegistrations[1]=chDDIdataBuffer[2];
chAllRegistrations[2]=chDDIdataBuffer[3];
// What type of registration
chRegistrationType[0]=chDDIdataBuffer[19];
goto END;
}
// Check if System Page
if((chDDIdataBuffer[6]=='P')&&(chDDIdataBuffer[7]=='a')&&(chDDIdataBuffer[8]=='g'))
{
bAllPaging = true;
// All Page of Which area code
chAllPaging[0]=chDDIdataBuffer[1];
chAllPaging[1]=chDDIdataBuffer[2];
chAllPaging[2]=chDDIdataBuffer[3];
goto END;
}
// Check if Control
if((chDDIdataBuffer[0]=='C')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='n') )
{
WriteToStatusBox(" DDI Successfully set to Control Mode");
ZeroMemVariables();
goto END;
}
// Check if Forward
if((chDDIdataBuffer[0]=='F')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='r'))
{
WriteToStatusBox(" DDI Successfully set to Forward Mode");
ZeroMemVariables();
goto END;
}
// Check if Reverse
if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='e')&&(chDDIdataBuffer[2]=='v') )
{
WriteToStatusBox(" DDI Successfully set to Reverse Mode");
ZeroMemVariables();
goto END;
}
// Check if System ID & DCC on Control Channel
if((chDDIdataBuffer[0]=='S')&&(chDDIdataBuffer[1]=='I')&&(chDDIdataBuffer[2]=='D'))
{
char chSID[5];
::ZeroMemory (chSID, sizeof (chSID));
char chDCC[2];
::ZeroMemory (chDCC, sizeof (chDCC));
chSID[0]=chDDIdataBuffer[4];
chSID[1]=chDDIdataBuffer[5];
chSID[2]=chDDIdataBuffer[6];
chSID[3]=chDDIdataBuffer[7];
SetDlgItemText(IDC_TEXT_SID,chSID);
if((chDDIdataBuffer[9]=='D')&&(chDDIdataBuffer[10]=='C')&&(chDDIdataBuffer[11]=='C') )
{
chDCC[0]=chDDIdataBuffer[4];
SetDlgItemText(IDC_TEXT_DCC,chDCC);
}
/* UpdateChannelStats(); */
ZeroMemVariables();
goto END;
}
// Check for NPC=xx on Control Channel
if((chDDIdataBuffer[0]=='N')&&(chDDIdataBuffer[1]=='P')&&(chDDIdataBuffer[2]=='C'))
{
char chNPC[3];
::ZeroMemory (chNPC, sizeof (chNPC));
chNPC[0]=chDDIdataBuffer[4];
chNPC[1]=chDDIdataBuffer[5];
SetDlgItemText(IDC_TEXT_NPC,chNPC);
ZeroMemVariables();
goto END;
}
// Check for NAC=xx on Control Channel
if((chDDIdataBuffer[0]=='N')&&(chDDIdataBuffer[1]=='A')&&(chDDIdataBuffer[2]=='C'))
{
char chNAC[3];
::ZeroMemory (chNAC, sizeof (chNAC));
chNAC[0]=chDDIdataBuffer[4];
chNAC[1]=chDDIdataBuffer[5];
SetDlgItemText(IDC_TEXT_NAC,chNAC);
ZeroMemVariables();
goto END;
}
// Check if RegInc=xxxx on Control Channel
if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='e')&&(chDDIdataBuffer[2]=='g')&&(chDDIdataBuffer[3]=='I') )
{
char chRegInc[6];
::ZeroMemory (chRegInc, sizeof (chRegInc));
chRegInc[0]=chDDIdataBuffer[7];
chRegInc[1]=chDDIdataBuffer[8];
chRegInc[2]=chDDIdataBuffer[9];
chRegInc[3]=chDDIdataBuffer[10];
SetDlgItemText(IDC_TEXT_REGINC,chRegInc);
ZeroMemVariables();
goto END;
}
// Check if Modes=XXXXXXX on Control Channel
if((chDDIdataBuffer[0]=='M')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='d'))
{
if((chDDIdataBuffer[6]=='S')|| (chDDIdataBuffer[7]=='S')||(chDDIdataBuffer[8]=='S')||(chDDIdataBuffer[9]=='S')||
(chDDIdataBuffer[10]=='S')|| (chDDIdataBuffer[11]=='S')|| (chDDIdataBuffer[12]=='S'))
{
SetDlgItemText(IDC_TEXT_MODES_S,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_S,"NO");
}
if((chDDIdataBuffer[6]=='E')|| (chDDIdataBuffer[7]=='E')||(chDDIdataBuffer[8]=='E')||(chDDIdataBuffer[9]=='E')||
(chDDIdataBuffer[10]=='E')|| (chDDIdataBuffer[11]=='E')|| (chDDIdataBuffer[12]=='E'))
{
SetDlgItemText(IDC_TEXT_MODES_E,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_E,"NO");
}
if((chDDIdataBuffer[6]=='H')|| (chDDIdataBuffer[7]=='H')||(chDDIdataBuffer[8]=='H')||(chDDIdataBuffer[9]=='H')||
(chDDIdataBuffer[10]=='H')|| (chDDIdataBuffer[11]=='H')|| (chDDIdataBuffer[12]=='H'))
{
SetDlgItemText(IDC_TEXT_MODES_H,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_H,"NO");
}
if((chDDIdataBuffer[6]=='R')|| (chDDIdataBuffer[7]=='R')||(chDDIdataBuffer[8]=='R')||(chDDIdataBuffer[9]=='R')||
(chDDIdataBuffer[10]=='R')|| (chDDIdataBuffer[11]=='R')|| (chDDIdataBuffer[12]=='R'))
{
SetDlgItemText(IDC_TEXT_MODES_R,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_R,"NO");
}
if((chDDIdataBuffer[6]=='D')|| (chDDIdataBuffer[7]=='D')||(chDDIdataBuffer[8]=='D')||(chDDIdataBuffer[9]=='D')||
(chDDIdataBuffer[10]=='D')|| (chDDIdataBuffer[11]=='D')|| (chDDIdataBuffer[12]=='D'))
{
SetDlgItemText(IDC_TEXT_MODES_D,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_D,"NO");
}
if((chDDIdataBuffer[6]=='F')|| (chDDIdataBuffer[7]=='F')||(chDDIdataBuffer[8]=='F')||(chDDIdataBuffer[9]=='F')||
(chDDIdataBuffer[10]=='F')|| (chDDIdataBuffer[11]=='F')|| (chDDIdataBuffer[12]=='F'))
{
SetDlgItemText(IDC_TEXT_MODES_F,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_F,"NO");
}
if((chDDIdataBuffer[6]=='C')|| (chDDIdataBuffer[7]=='C')||(chDDIdataBuffer[8]=='C')||(chDDIdataBuffer[9]=='C')||
(chDDIdataBuffer[10]=='C')|| (chDDIdataBuffer[11]=='C')|| (chDDIdataBuffer[12]=='C'))
{
SetDlgItemText(IDC_TEXT_MODES_C,"YES");
}
else
{
SetDlgItemText(IDC_TEXT_MODES_C,"NO");
}
ZeroMemVariables();
goto END;
}
//check for Ring Phone on Voice Channel
if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='i')&&(chDDIdataBuffer[2]=='n') )
{
// ring = true;
WriteToStatusBox(" Incoming Ring on Voice Channel");
ZeroMemVariables();
goto END;
}
}
if((chDDIdataBuffer[0]>=0x30) && (chDDIdataBuffer[0]<=0x39)) // Is first character a number ?
{
// Change phone number to (xxx) xxx-xxxx format & save in chPhoneNumber array
chPhoneNumber[0] =chDDIdataBuffer[9]; // Area Code
chPhoneNumber[1] =chDDIdataBuffer[10];// 6
chPhoneNumber[2] =chDDIdataBuffer[11];// 1
chPhoneNumber[3] =chDDIdataBuffer[12];// 9
chPhoneNumber[4] =chDDIdataBuffer[13];
chPhoneNumber[5] =chDDIdataBuffer[8]; // Space
chPhoneNumber[6] =chDDIdataBuffer[0]; // prefix
chPhoneNumber[7] =chDDIdataBuffer[1];
chPhoneNumber[8] =chDDIdataBuffer[2];
chPhoneNumber[9] =chDDIdataBuffer[3]; // -
chPhoneNumber[10]=chDDIdataBuffer[4]; // suffix
chPhoneNumber[11]=chDDIdataBuffer[5];
chPhoneNumber[12]=chDDIdataBuffer[6];
chPhoneNumber[13]=chDDIdataBuffer[7];
chAreaCode[0] = chDDIdataBuffer[10];
chAreaCode[1] = chDDIdataBuffer[11];
chAreaCode[2] = chDDIdataBuffer[12];
strcpy(phonelst.Dphone,chPhoneNumber);
search();
areabase.Anumber[0] =chPhoneNumber[1];// 6
areabase.Anumber[1] =chPhoneNumber[2];// 1
areabase.Anumber[2] =chPhoneNumber[3];// 9
areabase.Anumber[3] =chPhoneNumber[6]; // prefix
areabase.Anumber[4] =chPhoneNumber[7];
areabase.Anumber[5] = 0x00;
areabase.Anumber[6] = 0x00;
areabase.Anumber[7] = 0x00;
areabase.Anumber[8] = 0x00;
areabase.Anumber[9] = 0x00;
areabase.Anumber[10] = 0x00;
areabase.Anumber[11] = 0x00;
areabase.Anumber[12] = 0x00;
areabase.Anumber[13] = 0x00;
if((areabase.find()== IM_OK))
{
strcpy(chArea,areabase.Aarea);
goto OK1;
}
else
{
areabase.Anumber[0] =chPhoneNumber[1];// 6
areabase.Anumber[1] =chPhoneNumber[2];// 1
areabase.Anumber[2] =chPhoneNumber[3];// 9
areabase.Anumber[3] =chPhoneNumber[6]; // prefix
areabase.Anumber[4] = 0x00;
areabase.Anumber[5] = 0x00;
areabase.Anumber[6] = 0x00;
areabase.Anumber[7] = 0x00;
areabase.Anumber[8] = 0x00;
areabase.Anumber[9] = 0x00;
areabase.Anumber[10] = 0x00;
areabase.Anumber[11] = 0x00;
areabase.Anumber[12] = 0x00;
areabase.Anumber[13] = 0x00;
if((areabase.find()== IM_OK))
{
strcpy(chArea,areabase.Aarea);
goto OK1;
}
else
{
areabase.Anumber[0] =chPhoneNumber[1];// 6
areabase.Anumber[1] =chPhoneNumber[2];// 1
areabase.Anumber[2] =chPhoneNumber[3];// 9
areabase.Anumber[3] = 0x00;
areabase.Anumber[4] = 0x00;
areabase.Anumber[5] = 0x00;
areabase.Anumber[6] = 0x00;
areabase.Anumber[7] = 0x00;
areabase.Anumber[8] = 0x00;
areabase.Anumber[9] = 0x00;
areabase.Anumber[10] = 0x00;
areabase.Anumber[11] = 0x00;
areabase.Anumber[12] = 0x00;
areabase.Anumber[13] = 0x00;
if((areabase.find()== IM_OK))
{
strcpy(chArea,areabase.Aarea);
goto OK1;
}
else
{
areabase.Anumber[0] =chPhoneNumber[1];// 6
areabase.Anumber[1] =chPhoneNumber[2];// 1
areabase.Anumber[2] = 0x00;
areabase.Anumber[3] = 0x00;
areabase.Anumber[4] = 0x00;
areabase.Anumber[5] = 0x00;
areabase.Anumber[6] = 0x00;
areabase.Anumber[7] = 0x00;
areabase.Anumber[8] = 0x00;
areabase.Anumber[9] = 0x00;
areabase.Anumber[10] = 0x00;
areabase.Anumber[11] = 0x00;
areabase.Anumber[12] = 0x00;
areabase.Anumber[13] = 0x00;
if((areabase.find()== IM_OK))
{
strcpy(chArea,areabase.Aarea);
goto OK1;
}
else
{
strcpy(chArea,"Not Found");
}
}
}
}
OK1:
// Check if Registration (check for "Reg")
if((chDDIdataBuffer[15]==0x52) && (chDDIdataBuffer[16]=='e') && (chDDIdataBuffer[17]==0x67) )
{
chRegistration[0] = chDDIdataBuffer[28];
if(bReverseChannel==false)
{
bRegistration = true;
}
if((chDDIdataBuffer[32]=='S') && (chDDIdataBuffer[33]=='C') && (chDDIdataBuffer[34]=='M'))
{
phonelst.Dscm[0]=chDDIdataBuffer[36];
phonelst.Dscm[1]=chDDIdataBuffer[37];
phonelst.Desn[0]=chDDIdataBuffer[43];
phonelst.Desn[1]=chDDIdataBuffer[44];
phonelst.Desn[2]=chDDIdataBuffer[45];
phonelst.Desn[3]=chDDIdataBuffer[46];
phonelst.Desn[4]=chDDIdataBuffer[47];
phonelst.Desn[5]=chDDIdataBuffer[48];
phonelst.Desn[6]=chDDIdataBuffer[49];
phonelst.Desn[7]=chDDIdataBuffer[50];
if(phonelst.Darea[0]==0x00)
{
strcpy(phonelst.Darea,chArea);
}
if(phonelst.Dtype[0]==0x00)
{
phonelst.Dtype[0]=chChannelBand[0];
}
if(phonelst.Dphone[0]==0x00)
{
strcpy(phonelst.Dphone,chPhoneNumber);
insert_record();
bNewTest=false;
bNewNumber=true;
}
if(bNewNumber==false)
{
strcpy(chWhereErrorOccured,"Line 2150");
amend_record();
bAmend=false;
bNewTest=false;
}
char chTempString[400];
char *pchTempString = chTempString;
sprintf(pchTempString," [%s] [SC = %s] [ESN = %s]",chPhoneNumber,phonelst.Dscm,phonelst.Desn);
WriteToCallBox(pchTempString);
}
goto END;
//}
}
// Check if Reorder (check for "Reo")
if((chDDIdataBuffer[15]=='R') && (chDDIdataBuffer[16]=='e') && (chDDIdataBuffer[17]=='o'))
{
TRACE("REORDER\n");
bReorder = true;
goto END;
}
// Check if Control channel Disconnect (check for "Di")
if((chDDIdataBuffer[15]=='D') && (chDDIdataBuffer[16]=='i') )
{
TRACE("DISCONNECT\n");
bDisconnect = true;
goto END;
}
// Check if Paging (check for "Pa")
if((chDDIdataBuffer[15]=='P')&&(chDDIdataBuffer[16]=='a'))
{
TRACE("PAGING\n");
bPaging = true;
goto END;
}
// Check if Goto Command (check for "Go")
if((chDDIdataBuffer[15]=='G')&&(chDDIdataBuffer[16]=='o'))
{
bGoto = true;
// Jump to which channel
chChannel[0] = chDDIdataBuffer[20];
chChannel[1] = chDDIdataBuffer[21];
chChannel[2] = chDDIdataBuffer[22];
chChannel[3] = chDDIdataBuffer[23];
// Jump to which frequency
chGoFrequency[0] = chDDIdataBuffer[25];// 8
chGoFrequency[1] = chDDIdataBuffer[26];// 8
chGoFrequency[2] = chDDIdataBuffer[27];// 0
chGoFrequency[3] = chDDIdataBuffer[28];// .
chGoFrequency[4] = chDDIdataBuffer[29];// 5
chGoFrequency[5] = chDDIdataBuffer[30];// 0
chGoFrequency[6] = '0';
if(bMonitor == true)
{
/*
if((phonelst.DRecordCall[0]!='Y'))
{
bLockOut=true;
}
*/
if((phonelst.Dalert[0]=='5'))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 4 Call");
bLockOut=true;
}
if((phonelst.Dalert[0]=='3'))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 3 Call");
bLockOut=true;
}
if((phonelst.Dalert[0]=='2'))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 2 Call");
bLockOut=true;
}
if((phonelst.Dalert[0]=='1'))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 1 Call");
bLockOut=true;
}
if((phonelst.Dalert[0]=='0'))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 0 Call");
bLockOut=true;
}
if((phonelst.Dalert[0]== 0x00))
{
WriteToStatusBox(" Monitor Mode: Locked Out Level 0 Call");
bLockOut=true;
}
}
if(bAquire == true)
{
if((phonelst.Dalert[0]=='3'))
{
bLockOut=true;
}
if((phonelst.Dalert[0]=='2'))
{
bLockOut=true;
}
if((phonelst.Dalert[0]=='1'))
{
bLockOut=true;
}
}
}
}
END:
TRACE("%s\n",chDDIdataBuffer);
return;
}
void CCELLULARDlg::OnErrspaceEditStatus()
{
m_Edit_Status.Clear();
WriteToStatusBox(" Status Edit Box Out of Memory");
}
void CCELLULARDlg::amend_record(void)
{
show_database();
if((phonelst.amend())!= IM_OK)
{
if((phonelst.amend())!= IM_OK)
{
if((phonelst.amend())!= IM_OK)
{
char chTempstring[500];
char *pchTempstring = chTempstring;
sprintf(pchTempstring,"ERROR : In phonelst.amend routine\nWhere : %s\n"
"number = %s\n phonelst.number = %s\n",chWhereErrorOccured,chPhoneNumber,phonelst.Dphone);
MyError(pchTempstring);
// WriteDebugLog(pchTempstring);
}
}
}
}
void CCELLULARDlg::insert_record(void)
{
show_database();
if((phonelst.insert())!= IM_OK)
{
if((phonelst.insert())!= IM_OK)
{
if((phonelst.insert())!= IM_OK)
{
char chTempstring[500];
char *pchTempstring = chTempstring;
sprintf(pchTempstring,"ERROR : In phonelst.insert routine\n"
"number = %s\nphonelst.number = %s\n",chPhoneNumber,phonelst.Dphone);
MyError(pchTempstring);
}
}
}
}
void CCELLULARDlg::show_database(void)
{
m_EditPhone.SetWindowText(phonelst.Dphone);
m_EditName.SetWindowText(phonelst.Dname);
m_EditName2.SetWindowText(phonelst.Dname2);
m_EditArea.SetWindowText(phonelst.Darea);
m_EditOccupation.SetWindowText(phonelst.Doccupation);
m_EditSubject.SetWindowText(phonelst.Dsubject);
m_EditGender.SetWindowText(phonelst.Dgender);
m_EditLanguage.SetWindowText(phonelst.Dlanguage);
m_EditDtmf.SetWindowText(phonelst.DDtmfDigits);
m_EditESN.SetWindowText(phonelst.Desn);
m_EditSCM.SetWindowText(phonelst.Dscm);
char chTempString[250];
char *pchTempString = chTempString;
sprintf(pchTempString,"%s %s",phonelst.DLastCallDate, phonelst.DLastCallTime);
m_EditLastCall.SetWindowText(pchTempString);
sprintf(pchTempString,"%d",phonelst.DTotalCalls);
m_Edit_TotalCalls.SetWindowText(pchTempString);
m_EditInfo1.SetWindowText(phonelst.Dinfo1);
m_EditInfo2.SetWindowText(phonelst.Dinfo2);
m_EditInfo3.SetWindowText(phonelst.Dinfo3);
m_EditLinkedFile.SetWindowText(phonelst.DLinkedFile);
if(phonelst.Dscm[1]=='0'||'1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9'||'A'||'B'||'C'||'D'||'E'||'F')
{
show_scm();
m_EditPhoneModel.SetWindowText(chSCMstring);
}
if(phonelst.Desn[0]!=0x00)
{
manufact.hex[0]=phonelst.Desn[0];
manufact.hex[1]=phonelst.Desn[1];
if((manufact.find()== IM_OK))
{
m_EditPhoneType.SetWindowText(manufact.man);
}
if((manufact.find()!= IM_OK))
{
m_EditPhoneType.SetWindowText("Unknown Phone Manufacture");
}
}
else
{
m_EditPhoneType.SetWindowText(" ");
}
m_EditModemCalls.SetWindowText(phonelst.Dmodem);
m_EditFaxCalls.SetWindowText(phonelst.Dfax);
m_EditAlertLevel.SetWindowText(phonelst.Dalert);
m_EditRecordCall.SetWindowText(phonelst.DRecordCall);
m_EditChannelAB.SetWindowText(phonelst.Dtype);
}
void CCELLULARDlg::search(void)
{
if((phonelst.find()== IM_OK))
{
bNewNumber=false;
show_database();
/*
if(phonelst.DLinkedFile[0]!=0x00)
{
get_linkfile();
}
*/
}
else
{
if(bNewTest==true)
{
bNewNumber = true;
return;
}
phonelst.clear_buf();
bAmend=false;
}
}
void CCELLULARDlg::which_channel(void)
{
bool bOK = false;
TRACE("which_channel chFrequency = %s\n",chFrequency);
strcpy(chGoFrequency,chFrequency);
ConvertGoFrequency();
//// BAND 'A' //////////////////////////////////
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.990")==0) // FORWARD
{
chChannelBand[0]='A';
bReverseChannel = false;
strcpy(chChannel,"333");
strcpy(chReverseChannel,"834.990");
bOK = true;
}
if(strcmp(chFrequency,"834.990")==0) //REVERSE
{
chChannelBand[0]='A';
bReverseChannel = true;
strcpy(chChannel,"333");
strcpy(chForwardChannel,"879.990");
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.960")==0) // FORWARD
{
chChannelBand[0]='A';
bReverseChannel = false;
strcpy(chChannel,"332");
strcpy(chReverseChannel,"834.960");
bOK = true;
}
if(strcmp(chFrequency,"834.960")==0)//REVERSE
{
chChannelBand[0]='A';
bReverseChannel = true;
strcpy(chChannel,"332");
strcpy(chForwardChannel,"879.960");
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.930")==0) // FORWARD
{
chChannelBand[0]='A';
bReverseChannel = false;
strcpy(chChannel,"331");
strcpy(chReverseChannel,"834.930");
bOK = true;
}
if(strcmp(chFrequency,"834.930")==0)//REVERSE
{
chChannelBand[0]='A';
bReverseChannel = true;
strcpy(chChannel,"331");
strcpy(chForwardChannel,"879.930");
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.900")==0) // FORWARD
{
strcpy(chChannel,"330");
strcpy(chReverseChannel,"834.900");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.900")==0)//REVERSE
{
strcpy(chChannel,"330");
strcpy(chForwardChannel,"879.900");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.870")==0) // FORWARD
{
strcpy(chChannel,"329");
strcpy(chReverseChannel,"834.870");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.870")==0)//REVERSE
{
strcpy(chChannel,"329");
strcpy(chForwardChannel,"879.870");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.840")==0) // FORWARD
{
strcpy(chChannel,"328");
strcpy(chReverseChannel,"834.840");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.840")==0)//REVERSE
{
strcpy(chChannel,"328");
strcpy(chForwardChannel,"879.840");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.810")==0) // FORWARD
{
strcpy(chChannel,"327");
strcpy(chReverseChannel,"834.810");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.810")==0)//REVERSE
{
strcpy(chChannel,"327");
strcpy(chForwardChannel,"879.810");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.780")==0) // FORWARD
{
strcpy(chChannel,"326");
strcpy(chReverseChannel,"834.780");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.780")==0)//REVERSE
{
strcpy(chChannel,"326");
strcpy(chForwardChannel,"879.780");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.750")==0) // FORWARD
{
strcpy(chChannel,"325");
strcpy(chReverseChannel,"834.750");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.750")==0)//REVERSE
{
strcpy(chChannel,"325");
strcpy(chForwardChannel,"879.750");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.720")==0) // FORWARD
{
strcpy(chChannel,"324");
strcpy(chReverseChannel,"834.720");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.720")==0)//REVERSE
{
strcpy(chChannel,"324");
strcpy(chForwardChannel,"879.720");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.690")==0) // FORWARD
{
strcpy(chChannel,"323");
strcpy(chReverseChannel,"834.690");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.690")==0)//REVERSE
{
strcpy(chChannel,"323");
strcpy(chForwardChannel,"879.690");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.660")==0) // FORWARD
{
strcpy(chChannel,"322");
strcpy(chReverseChannel,"834.660");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.660")==0)//REVERSE
{
strcpy(chChannel,"322");
strcpy(chForwardChannel,"879.660");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.630")==0) // FORWARD
{
strcpy(chChannel,"321");
strcpy(chReverseChannel,"834.630");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.630")==0)//REVERSE
{
strcpy(chChannel,"321");
strcpy(chForwardChannel,"879.630");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.600")==0) // FORWARD
{
strcpy(chChannel,"320");
strcpy(chReverseChannel,"834.600");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.600")==0)//REVERSE
{
strcpy(chChannel,"320");
strcpy(chForwardChannel,"879.600");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.570")==0) // FORWARD
{
strcpy(chChannel,"319");
strcpy(chReverseChannel,"834.570");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.570")==0)//REVERSE
{
strcpy(chChannel,"319");
strcpy(chForwardChannel,"879.570");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.540")==0) // FORWARD
{
strcpy(chChannel,"318");
strcpy(chReverseChannel,"834.540");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.540")==0)//REVERSE
{
strcpy(chChannel,"318");
strcpy(chForwardChannel,"879.540");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.510")==0) // FORWARD
{
strcpy(chChannel,"317");
strcpy(chReverseChannel,"834.510");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.510")==0)//REVERSE
{
strcpy(chChannel,"317");
strcpy(chForwardChannel,"879.510");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.480")==0) // FORWARD
{
strcpy(chChannel,"316");
strcpy(chReverseChannel,"834.480");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.480")==0)//REVERSE
{
strcpy(chChannel,"316");
strcpy(chForwardChannel,"879.480");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.450")==0) // FORWARD
{
strcpy(chChannel,"315");
strcpy(chReverseChannel,"834.450");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.450")==0)//REVERSE
{
strcpy(chChannel,"315");
strcpy(chForwardChannel,"879.450");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.420")==0) // FORWARD
{
strcpy(chChannel,"314");
strcpy(chReverseChannel,"834.420");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.420")==0)//REVERSE
{
strcpy(chChannel,"314");
strcpy(chForwardChannel,"879.420");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"879.390")==0) // FORWARD
{
strcpy(chChannel,"313");
strcpy(chReverseChannel,"834.390");
bReverseChannel = false;
chChannelBand[0]='A';
bOK = true;
}
if(strcmp(chFrequency,"834.390")==0)//REVERSE
{
strcpy(chChannel,"313");
strcpy(chForwardChannel,"879.390");
bReverseChannel = true;
chChannelBand[0]='A';
bOK = true;
}
///////////// Band 'B' /////////////////////////
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.020")==0) // FORWARD
{
strcpy(chChannel,"334");
strcpy(chReverseChannel,"835.020");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.020")==0)//REVERSE
{
strcpy(chChannel,"334");
strcpy(chForwardChannel,"880.020");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.050")==0) // FORWARD
{
strcpy(chChannel,"335");
strcpy(chReverseChannel,"835.050");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.050")==0)//REVERSE
{
strcpy(chChannel,"335");
strcpy(chForwardChannel,"880.050");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.080")==0) // FORWARD
{
strcpy(chChannel,"336");
strcpy(chReverseChannel,"835.080");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.080")==0)//REVERSE
{
strcpy(chChannel,"336");
strcpy(chForwardChannel,"880.080");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.110")==0) // FORWARD
{
strcpy(chChannel,"337");
strcpy(chReverseChannel,"835.110");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.110")==0)//REVERSE
{
strcpy(chChannel,"337");
strcpy(chForwardChannel,"880.110");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.140")==0) // FORWARD
{
strcpy(chChannel,"338");
strcpy(chReverseChannel,"835.140");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.140")==0)//REVERSE
{
strcpy(chChannel,"338");
strcpy(chForwardChannel,"880.140");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.170")==0) // FORWARD
{
strcpy(chChannel,"339");
strcpy(chReverseChannel,"835.170");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.170")==0)//REVERSE
{
strcpy(chChannel,"339");
strcpy(chForwardChannel,"880.170");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.200")==0) // FORWARD
{
strcpy(chChannel,"340");
strcpy(chReverseChannel,"835.200");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.200")==0)//REVERSE
{
strcpy(chChannel,"340");
strcpy(chForwardChannel,"880.200");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.230")==0) // FORWARD
{
strcpy(chChannel,"341");
strcpy(chReverseChannel,"835.230");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.230")==0)//REVERSE
{
strcpy(chChannel,"341");
strcpy(chForwardChannel,"880.230");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.260")==0) // FORWARD
{
strcpy(chChannel,"342");
strcpy(chReverseChannel,"835.260");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.260")==0)//REVERSE
{
strcpy(chChannel,"342");
strcpy(chForwardChannel,"880.260");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.290")==0) // FORWARD
{
strcpy(chChannel,"343");
strcpy(chReverseChannel,"835.290");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.290")==0)//REVERSE
{
strcpy(chChannel,"343");
strcpy(chForwardChannel,"880.290");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.320")==0) // FORWARD
{
strcpy(chChannel,"344");
strcpy(chReverseChannel,"835.320");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.320")==0)//REVERSE
{
strcpy(chChannel,"344");
strcpy(chForwardChannel,"880.320");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.350")==0) // FORWARD
{
strcpy(chChannel,"345");
strcpy(chReverseChannel,"835.350");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.350")==0)//REVERSE
{
strcpy(chChannel,"345");
strcpy(chForwardChannel,"880.350");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.380")==0) // FORWARD
{
strcpy(chChannel,"346");
strcpy(chReverseChannel,"835.380");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.380")==0)//REVERSE
{
strcpy(chChannel,"346");
strcpy(chForwardChannel,"880.380");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.410")==0) // FORWARD
{
strcpy(chChannel,"347");
strcpy(chReverseChannel,"835.410");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.410")==0)//REVERSE
{
strcpy(chChannel,"347");
strcpy(chForwardChannel,"880.410");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.440")==0) // FORWARD
{
strcpy(chChannel,"348");
strcpy(chReverseChannel,"835.440");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.440")==0)//REVERSE
{
strcpy(chChannel,"348");
strcpy(chForwardChannel,"880.440");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.470")==0) // FORWARD
{
strcpy(chChannel,"349");
strcpy(chReverseChannel,"835.470");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.470")==0)//REVERSE
{
strcpy(chChannel,"349");
strcpy(chForwardChannel,"880.470");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.500")==0) // FORWARD
{
strcpy(chChannel,"350");
strcpy(chReverseChannel,"835.500");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.500")==0)//REVERSE
{
strcpy(chChannel,"350");
strcpy(chForwardChannel,"880.500");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.530")==0) // FORWARD
{
strcpy(chChannel,"351");
strcpy(chReverseChannel,"835.530");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.530")==0)//REVERSE
{
strcpy(chChannel,"351");
strcpy(chForwardChannel,"880.530");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.560")==0) // FORWARD
{
strcpy(chChannel,"352");
strcpy(chReverseChannel,"835.560");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.560")==0)//REVERSE
{
strcpy(chChannel,"352");
strcpy(chForwardChannel,"880.560");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.590")==0) // FORWARD
{
strcpy(chChannel,"353");
strcpy(chReverseChannel,"835.590");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.590")==0)//REVERSE
{
strcpy(chChannel,"353");
strcpy(chForwardChannel,"880.590");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
////////////////////////////////////////////////
if(strcmp(chFrequency,"880.620")==0) // FORWARD
{
strcpy(chChannel,"354");
strcpy(chReverseChannel,"835.620");
bReverseChannel = false;
chChannelBand[0]='B';
bOK = true;
}
if(strcmp(chFrequency,"835.620")==0)//REVERSE
{
strcpy(chChannel,"354");
strcpy(chForwardChannel,"880.620");
bReverseChannel = true;
chChannelBand[0]='B';
bOK = true;
}
if(bOK != true)
{
MyError("This is not a valid Control Channel Frequency\nPlease choose a different one");
return;
}
if(bReverseChannel == false)
{
m_ButtonSwitchControlType.SetWindowText("Switch To Reverse Control");
strcpy(chChannelType,"Forward Control");
}
else
{
m_ButtonSwitchControlType.SetWindowText("Switch To Forward Control");
strcpy(chChannelType,"Reverse Control");
}
/*
if (iWhichcontrolChannel == 1)
{
stanum=0x80; endnum=0x50;
//strcpy(name,"TELCEL");
strcpy(chChannelType,"Forward Control");
strcpy(chGoFrequency,"880.500");
// strcpy(chChannel,"0350");
chChannelBand[0]='B';
}
if (iWhichcontrolChannel == 2)
{
//strcpy(name,"Baja Cellular");
strcpy(chChannelType,"Forward Control");
// Most of the time this one
stanum=0x79; endnum=0x54;
strcpy(chGoFrequency,"879.540");
// strcpy(chChannel,"0318");
// But sometimes this one
//stanum=0x79; endnum=0x42;
//strcpy(chGoFrequency,"879.420");
//strcpy(chChannel,"0314");
chChannelBand[0]='A';
}
if (iWhichcontrolChannel == 3)
{
stanum=0x35; endnum=0x50;
//strcpy(name,"TELCEL");
strcpy(chChannelType,"Reverse Control");
strcpy(chGoFrequency,"835.500");
// strcpy(chChannel,"0350");
chChannelBand[0]='B';
}
if (iWhichcontrolChannel == 4)
{
stanum=0x34; endnum=0x54;
//strcpy(name,"Baja Cellular");
strcpy(chChannelType,"Reverse Control");
strcpy(chGoFrequency,"834.540");
// strcpy(chChannel,"0318");
// But sometimes this one
// stanum=0x34; endnum=0x42;
// strcpy(chGoFrequency,"834.420");
// strcpy(chChannel,"0314");
chChannelBand[0]='A';
}
*/
UpdateChannelStats();
}
void CCELLULARDlg::InitalizeOS456(void)
{
WriteToStatusBox(" Initalizing OS456");
ComInit(iCommPortOS456);
if(ComValid(iCommPortOS456))
{
ComSetState(iCommPortOS456,9600,8,1,'N',SIGNAL_NONE);
ComBufClear(iCommPortOS456,DIR_INC);
ComBufClear(iCommPortOS456,DIR_OUT);
WriteToStatusBox(" OS456 Comm Port Initalized @ 9600 BPS");
}
else
{
char chTempString[250];
char *pchTempString = chTempString;
sprintf(pchTempString,"Com Port %d is not available or is in use",iCommPortOS456+1);
MyError(pchTempString);
return;
}
ComDTROn(iCommPortOS456); // set DTR
ComRTSOn(iCommPortOS456); // set RTS
osremote();
osmode();
osspeakeroff();
osfreq(endnum,stanum);
}
// OS456 General access Commands
void CCELLULARDlg::os456(void)
{
// Sleep(100);
Sleep(30);
ComWrite(iCommPortOS456,(char)0xFE);
ComWrite(iCommPortOS456,(char)0xFE);
ComWrite(iCommPortOS456,(char)0x80);
ComWrite(iCommPortOS456,(char)0xE0);
}
// Switch OS456 transfer mode to FM-narrowband
void CCELLULARDlg::osmode(void)
{
os456();
ComWrite(iCommPortOS456,(char)0x01);
ComWrite(iCommPortOS456,(char)0x05);
ComWrite(iCommPortOS456,(char)0xFD);
}
// Switch OS456 to Local Control
void CCELLULARDlg::oslocal(void)
{
os456();
ComWrite(iCommPortOS456,(char)0x7F);
ComWrite(iCommPortOS456,(char)0x01);
ComWrite(iCommPortOS456,(char)0xFD);
}
// Switch OS456 to Remote Control
void CCELLULARDlg::osremote(void)
{
os456();
ComWrite(iCommPortOS456,(char)0x7F);
ComWrite(iCommPortOS456,(char)0x02);
ComWrite(iCommPortOS456,(char)0xFD);
}
// Switch OS456 Frequency
void CCELLULARDlg::osfreq(int endnum,int stanum)
{
int iTest = 1;
again:
os456();
ComWrite(iCommPortOS456,(char)0x00); // always
ComWrite(iCommPortOS456,(char)0x00); // always
ComWrite(iCommPortOS456,(char)0x00); // always
ComWrite(iCommPortOS456,(char)endnum); // 880.XX00 0x50
ComWrite(iCommPortOS456,(char)stanum); // 8XX.5000 0x80
ComWrite(iCommPortOS456,(char)0x08); // X80.5000 (always 8 for 800 band cellular)
ComWrite(iCommPortOS456,(char)0xFD); // always
if(iTest==5)
{
WriteToStatusBox(" Error : in fuction [osfreqcheck] (5 Tries!)");
return;
}
iTest ++;
if (osfreqcheck()== 1){ goto again;}
// signal strength
// Sleep(100);
ossignalstr();
UpdateChannelStats();
}
int CCELLULARDlg::osfreqcheck(void)
{
/*
Sleep(250);
ComBufClear(iCommPortOS456,DIR_INC);
osreadfreq();
Sleep(250);
char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,ch16;
if(ComRead(iCommPortOS456,&ch1)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 1");
}
if(ComRead(iCommPortOS456,&ch2)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 2");
}
if(ComRead(iCommPortOS456,&ch3)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 3");
}
if(ComRead(iCommPortOS456,&ch4)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 4");
}
if(ComRead(iCommPortOS456,&ch5)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 5");
}
if(ComRead(iCommPortOS456,&ch6)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 6");
}
if(ComRead(iCommPortOS456,&ch7)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 7");
}
if(ComRead(iCommPortOS456,&ch8)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 8");
}
if(ComRead(iCommPortOS456,&ch9)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 9");
}
if(ComRead(iCommPortOS456,&ch10)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 10");
}
if(ComRead(iCommPortOS456,&ch11)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 11");
}
if(ComRead(iCommPortOS456,&ch12)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 12");
}
if(ComRead(iCommPortOS456,&ch13)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 13");
}
if(ComRead(iCommPortOS456,&ch14)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 14");
}
if(ComRead(iCommPortOS456,&ch15)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 15");
}
if(ComRead(iCommPortOS456,&ch16)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 Frequency reading byte 16");
}
char chTempString[500];
char *pchTempString = chTempString;
TRACE("FREQ DATA: 1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X] 14[%2X] 15[%2X] 16[%2X]\n",
ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,ch16);
TRACE("FREQ2 DATA: endnum[%2X] stanum[%2X] \n",endnum,stanum);
if ((ch12!=0x00)|| (ch13!=0x00) || (ch14!=endnum) || (ch15!=stanum) || (ch16!=0x08))
//&& ((ch14!=0x00)|| (ch15!=0x00) || (ch16!=endnum) || (ch17!=stanum) || (ch18!=0x08))
// && ((ch15!=0x00)|| (ch16!=0x00) || (ch17!=endnum) || (ch18!=stanum) || (ch19!=0x08)) )
{
WriteToStatusBox(" ERROR: OS456 Frequency Check Failed so trying again");
TRACE("FREQ ERROR\n");
// char chTempString[250];
//char *pchTempString = chTempString;
//sprintf(pchTempString," [%c][%c][%c]",ch17,ch18,ch19);
//WriteToStatusBox(pchTempString);
return 1;
}
*/
return OK;
}
void CCELLULARDlg::osreadfreq(void)
{
os456();
ComWrite(iCommPortOS456,(char)0x03);
ComWrite(iCommPortOS456,(char)0xFD);
}
// Switch OS456 Speaker OFF
void CCELLULARDlg::osspeakeroff(void)
{
int iTest=1;
again:
ComBufClear(iCommPortOS456,DIR_INC);
os456();
ComWrite(iCommPortOS456,(char)0x7F);
ComWrite(iCommPortOS456,(char)0x0B);
ComWrite(iCommPortOS456,(char)0xFD);
iTest++;
if(iTest==5)
{
MyError("Error : in fuction [osspeakercheck (osspeakeroff)] (5 Tries!)");
}
iTest++;
if(osspeakercheck()== 1){ goto again;}
}
// Switch OS456 Speaker ON
void CCELLULARDlg::osspeakeron(void)
{
int iTest=1;
again:
ComBufClear(iCommPortOS456,DIR_INC);
os456();
ComWrite(iCommPortOS456,(char)0x7F);
ComWrite(iCommPortOS456,(char)0x0A);
ComWrite(iCommPortOS456,(char)0xFD);
iTest++;
if(iTest==5)
{
MyError("Error : in fuction [osspeakercheck (osspeakeron)] (5 Tries!)");
}
iTest++;
if (osspeakercheck()== 1){ goto again;}
}
int CCELLULARDlg::osspeakercheck(void)
{
char ch1=0,ch2=0,ch3=0,ch4=0,ch5=0,ch6=0,ch7=0,ch8=0,ch9=0,ch10=0,ch11=0,ch12=0,ch13=0;
Sleep(250);
// Sleep(30);
// TRYAGAIN:
// if(ComBufCount(iCommPortOS456,DIR_INC) >= 15)
{
if(ComRead(iCommPortOS456,&ch1)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 1");
}
if(ComRead(iCommPortOS456,&ch2)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 2");
}
if(ComRead(iCommPortOS456,&ch3)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 3");
}
if(ComRead(iCommPortOS456,&ch4)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 4");
}
if(ComRead(iCommPortOS456,&ch5)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 5");
}
if(ComRead(iCommPortOS456,&ch6)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 6");
}
if(ComRead(iCommPortOS456,&ch7)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 7");
}
if(ComRead(iCommPortOS456,&ch8)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 8");
}
if(ComRead(iCommPortOS456,&ch9)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 9");
}
if(ComRead(iCommPortOS456,&ch10)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 10");
}
if(ComRead(iCommPortOS456,&ch11)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 11");
}
if(ComRead(iCommPortOS456,&ch12)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 12");
}
if(ComRead(iCommPortOS456,&ch13)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 13");
}
}
/*
else
{
Sleep(100);
char chTempString[100];
char *pchTempString = chTempString;
sprintf(pchTempString," OS456 Buffercount = %d ",ComBufCount(iCommPortOS456,DIR_INC) );
WriteToStatusBox(pchTempString);
goto TRYAGAIN;
}
*/
char chTempString[500];
char *pchTempString = chTempString;
TRACE("SPEAKER DATA:1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X]\n",
ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13);
if((ch10!=0xFFFFFFE0)|| (ch11!=0xFFFFFF80) || (ch12!=0xFFFFFFFB) || (ch13!=0xFFFFFFFD))
// if(((ch10!=0xE0)|| (ch11!=0x80) || (ch12!=0xFB))
// &&((ch12!=0xE0)|| (ch13!=0x80) || (ch14!=0xFB))
// &&((ch13!=0xE0)|| (ch14!=0x80) || (ch15!=0xFB)))
{
WriteToStatusBox(" ERROR: OS456 Speaker Check Failed!");
return 1;
}
else
{
// WriteToStatusBox(" OS456 Speaker Check Returned OK");
return OK;
}
}
void CCELLULARDlg::ossignalstr(void)
{
ComBufClear(iCommPortOS456,DIR_INC);
os456();
ComWrite(iCommPortOS456,(char)0x15);
ComWrite(iCommPortOS456,(char)0x02);
ComWrite(iCommPortOS456,(char)0xFD);
Sleep(30);
char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15;
if(ComRead(iCommPortOS456,&ch1)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 1");
}
if(ComRead(iCommPortOS456,&ch2)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 2");
}
if(ComRead(iCommPortOS456,&ch3)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 3");
}
if(ComRead(iCommPortOS456,&ch4)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 4");
}
if(ComRead(iCommPortOS456,&ch5)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 5");
}
if(ComRead(iCommPortOS456,&ch6)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 6");
}
if(ComRead(iCommPortOS456,&ch7)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 7");
}
if(ComRead(iCommPortOS456,&ch8)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 8");
}
if(ComRead(iCommPortOS456,&ch9)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 9");
}
if(ComRead(iCommPortOS456,&ch10)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 10");
}
if(ComRead(iCommPortOS456,&ch11)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 11");
}
if(ComRead(iCommPortOS456,&ch12)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 12");
}
if(ComRead(iCommPortOS456,&ch13)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 13");
}
if(ComRead(iCommPortOS456,&ch14)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 14");
}
if(ComRead(iCommPortOS456,&ch15)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 15");
}
// sprintf(chSignalStrength,"-%X.%X dBm",ch14,ch15);
if(ch14 == 0x00)
{
if(ch15 == 0x00)
{
sprintf(chSignalStrength,"- 0 dBm",ch15);
}
else if(ch15 == 0x01)
{
sprintf(chSignalStrength,"- 1 dBm",ch15);
}
else if(ch15 == 0x02)
{
sprintf(chSignalStrength,"- 2 dBm",ch15);
}
else if(ch15 == 0x03)
{
sprintf(chSignalStrength,"- 3 dBm",ch15);
}
else if(ch15 == 0x04)
{
sprintf(chSignalStrength,"- 4 dBm",ch15);
}
else if(ch15 == 0x05)
{
sprintf(chSignalStrength,"- 5 dBm",ch15);
}
else if(ch15 == 0x06)
{
sprintf(chSignalStrength,"- 6 dBm",ch15);
}
else if(ch15 == 0x07)
{
sprintf(chSignalStrength,"- 7 dBm",ch15);
}
else if(ch15 == 0x08)
{
sprintf(chSignalStrength,"- 8 dBm",ch15);
}
else if(ch15 == 0x09)
{
sprintf(chSignalStrength,"- 9 dBm",ch15);
}
else if(ch15 >= 0x10)
{
sprintf(chSignalStrength,"- %X dBm",ch15);
}
}
if(ch14 == 0x01)
{
if(ch15 == 0x00)
{
sprintf(chSignalStrength,"- 100 dBm",ch15);
}
else if(ch15 == 0x01)
{
sprintf(chSignalStrength,"- 101 dBm",ch15);
}
else if(ch15 == 0x02)
{
sprintf(chSignalStrength,"- 102 dBm",ch15);
}
else if(ch15 == 0x03)
{
sprintf(chSignalStrength,"- 103 dBm",ch15);
}
else if(ch15 == 0x04)
{
sprintf(chSignalStrength,"- 104 dBm",ch15);
}
else if(ch15 == 0x05)
{
sprintf(chSignalStrength,"- 105 dBm",ch15);
}
else if(ch15 == 0x06)
{
sprintf(chSignalStrength,"- 106 dBm",ch15);
}
else if(ch15 == 0x07)
{
sprintf(chSignalStrength,"- 107 dBm",ch15);
}
else if(ch15 == 0x08)
{
sprintf(chSignalStrength,"- 108 dBm",ch15);
}
else if(ch15 == 0x09)
{
sprintf(chSignalStrength,"- 109 dBm",ch15);
}
else if(ch15 >= 0x10)
{
sprintf(chSignalStrength,"- 1%X dBm",ch15);
}
}
m_EditSignalStrength.SetWindowText(chSignalStrength);
char chTempString[100];
char *pchTempString = chTempString;
sprintf(pchTempString,"%X%X",ch14,ch15);
int iSignal = atoi(pchTempString);
if(iSignal <= 125)
{
if(iSignal <= 100)
{
m_ProgressSignal.SetPos(25);
}
else if(iSignal == 101)
{
m_ProgressSignal.SetPos(24);
}
else if(iSignal == 102)
{
m_ProgressSignal.SetPos(23);
}
else if(iSignal == 103)
{
m_ProgressSignal.SetPos(22);
}
else if(iSignal == 104)
{
m_ProgressSignal.SetPos(21);
}
else if(iSignal == 105)
{
m_ProgressSignal.SetPos(20);
}
else if(iSignal == 106)
{
m_ProgressSignal.SetPos(19);
}
else if(iSignal == 107)
{
m_ProgressSignal.SetPos(18);
}
else if(iSignal == 108)
{
m_ProgressSignal.SetPos(17);
}
else if(iSignal == 109)
{
m_ProgressSignal.SetPos(16);
}
else if(iSignal == 110)
{
m_ProgressSignal.SetPos(15);
}
else if(iSignal == 111)
{
m_ProgressSignal.SetPos(14);
}
else if(iSignal == 112)
{
m_ProgressSignal.SetPos(13);
}
else if(iSignal == 113)
{
m_ProgressSignal.SetPos(12);
}
else if(iSignal == 114)
{
m_ProgressSignal.SetPos(11);
}
else if(iSignal == 115)
{
m_ProgressSignal.SetPos(10);
}
else if(iSignal == 116)
{
m_ProgressSignal.SetPos(9);
}
else if(iSignal == 117)
{
m_ProgressSignal.SetPos(8);
}
else if(iSignal == 118)
{
m_ProgressSignal.SetPos(7);
}
else if(iSignal == 119)
{
m_ProgressSignal.SetPos(6);
}
else if(iSignal == 120)
{
m_ProgressSignal.SetPos(5);
}
else if(iSignal == 121)
{
m_ProgressSignal.SetPos(4);
}
else if(iSignal == 122)
{
m_ProgressSignal.SetPos(3);
}
else if(iSignal == 123)
{
m_ProgressSignal.SetPos(2);
}
else if(iSignal == 124)
{
m_ProgressSignal.SetPos(1);
}
else if(iSignal == 125)
{
m_ProgressSignal.SetPos(0);
}
}
}
void CCELLULARDlg::ossquelch(void)
{
ComBufClear(iCommPortOS456,DIR_INC);
os456();
ComWrite(iCommPortOS456,(char)0x15);
ComWrite(iCommPortOS456,(char)0x01);
ComWrite(iCommPortOS456,(char)0xFD);
Sleep(250);
// Sleep(30);
char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14;
if(ComRead(iCommPortOS456,&ch1)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 1");
}
if(ComRead(iCommPortOS456,&ch2)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 2");
}
if(ComRead(iCommPortOS456,&ch3)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 3");
}
if(ComRead(iCommPortOS456,&ch4)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 4");
}
if(ComRead(iCommPortOS456,&ch5)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 5");
}
if(ComRead(iCommPortOS456,&ch6)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 6");
}
if(ComRead(iCommPortOS456,&ch7)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 7");
}
if(ComRead(iCommPortOS456,&ch8)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 8");
}
if(ComRead(iCommPortOS456,&ch9)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 9");
}
if(ComRead(iCommPortOS456,&ch10)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 10");
}
if(ComRead(iCommPortOS456,&ch11)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 11");
}
if(ComRead(iCommPortOS456,&ch12)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 12");
}
if(ComRead(iCommPortOS456,&ch13)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 13");
}
if(ComRead(iCommPortOS456,&ch14)==FALSE)
{
WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 14");
}
char chTempString[500];
char *pchTempString = chTempString;
TRACE("SQUELCH DATA: 1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X] 14[%2X]\n",
ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14);
if (ch14==0x00)
{
WriteToStatusBox(" OS456 reports Squelch is CLOSED");
squelch = CLOSED;
}
if (ch14==0x01)
{
TRACE("OS456 reports Squelch is OPEN");
squelch = OPEN;
}
}
void CCELLULARDlg::SetDDIvoiceMode(void)
{
WriteToStatusBox(" Sending DDI Command to switch to VOICE mode.");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'V');
}
void CCELLULARDlg::SetDDItoControlChannel(void)
{
WriteToStatusBox(" Sending DDI Command to switch to Control Channel");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'C');
}
void CCELLULARDlg::SetDDItoForward(void)
{
WriteToStatusBox(" Sending DDI Command to switch to Forward Channel Mode");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'r');
bReverseChannel = false;
}
void CCELLULARDlg::SetDDItoReverse(void)
{
WriteToStatusBox(" Sending DDI Command to switch to Reverse Channel Mode");
ComWrite(iCommPortDDI,'-');
ComWrite(iCommPortDDI,'R');
bReverseChannel = true;
}
void CCELLULARDlg::check_call_time(void)
{
time_t current_time;
current_time=time(NULL);
if(current_time>=start_time+iMaxCallTime)
{
squelch=CLOSED;
}
}
void CCELLULARDlg::switch_to_voice(void)
{
MessageBeep(MB_OK);
/*
if(logit==TRUE)
{
fprintf(log," \n");
}
*/
ConvertGoFrequency();
SetDDIvoiceMode();
strcpy(chChannelType,"Forward Voice");
osfreq(endnum,stanum);
ComBufClear(iCommPortDDI,DIR_INC);
osspeakeron();
/*
for(j=0;j < BUFFERSIZE2 ;j++)
{
for(k=0;k < BUFFERLENGTH ;k++)
{voicebuffer[j][k] =(char) 0x00;}
}
whichbuffer2=1;
noofrings=0;
ring=FALSE;
*/
// call started
m_EditStart.SetWindowText(timeis);
m_EditCallEnd.SetWindowText(" ");
start_time=time(NULL); // Start Second Timer for iMaxCallTime Function
if(phonelst.Darea[0]==0x00)
{
strcpy(phonelst.Darea,chArea);
}
if(phonelst.Dtype[0]==0x00)
{
phonelst.Dtype[0]=chChannelBand[0];
}
if(phonelst.DLastCallDate[0]==0x00)
{
strcpy(phonelst.DLastCallDate,dateis);
}
if(phonelst.DLastCallTime[0]==0x00)
{
strcpy(phonelst.DLastCallTime,d_timeis);
}
if(phonelst.Dphone[0]==0x00)
{
strcpy(phonelst.Dphone,chPhoneNumber);
phonelst.Dphone[14]=0x00;
insert_record();
}
show_database();
// Increment Total Call Counter
char chTempString[50];
char *pchTempString = chTempString;
iCallCounter_total++;
sprintf(pchTempString,"%d",iCallCounter_total);
m_Text_CallsTotal.SetWindowText(pchTempString);
if(phonelst.Dalert[0]==0x00||phonelst.Dalert[0]=='0')
{
iCallCounter_0++;
sprintf(pchTempString,"%d",iCallCounter_0);
m_Text_CallsLevel0.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='1')
{
iCallCounter_1++;
sprintf(pchTempString,"%d",iCallCounter_1);
m_Text_CallsLevel1.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='2')
{
iCallCounter_2++;
sprintf(pchTempString,"%d",iCallCounter_2);
m_Text_CallsLevel2.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='3')
{
iCallCounter_3++;
sprintf(pchTempString,"%d",iCallCounter_3);
m_Text_CallsLevel3.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='4')
{
iCallCounter_4++;
sprintf(pchTempString,"%d",iCallCounter_4);
m_Text_CallsLevel4.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='5')
{
iCallCounter_5++;
sprintf(pchTempString,"%d",iCallCounter_5);
m_Text_CallsLevel5.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='6')
{
iCallCounter_6++;
sprintf(pchTempString,"%d",iCallCounter_6);
m_Text_CallsLevel6.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='7')
{
iCallCounter_7++;
sprintf(pchTempString,"%d",iCallCounter_7);
m_Text_CallsLevel7.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='8')
{
iCallCounter_8++;
sprintf(pchTempString,"%d",iCallCounter_8);
m_Text_CallsLevel8.SetWindowText(pchTempString);
}
if(phonelst.Dalert[0]=='9')
{
iCallCounter_9++;
sprintf(pchTempString,"%d",iCallCounter_9);
m_Text_CallsLevel9.SetWindowText(pchTempString);
}
if(phonelst.Dmodem[0]=='Y')
{
iCallCounter_modem++;
sprintf(pchTempString,"%d",iCallCounter_modem);
m_Text_CallsModem.SetWindowText(pchTempString);
}
if(phonelst.Dfax[0]=='Y')
{
iCallCounter_fax++;
sprintf(pchTempString,"%d",iCallCounter_fax);
m_Text_CallsFax.SetWindowText(pchTempString);
}
/*
if(logit==TRUE)
{
fprintf(log,"\n %s %s (%s)\n"
,timeis,number,area);
fprintf(log," Changing to Voice Channel %s at %s MHz\n"
,chChannel,chGoFrequency);
fprintf(log," %s\n",chSignalStrength);
}
*/
bCancelCall = false;
// rev = FALSE;
/*
if(((phonelst.DRecordCall[0]==Y)||(bRecordAll==TRUE))&&(bRecording==FALSE))
{
rec_raw();
bRecording = TRUE;
record_on_box();
iCallCounter_record++;
sprintf(pchTempString,"%04d",iCallCounter_record);
m_Text_CallsRecorded.SetWindowText(pchTempString);
}
*/
Sleep(250); // This is to give the MCI Device time to respond
////////////////////////////////////////////////////////////////////////
#ifdef RECORD
DWORD dwReturn;
MCI_OPEN_PARMS mciOpenParms;
MCI_RECORD_PARMS mciRecordParms;
// Open a waveform-audio device with a new file for recording.
mciOpenParms.lpstrDeviceType = "waveaudio";
mciOpenParms.lpstrElementName = "";
if(dwReturn = mciSendCommand(0, MCI_OPEN,MCI_OPEN_ELEMENT | MCI_OPEN_TYPE,(DWORD)(LPVOID) &mciOpenParms))
{
MyError("Failed to open MCI device;");
return;
}
// The device opened successfully; get the device ID.
wDeviceID = mciOpenParms.wDeviceID;
// Begin recording and record for the specified number of
// milliseconds. Wait for recording to complete before continuing.
// Assume the default time format for the waveform-audio device
// (milliseconds).
//mciRecordParms.dwTo = dwMilliSeconds;
if(dwReturn = mciSendCommand(wDeviceID, MCI_RECORD,MCI_TO , (DWORD)(LPVOID) &mciRecordParms))
{
mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);
MyError("Failed to to tell MCI device to record.");
return;
}
////////////////////////////////////////////////////////////////////////
#endif
char chTotalTime[30];
char *pchTotalTime = chTotalTime;
strcpy(pchTotalTime,"NONE");
char chTempBuffer[500];
char *pchTempBuffer = chTempBuffer;
sprintf(pchTempBuffer," %s %s\tGoto Voice Chann\t%s",timeis,chPhoneNumber,chArea);
WriteToStatusBox(pchTempBuffer);
ossquelch();
for(int i=0; i < 5; i++)
{
if(squelch==CLOSED)
{
Sleep(100);
ossquelch();
}
else
{
break;
}
}
while(squelch==OPEN)
{
ossignalstr();
if(bGoReverseVoice == true)
{
bGoReverseVoice = false;
GoReverseVoice();
}
if(bGoForwardVoice == true)
{
bGoForwardVoice = false;
GoForwardVoice();
}
if(bHoldCall==false)
{
ossquelch();
check_call_time();
}
if(bCancelCall==true)
{
bCancelCall=false;
WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM MAIN FORWARD VOICE");
break;
}
time_t current_time;
current_time=time(NULL);
double fSeconds = difftime(current_time,start_time);
if(fSeconds < 60)
{
sprintf(pchTotalTime,"%.0f Seconds",fSeconds);
}
else
{
double fMinutes = fSeconds / 60;
sprintf(pchTotalTime,"%.2f Minutes",fMinutes);
}
m_EditCallTime.SetWindowText(pchTotalTime);
char i;
if(ComRead(iCommPortDDI,&i)==TRUE)
{
if(i==0x0D)
{
char chTempBuffer[500];
char *pchTempBuffer = chTempBuffer;
iBufferCounter=-1;
whattime();
AnalyzeDDIdata();
if(bGoto ==true)
{
ZeroMemVariables();
}
else
if(bVoiceGoto ==true)
{
sprintf(pchTempBuffer," %s %s\tGoto in Voice Function %s\t%s",timeis,chPhoneNumber,chGoFrequency,chArea);
WriteToStatusBox(pchTempBuffer);
ZeroMemVariables();
ConvertGoFrequency();
squelch=OPEN;
osfreq(endnum,stanum);
Sleep(100);
squelch=OPEN;
}
} // End if (i>1)
if((i>=0x20) && (i <=0x7A))
{
iBufferCounter++;
chDDIdataBuffer[iBufferCounter] = (char) i;;
}
}
} // End While
m_ButtonSwitchVoice.SetWindowText("Reverse Voice");
bVoiceForward = true;
// call ended
whattime();
m_EditCallEnd.SetWindowText(timeis);
strcpy(phonelst.DLastCallDate,dateis);
strcpy(phonelst.DLastCallTime,d_timeis);
phonelst.DTotalCalls++;
////////////////////////////////////////////////////////////////////////
iWaveFileNumber++;
WriteWhoFile(iWaveFileNumber,pchTotalTime);
UpdateCallList(iWaveFileNumber,pchTotalTime);
#ifdef RECORD
sprintf(chTempBuffer,"RECORD\\%d.WAV",iWaveFileNumber);
MCI_SAVE_PARMS mciSaveParms;
mciSaveParms.lpfilename = chTempBuffer;
// mciSaveParms.lpfilename = "tempfile.wav";
if(dwReturn = mciSendCommand(wDeviceID, MCI_SAVE,MCI_SAVE_FILE | MCI_WAIT, (DWORD)(LPVOID) &mciSaveParms))
{
mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);
MyError("Failed to SAVE MCI device wavefile;");
return;
}
////////////////////////////////////////////////////////////////////////
mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL);
#endif
CopyEditFieldsToDataBase();
strcpy(chWhereErrorOccured,"switch_to_voice");
amend_record(); // Error Because of this Amend Routine
ComBufClear(iCommPortDDI,DIR_INC); // Flush DDI Recieve Port so extra stuff doesnt appear when finished
ZeroMemVariables();
osspeakeroff();
SetDDItoControlChannel();
SetDDItoForward();
which_channel();
osfreq(endnum,stanum);
// UpdateChannelStats();
/*
if(logit==TRUE)
{
fprintf(log,"\n %s %s @ %s [%s]\n",name,type,chChannel,chGoFrequency);
fprintf(log," %s\n\n",chSignalStrength);
}
*/
}
/*
m_EditPhone.LimitText(14);
m_EditName.LimitText(30);
m_EditName2.LimitText(30);
m_EditArea.LimitText(30);
m_EditOccupation.LimitText(30);
m_EditSubject.LimitText(30);
m_EditLanguage.LimitText(10);
m_EditGender.LimitText(1);
m_EditInfo1.LimitText(30);
m_EditInfo2.LimitText(30);
m_EditInfo3.LimitText(30);
m_EditLinkedFile.LimitText(12);
m_EditModemCalls.LimitText(1);
m_EditFaxCalls.LimitText(1);
m_EditAlertLevel.LimitText(1);
m_EditRecordCall.LimitText(1);
m_EditDtmf.LimitText(30);
m_EditESN.LimitText(8);
m_EditSCM.LimitText(2);
*/
void CCELLULARDlg::OnButtonSkipvoicecall()
{
WriteToStatusBox(" Skip voice call button pressed");
bCancelCall=true;
}
void CCELLULARDlg::CopyEditFieldsToDataBase(void)
{
m_EditPhone.GetWindowText(phonelst.Dphone,15);
m_EditName.GetWindowText(phonelst.Dname,31);
m_EditName2.GetWindowText(phonelst.Dname2,31);
m_EditArea.GetWindowText(phonelst.Darea,31);
m_EditOccupation.GetWindowText(phonelst.Doccupation,31);
m_EditSubject.GetWindowText(phonelst.Dsubject,31);
m_EditLanguage.GetWindowText(phonelst.Dlanguage,11);
m_EditGender.GetWindowText(phonelst.Dgender,2);
m_EditInfo1.GetWindowText(phonelst.Dinfo1,31);
m_EditInfo2.GetWindowText(phonelst.Dinfo2,31);
m_EditInfo3.GetWindowText(phonelst.Dinfo3,31);
m_EditLinkedFile.GetWindowText(phonelst.DLinkedFile,13);
m_EditModemCalls.GetWindowText(phonelst.Dmodem,2);
m_EditFaxCalls.GetWindowText(phonelst.Dfax,2);
m_EditAlertLevel.GetWindowText(phonelst.Dalert,2);
m_EditRecordCall.GetWindowText(phonelst.DRecordCall,2);
m_EditDtmf.GetWindowText(phonelst.DDtmfDigits,31);
m_EditESN.GetWindowText(phonelst.Desn,9);
m_EditSCM.GetWindowText(phonelst.Dscm,3);
}
void CCELLULARDlg::OnButtonSaveData()
{
phonelst.clear_buf();
m_EditPhone.GetWindowText(phonelst.Dphone,15);
if((phonelst.find()== IM_OK))
{
CopyEditFieldsToDataBase();
strcpy(chWhereErrorOccured,"OnButtonSaveData");
amend_record();
}
else
{
MyError("Could not append record in fuction OnButtonSaveData");
}
}
void CCELLULARDlg::OnButtonFindPhone()
{
phonelst.clear_buf();
m_EditPhone.GetWindowText(phonelst.Dphone,15);
search();
if((bNewNumber == true)||(bAmend==false))
{
phonelst.clear_buf();
return;
}
}
void CCELLULARDlg::OnCheckHoldcall()
{
if(bHoldCall==false)
{
bHoldCall = true;
return;
}
else
{
bHoldCall = false;
return;
}
}
void CCELLULARDlg::UpdateCallList(int iWaveFileNumber,char *pchTotalTime)
{
char chTempBuffer[500];
char *pchTempBuffer = chTempBuffer;
if(phonelst.Dalert[0]==0x00)
{
phonelst.Dalert[0] = '0';
}
if(phonelst.Dname[0]==0x00)
{
sprintf(pchTempBuffer," %04d %s [%s] [%s] [%s] %s %s %s",iWaveFileNumber,timeis,chPhoneNumber,phonelst.Dalert,pchTotalTime,phonelst.Doccupation,phonelst.Dsubject,phonelst.Darea);
}
else
{
sprintf(pchTempBuffer," %04d %s [%s] [%s] [%s] (%s) %s %s",iWaveFileNumber,timeis, chPhoneNumber,phonelst.Dalert,pchTotalTime,phonelst.Dname,phonelst.Doccupation,phonelst.Dsubject);
}
WriteToCallBox(pchTempBuffer);
}
void CCELLULARDlg::WriteWhoFile(int iFilenum,char *pchTotalTime)
{
char chTempFileName[100];
char *pchTempFileName = chTempFileName;
sprintf(chTempFileName,"RECORD\\%d.TXT",iFilenum);
FILE *whofile;
if((whofile=fopen(chTempFileName,"wt"))==0)
{
MyError("Opening Whofile for write");
}
else
{
fprintf(whofile,"\n");
fprintf(whofile,"TIME : %s %s\n",dateis,timeis);
fprintf(whofile,"CALL TIME : %s\n",pchTotalTime);
fprintf(whofile,"NUMBER : %s\n",phonelst.Dphone);
fprintf(whofile,"AREA : %s\n",phonelst.Darea);
fprintf(whofile,"NAME : %s\n",phonelst.Dname);
fprintf(whofile,"NAME #2 : %s\n",phonelst.Dname2);
fprintf(whofile,"OCCUPATION : %s\n",phonelst.Doccupation);
fprintf(whofile,"SUBJECT : %s\n",phonelst.Dsubject);
fprintf(whofile,"GENDER : %s\n",phonelst.Dgender);
fprintf(whofile,"LANGUAGE : %s\n",phonelst.Dlanguage);
fprintf(whofile,"DTMF DIGITS: %s\n",phonelst.DDtmfDigits);
fprintf(whofile,"INFO #1 : %s\n",phonelst.Dinfo1);
fprintf(whofile,"INFO #2 : %s\n",phonelst.Dinfo2);
fprintf(whofile,"INFO #3 : %s\n",phonelst.Dinfo3);
fprintf(whofile,"LINKED FILE: %s\n",phonelst.DLinkedFile);
fprintf(whofile,"ESN : %s\n",phonelst.Desn);
fprintf(whofile,"SCM : %s\n",phonelst.Dscm);
fprintf(whofile,"LAST CALL : %s %s\n",phonelst.DLastCallDate,phonelst.DLastCallTime);
fprintf(whofile,"TOTAL CALLS: %d\n",phonelst.DTotalCalls);
fprintf(whofile,"MODEM : %s\n",phonelst.Dmodem);
fprintf(whofile,"FAX : %s\n",phonelst.Dfax);
fprintf(whofile,"ALERT LEVEL: %s\n",phonelst.Dalert);
fprintf(whofile,"RECORD CALL: %s\n",phonelst.DRecordCall);
fprintf(whofile,"SYSTEM TYPE: %s\n",phonelst.Dtype);
fprintf(whofile,"\n");
fclose(whofile);
}
}
#define BRIGHT_RED RGB(255, 0, 0)
#define BRIGHT_GREEN RGB(0, 255, 0)
#define PURPLE RGB(255, 0, 255)
#define BRIGHT_BLUE RGB(0, 0, 255)
#define BLUE RGB(0, 0, 100)
#define BLACK RGB(0,0,0)
HBRUSH CCELLULARDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
int nCtrl = pWnd->GetDlgCtrlID();
switch (nCtrl)
{
case IDC_EDIT_STATUS:
pDC->SetTextColor(BRIGHT_BLUE);
break;
case IDC_EDIT_CALLS:
pDC->SetTextColor(BRIGHT_RED);
break;
case IDC_TEXT_TOTALCALL:
case IDC_TEXT_CALLSLEVEL6:
case IDC_TEXT_CALLSLEVEL5:
case IDC_TEXT_CALLSLEVEL4:
case IDC_TEXT_CALLSLEVEL3:
case IDC_TEXT_CALLSLEVEL2:
case IDC_TEXT_CALLSLEVEL1:
case IDC_TEXT_CALLSLEVEL0:
pDC->SetTextColor(BLUE);
break;
case IDC_TEXT_CALLSLEVEL7:
case IDC_TEXT_CALLSLEVEL8:
case IDC_TEXT_CALLSLEVEL9:
case IDC_TEXT_CALLSRECORD:
case IDC_TEXT_CALLSMODEM:
case IDC_TEXT_CALLSFAX:
pDC->SetTextColor(BRIGHT_RED);
break;
default:
break;
}
return hbr;
}
void CCELLULARDlg::OnCheckAquire()
{
if(bAquire==false)
{
bAquire = true;
return;
}
else
{
bAquire = false;
return;
}
}
void CCELLULARDlg::OnCheckMonitor()
{
if(bMonitor==false)
{
bMonitor = true;
return;
}
else
{
bMonitor = false;
return;
}
}
void CCELLULARDlg::GoForwardVoice(void)
{
Sleep(250);
SetDDItoForward();
if(stanum ==0x54) stanum = 0x99;
if(stanum ==0x53) stanum = 0x98;
if(stanum ==0x52) stanum = 0x97;
if(stanum ==0x51) stanum = 0x96;
if(stanum ==0x50) stanum = 0x95;
if(stanum ==0x49) stanum = 0x94;
if(stanum ==0x48) stanum = 0x93;
if(stanum ==0x47) stanum = 0x92;
if(stanum ==0x46) stanum = 0x91;
if(stanum ==0x45) stanum = 0x90;
if(stanum ==0x44) stanum = 0x89;
if(stanum ==0x43) stanum = 0x88;
if(stanum ==0x42) stanum = 0x87;
if(stanum ==0x41) stanum = 0x86;
if(stanum ==0x40) stanum = 0x85;
if(stanum ==0x39) stanum = 0x84;
if(stanum ==0x38) stanum = 0x83;
if(stanum ==0x37) stanum = 0x82;
if(stanum ==0x36) stanum = 0x81;
if(stanum ==0x35) stanum = 0x80;
if(stanum ==0x34) stanum = 0x79;
if(stanum ==0x33) stanum = 0x78;
if(stanum ==0x32) stanum = 0x77;
if(stanum ==0x31) stanum = 0x76;
if(stanum ==0x30) stanum = 0x75;
if(stanum ==0x29) stanum = 0x74;
if(stanum ==0x28) stanum = 0x73;
if(stanum ==0x27) stanum = 0x72;
if(stanum ==0x26) stanum = 0x71;
if(stanum ==0x25) stanum = 0x70;
strcpy(chChannelType,"Forward Voice");
osfreq(endnum,stanum);
squelch=OPEN;
while(squelch==OPEN)
{
if(bCancelCall==true)
{
bCancelCall=false;
WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM SECONDARY FORWARD VOICE");
break;
}
}
}
void CCELLULARDlg::GoReverseVoice(void)
{
Sleep(250);
SetDDItoReverse();
if(stanum ==0x99) stanum = 0x54;
if(stanum ==0x98) stanum = 0x53;
if(stanum ==0x97) stanum = 0x52;
if(stanum ==0x96) stanum = 0x51;
if(stanum ==0x95) stanum = 0x50;
if(stanum ==0x94) stanum = 0x49;
if(stanum ==0x93) stanum = 0x48;
if(stanum ==0x92) stanum = 0x47;
if(stanum ==0x91) stanum = 0x46;
if(stanum ==0x90) stanum = 0x45;
if(stanum ==0x89) stanum = 0x44;
if(stanum ==0x88) stanum = 0x43;
if(stanum ==0x87) stanum = 0x42;
if(stanum ==0x86) stanum = 0x41;
if(stanum ==0x85) stanum = 0x40;
if(stanum ==0x84) stanum = 0x39;
if(stanum ==0x83) stanum = 0x38;
if(stanum ==0x82) stanum = 0x37;
if(stanum ==0x81) stanum = 0x36;
if(stanum ==0x80) stanum = 0x35;
if(stanum ==0x79) stanum = 0x34;
if(stanum ==0x78) stanum = 0x33;
if(stanum ==0x77) stanum = 0x32;
if(stanum ==0x76) stanum = 0x31;
if(stanum ==0x75) stanum = 0x30;
if(stanum ==0x74) stanum = 0x29;
if(stanum ==0x73) stanum = 0x28;
if(stanum ==0x72) stanum = 0x27;
if(stanum ==0x71) stanum = 0x26;
if(stanum ==0x70) stanum = 0x25;
strcpy(chChannelType,"Reverse Voice");
osfreq(endnum,stanum);
squelch=OPEN;
while(squelch==OPEN)
{
if(bHoldCall==false)
{
ossquelch();
check_call_time();
}
if(bCancelCall==true)
{
bCancelCall=false;
WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM REVERSE VOICE");
break;
}
}
GoForwardVoice();
squelch=OPEN;
}
void CCELLULARDlg::UpdateChannelStats(void)
{
char chTempString[25];
char *pchTempString = chTempString;
sprintf(pchTempString,"8%x.%x0 Mhz",stanum,endnum);
SetDlgItemText(IDC_TEXT_FREQUENCY,pchTempString);
SetDlgItemText(IDC_TEXT_CHANNELTYPE,chChannelType);
}
void CCELLULARDlg::show_scm(void)
{
::ZeroMemory(chSCMstring, sizeof(chSCMstring));
if (phonelst.Dscm[1]=='0')
{sprintf(chSCMstring,"666 Chan, Continuous, 3.0 Wts");}
if (phonelst.Dscm[1]=='1')
{sprintf(chSCMstring,"666 Chan, Continuous, 1.2 Wts");}
if (phonelst.Dscm[1]=='2')
{sprintf(chSCMstring,"666 Chan, Continuous, 0.6 Wts");}
if (phonelst.Dscm[1]=='3')
{sprintf(chSCMstring,"666 Chan, Continuous, Resv Wts");}
if (phonelst.Dscm[1]=='4')
{sprintf(chSCMstring,"666 Channels, VOX, 3.0 Watts");}
if (phonelst.Dscm[1]=='5')
{sprintf(chSCMstring,"666 Channels, VOX, 1.2 Watts");}
if (phonelst.Dscm[1]=='6')
{sprintf(chSCMstring,"666 Channels, VOX, 0.6 Watts");}
if (phonelst.Dscm[1]=='7')
{sprintf(chSCMstring,"666 Channels, VOX, Resv Watts");}
if (phonelst.Dscm[1]=='8')
{sprintf(chSCMstring,"832 Chan, Continuous, 3.0 Wts");}
if (phonelst.Dscm[1]=='9')
{sprintf(chSCMstring,"832 Chan, Continuous, 1.2 Wts");}
if (phonelst.Dscm[1]=='A')
{sprintf(chSCMstring,"832 Chan, Continuous, 0.6 Wts");}
if (phonelst.Dscm[1]=='B')
{sprintf(chSCMstring,"832 Chan, Continuous, Resv Wts");}
if (phonelst.Dscm[1]=='C')
{sprintf(chSCMstring,"832 Channels, VOX, 3.0 Watts");}
if (phonelst.Dscm[1]=='D')
{sprintf(chSCMstring,"832 Channels, VOX, 1.2 Watts");}
if (phonelst.Dscm[1]=='E')
{sprintf(chSCMstring,"832 Channels, VOX, 0.6 Watts");}
if (phonelst.Dscm[1]=='F')
{sprintf(chSCMstring,"832 Channels, VOX, Resv Watts");}
}
void CCELLULARDlg::ConvertGoFrequency(void)
{
if(chGoFrequency[1] == '0')
{
if(chGoFrequency[2] == '0') {stanum=0x00;}
if(chGoFrequency[2] == '1') {stanum=0x01;}
if(chGoFrequency[2] == '2') {stanum=0x02;}
if(chGoFrequency[2] == '3') {stanum=0x03;}
if(chGoFrequency[2] == '4') {stanum=0x04;}
if(chGoFrequency[2] == '5') {stanum=0x05;}
if(chGoFrequency[2] == '6') {stanum=0x06;}
if(chGoFrequency[2] == '7') {stanum=0x07;}
if(chGoFrequency[2] == '8') {stanum=0x08;}
if(chGoFrequency[2] == '9') {stanum=0x09;}
}
if(chGoFrequency[1] == '1')
{
if(chGoFrequency[2] == '0') {stanum=0x10;}
if(chGoFrequency[2] == '1') {stanum=0x11;}
if(chGoFrequency[2] == '2') {stanum=0x12;}
if(chGoFrequency[2] == '3') {stanum=0x13;}
if(chGoFrequency[2] == '4') {stanum=0x14;}
if(chGoFrequency[2] == '5') {stanum=0x15;}
if(chGoFrequency[2] == '6') {stanum=0x16;}
if(chGoFrequency[2] == '7') {stanum=0x17;}
if(chGoFrequency[2] == '8') {stanum=0x18;}
if(chGoFrequency[2] == '9') {stanum=0x19;}
}
if(chGoFrequency[1] == '2')
{
if(chGoFrequency[2] == '0') {stanum=0x20;}
if(chGoFrequency[2] == '1') {stanum=0x21;}
if(chGoFrequency[2] == '2') {stanum=0x22;}
if(chGoFrequency[2] == '3') {stanum=0x23;}
if(chGoFrequency[2] == '4') {stanum=0x24;}
if(chGoFrequency[2] == '5') {stanum=0x25;}
if(chGoFrequency[2] == '6') {stanum=0x26;}
if(chGoFrequency[2] == '7') {stanum=0x27;}
if(chGoFrequency[2] == '8') {stanum=0x28;}
if(chGoFrequency[2] == '9') {stanum=0x29;}
}
if(chGoFrequency[1] == '3')
{
if(chGoFrequency[2] == '0') {stanum=0x30;}
if(chGoFrequency[2] == '1') {stanum=0x31;}
if(chGoFrequency[2] == '2') {stanum=0x32;}
if(chGoFrequency[2] == '3') {stanum=0x33;}
if(chGoFrequency[2] == '4') {stanum=0x34;}
if(chGoFrequency[2] == '5') {stanum=0x35;}
if(chGoFrequency[2] == '6') {stanum=0x36;}
if(chGoFrequency[2] == '7') {stanum=0x37;}
if(chGoFrequency[2] == '8') {stanum=0x38;}
if(chGoFrequency[2] == '9') {stanum=0x39;}
}
if(chGoFrequency[1] == '4')
{
if(chGoFrequency[2] == '0') {stanum=0x40;}
if(chGoFrequency[2] == '1') {stanum=0x41;}
if(chGoFrequency[2] == '2') {stanum=0x42;}
if(chGoFrequency[2] == '3') {stanum=0x43;}
if(chGoFrequency[2] == '4') {stanum=0x44;}
if(chGoFrequency[2] == '5') {stanum=0x45;}
if(chGoFrequency[2] == '6') {stanum=0x46;}
if(chGoFrequency[2] == '7') {stanum=0x47;}
if(chGoFrequency[2] == '8') {stanum=0x48;}
if(chGoFrequency[2] == '9') {stanum=0x49;}
}
if(chGoFrequency[1] == '5')
{
if(chGoFrequency[2] == '0') {stanum=0x50;}
if(chGoFrequency[2] == '1') {stanum=0x51;}
if(chGoFrequency[2] == '2') {stanum=0x52;}
if(chGoFrequency[2] == '3') {stanum=0x53;}
if(chGoFrequency[2] == '4') {stanum=0x54;}
if(chGoFrequency[2] == '5') {stanum=0x55;}
if(chGoFrequency[2] == '6') {stanum=0x56;}
if(chGoFrequency[2] == '7') {stanum=0x57;}
if(chGoFrequency[2] == '8') {stanum=0x58;}
if(chGoFrequency[2] == '9') {stanum=0x59;}
}
if(chGoFrequency[1] == '6')
{
if(chGoFrequency[2] == '0') {stanum=0x60;}
if(chGoFrequency[2] == '1') {stanum=0x61;}
if(chGoFrequency[2] == '2') {stanum=0x62;}
if(chGoFrequency[2] == '3') {stanum=0x63;}
if(chGoFrequency[2] == '4') {stanum=0x64;}
if(chGoFrequency[2] == '5') {stanum=0x65;}
if(chGoFrequency[2] == '6') {stanum=0x66;}
if(chGoFrequency[2] == '7') {stanum=0x67;}
if(chGoFrequency[2] == '8') {stanum=0x68;}
if(chGoFrequency[2] == '9') {stanum=0x69;}
}
if(chGoFrequency[1] == '7')
{
if(chGoFrequency[2] == '0') {stanum=0x70;}
if(chGoFrequency[2] == '1') {stanum=0x71;}
if(chGoFrequency[2] == '2') {stanum=0x72;}
if(chGoFrequency[2] == '3'){stanum=0x73;}
if(chGoFrequency[2] == '4') {stanum=0x74;}
if(chGoFrequency[2] == '5') {stanum=0x75;}
if(chGoFrequency[2] == '6') {stanum=0x76;}
if(chGoFrequency[2] == '7'){stanum=0x77;}
if(chGoFrequency[2] == '8'){stanum=0x78;}
if(chGoFrequency[2] == '9') {stanum=0x79;}
}
if(chGoFrequency[1] == '8')
{
if (chGoFrequency[2] == '0'){stanum=0x80;}
if (chGoFrequency[2] == '1') {stanum=0x81;}
if (chGoFrequency[2] == '2') {stanum=0x82;}
if (chGoFrequency[2] == '3'){stanum=0x83;}
if (chGoFrequency[2] == '4') {stanum=0x84;}
if (chGoFrequency[2] == '5') {stanum=0x85;}
if (chGoFrequency[2] == '6') {stanum=0x86;}
if (chGoFrequency[2] == '7'){stanum=0x87;}
if (chGoFrequency[2] == '8'){stanum=0x88;}
if (chGoFrequency[2] == '9') {stanum=0x89;}
}
if(chGoFrequency[1] == '9')
{
if (chGoFrequency[2] == '0') {stanum=0x90;}
if (chGoFrequency[2] == '1') {stanum=0x91;}
if (chGoFrequency[2] == '2') {stanum=0x92;}
if (chGoFrequency[2] == '3'){stanum=0x93;}
if (chGoFrequency[2] == '4') {stanum=0x94;}
if (chGoFrequency[2] == '5') {stanum=0x95;}
if (chGoFrequency[2] == '6') {stanum=0x96;}
if (chGoFrequency[2] == '7'){stanum=0x97;}
if (chGoFrequency[2] == '8'){stanum=0x98;}
if (chGoFrequency[2] == '9') {stanum=0x99;}
}
if(chGoFrequency[4] == '0')
{
if (chGoFrequency[5] == '0') {endnum=0x00;}
if (chGoFrequency[5] == '1') {endnum=0x01;}
if (chGoFrequency[5] == '2') {endnum=0x02;}
if (chGoFrequency[5] == '3'){endnum=0x03;}
if (chGoFrequency[5] == '4') {endnum=0x04;}
if (chGoFrequency[5] == '5') {endnum=0x05;}
if (chGoFrequency[5] == '6') {endnum=0x06;}
if (chGoFrequency[5] == '7'){endnum=0x07;}
if (chGoFrequency[5] == '8'){endnum=0x08;}
if (chGoFrequency[5] == '9') {endnum=0x09;}
}
if(chGoFrequency[4] == '1')
{
if (chGoFrequency[5] == '0') {endnum=0x10;}
if (chGoFrequency[5] == '1') {endnum=0x11;}
if (chGoFrequency[5] == '2') {endnum=0x12;}
if (chGoFrequency[5] == '3'){endnum=0x13;}
if (chGoFrequency[5] == '4') {endnum=0x14;}
if (chGoFrequency[5] == '5') {endnum=0x15;}
if (chGoFrequency[5] == '6') {endnum=0x16;}
if (chGoFrequency[5] == '7'){endnum=0x17;}
if (chGoFrequency[5] == '8'){endnum=0x18;}
if (chGoFrequency[5] == '9') {endnum=0x19;}
}
if(chGoFrequency[4] == '2')
{
if (chGoFrequency[5] == '0') {endnum=0x20;}
if (chGoFrequency[5] == '1') {endnum=0x21;}
if (chGoFrequency[5] == '2') {endnum=0x22;}
if (chGoFrequency[5] == '3'){endnum=0x23;}
if (chGoFrequency[5] == '4') {endnum=0x24;}
if (chGoFrequency[5] == '5') {endnum=0x25;}
if (chGoFrequency[5] == '6') {endnum=0x26;}
if (chGoFrequency[5] == '7'){endnum=0x27;}
if (chGoFrequency[5] == '8'){endnum=0x28;}
if (chGoFrequency[5] == '9') {endnum=0x29;}
}
if(chGoFrequency[4] == '3')
{
if (chGoFrequency[5] == '0') {endnum=0x30;}
if (chGoFrequency[5] == '1') {endnum=0x31;}
if (chGoFrequency[5] == '2') {endnum=0x32;}
if (chGoFrequency[5] == '3'){endnum=0x33;}
if (chGoFrequency[5] == '4') {endnum=0x34;}
if (chGoFrequency[5] == '5') {endnum=0x35;}
if (chGoFrequency[5] == '6') {endnum=0x36;}
if (chGoFrequency[5] == '7'){endnum=0x37;}
if (chGoFrequency[5] == '8'){endnum=0x38;}
if (chGoFrequency[5] == '9') {endnum=0x39;}
}
if(chGoFrequency[4] == '4')
{
if (chGoFrequency[5] == '0') {endnum=0x40;}
if (chGoFrequency[5] == '1') {endnum=0x41;}
if (chGoFrequency[5] == '2') {endnum=0x42;}
if (chGoFrequency[5] == '3'){endnum=0x43;}
if (chGoFrequency[5] == '4') {endnum=0x44;}
if (chGoFrequency[5] == '5') {endnum=0x45;}
if (chGoFrequency[5] == '6') {endnum=0x46;}
if (chGoFrequency[5] == '7'){endnum=0x47;}
if (chGoFrequency[5] == '8'){endnum=0x48;}
if (chGoFrequency[5] == '9') {endnum=0x49;}
}
if(chGoFrequency[4] == '5')
{
if (chGoFrequency[5] == '0') {endnum=0x50;}
if (chGoFrequency[5] == '1') {endnum=0x51;}
if (chGoFrequency[5] == '2') {endnum=0x52;}
if (chGoFrequency[5] == '3'){endnum=0x53;}
if (chGoFrequency[5] == '4') {endnum=0x54;}
if (chGoFrequency[5] == '5') {endnum=0x55;}
if (chGoFrequency[5] == '6') {endnum=0x56;}
if (chGoFrequency[5] == '7'){endnum=0x57;}
if (chGoFrequency[5] == '8'){endnum=0x58;}
if (chGoFrequency[5] == '9') {endnum=0x59;}
}
if(chGoFrequency[4] == '6')
{
if (chGoFrequency[5] == '0') {endnum=0x60;}
if (chGoFrequency[5] == '1') {endnum=0x61;}
if (chGoFrequency[5] == '2') {endnum=0x62;}
if (chGoFrequency[5] == '3'){endnum=0x63;}
if (chGoFrequency[5] == '4') {endnum=0x64;}
if (chGoFrequency[5] == '5') {endnum=0x65;}
if (chGoFrequency[5] == '6') {endnum=0x66;}
if (chGoFrequency[5] == '7'){endnum=0x67;}
if (chGoFrequency[5] == '8'){endnum=0x68;}
if (chGoFrequency[5] == '9') {endnum=0x69;}
}
if(chGoFrequency[4] == '7')
{
if (chGoFrequency[5] == '0') {endnum=0x70;}
if (chGoFrequency[5] == '1') {endnum=0x71;}
if (chGoFrequency[5] == '2') {endnum=0x72;}
if (chGoFrequency[5] == '3'){endnum=0x73;}
if (chGoFrequency[5] == '4') {endnum=0x74;}
if (chGoFrequency[5] == '5') {endnum=0x75;}
if (chGoFrequency[5] == '6') {endnum=0x76;}
if (chGoFrequency[5] == '7'){endnum=0x77;}
if (chGoFrequency[5] == '8'){endnum=0x78;}
if (chGoFrequency[5] == '9') {endnum=0x79;}
}
if(chGoFrequency[4] == '8')
{
if (chGoFrequency[5] == '0') {endnum=0x80;}
if (chGoFrequency[5] == '1') {endnum=0x81;}
if (chGoFrequency[5] == '2') {endnum=0x82;}
if (chGoFrequency[5] == '3'){endnum=0x83;}
if (chGoFrequency[5] == '4') {endnum=0x84;}
if (chGoFrequency[5] == '5') {endnum=0x85;}
if (chGoFrequency[5] == '6') {endnum=0x86;}
if (chGoFrequency[5] == '7'){endnum=0x87;}
if (chGoFrequency[5] == '8'){endnum=0x88;}
if (chGoFrequency[5] == '9') {endnum=0x89;}
}
if(chGoFrequency[4] == '9')
{
if (chGoFrequency[5] == '0') {endnum=0x90;}
if (chGoFrequency[5] == '1') {endnum=0x91;}
if (chGoFrequency[5] == '2') {endnum=0x92;}
if (chGoFrequency[5] == '3'){endnum=0x93;}
if (chGoFrequency[5] == '4') {endnum=0x94;}
if (chGoFrequency[5] == '5') {endnum=0x95;}
if (chGoFrequency[5] == '6') {endnum=0x96;}
if (chGoFrequency[5] == '7'){endnum=0x97;}
if (chGoFrequency[5] == '8'){endnum=0x98;}
if (chGoFrequency[5] == '9') {endnum=0x99;}
}
}
void CCELLULARDlg::ReadIniFile(void)
{
char chDirectoryName[MAX_PATH+100];
char *pchDirectoryName = chDirectoryName;
::GetCurrentDirectory(MAX_PATH,pchDirectoryName);
strcat(pchDirectoryName,"\\CELLULAR.INI");
TRACE("INI Filename = %s\n",pchDirectoryName);
char chTextString[255];
char *pchTextString = chTextString;
DDICOM:
GetPrivateProfileString("SETTINGS","DDI COMM PORT","Not Found",pchTextString,17,pchDirectoryName);
if(strcmp("Not Found",pchTextString)==0)
{
WritePrivateProfileString("SETTINGS","DDI COMM PORT","2",pchDirectoryName);
goto DDICOM;
}
else
{
iCommPortDDI = atoi(pchTextString);
iCommPortDDI = iCommPortDDI - 1;
TRACE("iCommPortDDI = %d\n",iCommPortDDI);
}
OS456COM:
GetPrivateProfileString("SETTINGS","OS456 COMM PORT","Not Found",pchTextString,17,pchDirectoryName);
if(strcmp("Not Found",pchTextString)==0)
{
WritePrivateProfileString("SETTINGS","OS456 COMM PORT","1",pchDirectoryName);
goto OS456COM;
}
else
{
iCommPortOS456 = atoi(pchTextString);
iCommPortOS456 = iCommPortOS456 - 1;
TRACE("iCommPortOS456 = %d\n",iCommPortOS456);
}
FREQUENCY:
GetPrivateProfileString("SETTINGS","FREQUENCY","Not Found",pchTextString,17,pchDirectoryName);
if(strcmp("Not Found",pchTextString)==0)
{
WritePrivateProfileString("SETTINGS","FREQUENCY","879.540",pchDirectoryName);
goto FREQUENCY;
}
else
{
strcpy(chFrequency,pchTextString);
TRACE1("chFrequency = %s\n",chFrequency);
strcpy(chGoFrequency,chFrequency);
ConvertGoFrequency();
}
/*
REVERSE:
bReverseChannel = false;
GetPrivateProfileString("SETTINGS","REVERSE CHANNEL","Not Found",pchTextString,17,pchDirectoryName);
if(strcmp("Not Found",pchTextString)==0)
{
WritePrivateProfileString("SETTINGS","REVERSE CHANNEL","NO",pchDirectoryName);
goto REVERSE;
}
else
{
if(strcmpi(pchTextString,"YES")==0)
{
bReverseChannel = true;
}
if(strcmpi(pchTextString,"Y")==0)
{
bReverseChannel = true;
}
if(strcmpi(pchTextString,"ENABLED")==0)
{
bReverseChannel = true;
}
if(strcmpi(pchTextString,"ENABLE")==0)
{
bReverseChannel = true;
}
if(strcmpi(pchTextString,"ON")==0)
{
bReverseChannel = true;
}
}
*/
MAXCALLTIME:
GetPrivateProfileString("SETTINGS","MAX CALL TIME","Not Found",pchTextString,17,pchDirectoryName);
if(strcmp("Not Found",pchTextString)==0)
{
WritePrivateProfileString("SETTINGS","MAX CALL TIME","1200",pchDirectoryName);
goto MAXCALLTIME;
}
else
{
iMaxCallTime = atoi(pchTextString);
TRACE("iMaxCallTime = %d\n",iMaxCallTime);
}
}
void CCELLULARDlg::OnButtonControlType()
{
m_EditCallList.SetWindowText(" ");
m_EditCallList.Clear();
if(bReverseChannel == false)
{
m_ButtonSwitchControlType.SetWindowText("Switch To Reverse Control");
strcpy(chFrequency,chReverseChannel);
TRACE("chReverseChannel = %s\n",chReverseChannel);
}
else
{
m_ButtonSwitchControlType.SetWindowText("Switch To Forward Control");
strcpy(chFrequency,chForwardChannel);
TRACE("chForwardChannel = %s\n",chForwardChannel);
}
which_channel();
if(bReverseChannel == true)
{
SetDDItoReverse();
}
else
{
SetDDItoForward();
}
osfreq(endnum,stanum);
}
void CCELLULARDlg::OnButtonSwitchvoice()
{
if(bVoiceForward == true)
{
m_ButtonSwitchVoice.SetWindowText("Forward Voice");
bVoiceForward = false;
bGoReverseVoice = true;
}
else
{
m_ButtonSwitchVoice.SetWindowText("Reverse Voice");
bVoiceForward = true;
bGoForwardVoice = true;
}
}
void CCELLULARDlg::OnButtonControlscan()
{
InitalizeOS456();
InitalizeDDI();
char chOriginalFrequency[50];
strcpy(chOriginalFrequency,chFrequency);
SetDDItoForward();
WriteToCallBox("FORWARD CONTROL CHANNEL SCAN (BAND 'A')");
WriteToCallBox("[ACTIVE] [CHANNEL] [FREQUENCY] [SIGNAL STRENGTH]");
ScanControlChannel("879.990");
ScanControlChannel("879.960");
ScanControlChannel("879.930");
ScanControlChannel("879.900");
ScanControlChannel("879.870");
ScanControlChannel("879.840");
ScanControlChannel("879.810");
ScanControlChannel("879.780");
ScanControlChannel("879.750");
ScanControlChannel("879.720");
ScanControlChannel("879.690");
ScanControlChannel("879.660");
ScanControlChannel("879.630");
ScanControlChannel("879.600");
ScanControlChannel("879.570");
ScanControlChannel("879.540");
ScanControlChannel("879.510");
ScanControlChannel("879.480");
ScanControlChannel("879.450");
ScanControlChannel("879.420");
ScanControlChannel("879.390");
WriteToCallBox(" ");
WriteToCallBox("FORWARD CONTROL CHANNEL SCAN (BAND 'B')");
WriteToCallBox("[ACTIVE] [CHANNEL] [FREQUENCY] [SIGNAL STRENGTH]");
ScanControlChannel("835.020");
ScanControlChannel("835.050");
ScanControlChannel("835.080");
ScanControlChannel("835.110");
ScanControlChannel("835.140");
ScanControlChannel("835.170");
ScanControlChannel("835.200");
ScanControlChannel("835.230");
ScanControlChannel("835.260");
ScanControlChannel("835.290");
ScanControlChannel("835.320");
ScanControlChannel("835.350");
ScanControlChannel("835.380");
ScanControlChannel("835.410");
ScanControlChannel("835.440");
ScanControlChannel("835.470");
ScanControlChannel("835.500");
ScanControlChannel("835.530");
ScanControlChannel("835.560");
ScanControlChannel("835.590");
ScanControlChannel("835.620");
WriteToCallBox(" ");
WriteToCallBox(" Channels mark with an X are active control channels.");
WriteToCallBox(" The lower the signal strength number is the better the signal");
WriteToCallBox(" 0 is a perfect signal. - 125 is the worst signal.");
osspeakeroff();
strcpy(chFrequency,chOriginalFrequency);
which_channel();
osfreq(endnum,stanum);
}
void CCELLULARDlg::ScanControlChannel(char *chFreq)
{
char chActive[5];
char chTempString[250];
char *pchTempString = chTempString;
strcpy(chFrequency,chFreq);
which_channel();
osfreq(endnum,stanum);
osspeakeron();
Sleep(250);
ossignalstr();
if(strcmp(chSignalStrength,"- 125 dBm")==0)
{
strcpy(chActive," ");
}
else
{
strcpy(chActive,"X");
}
sprintf(pchTempString," [%s] [%s] [%s] [%s]",chActive,chChannel,chFrequency,chSignalStrength);
WriteToCallBox(pchTempString);
}
| 26.806627
| 190
| 0.587279
|
yantis
|
68c3732c72577fd424f41c28144aca72ff4e6b24
| 1,950
|
cpp
|
C++
|
src/Elements/emitter.cpp
|
attilabibok/epanet-dev
|
91d87377b8462cf0a12cb55ea0554951fb586993
|
[
"MIT"
] | 1
|
2017-12-21T19:40:35.000Z
|
2017-12-21T19:40:35.000Z
|
src/Elements/emitter.cpp
|
attilabibok/epanet-dev
|
91d87377b8462cf0a12cb55ea0554951fb586993
|
[
"MIT"
] | null | null | null |
src/Elements/emitter.cpp
|
attilabibok/epanet-dev
|
91d87377b8462cf0a12cb55ea0554951fb586993
|
[
"MIT"
] | null | null | null |
/* EPANET 3
*
* Copyright (c) 2016 Open Water Analytics
* Distributed under the MIT License (see the LICENSE file for details).
*
*/
#include "emitter.h"
#include "junction.h"
#include "pattern.h"
#include "Core/network.h"
#include <cmath>
using namespace std;
//-----------------------------------------------------------------------------
// Emitter Constructor
Emitter::Emitter() :
flowCoeff(0),
expon(0.0),
timePattern(0)
{}
//-----------------------------------------------------------------------------
// Emitter Destructor
Emitter::~Emitter() {}
//-----------------------------------------------------------------------------
// Adds or edits a junction's emitter.
bool Emitter::addEmitter(Junction* junc, double c, double e, Pattern* p)
{
if ( junc->emitter == nullptr )
{
junc->emitter = new Emitter();
if ( junc->emitter == nullptr ) return false;
}
junc->emitter->flowCoeff = c;
junc->emitter->expon = e;
junc->emitter->timePattern = p;
return true;
}
//-----------------------------------------------------------------------------
// Converts an emitter's properties from user units to internal units.
void Emitter::convertUnits(Network* network)
{
// ... get units conversion factors
double qUcf = network->ucf(Units::FLOW);
double pUcf = network->ucf(Units::PRESSURE);
// ... convert flowCoeff from user flow units per psi (or meter)
// to cfs per foot of head
flowCoeff *= pow(pUcf, expon) / qUcf;
}
//-----------------------------------------------------------------------------
// Finds the outflow and its derivative from an emitter at a given pressure head.
double Emitter::findFlowRate(double h, double& dqdh)
{
dqdh = 0.0;
if ( h <= 0.0 ) return 0.0;
double a = flowCoeff;
if (timePattern) a *= timePattern->currentFactor();
double q = a * pow(h, expon);
dqdh = expon * q / h;
return q;
}
| 24.375
| 82
| 0.507692
|
attilabibok
|
68c4415146bf139aac80e5779108f3bd23f4fefa
| 10,585
|
cpp
|
C++
|
src/arboretum/stPartitionNode.cpp
|
marcosivni/arboretum
|
329147b2d147903bc8e527fc3dcfe2349141725a
|
[
"Apache-2.0"
] | null | null | null |
src/arboretum/stPartitionNode.cpp
|
marcosivni/arboretum
|
329147b2d147903bc8e527fc3dcfe2349141725a
|
[
"Apache-2.0"
] | null | null | null |
src/arboretum/stPartitionNode.cpp
|
marcosivni/arboretum
|
329147b2d147903bc8e527fc3dcfe2349141725a
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2003-2017 GBDI-ICMC-USP <caetano@icmc.usp.br>
*
* 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
*
* This file implements the blocks of Partition.
*
* @version 1.0
* @author Enzo Seraphim(seraphim@icmc.usp.br)
*/
#include <arboretum/stPartitionNode.h>
//------------------------------------------------------------------------------
// class stPartitionRegionDesc
//------------------------------------------------------------------------------
int stPartitionRegionDesc::GetFirstDigit(){
return (int)(Desc.Region / pow (Desc.NumberRep, (long double)(Desc.NumberRep - 1)));
}//end stPartitionRegionDesc::GetFirstDigit
//------------------------------------------------------------------------------
void stPartitionRegionDesc::ConvertToBins(unsigned char base, unsigned char *result){
u_int32_t long res = Desc.Region;
int i = 0;
u_int32_t long powbase;
for (int i =0; i < base; i++){
powbase = (u_int32_t long) pow (Desc.NumberRep, (long double)(base - i - 1));
result[i] = (unsigned char)(res / powbase);
res = res - (powbase * result[i]);
}//end while
} //end stPartitionRegionDesc::ConvertToBins
//-----------------------------------------------------------------------------
// Class stPartitionListRegionDesc
//-----------------------------------------------------------------------------
stPartitionListRegionDesc::~stPartitionListRegionDesc(){
IdActual = 0;
for (;IdActual < NumberItem;IdActual++){
Actual = Root;
Root = Actual->Next;
delete Actual;
IdActual++;
}//end for
}//end stPartitionListRegionDesc::~stPartitionRegionDesc
//------------------------------------------------------------------------------
stPartitionRegionDesc stPartitionListRegionDesc::GetRegionDesc(int id){
#ifdef __stDEBUG__
if ((id < 0) && (id >= NumberItem)){
throw invalid_argument("id value is out of range.");
}//end if
#endif //__stDEBUG__
//if index is the first
if(id == 0){
return Root->RegionDesc;
}
//if index is the last
if(id == NumberItem){
return Last->RegionDesc;
}
//otherwise
if (IdActual > id){
Actual = Root;
for (IdActual=0;IdActual<id;IdActual++){
Actual = Actual->Next;
}//end for
}else{
for (;IdActual<id;IdActual++){
Actual = Actual->Next;
}//end for
}//end if
return Actual->RegionDesc;
}//end stPartitionListRegionDesc::GetRegionDesc
//------------------------------------------------------------------------------
int stPartitionListRegionDesc::Add(stPartitionRegionDesc regDesc){
//locating previous item to insered position
stItemRegionDesc * ant;
stItemRegionDesc * aux = Root;
IdActual = 0;
while((IdActual < NumberItem) && (aux->RegionDesc.GetRegion() < regDesc.GetRegion())){
ant = aux;
aux = aux->Next;
IdActual++;
}//end while
//inserting item
Actual = new stItemRegionDesc;
Actual->RegionDesc = regDesc;
Actual->Next = aux;
//if change the last item
if (IdActual == NumberItem){
Last = Actual;
}//end if
//if change the root
if (IdActual == 0){
Root = Actual;
}else{
ant->Next = Actual;
}//end if
//update number of representatives
NumberItem++;
return IdActual;
}//end stPartitionListRegionDesc::Add
//------------------------------------------------------------------------------
// class stPartitionNode
//------------------------------------------------------------------------------
stPartitionNode * stPartitionNode::CreateBucket(stPage * page){
stPartitionNode::stPartitionNodeHeader * header;
header = (stPartitionNodeHeader *)(page->GetData());
switch (header->Type){
case INDEX:
// Create an index page
return new stPartitionIndexBucket(page, false);
case LEAF:
// Create a leaf page
return new stPartitionLeafBucket(page, false);
default:
return NULL;
}//end switch
}//end stPartitionNode::CreateBucket()
//------------------------------------------------------------------------------
// class stPartitionIndexBucket
//------------------------------------------------------------------------------
stPartitionIndexBucket::stPartitionIndexBucket(stPage * page, bool create):
stPartitionNode(page){
// Attention to this manouver! It is the brain of this
// implementation.
Entries = (stPartitionIndexEntry*)(page->GetData() + sizeof(stPartitionNodeHeader));
// Initialize page
if (create){
#ifdef __stDEBUG__
Page->Clear();
#endif //__stDEBUG__
Header->Type = INDEX;
Header->Occupation = 0;
Header->NextBucket = 0;
}//end if
}//end stPartitionIndexBucket::stPartitionIndexBucket()
//------------------------------------------------------------------------------
u_int32_t stPartitionIndexBucket::GetFree(){
u_int32_t usedsize;
// Fixed size
usedsize = sizeof(stPartitionNodeHeader);
// Entries
if (GetNumberOfEntries() > 0){
usedsize +=
// Total size of entries
(sizeof(stPartitionIndexEntry) * GetNumberOfEntries());
}//end if
return Page->GetPageSize() - usedsize;
}//end stPartitionIndexBucket::GetFree()
//------------------------------------------------------------------------------
// class stPartitionLeafBucket
//------------------------------------------------------------------------------
stPartitionLeafBucket::stPartitionLeafBucket(stPage * page, bool create):
stPartitionNode(page){
Entries = (stPartitionLeafEntry*)(page->GetData() + sizeof(stPartitionNodeHeader));
// Initialize page
if (create){
#ifdef __stDEBUG__
Page->Clear();
#endif //__stDEBUG__
Header->Type = LEAF;
Header->Occupation = 0;
Header->NextBucket = 0;
}//end if
}//end stPartitionLeafBucket::stPartitionLeafBucket()
//------------------------------------------------------------------------------
u_int32_t stPartitionLeafBucket::GetObjectSize(int id){
#ifdef __stDEBUG__
if ((id < 0) && (id >= GetNumberOfEntries())){
throw invalid_argument("id value is out of range.");
}//end if
#endif //__stDEBUG__
if (id == 0){
// First object
return Page->GetPageSize() - Entries[0].Offset;
}else{
// Any other
return Entries[id - 1].Offset - Entries[id].Offset;
}//end if
}//end stPartitionLeafBucket::GetObjectSize()
//------------------------------------------------------------------------------
u_int32_t stPartitionLeafBucket::GetFree(){
u_int32_t usedsize;
// Fixed size
usedsize = sizeof(stPartitionNodeHeader);
// Entries
if (GetNumberOfEntries() > 0){
usedsize +=
// Total size of entries
(sizeof(stPartitionLeafEntry) * GetNumberOfEntries()) +
// Total object size
(Page->GetPageSize() - Entries[GetNumberOfEntries() - 1].Offset);
}//end if
return Page->GetPageSize() - usedsize;
}//end stPartitionLeafBucket::GetFree()
//-----------------------------------------------------------------------------
// Class stPartitionRepresentativesNode
//-----------------------------------------------------------------------------
stPartitionRepresentativesNode::stPartitionRepresentativesNode(
stPage * page, bool create):stPartitionNode(page){
// Attention to this manouver! It is the brain of this
// implementation.
Entries = (u_int32_t *)((this->Page->GetData())+
sizeof(stPartitionNodeHeader));
// Initialize page
if (create){
#ifdef __stDEBUG__
Page->Clear();
#endif //__stDEBUG__
Header->Type = REPRESENT;
Header->Occupation = 0;
Header->NextBucket = 0;
}//end if
}//end stPartitionRepresentativesNode::stPartitionRepresentativesNode()
//-----------------------------------------------------------------------------
int stPartitionRepresentativesNode::AddEntry(u_int32_t size, const unsigned char * object){
u_int32_t entrysize;
#ifdef __stDEBUG__
if (size == 0){
throw invalid_argument("The object size is 0.");
}//end if
#endif //__stDEBUG__
// Does it fit ?
entrysize = size + sizeof(u_int32_t);
if (entrysize > this->GetFree()){
// No, it doesn't.
return -1;
}//end if
// Ok. I can put it. Lets put it in the last position.
// Adding the object. Take care with these pointers or you will destroy the
// node. The idea is to put the object of an entry in the reverse order
// in the data array.
if (Header->Occupation == 0){
Entries[Header->Occupation] = Page->GetPageSize() - size;
}else{
Entries[Header->Occupation] = Entries[Header->Occupation - 1] - size;
}//end if
memcpy((void*)(Page->GetData() + Entries[Header->Occupation]),
(void*)object, size);
// Update # of entries
Header->Occupation++; // One more!
return Header->Occupation - 1;
}//end stPartitionRepresentativesNode::AddEntry()
//------------------------------------------------------------------------------
u_int32_t stPartitionRepresentativesNode::GetObjectSize(int id){
#ifdef __stDEBUG__
if ((id < 0) && (id >= GetNumberOfEntries())){
throw invalid_argument("id value is out of range.");
}//end if
#endif //__stDEBUG__
if (id == 0){
// First object
return Page->GetPageSize() - Entries[0];
}else{
// Any otherstPartitionLeafBucket
return Entries[id - 1] - Entries[id];
}//end if
}//end stPartitionRepresentativesNode::GetObjectSize()
//------------------------------------------------------------------------------
u_int32_t stPartitionRepresentativesNode::GetFree(){
u_int32_t usedsize;
// Fixed size
usedsize = sizeof(stPartitionNodeHeader);
// Entries
if (GetNumberOfEntries() > 0){
usedsize +=
// Total size of entries
(sizeof(u_int32_t) * GetNumberOfEntries()) +
// Total object size
(Page->GetPageSize() - Entries[GetNumberOfEntries() - 1]);
}//end if
return Page->GetPageSize() - usedsize;
}//end stPartitionRepresentativesNode::GetFree()
| 32.469325
| 91
| 0.559565
|
marcosivni
|
68c503a54d6a500daeb69a026d88a4463a5e20eb
| 6,845
|
cpp
|
C++
|
src/PinholePCLCam.cpp
|
HWiese1980/merge_depth_cam
|
974008b6b1f84d516a0f74dfd3832bfa55ef163d
|
[
"BSD-3-Clause"
] | 16
|
2019-01-23T10:35:27.000Z
|
2022-03-10T16:21:34.000Z
|
src/PinholePCLCam.cpp
|
mmiles19/merge_depth_cam
|
7bd00a7d2baabdb9c4a8afc6a4eb516898f995b0
|
[
"BSD-3-Clause"
] | 3
|
2019-02-26T16:48:08.000Z
|
2022-01-24T18:16:15.000Z
|
src/PinholePCLCam.cpp
|
mmiles19/merge_depth_cam
|
7bd00a7d2baabdb9c4a8afc6a4eb516898f995b0
|
[
"BSD-3-Clause"
] | 4
|
2019-10-27T10:45:41.000Z
|
2021-01-23T08:44:37.000Z
|
// #include <pluginlib/class_list_macros.h>
#include "PinholePCLCam.hpp"
#include <opencv2/opencv.hpp>
#include <pcl/range_image/range_image_planar.h>
#include <cassert>
#include <cmath>
using namespace sensor_msgs;
using namespace std_msgs;
namespace ap34 {
void store_image(std::string fname, cv::Mat& img) {
ROS_INFO_STREAM("Storing image");
std::stringstream ss_yml, ss_png;
ss_yml << fname << ".yml";
ss_png << fname << ".png";
cv::FileStorage file(ss_yml.str().c_str(), cv::FileStorage::WRITE);
file << "depth_image" << img;
std::vector<int> compression_params;
compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
compression_params.push_back(9);
cv::Mat write_image;
cv::normalize(img, write_image, 0, 255, cv::NORM_MINMAX, CV_8UC1);
cv::imwrite(ss_png.str().c_str(), write_image, compression_params);
}
void PinholePCLCam::PCL2Mat(const PointCloud::ConstPtr& ptr_cld, cv::Mat& depth_image, int original_width, int original_height)
{
int blob_offset_u = (blob_size - (blob_size%2)) / 2;
int blob_offset_v = (blob_size - (blob_size%2)) / 2;
std::vector<cv::Point2f> projectedPoints;
std::vector<cv::Point3f> cv_points;
for(const auto& point : ptr_cld->points) {
cv_points.push_back(cv::Point3f(point.x, point.y, point.z));
}
cv::projectPoints(cv_points, rvecR, T, K, distCoeffs, projectedPoints);
cv::Rect valid_range(blob_offset_u, blob_offset_v, original_width - (2*blob_offset_u), original_height - (2*blob_offset_v));
int mid_x = original_width/2;
int mid_y = original_height/2;
#pragma omp parallel for
for(int i = 0; i < ptr_cld->points.size(); i += stride)
{
auto point2d = projectedPoints[i];
int u = (int)(point2d.x + mid_x);
int v = (int)(point2d.y + mid_y);
cv::Point p(u, v);
if(!valid_range.contains(p)) continue;
float z = ptr_cld->points[i].z;
float new_val = (float)(z * 1000.0);
float current_val = depth_image.at<float>(v, u);
if(current_val < std::numeric_limits<float>::epsilon() || new_val < current_val)
// only set depth value if current pixel is unset or the new value is closer to the cam (z-buffer)
// depth_image(cv::Rect(u-blob_offset_u,v-blob_offset_v,2*blob_offset_u,2*blob_offset_v)).setTo(new_val);
cv::circle(depth_image, p, blob_size/2, new_val, -1);
}
}
void PinholePCLCam::dynconf_cb(merged_depth_cam::PinholePCLCamConfig &config, uint32_t level) {
ROS_INFO("[PinholePCLCam] Reconfiguring");
ROS_INFO(" Stride : %d", config.stride);
ROS_INFO(" Blob Size : %d", config.blob_size);
ROS_INFO(" Focal Length : %3.3f", config.focal_length);
ROS_INFO(" Rescale Factor : %3.3f", config.rescale_factor);
stride = config.stride;
blob_size = config.blob_size;
focal_length = config.focal_length;
rescale_factor = config.rescale_factor;
float _upscale_factor_internal = (float)target_width / diw;
ROS_INFO("[Pinhole Cam] Internal upscale factor : %3.3f", _upscale_factor_internal);
_downscale_factor = rescale_factor;
_upscale_factor = _upscale_factor_internal / _downscale_factor;
P.at<float>(0,0) = focal_length / 2;
P.at<float>(1,1) = focal_length / 2;
P.at<float>(2,2) = 1;
cv::decomposeProjectionMatrix(P, K, rvec, Thomogeneous);
cv::Rodrigues(rvec, rvecR);
}
PinholePCLCam::PinholePCLCam(ros::NodeHandle& nh) {
this->nh = nh;
image_transport::ImageTransport it(this->nh);
pcl_sub = nh.subscribe("input_pcl", 1, &PinholePCLCam::IncomingPCL, this);
depth_pub = it.advertise("output_merged_depth", 1);
P = cv::Mat(3, 4, cv::DataType<float>::type, cv::Scalar(0.));
K = cv::Mat(3, 3, cv::DataType<float>::type, cv::Scalar(0.));
rvec = cv::Mat(3, 3, cv::DataType<float>::type, cv::Scalar(0.));
Thomogeneous = cv::Mat(4, 1, cv::DataType<float>::type, cv::Scalar(0.));
T = cv::Mat(3, 1, cv::DataType<float>::type, cv::Scalar(0.));
distCoeffs = cv::Mat(4, 1, cv::DataType<float>::type, cv::Scalar(0.));
rvecR = cv::Mat(3, 1, cv::DataType<float>::type, cv::Scalar(0.));
usleep(500000);
nh.param<std::string>("virtual_cam_frame", virtual_cam_frame, "virtual_cam_link");
nh.param<int>("depth_image_width", diw, 640);
nh.param<int>("depth_image_height", dih, 960);
nh.param<int>("stride", stride, 1);
nh.param<int>("target_width", target_width, 320);
nh.param<int>("blob_size", blob_size, 1);
nh.param<float>("focal_length", focal_length, 1000.0);
nh.param<float>("rescale_factor", rescale_factor, 1.0);
float _upscale_factor_internal = (float)target_width / diw;
ROS_INFO("[Pinhole Cam] Internal upscale factor : %3.3f", _upscale_factor_internal);
_downscale_factor = rescale_factor;
_upscale_factor = _upscale_factor_internal / _downscale_factor;
ROS_INFO("[Pinhole Cam] Downscale Factor : %3.3f", _downscale_factor);
ROS_INFO("[Pinhole Cam] Upscale Factor : %3.3f", _upscale_factor);
ROS_INFO("[Pinhole Cam] Blob Size : %d", blob_size);
cb_type = boost::bind(&PinholePCLCam::dynconf_cb, this, _1, _2);
server.setCallback(cb_type);
}
void PinholePCLCam::IncomingPCL(const PointCloud::ConstPtr& pcl) {
if(diw <= 0 || dih <= 0) return;
cv::Mat depth_image(dih, diw, CV_32FC1, cv::Scalar(0.0));
PCL2Mat(pcl, depth_image, diw, dih);
cv::Mat resized_image;
if(fabs(1.0F - _upscale_factor) >= std::numeric_limits<float>::epsilon())
{
cv::resize(depth_image, resized_image, cv::Size(), _downscale_factor, _downscale_factor, CV_INTER_AREA);
cv::resize(resized_image, resized_image, cv::Size(), _upscale_factor, _upscale_factor, CV_INTER_AREA);
}
else{
ROS_INFO_ONCE("No rescaling necessary");
resized_image = depth_image;
}
sensor_msgs::Image msg;
std_msgs::Header header;
pcl_conversions::fromPCL(pcl->header, header);
// header.frame_id = virtual_cam_frame;
// header.seq = seq++;
// header.stamp = ros::Time(pcl->header.stamp);
auto img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::TYPE_32FC1, resized_image);
img_bridge.toImageMsg(msg);
depth_pub.publish(msg);
depth_image.release();
resized_image.release();
}
}
| 41.737805
| 132
| 0.622498
|
HWiese1980
|
68c5c2ec21cf1af2560c0717b4118df93f520b17
| 4,866
|
cc
|
C++
|
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
|
nagineni/chromium-crosswalk
|
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231
|
2015-01-08T09:04:44.000Z
|
2021-12-30T03:03:10.000Z
|
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
|
j4ckfrost/android_external_chromium_org
|
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2021-12-13T19:44:12.000Z
|
2021-12-13T19:44:12.000Z
|
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
|
j4ckfrost/android_external_chromium_org
|
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268
|
2015-01-21T05:53:28.000Z
|
2022-03-25T22:09:01.000Z
|
// Copyright (c) 2012 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 "gpu/command_buffer/service/transfer_buffer_manager.h"
#include "base/memory/scoped_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
using base::SharedMemory;
namespace gpu {
const static size_t kBufferSize = 1024;
class TransferBufferManagerTest : public testing::Test {
protected:
virtual void SetUp() {
for (size_t i = 0; i < arraysize(buffers_); ++i) {
buffers_[i].CreateAnonymous(kBufferSize);
buffers_[i].Map(kBufferSize);
}
TransferBufferManager* manager = new TransferBufferManager();
transfer_buffer_manager_.reset(manager);
ASSERT_TRUE(manager->Initialize());
}
base::SharedMemory buffers_[3];
scoped_ptr<TransferBufferManagerInterface> transfer_buffer_manager_;
};
TEST_F(TransferBufferManagerTest, ZeroHandleMapsToNull) {
EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(0).ptr);
}
TEST_F(TransferBufferManagerTest, NegativeHandleMapsToNull) {
EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(-1).ptr);
}
TEST_F(TransferBufferManagerTest, OutOfRangeHandleMapsToNull) {
EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(1).ptr);
}
TEST_F(TransferBufferManagerTest, CanRegisterTransferBuffer) {
EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[0],
kBufferSize));
Buffer registered = transfer_buffer_manager_->GetTransferBuffer(1);
// Distinct memory range and shared memory handle from that originally
// registered.
EXPECT_NE(static_cast<void*>(NULL), registered.ptr);
EXPECT_NE(buffers_[0].memory(), registered.ptr);
EXPECT_EQ(kBufferSize, registered.size);
EXPECT_NE(&buffers_[0], registered.shared_memory);
// But maps to the same physical memory.
*static_cast<int*>(registered.ptr) = 7;
*static_cast<int*>(buffers_[0].memory()) = 8;
EXPECT_EQ(8, *static_cast<int*>(registered.ptr));
}
TEST_F(TransferBufferManagerTest, CanDestroyTransferBuffer) {
EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[0],
kBufferSize));
transfer_buffer_manager_->DestroyTransferBuffer(1);
Buffer registered = transfer_buffer_manager_->GetTransferBuffer(1);
EXPECT_EQ(static_cast<void*>(NULL), registered.ptr);
EXPECT_EQ(0U, registered.size);
EXPECT_EQ(static_cast<base::SharedMemory*>(NULL), registered.shared_memory);
}
TEST_F(TransferBufferManagerTest, CannotRegregisterTransferBufferId) {
EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[0],
kBufferSize));
EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[0],
kBufferSize));
EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[1],
kBufferSize));
}
TEST_F(TransferBufferManagerTest, CanReuseTransferBufferIdAfterDestroying) {
EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[0],
kBufferSize));
transfer_buffer_manager_->DestroyTransferBuffer(1);
EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1,
&buffers_[1],
kBufferSize));
}
TEST_F(TransferBufferManagerTest, DestroyUnusedTransferBufferIdDoesNotCrash) {
transfer_buffer_manager_->DestroyTransferBuffer(1);
}
TEST_F(TransferBufferManagerTest, CannotRegisterNullTransferBuffer) {
EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(0,
&buffers_[0],
kBufferSize));
}
TEST_F(TransferBufferManagerTest, CannotRegisterNegativeTransferBufferId) {
EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(-1,
&buffers_[0],
kBufferSize));
}
} // namespace gpu
| 41.948276
| 78
| 0.606658
|
nagineni
|
68c7a487e962bab969ab40a56ea58e555a3defc7
| 1,848
|
cpp
|
C++
|
tests/src/main.cpp
|
nemu-cpp/web-server
|
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
|
[
"MIT"
] | null | null | null |
tests/src/main.cpp
|
nemu-cpp/web-server
|
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
|
[
"MIT"
] | null | null | null |
tests/src/main.cpp
|
nemu-cpp/web-server
|
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2019-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/nemu-cpp/web-framework/blob/main/LICENSE.txt
*/
#include "DebugTemplateEngineProfileTests.hpp"
#include "DebugTemplateEngineTests.hpp"
#include "FileSystemWebRequestHandlerTests.hpp"
#include "FunctionWebRequestHandlerTests.hpp"
#include "HardcodedWebRequestHandlerTests.hpp"
#include "MapViewContextTests.hpp"
#include "RouteTests.hpp"
#include "RoutesTests.hpp"
#include "SingleConnectionWebServerTests.hpp"
#include "ViewsTests.hpp"
#include "ViewWebRequestHandlerTests.hpp"
#include "WebApplicationTests.hpp"
#include "WebRequestTests.hpp"
#include "WebResponseBuilderTests.hpp"
#include "Nemu/WebFramework/linkoptions.hpp"
#include <Ishiko/TestFramework.hpp>
using namespace Ishiko;
int main(int argc, char* argv[])
{
TestHarness theTestHarness("NemuWebFramework");
theTestHarness.context().setTestDataDirectory("../../data");
theTestHarness.context().setTestOutputDirectory("../../output");
theTestHarness.context().setReferenceDataDirectory("../../reference");
TestSequence& theTests = theTestHarness.tests();
theTests.append<MapViewContextTests>();
theTests.append<ViewsTests>();
theTests.append<DebugTemplateEngineTests>();
theTests.append<DebugTemplateEngineProfileTests>();
theTests.append<SingleConnectionWebServerTests>();
theTests.append<WebRequestTests>();
theTests.append<WebResponseBuilderTests>();
theTests.append<RouteTests>();
theTests.append<RoutesTests>();
theTests.append<HardcodedWebRequestHandlerTests>();
theTests.append<FunctionWebRequestHandlerTests>();
theTests.append<FileSystemWebRequestHandlerTests>();
theTests.append<ViewWebRequestHandlerTests>();
theTests.append<WebApplicationTests>();
return theTestHarness.run();
}
| 35.538462
| 74
| 0.77381
|
nemu-cpp
|
68c7f065cffccfaa24d72f7e637a04addbf03f30
| 5,053
|
cpp
|
C++
|
src/main_void_MPI_bitvec.cpp
|
rapastranac/gempba
|
3b50f9809af95e2001615ab704bb055db68f50c8
|
[
"MIT"
] | 1
|
2021-07-08T13:52:06.000Z
|
2021-07-08T13:52:06.000Z
|
src/main_void_MPI_bitvec.cpp
|
rapastranac/gempba
|
3b50f9809af95e2001615ab704bb055db68f50c8
|
[
"MIT"
] | 2
|
2021-07-31T14:58:02.000Z
|
2021-09-07T01:55:06.000Z
|
src/main_void_MPI_bitvec.cpp
|
rapastranac/gempba
|
3b50f9809af95e2001615ab704bb055db68f50c8
|
[
"MIT"
] | null | null | null |
#ifdef BITVECTOR_VC
#include "../include/main.h"
#include "../include/Graph.hpp"
#include "../MPI_Modules/MPI_Scheduler.hpp"
#include "../include/VC_void_MPI_bitvec.hpp"
#include "../include/resultholder/ResultHolder.hpp"
#include "../include/BranchHandler.hpp"
#include "../include/DLB_Handler.hpp"
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <istream>
#include <sstream>
#include <iterator>
#include <string>
#include <vector>
#include <unistd.h>
int main_void_MPI_bitvec(int numThreads, int prob, std::string &filename)
{
auto &branchHandler = GemPBA::BranchHandler::getInstance(); // parallel library
auto &mpiScheduler = GemPBA::MPI_Scheduler::getInstance();
int rank = mpiScheduler.rank_me();
branchHandler.passMPIScheduler(&mpiScheduler);
cout << "NUMTHREADS= " << numThreads << endl;
VC_void_MPI_bitvec cover;
auto function = std::bind(&VC_void_MPI_bitvec ::mvcbitset, &cover, _1, _2, _3, _4, _5); // target algorithm [all arguments]
// initialize MPI and member variable linkin
/* this is run by all processes, because it is a bitvector implementation,
all processes should know the original graph ******************************************************/
Graph graph;
graph.readEdges(filename);
cover.init(graph, numThreads, filename, prob);
cover.setGraph(graph);
int gsize = graph.adj.size() + 1; //+1 cuz some files use node ids from 1 to n (instead of 0 to n - 1)
gbitset allzeros(gsize);
gbitset allones = ~allzeros;
branchHandler.setRefValue(gsize); // thus, all processes know the best value so far
branchHandler.setRefValStrategyLookup("minimise");
int zero = 0;
int solsize = graph.size();
cout << "solsize=" << solsize << endl;
std::string buffer = serializer(zero, allones, zero);
std::cout << "Starting MPI node " << branchHandler.rank_me() << std::endl;
int pid = getpid(); // for debugging purposes
fmt::print("rank {} is process ID : {}\n", rank, pid); // for debugging purposes
if (rank == 0)
{
// center process
mpiScheduler.runCenter(buffer.data(), buffer.size());
}
else
{
/* worker process
main thread will take care of Inter-process communication (IPC), dedicated core
numThreads could be the number of physical cores managed by this process - 1
*/
branchHandler.initThreadPool(numThreads);
auto bufferDecoder = branchHandler.constructBufferDecoder<void, int, gbitset, int>(function, deserializer);
auto resultFetcher = branchHandler.constructResultFetcher();
mpiScheduler.runNode(branchHandler, bufferDecoder, resultFetcher, serializer);
}
mpiScheduler.barrier();
// *****************************************************************************************
// this is a generic way of getting information from all the other processes after execution retuns
auto world_size = mpiScheduler.getWorldSize();
std::vector<double> idleTime(world_size);
std::vector<size_t> threadRequests(world_size);
std::vector<int> nTasksRecvd(world_size);
std::vector<int> nTasksSent(world_size);
double idl_tm = 0;
size_t rqst = 0;
int taskRecvd;
int taskSent;
if (rank != 0)
{ //rank 0 does not run the main function
idl_tm = branchHandler.getPoolIdleTime();
rqst = branchHandler.number_thread_requests();
taskRecvd = mpiScheduler.tasksRecvd();
taskSent = mpiScheduler.tasksSent();
}
// here below, idl_tm is the idle time of the other ranks, which is gathered by .allgather() and stored in
// a contiguos array
mpiScheduler.allgather(idleTime.data(), &idl_tm, MPI_DOUBLE);
mpiScheduler.allgather(threadRequests.data(), &rqst, MPI_UNSIGNED_LONG_LONG);
mpiScheduler.gather(&taskRecvd, 1, MPI_INT, nTasksRecvd.data(), 1, MPI_INT, 0);
mpiScheduler.gather(&taskSent, 1, MPI_INT, nTasksSent.data(), 1, MPI_INT, 0);
// *****************************************************************************************
if (rank == 0)
{
auto solutions = mpiScheduler.fetchResVec();
mpiScheduler.printStats();
//print sumation of refValGlobal
int solsize;
std::stringstream ss;
std::string buffer = mpiScheduler.fetchSolution(); // returns a stringstream
ss << buffer;
deserializer(ss, solsize);
fmt::print("Cover size : {} \n", solsize);
double sum = 0;
for (int i = 1; i < world_size; i++)
{
sum += idleTime[i];
}
fmt::print("\nGlobal pool idle time: {0:.6f} seconds\n\n\n", sum);
// **************************************************************************
for (int rank = 1; rank < world_size; rank++)
{
fmt::print("tasks sent by rank {} = {} \n", rank, nTasksSent[rank]);
}
fmt::print("\n");
for (int rank = 1; rank < world_size; rank++)
{
fmt::print("tasks received by rank {} = {} \n", rank, nTasksRecvd[rank]);
}
fmt::print("\n");
for (int rank = 1; rank < world_size; rank++)
{
fmt::print("rank {}, thread requests: {} \n", rank, threadRequests[rank]);
}
fmt::print("\n\n\n");
// **************************************************************************
}
return 0;
}
#endif
| 30.624242
| 124
| 0.64338
|
rapastranac
|
68c845b9335cdf764e208c6c9a498556a8478c7c
| 16,778
|
hh
|
C++
|
include/click/flow/flowelement.hh
|
MassimoGirondi/fastclick
|
71b9a3392c2e847a22de3c354be1d9f61216cb5b
|
[
"BSD-3-Clause-Clear"
] | 1
|
2021-01-22T16:51:37.000Z
|
2021-01-22T16:51:37.000Z
|
include/click/flow/flowelement.hh
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
include/click/flow/flowelement.hh
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
// -*- c-basic-offset: 4 -*-
#ifndef CLICK_FLOWELEMENT_HH
#define CLICK_FLOWELEMENT_HH
#include <click/glue.hh>
#include <click/vector.hh>
#include <click/string.hh>
#include <click/batchelement.hh>
#include <click/routervisitor.hh>
#include <click/pair.hh>
#include "flow.hh"
CLICK_DECLS
#ifdef HAVE_FLOW
# if HAVE_CTX
class CTXManager;
# endif
class VirtualFlowManager;
enum FlowType {
FLOW_NONE = 0,
FLOW_ETHER,
FLOW_ARP,
FLOW_IP,
FLOW_TCP,
FLOW_UDP,
FLOW_ICMP,
FLOW_HTTP
};
class FlowElement : public BatchElement {
public:
FlowElement();
~FlowElement();
# if HAVE_CTX
virtual FlowNode* get_table(int iport, Vector<FlowElement*> contextStack);
virtual FlowNode* resolveContext(FlowType, Vector<FlowElement*> stack);
# endif
virtual FlowType getContext(int port);
virtual bool stopClassifier() { return false; };
};
/**
* Element that needs FCB space
*/
class VirtualFlowSpaceElement : public FlowElement {
public:
VirtualFlowSpaceElement();
virtual const size_t flow_data_size() const = 0;
virtual const int flow_data_index() const {
return -1;
}
inline void set_flow_data_offset(int offset) {_flow_data_offset = offset; }
inline int flow_data_offset() {return _flow_data_offset; }
int configure_phase() const { return CONFIGURE_PHASE_DEFAULT + 5; }
void *cast(const char *name) override;
#if HAVE_FLOW_DYNAMIC
inline void fcb_acquire(int count = 1) {
fcb_stack->acquire(count);
}
inline void fcb_update(int count) {
if (count > 0)
fcb_stack->acquire(count);
else if (count < 0)
fcb_stack->release(-count);
}
inline void fcb_release(int count = 1) {
fcb_stack->release(count);
}
#else
inline void fcb_acquire(int count = 1) {
(void)count;
}
inline void fcb_update(int) {}
inline void fcb_release(int count = 1) {
(void)count;
}
#endif
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
inline void fcb_acquire_timeout(int nmsec) {
//Do not set a smaller timeout
if ((fcb_stack->flags & FLOW_TIMEOUT) && (nmsec <= (int)(fcb_stack->flags >> FLOW_TIMEOUT_SHIFT))) {
#if DEBUG_CLASSIFIER_TIMEOUT > 1
click_chatter("Acquiring timeout of %p, not changing it, flag %d",this,fcb_stack->flags);
#endif
return;
}
#if DEBUG_CLASSIFIER_TIMEOUT > 1
click_chatter("Acquiring timeout of %p to %d, flag %d",this,nmsec,fcb_stack->flags);
#endif
fcb_stack->flags = (nmsec << FLOW_TIMEOUT_SHIFT) | FLOW_TIMEOUT | ((fcb_stack->flags & FLOW_TIMEOUT_INLIST) ? FLOW_TIMEOUT_INLIST : 0);
}
inline void fcb_release_timeout() {
#if DEBUG_CLASSIFIER_TIMEOUT > 1
click_chatter("Releasing timeout of %p",this);
#endif
//If the timeout is in list, we must not put it back in the pool
if (fcb_stack->flags & FLOW_TIMEOUT_INLIST)
assert(fcb_stack->flags & FLOW_TIMEOUT);
if ((fcb_stack->flags & FLOW_TIMEOUT) && (fcb_stack->flags & FLOW_TIMEOUT_INLIST))
fcb_stack->flags = 0 | FLOW_TIMEOUT | FLOW_TIMEOUT_INLIST;
else
fcb_stack->flags = 0;
}
#else
inline void fcb_acquire_timeout(int nmsec) {
//TODO : use a local timer
fcb_acquire();
}
inline void fcb_release_timeout() {
fcb_release();
}
#endif
#if HAVE_DYNAMIC_FLOW_RELEASE_FNT
inline void fcb_set_release_fnt(struct FlowReleaseChain* fcb_chain, SubFlowRealeaseFnt fnt) {
fcb_chain->previous_fnt = fcb_stack->release_fnt;
fcb_chain->previous_thunk = fcb_stack->thunk;
fcb_stack->release_fnt = fnt;
fcb_stack->thunk = this;
#if DEBUG_CLASSIFIER_RELEASE
click_chatter("Release fnt set to %p, was %p",fcb_stack->release_fnt,fcb_chain->previous_fnt);
#endif
}
inline void fcb_remove_release_fnt(struct FlowReleaseChain* fcb_chain, SubFlowRealeaseFnt fnt) {
debug_flow("Release fnt remove %p",fnt);
if (likely(fcb_stack->release_fnt == fnt)) { //Normally it will call the chain in the same order
fcb_stack->release_fnt = fcb_chain->previous_fnt;
fcb_stack->thunk = fcb_chain->previous_thunk;
debug_flow("Release removed is now to %p",fcb_stack->release_fnt);
} else {
SubFlowRealeaseFnt chain_fnt = fcb_stack->release_fnt;
VirtualFlowSpaceElement* fe = static_cast<VirtualFlowSpaceElement*>(fcb_stack->thunk);
FlowReleaseChain* frc;
do {
if (fe == 0) {
click_chatter("BAD ERROR : Trying to remove a timeout flow function that is not set...");
return;
}
frc = reinterpret_cast<FlowReleaseChain*>(&fcb_stack->data[fe->_flow_data_offset]);
chain_fnt = frc->previous_fnt;
if (chain_fnt == 0) {
click_chatter("ERROR : Trying to remove a timeout flow function that is not set...");
return;
}
fe = static_cast<VirtualFlowSpaceElement*>(frc->previous_thunk);
} while (chain_fnt != fnt);
frc->previous_fnt = fcb_chain->previous_fnt;
frc->previous_thunk = fcb_chain->previous_thunk;
}
}
#else
inline void fcb_set_release_fnt(struct FlowReleaseChain* fcb, SubFlowRealeaseFnt fnt) {
click_chatter("ERROR: YOU MUST HAVE DYNAMIC FLOW RELEASE FNT fct setted !");
assert(false);
}
#endif
virtual PacketBatch* pull_batch(int port, unsigned max) override final {
click_chatter("ERROR : Flow Elements do not support pull");
return 0;
}
int initialize(ErrorHandler *errh) override CLICK_COLD {
//The element itself is automatically posted by build_fcb via fcb_builded_init_future
return 0;
}
protected:
int _flow_data_offset;
friend class FlowBufferVisitor;
friend class VirtualFlowManager;
};
/**
* This future will only trigger once it is called N times.
* N is increased by calling add(). The typical usage is a future
* that will only trigger when all parents have called. To do this,
* you call add() in the constructor of the parents.
*/
class CounterInitFuture : public Router::ChildrenFuture { public:
CounterInitFuture(String name, std::function<int(ErrorHandler*)> on_reached);
CounterInitFuture(String name, std::function<void(void)> on_reached);
virtual void notifyParent(InitFuture* future) override;
virtual int solve_initialize(ErrorHandler* errh) override;
virtual int completed(ErrorHandler* errh) override;
private:
int _n;
String _name;
std::function<int(ErrorHandler*)> _on_reached;
};
/**
* Element that allocates some FCB Space
*/
class VirtualFlowManager : public FlowElement { public:
VirtualFlowManager();
static CounterInitFuture* fcb_builded_init_future() {
return &_fcb_builded_init_future;
}
static CounterInitFuture _fcb_builded_init_future;
protected:
int _reserve;
typedef Pair<Element*,int> EDPair;
Vector<EDPair> _reachable_list;
static Vector<VirtualFlowManager*> _entries;
void find_children(int verbose = 0);
static void _build_fcb(int verbose, bool ordered);
static void build_fcb();
virtual void fcb_built() {
}
bool stopClassifier() { return true; };
friend class CTXElement;
};
template<typename T> class FlowSpaceElement : public VirtualFlowSpaceElement {
public :
FlowSpaceElement() CLICK_COLD;
void fcb_set_init_data(FlowControlBlock* fcb, const T data) CLICK_COLD;
virtual const size_t flow_data_size() const override { return sizeof(T); }
/**
* Return the T type for a given FCB
*/
inline T* fcb_data_for(FlowControlBlock* fcb) {
T* flowdata = static_cast<T*>((void*)&fcb->data[_flow_data_offset]);
return flowdata;
}
/**
* Return the T type in the current FCB on the stack
*/
inline T* fcb_data() {
return fcb_data_for(fcb_stack);
}
void push_batch(int port, PacketBatch* head) final {
push_flow(port, fcb_data(), head);
};
virtual void push_flow(int port, T* flowdata, PacketBatch* head) = 0;
};
/**
* FlowStateElement is like FlowSpaceElement but handle a timeout and a release functions
*
* The child must implement :
* static const int timeout; //Timeout in msec for a flow
* bool new_flow(T*, Packet*);
* void push_batch(int port, T*, Packet*);
* void release_flow(T*);
*
* close_flow() can be called to release the flow now, remove timer etc It will not call your release_flow(); automatically, do it before. A packet coming for the same flow after close_flow() is called will be considered from a new flow (seen flag is reset).
*/
template<class Derived, typename T> class FlowStateElement : public VirtualFlowSpaceElement {
struct AT : public FlowReleaseChain {
T v;
bool seen;
};
public :
typedef FlowStateElement<Derived, T> derived;
FlowStateElement() CLICK_COLD;
virtual const size_t flow_data_size() const { return sizeof(AT); }
/**
* CRTP virtual
*/
inline bool new_flow(T*, Packet*) {
return true;
}
/**
* Return the T type for a given FCB
*/
inline T* fcb_data_for(FlowControlBlock* fcb) {
AT* flowdata = static_cast<AT*>((void*)&fcb->data[_flow_data_offset]);
return &flowdata->v;
}
/**
* Return the T type in the current FCB on the stack
*/
inline T* fcb_data() {
return fcb_data_for(fcb_stack);
}
static void release_fnt(FlowControlBlock* fcb, void* thunk ) {
Derived* derived = static_cast<Derived*>(thunk);
AT* my_fcb = reinterpret_cast<AT*>(&fcb->data[derived->_flow_data_offset]);
derived->release_flow(&my_fcb->v);
if (my_fcb->previous_fnt)
my_fcb->previous_fnt(fcb, my_fcb->previous_thunk);
}
void push_batch(int port, PacketBatch* head) {
auto my_fcb = my_fcb_data();
if (!my_fcb->seen) {
if (static_cast<Derived*>(this)->new_flow(&my_fcb->v, head->first())) {
my_fcb->seen = true;
if (Derived::timeout > 0)
this->fcb_acquire_timeout(Derived::timeout);
#if HAVE_DYNAMIC_FLOW_RELEASE_FNT
this->fcb_set_release_fnt(my_fcb, &release_fnt);
#endif
} else { //TODO set early drop?
head->fast_kill();
return;
}
}
static_cast<Derived*>(this)->push_flow(port, &my_fcb->v, head);
};
void close_flow() {
if (Derived::timeout > 0) {
this->fcb_release_timeout();
}
#if HAVE_DYNAMIC_FLOW_RELEASE_FNT
this->fcb_remove_release_fnt(my_fcb_data(), &release_fnt);
#endif
my_fcb_data()->seen = false;
}
private:
inline AT* my_fcb_data() {
return static_cast<AT*>((void*)&fcb_stack->data[_flow_data_offset]);
}
};
template<typename T, int index> class FlowSharedBufferElement : public FlowSpaceElement<T> {
public :
FlowSharedBufferElement() : FlowSpaceElement<T>() {
}
const size_t flow_data_size() const final { return sizeof(T); }
const int flow_data_index() const final { return index; }
};
#define DefineFlowSharedBuffer(name,type,index) class FlowSharedBuffer ## name ## Element : public FlowSharedBufferElement<type,index>{ };
DefineFlowSharedBuffer(Paint,int,0);
#define NR_SHARED_FLOW 1
class FlowElementVisitor : public RouterVisitor {
public:
Element* origin;
FlowElementVisitor(Element* e) : origin(e) {
}
struct inputref {
FlowElement* elem;
int iport;
};
Vector<struct inputref> dispatchers;
bool visit(Element *e, bool isoutput, int port,
Element *from_e, int from_port, int distance) {
FlowElement* dispatcher = dynamic_cast<FlowElement*>(e);
if (dispatcher != NULL) {
if (dispatcher == origin)
return false;
struct inputref ref = {.elem = dispatcher, .iport = port};
dispatchers.push_back(ref);
return false;
} else {
}
/*if (v.dispatchers[i] == (FlowElement*)e) {
click_chatter("Classification loops are unsupported, place another CTXManager before reinjection of the packets.");
e->router()->please_stop_driver();
return 0;
}*/
return true;
}
static FlowNode* get_downward_table(Element* e, int output, Vector<FlowElement*> context, bool resolve_context = false);
};
/**
* FlowSpaceElement
*/
template<typename T>
FlowSpaceElement<T>::FlowSpaceElement() : VirtualFlowSpaceElement() {
}
# if HAVE_CTX
template<typename T>
void FlowSpaceElement<T>::fcb_set_init_data(FlowControlBlock* fcb, const T data) {
for (int i = 0; i < sizeof(T); i++) {
if (fcb->data[FCBPool::init_data_size() + _flow_data_offset + i] && fcb->data[_flow_data_offset + i] != ((uint8_t*)&data)[i]) {
click_chatter("In %p{element} for offset %d :",this, _flow_data_offset+i);
click_chatter("Index [%d] : Cannot set data to %d, as it is already %d",i,*((T*)(&fcb->data[_flow_data_offset])),data);
click_chatter("Is marked as set : %d", fcb->data[FCBPool::init_data_size() + _flow_data_offset + i]);
fcb->reverse_print();
click_chatter("It generally means your graph is messed up");
assert(false);
}
fcb->data[FCBPool::init_data_size() + _flow_data_offset + i] = 0xff;
}
*((T*)(&fcb->data[_flow_data_offset])) = data;
}
# endif
/**
* FlowSpaceElement
*/
template<class Derived, typename T>
FlowStateElement<Derived, T>::FlowStateElement() : VirtualFlowSpaceElement() {
}
/**
* Macro to define context
*
* In practice it will overwrite get_table
*/
# if HAVE_CTX
#define DEFAULT_4TUPLE "12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3"
//Those should not be used anymore, as the FLOW_CONTEXT is a much better alternative that assuming the top session is IP...
#define TCP_SESSION "9/06! 12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3"
#define UDP_SESSION "9/11! 12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3"
//Use only one of the 3 following macros
/**
* Define a context (such as FLOW_IP) but no rule/session
*/
#define FLOW_ELEMENT_DEFINE_CONTEXT(ft) \
FlowNode* get_table(int iport, Vector<FlowElement*> context) override CLICK_COLD {\
context.push_back(this);\
return FlowElement::get_table(iport, context);\
}\
virtual FlowType getContext(int) override {\
return ft;\
}\
/**
* Define a context (such as FLOW_TCP) and a rule/session definition
*/
#define FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,ft) \
FlowNode* get_table(int iport, Vector<FlowElement*> contextStack) override CLICK_COLD {\
if (ft)\
contextStack.push_back(this);\
FlowNode* down = FlowElement::get_table(iport,contextStack); \
FlowNode* my = FlowClassificationTable::parse(this,rule).root;\
return my->combine(down, true, true, true, this);\
}\
virtual FlowType getContext(int) override {\
return ft;\
}\
/**
* Define only a rule/session definition but no context
*/
#define FLOW_ELEMENT_DEFINE_SESSION(rule) \
FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,FLOW_NONE)
/**
* Defin two rules/sessions but no context
*/
#define FLOW_ELEMENT_DEFINE_SESSION_DUAL(ruleA,ruleB) \
FlowNode* get_table(int iport, Vector<FlowElement*> context) override CLICK_COLD {\
return FlowClassificationTable::parse(this,ruleA).root->combine(FlowClassificationTable::parse(this,ruleB).root,false,false,true,this)->combine(FlowElement::get_table(iport,context), true, true, true, this);\
}
/**
* Define the context no matter the input port, and a rule but only for one specific port
*/
#define FLOW_ELEMENT_DEFINE_PORT_SESSION_CONTEXT(port_num,rule,ft) \
FlowNode* get_table(int iport, Vector<FlowElement*> contextStack) override {\
if (iport == port_num) {\
return FlowClassificationTable::parse(this,rule).root->combine(FlowElement::get_table(iport,contextStack), true, true, true, this);\
}\
if (ft)\
contextStack.push_back(this);\
return FlowElement::get_table(iport,contextStack);\
}\
virtual FlowType getContext(int) override {\
return ft;\
}
#endif
#else //Not even HAVE_FLOW
typedef BatchElement FlowElement;
#endif
#if !defined(HAVE_CTX)
#define FLOW_ELEMENT_DEFINE_SESSION(rule,context)
#define FLOW_ELEMENT_DEFINE_PORT_CONTEXT(port,rule,context)
#define FLOW_ELEMENT_DEFINE_SESSION_DUAL(ruleA,ruleB)
#define FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,context)
#define FLOW_ELEMENT_DEFINE_PORT_SESSION_CONTEXT(port,rule,context)
#endif
CLICK_ENDDECLS
#endif
| 30.672761
| 258
| 0.671355
|
MassimoGirondi
|
68c88971ef4e0dc763be19d3efed1264cdbf02af
| 4,475
|
cpp
|
C++
|
arangod/Scheduler/JobQueue.cpp
|
pjesudhas/ArangoDB
|
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
|
[
"BSL-1.0",
"Zlib",
"ICU",
"Apache-2.0"
] | null | null | null |
arangod/Scheduler/JobQueue.cpp
|
pjesudhas/ArangoDB
|
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
|
[
"BSL-1.0",
"Zlib",
"ICU",
"Apache-2.0"
] | null | null | null |
arangod/Scheduler/JobQueue.cpp
|
pjesudhas/ArangoDB
|
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
|
[
"BSL-1.0",
"Zlib",
"ICU",
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "JobQueue.h"
#include "Basics/ConditionLocker.h"
#include "GeneralServer/RestHandler.h"
#include "Logger/Logger.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/SchedulerFeature.h"
using namespace arangodb;
namespace {
class JobQueueThread final : public Thread {
public:
JobQueueThread(JobQueue* server, boost::asio::io_service* ioService)
: Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {}
~JobQueueThread() { shutdown(); }
void beginShutdown() {
Thread::beginShutdown();
_jobQueue->wakeup();
}
public:
void run() {
int idleTries = 0;
auto jobQueue = _jobQueue;
// iterate until we are shutting down
while (!isStopping()) {
++idleTries;
for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) {
LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": "
<< _jobQueue->queueSize(i);
while (_jobQueue->tryActive()) {
Job* job = nullptr;
if (!_jobQueue->pop(i, job)) {
_jobQueue->releaseActive();
break;
}
LOG_TOPIC(TRACE, Logger::THREADS)
<< "starting next queued job, number currently active "
<< _jobQueue->active();
idleTries = 0;
_ioService->dispatch([jobQueue, job]() {
std::unique_ptr<Job> guard(job);
job->_callback(std::move(job->_handler));
jobQueue->releaseActive();
jobQueue->wakeup();
});
}
}
// we need to check again if more work has arrived after we have
// aquired the lock. The lockfree queue and _nrWaiting are accessed
// using "memory_order_seq_cst", this guarantees that we do not
// miss a signal.
if (idleTries >= 2) {
LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep";
_jobQueue->waitForWork();
}
}
}
private:
JobQueue* _jobQueue;
boost::asio::io_service* _ioService;
};
}
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService)
: _queueAql(queueSize),
_queueRequeue(queueSize),
_queueStandard(queueSize),
_queueUser(queueSize),
_queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser},
_active(0),
_ioService(ioService),
_queueThread(new JobQueueThread(this, _ioService)) {
for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) {
_queuesSize[i].store(0);
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
void JobQueue::start() {
_queueThread->start();
}
void JobQueue::beginShutdown() {
_queueThread->beginShutdown();
}
bool JobQueue::tryActive() {
if (!SchedulerFeature::SCHEDULER->tryBlocking()) {
return false;
}
++_active;
return true;
}
void JobQueue::releaseActive() {
SchedulerFeature::SCHEDULER->unworkThread();
--_active;
}
void JobQueue::wakeup() {
CONDITION_LOCKER(guard, _queueCondition);
guard.signal();
}
void JobQueue::waitForWork() {
static uint64_t WAIT_TIME = 1000 * 1000;
CONDITION_LOCKER(guard, _queueCondition);
guard.wait(WAIT_TIME);
}
| 28.685897
| 80
| 0.56
|
pjesudhas
|
68d06c4cee3563eb2780bc7480f894d15594a007
| 1,066
|
hpp
|
C++
|
src/ipc/ipc.hpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 277
|
2021-11-19T20:15:18.000Z
|
2022-03-29T12:07:59.000Z
|
src/ipc/ipc.hpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 46
|
2021-11-21T10:25:58.000Z
|
2022-03-23T15:04:51.000Z
|
src/ipc/ipc.hpp
|
imaphatduc/Hypr
|
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
|
[
"BSD-3-Clause"
] | 28
|
2021-12-07T02:49:16.000Z
|
2022-03-22T05:26:07.000Z
|
#pragma once
#include "../defines.hpp"
std::string readFromIPCChannel(const std::string);
int writeToIPCChannel(const std::string, std::string);
#define IPC_END_OF_FILE (std::string)"HYPR_END_OF_FILE"
#define IPC_MESSAGE_SEPARATOR std::string("\t")
#define IPC_MESSAGE_EQUALITY std::string("=")
struct SIPCMessageMainToBar {
std::vector<int> openWorkspaces;
uint64_t activeWorkspace;
std::string lastWindowName;
std::string lastWindowClass;
bool fullscreenOnBar;
};
struct SIPCMessageBarToMain {
uint64_t windowID;
};
struct SIPCPipe {
std::string szPipeName = "";
uint64_t iPipeFD = 0;
};
// /tmp/ is RAM so the speeds will be decent, if anyone wants to implement
// actual pipes feel free.
void IPCSendMessage(const std::string, SIPCMessageMainToBar);
void IPCSendMessage(const std::string, SIPCMessageBarToMain);
void IPCRecieveMessageB(const std::string);
void IPCRecieveMessageM(const std::string);
| 31.352941
| 74
| 0.666979
|
imaphatduc
|
68d34d564ceb53f0ebc5b1a17bfa5928436ccd5e
| 2,009
|
cpp
|
C++
|
Engine/Model.cpp
|
kristofe/VolumeRenderer
|
653976ef8c80d05fd1059ebc0b3d3542649879fc
|
[
"MIT"
] | null | null | null |
Engine/Model.cpp
|
kristofe/VolumeRenderer
|
653976ef8c80d05fd1059ebc0b3d3542649879fc
|
[
"MIT"
] | null | null | null |
Engine/Model.cpp
|
kristofe/VolumeRenderer
|
653976ef8c80d05fd1059ebc0b3d3542649879fc
|
[
"MIT"
] | null | null | null |
/*
* Model.cpp
* XPlatformGL
*
* Created by Kristofer Schlachter on 1/2/09.
* Copyright 2009 __MyCompanyName__. All rights reserved.
*
*/
#include "Model.h"
#include "Platform.h"
#include "Globals.h"
#include "Mesh.h"
#include <stdlib.h>
//#include <stdio.h>
#include <math.h>
////////////////////////////////////////////////////////////////////////////////
Model::Model(){
mRendererMesh = 0;
// mDisplayModel = NULL;
// mChangeBufferModel = NULL;
// mUpdatesArePending = false;
}
////////////////////////////////////////////////////////////////////////////////
/*
Model::Model(Mesh* md){
Model::Model();
mDisplayModel = md;
}
////////////////////////////////////////////////////////////////////////////////
Model::~Model()
{
SAFE_DELETE(mDisplayModel);
SAFE_DELETE(mChangeBufferModel);
Threading::MutexDestroy(mMutex);
}
////////////////////////////////////////////////////////////////////////////////
void Model::Update(Mesh* updatedModel){
Threading::MutexLock(mMutex);
mUpdatesArePending = true;
mChangeBufferModel = updatedModel;
Threading::MutexUnlock(mMutex);
};
////////////////////////////////////////////////////////////////////////////////
void Model::ForceSyncOfModelData(){
Threading::MutexLock(mMutex);
if(mUpdatesArePending){
SyncModelData();
mUpdatesArePending = false;
}
Threading::MutexUnlock(mMutex);
}
////////////////////////////////////////////////////////////////////////////////
void Model::SyncModelData(){
if(mChangeBufferModel == NULL) return;
Threading::MutexLock(mMutex);
if(mDisplayModel == NULL){
mDisplayModel = new Mesh();
}
mDisplayModel->Sync(mChangeBufferModel);
mChangeBufferModel->SetDirtyFlags(MESH_STATE_CLEAN);
mDisplayModel->SetDirtyFlags(MESH_STATE_CLEAN);
Threading::MutexUnlock(mMutex);
}
////////////////////////////////////////////////////////////////////////////////
bool Model::HasPendingUpdates(){
Threading::MutexLock(mMutex);
return mUpdatesArePending;
Threading::MutexUnlock(mMutex);
}
*/
| 22.573034
| 80
| 0.520159
|
kristofe
|
68d4601f864810d0ecc2a731fa03496616a82c2b
| 8,737
|
hpp
|
C++
|
include/metrics/pu_encode_data.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/metrics/pu_encode_data.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/metrics/pu_encode_data.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_METRICS_PU_ENCODE_DATA_HPP
#define PIC_METRICS_PU_ENCODE_DATA_HPP
#include <math.h>
#include "../base.hpp"
#include "../image.hpp"
#include "../util/array.hpp"
namespace pic {
float C_PU_x[256] = {
-5.000000f,
-4.882784f,
-4.765568f,
-4.706960f,
-4.648352f,
-4.589744f,
-4.531136f,
-4.472527f,
-4.413919f,
-4.355311f,
-4.296703f,
-4.238095f,
-4.179487f,
-4.120879f,
-4.062271f,
-4.003663f,
-3.945055f,
-3.886447f,
-3.827839f,
-3.769231f,
-3.710623f,
-3.652015f,
-3.593407f,
-3.534799f,
-3.476190f,
-3.417582f,
-3.358974f,
-3.300366f,
-3.241758f,
-3.183150f,
-3.124542f,
-3.065934f,
-3.007326f,
-2.948718f,
-2.890110f,
-2.831502f,
-2.772894f,
-2.743590f,
-2.714286f,
-2.684982f,
-2.655678f,
-2.626374f,
-2.597070f,
-2.567766f,
-2.538462f,
-2.509158f,
-2.479853f,
-2.450549f,
-2.421245f,
-2.391941f,
-2.362637f,
-2.333333f,
-2.304029f,
-2.274725f,
-2.245421f,
-2.216117f,
-2.186813f,
-2.157509f,
-2.128205f,
-2.098901f,
-2.069597f,
-2.040293f,
-2.010989f,
-1.981685f,
-1.952381f,
-1.923077f,
-1.893773f,
-1.864469f,
-1.835165f,
-1.805861f,
-1.776557f,
-1.747253f,
-1.717949f,
-1.688645f,
-1.659341f,
-1.630037f,
-1.600733f,
-1.571429f,
-1.542125f,
-1.512821f,
-1.483516f,
-1.454212f,
-1.424908f,
-1.395604f,
-1.366300f,
-1.336996f,
-1.307692f,
-1.278388f,
-1.249084f,
-1.219780f,
-1.190476f,
-1.161172f,
-1.131868f,
-1.102564f,
-1.073260f,
-1.043956f,
-1.014652f,
-0.985348f,
-0.956044f,
-0.926740f,
-0.897436f,
-0.868132f,
-0.838828f,
-0.809524f,
-0.780220f,
-0.750916f,
-0.736264f,
-0.721612f,
-0.706960f,
-0.692308f,
-0.677656f,
-0.663004f,
-0.648352f,
-0.633700f,
-0.619048f,
-0.604396f,
-0.589744f,
-0.575092f,
-0.560440f,
-0.545788f,
-0.531136f,
-0.516484f,
-0.501832f,
-0.487179f,
-0.472527f,
-0.457875f,
-0.443223f,
-0.428571f,
-0.413919f,
-0.399267f,
-0.384615f,
-0.369963f,
-0.355311f,
-0.340659f,
-0.326007f,
-0.311355f,
-0.296703f,
-0.282051f,
-0.267399f,
-0.252747f,
-0.238095f,
-0.223443f,
-0.208791f,
-0.194139f,
-0.179487f,
-0.164835f,
-0.150183f,
-0.135531f,
-0.120879f,
-0.106227f,
-0.091575f,
-0.076923f,
-0.062271f,
-0.047619f,
-0.032967f,
-0.018315f,
-0.003663f,
0.010989f,
0.025641f,
0.040293f,
0.054945f,
0.069597f,
0.084249f,
0.098901f,
0.113553f,
0.128205f,
0.142857f,
0.157509f,
0.172161f,
0.186813f,
0.201465f,
0.216117f,
0.230769f,
0.245421f,
0.267399f,
0.285714f,
0.300366f,
0.315018f,
0.329670f,
0.344322f,
0.358974f,
0.373626f,
0.388278f,
0.402930f,
0.417582f,
0.432234f,
0.446886f,
0.461538f,
0.476190f,
0.490842f,
0.505495f,
0.520147f,
0.534799f,
0.549451f,
0.564103f,
0.578755f,
0.593407f,
0.608059f,
0.622711f,
0.637363f,
0.652015f,
0.666667f,
0.681319f,
0.695971f,
0.710623f,
0.725275f,
0.739927f,
0.754579f,
0.769231f,
0.783883f,
0.798535f,
0.813187f,
0.827839f,
0.842491f,
0.857143f,
0.871795f,
0.886447f,
0.915751f,
0.945055f,
0.974359f,
1.003663f,
1.032967f,
1.062271f,
1.091575f,
1.120879f,
1.150183f,
1.179487f,
1.208791f,
1.238095f,
1.267399f,
1.296703f,
1.326007f,
1.355311f,
1.384615f,
1.413919f,
1.443223f,
1.472527f,
1.501832f,
1.531136f,
1.589744f,
1.648352f,
1.706960f,
1.765568f,
1.824176f,
1.882784f,
1.930403f,
2.007326f,
2.095238f,
2.186813f,
2.307692f,
2.399267f,
2.567766f,
2.725275f,
2.871795f,
3.260073f,
10.000000f
};
float C_PU_y[256] = {
0.000000f,
0.025875f,
0.055091f,
0.071086f,
0.088082f,
0.106142f,
0.125333f,
0.145726f,
0.167397f,
0.190424f,
0.214893f,
0.240894f,
0.268524f,
0.297884f,
0.329082f,
0.362234f,
0.397462f,
0.434897f,
0.474675f,
0.516944f,
0.561860f,
0.609589f,
0.660307f,
0.714201f,
0.771470f,
0.832325f,
0.896991f,
0.965706f,
1.038724f,
1.116315f,
1.198765f,
1.286377f,
1.379476f,
1.478406f,
1.583530f,
1.695237f,
1.813939f,
1.876050f,
1.940075f,
2.006075f,
2.074110f,
2.144242f,
2.216537f,
2.291062f,
2.367884f,
2.447076f,
2.528709f,
2.612859f,
2.699604f,
2.789024f,
2.881201f,
2.976220f,
3.074169f,
3.175139f,
3.279222f,
3.386514f,
3.497114f,
3.611125f,
3.728651f,
3.849802f,
3.974687f,
4.103424f,
4.236130f,
4.372927f,
4.513943f,
4.659307f,
4.809153f,
4.963618f,
5.122847f,
5.286985f,
5.456184f,
5.630599f,
5.810392f,
5.995728f,
6.186778f,
6.383718f,
6.586730f,
6.796000f,
7.011722f,
7.234093f,
7.463319f,
7.699611f,
7.943187f,
8.194270f,
8.453091f,
8.719889f,
8.994909f,
9.278403f,
9.570633f,
9.871866f,
10.182379f,
10.502456f,
10.832392f,
11.172488f,
11.523055f,
11.884415f,
12.256896f,
12.640840f,
13.036596f,
13.444523f,
13.864993f,
14.298387f,
14.745097f,
15.205526f,
15.680088f,
16.169211f,
16.419369f,
16.673331f,
16.931156f,
17.192899f,
17.458619f,
17.728376f,
18.002228f,
18.280235f,
18.562459f,
18.848962f,
19.139806f,
19.435055f,
19.734773f,
20.039023f,
20.347873f,
20.661388f,
20.979636f,
21.302683f,
21.630599f,
21.963452f,
22.301312f,
22.644250f,
22.992336f,
23.345643f,
23.704242f,
24.068207f,
24.437610f,
24.812526f,
25.193029f,
25.579193f,
25.971094f,
26.368808f,
26.772409f,
27.181974f,
27.597580f,
28.019302f,
28.447218f,
28.881403f,
29.321934f,
29.768887f,
30.222337f,
30.682362f,
31.149035f,
31.622432f,
32.102627f,
32.589692f,
33.083700f,
33.584723f,
34.092830f,
34.608091f,
35.130574f,
35.660343f,
36.197464f,
36.741998f,
37.294006f,
37.853546f,
38.420673f,
38.995440f,
39.577897f,
40.168091f,
40.766065f,
41.371860f,
41.985513f,
42.607056f,
43.236517f,
43.873922f,
44.519290f,
45.172636f,
46.167636f,
47.010542f,
47.693856f,
48.385150f,
49.084410f,
49.791614f,
50.506734f,
51.229738f,
51.960586f,
52.699233f,
53.445627f,
54.199709f,
54.961417f,
55.730679f,
56.507418f,
57.291553f,
58.082994f,
58.881648f,
59.687414f,
60.500187f,
61.319857f,
62.146308f,
62.979420f,
63.819070f,
64.665127f,
65.517461f,
66.375935f,
67.240411f,
68.110747f,
68.986801f,
69.868426f,
70.755476f,
71.647801f,
72.545254f,
73.447684f,
74.354943f,
75.266880f,
76.183346f,
77.104195f,
78.029279f,
78.958452f,
79.891572f,
80.828498f,
82.713208f,
84.611499f,
86.522330f,
88.444709f,
90.377696f,
92.320405f,
94.272002f,
96.231710f,
98.198806f,
100.172619f,
102.152530f,
104.137968f,
106.128409f,
108.123375f,
110.122427f,
112.125165f,
114.131226f,
116.140281f,
118.152030f,
120.166201f,
122.182551f,
124.200857f,
128.242559f,
132.289936f,
136.341877f,
140.397483f,
144.456030f,
148.516935f,
151.817830f,
157.152166f,
163.251012f,
169.605996f,
177.996740f,
184.354479f,
196.054275f,
206.992126f,
217.167385f,
244.132872f,
712.224440f
};
} // end namespace pic
#endif /* PIC_METRICS_PU_ENCODE_DATA_HPP */
| 15.856624
| 67
| 0.550418
|
ecarpita93
|
68d512e62f9c1e8496242c297e03eb8efe4f94de
| 1,478
|
cpp
|
C++
|
src/environment/model/ModelContainer.cpp
|
tobiaskohlbau/IPPP
|
91432f00b49ea5a83648e3294ad5b4b661dcd284
|
[
"Apache-2.0"
] | null | null | null |
src/environment/model/ModelContainer.cpp
|
tobiaskohlbau/IPPP
|
91432f00b49ea5a83648e3294ad5b4b661dcd284
|
[
"Apache-2.0"
] | null | null | null |
src/environment/model/ModelContainer.cpp
|
tobiaskohlbau/IPPP
|
91432f00b49ea5a83648e3294ad5b4b661dcd284
|
[
"Apache-2.0"
] | null | null | null |
//-------------------------------------------------------------------------//
//
// Copyright 2017 Sascha Kaden
//
// 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 <ippp/util/Logging.h>
#include <ippp/environment/model/ModelContainer.h>
namespace ippp {
/*!
* \brief Standard destructor of the ModelContainer
* \author Sascha Kaden
* \date 2017-02-19
*/
ModelContainer::~ModelContainer() = default;
/*!
* \brief Standard constructor of ModelContainer
* \author Sascha Kaden
* \date 2017-02-19
*/
ModelContainer::ModelContainer(const std::string &name, const AABB &boundingBox) : Identifier(name) {
m_mesh.aabb = boundingBox;
}
/*!
* \brief Return AABB of the model.
* \param[out] AABB
* \author Sascha Kaden
* \date 2017-02-19
*/
AABB ModelContainer::getAABB() const {
return m_mesh.aabb;
}
} /* namespace ippp */
| 28.980392
| 101
| 0.621786
|
tobiaskohlbau
|
68d6a5ca027ce4152a2eb01862726e28dd603b9c
| 19,968
|
hpp
|
C++
|
atto/atto/math/geometry/algebra.hpp
|
ubikoo/libfish
|
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
|
[
"MIT"
] | null | null | null |
atto/atto/math/geometry/algebra.hpp
|
ubikoo/libfish
|
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
|
[
"MIT"
] | null | null | null |
atto/atto/math/geometry/algebra.hpp
|
ubikoo/libfish
|
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
|
[
"MIT"
] | null | null | null |
/*
* algebra.hpp
*
* Copyright (c) 2020 Carlos Braga
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* See accompanying LICENSE.md or https://opensource.org/licenses/MIT.
*/
#ifndef ATTO_MATH_GEOMETRY_ALGEBRA_H_
#define ATTO_MATH_GEOMETRY_ALGEBRA_H_
#include "atto/math/geometry/vec2.hpp"
#include "atto/math/geometry/vec3.hpp"
#include "atto/math/geometry/vec4.hpp"
#include "atto/math/geometry/mat2.hpp"
#include "atto/math/geometry/mat3.hpp"
#include "atto/math/geometry/mat4.hpp"
namespace atto {
namespace math {
/** ---------------------------------------------------------------------------
* dot
* @brief Return the 2-dimensional dot product.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml
*/
template<typename Type>
core_inline
Type dot(const vec2<Type> &a, const vec2<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a(0) * b(0) +
a(1) * b(1));
}
template<typename Type>
core_inline
vec2<Type> dot(const mat2<Type> &a, const vec2<Type> &v)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return vec2<Type>(
a(0,0) * v(0) + a(0,1) * v(1),
a(1,0) * v(0) + a(1,1) * v(1));
}
template<typename Type>
core_inline
mat2<Type> dot(const mat2<Type> &a, const mat2<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat2<Type>(
a(0,0) * b(0,0) + a(0,1) * b(1,0),
a(0,0) * b(0,1) + a(0,1) * b(1,1),
a(1,0) * b(0,0) + a(1,1) * b(1,0),
a(1,0) * b(0,1) + a(1,1) * b(1,1));
}
/**
* dot
* @brief Return the 3-dimensional dot product.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml
*/
template<typename Type>
core_inline
Type dot(const vec3<Type> &a, const vec3<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a(0) * b(0) +
a(1) * b(1) +
a(2) * b(2));
}
template<typename Type>
core_inline
vec3<Type> dot(const mat3<Type> &a, const vec3<Type> &v)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return vec3<Type>(
a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2),
a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2),
a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2));
}
template<typename Type>
core_inline
mat3<Type> dot(const mat3<Type> &a, const mat3<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat3<Type>(
a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0),
a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1),
a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2),
a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0),
a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1),
a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2),
a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0),
a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1),
a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2));
}
/**
* dot
* @brief Return the 4-dimensional dot product.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml
*/
template<typename Type>
core_inline
Type dot(const vec4<Type> &a, const vec4<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a(0) * b(0) +
a(1) * b(1) +
a(2) * b(2) +
a(3) * b(3));
}
template<typename Type>
core_inline
vec4<Type> dot(const mat4<Type> &a, const vec4<Type> &v)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return vec4<Type>(
a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2) + a(0,3) * v(3),
a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2) + a(1,3) * v(3),
a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2) + a(2,3) * v(3),
a(3,0) * v(0) + a(3,1) * v(1) + a(3,2) * v(2) + a(3,3) * v(3));
}
template<typename Type>
core_inline
mat4<Type> dot(const mat4<Type> &a, const mat4<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat4<Type>(
a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0) + a(0,3) * b(3,0),
a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1) + a(0,3) * b(3,1),
a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2) + a(0,3) * b(3,2),
a(0,0) * b(0,3) + a(0,1) * b(1,3) + a(0,2) * b(2,3) + a(0,3) * b(3,3),
a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0) + a(1,3) * b(3,0),
a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1) + a(1,3) * b(3,1),
a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2) + a(1,3) * b(3,2),
a(1,0) * b(0,3) + a(1,1) * b(1,3) + a(1,2) * b(2,3) + a(1,3) * b(3,3),
a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0) + a(2,3) * b(3,0),
a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1) + a(2,3) * b(3,1),
a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2) + a(2,3) * b(3,2),
a(2,0) * b(0,3) + a(2,1) * b(1,3) + a(2,2) * b(2,3) + a(2,3) * b(3,3),
a(3,0) * b(0,0) + a(3,1) * b(1,0) + a(3,2) * b(2,0) + a(3,3) * b(3,0),
a(3,0) * b(0,1) + a(3,1) * b(1,1) + a(3,2) * b(2,1) + a(3,3) * b(3,1),
a(3,0) * b(0,2) + a(3,1) * b(1,2) + a(3,2) * b(2,2) + a(3,3) * b(3,2),
a(3,0) * b(0,3) + a(3,1) * b(1,3) + a(3,2) * b(2,3) + a(3,3) * b(3,3));
}
/** ---------------------------------------------------------------------------
* norm
* @brief Return the norm product of two vectors.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/length.xhtml
*/
template<typename Type>
core_inline
Type norm(const vec2<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return std::sqrt(dot(a,a));
}
template<typename Type>
core_inline
Type norm(const vec3<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return std::sqrt(dot(a,a));
}
template<typename Type>
core_inline
Type norm(const vec4<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return std::sqrt(dot(a,a));
}
/** ---------------------------------------------------------------------------
* normalize
* @brief Return the normalize product of two vectors.
* @see
* https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/normalize.xhtml
*/
template<typename Type>
core_inline
vec2<Type> normalize(const vec2<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a / norm(a));
}
template<typename Type>
core_inline
vec3<Type> normalize(const vec3<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a / norm(a));
}
template<typename Type>
core_inline
vec4<Type> normalize(const vec4<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return (a / norm(a));
}
/** ---------------------------------------------------------------------------
* distance
* @brief Return the distance product of two vectors.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/distance.xhtml
*/
template<typename Type>
core_inline
Type distance(const vec2<Type> &a, const vec2<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return norm(a-b);
}
template<typename Type>
core_inline
Type distance(const vec3<Type> &a, const vec3<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return norm(a-b);
}
template<typename Type>
core_inline
Type distance(const vec4<Type> &a, const vec4<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return norm(a-b);
}
/** ---------------------------------------------------------------------------
* cross
* @brief Return the cross product of two vectors.
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/cross.xhtml
*/
template<typename Type>
core_inline
vec3<Type> cross(const vec3<Type> &a, const vec3<Type> &b)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return vec3<Type>(
a(1)*b(2) - a(2)*b(1),
a(2)*b(0) - a(0)*b(2),
a(0)*b(1) - a(1)*b(0));
}
/** ---------------------------------------------------------------------------
* transpose
* @brief Return the transpose of the matrix.
*/
template<typename Type>
core_inline
mat2<Type> transpose(const mat2<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat2<Type>(
a(0,0), a(1,0),
a(0,1), a(1,1));
}
template<typename Type>
core_inline
mat3<Type> transpose(const mat3<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat3<Type>(
a(0,0), a(1,0), a(2,0),
a(0,1), a(1,1), a(2,1),
a(0,2), a(1,2), a(2,2));
}
template<typename Type>
core_inline
mat4<Type> transpose(const mat4<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
return mat4<Type>(
a(0,0), a(1,0), a(2,0), a(3,0),
a(0,1), a(1,1), a(2,1), a(3,1),
a(0,2), a(1,2), a(2,2), a(3,2),
a(0,3), a(1,3), a(2,3), a(3,3));
}
/** ---------------------------------------------------------------------------
* determinant
* @brief Return the determinant of the matrix.
*/
template<typename Type>
core_inline
Type determinant(const mat2<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* M = {m0, m1,
* m2, m3}
*
* det(M) = +m0 * m3
* -m1 * m2
*/
Type det = a(0,0)*a(1,1) - a(0,1)*a(1,0);
return det;
}
template<typename Type>
core_inline
Type determinant(const mat3<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* M = {m0, m1, m2,
* m3, m4, m5,
* m6, m7, m8}
*
* det(M) = +m0 * m4 * m8
* -m0 * m5 * m7
* -m1 * m3 * m8
* +m1 * m5 * m6
* +m2 * m3 * m7
* -m2 * m4 * m6
*/
Type minor0 = a(1,1)*a(2,2) - a(1,2)*a(2,1);
Type minor1 = a(1,2)*a(2,0) - a(1,0)*a(2,2);
Type minor2 = a(1,0)*a(2,1) - a(1,1)*a(2,0);
Type det = a(0,0)*minor0 + a(0,1)*minor1 + a(0,2)*minor2;
return det;
}
template<typename Type>
core_inline
Type determinant(const mat4<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* M = {m0, m1, m2, m3,
* m4, m5, m6, m7,
* m8, m9, m10, m11,
* m12, m13, m14, m15}
*
* det(M) = -m0 * m10 * m13 * m7
* +m0 * m10 * m15 * m5
* +m0 * m11 * m13 * m6
* -m0 * m11 * m14 * m5
* +m0 * m14 * m7 * m9
* -m0 * m15 * m6 * m9
* +m1 * m10 * m12 * m7
* -m1 * m10 * m15 * m4
* -m1 * m11 * m12 * m6
* +m1 * m11 * m14 * m4
* -m1 * m14 * m7 * m8
* +m1 * m15 * m6 * m8
* -m10 * m12 * m3 * m5
* +m10 * m13 * m3 * m4
* +m11 * m12 * m2 * m5
* -m11 * m13 * m2 * m4
* -m12 * m2 * m7 * m9
* +m12 * m3 * m6 * m9
* +m13 * m2 * m7 * m8
* -m13 * m3 * m6 * m8
* -m14 * m3 * m4 * m9
* +m14 * m3 * m5 * m8
* +m15 * m2 * m4 * m9
* -m15 * m2 * m5 * m8
*/
Type minor0 = a(2,2)*a(3,3) - a(2,3)*a(3,2);
Type minor1 = a(2,3)*a(3,1) - a(2,1)*a(3,3);
Type minor2 = a(2,1)*a(3,2) - a(2,2)*a(3,1);
Type minor3 = a(2,3)*a(3,2) - a(2,2)*a(3,3);
Type minor4 = a(2,0)*a(3,3) - a(2,3)*a(3,0);
Type minor5 = a(2,2)*a(3,0) - a(2,0)*a(3,2);
Type minor6 = a(2,1)*a(3,3) - a(2,3)*a(3,1);
Type minor7 = a(2,3)*a(3,0) - a(2,0)*a(3,3);
Type minor8 = a(2,0)*a(3,1) - a(2,1)*a(3,0);
Type minor9 = a(2,2)*a(3,1) - a(2,1)*a(3,2);
Type minor10 = a(2,0)*a(3,2) - a(2,2)*a(3,0);
Type minor11 = a(2,1)*a(3,0) - a(2,0)*a(3,1);
Type det =
a(0,0) * (a(1,1) * minor0 + a(1,2) * minor1 + a(1,3) * minor2) +
a(0,1) * (a(1,0) * minor3 + a(1,2) * minor4 + a(1,3) * minor5) +
a(0,2) * (a(1,0) * minor6 + a(1,1) * minor7 + a(1,3) * minor8) +
a(0,3) * (a(1,0) * minor9 + a(1,1) * minor10 + a(1,2) * minor11);
return det;
}
/** ---------------------------------------------------------------------------
* inverse
* @brief Return the inverse of the matrix.
*/
template<typename Type>
core_inline
mat2<Type> inverse(const mat2<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* Compute the inverse matrix from the corresponding adjugate:
* inv(M) = adj(M) / det(M)
* adj(M) = { m3, -m1,
* -m2, m0}
*/
mat2<Type> adj(
a(1,1), -a(0,1),
-a(1,0), a(0,0));
/* Compute determinant from Laplace's expansion */
double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0);
det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0;
return (adj *= det);
}
template<typename Type>
core_inline
mat3<Type> inverse(const mat3<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* Compute the inverse matrix from the corresponding adjugate:
* inv(M) = adj(M) / det(M)
* adj(M) = {+m4*m8 - m5*m7,
* +m2*m7 - m1*m8,
* +m1*m5 - m2*m4
* +m5*m6 - m3*m8,
* +m0*m8 - m2*m6,
* +m2*m3 - m0*m5,
* +m3*m7 - m4*m6,
* +m1*m6 - m0*m7,
* +m0*m4 - m1*m3}
*/
mat3<Type> adj(
a(1,1) * a(2,2) - a(1,2) * a(2,1),
a(0,2) * a(2,1) - a(0,1) * a(2,2),
a(0,1) * a(1,2) - a(0,2) * a(1,1),
a(1,2) * a(2,0) - a(1,0) * a(2,2),
a(0,0) * a(2,2) - a(0,2) * a(2,0),
a(0,2) * a(1,0) - a(0,0) * a(1,2),
a(1,0) * a(2,1) - a(1,1) * a(2,0),
a(0,1) * a(2,0) - a(0,0) * a(2,1),
a(0,0) * a(1,1) - a(0,1) * a(1,0));
/* Compute determinant from Laplace's expansion */
double det = a(0,0) * adj(0,0) +
a(0,1) * adj(1,0) +
a(0,2) * adj(2,0);
det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0;
return (adj *= det);
}
template<typename Type>
core_inline
mat4<Type> inverse(const mat4<Type> &a)
{
static_assert(std::is_floating_point<Type>::value, "non floating point");
/*
* Compute the inverse matrix from the corresponding adjugate:
* inv(M) = adj(M) / det(M)
* adj(M) =
* {
* -m11*m14*m5 +m10*m15*m5 +m11*m13*m6
* -m10*m13*m7 -m15*m6 *m9 +m14*m7 *m9,
*
* +m1 *m11*m14 -m3 *m9 *m14 -m1 *m10*m15
* -m11*m13*m2 +m10*m13*m3 +m15*m2 *m9,
*
* -m15*m2 *m5 +m14*m3 *m5 +m1 *m15*m6
* -m13*m3 *m6 -m1 *m14*m7 +m13*m2 *m7,
*
* +m11*m2 *m5 -m10*m3 *m5 -m1 *m11*m6
* +m1 *m10*m7 +m3 *m6 *m9 -m2 *m7 *m9,
*
* +m11*m14*m4 -m10*m15*m4 -m11*m12*m6
* +m10*m12*m7 +m15*m6 *m8 -m14*m7 *m8,
*
* -m0 *m11*m14 +m3 *m8 *m14 +m0 *m10*m15
* +m11*m12*m2 -m10*m12*m3 -m15*m2 *m8,
*
* +m15*m2 *m4 -m14*m3 *m4 -m0 *m15*m6
* +m12*m3 *m6 +m0 *m14*m7 -m12*m2 *m7,
*
* -m11*m2 *m4 +m10*m3 *m4 +m0 *m11*m6
* -m0 *m10*m7 -m3 *m6 *m8 +m2 *m7 *m8,
*
* -m11*m13*m4 +m15*m9 *m4 +m11*m12*m5
* -m15*m5 *m8 +m13*m7 *m8 -m12*m7 *m9,
*
* -m1 *m11*m12 +m3 *m9 *m12 +m0 *m11*m13
* +m1 *m15*m8 -m13*m3 *m8 -m0 *m15*m9,
*
* -m1 *m15*m4 +m13*m3 *m4 +m0 *m15*m5
* -m12*m3 *m5 +m1 *m12*m7 -m0 *m13*m7,
*
* +m1 *m11*m4 -m3 *m9 *m4 -m0 *m11*m5
* +m3 *m5 *m8 -m1 *m7 *m8 +m0 *m7 *m9,
*
* +m10*m13*m4 -m14*m9 *m4 -m10*m12*m5
* +m14*m5 *m8 -m13*m6 *m8 +m12*m6 *m9,
*
* +m1 *m10*m12 -m2 *m9 *m12 -m0 *m10*m13
* -m1 *m14*m8 +m13*m2 *m8 +m0 *m14*m9,
*
* +m1 *m14*m4 -m13*m2 *m4 -m0 *m14*m5
* +m12*m2 *m5 -m1 *m12*m6 +m0 *m13*m6,
*
* -m1 *m10*m4 +m2 *m9 *m4 +m0 *m10*m5
* -m2 *m5 *m8 +m1 *m6 *m8 -m0 *m6 *m9
* }
*/
mat4<Type> adj(
a(1,1) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) +
a(1,2) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) +
a(1,3) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)),
a(0,1) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) +
a(0,2) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) +
a(0,3) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)),
a(1,1) * (a(0,3) * a(3,2) - a(0,2) * a(3,3)) +
a(1,2) * (a(0,1) * a(3,3) - a(0,3) * a(3,1)) +
a(1,3) * (a(0,2) * a(3,1) - a(0,1) * a(3,2)),
a(1,1) * (a(0,2) * a(2,3) - a(2,2) * a(0,3)) +
a(1,2) * (a(0,3) * a(2,1) - a(0,1) * a(2,3)) +
a(1,3) * (a(0,1) * a(2,2) - a(0,2) * a(2,1)),
a(1,0) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) +
a(1,2) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) +
a(1,3) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)),
a(0,0) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) +
a(0,2) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) +
a(0,3) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)),
a(0,0) * (a(1,3) * a(3,2) - a(1,2) * a(3,3)) +
a(0,2) * (a(1,0) * a(3,3) - a(1,3) * a(3,0)) +
a(0,3) * (a(1,2) * a(3,0) - a(1,0) * a(3,2)),
a(0,0) * (a(1,2) * a(2,3) - a(1,3) * a(2,2)) +
a(0,2) * (a(1,3) * a(2,0) - a(1,0) * a(2,3)) +
a(0,3) * (a(1,0) * a(2,2) - a(1,2) * a(2,0)),
a(1,0) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) +
a(1,1) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) +
a(1,3) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)),
a(0,0) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) +
a(0,1) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) +
a(0,3) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)),
a(0,0) * (a(1,1) * a(3,3) - a(1,3) * a(3,1)) +
a(0,1) * (a(1,3) * a(3,0) - a(1,0) * a(3,3)) +
a(0,3) * (a(1,0) * a(3,1) - a(1,1) * a(3,0)),
a(0,0) * (a(1,3) * a(2,1) - a(1,1) * a(2,3)) +
a(0,1) * (a(1,0) * a(2,3) - a(1,3) * a(2,0)) +
a(0,3) * (a(1,1) * a(2,0) - a(2,1) * a(1,0)),
a(1,0) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)) +
a(1,1) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)) +
a(1,2) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)),
a(0,0) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)) +
a(0,1) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)) +
a(0,2) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)),
a(0,0) * (a(1,2) * a(3,1) - a(1,1) * a(3,2)) +
a(0,1) * (a(1,0) * a(3,2) - a(1,2) * a(3,0)) +
a(0,2) * (a(1,1) * a(3,0) - a(1,0) * a(3,1)),
a(0,0) * (a(1,1) * a(2,2) - a(1,2) * a(2,1)) +
a(0,1) * (a(1,2) * a(2,0) - a(1,0) * a(2,2)) +
a(0,2) * (a(1,0) * a(2,1) - a(1,1) * a(2,0)));
/* Compute inverse matrix using Laplace's expansion */
double det = a(0,0) * adj(0,0) +
a(0,1) * adj(1,0) +
a(0,2) * adj(2,0) +
a(0,3) * adj(3,0);
det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0;
return (adj *= det);
}
} /* namespace math */
} /* namespace atto */
/** ---------------------------------------------------------------------------
* @brief Enable simd vectorized instructions.
*/
#ifdef ATTO_MATH_SIMD
#include "atto/math/geometry/algebra-simd.hpp"
#endif
#endif /* ATTO_MATH_GEOMETRY_ALGEBRA */
| 31.796178
| 80
| 0.455629
|
ubikoo
|
68d7c6a7182e36cfd4e148b2297d38ea46c3c128
| 3,313
|
cpp
|
C++
|
src/SceneMonitor.cpp
|
rcstilborn/SecMon
|
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
|
[
"MIT"
] | 2
|
2021-12-17T17:35:07.000Z
|
2022-01-11T12:38:00.000Z
|
src/SceneMonitor.cpp
|
rcstilborn/SecMon
|
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
|
[
"MIT"
] | null | null | null |
src/SceneMonitor.cpp
|
rcstilborn/SecMon
|
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
|
[
"MIT"
] | 2
|
2018-01-15T06:10:07.000Z
|
2021-07-08T19:40:49.000Z
|
/*
* SceneMonitor.cpp
*
* Created on: Jul 27, 2015
* Author: richard
*
* Copyright 2017 Richard Stilborn
* Licensed under the MIT License
*/
#include "SceneMonitor.h"
#include <boost/asio/io_service.hpp>
#include <boost/bind/bind.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/ptr_container/detail/associative_ptr_container.hpp>
#include <boost/ptr_container/detail/reversible_ptr_container.hpp>
#include <boost/ptr_container/ptr_map_adapter.hpp>
#include <boost/thread/lock_guard.hpp>
#include <iostream>
#include <list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include "GUI/GUI_Interface.h"
SceneMonitor::SceneMonitor(boost::asio::io_service& io_service, GUI_Interface& gui)
: io_service_(io_service),
gui_(gui),
scenes_(),
scenes_mtx_() {
// gui_.createRoom("cameras", boost::bind<const std::string>(&SceneMonitor::get_scene_names, this));
}
SceneMonitor::~SceneMonitor() {
boost::lock_guard<boost::mutex> guard(scenes_mtx_);
for (boost::ptr_map<std::string, Scene>::iterator it = scenes_.begin(); it != scenes_.end(); ++it)
scenes_.erase(it);
}
void SceneMonitor::start_monitoring(const std::string& name, const std::string& url, const double realtime_factor) {
// Check if we already have this name
boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name);
if (it != this->scenes_.end())
throw std::invalid_argument("A scene with this name already exists: " + name);
// Create the scene
{
Scene* scene = new Scene(name, url, io_service_, gui_, realtime_factor);
boost::lock_guard<boost::mutex> guard(scenes_mtx_);
// TODO(richard): Fix this silliness!
std::string foo(name);
this->scenes_.insert(foo, scene);
}
}
void SceneMonitor::stop_monitoring(const std::string& name) {
std::cout << "SceneMonitor.stopMonitoring() - enter" << std::endl;
boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name);
if (it != this->scenes_.end()) {
boost::lock_guard<boost::mutex> guard(scenes_mtx_);
it->second->shutdown();
}
}
void SceneMonitor::stop_all_monitoring() {
std::cout << "SceneMonitor.stopAllMonitoring() - enter" << std::endl;
for (auto scene : this->scenes_)
scene.second->shutdown();
std::this_thread::sleep_for(std::chrono::seconds(2));
}
const std::string SceneMonitor::get_scene_names() const {
std::stringstream list;
const char* separator = "";
list << '[';
for (auto name : this->scenes_) {
list << separator << name.first;
separator = ",";
}
list << ']';
return list.str();
}
// std::vector<scene_details> SceneMonitor::getSceneDetails(){
// std::vector<scene_details> details;
// for(auto entry: this->scenes){
// scene_details detail;
// detail.name = entry.second->getName();
// detail.height = entry.second->getCamera().getHeight();
// detail.width = entry.second->getCamera().getWidth();
// details.push_back(detail);
// }
// return details;
//}
void SceneMonitor::toggle_pause() {
for (auto scene : this->scenes_)
scene.second->toggle_pause();
}
void SceneMonitor::set_realtime_factor(const double realtime_factor) {
for (auto scene : this->scenes_)
scene.second->set_realtime_factor(realtime_factor);
}
| 29.061404
| 116
| 0.686991
|
rcstilborn
|
68d9deed1f22ec03ee368305b88181ee84a5347d
| 1,854
|
cpp
|
C++
|
m4cpp/src/uart.cpp
|
matheusmb/smep-gateway
|
c32ff83cf48488404a5c094137b33be09d84581c
|
[
"MIT"
] | null | null | null |
m4cpp/src/uart.cpp
|
matheusmb/smep-gateway
|
c32ff83cf48488404a5c094137b33be09d84581c
|
[
"MIT"
] | null | null | null |
m4cpp/src/uart.cpp
|
matheusmb/smep-gateway
|
c32ff83cf48488404a5c094137b33be09d84581c
|
[
"MIT"
] | null | null | null |
#include "uart.h"
#include "board.h"
#include "WString.h"
#define UARTx_IRQn USART0_IRQn
void UART_Init( const uint32_t baud ) {
Board_UART_Init( LPC_UART );
Chip_UART_Init( LPC_UART );
Chip_UART_SetBaud( LPC_UART, baud );
Chip_UART_TXEnable( LPC_UART );
}
void UART_IRQ_Init() {
UART_IntEnable();
Chip_UART_SetupFIFOS( LPC_UART, UART_FCR_FIFO_EN | UART_FCR_TRG_LEV2 | UART_FCR_RX_RS );
NVIC_SetPriority(UARTx_IRQn, 1);
NVIC_EnableIRQ(UARTx_IRQn);
}
void UART_IntEnable() {
Chip_UART_IntEnable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) );
}
void UART_IntDisable() {
Chip_UART_IntDisable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) );
}
void UART_Send(const void * data, int numBytes ) {
Chip_UART_SendBlocking( LPC_UART, data, numBytes );
}
void UART_Send( String cmd ) {
UART_Send( cmd.c_str(), cmd.length() );
}
uint8_t UART_Read() {
return Chip_UART_ReadByte( LPC_UART );
}
bool UART_Available() {
return Chip_UART_ReadLineStatus( LPC_UART ) & UART_LSR_RDR;
}
#define MAX_BUFFER_SIZE 1500
String receiveBuffer;
void UARTx_IRQHandler(void)
{
String out;
uint32_t IIR = LPC_UART->IIR & UART_IIR_BITMASK;
uint32_t INTID = IIR & UART_IIR_INTID_MASK;
uint32_t LSR = 0;
bool recv = false;
switch(INTID) {
case UART_IIR_INTID_CTI:
case UART_IIR_INTID_RDA:
recv = true;
if( receiveBuffer.length() > MAX_BUFFER_SIZE )
receiveBuffer = receiveBuffer.substring( MAX_BUFFER_SIZE / 2); // Discard half of the contents
while( UART_Available() ) {
receiveBuffer += (char) UART_Read();
}
break;
case UART_IIR_INTID_RLS:
LSR = Chip_UART_ReadLineStatus(LPC_UART) & UART_LSR_BITMASK; // Clear RLS interrupt
printf("RLS %d", LSR);
break;
default:
printf("Unkown %d", INTID);
}
/*if( recv ) {
printf("UART_IRQ:");
printf( receiveBuffer );
receiveBuffer = "";
}*/
}
| 20.373626
| 98
| 0.718986
|
matheusmb
|
68dadb09346cfe63541bc35f3e22509be8a45b89
| 1,970
|
cpp
|
C++
|
llarp/service/info.cpp
|
KeeJef/loki-network
|
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
|
[
"Zlib"
] | null | null | null |
llarp/service/info.cpp
|
KeeJef/loki-network
|
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
|
[
"Zlib"
] | null | null | null |
llarp/service/info.cpp
|
KeeJef/loki-network
|
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
|
[
"Zlib"
] | null | null | null |
#include <buffer.hpp>
#include <service/Info.hpp>
#include <service/address.hpp>
#include <cassert>
#include <sodium/crypto_generichash.h>
namespace llarp
{
namespace service
{
bool
ServiceInfo::DecodeKey(llarp_buffer_t key, llarp_buffer_t* val)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("e", enckey, read, key, val))
return false;
if(!BEncodeMaybeReadDictEntry("s", signkey, read, key, val))
return false;
if(!BEncodeMaybeReadDictInt("v", version, read, key, val))
return false;
if(!BEncodeMaybeReadDictEntry("x", vanity, read, key, val))
return false;
return read;
}
bool
ServiceInfo::BEncode(llarp_buffer_t* buf) const
{
if(!bencode_start_dict(buf))
return false;
if(!BEncodeWriteDictEntry("e", enckey, buf))
return false;
if(!BEncodeWriteDictEntry("s", signkey, buf))
return false;
if(!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf))
return false;
if(!vanity.IsZero())
{
if(!BEncodeWriteDictEntry("x", vanity, buf))
return false;
}
return bencode_end(buf);
}
std::string
ServiceInfo::Name() const
{
if(m_CachedAddr.IsZero())
{
Address addr;
CalculateAddress(addr.data());
return addr.ToString();
}
return m_CachedAddr.ToString();
}
bool ServiceInfo::CalculateAddress(std::array< byte_t, 32 >& data) const
{
byte_t tmp[256] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
if(!BEncode(&buf))
return false;
return crypto_generichash_blake2b(data.data(), data.size(), buf.base,
buf.cur - buf.base, nullptr, 0)
!= -1;
}
bool
ServiceInfo::UpdateAddr()
{
return CalculateAddress(m_CachedAddr.data());
}
} // namespace service
} // namespace llarp
| 25.25641
| 76
| 0.591371
|
KeeJef
|
68dd0fd03a89896af9cefc24fd2642e92fc94ade
| 22,627
|
cpp
|
C++
|
framework/areg/component/private/ComponentLoader.cpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 70
|
2021-07-20T11:26:16.000Z
|
2022-03-27T11:17:43.000Z
|
framework/areg/component/private/ComponentLoader.cpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 32
|
2021-07-31T05:20:44.000Z
|
2022-03-20T10:11:52.000Z
|
framework/areg/component/private/ComponentLoader.cpp
|
Ali-Nasrolahi/areg-sdk
|
4fbc2f2644220196004a31672a697a864755f0b6
|
[
"Apache-2.0"
] | 40
|
2021-11-02T09:45:38.000Z
|
2022-03-27T11:17:46.000Z
|
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/component/private/ComponentLoader.cpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform, Component Loader singleton object.
*
************************************************************************/
#include "areg/component/ComponentLoader.hpp"
#include "areg/component/Component.hpp"
#include "areg/component/ComponentThread.hpp"
#include "areg/component/private/ServiceManager.hpp"
#include "areg/base/NECommon.hpp"
//////////////////////////////////////////////////////////////////////////
// ModelDataCreator class implementation
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// ModelDataCreator class, constructor / destructor
//////////////////////////////////////////////////////////////////////////
ModelDataCreator::ModelDataCreator( FuncInitLoaderItem funtCreateModelData, const char * modelName )
{
ASSERT( funtCreateModelData != nullptr );
NERegistry::Model newModel = funtCreateModelData(modelName);
VERIFY( ComponentLoader::getInstance().addModel( newModel ) );
}
ModelDataCreator::ModelDataCreator( const NERegistry::Model & newModel )
{
VERIFY( ComponentLoader::getInstance().addModel( newModel ) );
}
//////////////////////////////////////////////////////////////////////////
// ComponentLoader class implementation
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// ComponentLoader class, static functions
//////////////////////////////////////////////////////////////////////////
ComponentLoader & ComponentLoader::getInstance( void )
{
static ComponentLoader _componentLoader;
return _componentLoader;
}
bool ComponentLoader::loadComponentModel( const char * modelName /*= nullptr*/ )
{
bool result = ComponentLoader::getInstance().loadModel( modelName );
if ( result == false)
ComponentLoader::getInstance().unloadModel( modelName );
return result;
}
void ComponentLoader::unloadComponentModel( const char * modelName /*= nullptr*/ )
{
ComponentLoader::getInstance( ).unloadModel( modelName );
}
const NERegistry::ComponentList& ComponentLoader::getComponentList( const char* threadName )
{
const NERegistry::ComponentList* result = nullptr;
ComponentLoader& loader = getInstance();
Lock lock(loader.mLock);
for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i )
{
const NERegistry::Model & model = loader.mModelList.getAt(i);
if ( model.isModelLoaded() )
{
const NERegistry::ComponentThreadList & threadList = model.getThreadList();
for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j )
{
const NERegistry::ComponentThreadEntry & thrEntry = threadList.getAt(j);
if (thrEntry.mThreadName == threadName)
result = &thrEntry.mComponents;
}
}
}
return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_LIST);
}
const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName, const char* threadName )
{
const NERegistry::ComponentEntry* result = nullptr;
const NERegistry::ComponentList& comList = getComponentList(threadName);
if (comList.isValid())
{
for (int i = 0; result == nullptr && i < comList.getSize(); ++ i)
{
const NERegistry::ComponentEntry& entry = comList[i];
result = entry.mRoleName == roleName ? &entry : nullptr;
}
}
return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY);
}
const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName )
{
const NERegistry::ComponentEntry* result = nullptr;
ComponentLoader & loader = ComponentLoader::getInstance();
Lock lock(loader.mLock);
for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i )
{
const NERegistry::ComponentThreadList & threadList = loader.mModelList.getAt(i).getThreadList();
for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j )
{
const NERegistry::ComponentThreadEntry & threadEntry = threadList.getAt(j);
for ( int k = 0; result == nullptr && k < threadEntry.mComponents.getSize(); ++ k )
result = threadEntry.mComponents.getAt(k).mRoleName == roleName ? &threadEntry.mComponents.getAt(k) : nullptr;
}
}
return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY);
}
bool ComponentLoader::isModelLoaded( const char * modelName )
{
bool result = false;
if ( NEString::isEmpty<char>(modelName) == false )
{
ComponentLoader & loader = ComponentLoader::getInstance();
Lock lock(loader.mLock);
for ( int i = 0; i < loader.mModelList.getSize(); ++ i )
{
const NERegistry::Model & model = loader.mModelList.getAt(i);
if ( model.getModelName() == modelName )
{
result = model.isModelLoaded();
break;
}
}
}
return result;
}
bool ComponentLoader::existModel( const char * modelName )
{
bool result = false;
if ( NEString::isEmpty<char>( modelName ) == false )
{
ComponentLoader & loader = ComponentLoader::getInstance( );
Lock lock( loader.mLock );
for ( int i = 0; i < loader.mModelList.getSize( ); ++ i )
{
const NERegistry::Model & model = loader.mModelList.getAt( i );
if ( model.getModelName( ) == modelName )
{
result = true;
break;
}
}
}
return result;
}
bool ComponentLoader::setComponentData( const char * roleName, NEMemory::uAlign compData )
{
bool result = false;
ComponentLoader & loader = ComponentLoader::getInstance( );
Lock lock( loader.mLock );
for ( int i = 0; i < loader.mModelList.getSize( ); ++ i )
{
NERegistry::Model & model = loader.mModelList.getAt( i );
if ( model.setComponentData( roleName, compData ) )
{
result = true;
break;
}
}
return result;
}
bool ComponentLoader::addModelUnique(const NERegistry::Model & newModel)
{
ComponentLoader & loader = ComponentLoader::getInstance();
Lock lock( loader.mLock );
return loader.addModel(newModel);
}
void ComponentLoader::removeComponentModel(const char * modelName /*= nullptr */)
{
OUTPUT_WARN("Removing components and model [ %s ]", modelName != nullptr ? modelName : "ALL MODELS");
ComponentLoader::unloadComponentModel(modelName);
ComponentLoader & loader = ComponentLoader::getInstance();
Lock lock( loader.mLock );
if ( NEString::isEmpty<char>(modelName) == false )
{
for ( int i = 0; i < loader.mModelList.getSize(); ++ i )
{
NERegistry::Model & model = loader.mModelList[i];
if ( model.getModelName() == modelName )
{
loader.mModelList.removeAt(i);
break;
}
}
}
else
{
loader.mModelList.removeAll();
}
}
//////////////////////////////////////////////////////////////////////////
// ComponentLoader class, constructor / destructor
//////////////////////////////////////////////////////////////////////////
ComponentLoader::ComponentLoader( void )
: mModelList ( )
, mDefaultModel ( NEString::EmptyStringA.data( ) )
, mLock ( )
{
}
ComponentLoader::~ComponentLoader( void )
{
mModelList.removeAll();
mDefaultModel = NEString::EmptyStringA.data( );
}
//////////////////////////////////////////////////////////////////////////
// ComponentLoader class, methods
//////////////////////////////////////////////////////////////////////////
bool ComponentLoader::addModel( const NERegistry::Model & newModel )
{
Lock lock(mLock);
OUTPUT_DBG("Registering model with name [ %s ]", newModel.getModelName().getString());
bool hasError = newModel.getModelName().isEmpty() || newModel.isModelLoaded() ? true : false;
// the new model name cannot be empty and it should be unique, and it cannot be marked as loaded.
ASSERT(hasError == false);
// search if model with the same name exists
for (int i = 0; hasError == false && i < mModelList.getSize(); ++ i )
{
const NERegistry::Model & regModel = mModelList.getAt(i);
if ( newModel.getModelName() != regModel.getModelName() )
{
const NERegistry::ComponentThreadList & regThreadList = regModel.getThreadList();
for ( int j = 0; hasError == false && j < regThreadList.getSize(); ++ j )
{
const NERegistry::ComponentThreadEntry & regThreadEntry = regThreadList.getAt(j);
if ( newModel.findThread(regThreadEntry) < 0 )
{
const NERegistry::ComponentList & regComponentList = regThreadEntry.mComponents;
for ( int k = 0; hasError == false && k < regComponentList.getSize(); ++ k )
{
const NERegistry::ComponentEntry & regComponentEntry = regComponentList.getAt(k);
if ( newModel.hasRegisteredComponent(regComponentEntry) )
{
OUTPUT_ERR("The component with role name [ %s ] is already registered in thread [ %s ] of model [ %s ], cannot add new model!"
, regComponentEntry.mRoleName.getString()
, regThreadEntry.mThreadName.getString()
, regModel.getModelName().getString() );
hasError = true;
ASSERT(false);
}
else
{
; // is OK, continue checking
}
} // end of for ( int k = 0; hasError == false && k < newComponentList.GetSize(); k ++ )
}
else
{
OUTPUT_ERR("The thread with name [ %s ] is already registered in model [ %s ], cannot add new model!"
, regThreadEntry.mThreadName.getString()
, regModel.getModelName().getString());
hasError = true;
ASSERT(false);
}
} // end of for ( int j = 0; hasError == false && j < newThreadList.GetSize(); j ++ )
}
else
{
OUTPUT_ERR("The model with name [ %s ] is already registered, cannot add new model!", regModel.getModelName().getString());
hasError = true;
ASSERT(false);
}
}
if ( hasError == false )
{
OUTPUT_DBG("The model [ %s ] is defined correct, adding in the list.", newModel.getModelName().getString());
mModelList.add(newModel);
if ( mDefaultModel.isEmpty() )
{
mDefaultModel = newModel.getModelName().getString();
}
}
return (hasError == false);
}
bool ComponentLoader::loadModel( const char * modelName /*= nullptr*/ )
{
Lock lock(mLock);
bool result = false;
OUTPUT_DBG("Requested to start load model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName);
if ( NEString::isEmpty<char>(modelName) )
{
result = mModelList.getSize() > 0;
for ( int i = 0; result && i < mModelList.getSize(); ++ i )
{
NERegistry::Model & model = mModelList[i];
if ( model.isModelLoaded() == false )
result = loadModel( model );
ASSERT( model.isModelLoaded() );
}
}
else
{
OUTPUT_DBG("Searching model [ %s ] in the list with size [ %d ]", modelName, mModelList.getSize() );
int index = -1;
for ( int i = 0; (index == -1) && (i < mModelList.getSize()); ++ i )
{
NERegistry::Model & model = mModelList[i];
OUTPUT_DBG("Checking the name, the entry [ %d ] has name [ %s ]", i, model.getModelName().getString());
if ( model.getModelName() == modelName )
{
OUTPUT_DBG("Found model with name [ %s ] at position [ %d ]", modelName, i);
index = i;
result = loadModel(model);
}
}
}
OUTPUT_DBG("Model [ %s ] loaded with [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName, result ? "SUCCESS" : "ERROR");
return result;
}
bool ComponentLoader::loadModel( NERegistry::Model & whichModel ) const
{
bool result = false;
if ( whichModel.isValid() && (whichModel.isModelLoaded( ) == false) )
{
const NERegistry::ComponentThreadList& thrList = whichModel.getThreadList( );
OUTPUT_DBG( "Starting to load model [ %s ]. There are [ %d ] component threads to start. Component loader is going to load objects and start Service Manager"
, whichModel.getModelName( ).getString( )
, thrList.getSize( ) );
whichModel.markModelLoaded( true );
result = true;
for ( int i = 0; result && i < thrList.getSize( ); ++ i )
{
Lock lock( mLock );
const NERegistry::ComponentThreadEntry& entry = thrList[i];
if ( entry.isValid( ) && Thread::findThreadByName( entry.mThreadName.getString( ) ) == nullptr )
{
ComponentThread* thrObject = DEBUG_NEW ComponentThread( entry.mThreadName.getString( ) );
if ( thrObject != nullptr )
{
OUTPUT_DBG( "Starting thread [ %s ] and loading components.", thrObject->getName( ).getString( ) );
if ( thrObject->createThread( NECommon::WAIT_INFINITE ) == false )
{
OUTPUT_ERR( "Failed to create and start thread [ %s ], going to delete and unload components.", thrObject->getName( ).getString( ) );
thrObject->destroyThread( NECommon::DO_NOT_WAIT );
delete thrObject;
result = false;
}
}
else
{
OUTPUT_ERR( "Failed instantiate component thread object with name [ %s ]", entry.mThreadName.getString( ) );
result = false;
}
}
else
{
result = entry.isValid( );
OUTPUT_ERR( "Either Thread [ %s ] is already created or it is invalid: is valid [ %s ], already exists [ %s ]."
, entry.mThreadName.getString( )
, entry.isValid( ) ? "TRUE" : "FALSE"
, Thread::findThreadByName( entry.mThreadName) != nullptr ? "EXISTS" : "DOES NOT EXIST" );
}
}
}
else
{
OUTPUT_WARN( "The model [ %s ] is already loaded. Ignoring loading model", whichModel.getModelName( ).getString( ) );
result = true;
}
return result;
}
void ComponentLoader::unloadModel( const char * modelName /*= nullptr*/ )
{
Lock lock(mLock);
OUTPUT_DBG("Requested to unload model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName);
if ( NEString::isEmpty<char>(modelName) )
{
for ( int i = 0; i < mModelList.getSize(); ++ i )
{
NERegistry::Model & model = mModelList[i];
lock.unlock();
unloadModel(model);
lock.lock();
ASSERT( model.isModelLoaded() == false );
}
}
else
{
int index = -1;
for ( int i = 0; index == -1 && i < mModelList.getSize(); ++ i )
{
NERegistry::Model & model = mModelList[i];
if ( model.getModelName() == modelName )
{
index = i;
lock.unlock();
unloadModel(model);
lock.lock();
}
}
}
}
void ComponentLoader::unloadModel( NERegistry::Model & whichModel ) const
{
Lock lock(mLock);
OUTPUT_WARN("Requested to unload components. Going to unload model [ %s ]!", static_cast<const char *>(whichModel.getModelName().getString()));
if (whichModel.isModelLoaded() )
{
const NERegistry::ComponentThreadList & threadList = whichModel.getThreadList();
shutdownThreads( threadList );
lock.unlock();
waitThreadsCompletion( threadList );
lock.lock();
destroyThreads( threadList );
whichModel.markModelLoaded( false );
}
else
{
OUTPUT_WARN("The model [ %s ] marked as unloaded. Ignoring request to unload model.", static_cast<const char *>(whichModel.getModelName().getString()));
}
}
void ComponentLoader::shutdownThreads( const NERegistry::ComponentThreadList & whichThreads ) const
{
OUTPUT_INFO("Starting First Level model shutdown. Shutdown Threads and Components");
for (int i = 0; i < whichThreads.getSize(); ++ i )
{
const NERegistry::ComponentThreadEntry& entry = whichThreads[i];
Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString());
if (thrObject != nullptr)
{
ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr);
OUTPUT_WARN("Shutdown thread [ %s ] and all its components", thrObject->getName().getString());
thrObject->shutdownThread();
}
else
{
OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString());
}
}
OUTPUT_INFO("Shuts down Service Manager thread!");
}
void ComponentLoader::waitThreadsCompletion( const NERegistry::ComponentThreadList & whichThreads ) const
{
OUTPUT_INFO("Starting Second Level model shutdown. Wait for Threads completion!");
for ( int i = 0; i < whichThreads.getSize(); ++ i )
{
const NERegistry::ComponentThreadEntry& entry = whichThreads[i];
Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString());
if (thrObject != nullptr)
{
ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr);
OUTPUT_WARN("Waiting thread [ %s ] completion", thrObject->getName().getString());
thrObject->completionWait(NECommon::WAIT_INFINITE);
}
else
{
OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString());
}
}
}
void ComponentLoader::destroyThreads( const NERegistry::ComponentThreadList & whichThreads ) const
{
OUTPUT_INFO("Starting Third Level model shutdown. Destroy threads and components!");
for ( int i = 0; i < whichThreads.getSize(); ++ i )
{
const NERegistry::ComponentThreadEntry& entry = whichThreads[i];
Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString());
if (thrObject != nullptr)
{
ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr);
OUTPUT_WARN("Stopping and deleting thread [ %s ] and deleting components", thrObject->getName().getString());
thrObject->destroyThread(NECommon::WAIT_INFINITE);
delete thrObject;
}
else
{
OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString());
}
}
}
const NERegistry::Model * ComponentLoader::findModelByName( const char * modelName ) const
{
const NERegistry::Model * result = nullptr;
if ( NEString::isEmpty<char>(modelName) == false )
{
for ( int i = 0; (result == nullptr) && (i < mModelList.getSize( )); ++i )
{
const NERegistry::Model & model = mModelList[i];
result = model.getModelName( ) == modelName ? &model : nullptr;
}
}
return result;
}
const NERegistry::ComponentThreadEntry * ComponentLoader::findThreadEntryByName( const char * threadName ) const
{
const NERegistry::ComponentThreadEntry * result = nullptr;
if ( NEString::isEmpty<char>(threadName) == false )
{
for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i )
{
const NERegistry::Model & model = mModelList[i];
int index = model.findThread(threadName);
if ( index != NECommon::INVALID_INDEX )
{
const NERegistry::ComponentThreadEntry & entry = model.getThreadList().getAt(index);
result = &entry;
}
}
}
return result;
}
const NERegistry::ComponentEntry * ComponentLoader::findComponentEntryByName( const char * roleName ) const
{
const NERegistry::ComponentEntry * result = nullptr;
if ( NEString::isEmpty<char>(roleName) == false )
{
for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i )
{
const NERegistry::Model & model = mModelList[i];
const NERegistry::ComponentThreadList & threadList= model.getThreadList();
for ( int j = 0; (result == nullptr) && (i < threadList.getSize()); ++i )
{
const NERegistry::ComponentThreadEntry & thread = threadList.getAt(j);
int index = thread.findComponentEntry(roleName);
if ( index != NECommon::INVALID_INDEX )
{
const NERegistry::ComponentEntry & entry = thread.mComponents.getAt(index);
result = & entry;
}
}
}
}
return result;
}
| 38.878007
| 165
| 0.557431
|
Ali-Nasrolahi
|
68e3ef0f200b918d322171a0dec5379e2df62dde
| 18,478
|
hpp
|
C++
|
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
|
xiacijie/omr-wala-linkage
|
a1aff7aef9ed131a45555451abde4615a04412c1
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#ifndef OMR_X86_REGISTER_DEPENDENCY_INCL
#define OMR_X86_REGISTER_DEPENDENCY_INCL
/*
* The following #define and typedef must appear before any #includes in this file
*/
#ifndef OMR_REGISTER_DEPENDENCY_CONNECTOR
#define OMR_REGISTER_DEPENDENCY_CONNECTOR
namespace OMR { namespace X86 { class RegisterDependencyConditions; } }
namespace OMR { typedef OMR::X86::RegisterDependencyConditions RegisterDependencyConditionsConnector; }
#else
#error OMR::X86::RegisterDependencyConditions expected to be a primary connector, but a OMR connector is already defined
#endif
#include "compiler/codegen/OMRRegisterDependency.hpp"
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include "codegen/CodeGenerator.hpp"
#include "codegen/RealRegister.hpp"
#include "codegen/Register.hpp"
#include "codegen/RegisterConstants.hpp"
#include "codegen/RegisterDependencyStruct.hpp"
#include "env/TRMemory.hpp"
#include "infra/Assert.hpp"
namespace TR { class Instruction; }
namespace TR { class Node; }
namespace TR { class RegisterDependencyConditions; }
template <typename ListKind> class List;
#define UsesGlobalDependentFPRegister (UsesDependentRegister | GlobalRegisterFPDependency)
#define NUM_DEFAULT_DEPENDENCIES 1
typedef uint16_t depsize_t;
class TR_X86RegisterDependencyGroup
{
bool _mayNeedToPopFPRegisters;
bool _needToClearFPStack;
TR::RegisterDependency _dependencies[NUM_DEFAULT_DEPENDENCIES];
TR_ALLOC_WITHOUT_NEW(TR_Memory::RegisterDependencyGroup)
// Use TR_X86RegisterDependencyGroup::create to allocate an object of this type
//
void * operator new(size_t s, int32_t numDependencies, TR_Memory * m)
{
TR_ASSERT(numDependencies > 0, "operator new called with numDependencies == 0");
if (numDependencies > NUM_DEFAULT_DEPENDENCIES)
{
s += (numDependencies-NUM_DEFAULT_DEPENDENCIES)*sizeof(TR::RegisterDependency);
}
return m->allocateHeapMemory(s);
}
void operator delete(void *p, int32_t numDependencies, TR_Memory * m)
{
m->freeMemory(p, TR_AllocationKind::heapAlloc);
}
public:
TR_X86RegisterDependencyGroup() {_mayNeedToPopFPRegisters = false; _needToClearFPStack = false;}
static TR_X86RegisterDependencyGroup * create(int32_t numDependencies, TR_Memory * m)
{
return numDependencies ? new (numDependencies, m) TR_X86RegisterDependencyGroup : 0;
}
TR::RegisterDependency *getRegisterDependency(TR_X86RegisterDependencyIndex index)
{
return &_dependencies[index];
}
void setDependencyInfo(TR_X86RegisterDependencyIndex index,
TR::Register *vr,
TR::RealRegister::RegNum rr,
TR::CodeGenerator *cg,
uint8_t flag = UsesDependentRegister,
bool isAssocRegDependency = false);
TR::RegisterDependency *findDependency(TR::Register *vr, TR_X86RegisterDependencyIndex stop)
{
TR::RegisterDependency *result = NULL;
for (TR_X86RegisterDependencyIndex i=0; !result && (i < stop); i++)
if (_dependencies[i].getRegister() == vr)
result = _dependencies+i;
return result;
}
TR::RegisterDependency *findDependency(TR::RealRegister::RegNum rr, TR_X86RegisterDependencyIndex stop)
{
TR::RegisterDependency *result = NULL;
for (TR_X86RegisterDependencyIndex i=0; !result && (i < stop); i++)
if (_dependencies[i].getRealRegister() == rr)
result = _dependencies+i;
return result;
}
void assignRegisters(TR::Instruction *currentInstruction,
TR_RegisterKinds kindsToBeAssigned,
TR_X86RegisterDependencyIndex numberOfRegisters,
TR::CodeGenerator *cg);
void assignFPRegisters(TR::Instruction *currentInstruction,
TR_RegisterKinds kindsToBeAssigned,
TR_X86RegisterDependencyIndex numberOfRegisters,
TR::CodeGenerator *cg);
void orderGlobalRegsOnFPStack(TR::Instruction *cursor,
TR_RegisterKinds kindsToBeAssigned,
TR_X86RegisterDependencyIndex numberOfRegisters,
List<TR::Register> *poppedRegisters,
TR::CodeGenerator *cg);
void blockRegisters(TR_X86RegisterDependencyIndex numberOfRegisters)
{
for (TR_X86RegisterDependencyIndex i = 0; i < numberOfRegisters; i++)
{
if (_dependencies[i].getRegister())
{
_dependencies[i].getRegister()->block();
}
}
}
void unblockRegisters(TR_X86RegisterDependencyIndex numberOfRegisters)
{
for (uint32_t i = 0; i < numberOfRegisters; i++)
{
if (_dependencies[i].getRegister())
{
_dependencies[i].getRegister()->unblock();
}
}
}
void setMayNeedToPopFPRegisters(bool b) {_mayNeedToPopFPRegisters = b;}
bool getMayNeedToPopFPRegisters() {return _mayNeedToPopFPRegisters;}
void setNeedToClearFPStack(bool b) {_needToClearFPStack = b;}
bool getNeedToClearFPStack() {return _needToClearFPStack;}
void blockRealDependencyRegisters(TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg);
void unblockRealDependencyRegisters(TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg);
};
namespace OMR
{
namespace X86
{
class RegisterDependencyConditions: public OMR::RegisterDependencyConditions
{
TR_X86RegisterDependencyGroup *_preConditions;
TR_X86RegisterDependencyGroup *_postConditions;
TR_X86RegisterDependencyIndex _numPreConditions;
TR_X86RegisterDependencyIndex _addCursorForPre;
TR_X86RegisterDependencyIndex _numPostConditions;
TR_X86RegisterDependencyIndex _addCursorForPost;
TR_X86RegisterDependencyIndex unionDependencies(TR_X86RegisterDependencyGroup *deps, TR_X86RegisterDependencyIndex cursor, TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag, bool isAssocRegDependency);
TR_X86RegisterDependencyIndex unionRealDependencies(TR_X86RegisterDependencyGroup *deps, TR_X86RegisterDependencyIndex cursor, TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag, bool isAssocRegDependency);
public:
TR_ALLOC(TR_Memory::RegisterDependencyConditions)
RegisterDependencyConditions()
: _preConditions(NULL),
_postConditions(NULL),
_numPreConditions(0),
_addCursorForPre(0),
_numPostConditions(0),
_addCursorForPost(0)
{}
RegisterDependencyConditions(TR_X86RegisterDependencyIndex numPreConds, TR_X86RegisterDependencyIndex numPostConds, TR_Memory * m)
: _preConditions(TR_X86RegisterDependencyGroup::create(numPreConds, m)),
_postConditions(TR_X86RegisterDependencyGroup::create(numPostConds, m)),
_numPreConditions(numPreConds),
_addCursorForPre(0),
_numPostConditions(numPostConds),
_addCursorForPost(0)
{}
RegisterDependencyConditions(TR::Node *node, TR::CodeGenerator *cg, TR_X86RegisterDependencyIndex additionalRegDeps = 0, List<TR::Register> * = 0);
void unionNoRegPostCondition(TR::Register *reg, TR::CodeGenerator *cg);
TR::RegisterDependencyConditions *clone(TR::CodeGenerator *cg, TR_X86RegisterDependencyIndex additionalRegDeps = 0);
TR_X86RegisterDependencyGroup *getPreConditions() {return _preConditions;}
void setMayNeedToPopFPRegisters(bool b)
{
if (_preConditions)
_preConditions->setMayNeedToPopFPRegisters(b);
if (_postConditions)
_postConditions->setMayNeedToPopFPRegisters(b);
}
void setNeedToClearFPStack(bool b)
{
if (_preConditions)
_preConditions->setNeedToClearFPStack(b);
else
{
if (_postConditions)
_postConditions->setNeedToClearFPStack(b);
}
}
TR_X86RegisterDependencyIndex getNumPreConditions() {return _numPreConditions;}
TR_X86RegisterDependencyIndex setNumPreConditions(TR_X86RegisterDependencyIndex n, TR_Memory * m)
{
if (_preConditions == NULL)
{
_preConditions = TR_X86RegisterDependencyGroup::create(n, m);
}
return (_numPreConditions = n);
}
TR_X86RegisterDependencyIndex getNumPostConditions() {return _numPostConditions;}
TR_X86RegisterDependencyIndex setNumPostConditions(TR_X86RegisterDependencyIndex n, TR_Memory * m)
{
if (_postConditions == NULL)
{
_postConditions = TR_X86RegisterDependencyGroup::create(n, m);
}
return (_numPostConditions = n);
}
TR_X86RegisterDependencyIndex getAddCursorForPre() {return _addCursorForPre;}
TR_X86RegisterDependencyIndex setAddCursorForPre(TR_X86RegisterDependencyIndex a) {return (_addCursorForPre = a);}
TR_X86RegisterDependencyIndex getAddCursorForPost() {return _addCursorForPost;}
TR_X86RegisterDependencyIndex setAddCursorForPost(TR_X86RegisterDependencyIndex a) {return (_addCursorForPost = a);}
void addPreCondition(TR::Register *vr,
TR::RealRegister::RegNum rr,
TR::CodeGenerator *cg,
uint8_t flag = UsesDependentRegister,
bool isAssocRegDependency = false)
{
TR_X86RegisterDependencyIndex newCursor = unionRealDependencies(_preConditions, _addCursorForPre, vr, rr, cg, flag, isAssocRegDependency);
TR_ASSERT(newCursor <= _numPreConditions, "Too many dependencies");
if (newCursor == _addCursorForPre)
_numPreConditions--; // A vmThread/ebp dependency was displaced, so there is now one less condition.
else
_addCursorForPre = newCursor;
}
void unionPreCondition(TR::Register *vr,
TR::RealRegister::RegNum rr,
TR::CodeGenerator *cg,
uint8_t flag = UsesDependentRegister,
bool isAssocRegDependency = false)
{
TR_X86RegisterDependencyIndex newCursor = unionDependencies(_preConditions, _addCursorForPre, vr, rr, cg, flag, isAssocRegDependency);
TR_ASSERT(newCursor <= _numPreConditions, "Too many dependencies");
if (newCursor == _addCursorForPre)
_numPreConditions--; // A union occurred, so there is now one less condition
else
_addCursorForPre = newCursor;
}
TR_X86RegisterDependencyGroup *getPostConditions() {return _postConditions;}
void addPostCondition(TR::Register *vr,
TR::RealRegister::RegNum rr,
TR::CodeGenerator *cg,
uint8_t flag = UsesDependentRegister,
bool isAssocRegDependency = false)
{
TR_X86RegisterDependencyIndex newCursor = unionRealDependencies(_postConditions, _addCursorForPost, vr, rr, cg, flag, isAssocRegDependency);
TR_ASSERT(newCursor <= _numPostConditions, "Too many dependencies");
if (newCursor == _addCursorForPost)
_numPostConditions--; // A vmThread/ebp dependency was displaced, so there is now one less condition.
else
_addCursorForPost = newCursor;
}
void unionPostCondition(TR::Register *vr,
TR::RealRegister::RegNum rr,
TR::CodeGenerator *cg,
uint8_t flag = UsesDependentRegister,
bool isAssocRegDependency = false)
{
TR_X86RegisterDependencyIndex newCursor = unionDependencies(_postConditions, _addCursorForPost, vr, rr, cg, flag, isAssocRegDependency);
TR_ASSERT(newCursor <= _numPostConditions, "Too many dependencies");
if (newCursor == _addCursorForPost)
_numPostConditions--; // A union occurred, so there is now one less condition
else
_addCursorForPost = newCursor;
}
TR::RegisterDependency *findPreCondition (TR::Register *vr){ return _preConditions ->findDependency(vr, _addCursorForPre ); }
TR::RegisterDependency *findPostCondition(TR::Register *vr){ return _postConditions->findDependency(vr, _addCursorForPost); }
TR::RegisterDependency *findPreCondition (TR::RealRegister::RegNum rr){ return _preConditions ->findDependency(rr, _addCursorForPre ); }
TR::RegisterDependency *findPostCondition(TR::RealRegister::RegNum rr){ return _postConditions->findDependency(rr, _addCursorForPost); }
void assignPreConditionRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR::CodeGenerator *cg)
{
if (_preConditions != NULL)
{
if ((kindsToBeAssigned & TR_X87_Mask))
{
_preConditions->assignFPRegisters(currentInstruction, kindsToBeAssigned, _numPreConditions, cg);
}
else
{
cg->clearRegisterAssignmentFlags();
cg->setRegisterAssignmentFlag(TR_PreDependencyCoercion);
_preConditions->assignRegisters(currentInstruction, kindsToBeAssigned, _numPreConditions, cg);
}
}
}
void assignPostConditionRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR::CodeGenerator *cg)
{
if (_postConditions != NULL)
{
if ((kindsToBeAssigned & TR_X87_Mask))
{
_postConditions->assignFPRegisters(currentInstruction, kindsToBeAssigned, _numPostConditions, cg);
}
else
{
cg->clearRegisterAssignmentFlags();
cg->setRegisterAssignmentFlag(TR_PostDependencyCoercion);
_postConditions->assignRegisters(currentInstruction, kindsToBeAssigned, _numPostConditions, cg);
}
}
}
void blockPreConditionRegisters()
{
_preConditions->blockRegisters(_numPreConditions);
}
void unblockPreConditionRegisters()
{
_preConditions->unblockRegisters(_numPreConditions);
}
void blockPostConditionRegisters()
{
_postConditions->blockRegisters(_numPostConditions);
}
void unblockPostConditionRegisters()
{
_postConditions->unblockRegisters(_numPostConditions);
}
void blockPostConditionRealDependencyRegisters(TR::CodeGenerator *cg)
{
_postConditions->blockRealDependencyRegisters(_numPostConditions, cg);
}
void unblockPostConditionRealDependencyRegisters(TR::CodeGenerator *cg)
{
_postConditions->unblockRealDependencyRegisters(_numPostConditions, cg);
}
void blockPreConditionRealDependencyRegisters(TR::CodeGenerator *cg)
{
_preConditions->blockRealDependencyRegisters(_numPreConditions, cg);
}
void unblockPreConditionRealDependencyRegisters(TR::CodeGenerator *cg)
{
_preConditions->unblockRealDependencyRegisters(_numPreConditions, cg);
}
// All conditions are added - set the number of conditions to be the number
// currently added
//
void stopAddingPreConditions()
{
_numPreConditions = _addCursorForPre;
}
void stopAddingPostConditions()
{
_numPostConditions = _addCursorForPost;
}
void stopAddingConditions()
{
stopAddingPreConditions();
stopAddingPostConditions();
}
void createRegisterAssociationDirective(TR::Instruction *instruction, TR::CodeGenerator *cg);
TR::RealRegister *getRealRegisterFromVirtual(TR::Register *virtReg, TR::CodeGenerator *cg);
bool refsRegister(TR::Register *r);
bool defsRegister(TR::Register *r);
bool usesRegister(TR::Register *r);
void useRegisters(TR::Instruction *instr, TR::CodeGenerator *cg);
#if defined(DEBUG) || defined(PROD_WITH_ASSUMES)
uint32_t numReferencedGPRegisters(TR::CodeGenerator *);
uint32_t numReferencedFPRegisters(TR::CodeGenerator *);
void printFullRegisterDependencyInfo(FILE *pOutFile);
void printDependencyConditions(TR_X86RegisterDependencyGroup *conditions,
TR_X86RegisterDependencyIndex numConditions,
char *prefix,
FILE *pOutFile);
#endif
};
}
}
////////////////////////////////////////////////////
// Generate Routines
////////////////////////////////////////////////////
TR::RegisterDependencyConditions * generateRegisterDependencyConditions(TR::Node *, TR::CodeGenerator *, TR_X86RegisterDependencyIndex = 0, List<TR::Register> * = 0);
TR::RegisterDependencyConditions * generateRegisterDependencyConditions(TR_X86RegisterDependencyIndex, TR_X86RegisterDependencyIndex, TR::CodeGenerator *);
#endif
| 40.700441
| 241
| 0.669391
|
xiacijie
|
68e7b53a748c7f1204bdbd44a08745d63ee42e9e
| 4,874
|
cpp
|
C++
|
jit.cpp
|
c3sr/go-pytorch
|
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
|
[
"Apache-2.0"
] | 14
|
2018-11-26T18:33:27.000Z
|
2021-12-17T11:14:33.000Z
|
jit.cpp
|
c3sr/go-pytorch
|
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
|
[
"Apache-2.0"
] | 7
|
2019-04-02T16:46:01.000Z
|
2020-06-10T02:02:33.000Z
|
jit.cpp
|
c3sr/go-pytorch
|
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
|
[
"Apache-2.0"
] | 3
|
2019-07-16T16:47:07.000Z
|
2021-12-29T07:47:59.000Z
|
#ifdef ENABLE_PYTROCH_JIT
#include "error.hpp"
#include "predictor.hpp"
#include <algorithm>
#include <iosfwd>
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <utility>
#include <vector>
extern Torch_IValue Torch_ConvertIValueToTorchIValue(torch::IValue value);
struct Torch_JITModule {
std::shared_ptr<torch::jit::script::Module> module;
};
struct Torch_JITModule_Method {
torch::jit::script::Method& run;
};
Torch_JITModuleContext Torch_CompileTorchScript(char* cstring_script, Torch_Error* error) {
HANDLE_TH_ERRORS(Torch_GlobalError);
std::string script(cstring_script);
auto mod = new Torch_JITModule();
mod->module = torch::jit::compile(script);
return (void*)mod;
END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL)
}
Torch_JITModuleContext Torch_LoadJITModule(char* cstring_path, Torch_Error* error) {
HANDLE_TH_ERRORS(Torch_GlobalError);
std::string module_path(cstring_path);
auto mod = new Torch_JITModule();
mod->module = torch::jit::load(module_path);
return (void*)mod;
END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL)
}
void Torch_ExportJITModule(Torch_JITModuleContext ctx, char* cstring_path, Torch_Error* error) {
HANDLE_TH_ERRORS(Torch_GlobalError);
std::string module_path(cstring_path);
auto mod = (Torch_JITModule*)ctx;
mod->module->save(module_path);
END_HANDLE_TH_ERRORS(Torch_GlobalError, )
}
Torch_JITModuleMethodContext Torch_JITModuleGetMethod(Torch_JITModuleContext ctx, char* cstring_method,
Torch_Error* error) {
HANDLE_TH_ERRORS(Torch_GlobalError);
std::string method_name(cstring_method);
auto mod = (Torch_JITModule*)ctx;
auto met = new Torch_JITModule_Method{mod->module->get_method(method_name)};
return (void*)met;
END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL)
}
char** Torch_JITModuleGetMethodNames(Torch_JITModuleContext ctx, size_t* len) {
auto mod = (Torch_JITModule*)ctx;
auto size = mod->module->get_methods().size();
*len = size;
auto result = (char**)malloc(sizeof(char*) * size);
int i = 0;
for (auto& method : mod->module->get_methods()) {
auto key = method.value()->name();
auto ckey = new char[key.length() + 1];
strcpy(ckey, key.c_str());
*(result + i) = ckey;
i++;
}
return result;
}
Torch_IValue Torch_JITModuleMethodRun(Torch_JITModuleMethodContext ctx, Torch_IValue* inputs, size_t input_size,
Torch_Error* error) {
HANDLE_TH_ERRORS(Torch_GlobalError);
auto met = (Torch_JITModule_Method*)ctx;
std::vector<torch::IValue> inputs_vec;
for (int i = 0; i < input_size; i++) {
auto ival = *(inputs + i);
inputs_vec.push_back(Torch_ConvertTorchIValueToIValue(ival));
}
auto res = met->run(inputs_vec);
return Torch_ConvertIValueToTorchIValue(res);
END_HANDLE_TH_ERRORS(Torch_GlobalError, Torch_IValue{})
}
Torch_ModuleMethodArgument* Torch_JITModuleMethodArguments(Torch_JITModuleMethodContext ctx, size_t* res_size) {
auto met = (Torch_JITModule_Method*)ctx;
auto schema = met->run.getSchema();
auto arguments = schema.arguments();
auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size());
*res_size = arguments.size();
for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) {
auto name = arguments[i].name();
char* cstr_name = new char[name.length() + 1];
strcpy(cstr_name, name.c_str());
auto type = arguments[i].type()->str();
char* cstr_type = new char[type.length() + 1];
strcpy(cstr_type, type.c_str());
*(result + i) = Torch_ModuleMethodArgument{
.name = cstr_name,
.typ = cstr_type,
};
}
return result;
}
Torch_ModuleMethodArgument* Torch_JITModuleMethodReturns(Torch_JITModuleMethodContext ctx, size_t* res_size) {
auto met = (Torch_JITModule_Method*)ctx;
auto schema = met->run.getSchema();
auto arguments = schema.returns();
auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size());
*res_size = arguments.size();
for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) {
auto name = arguments[i].name();
char* cstr_name = new char[name.length() + 1];
strcpy(cstr_name, name.c_str());
auto type = arguments[i].type()->str();
char* cstr_type = new char[type.length() + 1];
strcpy(cstr_type, type.c_str());
*(result + i) = Torch_ModuleMethodArgument{
.name = cstr_name,
.typ = cstr_type,
};
}
return result;
}
void Torch_DeleteJITModuleMethod(Torch_JITModuleMethodContext ctx) {
auto med = (Torch_JITModule_Method*)ctx;
delete med;
}
void Torch_DeleteJITModule(Torch_JITModuleContext ctx) {
auto mod = (Torch_JITModule*)ctx;
delete mod;
}
#endif // ENABLE_PYTROCH_JIT
| 29.539394
| 112
| 0.708863
|
c3sr
|
68eeb54c52b1f098da02acc840a138117e18e72c
| 2,191
|
cpp
|
C++
|
src/stereo_ugv/image_source.cpp
|
yunhao-qian/stereo_ugv
|
23480a8b93918fc2bc44e16416ac0b4e0598788b
|
[
"BSD-2-Clause"
] | null | null | null |
src/stereo_ugv/image_source.cpp
|
yunhao-qian/stereo_ugv
|
23480a8b93918fc2bc44e16416ac0b4e0598788b
|
[
"BSD-2-Clause"
] | null | null | null |
src/stereo_ugv/image_source.cpp
|
yunhao-qian/stereo_ugv
|
23480a8b93918fc2bc44e16416ac0b4e0598788b
|
[
"BSD-2-Clause"
] | null | null | null |
#include "stereo_ugv/image_source.h"
namespace stereo_ugv
{
/**
* @brief Creates an ImageSource.
* @details The function determines the concrete subclass of the layout to be created by looking up the "type" key, and
* calls the corresponding initialization function. Currently, "camera", "images" and "video" are supported.
* @param context The context containing initialization parameters.
* @return A unique pointer to the created image source.
*/
std::unique_ptr<ImageSource> ImageSource::create(const Context& context)
{
nlohmann::json internal_json;
const auto internal_context{ openInternalContext(&internal_json, context) };
std::string type;
internal_context.getParameter("type", &type);
if (type == "camera")
{
auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::CAMERA>>() };
initialize(source.get(), internal_context);
return source;
}
if (type == "images")
{
auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::IMAGES>>() };
initialize(source.get(), internal_context);
return source;
}
if (type == "video")
{
auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::VIDEO>>() };
initialize(source.get(), internal_context);
return source;
}
throw InvalidParameter{ fmt::format(R"(Unknown ImageSource type "{}")", type) };
}
/**
* @brief Finds the character device file of a camera device given the prefix of its device name.
* @warning This function has not been implemented, and calling it will always cause a RuntimeError.
* @param device_name_prefix The prefix of its device name. Due to the limits of the V4L2 API, device names longer than
* 31 characters are truncated. Therefore, the length of the given prefix should not be longer than 31 characters.
* Otherwise, no matching camera can be found.
* @return The full path to the character device file. If multiple matching cameras are detected, the function issues a
* warning and returns any one among them.
*/
std::string findCameraCharacterDeviceFile(const std::string&)
{
throw RuntimeError{ "This function has not been implemented" };
}
} // namespace stereo_ugv
| 37.135593
| 119
| 0.740758
|
yunhao-qian
|
68f10e810d3722fa4aaf268cea3e77e0684a346c
| 2,325
|
cpp
|
C++
|
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
|
sam1016yu/cicada-exp-sigmod2017
|
64e582370076b2923d37b279d1c32730babc15f8
|
[
"Apache-2.0"
] | null | null | null |
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
|
sam1016yu/cicada-exp-sigmod2017
|
64e582370076b2923d37b279d1c32730babc15f8
|
[
"Apache-2.0"
] | null | null | null |
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
|
sam1016yu/cicada-exp-sigmod2017
|
64e582370076b2923d37b279d1c32730babc15f8
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details. You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* HP designates this particular file as subject to the "Classpath" exception
* as provided by HP in the LICENSE.txt file that accompanied this code.
*/
#include "foedus/storage/sequential/sequential_partitioner_impl.hpp"
#include <cstring>
#include <ostream>
namespace foedus {
namespace storage {
namespace sequential {
SequentialPartitioner::SequentialPartitioner(Partitioner* parent)
: engine_(parent->get_engine()),
id_(parent->get_storage_id()),
metadata_(PartitionerMetadata::get_metadata(engine_, id_)) {
}
ErrorStack SequentialPartitioner::design_partition(
const Partitioner::DesignPartitionArguments& /*args*/) {
// no data required for SequentialPartitioner
metadata_->data_offset_ = 0;
metadata_->data_size_ = 0;
metadata_->valid_ = true;
return kRetOk;
}
void SequentialPartitioner::partition_batch(
const Partitioner::PartitionBatchArguments& args) const {
// all local
for (uint32_t i = 0; i < args.logs_count_; ++i) {
args.results_[i] = args.local_partition_;
}
}
void SequentialPartitioner::sort_batch(const Partitioner::SortBatchArguments& args) const {
// no sorting needed.
std::memcpy(
args.output_buffer_,
args.log_positions_,
sizeof(snapshot::BufferPosition) * args.logs_count_);
*args.written_count_ = args.logs_count_;
}
std::ostream& operator<<(std::ostream& o, const SequentialPartitioner& /*v*/) {
o << "<SequentialPartitioner>"
<< "</SequentialPartitioner>";
return o;
}
} // namespace sequential
} // namespace storage
} // namespace foedus
| 33.695652
| 91
| 0.744946
|
sam1016yu
|
190387dff2ca8b91b790b2a534eec90c398aa606
| 3,683
|
hpp
|
C++
|
PhantomEngine/Common/Value.hpp
|
restary/Phantom
|
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
|
[
"MIT"
] | null | null | null |
PhantomEngine/Common/Value.hpp
|
restary/Phantom
|
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
|
[
"MIT"
] | null | null | null |
PhantomEngine/Common/Value.hpp
|
restary/Phantom
|
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include <string>
#include <Define.hpp>
using namespace std;
namespace PhantomEngine
{
namespace DataTypes
{
static const uint8_t UNDEFINED = 255;
static const uint8_t INTEGER = 0;
static const uint8_t FLOAT = 1;
static const uint8_t VECTOR2 = 2;
static const uint8_t VECTOR3 = 3;
static const uint8_t SHORT_STRING = 4;
static const uint8_t STRING = 5;
static const uint8_t OBJECT = 6;
static const uint8_t ARRAY = 7;
union DataPointer
{
void* pointer;
uint32_t offset;
};
struct Integer
{
int64_t value;
uint8_t reserved[7];
uint8_t type;
};
struct Float
{
float value;
uint8_t reserved[11];
uint8_t type;
};
struct Vector2
{
float x;
float y;
uint8_t reserved[7];
uint8_t type;
};
struct Vector3
{
float x;
float y;
float z;
uint8_t reserved[3];
uint8_t type;
};
struct ShortString
{
const static uint32_t MAX_SIZE = 14;
char content[MAX_SIZE];
uint8_t length;
uint8_t type;
};
struct String
{
DataPointer data;
uint32_t size;
uint8_t reserved[3];
uint8_t type;
};
struct Object
{
DataPointer data;
uint32_t size;
uint8_t reserved[3];
uint8_t type;
};
struct Array
{
DataPointer data;
uint32_t size;
uint8_t reserved[3];
uint8_t type;
};
union Data
{
Integer integer;
Float number;
Vector2 vector2;
Vector3 vector3;
ShortString shortString;
String string;
Object object;
Array array;
void operator=(int i) { integer.type = INTEGER; integer.value = i; }
void operator=(float f) { number.type = FLOAT; number.value = f; }
void operator=(Vector2 v2) { vector2 = v2; }
void operator=(Vector3 v3) { vector3 = v3; }
void operator=(std::string s);
uint8_t GetType() { return integer.type; }
bool IsReference() { return integer.type > SHORT_STRING; }
};
}
template<typename T>
struct Value
{
uint8_t GetType() { return DataTypes::UNDEFINED; }
};
template<>
struct Value<int>
{
Value() { data = 0; }
uint8_t GetType() { return DataTypes::INTEGER; }
void operator=(int i) { data = i; }
private:
DataTypes::Data data;
};
template<>
struct Value<float>
{
Value() { data = 0.0f; }
uint8_t GetType() { return DataTypes::FLOAT; }
void operator=(float f) { data = f; }
private:
DataTypes::Data data;
};
template<>
struct Value<string>
{
Value() { data = ""; }
uint8_t GetType() { return DataTypes::FLOAT; }
void operator=(string s) { data = s; }
private:
DataTypes::Data data;
};
template<typename T>
struct Field
{
Value<string> name;
Value<T> value;
Field(std::string fieldName);
};
}
| 23.01875
| 80
| 0.472984
|
restary
|
1903fb7b9a2da957750f0a1fd043519c6fc9c0b3
| 8,239
|
cpp
|
C++
|
src/StockExchange/StockExchange.cpp
|
SABCEMM/SABCEMM
|
a87ea83b57a8a7d16591abe30e56db459e710a0e
|
[
"BSD-3-Clause"
] | 17
|
2018-01-08T13:38:28.000Z
|
2022-01-21T05:39:26.000Z
|
src/StockExchange/StockExchange.cpp
|
SABCEMM/SABCEMM
|
a87ea83b57a8a7d16591abe30e56db459e710a0e
|
[
"BSD-3-Clause"
] | null | null | null |
src/StockExchange/StockExchange.cpp
|
SABCEMM/SABCEMM
|
a87ea83b57a8a7d16591abe30e56db459e710a0e
|
[
"BSD-3-Clause"
] | 1
|
2018-01-08T13:39:00.000Z
|
2018-01-08T13:39:00.000Z
|
/* Copyright 2017 - BSD-3-Clause
*
* Copyright Holder (alphabetical):
*
* Beikirch, Maximilian
* Cramer, Simon
* Frank, Martin
* Otte, Philipp
* Pabich, Emma
* Trimborn, Torsten
*
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @author Beikirch, Cramer, Pabich
* @date 08 Nov 2017
* @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM
*/
#include <cassert>
#include <vector>
#include "StockExchange.h"
#include <cstddef> //for std::size_t
#include <algorithm>
#include <random>
#include <boost/core/ignore_unused.hpp>
#include <limits>
#include "../DataCollector/DataCollector.h"
/** Setter method for the DataCollector composite
* \param newDataCollector Pointer to the new DataCollector composite
*/
void StockExchange::setDataCollector(DataCollector* newDataCollector) {
dataCollector = newDataCollector;
}
/** Setter method for the agents vector
* \param newAgents Pointer to the new vector of agents.
*/
void StockExchange::setAgents(std::vector<Agent*>* newAgents){
agents = newAgents;
setNumAgents();
}
/** Setter method for the RandomGenerator
* \param newRandomGenerator Pointer to a RandomGenerator
*/
void StockExchange::setRandomGenerator(RandomGenerator* newRandomGenerator) {
randomGenerator = newRandomGenerator;
}
/** Setter method for the PriceCalculator
* \param newPriceCalculator Pointer to the PriceCalculator
*/
void StockExchange::setPriceCalculator(PriceCalculator* newPriceCalculator) {
priceCalculator = newPriceCalculator;
}
/** Setter method for the ExcessDemandCalculator
* \param newExcessDemandCalculator Pointer to the ExcessDemandCalculator
*/
void StockExchange::setExcessDemandCalculator(ExcessDemandCalculator* newExcessDemandCalculator) {
excessDemandCalculator = newExcessDemandCalculator;
}
/** Setter method for the number of agents. The number is not taken as a paramter but from the array of agents.
*/
void StockExchange::setNumAgents() {
if (agents!=nullptr){
numAgents = agents->size();
}else{
numAgents = 0;
}
}
/** StandardConstructor of the StockExchange
*/
StockExchange::StockExchange(): StockExchange(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) {
}
/** Constructor of the StockExchange.
* \param newDataCollector Pointer to a DataCollector composite
* \param newAgents Pointer to a vector of agents
* \param newRandomGenerator Pointer to a RandomGenerator
* \param newPriceCalculator Pointer to a PriceCalculator
* \param newExcessDemandCalculator Pointer to an ExcessDemandCalculator
*/
StockExchange::StockExchange(DataCollector* newDataCollector, std::vector<Agent*>* newAgents,
RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator,
ExcessDemandCalculator* newExcessDemandCalculator,
ShareCalculator* newShareCalculator,
Dividend* newDividend,
GlobalNews* newGlobalNews){
numAgents = 0;
agents = newAgents;
dataCollector = newDataCollector;
randomGenerator = newRandomGenerator;
priceCalculator = newPriceCalculator;
excessDemandCalculator = newExcessDemandCalculator;
shareCalculator = newShareCalculator;
dividend = newDividend;
setNumAgents();
agentIndex.clear();
globalNews = newGlobalNews;
}
/** Destructor
*/
StockExchange::~StockExchange() = default;
/** Check if the object is fully configured and ready to be used.
*/
void StockExchange::checkInitilisation() {
assert(agents != nullptr);
assert(dataCollector != nullptr);
assert(randomGenerator != nullptr);
assert(priceCalculator != nullptr);
assert(excessDemandCalculator != nullptr);
assert(numAgents == agents->size());
}
void StockExchange::setDividend(Dividend* newDividend){
assert(newDividend != nullptr);
dividend = newDividend;
}
/** Setter method for the GlobalNews container
* \param newGlobalNews Pointer to a GlobalNews container
*/
void StockExchange::setGlobalNews(GlobalNews* newGlobalNews){
this->globalNews = newGlobalNews;
}
/** PreStep: Execute all calls that are required before a new update of the price and the agents can be triggered.
* Generates new GlobalNews.
*/
void StockExchange::preStep() {
assert(priceCalculator != nullptr);
if(globalNews!=nullptr){
globalNews->generateNewGlobalNews();
}
if(dividend!= nullptr){
dividend->calculateDividend();
}
if(excessDemandCalculator != nullptr)
excessDemandCalculator->preStepCalculate();
priceCalculator->preStepCalculate();
for (auto &agent : *agents) {
agent->preStepUpdate();
}
}
/** Step: Calculate a new Price and update all agents.
* The agents are updated in a random order.
*/
void StockExchange::step(){
assert(agents!=nullptr);
assert(priceCalculator!=nullptr);
assert(randomGenerator != nullptr);
//Random over all Agents
priceCalculator->stepCalculate();
if(agentIndex.size() != agents->size()){
agentIndex.clear();
for(std::size_t j=0;j<agents->size();j++)
{
agentIndex.push_back(j);
}
}
// shuffling needs to be coupled to the RNG to ensure reproducability for
// equal seeds.
int seed=0;
randomGenerator->getUniformRandomInt(0, std::numeric_limits<int>::max(), &seed);
std::mt19937 g(static_cast<unsigned int>(seed));
std::shuffle(agentIndex.begin(),agentIndex.end(),g);
for(std::size_t j=0;j<agents->size();j++)
{
agents->at(agentIndex[j])->stepUpdate();
}
}
/** PostStep.
* Calls the DataCollector.
*/
void StockExchange::postStep(){
// ED-postInfo (the correction terms for the price) must be available
// before price correction.
/// @todo this, however, is not general. Can we specify a rule that will
/// likely hold for future models?
if(excessDemandCalculator != nullptr)
excessDemandCalculator->postStepCalculate();
priceCalculator->postStepCalculate();
for (auto &agent : *agents) {
agent->postStepUpdate();
}
if(shareCalculator != nullptr)
shareCalculator->updateShares();
dataCollector->collect();
}
StockExchange* StockExchange::factory() {
return new StockExchange();
}
StockExchange* StockExchange::factory(DataCollector* newDataCollector, std::vector<Agent*>* newAgents,
RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator,
ExcessDemandCalculator* newExcessDemandCalculator, ShareCalculator* newShareCalculator,
Dividend* newDividend,
GlobalNews* newGlobalNews) {
return new StockExchange(newDataCollector, newAgents,
newRandomGenerator, newPriceCalculator,
newExcessDemandCalculator, newShareCalculator, newDividend,
newGlobalNews);
}
| 28.908772
| 125
| 0.73237
|
SABCEMM
|
1905c4166233cc8b835b80f27c0aa834ce68fb80
| 933
|
cpp
|
C++
|
src/world/abilities/blink.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 7
|
2015-01-28T09:17:08.000Z
|
2020-04-21T13:51:16.000Z
|
src/world/abilities/blink.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | null | null | null |
src/world/abilities/blink.cpp
|
louiz/batajelo
|
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
|
[
"BSL-1.0",
"BSD-2-Clause",
"Zlib",
"MIT"
] | 1
|
2020-07-11T09:20:25.000Z
|
2020-07-11T09:20:25.000Z
|
#include <world/abilities/blink.hpp>
#include <world/works/blink_work.hpp>
#include <world/entity.hpp>
#include <logging/logging.hpp>
#include <memory>
using namespace std::chrono_literals;
template<>
const std::string NamedAbility<Blink>::name = "Blink";
template<>
const AbilityType NamedAbility<Blink>::ability_type = AbilityType::Blink;
Blink::Blink():
ActiveAbility(TargetType::Point)
{
log_debug("Creating a blink instance");
this->cooldown.set_max(0s);
log_debug(this->cooldown.get_max_in_ticks());
}
void Blink::cast(Entity* entity, World* world, const Position& position, const bool queue)
{
// Check mana, cooldown etc etc
log_debug("CASTING blink for entity" << entity->get_id() << " to pos " << position);
auto work = std::make_unique<BlinkWork>(world, entity, position);
if (queue)
entity->queue_work(std::move(work));
else
entity->set_work(std::move(work));
this->cooldown.start();
}
| 25.916667
| 90
| 0.719185
|
louiz
|
19061669c719a818d8563f9c8f75664fb79d9bf7
| 1,004
|
hpp
|
C++
|
tests/messaging/sock/networkcommon.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 61
|
2015-01-08T08:05:28.000Z
|
2022-01-07T16:47:47.000Z
|
tests/messaging/sock/networkcommon.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 30
|
2015-04-06T21:41:18.000Z
|
2021-08-18T13:24:51.000Z
|
tests/messaging/sock/networkcommon.hpp
|
arntanguy/libqi
|
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
|
[
"BSD-3-Clause"
] | 64
|
2015-02-23T20:01:11.000Z
|
2022-03-14T13:31:20.000Z
|
#pragma once
#ifndef _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP
#define _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP
#include <algorithm>
#include <random>
#include <boost/lexical_cast.hpp>
/// @file
/// Contains functions and types used by socket tests.
/// Precondition: With p = reinterpret_cast<unsigned char*>(t),
/// writable_counted_range(p, sizeof(T))
template<typename T>
void overwrite(T* t)
{
auto p = reinterpret_cast<unsigned char*>(t);
std::fill(p, p + sizeof(T), '\xFF');
}
/// Expects a string with the format:
/// error_code: error_message
/// where error_code is an integer.
inline int code(const std::string& s)
{
std::string c{begin(s), std::find(begin(s), end(s), ':')};
return boost::lexical_cast<int>(c);
}
// Distribution D, Generator G, BasicLockable L
template<typename D, typename G, typename L>
auto syncRand(D& dist, G& gen, L& lockable) -> decltype(dist(gen))
{
std::lock_guard<L> lock{lockable};
return dist(gen);
}
#endif // _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP
| 26.421053
| 66
| 0.718127
|
arntanguy
|
1907555a950fd68d43b118706ee986f0fe711c7a
| 3,089
|
cpp
|
C++
|
worker/callback_runner_test.cpp
|
tkwong/parameter_server
|
ef8424f341f3b4c4e1088b72d88930fac8b78daf
|
[
"Apache-2.0"
] | null | null | null |
worker/callback_runner_test.cpp
|
tkwong/parameter_server
|
ef8424f341f3b4c4e1088b72d88930fac8b78daf
|
[
"Apache-2.0"
] | null | null | null |
worker/callback_runner_test.cpp
|
tkwong/parameter_server
|
ef8424f341f3b4c4e1088b72d88930fac8b78daf
|
[
"Apache-2.0"
] | null | null | null |
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "worker/callback_runner.cpp"
namespace csci5570 {
class TestCallbackRunner: public testing::Test {
protected:
void SetUp() {}
void TearDown() {}
}; // class TestCallbackRunner
TEST_F(TestCallbackRunner, Init)
{
CallbackRunner runner;
}
TEST_F(TestCallbackRunner, AddResponse)
{
CallbackRunner runner;
std::map<Key,float> reply;
bool finished = false;
runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){
auto re_keys = third_party::SArray<Key>(msg.data[0]);
auto re_vals = third_party::SArray<float>(msg.data[1]);
for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i]));
});
runner.RegisterRecvFinishHandle(0, 0, [&finished]{finished=true;});
runner.NewRequest(0, 0, 2);
Message r1, r2;
third_party::SArray<Key> r1_keys{3};
third_party::SArray<float> r1_vals{0.1};
r1.AddData(r1_keys);
r1.AddData(r1_vals);
third_party::SArray<Key> r2_keys{4, 5, 6};
third_party::SArray<float> r2_vals{0.4, 0.2, 0.3};
r2.AddData(r2_keys);
r2.AddData(r2_vals);
runner.AddResponse(0, 0, r1);
runner.AddResponse(0, 0, r2);
runner.WaitRequest(0, 0);
EXPECT_EQ(reply.size(), 4);
std::map<Key, float> expected {
{3, 0.1},
{4, 0.4},
{5, 0.2},
{6, 0.3}
};
EXPECT_EQ(reply, expected);
EXPECT_EQ(finished, true);
}
TEST_F(TestCallbackRunner, AddResponseTwoWorkers)
{
CallbackRunner runner;
std::map<Key,float> reply;
float sum = 0;
// Register for first worker
runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){
auto re_keys = third_party::SArray<Key>(msg.data[0]);
auto re_vals = third_party::SArray<float>(msg.data[1]);
for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i]));
});
runner.RegisterRecvFinishHandle(0, 0, []{});
runner.NewRequest(0, 0, 2);
// Register for second worker
runner.RegisterRecvHandle(1, 0,[&sum](Message& msg){
auto re_vals = third_party::SArray<float>(msg.data[1]);
for (int i=0; i<re_vals.size(); i++) sum += re_vals[i];
});
runner.RegisterRecvFinishHandle(1, 0, []{});
runner.NewRequest(1, 0, 2);
// Respond to both worker
Message r1, r2;
third_party::SArray<Key> r1_keys{3};
third_party::SArray<float> r1_vals{0.1};
r1.AddData(r1_keys);
r1.AddData(r1_vals);
third_party::SArray<Key> r2_keys{4, 5, 6};
third_party::SArray<float> r2_vals{0.4, 0.2, 0.3};
r2.AddData(r2_keys);
r2.AddData(r2_vals);
runner.AddResponse(0, 0, r1);
runner.AddResponse(0, 0, r2);
runner.AddResponse(1, 0, r1);
runner.AddResponse(1, 0, r2);
runner.WaitRequest(0, 0);
EXPECT_EQ(reply.size(), 4);
std::map<Key, float> expected {
{3, 0.1},
{4, 0.4},
{5, 0.2},
{6, 0.3}
};
EXPECT_EQ(reply, expected);
runner.WaitRequest(1, 0);
EXPECT_EQ(sum, 1.0);
}
} // namespace csci5570
| 27.336283
| 98
| 0.616381
|
tkwong
|
190ee3f87e869fae0d4deb4a480c1b36a6b936b3
| 3,141
|
cpp
|
C++
|
src/blackboard_entry.cpp
|
robotics-upo/BehaviorTree.CPP
|
320e61711f75604a23726fbf16fd2660e8c68efe
|
[
"MIT"
] | null | null | null |
src/blackboard_entry.cpp
|
robotics-upo/BehaviorTree.CPP
|
320e61711f75604a23726fbf16fd2660e8c68efe
|
[
"MIT"
] | null | null | null |
src/blackboard_entry.cpp
|
robotics-upo/BehaviorTree.CPP
|
320e61711f75604a23726fbf16fd2660e8c68efe
|
[
"MIT"
] | null | null | null |
#include "behaviortree_cpp_v3/blackboard_entry.h"
namespace BT
{
Entry::Entry(const Entry& _other_entry, const TypesConverter& _converter) :
converter_ ( _converter )
{
input_types_ = _other_entry.input_types_;
output_types_ = _other_entry.output_types_;
checkTypesCompatible(input_types_, output_types_);
}
Entry::Entry(const PortInfo& _port_info, const TypesConverter& _converter) :
converter_ ( _converter )
{
addPortInfo(_port_info);
}
Entry::Entry(Any&& other_any, const TypesConverter& _converter):
value_ (std::move(other_any)),
converter_ (_converter)
{}
Entry::Entry(Any&& other_any, const PortInfo& _port_info, const TypesConverter& _converter):
value_ (std::move(other_any)),
converter_ (_converter)
{
addPortInfo(value_.type(), _port_info.direction());
}
Entry::Entry(Any&& other_any, const PortDirection _direction, const TypesConverter& _converter):
value_ (std::move(other_any)),
converter_ (_converter)
{
addPortInfo(value_.type(), _direction);
}
template<>
void Entry::setValue(Any&& _other_any)
{
addPortInfo(_other_any.type(), PortDirection::OUTPUT);
value_ = _other_any;
}
template<>
Any Entry::getValue()
{
return value_;
}
void Entry::addPortInfo(const PortInfo& _port_info)
{
if(!_port_info.type()) { return; }
addPortInfo(*_port_info.type(), _port_info.direction());
}
void Entry::addPortInfo(const std::type_info& _type, const PortDirection _direction)
{
std::pair<Types::iterator, bool> insert_result {};
switch(_direction)
{
case PortDirection::INPUT:
insert_result = input_types_.insert(_type);
break;
case PortDirection::OUTPUT:
insert_result = output_types_.insert(_type);
break;
case PortDirection::INOUT:
{
insert_result = input_types_.insert(_type);
if(insert_result.second) { output_types_.insert(_type); }
else { insert_result = output_types_.insert(_type); }
}
break;
}
//Check for type compatibility only if there has been changes in the type
if(insert_result.second)
{
checkTypesCompatible(output_types_, input_types_);
}
}
// Private
void Entry::checkTypesCompatible(const Types& _output_types, const Types& _input_types)
{
for(const std::type_index& output_type : _output_types)
{
for(const std::type_index& input_type : _input_types)
{
if(!converter_.isConvertible(output_type, input_type))
{
throw LogicError { "Incompatible entry types. No known conversion from ",
demangle(output_type), " to ", demangle(input_type) };
}
}
}
}
} // end namespace BT
| 30.201923
| 100
| 0.589621
|
robotics-upo
|
190f6fb15793fc116a783933ffddd3c33e11ddd0
| 502
|
cpp
|
C++
|
beta versions/Processor.cpp
|
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
|
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
|
[
"MIT"
] | null | null | null |
beta versions/Processor.cpp
|
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
|
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
|
[
"MIT"
] | null | null | null |
beta versions/Processor.cpp
|
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
|
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
|
[
"MIT"
] | null | null | null |
#include "Processor.hpp"
using namespace std;
void Processor::setEverything(int anID, int amountOfCores, float alpha,
float beta, float delta, float gamma, float c){
id = anID;
cores = amountOfCores;
failureP = 1 / gamma;
probRc = c;
probRb = 1 - c;
TRc = 1 / beta;
TRb = 1 / alpha;
TRepair = 1 / delta;
}
int Processor::calculatePoisson(int x){
srand(time(0));
float r = rand() / INT_MAX;
int xPoisson = (1 / x) * log(1 - r);
return xPoisson;
}
| 21.826087
| 72
| 0.605578
|
tec-csf
|
190fc0414b47b91ff40165dcabf6f578c9737971
| 18,167
|
cpp
|
C++
|
admin/cmdline/scheduledtasks/end.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
admin/cmdline/scheduledtasks/end.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
admin/cmdline/scheduledtasks/end.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/******************************************************************************
Copyright(c) Microsoft Corporation
Module Name:
end.cpp
Abstract:
This module terminates the schedule task which is currently running in the system
Author:
Venu Gopal Choudary 12-Mar-2001
Revision History:
Venu Gopal Choudary 12-Mar-2001 : Created it
******************************************************************************/
//common header files needed for this file
#include "pch.h"
#include "CommonHeaderFiles.h"
// Function declaration for the Usage function.
VOID DisplayEndUsage();
/*****************************************************************************
Routine Description:
This routine terminates the scheduled task(s)
Arguments:
[ in ] argc : Number of command line arguments
[ in ] argv : Array containing command line arguments
Return Value :
A DWORD value indicating EXIT_SUCCESS on success else
EXIT_FAILURE on failure
*****************************************************************************/
DWORD
TerminateScheduledTask(
IN DWORD argc,
IN LPCTSTR argv[]
)
{
// Variables used to find whether End option, Usage option
// are specified or not
BOOL bEnd = FALSE;
BOOL bUsage = FALSE;
BOOL bFlag = FALSE;
// Set the TaskSchduler object as NULL
ITaskScheduler *pITaskScheduler = NULL;
// Return value
HRESULT hr = S_OK;
// Initialising the variables that are passed to TCMDPARSER structure
LPWSTR szServer = NULL;
WCHAR szTaskName[ MAX_JOB_LEN ] = L"\0";
LPWSTR szUser = NULL;
LPWSTR szPassword = NULL;
// Dynamic Array contaning array of jobs
TARRAY arrJobs = NULL;
BOOL bNeedPassword = FALSE;
BOOL bResult = FALSE;
BOOL bCloseConnection = TRUE;
//buffer for displaying error message
WCHAR szMessage[2 * MAX_STRING_LENGTH] = L"\0";
TCMDPARSER2 cmdEndOptions[MAX_END_OPTIONS];
BOOL bReturn = FALSE;
DWORD dwCheck = 0;
DWORD dwPolicy = 0;
// /run sub-options
const WCHAR szEndnOpt[] = L"end";
const WCHAR szEndHelpOpt[] = L"?";
const WCHAR szEndServerOpt[] = L"s";
const WCHAR szEndUserOpt[] = L"u";
const WCHAR szEndPwdOpt[] = L"p";
const WCHAR szEndTaskNameOpt[] = L"tn";
// set all the fields to 0
SecureZeroMemory( cmdEndOptions, sizeof( TCMDPARSER2 ) * MAX_END_OPTIONS );
//
// fill the commandline parser
//
// /delete option
StringCopyA( cmdEndOptions[ OI_END_OPTION ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_OPTION ].dwType = CP_TYPE_BOOLEAN;
cmdEndOptions[ OI_END_OPTION ].pwszOptions = szEndnOpt;
cmdEndOptions[ OI_END_OPTION ].dwCount = 1;
cmdEndOptions[ OI_END_OPTION ].dwFlags = 0;
cmdEndOptions[ OI_END_OPTION ].pValue = &bEnd;
// /? option
StringCopyA( cmdEndOptions[ OI_END_USAGE ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_USAGE ].dwType = CP_TYPE_BOOLEAN;
cmdEndOptions[ OI_END_USAGE ].pwszOptions = szEndHelpOpt;
cmdEndOptions[ OI_END_USAGE ].dwCount = 1;
cmdEndOptions[ OI_END_USAGE ].dwFlags = CP2_USAGE;
cmdEndOptions[ OI_END_USAGE ].pValue = &bUsage;
// /s option
StringCopyA( cmdEndOptions[ OI_END_SERVER ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_SERVER ].dwType = CP_TYPE_TEXT;
cmdEndOptions[ OI_END_SERVER].pwszOptions = szEndServerOpt;
cmdEndOptions[ OI_END_SERVER ].dwCount = 1;
cmdEndOptions[ OI_END_SERVER ].dwFlags = CP2_ALLOCMEMORY| CP2_VALUE_TRIMINPUT|CP2_VALUE_NONULL ;
// /u option
StringCopyA( cmdEndOptions[ OI_END_USERNAME ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_USERNAME ].dwType = CP_TYPE_TEXT;
cmdEndOptions[ OI_END_USERNAME ].pwszOptions = szEndUserOpt;
cmdEndOptions[ OI_END_USERNAME ].dwCount = 1;
cmdEndOptions[ OI_END_USERNAME ].dwFlags = CP2_ALLOCMEMORY| CP2_VALUE_TRIMINPUT|CP2_VALUE_NONULL ;
// /p option
StringCopyA( cmdEndOptions[ OI_END_PASSWORD ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_PASSWORD ].dwType = CP_TYPE_TEXT;
cmdEndOptions[ OI_END_PASSWORD ].pwszOptions = szEndPwdOpt;
cmdEndOptions[ OI_END_PASSWORD ].dwCount = 1;
cmdEndOptions[ OI_END_PASSWORD ].dwActuals = 0;
cmdEndOptions[ OI_END_PASSWORD ].dwFlags = CP2_ALLOCMEMORY | CP2_VALUE_OPTIONAL;
// /tn option
StringCopyA( cmdEndOptions[ OI_END_TASKNAME ].szSignature, "PARSER2\0", 8 );
cmdEndOptions[ OI_END_TASKNAME ].dwType = CP_TYPE_TEXT;
cmdEndOptions[ OI_END_TASKNAME ].pwszOptions = szEndTaskNameOpt;
cmdEndOptions[ OI_END_TASKNAME ].dwCount = 1;
cmdEndOptions[ OI_END_TASKNAME ].dwFlags = CP2_MANDATORY;
cmdEndOptions[ OI_END_TASKNAME ].pValue = szTaskName;
cmdEndOptions[ OI_END_TASKNAME ].dwLength = MAX_JOB_LEN;
//parse command line arguments
bReturn = DoParseParam2( argc, argv, 0, SIZE_OF_ARRAY(cmdEndOptions), cmdEndOptions, 0);
if( FALSE == bReturn) // Invalid commandline
{
//display an error message
ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL );
ReleaseGlobals();
return EXIT_FAILURE;
}
// get the buffer pointers allocated by command line parser
szServer = (LPWSTR)cmdEndOptions[ OI_RUN_SERVER ].pValue;
szUser = (LPWSTR)cmdEndOptions[ OI_RUN_USERNAME ].pValue;
szPassword = (LPWSTR)cmdEndOptions[ OI_RUN_PASSWORD ].pValue;
if ( (argc > 3) && (bUsage == TRUE) )
{
ShowMessage ( stderr, GetResString (IDS_ERROR_ENDPARAM) );
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
// Displaying end usage if user specified -? with -run option
if( bUsage == TRUE )
{
DisplayEndUsage();
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_SUCCESS;
}
// check for invalid user name
if( ( cmdEndOptions[OI_END_SERVER].dwActuals == 0 ) && ( cmdEndOptions[OI_END_USERNAME].dwActuals == 1 ) )
{
ShowMessage(stderr, GetResString(IDS_END_USER_BUT_NOMACHINE));
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL;
}
// check for invalid username
if ( cmdEndOptions[ OI_END_USERNAME ].dwActuals == 0 && cmdEndOptions[ OI_END_PASSWORD ].dwActuals == 1 )
{
// invalid syntax
ShowMessage(stderr, GetResString(IDS_EPASSWORD_BUT_NOUSERNAME));
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL; // indicate failure
}
// check for the length of the taskname
if( ( StringLength( szTaskName, 0 ) > MAX_JOB_LEN ) )
{
ShowMessage(stderr, GetResString(IDS_INVALID_TASKLENGTH));
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL;
}
//for holding values of parameters in FormatMessage()
WCHAR* szValues[1] = {NULL};
// check whether the password (-p) specified in the command line or not
// and also check whether '*' or empty is given for -p or not
// check whether the password (-p) specified in the command line or not
// and also check whether '*' or empty is given for -p or not
// check whether the password (-p) specified in the command line or not
// and also check whether '*' or empty is given for -p or not
// check the remote connectivity information
if ( szServer != NULL )
{
//
// if -u is not specified, we need to allocate memory
// in order to be able to retrive the current user name
//
// case 1: -p is not at all specified
// as the value for this switch is optional, we have to rely
// on the dwActuals to determine whether the switch is specified or not
// in this case utility needs to try to connect first and if it fails
// then prompt for the password -- in fact, we need not check for this
// condition explicitly except for noting that we need to prompt for the
// password
//
// case 2: -p is specified
// but we need to check whether the value is specified or not
// in this case user wants the utility to prompt for the password
// before trying to connect
//
// case 3: -p * is specified
// user name
if ( szUser == NULL )
{
szUser = (LPWSTR) AllocateMemory( MAX_STRING_LENGTH * sizeof( WCHAR ) );
if ( szUser == NULL )
{
SaveLastError();
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL;
}
}
// password
if ( szPassword == NULL )
{
bNeedPassword = TRUE;
szPassword = (LPWSTR)AllocateMemory( MAX_STRING_LENGTH * sizeof( WCHAR ) );
if ( szPassword == NULL )
{
SaveLastError();
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL;
}
}
// case 1
if ( cmdEndOptions[ OI_END_PASSWORD ].dwActuals == 0 )
{
// we need not do anything special here
}
// case 2
else if ( cmdEndOptions[ OI_END_PASSWORD ].pValue == NULL )
{
StringCopy( szPassword, L"*", GetBufferSize(szPassword)/sizeof(WCHAR));
}
// case 3
else if ( StringCompareEx( szPassword, L"*", TRUE, 0 ) == 0 )
{
if ( ReallocateMemory( (LPVOID*)&szPassword,
MAX_STRING_LENGTH * sizeof( WCHAR ) ) == FALSE )
{
SaveLastError();
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return RETVAL_FAIL;
}
// ...
bNeedPassword = TRUE;
}
}
if( ( IsLocalSystem( szServer ) == FALSE ) || ( cmdEndOptions[OI_END_USERNAME].dwActuals == 1 ))
{
bFlag = TRUE;
// Establish the connection on a remote machine
bResult = EstablishConnection(szServer,szUser,GetBufferSize(szUser)/sizeof(WCHAR),szPassword,GetBufferSize(szPassword)/sizeof(WCHAR), bNeedPassword);
if (bResult == FALSE)
{
ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL );
//ShowMessage( stderr, GetResString(IDS_ERROR_STRING) );
//ShowMessage( stderr, GetReason());
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE ;
}
else
{
// though the connection is successfull, some conflict might have occured
switch( GetLastError() )
{
case I_NO_CLOSE_CONNECTION:
bCloseConnection = FALSE;
break;
case E_LOCAL_CREDENTIALS:
case ERROR_SESSION_CREDENTIAL_CONFLICT:
{
bCloseConnection = FALSE;
ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL );
//ShowMessage( stderr, GetResString(IDS_ERROR_STRING) );
//ShowMessage( stderr, GetReason());
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
default :
bCloseConnection = TRUE;
}
}
//release memory for password
FreeMemory((LPVOID*) &szPassword);
}
// Get the task Scheduler object for the machine.
pITaskScheduler = GetTaskScheduler( szServer );
// If the Task Scheduler is not defined then give the error message.
if ( pITaskScheduler == NULL )
{
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
// check whether the task scheduler service is running or not.
if ( TRUE == CheckServiceStatus(szServer, &dwCheck, FALSE) )
{
ShowMessage ( stderr, GetResString (IDS_SERVICE_NOT_RUNNING) );
}
// Validate the Given Task and get as TARRAY in case of taskname
arrJobs = ValidateAndGetTasks( pITaskScheduler, szTaskName);
if( arrJobs == NULL )
{
StringCchPrintf( szMessage , SIZE_OF_ARRAY(szMessage), GetResString(IDS_TASKNAME_NOTEXIST), _X( szTaskName ));
ShowMessage(stderr, szMessage );
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
// check whether the group policy prevented user from running or not.
if ( FALSE == GetGroupPolicy( szServer, szUser, TS_KEYPOLICY_DENY_EXECUTION, &dwPolicy ) )
{
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
if ( dwPolicy > 0 )
{
ShowMessage ( stdout, GetResString (IDS_PREVENT_END));
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_SUCCESS;
}
IPersistFile *pIPF = NULL;
ITask *pITask = NULL;
StringConcat ( szTaskName, JOB, SIZE_OF_ARRAY(szTaskName) );
// return an pITask inteface for szTaskName
hr = pITaskScheduler->Activate(szTaskName,IID_ITask,
(IUnknown**) &pITask);
if (FAILED(hr))
{
SetLastError ((DWORD) hr);
ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_SYSTEM );
if( pIPF )
pIPF->Release();
if( pITask )
pITask->Release();
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
//WCHAR szBuffer[2 * MAX_STRING_LENGTH] = L"\0";
if ( ParseTaskName( szTaskName ) )
{
if( pIPF )
pIPF->Release();
if( pITask )
pITask->Release();
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
// terminate the scheduled task
hr = pITask->Terminate();
if ( FAILED(hr) )
{
SetLastError ((DWORD) hr);
ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_SYSTEM );
if( pIPF )
pIPF->Release();
if( pITask )
pITask->Release();
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_FAILURE;
}
else
{
szValues[0] = (WCHAR*) (szTaskName);
StringCchPrintf ( szMessage, SIZE_OF_ARRAY(szMessage), GetResString(IDS_END_SUCCESSFUL), _X(szTaskName));
ShowMessage(stdout, _X(szMessage));
}
if( pIPF )
pIPF->Release();
if( pITask )
pITask->Release();
if ( (TRUE == bFlag) && (bCloseConnection == TRUE) )
{
CloseConnection( szServer );
}
Cleanup(pITaskScheduler);
FreeMemory((LPVOID*) &szServer);
FreeMemory((LPVOID*) &szUser);
FreeMemory((LPVOID*) &szPassword);
return EXIT_SUCCESS;
}
/*****************************************************************************
Routine Description:
This routine displays the usage of -end option
Arguments:
None
Return Value :
VOID
******************************************************************************/
VOID
DisplayEndUsage()
{
// Displaying run option usage
DisplayUsage( IDS_END_HLP1, IDS_END_HLP17);
}
| 32.499106
| 158
| 0.565641
|
npocmaka
|
1914208c93fcd9ad93a53e72ac939974f736e864
| 2,202
|
cc
|
C++
|
net/tools/transport_security_state_generator/spki_hash_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
|
net/tools/transport_security_state_generator/spki_hash_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
net/tools/transport_security_state_generator/spki_hash_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 2017 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 "net/tools/transport_security_state_generator/spki_hash.h"
#include "base/strings/string_number_conversions.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace transport_security_state {
namespace {
TEST(SPKIHashTest, FromString) {
SPKIHash hash;
// Valid SHA256.
EXPECT_TRUE(
hash.FromString("sha256/1111111111111111111111111111111111111111111="));
std::vector<uint8_t> hash_vector(hash.data(), hash.data() + hash.size());
EXPECT_THAT(
hash_vector,
testing::ElementsAreArray(
{0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D,
0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7,
0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D}));
SPKIHash hash2;
EXPECT_TRUE(
hash2.FromString("sha256/4osU79hfY3P2+WJGlT2mxmSL+5FIwLEVxTQcavyBNgQ="));
std::vector<uint8_t> hash_vector2(hash2.data(), hash2.data() + hash2.size());
EXPECT_THAT(
hash_vector2,
testing::ElementsAreArray(
{0xE2, 0x8B, 0x14, 0xEF, 0xD8, 0x5F, 0x63, 0x73, 0xF6, 0xF9, 0x62,
0x46, 0x95, 0x3D, 0XA6, 0xC6, 0x64, 0x8B, 0xFB, 0x91, 0x48, 0xC0,
0xB1, 0x15, 0xC5, 0x34, 0x1C, 0x6A, 0xFC, 0x81, 0x36, 0x04}));
SPKIHash hash3;
// Valid SHA1 should be rejected.
EXPECT_FALSE(hash3.FromString("sha1/111111111111111111111111111="));
EXPECT_FALSE(hash3.FromString("sha1/gzF+YoVCU9bXeDGQ7JGQVumRueM="));
// SHA1 disguised as SHA256.
EXPECT_FALSE(hash3.FromString("sha256/111111111111111111111111111="));
// SHA512 disguised as SHA256.
EXPECT_FALSE(
hash3.FromString("sha256/ns3smS51SK/4P7uSVhSlCIMNAxkD+r6C/ZZA/"
"07vac0uyMdRS4jKfqlvk3XxLFP1v5aMIxM5cdTM7FHNwxagQg=="));
// Invalid BASE64.
EXPECT_FALSE(hash3.FromString("sha256/hsts-preload"));
EXPECT_FALSE(hash3.FromString("sha256/1. 2. 3. security!="));
}
} // namespace
} // namespace transport_security_state
} // namespace net
| 33.876923
| 79
| 0.701635
|
zealoussnow
|
191a6c446228ac19142afb92a40c92586a351358
| 1,350
|
cpp
|
C++
|
src/plugins/blasq/plugins/rappor/rappor.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 120
|
2015-01-22T14:10:39.000Z
|
2021-11-25T12:57:16.000Z
|
src/plugins/blasq/plugins/rappor/rappor.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 8
|
2015-02-07T19:38:19.000Z
|
2017-11-30T20:18:28.000Z
|
src/plugins/blasq/plugins/rappor/rappor.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 33
|
2015-02-07T16:59:55.000Z
|
2021-10-12T00:36:40.000Z
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "rappor.h"
#include <QIcon>
#include <util/util.h>
#include "vkservice.h"
namespace LC
{
namespace Blasq
{
namespace Rappor
{
void Plugin::Init (ICoreProxy_ptr proxy)
{
Util::InstallTranslator ("blasq_rappor");
Service_ = new VkService (proxy);
}
void Plugin::SecondInit ()
{
}
QByteArray Plugin::GetUniqueID () const
{
return "org.LeechCraft.Blasq.Rappor";
}
void Plugin::Release ()
{
}
QString Plugin::GetName () const
{
return "Blasq Rappor";
}
QString Plugin::GetInfo () const
{
return tr ("VKontakte support module for Blasq.");
}
QIcon Plugin::GetIcon () const
{
return QIcon ();
}
QSet<QByteArray> Plugin::GetPluginClasses () const
{
QSet<QByteArray> result;
result << "org.LeechCraft.Blasq.ServicePlugin";
return result;
}
QList<IService*> Plugin::GetServices () const
{
return { Service_ };
}
}
}
}
LC_EXPORT_PLUGIN (leechcraft_blasq_rappor, LC::Blasq::Rappor::Plugin);
| 19.014085
| 83
| 0.622222
|
Maledictus
|
191a7076b71459404f6bfe86cc3f97fd5cd82611
| 4,088
|
cpp
|
C++
|
src/optimizer/ind_var.cpp
|
kylinsoft/test
|
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
|
[
"MIT"
] | null | null | null |
src/optimizer/ind_var.cpp
|
kylinsoft/test
|
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
|
[
"MIT"
] | null | null | null |
src/optimizer/ind_var.cpp
|
kylinsoft/test
|
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
|
[
"MIT"
] | null | null | null |
#include "pass.hpp"
void ind_var_discovery(NormalFunc *f) {
// TODO: debug
dbg << "## ind var discovery: " << f->name << "\n";
auto S = build_dom_tree(f);
auto defs = build_defs(f);
auto i2bb = build_in2bb(f);
std::unordered_set<Reg> la;
std::unordered_map<Reg, Reg> mp_reg;
dom_tree_dfs(S, [&](BB *w) {
w->for_each([&](Instr *i) {
Case(LoadAddr, i0, i) { la.insert(i0->d1); }
else Case(BinaryOpInstr, i0, i) {
if (la.count(i0->s1) || la.count(i0->s2)) la.insert(i0->d1);
}
});
});
dom_tree_dfs(S, [&](BB *w) {
auto &sw = S[w];
if (sw.loop_rt) {
auto get_BB = [&](Reg r) { return i2bb[defs[r]]; };
auto is_c = [&](Reg r) { return r.id && S[get_BB(r)].sdom(sw); };
std::unordered_map<Reg, IndVarInfo> indvar;
for (auto it = w->instrs.begin(); it != w->instrs.end(); ++it) {
Instr *i = it->get();
Case(PhiInstr, phi, i) {
if (phi->uses.size() != 2) continue;
auto u1 = phi->uses[0];
auto u2 = phi->uses[1];
if (!is_c(u1.first)) std::swap(u1, u2);
if (!is_c(u1.first)) continue;
Case(BinaryOpInstr, bop, defs[u2.first]) {
auto op = bop->op.type;
if (op == BinaryOp::ADD || op == BinaryOp::SUB)
if (bop->s1 == phi->d1 && is_c(bop->s2)) {
// phi.d1 = u1.first + k * bop.s2
auto &s = indvar[phi->d1];
s.base = u1.first;
s.step = bop->s2;
s.op = op;
BB *bb1 = get_BB(s.base);
BB *bb2 = get_BB(s.step);
s.bb = S[bb1].dom(S[bb2]) ? bb2 : bb1;
auto &iv2 = s;
dbg << "basic ind var " << f->get_name(iv2.base) << ","
<< f->get_name(iv2.step) << " : " << f->get_name(bop->d1)
<< "\n";
}
}
}
else Case(BinaryOpInstr, bop, i) {
if (bop->op.type == BinaryOp::MUL || bop->op.type == BinaryOp::ADD) {
auto ind = bop->s1, step = bop->s2;
if (!(indvar.count(ind) && is_c(step))) std::swap(ind, step);
if (!(indvar.count(ind) && is_c(step))) continue;
if (bop->op.type == BinaryOp::ADD) {
// only rewrite as indvar for array index compute
if (!la.count(bop->s1) && !la.count(bop->s2)) continue;
}
auto &iv1 = indvar[ind];
auto &iv2 = indvar[bop->d1];
iv2.base = f->new_Reg();
iv2.op = iv1.op;
Reg base1 = f->new_Reg();
Reg base2 = f->new_Reg();
mp_reg[bop->d1] = base1;
BB *bb = iv2.bb = iv1.bb;
if (bop->op.type == BinaryOp::MUL) {
iv2.step = f->new_Reg();
iv1.bb->push1(
new BinaryOpInstr(iv2.base, iv1.base, step,
BinaryOp::MUL)); // base = base0 * step
iv1.bb->push1(
new BinaryOpInstr(iv2.step, iv1.step, step,
BinaryOp::MUL)); // step = step0 * step
} else {
iv2.step = iv1.step;
iv1.bb->push1(
new BinaryOpInstr(iv2.base, iv1.base, step,
BinaryOp::ADD)); // base = base0 + step
}
dbg << "ind var " << f->get_name(iv2.base) << ","
<< f->get_name(iv2.step) << " : " << f->get_name(base1) << ","
<< f->get_name(base2) << "\n";
PhiInstr *phi = new PhiInstr(base1);
w->push_front(phi);
for (BB *u : sw.in) {
phi->add_use(sw.dom(S[u]) ? base2 : iv2.base, u);
}
*it = std::unique_ptr<Instr>(new BinaryOpInstr(
base2, base1, iv2.step, iv2.op)); // base += step
}
}
}
}
});
map_use(f, mp_reg);
remove_unused_def(f);
}
| 37.163636
| 80
| 0.429305
|
kylinsoft
|
191cddd5415bab0a4e1557200a8ec1ed88edf626
| 17,000
|
cpp
|
C++
|
libpvkernel/src/rush/PVFormatVersion.cpp
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
libpvkernel/src/rush/PVFormatVersion.cpp
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
libpvkernel/src/rush/PVFormatVersion.cpp
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
//
// MIT License
//
// © ESI Group, 2015
//
// 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 <pvkernel/rush/PVFormatVersion.h>
#include <pvkernel/rush/PVFormat_types.h>
#include <cassert>
#include <QChar>
#include <QDomNode>
#include <QString>
#include <QStringList>
// Utility function to convert pre 7 format to 7 format.for mapping/type/plotting
static QString const get_type_from_format(QString const& type_attr, QString const& mapped_attr)
{
if (type_attr == "integer" and mapped_attr == "unsigned")
return "number_uint32";
else if (type_attr == "integer" and mapped_attr == "hexadecimal")
return "number_uint32";
else if (type_attr == "integer" and mapped_attr == "octal")
return "number_uint32";
else if (type_attr == "integer" and mapped_attr == "default")
return "number_int32";
else if (type_attr == "host" and mapped_attr == "default")
return "string";
else if (type_attr == "enum" and mapped_attr == "default")
return "string";
else if (type_attr == "float")
return "number_float";
return type_attr;
}
static QString const get_mapped_from_format(QString const& type_attr, QString const& mapped_attr)
{
if (type_attr == "integer" and mapped_attr == "unsigned")
return "default";
else if (type_attr == "integer" and mapped_attr == "hexadecimal")
return "default";
else if (type_attr == "integer" and mapped_attr == "octal")
return "default";
else if (type_attr == "integer" and mapped_attr == "default")
return "default";
else if (type_attr == "host" and mapped_attr == "default")
return "host";
else if (type_attr == "enum" and mapped_attr == "default")
return "default";
else if (type_attr == "string" and mapped_attr == "default")
return "string";
else if (type_attr == "ipv4" and mapped_attr == "uniform")
return "default";
return mapped_attr;
}
static QString const get_plotted_from_format(QString const& type_attr,
QString const& mapped_attr,
QString const& plotted_attr)
{
if (type_attr == "enum")
return "enum";
else if (type_attr == "ipv4" and mapped_attr == "uniform")
return "enum";
else if (plotted_attr == "minmax")
return "default";
return plotted_attr;
}
QString PVRush::PVFormatVersion::__impl::get_version(QDomDocument const& doc)
{
return doc.documentElement().attribute("version", "0");
}
void PVRush::PVFormatVersion::to_current(QDomDocument& doc)
{
QString version = __impl::get_version(doc);
if (version == "0") {
__impl::from0to1(doc);
version = "1";
}
if (version == "1") {
__impl::from1to2(doc);
version = "2";
}
if (version == "2") {
__impl::from2to3(doc);
version = "3";
}
if (version == "3") {
__impl::from3to4(doc);
version = "4";
}
if (version == "4") {
__impl::from4to5(doc);
version = "5";
}
if (version == "5") {
__impl::from5to6(doc);
version = "6";
}
if (version == "6") {
__impl::from6to7(doc);
version = "7";
}
if (version == "7") {
__impl::from7to8(doc);
version = "8";
}
if (version == "8") {
__impl::from8to9(doc);
version = "9";
}
if (version == "9") {
__impl::from9to10(doc);
version = "10";
}
}
void PVRush::PVFormatVersion::__impl::from0to1(QDomDocument& doc)
{
_rec_0to1(doc.documentElement());
doc.documentElement().setAttribute("version", "1");
}
void PVRush::PVFormatVersion::__impl::from1to2(QDomDocument& doc)
{
_rec_1to2(doc.documentElement());
doc.documentElement().setAttribute("version", "2");
}
void PVRush::PVFormatVersion::__impl::from2to3(QDomDocument& doc)
{
_rec_2to3(doc.documentElement());
doc.documentElement().setAttribute("version", "3");
}
void PVRush::PVFormatVersion::__impl::from3to4(QDomDocument& doc)
{
_rec_3to4(doc.documentElement());
doc.documentElement().setAttribute("version", "4");
}
void PVRush::PVFormatVersion::__impl::from4to5(QDomDocument& doc)
{
_rec_4to5(doc.documentElement());
doc.documentElement().setAttribute("version", "5");
}
void PVRush::PVFormatVersion::__impl::from5to6(QDomDocument& doc)
{
_rec_5to6(doc.documentElement());
doc.documentElement().setAttribute("version", "6");
}
void PVRush::PVFormatVersion::__impl::from7to8(QDomDocument& doc)
{
QDomNodeList splitter = doc.documentElement().elementsByTagName("splitter");
for (int i = 0; i < splitter.size(); i++) {
QDomElement ax = splitter.at(i).toElement();
// Update type value
QString type = ax.attribute("type");
if (type != "url") {
continue;
}
std::vector<int> pos(10, -1);
auto fields = ax.childNodes();
for (int j = 0; j < fields.size(); j++) {
QDomElement axis = fields.at(j).namedItem("axis").toElement();
if (axis.isNull()) {
// Field without axis is like "no field" in url splitter
continue;
}
QString tag = axis.attribute("tag");
if (tag.contains("protocol")) {
pos[j] = 0;
} else if (tag.contains("subdomain")) {
pos[j] = 1;
} else if (tag.contains("host")) {
pos[j] = 2;
} else if (tag.contains("domain")) {
pos[j] = 3;
} else if (tag.contains("tld")) {
pos[j] = 4;
} else if (tag.contains("port")) {
pos[j] = 5;
} else if (tag.contains("url-variables")) {
pos[j] = 7;
} else if (tag.contains("url-credentials")) {
pos[j] = 9;
} else if (tag.contains("url-anchor")) {
pos[j] = 8;
} else {
assert(tag == "url");
// CHeck it at the end to avoid mismatch with variables, cred...
pos[j] = 6;
}
}
QDomElement new_splitter = ax.ownerDocument().createElement("splitter");
new_splitter.setAttribute("type", "url");
for (int p : pos) {
if (p == -1) {
QDomElement new_field = ax.ownerDocument().createElement("field");
new_splitter.appendChild(new_field);
} else {
new_splitter.appendChild(fields.at(p).cloneNode());
}
}
splitter.at(i).parentNode().replaceChild(new_splitter, splitter.at(i));
}
QDomNodeList axis = doc.documentElement().elementsByTagName("axis");
for (int i = 0; i < axis.size(); i++) {
QDomElement ax = axis.at(i).toElement();
ax.removeAttribute("tag");
ax.removeAttribute("key");
ax.removeAttribute("group");
}
doc.documentElement().setAttribute("version", "8");
}
void PVRush::PVFormatVersion::__impl::from8to9(QDomDocument& doc)
{
QDomNodeList converters = doc.documentElement().elementsByTagName("converter");
for (int i = 0; i < converters.size(); i++) {
QDomElement converter = converters.at(i).toElement();
if (converter.attribute("type") != "substitution") {
continue;
}
converter.setAttribute("modes", 1);
converter.setAttribute("substrings_map", "");
converter.setAttribute("invert_order", false);
}
doc.documentElement().setAttribute("version", "9");
}
void PVRush::PVFormatVersion::__impl::from9to10(QDomDocument& doc)
{
QDomNodeList axis = doc.documentElement().elementsByTagName("axis");
for (int i = 0; i < axis.size(); i++) {
QDomElement ax = axis.at(i).toElement();
// Limit the choice of port plotting to uint16
QDomElement plotted = ax.namedItem("plotting").toElement();
QString plotting = plotted.attribute("mode");
if (plotting == "port") {
ax.setAttribute("type", "number_uint16");
}
}
doc.documentElement().setAttribute("version", "10");
}
void PVRush::PVFormatVersion::__impl::from6to7(QDomDocument& doc)
{
QDomNodeList axis = doc.documentElement().elementsByTagName("axis");
for (int i = 0; i < axis.size(); i++) {
QDomElement ax = axis.at(i).toElement();
// Update type value
QString type = ax.attribute("type");
if (type.isNull()) {
type = "string";
}
// Update mapping value
QDomElement mapped = ax.namedItem("mapping").toElement();
QString mapping = mapped.attribute("mode");
if (mapping.isNull()) {
mapping = "default";
}
// Update plotting value
QDomElement plotted = ax.namedItem("plotting").toElement();
QString plotting = plotted.attribute("mode");
if (plotting.isNull()) {
plotting = "default";
}
plotted.toElement().setAttribute("mode", get_plotted_from_format(type, mapping, plotting));
mapped.toElement().setAttribute("mode", get_mapped_from_format(type, mapping));
ax.setAttribute("type", get_type_from_format(type, mapping));
// Update type_format
if (mapping == "hexadecimal") {
ax.toElement().setAttribute("type_format", "%#x");
} else if (mapping == "octal") {
ax.toElement().setAttribute("type_format", "%#o");
}
// Remove extra mapped node
auto mappings = ax.elementsByTagName("mapping");
for (int j = 1; j < mappings.count(); j++) {
ax.removeChild(mappings.at(j));
}
// Remove extra plotted node
auto plottings = ax.elementsByTagName("plotting");
for (int j = 1; j < plottings.count(); j++) {
ax.removeChild(plottings.at(j));
}
// Remove time-sample attribute
ax.removeAttribute("time-sample");
}
doc.documentElement().setAttribute("version", "7");
}
void PVRush::PVFormatVersion::__impl::_rec_0to1(QDomElement elt)
{
QString const& tag_name = elt.tagName();
if (tag_name == "RegEx") {
elt.setTagName("splitter");
elt.setAttribute("type", "regexp");
elt.setAttribute("regexp", elt.attribute("expression"));
elt.removeAttribute("expression");
} else if (tag_name == "url") {
elt.setTagName("splitter");
elt.setAttribute("type", "url");
} else if (tag_name == "csv") {
elt.setTagName("splitter");
elt.setAttribute("type", "csv");
elt.setAttribute("sep", elt.attribute("delimiter"));
elt.removeAttribute("delimiter");
} else if (tag_name == "filter") {
if (elt.attribute("type") == "include") {
elt.setAttribute("reverse", "0");
} else {
elt.setAttribute("reverse", "1");
}
elt.setAttribute("type", "regexp");
elt.setAttribute("regexp", elt.attribute("expression"));
elt.removeAttribute("expression");
elt.removeAttribute("type");
}
QDomNodeList children = elt.childNodes();
for (int i = 0; i < children.size(); i++) {
_rec_0to1(children.at(i).toElement());
}
}
void PVRush::PVFormatVersion::__impl::_rec_1to2(QDomElement elt)
{
QString const& tag_name = elt.tagName();
static QStringList tags = QStringList() << "protocol"
<< "domain"
<< "tld"
<< "port"
<< "url"
<< "url-variables";
static QStringList plottings = QStringList() << "default"
<< "default"
<< "default"
<< "port"
<< "minmax"
<< "minmax";
if (tag_name == "splitter") {
QString type = elt.attribute("type", "");
if (type == "url") {
// Set default axes tags and plottings
QDomNodeList children = elt.childNodes();
for (unsigned int i = 0; i < 6; i++) {
QDomElement c_elt = children.at(i).toElement();
if (c_elt.tagName() == "field") {
// Take the axis
QDomElement axis = c_elt.firstChildElement("axis");
// and set the default tag
axis.setAttribute("tag", tags[i]);
axis.setAttribute("plotting", plottings[i]);
}
}
} else if (type == "regexp") {
// Default dehavioru was to match the regular expression somewhere in the line
elt.setAttribute("full-line", "false");
}
} else if (tag_name == "axis") {
bool is_key = elt.attribute("key", "false") == "true";
if (is_key) {
QString cur_tag = elt.attribute("tag");
if (!cur_tag.isEmpty()) {
cur_tag += QString(QChar(':')) + "key";
} else {
cur_tag = "key";
}
elt.setAttribute("tag", cur_tag);
}
elt.removeAttribute("key");
}
QDomNodeList children = elt.childNodes();
for (int i = 0; i < children.size(); i++) {
_rec_1to2(children.at(i).toElement());
}
}
void PVRush::PVFormatVersion::__impl::_rec_2to3(QDomElement elt)
{
QString const& tag_name = elt.tagName();
if (tag_name == "axis") {
QString plotting = elt.attribute("plotting", "");
QString type = elt.attribute("type", "");
if (type != "time" && type != "ipv4" && plotting == "minmax") {
// minmax is now default. if default was not minmax, it was only relevant for the time
// and ipv4
elt.setAttribute("plotting", "default");
}
}
QDomNodeList children = elt.childNodes();
for (int i = 0; i < children.size(); i++) {
_rec_2to3(children.at(i).toElement());
}
}
void PVRush::PVFormatVersion::__impl::_rec_3to4(QDomNode node)
{
if (node.isElement()) {
QDomElement elt = node.toElement();
if (elt.tagName() == "axis") {
QString mapping = elt.attribute("mapping", "");
QString plotting = elt.attribute("plotting", "");
QString type = elt.attribute("type", "");
QDomElement elt_mapping = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_MAPPING);
elt_mapping.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, mapping);
if (type == "time") {
elt_mapping.setAttribute("time-format", QLatin1String("@PVTimeFormat(") +
elt.attribute("time-format", "") +
QLatin1String(")"));
elt.removeAttribute("time-format");
}
elt.appendChild(elt_mapping);
QDomElement elt_plotting = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_PLOTTING);
elt_plotting.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, plotting);
elt.appendChild(elt_plotting);
elt.removeAttribute("mapping");
elt.removeAttribute("plotting");
}
}
QDomNode child = node.firstChild();
while (!child.isNull()) {
_rec_3to4(child);
child = child.nextSibling();
}
}
void PVRush::PVFormatVersion::__impl::_rec_4to5(QDomNode node)
{
if (node.isElement()) {
QDomElement elt = node.toElement();
if (elt.tagName() == "mapping") {
QString tf = elt.attribute("time-format", QString());
if (tf.size() > 0 && tf.startsWith("@PVTimeFormat(")) {
tf = tf.mid(14, tf.size() - 15);
elt.setAttribute("time-format", tf);
}
QString cl = elt.attribute("convert-lowercase", QString());
if (cl.size() > 0 && cl.startsWith("@Bool(")) {
cl = cl.mid(6, cl.size() - 7);
elt.setAttribute("convert-lowercase", cl);
}
}
if (elt.tagName() == "splitter") {
QString sep = elt.attribute("sep", QString());
if (sep.size() > 0 && sep.startsWith("@Char(")) {
sep = sep.mid(6, sep.size() - 7);
elt.setAttribute("sep", sep);
}
}
}
QDomNode child = node.firstChild();
while (!child.isNull()) {
_rec_4to5(child);
child = child.nextSibling();
}
}
void PVRush::PVFormatVersion::__impl::_rec_5to6(QDomNode node)
{
if (node.isElement()) {
QDomElement elt = node.toElement();
if (elt.tagName() == "mapping") {
QString tf = elt.attribute("time-format", QString());
if (tf.size() > 0) {
QDomElement axis_node = node.parentNode().toElement();
axis_node.setAttribute("type_format", tf);
elt.removeAttribute("time-format");
}
} else if (elt.tagName() == "axis") {
// Move mapping from attribute to node
QString mapping = elt.attribute("mapping", QString());
QDomElement mapping_node = node.ownerDocument().createElement("mapping");
mapping_node.setAttribute("mode", mapping);
elt.appendChild(mapping_node);
elt.removeAttribute("mapping");
// Move plotting from attribute to node
QString plotting = elt.attribute("plotting", QString());
QDomElement plotting_node = node.ownerDocument().createElement("plotting");
plotting_node.setAttribute("mode", plotting);
elt.appendChild(plotting_node);
elt.removeAttribute("plotting");
// Move axis/time-format to axis/mapping/type_format
QString tf = elt.attribute("time-format", QString());
if (tf.size() > 0) {
QDomElement axis_node = node.toElement();
axis_node.setAttribute("type_format", tf);
}
elt.removeAttribute("time-format");
}
}
QDomNode child = node.firstChild();
while (!child.isNull()) {
_rec_5to6(child);
child = child.nextSibling();
}
}
| 31.25
| 97
| 0.644059
|
inendi-inspector
|
191f35d1a71135b003818c6fa2e94660e7bac8ad
| 2,089
|
cpp
|
C++
|
lab4/code/main_mpi.cpp
|
ankurshaswat/COL380
|
5c54f629d3709214f9e082aa5cd9449d14848e1c
|
[
"MIT"
] | null | null | null |
lab4/code/main_mpi.cpp
|
ankurshaswat/COL380
|
5c54f629d3709214f9e082aa5cd9449d14848e1c
|
[
"MIT"
] | null | null | null |
lab4/code/main_mpi.cpp
|
ankurshaswat/COL380
|
5c54f629d3709214f9e082aa5cd9449d14848e1c
|
[
"MIT"
] | null | null | null |
#include "lab4_io.h"
#include "lab4_mpi.h"
#include <stdlib.h>
#include "mpi.h"
/*
Arguments:
arg: input filename (consist text, pattern_set)
*/
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("\nLess Arguments\n");
return 0;
}
if (argc > 2)
{
printf("\nTOO many Arguments\n");
return 0;
}
//---------------------------------------------------------------------
int n; // length of text (input)
char *text; // text (input)
int num_patterns; // #patterns to be searched in the text (input)
int *m_set; // lengths of patterns in pattern_set (input)
int *p_set; // periods of patterns in pattern_set (input)
char **pattern_set; // set of patterns to be searched (input)
int *match_counts; // #match of pattern_i in text (to be computed)
int *matches; // set of all match of each pattern_i in text (to be computed)
//---------------------------------------------------------------------
double start_time, computation_time, total_time;
int id;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
/*
-- Pre-defined function --
reads input text and patterns from input file and creats array text, m_set, p_set and pattern_set
see lab4_io.h for details
*/
// if (id == 0)
read_data(argv[1], &n, &text, &num_patterns, &m_set, &p_set, &pattern_set);
start_time = MPI_Wtime();
// /*
// *****************************************************
// TODO -- You must implement this two function
// *****************************************************
// */
periodic_pattern_matching(
n,
text,
num_patterns,
m_set,
p_set,
pattern_set,
&match_counts,
&matches);
computation_time = MPI_Wtime() - start_time;
MPI_Reduce(&computation_time, &total_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if (id == 0)
{
/*
--Pre-defined function --
checks for correctness of results computed by periodic_pattern_matching
and outputs the results
*/
write_result(match_counts, matches, total_time);
format_checker(num_patterns, match_counts, matches);
}
MPI_Finalize();
return 0;
}
| 24.011494
| 99
| 0.594064
|
ankurshaswat
|
191fe62fb000c162bdae37ea3e70df3729d30c11
| 9,164
|
cpp
|
C++
|
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
|
hinnie123/qpang-essence-emulator-1
|
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
|
[
"MIT"
] | 1
|
2021-11-23T00:31:46.000Z
|
2021-11-23T00:31:46.000Z
|
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
|
hinnie123/qpang-essence-emulator-1
|
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
|
[
"MIT"
] | null | null | null |
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
|
hinnie123/qpang-essence-emulator-1
|
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
|
[
"MIT"
] | 1
|
2021-12-18T12:50:46.000Z
|
2021-12-18T12:50:46.000Z
|
#include "PlayerWeaponManager.h"
#include "qpang/Game.h"
#include "qpang/room/session/RoomSession.h"
#include "qpang/room/tnl/net_events/client/cg_weapon.hpp"
#include "qpang/room/tnl/net_events/server/gc_weapon.hpp"
#include "qpang/room/tnl/net_events/server/gc_respawn.hpp"
#include "qpang/room/tnl/net_events/server/gc_game_item.hpp"
#include "qpang/room/tnl/net_events/server/gc_essence.hpp"
constexpr auto RIFLE_INDEX = 0;
PlayerWeaponManager::PlayerWeaponManager() :
m_selectedWeaponIndex(0),
m_previousSelectedWeaponIndex(0),
m_hasEquippedMachineGun(false),
m_equippedMachineGunSeqId(0)
{
}
void PlayerWeaponManager::initialize(const std::shared_ptr<RoomSessionPlayer>& player)
{
m_player = player;
auto* equipmentManager = player->getPlayer()->getEquipmentManager();
const auto itemIds = equipmentManager->getWeaponItemIdsByCharacter(player->getCharacter());
const auto isMeleeOnly = player->getRoomSession()->getRoom()->isMeleeOnly();
for (int i = 0; i < itemIds.size(); i++)
{
const auto weapon = Game::instance()->getWeaponManager()->get(itemIds[i]);
if (isMeleeOnly)
{
// melee weapon
if (i == 3)
{
m_weapons[3] = weapon;
}
}
else
{
m_weapons[i] = weapon;
}
auto& [first, second] = m_defaultAmmo[weapon.itemId];
first = weapon.clipCount + equipmentManager->getExtraAmmoForWeaponIndex(i);
second = weapon.clipSize;
}
m_selectedWeaponIndex = 3;
}
Weapon PlayerWeaponManager::getSelectedWeapon()
{
return m_weapons[m_selectedWeaponIndex];
}
void PlayerWeaponManager::selectTagWeapon()
{
m_previousSelectedWeaponIndex = m_selectedWeaponIndex;
m_selectedWeaponIndex = RIFLE_INDEX;
m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex];
const auto chainLightWeapon = Game::instance()->getWeaponManager()->get(WEAPON_PREY_CHAIN_LIGHT);
m_weapons[RIFLE_INDEX] = chainLightWeapon;
auto& [first, second] = m_defaultAmmo[chainLightWeapon.itemId];
first = chainLightWeapon.clipCount;
second = chainLightWeapon.clipSize;
refillCurrentWeapon();
switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false);
}
void PlayerWeaponManager::deselectTagWeapon()
{
m_weapons[RIFLE_INDEX] = m_currentRifleWeapon;
m_selectedWeaponIndex = m_previousSelectedWeaponIndex;
switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false);
reset();
}
void PlayerWeaponManager::reset()
{
const auto player = m_player.lock();
if (player == nullptr)
return;
// ReSharper disable once CppUseStructuredBinding
for (auto& weapon : m_weapons)
{
const auto [first, second] = m_defaultAmmo[weapon.itemId];
weapon.clipCount = first;
weapon.clipSize = second;
player->post(new GCGameItem(14, { {1191182337, 1} }, weapon.itemId));
}
}
void PlayerWeaponManager::reload(const uint32_t seqId)
{
m_weapons[m_selectedWeaponIndex].clipCount--;
m_weapons[m_selectedWeaponIndex].clipSize = m_defaultAmmo[getSelectedWeapon().itemId].second;
if (const auto player = m_player.lock(); player != nullptr)
player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 3, m_weapons[m_selectedWeaponIndex].itemId, seqId);
}
void PlayerWeaponManager::shoot(uint32_t entityId)
{
m_weapons[m_selectedWeaponIndex].clipSize--;
}
bool PlayerWeaponManager::canReload()
{
return m_weapons[m_selectedWeaponIndex].clipCount > 0;
}
bool PlayerWeaponManager::canShoot()
{
if (isHoldingMelee())
{
return true;
}
return m_weapons[m_selectedWeaponIndex].clipSize > 0;
}
bool PlayerWeaponManager::hasWeapon(uint32_t weaponId) const
{
return std::find_if(m_weapons.cbegin(), m_weapons.cend(),
[weaponId](const Weapon& weapon)
{
return weapon.itemId == weaponId;
}
) != m_weapons.cend();
}
void PlayerWeaponManager::switchWeapon(uint32_t weaponId, bool isReloadGlitchEnabled)
{
if (!isReloadGlitchEnabled)
{
if (m_weapons[m_selectedWeaponIndex].itemId == weaponId)
{
// already chose this weapon
return;
}
}
for (size_t i = 0; i < m_weapons.size(); i++)
{
if (m_weapons[i].itemId == weaponId)
{
m_selectedWeaponIndex = i;
break;
}
}
if (const auto player = m_player.lock(); player != nullptr)
{
player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 0, m_weapons[m_selectedWeaponIndex].itemId, 0);
player->post(new GCWeapon(player->getPlayer()->getId(), 5, m_weapons[m_selectedWeaponIndex].itemId, 0));
}
}
void PlayerWeaponManager::refillWeapon(const uint32_t weaponId)
{
const auto [first, second] = m_defaultAmmo[weaponId];
m_weapons[m_selectedWeaponIndex].clipCount = first;
m_weapons[m_selectedWeaponIndex].clipSize = second;
if (const auto player = m_player.lock(); player != nullptr)
{
player->post(new GCGameItem(
14,
std::vector({ GCGameItem::Item{1191182337, 0x01, 0x00, 0x00, 0x00} }),
weaponId
));
}
}
void PlayerWeaponManager::refillCurrentWeapon()
{
const auto itemId = getSelectedWeapon().itemId;
refillWeapon(itemId);
}
std::array<uint32_t, 4> PlayerWeaponManager::getWeaponIds()
{
std::array<uint32_t, 4> weaponIds{};
for (size_t i = 0; i < m_weapons.size(); i++)
{
weaponIds[i] = m_weapons[i].itemId;
}
return weaponIds;
}
std::array<Weapon, 4> PlayerWeaponManager::getWeapons() const
{
return m_weapons;
}
bool PlayerWeaponManager::hasEquippedMachineGun() const
{
return m_hasEquippedMachineGun;
}
uint64_t PlayerWeaponManager::getEquippedMachineGunSeqId() const
{
return m_equippedMachineGunSeqId;
}
void PlayerWeaponManager::equipMachineGun(const uint64_t seqId)
{
// If the player attempts to equip the machine gun whilst already equipping a machine gun, disallow it.
if (m_hasEquippedMachineGun)
{
return;
}
// Check if the seqId is a valid sequence id.
if (seqId < 1 || seqId > 4)
{
return;
}
// TODO: Perhaps check if the player is "in range" of the machine gun (by seq id).
// TODO: Check if the machine gun with the seq id is already taken by another player.
if (const auto player = m_player.lock(); player != nullptr)
{
if (player->getSkillManager()->hasActiveSkill())
{
return;
}
// Disallow the machine gun in public enemy mode for now.
if (player->getRoomSession()->getGameMode()->isPublicEnemyMode())
{
player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode.");
return;
}
// Let client know the player is shooting with ground zero gun.
player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::EQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, seqId);
// Allow client to shoot.
player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::ENABLE_SHOOTING, WEAPON_MACHINE_GUN, seqId);
// Save the currently selected weapon index.
m_previousSelectedWeaponIndex = m_selectedWeaponIndex;
// Set the currently selected weapon index to gun.
m_selectedWeaponIndex = 0;
// Set the current gun weapon to the current weapon.
m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex];
const auto machineGunWeapon = Game::instance()->getWeaponManager()->get(WEAPON_MACHINE_GUN);
m_weapons[0] = machineGunWeapon;
auto& [first, second] = m_defaultAmmo[machineGunWeapon.itemId];
first = machineGunWeapon.clipCount;
second = machineGunWeapon.clipSize;
refillCurrentWeapon();
switchWeapon(machineGunWeapon.itemId, false);
m_hasEquippedMachineGun = true;
m_equippedMachineGunSeqId = seqId;
}
}
void PlayerWeaponManager::unequipMachineGun()
{
// If the player does not have a machine gun equipped, do not allow them to unequip one.
if (!m_hasEquippedMachineGun)
{
return;
}
if (const auto player = m_player.lock(); player != nullptr)
{
// Disallow the machine gun in public enemy mode for now.
if (player->getRoomSession()->getGameMode()->isPublicEnemyMode())
{
player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode.");
return;
}
player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::UNEQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, m_equippedMachineGunSeqId);
m_weapons[0] = m_currentRifleWeapon;
m_selectedWeaponIndex = m_previousSelectedWeaponIndex;
switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false);
m_hasEquippedMachineGun = false;
m_equippedMachineGunSeqId = 0;
}
}
void PlayerWeaponManager::equipRainbowSkillCardWeapon(uint32_t weaponId)
{
m_previousSelectedWeaponIndex = m_selectedWeaponIndex;
m_selectedWeaponIndex = RIFLE_INDEX;
m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex];
const auto weapon = Game::instance()->getWeaponManager()->get(weaponId);
m_weapons[RIFLE_INDEX] = weapon;
auto& [first, second] = m_defaultAmmo[weapon.itemId];
first = weapon.clipCount;
second = weapon.clipSize;
refillCurrentWeapon();
switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false);
}
void PlayerWeaponManager::unequipRainbowSkillCardWeapon()
{
m_weapons[RIFLE_INDEX] = m_currentRifleWeapon;
m_selectedWeaponIndex = m_previousSelectedWeaponIndex;
switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false);
reset();
}
bool PlayerWeaponManager::isHoldingMelee() const
{
return m_selectedWeaponIndex == 3;
}
| 25.669468
| 164
| 0.748691
|
hinnie123
|
19202436500c1a6eb406fc35dc9d3f49f8601c6d
| 6,361
|
cpp
|
C++
|
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-15T01:14:15.000Z
|
2019-07-15T01:14:15.000Z
|
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 76
|
2018-10-27T16:59:36.000Z
|
2022-03-30T17:40:39.000Z
|
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-29T02:02:08.000Z
|
2019-07-29T02:02:08.000Z
|
#include "../../include/graphics/animation/CMeshAnimatorComponent.h"
#include <tuple>
namespace TDEngine2
{
static const std::string ComponentTypeName = "mesh_animator";
const std::string CMeshAnimatorComponent::mPositionJointChannelPattern = "joint_{0}.position";
const std::string CMeshAnimatorComponent::mRotationJointChannelPattern = "joint_{0}.rotation";
const std::string& CMeshAnimatorComponent::GetPositionJointChannelPattern()
{
return mPositionJointChannelPattern;
}
const std::string& CMeshAnimatorComponent::GetRotationJointChannelPattern()
{
return mRotationJointChannelPattern;
}
const std::string& CMeshAnimatorComponent::GetComponentTypeName()
{
return ComponentTypeName;
}
CMeshAnimatorComponent::CMeshAnimatorComponent() :
CBaseComponent()
{
}
E_RESULT_CODE CMeshAnimatorComponent::Init()
{
if (mIsInitialized)
{
return RC_FAIL;
}
mIsDirty = true;
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CMeshAnimatorComponent::Load(IArchiveReader* pReader)
{
if (!pReader)
{
return RC_FAIL;
}
return RC_OK;
}
E_RESULT_CODE CMeshAnimatorComponent::Save(IArchiveWriter* pWriter)
{
if (!pWriter)
{
return RC_FAIL;
}
pWriter->BeginGroup("component");
{
pWriter->SetUInt32("type_id", static_cast<U32>(CMeshAnimatorComponent::GetTypeId()));
}
pWriter->EndGroup();
return RC_OK;
}
void CMeshAnimatorComponent::SetDirtyFlag(bool value)
{
mIsDirty = value;
}
bool CMeshAnimatorComponent::IsDirty() const
{
return mIsDirty;
}
CMeshAnimatorComponent::TJointsMap& CMeshAnimatorComponent::GetJointsTable()
{
return mJointsTable;
}
CMeshAnimatorComponent::TJointPose& CMeshAnimatorComponent::GetCurrAnimationPose()
{
return mCurrAnimationPose;
}
const std::vector<TVector3>& CMeshAnimatorComponent::GetJointPositionsArray() const
{
return mJointsCurrPositions;
}
const std::vector<TQuaternion>& CMeshAnimatorComponent::GetJointRotationsArray() const
{
return mJointsCurrRotation;
}
enum class E_JOINT_PROPERTY_TYPE : U8
{
POSITION, ROTATION
};
static std::tuple<std::string, E_JOINT_PROPERTY_TYPE> GetJointInfoFromProperty(const std::string& propertyId)
{
auto p0 = propertyId.find_first_of('_') + 1;
auto p1 = propertyId.find_first_of('.');
return { propertyId.substr(p0, p1 - p0), propertyId.substr(p1 + 1) == "position" ? E_JOINT_PROPERTY_TYPE::POSITION : E_JOINT_PROPERTY_TYPE::ROTATION };
}
IPropertyWrapperPtr CMeshAnimatorComponent::GetProperty(const std::string& propertyName)
{
auto&& properties = GetAllProperties();
if (std::find_if(properties.cbegin(), properties.cend(), [&propertyName](const std::string& id) { return propertyName == id; }) == properties.cend())
{
return CBaseComponent::GetProperty(propertyName);
}
std::string jointId;
E_JOINT_PROPERTY_TYPE propertyType;
std::tie(jointId, propertyType) = GetJointInfoFromProperty(propertyName);
switch (propertyType)
{
case E_JOINT_PROPERTY_TYPE::POSITION:
return IPropertyWrapperPtr(CBasePropertyWrapper<TVector3>::Create([this, jointId](const TVector3& pos) { _setPositionForJoint(jointId, pos); return RC_OK; }, nullptr));
case E_JOINT_PROPERTY_TYPE::ROTATION:
return IPropertyWrapperPtr(CBasePropertyWrapper<TQuaternion>::Create([this, jointId](const TQuaternion& rot) { _setRotationForJoint(jointId, rot); return RC_OK; }, nullptr));
}
return CBaseComponent::GetProperty(propertyName);
}
const std::vector<std::string>& CMeshAnimatorComponent::GetAllProperties() const
{
static std::vector<std::string> properties;
if (properties.size() / 2 == mJointsTable.size())
{
return properties;
}
properties.clear();
for (auto&& currJointEntity : mJointsTable)
{
properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mPositionJointChannelPattern, currJointEntity.first));
properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mRotationJointChannelPattern, currJointEntity.first));
}
return properties;
}
const std::string& CMeshAnimatorComponent::GetTypeName() const
{
return ComponentTypeName;
}
void CMeshAnimatorComponent::_setPositionForJoint(const std::string& jointId, const TVector3& position)
{
auto it = mJointsTable.find(jointId);
if (it == mJointsTable.cend())
{
TDE2_ASSERT(false);
return;
}
if (static_cast<U32>(mJointsCurrPositions.size()) <= it->second)
{
mJointsCurrPositions.resize(it->second + 1);
}
mJointsCurrPositions[it->second] = position;
mIsDirty = true;
}
void CMeshAnimatorComponent::_setRotationForJoint(const std::string& jointId, const TQuaternion& rotation)
{
auto it = mJointsTable.find(jointId);
if (it == mJointsTable.cend())
{
TDE2_ASSERT(false);
return;
}
if (static_cast<U32>(mJointsCurrRotation.size()) <= it->second)
{
mJointsCurrRotation.resize(it->second + 1);
}
mJointsCurrRotation[it->second] = rotation;
mIsDirty = true;
}
IComponent* CreateMeshAnimatorComponent(E_RESULT_CODE& result)
{
return CREATE_IMPL(IComponent, CMeshAnimatorComponent, result);
}
CMeshAnimatorComponentFactory::CMeshAnimatorComponentFactory() :
CBaseObject()
{
}
E_RESULT_CODE CMeshAnimatorComponentFactory::Init()
{
if (mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = true;
return RC_OK;
}
E_RESULT_CODE CMeshAnimatorComponentFactory::Free()
{
if (!mIsInitialized)
{
return RC_FAIL;
}
mIsInitialized = false;
delete this;
return RC_OK;
}
IComponent* CMeshAnimatorComponentFactory::Create(const TBaseComponentParameters* pParams) const
{
if (!pParams)
{
return nullptr;
}
const TMeshAnimatorComponentParameters* pAnimatorParams = static_cast<const TMeshAnimatorComponentParameters*>(pParams);
E_RESULT_CODE result = RC_OK;
return CreateMeshAnimatorComponent(result);
}
IComponent* CMeshAnimatorComponentFactory::CreateDefault(const TBaseComponentParameters& params) const
{
E_RESULT_CODE result = RC_OK;
return CreateMeshAnimatorComponent(result);
}
TypeId CMeshAnimatorComponentFactory::GetComponentTypeId() const
{
return CMeshAnimatorComponent::GetTypeId();
}
IComponentFactory* CreateMeshAnimatorComponentFactory(E_RESULT_CODE& result)
{
return CREATE_IMPL(IComponentFactory, CMeshAnimatorComponentFactory, result);
}
}
| 23.047101
| 178
| 0.748782
|
bnoazx005
|
1921e6547eacf6dd5f124f74def4dd1d03fa4150
| 1,602
|
cpp
|
C++
|
19A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
19A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
19A.cpp
|
felikjunvianto/kfile-codeforces-submissions
|
1b53da27a294a12063b0912e12ad32efe24af678
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
typedef struct{string name;int poin,scored,missed;} team;
string tim[111];
char mska[50],mskb[50],dummy;
int N,x,ida,idb,a,b;
team ans[111];
bool cfscore(team i,team j)
{
if(i.poin!=j.poin) return(i.poin>j.poin);
if(i.scored-i.missed!=j.scored-j.missed) return(i.scored-i.missed>j.scored-j.missed);
if(i.scored!=j.scored) return(i.scored>j.scored);
return(i.name<j.name);
}
bool cfname(team i,team j)
{
return(i.name<j.name);
}
int main()
{
scanf("%d",&N);
for(x=0;x<N;x++)
{
scanf("%s",mska);
tim[x]=mska;
}
sort(tim,tim+N);
for(x=0;x<N;x++) ans[x]=(team){tim[x],0,0,0};
for(x=1;2*x<=N*(N-1);x++)
{
getchar();
scanf("%[^-]%c%s %d:%d",mska,&dummy,mskb,&a,&b);
ida=lower_bound(tim,tim+N,mska)-tim;
idb=lower_bound(tim,tim+N,mskb)-tim;
ans[ida].scored+=a,ans[ida].missed+=b;
ans[idb].scored+=b,ans[idb].missed+=a;
if(a==b) ans[ida].poin++,ans[idb].poin++; else
if(a>b) ans[ida].poin+=3; else ans[idb].poin+=3;
}
sort(ans,ans+N,cfscore);
sort(ans,ans+(N/2),cfname);
for(x=0;2*x<N;x++) printf("%s\n",ans[x].name.c_str());
return 0;
}
| 20.805195
| 87
| 0.615481
|
felikjunvianto
|
192792ac79a3b689427d4827807f3490eaf2a12b
| 1,443
|
cc
|
C++
|
raytracing/geometry.cc
|
jpanikulam/experiments
|
be36319a89f8baee54d7fa7618b885edb7025478
|
[
"MIT"
] | 1
|
2019-04-14T11:40:28.000Z
|
2019-04-14T11:40:28.000Z
|
raytracing/geometry.cc
|
IJDykeman/experiments-1
|
22badf166b2ea441e953939463f751020b8c251b
|
[
"MIT"
] | 5
|
2018-04-18T13:54:29.000Z
|
2019-08-22T20:04:17.000Z
|
raytracing/geometry.cc
|
IJDykeman/experiments-1
|
22badf166b2ea441e953939463f751020b8c251b
|
[
"MIT"
] | 1
|
2018-12-24T03:45:47.000Z
|
2018-12-24T03:45:47.000Z
|
#include "geometry.hh"
namespace raytrace {
using Vec2 = Eigen::Vector2d;
double cross2d(const Vec2 &a, const Vec2 &b) {
return (a(0) * b(1)) - (a(1) * b(0));
}
bool ray_line_intersection(const Ray &ray, const Line &line, Out<Vec2> intersection) {
Eigen::Matrix2d A;
A.col(0) = ray.direction;
A.col(1) = -line.direction;
const Vec2 b = line.point - ray.origin;
const Eigen::ColPivHouseholderQR<Eigen::Matrix2d> qr = A.colPivHouseholderQr();
// This takes FOREVER to compile (I guess Eigen inlines the whole operation?)
// Lines are parallel
if (qr.absDeterminant() < 1e-3) {
return false;
}
const Vec2 soln = qr.solve(b);
*intersection = soln(0) * ray.direction + ray.origin;
// Ray pointing the wrong direction
if (soln(0) < 0.0) {
return false;
}
return true;
}
bool ray_line_segment_intersection(const Ray &ray, const LineSegment &segment, Out<Vec2> intersection) {
const Line temp_line(segment.start, segment.end - segment.start);
const bool valid_intersection = ray_line_intersection(ray, temp_line, intersection);
if (valid_intersection) {
const double half_space_start = (*intersection - segment.start).dot(temp_line.direction);
const double half_space_end = (*intersection - segment.end).dot(temp_line.direction);
if ((half_space_start > 0.0) && (half_space_end < 0.0)) {
return true;
}
}
return false;
}
}
| 28.294118
| 104
| 0.668053
|
jpanikulam
|
192db529428201d58d905a62921de0c632fa449b
| 1,927
|
cc
|
C++
|
cpp/src/arrow/compute/exec/accumulation_queue.cc
|
AlvinJ15/arrow
|
095179f8a38f99e2eb10a59ad7e71252d8491e8f
|
[
"Apache-2.0"
] | 1
|
2021-11-24T04:43:52.000Z
|
2021-11-24T04:43:52.000Z
|
cpp/src/arrow/compute/exec/accumulation_queue.cc
|
AlvinJ15/arrow
|
095179f8a38f99e2eb10a59ad7e71252d8491e8f
|
[
"Apache-2.0"
] | null | null | null |
cpp/src/arrow/compute/exec/accumulation_queue.cc
|
AlvinJ15/arrow
|
095179f8a38f99e2eb10a59ad7e71252d8491e8f
|
[
"Apache-2.0"
] | null | null | null |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "arrow/compute/exec/accumulation_queue.h"
#include <iterator>
namespace arrow {
namespace util {
using arrow::compute::ExecBatch;
AccumulationQueue::AccumulationQueue(AccumulationQueue&& that) {
this->batches_ = std::move(that.batches_);
this->row_count_ = that.row_count_;
that.Clear();
}
AccumulationQueue& AccumulationQueue::operator=(AccumulationQueue&& that) {
this->batches_ = std::move(that.batches_);
this->row_count_ = that.row_count_;
that.Clear();
return *this;
}
void AccumulationQueue::Concatenate(AccumulationQueue&& that) {
this->batches_.reserve(this->batches_.size() + that.batches_.size());
std::move(that.batches_.begin(), that.batches_.end(),
std::back_inserter(this->batches_));
this->row_count_ += that.row_count_;
that.Clear();
}
void AccumulationQueue::InsertBatch(ExecBatch batch) {
row_count_ += batch.length;
batches_.emplace_back(std::move(batch));
}
void AccumulationQueue::Clear() {
row_count_ = 0;
batches_.clear();
}
ExecBatch& AccumulationQueue::operator[](size_t i) { return batches_[i]; }
} // namespace util
} // namespace arrow
| 32.661017
| 75
| 0.737416
|
AlvinJ15
|
192ee663eb16a798a38f768cb86e6c158d838f2a
| 88
|
cpp
|
C++
|
problemsets/Codeforces/C++/C1360.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
problemsets/Codeforces/C++/C1360.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
problemsets/Codeforces/C++/C1360.cpp
|
juarezpaulino/coderemite
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
[
"Apache-2.0"
] | null | null | null |
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
| 12.571429
| 38
| 0.625
|
juarezpaulino
|
192fa1261098731268c3405b3a731b39d25d8a31
| 847
|
cpp
|
C++
|
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
|
medismailben/llvm-project
|
e334a839032fe500c3bba22bf976ab7af13ce1c1
|
[
"Apache-2.0"
] | 3,102
|
2015-01-04T02:28:35.000Z
|
2022-03-30T12:53:41.000Z
|
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
|
medismailben/llvm-project
|
e334a839032fe500c3bba22bf976ab7af13ce1c1
|
[
"Apache-2.0"
] | 3,740
|
2019-01-23T15:36:48.000Z
|
2022-03-31T22:01:13.000Z
|
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
|
medismailben/llvm-project
|
e334a839032fe500c3bba22bf976ab7af13ce1c1
|
[
"Apache-2.0"
] | 1,868
|
2015-01-03T04:27:11.000Z
|
2022-03-25T13:37:35.000Z
|
// RUN: %clang_cc1 -std=c++1z -verify %s
[[disable_tail_calls, noduplicate]] void f() {} // expected-warning {{unknown attribute 'disable_tail_calls'}} expected-warning {{unknown attribute 'noduplicate'}}
[[using clang: disable_tail_calls, noduplicate]] void g() {} // ok
[[using]] extern int n; // expected-error {{expected identifier}}
[[using foo
] // expected-error {{expected ':'}}
] extern int n;
[[using 42:]] extern int n; // expected-error {{expected identifier}}
[[using clang:]] extern int n; // ok
[[using blah: clang::optnone]] extern int n; // expected-error {{attribute with scope specifier cannot follow}} expected-warning {{only applies to functions}}
[[using clang: unknown_attr]] extern int n; // expected-warning {{unknown attribute}}
[[using unknown_ns: something]] extern int n; // expected-warning {{unknown attribute}}
| 49.823529
| 163
| 0.707202
|
medismailben
|
1930b9cdd5fdfc4442f2e9abf0c26280cc8f2787
| 196
|
cpp
|
C++
|
10.10-span0/main.cpp
|
andreasfertig/programming-with-cpp20
|
7c70351f3a46aea295e964096be77eb159be6e9f
|
[
"MIT"
] | 107
|
2021-04-13T12:43:06.000Z
|
2022-03-30T05:07:16.000Z
|
10.10-span0/main.cpp
|
jessesimpson/programming-with-cpp20
|
7c70351f3a46aea295e964096be77eb159be6e9f
|
[
"MIT"
] | 1
|
2021-04-13T12:59:30.000Z
|
2021-04-13T13:02:55.000Z
|
10.10-span0/main.cpp
|
jessesimpson/programming-with-cpp20
|
7c70351f3a46aea295e964096be77eb159be6e9f
|
[
"MIT"
] | 29
|
2021-04-13T18:07:03.000Z
|
2022-03-28T13:44:01.000Z
|
// Copyright (c) Andreas Fertig.
// SPDX-License-Identifier: MIT
#include <cstddef>
template<typename T>
class Span {
T* mData;
size_t mSize;
public:
// constructors
};
int main() {}
| 13.066667
| 32
| 0.658163
|
andreasfertig
|
1931129329fd5b84da776098dce6603e6732fe41
| 20,685
|
cpp
|
C++
|
vtkdiff.cpp
|
ufz/vtkdiff
|
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
|
[
"BSD-4-Clause"
] | 1
|
2021-03-08T00:35:07.000Z
|
2021-03-08T00:35:07.000Z
|
vtkdiff.cpp
|
ufz/vtkdiff
|
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
|
[
"BSD-4-Clause"
] | 3
|
2015-06-05T13:09:05.000Z
|
2016-09-26T19:50:16.000Z
|
vtkdiff.cpp
|
ufz/vtkdiff
|
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
|
[
"BSD-4-Clause"
] | 5
|
2016-06-01T15:32:56.000Z
|
2022-03-20T04:22:30.000Z
|
/**
* \copyright
* Copyright (c) 2015-2020, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*/
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <ios>
#include <iterator>
#include <sstream>
#include <tuple>
#include <type_traits>
#include <tclap/CmdLine.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkCommand.h>
#include <vtkDataArray.h>
#include <vtkDoubleArray.h>
#include <vtkPointData.h>
#include <vtkSmartPointer.h>
#include <vtkUnstructuredGrid.h>
#include <vtkVersion.h>
#include <vtkXMLUnstructuredGridReader.h>
template <typename T>
auto float_to_string(T const& v) -> std::string
{
static_assert(std::is_floating_point<T>::value,
"float_to_string requires a floating point input type.");
std::stringstream double_eps_sstream;
double_eps_sstream << std::scientific << std::setprecision(16) << v;
return double_eps_sstream.str();
}
bool stringEndsWith(std::string const& str, std::string const& ending)
{
if (str.length() < ending.length())
return false;
// now the difference is non-negative, no underflow possible.
auto const string_end_length = str.length() - ending.length();
return str.compare(string_end_length, ending.length(), ending) == 0;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> const& vector)
{
if (vector.empty())
{
return os << "[]";
}
// print first n-1 elements
os << "[";
std::size_t const size = vector.size();
for (std::size_t i = 0; i < size - 1; ++i)
{
os << vector[i] << ", ";
}
return os << vector.back() << "]";
}
struct Args
{
bool const quiet;
bool const verbose;
bool const meshcheck;
double const abs_err_thr;
double const rel_err_thr;
std::string const vtk_input_a;
std::string const vtk_input_b;
std::string const data_array_a;
std::string const data_array_b;
};
auto parseCommandLine(int argc, char* argv[]) -> Args
{
TCLAP::CmdLine cmd(
"VtkDiff software.\n"
"Copyright (c) 2015-2021, OpenGeoSys Community "
"(http://www.opengeosys.org) "
"Distributed under a Modified BSD License. "
"See accompanying file LICENSE.txt or "
"http://www.opengeosys.org/project/license",
' ',
"0.1");
TCLAP::UnlabeledValueArg<std::string> vtk_input_a_arg(
"input-file-a",
"Path to the VTK unstructured grid input file.",
true,
"",
"VTK FILE");
cmd.add(vtk_input_a_arg);
TCLAP::UnlabeledValueArg<std::string> vtk_input_b_arg(
"input-file-b",
"Path to the second VTK unstructured grid input file.",
false,
"",
"VTK FILE");
cmd.add(vtk_input_b_arg);
TCLAP::ValueArg<std::string> data_array_a_arg(
"a", "first_data_array", "First data array name for comparison", true,
"", "NAME");
TCLAP::ValueArg<std::string> data_array_b_arg(
"b",
"second_data_array",
"Second data array name for comparison",
false,
"",
"NAME");
cmd.add(data_array_b_arg);
TCLAP::SwitchArg meshcheck_arg(
"m", "mesh_check", "Compare mesh geometries using absolute tolerance.");
cmd.xorAdd(data_array_a_arg, meshcheck_arg);
TCLAP::SwitchArg quiet_arg("q", "quiet", "Suppress all but error output.");
cmd.add(quiet_arg);
TCLAP::SwitchArg verbose_arg("v", "verbose",
"Also print which values differ.");
cmd.add(verbose_arg);
auto const double_eps_string =
float_to_string(std::numeric_limits<double>::epsilon());
TCLAP::ValueArg<double> abs_err_thr_arg(
"",
"abs",
"Tolerance for the absolute error in the maximum norm (" +
double_eps_string + ")",
false,
std::numeric_limits<double>::epsilon(),
"FLOAT");
cmd.add(abs_err_thr_arg);
TCLAP::ValueArg<double> rel_err_thr_arg(
"",
"rel",
"Tolerance for the componentwise relative error (" + double_eps_string +
")",
false,
std::numeric_limits<double>::epsilon(),
"FLOAT");
cmd.add(rel_err_thr_arg);
cmd.parse(argc, argv);
return Args{quiet_arg.getValue(), verbose_arg.getValue(),
meshcheck_arg.getValue(), abs_err_thr_arg.getValue(),
rel_err_thr_arg.getValue(), vtk_input_a_arg.getValue(),
vtk_input_b_arg.getValue(), data_array_a_arg.getValue(),
data_array_b_arg.getValue()};
}
template <typename T>
class ErrorCallback : public vtkCommand
{
public:
vtkTypeMacro(ErrorCallback, vtkCommand);
static ErrorCallback<T>* New() { return new ErrorCallback<T>; }
void Execute(vtkObject* caller, unsigned long vtkNotUsed(eventId),
void* callData) override
{
auto* reader = static_cast<T*>(caller);
std::cerr << "Error reading file `" << reader->GetFileName() << "'\n"
<< static_cast<char*>(callData) << "\nAborting." << std::endl;
std::exit(2);
}
};
vtkSmartPointer<vtkUnstructuredGrid> readMesh(std::string const& filename)
{
if (filename.empty())
{
return nullptr;
}
if (!stringEndsWith(filename, ".vtu"))
{
std::cerr << "Error: Expected a file with .vtu extension."
<< "File '" << filename << "' not read.";
return nullptr;
}
vtkSmartPointer<ErrorCallback<vtkXMLUnstructuredGridReader>> errorCallback =
vtkSmartPointer<ErrorCallback<vtkXMLUnstructuredGridReader>>::New();
vtkSmartPointer<vtkXMLUnstructuredGridReader> reader =
vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
reader->AddObserver(vtkCommand::ErrorEvent, errorCallback);
reader->SetFileName(filename.c_str());
reader->Update();
return reader->GetOutput();
}
std::tuple<vtkSmartPointer<vtkUnstructuredGrid>,
vtkSmartPointer<vtkUnstructuredGrid>>
readMeshes(std::string const& file_a_name, std::string const& file_b_name)
{
return {readMesh(file_a_name), readMesh(file_b_name)};
}
std::tuple<bool, vtkSmartPointer<vtkDataArray>, vtkSmartPointer<vtkDataArray>>
readDataArraysFromMeshes(
std::tuple<vtkSmartPointer<vtkUnstructuredGrid>,
vtkSmartPointer<vtkUnstructuredGrid>> const& meshes,
std::string const& data_array_a_name,
std::string const& data_array_b_name)
{
if (std::get<0>(meshes) == nullptr)
{
std::cerr << "First mesh was not read correctly and is a nullptr.\n";
return {false, nullptr, nullptr};
}
bool point_data(false);
if (std::get<0>(meshes)->GetPointData()->HasArray(
data_array_a_name.c_str()))
{
point_data = true;
}
else if (std::get<0>(meshes)->GetCellData()->HasArray(
data_array_a_name.c_str()))
{
point_data = false;
}
else
{
std::cerr << "Error: Scalars data array "
<< "\'" << data_array_a_name.c_str() << "\'"
<< " neither found in point data nor in cell data.\n";
return std::make_tuple(false, nullptr, nullptr);
}
// Get arrays
vtkSmartPointer<vtkDataArray> a;
if (point_data)
{
a = vtkSmartPointer<vtkDataArray>{
std::get<0>(meshes)->GetPointData()->GetScalars(
data_array_a_name.c_str())};
}
else
{
a = vtkSmartPointer<vtkDataArray>{
std::get<0>(meshes)->GetCellData()->GetScalars(
data_array_a_name.c_str())};
}
// Check arrays' validity
if (!a)
{
std::cerr << "Error: Scalars data array "
<< "\'" << data_array_a_name.c_str() << "\'"
<< " could not be read.\n";
return std::make_tuple(false, nullptr, nullptr);
}
vtkSmartPointer<vtkDataArray> b;
if (std::get<1>(meshes) == nullptr)
{
if (data_array_a_name == data_array_b_name)
{
std::cerr << "Error: You are trying to compare data array `"
<< data_array_a_name
<< "' from first file to itself. Aborting.\n";
std::exit(3);
}
if (point_data)
{
b = vtkSmartPointer<vtkDataArray>{
std::get<0>(meshes)->GetPointData()->GetScalars(
data_array_b_name.c_str())};
}
else
{
b = vtkSmartPointer<vtkDataArray>{
std::get<0>(meshes)->GetCellData()->GetScalars(
data_array_b_name.c_str())};
}
}
else
{
if (point_data)
{
b = vtkSmartPointer<vtkDataArray>{
std::get<1>(meshes)->GetPointData()->GetScalars(
data_array_b_name.c_str())};
}
else
{
b = vtkSmartPointer<vtkDataArray>{
std::get<1>(meshes)->GetCellData()->GetScalars(
data_array_b_name.c_str())};
}
}
if (!b)
{
std::cerr << "Error: Scalars data array "
<< "\'" << data_array_b_name.c_str() << "\'"
<< " not found.\n";
return std::make_tuple(false, nullptr, nullptr);
}
return std::make_tuple(true, a, b);
}
bool compareCellTopology(vtkCellArray* const cells_a,
vtkCellArray* const cells_b)
{
vtkIdType const n_cells_a{cells_a->GetNumberOfCells()};
vtkIdType const n_cells_b{cells_b->GetNumberOfCells()};
if (n_cells_a != n_cells_b)
{
std::cerr << "Number of cells in the first mesh is " << n_cells_a
<< " and differs from the number of cells in the second "
"mesh, which is "
<< n_cells_b << "\n";
return false;
}
vtkIdType n_cell_points_a, n_cell_points_b;
#if (VTK_MAJOR_VERSION > 8 || VTK_MINOR_VERSION == 90)
const vtkIdType *cell_points_a, *cell_points_b;
#else
vtkIdType *cell_points_a, *cell_points_b;
#endif
cells_a->InitTraversal();
cells_b->InitTraversal();
int get_next_cell_a = cells_a->GetNextCell(n_cell_points_a, cell_points_a);
int get_next_cell_b = cells_b->GetNextCell(n_cell_points_b, cell_points_b);
int cell_number = 0;
while (get_next_cell_a == 1 && get_next_cell_b == 1)
{
if (n_cell_points_a != n_cell_points_b)
{
std::cerr << "Cell " << cell_number << " in first input has "
<< n_cell_points_a << " points but in the second input "
<< n_cell_points_b << " points.\n";
}
for (vtkIdType i = 0; i < n_cell_points_a; ++i)
{
if (cell_points_a[i] != cell_points_b[i])
{
std::cerr << "Point " << i << " of cell " << cell_number
<< " has id " << cell_points_a[i]
<< " in the first input but id " << cell_points_b[i]
<< " in the second input.\n";
return false;
}
}
get_next_cell_a = cells_a->GetNextCell(n_cell_points_a, cell_points_a);
get_next_cell_b = cells_b->GetNextCell(n_cell_points_b, cell_points_b);
cell_number++;
}
if (get_next_cell_a != 0)
{
std::cerr << "Unexpected return value (" << get_next_cell_a
<< ") for cells_a->GetNextCell() call. Expected 0 for "
"end-of-list or 1 for no error.\n";
return false;
}
if (get_next_cell_b != 0)
{
std::cerr << "Unexpected return value (" << get_next_cell_b
<< ") for cells_b->GetNextCell() call. Expected 0 for "
"end-of-list or 1 for no error.\n";
return false;
}
return true;
}
bool comparePoints(vtkPoints* const points_a, vtkPoints* const points_b,
double const eps_squared)
{
vtkIdType const n_points_a{points_a->GetNumberOfPoints()};
vtkIdType const n_points_b{points_b->GetNumberOfPoints()};
if (n_points_a != n_points_b)
{
std::cerr << "Number of points in the first mesh is " << n_points_a
<< " and differst from the number of point in the second "
"mesh, which is "
<< n_points_b << "\n";
return false;
}
for (vtkIdType p = 0; p < n_points_a; ++p)
{
auto const a = points_a->GetPoint(p);
auto const b = points_b->GetPoint(p);
double const distance2 = vtkMath::Distance2BetweenPoints(a, b);
if (distance2 >= eps_squared)
{
std::cerr << "Point " << p << " with coordinates (" << a[0] << ", "
<< a[1] << ", " << a[2]
<< ") from the first mesh is significantly different "
"from the same point in the second mesh, which "
"has coordinates ("
<< b[0] << ", " << b[1] << ", " << b[2]
<< ") with distance between them " << std::sqrt(distance2)
<< "\n";
return false;
}
}
return true;
}
int main(int argc, char* argv[])
{
auto const digits10 = std::numeric_limits<double>::digits10;
auto const args = parseCommandLine(argc, argv);
// Setup the standard output and error stream numerical formats.
std::cout << std::scientific << std::setprecision(digits10);
std::cerr << std::scientific << std::setprecision(digits10);
auto meshes = readMeshes(args.vtk_input_a, args.vtk_input_b);
if (args.meshcheck)
{
if (args.vtk_input_a == args.vtk_input_b)
{
std::cout << "Will not compare meshes from same input file.\n";
return EXIT_SUCCESS;
}
if (!comparePoints(std::get<0>(meshes)->GetPoints(),
std::get<1>(meshes)->GetPoints(),
args.abs_err_thr * args.abs_err_thr))
{
std::cerr << "Error in mesh points' comparison occured.\n";
return EXIT_FAILURE;
}
if (!compareCellTopology(std::get<0>(meshes)->GetCells(),
std::get<1>(meshes)->GetCells()))
{
std::cerr << "Error in cells' topology comparison occured.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// Read arrays from input file.
bool read_successful;
vtkSmartPointer<vtkDataArray> a;
vtkSmartPointer<vtkDataArray> b;
std::tie(read_successful, a, b) =
readDataArraysFromMeshes(meshes, args.data_array_a, args.data_array_b);
if (!read_successful)
return EXIT_FAILURE;
if (!args.quiet)
std::cout << "Comparing data array `" << args.data_array_a
<< "' from file `" << args.vtk_input_a << "' to data array `"
<< args.data_array_b << "' from file `" << args.vtk_input_b
<< "'.\n";
// Check similarity of the data arrays.
// Is numeric
if (!a->IsNumeric())
{
std::cerr << "Data in data array a is not numeric:\n"
<< "data type is " << a->GetDataTypeAsString() << "\n";
return EXIT_FAILURE;
}
if (!b->IsNumeric())
{
std::cerr << "Data in data array b is not numeric.\n"
<< "data type is " << b->GetDataTypeAsString() << "\n";
return EXIT_FAILURE;
}
auto const num_tuples = a->GetNumberOfTuples();
// Number of components
if (num_tuples != b->GetNumberOfTuples())
{
std::cerr << "Number of tuples differ:\n"
<< num_tuples << " in data array a and "
<< b->GetNumberOfTuples() << " in data array b\n";
return EXIT_FAILURE;
}
auto const num_components = a->GetNumberOfComponents();
// Number of components
if (num_components != b->GetNumberOfComponents())
{
std::cerr << "Number of components differ:\n"
<< num_components << " in data array a and "
<< b->GetNumberOfComponents() << " in data array b\n";
return EXIT_FAILURE;
}
// Calculate difference of the data arrays.
// Absolute error and norms.
std::vector<double> abs_err_norm_l1(num_components);
std::vector<double> abs_err_norm_2_2(num_components);
std::vector<double> abs_err_norm_max(num_components);
// Relative error and norms.
std::vector<double> rel_err_norm_l1(num_components);
std::vector<double> rel_err_norm_2_2(num_components);
std::vector<double> rel_err_norm_max(num_components);
for (auto tuple_idx = 0; tuple_idx < num_tuples; ++tuple_idx)
{
for (auto component_idx = 0; component_idx < num_components;
++component_idx)
{
auto const a_comp = a->GetComponent(tuple_idx, component_idx);
auto const b_comp = b->GetComponent(tuple_idx, component_idx);
auto const abs_err = std::abs(a_comp - b_comp);
abs_err_norm_l1[component_idx] += abs_err;
abs_err_norm_2_2[component_idx] += abs_err * abs_err;
abs_err_norm_max[component_idx] =
std::max(abs_err_norm_max[component_idx], abs_err);
// relative error and its norms:
double rel_err;
if (abs_err == 0.0)
{
rel_err = 0.0;
}
else if (a_comp == 0.0 || b_comp == 0.0)
{
rel_err = std::numeric_limits<double>::infinity();
}
else
{
rel_err =
abs_err / std::min(std::abs(a_comp), std::abs(b_comp));
}
rel_err_norm_l1[component_idx] += rel_err;
rel_err_norm_2_2[component_idx] += rel_err * rel_err;
rel_err_norm_max[component_idx] =
std::max(rel_err_norm_max[component_idx], rel_err);
if (abs_err > args.abs_err_thr && rel_err > args.rel_err_thr &&
args.verbose)
{
std::cout << "tuple: " << std::setw(4) << tuple_idx
<< "component: " << std::setw(2) << component_idx
<< ": abs err = " << std::setw(digits10 + 7)
<< abs_err
<< ", rel err = " << std::setw(digits10 + 7)
<< rel_err << "\n";
}
}
}
// Error information
if (!args.quiet)
{
std::cout << "Computed difference between data arrays:\n";
std::cout << "abs l1 norm = " << abs_err_norm_l1 << "\n";
std::cout << "abs l2-norm^2 = " << abs_err_norm_2_2 << "\n";
// temporary squared norm vector for output.
std::vector<double> abs_err_norm_2;
std::transform(std::begin(abs_err_norm_2_2), std::end(abs_err_norm_2_2),
std::back_inserter(abs_err_norm_2),
[](double x) { return std::sqrt(x); });
std::cout << "abs l2-norm = " << abs_err_norm_2 << "\n";
std::cout << "abs maximum norm = " << abs_err_norm_max << "\n";
std::cout << "\n";
std::cout << "rel l1 norm = " << rel_err_norm_l1 << "\n";
std::cout << "rel l2-norm^2 = " << rel_err_norm_2_2 << "\n";
// temporary squared norm vector for output.
std::vector<double> rel_err_norm_2;
std::transform(std::begin(rel_err_norm_2_2), std::end(rel_err_norm_2_2),
std::back_inserter(rel_err_norm_2),
[](double x) { return std::sqrt(x); });
std::cout << "rel l2-norm = " << rel_err_norm_2_2 << "\n";
std::cout << "rel maximum norm = " << rel_err_norm_max << "\n";
}
if (*std::max_element(abs_err_norm_max.begin(), abs_err_norm_max.end()) >
args.abs_err_thr &&
*std::max_element(rel_err_norm_max.begin(), rel_err_norm_max.end()) >
args.rel_err_thr)
{
if (!args.quiet)
std::cout << "Absolute and relative error (maximum norm) are larger"
" than the corresponding thresholds "
<< args.abs_err_thr << " and " << args.rel_err_thr
<< ".\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 33.096
| 80
| 0.562388
|
ufz
|
19312e28c17a1befa02f080f5fd4c09660436f0f
| 209
|
cpp
|
C++
|
src/algorithm_list.cpp
|
GoncaloFDS/Lift
|
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
|
[
"BSD-3-Clause"
] | 30
|
2019-07-24T09:58:22.000Z
|
2021-09-03T08:20:22.000Z
|
src/algorithm_list.cpp
|
GoncaloFDS/Lift
|
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
|
[
"BSD-3-Clause"
] | 15
|
2020-06-20T13:20:50.000Z
|
2021-04-26T16:05:33.000Z
|
src/algorithm_list.cpp
|
GoncaloFDS/Lift
|
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
|
[
"BSD-3-Clause"
] | 5
|
2020-06-17T08:38:34.000Z
|
2021-09-08T22:14:02.000Z
|
#include "algorithm_list.h"
const std::vector<std::pair<std::string, Algorithm>> AlgorithmList::all_algorithms = {
{"Path Tracing", Algorithm::PT},
{"Bidirectional Path Tracing", Algorithm::BDPT},
};
| 29.857143
| 86
| 0.703349
|
GoncaloFDS
|
193544cc9f9e2b529c13ba814c29132be07d032b
| 2,331
|
hpp
|
C++
|
src/cpu/rtweekend.hpp
|
DveloperY0115/ray-tracing-in-one-weekend-cpp
|
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
|
[
"MIT"
] | 1
|
2021-02-18T08:38:21.000Z
|
2021-02-18T08:38:21.000Z
|
src/cpu/rtweekend.hpp
|
DveloperY0115/ray-tracing-in-one-weekend-cpp
|
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
|
[
"MIT"
] | 1
|
2021-02-13T04:42:01.000Z
|
2021-02-13T04:42:01.000Z
|
src/cpu/rtweekend.hpp
|
DveloperY0115/ray-tracing-in-one-weekend-cpp
|
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
|
[
"MIT"
] | null | null | null |
//
// Created by 유승우 on 2020/05/15.
//
#ifndef FIRSTRAYTRACER_RTWEEKEND_HPP
#define FIRSTRAYTRACER_RTWEEKEND_HPP
#include <cmath>
#include <cstdlib>
#include <limits>
#include <memory>
#include <random>
#include <time.h>
// using statements to make codes more simple
using std::shared_ptr;
using std::make_shared;
using std::sqrt;
// Constants
const double infinity = std::numeric_limits<double>::infinity();
const double pi = 3.1415926535897932385;
// Utility Functions
/**
* Clamps the value 'x' to the interval specified by ['min', 'max']
*
* If 'x' is smaller than the lower bound 'min', it's clamped to the value 'min'
* else if 'x' is greater than the upper bound 'max', it's clamped to the value 'max',
* otherwise 'x' retains its own value since it doesn't needed to be clamped
*
* @param x a double type value that is needed to be clamped
* @param min the lower bound of the interval
* @param max the upper bound of the interval
* @return clamped value
*/
inline double clamp(double x, double min, double max)
{
if (x < min) return min;
if (x > max) return max;
return x;
}
/**
* Generates a double type random number whose value lies between 0.0 and 1.0.
* @return a double type value between 0.0 and 1.0
*/
inline double random_double()
{
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
static std::mt19937 generator;
return distribution(generator);
}
/*
inline double random_double()
{
// Returns a random real number in [0, 1).
return rand() / (RAND_MAX + 1.0);
}
*/
/**
* Generates a double type random number whose value lies between 'min' and 'max'
*
* @param min the lower bound for a desired random number
* @param max the upper bound for a desired random number
* @return a double type randomly generated number within the interval ['min', 'max']
*/
inline double random_double(double min, double max)
{
// Returns a random real number in [min, max)
return min + (max-min)*random_double();
}
/**
* Converts the angle represented in degrees to radian
*
* @param degrees an angle in degrees
* @return same angle but in radian
*/
inline double degress_to_radians(double degrees)
{
return degrees * (pi / 180);
}
// Common Headers
#include "ray.hpp"
#include "vector3.hpp"
#endif //FIRSTRAYTRACER_RTWEEKEND_HPP
| 24.536842
| 86
| 0.703561
|
DveloperY0115
|
1937294b0fbbd690599e20cd5d73e9c10dce5c45
| 1,839
|
tpp
|
C++
|
include/Sirius/Math/Matrix/Matrix2.tpp
|
xam4lor/Sirius
|
f05a89538ab2bc79a8d46f482fbb060271adce0a
|
[
"MIT"
] | 1
|
2021-07-12T11:53:06.000Z
|
2021-07-12T11:53:06.000Z
|
include/Sirius/Math/Matrix/Matrix2.tpp
|
xam4lor/Sirius
|
f05a89538ab2bc79a8d46f482fbb060271adce0a
|
[
"MIT"
] | null | null | null |
include/Sirius/Math/Matrix/Matrix2.tpp
|
xam4lor/Sirius
|
f05a89538ab2bc79a8d46f482fbb060271adce0a
|
[
"MIT"
] | 1
|
2021-07-12T11:51:53.000Z
|
2021-07-12T11:51:53.000Z
|
#include "Matrix2.hpp"
namespace Sirius
{
template<typename T>
constexpr Matrix<2, T> operator+(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2)
{
return Matrix<2, T>(mat1[0] + mat2[0], mat1[1] + mat2[1]);
}
template<typename T>
constexpr Matrix<2, T> operator-(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2)
{
return Matrix<2, T>(mat1[0] - mat2[0], mat1[1] - mat2[1]);
}
template<typename T>
constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat, T scalar)
{
return { mat[0] * scalar, mat[1] * scalar };
}
template<typename T>
constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2)
{
return { mat1[0][0] * mat2[0][0] + mat1[1][0] * mat2[0][1],
mat1[0][1] * mat2[0][0] + mat1[1][1] * mat2[0][1],
mat1[0][0] * mat2[1][0] + mat1[1][0] * mat2[1][1],
mat1[0][1] * mat2[1][0] + mat1[1][1] * mat2[1][1] };
}
template<typename T>
constexpr Vector<2, T> operator*(const Matrix<2, T>& mat, const Vector<2, T>& vec)
{
return { mat[0][0] * vec.x + mat[1][0] * vec.y,
mat[0][1] * vec.x + mat[1][1] * vec.y };
}
}
template <typename T>
struct fmt::formatter<Sirius::Matrix<2, T>>
{
constexpr auto parse(format_parse_context& ctx)
{
return ctx.end();
}
template <typename Context>
auto format(const Sirius::Matrix<2, T>& mat, Context& ctx)
{
return format_to(ctx.out(), "\n\t[{} {}]\n\t[{} {}]", mat[0][0], mat[1][0], mat[0][1], mat[1][1]);
}
};
template<typename T>
std::ostream& operator<<(std::ostream& out, const Sirius::Matrix<2, T>& mat)
{
return out << "[" << mat[0][0] << " " << mat[1][0]
<< "]\n[" << mat[0][1] << " " << mat[1][1] << "]";
}
| 29.66129
| 106
| 0.516041
|
xam4lor
|
193898f97013de96c717a848897f6a54e2d1b516
| 17,785
|
cpp
|
C++
|
co-op/CmdVector.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | 67
|
2018-03-02T10:50:02.000Z
|
2022-03-23T18:20:29.000Z
|
co-op/CmdVector.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | null | null | null |
co-op/CmdVector.cpp
|
BartoszMilewski/CodeCoop
|
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
|
[
"MIT"
] | 9
|
2018-03-01T16:38:28.000Z
|
2021-03-02T16:17:09.000Z
|
//----------------------------------
// (c) Reliable Software 1997 - 2008
//----------------------------------
#include "precompiled.h"
#include "CmdVector.h"
#include "Commander.h"
// Code Co-op Commands
namespace Cmd
{
const Cmd::Item<Commander> Table [] =
{
{ "Program_Update", &Commander::Program_Update, 0, "Check for Co-op updates on the Internet" },
{ "Program_Options", &Commander::Program_Options, 0, "View/Change program options" },
{ "Program_Dispatching", &Commander::Program_Dispatching, 0, "View/Change script dispatching options" },
{ "Program_Licensing", &Commander::Program_Licensing, 0, "Go to Web site to purchase license(s)" },
{ "Program_About", &Commander::Program_About, 0, "About this program" },
{ "Program_Exit", &Commander::Program_Exit, 0, "Exit program" },
{ "Project_Visit", &Commander::Project_Visit, &Commander::can_Project_Visit, "Visit another project on this machine" },
{ "Project_Move", &Commander::Project_Move, &Commander::can_Project_Move, "Move project tree to another location" },
{ "Project_Repair", &Commander::Project_Repair, &Commander::can_Project_Repair, "Repair project file(s)" },
{ "Project_RequestVerification", &Commander::Project_RequestVerification, &Commander::can_Project_RequestVerification, "Request project verification data from some other project member" },
{ "Project_VerifyRootPaths",&Commander::Project_VerifyRootPaths,0, "Check if all projects have a valid root path" },
{ "Project_Join", &Commander::Project_Join, 0, "Join an existing project" },
{ "Project_Invite", &Commander::Project_Invite, &Commander::can_Project_Invite, "Invite someone to join your project" },
{ "Project_OpenInvitation", &Commander::Project_OpenInvitation, 0, "Download project invitation" },
{ "Project_New", &Commander::Project_New, 0, "Start a new project" },
{ "Project_Branch", &Commander::Project_Branch, &Commander::can_Project_Branch, "Start a branch project" },
{ "Project_Export", &Commander::Project_Export, &Commander::can_Project_Export, "Export project files and folders" },
{ "Project_Members", &Commander::Project_Members, &Commander::can_Project_Members, "List/Edit project members' info" },
{ "Project_Defect", &Commander::Project_Defect, &Commander::can_Project_Defect, "Rescind your membership in this project" },
{ "Project_Admin", &Commander::Project_Admin, &Commander::can_Project_Admin, "Emergency project administrator election" },
{ "Project_Options", &Commander::Project_Options, &Commander::can_Project_Options, "View/Change project options" },
{ "Project_AddMoreFiles", &Commander::Project_AddMoreFiles, &Commander::can_Project_AddMoreFiles,"Add more files to the project" },
{ "Project_NewFromHistory", &Commander::Project_NewFromHistory, &Commander::can_Project_NewFromHistory,"Start a new project from previously exported history" },
{ "History_Export", &Commander::History_ExportHistory, &Commander::can_History_Export, "Export project history" },
{ "History_Import", &Commander::History_ImportHistory, &Commander::can_History_Import, "Import project history" },
{ "History_AddLabel", &Commander::History_AddLabel, &Commander::can_History_AddLabel, "Label project version" },
{ "View_Back", &Commander::View_Back, &Commander::can_View_Back, "Navigate back" },
{ "View_Forward", &Commander::View_Forward, &Commander::can_View_Forward, "Navigate forward" },
{ "View_Home", &Commander::View_Home, &Commander::can_View_Home, "Navigate home" },
{ "View_Refresh", &Commander::View_Refresh, &Commander::can_View_Refresh, "Update displayed information" },
{ "View_ApplyFileFilter", &Commander::View_ApplyFileFilter, &Commander::can_View_ApplyFileFilter,"Apply file filter" },
{ "View_ChangeFileFilter", &Commander::View_ChangeFileFilter, &Commander::can_View_ChangeFileFilter,"Change file filter" },
{ "View_Browser", &Commander::View_Browser, &Commander::can_View_Browser, "View web page" },
{ "View_Files", &Commander::View_Files, &Commander::can_View_Files, "Browse through files in the project" },
{ "View_Mailbox", &Commander::View_Mailbox, &Commander::can_View_Mailbox, "Look at outgoing/incoming scripts" },
{ "View_CheckIn", &Commander::View_CheckIn, &Commander::can_View_CheckIn, "Look at checked-out files" },
{ "View_Synch", &Commander::View_Synch, &Commander::can_View_Synch, "Look at files changed by the sync" },
{ "View_History", &Commander::View_History, &Commander::can_View_History, "Look at the history of the project" },
{ "View_Projects", &Commander::View_Projects, &Commander::can_View_Projects, "Look at projects present on this machine" },
{ "View_MergeProjects", &Commander::View_MergeProjects, &Commander::can_View_MergeProjects, "Open project merge view" },
{ "View_Project_Folders", &Commander::View_Hierarchy, &Commander::can_View_Hierarchy, "Show a hierarchical view panel for the current list" },
{ "View_Active_Projects", &Commander::View_Active_Projects, &Commander::can_View_Active_Projects,"Show active projects (projects with checked out files or incoming scripts)" },
{ "View_Next", &Commander::View_Next, 0, "" },
{ "View_Previous", &Commander::View_Previous, 0, "" },
{ "View_ClosePage", &Commander::View_ClosePage, &Commander::can_View_ClosePage, "Close page" },
{ "ChangeFilter", &Commander::ChangeFilter, 0, "" },
{ "GoBack", &Commander::GoBack, 0, "" },
{ "Folder_GoUp", &Commander::Folder_GoUp, &Commander::can_Folder_GoUp, "Go to parent folder" },
{ "Folder_GotoRoot", &Commander::Folder_GotoRoot, &Commander::can_Folder_GotoRoot, "Go to project's root folder" },
{ "Folder_NewFile", &Commander::Folder_NewFile, &Commander::can_Folder_NewFile, "Create a new file in the project" },
{ "Folder_NewFolder", &Commander::Folder_NewFolder, &Commander::can_Folder_NewFolder, "Create a new folder in the project" },
{ "Folder_AddMoreFiles", &Commander::Folder_AddMoreFiles, &Commander::can_Folder_AddMoreFiles,"Add more files to the project from the current folder" },
{ "Folder_Wikify", &Commander::Folder_Wikify, &Commander::can_Folder_Wikify, "Turn current folder into a wiki site" },
{ "Folder_ExportHtml", &Commander::Folder_ExportHtml, &Commander::can_Folder_ExportHtml, "Export wiki folder as HTML web site" },
{ "All_CheckIn", &Commander::All_CheckIn, &Commander::can_All_CheckIn, "Check-in all files" },
{ "All_CheckOut", &Commander::All_CheckOut, &Commander::can_All_CheckOut, "Check-out all files in current view" },
{ "All_DeepCheckOut", &Commander::All_DeepCheckOut, &Commander::can_All_DeepCheckOut, "Check-out all files including sub-folders" },
{ "All_Uncheckout", &Commander::All_Uncheckout, &Commander::can_All_Uncheckout, "Un-Checkout all checked-out files" },
{ "All_AcceptSynch", &Commander::All_AcceptSynch, &Commander::can_All_AcceptSynch, "Accept this sync in full" },
{ "All_Synch", &Commander::All_Synch, &Commander::can_All_Synch, "Execute and accept all sync scripts" },
{ "All_Report", &Commander::All_Report, &Commander::can_All_Report, "Create report from all view items" },
{ "All_Select", &Commander::All_Select, &Commander::can_All_Select, "Select all view items" },
{ "All_SaveFileVersion", &Commander::All_SaveFileVersion, &Commander::can_All_SaveFileVersion, "Save version of file(s)" },
{ "Selection_CheckOut", &Commander::Selection_CheckOut, &Commander::can_Selection_CheckOut, "Check-out selected files" },
{ "Selection_DeepCheckOut", &Commander::Selection_DeepCheckOut,&Commander::can_Selection_DeepCheckOut, "Check-out selected files including sub-folders" },
{ "Selection_CheckIn", &Commander::Selection_CheckIn, &Commander::can_Selection_CheckIn, "Check-in selected files" },
{ "Selection_Uncheckout", &Commander::Selection_Uncheckout, &Commander::can_Selection_Uncheckout,"Un-Checkout selected files" },
{ "Selection_Properties", &Commander::Selection_Properties, &Commander::can_Selection_Properties,"Selected item properties" },
{ "Selection_Open", &Commander::Selection_Open, &Commander::can_Selection_Open, "Open selected files for viewing/editing" },
{ "Selection_OpenWithShell",&Commander::Selection_OpenWithShell,&Commander::can_Selection_OpenWithShell,"Open selected files for viewing/editing using Windows Shell" },
{ "Selection_SearchWithShell",&Commander::Selection_SearchWithShell,&Commander::can_Selection_SearchWithShell,"Search selected folder using Windows Shell" },
{ "Selection_Add", &Commander::Selection_Add, &Commander::can_Selection_Add, "Add selected file(s) to project" },
{ "Selection_Remove", &Commander::Selection_Remove, &Commander::can_Selection_Remove, "Remove selected file(s) from project (don't delete!)" },
{ "Selection_Delete", &Commander::Selection_Delete, &Commander::can_Selection_Delete, "Delete selected file(s)" },
{ "Selection_DeleteFile", &Commander::Selection_DeleteFile, 0, "" },
{ "Selection_DeleteScript", &Commander::Selection_DeleteScript, 0, "" },
{ "Selection_Rename", &Commander::Selection_Rename, &Commander::can_Selection_Rename, "Rename selected file" },
{ "Selection_Move", &Commander::Selection_MoveFiles, &Commander::can_Selection_MoveFiles,"Move selected file(s)" },
{ "Selection_ChangeFileType",&Commander::Selection_ChangeFileType, &Commander::can_Selection_ChangeFileType, "Change type" },
{ "Selection_Cut", &Commander::Selection_Cut, &Commander::can_Selection_Cut, "Cut selected file(s) (to be pasted into another folder)" },
{ "Selection_Copy", &Commander::Selection_Copy, &Commander::can_Selection_Copy, "Copy selected file(s) to Windows clipboard" },
{ "Selection_Paste", &Commander::Selection_Paste, &Commander::can_Selection_Paste, "Move file(s) that have been cut or copied to current folder" },
{ "Selection_AcceptSynch", &Commander::Selection_AcceptSynch, &Commander::can_Selection_AcceptSynch,"Accept sync changes for selected file(s)" },
{ "Selection_Synch", &Commander::Selection_Synch, &Commander::can_Selection_Synch, "Execute and accept next sync script" },
{ "Selection_EditSync", &Commander::Selection_EditSync, &Commander::can_Selection_EditSync, "Execute next sync script and edit its result" },
{ "Selection_SendScript", &Commander::Selection_SendScript, &Commander::can_Selection_SendScript,"Re-send script to project members" },
{ "Selection_RequestResend",&Commander::Selection_RequestResend,&Commander::can_Selection_RequestResend,"Request script to be re-send to you" },
{ "Selection_ShowHistory", &Commander::Selection_ShowHistory, &Commander::can_Selection_ShowHistory,"Show history of file(s)" },
{ "Selection_Blame", &Commander::Selection_Blame, &Commander::can_Selection_Blame, "Who did it?" },
{ "Selection_Report", &Commander::Selection_Report, &Commander::can_Selection_Report, "Create report from selected view item(s)" },
{ "Selection_Compare", &Commander::Selection_Compare, &Commander::can_Selection_Compare, "Compare old versions of file(s) " },
{ "Selection_CompareWithPrevious",&Commander::Selection_CompareWithPrevious, &Commander::can_Selection_CompareWithPrevious, "Compare with previous version of file(s) " },
{ "Selection_CompareWithCurrent",&Commander::Selection_CompareWithCurrent, &Commander::can_Selection_CompareWithCurrent, "Compare with current version of file(s) " },
{ "Selection_Revert", &Commander::Selection_Revert, &Commander::can_Selection_Revert, "Restore old version of file(s)" },
{ "Selection_MergeBranch", &Commander::Selection_MergeBranch, &Commander::can_Selection_MergeBranch, "Merge change from the branch into the current project version" },
{ "Selection_Branch", &Commander::Selection_Branch, &Commander::can_Selection_Branch, "Create project branch starting from this version" },
{ "Selection_VersionExport",&Commander::Selection_VersionExport,&Commander::can_Selection_VersionExport,"Export old version of file(s)" },
{ "Selection_Archive", &Commander::Selection_Archive, &Commander::can_Selection_Archive, "Archive all versions before selection" },
{ "Selection_UnArchive", &Commander::Selection_UnArchive, &Commander::can_Selection_UnArchive, "Open archive" },
{ "Selection_Add2FileFilter",&Commander::Selection_Add2FileFilter, &Commander::can_Selection_Add2FileFilter,"Don't show files with the selected extension(s)" },
{ "Selection_RemoveFromFileFilter", &Commander::Selection_RemoveFromFileFilter, &Commander::can_Selection_RemoveFromFileFilter, "Remove the selected file extension(s) from the file filter" },
{ "Selection_HistoryFilterAdd", &Commander::Selection_HistoryFilterAdd, &Commander::can_Selection_HistoryFilterAdd, "Filter history by selected files" },
{ "Selection_HistoryFilterRemove", &Commander::Selection_HistoryFilterRemove, &Commander::can_Selection_HistoryFilterRemove, "Clear history filter" },
{ "Selection_SaveFileVersion", &Commander::Selection_SaveFileVersion, &Commander::can_Selection_SaveFileVersion, "Save version of file(s)" },
{ "Selection_RestoreFileVersion", &Commander::Selection_RestoreFileVersion, &Commander::can_Selection_RestoreFileVersion, "Restores version of file(s)" },
{ "Selection_MergeFileVersion", &Commander::Selection_MergeFileVersion, &Commander::can_Selection_MergeFileVersion, "Merges version of file(s) into the current project version" },
{ "Selection_AutoMergeFileVersion", &Commander::Selection_AutoMergeFileVersion, &Commander::can_Selection_AutoMergeFileVersion, "Automatically merges version of file(s) into the current project version" },
{ "Selection_CopyList", &Commander::Selection_CopyList, &Commander::can_Selection_CopyList, "Copy Select List To Clipboard" },
{ "Selection_Edit", &Commander::Selection_Edit, &Commander::can_Selection_Edit, "Edit File" },
{ "Selection_Next", &Commander::Selection_Next, &Commander::can_Selection_Next, "Next Page" },
{ "Selection_Previous", &Commander::Selection_Previous, &Commander::can_Selection_Previous, "Previous Page" },
{ "Selection_Home", &Commander::Selection_Home, &Commander::can_Selection_Home, "Browse Home" },
{ "Selection_Reload", &Commander::Selection_Reload, &Commander::can_Selection_Reload, "Reload Page" },
{ "Selection_CopyScriptComment", &Commander::Selection_CopyScriptComment, &Commander::can_Selection_CopyScriptComment, "Copy Script Comment To Clipboard" },
{ "Tools_Differ", &Commander::Tools_Differ, 0, "Configure Differ Tool" },
{ "Tools_Merger", &Commander::Tools_Merger, 0, "Configure Merger Tool" },
{ "Tools_Editor", &Commander::Tools_Editor, 0, "Configure Editor Tool" },
{ "Tools_CreateBackup", &Commander::Tools_CreateBackup, &Commander::can_Tools_CreateBackup, "Backup all projects" },
{ "Tools_RestoreFromBackup",&Commander::Tools_RestoreFromBackup,&Commander::can_Tools_RestoreFromBackup, "Restore all projects from backup" },
{ "Tools_MoveToMachine", &Commander::Tools_MoveToMachine, 0, "Move Code Co-op to a new machine" },
{ "Help_Contents", &Commander::Help_Contents, 0, "Display Help" },
{ "Help_Index", &Commander::Help_Index, 0, "Display Help Index" },
{ "Help_Tutorial", &Commander::Help_Tutorial, 0, "Step-by-step tutorial" },
{ "Help_Support", &Commander::Help_Support, 0, "On-line support" },
{ "Help_SaveDiagnostics", &Commander::Help_SaveDiagnostics, 0, "Save diagnostic information to file" },
{ "Help_RestoreOriginal", &Commander::Help_RestoreOriginal, &Commander::can_Help_RestoreOriginal, "Uninstall the current temporary version and restore the original version" },
{ "Help_BeginnerMode", &Commander::Help_BeginnerMode, &Commander::can_Help_BeginnerMode, "Display helpful hints for the inexperienced user" },
// Commands triggered by control notification handlers
{ "DoNewFolder", &Commander::DoNewFolder, 0, "" },
{ "DoRenameFile", &Commander::DoRenameFile, 0, "" },
{ "DoDrag", &Commander::DoDrag, &Commander::can_Drag, "" },
{ "DoDrop", &Commander::DoDrop, 0, "" },
{ "SetCurrentFolder", &Commander::SetCurrentFolder, 0, "" },
{ "DoNewFile", &Commander::DoNewFile, 0, "" },
{ "DoDeleteFile", &Commander::DoDeleteFile, 0, "" },
{ "Project_SelectMergeTarget", &Commander::Project_SelectMergeTarget, 0, "" },
{ "Project_SetMergeType", &Commander::Project_SetMergeType, 0, "" },
{ "Selection_OpenHistoryDiff", &Commander::Selection_OpenHistoryDiff, 0, "" },
// Commands not associated with any menu item, but used by SccDll or others
{ "GoBrowse", &Commander::GoBrowse, 0, "" },
{ "OnBrowse", &Commander::OnBrowse, 0, "" },
{ "Navigate", &Commander::Navigate, 0, "" },
{ "OpenFile", &Commander::OpenFile, 0, "" },
{ "CreateRange", &Commander::CreateRange, 0, "" },
{ "Selection_OpenCheckInDiff", &Commander::Selection_OpenCheckInDiff, 0, "" },
{ "RefreshMailbox", &Commander::RefreshMailbox, 0, "" },
{ "RestoreVersion", &Commander::RestoreVersion, 0, "" },
{ "Maintenance", &Commander::Maintenance, 0, "" },
{ "ReCreateFile", &Commander::ReCreateFile, 0, "" },
{ "MergeAttributes", &Commander::MergeAttributes, 0, "" },
#if !defined (NDEBUG)
{ "RestoreOneVersion", &Commander::RestoreOneVersion, 0, "" },
#endif
{ 0, 0, 0 }
};
}
| 94.100529
| 207
| 0.721001
|
BartoszMilewski
|
193b13954156d2292b272b4c13f84bb937a3810a
| 1,820
|
cpp
|
C++
|
Algorithms/0023.MergeKSortedLists/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0023.MergeKSortedLists/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
Algorithms/0023.MergeKSortedLists/solution.cpp
|
stdstring/leetcode
|
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
|
[
"MIT"
] | null | null | null |
#include <queue>
#include <vector>
#include "ListNode.h"
#include "ListNodeUtils.h"
#include "gtest/gtest.h"
using CommonLib::ListNode;
namespace
{
class Solution
{
public:
ListNode* mergeKLists(std::vector<ListNode*> const &lists)
{
auto comp = [](ListNode* left, ListNode* right){ return left->val > right->val; };
std::priority_queue<ListNode*, std::vector<ListNode*>, decltype(comp)> queue(comp);
for (ListNode* head : lists)
{
while (head != nullptr)
{
queue.push(head);
head = head->next;
}
}
ListNode* head = nullptr;
ListNode* current = nullptr;
while (!queue.empty())
{
if (current == nullptr)
head = current = queue.top();
else
{
current->next = queue.top();
current = current->next;
}
queue.pop();
}
if (current != nullptr)
current->next = nullptr;
return head;
}
};
}
using CommonLib::createLinkedList;
using CommonLib::checkAndDeleteLinkedList;
namespace MergeKSortedListsTask
{
TEST(ReorderListTaskTests, Examples)
{
Solution solution;
checkAndDeleteLinkedList({1, 1, 2, 3, 4, 4, 5, 6}, solution.mergeKLists({createLinkedList({1, 4, 5}, false).get(),
createLinkedList({1, 3, 4}, false).get(),
createLinkedList({2, 6}, false).get()}));
}
TEST(ReorderListTaskTests, FromWrongAnswers)
{
Solution solution;
checkAndDeleteLinkedList({}, solution.mergeKLists({}));
checkAndDeleteLinkedList({}, solution.mergeKLists({nullptr}));
}
}
| 25.633803
| 118
| 0.52967
|
stdstring
|
193b65c74c6443443efd2c4733991672729e7e86
| 1,433
|
hpp
|
C++
|
minimal_sdk/public/containers/utldict.hpp
|
vocweb/cso2-launcher
|
abc144acaa3dfb5b0c9acd61cd75970cac012617
|
[
"MIT"
] | 55
|
2018-09-01T17:52:17.000Z
|
2019-09-23T10:30:49.000Z
|
minimal_sdk/public/containers/utldict.hpp
|
RedheatWei/cso2-launcher
|
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
|
[
"MIT"
] | 70
|
2018-08-22T05:53:34.000Z
|
2019-09-23T15:11:39.000Z
|
minimal_sdk/public/containers/utldict.hpp
|
RedheatWei/cso2-launcher
|
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
|
[
"MIT"
] | 39
|
2018-09-01T21:42:50.000Z
|
2019-09-23T18:38:07.000Z
|
#pragma once
#include <cstring>
#include "containers/utlmap.hpp"
#ifdef _WIN32
#define stricmp _stricmp
#else
#define stricmp strcasecmp
#endif
inline bool CaselessStringLessThan( const char* const& lhs,
const char* const& rhs )
{
if ( !lhs )
return false;
if ( !rhs )
return true;
return ( stricmp( lhs, rhs ) < 0 );
}
inline char* UtlDict_DupStr( const char* inStr )
{
const size_t len = std::strlen( inStr ) + 1;
char* newStr = new char[len];
memcpy_s( newStr, len, inStr, len );
return newStr;
}
template <class T, class I = int>
class CUtlDict
{
public:
using DictElementMap_t = CUtlMap<const char*, T, I>;
DictElementMap_t m_Elements;
CUtlDict( int growSize = 0, int initSize = 0 )
: m_Elements( growSize, initSize )
{
m_Elements.SetLessFunc( CaselessStringLessThan );
}
~CUtlDict() { Purge(); }
void Purge() { RemoveAll(); }
void RemoveAll()
{
typename DictElementMap_t::IndexType_t index =
m_Elements.FirstInorder();
while ( index != m_Elements.InvalidIndex() )
{
delete m_Elements.Key( index );
index = m_Elements.NextInorder( index );
}
m_Elements.RemoveAll();
}
I Insert( const char* pName, const T& element )
{
return m_Elements.Insert( UtlDict_DupStr( pName ), element );
}
};
| 22.046154
| 69
| 0.598046
|
vocweb
|
193baa28349a290947ae28e4780acc661b713584
| 709
|
cpp
|
C++
|
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
|
mgehre-xlx/sycl
|
2086745509ef4bc298d7bbec402a123dae68f25e
|
[
"Apache-2.0"
] | 61
|
2019-04-12T18:49:57.000Z
|
2022-03-19T22:23:16.000Z
|
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
|
mgehre-xlx/sycl
|
2086745509ef4bc298d7bbec402a123dae68f25e
|
[
"Apache-2.0"
] | 127
|
2019-04-09T00:55:50.000Z
|
2022-03-21T15:35:41.000Z
|
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
|
mgehre-xlx/sycl
|
2086745509ef4bc298d7bbec402a123dae68f25e
|
[
"Apache-2.0"
] | 10
|
2019-04-02T18:25:40.000Z
|
2022-02-15T07:11:37.000Z
|
// REQUIRES: xocc
// RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -o %t.out
// RUN: %ACC_RUN_PLACEHOLDER %t.out
// TODO should be a Sema test
#include <CL/sycl.hpp>
#include "../utilities/device_selectors.hpp"
using namespace cl::sycl;
class add_2;
int main() {
selector_defines::CompiledForDeviceSelector selector;
queue q {selector};
q.submit([&] (handler &cgh) {
cgh.single_task<add_2>([=] () {
});
});
q.submit([&] (handler &cgh) {
cgh.single_task<add_2>([=] () {
});
});
q.submit([&] (handler &cgh) {
cgh.single_task<class add>([=] () {
});
});
q.submit([&] (handler &cgh) {
cgh.single_task<class add>([=] () {
});
});
return 0;
}
| 16.880952
| 64
| 0.57969
|
mgehre-xlx
|
193feff6c0408370500518f0e617c3b5ca13178c
| 1,929
|
cpp
|
C++
|
SDK/BP_WheelInterface_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | 3
|
2021-03-27T08:30:37.000Z
|
2021-04-18T19:32:53.000Z
|
SDK/BP_WheelInterface_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | null | null | null |
SDK/BP_WheelInterface_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | 1
|
2021-06-01T03:05:50.000Z
|
2021-06-01T03:05:50.000Z
|
// Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_WheelInterface.BP_WheelInterface_C.Receive Animation State
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FRotator WheelRotation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// float WheelAnimationTime (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<EWheel_EWheel> EWheel (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// float Direction (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// float WheelRate (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UBP_WheelInterface_C::Receive_Animation_State(const struct FRotator& WheelRotation, float WheelAnimationTime, TEnumAsByte<EWheel_EWheel> EWheel, float Direction, float WheelRate)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_WheelInterface.BP_WheelInterface_C.Receive Animation State");
UBP_WheelInterface_C_Receive_Animation_State_Params params;
params.WheelRotation = WheelRotation;
params.WheelAnimationTime = WheelAnimationTime;
params.EWheel = EWheel;
params.Direction = Direction;
params.WheelRate = WheelRate;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBP_WheelInterface_C::AfterRead()
{
UInterface::AfterRead();
}
void UBP_WheelInterface_C::BeforeDelete()
{
UInterface::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 29.676923
| 183
| 0.641265
|
alxalx14
|
1943e504d831c8eac0d1a9ed4fd33283c4ceb1ea
| 2,860
|
hpp
|
C++
|
bsengine/src/bstorm/logger.hpp
|
At-sushi/bstorm
|
156036afd698d98f0ed67f0efa6bc416115806f7
|
[
"MIT"
] | null | null | null |
bsengine/src/bstorm/logger.hpp
|
At-sushi/bstorm
|
156036afd698d98f0ed67f0efa6bc416115806f7
|
[
"MIT"
] | null | null | null |
bsengine/src/bstorm/logger.hpp
|
At-sushi/bstorm
|
156036afd698d98f0ed67f0efa6bc416115806f7
|
[
"MIT"
] | null | null | null |
#pragma once
#include <bstorm/source_map.hpp>
#include <string>
#include <memory>
#include <vector>
#include <mutex>
namespace bstorm
{
class LogParam
{
public:
enum class Tag
{
TEXT,
TEXTURE,
SOUND,
MESH,
PLAYER_SHOT_DATA,
ENEMY_SHOT_DATA,
ITEM_DATA,
SCRIPT,
RENDER_TARGET,
SHADER
};
LogParam(Tag tag, const std::string& text);
LogParam(Tag tag, const std::wstring& text);
LogParam(Tag tag, std::string&& text);
Tag GetTag() const { return tag_; }
const std::string& GetText() const { return text_; }
private:
Tag tag_;
std::string text_; // utf8
};
enum class LogLevel
{
LV_INFO,
LV_WARN,
LV_ERROR,
LV_SUCCESS,
LV_DEBUG,
LV_USER
};
class Log
{
public:
static const char* GetLevelName(LogLevel level);
Log();
Log(LogLevel level);
Log& Msg(const std::string& text);
Log& Msg(const std::wstring& text);
Log& Msg(std::string&& text);
const std::string& Msg() const { return msg_; }
Log& Param(const LogParam& param);
Log& Param(LogParam&& param);
const std::shared_ptr<LogParam>& Param() const { return param_; }
Log& Level(LogLevel level);
LogLevel Level() const { return level_; }
Log& AddSourcePos(const std::shared_ptr<SourcePos>& srcPos);
const std::vector<SourcePos>& GetSourcePosStack() const { return srcPosStack_; }
std::string ToString() const;
Log&& move() { return std::move(*this); }
private:
LogLevel level_;
std::string msg_; // utf8
std::shared_ptr<LogParam> param_; // Nullable
std::vector<SourcePos> srcPosStack_; // add = push_back
};
Log LogInfo(const std::wstring& msg);
Log LogInfo(const std::string& msg);
Log LogInfo(std::string&& msg);
Log LogWarn(const std::wstring& msg);
Log LogWarn(const std::string& msg);
Log LogWarn(std::string&& msg);
Log LogError(const std::wstring& msg);
Log LogError(const std::string& msg);
Log LogError(std::string&& msg);
Log LogDebug(const std::wstring& msg);
Log LogDebug(const std::string& msg);
Log LogDebug(std::string&& msg);
class Logger
{
public:
static void Init(const std::shared_ptr<Logger>& logger);
static void Write(Log& lg);
static void Write(Log&& lg);
static void Write(LogLevel level, const std::string& text);
static void Write(LogLevel level, const std::wstring& text);
static void Write(LogLevel level, std::string&& text);
static void Shutdown();
virtual ~Logger() {}
virtual void log(Log& lg) noexcept(false) = 0;
virtual void log(Log&& lg) noexcept(false) = 0;
void log(LogLevel level, const std::string& text);
void log(LogLevel level, const std::wstring& text);
void log(LogLevel level, std::string&& text);
private:
static std::shared_ptr<Logger> logger;
static std::mutex mutex;
};
}
| 26
| 84
| 0.654196
|
At-sushi
|
1944823fef65060394f79ec527543ef0dc6f84af
| 14,712
|
cpp
|
C++
|
examples/hxhim/cli.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 2
|
2020-11-25T17:45:58.000Z
|
2021-12-21T02:01:16.000Z
|
examples/hxhim/cli.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | null | null | null |
examples/hxhim/cli.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 1
|
2021-10-11T19:54:05.000Z
|
2021-10-11T19:54:05.000Z
|
#include <cstring>
#include <ios>
#include <iostream>
#include <list>
#include <map>
#include <sstream>
#include "hxhim/hxhim.hpp"
#include "print_results.h"
#include "utils/Blob.hpp" // private header
#include "utils/memory.hpp"
enum HXHIM_OP {
PUT,
GET,
GETOP,
DEL,
BPUT,
BGET,
BGETOP,
BDEL,
FLUSHPUTS,
FLUSHGETS,
FLUSHDELS,
FLUSH,
};
const std::map<HXHIM_OP, std::string> FORMAT = {
std::make_pair(HXHIM_OP::PUT, "PUT <SUBJECT> <PREDICATE> <OBJECT>"),
std::make_pair(HXHIM_OP::GET, "GET <SUBJECT> <PREDICATE> <OBJECT_TYPE>"),
std::make_pair(HXHIM_OP::GETOP, "GETOP <SUBJECT> <PREDICATE> <OBJECT_TYPE> <NUM_RECS> <OP>"),
std::make_pair(HXHIM_OP::DEL, "DEL <SUBJECT> <PREDICATE>"),
std::make_pair(HXHIM_OP::BPUT, "BPUT N <SUBJECT_1> <PREDICATE_1> <OBJECT_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_N>"),
std::make_pair(HXHIM_OP::BGET, "BGET N <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N>"),
std::make_pair(HXHIM_OP::BGETOP, "BGETOP <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> <NUM_RECS_1> <OP_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N> <NUM_RECS_N> <OP_N>"),
std::make_pair(HXHIM_OP::BDEL, "BDEL N <SUBJECT_1> <PREDICATE_1> ... <SUBJECT_N> <PREDICATE_N>"),
std::make_pair(HXHIM_OP::FLUSHPUTS, "FLUSHPUTS"),
std::make_pair(HXHIM_OP::FLUSHGETS, "FLUSHGETS"),
std::make_pair(HXHIM_OP::FLUSHDELS, "FLUSHDELS"),
std::make_pair(HXHIM_OP::FLUSH, "FLUSH"),
};
const std::map<std::string, HXHIM_OP> USER2OP = {
std::make_pair("PUT", HXHIM_OP::PUT),
std::make_pair("BPUT", HXHIM_OP::BPUT),
std::make_pair("GET", HXHIM_OP::GET),
std::make_pair("BGET", HXHIM_OP::BGET),
std::make_pair("GETOP", HXHIM_OP::GETOP),
std::make_pair("BGETOP", HXHIM_OP::BGETOP),
std::make_pair("DEL", HXHIM_OP::DEL),
std::make_pair("BDEL", HXHIM_OP::BDEL),
std::make_pair("FLUSHPUTS", HXHIM_OP::FLUSHPUTS),
std::make_pair("FLUSHGETS", HXHIM_OP::FLUSHGETS),
std::make_pair("FLUSHDELS", HXHIM_OP::FLUSHDELS),
std::make_pair("FLUSH", HXHIM_OP::FLUSH),
};
const std::map<std::string, hxhim_data_t> USER2OT = {
std::make_pair("INT32", HXHIM_DATA_INT32),
std::make_pair("INT64", HXHIM_DATA_INT64),
std::make_pair("UINT32", HXHIM_DATA_UINT32),
std::make_pair("UINT64", HXHIM_DATA_UINT64),
std::make_pair("FLOAT", HXHIM_DATA_FLOAT),
std::make_pair("DOUBLE", HXHIM_DATA_DOUBLE),
std::make_pair("BYTE", HXHIM_DATA_BYTE),
};
const std::map<std::string, hxhim_getop_t> USER2GETOP = {
std::make_pair("EQ", HXHIM_GETOP_EQ),
std::make_pair("NEXT", HXHIM_GETOP_NEXT),
std::make_pair("PREV", HXHIM_GETOP_PREV),
std::make_pair("FIRST", HXHIM_GETOP_FIRST),
std::make_pair("LAST", HXHIM_GETOP_LAST),
// std::make_pair("PRIMARY_EQ", HXHIM_GETOP_PRIMARY_EQ),
};
std::ostream &help(char *self, std::ostream &stream = std::cout) {
stream << "Syntax: " << self << " [-h | --help] [--ds <name>]" << std::endl
<< std::endl
<< "--ds implies a single rank. Running multiple MPI ranks will error." << std::endl
<< std::endl
<< "Input is passed in through the stdin of rank 0, delimited with newlines, in the following formats:" << std::endl;
for(decltype(FORMAT)::value_type const &format : FORMAT) {
stream << " " << format.second << std::endl;
}
stream << "Where <SUBJECT>, <PREDICATE>, and <OBJECT> are pairs of <type, data>" << std::endl
<< "<OBJECT_TYPE> is only the type" << std::endl
<< std::endl
<< "Available Types:" << std::endl;
for(decltype(USER2OT)::value_type const &type : USER2OT) {
stream << " " << type.first << std::endl;
}
stream << std::endl
<< "The <OP> argument to (B)GETOP can be one of the following:" << std::endl;
for(decltype(USER2GETOP)::value_type const &op : USER2GETOP) {
stream << " " << op.first << std::endl;
}
return stream;
}
std::istream &operator>>(std::istream &stream, hxhim_data_t &type) {
std::string str;
if ((stream >> str)) {
const decltype(USER2OT)::const_iterator it = USER2OT.find(str);
if (it == USER2OT.end()) {
stream.setstate(std::ios::failbit);
}
else {
type = it->second;
}
}
return stream;
}
std::istream &operator>>(std::istream &stream, Blob &input) {
hxhim_data_t type;
if (!(stream >> type)) {
return stream;
}
void *data = nullptr;
std::size_t size = 0;
switch (type) {
case HXHIM_DATA_INT32:
size = sizeof(int32_t);
data = alloc(size);
stream >> * (int32_t *) data;
break;
case HXHIM_DATA_INT64:
size = sizeof(int64_t);
data = alloc(size);
stream >> * (int64_t *) data;
break;
case HXHIM_DATA_UINT32:
size = sizeof(uint32_t);
data = alloc(size);
stream >> * (uint32_t *) data;
break;
case HXHIM_DATA_UINT64:
size = sizeof(uint64_t);
data = alloc(size);
stream >> * (uint64_t *) data;
break;
case HXHIM_DATA_FLOAT:
size = sizeof(float);
data = alloc(size);
stream >> * (float *) data;
break;
case HXHIM_DATA_DOUBLE:
size = sizeof(double);
data = alloc(size);
stream >> * (double *) data;
break;
case HXHIM_DATA_BYTE:
{
std::string str;
if ((stream >> str)) {
size = str.size();
data = alloc(size);
memcpy(data, str.c_str(), str.size());
}
}
break;
default:
stream.setstate(std::ios::failbit);
break;
}
// on error, will be deallocated automatically
input = RealBlob(data, size, type);
return stream;
}
struct UserInput {
HXHIM_OP hxhim_op;
Blob subject;
Blob predicate;
Blob object; // data field is only used by (B)PUT
// only used by (B)GETOP
std::size_t num_recs;
hxhim_getop_t op;
};
using UserInputs = std::list<UserInput>;
// A quick and dirty cleanup function
void cleanup(hxhim_t *hx) {
hxhim::Close(hx);
MPI_Finalize();
}
// serialize user input
// B* becomes individual operations
std::size_t parse_commands(std::istream &stream, UserInputs &commands) {
std::string line;
while (std::getline(stream, line)) {
std::stringstream command(line);
// empty line
std::string op_str;
if (!(command >> op_str)) {
continue;
}
const decltype(USER2OP)::const_iterator op_it = USER2OP.find(op_str);
if (op_it == USER2OP.end()) {
std::cerr << "Error: Bad operation: " << op_str << std::endl;
continue;
}
const HXHIM_OP hxhim_op = op_it->second;
std::size_t count = 1;
// bulk, so get count first
if (op_str[0] == 'B') {
if (!(command >> count)) {
std::cerr << "Error: Bad count: " << line << std::endl;
continue;
}
}
// read input
for(std::size_t i = 0; i < count; i++) {
UserInput input;
bool ok = true;
switch ((input.hxhim_op = hxhim_op)) {
case HXHIM_OP::PUT:
case HXHIM_OP::BPUT:
{
if (!(command >> input.subject >> input.predicate >> input.object)) {
ok = false;
}
}
break;
case HXHIM_OP::GET:
case HXHIM_OP::BGET:
{
hxhim_data_t object_type;
if (!(command >> input.subject >> input.predicate >> object_type)) {
ok = false;
}
else {
input.object.set_type(object_type);
}
}
break;
case HXHIM_OP::GETOP:
case HXHIM_OP::BGETOP:
{
hxhim_data_t object_type;
std::string op;
if (!(command >> input.subject >> input.predicate >> object_type >> input.num_recs >> op)) {
ok = false;
}
else {
input.object.set_type(object_type);
}
const decltype(USER2GETOP)::const_iterator getop_it = USER2GETOP.find(op);
if (getop_it == USER2GETOP.end()) {
ok = false;
}
else {
input.op = getop_it->second;
}
}
break;
case HXHIM_OP::DEL:
case HXHIM_OP::BDEL:
if (!(command >> input.subject >> input.predicate)) {
ok = false;
}
break;
case HXHIM_OP::FLUSHPUTS:
case HXHIM_OP::FLUSHGETS:
case HXHIM_OP::FLUSHDELS:
case HXHIM_OP::FLUSH:
break;
}
if (!ok) {
std::cerr << "Error: Could not parse line \"" << line << "\"." << std::endl
<< "Expected: " << FORMAT.at(hxhim_op) << std::endl;
break;
}
commands.emplace_back(std::move(input));
}
}
return commands.size();
}
std::size_t run_commands(hxhim_t *hx, const UserInputs &commands) {
std::size_t successful = 0;
for(UserInputs::value_type const &cmd : commands) {
int rc = HXHIM_SUCCESS;
hxhim_results *res = nullptr;
switch (cmd.hxhim_op) {
case HXHIM_OP::PUT:
case HXHIM_OP::BPUT:
rc = hxhimPut(hx,
(void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(),
(void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(),
(void *) cmd.object.data(), cmd.object.size(), cmd.object.data_type(),
HXHIM_PUT_ALL);
break;
case HXHIM_OP::GET:
case HXHIM_OP::BGET:
rc = hxhimGet(hx,
(void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(),
(void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(),
cmd.object.data_type());
break;
case HXHIM_OP::GETOP:
case HXHIM_OP::BGETOP:
rc = hxhimGetOp(hx,
(void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(),
(void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(),
cmd.object.data_type(),
cmd.num_recs, cmd.op);
break;
case HXHIM_OP::DEL:
case HXHIM_OP::BDEL:
rc = hxhimDelete(hx,
(void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(),
(void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type());
break;
case HXHIM_OP::FLUSHPUTS:
res = hxhimFlushPuts(hx);
break;
case HXHIM_OP::FLUSHGETS:
res = hxhimFlushGets(hx);
break;
case HXHIM_OP::FLUSHDELS:
res = hxhimFlushDeletes(hx);
break;
case HXHIM_OP::FLUSH:
res = hxhimFlush(hx);
break;
}
print_results(hx, 0, res);
hxhim_results_destroy(res);
if (rc == HXHIM_ERROR) {
std::cerr << "Error" << std::endl;
}
else {
successful++;
}
}
// do not implicity flush
return successful;
}
int main(int argc, char *argv[]) {
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
char * ds = nullptr;
for(int i = 1; i < argc;) {
const std::string args(argv[i]);
if ((args == "-h")|| (args == "--help")) {
if (rank == 0) {
help(argv[0], std::cerr);
}
MPI_Finalize();
return 0;
}
if (args == "--ds") {
// --ds implies a single rank, but a single rank does not imply --ds
if (size != 1) {
std::cerr << "Error: The --ds flag implies 1 rank. Have " << size << std::endl;
MPI_Finalize();
return 1;
}
ds = argv[++i];
}
i++;
}
// read the config
hxhim_t hx;
if (hxhimInit(&hx, MPI_COMM_WORLD) != HXHIM_SUCCESS) {
if (rank == 0) {
std::cout << "Error: Failed to read configuration" << std::endl;
}
cleanup(&hx);
return 1;
}
// initialize hxhim context
if (ds) {
if (hxhimOpenOne(&hx, ds, strlen(ds)) != HXHIM_SUCCESS) {
if (rank == 0) {
std::cerr << "Failed to initialize hxhim" << std::endl;
}
cleanup(&hx);
return 1;
}
}
else {
if (hxhimOpen(&hx) != HXHIM_SUCCESS) {
if (rank == 0) {
std::cerr << "Failed to initialize hxhim" << std::endl;
}
cleanup(&hx);
return 1;
}
}
// parse and run input
if (rank == 0) {
UserInputs cmds;
const std::size_t valid_count = parse_commands(std::cin, cmds);
std::cout << "Read " << valid_count << " valid commands" << std::endl;
run_commands(&hx, cmds);
}
MPI_Barrier(MPI_COMM_WORLD);
cleanup(&hx);
return 0;
}
| 32.548673
| 178
| 0.494562
|
hpc
|