hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses 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 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
628cb8829a20f7becc2f52bd0a7c1d992a26d812 | 16,159 | hh | C++ | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | /*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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 (C) 2015 Cloudius Systems, Ltd.
*/
//
// Buffered input and output streams
//
// Two abstract classes (data_source and data_sink) provide means
// to acquire bulk data from, or push bulk data to, some provider.
// These could be tied to a TCP connection, a disk file, or a memory
// buffer.
//
// Two concrete classes (input_stream and output_stream) buffer data
// from data_source and data_sink and provide easier means to process
// it.
//
#pragma once
#include "future.hh"
#include "temporary_buffer.hh"
#include "scattered_message.hh"
#ifdef __USE_KJ__
#include "core/do_with.hh"
#include "kj/debug.h"
#include "kj/async.h"
#include "kj/async-io.h"
#include <limits.h>
#endif
#if !defined(IOV_MAX) && defined(UIO_MAXIOV)
#define IOV_MAX UIO_MAXIOV
#endif
namespace net { class packet; }
class data_source_impl {
public:
virtual ~data_source_impl() {}
virtual future<temporary_buffer<char>> get() = 0;
#ifdef __USE_KJ__
virtual void setBuffer(temporary_buffer<char> && buf) = 0;
virtual kj::Promise<temporary_buffer<char>> kj_get(size_t maxBytes = 8192) = 0;
#endif
};
class data_source {
std::unique_ptr<data_source_impl> _dsi;
protected:
data_source_impl* impl() const { return _dsi.get(); }
public:
data_source() = default;
explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {}
data_source(data_source&& x) = default;
data_source& operator=(data_source&& x) = default;
future<temporary_buffer<char>> get() { return _dsi->get(); }
#ifdef __USE_KJ__
void setBuffer(temporary_buffer<char> && buf){
_dsi->setBuffer(std::move(buf) );
}
kj::Promise<temporary_buffer<char>> kj_get(size_t maxBytes = 8192) {
return _dsi->kj_get(maxBytes);
};
#endif
};
class data_sink_impl {
public:
virtual ~data_sink_impl() {}
virtual temporary_buffer<char> allocate_buffer(size_t size) {
return temporary_buffer<char>(size);
}
virtual future<> put(net::packet data) = 0;
virtual future<> put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return put(std::move(p));
}
virtual future<> put(temporary_buffer<char> buf) {
return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual future<> close() = 0;
#ifdef __USE_KJ__
virtual kj::Promise<void> kj_put(net::packet data) = 0;
virtual kj::Promise<void> kj_put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return kj_put(std::move(p));
}
virtual kj::Promise<void> kj_put(temporary_buffer<char> buf) {
return kj_put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual kj::Promise<void> kj_close() = 0;
#endif
};
class data_sink {
std::unique_ptr<data_sink_impl> _dsi;
public:
data_sink() = default;
explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {}
data_sink(data_sink&& x) = default;
data_sink& operator=(data_sink&& x) = default;
temporary_buffer<char> allocate_buffer(size_t size) {
return _dsi->allocate_buffer(size);
}
future<> put(std::vector<temporary_buffer<char>> data) {
return _dsi->put(std::move(data));
}
future<> put(temporary_buffer<char> data) {
return _dsi->put(std::move(data));
}
future<> put(net::packet p) {
return _dsi->put(std::move(p));
}
future<> close() { return _dsi->close(); }
#ifdef __USE_KJ__
kj::Promise<void> kj_put(std::vector<temporary_buffer<char>> data) {
return _dsi->kj_put(std::move(data));
}
kj::Promise<void> kj_put(temporary_buffer<char> data) {
return _dsi->kj_put(std::move(data));
}
kj::Promise<void> kj_put(net::packet p) {
return _dsi->kj_put(std::move(p));
}
kj::Promise<void> kj_close() { return _dsi->kj_close(); }
#endif
};
#ifdef __USE_KJ__
template <typename CharType>
class input_stream final : public kj::AsyncInputStream {
#else
template <typename CharType>
class input_stream final {
#endif
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_source _fd;
temporary_buffer<CharType> _buf;
bool _eof = false;
private:
using tmp_buf = temporary_buffer<CharType>;
size_t available() const { return _buf.size(); }
protected:
void reset() { _buf = {}; }
data_source* fd() { return &_fd; }
public:
// Consumer concept, for consume() method:
using unconsumed_remainder = std::experimental::optional<tmp_buf>;
struct ConsumerConcept {
// The consumer should operate on the data given to it, and
// return a future "unconsumed remainder", which can be undefined
// if the consumer consumed all the input given to it and is ready
// for more, or defined when the consumer is done (and in that case
// the value is the unconsumed part of the last data buffer - this
// can also happen to be empty).
future<unconsumed_remainder> operator()(tmp_buf data);
};
using char_type = CharType;
input_stream() = default;
explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {}
input_stream(input_stream&&) = default;
input_stream& operator=(input_stream&&) = default;
future<temporary_buffer<CharType>> read_exactly(size_t n);
template <typename Consumer>
future<> consume(Consumer& c);
bool eof() { return _eof; }
#ifdef __USE_KJ__
template <typename Consumer>
kj::Promise<void> kj_consume(Consumer& c);
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
return tryReadInternal(buffer, minBytes, maxBytes, 0);
}
kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override {
return tryReadInternal(buffer, minBytes, maxBytes, 0).then([ = ](size_t result) {
KJ_REQUIRE(result >= minBytes, "Premature EOF") {
// Pretend we read zeros from the input.
memset(reinterpret_cast<kj::byte*>(buffer) + result, 0, minBytes - result);
return minBytes;
}
return result;
});
}
kj::Promise<temporary_buffer<CharType>> kj_read_exactly(size_t n);
#endif
private:
future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed);
#ifdef __USE_KJ__
kj::Promise<temporary_buffer<CharType>> kj_read_exactly_part(size_t n, tmp_buf buf, size_t completed);
kj::Promise<size_t> tryReadInternal(void* buffer, size_t minBytes, size_t maxBytes,
size_t alreadyRead) {
// printf("tryReadInternal %zu, %zu \n",minBytes,maxBytes);
if (available()) {//Should not happen now
printf("Available \n");
auto now = std::min(maxBytes, available());
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Copy here\n");
std::copy(_buf.get(), _buf.get() + now, reinterpret_cast<CharType*>(buffer) + alreadyRead);
}
_buf.trim_front(now);
alreadyRead += now;
minBytes -= now;
maxBytes -= now;
}
// printf("Buffer now = %zu %zu\t%zu\t%zu\n",(size_t)buffer,alreadyRead,minBytes,maxBytes);
if (minBytes <= 0) {
printf("Done %zu\n",alreadyRead);
return alreadyRead;
}
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Copy here\n");
_buf = std::move( temporary_buffer<CharType>(reinterpret_cast<CharType*>(buffer)+alreadyRead, maxBytes, make_free_deleter(NULL) ) );
}
// printf("_buf now = %zu %zu\n",(size_t)_buf.get(),alreadyRead);
// _buf is now empty
_fd.setBuffer(std::move(_buf));
return _fd.kj_get(maxBytes).then([this, minBytes, maxBytes, buffer, alreadyRead] (auto buf) mutable {
if (buf.size() == 0) {
_eof = true;
// printf("OK, Done %zu\n",alreadyRead);
return kj::Promise<size_t>(alreadyRead);
}
_buf = std::move(buf);
// printf("Buff now = %zu %zu\n",(size_t)_buf.get(),_buf.size() );
auto now = kj::min(minBytes, _buf.size());
// KJ_DBG(now);
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Oh crap\n");
std::copy(_buf.get(), _buf.get() + now, reinterpret_cast<CharType*>(buffer) + alreadyRead);
}
alreadyRead += _buf.size();
minBytes -= now;
maxBytes -= now;
// for (size_t i=0;i<21;++i){
// printf("%d\t",(int)_buf[i]);
// }
// printf("\n");
_buf.trim_front(_buf.size());
// printf("Buff after trim now = %zu\t%zu\n",(size_t)_buf.get(), (size_t)(reinterpret_cast<CharType*>(buffer) + alreadyRead) );
// printf("Hey a, alreadyRead = %zu, buff size = %zu, minBytes = %zu\n",alreadyRead,_buf.size(),minBytes);
if (minBytes<=0) {
// printf("Returned %zu\n",alreadyRead);
return kj::Promise<size_t>(alreadyRead);
}
return this->tryReadInternal(buffer, minBytes, maxBytes, alreadyRead);
});
}
#endif
};
// Facilitates data buffering before it's handed over to data_sink.
//
// When trim_to_size is true it's guaranteed that data sink will not receive
// chunks larger than the configured size, which could be the case when a
// single write call is made with data larger than the configured size.
//
// The data sink will not receive empty chunks.
//
#ifdef __USE_KJ__
template <typename CharType>
class output_stream final : public kj::AsyncOutputStream {
#else
template <typename CharType>
class output_stream final {
#endif
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_sink _fd;
temporary_buffer<CharType> _buf;
size_t _size = 0;
size_t _begin = 0;
size_t _end = 0;
bool _trim_to_size = false;
private:
size_t available() const { return _end - _begin; }
size_t possibly_available() const { return _size - _begin; }
future<> split_and_put(temporary_buffer<CharType> buf);
#ifdef __USE_KJ__
kj::Promise<void> kj_split_and_put(temporary_buffer<CharType> buf);
#endif
public:
using char_type = CharType;
output_stream() = default;
output_stream(data_sink fd, size_t size, bool trim_to_size = false)
: _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size) {}
output_stream(output_stream&&) = default;
output_stream& operator=(output_stream&&) = default;
future<> write(const char_type* buf, size_t n);
future<> write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
future<> write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
future<> write(const std::basic_string<char_type>& s);
future<> write(net::packet p);
future<> write(scattered_message<char_type> msg);
future<> flush();
future<> close() { return flush().then([this] { return _fd.close(); }); }
#ifdef __USE_KJ__
kj::Promise<void> kj_write(const char_type* buf, size_t n);
kj::Promise<void> kj_write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
kj::Promise<void> kj_write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
kj::Promise<void> kj_write(const std::basic_string<char_type>& s);
kj::Promise<void> kj_write(net::packet p);
kj::Promise<void> kj_write(scattered_message<char_type> msg);
kj::Promise<void> kj_flush();
kj::Promise<void> kj_close() { return kj_flush().then([this] { return _fd.kj_close(); }); }
kj::Promise<void> write(const void* buffer, size_t size) override {
return kj_write((const char_type*)buffer, size).then([this]() {
return kj_flush();
});
}
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const kj::byte>> pieces) override {
if (pieces.size() == 0) {
return writeInternal(nullptr, nullptr);
} else {
return writeInternal(pieces[0], pieces.slice(1, pieces.size()));
}
}
private:
kj::Promise<void> writeInternal(kj::ArrayPtr<const kj::byte> firstPiece,
kj::ArrayPtr<const kj::ArrayPtr<const kj::byte>> morePieces) {
scattered_message<char> msg;
msg.append_static((char*)firstPiece.begin(),firstPiece.size() );
for (size_t i =0;i<morePieces.size();++i){
auto& buf = morePieces[i];
msg.append_static((char*)buf.begin(),buf.size() );
}
return kj_write(std::move(msg));
// auto promise = kj_write((const char_type*)firstPiece.begin(),firstPiece.size() );
// for (size_t i = 0;i<morePieces.size();++i){
// auto & pieces = morePieces[i];
// promise = promise.then([&pieces,this](){
// return kj_write((const char_type*)pieces.begin(),pieces.size() );
// });
// };
// return promise.then([this]() {
// return kj_flush();
// });
/*KJ_NONBLOCKING_SYSCALL(writeResult = ::writev(fd, iov.begin(), iov.size())) {
// Error.
// We can't "return kj::READY_NOW;" inside this block because it causes a memory leak due to
// a bug that exists in both Clang and GCC:
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=33799
// http://llvm.org/bugs/show_bug.cgi?id=12286
goto error;
}
if (false) {
error:
return kj::READY_NOW;
}
// A negative result means EAGAIN, which we can treat the same as having written zero bytes.
size_t n = writeResult < 0 ? 0 : writeResult;
// Discard all data that was written, then issue a new write for what's left (if any).
for (;;) {
if (n < firstPiece.size()) {
// Only part of the first piece was consumed. Wait for POLLOUT and then write again.
firstPiece = firstPiece.slice(n, firstPiece.size());
return onWritable().then([=]() {
return writeInternal(firstPiece, morePieces);
});
} else if (morePieces.size() == 0) {
// First piece was fully-consumed and there are no more pieces, so we're done.
KJ_DASSERT(n == firstPiece.size(), n);
return kj::READY_NOW;
} else {
// First piece was fully consumed, so move on to the next piece.
n -= firstPiece.size();
firstPiece = morePieces[0];
morePieces = morePieces.slice(1, morePieces.size());
}
}//*/
}
#endif
private:
};
#include "iostream-impl.hh"
| 36.230942 | 144 | 0.622811 | ducthangho |
62949e8bd8513e581a54f3f25af9e3391f1cb932 | 12,728 | cpp | C++ | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 6 | 2018-01-29T10:20:20.000Z | 2021-06-13T05:35:32.000Z | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | null | null | null | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 2 | 2019-04-03T12:10:54.000Z | 2019-05-13T09:44:01.000Z | #include "linker.h"
bool
Linker::poses_comparator(const Pose_Data& pose1, const Pose_Data& pose2) {
return pose1.inlier_fraction > pose2.inlier_fraction;
}
bool
Linker::id_comparator(const ID_Data& id1, const ID_Data& id2) {
return id1.scores[0] < id2.scores[0];
}
/**
Links pose data from the merged cloud called prev_merged_name to the merged cloud called current_merged_name
@param ar Access_Results object
@param m Manipulation object
@param prev_merged_name The main folder name of the previous merged cloud
@param current_merged_name The main folder name of the current merged cloud
@param model_names The model names for each cluster in the current merged cloud, as identified in the pose estimation for the previous merged cloud
@param view_indices The model view indices for clusters in the current merged cloud, as identified in pose estimation for the prev merged cloud
@param model_scores The model scores for clusters in the current merged cloud, as identified in the pose estimation for the prev merged cloud
@returns The merged clusters
*/
std::vector<Linker::Point_Cloud_N::Ptr>
Linker::link_pose_data(Access_Results ar,
Manipulation m,
std::string prev_merged_name,
std::string current_merged_name,
std::vector<std::vector<std::string> > &model_names,
std::vector<std::vector<std::vector<int> > > &view_indices,
std::vector<std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > > poses,
std::vector<std::vector<double> > inlier_fractions,
std::vector<std::vector<double> > accuracies) {
std::vector<std::string> links; // Used for debugging
Point_Cloud_N::Ptr scene_original (new Point_Cloud_N);
Point_Cloud_N::Ptr scene (new Point_Cloud_N);
std::vector<Point_Cloud_N::Ptr> prev_merged_clusters;
std::vector<Point_Cloud_N::Ptr> current_merged_clusters;
std::vector<std::vector<Pose_Data> > cluster_pose_data; // Object used to keep track of all pose data for each cluster
// Get clusters
ar.load_segmentation_results(prev_merged_name + "/merged", scene_original, scene, prev_merged_clusters);
ar.load_segmentation_results(current_merged_name + "/merged", scene_original, scene, current_merged_clusters);
model_names.resize(current_merged_clusters.size());
view_indices.resize(current_merged_clusters.size());
poses.resize(current_merged_clusters.size());
inlier_fractions.resize(current_merged_clusters.size());
accuracies.resize(current_merged_clusters.size());
cluster_pose_data.resize(current_merged_clusters.size());
// Get transformation matrices and compute transformation between clouds
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_CtoH = ar.get_T_CtoH();
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_prev_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + prev_merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_current_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + current_merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_prev_to_current = T_CtoH.inverse() * T_current_merged.inverse()*T_prev_merged * T_CtoH;
// Loop through each cluster in prev_merged_clusters
for(int i = 0; i < prev_merged_clusters.size(); i++) {
// Transform the previous cluster to the current_merged_clusters coordinate system
Point_Cloud_N::Ptr prev_cluster = prev_merged_clusters[i];
pcl::transformPointCloud(*prev_cluster, *prev_cluster, T_prev_to_current);
/*
std::vector<std::string> model_names_prev;
std::vector<std::vector<int> > view_indices_prev;
std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > poses_prev;
std::vector<double> inlier_fractions_prev;
std::vector<double> accuracies_prev;
ar.load_pose_estimation_results(prev_merged_name, i, model_names_prev, view_indices_prev, poses_prev, inlier_fractions_prev, accuracies_prev);
*/
std::vector<Pose_Data> prev_pose_data;
ar.load_pose_estimation_results_pose_format(prev_merged_name, i, prev_pose_data);
// Loop through each cluster in current_merged_clusters
for(int n = 0; n < current_merged_clusters.size(); n++) {
// Compute inliers when fitting the previous cluster to the current cluster
std::vector<int> inliers;
std::vector<int> outliers;
m.compute_inliers(current_merged_clusters[n], prev_merged_clusters[i], 0.001, &inliers, &outliers);
double inlier_fraction = (double) inliers.size() / (double) prev_merged_clusters[i]->points.size();
// If it fits, data for the current cluster should be equal to data for the previous cluster
if(inlier_fraction > 0) {
std::cout << "Linked pose data from previous cluster " << i << " to current cluster " << n << '\n';
/*
if(cluster_pose_data[n].size() > 0) {
std::cout << "\tCurrent cluster " << n << " has already been merged before!!" << '\n';
}
*/
cluster_pose_data[n].insert(cluster_pose_data[n].end(), prev_pose_data.begin(), prev_pose_data.end());
/*
model_names[n].insert(model_names[n].end(), model_names_prev.begin(), model_names_prev.end());
view_indices[n].insert(view_indices[n].end(), view_indices_prev.begin(), view_indices_prev.end());
poses[n].insert(poses[n].end(), poses_prev.begin(), poses_prev.end());
inlier_fractions[n].insert(inlier_fractions[n].end(), inlier_fractions_prev.begin(), inlier_fractions_prev.end());
accuracies[n].insert(accuracies[n].end(), accuracies_prev.begin(), accuracies_prev.end());
*/
/*
model_names[n] = model_names_prev;
view_indices[n] = view_indices_prev;
poses[n] = poses_prev;
inlier_fractions[n] = inlier_fractions_prev;
accuracies[n] = accuracies_prev;
*/
std::ostringstream oss;
oss << i << "->" << n;
links.push_back(oss.str());
break;
}
}
}
// Sort cluster_pose_data for each cluster based on inlier_fraction
for(int c = 0; c < cluster_pose_data.size(); c++) {
std::sort(cluster_pose_data[c].begin(), cluster_pose_data[c].end(), poses_comparator);
}
// Move data back into vectors
for(int c = 0; c < cluster_pose_data.size(); c++) {
std::cout << "Linked pose data from cluster " << c << '\n';
std::vector<std::string> m_n;
std::vector<std::vector<int> > v_i;
std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > p;
std::vector<double> i_f;
std::vector<double> acc;
for(int i = 0; i < cluster_pose_data[c].size(); i++) {
std::cout << "\t" << cluster_pose_data[c][i].model_name << ",";
for(int n = 0; n < cluster_pose_data[c][i].view_indices.size(); n++) {
std::cout << cluster_pose_data[c][i].view_indices[n] << "+";
}
std::cout << "," << cluster_pose_data[c][i].inlier_fraction << "," << cluster_pose_data[c][i].accuracy << '\n';
m_n.push_back(cluster_pose_data[c][i].model_name);
v_i.push_back(cluster_pose_data[c][i].view_indices);
p.push_back(cluster_pose_data[c][i].transformation);
i_f.push_back(cluster_pose_data[c][i].inlier_fraction);
acc.push_back(cluster_pose_data[c][i].accuracy);
}
model_names[c] = m_n;
view_indices[c] = v_i;
poses[c] = p;
inlier_fractions[c] = i_f;
accuracies[c] = acc;
}
// Write link data (for debugging purposes)
std::ofstream ofs;
std::string p = ar.path_to_segmentation_results().string() + "/" + current_merged_name + "/merged/pose_link_" + prev_merged_name;
std::cout << "WRITING POSE LINK DEBUG DATA TO " << p << '\n';
ofs.open(p.c_str());
for(int i = 0; i < links.size(); i++) {
ofs << links[i] << "\n";
}
ofs.close();
return current_merged_clusters;
}
/**
Links identification data from single_name to merged_name
@param ar Access_Results object
@param m Manipulation object
@param single_name The main folder name of the single cloud
@param merged_name The main folder name of the merged cloud
@param models_single_in_merged The model names for each merged clusters, as identified in the linked single cluster
@param model_view_indices_1_in_2 The model view indices for each merged clusters, as identified in the linked single cluster
@param model_scores_1_in_2 The model scores for each merged clusters, as identified in the linked single cluster
@returns The merged clusters
*/
std::vector<Linker::Point_Cloud_N::Ptr>
Linker::link_identification_data(Access_Results ar,
Manipulation m,
std::string single_name,
std::string merged_name,
std::vector<std::vector<std::string> > &models_single_in_merged,
std::vector<std::vector<std::vector<int> > > &model_view_indices_single_in_merged,
std::vector<std::vector<std::vector<float> > > &model_scores_single_in_merged) {
std::vector<std::string> links; // Used for debugging
Point_Cloud_N::Ptr scene_original (new Point_Cloud_N);
Point_Cloud_N::Ptr scene (new Point_Cloud_N);
std::vector<Point_Cloud_N::Ptr> single_clusters;
std::vector<Point_Cloud_N::Ptr> merged_clusters;
std::vector<std::vector<ID_Data> > cluster_id_data; // Object used to keep track of all ID data for each cluster
// Get clusters
ar.load_segmentation_results(single_name + "/single", scene_original, scene, single_clusters);
ar.load_segmentation_results(merged_name + "/merged", scene_original, scene, merged_clusters);
models_single_in_merged.resize(merged_clusters.size());
model_view_indices_single_in_merged.resize(merged_clusters.size());
model_scores_single_in_merged.resize(merged_clusters.size());
cluster_id_data.resize(merged_clusters.size());
// Get transformation matrices and compute transformation between clouds
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_CtoH = ar.get_T_CtoH();
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_single = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + single_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_single_to_merged = T_CtoH.inverse() * T_merged.inverse()*T_single * T_CtoH;
// Loop through each cluster in single_clusters
for(int i = 0; i < single_clusters.size(); i++) {
// Transform the single cluster to the merged_clusters coordinate system
Point_Cloud_N::Ptr single_cluster = single_clusters[i];
pcl::transformPointCloud(*single_cluster, *single_cluster, T_single_to_merged);
std::vector<ID_Data> id_data;
ar.load_identification_results_id_data_format(single_name, i, id_data);
// Loop through each cluster in merged clusters
for(int n = 0; n < merged_clusters.size(); n++) {
// Compute inliers when fitting the single cluster into the merged cluster
std::vector<int> inliers;
std::vector<int> outliers;
m.compute_inliers(merged_clusters[n], single_clusters[i], 0.001, &inliers, &outliers);
double inlier_fraction = (double) inliers.size() / (double) single_clusters[i]->points.size();
// If it fits, data for the merged cluster should be equal to data for the single cluster
if(inlier_fraction > 0) {
std::cout << "Linked ID data from single cluster " << i << " to merged cluster " << n << '\n';
cluster_id_data[n].insert(cluster_id_data[n].end(), id_data.begin(), id_data.end());
std::ostringstream oss;
oss << i << "->" << n;
links.push_back(oss.str());
break;
}
}
}
// Sort ID data
for(int c = 0; c < cluster_id_data.size(); c++) {
std::sort(cluster_id_data[c].begin(), cluster_id_data[c].end(), id_comparator);
}
// Move data back into vectors
for(int c = 0; c < cluster_id_data.size(); c++) {
std::cout << "Linked ID data for cluster " << c << '\n';
std::vector<std::string> m_n;
std::vector<std::vector<int> > v_i;
std::vector<std::vector<float> > s;
for(int i = 0; i < cluster_id_data[c].size(); i++) {
std::cout << "\t" << cluster_id_data[c][i].model_name << ",";
for(int n = 0; n < cluster_id_data[c][i].view_indices.size(); n++) {
std::cout << cluster_id_data[c][i].view_indices[n] << "," << cluster_id_data[c][i].scores[n] << ",";
}
std::cout << '\n';
m_n.push_back(cluster_id_data[c][i].model_name);
v_i.push_back(cluster_id_data[c][i].view_indices);
s.push_back(cluster_id_data[c][i].scores);
}
models_single_in_merged[c] = m_n;
model_view_indices_single_in_merged[c] = v_i;
model_scores_single_in_merged[c] = s;
}
// Write link data (for debugging purposes)
std::ofstream ofs;
std::string p = ar.path_to_segmentation_results().string() + "/" + merged_name + "/merged/id_link_" + single_name;
std::cout << "WRITING ID LINK DEBUG DATA TO " << p << '\n';
ofs.open(p.c_str());
for(int i = 0; i < links.size(); i++) {
ofs << links[i] << "\n";
}
ofs.close();
return merged_clusters;
}
| 45.620072 | 179 | 0.719045 | Laxen |
62a2691247bc3e7481468ed36136d70a3ac99a2e | 480 | cpp | C++ | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | // https://atcoder.jp/contests/abc168/tasks/abc168_b
#include <bits/stdc++.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int K;
string S;
cin >> K >> S;
if (S.size() <= K) {
cout << S << endl;
} else {
string Q = S.substr(0, K) + "...";
cout << Q << endl;
}
return 0;
} | 17.777778 | 52 | 0.55 | xirc |
62a993753ae18d905faa64ac35935d3a7cfd92ec | 3,720 | cpp | C++ | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | 1 | 2018-12-05T18:32:50.000Z | 2018-12-05T18:32:50.000Z | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <array>
#include <regex>
#include <vector>
typedef int ll;
ll getManhattenDist4D(std::array<ll, 4>, std::array<ll, 4>);
std::list<std::string> getInputPerLines(std::string);
int main() {
std::array<ll, 4> point;
std::vector<std::array<ll, 4>> pointList;
// PARSE INPUT
std::list<std::string> pointStrings = getInputPerLines("input_Day25.txt");
std::regex regexpr("(-?[0-9]+)");
std::smatch m;
for (std::list<std::string>::iterator it = pointStrings.begin(); it != pointStrings.end(); ++it) {
std::regex_iterator<std::string::iterator> rit(it->begin(), it->end(), regexpr);
std::regex_iterator<std::string::iterator> rend;
point[0] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[1] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[2] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[3] = std::stoi(rit->str(), nullptr, 0);
//for (auto n : point) {
// std::cout << n << " ";
//}
//std::cout << std::endl;
pointList.push_back(point);
}
//std::cout << "=====================" << std::endl;
int numConst = 1;
int dist;
std::vector<int> usedPoints(pointList.size(),0);
std::vector<int> cliqueIdx;
std::vector<std::vector<int>> cliqueListIdx;
for (int i = 0; i < pointList.size(); ++i) {
if (usedPoints[i] < 1) {
cliqueIdx.push_back(i);
usedPoints[i] = numConst;
bool stillMembersToCheck = true;
while (stillMembersToCheck) {
stillMembersToCheck = false;
}
for (int j = 0; j < pointList.size(); ++j) {
if (i == j) continue;
bool isInConstellation = false;
//bool notAlreadyContained = true;
for (int k = 0; k < cliqueIdx.size(); ++k) {
dist = getManhattenDist4D(pointList[cliqueIdx[k]], pointList[j]);
//std::cout << "Dist: " << j << "-" << cliqueIdx[k] << ": " << dist << std::endl;
if (dist < 4 &&
j != cliqueIdx[k] &&
usedPoints[j] < 1) {
//std::cout << "\t MatchDist: " << j << "-" << cliqueIdx[k] << ": " << dist << std::endl;
// these two point form a constelation
isInConstellation = true;
break;
}
}
if (isInConstellation) {
//std::cout << "Adding " << j << " to clique " << numConst << std::endl;
cliqueIdx.push_back(j);
usedPoints[j] = numConst;
j = 0; // start over
// DEBUG
//for (auto s : cliqueIdx) {
// std::cout << "[" << s << "]" << " ";
//}
//std::cout << std::endl;
//std::cin.get();
}
}
cliqueListIdx.push_back(cliqueIdx);
cliqueIdx.erase(cliqueIdx.begin(), cliqueIdx.end());
}
++numConst;
}
//std::cout << "=====================" << std::endl;
numConst = 0;
for (auto c : cliqueListIdx) {
if (c.size() > 2) ++numConst;
for (auto s : c) {
std::cout << "[" << s << "]" << " ";
}
std::cout << std::endl;
}
std::cout << "Num Constellations: " << cliqueListIdx.size() << std::endl;
// 169: too low
// 567: too high (counted all longly single points as well)
return 0;
}
/******************************
* INPUT HELPER FUNCTIONS *
******************************/
ll getManhattenDist4D(std::array<ll, 4> a, std::array<ll, 4> b)
{
ll dist;
dist = abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]);
return dist;
}
std::list<std::string> getInputPerLines(std::string fileName) {
std::list<std::string> lines;
std::string line;
// Open File
std::ifstream in(fileName);
if (!in.is_open() || !in.good()) {
std::cout << "Failed to open input" << std::endl;
lines.push_back(std::string()); // empty string
return lines;
}
// Create Vector of lines
while (getline(in, line)) {
lines.push_back(line);
}
in.close();
return lines;
} | 25.655172 | 99 | 0.560753 | ATRI17Z |
62ade6f1df319792c79f00f6e4b4194a8d8b2d7c | 1,015 | cpp | C++ | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
int m[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int y,mon,d;
char date[10];// 1985/1/20
while(~scanf("%s", date)){
getchar();
m[2] = 28;
y = (date[0]-'0')*1000+(date[1]-'0')*100+(date[2]-'0')*10+date[3]-'0';
if(date[6] == '/'){
mon = date[5]-'0';
if(strlen(date) == 8) d = date[7]-'0';
else d = (date[7]-'0')*10 +date[8]-'0';
}else{
mon = (date[5]-'0')*10+date[6]-'0';
if(strlen(date) == 9) d = date[8]-'0';
else d = (date[8]-'0')*10 +date[9]-'0';
}
if( y%400==0 || (y%4==0 && y%100!=0))
m[2] = 29;
if(mon == 1){
printf("%d\n", d);
}else{
int i=1;
while(i<mon){
d += m[i];
i++;
}
printf("%d\n", d);
}
}
return 0;
}
| 25.375 | 78 | 0.375369 | hunterMG |
62b355299e738802da25d86381eeab9604199668 | 1,680 | cpp | C++ | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | 5 | 2018-10-07T11:13:18.000Z | 2021-11-18T13:57:27.000Z | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | null | null | null | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | 1 | 2018-12-07T18:20:17.000Z | 2018-12-07T18:20:17.000Z | /*-------------------------------------------------------------------------
This source file is a part of Placid
For the latest info, see http:www.marrin.org/
Copyright (c) 2018-2019, Chris Marrin
All rights reserved.
Use of this source code is governed by the MIT license that can be
found in the LICENSE file.
-------------------------------------------------------------------------*/
#include "bare.h"
#include "bare/Serial.h"
#include "bare/GPIO.h"
#include "bare/InterruptManager.h"
#include "bare/Timer.h"
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <util.h>
#include <termios.h>
//#define USE_PTY
using namespace bare;
#ifdef USE_PTY
static int master;
static int slave;
#endif
void Serial::init(uint32_t baudrate)
{
#ifdef USE_PTY
struct termios tty;
tty.c_iflag = (tcflag_t) 0;
tty.c_lflag = (tcflag_t) 0;
tty.c_cflag = CS8;
tty.c_oflag = (tcflag_t) 0;
char buf[256];
auto e = openpty(&master, &slave, buf, &tty, nullptr);
if(0 > e) {
::printf("Error: %s\n", strerror(errno));
return;
}
::printf("Slave PTY: %s\n", buf);
fflush(stdout);
#endif
}
Serial::Error Serial::read(uint8_t& c)
{
#ifdef USE_PTY
return (::read(master, &c, 1) == -1) ? Error::Fail : Error::OK;
#else
c = getchar();
return Error::OK;
#endif
}
bool Serial::rxReady()
{
return true;
}
Serial::Error Serial::write(uint8_t c)
{
#ifdef USE_PTY
::write(master, &c, 1);
#else
if (c != '\r') {
std::cout.write(reinterpret_cast<const char*>(&c), 1);
}
#endif
return Error::OK;
}
void Serial::handleInterrupt()
{
}
void Serial::clearInput()
{
}
| 18.26087 | 75 | 0.574405 | cmarrin |
62b445c9a6c11810df1ff6cde9a5f65e11b3515a | 2,106 | cc | C++ | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 20 | 2020-06-28T03:55:40.000Z | 2022-03-08T06:00:31.000Z | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | null | null | null | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 1 | 2020-06-29T08:47:21.000Z | 2020-06-29T08:47:21.000Z | //
// Created by panda on 2021/2/28.
//
#include "quad.h"
using namespace DR;
Quad::Quad(observer_ptr<Transform> LocalToWorld,
observer_ptr<Transform> WorldToObject, Point3f a, Point3f b,
Point3f c, bool reverse)
: Shape(LocalToWorld, WorldToObject, reverse)
// clang-format off
/*
* (2)c ------- d(3)
* / \ /
* / \ /
* /------/
* a(0) b(1)
* index: 0 1 2
* index: 1 3 2
*/
// clang-format on
{
vec3 ad = (b - a) + (c - a);
Point3f d = a + ad;
std::vector<Point3f> vertices{a, b, c, d};
int nVertices = 4;
int nTriangles = 2;
std::vector<DR::uint> vertexIndices{0, 1, 2, 1, 3, 2};
Normal3f normal = reverse ? (c - a).cross(b - a) : (b - a).cross(c - a);
normal = normal.normalize();
std::vector<Normal3f> normals(4, normal);
std::vector<Point2f> uvs{{0, 0}, {0, 1}, {1, 0}, {1, 1}};
std::vector<int> faceIndices(nTriangles, 0);
auto mesh_ptr = std::make_shared<TriangleMesh>(
LocalToWorld, nTriangles, nVertices, vertexIndices.data(),
vertices.data(), normals.data(), uvs.data(), faceIndices.data());
this->tris_[0] = std::make_unique<Triangle>(LocalToWorld, WorldToObject,
reverse, mesh_ptr, 0);
this->tris_[1] = std::make_unique<Triangle>(LocalToWorld, WorldToObject,
reverse, mesh_ptr, 1);
}
Bounds3 Quad::ObjectBounds() const {
return Bounds3::Union(tris_[0]->ObjectBounds(), tris_[1]->ObjectBounds());
}
Bounds3 Quad::WorldBounds() const {
return Bounds3::Union(tris_[0]->WorldBounds(), tris_[1]->WorldBounds());
}
bool Quad::Intersect(const Ray &ray, float *time, Intersection *isect) const {
if (tris_[0]->Intersect(ray, time, isect))
return true;
return tris_[1]->Intersect(ray, time, isect);
}
float Quad::Area() const { return tris_[0]->Area() + tris_[1]->Area(); }
std::pair<Intersection, float> Quad::sample() const {
// naive sampler
int index = get_random_float() > 0.5 ? 0 : 1;
return tris_[index]->sample();
}
| 34.52459 | 78 | 0.581671 | BlurryLight |
62bb221b2319ebc04c68b74a53c08295f08adc42 | 1,358 | cpp | C++ | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 25 | 2019-05-20T08:07:39.000Z | 2021-08-17T11:25:02.000Z | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | null | null | null | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 17 | 2019-07-07T12:20:16.000Z | 2022-01-11T08:27:44.000Z | #include <string>
#include <ace/Singleton.h>
#include "HalfNetworkType.h"
#include "ReactorPool.h"
namespace HalfNetwork
{
/////////////////////////////////////////
// ReactorTask
/////////////////////////////////////////
ReactorTask::ReactorTask()
{
this->reactor(ACE_Reactor::instance());
}
ReactorTask::~ReactorTask()
{
this->reactor(NULL);
}
bool ReactorTask::Open(uint8 poolSize)
{
int properPoolSize = poolSize;
if (0 == properPoolSize)
properPoolSize = 1;
m_poolSize = properPoolSize;
return (-1 != this->activate(THR_NEW_LWP|THR_JOINABLE, m_poolSize));
}
void ReactorTask::Close()
{
ACE_Reactor::instance()->end_reactor_event_loop();
this->wait();
ACE_Reactor::instance()->reset_reactor_event_loop();
}
uint8 ReactorTask::GetPoolSize()
{
return m_poolSize;
}
int ReactorTask::svc()
{
ACE_Reactor::instance()->owner(ACE_Thread::self());
ACE_Reactor::instance()->run_reactor_event_loop();
return 0;
}
/////////////////////////////////////////
// ReactorPool
/////////////////////////////////////////
bool ReactorPool::Open(uint8 poolSize)
{
return _task.Open(poolSize);
}
void ReactorPool::Close()
{
_task.Close();
}
uint8 ReactorPool::GetPoolSize()
{
return _task.GetPoolSize();
}
} // namespace HalfNetwork | 20.268657 | 71 | 0.576583 | cjwcjswo |
62bdaeffef0d5c0a033cefe99c63556843f15e5e | 3,249 | cc | C++ | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | 12 | 2016-12-01T02:49:35.000Z | 2020-11-23T14:32:24.000Z | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | null | null | null | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | 6 | 2018-01-25T03:42:07.000Z | 2020-11-03T04:19:21.000Z | /*
* Copyright (c) 2016, https://github.com/nebula-im/imengine
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dal/group_dao_impl.h"
GroupDAO& GroupDAO::GetInstance() {
static GroupDAOImpl impl;
return impl;
}
int GroupDAOImpl::CheckExists(const std::string& creator_user_id, uint64_t client_group_id) {
return DoStorageQuery("nebula_engine",
[&](std::string& query_string) {
folly::format(&query_string, "SELECT id FROM groups WHERE creator_user_id='{}' AND client_group_id={} LIMIT 1",
creator_user_id,
client_group_id);
},
[&](MysqlResultSet& answ) -> int {
return BREAK;
});
}
int64_t GroupDAOImpl::Create(GroupDO& group) {
return DoStorageInsertID("nebula_engine",
[&](std::string& query_string) {
QueryParam p;
p.AddParam(group.group_id.c_str());
p.AddParam(group.creator_user_id.c_str());
p.AddParam(&group.client_group_id);
p.AddParamEsc(group.title.c_str());
p.AddParamEsc(group.avatar.c_str());
p.AddParamEsc(group.topic.c_str());
p.AddParamEsc(group.about.c_str());
p.AddParam(&group.created_at);
p.AddParam(&group.updated_at);
MakeQueryString("INSERT INTO groups "
"(group_id,creator_user_id,client_group_id,title,avatar,topic,about,status,created_at,updated_at) "
"VALUES "
"(:1,:2,:3,:4,:5,:6,:7,1,:8,:9)",
&p,
&query_string);
});
}
int GroupDAOImpl::GetGroup(const std::string& group_id, GroupDO& group) {
return DoStorageQuery("nebula_engine",
[&](std::string& query_string) {
folly::format(&query_string, "SELECT id FROM groups WHERE group_id='{}' LIMIT 1",
group_id);
},
[&](MysqlResultSet& answ) -> int {
group.app_id = 1;
// ...
return BREAK;
});
}
| 45.125 | 148 | 0.480148 | nebula-im |
62bdb0d602368a1aba7f31194b7bf570985447e3 | 459 | hpp | C++ | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | 3 | 2015-08-19T19:29:28.000Z | 2016-11-15T07:41:06.000Z | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | null | null | null | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | null | null | null | #ifndef KEYHOOK_HPP
#define KEYHOOK_HPP
#include <string>
#include <functional>
typedef std::function<bool()> KeyPressedCallback;
bool isKeyRegistered(const std::string& key);
bool registerKey(const std::string& key, KeyPressedCallback callback);
bool unregisterKey(const std::string& key);
bool initializeKeyhook();
bool destroyKeyhook();
void setKeyboardHookedCallback(std::function<void(bool)> callback);
void unsetKeyboardHookedCallback();
#endif | 20.863636 | 70 | 0.79085 | agrippa1994 |
498ba48a20f7569d7ea878890b12a5fba546d518 | 787 | cpp | C++ | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
/*program to explain the concept of namespaces
namespaces consists of a set of identifiers which are local to that particular name space.Also namespaces are like the lastname of a 2 persons having different names.
Like we can differentiate 2persons with smae first names using their last names(Which are different) in the same way to avoid name collisions in c++, we use
namespaces.
To access members of a namespace outside it, we have to use scope resolution operator.
'using' keyword actually loads the particular namespace into the golbal namespace or global scope.
Each program has a un-named or anynymous namespace.
*/
#include "one.cpp"
#include "two.cpp"
int main()
{
one::x=20;
one::display();
two::x=30;
two::display();
}
| 26.233333 | 166 | 0.76493 | anjali9811 |
498d73819a96ddf8ea1759cbfd7076d67af9f7cd | 3,150 | hh | C++ | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 19 | 2018-04-23T09:30:48.000Z | 2022-03-06T21:35:18.000Z | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 22 | 2017-11-27T23:39:25.000Z | 2019-08-09T08:56:57.000Z | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 28 | 2017-11-16T20:53:56.000Z | 2021-01-04T11:13:17.000Z | <?hh // strict
namespace Zynga\Framework\StorableObject\V1;
use JsonSerializable;
use Zynga\Framework\StorableObject\V1\Interfaces\StorableObjectInterface;
use
Zynga\Framework\StorableObject\V1\Exceptions\MissingKeyFromImportDataException
;
use Zynga\Framework\StorableObject\V1\Exceptions\UnsupportedTypeException;
use
Zynga\Framework\StorableObject\V1\Exceptions\PropertyUnavailableException
;
use
Zynga\Framework\StorableObject\V1\Exceptions\ExpectedFieldCountMismatchException
;
use Zynga\Framework\StorableObject\V1\SupportedTypes;
use Zynga\Framework\StorableObject\V1\Interfaces\ImportInterface;
use Zynga\Framework\StorableObject\V1\Interfaces\ExportInterface;
use Zynga\Framework\StorableObject\V1\Interfaces\FieldsInterface;
use Zynga\Framework\StorableObject\V1\Object\Importer;
use Zynga\Framework\StorableObject\V1\Object\Exporter;
use Zynga\Type\V1\Interfaces\TypeInterface;
use Zynga\Framework\StorableObject\V1\Fields;
use Zynga\Framework\StorableObject\V1\Fields\Generic as FieldsGeneric;
use Zynga\Framework\Exception\V1\Exception;
abstract class Base implements StorableObjectInterface, JsonSerializable {
private bool $_isRequired;
private ?bool $_isDefaultValue;
public function __construct() {
// --
// As hack requires you to not use $this-><func> until the init is overwith
// we can make the assumption the default value is going to be set for the
// object
// --
$this->_isRequired = false;
$this->_isDefaultValue = null;
}
public function fields(): FieldsInterface {
$fields = new Fields($this);
return $fields;
}
public function import(): ImportInterface {
$importer = new Importer($this);
return $importer;
}
public function export(): ExportInterface {
$exporter = new Exporter($this);
return $exporter;
}
public function setIsRequired(bool $isRequired): bool {
$this->_isRequired = $isRequired;
return true;
}
public function getIsRequired(): bool {
return $this->_isRequired;
}
public function setIsDefaultValue(bool $tf): bool {
$this->_isDefaultValue = $tf;
return true;
}
public function isDefaultValue(): (bool, Vector<string>) {
$defaultFields = Vector {};
if ($this->_isDefaultValue !== null) {
return tuple($this->_isDefaultValue, $defaultFields);
}
$fields = $this->fields()->getForObject();
foreach ($fields as $fieldName => $field) {
list($f_isRequired, $f_isDefaultValue) =
FieldsGeneric::getIsRequiredAndIsDefaultValue($field);
// echo json_encode(array(get_class($this), $fieldName, $f_isDefaultValue)) . "\n";
if ($f_isDefaultValue === true) {
$defaultFields[] = $fieldName;
}
}
$isDefaultValue = true;
// --
// if any of the fields or child fields are not the default,
// we are okay marking this object as not default.
// --
if ($defaultFields->count() != $fields->count()) {
$isDefaultValue = false;
}
return tuple($isDefaultValue, $defaultFields);
}
public function jsonSerialize(): mixed {
return $this->export()->asMap()->toArray();
}
}
| 26.25 | 89 | 0.713333 | chintan-j-patel |
499065902e136fd401a2fcbc4826c7116b0293b3 | 828 | cpp | C++ | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <iomanip>
#include "console.h"
#include "timer.h"
#include "hashset.h"
#include "lexicon.h"
#include "queue.h"
#include "set.h"
#include "vector.h"
#include "grid.h"
#include "filelib.h"
#include "gwindow.h"
#include "gobjects.h"
#include "simpio.h"
#include "ghanoi.h"
using namespace std;
static const int N = 5;
void findSolution(int n, char source, char target, char aux) {
// All about that base
if(n == 1) {
moveSingleDisk(source, target);
// Recursive case
} else {
findSolution(n - 1, source, aux, target);
moveSingleDisk(source, target);
findSolution(n - 1, aux, target, source);
}
}
int main() {
cout << "Towers of Hanoi" << endl;
initHanoiDisplay(N);
findSolution(N, 'a', 'c', 'b');
return 0;
}
| 19.714286 | 62 | 0.628019 | tofergregg |
49943a09d854cd6ab0ddb0b87fc8edf1c5ba6e6e | 767 | cpp | C++ | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | 1 | 2020-10-21T07:53:54.000Z | 2020-10-21T07:53:54.000Z | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | null | null | null | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | 1 | 2020-10-20T09:11:34.000Z | 2020-10-20T09:11:34.000Z | #include <bits/stdc++.h>
using namespace std;
void bubblesort(int a[],int n)
{
for (int i=0; i<n-1; i++)
{
bool swapped = false;
for (int j=0; j<n-i-1; j++)
{
if (a[j]>a[j+1])
{
swap(a[j],a[j+1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
int main(void)
{
int arr[10],i,ans;
cout << "Enter 10 elements in array: " << endl;
for (int i=0; i<10; i++)
cin >> arr[i];
cout << "Original Array is: ";
for (int i=0; i<10; i++)
cout << arr[i] << " ";
cout << "\n";
bubblesort(arr,10);
cout << "Array after sorting is: ";
for (int i=0; i<10; i++)
cout << arr[i] << " ";
}
| 20.72973 | 51 | 0.411995 | VanshMaheshwari30 |
499884591bc69d37dac296592b1491123427b87d | 12,848 | cpp | C++ | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaGUICrossSplitter
Authors: Silvano Imboden
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaDecl.h"
#include "albaGUICrossSplitter.h"
//----------------------------------------------------------------------------
// albaGUICrossSplitter
//----------------------------------------------------------------------------
BEGIN_EVENT_TABLE(albaGUICrossSplitter,albaGUIPanel)
EVT_SIZE(albaGUICrossSplitter::OnSize)
EVT_LEFT_DOWN(albaGUICrossSplitter::OnLeftMouseButtonDown)
EVT_LEFT_UP(albaGUICrossSplitter::OnLeftMouseButtonUp)
EVT_MOTION(albaGUICrossSplitter::OnMouseMotion)
EVT_LEAVE_WINDOW(albaGUICrossSplitter::OnMouseMotion)
END_EVENT_TABLE()
//----------------------------------------------------------------------------
albaGUICrossSplitter::albaGUICrossSplitter(wxWindow* parent,wxWindowID id)
: albaGUIPanel(parent, id)
//----------------------------------------------------------------------------
{
m_ViewPanel1 = new wxPanel(this,1,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel2 = new wxPanel(this,2,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel3 = new wxPanel(this,3,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel4 = new wxPanel(this,4,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_Maximized = false;
m_FocusedPanel = m_ViewPanel1;
m_CursorNS = new wxCursor(wxCURSOR_SIZENS);
m_CursorWE = new wxCursor(wxCURSOR_SIZEWE);
m_CursorNSWE = new wxCursor(wxCURSOR_SIZING);
m_Pen = new wxPen(*wxBLACK, 2, wxSOLID);
m_With = m_Height = 100;
m_XPos = m_YPos = m_Margin = 20;
m_Dragging = drag_none;
m_RelXPos = m_RelYPos = 0.5,
Split(VA_FOUR);
}
//----------------------------------------------------------------------------
albaGUICrossSplitter::~albaGUICrossSplitter()
//----------------------------------------------------------------------------
{
delete m_CursorNS;
delete m_CursorWE;
delete m_CursorNSWE;
delete m_Pen;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnSize(wxSizeEvent &event)
//----------------------------------------------------------------------------
{
wxPanel::OnSize(event);
albaYield();
if (m_With == -1 )
{
return;
}
GetClientSize(&m_With,&m_Height);
m_XPos = m_RelXPos * m_With;
m_YPos = m_RelYPos * m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Split(CrossSplitterModes mode)
//----------------------------------------------------------------------------
{
m_Maximized = false;
m_Mode = mode;
switch(m_Mode)
{
case VA_ONE:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(false);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
break;
case VA_TWO_VERT:
case VA_TWO_HORZ:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
break;
case VA_THREE_UP:
case VA_THREE_DOWN:
case VA_THREE_LEFT:
case VA_THREE_RIGHT:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(true);
m_ViewPanel4->Show(false);
break;
case VA_FOUR:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(true);
m_ViewPanel4->Show(true);
break;
}
m_RelXPos = 0.5;
m_RelYPos = 0.5;
m_XPos = m_With * m_RelXPos;
m_YPos = m_Height * m_RelYPos;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetSplitPos(int x,int y)
//----------------------------------------------------------------------------
{
if (m_XPos < m_Margin) m_XPos = m_Margin;
if (m_XPos > m_With - m_Margin) m_XPos = m_With - m_Margin;
if (m_YPos < m_Margin) m_YPos = m_Margin;
if (m_YPos > m_Height - m_Margin) m_YPos = m_Height - m_Margin;
m_XPos = x;
m_YPos = y;
m_RelXPos = (x * 1.0 )/m_With;
m_RelYPos = (y * 1.0 )/m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetSplitPosRel(float x,float y)
//----------------------------------------------------------------------------
{
m_RelXPos = x;
m_RelYPos = y;
m_XPos = x * m_With;
m_YPos = y * m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLeftMouseButtonDown(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
CaptureMouse();
m_Dragging = HitTest(event);
if(m_Dragging == 0) return;
int x = event.GetX();
int y = event.GetY();
DrawTracker(x,y);
m_OldXPos = x;
m_OldYPos = y;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLeftMouseButtonUp(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
if(m_Dragging != drag_none)
{
DrawTracker(m_OldXPos,m_OldYPos);
int x = event.GetX();
int y = event.GetY();
switch(m_Dragging)
{
case drag_y:
SetSplitPos(m_XPos,y);
break;
case drag_x:
SetSplitPos(x,m_YPos);
break;
case drag_xy:
SetSplitPos(x,y);
break;
}
m_Dragging = drag_none;
}
ReleaseMouse();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnMouseMotion(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
if (m_Dragging == drag_none )
{
switch(HitTest(event))
{
case drag_y:
SetCursor(*m_CursorNS);
break;
case drag_x:
SetCursor(*m_CursorWE);
break;
case drag_xy:
SetCursor(*m_CursorNSWE);
break;
case drag_none:
SetCursor(*wxSTANDARD_CURSOR);
break;
}
}
else
{
int x = event.GetX();
int y = event.GetY();
DrawTracker(m_OldXPos,m_OldYPos);
DrawTracker(x,y);
m_OldXPos = x;
m_OldYPos = y;
}
if( event.Leaving() )
{
SetCursor(*wxSTANDARD_CURSOR);
}
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLayout()
//----------------------------------------------------------------------------
{
if (m_XPos < m_Margin) m_XPos = m_Margin;
if (m_XPos > m_With - m_Margin) m_XPos = m_With - m_Margin;
if (m_YPos < m_Margin) m_YPos = m_Margin;
if (m_YPos > m_Height - m_Margin) m_YPos = m_Height - m_Margin;
int m = 3;
int w = m_With -m;
int h = m_Height -m;
int x1 = 0;
int x2 = m_XPos + m;
int y1 = 0;
int y2 = m_YPos + m;
int w1 = m_XPos - m;
int w2 = w - m_XPos -m;
int h1 = m_YPos - m;
int h2 = h - m_YPos -m;
if(this->m_Maximized)
{
this->m_FocusedPanel->Move(x1, y1);
this->m_FocusedPanel->SetSize(w,h);
}
else
{
switch(m_Mode)
{
case VA_ONE:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h);
break;
case VA_TWO_VERT:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h);
break;
case VA_TWO_HORZ:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h1);
m_ViewPanel2->Move(x1,y2);
m_ViewPanel2->SetSize(w,h2);
break;
case VA_THREE_UP:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h1);
m_ViewPanel2->Move(x1, y2);
m_ViewPanel2->SetSize(w1,h2);
m_ViewPanel3->Move(x2, y2);
m_ViewPanel3->SetSize(w2,h2);
break;
case VA_THREE_DOWN:
m_ViewPanel1->Move(x1, y2);
m_ViewPanel1->SetSize(w,h2);
m_ViewPanel2->Move(x1, y1);
m_ViewPanel2->SetSize(w1,h1);
m_ViewPanel3->Move(x2, y1);
m_ViewPanel3->SetSize(w2,h1);
break;
case VA_THREE_LEFT:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h1);
m_ViewPanel3->Move(x2, y2);
m_ViewPanel3->SetSize(w2,h2);
break;
case VA_THREE_RIGHT:
m_ViewPanel1->Move(x2, y1);
m_ViewPanel1->SetSize(w2,h);
m_ViewPanel2->Move(x1, y1);
m_ViewPanel2->SetSize(w1,h1);
m_ViewPanel3->Move(x1, y2);
m_ViewPanel3->SetSize(w1,h2);
break;
case VA_FOUR:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h1);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h1);
m_ViewPanel3->Move(x1, y2);
m_ViewPanel3->SetSize(w1,h2);
m_ViewPanel4->Move(x2, y2);
m_ViewPanel4->SetSize(w2,h2);
break;
}
}
m_ViewPanel1->Layout();
m_ViewPanel2->Layout();
m_ViewPanel3->Layout();
m_ViewPanel4->Layout();
this->Refresh();
}
//----------------------------------------------------------------------------
CrossSplitterDragModes albaGUICrossSplitter::HitTest(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
wxCoord x = (wxCoord)event.GetX(),
y = (wxCoord)event.GetY();
if ( abs(m_XPos-x) < 5 && abs(m_YPos-y) < 5 && m_Mode >= VA_THREE_UP) return drag_xy;
if ( abs(m_XPos-x) < 5 ) return drag_x;
if ( abs(m_YPos-y) < 5 ) return drag_y;
return drag_none;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::DrawTracker(int x, int y)
//----------------------------------------------------------------------------
{
int m = 3;
int x1, y1;
int x2, y2;
if (x < m_Margin) x = m_Margin;
if (x > m_With - m_Margin) x = m_With - m_Margin;
if (y < m_Margin) y = m_Margin;
if (y > m_Height - m_Margin) y = m_Height - m_Margin;
wxScreenDC screenDC;
screenDC.SetLogicalFunction(wxINVERT);
screenDC.SetPen(*m_Pen);
screenDC.SetBrush(*wxTRANSPARENT_BRUSH);
if ( m_Dragging == 1 || m_Dragging == 3 )
{
x1 = x; y1 = m;
x2 = x; y2 = m_Height-m;
ClientToScreen(&x1, &y1);
ClientToScreen(&x2, &y2);
screenDC.DrawLine(x1, y1, x2, y2);
}
if ( m_Dragging == 2 || m_Dragging == 3 )
{
x1 = m; y1 = y;
x2 = m_With-m; y2 = y;
ClientToScreen(&x1, &y1);
ClientToScreen(&x2, &y2);
screenDC.DrawLine(x1, y1, x2, y2);
}
screenDC.SetLogicalFunction(wxCOPY);
screenDC.SetPen(wxNullPen);
screenDC.SetBrush(wxNullBrush);
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Put(wxWindow* w,int i)
//----------------------------------------------------------------------------
{
w->Reparent(this);
switch(i)
{
case 1:
if (m_ViewPanel1) delete m_ViewPanel1;
m_ViewPanel1 = w;
m_ViewPanel1->Layout();
break;
case 2:
if (m_ViewPanel2) delete m_ViewPanel2;
m_ViewPanel2 = w;
m_ViewPanel2->Layout();
break;
case 3:
if (m_ViewPanel3) delete m_ViewPanel3;
m_ViewPanel3 = w;
m_ViewPanel3->Layout();
break;
case 4:
if (m_ViewPanel4) delete m_ViewPanel4;
m_ViewPanel4 = w;
m_ViewPanel4->Layout();
break;
};
w->Show(true);
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetFocusedPanel(wxWindow* w)
//----------------------------------------------------------------------------
{
this->m_FocusedPanel = w;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Maximize()
//----------------------------------------------------------------------------
{
m_Maximized = !m_Maximized;
if(m_Maximized)
{
m_ViewPanel1->Show(false);
m_ViewPanel2->Show(false);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
this->m_FocusedPanel->Show(true);
OnLayout();
}
else
{
Split(m_Mode);
OnLayout();
}
this->Layout();
}
| 28.052402 | 94 | 0.511753 | IOR-BIC |
49a646f40e7e32094d7ee8470a1d9b27ee9537f2 | 6,940 | cpp | C++ | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | 1 | 2021-04-11T23:44:43.000Z | 2021-04-11T23:44:43.000Z | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | #include "../AliveLibCommon/stdafx_common.h"
#include "alive_api.hpp"
#include "SDL.h"
#include "logger.hpp"
#include "AOTlvs.hpp"
#include <gmock/gmock.h>
#include "../AliveLibAE/DebugHelpers.hpp"
const std::string kAEDir = "C:\\GOG Games\\Abes Exoddus\\";
const std::string kAODir = "C:\\GOG Games\\Abes Oddysee\\";
const std::string kAETestLvl = "pv.lvl";
const std::vector<std::string> kAELvls =
{
"ba.lvl",
"bm.lvl",
"br.lvl",
"bw.lvl",
"cr.lvl",
"fd.lvl",
"mi.lvl",
"ne.lvl",
"pv.lvl",
"st.lvl",
"sv.lvl",
};
const std::vector<std::string> kAOLvls =
{
"c1.lvl",
"d1.lvl",
"d2.lvl",
"d7.lvl",
"e1.lvl",
"e2.lvl",
"f1.lvl",
"f2.lvl",
"f4.lvl",
"l1.lvl",
"r1.lvl",
"r2.lvl",
"r6.lvl",
"s1.lvl",
};
static std::string AEPath(const std::string& fileName)
{
return kAEDir + fileName;
}
static std::string AOPath(const std::string& fileName)
{
return kAODir + fileName;
}
TEST(alive_api, ExportPathBinaryToJsonAE)
{
auto ret = AliveAPI::ExportPathBinaryToJson("OutputAE.json", AEPath(kAETestLvl), 14);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ExportPathBinaryToJsonAO)
{
auto ret = AliveAPI::ExportPathBinaryToJson("OutputAO.json", AOPath("R1.LVL"), 19);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ImportPathJsonToBinaryAO)
{
auto ret = AliveAPI::ImportPathJsonToBinary("OutputAO.json", AOPath("R1.LVL"), "newAO.lvl", {});
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
const auto ogR1 = FS::ReadFile(AOPath("R1.LVL"));
ASSERT_NE(ogR1.size(), 0u);
const auto rewrittenR1 = FS::ReadFile("newAO.lvl");
ASSERT_NE(rewrittenR1.size(), 0u);
ASSERT_EQ(ogR1, rewrittenR1);
}
TEST(alive_api, ImportPathJsonToBinaryAE)
{
auto ret = AliveAPI::ImportPathJsonToBinary("OutputAE.json", AEPath(kAETestLvl), "newAE.lvl", {});
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
const auto ogLVL = FS::ReadFile(AEPath(kAETestLvl));
ASSERT_NE(ogLVL.size(), 0u);
const auto rewrittenLVL = FS::ReadFile("newAE.lvl");
ASSERT_NE(rewrittenLVL.size(), 0u);
if (ogLVL != rewrittenLVL)
{
AliveAPI::DebugDumpTlvs("old/", AEPath(kAETestLvl), 14);
AliveAPI::DebugDumpTlvs("new/", "newAE.lvl", 14);
}
ASSERT_EQ(ogLVL, rewrittenLVL);
}
TEST(alive_api, EnumeratePathsAO)
{
auto ret = AliveAPI::EnumeratePaths(AOPath("R1.LVL"));
ASSERT_EQ(ret.pathBndName, "R1PATH.BND");
const std::vector<int> paths {15, 16, 18, 19};
ASSERT_EQ(ret.paths, paths);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ReSaveAllPathsAO)
{
for (const auto& lvl : kAOLvls)
{
auto ret = AliveAPI::EnumeratePaths(AOPath(lvl));
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
for (int path : ret.paths)
{
const std::string jsonName = "OutputAO_" + lvl + "_" + std::to_string(path) + ".json";
LOG_INFO("Save " << jsonName);
auto exportRet = AliveAPI::ExportPathBinaryToJson(jsonName, AOPath(lvl), path);
ASSERT_EQ(exportRet.mResult, AliveAPI::Error::None);
const std::string lvlName = "OutputAO_" + lvl + "_" + std::to_string(path) + ".lvl";
LOG_INFO("Resave " << lvlName);
auto importRet = AliveAPI::ImportPathJsonToBinary(jsonName, AOPath(lvl), lvlName, {});
ASSERT_EQ(importRet.mResult, AliveAPI::Error::None);
const auto originalLvlBytes = FS::ReadFile(AOPath(lvl));
ASSERT_NE(originalLvlBytes.size(), 0u);
const auto resavedLvlBytes = FS::ReadFile(lvlName);
ASSERT_NE(resavedLvlBytes.size(), 0u);
if (originalLvlBytes != resavedLvlBytes)
{
AliveAPI::DebugDumpTlvs("old/", AOPath(lvl), path);
AliveAPI::DebugDumpTlvs("new/", lvlName, path);
}
ASSERT_EQ(originalLvlBytes, resavedLvlBytes);
}
}
}
TEST(alive_api, ReSaveAllPathsAE)
{
for (const auto& lvl : kAELvls)
{
auto ret = AliveAPI::EnumeratePaths(AEPath(lvl));
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
for (int path : ret.paths)
{
const std::string jsonName = "OutputAE_" + lvl + "_" + std::to_string(path) + ".json";
LOG_INFO("Save " << jsonName);
auto exportRet = AliveAPI::ExportPathBinaryToJson(jsonName, AEPath(lvl), path);
ASSERT_EQ(exportRet.mResult, AliveAPI::Error::None);
const std::string lvlName = "OutputAE_" + lvl + "_" + std::to_string(path) + ".lvl";
LOG_INFO("Resave " << lvlName);
auto importRet = AliveAPI::ImportPathJsonToBinary(jsonName, AEPath(lvl), lvlName, {});
ASSERT_EQ(importRet.mResult, AliveAPI::Error::None);
const auto originalLvlBytes = FS::ReadFile(AEPath(lvl));
ASSERT_NE(originalLvlBytes.size(), 0u);
const auto resavedLvlBytes = FS::ReadFile(lvlName);
ASSERT_NE(resavedLvlBytes.size(), 0u);
if (originalLvlBytes != resavedLvlBytes)
{
AliveAPI::DebugDumpTlvs("old/", AEPath(lvl), path);
AliveAPI::DebugDumpTlvs("new/", lvlName, path);
}
ASSERT_EQ(originalLvlBytes, resavedLvlBytes);
}
}
}
// Get version
// Upgrade
TEST(alive_api, tlv_reflection)
{
TypesCollection types(Game::AO);
AO::Path_Hoist tlv = {};
std::unique_ptr<TlvObjectBase> pHoist = types.MakeTlvAO(AO::TlvTypes::Hoist_3, &tlv, 99);
auto obj = pHoist->InstanceToJson(types);
pHoist->InstanceFromJson(types, obj);
pHoist->StructureToJson();
ASSERT_EQ(pHoist->InstanceNumber(), 99);
}
/*
TEST(json_upgrade, upgrade_rename_structure)
{
AliveAPI::JsonUpgradeResult r = AliveAPI::UpgradePathJson("rename_field.json");
ASSERT_EQ(r.mResult, AliveAPI::UpgradeError::None);
}
*/
class ArgsAdapter
{
public:
ArgsAdapter(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
mArgs.push_back(argv[i]);
}
}
void Add(const std::string& arg)
{
mArgs.push_back(arg);
}
int ArgC() const
{
return static_cast<int>(mArgs.size());
}
std::unique_ptr<char*[]> ArgV() const
{
auto ptr = std::make_unique<char* []>(mArgs.size());
int i = 0;
for (const auto& arg : mArgs)
{
ptr[i++] = const_cast<char*>(arg.c_str());
}
return ptr;
}
private:
std::vector<std::string> mArgs;
};
int main(int argc, char* argv[])
{
ArgsAdapter args(argc, argv);
args.Add("--gtest_catch_exceptions=0");
int newArgc = args.ArgC();
auto newArgv = args.ArgV();
::testing::InitGoogleTest(&newArgc, newArgv.get());
const auto ret = RUN_ALL_TESTS();
return ret;
}
| 27.109375 | 102 | 0.606916 | THEONLYDarkShadow |
49a89792602e67ef169ad5931e18c36d24956944 | 9,971 | cpp | C++ | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 2 | 2021-07-19T12:03:39.000Z | 2021-07-22T18:37:45.000Z | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | null | null | null | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 1 | 2021-07-08T09:07:10.000Z | 2021-07-08T09:07:10.000Z | #include "ds3231.hpp"
//Registers
#define REG_SEC 0x00
#define REG_MIN 0x01
#define REG_HOUR 0x02
#define REG_DOW 0x03
#define REG_DATE 0x04
#define REG_MON 0x05
#define REG_YEAR 0x06
#define REG_CON 0x0e
#define REG_STATUS 0x0f
#define REG_AGING 0x10
#define REG_TEMPM 0x11
#define REG_TEMPL 0x12
//Alarm 1 registers
#define REG_ALARM1_SEC 0x07
#define REG_ALARM1_MIN 0x08
#define REG_ALARM1_HOUR 0x09
#define REG_ALARM1_DATE 0x0A
//Alarm 2 regiters
#define REG_ALARM2_MIN 0x0B
#define REG_ALARM2_HOUR 0x0C
#define REG_ALARM2_DATE 0x0D
//Bits
#define BIT_AMPM 5 //1: PM | 0: AM
#define BIT_1224 6 //1: 12 | 0: 24
#define BIT_CENTURY 7
//Control register bits
#define BIT_EOSC 7
#define BIT_BBSQW 6
#define BIT_CONV 5
#define BIT_RS2 4
#define BIT_RS1 3
#define BIT_INTCN 2
#define BIT_A2IE 1
#define BIT_A1IE 0
//Status register bits
#define BIT_OSF 7
#define BIT_EN32kHz 3 //1: enable /0: disable
#define BIT_BSY 2
#define BIT_A2F 1 //1: Alarm 2 match
#define BIT_A1F 0 //1: Alarm 1 match
#define DS3231_ADDR 0b01101000 // 0x68 >> 1
DS3231::DS3231(I2C_Master *i2c, uint8_t time_mode /* = FORMAT_24H */)
: _i2c(i2c), _time_mode(time_mode)
{}
bool DS3231::probe() noexcept
{
return _i2c->probe(DS3231_ADDR);
}
void DS3231::begin(){
_set_bit_reg(REG_HOUR, BIT_1224, _time_mode);
enableAlarm1Int(false);
enableAlarm2Int(false);
enableInterrupt(false);
}
void DS3231::setDateTime(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
//_encode(dateTime->dayOfWeek()),
1,
_encode(dateTime->getDay()),
_encode(dateTime->getMonth()),
_encode((uint8_t)(dateTime->getYear()-2000))
};
_send(REG_SEC,date,7);
}
void DS3231::getDateTime(DateTime* dateTime)
{
uint8_t date[7];
_receive(REG_SEC, date, 7);
dateTime->setDateTime((uint16_t)_decodeY(date[6])+2000,
_decode(date[5]),
_decode(date[4]),
_decodeH(date[2]),
_decode(date[1]),
_decode(date[0]));
}
void DS3231::setTime(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour())
};
_send(REG_SEC,date,3);
}
void DS3231::getTime(DateTime* dateTime)
{
uint8_t date[3];
_receive(REG_SEC,date,3);
dateTime->setTime(_decodeH(date[2]),
_decode(date[1]),
_decode(date[0]));
}
void DS3231::setDate(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getDay()),
_encode(dateTime->getMonth()),
_encode((uint8_t)(dateTime->getYear()-2000))
};
_send(REG_DATE,date,3);
}
void DS3231::getDate(DateTime *dateTime)
{
uint8_t date[3];
_receive(REG_DATE,date,3);
dateTime->setDate((uint16_t)(_decodeY(date[2])+2000),
_decode(date[1]),
_decode(date[0])
);
}
void DS3231::setTimeMode(uint8_t mode)
{
_set_bit_reg(REG_HOUR,6,mode);
}
uint8_t DS3231::getTimeMode()
{
return _get_bit_reg(REG_HOUR,6);
}
void DS3231::setDOW(uint8_t dow)
{
_send(REG_DOW,dow);
}
uint8_t DS3231::getDOW()
{
return _receive(REG_DOW);
}
void DS3231::enable32kHz(bool enable)
{
_set_bit_reg(REG_STATUS, BIT_EN32kHz, enable);
}
void DS3231::enableInterrupt(uint8_t enable /*= true*/)
{
_set_bit_reg(REG_CON, BIT_INTCN, enable);
}
void DS3231::enableSQWRate(DS3231SQWrate rate, uint8_t enable /*= true*/)
{
if(enable)
enableInterrupt(false);
_set_bit_reg(REG_CON, BIT_BBSQW, enable);
switch(rate){
case SQW_RATE_1K:
_set_bit_reg(REG_CON,BIT_RS2,false);
_set_bit_reg(REG_CON,BIT_RS1,true);
break;
case SQW_RATE_4K:
_set_bit_reg(REG_CON,BIT_RS2,true);
_set_bit_reg(REG_CON,BIT_RS1,false);
break;
case SQW_RATE_8K:
_set_bit_reg(REG_CON,BIT_RS2,true);
_set_bit_reg(REG_CON,BIT_RS1,true);
break;
default: /* SQW_RATE_1 */
_set_bit_reg(REG_CON,BIT_RS2,false);
_set_bit_reg(REG_CON,BIT_RS1,false);
break;
}
}
void DS3231::enableAlarm2Int(bool enable /*= true*/)
{
_set_bit_reg(REG_CON,BIT_A2IE,enable);
}
void DS3231::enableAlarm1Int(bool enable /*= true*/)
{
_set_bit_reg(REG_CON,BIT_A1IE,enable);
}
uint8_t DS3231::clearAlarmFlags()
{
uint8_t alarms = _receive(REG_STATUS) & ((1<<BIT_A2F)|(1<<BIT_A1F));
_set_bit_reg(REG_STATUS, BIT_A2F, false);
_set_bit_reg(REG_STATUS, BIT_A1F, false);
return alarms;
}
void DS3231::configAlarm2(DS3231Alarm2Config type_alarm, DateTime *dateTime /* = NULL */)
{
switch(type_alarm){
case PER_MINUTE:
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7);
_set_bit_reg(REG_ALARM2_MIN, 7);
break;
case MINUTES_MATCH:
_send(REG_ALARM2_MIN, _encode(dateTime->getMinute()));
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
break;
case HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour())};
_send(REG_ALARM2_MIN, data, 2);
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
}
break;
case DATE_HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->getDay())};
_send(REG_ALARM2_MIN, data, 3);
_set_bit_reg(REG_ALARM2_DATE, 7, false);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
_set_bit_reg(REG_ALARM2_DATE, 6, false);
}
break;
case DAY_HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->dayOfWeek())};
_send(REG_ALARM2_MIN, data, 3);
_set_bit_reg(REG_ALARM2_DATE, 7, false);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
_set_bit_reg(REG_ALARM2_DATE, 6, true);
}
break;
default:
break;
}
}
void DS3231::configAlarm1(DS3231Alarm1Config type_alarm, DateTime *dateTime /* = NULL */)
{
switch(type_alarm){
case PER_SECOND:
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7);
_set_bit_reg(REG_ALARM1_SEC, 7);
break;
case SECONDS_MATCH:
_send(REG_ALARM1_SEC, _encode(dateTime->getSecond()));
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
break;
case MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute())};
_send(REG_ALARM1_SEC, data, 2);
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
}
break;
case HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour())};
_send(REG_ALARM1_SEC, data, 3);
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
}
break;
case DATE_HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->getDay())};
_send(REG_ALARM1_SEC,data, 4);
_set_bit_reg(REG_ALARM1_DATE, 7, false);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
_set_bit_reg(REG_ALARM1_DATE, 6, false);
}
break;
case DAY_HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->dayOfWeek())};
_send(REG_ALARM1_SEC,data, 4);
_set_bit_reg(REG_ALARM1_DATE, 7, false);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
_set_bit_reg(REG_ALARM1_DATE, 6);
}
break;
default:
break;
}
}
void DS3231::startConvTemp()
{
if(_get_bit_reg(REG_CON, BIT_CONV))
return;
_set_bit_reg(REG_CON, BIT_CONV);
}
float DS3231::getTemp()
{
uint8_t data[2];
_receive(REG_TEMPM, data, 2);
return (float)data[0] + ((data[1] >> 6) * 0.25f);
}
/* Private */
void DS3231::_send(uint8_t reg, uint8_t* data, size_t length)
{
_i2c->write(DS3231_ADDR, reg, data, length, true);
}
void DS3231::_send(uint8_t reg,uint8_t data)
{
_i2c->write(DS3231_ADDR, reg, data, true);
}
void DS3231::_receive(uint8_t reg,uint8_t* data, size_t length)
{
_i2c->read(DS3231_ADDR, reg, data, length, true);
}
uint8_t DS3231::_receive(uint8_t reg)
{
uint8_t data;
_i2c->read(DS3231_ADDR, reg, &data, true);
return data;
}
void DS3231::_set_bit_reg(uint8_t reg, uint8_t bit, bool value /* = true*/)
{
uint8_t r = _receive(reg);
r &= ~(1 << bit);
r |= (value << bit);
_send(reg, r);
}
uint8_t DS3231::_get_bit_reg(uint8_t reg, uint8_t bit)
{
return (_receive(reg) >> bit) & 1;
}
uint8_t DS3231::_decode(uint8_t value)
{
uint8_t decoded = value & 127;
decoded = (decoded & 15) + 10 * ((decoded & (15 << 4)) >> 4);
return decoded;
}
uint8_t DS3231::_decodeH(uint8_t value)
{
if (value & 128)
value = (value & 15) + (12 * ((value & 32) >> 5));
else
value = (value & 15) + (10 * ((value & 48) >> 4));
return value;
}
uint8_t DS3231::_decodeY(uint8_t value)
{
return (value & 15) + 10 * ((value & (15 << 4)) >> 4);
}
uint8_t DS3231::_encode(uint8_t value)
{
return ((value / 10) << 4) + (value % 10);
}
| 23.627962 | 90 | 0.664627 | thmalmeida |
49aaf4ac7f6b7fb8effddf07d0272531622de3f5 | 6,437 | cpp | C++ | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | 4 | 2016-12-16T16:42:41.000Z | 2017-01-27T23:49:33.000Z | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | null | null | null | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include "AGNES.h"
#include <iostream>
#include "Silhouette.h"
using namespace std;
using namespace Silhouette;
namespace AGNES {
UnsupervisedNode* UnsupervisedNode::getChild1 (){return child1;}
UnsupervisedNode* UnsupervisedNode::getChild2 (){return child2;}
void UnsupervisedNode::modChild1 (UnsupervisedNode* n){child1 = n;}
void UnsupervisedNode::modChild2 (UnsupervisedNode* n){child2 = n;}
// Initializes the Distance matrix with values
void initializeDistMatrix (vector<vector<float>>& distMatrix, vector<vector<float>>& unlabeledData) {
// For every data set in the data set holder
// Or in another perspective: generate the rows of the matrices
for (int k = 0; k < unlabeledData.size(); k++) {
vector<float> inV;
inV.clear();
// and generate the columns of the matrices
for (int l = 0; l < unlabeledData.size(); l++) {
inV.push_back(0);
}
distMatrix.push_back(inV);
}
// For every row
for (int i = 0; i < unlabeledData.size(); i++) {
// and every column
for (int j = 0; j < unlabeledData.size(); j++) {
// Gets the Euclidean distance between two data sets
distMatrix[i][j] = getDistance(unlabeledData[i], unlabeledData[j]);
}
}
}
// Initializes the vector of unsupervised node clusters
// with values obtained from a file
void initializeNodesVector (vector<UnsupervisedNode*>& vNodes, vector<vector<float>>& unlabeledData) {
// For every value in the vector of datasets
for (int i = 0; i < unlabeledData.size(); i++) {
// create a Node pointer pointing to a Unsupervised Node with the data set
UnsupervisedNode* n = new UnsupervisedNode (unlabeledData[i]);
// and add it to the vector of unsupervised node clusters
vNodes.push_back(n);
}
}
// Finds the smallest distance between two datasets
// inside the distance matrix
pair<int, int> findMinDistCluster (vector<vector<float>>& distMatrix) {
// initialize a minimum value with the largest float value
float min = MAXFLOAT;
pair<int, int> indices (0,0);
// look at every row
for (int i = 0; i < distMatrix.size(); i++) {
// look at every column
for (int j = 0; j < distMatrix.size(); j++) {
// if the indices arent the same
// because if they were, it would just return itself
if (i != j) {
// if the distance is smaller than the minimum
if (distMatrix[i][j] < min) {
// reassign value
min = distMatrix[i][j];
// save the indices
indices.first = i;
indices.second = j;
}
}
}
}
// return the indices
return indices;
}
// Modify the matrix to update its values
void modMatrix (vector<vector<float>>& distMatrix, int index1, int index2) {
// Since a new cluster will be created, it's closest distance must be updated
// Luckily since it's members already have distances
// Find the smallest distance from one of its members to other clusters
// And use that value as the minimum distance
for (int i = 0; i < distMatrix.size(); i++) {
// Compares the smaller of the two values and saves the smaller of the two
// at the end of the matrix row
if (distMatrix[i][index1] > distMatrix[i][index2]) {
distMatrix[i].push_back(distMatrix[i][index2]);
}
else {
distMatrix[i].push_back(distMatrix[i][index1]);
}
// Remove the two data values from every row
// Or the column of these two data sets
distMatrix[i].erase(distMatrix[i].begin()+index1);
distMatrix[i].erase(distMatrix[i].begin()+index2-1);
}
// Remove the rows of these two data sets
distMatrix.erase(distMatrix.begin()+index1);
if (index2 > index1) distMatrix.erase(distMatrix.begin()+index2-1);
else distMatrix.erase(distMatrix.begin()+index2);
vector<float> newRow;
newRow.clear();
// Insert a new row into the matrix holding it's smallest distance values
// to other clusters
for (int j = 0; j < distMatrix.size(); j++) {
newRow.push_back(distMatrix[j][distMatrix.size()-1]);
}
newRow.push_back(0);
distMatrix.push_back(newRow);
}
// Update the vector of clusters
void modVNodes (vector<UnsupervisedNode*>& vNodes, int index1, int index2) {
// Create a new cluster
UnsupervisedNode* n = new UnsupervisedNode();
// that holds the previous clusters
n->modChild1(vNodes[index1]);
n->modChild2(vNodes[index2]);
// Remove the clusters from the vector of clusters
vNodes.erase(vNodes.begin()+index1);
if (index2 > index1) vNodes.erase(vNodes.begin()+index2-1);
else vNodes.erase(vNodes.begin()+index2);
// and put the new cluster in the vector of clusters
vNodes.push_back(n);
}
// Generate the unsupervised tree for the agglomerate nesting cluster
UnsupervisedNode* genTree (vector<vector<float>>& distMatrix, vector<UnsupervisedNode*>& nodes) {
// Return a stump if there is nothing to create with
if (nodes.size() == 0 || distMatrix.size() == 0) return nullptr;
// Until there is only one giant cluster
while (nodes.size() > 1) {
cout << "Number of current clusters: " << nodes.size() << ", still processing..." << endl;
// Find the smallest distance pair
pair<int,int> t = findMinDistCluster(distMatrix);
// Combine the two clusters into one
modVNodes(nodes, t.first, t.second);
// and fix the distance matrix to reflect this combination
modMatrix(distMatrix, t.first, t.second);
}
// Return the head of the tree
return nodes[0];
}
}
| 41.262821 | 106 | 0.5762 | Quanhaoli2641 |
49ae7cf017d7df0da7d85bfc9677fe387b4dd2d2 | 550 | cpp | C++ | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | #include "internal.hpp"
namespace CaDiCaL {
Limit::Limit () { memset (this, 0, sizeof *this); }
bool Internal::terminating () {
if (termination) {
LOG ("termination forced");
return true;
}
if (lim.conflict >= 0 && stats.conflicts >= lim.conflict) {
LOG ("conflict limit %ld reached", lim.conflict);
return true;
}
if (lim.decision >= 0 && stats.decisions >= lim.decision) {
LOG ("decision limit %ld reached", lim.decision);
return true;
}
return false;
}
Inc::Inc () { memset (this, 0, sizeof *this); }
};
| 21.153846 | 61 | 0.616364 | henrikt-ma |
49b21525f89fdb60466b3d2d7515bfc68fda09a4 | 4,985 | cpp | C++ | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | 1 | 2017-10-28T07:39:29.000Z | 2017-10-28T07:39:29.000Z | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | null | null | null | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | null | null | null | #include "pch.h"
#include "slideshow.h"
//////////////////////////////////////////////////////////////////////////////
//
// Training Screen
//
//////////////////////////////////////////////////////////////////////////////
void Slideshow::CleanUpTimers (void)
{
if (m_bInTimer)
{
// if a timer event had already been fired, then we need to remove it now
ITimerEventSource* pTimer = GetEngineWindow()->GetTimer ();
pTimer->RemoveSink (m_pEventSink);
m_bInTimer = false;
}
}
void Slideshow::StopSound (void)
{
// check to see if there is a sound already playing
if (static_cast<ISoundInstance*> (m_pSoundInstance))
if (m_pSoundInstance->IsPlaying () == S_OK)
{
m_pSoundInstance->GetFinishEventSource ()->RemoveSink(m_pEventSink);
m_pSoundInstance->Stop (true);
}
}
Slideshow::Slideshow (Modeler* pmodeler, const ZString& strNamespace) :
m_bNextSlide (false),
m_bInTimer (false)
{
// create the wrap image
m_pWrapImage = new WrapImage(Image::GetEmpty());
m_pImage = new GroupImage(new PickImage (this), m_pWrapImage);
// create a namespace for exporting information
TRef<INameSpace> pTrainingDataNameSpace = pmodeler->CreateNameSpace ("SlideshowData", pmodeler->GetNameSpace ("gamepanes"));
// Load the members from MDL
TRef<INameSpace> pNameSpace = pmodeler->GetNameSpace(strNamespace);
CastTo(m_pSlideList, pNameSpace->FindMember("slides"));
pmodeler->UnloadNameSpace(strNamespace);
// create a delegate for myself
m_pEventSink = IEventSink::CreateDelegate(this);
// make the keyboard inputs come to us
m_pkeyboardInputOldFocus = GetEngineWindow()->GetFocus();
GetEngineWindow()->SetFocus(IKeyboardInput::CreateDelegate(this));
// set the flag to indicate we are in a slideshow
m_bIsInSlideShow = true;
// start with the first slide
m_pSlideList->GetFirst();
NextSlide ();
}
Slideshow::~Slideshow (void)
{
// set the flag to indicate we are no longer in a slideshow
m_bIsInSlideShow = false;
// clean up timers so nothing fires an event at us when we're gone
CleanUpTimers ();
// stop sounds so nothing fires an event at us when we're gone
StopSound ();
// reset the focus for inputs
GetEngineWindow()->SetFocus(m_pkeyboardInputOldFocus);
}
// do the work
void Slideshow::NextSlide (void)
{
// stop any playing sounds
StopSound ();
// clean up any existing timers
CleanUpTimers ();
// check to see if there are any more slides to show
if (m_pSlideList->GetCurrent() != NULL)
{
// get the image and sound id for the slide
TRef<IObjectPair> pPair;
CastTo (pPair, m_pSlideList->GetCurrent());
//TRef<Image> pImage = Image::Cast((Value*)pPair->GetFirst ());
TRef<Image> pImage = Image::Cast (static_cast<Value*> (pPair->GetFirst ()));
SoundID soundID = static_cast<SoundID> (GetNumber (pPair->GetSecond ()));
// advance to the next slide
m_pSlideList->GetNext();
// set the image to the next image in the list
m_pWrapImage->SetImage (pImage);
// start the sound
m_pSoundInstance = GetWindow ()->StartSound (soundID);
// wait for the sound to finish
m_pSoundInstance->GetFinishEventSource ()->AddSink (m_pEventSink);
}
else
{
// get out of the slideshow
Dismiss ();
}
}
void Slideshow::Dismiss (void)
{
}
// UI Events
bool Slideshow::OnEvent (IEventSource* pEventSource)
{
// get the timer event source
ITimerEventSource* pTimer = GetEngineWindow()->GetTimer ();
// XXX something strange, in that timers are not passing the event source in,
// so I am assuming that if there is an event source, then it is from the
// current sound ending.
if (pEventSource)
{
// delay one second before processing the event
pTimer->AddSink (m_pEventSink, 1.0f);
m_bInTimer = true;
}
else
{
// skip to the next slide on the next update
m_bNextSlide = true;
pTimer->RemoveSink (m_pEventSink);
m_bInTimer = false;
}
return false;
}
void Slideshow::Picked (void)
{
NextSlide ();
}
// Screen Methods
Image* Slideshow::GetImage (void)
{
return m_pImage;
}
void Slideshow::OnFrame (void)
{
if (m_bNextSlide)
{
m_bNextSlide = false;
NextSlide ();
}
}
bool Slideshow::m_bIsInSlideShow = false;
bool Slideshow::IsInSlideShow (void)
{
return m_bIsInSlideShow;
}
//////////////////////////////////////////////////////////////////////////////
//
// IKeyboardInput
//
//////////////////////////////////////////////////////////////////////////////
bool Slideshow::OnKey(IInputProvider* pprovider, const KeyState& ks, bool& fForceTranslate)
{
if (ks.bDown)
NextSlide();
return false;
}
| 26.801075 | 131 | 0.604614 | nikodemak |
49bdc478f03d5b57259e07de05882e47c3e581e7 | 3,224 | hpp | C++ | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 3 | 2022-01-25T19:31:17.000Z | 2022-01-25T21:10:39.000Z | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 20 | 2021-12-17T14:58:00.000Z | 2022-02-05T21:25:35.000Z | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | null | null | null | #pragma once
#include <chrono>
#include <fstream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include "typedefs.hpp"
enum class LogLevel { trace, debug, info, warning, error, fatal };
class Logger {
public:
static Logger& get()
{
static Logger S;
return S;
}
void disable();
void enable();
void initLogFile(std::string file, LogLevel lvl = LogLevel::trace);
const std::string& logFilename() const { return log_filename_; }
void closeLogFile();
void setLogLevel(LogLevel lvl);
void updateLog();
void setTimeMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
void setResidualMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
void setSolutionMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
const std::vector<std::pair<std::string, double>> getTimeMonitor() const { return time_status_; }
const std::vector<std::pair<std::string, double>> getResidualMonitor() const { return residual_status_; }
const std::vector<std::pair<std::string, double>> getSolutionMonitor() const { return solution_status_; }
void Message(const std::string& str, LogLevel lvl);
void TraceMessage(std::string str);
void DebugMessage(std::string str);
void InfoMessage(std::string str);
void WarningMessage(std::string str);
void ErrorMessage(std::string str);
void FatalMessage(std::string str);
void WarningAssert(bool, const std::string&);
void FatalAssert(bool, const std::string&);
void logDeviceMemoryTransfer(const std::string& description);
void closeDeviceMemoryTransferLog();
class Timer {
public:
Timer(const std::string& msg, const LogLevel log_level);
virtual ~Timer();
real_t elapsed();
protected:
const std::chrono::time_point<std::chrono::high_resolution_clock> start_;
const std::string msg_;
const LogLevel log_level_;
bool elapsed_called_;
};
Timer timer(const std::string& msg, const LogLevel log_level = LogLevel::trace) { return Timer(msg, log_level); }
private:
Logger();
~Logger() = default;
static std::string makeBanner();
const std::string banner_;
std::string log_filename_;
int_t n_update_calls_;
bool initialized_;
bool auto_flush_;
bool log_level_overridden_ = false;
std::unique_ptr<std::ofstream> memlog_;
int_t n_device_to_host_copies_ = 0;
std::vector<std::pair<std::string, double>> time_status_;
std::vector<std::pair<std::string, double>> residual_status_;
std::vector<std::pair<std::string, double>> solution_status_;
boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_file_backend>> g_file_sink_;
boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>> g_console_sink_;
};
| 31.607843 | 115 | 0.675248 | mlohry |
49c295ebfb66665055fce5546a6c9de1b1185948 | 9,696 | hpp | C++ | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | 2 | 2017-01-13T09:20:58.000Z | 2019-06-28T15:27:13.000Z | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | null | null | null | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | 2 | 2017-05-31T12:05:26.000Z | 2019-10-13T22:36:32.000Z | //! \file tao/algorithm/selection/min_max_element.hpp
// Tao.Algorithm
//
// Copyright (c) 2016-2021 Fernando Pelliccioni.
//
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_
#define TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_
#include <algorithm>
#include <iterator>
#include <utility>
#include <tao/algorithm/concepts.hpp>
#include <tao/algorithm/integers.hpp>
#include <tao/algorithm/type_attributes.hpp>
namespace tao { namespace algorithm {
// --------------------------------------------
template <ForwardIterator I>
using min_max_ret_elem = std::pair<I, DistanceType<I>>;
template <ForwardIterator I>
using min_max_ret = std::pair<min_max_ret_elem<I>, min_max_ret_elem<I>>;
template <ForwardIterator I>
ValueType<I> const& operator*(min_max_ret_elem<I> const& p) {
return *p.first;
}
template <StrictWeakOrdering R>
struct min_max {
R r;
template <Regular T>
requires(Domain<R, T>)
T const& min(T const& x, T const& y) const {
if (r(y, x)) return y;
return x;
}
template <Regular T>
requires(Domain<R, T>)
T const& max(T const& x, T const& y) const {
if (r(y, x)) return x;
return y;
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> construct(T const& x, T const& y) const {
if (r(y, x)) return {y, x};
return {x, y};
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> combine(std::pair<T, T> const& x, pair<T, T> const& y) const {
return { min(x.first, y.first), max(x.second, y.second) };
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> combine(std::pair<T, T> const& x, T const& val) const {
if (r(val, x.first)) return {val, x.second};
if (r(val, x.second)) return x;
return {x.first, val};
}
};
template <StrictWeakOrdering R>
struct compare_dereference {
R r;
template <Iterator I>
requires(Readable<I> && Domain<R, ValueType<I>>)
bool operator()(I const& x, I const& y) const {
return r(*x, *y);
}
};
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element_even_length(I f, I l, R r) {
// precondition: distance(f, l) % 2 == 0 &&
// readable_bounded_range(f, l)
// postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
if (f == l) return {l, l};
I prev = f;
min_max<compare_dereference<R>> op{r};
auto result = op.construct(prev, ++f);
while (++f != l) {
prev = f;
result = op.combine(result, op.construct(prev, ++f));
}
return result;
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<I, I> min_max_element_n_basis(I f, DistanceType<I> n, R r) {
//precondition: readable_counted_range(f, n)
//postcondition: result.first == stable_sort_copy_n(f, n, r)[0] &&
// result.second == stable_sort_copy_n(f, n, r)[n - 1]
if (zero(n)) return {f, f};
if (one(n)) return {f, f};
auto m = 2 * half(n);
min_max<compare_dereference<R>> op{r};
I prev = f;
++f;
auto result = op.construct(prev, f);
++f;
DistanceType<I> i = 2;
while (i != m) {
prev = f;
++i; ++f;
result = op.combine(result, op.construct(prev, f));
++i; ++f;
}
if (i != n) {
// return op.combine(result, {f, f});
return op.combine(result, f);
}
return result;
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element(I f, I l, R r, std::forward_iterator_tag) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
I prev = f;
if (f == l || ++f == l) return {prev, prev};
min_max<compare_dereference<R>> op{r};
auto result = op.construct(prev, f);
while (++f != l) {
prev = f;
// if (++f == l) return op.combine(result, {prev, prev});
if (++f == l) return op.combine(result, prev);
result = op.combine(result, op.construct(prev, f));
}
return result;
}
template <RandomAccessIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element(I f, I l, R r, std::random_access_iterator_tag) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
auto n = std::distance(f, l);
return min_max_element_n_basis(f, n, r);
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
inline
auto min_max_element(I f, I l, R r) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
return min_max_element(f, l, r, IteratorCategory<I>{});
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
min_max_ret<I> min_max_element_n(I f, DistanceType<I> n, R r) {
//precondition: readable_counted_range(f, n)
//postcondition: result.first == stable_sort_copy_n(f, n, r)[0] &&
// result.second == stable_sort_copy_n(f, n, r)[n - 1]
if (zero(n)) return {{f, n}, {f, n}};
if (one(n)) return {{f, n}, {f, n}};
min_max<compare_dereference<R>> op{r};
min_max_ret_elem<I> prev{f, n}; //I prev = f;
++f;
auto result = op.construct(prev, min_max_ret_elem<I>{f, n - 1});
++f;
DistanceType<I> i = 2;
auto m = 2 * half(n);
while (i != m) {
prev = min_max_ret_elem<I>{f, n - i};
++i; ++f;
result = op.combine(result, op.construct(prev, min_max_ret_elem<I>{f, n - i}));
++i; ++f;
}
if (i != n) {
// return op.combine(result, {min_max_ret_elem<I>{f, n - i}, min_max_ret_elem<I>{f, n - i}});
return op.combine(result, min_max_ret_elem<I>{f, n - i});
}
return result;
}
template <Iterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<ValueType<I>, ValueType<I>> min_max_value_nonempty(I f, I l, R r) {
using T = ValueType<I>;
min_max<R> op{r};
T val = std::move(*f);
if (++f == l) return {val, val};
auto result = op.construct(val, *f);
while (++f != l) {
val = std::move(*f);
// if (++f == l) return op.combine(result, {val, val});
if (++f == l) return op.combine(result, val);
result = op.combine(result, op.construct(val, *f));
}
return result;
}
template <Iterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<ValueType<I>, ValueType<I>> min_max_value(I f, I l, R r) {
using T = ValueType<I>;
// if (f == l) return {supremum(r), infimum(r)};
if (f == l) return {supremum<T>, infimum<T>};
return min_max_value_nonempty(f, l, r);
}
// TODO(fernando): create min_max_value_n
// TODO(fernando): create min_max_value even vesion
}} /*tao::algorithm*/
#include <tao/algorithm/concepts_undef.hpp>
#endif /*TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_*/
#ifdef DOCTEST_LIBRARY_INCLUDED
#include <tao/benchmark/instrumented.hpp>
using namespace tao::algorithm;
using namespace std;
TEST_CASE("[min_max_element] testing min_max_element selection algorithm, instrumented, random access") {
using T = instrumented<int>;
vector<T> a = {3, 6, 2, 1, 4, 5, 1, 6, 2, 3}; //do it with random number of elements...
instrumented<int>::initialize(0);
auto p = tao::algorithm::min_max_element(begin(a), end(a), less<>());
double* count_p = instrumented<int>::counts;
// ceil(3/2 * 2) - 2
CHECK(count_p[instrumented_base::comparison] <= (3 * a.size()) / 2 - 2);
// for (size_t i = 0; i < instrumented_base::number_ops; ++i) {
// std::cout << instrumented_base::counter_names[i] << ": "
// << count_p[i]
// << std::endl;
// }
// CHECK(1 == 0);
}
TEST_CASE("[min_max_element] testing min_max_element selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_element(begin(a), end(a), std::less<>());
CHECK(p.first == next(begin(a), 3));
CHECK(p.second == next(begin(a), 6));
}
TEST_CASE("[min_max_element] testing min_max_element_n selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_element_n(begin(a), a.size(), std::less<>());
CHECK(p.first.first == next(begin(a), 3));
CHECK(p.second.first == next(begin(a), 6));
CHECK(p.first.second == a.size() - 3);
CHECK(p.second.second == a.size() - 6);
}
TEST_CASE("[min_max_element] testing min_max_value selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_value(begin(a), end(a), std::less<>());
CHECK(p.first == *next(begin(a), 3));
CHECK(p.second == *next(begin(a), 6));
}
#endif /*DOCTEST_LIBRARY_INCLUDED*/
| 31.076923 | 105 | 0.60066 | tao-cpp |
49c47e8ccc1f031844436950f924c1d2ac308f50 | 3,550 | cpp | C++ | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | #include "global.h"
/**
* @brief
* SYNTAX: R <- GROUP BY <attr> FROM relation_name RETURN MIN|MAX|SUM|AVG(attr)
*/
bool syntacticParseGROUP()
{
logger.log("syntacticParseGROUP");
if (tokenizedQuery.size() != 9 || tokenizedQuery[3] != "BY" || tokenizedQuery[7] != "RETURN" || tokenizedQuery[5] != "FROM")
{
cout << "SYNTAX ERROR" << endl;
return false;
}
parsedQuery.queryType = GROUP;
parsedQuery.groupResultRelationName = tokenizedQuery[0];
parsedQuery.groupRelationName = tokenizedQuery[6];
parsedQuery.groupColumnName = tokenizedQuery[4];
parsedQuery.groupOperation = tokenizedQuery[8].substr(0, 3);
if (parsedQuery.groupOperation != "MAX" && parsedQuery.groupOperation != "AVG" && parsedQuery.groupOperation != "MIN" && parsedQuery.groupOperation != "SUM")
{
cout << "SYNTAX:ERROR" << endl;
return false;
}
string temp = tokenizedQuery[8];
temp = temp.substr(4, temp.length() - 5);
parsedQuery.groupOperationColumn = temp;
return true;
}
bool semanticParseGROUP()
{
logger.log("semanticParseGROUP");
if (tableCatalogue.isTable(parsedQuery.groupResultRelationName))
{
cout << "SEMANTIC ERROR: Resultant relation already exists" << endl;
return false;
}
if (!tableCatalogue.isTable(parsedQuery.groupRelationName))
{
cout << "SEMANTIC ERROR: Relation doesn't exist" << endl;
return false;
}
Table table = *tableCatalogue.getTable(parsedQuery.groupRelationName);
if (!table.isColumn(parsedQuery.groupColumnName))
{
cout << "SEMANTIC ERROR: Column doesn't exist in relation";
return false;
}
if (!table.isColumn(parsedQuery.groupOperationColumn))
{
cout << "SEMANTIC ERROR: Column doesn't exist in relation";
return false;
}
return true;
}
void executeGROUP()
{
logger.log("executeGROUP");
vector<string> columns = {parsedQuery.groupColumnName, parsedQuery.groupOperation + parsedQuery.groupOperationColumn};
Table *resultantTable = new Table(parsedQuery.groupResultRelationName, columns);
Table table = *tableCatalogue.getTable(parsedQuery.groupRelationName);
table.sortTable(parsedQuery.groupColumnName, 0, 10);
Cursor cursor = table.getCursor();
int groupColumnIndex = table.getColumnIndex(parsedQuery.groupColumnName);
int groupOperationIndex = table.getColumnIndex(parsedQuery.groupOperationColumn);
vector<int> row = cursor.getNext();
vector<int> res(2);
int min_val = INT_MAX, max_val = INT_MIN, cnt = 0, sum = 0;
int cur_val = -1;
while (!row.empty())
{
if(cur_val != -1 && cur_val != row[groupColumnIndex]) {
res[0] = cur_val;
if(parsedQuery.groupOperation == "MAX") {
res[1] = max_val;
} else if(parsedQuery.groupOperation == "MIN") {
res[1] = min_val;
} else if(parsedQuery.groupOperation == "SUM") {
res[1] = sum;
} else {
res[1] = sum/cnt;
}
resultantTable->writeRow(res);
min_val = INT_MAX, max_val = INT_MIN, cnt = 0, sum = 0;
}
cur_val = row[groupColumnIndex];
max_val = max(max_val, row[groupOperationIndex]);
min_val = min(min_val, row[groupOperationIndex]);
sum += row[groupOperationIndex];
cnt++;
row = cursor.getNext();
}
resultantTable->blockify();
tableCatalogue.insertTable(resultantTable);
return;
} | 34.803922 | 161 | 0.63493 | dhruvarya |
49cc3d5ab65230e5f951f35388e76e4101d80aae | 5,121 | cpp | C++ | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 93 | 2015-01-11T03:10:17.000Z | 2022-01-27T15:53:35.000Z | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 6 | 2016-01-10T11:11:50.000Z | 2019-10-31T05:23:58.000Z | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 35 | 2015-01-11T04:08:30.000Z | 2022-02-11T10:17:20.000Z | /*
Copyright (c) 2011, The Mineserver Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Mineserver Project 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 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 <stdio.h>
#include "mineserver.h"
#include "map.h"
#include "plugin.h"
#include "logger.h"
#include "protocol.h"
#include "physics.h"
#include "falling.h"
bool BlockFalling::affectedBlock(int block) const
{
if (block == BLOCK_SAND || block == BLOCK_SLOW_SAND || block == BLOCK_GRAVEL)
return true;
return false;
}
std::string printfify(const char *fmt, ...)
{
if(fmt)
{
va_list args;
char buf[4096];
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
return buf;
}
else
return fmt;
}
void BlockFalling::onNeighbourBroken(User* user, int16_t, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
this->onNeighbourMove(user, 0, x, y, z, direction, map);
}
bool BlockFalling::onPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
uint8_t oldblock;
uint8_t oldmeta;
if (!ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
{
revertBlock(user, x, y, z, map);
return true;
}
/* Check block below allows blocks placed on top */
if (!this->isBlockStackable(oldblock))
{
revertBlock(user, x, y, z, map);
return true;
}
/* move the x,y,z coords dependent upon placement direction */
if (!this->translateDirection(&x, &y, &z, map, direction))
{
revertBlock(user, x, y, z, map);
return true;
}
if (this->isUserOnBlock(x, y, z, map))
{
revertBlock(user, x, y, z, map);
return true;
}
if (!this->isBlockEmpty(x, y, z, map))
{
revertBlock(user, x, y, z, map);
return true;
}
ServerInstance->map(map)->setBlock(x, y, z, (char)newblock, 0);
ServerInstance->map(map)->sendBlockChange(x, y, z, newblock, 0);
applyPhysics(user, x, y, z, map);
return false;
}
void BlockFalling::onNeighbourMove(User* user, int16_t, int32_t x, int16_t y, int32_t z, int8_t direction, int map)
{
uint8_t block;
uint8_t meta;
if(!ServerInstance->map(map)->getBlock(x, y, z, &block, &meta))
return;
if (affectedBlock(block))
{
applyPhysics(user, x, y, z, map);
}
}
void BlockFalling::applyPhysics(User* user, int32_t x, int16_t y, int32_t z, int map)
{
uint8_t fallblock, block;
uint8_t fallmeta, meta;
if (!ServerInstance->map(map)->getBlock(x, y, z, &fallblock, &fallmeta))
{
return;
}
if (ServerInstance->map(map)->getBlock(x, y - 1, z, &block, &meta))
{
switch (block)
{
case BLOCK_AIR:
case BLOCK_WATER:
case BLOCK_STATIONARY_WATER:
case BLOCK_LAVA:
case BLOCK_STATIONARY_LAVA:
case BLOCK_SNOW:
break;
default:
return;
break;
}
// Destroy original block
ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);
ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
y--;
//Spawn an entity for the falling block
const int chunk_x = blockToChunk(x);
const int chunk_z = blockToChunk(z);
const ChunkMap::const_iterator it = ServerInstance->map(map)->chunks.find(Coords(chunk_x, chunk_z));
if (it == ServerInstance->map(map)->chunks.end())
return;
uint32_t EID = Mineserver::generateEID();
uint8_t object = 70; //type == Falling object
Packet pkt = Protocol::spawnObject(EID,object, (x<<5)+16, ((y+1)<<5)+16, (z<<5)+16, fallblock|(fallmeta<<0x10));
it->second->sendPacket(pkt);
//Add to physics loop
ServerInstance->physics(map)->addFallSimulation(fallblock,vec(x, y, z), EID);
this->notifyNeighbours(x, y + 1, z, map, "onNeighbourMove", user, fallblock, BLOCK_BOTTOM);
}
}
| 28.608939 | 117 | 0.68717 | BonemealPioneer |
49d0ad93f2733814bcdc3a2c80701f0e72f223dc | 2,033 | cpp | C++ | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | #include <SDL2/SDL.h>
#include <iostream>
const int WINDOW_HEIGHT = 640;
const int WINDOW_WIDTH = 480;
// Starting point.
int main(int argc, const char * argv[])
{
// Create the window & screen surface.
// We render to the window & the surface is "contained" by the window.
SDL_Window* window = nullptr;
SDL_Surface* screenSurface = nullptr;
// Initiate SDL. If an error occurs, stop & print the error.
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
std::cout << "SDL could not be initialized. SDL_Error: " << SDL_GetError() << std::endl;
}
else
{
// Create the window.
window = SDL_CreateWindow("Window Title",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WINDOW_HEIGHT,
WINDOW_WIDTH,
SDL_WINDOW_OPENGL);
// If the window can't be created, print the error.
if (window == nullptr)
{
std::cout << "The window couldn't be created. SDL_Error: " << SDL_GetError() << std::endl;
}
else
{
// Get the window's surface.
screenSurface = SDL_GetWindowSurface(window);
// Make the screen surface white.
SDL_FillRect(screenSurface, nullptr, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
// Update the surface.
SDL_UpdateWindowSurface(window);
SDL_Event event;
bool quit = false;
// Event loop.
while (!quit) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT)
{
quit = true;
}
}
}
}
}
// Destroy the window.
SDL_DestroyWindow( window );
// Quit SDL.
SDL_Quit();
return 0;
}
| 29.042857 | 102 | 0.487949 | coltonhurst |
49d1f5e89dd6a3655548bc676cfc8ac33df047a3 | 3,185 | cpp | C++ | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | // The Tortoise and the Hare
// Main.cpp (Main function | Program execution begins and ends there)
/*
EXERCICE 8.12 PSEUDOCODE
- utilisation de nombre aléatoire pour recréation de la simulation
- créer un array de 70 cases
- chacune des 70 cases représente une position le long du parcours de course
- la ligne d'arrivée est à la case 70
- le premier a atteindre la case 70 reçois : "pail of fresh carrots and lettuce"
- Le parcours serpente le long d'une montagne glissante, donc parfois les prétendants perdent du terrain.
- Il y a une horloge qui tic-tac une fois par seconde.
- Le programme doit utiliser les fonctions "moveTortoise" et "moveHare" pour ajuster la position des animaux selon les règles de la Figure 8.18
- Ces fonctions doivent utiliser des pointeurs passe-par-référence pour modifier la position de la tortue et du lièvre.
- Utilisez des variables pour garder une trace des positions des animaux (les numéros de position vont de 1 à 70).
- Commencer chaque animal à la position 1 (c'est-à-dire la "starting gate")
- Si un animal glisse à gauche avant la case 1, déplacez l'animal vers la case 1.
PERCENTAGE (FIG 8.18)
- Générez les pourcentages de la Figure 8.18 en produisant un entier aléatoire i dans la plage 1 <= i <= 10
- Pour la tortue, effectuez une :
> "fast plod" quand 1 <= i <= 5 (50%) actual move : 3 case a droite
> "slip" quand 6 <= i <= 7 (20%) actual move : 6 case a GAUCHE
> "slow plod" quand 8 <= i <= 10 (30%) actual move : 1 case a droite
- Utilisez une technique similaire pour déplacer le lièvre :
> "sleep" quand 1 <= i <= 2 (20%) actual move : ne bouge pas
> "big hop" quand 3 <= i <= 4 (20%) actual move : 9 case a droite
> "big slip" quand 5 <= i <= 5 (10%) actual move : 12 case a GAUCHE
> "small hop" quand 6 <= i <= 8 (30%) actual move : 1 case a droite
> "small slip" quand 9 <= i <= 10 (20%) actual move : 2 case a GAUCHE
BEGIN THE RACE BY DISPLAYING :
BANG !!!!!
AND THEY'RE OFF !!!!!
- Pour chaque tick de l'horloge (c'est-à-dire chaque itération d'une boucle), affichez une ligne à 70 positions indiquant la lettre "T" en position de tortue (tortoise) et la lettre "H" en position de lièvre (hare).
- Parfois, les concurrents atterrissent sur la même case. Dans ce cas, la tortue mord le lièvre et votre programme devrait afficher "OUCH!!!" commençant à cette position.
- Toutes les positions autres que le "T" , le "H" ou "OUCH!!!" (en cas d'égalité) doit être vide.
WINNING
- Après avoir affiché chaque ligne, testez si l'un ou l'autre des animaux a atteint ou dépassé la case 70.
- Si c'est le cas, affichez le gagnant et terminer la simulation.
- Si la tortue gagne, affichez "TORTOISE WINS!!! YAY!!!" | "LA TORTUE GAGNE!!! YAY!!!"
- Si le lièvre gagne, affichez "Hare wins. Yuch." | "Le lièvre gagne. Yuch."
- Si les deux animaux gagnent sur le même tic d'horloge, afficher "It's a tie."
- Si aucun animal ne gagne, refaites la boucle pour simuler le prochain tic-tac de l'horloge.
*/
#include <iostream>
using namespace std;
int main()
{
system("pause");
return 0;
}
| 49.765625 | 216 | 0.6854 | EpsilonsQc |
49d7145725729878d437d073cf0594dbd68d839c | 4,490 | hh | C++ | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | 1 | 2021-09-13T17:06:34.000Z | 2021-09-13T17:06:34.000Z | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | null | null | null | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2021, King Abdullah University of Science and Technology
// (KAUST). All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause. See the accompanying LICENSE file.
#ifndef HCORE_EXCEPTION_HH
#define HCORE_EXCEPTION_HH
#include <string>
#include <cstdio>
#include <cstdarg>
#include <exception>
namespace hcore {
class Error : public std::exception {
public:
Error() : std::exception()
{
}
Error(const std::string& what_arg) : std::exception(), what_arg_(what_arg)
{
}
Error(
const std::string& what_arg, const char* function) : std::exception(),
what_arg_(what_arg + ", function " + function + ".")
{
}
Error(
const std::string& what_arg,
const char* function, const char* file, int line) : std::exception(),
what_arg_(what_arg
+ ", function " + function
+ ", file " + file
+ ", line " + std::to_string(line) + ".")
{
}
virtual const char* what() const noexcept override
{
return what_arg_.c_str();
}
private:
std::string what_arg_;
};
namespace internal {
// throws hcore::Error if condition is true called by hcore_error_if macro
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line)
{
if (condition) {
throw Error(condition_string, function, file, line);
}
}
// throws hcore::Error if condition is true called by hcore_error_if_msg macro
// and uses printf-style format for error message
// condition_string is ignored, but differentiates this from other version.
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line, const char* format, ...)
__attribute__((format(printf, 6, 7)));
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line, const char* format, ...)
{
if (condition) {
char bufffer[80];
va_list v;
va_start(v, format);
vsnprintf(bufffer, sizeof(bufffer), format, v);
va_end(v);
throw Error(bufffer, function, file, line);
}
}
// internal helper function; aborts if condition is true
// uses printf-style format for error message
// called by hcore_error_if_msg macro
inline void abort_if(
bool condition,
const char* function, const char* file, int line, const char* format, ...)
__attribute__((format(printf, 5, 6)));
inline void abort_if(
bool condition,
const char* function, const char* file, int line, const char* format, ...)
{
if (condition) {
char bufffer[80];
va_list v;
va_start(v, format);
vsnprintf(bufffer, sizeof(bufffer), format, v);
va_end(v);
fprintf(stderr,
"HCORE assertion failed: (%s), function %s, file %s, line %d.\n",
bufffer, function, file, line);
abort();
}
}
} // namespace internal
} // namespace hcore
#if defined(HCORE_ERROR_NDEBUG) || \
(defined(HCORE_ERROR_ASSERT) && defined(NDEBUG))
// HCORE does no error checking, and thus errors maybe either handled by
// - BLAS++ and LAPACK++, or
// - Lower level BLAS and LAPACK via xerbla
#define hcore_error_if(condition) ((void)0)
#define hcore_error_if_msg(condition, ...) ((void)0)
#elif defined(HCORE_ERROR_ASSERT)
// HCORE aborts on error (similar to C/C++ assert)
#define hcore_error_if(condition) \
hcore::internal::abort_if( \
condition, __func__, __FILE__, __LINE__, "%s", #condition)
#define hcore_error_if_msg(condition, ...) \
hcore::internal::abort_if( \
condition, __func__, __FILE__, __LINE__, __VA_ARGS__)
#else
// HCORE throws errors (default)
// internal macro to get string #condition; throws hcore::Error if condition
// is true. Example: hcore_error_if(a < b)
#define hcore_error_if(condition) \
hcore::internal::throw_if( \
condition, #condition, __func__, __FILE__, __LINE__)
// internal macro takes condition and printf-style format for error message.
// throws Error if condition is true.
// example: hcore_error_if_msg(a < b, "a %d < b %d", a, b);
#define hcore_error_if_msg(condition, ...) \
hcore::internal::throw_if( \
condition, #condition, __func__, __FILE__, __LINE__, __VA_ARGS__)
#endif
#endif // HCORE_EXCEPTION_HH
| 32.536232 | 80 | 0.647216 | ecrc |
49d7d8f2724c252c81e0e4ffadee4979028d3186 | 198 | cpp | C++ | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | //
// Created by chenqwwq on 2022/6/18.
//
#include "stdc++.h"
#include "common.h"
#include "iostream"
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
} | 12.375 | 36 | 0.641414 | CheNbXxx |
49e8bb7742522cd602eb35a5fabf30f00d3f530d | 479 | cpp | C++ | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | // Copyright Adam Berg 2017
#include "TIShootEffect.h"
// Sets default values
ATIShootEffect::ATIShootEffect()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ATIShootEffect::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ATIShootEffect::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| 17.107143 | 115 | 0.730689 | APBerg |
49e9501641183e601d40851df1fc9954e5359dd4 | 2,206 | cpp | C++ | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | #include "editopgraph/component/Ray.h"
#include "editopgraph/CompHelper.h"
#include "editopgraph/ParamImpl.h"
#include "editopgraph/Context.h"
#include <painting3/PerspCam.h>
#include <painting3/Viewport.h>
namespace editopgraph
{
namespace comp
{
void Ray::Execute(const std::shared_ptr<dag::Context>& ctx)
{
m_vals.resize(1, nullptr);
auto start_pos = m_start_pos;
auto end_pos = m_end_pos;
auto p_start = CompHelper::GetInputParam(*this, 0);
auto p_end = CompHelper::GetInputParam(*this, 1);
if (p_start)
{
switch (p_start->Type())
{
case ParamType::Camera:
{
auto cam = std::static_pointer_cast<CameraParam>(p_start)->GetCamera();
auto cam_type = cam->TypeID();
if (cam_type == pt0::GetCamTypeID<pt3::PerspCam>()) {
start_pos = std::dynamic_pointer_cast<pt3::PerspCam>(cam)->GetPos();
}
}
break;
case ParamType::Float3:
start_pos = std::static_pointer_cast<Float3Param>(p_start)->GetValue();
break;
}
}
if (p_end)
{
switch (p_end->Type())
{
case ParamType::ScreenPos:
{
if (ctx)
{
auto _ctx = std::static_pointer_cast<Context>(ctx);
auto cam = _ctx->GetCamera();
auto cam_type = cam->TypeID();
if (cam_type == pt0::GetCamTypeID<pt3::PerspCam>())
{
auto p_cam = std::dynamic_pointer_cast<pt3::PerspCam>(cam);
auto pos = std::static_pointer_cast<ScreenPosParam>(p_end)->GetPos();
sm::vec3 ray_dir = _ctx->GetViewport().TransPos3ScreenToDir(
sm::vec2(static_cast<float>(pos.x), static_cast<float>(pos.y)), *p_cam);
end_pos = start_pos + ray_dir;
}
}
}
break;
case ParamType::Float3:
end_pos = std::static_pointer_cast<Float3Param>(p_end)->GetValue();
break;
}
}
sm::Ray ray(start_pos, end_pos - start_pos);
m_vals[0] = std::make_shared<RayParam>(ray);
}
}
} | 28.649351 | 96 | 0.549864 | xzrunner |
49ee10a0eaea9ab4add5e5303cb60379b4cde470 | 10,973 | cc | C++ | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC, Andrew Hines
//
// 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 "visqol_api.h"
#include "gtest/gtest.h"
#include "google/protobuf/stubs/status.h"
#include "audio_signal.h"
#include "commandline_parser.h"
#include "conformance.h"
#include "file_path.h"
#include "misc_audio.h"
#include "similarity_result.pb.h" // Generated by cc_proto_library rule
#include "visqol_config.pb.h" // Generated by cc_proto_library rule
namespace Visqol {
namespace {
const size_t kSampleRate = 48000;
const size_t kUnsupportedSampleRate = 44100;
const double kTolerance = 0.0001;
const char kContrabassoonRef[] =
"testdata/conformance_testdata_subset/contrabassoon48_stereo.wav";
const char kContrabassoonDeg[] =
"testdata/conformance_testdata_subset/contrabassoon48_stereo_24kbps_aac.wav";
const char kCleanSpeechRef[] =
"testdata/clean_speech/CA01_01.wav";
const char kCleanSpeechDeg[] =
"testdata/clean_speech/transcoded_CA01_01.wav";
const char kNoSampleRateErrMsg[] =
"INVALID_ARGUMENT:Audio info must be supplied for config.";
const char kNonExistantModelFile[] = "non_existant.txt";
const char kNonExistantModelFileErrMsg[] =
"INVALID_ARGUMENT:Failed to load the SVR model file: non_existant.txt";
const char kNon48kSampleRateErrMsg[] =
"INVALID_ARGUMENT:Currently, 48k is the only sample rate supported by "
"ViSQOL Audio. See README for details of overriding.";
// These values match the known version.
const double kContrabassoonVnsim = 0.90758;
const double kContrabassoonFvnsim[] = {
0.884680, 0.925437, 0.980274, 0.996635, 0.996060, 0.979772, 0.984409,
0.986112, 0.977326, 0.982975, 0.958038, 0.971650, 0.964743, 0.959870,
0.959018, 0.954554, 0.967928, 0.962373, 0.940116, 0.865323, 0.851010,
0.856138, 0.852182, 0.825574, 0.791404, 0.805591, 0.779993, 0.789653,
0.805530, 0.786122, 0.823594, 0.878549
};
const double kCA01_01AsAudio = 2.0003927800390828;
const double kPerfectScore = 5.0;
const double kCA01_01UnscaledPerfectScore = 4.456782;
/**
* Happy path test for the ViSQOL API with a model file specified.
*/
TEST(VisqolApi, happy_path_specified_model) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kConformanceContrabassoon24aac, sim_result.moslqo(), kTolerance);
ASSERT_NEAR(kContrabassoonVnsim, sim_result.vnsim(), kTolerance);
for (int i = 0; i < sim_result.fvnsim_size(); i++) {
ASSERT_NEAR(kContrabassoonFvnsim[i], sim_result.fvnsim(i), kTolerance);
}
}
/**
* Happy path test for the ViSQOL API with the default model file used.
*/
TEST(VisqolApi, happy_path_default_model) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API without specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kConformanceContrabassoon24aac, sim_result.moslqo(), kTolerance);
ASSERT_NEAR(kContrabassoonVnsim, sim_result.vnsim(), kTolerance);
for (int i = 0; i < sim_result.fvnsim_size(); i++) {
ASSERT_NEAR(kContrabassoonFvnsim[i], sim_result.fvnsim(i), kTolerance);
}
}
/**
* Test calling the ViSQOL API without sample rate data for the input signals.
*/
TEST(VisqolApi, no_sample_rate_info) {
// Create the API with no sample rate data.
VisqolConfig config;
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(!result.ok());
ASSERT_EQ(kNoSampleRateErrMsg, result.ToString());
}
/**
* Test calling the ViSQOL API with an unsupported sample rate and the 'allow
* unsupported sample rates' override set to false.
*/
TEST(VisqolApi, unsupported_sample_rate_no_override) {
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kUnsupportedSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_FALSE(result.ok());
ASSERT_EQ(kNon48kSampleRateErrMsg, result.ToString());
}
/**
* Test calling the ViSQOL API with an unsupported sample rate and the 'allow
* unsupported sample rates' override set to true.
*/
TEST(VisqolApi, unsupported_sample_rate_with_override) {
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kUnsupportedSampleRate);
config.mutable_options()->set_allow_unsupported_sample_rates(true);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(result.ok());
}
/**
* Test calling the ViSQOL API with a model file specified that does not exist.
*/
TEST(VisqolApi, non_existant_mode_file) {
// Create the API with no sample rate data.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(kNonExistantModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(!result.ok());
ASSERT_EQ(kNonExistantModelFileErrMsg, result.ToString());
}
/**
* Confirm that when running the ViSQOL API with speech mode disabled (even
* with the 'use unscaled mapping' bool set to true), the input files will be
* compared as audio.
*/
TEST(VisqolApi, speech_mode_disabled) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(false);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(true);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kCA01_01AsAudio, sim_result.moslqo(), kTolerance);
}
/**
* Test the ViSQOL API running in speech mode. Use the same file for both the
* reference and degraded signals and run in scaled mode. A perfect score of
* 5.0 is expected.
*/
TEST(VisqolApi, speech_mode_with_scaled_mapping) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(true);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(false);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kPerfectScore, sim_result.moslqo(), kTolerance);
}
/**
* Test the ViSQOL API running in speech mode. Use the same file for both the
* reference and degraded signals and run in unscaled mode. A score of 4.x is
* expected.
*/
TEST(VisqolApi, speech_mode_with_unscaled_mapping) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(true);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(true);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kCA01_01UnscaledPerfectScore, sim_result.moslqo(), kTolerance);
}
} // namespace
} // namespace Visqol
| 37.707904 | 80 | 0.760868 | bartvanerp |
49ef9412b35915c185181db579fbfde345c49114 | 4,891 | cpp | C++ | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | /*
* src/mpreal.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2002
*
*/
#include <arprec/mp_real.h>
#include "small_inline.h"
using std::cerr;
using std::endl;
void mp_real::mpdiv(const mp_real& a, const mp_real& b, mp_real& c, int prec_words)
{
/**
* This divides the MP number A by the MP number B to yield the MP
* quotient C. For extra high levels of precision, use MPDIVX.
* Debug output starts with debug_level = 8.
*
* The algorithm is by long division.
*/
int i, ia, ib, ij, is, i2, i3=0, j, j3, na, nb, nc, BreakLoop;
double rb, ss, t0, t1, t2, t[2];
double* d;
if (error_no != 0) {
if (error_no == 99) mpabrt();
zero(c);
return;
}
if (debug_level >= 8) {
print_mpreal("MPDIV a ", a);
print_mpreal("MPDIV b ", b);
}
ia = (a[1] >= 0 ? 1 : -1);
ib = (b[1] >= 0 ? 1 : -1);
na = std::min (int(std::abs(a[1])), prec_words);
nb = std::min (int(std::abs(b[1])), prec_words);
// Check if dividend is zero.
if (na == 0) {
zero(c);
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
if (nb == 1 && b[FST_M] == 1.) {
// Divisor is 1 or -1 -- result is A or -A.
c[1] = sign(na, ia * ib);
c[2] = a[2] - b[2];
for (i = FST_M; i < na+FST_M; ++i) c[i] = a[i];
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
// Check if divisor is zero.
if (nb == 0) {
if (MPKER[31] != 0) {
cerr << "*** MPDIV: Divisor is zero." << endl;
error_no = 31;
if (MPKER[error_no] == 2) mpabrt();
}
return;
}
//need the scratch space now...
d = new double[prec_words+9];
int d_add=0;
d++; d_add--;
// Initialize trial divisor and trial dividend.
t0 = mpbdx * b[3];
if (nb >= 2) t0 = t0 + b[4];
if (nb >= 3) t0 = t0 + mprdx * b[5];
rb = 1.0 / t0;
d[0] = d[1] = 0.0;
for (i = 2; i < na+2; ++i) d[i] = a[i+1];
for (/*i = na+2*/; i <= prec_words+7; ++i) d[i] = 0.0;
// Perform ordinary long division algorithm. First compute only the first
// NA words of the quotient.
for (j = 2; j <= na+1; ++j) {
t1 = mpbx2 * d[j-1] + mpbdx * d[j] + d[j+1];
t0 = AINT (rb * t1); // trial quotient, approx is ok.
j3 = j - 3;
i2 = std::min (nb, prec_words + 2 - j3) + 2;
ij = i2 + j3;
for (i = 3; i <= i2; ++i) {
i3 = i + j3;
t[0] = mp_two_prod(t0, b[i], t[1]);
d[i3-1] -= t[0]; // >= -(2^mpnbt-1), <= 2^mpnbt-1
d[i3] -= t[1];
}
// Release carry to avoid overflowing the exact integer capacity
// (2^52-1) of a floating point word in D.
if(!(j & (mp::mpnpr-1))) { // assume mpnpr is power of two
t2 = 0.0;
for(i=i3;i>j+1;i--) {
t1 = t2 + d[i];
t2 = int (t1 * mprdx); // carry <= 1
d[i] = t1 - t2 * mpbdx; // remainder of t1 * 2^(-mpnbt)
}
d[i] += t2;
}
d[j] += mpbdx * d[j-1];
d[j-1] = t0; // quotient
}
// Compute additional words of the quotient, as long as the remainder
// is nonzero.
BreakLoop = 0;
for (j = na+2; j <= prec_words+3; ++j) {
t1 = mpbx2 * d[j-1] + mpbdx * d[j];
if (j < prec_words + 3) t1 += d[j+1];
t0 = AINT (rb * t1); // trial quotient, approx is ok.
j3 = j - 3;
i2 = std::min (nb, prec_words + 2 - j3) + 2;
ij = i2 + j3;
ss = 0.0;
for (i = 3; i <= i2; ++i) {
i3 = i + j3;
t[0] = mp_two_prod(t0, b[i], t[1]);
d[i3-1] -= t[0]; // >= -(2^mpnbt-1), <= 2^mpnbt-1
d[i3] -= t[1];
//square to avoid cancellation when d[i3] or d[i3-1] are negative
ss += sqr (d[i3-1]) + sqr (d[i3]);
}
// Release carry to avoid overflowing the exact integer capacity
// (2^mpnbt-1) of a floating point word in D.
if(!(j & (mp::mpnpr-1))) { // assume mpnpr is power of two
t2 = 0.0;
for(i=i3;i>j+1;i--) {
t1 = t2 + d[i];
t2 = int (t1 * mprdx); // carry <= 1
d[i] = t1 - t2 * mpbdx; // remainder of t1 * 2^(-mpnbt)
}
d[i] += t2;
}
d[j] += mpbdx * d[j-1];
d[j-1] = t0;
if (ss == 0.0) {
BreakLoop = 1;
break;
}
if (ij <= prec_words+1) d[ij+3] = 0.0;
}
// Set sign and exponent, and fix up result.
if(!BreakLoop) j--;
d[j] = 0.0;
if (d[1] == 0.0) {
is = 1;
d--; d_add++;
} else {
is = 2;
d-=2; d_add+=2;
//for (i = j+1; i >= 3; --i) d[i] = d[i-2];
}
nc = std::min( (int(c[0])-FST_M-2), std::min (j-1, prec_words));
d[1] = ia+ib ? nc : -nc;//sign(nc, ia * ib);
d[2] = a[2] - b[2] + is - 2;
mpnorm(d, c, prec_words);
delete [] (d+d_add);
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
| 26.015957 | 83 | 0.491924 | paveloom-p |
49f4cbdf6382fce666081e78703ca70c4dd019a7 | 784 | cc | C++ | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// physics/physx/physxhinge.cc
// (C) 2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "physics/physx/physxhinge.h"
#include "extensions/PxRevoluteJoint.h"
#include "physxutils.h"
#include "PxRigidDynamic.h"
#include "physxphysicsserver.h"
using namespace physx;
namespace PhysX
{
__ImplementClass(PhysX::PhysXHinge, 'PXHI', Physics::BaseHinge);
//------------------------------------------------------------------------------
/**
*/
PhysXHinge::PhysXHinge()
{
}
//------------------------------------------------------------------------------
/**
*/
PhysXHinge::~PhysXHinge()
{
}
} | 21.189189 | 80 | 0.423469 | gscept |
49f60a5116002e89286182579b4e0810935303c2 | 1,228 | cpp | C++ | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#ifdef DGC
#include "debug.h"
#else
#define debug(...) 9715;
#endif
typedef long long ll;
typedef long double ld;
typedef complex<double> point;
#define F first
#define S second
const int mod = 1e9+7;
int dp[205][205][205];
void add(int &x, int y)
{
x += y;
if (x >= mod)
x -= mod;
}
int solve(int n, int k)
{
memset(dp, 0, sizeof dp);
dp[0][1][0] = 1;
dp[0][1][1] = mod-1;
for (int i = 0; i < n; ++i)
for (int j = 1; j <= k; ++j)
for (int g = 0; g <= n; ++g)
{
if (g) add(dp[i][j][g], dp[i][j][g-1]);
if (j < k && g > 0)
{
add(dp[i+1][j+1][0], dp[i][j][g]);
add(dp[i+1][j+1][g], mod-dp[i][j][g]);
}
int l = n-i - g;
if (l > 0)
{
add(dp[i+1][1][g], dp[i][j][g]);
add(dp[i+1][1][g+l], mod-dp[i][j][g]);
}
}
int ans = 0;
for (int j = 1; j <= k; ++j)
add(ans, dp[n][j][0]);
return ans;
}
int main()
{
#ifdef DGC
//freopen("b.out", "w", stdout);
#endif
freopen("permutations.in", "r", stdin);
ios_base::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int ans = solve(n, k);
add(ans, mod-solve(n, k-1));
cout << ans << "\n";
}
return 0;
} | 15.948052 | 43 | 0.491042 | albexl |
b701a409556873b9c54a13de7d60f9f99952ce99 | 996 | cpp | C++ | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 4 | 2018-09-09T13:40:01.000Z | 2022-03-27T10:00:24.000Z | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 3 | 2016-04-02T05:59:43.000Z | 2020-06-27T11:30:40.000Z | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 6 | 2017-04-05T20:00:48.000Z | 2020-10-26T08:35:11.000Z | /*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetViewWindow.h"
HTGTweetViewWindow::HTGTweetViewWindow(BWindow *parent, BList *tweets)
: BWindow(BRect(300, 300, 615, 840), "Tweet Viewer", B_TITLED_WINDOW, B_NOT_H_RESIZABLE)
{
/*Set parent window (used for handeling messages)*/
this->parent = parent;
/*Set up timeline*/
theTimeLine = new HTGTimeLineView(TIMELINE_HDD, Bounds(), tweets);
this->AddChild(theTimeLine);
}
void
HTGTweetViewWindow::AddList(BList *tweets)
{
theTimeLine->AddList(tweets);
}
void
HTGTweetViewWindow::MessageReceived(BMessage *message)
{
switch (message->what) {
default:
be_app->PostMessage(message);
break;
}
}
bool
HTGTweetViewWindow::QuitRequested()
{
MessageReceived(new BMessage(TWEETVIEWWINDOW_CLOSED));
return true;
}
HTGTweetViewWindow::~HTGTweetViewWindow()
{
theTimeLine->RemoveSelf();
delete theTimeLine;
}
| 20.75 | 89 | 0.75 | HaikuArchives |
8e6616d984cafa0516321ef863e20b641c07371e | 489 | hpp | C++ | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | #ifndef CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
#define CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
//
// strong-types.hpp
//
#include "strong-type.hpp"
namespace castlecrawl
{
// phantom tags
struct ArmorTag;
// strong types
using Armor_t = util::StrongType<int, ArmorTag>;
// user defined literals
inline Armor_t operator"" _armor(unsigned long long armor) { return Armor_t::make(armor); }
} // namespace castlecrawl
#endif // CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
| 21.26087 | 95 | 0.744376 | tilnewman |
8e68677527d44e93def4cc676de51ef99ce59be9 | 2,098 | cpp | C++ | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | /*
* Author: Deklyn Palmer.
* Editors:
* - Deklyn Palmer.
*/
#include "ShaderManager.h"
namespace Kross
{
ShaderManager* ShaderManager::m_Instance = nullptr;
ShaderManager::~ShaderManager()
{
/* Destroy all the Shaders. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
Shader::OnDestroy(m_Instance->m_Shaders[i]);
m_Instance->m_Shaders[i] = nullptr;
}
/* Clean up Memory. */
m_Instance->m_Shaders.clear();
m_Instance->m_Shaders.~vector();
}
void ShaderManager::OnCreate()
{
if (!m_Instance)
{
m_Instance = KROSS_NEW ShaderManager();
}
}
void ShaderManager::OnDestroy()
{
if (m_Instance)
{
delete m_Instance;
}
}
void ShaderManager::AttachShader(Shader* shader)
{
/* Incase for some reason the Shader doesn't exist. Early out. */
if (!shader)
{
return;
}
/* Check for duplicates. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i] == shader)
{
return;
}
}
/* If no duplicate was found, add it. */
m_Instance->m_Shaders.push_back(shader);
}
void ShaderManager::DetachShader(Shader* shader)
{
/* Incase for some reason the Shader doesn't exist. Early out. */
if (!shader)
{
return;
}
/* Check for Shader. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i] == shader)
{
/* Remove the Shader. */
Shader::OnDestroy(shader);
m_Instance->m_Shaders.erase(m_Instance->m_Shaders.begin() + i);
return;
}
}
}
void ShaderManager::OnReloadShader(Shader* shader)
{
/* Reload the Shader. */
shader = Shader::OnReload(shader);
}
void ShaderManager::OnUpdateShaderVPMatrix(Matrix4 viewMatrix, Matrix4 projectionMatrix)
{
/* Update all Shaders View and Projection Matrix. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i]->GetType() == ShaderType::Standard)
{
m_Instance->m_Shaders[i]->SetUniform("u_View", viewMatrix);
m_Instance->m_Shaders[i]->SetUniform("u_Projection", projectionMatrix);
}
}
}
} | 20.772277 | 89 | 0.639657 | Deklyn-Palmer |
8e77c8b65e1a115502a7925c072aad85516edc19 | 1,212 | hpp | C++ | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | 1 | 2021-06-03T15:56:32.000Z | 2021-06-03T15:56:32.000Z | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | 1 | 2015-08-05T05:51:49.000Z | 2015-08-05T05:51:49.000Z | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | null | null | null | #if !defined(SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__)
#define SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__
#include "parser/tokens/TokenAbstract.hpp"
#include "parser/tokens/Operators.hpp"
#include "parser/tokens/TokenRegex.hpp"
#include "parser/tokens/TokenSIPMethod.hpp"
#include "parser/tokens/messageheaders/TokenSIPMessageHeader_base.hpp"
namespace sip0x
{
namespace parser
{
// Accept-Encoding = "Accept-Encoding" HCOLON
// [ encoding *(COMMA encoding) ]
// encoding = codings *(SEMI accept-param)
// codings = content-coding / "*"
// content-coding = token
class TokenSIPMessageHeader_Accept_Encoding : public TokenSIPMessageHeader_base<Sequence<TokenDigits, TokenLWS, TokenSIPMethod>> {
protected:
public:
//
TokenSIPMessageHeader_Accept_Encoding() : TokenSIPMessageHeader_base("Accept-Encoding", "Accept\\-Encoding",
Sequence<TokenDigits, TokenLWS, TokenSIPMethod>
(
TokenDigits(),
TokenLWS(),
TokenSIPMethod()
)
)
{
}
};
}
}
#endif // SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__
| 26.933333 | 134 | 0.685644 | zanfire |
8e7954158da411790676266ca929404d39018dc9 | 293 | cpp | C++ | Contest 1007/A.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1007/A.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | Contest 1007/A.cpp | PC-DOS/SEUCPP-OJ-KEYS | 073f97fb29a659abd25554330382f0a7149c2511 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
double squaresum(double a,double b){
return a*a+b*b;
}
int main(){
double a, b;
cin >> a >> b;
cout << squaresum(a,b);
//system("pause > nul");
return 0;
} | 18.3125 | 36 | 0.614334 | PC-DOS |
8e83a03ca069f2e1934d5464346eb101163cd3b8 | 56,637 | cpp | C++ | src/Gull.cpp | kazu-nanoha/NanohaM | 412f95fdcbc1eb1e8aeb5a75872eba0e544a1675 | [
"MIT"
] | null | null | null | src/Gull.cpp | kazu-nanoha/NanohaM | 412f95fdcbc1eb1e8aeb5a75872eba0e544a1675 | [
"MIT"
] | null | null | null | src/Gull.cpp | kazu-nanoha/NanohaM | 412f95fdcbc1eb1e8aeb5a75872eba0e544a1675 | [
"MIT"
] | null | null | null | ///#define W32_BUILD
///#undef W32_BUILD
#ifdef W32_BUILD
#define NTDDI_VERSION 0x05010200
#define _WIN32_WINNT 0x0501
#endif
///#ifndef W32_BUILD
///#define HNI
///#undef HNI
///#endif
#include <iostream>
#include <cmath>
#include <cinttypes>
#include <thread>
#include <mutex>
#include <intrin.h>
#include "setjmp.h"
#include "windows.h"
#include "types.h"
#include "misc.h"
#include "TT.h"
#include "evaluate.h"
#include "position.h"
#include "uci.h"
#include "genmove.h"
#include "search.h"
#include "thread.h"
///#define MP_NPS // --> search.cpp
/////#undef MP_NPS
///#define TIME_TO_DEPTH
/////#undef TIME_TO_DEPTH
using namespace std;
#if 0 // ToDo: DEL
constexpr uint8_t UpdateCastling[64] =
{
0xFF^CanCastle_OOO,0xFF,0xFF,0xFF,0xFF^(CanCastle_OO|CanCastle_OOO),
0xFF,0xFF,0xFF^CanCastle_OO,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF^CanCastle_ooo,0xFF,0xFF,0xFF,0xFF^(CanCastle_oo|CanCastle_ooo),
0xFF,0xFF,0xFF^CanCastle_oo
};
#endif
const uint64_t BMagic[64] =
{
0x0048610528020080, 0x00c4100212410004, 0x0004180181002010,
0x0004040188108502, 0x0012021008003040, 0x0002900420228000,
0x0080808410c00100, 0x000600410c500622, 0x00c0056084140184,
0x0080608816830050, 0x00a010050200b0c0, 0x0000510400800181,
0x0000431040064009, 0x0000008820890a06, 0x0050028488184008,
0x00214a0104068200, 0x004090100c080081, 0x000a002014012604,
0x0020402409002200, 0x008400c240128100, 0x0001000820084200,
0x0024c02201101144, 0x002401008088a800, 0x0003001045009000,
0x0084200040981549, 0x0001188120080100, 0x0048050048044300,
0x0008080000820012, 0x0001001181004003, 0x0090038000445000,
0x0010820800a21000, 0x0044010108210110, 0x0090241008204e30,
0x000c04204004c305, 0x0080804303300400, 0x00a0020080080080,
0x0000408020220200, 0x0000c08200010100, 0x0010008102022104,
0x0008148118008140, 0x0008080414809028, 0x0005031010004318,
0x0000603048001008, 0x0008012018000100, 0x0000202028802901,
0x004011004b049180, 0x0022240b42081400, 0x00c4840c00400020,
0x0084009219204000, 0x000080c802104000, 0x0002602201100282,
0x0002040821880020, 0x0002014008320080, 0x0002082078208004,
0x0009094800840082, 0x0020080200b1a010, 0x0003440407051000,
0x000000220e100440, 0x00480220a4041204, 0x00c1800011084800,
0x000008021020a200, 0x0000414128092100, 0x0000042002024200,
0x0002081204004200
};
const uint64_t RMagic[64] =
{
0x00800011400080a6, 0x004000100120004e, 0x0080100008600082,
0x0080080016500080, 0x0080040008000280, 0x0080020005040080,
0x0080108046000100, 0x0080010000204080, 0x0010800424400082,
0x00004002c8201000, 0x000c802000100080, 0x00810010002100b8,
0x00ca808014000800, 0x0002002884900200, 0x0042002148041200,
0x00010000c200a100, 0x00008580004002a0, 0x0020004001403008,
0x0000820020411600, 0x0002120021401a00, 0x0024808044010800,
0x0022008100040080, 0x00004400094a8810, 0x0000020002814c21,
0x0011400280082080, 0x004a050e002080c0, 0x00101103002002c0,
0x0025020900201000, 0x0001001100042800, 0x0002008080022400,
0x000830440021081a, 0x0080004200010084, 0x00008000c9002104,
0x0090400081002900, 0x0080220082004010, 0x0001100101000820,
0x0000080011001500, 0x0010020080800400, 0x0034010224009048,
0x0002208412000841, 0x000040008020800c, 0x001000c460094000,
0x0020006101330040, 0x0000a30010010028, 0x0004080004008080,
0x0024000201004040, 0x0000300802440041, 0x00120400c08a0011,
0x0080006085004100, 0x0028600040100040, 0x00a0082110018080,
0x0010184200221200, 0x0040080005001100, 0x0004200440104801,
0x0080800900220080, 0x000a01140081c200, 0x0080044180110021,
0x0008804001001225, 0x00a00c4020010011, 0x00001000a0050009,
0x0011001800021025, 0x00c9000400620811, 0x0032009001080224,
0x001400810044086a
};
const int32_t BShift[64] =
{
58, 59, 59, 59, 59, 59, 59, 58,
59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 57, 57, 57, 57, 59, 59,
59, 59, 57, 55, 55, 57, 59, 59,
59, 59, 57, 55, 55, 57, 59, 59,
59, 59, 57, 57, 57, 57, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59,
58, 59, 59, 59, 59, 59, 59, 58
};
const int32_t BOffset[64] =
{
0, 64, 96, 128, 160, 192, 224, 256,
320, 352, 384, 416, 448, 480, 512, 544,
576, 608, 640, 768, 896, 1024, 1152, 1184,
1216, 1248, 1280, 1408, 1920, 2432, 2560, 2592,
2624, 2656, 2688, 2816, 3328, 3840, 3968, 4000,
4032, 4064, 4096, 4224, 4352, 4480, 4608, 4640,
4672, 4704, 4736, 4768, 4800, 4832, 4864, 4896,
4928, 4992, 5024, 5056, 5088, 5120, 5152, 5184
};
const int32_t RShift[64] =
{
52, 53, 53, 53, 53, 53, 53, 52,
53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53,
52, 53, 53, 53, 53, 53, 53, 52
};
const int32_t ROffset[64] =
{
5248, 9344, 11392, 13440, 15488, 17536, 19584, 21632,
25728, 27776, 28800, 29824, 30848, 31872, 32896, 33920,
35968, 38016, 39040, 40064, 41088, 42112, 43136, 44160,
46208, 48256, 49280, 50304, 51328, 52352, 53376, 54400,
56448, 58496, 59520, 60544, 61568, 62592, 63616, 64640,
66688, 68736, 69760, 70784, 71808, 72832, 73856, 74880,
76928, 78976, 80000, 81024, 82048, 83072, 84096, 85120,
87168, 91264, 93312, 95360, 97408, 99456, 101504, 103552
};
uint64_t * BOffsetPointer[64];
uint64_t * ROffsetPointer[64];
#define FlagUnusualMaterial (1 << 30)
#if 0 // Memo
const int MatCode[16] = {0,0,MatWP,MatBP,MatWN,MatBN,MatWL,MatBL,MatWD,MatBD,MatWR,MatBR,MatWQ,MatBQ,0,0};
const uint64_t File[8] = {FileA,FileA<<1,FileA<<2,FileA<<3,FileA<<4,FileA<<5,FileA<<6,FileA<<7};
const uint64_t Line[8] = {Line0,(Line0<<8),(Line0<<16),(Line0<<24),(Line0<<32),(Line0<<40),(Line0<<48),(Line0<<56)};
#endif
/*
general move:
0 - 11: from & to
12 - 15: flags
16 - 23: history
24 - 25: spectial moves: killers, refutations...
26 - 30: MvvLva
delta move:
0 - 11: from & to
12 - 15: flags
16 - 31: int16_t delta + (int16_t)0x4000
*/
///const int MvvLvaVictim[16] = {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3};
const int MvvLvaAttacker[16] = {0, 0, 5, 5, 4, 4, 3, 3, 3, 3, 2, 2, 1, 1, 6, 6};
const int MvvLvaAttackerKB[16] = {0, 0, 9, 9, 7, 7, 5, 5, 5, 5, 3, 3, 1, 1, 11, 11};
#define PawnCaptureMvvLva(attacker) (MvvLvaAttacker[attacker])
#define MaxPawnCaptureMvvLva (MvvLvaAttacker[15]) // 6
#define KnightCaptureMvvLva(attacker) (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker])
#define MaxKnightCaptureMvvLva (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15]) // 17
#define BishopCaptureMvvLva(attacker) (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[attacker] + 1)
#define MaxBishopCaptureMvvLva (MaxPawnCaptureMvvLva + MvvLvaAttackerKB[15] + 1) // 18
#define RookCaptureMvvLva(attacker) (MaxBishopCaptureMvvLva + MvvLvaAttacker[attacker])
#define MaxRookCaptureMvvLva (MaxBishopCaptureMvvLva + MvvLvaAttacker[15]) // 24
#define QueenCaptureMvvLva(attacker) (MaxRookCaptureMvvLva + MvvLvaAttacker[attacker])
///#define MvvLvaPromotion (MvvLva[WhiteQueen][BlackQueen])
///#define MvvLvaPromotionKnight (MvvLva[WhiteKnight][BlackKnight])
///#define MvvLvaPromotionCap(capture) (MvvLva[((capture) < WhiteRook) ? WhiteRook : ((capture) >= WhiteQueen ? WhiteKing : WhiteKnight)][BlackQueen])
///#define MvvLvaPromotionKnightCap(capture) (MvvLva[WhiteKing][capture])
///#define MvvLvaXray (MvvLva[WhiteQueen][WhitePawn])
///#define MvvLvaXrayCap(capture) (MvvLva[WhiteKing][capture])
///#define RefOneScore ((0xFF << 16) | (3 << 24))
///#define RefTwoScore ((0xFF << 16) | (2 << 24))
///#define KillerOneScore ((0xFF << 16) | (1 << 24))
///#define KillerTwoScore (0xFF << 16)
///#define halt_check if ((Current - Data) >= 126) {evaluate(); return Current->score;} \
/// if (Current->ply >= 100) return 0; \
/// for (i = 4; i <= Current->ply; i+= 2) if (Stack[sp-i] == Current->key) return 0
///#define ExtFlag(ext) ((ext) << 16)
///#define Ext(flags) (((flags) >> 16) & 0xF)
///#define FlagHashCheck (1 << 20) // first 20 bits are reserved for the hash killer and extension
///#define FlagHaltCheck (1 << 21)
///#define FlagCallEvaluation (1 << 22)
///#define FlagDisableNull (1 << 23)
///#define FlagNeatSearch (FlagHashCheck | FlagHaltCheck | FlagCallEvaluation)
///#define FlagNoKillerUpdate (1 << 24)
///#define FlagReturnBestMove (1 << 25)
///#define MSBZ(x) ((x) ? msb(x) : 63)
///#define LSBZ(x) ((x) ? lsb(x) : 0)
///#define NB(me, x) ((me) ? msb(x) : lsb(x))
///#define NBZ(me, x) ((me) ? MSBZ(x) : LSBZ(x))
alignas(64) GBoard Board[1];
uint64_t Stack[2048];
int sp, save_sp;
uint64_t nodes, check_node, check_node_smp;
///GBoard SaveBoard[1];
///struct GPosData {
/// uint64_t key, pawn_key;
/// uint16_t move;
/// uint8_t turn, castle_flags, ply, ep_square, piece, capture;
/// uint8_t square[64];
/// int pst, material;
///};
alignas(64) GData Data[128]; // [ToDo] 数値の意味を確認する.
GData *Current = Data;
///#define FlagSort (1 << 0)
///#define FlagNoBcSort (1 << 1)
///GData SaveData[1];
///enum {
/// stage_search, s_hash_move, s_good_cap, s_special, s_quiet, s_bad_cap, s_none,
/// stage_evasion, e_hash_move, e_ev, e_none,
/// stage_razoring, r_hash_move, r_cap, r_checks, r_none
///};
///#define StageNone ((1 << s_none) | (1 << e_none) | (1 << r_none))
int RootList[256];
///#define prefetch(a,mode) _mm_prefetch(a,mode)
uint64_t Forward[2][8];
uint64_t West[8];
uint64_t East[8];
uint64_t PIsolated[8];
uint64_t HLine[64];
uint64_t VLine[64];
uint64_t NDiag[64];
uint64_t SDiag[64];
uint64_t RMask[64];
uint64_t BMask[64];
uint64_t QMask[64];
uint64_t BMagicMask[64];
uint64_t RMagicMask[64];
uint64_t NAtt[64];
uint64_t SArea[64];
uint64_t DArea[64];
uint64_t NArea[64];
uint64_t BishopForward[2][64];
uint64_t PAtt[2][64];
uint64_t PMove[2][64];
uint64_t PWay[2][64];
uint64_t PSupport[2][64];
uint64_t Between[64][64];
uint64_t FullLine[64][64];
///uint64_t * MagicAttacks;
///GMaterial * Material;
uint64_t MagicAttacks[magic_size];
GMaterial Material[TotalMat];
///#define FlagSingleBishop_w (1 << 0)
///#define FlagSingleBishop_b (1 << 1)
///#define FlagCallEvalEndgame_w (1 << 2)
///#define FlagCallEvalEndgame_b (1 << 3)
uint64_t TurnKey;
uint64_t PieceKey[16][64];
uint64_t CastleKey[16];
uint64_t EPKey[8];
uint16_t date;
uint64_t Kpk[2][64][64];
#if 0 // ToDo: DEL
int16_t History[16 * 64];
#define HistoryScore(piece,from,to) History[((piece) << 6) | (to)]
#define HistoryP(piece,from,to) ((Convert(HistoryScore(piece,from,to) & 0xFF00,int)/Convert(HistoryScore(piece,from,to) & 0x00FF,int)) << 16)
#define History(from,to) HistoryP(Square(from),from,to)
#define HistoryM(move) HistoryScore(Square(From(move)),From(move),To(move))
#define HistoryInc(depth) Min(((depth) >> 1) * ((depth) >> 1), 64)
#define HistoryGood(move) if ((HistoryM(move) & 0x00FF) >= 256 - HistoryInc(depth)) \
HistoryM(move) = ((HistoryM(move) & 0xFEFE) >> 1) + ((HistoryInc(depth) << 8) | HistoryInc(depth)); \
else HistoryM(move) += ((HistoryInc(depth) << 8) | HistoryInc(depth))
#define HistoryBad(move) if ((HistoryM(move) & 0x00FF) >= 256 - HistoryInc(depth)) \
HistoryM(move) = ((HistoryM(move) & 0xFEFE) >> 1) + HistoryInc(depth); else HistoryM(move) += HistoryInc(depth)
#endif
GRef Ref[16 * 64];
uint64_t seed = 1;
uint8_t PieceFromChar[256];
uint16_t PV[128];
char info_string[1024];
char pv_string[1024];
char score_string[16];
char mstring[65536];
int MultiPV[256];
int pvp;
int pv_length;
int best_move, best_score;
int TimeLimit1, TimeLimit2, Console, HardwarePopCnt;
int DepthLimit, LastDepth, LastTime, LastValue, LastExactValue, PrevMove, InstCnt;
int64_t LastSpeed;
int PVN, Stop, Print, Input = 1, PVHashing = 1, Infinite, MoveTime, SearchMoves, SMPointer, Ponder, Searching, Previous;
GSearchInfo CurrentSI[1], BaseSI[1];
int Aspiration = 1;
#define TimeSingTwoMargin 20
#define TimeSingOneMargin 30
#define TimeNoPVSCOMargin 60
#define TimeNoChangeMargin 70
#define TimeRatio 120
#define PonderRatio 120
#define MovesTg 30
#define InfoLag 5000
#define InfoDelay 1000
int64_t StartTime, InfoTime, CurrTime;
uint16_t SMoves[256];
jmp_buf Jump, ResetJump;
HANDLE StreamHandle;
///#define ExclSingle(depth) 8
///#define ExclDouble(depth) 16
///#define ExclSinglePV(depth) 8
///#define ExclDoublePV(depth) 16
// EVAL
const int8_t DistC[8] = {3, 2, 1, 0, 0, 1, 2, 3};
const int8_t RankR[8] = {-3, -2, -1, 0, 1, 2, 3, 4};
///const int SeeValue[16] = {0, 0, 90, 90, 325, 325, 325, 325, 325, 325, 510, 510, 975, 975, 30000, 30000};
const int PieceType[16] = {0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5};
#define V(x) (x)
// EVAL WEIGHTS
// tuner: start
enum { // tuner: enum
IMatLinear,
IMatQuadMe = IMatLinear + 5,
IMatQuadOpp = IMatQuadMe + 14,
IBishopPairQuad = IMatQuadOpp + 10,
IMatSpecial = IBishopPairQuad + 9,
IPstQuadWeights = IMatSpecial + 20,
IPstLinearWeights = IPstQuadWeights + 48,
IPstQuadMixedWeights = IPstLinearWeights + 48,
IMobilityLinear = IPstQuadMixedWeights + 24,
IMobilityLog = IMobilityLinear + 8,
IShelterValue = IMobilityLog + 8,
IStormQuad = IShelterValue + 15,
IStormLinear = IStormQuad + 5,
IStormHof = IStormLinear + 5,
IPasserQuad = IStormHof + 2,
IPasserLinear = IPasserQuad + 18,
IPasserAttDefQuad = IPasserLinear + 18,
IPasserAttDefLinear = IPasserAttDefQuad + 4,
IPasserSpecial = IPasserAttDefLinear + 4,
IIsolated = IPasserSpecial + 4,
IUnprotected = IIsolated + 10,
IBackward = IUnprotected + 6,
IDoubled = IBackward + 4,
IRookSpecial = IDoubled + 4,
ITactical = IRookSpecial + 20,
IKingDefence = ITactical + 12,
IPawnSpecial = IKingDefence + 8,
IBishopSpecial = IPawnSpecial + 8,
IKnightSpecial = IBishopSpecial + 4,
IPin = IKnightSpecial + 10,
IKingRay = IPin + 10,
IKingAttackWeight = IKingRay + 6
};
const int Phase[5] = {
0, 325, 325, 510, 975
};
#define MaxPhase (16 * Phase[0] + 4 * Phase[1] + 4 * Phase[2] + 4 * Phase[3] + 2 * Phase[4])
#define PhaseMin (2 * Phase[3] + Phase[1] + Phase[2])
#define PhaseMax (MaxPhase - Phase[1] - Phase[2])
const int MatLinear[5] = { // tuner: type=array, var=50, active=0
3, 0, 3, 19, 0
};
// pawn, knight, bishop, rook, queen
const int MatQuadMe[14] = { // tuner: type=array, var=1000, active=0
-33, 17, -23, -155, -247,
15, 296, -105, -83,
-162, 327, 315,
-861, -1013
};
const int MatQuadOpp[10] = { // tuner: type=array, var=1000, active=0
-14, 47, -20, -278,
35, 39, 49,
9, -2,
75
};
const int BishopPairQuad[9] = { // tuner: type=array, var=1000, active=0
-38, 164, 99, 246, -84, -57, -184, 88, -186
};
enum { MatRB, MatRN, MatQRR, MatQRB, MatQRN, MatQ3, MatBBR, MatBNR, MatNNR, MatM };
const int MatSpecial[20] = { // tuner: type=array, var=30, active=0
13, -13, 10, -9, 8, 12, 4, 6, 5, 9, -3, -8, -4, 7, 2, 0, 0, -6, 1, 3
};
// piece type (6) * direction (4: h center dist, v center dist, diag dist, rank) * phase (2)
const int PstQuadWeights[48] = { // tuner: type=array, var=100, active=0
-15, -19, -70, -13, 33, -20, 0, 197, -36, -122, 0, -60, -8, -3, -17, -28,
-27, -63, -17, -7, 14, 0, -24, -5, -64, -2, 0, -38, -8, 0, 77, 11,
-67, 3, -4, -92, -2, 12, -13, -42, -62, -84, -175, -42, -2, -17, 40, -19
};
const int PstLinearWeights[48] = { // tuner: type=array, var=500, active=0
-107, 67, -115, 83, -55, 67, 92, 443, -177, 5, -82, -61, -106, -104, 273, 130,
0, -145, -105, -58, -99, -37, -133, 14, -185, -43, -67, -53, 53, -65, 174, 134,
-129, 7, 98, -231, 107, -40, -27, 311, 256, -117, 813, -181, 2, -215, -44, 344
};
// piece type (6) * type (2: h * v, h * rank) * phase (2)
const int PstQuadMixedWeights[24] = { // tuner: type=array, var=100, active=0
14, -6, 1, -4, -8, -2, 4, -4,
1, -7, -12, 0, -2, -1, -5, 4,
5, -10, 0, 4, -2, 5, 4, -2
};
// tuner: stop
// END EVAL WEIGHTS
// SMP
int PrN = 1, CPUs = 1, HT = 0, parent = 1, child = 0, WinParId, Id = 0, ResetHash = 1, NewPrN = 0;
HANDLE ChildPr[MaxPrN];
///#define FlagClaimed (1 << 1)
///#define FlagFinished (1 << 2)
///GSMPI * Smpi;
///jmp_buf CheckJump;
HANDLE SHARED = NULL, HASH = NULL;
inline unsigned get_num_cpus(void) {
return std::thread::hardware_concurrency();
}
// END SMP
int lsb(uint64_t x);
int msb(uint64_t x);
int popcnt(uint64_t x);
int MinF(int x, int y);
int MaxF(int x, int y);
double MinF(double x, double y);
double MaxF(double x, double y);
template <bool HPopCnt> int popcount(uint64_t x);
uint64_t BMagicAttacks(int i, uint64_t occ);
uint64_t RMagicAttacks(int i, uint64_t occ);
uint16_t rand16();
uint64_t rand64();
void init_pst();
void init();
///void setup_board();
///void get_board(const char fen[]);
///template <bool me, bool pv> int q_search(int alpha, int beta, int depth, int flags);
///template <bool me, bool pv> int q_evasion(int alpha, int beta, int depth, int flags);
///template <bool me, bool exclusion> int search(int beta, int depth, int flags);
///template <bool me, bool exclusion> int search_evasion(int beta, int depth, int flags);
///template <bool me, bool root> int pv_search(int alpha, int beta, int depth, int flags);
///template <bool me> void root();
///template <bool me> int multipv(int depth);
///void send_multipv(int depth, int curr_number);
///void check_time(int searching);
///void check_time(int time, int searching);
///void check_state();
#ifndef W32_BUILD
int lsb(uint64_t x) {
#if defined(__GNUC__)
unsigned int y;
#else
unsigned long y;
#endif
_BitScanForward64(&y, x);
return y;
}
int msb(uint64_t x) {
#if defined(__GNUC__)
unsigned int y;
#else
unsigned long y;
#endif
_BitScanReverse64(&y, x);
return y;
}
int popcnt(uint64_t x) {
x = x - ((x >> 1) & 0x5555555555555555);
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
return (x * 0x0101010101010101) >> 56;
}
template <bool HPopCnt> int popcount(uint64_t x) {
return HPopCnt ? _mm_popcnt_u64(x) : popcnt(x);
}
template int popcount<true>(uint64_t x);
#else
__forceinline int lsb(uint64_t x) {
_asm {
mov eax, dword ptr x[0]
test eax, eax
jz l_high
bsf eax, eax
jmp l_ret
l_high : bsf eax, dword ptr x[4]
add eax, 20h
l_ret :
}
}
__forceinline int msb(uint64_t x) {
_asm {
mov eax, dword ptr x[4]
test eax, eax
jz l_low
bsr eax, eax
add eax, 20h
jmp l_ret
l_low : bsr eax, dword ptr x[0]
l_ret :
}
}
__forceinline int popcnt(uint64_t x) {
unsigned int x1, x2;
x1 = (unsigned int)(x & 0xFFFFFFFF);
x1 -= (x1 >> 1) & 0x55555555;
x1 = (x1 & 0x33333333) + ((x1 >> 2) & 0x33333333);
x1 = (x1 + (x1 >> 4)) & 0x0F0F0F0F;
x2 = (unsigned int)(x >> 32);
x2 -= (x2 >> 1) & 0x55555555;
x2 = (x2 & 0x33333333) + ((x2 >> 2) & 0x33333333);
x2 = (x2 + (x2 >> 4)) & 0x0F0F0F0F;
return ((x1 * 0x01010101) >> 24) + ((x2 * 0x01010101) >> 24);
}
template <bool HPopCnt> __forceinline int popcount(uint64_t x) {
return HPopCnt ? (__popcnt((int)x) + __popcnt(x >> 32)) : popcnt(x);
}
#endif
int MinF(int x, int y) { return Min(x, y); }
int MaxF(int x, int y) { return Max(x, y); }
double MinF(double x, double y) { return Min(x, y); }
double MaxF(double x, double y) { return Max(x, y); }
uint16_t rand16() {
seed = (seed * Convert(6364136223846793005,uint64_t)) + Convert(1442695040888963407,uint64_t);
return Convert((seed >> 32) & 0xFFFF,uint16_t);
}
uint64_t BMagicAttacks(int i, uint64_t occ)
{
uint64_t att = 0;
for (uint64_t u = BMask[i]; T(u); Cut(u)) {
if (F(Between[i][lsb(u)] & occ))
att |= Between[i][lsb(u)] | Bit(lsb(u));
}
return att;
}
uint64_t RMagicAttacks(int i, uint64_t occ)
{
uint64_t att = 0;
for (uint64_t u = RMask[i]; T(u); Cut(u)) {
if (F(Between[i][lsb(u)] & occ))
att |= Between[i][lsb(u)] | Bit(lsb(u));
}
return att;
}
uint64_t rand64()
{
uint64_t key = Convert(rand16(),uint64_t); key <<= 16;
key |= Convert(rand16(),uint64_t); key <<= 16;
key |= Convert(rand16(),uint64_t); key <<= 16;
return key | Convert(rand16(),uint64_t);
}
void init_misc() {
int i, j, k, l, n;
uint64_t u;
for (i = 0; i < 64; i++) {
HLine[i] = VLine[i] = NDiag[i] = SDiag[i] = RMask[i] = BMask[i] = QMask[i] = 0;
BMagicMask[i] = RMagicMask[i] = NAtt[i] = SArea[i] = DArea[i] = NArea[i] = 0;
PAtt[0][i] = PAtt[1][i] = PMove[0][i] = PMove[1][i] = PWay[0][i] = PWay[1][i] = PSupport[0][i] = PSupport[1][i] = BishopForward[0][i] = BishopForward[1][i] = 0;
for (j = 0; j < 64; j++) Between[i][j] = FullLine[i][j] = 0;
}
for (i = 0; i < 64; i++) for (j = 0; j < 64; j++) if (i != j) {
u = Bit(j);
if (File(i) == File(j)) VLine[i] |= u;
if (Rank(i) == Rank(j)) HLine[i] |= u;
if (NDiag(i) == NDiag(j)) NDiag[i] |= u;
if (SDiag(i) == SDiag(j)) SDiag[i] |= u;
if (Dist(i,j) <= 2) {
DArea[i] |= u;
if (Dist(i,j) <= 1) SArea[i] |= u;
if (Abs(Rank(i)-Rank(j)) + Abs(File(i)-File(j)) == 3) NAtt[i] |= u;
}
if (j == i + 8) PMove[0][i] |= u;
if (j == i - 8) PMove[1][i] |= u;
if (Abs(File(i) - File(j)) == 1) {
if (Rank(j) >= Rank(i)) {
PSupport[1][i] |= u;
if (Rank(j) - Rank(i) == 1) PAtt[0][i] |= u;
}
if (Rank(j) <= Rank(i)) {
PSupport[0][i] |= u;
if (Rank(i) - Rank(j) == 1) PAtt[1][i] |= u;
}
} else if (File(i) == File(j)) {
if (Rank(j) > Rank(i)) PWay[0][i] |= u;
else PWay[1][i] |= u;
}
}
for (i = 0; i < 64; i++) {
RMask[i] = HLine[i] | VLine[i];
BMask[i] = NDiag[i] | SDiag[i];
QMask[i] = RMask[i] | BMask[i];
BMagicMask[i] = BMask[i] & Interior;
RMagicMask[i] = RMask[i];
if (File(i) > 0) RMagicMask[i] &= ~File[0];
if (Rank(i) > 0) RMagicMask[i] &= ~Line[0];
if (File(i) < 7) RMagicMask[i] &= ~File[7];
if (Rank(i) < 7) RMagicMask[i] &= ~Line[7];
for (j = 0; j < 64; j++) if (NAtt[i] & NAtt[j]) Add(NArea[i],j);
}
for (i = 0; i < 8; i++) {
West[i] = 0;
East[i] = 0;
Forward[0][i] = Forward[1][i] = 0;
PIsolated[i] = 0;
for (j = 0; j < 8; j++) {
if (i < j) Forward[0][i] |= Line[j];
else if (i > j) Forward[1][i] |= Line[j];
if (i < j) East[i] |= File[j];
else if (i > j) West[i] |= File[j];
}
if (i > 0) PIsolated[i] |= File[i - 1];
if (i < 7) PIsolated[i] |= File[i + 1];
}
for (i = 0; i < 64; i++) {
for (u = QMask[i]; T(u); Cut(u)) {
j = lsb(u);
k = Sgn(Rank(j)-Rank(i));
l = Sgn(File(j)-File(i));
for (n = i + 8 * k + l; n != j; n += (8 * k + l)) Add(Between[i][j],n);
}
for (u = BMask[i]; T(u); Cut(u)) {
j = lsb(u);
FullLine[i][j] = BMask[i] & BMask[j];
}
for (u = RMask[i]; T(u); Cut(u)) {
j = lsb(u);
FullLine[i][j] = RMask[i] & RMask[j];
}
BishopForward[0][i] |= PWay[0][i];
BishopForward[1][i] |= PWay[1][i];
for (j = 0; j < 64; j++) {
if ((PWay[1][j] | Bit(j)) & BMask[i] & Forward[0][Rank(i)]) BishopForward[0][i] |= Bit(j);
if ((PWay[0][j] | Bit(j)) & BMask[i] & Forward[1][Rank(i)]) BishopForward[1][i] |= Bit(j);
}
}
for (i = 0; i < 16; i++) for (j = 0; j < 16; j++) {
if (j < WhitePawn) MvvLva[i][j] = 0;
else if (j < WhiteKnight) MvvLva[i][j] = PawnCaptureMvvLva(i) << 26;
else if (j < WhiteLight) MvvLva[i][j] = KnightCaptureMvvLva(i) << 26;
else if (j < WhiteRook) MvvLva[i][j] = BishopCaptureMvvLva(i) << 26;
else if (j < WhiteQueen) MvvLva[i][j] = RookCaptureMvvLva(i) << 26;
else MvvLva[i][j] = QueenCaptureMvvLva(i) << 26;
}
for (i = 0; i < 256; i++) PieceFromChar[i] = 0;
PieceFromChar[66] = 6; PieceFromChar[75] = 14; PieceFromChar[78] = 4; PieceFromChar[80] = 2; PieceFromChar[81] = 12; PieceFromChar[82] = 10;
PieceFromChar[98] = 7; PieceFromChar[107] = 15; PieceFromChar[110] = 5; PieceFromChar[112] = 3; PieceFromChar[113] = 13; PieceFromChar[114] = 11;
TurnKey = rand64();
for (i = 0; i < 8; i++) EPKey[i] = rand64();
for (i = 0; i < 16; i++) CastleKey[i] = rand64();
for (i = 0; i < 16; i++) for (j = 0; j < 64; j++) {
if (i == 0) PieceKey[i][j] = 0;
else PieceKey[i][j] = rand64();
}
/// for (i = 0; i < 16; i++) LogDist[i] = (int)(10.0 * log(1.01 + (double)i));
}
void init_magic() {
int i;
uint64_t j;
int k, index, bits, bit_list[16];
uint64_t u;
for (i = 0; i < 64; i++) {
bits = 64 - BShift[i];
for (u = BMagicMask[i], j = 0; T(u); Cut(u), j++) bit_list[j] = lsb(u);
for (j = 0; j < Bit(bits); j++) {
u = 0;
for (k = 0; k < bits; k++)
if (Odd(j >> k)) Add(u,bit_list[k]);
#ifndef HNI
index = Convert(BOffset[i] + ((BMagic[i] * u) >> BShift[i]),int);
#else
index = Convert(BOffset[i] + _pext_u64(u,BMagicMask[i]),int);
#endif
MagicAttacks[index] = BMagicAttacks(i,u);
}
bits = 64 - RShift[i];
for (u = RMagicMask[i], j = 0; T(u); Cut(u), j++) bit_list[j] = lsb(u);
for (j = 0; j < Bit(bits); j++) {
u = 0;
for (k = 0; k < bits; k++)
if (Odd(j >> k)) Add(u,bit_list[k]);
#ifndef HNI
index = Convert(ROffset[i] + ((RMagic[i] * u) >> RShift[i]),int);
#else
index = Convert(ROffset[i] + _pext_u64(u,RMagicMask[i]),int);
#endif
MagicAttacks[index] = RMagicAttacks(i,u);
}
}
}
void gen_kpk() {
int turn, wp, wk, bk, to, cnt, old_cnt, un;
uint64_t bwp, bwk, bbk, u;
uint8_t Kpk_gen[2][64][64][64];
memset(Kpk_gen, 0, 2 * 64 * 64 * 64);
cnt = 0;
old_cnt = 1;
start:
if (cnt == old_cnt) goto end;
old_cnt = cnt;
cnt = 0;
for (turn = 0; turn < 2; turn++) {
for (wp = 0; wp < 64; wp++) {
for (wk = 0; wk < 64; wk++) {
for (bk = 0; bk < 64; bk++) {
if (Kpk_gen[turn][wp][wk][bk]) continue;
cnt++;
if (wp < 8 || wp >= 56) goto set_draw;
if (wp == wk || wk == bk || bk == wp) goto set_draw;
bwp = Bit(wp);
bwk = Bit(wk);
bbk = Bit(bk);
if (PAtt[White][wp] & bbk) {
if (turn == White) goto set_draw;
else if (F(SArea[wk] & bwp)) goto set_draw;
}
un = 0;
if (turn == Black) {
u = SArea[bk] & (~(SArea[wk] | PAtt[White][wp]));
if (F(u)) goto set_draw;
for (; T(u); Cut(u)) {
to = lsb(u);
if (Kpk_gen[turn ^ 1][wp][wk][to] == 1) goto set_draw;
else if (Kpk_gen[turn ^ 1][wp][wk][to] == 0) un++;
}
if (F(un)) goto set_win;
}
else {
for (u = SArea[wk] & (~(SArea[bk] | bwp)); T(u); Cut(u)) {
to = lsb(u);
if (Kpk_gen[turn ^ 1][wp][to][bk] == 2) goto set_win;
else if (Kpk_gen[turn ^ 1][wp][to][bk] == 0) un++;
}
to = wp + 8;
if (to != wk && to != bk) {
if (to >= 56) {
if (F(SArea[to] & bbk)) goto set_win;
if (SArea[to] & bwk) goto set_win;
}
else {
if (Kpk_gen[turn ^ 1][to][wk][bk] == 2) goto set_win;
else if (Kpk_gen[turn ^ 1][to][wk][bk] == 0) un++;
if (to < 24) {
to += 8;
if (to != wk && to != bk) {
if (Kpk_gen[turn ^ 1][to][wk][bk] == 2) goto set_win;
else if (Kpk_gen[turn ^ 1][to][wk][bk] == 0) un++;
}
}
}
}
if (F(un)) goto set_draw;
}
continue;
set_draw:
Kpk_gen[turn][wp][wk][bk] = 1;
continue;
set_win:
Kpk_gen[turn][wp][wk][bk] = 2;
continue;
}
}
}
}
if (cnt) goto start;
end:
for (turn = 0; turn < 2; turn++) {
for (wp = 0; wp < 64; wp++) {
for (wk = 0; wk < 64; wk++) {
Kpk[turn][wp][wk] = 0;
for (bk = 0; bk < 64; bk++) {
if (Kpk_gen[turn][wp][wk][bk] == 2) Kpk[turn][wp][wk] |= Bit(bk);
}
}
}
}
}
void init_pst()
{
/// ToDo: ここの処理.
#if 0
int i, j, k, op, eg, index, r, f, d, e, distQ[4], distL[4], distM[2];
memset(Pst,0,16 * 64 * sizeof(int));
for (i = 0; i < 64; i++) {
r = Rank(i);
f = File(i);
d = Abs(f - r);
e = Abs(f + r - 7);
distQ[0] = DistC[f] * DistC[f]; distL[0] = DistC[f];
distQ[1] = DistC[r] * DistC[r]; distL[1] = DistC[r];
distQ[2] = RankR[d] * RankR[d] + RankR[e] * RankR[e]; distL[2] = RankR[d] + RankR[e];
distQ[3] = RankR[r] * RankR[r]; distL[3] = RankR[r];
distM[0] = DistC[f] * DistC[r]; distM[1] = DistC[f] * RankR[r];
for (j = 2; j < 16; j += 2) {
index = PieceType[j];
op = eg = 0;
for (k = 0; k < 2; k++) {
op += Av(PstQuadMixedWeights, 4, index, (k * 2)) * distM[k];
eg += Av(PstQuadMixedWeights, 4, index, (k * 2) + 1) * distM[k];
}
for (k = 0; k < 4; k++) {
op += Av(PstQuadWeights,8,index,(k * 2)) * distQ[k];
eg += Av(PstQuadWeights,8,index,(k * 2) + 1) * distQ[k];
op += Av(PstLinearWeights,8,index,(k * 2)) * distL[k];
eg += Av(PstLinearWeights,8,index,(k * 2) + 1) * distL[k];
}
Pst(j,i) = Compose(op/64, eg/64);
}
}
Pst(WhiteKnight,56) -= Compose(100, 0);
Pst(WhiteKnight,63) -= Compose(100, 0);
for (i = 0; i < 64; i++) {
for (j = 3; j < 16; j+=2) {
op = Opening(Pst(j-1,63-i));
eg = Endgame(Pst(j-1,63-i));
Pst(j,i) = Compose(-op,-eg);
}
}
Current->pst = 0;
for (i = 0; i < 64; i++)
if (Square(i)) Current->pst += Pst(Square(i),i);
#endif
}
void calc_material(int index) {
int pawns[2], knights[2], light[2], dark[2], rooks[2], queens[2], bishops[2], major[2], minor[2], tot[2], mat[2], mul[2], quad[2], score, phase, me, i = index;
queens[White] = i % 3; i /= 3;
queens[Black] = i % 3; i /= 3;
rooks[White] = i % 3; i /= 3;
rooks[Black] = i % 3; i /= 3;
light[White] = i % 2; i /= 2;
light[Black] = i % 2; i /= 2;
dark[White] = i % 2; i /= 2;
dark[Black] = i % 2; i /= 2;
knights[White] = i % 3; i /= 3;
knights[Black] = i % 3; i /= 3;
pawns[White] = i % 9; i /= 9;
pawns[Black] = i % 9;
for (me = 0; me < 2; me++) {
bishops[me] = light[me] + dark[me];
major[me] = rooks[me] + queens[me];
minor[me] = bishops[me] + knights[me];
tot[me] = 3 * minor[me] + 5 * rooks[me] + 9 * queens[me];
mat[me] = mul[me] = 32;
quad[me] = 0;
}
score = (SeeValue[WhitePawn] + Av(MatLinear, 0, 0, 0)) * (pawns[White] - pawns[Black]) + (SeeValue[WhiteKnight] + Av(MatLinear, 0, 0, 1)) * (knights[White] - knights[Black])
+ (SeeValue[WhiteLight] + Av(MatLinear, 0, 0, 2)) * (bishops[White] - bishops[Black]) + (SeeValue[WhiteRook] + Av(MatLinear, 0, 0, 3)) * (rooks[White] - rooks[Black])
+ (SeeValue[WhiteQueen] + Av(MatLinear, 0, 0, 4)) * (queens[White] - queens[Black]) + 50 * ((bishops[White] / 2) - (bishops[Black] / 2));
phase = Phase[PieceType[WhitePawn]] * (pawns[White] + pawns[Black]) + Phase[PieceType[WhiteKnight]] * (knights[White] + knights[Black])
+ Phase[PieceType[WhiteLight]] * (bishops[White] + bishops[Black]) + Phase[PieceType[WhiteRook]] * (rooks[White] + rooks[Black])
+ Phase[PieceType[WhiteQueen]] * (queens[White] + queens[Black]);
Material[index].phase = Min((Max(phase - PhaseMin, 0) * 128) / (PhaseMax - PhaseMin), 128);
int special = 0;
for (me = 0; me < 2; me++) {
const int opp = (1 ^ me);
if (queens[me] == queens[opp]) {
if (rooks[me] - rooks[opp] == 1) {
if (knights[me] == knights[opp] && bishops[opp] - bishops[me] == 1) IncV(special, Ca(MatSpecial, MatRB));
else if (bishops[me] == bishops[opp] && knights[opp] - knights[me] == 1) IncV(special, Ca(MatSpecial, MatRN));
else if (knights[me] == knights[opp] && bishops[opp] - bishops[me] == 2) DecV(special, Ca(MatSpecial, MatBBR));
else if (bishops[me] == bishops[opp] && knights[opp] - knights[me] == 2) DecV(special, Ca(MatSpecial, MatNNR));
else if (bishops[opp] - bishops[me] == 1 && knights[opp] - knights[me] == 1) DecV(special, Ca(MatSpecial, MatBNR));
} else if (rooks[me] == rooks[opp] && minor[me] - minor[opp] == 1) IncV(special, Ca(MatSpecial, MatM));
} else if (queens[me] - queens[opp] == 1) {
if (rooks[opp] - rooks[me] == 2 && minor[opp] - minor[me] == 0) IncV(special, Ca(MatSpecial, MatQRR));
else if (rooks[opp] - rooks[me] == 1 && knights[opp] == knights[me] && bishops[opp] - bishops[me] == 1) IncV(special, Ca(MatSpecial, MatQRB));
else if (rooks[opp] - rooks[me] == 1 && knights[opp] - knights[me] == 1 && bishops[opp] == bishops[me]) IncV(special, Ca(MatSpecial, MatQRN));
else if ((major[opp] + minor[opp]) - (major[me] + minor[me]) >= 2) IncV(special, Ca(MatSpecial, MatQ3));
}
}
score += (Opening(special) * Material[index].phase + Endgame(special) * (128 - (int)Material[index].phase)) / 128;
for (me = 0; me < 2; me++) {
const int opp = (1 ^ me);
quad[me] += pawns[me] * (pawns[me] * TrAv(MatQuadMe, 5, 0, 0) + knights[me] * TrAv(MatQuadMe, 5, 0, 1)
+ bishops[me] * TrAv(MatQuadMe, 5, 0, 2) + rooks[me] * TrAv(MatQuadMe, 5, 0, 3) + queens[me] * TrAv(MatQuadMe, 5, 0, 4));
quad[me] += knights[me] * (knights[me] * TrAv(MatQuadMe, 5, 1, 0)
+ bishops[me] * TrAv(MatQuadMe, 5, 1, 1) + rooks[me] * TrAv(MatQuadMe, 5, 1, 2) + queens[me] * TrAv(MatQuadMe, 5, 1, 3));
quad[me] += bishops[me] * (bishops[me] * TrAv(MatQuadMe, 5, 2, 0) + rooks[me] * TrAv(MatQuadMe, 5, 2, 1) + queens[me] * TrAv(MatQuadMe, 5, 2, 2));
quad[me] += rooks[me] * (rooks[me] * TrAv(MatQuadMe, 5, 3, 0) + queens[me] * TrAv(MatQuadMe, 5, 3, 1));
quad[me] += pawns[me] * (knights[opp] * TrAv(MatQuadOpp, 4, 0, 0)
+ bishops[opp] * TrAv(MatQuadOpp, 4, 0, 1) + rooks[opp] * TrAv(MatQuadOpp, 4, 0, 2) + queens[opp] * TrAv(MatQuadOpp, 4, 0, 3));
quad[me] += knights[me] * (bishops[opp] * TrAv(MatQuadOpp, 4, 1, 0) + rooks[opp] * TrAv(MatQuadOpp, 4, 1, 1) + queens[opp] * TrAv(MatQuadOpp, 4, 1, 2));
quad[me] += bishops[me] * (rooks[opp] * TrAv(MatQuadOpp, 4, 2, 0) + queens[opp] * TrAv(MatQuadOpp, 4, 2, 1));
quad[me] += rooks[me] * queens[opp] * TrAv(MatQuadOpp, 4, 3, 0);
if (bishops[me] >= 2) quad[me] += pawns[me] * Av(BishopPairQuad, 0, 0, 0) + knights[me] * Av(BishopPairQuad, 0, 0, 1) + rooks[me] * Av(BishopPairQuad, 0, 0, 2)
+ queens[me] * Av(BishopPairQuad, 0, 0, 3) + pawns[opp] * Av(BishopPairQuad, 0, 0, 4) + knights[opp] * Av(BishopPairQuad, 0, 0, 5)
+ bishops[opp] * Av(BishopPairQuad, 0, 0, 6) + rooks[opp] * Av(BishopPairQuad, 0, 0, 7) + queens[opp] * Av(BishopPairQuad, 0, 0, 8);
}
score += (quad[White] - quad[Black]) / 100;
for (me = 0; me < 2; me++) {
const int opp = (1 ^ me);
if (tot[me] - tot[opp] <= 3) {
if (!pawns[me]) {
if (tot[me] <= 3) mul[me] = 0;
if (tot[me] == tot[opp] && major[me] == major[opp] && minor[me] == minor[opp]) mul[me] = major[me] + minor[me] <= 2 ? 0 : (major[me] + minor[me] <= 3 ? 16 : 32);
else if (minor[me] + major[me] <= 2) {
if (bishops[me] < 2) mat[me] = (bishops[me] && rooks[me]) ? 8 : 1;
else if (bishops[opp] + rooks[opp] >= 1) mat[me] = 1;
else mat[me] = 32;
} else if (tot[me] - tot[opp] < 3 && minor[me] + major[me] - minor[opp] - major[opp] <= 1) mat[me] = 4;
else if (minor[me] + major[me] <= 3) mat[me] = 8 * (1 + bishops[me]);
else mat[me] = 8 * (2 + bishops[me]);
}
if (pawns[me] <= 1) {
mul[me] = Min(28, mul[me]);
if (rooks[me] == 1 && queens[me] + minor[me] == 0 && rooks[opp] == 1) mat[me] = Min(23, mat[me]);
}
}
if (!major[me]) {
if (!minor[me]) {
if (!tot[me] && pawns[me] < pawns[opp]) DecV(score, (pawns[opp] - pawns[me]) * SeeValue[WhitePawn]);
} else if (minor[me] == 1) {
if (pawns[me] <= 1 && minor[opp] >= 1) mat[me] = 1;
if (bishops[me] == 1) {
if (minor[opp] == 1 && bishops[opp] == 1 && light[me] != light[opp]) {
mul[me] = Min(mul[me], 15);
if (pawns[me] - pawns[opp] <= 1) mul[me] = Min(mul[me], 11);
}
}
} else if (!pawns[me] && knights[me] == 2 && !bishops[me]) {
if (!tot[opp] && pawns[opp]) mat[me] = 6;
else mul[me] = 0;
}
}
if (!mul[me]) mat[me] = 0;
if (mat[me] <= 1 && tot[me] != tot[opp]) mul[me] = Min(mul[me], 8);
}
if (bishops[White] == 1 && bishops[Black] == 1 && light[White] != light[Black]) {
mul[White] = Min(mul[White], 24 + 2 * (knights[Black] + major[Black]));
mul[Black] = Min(mul[Black], 24 + 2 * (knights[White] + major[White]));
} else if (!minor[White] && !minor[Black] && major[White] == 1 && major[Black] == 1 && rooks[White] == rooks[Black]) {
mul[White] = Min(mul[White], 25);
mul[Black] = Min(mul[Black], 25);
}
for (me = 0; me < 2; me++) {
Material[index].mul[me] = mul[me];
Material[index].pieces[me] = major[me] + minor[me];
}
if (score > 0) score = (score * mat[White]) / 32;
else score = (score * mat[Black]) / 32;
Material[index].score = score;
for (me = 0; me < 2; me++) {
const int opp = (1 ^ me);
if (major[me] == 0 && minor[me] == bishops[me] && minor[me] <= 1) Material[index].flags |= VarC(FlagSingleBishop, me);
if (((major[me] == 0 || minor[me] == 0) && major[me] + minor[me] <= 1) || major[opp] + minor[opp] == 0
|| (!pawns[me] && major[me] == rooks[me] && major[me] == 1 && minor[me] == bishops[me] && minor[me] == 1 && rooks[opp] == 1 && !minor[opp] && !queens[opp])) Material[index].flags |= VarC(FlagCallEvalEndgame, me);
}
}
void init_material() {
memset(Material,0,TotalMat * sizeof(GMaterial));
for (int index = 0; index < TotalMat; index++) calc_material(index);
}
#if 0
void init_shared() {
char name[256];
int64_t size = SharedPVHashOffset + pv_hash_size * sizeof(GPVEntry);
sprintf(name, "GULL_SHARED_%d", WinParId);
if (parent && SHARED != NULL) {
UnmapViewOfFile(Smpi);
CloseHandle(SHARED);
}
if (parent) SHARED = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, name);
else SHARED = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, name);
Smpi = (GSMPI*)MapViewOfFile(SHARED, FILE_MAP_ALL_ACCESS, 0, 0, size);
if (parent) memset(Smpi, 0, size);
Material = (GMaterial*)(((char*)Smpi) + SharedMaterialOffset);
MagicAttacks = (uint64_t*)(((char*)Smpi) + SharedMagicOffset);
PVHash = (GPVEntry*)(((char*)Smpi) + SharedPVHashOffset);
if (parent) memset(PVHash, 0, pv_hash_size * sizeof(GPVEntry));
}
#endif
void init() {
/// init_shared();
init_misc();
if (parent) init_magic();
for (int i = 0; i < 64; i++) {
BOffsetPointer[i] = MagicAttacks + BOffset[i];
ROffsetPointer[i] = MagicAttacks + ROffset[i];
}
gen_kpk();
init_pst();
init_eval();
if (parent) init_material();
USI::init();
TT.init();
}
// -->search.cpp
//// void init_search(int clear_hash)
#if 0
void setup_board()
{
int i;
uint64_t occ;
occ = 0;
sp = 0;
date++;
if (date > 0x8000) { // musn't ever happen
date = 2;
// now GUI must wait for readyok... we have plenty of time :)
TT.rewind();
PVHASH.rewind();
}
Current->material = 0;
Current->pst = 0;
Current->key = PieceKey[0][0];
if (Current->turn) Current->key ^= TurnKey;
Current->key ^= CastleKey[Current->castle_flags];
if (Current->ep_square) Current->key ^= EPKey[File(Current->ep_square)];
Current->pawn_key = 0;
Current->pawn_key ^= CastleKey[Current->castle_flags];
for (i = 0; i < 16; i++) BB(i) = 0;
for (i = 0; i < 64; i++) {
if (Square(i)) {
Add(BB(Square(i)),i);
Add(BB(Square(i) & 1),i);
Add(occ,i);
Current->key ^= PieceKey[Square(i)][i];
if (Square(i) < WhiteKnight) Current->pawn_key ^= PieceKey[Square(i)][i];
if (Square(i) < WhiteKing) Current->material += MatCode[Square(i)];
else Current->pawn_key ^= PieceKey[Square(i)][i];
Current->pst += Pst(Square(i),i);
}
}
if (popcnt(BB(WhiteKnight)) > 2 || popcnt(BB(WhiteLight)) > 1 || popcnt(BB(WhiteDark)) > 1
|| popcnt(BB(WhiteRook)) > 2 || popcnt(BB(WhiteQueen)) > 2) Current->material |= FlagUnusualMaterial;
if (popcnt(BB(BlackKnight)) > 2 || popcnt(BB(BlackLight)) > 1 || popcnt(BB(BlackDark)) > 1
|| popcnt(BB(BlackRook)) > 2 || popcnt(BB(BlackQueen)) > 2) Current->material |= FlagUnusualMaterial;
Current->capture = 0;
Current->killer[1] = Current->killer[2] = 0;
Current->ply = 0;
Stack[sp] = Current->key;
}
void get_board(const char fen[])
{
int pos, i, j;
unsigned char c;
Current = Data;
memset(Board,0,sizeof(GBoard));
memset(Current,0,sizeof(GData));
pos = 0;
c = fen[pos];
while (c == ' ') c = fen[++pos];
for (i = 56; i >= 0; i -= 8) {
for (j = 0; j <= 7; ) {
if (c <= '8') j += c - '0';
else {
Square(i+j) = PieceFromChar[c];
if (Even(SDiag(i+j)) && (Square(i+j)/2) == 3) Square(i+j) += 2;
j++;
}
c = fen[++pos];
}
c = fen[++pos];
}
if (c == 'b') Current->turn = 1;
c = fen[++pos]; c = fen[++pos];
if (c == '-') c = fen[++pos];
if (c == 'K') { Current->castle_flags |= CanCastle_OO; c = fen[++pos]; }
if (c == 'Q') { Current->castle_flags |= CanCastle_OOO; c = fen[++pos]; }
if (c == 'k') { Current->castle_flags |= CanCastle_oo; c = fen[++pos]; }
if (c == 'q') { Current->castle_flags |= CanCastle_ooo; c = fen[++pos]; }
c = fen[++pos];
if (c != '-') {
i = c + fen[++pos] * 8 - 489;
j = i ^ 8;
if (Square(i) != 0) i = 0;
else if (Square(j) != (3 - Current->turn)) i = 0;
else if (Square(j-1) != (Current->turn+2) && Square(j+1) != (Current->turn+2)) i = 0;
Current->ep_square = i;
}
setup_board();
}
#endif
void move_to_string(int move, char string[])
{
int pos = 0;
string[pos++] = ((move >> 6) & 7) + 'a';
string[pos++] = ((move >> 9) & 7) + '1';
string[pos++] = (move & 7) + 'a';
string[pos++] = ((move >> 3) & 7) + '1';
if (IsPromotion(move)) {
if ((move & 0xF000) == FlagPQueen) string[pos++] = 'q';
else if ((move & 0xF000) == FlagPRook) string[pos++] = 'r';
else if ((move & 0xF000) == FlagPLight || (move & 0xF000) == FlagPDark) string[pos++] = 'b';
else if ((move & 0xF000) == FlagPKnight) string[pos++] = 'n';
}
string[pos] = 0;
}
int move_from_string(const char string[]) {
int from, to, move;
from = ((string[1] - '1') * 8) + (string[0] - 'a');
to = ((string[3] - '1') * 8) + (string[2] - 'a');
move = (from << 6) | to;
if (Board->square[from] >= WhiteKing && Abs(to - from) == 2) move |= FlagCastling;
if (T(Current->ep_square) && to == Current->ep_square) move |= FlagEP;
if (string[4] != 0) {
if (string[4] == 'q') move |= FlagPQueen;
else if (string[4] == 'r') move |= FlagPRook;
else if (string[4] == 'b') {
if (Odd(to ^ Rank(to))) move |= FlagPLight;
else move |= FlagPDark;
} else if (string[4] == 'n') move |= FlagPKnight;
}
return move;
}
// -->search.cpp
////void pick_pv()
////template <bool me> int draw_in_pv()
// -->position.cpp
////template <bool me> void do_move(int move)
////template <bool me> void undo_move(int move)
////void do_null()
////void undo_null()
////template <bool me> int is_legal(int move)
////template <bool me> int is_check(int move) // doesn't detect castling and ep checks
// -->search.cpp
////void hash_high(int value, int depth)
////void hash_low(int move, int value, int depth)
////void hash_exact(int move, int value, int depth, int exclusion, int ex_depth, int knodes)
////template <bool pv> __forceinline int extension(int move, int depth)
// -->genmove.cpp
////void sort(int * start, int * finish)
// -->search.cpp
////void sort_moves(int * start, int * finish)
// -->genmove.cpp
////__forceinline int pick_move()
////template <bool me> void gen_next_moves()
////template <bool me, bool root> int get_move()
////template <bool me> int see(int move, int margin)
////template <bool me> void gen_root_moves()
////template <bool me> int * gen_captures(int * list)
////template <bool me> int * gen_evasions(int * list)
////void mark_evasions(int * list)
////template <bool me> int * gen_quiet_moves(int * list)
////template <bool me> int * gen_checks(int * list)
////template <bool me> int * gen_delta_moves(int * list)
// -->search.cpp
////template <bool me> int singular_extension(int ext, int prev_ext, int margin_one, int margin_two, int depth, int killer)
////template <bool me> __forceinline void capture_margin(int alpha, int &score)
////template <bool me, bool pv> int q_search(int alpha, int beta, int depth, int flags)
////template <bool me, bool pv> int q_evasion(int alpha, int beta, int depth, int flags)
////void send_position(GPos * Pos)
////void retrieve_board(GPos * Pos)
////void retrieve_position(GPos * Pos, int copy_stack)
////void halt_all(GSP * Sp, int locked)
////void halt_all(int from, int to)
////void init_sp(GSP * Sp, int alpha, int beta, int depth, int pv, int singular, int height)
////template <bool me> int smp_search(GSP * Sp)
////template <bool me, bool exclusion> int search(int beta, int depth, int flags)
////template <bool me, bool exclusion> int search_evasion(int beta, int depth, int flags)
////template <bool me, bool root> int pv_search(int alpha, int beta, int depth, int flags)
////template <bool me> void root()
////template <bool me> int multipv(int depth)
////void send_pv(int depth, int alpha, int beta, int score)
////void send_best_move()
void get_position(char string[]) {
#if 0 // ToDo: ちゃんと考える。
const char * fen;
char * moves;
const char * ptr;
int move, move1 = 0;
fen = strstr(string,"fen ");
moves = strstr(string,"moves ");
if (fen != NULL) get_board(fen+4);
else get_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
PrevMove = 0;
if (moves != NULL) {
ptr = moves+6;
while (*ptr != 0) {
pv_string[0] = *ptr++;
pv_string[1] = *ptr++;
pv_string[2] = *ptr++;
pv_string[3] = *ptr++;
if (*ptr == 0 || *ptr == ' ') pv_string[4] = 0;
else {
pv_string[4] = *ptr++;
pv_string[5] = 0;
}
evaluate();
move = move_from_string(pv_string);
PrevMove = move1;
move1 = move;
if (Current->turn) do_move<1>(move);
else do_move<0>(move);
memcpy(Data,Current,sizeof(GData));
Current = Data;
while (*ptr == ' ') ptr++;
}
}
memcpy(Stack, Stack + sp - Current->ply, (Current->ply + 1) * sizeof(uint64_t));
sp = Current->ply;
#endif
}
void get_time_limit(char string[]) {
const char * ptr;
int i, time, inc, wtime, btime, winc, binc, moves, pondering, movetime = 0, exp_moves = MovesTg - 1;
Infinite = 1;
MoveTime = 0;
SearchMoves = 0;
SMPointer = 0;
pondering = 0;
TimeLimit1 = 0;
TimeLimit2 = 0;
wtime = btime = 0;
winc = binc = 0;
moves = 0;
Stop = 0;
DepthLimit = 128;
ptr = strtok(string," ");
for (ptr = strtok(NULL," "); ptr != NULL; ptr = strtok(NULL," ")) {
if (!strcmp(ptr,"binc")) {
ptr = strtok(NULL," ");
binc = atoi(ptr);
Infinite = 0;
} else if (!strcmp(ptr,"btime")) {
ptr = strtok(NULL," ");
btime = atoi(ptr);
Infinite = 0;
} else if (!strcmp(ptr,"depth")) {
ptr = strtok(NULL," ");
DepthLimit = 2 * atoi(ptr) + 2;
Infinite = 1;
} else if (!strcmp(ptr,"infinite")) {
Infinite = 1;
} else if (!strcmp(ptr,"movestogo")) {
ptr = strtok(NULL," ");
moves = atoi(ptr);
Infinite = 0;
} else if (!strcmp(ptr,"winc")) {
ptr = strtok(NULL," ");
winc = atoi(ptr);
Infinite = 0;
} else if (!strcmp(ptr,"wtime")) {
ptr = strtok(NULL," ");
wtime = atoi(ptr);
Infinite = 0;
} else if (!strcmp(ptr,"movetime")) {
ptr = strtok(NULL," ");
movetime = atoi(ptr);
MoveTime = 1;
Infinite = 0;
} else if (!strcmp(ptr,"searchmoves")) {
if (F(SearchMoves)) {
for (i = 0; i < 256; i++) SMoves[i] = 0;
}
SearchMoves = 1;
ptr += 12;
while (ptr != NULL && ptr[0] >= 'a' && ptr[0] <= 'h' && ptr[1] >= '1' && ptr[1] <= '8') {
pv_string[0] = *ptr++;
pv_string[1] = *ptr++;
pv_string[2] = *ptr++;
pv_string[3] = *ptr++;
if (*ptr == 0 || *ptr == ' ') pv_string[4] = 0;
else {
pv_string[4] = *ptr++;
pv_string[5] = 0;
}
SMoves[SMPointer] = move_from_string(pv_string);
SMPointer++;
ptr = strtok(NULL," ");
}
} else if (!strcmp(ptr,"ponder")) pondering = 1;
}
if (pondering) Infinite = 1;
if (Current->turn == White) {
time = wtime;
inc = winc;
} else {
time = btime;
inc = binc;
}
if (moves) moves = Max(moves - 1, 1);
int time_max = Max(time - Min(1000, time/2), 0);
int nmoves;
if (moves) nmoves = moves;
else {
nmoves = MovesTg - 1;
if (Current->ply > 40) nmoves += Min(Current->ply - 40, (100 - Current->ply)/2);
exp_moves = nmoves;
}
TimeLimit1 = Min(time_max, (time_max + (Min(exp_moves, nmoves) * inc))/Min(exp_moves, nmoves));
TimeLimit2 = Min(time_max, (time_max + (Min(exp_moves, nmoves) * inc))/Min(3,Min(exp_moves, nmoves)));
TimeLimit1 = Min(time_max, (TimeLimit1 * TimeRatio)/100);
if (Ponder) TimeLimit1 = (TimeLimit1 * PonderRatio)/100;
if (MoveTime) {
TimeLimit2 = movetime;
TimeLimit1 = TimeLimit2 * 100;
}
InfoTime = StartTime = get_time();
Searching = 1;
/// if (MaxPrN > 1) SET_BIT_64(Smpi->searching, 0);
if (F(Infinite)) PVN = 1;
if (Current->turn == White) root<0>(); else root<1>();
}
int time_to_stop(GSearchInfo * SI, int time, int searching) {
if (Infinite) return 0;
if (time > TimeLimit2) return 1;
if (searching) return 0;
if (2 * time > TimeLimit2 && F(MoveTime)) return 1;
if (SI->Bad) return 0;
if (time > TimeLimit1) return 1;
if (T(SI->Change) || T(SI->FailLow)) return 0;
if (time * 100 > TimeLimit1 * TimeNoChangeMargin) return 1;
if (F(SI->Early)) return 0;
if (time * 100 > TimeLimit1 * TimeNoPVSCOMargin) return 1;
if (SI->Singular < 1) return 0;
if (time * 100 > TimeLimit1 * TimeSingOneMargin) return 1;
if (SI->Singular < 2) return 0;
if (time * 100 > TimeLimit1 * TimeSingTwoMargin) return 1;
return 0;
}
void check_time(int searching) {
/// while (!Stop && input()) uci();
int Time;
if (Stop) goto jump;
CurrTime = get_time();
Time = Convert(CurrTime - StartTime,int);
if (T(Print) && Time > InfoLag && CurrTime - InfoTime > InfoDelay) {
InfoTime = CurrTime;
if (info_string[0]) {
fprintf(stdout,"%s",info_string);
info_string[0] = 0;
fflush(stdout);
}
}
if (time_to_stop(CurrentSI, Time, searching)) goto jump;
return;
jump:
Stop = 1;
longjmp(Jump,1);
}
void check_time(int time, int searching) {
/// while (!Stop && input()) uci();
int Time;
if (Stop) goto jump;
CurrTime = get_time();
Time = Convert(CurrTime - StartTime,int);
if (T(Print) && Time > InfoLag && CurrTime - InfoTime > InfoDelay) {
InfoTime = CurrTime;
if (info_string[0]) {
fprintf(stdout,"%s",info_string);
info_string[0] = 0;
fflush(stdout);
}
}
if (time_to_stop(CurrentSI, time, searching)) goto jump;
return;
jump:
Stop = 1;
longjmp(Jump,1);
}
#if 0 // ToDo: ちゃんと考える。
void check_state() {
GSP *Sp, *Spc;
int n, nc, score, best, pv, alpha, beta, new_depth, r_depth, ext, move, value;
GMove * M;
if (parent) {
for (uint64_t u = TEST_RESET(Smpi->fail_high); u; Cut(u)) {
Sp = &Smpi->Sp[lsb(u)];
LOCK(Sp->lock);
if (Sp->active && Sp->finished) {
UNLOCK(Sp->lock);
longjmp(Sp->jump, 1);
}
UNLOCK(Sp->lock);
}
return;
}
start:
if (TEST_RESET_BIT(Smpi->stop, Id)) longjmp(CheckJump, 1);
if (Smpi->searching & Bit(Id)) return;
if (!(Smpi->searching & 1)) {
Sleep(1);
return;
}
while ((Smpi->searching & 1) && !Smpi->active_sp) _mm_pause();
while ((Smpi->searching & 1) && !(Smpi->searching & Bit(Id - 1))) _mm_pause();
Sp = NULL; best = -0x7FFFFFFF;
for (uint64_t u = Smpi->active_sp; u; Cut(u)) {
Spc = &Smpi->Sp[lsb(u)];
if (!Spc->active || Spc->finished || Spc->lock) continue;
for (nc = Spc->current + 1; nc < Spc->move_number; nc++) if (!(Spc->move[nc].flags & FlagClaimed)) break;
if (nc < Spc->move_number) score = 1024 * 1024 + 512 * 1024 * (Spc->depth >= 20) + 128 * 1024 * (!(Spc->split))
+ ((Spc->depth + 2 * Spc->singular) * 1024) - (((16 * 1024) * (nc - Spc->current)) / nc);
else continue;
if (score > best) {
best = score;
Sp = Spc;
n = nc;
}
}
if (Sp == NULL) goto start;
if (!Sp->active || Sp->finished || (Sp->move[n].flags & FlagClaimed) || n <= Sp->current || n >= Sp->move_number) goto start;
if (Sp->lock) goto start;
LOCK(Sp->lock);
if (!Sp->active || Sp->finished || (Sp->move[n].flags & FlagClaimed) || n <= Sp->current || n >= Sp->move_number) {
UNLOCK(Sp->lock);
goto start;
}
M = &Sp->move[n];
M->flags |= FlagClaimed;
M->id = Id;
Sp->split |= Bit(Id);
pv = Sp->pv;
alpha = Sp->alpha;
beta = Sp->beta;
new_depth = M->reduced_depth;
r_depth = M->research_depth;
ext = M->ext;
move = M->move;
Current = Data;
retrieve_position(Sp->Pos, 1);
evaluate();
SET_BIT_64(Smpi->searching, Id);
UNLOCK(Sp->lock);
if (setjmp(CheckJump)) {
ZERO_BIT_64(Smpi->searching, Id);
return;
}
if (Current->turn == White) {
do_move<0>(move);
if (pv) {
value = -search<1, 0>(-alpha, new_depth, FlagNeatSearch | ExtFlag(ext));
if (value > alpha) value = -pv_search<1, 0>(-beta, -alpha, r_depth, ExtFlag(ext));
} else {
value = -search<1, 0>(1 - beta, new_depth, FlagNeatSearch | ExtFlag(ext));
if (value >= beta && new_depth < r_depth) value = -search<1, 0>(1 - beta, r_depth, FlagNeatSearch | FlagDisableNull | ExtFlag(ext));
}
undo_move<0>(move);
} else {
do_move<1>(move);
if (pv) {
value = -search<0, 0>(-alpha, new_depth, FlagNeatSearch | ExtFlag(ext));
if (value > alpha) value = -pv_search<0, 0>(-beta, -alpha, r_depth, ExtFlag(ext));
} else {
value = -search<0, 0>(1 - beta, new_depth, FlagNeatSearch | ExtFlag(ext));
if (value >= beta && new_depth < r_depth) value = -search<0, 0>(1 - beta, r_depth, FlagNeatSearch | FlagDisableNull | ExtFlag(ext));
}
undo_move<1>(move);
}
LOCK(Sp->lock);
ZERO_BIT_64(Smpi->searching, Id);
if (TEST_RESET_BIT(Smpi->stop, Id)) {
UNLOCK(Sp->lock);
return;
}
M->flags |= FlagFinished;
if (value > Sp->alpha) {
Sp->alpha = Min(value, beta);
Sp->best_move = move;
if (value >= beta) {
Sp->finished = 1;
SET_BIT_64(Smpi->fail_high, (int)(Sp - Smpi->Sp));
}
}
UNLOCK(Sp->lock);
}
#endif
HANDLE CreateChildProcess(int child_id) {
char name[1024];
TCHAR szCmdline[1024];
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
ZeroMemory(szCmdline, 1024 * sizeof(TCHAR));
ZeroMemory(name, 1024);
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
GetModuleFileName(NULL, name, 1024);
sprintf(szCmdline, " child %d %d", WinParId, child_id);
bSuccess = CreateProcess(TEXT(name), TEXT(szCmdline), NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &siStartInfo, &piProcInfo);
if (bSuccess) {
CloseHandle(piProcInfo.hThread);
return piProcInfo.hProcess;
} else {
fprintf(stdout, "Error %d\n", GetLastError());
return NULL;
}
}
int main(int argc, char *argv[]) {
DWORD p;
int i;
if (argc >= 2) if (!memcmp(argv[1], "child", 5)) {
child = 1; parent = 0;
WinParId = atoi(argv[2]);
Id = atoi(argv[3]);
}
int CPUInfo[4] = { -1 };
/// __cpuid(CPUInfo, 1);
/// HardwarePopCnt = (CPUInfo[2] >> 23) & 1;
HardwarePopCnt = 1;
if (parent) {
if (((CPUInfo[3] >> 28) & 1) && GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation") != NULL) {
SYSTEM_LOGICAL_PROCESSOR_INFORMATION syslogprocinfo[1];
p = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
#ifndef W32_BUILD
GetLogicalProcessorInformation(syslogprocinfo, &p);
if (syslogprocinfo->ProcessorCore.Flags == 1) HT = 1;
#endif
}
WinParId = GetProcessId(GetCurrentProcess());
HANDLE JOB = CreateJobObject(NULL, NULL);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(JOB, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli));
AssignProcessToJobObject(JOB, GetCurrentProcess());
if (MaxPrN > 1) {
PrN = get_num_cpus();
}
}
init();
StreamHandle = GetStdHandle(STD_INPUT_HANDLE);
Console = GetConsoleMode(StreamHandle, &p);
if (Console) {
SetConsoleMode(StreamHandle, p & (~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT)));
FlushConsoleInputBuffer(StreamHandle);
}
setbuf(stdout, NULL);
setbuf(stdin, NULL);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stdin, NULL, _IONBF, 0);
fflush(NULL);
#if 0 // ToDo
reset_jump:
if (parent) {
if (setjmp(ResetJump)) {
for (i = 1; i < PrN; i++) TerminateProcess(ChildPr[i], 0);
for (i = 1; i < PrN; i++) {
WaitForSingleObject(ChildPr[i], INFINITE);
CloseHandle(ChildPr[i]);
}
Smpi->searching = Smpi->active_sp = Smpi->stop = 0;
for (i = 0; i < MaxSplitPoints; i++) Smpi->Sp->active = Smpi->Sp->claimed = 0;
Smpi->hash_size = hash_size;
if (NewPrN) Smpi->PrN = PrN = NewPrN;
goto reset_jump;
}
Smpi->hash_size = hash_size;
Smpi->PrN = PrN;
} else {
hash_size = Smpi->hash_size;
PrN = Smpi->PrN;
}
#endif
/// if (ResetHash) init_hash();
if (ResetHash) TT.init();
/// init_search(0);
#if 0 // ToDo: ちゃんと考える。
if (child) while (true) check_state();
#endif
// if (parent) for (i = 1; i < PrN; i++) ChildPr[i] = CreateChildProcess(i);
Threads.init();
USI::loop(argc, argv);
Threads.set_size(0);
return 0;
}
| 33.592527 | 215 | 0.610114 | kazu-nanoha |
8e83bcfaabbf612acfdb038749b5043345b70b7a | 2,346 | cpp | C++ | src/prod/src/ServiceModel/ContainerIsolationMode.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/ServiceModel/ContainerIsolationMode.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/ServiceModel/ContainerIsolationMode.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
namespace ServiceModel
{
namespace ContainerIsolationMode
{
void WriteToTextWriter(TextWriter & w, Enum const & val)
{
switch (val)
{
case ContainerIsolationMode::process:
w << L"process";
return;
case ContainerIsolationMode::hyperv:
w << L"hyperv";
return;
default:
Assert::CodingError("Unknown ContainerIsolationMode value {0}", (int)val);
}
}
ErrorCode FromString(wstring const & value, __out Enum & val)
{
if (value == L"process" || value == L"default")
{
val = ContainerIsolationMode::process;
return ErrorCode(ErrorCodeValue::Success);
}
else if (value == L"hyperv")
{
val = ContainerIsolationMode::hyperv;
return ErrorCode(ErrorCodeValue::Success);
}
else
{
return ErrorCode::FromHResult(E_INVALIDARG);
}
}
wstring EnumToString(Enum val)
{
switch (val)
{
case ContainerIsolationMode::process:
return L"process";
case ContainerIsolationMode::hyperv:
return L"hyperv";
default:
Assert::CodingError("Unknown ContainerIsolationMode value {0}", (int)val);
}
}
FABRIC_CONTAINER_ISOLATION_MODE ContainerIsolationMode::ToPublicApi(Enum isolationMode)
{
switch (isolationMode)
{
case process:
return FABRIC_CONTAINER_ISOLATION_MODE_PROCESS;
case hyperv:
return FABRIC_CONTAINER_ISOLATION_MODE_HYPER_V;
default:
return FABRIC_CONTAINER_ISOLATION_MODE_PROCESS;
}
}
}
}
| 29.696203 | 98 | 0.507246 | vishnuk007 |
8e87d1ea8ddc6b31f98de81d6a9e252e1e4a26f9 | 580 | cpp | C++ | etc/FastIO.cpp | jinhan814/algorithms-implementation | b5185f98c5d5d34c0f98de645e5b755fcf75c120 | [
"MIT"
] | null | null | null | etc/FastIO.cpp | jinhan814/algorithms-implementation | b5185f98c5d5d34c0f98de645e5b755fcf75c120 | [
"MIT"
] | null | null | null | etc/FastIO.cpp | jinhan814/algorithms-implementation | b5185f98c5d5d34c0f98de645e5b755fcf75c120 | [
"MIT"
] | null | null | null | /*
* https://blog.naver.com/jinhan814/222400578937
*/
#include <bits/stdc++.h>
#include <sys/stat.h>
#include <sys/mman.h>
using namespace std;
int main() {
struct stat st; fstat(0, &st);
char* p = (char*)mmap(0, st.st_size, PROT_READ, MAP_SHARED, 0, 0);
auto ReadInt = [&]() {
int ret = 0;
for (char c = *p++; c & 16; ret = 10 * ret + (c & 15), c = *p++);
return ret;
};
auto ReadSignedInt = [&]() {
int ret = 0; char c = *p++, flag = 0;
if (c == '-') c = *p++, flag = 1;
for (; c & 16; ret = 10 * ret + (c & 15), c = *p++);
return flag ? -ret : ret;
};
} | 24.166667 | 67 | 0.524138 | jinhan814 |
8e88ffdb44fa10c13a4a05e29143abca1544cfb5 | 426 | hpp | C++ | src/rstd/core.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | src/rstd/core.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | src/rstd/core.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | #pragma once
#include <rcore/prelude.hpp>
namespace rstd {
inline std::istream &stdin_() { return rcore::stdin_(); }
inline std::ostream &stdout_() { return rcore::stdout_(); }
inline std::ostream &stderr_() { return rcore::stderr_(); }
typedef rcore::Once Once;
typedef rcore::Thread Thread;
namespace thread {
inline Thread ¤t() { return rcore::thread::current(); }
} // namespace thread
} // namespace rstd
| 18.521739 | 61 | 0.694836 | agerasev |
8e8b2b55ebd85f56968f92046be4946bd7d01de8 | 27,439 | cpp | C++ | cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 27 | 2020-03-29T16:02:09.000Z | 2021-12-18T20:08:51.000Z | cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 22 | 2020-04-03T03:40:59.000Z | 2022-03-29T15:55:28.000Z | cpp/visual studio/CalculatorServer/reader/reader_statistics_screen.cpp | NiHoel/Anno1800UXEnhancer | b430fdb428696b5218ca65a5e9b977d659cfca01 | [
"Apache-2.0"
] | 2 | 2021-10-17T16:15:46.000Z | 2022-01-10T18:56:49.000Z | #include "reader_statistics_screen.hpp"
#include <iostream>
#include <numeric>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
namespace reader
{
////////////////////////////////////////
//
// Class: statistics_screen_params
//
////////////////////////////////////////
const cv::Scalar statistics_screen_params::background_blue_dark = cv::Scalar(103, 87, 79, 255);
const cv::Scalar statistics_screen_params::background_brown_light = cv::Scalar(124, 181, 213, 255);
const cv::Scalar statistics_screen_params::foreground_brown_light = cv::Scalar(96, 195, 255, 255);
const cv::Scalar statistics_screen_params::foreground_brown_dark = cv::Scalar(19, 53, 81, 255);
const cv::Scalar statistics_screen_params::expansion_arrow = cv::Scalar(78, 98, 115, 255);
const cv::Rect2f statistics_screen_params::pane_tabs = cv::Rect2f(cv::Point2f(0.2352f, 0.147f), cv::Point2f(0.7648f, 0.1839f));
const cv::Rect2f statistics_screen_params::pane_title = cv::Rect2f(cv::Point2f(0.3839f, 0), cv::Point2f(0.6176f, 0.0722f));
const cv::Rect2f statistics_screen_params::pane_all_islands = cv::Rect2f(cv::Point2f(0.0234f, 0.2658f), cv::Point2f(0.19f, 0.315f));
const cv::Rect2f statistics_screen_params::pane_islands = cv::Rect2f(cv::Point2f(0.0215f, 0.3326f), cv::Point2f(0.1917f, 0.9586f));
const cv::Rect2f statistics_screen_params::pane_finance_center = cv::Rect2f(cv::Point2f(0.2471f, 0.3084f), cv::Point2f(0.5805f, 0.9576f));
const cv::Rect2f statistics_screen_params::pane_finance_right = cv::Rect2f(cv::Point2f(0.6261f, 0.3603f), cv::Point2f(0.9635f, 0.9587f));
const cv::Rect2f statistics_screen_params::pane_production_center = cv::Rect2f(cv::Point2f(0.24802f, 0.3639f), cv::Point2f(0.583f, 0.9568f));
const cv::Rect2f statistics_screen_params::pane_production_right = cv::Rect2f(cv::Point2f(0.629f, 0.3613f), cv::Point2f(0.9619f, 0.9577f));
const cv::Rect2f statistics_screen_params::pane_population_center = cv::Rect2f(cv::Point2f(0.247f, 0.3571f), cv::Point2f(0.5802f, 0.7006f));
const cv::Rect2f statistics_screen_params::pane_header_center = cv::Rect2f(cv::Point2f(0.24485f, 0.21962f), cv::Point2f(0.4786f, 0.2581f));
const cv::Rect2f statistics_screen_params::pane_header_right = cv::Rect2f(cv::Point2f(0.6276f, 0.2238f), cv::Point2f(0.7946f, 0.2581f));
const cv::Rect2f statistics_screen_params::position_factory_icon = cv::Rect2f(0.0219f, 0.135f, 0.0838f, 0.7448f);
const cv::Rect2f statistics_screen_params::position_small_factory_icon = cv::Rect2f(cv::Point2f(0.072590f, 0.062498f), cv::Point2f(0.14436f, 0.97523f));
const cv::Rect2f statistics_screen_params::position_population_icon = cv::Rect2f(0.f, 0.05f, 0.f, 0.9f);
const cv::Rect2f statistics_screen_params::position_factory_output = cv::Rect2f(cv::Point2f(0.31963f, 0.58402f), cv::Point2f(0.49729f, 0.83325f));
////////////////////////////////////////
//
// Class: statistics_screen
//
////////////////////////////////////////
const std::string statistics_screen::KEY_AMOUNT = "amount";
const std::string statistics_screen::KEY_EXISTING_BUILDINGS = "existingBuildings";
const std::string statistics_screen::KEY_LIMIT = "limit";
const std::string statistics_screen::KEY_PRODUCTIVITY = "percentBoost";
statistics_screen::statistics_screen(image_recognition& recog)
:
recog(recog),
open_tab(tab::NONE),
center_pane_selection(0),
selected_session(0)
{
}
void statistics_screen::update(const std::string& language, const cv::Mat& img)
{
selected_island = std::string();
multiple_islands_selected = false;
selected_session = 0;
center_pane_selection = 0;
current_island_to_session.clear();
recog.update(language);
// test if open
cv::Mat cropped_image = recog.crop_widescreen(img);
cv::Mat statistics_text_img = recog.binarize(recog.get_pane(statistics_screen_params::pane_title, cropped_image), true);
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_text.png", statistics_text_img);
cv::imwrite("debug_images/statistics_screenshot.png", cropped_image);
}
if (recog.get_guid_from_name(statistics_text_img, recog.make_dictionary({ phrase::STATISTICS })).empty())
{
open_tab = tab::NONE;
if (recog.is_verbose()) {
std::cout << std::endl;
}
return;
}
if (recog.is_verbose()) {
std::cout << std::endl;
}
cropped_image.copyTo(this->screenshot);
open_tab = compute_open_tab();
if (open_tab == tab::NONE)
return;
bool update = true;
if (prev_islands.size().area() == recog.get_pane(statistics_screen_params::pane_islands, screenshot).size().area())
{
cv::Mat diff;
cv::absdiff(recog.get_pane(statistics_screen_params::pane_islands, screenshot), prev_islands, diff);
std::cout << ((float)cv::sum(diff).ddot(cv::Scalar::ones())) << std::endl;
float match = ((float)cv::sum(diff).ddot(cv::Scalar::ones())) / prev_islands.rows / prev_islands.cols;
update = match > 30;
}
if (update)
{ // island list changed
recog.get_pane(statistics_screen_params::pane_islands, screenshot).copyTo(prev_islands);
update_islands();
}
}
bool statistics_screen::is_open() const
{
return get_open_tab() != tab::NONE;
}
statistics_screen::tab statistics_screen::get_open_tab() const
{
return open_tab;
}
statistics_screen::tab statistics_screen::compute_open_tab() const
{
cv::Mat tabs = recog.get_pane(statistics_screen_params::pane_tabs, screenshot);
int tabs_count = (int)tab::ITEMS;
int tab_width = tabs.cols / tabs_count;
int v_center = tabs.rows / 2;
for (int i = 1; i <= (int)tabs_count; i++)
{
cv::Vec4b pixel = tabs.at<cv::Vec4b>(v_center, (int)(i * tab_width - 0.2f * tab_width));
if (is_tab_selected(pixel))
{
if (recog.is_verbose()) {
cv::imwrite("debug_images/tab.png", tabs(cv::Rect(static_cast<int>(i * tab_width - 0.2f * tab_width), v_center, 10, 10)));
}
if (recog.is_verbose()) {
std::cout << "Open tab:\t" << i << std::endl;
}
return tab(i);
}
}
return tab::NONE;
}
void statistics_screen::update_islands()
{
unsigned int session_guid = 0;
const auto phrases = recog.make_dictionary({
phrase::THE_OLD_WORLD,
phrase::THE_NEW_WORLD,
phrase::THE_ARCTIC,
phrase::CAPE_TRELAWNEY,
phrase::ENBESA });
recog.iterate_rows(prev_islands, 0.75f, [&](const cv::Mat& row) {
if (recog.is_verbose()) {
cv::imwrite("debug_images/row.png", row);
}
cv::Mat subheading = recog.binarize(recog.get_cell(row, 0.01f, 0.6f, 0.f), true);
if (recog.is_verbose()) {
cv::imwrite("debug_images/subheading.png", subheading);
}
std::vector<unsigned int> ids = recog.get_guid_from_name(subheading, phrases);
if (ids.size() == 1)
{
session_guid = ids.front();
return;
}
if (recog.is_verbose()) {
cv::imwrite("debug_images/selection_test.png", row(cv::Rect((int)(0.8f * row.cols), (int)(0.5f * row.rows), 10, 10)));
}
bool selected = is_selected(row.at<cv::Vec4b>((int)(0.5f * row.rows), (int)(0.8f * row.cols)));
cv::Mat island_name_image = recog.binarize(recog.get_cell(row, 0.15f, 0.65f), selected);
if (recog.is_verbose()) {
cv::imwrite("debug_images/island_name.png", island_name_image);
}
std::string island_name = recog.join(recog.detect_words(island_name_image), true);
if (island_name.empty())
return;
auto iter = island_to_session.find(island_name);
if (iter != island_to_session.end())
{
current_island_to_session.emplace(*iter);
return;
}
cv::Mat session_icon = recog.get_cell(row, 0.025f, 0.14f);
if (recog.is_verbose()) {
cv::imwrite("debug_images/session_icon.png", session_icon);
}
session_guid = recog.get_session_guid(session_icon);
if (session_guid) {
island_to_session.emplace(island_name, session_guid);
current_island_to_session.emplace(island_name, session_guid);
}
if (recog.is_verbose()) {
std::cout << "Island added:\t" << island_name;
try {
std::cout << " (" << recog.get_dictionary().ui_texts.at(session_guid) << ")";
}
catch (const std::exception&) {}
std::cout << std::endl;
}
});
}
bool statistics_screen::is_all_islands_selected() const
{
if (!screenshot.size || !is_open())
return false;
cv::Mat button = recog.get_pane(statistics_screen_params::pane_all_islands, screenshot);
if (button.empty())
return false;
return is_selected(button.at<cv::Vec4b>(static_cast<int>(0.1f * button.rows), static_cast<int>(0.5f * button.cols)));
}
std::pair<std::string, unsigned int> statistics_screen::get_island_from_list(std::string name) const
{
for (const auto& entry : island_to_session)
if (recog.lcs_length(entry.first, name) > 0.66f * std::max(entry.first.size(), name.size()))
return entry;
return std::make_pair(name, 0);
}
cv::Mat statistics_screen::get_center_pane() const
{
switch (get_open_tab())
{
case tab::FINANCE:
return recog.get_pane(statistics_screen_params::pane_finance_center, screenshot);
case tab::PRODUCTION:
return recog.get_pane(statistics_screen_params::pane_production_center, screenshot);
case tab::POPULATION:
return recog.get_pane(statistics_screen_params::pane_population_center, screenshot);
default:
return cv::Mat();
}
}
cv::Mat statistics_screen::get_left_pane() const
{
switch (get_open_tab())
{
case tab::NONE:
return cv::Mat();
default:
return recog.get_pane(statistics_screen_params::pane_islands, screenshot);
}
}
cv::Mat statistics_screen::get_right_pane() const
{
switch (get_open_tab())
{
case tab::FINANCE:
return recog.get_pane(statistics_screen_params::pane_finance_right, screenshot);
case tab::PRODUCTION:
return recog.get_pane(statistics_screen_params::pane_production_right, screenshot);
default:
return cv::Mat();
}
}
cv::Mat statistics_screen::get_center_header() const
{
switch (get_open_tab())
{
case tab::NONE:
return cv::Mat();
default:
return recog.get_pane(statistics_screen_params::pane_header_center, screenshot);
}
}
cv::Mat statistics_screen::get_right_header() const
{
switch (get_open_tab())
{
case tab::NONE:
return cv::Mat();
default:
return recog.get_pane(statistics_screen_params::pane_header_right, screenshot);
}
}
bool statistics_screen::is_selected(const cv::Vec4b& point)
{
return image_recognition::closer_to(point, statistics_screen_params::background_blue_dark, statistics_screen_params::background_brown_light);
}
bool statistics_screen::is_tab_selected(const cv::Vec4b& point)
{
return image_recognition::closer_to(point, cv::Scalar(234, 205, 149, 255), cv::Scalar(205, 169, 119, 255));
}
std::pair<unsigned int, int> statistics_screen::get_optimal_productivity()
{
const cv::Mat& im = screenshot;
if (get_open_tab() != statistics_screen::tab::PRODUCTION)
return std::make_pair(0, 0);
if (recog.is_verbose()) {
std::cout << "Optimal productivities" << std::endl;
}
cv::Mat buildings_text = recog.binarize(im(cv::Rect(static_cast<int>(0.6522f * im.cols), static_cast<int>(0.373f * im.rows), static_cast<int>(0.093f * im.cols), static_cast<int>(0.0245f * im.rows))));
if (recog.is_verbose()) {
cv::imwrite("debug_images/buildings_text.png", buildings_text);
}
int buildings_count = recog.number_from_region(buildings_text);
if (recog.is_verbose()) {
std::cout << std::endl;
}
if (buildings_count < 0)
return std::make_pair(0, 0);
cv::Mat roi = get_right_pane();
if (roi.empty())
return std::make_pair(0, 0);
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_scroll_area.png", roi);
}
cv::Mat factory_text = im(cv::Rect(static_cast<int>(0.6522f * im.cols), static_cast<int>(0.373f * im.rows), static_cast<int>(0.093f * im.cols), static_cast<int>(0.0245f * im.rows)));
if (recog.is_verbose()) {
cv::imwrite("debug_images/factory_text.png", factory_text);
}
std::vector<unsigned int> guids = recog.get_guid_from_name(factory_text, recog.get_dictionary().factories);
if (guids.size() != 1)
return std::make_pair(0, 0);
if (recog.is_verbose()) {
try {
std::cout << recog.get_dictionary().factories.at(guids.front()) << ":\t";
}
catch (...) {}
std::cout << std::endl;
}
std::vector<int> productivities;
recog.iterate_rows(roi, 0.8f, [&](const cv::Mat& row)
{
int productivity = 0;
for (const std::pair<float, float> cell : std::vector<std::pair<float, float>>({ {0.6f, 0.2f}, {0.8f, 0.2f} }))
{
cv::Mat productivity_text = recog.binarize(recog.get_cell(row, cell.first, cell.second));
if (recog.is_verbose()) {
cv::imwrite("debug_images/productivity_text.png", productivity_text);
}
int prod = recog.number_from_region(productivity_text);
if (prod > 1000) // sometimes '%' is detected as '0/0' or '00'
prod /= 100;
if (prod >= 0)
productivity += prod;
else
return;
}
if (recog.is_verbose()) {
std::cout << std::endl;
}
productivities.push_back(productivity);
});
if (productivities.empty())
return std::make_pair(0, 0);
int sum = std::accumulate(productivities.begin(), productivities.end(), 0);
if (recog.is_verbose()) {
std::cout << " = " << sum << std::endl;
}
if (productivities.size() != buildings_count)
{
std::sort(productivities.begin(), productivities.end());
sum += (buildings_count - productivities.size()) * productivities[productivities.size() / 2];
}
return std::make_pair(guids.front(), sum / buildings_count);
}
std::map<unsigned int, statistics_screen::properties> statistics_screen::get_factory_properties()
{
const cv::Mat& im = screenshot;
std::map<unsigned int, properties> result;
if (get_open_tab() != statistics_screen::tab::PRODUCTION)
return result;
cv::Mat roi = get_center_pane();
if (roi.empty())
return result;
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_scroll_area.png", roi);
}
if (recog.is_verbose()) {
std::cout << "Average productivities" << std::endl;
}
recog.iterate_rows(roi, 0.9f, [&](const cv::Mat& row)
{
properties props;
if (recog.is_verbose()) {
cv::imwrite("debug_images/row.png", row);
}
cv::Mat product_icon = recog.get_square_region(row, statistics_screen_params::position_factory_icon);
if (recog.is_verbose()) {
cv::imwrite("debug_images/factory_icon.png", product_icon);
}
cv::Scalar background_color = statistics_screen::is_selected(product_icon.at<cv::Vec4b>(0, 0)) ? statistics_screen_params::background_blue_dark : statistics_screen_params::background_brown_light;
std::vector<unsigned int> p_guids = recog.get_guid_from_icon(product_icon, recog.product_icons, background_color);
if (p_guids.empty())
return;
if (recog.is_verbose()) {
try {
std::cout << recog.get_dictionary().products.at(p_guids.front()) << ":\t";
}
catch (...) {}
}
bool selected = is_selected(row.at<cv::Vec4b>(0.1f * row.rows, 0.5f * row.cols));
cv::Mat productivity_text = recog.binarize(recog.get_cell(row, 0.7f, 0.1f, 0.4f), selected);
if (recog.is_verbose()) {
cv::imwrite("debug_images/productivity_text.png", productivity_text);
}
int prod = recog.number_from_region(productivity_text);
if (prod > 500 && prod % 100 == 0)
prod /= 100;
if (prod >= 0)
props.emplace(KEY_PRODUCTIVITY, prod);
cv::Mat text_img = recog.binarize(recog.get_pane(statistics_screen_params::position_factory_output, row), true, true, 200);
if (recog.is_verbose()) {
cv::imwrite("debug_images/factory_output_text.png", text_img);
}
auto pair = recog.read_number_slash_number(text_img);
if (pair.first >= 0)
props.emplace(KEY_AMOUNT, pair.first);
if (pair.second >= 0 && pair.second >= pair.first)
props.emplace(KEY_LIMIT, pair.second);
if (prod >= 0)
{
for (unsigned int p_guid : p_guids)
for (unsigned int f_guid : recog.product_to_factories[p_guid])
result.emplace(f_guid, props);
}
if (recog.is_verbose()) {
std::cout << std::endl;
}
});
return result;
}
std::map<unsigned int, int> statistics_screen::get_assets_existing_buildings_from_finance_screen()
{
std::map<unsigned int, int> result;
if (get_open_tab() != statistics_screen::tab::FINANCE)
return result;
cv::Mat roi = get_center_pane();
if (roi.empty())
return result;
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_scroll_area.png", roi);
}
std::map<unsigned int, std::string> category_dict = recog.make_dictionary({ phrase::RESIDENTS, phrase::PRODUCTION, phrase::SKYSCRAPERS, phrase::FOOD_AND_DRINK_VENUES, phrase::MALLS });
cv::Mat text = recog.binarize(get_right_header());
std::vector<unsigned int> selection = recog.get_guid_from_name(text, category_dict);
if (recog.is_verbose()) {
try {
std::cout << recog.get_dictionary().ui_texts.at(center_pane_selection) << std::endl;
}
catch (...) {}
}
if (selection.size() != 1)
return result; // nothing selected that we want to evaluate
center_pane_selection = selection.front();
const std::map<unsigned int, std::string>* dictionary = nullptr;
switch ((phrase)center_pane_selection)
{
case phrase::RESIDENTS:
dictionary = &recog.get_dictionary().population_levels;
break;
case phrase::PRODUCTION:
dictionary = &recog.get_dictionary().factories;
break;
case phrase::SKYSCRAPERS:
dictionary = &recog.get_dictionary().skyscrapers;
break;
case phrase::FOOD_AND_DRINK_VENUES:
dictionary = &recog.get_dictionary().food_and_drink_venues;
break;
case phrase::MALLS:
dictionary = &recog.get_dictionary().malls;
break;
}
roi = get_right_pane();
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_table_area.png", roi);
}
std::vector<unsigned int> prev_guids;
int prev_count = 0;
recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row)
{
if (recog.is_verbose()) {
cv::imwrite("debug_images/row.png", row);
cv::imwrite("debug_images/selection_test.png", row(cv::Rect((int)(0.037f * row.cols), (int)(0.5f * row.rows), 10, 10)));
}
bool is_summary_entry = image_recognition::closer_to(row.at<cv::Vec4b>(0.5f * row.rows, 0.037f * row.cols), statistics_screen_params::expansion_arrow, statistics_screen_params::background_brown_light);
if (is_summary_entry)
{
prev_guids.clear();
cv::Mat text = recog.binarize(recog.get_cell(row, 0.15f, 0.5f));
std::vector<unsigned int> guids = recog.get_guid_from_name(text, *dictionary);
if (recog.is_verbose()) {
try {
for (unsigned int guid : guids)
std::cout << dictionary->at(guid) << ", ";
std::cout << "\t";
}
catch (...) {}
}
cv::Mat count_text = recog.binarize(recog.get_cell(row, 0.15f, 0.6f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/count_text.png", count_text);
}
std::vector<std::pair<std::string, cv::Rect>> words = recog.detect_words(count_text, tesseract::PSM_SINGLE_LINE);
std::string number_string;
bool found_opening_bracket = false;
for (const auto& word : words)
{
if (found_opening_bracket)
number_string += word.first;
else
{
std::vector<std::string> split_string;
boost::split(split_string, word.first, [](char c) {return c == '('; });
if (split_string.size() > 1)
{
found_opening_bracket = true;
number_string += split_string.back();
}
}
}
number_string = std::regex_replace(number_string, std::regex("\\D"), "");
if (recog.is_verbose()) {
std::cout << number_string;
}
int count = std::numeric_limits<int>::lowest();
try { count = std::stoi(number_string); }
catch (...) {
if (recog.is_verbose()) {
std::cout << " (could not recognize number)";
}
}
if (count >= 0)
{
if (guids.size() != 1 && get_selected_session() && !is_all_islands_selected())
recog.filter_factories(guids, get_selected_session());
if (guids.size() != 1) {
cv::Mat product_icon = recog.get_square_region(row, statistics_screen_params::position_small_factory_icon);
if (recog.is_verbose()) {
cv::imwrite("debug_images/factory_icon.png", product_icon);
}
cv::Scalar background_color = statistics_screen_params::background_brown_light;
std::map<unsigned int, cv::Mat> icon_candidates;
for (unsigned int guid : guids)
{
auto iter = recog.factory_icons.find(guid);
if (iter != recog.factory_icons.end())
icon_candidates.insert(*iter);
}
guids = recog.get_guid_from_icon(product_icon, icon_candidates, background_color);
}
if (guids.size() == 1)
result.emplace(guids.front(), count);
else
{
prev_guids = guids;
prev_count = count;
}
}
}
else if (!prev_guids.empty()) // no summary entry, test whether upper row is expanded
{
cv::Mat session_icon = recog.get_cell(row, 0.08f, 0.08f);
if (recog.is_verbose()) {
cv::imwrite("debug_images/session_icon.png", session_icon);
}
unsigned int session_guid = recog.get_session_guid(session_icon);
if (!session_guid)
{
// prev_guids.clear();
return;
}
recog.filter_factories(prev_guids, session_guid);
if (prev_guids.size() == 1)
result.emplace(prev_guids.front(), prev_count);
prev_guids.clear();
}
if (recog.is_verbose()) {
std::cout << std::endl;
}
});
return result;
}
std::map<unsigned int, statistics_screen::properties> statistics_screen::get_population_properties() const
{
const cv::Mat& im = screenshot;
std::map<unsigned int, properties> result;
if (get_open_tab() != statistics_screen::tab::POPULATION)
return result;
cv::Mat roi = get_center_pane();
if (roi.empty())
return result;
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_scroll_area.png", roi);
}
recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row)
{
properties props;
cv::Mat population_name = recog.binarize(recog.get_cell(row, 0.076f, 0.2f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/population_name.png", population_name);
}
std::vector<unsigned int> guids = recog.get_guid_from_name(population_name, recog.get_dictionary().population_levels);
if (guids.size() != 1)
return;
// read amount and limit
cv::Mat text_img = recog.binarize(recog.get_cell(row, 0.5f, 0.27f, 0.4f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/pop_amount_text.png", text_img);
}
if (recog.is_verbose()) {
try {
std::cout << recog.get_dictionary().population_levels.at(guids.front()) << "\t";
}
catch (...) {}
}
auto pair = recog.read_number_slash_number(text_img);
if (pair.first >= 0)
props.emplace(KEY_AMOUNT, pair.first);
if (pair.second >= 0 && pair.second >= pair.first)
props.emplace(KEY_LIMIT, pair.second);
// read existing buildings
text_img = recog.binarize(recog.get_cell(row, 0.3f, 0.15f, 0.4f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/pop_houses_text.png", text_img);
}
int houses = recog.number_from_region(text_img);
if (houses >= 0)
props.emplace(KEY_EXISTING_BUILDINGS, houses);
if (recog.is_verbose()) {
std::cout << std::endl;
}
if (!props.empty())
result.emplace(guids.front(), props);
});
if (result.size() < 6)
for (const auto& entry : recog.get_dictionary().population_levels)
{
if (result.find(entry.first) == result.end())
result.emplace(entry.first,
std::map<std::string, int>({
{KEY_AMOUNT, 0},
{KEY_EXISTING_BUILDINGS, 0},
{KEY_LIMIT, 0}
}));
}
return result;
}
std::map<std::string, unsigned int> statistics_screen::get_islands() const
{
return island_to_session;
}
std::map<std::string, unsigned int> statistics_screen::get_current_islands() const
{
return current_island_to_session;
}
std::string statistics_screen::get_selected_island()
{
if (!selected_island.empty() || multiple_islands_selected)
return selected_island;
if (is_all_islands_selected())
{
if (recog.is_verbose()) {
std::cout << recog.ALL_ISLANDS << std::endl;
}
selected_session = recog.SESSION_META;
selected_island = recog.ALL_ISLANDS;
return selected_island;
}
std::string result;
cv::Mat roi = recog.binarize(get_center_header());
if (roi.empty())
return result;
if (recog.is_verbose()) {
cv::imwrite("debug_images/header.png", roi);
}
auto words_and_boxes = recog.detect_words(roi, tesseract::PSM_SINGLE_LINE);
// check whether mutliple islands are selected
std::string joined_string = recog.join(words_and_boxes);
std::vector<std::string> split_string;
boost::split(split_string, joined_string, [](char c) {return c == '/' || c == '[' || c == '(' || c == '{'; });
if (!recog.get_guid_from_name(split_string.front(), recog.make_dictionary({ phrase::MULTIPLE_ISLANDS })).empty())
{
if (recog.is_verbose()) {
std::cout << recog.get_dictionary().ui_texts.at((unsigned int)phrase::MULTIPLE_ISLANDS) << std::endl;
}
multiple_islands_selected = true;
return selected_island;
}
int max_dist = 0;
int last_index = 0;
// detect split between island and session
for (int i = 0; i < words_and_boxes.size() - 1; i++) {
int dist = words_and_boxes[i + 1].second.x -
(words_and_boxes[i].second.x + words_and_boxes[i].second.width);
if (dist > max_dist)
{
max_dist = dist;
last_index = i;
}
}
std::string island;
std::string session;
for (int i = 0; i < words_and_boxes.size(); i++)
{
if (i <= last_index)
island += words_and_boxes[i].first + " ";
else
session += words_and_boxes[i].first;
}
island.pop_back();
selected_island = island;
auto session_result = recog.get_guid_from_name(session, recog.make_dictionary({
phrase::THE_ARCTIC,
phrase::THE_OLD_WORLD,
phrase::THE_NEW_WORLD,
phrase::CAPE_TRELAWNEY,
phrase::ENBESA
}));
if (session_result.size())
{
selected_session = session_result[0];
island_to_session.emplace(selected_island, selected_session);
current_island_to_session.emplace(selected_island, selected_session);
}
if (recog.is_verbose()) {
std::cout << result << std::endl;
}
return selected_island;
}
unsigned int statistics_screen::get_selected_session()
{
get_selected_island(); // update island information
return selected_session;
}
std::map<unsigned int, int> statistics_screen::get_population_workforce() const
{
const cv::Mat& im = screenshot;
std::map<unsigned int, int> result;
if (get_open_tab() != statistics_screen::tab::POPULATION)
return result;
cv::Mat roi = get_center_pane();
if (roi.empty())
return result;
if (recog.is_verbose()) {
cv::imwrite("debug_images/statistics_window_scroll_area.png", roi);
}
recog.iterate_rows(roi, 0.75f, [&](const cv::Mat& row)
{
cv::Mat population_name = recog.binarize(recog.get_cell(row, 0.076f, 0.2f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/population_name.png", population_name);
}
std::vector<unsigned int> guids = recog.get_guid_from_name(population_name, recog.get_dictionary().population_levels);
if (guids.size() != 1)
return;
cv::Mat text_img = recog.binarize(recog.get_cell(row, 0.8f, 0.1f));
if (recog.is_verbose()) {
cv::imwrite("debug_images/pop_houses_text.png", text_img);
}
int workforce = recog.number_from_region(text_img);
if (workforce >= 0)
result.emplace(guids.front(), workforce);
});
for (const auto& entry : recog.get_dictionary().population_levels)
{
if (result.find(entry.first) == result.end())
result[entry.first] = 0;
}
return result;
}
}
| 28.974657 | 204 | 0.688691 | NiHoel |
8e8c428082f3f640b1a82eaa4eea3a014391e900 | 1,796 | cpp | C++ | SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Xenomorph_Character_BP_Male_Tamed_Gen2_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.UserConstructionScript
// ()
void AXenomorph_Character_BP_Male_Tamed_Gen2_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.UserConstructionScript");
AXenomorph_Character_BP_Male_Tamed_Gen2_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void AXenomorph_Character_BP_Male_Tamed_Gen2_C::ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Xenomorph_Character_BP_Male_Tamed_Gen2.Xenomorph_Character_BP_Male_Tamed_Gen2_C.ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2");
AXenomorph_Character_BP_Male_Tamed_Gen2_C_ExecuteUbergraph_Xenomorph_Character_BP_Male_Tamed_Gen2_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 31.508772 | 197 | 0.754454 | 2bite |
8e907c11dd1da0d4fb7850fd02019af2a6e95d0b | 2,948 | cpp | C++ | test/source/local_shared_ptr_test.cpp | anders-wind/shared_ptr | ec5db7bf9a9516149b41dbf7e131c24536a393ae | [
"MIT"
] | null | null | null | test/source/local_shared_ptr_test.cpp | anders-wind/shared_ptr | ec5db7bf9a9516149b41dbf7e131c24536a393ae | [
"MIT"
] | 1 | 2022-01-04T23:55:10.000Z | 2022-01-04T23:55:10.000Z | test/source/local_shared_ptr_test.cpp | anders-wind/shared_ptr | ec5db7bf9a9516149b41dbf7e131c24536a393ae | [
"MIT"
] | null | null | null | #include <functional>
#include <doctest/doctest.h>
#include <shared_ptr/local_shared_ptr.hpp>
TEST_SUITE("local::shared_ptr") // NOLINT
{
TEST_CASE("local::shared_ptr: make_shared works") // NOLINT
{
auto my_shared = wind::local::make_shared<int>(42);
CHECK(*my_shared == 42);
CHECK(my_shared.use_count() == 1);
}
TEST_CASE("local::shared_ptr: copy operator= works") // NOLINT
{
auto my_shared = wind::local::make_shared<int>(42);
auto copy = my_shared;
CHECK((*copy) == (*my_shared));
CHECK(my_shared.use_count() == 2);
CHECK(copy.use_count() == 2);
}
TEST_CASE("local::shared_ptr: move operator= works") // NOLINT
{
auto my_shared = wind::local::make_shared<int>(42);
auto moved = std::move(my_shared);
CHECK(moved.use_count() == 1);
}
TEST_CASE("local::shared_ptr: Destructor does not delete when copy exists") // NOLINT
{
wind::local::shared_ptr<int> out_copy;
{
auto my_shared = wind::local::make_shared<int>(42);
out_copy = my_shared;
CHECK(out_copy.use_count() == 2);
}
CHECK(out_copy.use_count() == 1);
CHECK(*out_copy == 42);
}
struct deleter_func_2 // NOLINT
{
std::function<void()> delete_func;
explicit deleter_func_2(std::function<void()> func)
: delete_func(std::move(func))
{
}
~deleter_func_2()
{
this->delete_func();
}
};
TEST_CASE("local::shared_ptr: Delete gets called") // NOLINT
{
bool was_called = false;
{
auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; });
CHECK(!was_called);
}
CHECK(was_called);
}
TEST_CASE("local::shared_ptr: Delete gets called when supplying pointer") // NOLINT
{
bool was_called = false;
{
auto ptr =
wind::local::shared_ptr<deleter_func_2>(new deleter_func_2([&was_called]() { was_called = true; }));
CHECK(!was_called);
}
CHECK(was_called);
}
TEST_CASE("local::shared_ptr: Delete gets called when 2 copies") // NOLINT
{
bool was_called = false;
{
auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; });
auto copy = ptr; // NOLINT
CHECK(!was_called);
}
CHECK(was_called);
}
TEST_CASE("local::shared_ptr: Delete only gets called on last destructor") // NOLINT
{
bool was_called = false;
{
auto ptr = wind::local::make_shared<deleter_func_2>([&was_called]() { was_called = true; });
{
auto copy = ptr; // NOLINT
}
CHECK(!was_called);
}
CHECK(was_called);
}
} | 29.48 | 116 | 0.549864 | anders-wind |
8e90ad8a313ebb808860eb60c64b8a9db67a56c0 | 3,180 | cpp | C++ | src/scenes/SFPC/cantusFirmusRiley/cantusFirmusRiley.cpp | roymacdonald/ReCoded | 3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1 | [
"MIT"
] | 64 | 2017-06-12T19:24:08.000Z | 2022-01-27T19:14:48.000Z | src/scenes/cantusFirmusRiley/cantusFirmusRiley.cpp | colaplate/recoded | 934e1184c7502d192435c406e56b8a2106e9b6b4 | [
"MIT"
] | 10 | 2017-06-13T10:38:39.000Z | 2017-11-15T11:21:05.000Z | src/scenes/cantusFirmusRiley/cantusFirmusRiley.cpp | colaplate/recoded | 934e1184c7502d192435c406e56b8a2106e9b6b4 | [
"MIT"
] | 24 | 2017-06-11T08:14:46.000Z | 2020-04-16T20:28:46.000Z | #include "cantusFirmusRiley.h"
void cantusFirmusRiley::setup(){
ofBackground(255);
size = 5000;
y.c.setHex(0xA79C26);
y.width = 9;
p.c.setHex(0xC781A8);
p.width = 9;
b.c.setHex(0x64A2C9);
b.width = 11;
k.c.setHex(0x222B32);
k.width = 39;
w.c.setHex(0xE3E2DE);
w.width = 29;
g.c.set(127);
g.width = 29;
r.c.set(255,0,0);
r.width = 10;
int counter = 0;
for (int i = 0; i <= size; i++){
if(i == size/2) stripes.push_back(w);
else if(abs(i-size/2)% 8 == 1) stripes.push_back(y);
else if(abs(i-size/2)% 8 == 2) stripes.push_back(p);
else if(abs(i-size/2)% 8 == 3) stripes.push_back(b);
else if(abs(i-size/2)% 8 == 5) stripes.push_back(b);
else if(abs(i-size/2)% 8 == 6) stripes.push_back(p);
else if(abs(i-size/2)% 8 == 7) stripes.push_back(y);
else if(abs(i-size/2)%12 == 0) stripes.push_back(w);
else if(abs(i-size/2)%12 == 8) stripes.push_back(k);
else if(abs(i-size/2)%12 == 4) {
int rand = ofRandom(120,180);
g.c.set(rand);
// cout << rand << endl;
stripes.push_back(g);
}
else stripes.push_back(r);
}
parameters.add(posNoiseSpeed.set("offsetX", 0, -300, 300));
parameters.add(zoomNoiseSpeed.set("zoom", 0.2, 0.05, 1));
//parameters.add(range.set("scale", 0.3, 0.02, 1.0));
setAuthor("Reed Tothong");
setOriginalArtist("Bridget Riley");
loadCode("scenes/cantusFirmusRiley/cantusFirmusRiley.cpp");
}
void cantusFirmusRiley::update(){
}
void cantusFirmusRiley::draw(){
ofFill();
ofSetRectMode(OF_RECTMODE_CORNER);
// posNoise = ofNoise(getElapsedTimef()*posNoiseSpeed);
//
// float posX = ofMap(posNoise, 0, 1.0, 0, ofGetWidth()/2);
ofTranslate(posNoiseSpeed, 0);
// zoomNoise = ofNoise(getElapsedTimef()*zoomNoiseSpeed);
// // cinematic = 0.1 // motion sickness = 10
//
//// float rangeNoise = ofNoise(getElapsedTimef()*rangeNoiseSpeed);
// float microScale = ofMap(range, 0, 0.5, 0.015, 1.0, true);
// float macroScale = ofMap(range, 0.5, 1.0, 1.0, 2.5,true);
//
// float maxZoomOut = range < 0.5 ? microScale : macroScale;
// // zoom range control
// float zoom = ofMap(zoomNoise, 0.0, 1.0, .0001, maxZoomOut, true);
ofScale(zoomNoiseSpeed, 1);
//midline
stripes[size/2].x = -stripes[size/2].width/2;
ofSetColor(stripes[size/2].c);
ofDrawRectangle(stripes[size/2].x, 0, stripes[size/2].width, dimensions.width*2);
//loop to the left
for (int i = (size/2)-1; i> 0; i--){
ofSetColor(stripes[i].c);
stripes[i].x = stripes[i+1].x - stripes[i].width;
ofDrawRectangle(stripes[i].x, 0, stripes[i].width, dimensions.height*2);
}
//loop to the right
for (int i = (size/2)+1; i< stripes.size();i++) {
ofSetColor(stripes[i].c);
stripes[i].x = stripes[i-1].x + stripes[i-1].width;
ofDrawRectangle(stripes[i].x, 0, stripes[i].width, dimensions.height*2);
}
}
| 28.909091 | 85 | 0.56195 | roymacdonald |
8e96a905341164dea3c171b14db932528377fc12 | 20,491 | cpp | C++ | math/src/matrix.cpp | blobrobots/libs | cc11f56bc4e1112033e8b7352e5653f98f1bfc13 | [
"MIT"
] | 1 | 2015-10-21T14:36:43.000Z | 2015-10-21T14:36:43.000Z | math/src/matrix.cpp | blobrobots/libs | cc11f56bc4e1112033e8b7352e5653f98f1bfc13 | [
"MIT"
] | null | null | null | math/src/matrix.cpp | blobrobots/libs | cc11f56bc4e1112033e8b7352e5653f98f1bfc13 | [
"MIT"
] | null | null | null | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Blob Robotics
*
* 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.
*
* \file matrix.h
* \brief implementation of matrix object and operations
* \author adrian jimenez-gonzalez ([email protected])
* \copyright the MIT License Copyright (c) 2017 Blob Robots.
*
******************************************************************************/
#include "blob/matrix.h"
#include "blob/math.h"
#if defined(__linux__)
#include <iostream>
#endif
blob::MatrixR::MatrixR (uint8_t rows, uint8_t cols, real_t *data) :
Matrix<real_t>(rows,cols,data) {};
bool blob::MatrixR::cholesky (bool zero)
{
bool retval = true;
if(_nrows == _ncols)
{
real_t t;
uint8_t n = _nrows;
int i=0,j=0,k=0;
for(i=0 ; i<n && retval == true; i++)
{
if(i > 0)
{
for(j=i; j<n; j++)
{
t = 0;
for(k=0; k<i; k++)
t += _data[j*n + k]*_data[i*n + k];
_data[j*n+i] -= t;
}
}
if(_data[i*n + i] <= 0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholesky() error: Matrix is not positive definite"
<< std::endl;
#endif
retval = false;
}
else
{
t = 1/blob::math::sqrtr(_data[i*n + i]);
for(j = i ; j < n ; j++)
_data[j*n + i] *= t;
}
}
if(zero)
{
for(int i=n-1; i>0; i--)
{
for(int j=i-1; j>=0; j--)
{
_data[j*n+i]=0;
}
}
}
}
else
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholesky() error: Matrix is not square" << std::endl;
#endif
retval = false;
}
return retval;
}
bool blob::MatrixR::cholupdate (MatrixR & v, int sign)
{
bool retval = false;
uint8_t n = _nrows;
if(_nrows != _ncols)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholupdate() error: Matrix is not square"<< std::endl;
#endif
return false;
}
if((v.length() != n)||((v.nrows() != 1)&&(v.ncols() != 1)))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholupdate() error: vector not 1x" << (int)n
<< std::endl;
#endif
return false;
}
if((sign != -1)&&(sign != 1))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::cholupdate() error: sign not unitary s=" << sign
<< std::endl;
#endif
return false;
}
for (int i=0; i<n; i++)
{
real_t sr = _data[i*n+i]*_data[i*n+i] + (real_t)sign*v[i]*v[i];
if(_data[i*n+i] == 0.0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholupdate() error: Matrix with zero diagonal "
<< "element " << i << std::endl;
#endif
return false;
}
if(sr < 0.0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::cholupdate() error: Result is not positive definite"
<< " sqrt(neg)" << std::endl;
#endif
return false;
}
real_t r = blob::math::sqrtr(_data[i*n+i]*_data[i*n+i] +
(real_t)sign*v[i]*v[i]);
real_t c = r/_data[i*n+i];
real_t s = v[i]/_data[i*n+i];
_data[i*n+i] = r;
if(c == 0.0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholupdate() error: Result is not positive definite"
<< std::endl;
#endif
return false;
}
for(int j=i+1; j<n; j++)
{
_data[j*n+i] = (_data[j*n+i] + sign*s*v[j])/c;
v[j] = c*v[j] - s*_data[j*n+i];
}
}
return true;
}
bool blob::MatrixR::cholrestore (bool zero)
{
bool retval = false;
if(_nrows == _ncols)
{
if(zero == false) // original matrix stored in upper triangle
{
uint8_t n = _nrows;
for(int i=0; i<n; i++)
{
real_t t = 0.0;
for(int j=0; j<i+1; j++)
{
t += _data[i*n+j]*_data[i*n+j];
// assumes original matrix stored in upper triangle
_data[i*n+j] = (i==j)? t:_data[j*n+i];
}
}
retval = true;
}
else
{ // TODO
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholrestore() error: not implemented for zero=true"
<< std::endl;
#endif
}
}
#if defined(__DEBUG__) & defined(__linux__)
else
std::cerr << "MatrixR::cholinverse() error: Matrix is not square"
<< std::endl;
#endif
return retval;
}
bool blob::MatrixR::cholinverse ()
{
bool retval = false;
if(_nrows == _ncols)
{
uint8_t n = _nrows;
for(int i=0; i<n; i++)
{
_data[i*n + i] = 1/_data[i*n + i];
for(int j=i+1; j<n; j++)
{
real_t t = 0.0;
for(int k=i; k<j; k++)
t -= _data[j*n + k]*_data[k*n + i];
_data[j*n + i] = t/_data[j*n + j];
}
}
retval = true;
}
#if defined(__DEBUG__) & defined(__linux__)
else
std::cerr <<"MatrixR::cholinverse() error: Matrix is not square"<< std::endl;
#endif
return retval;
}
bool blob::MatrixR::lu()
{
if(_nrows!=_ncols)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::lu() error: Matrix is not square" << std::endl;
#endif
return false;
}
for(int k=0; k<_ncols-1; k++)
{
for(int j=k+1; j<_ncols; j++)
{
_data[j*_ncols+k]=_data[j*_ncols+k]/_data[k*_ncols+k];
for(int l=k+1;l<_ncols;l++)
_data[j*_ncols+l]=_data[j*_ncols+l]-_data[j*_ncols+k]*_data[k*_ncols+l];
}
}
return true;
}
bool blob::MatrixR::lurestore()
{
if(_nrows!=_ncols)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::lurestore() error: Matrix is not square" << std::endl;
#endif
return false;
}
for(int i=_nrows-1; i>0; i--)
{
for(int j=_ncols-1; j>=0; j--)
{
if(i>j)
_data[i*_ncols+j]*=_data[j*_ncols+j];
for(int k=0;k<i&&k<j;k++)
_data[i*_ncols+j]+=_data[i*_ncols+k]*_data[k*_ncols+j];
#if defined(__DEBUG__) & defined(__linux__)
print();
std::cout << std::endl;
std::cout << i << "," << j << std::endl;
std::cout << std::endl;
#endif
}
}
return true;
}
bool blob::MatrixR::inverse (bool isPositiveDefinite)
{
bool retval = false;
if((isPositiveDefinite == true) && (cholesky(false) == true) &&
(cholinverse() == true))
{
// reconstruct inverse of A: inv(A) = inv(L)'*inv(L)
uint8_t n = _nrows;
for(int i=0; i<n; i++)
{
int ii = n-i-1;
for(int j=0; j<=i; j++)
{
int jj = n-j-1;
real_t t = 0.0;
for(int k=0; k<=ii; k++)
{
int kk = n-k-1;
t += _data[kk*n + i]*_data[kk*n + j];
}
_data[i*n + j] = t;
}
}
//de-triangularization
for(int i=n-1; i>0; i--)
{
for(int j=i-1; j>=0; j--)
{
_data[j*n+i] = _data[i*n+j];
}
}
retval = true;
}
else // lu decomposition inverse
{
real_t r[this->length()]; //real_t r[MATRIX_MAX_LENGTH];
MatrixR LU(this->nrows(),this->ncols(),r);
if( blob::MatrixR::lu(*this,LU)==true )
{
this->zero();
real_t y[this->nrows()]; //real_t y[MATRIX_MAX_ROWCOL];
memset(y,0,sizeof(real_t)*this->nrows()); //memset(y,0,sizeof(real_t)*MATRIX_MAX_ROWCOL);
uint8_t n = _nrows;
for(int c=0;c<n;c++)
{
for(int i=0;i<n;i++)
{
real_t x=0;
for(int j=0;j<=i-1;j++)
{
x += LU(i,j)*y[j];
}
y[i] = (i==c)? (1-x):(-x);
}
for(int i=n-1;i>=0;i--)
{
real_t x=0;
for(int j=i+1;j<n;j++)
{
x += LU(i,j)*_data[j*_ncols+c];
}
_data[i*_ncols+c] = (y[i]-x)/LU(i,i);
}
}
}
}
return retval;
}
bool blob::MatrixR::forcePositive ()
{
bool retval = false;
if(_nrows == _ncols)
{
real_t min = blob::math::rabs(_data[0]);
real_t max = min;
for (int i = 0; i<_nrows; i++)
{
real_t mm = blob::math::rabs(_data[i*_ncols + i]);
if (mm < min) min = mm;
if (mm > max) max = mm;
}
real_t epsilon = min/max;
if(epsilon < 1.0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cout << "MatrixR::forcePositive() epsilon=" << epsilon << std::endl;
#endif
for (int i = 0; i<_nrows; i++)
_data[i*_ncols + i] += epsilon;
}
retval = true;
}
#if defined(__DEBUG__) & defined(__linux__)
else
std::cerr << "MatrixR::forcePositive() error: Matrix is not square"
<< std::endl;
#endif
return retval;
}
bool blob::MatrixR::simmetrize ()
{
bool retval = false;
if(_nrows == _ncols)
{
for (int i = 0; i<_nrows; i++)
{
for (int j = 0; j<i; j++)
{
real_t t = (_data[i*_ncols + j]+_data[j*_ncols + i])/2;
_data[i*_ncols + j] = _data[j*_ncols + i] = t;
}
}
retval = true;
}
#if defined(__DEBUG__) & defined(__linux__)
else
std::cerr<< "MatrixR::simmetrize() error: Matrix is not square" << std::endl;
#endif
return retval;
}
bool blob::MatrixR::divide (const blob::MatrixR & A, blob::MatrixR & B,
blob::MatrixR & R)
{
bool retval = false;
uint8_t n = B.nrows();
uint8_t m = A.nrows();
if((R.nrows() == m)&&
(R.ncols() == n)&&
B.cholesky(false) == true)
{
for(int c = 0; c<m; c++)
{
// forward solve Ly = I(c)
for(int i = 0; i<n; i++)
{
R(c,i) = A(c,i);
for(int j=0; j<i; j++)
R(c,i) -= B(i,j)*R(c,j);
R(c,i) /= B(i,i);
}
// backward solve L'x = y
for(int i=n-1; i>=0; i--)
{
for (int j=i+1; j<n; j++)
R(c,i) -= B(j,i)*R(c,j);
R(c,i) /= B(i,i);
}
}
// restore A from L
B.cholrestore(false);
retval = true;
}
return retval;
}
bool blob::MatrixR::cholesky (const blob::MatrixR & A, blob::MatrixR & L)
{
bool retval = true;
real_t t;
uint8_t n = A.nrows();
L.zero();
if((A.nrows() == A.ncols()) &&
(A.nrows() == L.nrows()) &&
(A.ncols() == L.ncols()))
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < (i+1); j++)
{
real_t s = 0;
for (int k = 0; k < j; k++)
{
s += L[i*n + k]*L[j*n + k];
}
if(i==j && (A[i*n + i] - s) <=0)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholesky() error: Matrix is not positive"
<< " definite" << std::endl;
#endif
return false;
}
else
{
L[i*n + j] = (i == j)?
blob::math::sqrtr(A[i*n + i] - s) : (1/L[j*n + j]*(A[i*n + j] - s));
}
}
}
}
else
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "MatrixR::cholesky() error: Matrix is not square" << std::endl;
#endif
retval = false;
}
return retval;
}
// TODO: optimize
bool blob::MatrixR::inverse (blob::MatrixR & A, blob::MatrixR & R,
bool isPositiveDefinite)
{
bool retval = false;
if((R.nrows() == R.ncols())&&
(R.nrows() == A.nrows())&&
(R.ncols() == R.ncols()))
{
if(isPositiveDefinite == true && A.cholesky(false) == true) // A=L
{
uint8_t n = R.nrows();
for(int c = 0; c<n; c++)
{
// forward solve Ly = I(c)
for(int i = 0; i<n; i++)
{
R(c,i) = (c==i)? 1:0;
for(int j=0; j<i; j++)
R(c,i) -= A(i,j)*R(c,j);
R(c,i) /= A(i,i);
}
// backward solve L'x = y
for(int i=n-1; i>=0; i--)
{
for (int j=i+1; j<n; j++)
R(c,i) -= A(j,i)*R(c,j);
R(c,i) /= A(i,i);
}
}
// restore A from L
A.cholrestore(false);
retval = true;
}
else if (A.lu()==true)
{
real_t y[A.nrows()]; //real_t y[MATRIX_MAX_ROWCOL];
memset(y,0,sizeof(real_t)*A.nrows()); //memset(y,0,sizeof(real_t)*MATRIX_MAX_ROWCOL);
R.zero();
uint8_t n = R.nrows();
for(int c=0;c<n;c++)
{
for(int i=0;i<n;i++)
{
real_t x=0;
for(int j=0;j<=i-1;j++)
{
x+=A(i,j)*y[j];
}
y[i] = (i==c)? (1-x):(-x);
}
for(int i=n-1;i>=0;i--)
{
real_t x=0;
for(int j=i+1;j<n;j++)
{
x+=A(i,j)*R(j,c);
}
R(i,c)=(y[i]-x)/A(i,i);
}
}
A.lurestore();
}
}
return retval;
}
bool blob::MatrixR::cholinverse (const blob::MatrixR & L, blob::MatrixR & R)
{
bool retval = false;
if((L.nrows() == L.ncols())&&
(R.nrows() == L.nrows())&&
(R.ncols() == L.ncols()))
{
uint8_t n = L.nrows();
R.zero();
for(int i=0; i<n; i++)
{
R[i*n + i] = 1/L[i*n + i];
for(int j=i+1; j<n; j++)
{
real_t t = 0.0;
for(int k=i; k<j; k++)
t -= L[j*n + k]*L[k*n + i];
R[j*n + i] = t/L[j*n + j];
}
}
retval = true;
}
#if defined(__DEBUG__) & defined(__linux__)
else
std::cerr << "Matrix::cholinverse() error: " << (int)L.nrows() << "=="
<< (int)L.ncols() << "?"
<< (int)R.nrows() << "=="
<< (int)L.nrows() << "?"
<< (int)R.ncols() << "=="
<< (int)L.ncols() << "?"
<< std::endl;
#endif
return retval;
}
bool blob::MatrixR::ldl (const blob::MatrixR & A, blob::MatrixR & L,
blob::MatrixR & d)
{
if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(A.ncols()!=L.nrows()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::ldl() error: Matrix is not square" << std::endl;
#endif
return false;
}
if(((d.nrows() != 1)&&(d.ncols() != 1))||(d.length() != A.ncols()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::ldl() error: Matrix is not square" << std::endl;
#endif
return false;
}
uint8_t n = A.nrows();
int i,j,k;
L.zero();
for(j=0; j<n; j++)
{
L(j,j) = 1.0;
real_t t = A(j,j);
for(k=1; k<j; k++)
t -= d[k]*L(j,k)*L(j,k);
d[j] = t;
for(i=j+1; i<n; i++)
{
L(j,i) = 0.0;
t = A(i,j);
for (k=1; k<j;k++)
t -= d[k]*L(i,k)*L(j,k);
L(i,j) = t/d[j];
}
}
}
bool blob::MatrixR::qr (const MatrixR & A, MatrixR &Q, MatrixR & R)
{
uint8_t m = A.nrows();
uint8_t n = A.ncols();
int i=0,j=0,k=0;
if(A.length()>MATRIX_MAX_LENGTH)
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::qr() error: Matrix A length is greater than "
<< (int)MATRIX_MAX_LENGTH << std::endl;
#endif
return false;
}
if((Q.nrows() != m)||(Q.ncols() != m))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::qr() error: Matrix Q is not square with m=" << (int)m
<< std::endl;
#endif
return false;
}
if((R.nrows() != m)||(R.ncols() != n))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::qr() error: Matrix R has not the same size as A"
<< std::endl;
#endif
return false;
}
//real_t h[MATRIX_MAX_LENGTH];
//real_t aux[MATRIX_MAX_LENGTH];
real_t h[A.nrows()*A.nrows()];
real_t aux[A.ncols()*A.nrows()];
Matrix H(m,m,h);
Matrix Aux(m,n,aux);
Q.eye();
R.copy(A);
for (i=0; i<n && i<(m-1); i++)
{
H.eye();
real_t sign = (R(i,i) < 0)? -1:1;
real_t nrm = 0.0;
for(k=i; k<m; k++)
nrm += R(k,i)*R(k,i);
nrm = blob::math::sqrtr(nrm);
real_t d = (R(i,i) + sign*nrm);
real_t t = 1;
for(k=i+1; k<m; k++)
t += (R(k,i)/d)*(R(k,i)/d);
t=2/t;
for(j=i; j<m; j++)
{
for(k=i; k<m; k++)
{
real_t vj = (j==i)? 1.0 : R(j,i)/d;
real_t vk = (k==i)? 1.0 : R(k,i)/d;
H(j,k) = H(j,k) - vj*vk*t;
}
}
Aux.refurbish(m,m);
multiply(Q,H,Aux);
Q.copy(Aux);
Aux.refurbish(m,n);
multiply(H,R,Aux);
R.copy(Aux);
}
return true;
}
// https://rosettacode.org/wiki/LU_decomposition
// TODO: Check why partial pivoting, applied but A=LU instead of PA=LU and result differs from octave and rosettacode
bool blob::MatrixR::lu (const MatrixR & A, MatrixR & L, MatrixR & U, MatrixR & P)
{
if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(U.ncols()!=U.nrows()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl;
#endif
return false;
}
if((A.nrows()!=L.ncols())||(A.nrows()!=U.ncols()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl;
#endif
return false;
}
U.copy(A);
L.eye();
P.eye();
for(int k=0; k<U.ncols()-1; k++)
{
// select next row to permute (partial pivoting)
real_t max=blob::math::rabs(U(k,k));
uint8_t imax=k;
for(int i=k+1; i<A.nrows(); i++)
{
real_t next=blob::math::rabs(U(i,k));
if(next>max)
{
max=next;
imax=i;
}
}
if(imax!=k)
{
U.permuteRows(k,imax,U.ncols()-k,k);
L.permuteRows(k,imax,k,0);
P.permuteRows(k,imax);
}
for(int j=k+1; j<A.ncols(); j++)
{
L(j,k)=U(j,k)/U(k,k);
for(int l=k;l<A.ncols();l++)
U(j,l)=U(j,l)-L(j,k)*U(k,l);
}
}
}
bool blob::MatrixR::lu (const MatrixR & A, MatrixR & L, MatrixR & U)
{
if((A.nrows()!=A.ncols())||(L.nrows()!=L.ncols())||(U.ncols()!=U.nrows()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl;
#endif
return false;
}
if((A.nrows()!=L.ncols())||(A.nrows()!=U.ncols()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl;
#endif
return false;
}
U.copy(A);
L.eye();
for(int k=0; k<U.ncols()-1; k++)
{
// select next row to permute (partial pivoting)
for(int j=k+1; j<A.ncols(); j++)
{
L(j,k)=U(j,k)/U(k,k);
for(int l=k;l<A.ncols();l++)
U(j,l)=U(j,l)-L(j,k)*U(k,l);
}
}
}
bool blob::MatrixR::lu (const MatrixR & A, MatrixR & R)
{
if((A.nrows()!=A.ncols())||(R.nrows()!=R.ncols()))
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix are not square" << std::endl;
#endif
return false;
}
if(A.nrows()!=R.ncols())
{
#if defined(__DEBUG__) & defined(__linux__)
std::cerr << "Matrix::lu() error: Matrix sizes are not equal" << std::endl;
#endif
return false;
}
R.copy(A);
for(int k=0; k<R.ncols()-1; k++)
{
for(int j=k+1; j<R.ncols(); j++)
{
R(j,k)=R(j,k)/R(k,k);
for(int l=k+1;l<R.ncols();l++)
R(j,l)=R(j,l)-R(j,k)*R(k,l);
}
}
return true;
}
| 24.078731 | 118 | 0.48636 | blobrobots |
8eadbd122506a76c97abc89ea53a27bb84c106c3 | 2,229 | cpp | C++ | Plugins/MixedReality-OpenXR-Unreal/MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp | peted70/hl2-ue-worldanchor-sample | e64515ff5821d1d11274fa9b78289445d6883e71 | [
"MIT"
] | 105 | 2020-11-24T17:24:36.000Z | 2022-03-31T05:33:24.000Z | MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp | Qianlixun/Microsoft-OpenXR-Unreal | 977e4b16a016d29897f8bf2ee793ba034eddfbc8 | [
"MIT"
] | 20 | 2021-02-06T16:08:34.000Z | 2022-03-10T15:07:30.000Z | MsftOpenXRGame/Plugins/MicrosoftOpenXR/Source/MicrosoftOpenXR/Private/TrackedGeometryCollision.cpp | Qianlixun/Microsoft-OpenXR-Unreal | 977e4b16a016d29897f8bf2ee793ba034eddfbc8 | [
"MIT"
] | 36 | 2020-11-26T15:14:50.000Z | 2022-03-30T21:34:42.000Z | // Copyright (c) 2020 Microsoft Corporation.
// Licensed under the MIT License.
#include "TrackedGeometryCollision.h"
namespace MicrosoftOpenXR
{
TrackedGeometryCollision::TrackedGeometryCollision(const TArray<FVector> InVertices, const TArray<MRMESH_INDEX_TYPE> InIndices)
{
if (InVertices.Num() == 0)
{
return;
}
Vertices = std::move(InVertices);
Indices = std::move(InIndices);
// Create a bounding box from the input vertices to reduce the number of full meshes that need to be hit-tested.
BoundingBox = FBox(&Vertices[0], Vertices.Num());
}
void TrackedGeometryCollision::UpdateVertices(const TArray<FVector> InVertices, const TArray<MRMESH_INDEX_TYPE> InIndices)
{
Vertices = InVertices;
Indices = InIndices;
// Create a bounding box from the input vertices to reduce the number of full meshes that need to be hit-tested.
BoundingBox = FBox(&Vertices[0], Vertices.Num());
}
bool TrackedGeometryCollision::Collides(const FVector Start, const FVector End, const FTransform MeshToWorld, FVector& OutHitPoint, FVector& OutHitNormal, float& OutHitDistance)
{
if (MeshToWorld.GetScale3D().IsNearlyZero())
{
return false;
}
// Check bounding box collision first so we don't check triangles for meshes we definitely won't collide with.
if (!FMath::LineBoxIntersection(BoundingBox.TransformBy(MeshToWorld), Start, End, End - Start))
{
return false;
}
// Check for triangle collision and set the output hit position, normal, and distance.
for (int i = 0; i < Indices.Num(); i += 3)
{
// Ignore this triangle if it has indices out of range.
if ((unsigned int)Indices[i] > (unsigned int)Vertices.Num()
|| (unsigned int)Indices[i + 1] > (unsigned int)Vertices.Num()
|| (unsigned int)Indices[i + 2] > (unsigned int)Vertices.Num())
{
continue;
}
if (FMath::SegmentTriangleIntersection(Start, End,
MeshToWorld.TransformPosition(Vertices[Indices[i]]),
MeshToWorld.TransformPosition(Vertices[Indices[i + 1]]),
MeshToWorld.TransformPosition(Vertices[Indices[i + 2]]),
OutHitPoint, OutHitNormal))
{
OutHitDistance = (OutHitPoint - Start).Size();
return true;
}
}
return false;
}
} // namespace MicrosoftOpenXR
| 32.304348 | 178 | 0.717811 | peted70 |
8eae656c140630fcb82003e67a13410f602d9a22 | 4,851 | cpp | C++ | cpp/MinQuintet.cpp | Tmyiri/QS-Net | d121ba9cea8105caed4bd0836ec23f8347935646 | [
"MIT"
] | 3 | 2019-04-21T00:58:44.000Z | 2019-12-18T06:36:48.000Z | cpp/MinQuintet.cpp | Tmyiri/QS-Net | d121ba9cea8105caed4bd0836ec23f8347935646 | [
"MIT"
] | 2 | 2020-08-08T17:54:23.000Z | 2021-04-29T05:23:13.000Z | cpp/MinQuintet.cpp | Tmyiri/QS-Net | d121ba9cea8105caed4bd0836ec23f8347935646 | [
"MIT"
] | 1 | 2019-04-21T01:20:20.000Z | 2019-04-21T01:20:20.000Z | #include <iostream>
#include "CSplitSys.h"
using namespace std;
// calculate w(21|543)
// Method 1 w(21|543)= min{
// w(43|21)-w(51|43)+w(51|32)-w(54|32)+w(54|21),
// w(53|21)-w(53|41)+w(41|32)-w(54|32)+w(54|21),
// w(43|21)-w(51|43)+w(51|42)-w(53|42)+w(53|21),
// w(54|21)-w(54|31)+w(42|31)-w(53|42)+w(53|21),
// w(53|21)-w(53|41)+w(52|41)-w(52|43)+w(43|21),
// w(54|21)-w(54|31)+w(52|31)-w(52|43)+w(43|21).}
double CSplitSys::MinQuintet(unsigned int gLeft[2], unsigned int gRight[3])
{
CQuartet qTemp;
// specify all the possible blocks
unsigned int iB21[2];
iB21[0] = gLeft[0];
iB21[1] = gLeft[1];
unsigned int iB31[2];
iB31[0] = gRight[2];
iB31[1] = gLeft[1];
unsigned int iB32[2];
iB32[0] = gRight[2];
iB32[1] = gLeft[0];
unsigned int iB41[2];
iB41[0] = gRight[1];
iB41[1] = gLeft[1];
unsigned int iB42[2];
iB42[0] = gRight[1];
iB42[1] = gLeft[0];
unsigned int iB43[2];
iB43[0] = gRight[1];
iB43[1] = gRight[2];
unsigned int iB51[2];
iB51[0] = gRight[0];
iB51[1] = gLeft[1];
unsigned int iB52[2];
iB52[0] = gRight[0];
iB52[1] = gLeft[0];
unsigned int iB53[2];
iB53[0] = gRight[0];
iB53[1] = gRight[2];
unsigned int iB54[2];
iB54[0] = gRight[0];
iB54[1] = gRight[1];
// First: w(43|21)-w(51|43)+w(51|32)-w(54|32)+w(54|21)
double dTemp = 0;
// + w(43|21)
qTemp.SetLabel(iB43, iB21);
double w4321 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w4321;
//- w(51|43)
qTemp.SetLabel(iB51, iB43);
double w5143 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5143;
//+w(51|32)
qTemp.SetLabel(iB51, iB32);
double w5132 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5132;
//-w(54|32)
qTemp.SetLabel(iB54, iB32);
double w5432 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5432;
//+w(54|21)
qTemp.SetLabel(iB54, iB21);
double w5421 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5421;
if(dTemp <= 0) return 0;
double dWei =dTemp;
// Second: w(53|21)-w(53|41)+w(41|32)-w(54|32)+w(54|21)
dTemp=0;
// + w(53|21)
qTemp.SetLabel(iB53, iB21);
double w5321 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5321;
//- w(53|41)
qTemp.SetLabel(iB53, iB41);
double w5341 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5341;
//+w(41|32)
qTemp.SetLabel(iB41, iB32);
double w4132 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w4132;
//-w(54|32)
dTemp -= w5432;
//+w(54|21)
dTemp += w5421;
if(dTemp <= 0) return 0;
if(dWei > dTemp) dWei = dTemp;
// Third: w(43|21)-w(51|43)+w(51|42)-w(53|42)+w(53|21)
dTemp=0;
// + w(43|21)
dTemp += w4321;
//- w(51|43)
dTemp -= w5143;
//+w(51|42)
qTemp.SetLabel(iB51, iB42);
double w5142 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5142;
//-w(53|42)
qTemp.SetLabel(iB53, iB42);
double w5342 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5342;
//+w(53|21)
dTemp += w5321;
if(dTemp <= 0) return 0;
if(dWei > dTemp) dWei = dTemp;
// Fourth: w(54|21)-w(54|31)+w(42|31)-w(53|42)+w(53|21),
dTemp=0;
// + w(54|21)
dTemp += w5421;
//-w(54|31)
qTemp.SetLabel(iB54, iB31);
double w5431 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5431;
//+w(42|31)
qTemp.SetLabel(iB42, iB31);
double w4231 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w4231;
//-w(53|42)
dTemp -= w5342;
//+w(53|21)
dTemp += w5321;
if(dTemp <= 0) return 0;
if(dWei > dTemp) dWei = dTemp;
// Fifth: w(53|21)-w(53|41)+w(52|41)-w(52|43)+w(43|21),
dTemp=0;
// + w(53|21)
dTemp += w5321;
//- w(53|41)
dTemp -= w5341;
//+w(52|41)
qTemp.SetLabel(iB52, iB41);
double w5241 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5241;
//-w(52|43)
qTemp.SetLabel(iB52, iB43);
double w5243 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp -= w5243;
//+w(43|21)
dTemp += w4321;
if(dTemp <= 0) return 0;
if(dWei > dTemp) dWei = dTemp;
// Sixth: w(54|21)-w(54|31)+w(52|31)-w(52|43)+w(43|21)
dTemp=0;
// + w(54|21)
dTemp += w5421;
//- w(54|31)
dTemp -= w5431;
//+w(52|31)
qTemp.SetLabel(iB52, iB31);
double w5231 = m_gQuartet[qTemp.GetIndex()].GetWeight();
dTemp += w5231;
//-w(52|43)
dTemp -= w5243;
//+w(43|21)
dTemp += w4321;
if(dTemp <= 0) return 0;
if(dWei > dTemp) dWei = dTemp;
return 0.5*dWei;
}
// EOF
| 22.354839 | 80 | 0.531025 | Tmyiri |
8eaedf4e36b6b3aacf8dbe5cab481d6cece203d4 | 8,753 | hpp | C++ | src/mlpack/methods/range_search/rs_model_impl.hpp | florian-rosenthal/mlpack | 4287a89886e39703571165ef1d40693eb51d22c6 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4,216 | 2015-01-01T02:06:12.000Z | 2022-03-31T19:12:06.000Z | src/mlpack/methods/range_search/rs_model_impl.hpp | florian-rosenthal/mlpack | 4287a89886e39703571165ef1d40693eb51d22c6 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2,621 | 2015-01-01T01:41:47.000Z | 2022-03-31T19:01:26.000Z | src/mlpack/methods/range_search/rs_model_impl.hpp | florian-rosenthal/mlpack | 4287a89886e39703571165ef1d40693eb51d22c6 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,972 | 2015-01-01T23:37:13.000Z | 2022-03-28T06:03:41.000Z | /**
* @file methods/range_search/rs_model_impl.hpp
* @author Ryan Curtin
*
* Implementation of serialize() and inline functions for RSModel.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP
#define MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP
// In case it hasn't been included yet.
#include "rs_model.hpp"
#include <mlpack/core/math/random_basis.hpp>
namespace mlpack {
namespace range {
template<template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RSWrapper<TreeType>::Train(util::Timers& timers,
arma::mat&& referenceSet,
const size_t /* leafSize */)
{
if (!Naive())
timers.Start("tree_building");
rs.Train(std::move(referenceSet));
if (!Naive())
timers.Stop("tree_building");
}
template<template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RSWrapper<TreeType>::Search(util::Timers& timers,
arma::mat&& querySet,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances,
const size_t /* leafSize */)
{
if (!Naive() && !SingleMode())
{
// We build the query tree manually, so that we can time how long it takes.
timers.Start("tree_building");
typename decltype(rs)::Tree queryTree(std::move(querySet));
timers.Stop("tree_building");
timers.Start("computing_neighbors");
rs.Search(&queryTree, range, neighbors, distances);
timers.Stop("computing_neighbors");
}
else
{
timers.Start("computing_neighbors");
rs.Search(std::move(querySet), range, neighbors, distances);
timers.Stop("computing_neighbors");
}
}
template<template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RSWrapper<TreeType>::Search(util::Timers& timers,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
timers.Start("computing_neighbors");
rs.Search(range, neighbors, distances);
timers.Stop("computing_neighbors");
}
template<template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void LeafSizeRSWrapper<TreeType>::Train(util::Timers& timers,
arma::mat&& referenceSet,
const size_t leafSize)
{
if (rs.Naive())
{
rs.Train(std::move(referenceSet));
}
else
{
timers.Start("tree_building");
std::vector<size_t> oldFromNewReferences;
typename decltype(rs)::Tree* tree =
new typename decltype(rs)::Tree(std::move(referenceSet),
oldFromNewReferences,
leafSize);
rs.Train(tree);
// Give the model ownership of the tree and the mappings.
rs.treeOwner = true;
rs.oldFromNewReferences = std::move(oldFromNewReferences);
timers.Stop("tree_building");
}
}
template<template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void LeafSizeRSWrapper<TreeType>::Search(
util::Timers& timers,
arma::mat&& querySet,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances,
const size_t leafSize)
{
if (!rs.Naive() && !rs.SingleMode())
{
// Build a second tree and search.
timers.Start("tree_building");
Log::Info << "Building query tree..." << std::endl;
std::vector<size_t> oldFromNewQueries;
typename decltype(rs)::Tree queryTree(std::move(querySet),
oldFromNewQueries,
leafSize);
Log::Info << "Tree built." << std::endl;
timers.Stop("tree_building");
std::vector<std::vector<size_t>> neighborsOut;
std::vector<std::vector<double>> distancesOut;
timers.Start("computing_neighbors");
rs.Search(&queryTree, range, neighborsOut, distancesOut);
timers.Stop("computing_neighbors");
// Remap the query points.
neighbors.resize(queryTree.Dataset().n_cols);
distances.resize(queryTree.Dataset().n_cols);
for (size_t i = 0; i < queryTree.Dataset().n_cols; ++i)
{
neighbors[oldFromNewQueries[i]] = neighborsOut[i];
distances[oldFromNewQueries[i]] = distancesOut[i];
}
}
else
{
timers.Start("computing_neighbors");
rs.Search(std::move(querySet), range, neighbors, distances);
timers.Stop("computing_neighbors");
}
}
// Serialize the model.
template<typename Archive>
void RSModel::serialize(Archive& ar, const uint32_t /* version */)
{
ar(CEREAL_NVP(treeType));
ar(CEREAL_NVP(randomBasis));
ar(CEREAL_NVP(q));
// This should never happen, but just in case...
if (cereal::is_loading<Archive>())
InitializeModel(false, false); // Values will be overwritten.
// Avoid polymorphic serialization by explicitly serializing the correct type.
switch (treeType)
{
case KD_TREE:
{
LeafSizeRSWrapper<tree::KDTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::KDTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case COVER_TREE:
{
RSWrapper<tree::StandardCoverTree>& typedSearch =
dynamic_cast<RSWrapper<tree::StandardCoverTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case R_TREE:
{
RSWrapper<tree::RTree>& typedSearch =
dynamic_cast<RSWrapper<tree::RTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case R_STAR_TREE:
{
RSWrapper<tree::RStarTree>& typedSearch =
dynamic_cast<RSWrapper<tree::RStarTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case BALL_TREE:
{
LeafSizeRSWrapper<tree::BallTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::BallTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case X_TREE:
{
RSWrapper<tree::XTree>& typedSearch =
dynamic_cast<RSWrapper<tree::XTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case HILBERT_R_TREE:
{
RSWrapper<tree::HilbertRTree>& typedSearch =
dynamic_cast<RSWrapper<tree::HilbertRTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case R_PLUS_TREE:
{
RSWrapper<tree::RPlusTree>& typedSearch =
dynamic_cast<RSWrapper<tree::RPlusTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case R_PLUS_PLUS_TREE:
{
RSWrapper<tree::RPlusPlusTree>& typedSearch =
dynamic_cast<RSWrapper<tree::RPlusPlusTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case VP_TREE:
{
LeafSizeRSWrapper<tree::VPTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::VPTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case RP_TREE:
{
LeafSizeRSWrapper<tree::RPTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::RPTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case MAX_RP_TREE:
{
LeafSizeRSWrapper<tree::MaxRPTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::MaxRPTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case UB_TREE:
{
LeafSizeRSWrapper<tree::UBTree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::UBTree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
case OCTREE:
{
LeafSizeRSWrapper<tree::Octree>& typedSearch =
dynamic_cast<LeafSizeRSWrapper<tree::Octree>&>(*rSearch);
ar(CEREAL_NVP(typedSearch));
break;
}
}
}
} // namespace range
} // namespace mlpack
#endif
| 30.929329 | 80 | 0.607677 | florian-rosenthal |
8eb22800d61e3b40e628fa1436bf42cdd446fa87 | 1,461 | cpp | C++ | algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 1201-1300/_1254_NumberOfClosedIslands.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | /* Source - https://leetcode.com/problems/number-of-closed-islands/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
int x[4] = {-1, 0, 1, 0};
int y[4] = {0, -1, 0, 1};
bool dfs(int sr, int sc, vector< vector<int> >& grid) {
grid[sr][sc] = 1;
if(sr == 0 || sc == 0 || sr == grid.size() - 1 || sc == grid[0].size() - 1)
return false;
int falseCount = 0;
for(int d = 0; d < 4; d++) {
int a = sr + x[d];
int b = sc + y[d];
if(grid[a][b] == 1)
continue;
bool result = dfs(a, b, grid);
if(result == false)
falseCount++;
}
return falseCount == 0;
}
int number_of_closed_islands(vector< vector<int> >& grid) {
int n = grid.size();
int m = grid[0].size();
int result = 0;
for(int i = 1; i < n - 1; i++) {
for(int j = 1; j < m - 1; j++) {
if(grid[i][j] == 0)
result += dfs(i, j, grid) ? 1 : 0;
}
}
return result;
}
int main()
{
int n, m;
cout<<"Enter dimensions of the grid: ";
cin>>n>>m;
vector< vector<int> > grid(n, vector<int> (m));
cout<<"Enter the values in the grid (1 - water, 0 - land) row-wise: "<<endl;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
cin>>grid[i][j];
}
cout<<"Number of closed islands: "<<number_of_closed_islands(grid)<<endl;
} | 22.476923 | 80 | 0.464066 | shivamacs |
8eb849f2a90f0aaac2f0f3de98d0a393fffc5fbb | 15,981 | cpp | C++ | sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp | ChampionCynthia/g-string_2013 | cae02cf5128be8a2469f242cff079a5f98e45427 | [
"Unlicense"
] | 28 | 2015-08-16T16:43:27.000Z | 2022-02-19T23:37:08.000Z | sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp | ChampionCynthia/g-string_2013 | cae02cf5128be8a2469f242cff079a5f98e45427 | [
"Unlicense"
] | null | null | null | sp/src/game/client/gstring/vgui/vgui_gstringoptions.cpp | ChampionCynthia/g-string_2013 | cae02cf5128be8a2469f242cff079a5f98e45427 | [
"Unlicense"
] | 6 | 2015-10-02T21:34:38.000Z | 2019-09-20T11:09:41.000Z |
#include "cbase.h"
#include "tier1/KeyValues.h"
#include "gstring/gstring_cvars.h"
#include "gstring/vgui/vgui_gstringoptions.h"
#include "ienginevgui.h"
#include "vgui_controls/Panel.h"
#include "vgui_controls/CheckButton.h"
#include "vgui_controls/ComboBox.h"
#include "vgui_controls/Slider.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/PropertyPage.h"
#include "matsys_controls/colorpickerpanel.h"
using namespace vgui;
extern ConVar gstring_firstpersonbody_enable;
//extern ConVar gstring_firstpersonbody_shadow_enable;
extern ConVar gstring_volumetrics_enabled;
static PostProcessingState_t presets[] =
{
// Subtle
{ true, true, true, true, true, true, false, true, false, 0.0f, 0.3f, 0.7f, 0.3f, 0.2f, 0.1f, 0.2f, 0.2f },
// Vibrant
{ true, true, true, true, true, true, true, true, true, 0.0f, 0.7f, 1.0f, 0.5f, 0.0f, 0.2f, 0.6f, 0.8f },
// film noir
{ true, true, true, true, true, true, true, true, false, 0.0f, 0.8f, 1.0f, 0.5f, 1.0f, 0.3f, 0.2f, 0.9f },
// film noir red
{ true, true, true, true, true, true, true, true, false, 0.0f, 0.8f, 1.0f, 0.5f, 0.5f, 0.3f, 0.2f, 0.9f },
// bw
{ false, false, false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
// bw red
//{ false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f },
// 70 mm
{ true, true, true, true, true, true, true, true, true, 1.0f, 0.2f, 0.8f, 0.1f, 0.1f, 0.2f, 0.7f, 0.6f },
// none
{ false, false, false, false, false, false, false, false, false, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f },
};
static float scales[ PP_VALS ] = {
5.0f,
1.0f,
0.2f,
1.0f,
1.0f,
5.0f,
1.0f,
100.0f
};
static Color HUDColors[ HUDCOLOR_VALS ] = {
Color( 255, 229, 153, 255 ),
Color( 255, 128, 0, 255 ),
Color( 255, 255, 255, 255 ),
Color( 164, 164, 164, 255 ),
};
CVGUIGstringOptions::CVGUIGstringOptions( VPANEL parent, const char *pName ) : BaseClass( NULL, pName )
{
SetParent( parent );
Activate();
m_pPropertySheet = new PropertySheet( this, "property_sheet" );
PropertyPage *pPagePostProcessing = new PropertyPage( m_pPropertySheet, "" );
PropertyPage *pPageGame = new PropertyPage( m_pPropertySheet, "" );
LoadControlSettings( "resource/gstring_options.res" );
m_pPropertySheet->AddPage( pPagePostProcessing, "#pp_postprocessing_title" );
m_pPropertySheet->AddPage( pPageGame, "#option_game_title" );
#define CREATE_VGUI_SLIDER( var, name, minRange, maxRange, ticks ) var = new Slider( pPagePostProcessing, name ); \
var->SetRange( minRange, maxRange ); \
var->SetNumTicks( ticks ); \
var->AddActionSignalTarget( this )
#define CREATE_VGUI_CHECKBOX( var, name, page ) var = new CheckButton( page, name, "" ); \
var->AddActionSignalTarget( this )
CREATE_VGUI_CHECKBOX( m_pCheck_HurtFX, "check_damageeffects", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_Vignette, "check_vignette", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_GodRays, "check_godrays", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_WaterEffects, "check_screenwater", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_LensFlare, "check_lensflare", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_DreamBlur, "check_dreamblur", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_ScreenBlur, "check_screenblur", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_CinemaOverlay, "check_cinemaoverlay", pPagePostProcessing );
CREATE_VGUI_CHECKBOX( m_pCheck_Dof, "check_dof", pPagePostProcessing );
m_pCBox_Preset = new ComboBox( pPagePostProcessing, "combo_preset", 10, false );
m_pCBox_Preset->AddItem( "#pp_preset_subtle", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_vibrant", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_filmnoir", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_filmnoir_red", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_bw", NULL );
//m_pCBox_Preset->AddItem( "#pp_preset_bw_red", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_70mm", NULL );
m_pCBox_Preset->AddItem( "#pp_preset_none", NULL );
m_pCBox_Preset->AddActionSignalTarget( this );
CREATE_VGUI_SLIDER( m_pSlider_CinematicBars_Size, "slider_bars", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_MotionBlur_Strength, "slider_mblur", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_BloomFlare_Strength, "slider_bflare", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_ExplosionBlur_Strength, "slider_expblur", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_Desaturation_Strength, "slider_desat", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_FilmGrain_Strength, "slider_filmgrain", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_Bend_Strength, "slider_bend", 0, 10, 10 );
CREATE_VGUI_SLIDER( m_pSlider_Chromatic_Strength, "slider_chromatic", 0, 10, 10 );
m_pLabel_Value_CinematicBars = new Label( pPagePostProcessing, "label_bars", "" );
m_pLabel_Value_MotionBlur = new Label( pPagePostProcessing, "label_mblur", "" );
m_pLabel_Value_BloomFlare = new Label( pPagePostProcessing, "label_bflare", "" );
m_pLabel_Value_ExplosionBlur = new Label( pPagePostProcessing, "label_expblur", "" );
m_pLabel_Value_Desaturation = new Label( pPagePostProcessing, "label_desat", "" );
m_pLabel_Value_FilmGrain = new Label( pPagePostProcessing, "label_filmgrain", "" );
m_pLabel_Value_Bend = new Label( pPagePostProcessing, "label_bend", "" );
m_pLabel_Value_Chromatic = new Label( pPagePostProcessing, "label_chromatic", "" );
pPagePostProcessing->LoadControlSettings( "resource/gstring_options_page_postprocessing.res" );
CREATE_VGUI_CHECKBOX( m_pCheck_FirstPersonBody, "check_first_person_body", pPageGame );
//CREATE_VGUI_CHECKBOX( m_pCheck_FirstPersonShadow, "check_first_person_shadow", pPageGame );
CREATE_VGUI_CHECKBOX( m_pCheck_LightVolumetrics, "check_volumetrics", pPageGame );
m_pCBox_HUDColorPreset = new ComboBox( pPageGame, "cbox_color_preset", 10, false );
m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_default", NULL );
m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_orange", NULL );
m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_white", NULL );
m_pCBox_HUDColorPreset->AddItem( "#options_game_hud_color_preset_dark", NULL );
m_pCBox_HUDColorPreset->AddActionSignalTarget( this );
m_pHUDColorPicker = new CColorPickerButton( pPageGame, "hud_color_picker_button", this );
pPageGame->LoadControlSettings( "resource/gstring_options_page_game.res" );
DoModal();
SetDeleteSelfOnClose( true );
SetVisible( true );
SetSizeable(false);
SetMoveable(true);
SetTitle( "#pp_title", false );
m_pVarChecks[ 0 ] = &cvar_gstring_drawhurtfx;
m_pVarChecks[ 1 ] = &cvar_gstring_drawgodrays;
m_pVarChecks[ 2 ] = &cvar_gstring_drawwatereffects;
m_pVarChecks[ 3 ] = &cvar_gstring_drawvignette;
m_pVarChecks[ 4 ] = &cvar_gstring_drawlensflare;
m_pVarChecks[ 5 ] = &cvar_gstring_drawdreamblur;
m_pVarChecks[ 6 ] = &cvar_gstring_drawscreenblur;
m_pVarChecks[ 7 ] = &cvar_gstring_drawcinemaoverlay;
m_pVarChecks[ 8 ] = &cvar_gstring_drawdof;
m_pVarValues[ 0 ] = &cvar_gstring_bars_scale;
m_pVarValues[ 1 ] = &cvar_gstring_motionblur_scale;
m_pVarValues[ 2 ] = &cvar_gstring_bloomflare_strength;
m_pVarValues[ 3 ] = &cvar_gstring_explosionfx_strength;
m_pVarValues[ 4 ] = &cvar_gstring_desaturation_strength;
m_pVarValues[ 5 ] = &cvar_gstring_filmgrain_strength;
m_pVarValues[ 6 ] = &cvar_gstring_bend_strength;
m_pVarValues[ 7 ] = &cvar_gstring_chromatic_aberration;
CvarToState();
OnSliderMoved( NULL );
}
CVGUIGstringOptions::~CVGUIGstringOptions()
{
}
void CVGUIGstringOptions::OnCommand( const char *cmd )
{
if ( !Q_stricmp( cmd, "save" ) )
{
#define CVAR_CHECK_INTEGER( x, y ) ( x.SetValue( ( y->IsSelected() ? 1 : int(0) ) ) )
//#define CVAR_SLIDER_FLOAT( x, y, ratio ) ( x.SetValue( (float)(y->GetValue()/(float)ratio ) ) )
//
// CVAR_CHECK_INTEGER( cvar_gstring_drawhurtfx, m_pCheck_HurtFX );
// CVAR_CHECK_INTEGER( cvar_gstring_drawvignette, m_pCheck_Vignette );
// CVAR_CHECK_INTEGER( cvar_gstring_drawgodrays, m_pCheck_GodRays );
// CVAR_CHECK_INTEGER( cvar_gstring_drawscreenblur, m_pCheck_ScreenBlur );
// CVAR_CHECK_INTEGER( cvar_gstring_drawdreamblur, m_pCheck_DreamBlur );
// CVAR_CHECK_INTEGER( cvar_gstring_drawlensflare, m_pCheck_LensFlare );
// CVAR_CHECK_INTEGER( cvar_gstring_drawwatereffects, m_pCheck_WaterEffects );
//
// CVAR_SLIDER_FLOAT( cvar_gstring_explosionfx_strength, m_pSlider_ExplosionBlur_Strength, 10 );
// CVAR_SLIDER_FLOAT( cvar_gstring_bars_scale, m_pSlider_CinematicBars_Size, 50 );
// CVAR_SLIDER_FLOAT( cvar_gstring_motionblur_scale, m_pSlider_MotionBlur_Strength, 10 );
// CVAR_SLIDER_FLOAT( cvar_gstring_bloomflare_strength, m_pSlider_BloomFlare_Strength, 2 );
// CVAR_SLIDER_FLOAT( cvar_gstring_desaturation_strength, m_pSlider_Desaturation_Strength, 10 );
// CVAR_SLIDER_FLOAT( cvar_gstring_filmgrain_strength, m_pSlider_FilmGrain_Strength, 50 );
// CVAR_SLIDER_FLOAT( cvar_gstring_bend_strength, m_pSlider_Bend_Strength, 10 );
// CVAR_SLIDER_FLOAT( cvar_gstring_chromatic_aberration, m_pSlider_Chromatic_Strength, 1000 );
CVAR_CHECK_INTEGER( gstring_firstpersonbody_enable, m_pCheck_FirstPersonBody );
CVAR_CHECK_INTEGER( gstring_volumetrics_enabled, m_pCheck_LightVolumetrics );
StateToCvar();
gstring_hud_color.SetValue( VarArgs( "%i %i %i 255", m_colHUD.r(), m_colHUD.g(), m_colHUD.b() ) );
engine->ClientCmd( "host_writeconfig" );
engine->ClientCmd( "hud_reloadscheme" );
CloseModal();
}
else if ( !Q_stricmp( cmd, "defaults" ) )
{
m_pCBox_Preset->ActivateItem( 0 );
gstring_hud_color.Revert();
ReadValues( true );
UpdateLabels();
}
else
{
BaseClass::OnCommand( cmd );
}
}
void CVGUIGstringOptions::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
ReadValues( true );
UpdateLabels();
}
void CVGUIGstringOptions::ReadValues( bool bUpdatePreset )
{
#define CVAR_CHECK_SELECTED( x, y ) ( y->SetSelectedNoMessage( x.GetBool() ) )
//#define CVAR_SLIDER_INTEGER( x, y, ratio ) ( y->SetValue( x.GetFloat() * ratio, false ) )
CVAR_CHECK_SELECTED( gstring_firstpersonbody_enable, m_pCheck_FirstPersonBody );
CVAR_CHECK_SELECTED( gstring_volumetrics_enabled, m_pCheck_LightVolumetrics );
#define CVAR_STATE_CHECK_SELECTED( i, y ) ( y->SetSelectedNoMessage( m_state.checks[ i ] ) )
#define CVAR_STATE_SLIDER_INTEGER( i, y ) ( y->SetValue( m_state.val[ i ] * 10.1f, false ) )
CVAR_STATE_CHECK_SELECTED( 0, m_pCheck_HurtFX );
CVAR_STATE_CHECK_SELECTED( 1, m_pCheck_GodRays );
CVAR_STATE_CHECK_SELECTED( 2, m_pCheck_WaterEffects );
CVAR_STATE_CHECK_SELECTED( 3, m_pCheck_Vignette );
CVAR_STATE_CHECK_SELECTED( 4, m_pCheck_LensFlare );
CVAR_STATE_CHECK_SELECTED( 5, m_pCheck_DreamBlur );
CVAR_STATE_CHECK_SELECTED( 6, m_pCheck_ScreenBlur );
CVAR_STATE_CHECK_SELECTED( 7, m_pCheck_CinemaOverlay );
CVAR_STATE_CHECK_SELECTED( 8, m_pCheck_Dof );
CVAR_STATE_SLIDER_INTEGER( 0, m_pSlider_CinematicBars_Size );
CVAR_STATE_SLIDER_INTEGER( 1, m_pSlider_MotionBlur_Strength );
CVAR_STATE_SLIDER_INTEGER( 2, m_pSlider_BloomFlare_Strength );
CVAR_STATE_SLIDER_INTEGER( 3, m_pSlider_ExplosionBlur_Strength );
CVAR_STATE_SLIDER_INTEGER( 4, m_pSlider_Desaturation_Strength );
CVAR_STATE_SLIDER_INTEGER( 5, m_pSlider_FilmGrain_Strength );
CVAR_STATE_SLIDER_INTEGER( 6, m_pSlider_Bend_Strength );
CVAR_STATE_SLIDER_INTEGER( 7, m_pSlider_Chromatic_Strength );
UTIL_StringToColor( m_colHUD, gstring_hud_color.GetString() );
m_pHUDColorPicker->SetColor( m_colHUD );
for ( int i = 0; i < HUDCOLOR_VALS; ++i )
{
const Color &col = HUDColors[ i ];
if ( col == m_colHUD )
{
m_pCBox_HUDColorPreset->ActivateItem( i );
break;
}
}
if ( bUpdatePreset )
{
int presetIndex = FindCurrentPreset();
if ( presetIndex >= 0 )
{
m_pCBox_Preset->ActivateItem( presetIndex );
}
}
}
void CVGUIGstringOptions::PerformLayout()
{
BaseClass::PerformLayout();
MoveToCenterOfScreen();
}
void CVGUIGstringOptions::OnCheckButtonChecked( Panel *panel )
{
CheckButton *pCheckButton = dynamic_cast< CheckButton* >( panel );
if ( pCheckButton != NULL )
{
bool value = pCheckButton->IsSelected();
CheckButton *checkButtons[ PP_CHECKS ] = {
m_pCheck_HurtFX,
m_pCheck_GodRays,
m_pCheck_WaterEffects,
m_pCheck_Vignette,
m_pCheck_LensFlare,
m_pCheck_DreamBlur,
m_pCheck_ScreenBlur,
m_pCheck_CinemaOverlay,
m_pCheck_Dof
};
for ( int i = 0; i < PP_CHECKS; ++i )
{
if ( checkButtons[ i ] == panel )
{
m_state.checks[ i ] = value;
}
}
}
OnPresetModified();
}
void CVGUIGstringOptions::UpdateLabels()
{
m_pLabel_Value_CinematicBars->SetText( VarArgs( "%.1f", m_state.val[ 0 ] ) );
m_pLabel_Value_MotionBlur->SetText( VarArgs( "%.1f", m_state.val[ 1 ] ) );
m_pLabel_Value_BloomFlare->SetText( VarArgs( "%.1f", m_state.val[ 2 ] ) );
m_pLabel_Value_ExplosionBlur->SetText( VarArgs( "%.1f", m_state.val[ 3 ] ) );
m_pLabel_Value_Desaturation->SetText( VarArgs( "%.1f", m_state.val[ 4 ] ) );
m_pLabel_Value_FilmGrain->SetText( VarArgs( "%.1f", m_state.val[ 5 ] ) );
m_pLabel_Value_Bend->SetText( VarArgs( "%.1f", m_state.val[ 6 ] ) );
m_pLabel_Value_Chromatic->SetText( VarArgs( "%.1f", m_state.val[ 7 ] ) );
}
void CVGUIGstringOptions::OnSliderMoved( Panel *panel )
{
Slider *pSlider = dynamic_cast< Slider* >( panel );
if ( pSlider != NULL )
{
int value = pSlider->GetValue();
Slider *sliders[ PP_VALS ] = {
m_pSlider_CinematicBars_Size,
m_pSlider_MotionBlur_Strength,
m_pSlider_BloomFlare_Strength,
m_pSlider_ExplosionBlur_Strength,
m_pSlider_Desaturation_Strength,
m_pSlider_FilmGrain_Strength,
m_pSlider_Bend_Strength,
m_pSlider_Chromatic_Strength
};
for ( int i = 0; i < PP_VALS; ++i )
{
if ( sliders[ i ] == panel )
{
m_state.val[ i ] = value * 0.101f;
}
}
}
OnPresetModified();
UpdateLabels();
}
void CVGUIGstringOptions::OnTextChanged( KeyValues *pKV )
{
Panel *p = (Panel*)pKV->GetPtr( "panel" );
if ( p == m_pCBox_Preset )
{
ApplyPreset( m_pCBox_Preset->GetActiveItem() );
}
else if ( p == m_pCBox_HUDColorPreset )
{
const Color &col = HUDColors[ m_pCBox_HUDColorPreset->GetActiveItem() ];
m_colHUD = col;
m_pHUDColorPicker->SetColor( col );
}
}
void CVGUIGstringOptions::OnPicked( KeyValues *pKV )
{
m_colHUD = pKV->GetColor( "color" );
}
void CVGUIGstringOptions::ApplyPreset( int index )
{
if ( index < 0 || index >= ARRAYSIZE( presets ) )
{
return;
}
const PostProcessingState_t &p = presets[ index ];
for ( int c = 0; c < PP_CHECKS; ++c )
{
m_state.checks[ c ] = p.checks[ c ];
}
for ( int v = 0; v < PP_VALS; ++v )
{
m_state.val[ v ] = p.val[ v ];
}
ReadValues( false );
UpdateLabels();
}
int CVGUIGstringOptions::FindCurrentPreset()
{
for ( int i = 0; i < ARRAYSIZE( presets ); ++i )
{
const PostProcessingState_t &p = presets[ i ];
bool bWrong = false;
for ( int c = 0; c < PP_CHECKS; ++c )
{
if ( m_state.checks[ c ] != p.checks[ c ] )
{
bWrong = true;
}
}
for ( int v = 0; v < PP_VALS; ++v )
{
if ( !CloseEnough( m_state.val[ v ], p.val[ v ] ) )
{
bWrong = true;
}
}
if ( !bWrong )
{
return i;
}
}
return -1;
}
void CVGUIGstringOptions::OnPresetModified()
{
m_pCBox_Preset->SetText( "#pp_preset_custom" );
}
void CVGUIGstringOptions::CvarToState()
{
for ( int i = 0; i < PP_CHECKS; ++i )
{
m_state.checks[ i ] = m_pVarChecks[ i ]->GetBool();
}
for ( int i = 0; i < PP_VALS; ++i )
{
m_state.val[ i ] = m_pVarValues[ i ]->GetFloat() * scales[ i ];
}
}
void CVGUIGstringOptions::StateToCvar()
{
for ( int i = 0; i < PP_CHECKS; ++i )
{
m_pVarChecks[ i ]->SetValue( m_state.checks[ i ] ? 1 : int( 0 ) );
}
for ( int i = 0; i < PP_VALS; ++i )
{
m_pVarValues[ i ]->SetValue( m_state.val[ i ] / scales[ i ] );
}
}
CON_COMMAND( vgui_showGstringOptions, "" )
{
vgui::VPANEL GameUIRoot = enginevgui->GetPanel( PANEL_GAMEUIDLL );
new CVGUIGstringOptions( GameUIRoot, "GstringOptions" );
}
| 34.074627 | 115 | 0.73093 | ChampionCynthia |
8ebc620eee4b12815926d4c6596310b0d5f981ff | 519 | hpp | C++ | coreneuron/permute/data_layout.hpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | 109 | 2016-04-08T09:27:54.000Z | 2022-03-15T02:10:47.000Z | coreneuron/permute/data_layout.hpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | 595 | 2016-04-01T09:12:47.000Z | 2022-03-31T23:44:58.000Z | coreneuron/permute/data_layout.hpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | 52 | 2016-03-29T08:11:35.000Z | 2022-03-11T07:37:38.000Z | /*
# =============================================================================
# Copyright (c) 2016 - 2021 Blue Brain Project/EPFL
#
# See top-level LICENSE file for details.
# =============================================================================
*/
#ifndef NRN_DATA_LAYOUT_HPP
#define NRN_DATA_LAYOUT_HPP
#define SOA_LAYOUT 0
#define AOS_LAYOUT 1
namespace coreneuron {
struct Memb_list;
int get_data_index(int node_index, int variable_index, int mtype, Memb_list* ml);
} // namespace coreneuron
#endif
| 27.315789 | 81 | 0.535645 | alexsavulescu |
8ebc679c6e7131ac3b876970c2499840dc8323da | 6,406 | cpp | C++ | src/testApp.cpp | zebradog/shaderTextureBlending | 939cf34ccf0e7b490eb483c0ecfc6e118801b1df | [
"MIT"
] | null | null | null | src/testApp.cpp | zebradog/shaderTextureBlending | 939cf34ccf0e7b490eb483c0ecfc6e118801b1df | [
"MIT"
] | null | null | null | src/testApp.cpp | zebradog/shaderTextureBlending | 939cf34ccf0e7b490eb483c0ecfc6e118801b1df | [
"MIT"
] | null | null | null | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
cout << "WARNING: this program may take a while to load" << endl;
ofBackground(127,127,127);
ofSetWindowTitle( "Shader Texture Blending by Ruud Bijnen" );
ofSetFrameRate ( 30 );
ofSetVerticalSync(true);
shadeBlendMix = 1.0;
shadeBlendMode = 0;
shadeContrast = 1.0;
shadeBrightness = 0.0;
readme.load();
readme.mOverlay = true;
ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 200));
ofxControlPanel::setTextColor(simpleColor(255, 0, 128, 255));
ofxControlPanel::setForegroundColor(simpleColor(64, 64, 64, 255));
//gui.loadFont("monaco.ttf", 8);
gui.setup("Shader Texture Blending", 10, 10, 570, ofGetHeight()-40);
ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 50));
gui.addPanel("Shader settings", 3, false);
ofxControlPanel::setBackgroundColor(simpleColor(255, 255, 255, 10));
//--------- PANEL 1
gui.setWhichPanel(0);
gui.setWhichColumn(0);
gui.addDrawableRect("Base Texture", &imgBase, 150, 150);
listerBase.listDir("images/");
listerBase.setSelectedFile(0);
imgBase.loadImage( listerBase.getSelectedPath() );
guiTypeFileLister * guiBaseLister = gui.addFileLister("Base Chooser", &listerBase, 150, 300);
guiBaseLister->selection = 0;
guiBaseLister->notify();
//--------------------
gui.setWhichColumn(1);
gui.addDrawableRect("Blend Texture", &imgBlend, 150, 150);
listerBlend.listDir("images/");
listerBlend.setSelectedFile(1);
imgBlend.loadImage( listerBlend.getSelectedPath() );
guiTypeFileLister * guiBlendLister = gui.addFileLister("Blend Chooser", &listerBlend, 150, 300);
guiBlendLister->selection = 1;
//some dummy vars we will update to show the variable lister object
elapsedTime = ofGetElapsedTimef();
appFrameCount = ofGetFrameNum();
appFrameRate = ofGetFrameRate();
//--------------------
gui.setWhichColumn(2);
//gui.addSlider("motion threshold", "MOTION_THRESHOLD", 29.0, 1.0, 255.0, false);
gui.addSlider("Contrast","SHADER_CONTRAST", shadeContrast, 0.0, 5.0, false);
gui.addSlider("Brightness","SHADER_BRIGHTNESS", shadeBrightness, -1.0, 1.0, false);
gui.addSlider("Blend Mix","SHADER_BLENDMIX", shadeBlendMix, 0.0, 1.0, false);
vector <string> blendmodes;
blendmodes.push_back("Normal");
blendmodes.push_back("Lighten");
blendmodes.push_back("Darken");
blendmodes.push_back("Multiply");
blendmodes.push_back("Average");
blendmodes.push_back("Add");
blendmodes.push_back("Substract");
blendmodes.push_back("Difference");
blendmodes.push_back("Negation");
blendmodes.push_back("Exclusion");
blendmodes.push_back("Screen");
blendmodes.push_back("Overlay");
blendmodes.push_back("SoftLight");
blendmodes.push_back("HardLight");
blendmodes.push_back("ColorDodge");
blendmodes.push_back("ColorBurn");
blendmodes.push_back("LinearDodge");
blendmodes.push_back("LinearBurn");
blendmodes.push_back("LinearLight");
blendmodes.push_back("VividLight");
blendmodes.push_back("PinLight");
blendmodes.push_back("HardMix");
blendmodes.push_back("Reflect");
blendmodes.push_back("Glow");
blendmodes.push_back("Phoenix");
//ofxControlPanel::setBackgroundColor(simpleColor(0, 0, 0, 255));
gui.addTextDropDown("Blendmode", "SHADER_BLENDMODE", shadeBlendMode, blendmodes);
//ofxControlPanel::setBackgroundColor(simpleColor(255, 255, 255, 10));
//SETTINGS AND EVENTS
//load from xml!
gui.loadSettings("controlPanelSettings.xml");
//if you want to use events call this after you have added all your gui elements
gui.setupEvents();
gui.enableEvents();
// -- this gives you back an ofEvent for all events in this control panel object
ofAddListener(gui.guiEvent, this, &testApp::guiEvents);
shader.setup( "shaders/myShader" );
}
//this captures all our control panel events - unless its setup differently in testApp::setup
//--------------------------------------------------------------
void testApp::guiEvents(guiCallbackData & data){
if ( data.getDisplayName() == "Base Chooser" ) {
imgBase.loadImage( data.getString(1) );
} else if ( data.getDisplayName() == "Blend Chooser" ) {
imgBlend.loadImage( data.getString(1) );
}
}
//--------------------------------------------------------------
void testApp::update(){
//some dummy vars we will update to show the variable lister object
elapsedTime = ofGetElapsedTimef();
appFrameCount = ofGetFrameNum();
appFrameRate = ofGetFrameRate();
shadeBlendMode = gui.getValueI("SHADER_BLENDMODE");
shadeBlendMix = gui.getValueF("SHADER_BLENDMIX");
shadeContrast = gui.getValueF("SHADER_CONTRAST");
shadeBrightness = gui.getValueF("SHADER_BRIGHTNESS");
gui.update();
}
//--------------------------------------------------------------
void testApp::draw(){
ofSetColor(0xffffff);
//------------------ image
shader.begin();
shader.setUniform( "contrast", shadeContrast );
shader.setUniform( "brightness", shadeBrightness );
shader.setUniform( "blendmix", shadeBlendMix );
shader.setUniform( "blendmode", shadeBlendMode );
//shader.setTexture( "texBase", imgBase, 0 );
shader.setTexture( "texBlend", imgBlend, 1 );
imgBase.draw ( 650, 10 );
shader.end();
//----------------- gui
ofSetLineWidth(2);
ofDisableSmoothing();
gui.draw();
//----------------- readme
readme.draw();
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
readme.hide();
}
//--------------------------------------------------------------
void testApp::keyReleased (int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
gui.mouseDragged(x, y, button);
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
gui.mousePressed(x, y, button);
}
//--------------------------------------------------------------
void testApp::mouseReleased(){
gui.mouseReleased();
}
| 32.353535 | 98 | 0.607868 | zebradog |
8ec17823b724f8047599e4bf863425aaf8d744e2 | 1,883 | cpp | C++ | readFile.cpp | sidvishnoi/filesystem-simulation | d1534795736c5938eba07a288e9996236211025b | [
"MIT"
] | 4 | 2018-01-24T22:21:29.000Z | 2021-03-21T18:14:57.000Z | readFile.cpp | sidvishnoi/filesystem-simulation | d1534795736c5938eba07a288e9996236211025b | [
"MIT"
] | null | null | null | readFile.cpp | sidvishnoi/filesystem-simulation | d1534795736c5938eba07a288e9996236211025b | [
"MIT"
] | 1 | 2017-04-18T10:24:51.000Z | 2017-04-18T10:24:51.000Z | #include "filesystem.h"
int FileSystem::readFile(const char *title) {
/*
objective: to read a single file from multiple non-continuous sectors
input:
title: title of file
return:
0: success
1: error
effect: contents of file are printed, if success
*/
TypeCastEntry entry;
if (strlen(title) == 0) {
std::cout << "File title: ";
std::cin >> entry.entry.name;
std::cin.ignore(32767, '\n');
} else {
strcpy(entry.entry.name, title);
}
entry.entry.startsAt = 0;
char buf[kSectorSize];
TypeCastEntry test;
for (int i = 0; i < sectorsForDir; ++i) {
readSector(currentDir + i, buf);
for (int j = 0; j < kSectorSize; j += 32) {
for (int k = 0; k < 32; ++k) {
test.str[k] = buf[j+k];
}
if (strcmp(test.entry.name, entry.entry.name) == 0) {
entry.entry.startsAt = test.entry.startsAt;
entry.entry.size = test.entry.size;
entry.entry.parent = test.entry.parent;
if (test.entry.type != 'F') return 1;
break;
}
}
if (entry.entry.startsAt != 0) break;
}
if (entry.entry.startsAt == 0) {
std::cout << "file not found" << std::endl;
return 1;
} else {
// read file content
std::cout << "READING FILE WITH" << std::endl;
std::cout << "TITLE = " << test.entry.name << std::endl;
std::cout << "SIZE = " << entry.entry.size << " bytes." << std::endl;
int sec = entry.entry.startsAt;
while (sec != 1) {
readSector(sec, buf);
for (int i = 0; i < kSectorSize; ++i) {
std::cout << buf[i];
}
sec = getStatus(sec);
}
std::cout << std::endl;
}
return 0;
} | 30.370968 | 77 | 0.491768 | sidvishnoi |
8ec21fbffb9a28de422becf918f06a2869bc32f4 | 4,498 | cpp | C++ | lib/Analysis/Intrinsics.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 14 | 2019-11-04T15:03:40.000Z | 2021-09-07T17:29:40.000Z | lib/Analysis/Intrinsics.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 11 | 2019-11-29T21:18:12.000Z | 2021-12-22T21:36:40.000Z | lib/Analysis/Intrinsics.cpp | yukatan1701/tsar | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | [
"Apache-2.0"
] | 17 | 2019-10-15T13:56:35.000Z | 2021-10-20T17:21:14.000Z | //===-- Instrinsics.cpp - TSAR Intrinsic Function Handling ------*- C++ -*-===//
//
// Traits Static Analyzer (SAPFOR)
//
// Copyright 2018 DVM System Group
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//===----------------------------------------------------------------------===//
//
// This file implements functions from Intrinsics.h which allow to process
// TSAR intrinsics.
//
//===----------------------------------------------------------------------===//
#include "tsar/Analysis/Intrinsics.h"
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/Module.h>
#include <tuple>
using namespace llvm;
using namespace tsar;
/// Table of string intrinsic names indexed by enum value.
static const char * const IntrinsicNameTable[] = {
"not_intrinsic",
#define GET_INTRINSIC_NAME_TABLE
#include "tsar/Analysis/Intrinsics.gen"
#undef GET_INTRINSIC_NAME_TABLE
};
namespace {
/// Kinds of types which can be used in an intrinsic prototype.
enum TypeKind : unsigned {
#define GET_INTRINSIC_TYPE_KINDS
#include "tsar/Analysis/Intrinsics.gen"
#undef GET_INTRINSIC_TYPE_KINDS
};
/// This literal type contains offsets for a prototype in table of prototypes
/// (see PrototypeOffsetTable and PrototypeTable for details).
struct PrototypeDescriptor {
unsigned Start;
unsigned End;
};
}
///\brief Table of offsets in prototype table indexed by enum value.
///
/// Each intrinsic has a prototype which is described by a table of prototypes.
/// Each description record has start and end points which are stored in this
/// table. So start point of a prototype for an intrinsic Id can be accessed
/// in a following way `PrototypeTable[PrototypeOffsetTable[Id].first]`.
static constexpr PrototypeDescriptor PrototypeOffsetTable[] = {
#define PROTOTYPE(Start,End) {Start, End},
PROTOTYPE(0,0) // there is no prototype for `tsar_not_intrinsic`
#define GET_INTRINSIC_PROTOTYPE_OFFSET_TABLE
#include "tsar/Analysis/Intrinsics.gen"
#undef GET_INTRINSIC_PROTOTYPE_OFFSET_TABLE
#undef PROTOTYPE
};
/// Table of intrinsic prototypes indexed by records in prototype offset table.
static constexpr TypeKind PrototypeTable[] = {
#define GET_INTRINSIC_PROTOTYPE_TABLE
#include "tsar/Analysis/Intrinsics.gen"
#undef GET_INTRINSIC_PROTOTYPE_TABLE
};
/// Builds LLVM type for a type which is described in PrototypeTable and is
/// started at a specified position.
static Type * DecodeType(LLVMContext &Ctx, unsigned &Start) {
switch (PrototypeTable[Start]) {
case Void: ++Start; return Type::getVoidTy(Ctx);
case Any: ++Start; return Type::getInt8Ty(Ctx);
case Size: ++Start; return Type::getInt64Ty(Ctx);
case Pointer: return PointerType::getUnqual(DecodeType(Ctx, ++Start));
default:
llvm_unreachable("Unknown kind of intrinsic parameter type!");
return nullptr;
}
}
namespace tsar {
StringRef getName(IntrinsicId Id) {
assert(Id < IntrinsicId::num_intrinsics && Id > IntrinsicId::not_intrinsic &&
"Invalid intrinsic ID!");
return IntrinsicNameTable[static_cast<unsigned>(Id)];
}
FunctionType *getType(LLVMContext &Ctx, IntrinsicId Id) {
auto Offset = PrototypeOffsetTable[static_cast<unsigned>(Id)];
Type *ResultTy = DecodeType(Ctx, Offset.Start);
SmallVector<Type *, 8> ArgsTys;
while (Offset.Start < Offset.End)
ArgsTys.push_back(DecodeType(Ctx, Offset.Start));
return FunctionType::get(ResultTy, ArgsTys, false);
}
llvm::FunctionCallee getDeclaration(Module *M, IntrinsicId Id) {
return M->getOrInsertFunction(getName(Id), getType(M->getContext(), Id));
}
bool getTsarLibFunc(StringRef funcName, IntrinsicId &Id) {
const char* const *Start = &IntrinsicNameTable[0];
const char* const *End =
&IntrinsicNameTable[(unsigned)IntrinsicId::num_intrinsics];
if (funcName.empty())
return false;
const char* const *I = std::find(Start, End, funcName);
if (I != End) {
Id = (IntrinsicId)(I - Start);
return true;
}
return false;
}
}
| 34.868217 | 80 | 0.715874 | yukatan1701 |
8ecccc22e118a6bff9fc0589ec5024f050aa2f82 | 3,988 | cpp | C++ | Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp | BTH-StoraSpel-DXR/SPLASH | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 12 | 2019-09-11T15:52:31.000Z | 2021-11-14T20:33:35.000Z | Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 227 | 2019-09-11T08:40:24.000Z | 2020-06-26T14:12:07.000Z | Sail/src/Sail/entities/systems/network/receivers/NetworkReceiverSystemHost.cpp | BTH-StoraSpel-DXR/Game | 1bf4c9b96cbcce570ed3a97f30a556a992e1ad08 | [
"MIT"
] | 2 | 2020-10-26T02:35:18.000Z | 2020-10-26T02:36:01.000Z | #include "pch.h"
#include "NetworkReceiverSystemHost.h"
#include "../NetworkSenderSystem.h"
#include "Network/NWrapperSingleton.h"
#include "Sail/utils/Utils.h"
#include "Sail/utils/GameDataTracker.h"
#include "Sail/events/types/StartKillCamEvent.h"
#include "Sail/events/types/StopKillCamEvent.h"
#include "../SPLASH/src/game/states/GameState.h"
NetworkReceiverSystemHost::NetworkReceiverSystemHost() {
EventDispatcher::Instance().subscribe(Event::Type::START_KILLCAM, this);
EventDispatcher::Instance().subscribe(Event::Type::STOP_KILLCAM, this);
}
NetworkReceiverSystemHost::~NetworkReceiverSystemHost() {
EventDispatcher::Instance().unsubscribe(Event::Type::START_KILLCAM, this);
EventDispatcher::Instance().unsubscribe(Event::Type::STOP_KILLCAM, this);
}
void NetworkReceiverSystemHost::handleIncomingData(const std::string& data) {
pushDataToBuffer(data);
// The host will also save the data in the sender system so that it can be forwarded to all other clients
m_netSendSysPtr->pushDataToBuffer(data);
}
void NetworkReceiverSystemHost::stop() {
m_startEndGameTimer = false;
m_finalKillCamOver = true;
}
#ifdef DEVELOPMENT
unsigned int NetworkReceiverSystemHost::getByteSize() const {
return BaseComponentSystem::getByteSize() + sizeof(*this);
}
#endif
void NetworkReceiverSystemHost::endGame() {
m_startEndGameTimer = true;
}
// HOST ONLY FUNCTIONS
void NetworkReceiverSystemHost::endMatchAfterTimer(const float dt) {
static float endGameClock = 0.f;
if (m_startEndGameTimer) {
endGameClock += dt;
}
// Wait until the final killcam has ended or until 2 seconds has passed
if (m_finalKillCamOver && endGameClock > 2.0f) {
NWrapperSingleton::getInstance().queueGameStateNetworkSenderEvent(
Netcode::MessageType::ENDGAME_STATS,
nullptr,
false
);
m_gameStatePtr->requestStackClear();
m_gameStatePtr->requestStackPush(States::EndGame);
// Reset clock for next session
m_startEndGameTimer = false;
endGameClock = 0.f;
}
}
void NetworkReceiverSystemHost::prepareEndScreen(const Netcode::PlayerID sender, const EndScreenInfo& info) {
GlobalTopStats* gts = &GameDataTracker::getInstance().getStatisticsGlobal();
// Process the data
if (info.bulletsFired > gts->bulletsFired) {
gts->bulletsFired = info.bulletsFired;
gts->bulletsFiredID = sender;
}
if (info.distanceWalked > gts->distanceWalked) {
gts->distanceWalked = info.distanceWalked;
gts->distanceWalkedID = sender;
}
if (info.jumpsMade > gts->jumpsMade) {
gts->jumpsMade = info.jumpsMade;
gts->jumpsMadeID = sender;
}
// Send data back in Netcode::MessageType::ENDGAME_STATS
endGame(); // Starts the end game timer. Runs only for the host
}
bool NetworkReceiverSystemHost::onEvent(const Event& event) {
NetworkReceiverSystem::onEvent(event);
switch (event.type) {
case Event::Type::START_KILLCAM:
if (((const StartKillCamEvent&)event).finalKillCam) {
m_finalKillCamOver = false;
}
break;
case Event::Type::STOP_KILLCAM:
if (((const StopKillCamEvent&)event).isFinalKill) {
m_finalKillCamOver = true;
}
break;
default:
break;
}
return true;
}
void NetworkReceiverSystemHost::mergeHostsStats() {
GameDataTracker* gdt = &GameDataTracker::getInstance();
Netcode::PlayerID id = NWrapperSingleton::getInstance().getMyPlayerID();
if (gdt->getStatisticsLocal().bulletsFired > gdt->getStatisticsGlobal().bulletsFired) {
gdt->getStatisticsGlobal().bulletsFired = gdt->getStatisticsLocal().bulletsFired;
gdt->getStatisticsGlobal().bulletsFiredID = id;
}
if (gdt->getStatisticsLocal().distanceWalked > gdt->getStatisticsGlobal().distanceWalked) {
gdt->getStatisticsGlobal().distanceWalked = gdt->getStatisticsLocal().distanceWalked;
gdt->getStatisticsGlobal().distanceWalkedID = id;
}
if (gdt->getStatisticsLocal().jumpsMade > gdt->getStatisticsGlobal().jumpsMade) {
gdt->getStatisticsGlobal().jumpsMade = gdt->getStatisticsLocal().jumpsMade;
gdt->getStatisticsGlobal().jumpsMadeID = id;
}
endGame();
}
| 29.323529 | 109 | 0.758275 | BTH-StoraSpel-DXR |
8ecd289f93aedd0c2cc88098ac3d8885840171ab | 3,185 | cpp | C++ | sp/src/game/server/czeror/weapon_fiveseven.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | 2 | 2016-11-22T04:25:54.000Z | 2020-02-02T12:24:42.000Z | sp/src/game/server/czeror/weapon_fiveseven.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | null | null | null | sp/src/game/server/czeror/weapon_fiveseven.cpp | ZombieRoxtar/cZeroR | 8c67b9e2e2da2479581d5a3863b8598d44ee69bb | [
"Unlicense"
] | null | null | null | //===== Copyright Bit Mage's Stuff, All rights probably reserved. =====
//
// Purpose: Five-SeveN weapon, FN Five-seven, ES Five-seven
//
//=============================================================================
#include "cbase.h"
#include "baseadvancedweapon.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// CWeaponFiveSeven
//-----------------------------------------------------------------------------
class CWeaponFiveSeven : public CBaseAdvancedWeapon
{
public:
DECLARE_CLASS( CWeaponFiveSeven, CBaseAdvancedWeapon );
DECLARE_NETWORKCLASS();
DECLARE_PREDICTABLE();
float GetFireRate() { return 0.15f; } // 400 Rounds per minute
DECLARE_ACTTABLE();
};
IMPLEMENT_SERVERCLASS_ST( CWeaponFiveSeven, DT_WeaponFiveSeven )
END_SEND_TABLE()
LINK_ENTITY_TO_CLASS( weapon_fiveseven, CWeaponFiveSeven );
PRECACHE_WEAPON_REGISTER( weapon_fiveseven );
acttable_t CWeaponFiveSeven::m_acttable[] =
{
{ ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_PISTOL, true },
{ ACT_RELOAD, ACT_RELOAD_PISTOL, true },
{ ACT_IDLE, ACT_IDLE_PISTOL, true },
{ ACT_IDLE_ANGRY, ACT_IDLE_ANGRY_PISTOL, true },
{ ACT_WALK, ACT_WALK_PISTOL, true },
{ ACT_IDLE_RELAXED, ACT_IDLE_SMG1_RELAXED, false },
{ ACT_IDLE_STIMULATED, ACT_IDLE_SMG1_STIMULATED, false },
{ ACT_IDLE_AGITATED, ACT_IDLE_ANGRY_SMG1, false },
{ ACT_WALK_RELAXED, ACT_WALK_RIFLE_RELAXED, false },
{ ACT_WALK_STIMULATED, ACT_WALK_RIFLE_STIMULATED, false },
{ ACT_WALK_AGITATED, ACT_WALK_AIM_PISTOL, false },
{ ACT_RUN_RELAXED, ACT_RUN_RIFLE_RELAXED, false },
{ ACT_RUN_STIMULATED, ACT_RUN_RIFLE_STIMULATED, false },
{ ACT_RUN_AGITATED, ACT_RUN_AIM_PISTOL, false },
{ ACT_IDLE_AIM_RELAXED, ACT_IDLE_SMG1_RELAXED, false },
{ ACT_IDLE_AIM_STIMULATED, ACT_IDLE_AIM_RIFLE_STIMULATED, false },
{ ACT_IDLE_AIM_AGITATED, ACT_IDLE_ANGRY_SMG1, false },
{ ACT_WALK_AIM_RELAXED, ACT_WALK_RIFLE_RELAXED, false },
{ ACT_WALK_AIM_STIMULATED, ACT_WALK_AIM_RIFLE_STIMULATED, false },
{ ACT_WALK_AIM_AGITATED, ACT_RUN_AIM_PISTOL, false },
{ ACT_RUN_AIM_RELAXED, ACT_RUN_RIFLE_RELAXED, false },
{ ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_RIFLE_STIMULATED, false },
{ ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_PISTOL, false },
{ ACT_WALK_AIM, ACT_WALK_AIM_PISTOL, true },
{ ACT_WALK_CROUCH, ACT_WALK_CROUCH_RIFLE, true },
{ ACT_WALK_CROUCH_AIM, ACT_WALK_CROUCH_AIM_RIFLE, true },
{ ACT_RUN, ACT_RUN_PISTOL, true },
{ ACT_RUN_AIM, ACT_RUN_AIM_PISTOL, true },
{ ACT_RUN_CROUCH, ACT_RUN_CROUCH_RIFLE, true },
{ ACT_RUN_CROUCH_AIM, ACT_RUN_CROUCH_AIM_RIFLE, true },
{ ACT_GESTURE_RANGE_ATTACK1, ACT_GESTURE_RANGE_ATTACK_PISTOL, false},
{ ACT_COVER_LOW, ACT_COVER_PISTOL_LOW, false },
{ ACT_RANGE_AIM_LOW, ACT_RANGE_AIM_AR2_LOW, false },
{ ACT_RANGE_ATTACK1_LOW, ACT_RANGE_ATTACK_PISTOL_LOW, true },
{ ACT_RELOAD_LOW, ACT_RELOAD_PISTOL_LOW, false },
{ ACT_GESTURE_RELOAD, ACT_GESTURE_RELOAD_PISTOL, true },
};
IMPLEMENT_ACTTABLE( CWeaponFiveSeven ); | 38.841463 | 79 | 0.686342 | ZombieRoxtar |
8ece732793da8be7ab07619ee3af03073f8e1d3c | 1,001 | hpp | C++ | core/logging.hpp | sdulloor/cyclone | a4606bfb50fb8ce01e21f245624d2f4a98961039 | [
"Apache-2.0"
] | 7 | 2017-11-21T03:08:15.000Z | 2019-02-13T08:05:37.000Z | core/logging.hpp | IntelLabs/LogReplicationRocksDB | 74f33e9a54f3ae820060230e28c42274696bf2f7 | [
"Apache-2.0"
] | null | null | null | core/logging.hpp | IntelLabs/LogReplicationRocksDB | 74f33e9a54f3ae820060230e28c42274696bf2f7 | [
"Apache-2.0"
] | 4 | 2020-03-27T18:06:33.000Z | 2021-03-24T09:56:17.000Z | #ifndef _LOGGING_
#define _LOGGING_
#include<iostream>
#include<string>
#include<sstream>
#include<boost/thread.hpp>
#include<boost/date_time/posix_time/posix_time.hpp>
enum log_state {
fatal = 0,
error = 1,
warning = 2,
info = 3,
debug=4,
total = 5
};
static const char *log_headers[total] =
{"FATAL",
"ERROR",
"WARNING",
"INFO",
"DEBUG"};
class BOOST_LOG_TRIVIAL {
enum log_state level;
public:
std::stringstream state;
BOOST_LOG_TRIVIAL(enum log_state level_in)
:level(level_in)
{
}
template<typename T>
BOOST_LOG_TRIVIAL& operator<< (T value)
{
state << value;
return *this;
}
~BOOST_LOG_TRIVIAL()
{
std::stringstream final;
final << "<" << log_headers[level] << " ";
final << boost::posix_time::to_simple_string(boost::posix_time::microsec_clock::local_time()) << " ";
final << boost::this_thread::get_id() << "> ";
final << state.str() << std::endl;
std::cerr << final.str() << std::flush;
}
};
#endif
| 19.627451 | 105 | 0.636364 | sdulloor |
8ed1fa2a918006b038fde4fa7a9d94ec0b4ec003 | 1,635 | cpp | C++ | targets/apps/argobots_1/main.cpp | range3/spack-playground | 3220494a7ee3266c1bd1dc55b98fb08a1c7840ba | [
"Apache-2.0"
] | null | null | null | targets/apps/argobots_1/main.cpp | range3/spack-playground | 3220494a7ee3266c1bd1dc55b98fb08a1c7840ba | [
"Apache-2.0"
] | null | null | null | targets/apps/argobots_1/main.cpp | range3/spack-playground | 3220494a7ee3266c1bd1dc55b98fb08a1c7840ba | [
"Apache-2.0"
] | null | null | null |
#include <abt.h>
#include <fmt/core.h>
#include <algorithm>
#include <iostream>
#include <memory>
#include <range/v3/view.hpp>
#include <unused.hpp>
#include <vector>
using thread_arg_t = struct { size_t tid; };
void helloWorld(void* arg) {
size_t tid = reinterpret_cast<thread_arg_t*>(arg)->tid;
int rank;
ABT_xstream_self_rank(&rank);
fmt::print("Hello world! (thread = {:d}, ES = {:d})\n", tid, rank);
}
auto main(int argc, char** argv) -> int {
ABT_init(argc, argv);
constexpr int kNxstreams = 2;
constexpr int kNthreads = 8;
std::vector<ABT_xstream> xstreams{kNxstreams};
std::vector<ABT_pool> pools{xstreams.size()};
std::vector<ABT_thread> threads{kNthreads};
std::vector<thread_arg_t> thread_args{threads.size()};
size_t i;
// get primary ES
ABT_xstream_self(&xstreams[0]);
// create seconday ESs
for (auto& xstream : xstreams | ranges::views::drop(1)) {
ABT_xstream_create(ABT_SCHED_NULL, &xstream);
}
// get default pools
i = 0;
for (auto& xstream : xstreams) {
ABT_xstream_get_main_pools(xstream, 1, &pools[i]);
++i;
}
// create ULTs
i = 0;
for (auto& thread : threads) {
size_t pool_id = i % xstreams.size();
thread_args[i].tid = i;
ABT_thread_create(pools[pool_id], helloWorld, &thread_args[i],
ABT_THREAD_ATTR_NULL, &thread);
++i;
}
// Join and free ULTs.
for (auto& thread : threads) {
ABT_thread_free(&thread);
}
// Join and free secondary execution streams.
for (auto& xstream : xstreams) {
ABT_xstream_join(xstream);
ABT_xstream_free(&xstream);
}
ABT_finalize();
return 0;
}
| 22.708333 | 69 | 0.654434 | range3 |
8ed742b2a725aaeabaca5df0f7478ca02b000376 | 539 | cpp | C++ | bzoj/5104.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | bzoj/5104.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | bzoj/5104.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
int main(int argc, char const *argv[]) {
int a = 1, b = 1;
int x = read();
if (x == 1) return puts("1")&0;
for (int p = 3; p; p++) {
int c = a + b;
if (c >= 1000000009)
c -= 1000000009;
if (c == x) return printf("%d\n", p)&0;
a = b; b = c;
}
return 0;
} | 23.434783 | 60 | 0.528757 | swwind |
8ee459f7963a2eef725bd4b1b9102b9fbb011d33 | 984 | hpp | C++ | include/geometry/serialization/point_set_serialization.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | include/geometry/serialization/point_set_serialization.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | include/geometry/serialization/point_set_serialization.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include <geometry/serialization/point_serialization.hpp>
#include <serializer.hpp>
#include <deserializer.hpp>
namespace MLCMST::geometry::serialization {
class PointSetSerializer final : public Serializer< std::vector<Point> >
{
public:
PointSetSerializer();
PointSetSerializer(std::shared_ptr< Serializer<Point> > point_serializer);
~PointSetSerializer() override;
void serialize(const std::vector<Point>& points, std::ostream& stream) override;
private:
std::shared_ptr< Serializer<Point> > _point_serializer;
};
class PointSetDeserializer final : public Deserializer< std::vector<Point> >
{
public:
PointSetDeserializer();
PointSetDeserializer(std::shared_ptr< Deserializer<Point> > point_deserializer);
~PointSetDeserializer() override;
std::vector<Point> deserialize(std::istream& stream) override;
private:
std::shared_ptr< Deserializer<Point> > _point_deserializer;
};
}
| 22.363636 | 84 | 0.748984 | qaskai |
8ee56b3553ff5b363d713e64adfb0ec99cf1a37d | 10,991 | cpp | C++ | Flight_controller/HEAR_nodelet/trajectory_node.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | Flight_controller/HEAR_nodelet/trajectory_node.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | Flight_controller/HEAR_nodelet/trajectory_node.cpp | AhmedHumais/HEAR_FC | 2e9abd990757f8b14711aa4f02f5ad85698da6fe | [
"Unlicense"
] | null | null | null | #include <ros/ros.h>
#include <std_srvs/SetBool.h>
#include <hear_msgs/set_float.h>
#include <hear_msgs/set_bool.h>
#include <std_msgs/Float32.h>
#include <geometry_msgs/Point.h>
#include <std_srvs/Empty.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
const std::string dir_name = "/home/pi/Waypoints/";
const float TAKE_OFF_VELOCITY = 0.5; //in m/s
const float LAND_VELOCITY = 0.75; // in m/s
const std::string file_path_x = dir_name + "waypoints_x.csv";
const std::string file_path_y = dir_name + "waypoints_y.csv";
const std::string file_path_z = dir_name + "waypoints_z.csv";
const std::string file_path_vel_x = dir_name + "waypoints_vel_x.csv";
const std::string file_path_vel_y = dir_name + "waypoints_vel_y.csv";
const std::string file_path_acc_x = dir_name + "waypoints_acc_x.csv";
const std::string file_path_acc_y = dir_name + "waypoints_acc_y.csv";
bool start_traj = false;
bool take_off_flag = false;
bool land_flag = false;
bool send_curr_pos_opti = false;
bool send_curr_pos_slam = false;
bool on_opti = true;
float take_off_height = 1.0;
float land_height = -0.1;
geometry_msgs::Point current_pos_opti;
geometry_msgs::Point current_pos_slam;
std_msgs::Float32 current_yaw;
ros::ServiceClient height_offset_client;
bool read_file(std::string fileName, std::vector<float>& vec){
std::ifstream ifs(fileName);
if(ifs.is_open()){
std::string line;
while(std::getline(ifs, line)){
vec.push_back(std::stof(line));
}
return true;
}
return false;
}
void opti_pos_Cb(const geometry_msgs::Point::ConstPtr& msg){
current_pos_opti = *msg;
}
void slam_pos_Cb(const geometry_msgs::Point::ConstPtr& msg){
current_pos_slam = *msg;
}
void yaw_Cb(const geometry_msgs::Point::ConstPtr& msg){
current_yaw.data = msg->x;
}
bool height_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){
hear_msgs::set_float t_srv;
t_srv.request.data = current_pos_opti.z;
height_offset_client.call(t_srv);
ROS_INFO("height offset called");
return true;
}
bool take_off_Cb(hear_msgs::set_float::Request& req, hear_msgs::set_float::Response& res){
take_off_height = req.data;
ROS_INFO("take off called");
take_off_flag = true;
return true;
}
bool land_Cb(hear_msgs::set_float::Request& req, hear_msgs::set_float::Response& res){
land_height = req.data;
ROS_INFO("land called");
land_flag = true;
return true;
}
bool send_curr_pos_opti_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){
send_curr_pos_opti = true;
on_opti = true;
ROS_INFO("sending curr opti position as reference");
return true;
}
bool send_curr_pos_slam_Cb(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){
send_curr_pos_slam = true;
on_opti = false;
ROS_INFO("sending curr slam position as reference");
return true;
}
bool srvCallback(hear_msgs::set_bool::Request& req, hear_msgs::set_bool::Response& res){
start_traj = req.data;
ROS_INFO("start trajectory called");
return true;
}
int main(int argc, char **argv){
ros::init(argc, argv, "trajectory_node");
ros::NodeHandle nh;
ros::Rate rt = 100;
ros::ServiceServer srv = nh.advertiseService("start_trajectory", &srvCallback);
ros::ServiceServer takeOff_srv = nh.advertiseService("take_off", &take_off_Cb);
ros::ServiceServer land_srv = nh.advertiseService("land", &land_Cb);
ros::ServiceServer height_offset_srv = nh.advertiseService("init_height", &height_Cb);
ros::ServiceServer send_curr_pos_opti_srv = nh.advertiseService("send_curr_pos_opti", &send_curr_pos_opti_Cb);
ros::ServiceServer send_curr_pos_slam_srv = nh.advertiseService("send_curr_pos_slam", &send_curr_pos_slam_Cb);
height_offset_client = nh.serviceClient<hear_msgs::set_float>("set_height_offset");
ros::Subscriber pos_opti_sub = nh.subscribe<geometry_msgs::Point>("/opti/pos", 10, &opti_pos_Cb);
ros::Subscriber pos_slam_sub = nh.subscribe<geometry_msgs::Point>("/slam/pos", 10, &slam_pos_Cb);
ros::Subscriber yaw_sub = nh.subscribe<geometry_msgs::Point>("/providers/yaw", 10, &yaw_Cb);
ros::Publisher pub_waypoint_pos = nh.advertise<geometry_msgs::Point>("/waypoint_reference/pos", 10);
ros::Publisher pub_waypoint_yaw = nh.advertise<std_msgs::Float32>("/waypoint_reference/yaw", 10);
ros::Publisher pub_waypoint_vel = nh.advertise<geometry_msgs::Point>("/waypoint_reference/vel", 10);
ros::Publisher pub_waypoint_acc = nh.advertise<geometry_msgs::Point>("/waypoint_reference/acc", 10);
std::vector<float> wp_x, wp_y, wp_z, wp_vel_x, wp_vel_y, wp_acc_x, wp_acc_y;
bool en_wp_x, en_wp_y, en_wp_z, en_wp_vel_x, en_wp_vel_y, en_wp_acc_x, en_wp_acc_y;
if(!(read_file(file_path_x, wp_x))){
ROS_WARN("Could not read file for x waypoints.\n ...Disabling trajectory for x channel");
en_wp_x = false;
}else{ en_wp_x = true; }
if(!(read_file(file_path_y, wp_y))){
ROS_WARN("Could not read file for y waypoints.\n ...Disabling trajectory for y channel");
en_wp_y = false;
}else{ en_wp_y = true; }
if(!(read_file(file_path_z, wp_z))){
ROS_WARN("Could not read file for z waypoints.\n ...Disabling trajectory for z channel");
en_wp_z = false;
}else{ en_wp_z = true; }
if(!(read_file(file_path_vel_x, wp_vel_x))){
ROS_WARN("Could not read file for vel_x waypoints.\n ...Disabling velocity reference for x channel");
en_wp_vel_x = false;
}else{ en_wp_vel_x = true; }
if(!(read_file(file_path_vel_y, wp_vel_y))){
ROS_WARN("Could not read file for vel_y waypoints.\n ...Disabling velocity reference for y channel");
en_wp_vel_y = false;
}else{ en_wp_vel_y = true; }
if(!(read_file(file_path_acc_x, wp_acc_x))){
ROS_WARN("Could not read file for acc_x waypoints.\n ...Disabling acceleration reference for x channel");
en_wp_acc_x = false;
}else{ en_wp_acc_x = true; }
if(!(read_file(file_path_acc_y, wp_acc_y))){
ROS_WARN("Could not read file for acc_y waypoints.\n ...Disabling acceleration reference for y channel");
en_wp_acc_y = false;
}else{ en_wp_acc_y = true; }
int i = 0;
int sz_x = wp_x.size(), sz_y = wp_y.size(), sz_z = wp_z.size();
if(en_wp_vel_x){
if(wp_vel_x.size() != sz_x){
ROS_ERROR("Size of velocity reference vector is not equal to position reference");
return 1;
}
}
if(en_wp_vel_y){
if(wp_vel_y.size() != sz_y){
ROS_ERROR("Size of velocity reference vector is not equal to position reference");
return 1;
}
}
if(en_wp_acc_x){
if(wp_acc_x.size() != sz_x){
ROS_ERROR("Size of acceleration reference vector is not equal to position reference");
return 1;
}
}
if(en_wp_acc_y){
if(wp_acc_y.size() != sz_y){
ROS_ERROR("Size of acceleration reference vector is not equal to position reference");
return 1;
}
}
geometry_msgs::Point wp_pos_msg, wp_vel_msg, wp_acc_msg, offset_pos;
float z_ref = 0.0;
bool take_off_started = false;
bool land_started = false;
bool trajectory_finished = false, trajectory_started = false;
while(ros::ok()){
if(send_curr_pos_opti){
send_curr_pos_opti = false;
wp_pos_msg = current_pos_opti;
pub_waypoint_pos.publish(wp_pos_msg);
}
if(send_curr_pos_slam){
send_curr_pos_slam = false;
wp_pos_msg = current_pos_slam;
pub_waypoint_pos.publish(wp_pos_msg);
}
if(land_flag){
if(!land_started){
ROS_INFO("land started");
land_started = true;
wp_pos_msg.x = current_pos_opti.x;
wp_pos_msg.y = current_pos_opti.y;
z_ref = current_pos_opti.z - 0.1;
pub_waypoint_pos.publish(wp_pos_msg);
}
z_ref -= (rt.expectedCycleTime()).toSec()*LAND_VELOCITY;
if(z_ref <= land_height){
land_flag = false;
land_started = false;
ROS_INFO("land finished");
}else{
wp_pos_msg.z = z_ref;
pub_waypoint_pos.publish(wp_pos_msg);
}
}
else if(take_off_flag){
if(!take_off_started){
ROS_INFO("take off started");
take_off_started = true;
wp_pos_msg.x = current_pos_opti.x;
wp_pos_msg.y = current_pos_opti.y;
z_ref = current_pos_opti.z + 0.1;
pub_waypoint_pos.publish(wp_pos_msg);
pub_waypoint_yaw.publish(current_yaw);
}
z_ref += (rt.expectedCycleTime()).toSec()*TAKE_OFF_VELOCITY;
if(z_ref >= take_off_height){
take_off_flag = false;
take_off_started = false;
ROS_INFO("take off finished");
}
else{
wp_pos_msg.z = z_ref;
pub_waypoint_pos.publish(wp_pos_msg);
}
}
else if(start_traj){
trajectory_finished = true;
if(!trajectory_started){
ROS_INFO("Trajectory Started");
trajectory_started = true;
if(on_opti){
offset_pos = current_pos_opti;
}else {
offset_pos = current_pos_slam;
}
}
if(i < sz_x && en_wp_x){
wp_pos_msg.x = wp_x[i] + offset_pos.x;
if(en_wp_vel_x){
wp_vel_msg.x = wp_vel_x[i];
}
if(en_wp_acc_x){
wp_acc_msg.x = wp_acc_x[i];
}
trajectory_finished = false;
}
if(i < sz_y && en_wp_y){
wp_pos_msg.y = wp_y[i] + offset_pos.y;
if(en_wp_vel_y){
wp_vel_msg.y = wp_vel_y[i];
}
if(en_wp_acc_y){
wp_acc_msg.y = wp_acc_y[i];
}
trajectory_finished = false;
}
if(i < sz_z && en_wp_z){
wp_pos_msg.z = wp_z[i];
trajectory_finished = false;
}
if(trajectory_finished){
ROS_INFO("Trajectory finished");
start_traj = false;
trajectory_started = false;
i = 0;
} else {
pub_waypoint_pos.publish(wp_pos_msg);
pub_waypoint_vel.publish(wp_vel_msg);
pub_waypoint_acc.publish(wp_acc_msg);
i++;
}
}
rt.sleep();
ros::spinOnce();
}
} | 36.036066 | 114 | 0.61514 | AhmedHumais |
8eeaa453dfee7eb78ccbc6267bd696e73e1e496b | 1,542 | cpp | C++ | src/QGCQmlWidgetHolder.cpp | DonLakeFlyer/PDCDogDatabase | 23700d16f21005b84738887d98c6c9c368b9eb6f | [
"Apache-2.0"
] | null | null | null | src/QGCQmlWidgetHolder.cpp | DonLakeFlyer/PDCDogDatabase | 23700d16f21005b84738887d98c6c9c368b9eb6f | [
"Apache-2.0"
] | null | null | null | src/QGCQmlWidgetHolder.cpp | DonLakeFlyer/PDCDogDatabase | 23700d16f21005b84738887d98c6c9c368b9eb6f | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "QGCQmlWidgetHolder.h"
#include <QQmlContext>
#include <QQmlError>
QGCQmlWidgetHolder::QGCQmlWidgetHolder(const QString& title, QAction* action, QWidget *parent) :
QWidget(parent)
{
_ui.setupUi(this);
layout()->setContentsMargins(0,0,0,0);
setResizeMode(QQuickWidget::SizeRootObjectToView);
}
QGCQmlWidgetHolder::~QGCQmlWidgetHolder()
{
}
bool QGCQmlWidgetHolder::setSource(const QUrl& qmlUrl)
{
bool success = _ui.qmlWidget->setSource(qmlUrl);
for (QQmlError error: _ui.qmlWidget->errors()) {
qDebug() << "Error" << error.toString();
}
return success;
}
void QGCQmlWidgetHolder::setContextPropertyObject(const QString& name, QObject* object)
{
_ui.qmlWidget->rootContext()->setContextProperty(name, object);
}
QQmlContext* QGCQmlWidgetHolder::getRootContext(void)
{
return _ui.qmlWidget->rootContext();
}
QQuickItem* QGCQmlWidgetHolder::getRootObject(void)
{
return _ui.qmlWidget->rootObject();
}
QQmlEngine* QGCQmlWidgetHolder::getEngine()
{
return _ui.qmlWidget->engine();
}
void QGCQmlWidgetHolder::setResizeMode(QQuickWidget::ResizeMode resizeMode)
{
_ui.qmlWidget->setResizeMode(resizeMode);
}
| 24.870968 | 96 | 0.659533 | DonLakeFlyer |
8eee3f2db028e9df12a5ffe16c14f15f4cf61b72 | 2,250 | cpp | C++ | XGF/Src/Core/Asyn.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | 5 | 2017-11-09T05:02:52.000Z | 2020-06-23T09:50:25.000Z | XGF/Src/Core/Asyn.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | XGF/Src/Core/Asyn.cpp | kadds/XGF | 610c98a93c0f287546f97efc654b95dc846721ad | [
"MIT"
] | null | null | null | #include "../../Include/Asyn.hpp"
#include <chrono>
#include "../../Include/Timer.hpp"
#include "../../Include/Logger.hpp"
namespace XGF {
Asyn::Asyn()
{
}
Asyn::~Asyn()
{
}
void Asyn::PostEvent(EventIdType id, EventGroupType evGroup, std::initializer_list< EventDataType> init)
{
if (mIsExit) return;
mMessageQueue.enqueue(Event(evGroup, id, init));
}
EventGroupType GetType(EventIdType t)
{
if (std::get_if<SystemEventId>(&t) != nullptr)
return EventGroupType::System;
if (std::get_if<KeyBoardEventId>(&t) != nullptr)
return EventGroupType::KeyBoard;
if (std::get_if<MouseEventId>(&t) != nullptr)
return EventGroupType::Mouse;
return EventGroupType::Custom;
}
void Asyn::PostEvent(EventIdType id, std::initializer_list<EventDataType> init)
{
PostEvent(id, GetType(id), init);
}
void Asyn::PostExitEvent()
{
mIsExit = true;
mMessageQueue.enqueue(Event(EventGroupType::System, SystemEventId::Exit, {}));
}
void Asyn::Wait()
{
auto m = std::unique_lock<std::mutex>(mutex);
mcVariable.wait(m);
}
void Asyn::Wait(unsigned long long microseconds)
{
auto m = std::unique_lock<std::mutex>(mutex);
mcVariable.wait_for(m, std::chrono::microseconds(microseconds));
}
void Asyn::Wait(std::function<bool()> predicate)
{
auto m = std::unique_lock<std::mutex>(mutex);
mcVariable.wait(m, predicate);
}
void Asyn::Notify()
{
mcVariable.notify_all();
}
void Asyn::DoAsyn(std::function<void(Asyn * asyn)> fun)
{
mThread = std::make_unique<std::thread>(fun, this);
mId = mThread->get_id();
mThread->detach();
}
bool Asyn::HandleMessage()
{
Event ev;
Timer timer;
float dt = 0;
while(mMessageQueue.try_dequeue(ev))
{
if (ev.GetEventGroup() == EventGroupType::System && ev.GetSystemEventId() == SystemEventId::Exit)
{
return true;
}
else
{
mHandleCallback(ev);
}
dt += timer.Tick();
if (dt > 0.001f)
{
break;
//XGF_Info(Framework, "Handle event time is too long ", time * 1000, "ms");
}
}
return false;
}
void Asyn::Sleep(unsigned long long microseconds)
{
auto d = std::chrono::microseconds(microseconds);
std::this_thread::sleep_for(d);
}
std::thread::id Asyn::GetThreadId() const
{
return mId;
}
}
| 21.028037 | 105 | 0.662667 | kadds |
8eef2a200c768a99ab2f01a79ee34ea8cc9e36a4 | 938 | cpp | C++ | src/allocateMem.cpp | neilenns/MobiFlight-FirmwareSource | af4d771ab26e8633f338298805e6fe56a855aa85 | [
"MIT"
] | 2 | 2022-03-07T08:10:51.000Z | 2022-03-08T20:59:45.000Z | src/allocateMem.cpp | Jak-Kav/MobiFlight-FirmwareSource | fb14a2e134d12bbd26b18e15dd1e5fa16063c97a | [
"MIT"
] | 13 | 2021-10-03T07:14:38.000Z | 2021-10-14T14:11:42.000Z | src/allocateMem.cpp | Jak-Kav/MobiFlight-FirmwareSource | fb14a2e134d12bbd26b18e15dd1e5fa16063c97a | [
"MIT"
] | 1 | 2021-10-16T15:57:18.000Z | 2021-10-16T15:57:18.000Z | #include <Arduino.h>
#include "MFBoards.h"
#include "mobiflight.h"
#include "allocateMem.h"
#include "commandmessenger.h"
char deviceBuffer[MF_MAX_DEVICEMEM] = {0};
uint16_t nextPointer = 0;
char * allocateMemory(uint8_t size)
{
uint16_t actualPointer = nextPointer;
nextPointer = actualPointer + size;
if (nextPointer >= MF_MAX_DEVICEMEM)
{
cmdMessenger.sendCmd(kStatus,F("DeviceBuffer Overflow!"));
return nullptr;
}
#ifdef DEBUG2CMDMESSENGER
cmdMessenger.sendCmdStart(kStatus);
cmdMessenger.sendCmdArg(F("BufferUsage"));
cmdMessenger.sendCmdArg(nextPointer);
cmdMessenger.sendCmdEnd();
#endif
return &deviceBuffer[actualPointer];
}
void ClearMemory() {
nextPointer = 0;
}
uint16_t GetAvailableMemory() {
return MF_MAX_DEVICEMEM - nextPointer;
}
bool FitInMemory(uint8_t size) {
if (nextPointer + size > MF_MAX_DEVICEMEM)
return false;
return true;
}
| 22.878049 | 66 | 0.712154 | neilenns |
8ef60df2a1095a38a703f3b4dca398e357701095 | 240 | hpp | C++ | levels/rocketball/rocketball.hpp | piotrplaza/MouseSpaceShooter | 9aed0c16889b6ce70e725c165bf28307201e81d1 | [
"MIT"
] | null | null | null | levels/rocketball/rocketball.hpp | piotrplaza/MouseSpaceShooter | 9aed0c16889b6ce70e725c165bf28307201e81d1 | [
"MIT"
] | null | null | null | levels/rocketball/rocketball.hpp | piotrplaza/MouseSpaceShooter | 9aed0c16889b6ce70e725c165bf28307201e81d1 | [
"MIT"
] | 1 | 2020-06-16T10:32:06.000Z | 2020-06-16T10:32:06.000Z | #pragma once
#include <memory>
#include "../level.hpp"
namespace Levels
{
class Rocketball: public Level
{
public:
Rocketball();
~Rocketball();
void step() override;
private:
class Impl;
std::unique_ptr<Impl> impl;
};
}
| 10.909091 | 31 | 0.658333 | piotrplaza |
8efdf2d451fbf9fa2d5f5a722b548439c4daa461 | 3,302 | cpp | C++ | src/wiggleDetector.cpp | malachi-iot/washer-monitor | af7786bbb204bf6dc31c30b759a82910feb6e946 | [
"MIT"
] | null | null | null | src/wiggleDetector.cpp | malachi-iot/washer-monitor | af7786bbb204bf6dc31c30b759a82910feb6e946 | [
"MIT"
] | null | null | null | src/wiggleDetector.cpp | malachi-iot/washer-monitor | af7786bbb204bf6dc31c30b759a82910feb6e946 | [
"MIT"
] | null | null | null | //
// Created by malachi on 2/22/17.
//
#include <Arduino.h>
#include <fact/CircularBuffer.h>
#include <SimpleTimer.h>
#include "state.h"
namespace util = FactUtilEmbedded;
const int SENSOR_PIN = 13;
volatile uint16_t wigglesDetected = 0;
util::layer1::CircularBuffer<uint16_t, 60> wigglesPerSecond;
util::layer1::CircularBuffer<uint32_t, 60> wigglesPerMinute;
// Utilize this if we want idle state to be HIGH (utilizing "weak" internal pullup)
// This mode means wiggle detection will go to LOW/ground when activated
// UNTESTED
#define WIGGLE_IDLE_HIGH
void wiggleDetector()
{
wigglesDetected++;
}
void wiggleDetector_setup()
{
#ifdef WIGGLE_IDLE_HIGH
pinMode(SENSOR_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), wiggleDetector, FALLING);
#else
pinMode(SENSOR_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), wiggleDetector, RISING);
#endif
}
// FIX: Some kind of odd alignment issue if I use a uint8_t here, so kludging it
// and using a uint32_t . I expect is related to above CircularBuffers perhaps not landing
// on perfect alignments
//__attribute__((section(".iram0.text"))) uint8_t minutesCounter = 0;
uint32_t minutesCounter = 0;
int wiggleTimeoutTimer = -1;
extern SimpleTimer timer;
// In seconds
#define WIGGLE_TIMEOUT (60 * 5)
void wiggle_stop_event()
{
state_change(State::NotifyingTimeout);
// specifically do not requeue stop event, instead let threshold manager do that
wiggleTimeoutTimer = -1;
}
void wiggle_set_detector_timeout()
{
wiggleTimeoutTimer = timer.setTimeout(WIGGLE_TIMEOUT * 1000, wiggle_stop_event);
}
uint32_t getTotalWigglesInLast60Seconds();
uint32_t getTotalWigglesInLast5Minutes();
void printWiggleStatus()
{
// represents number of wiggles detected since last we entered detected state
static uint32_t wd_timeout = 0;
uint16_t wd = wigglesDetected;
// FIX: we should divide up things that have side effects outside of
// printWiggleStatus
if(wd > 0)
{
// we must get more than a "little" bit of wiggling to think that stuff is shaking
// will need fine tuning
// also wiggleTimeoutTimer == -1 means we are not initialized/listening for a timeout
if(wd > 5 && wiggleTimeoutTimer != -1)
{
state_change(State::Detected);
timer.restartTimer(wiggleTimeoutTimer);
}
// Side effect
wigglesDetected = 0;
}
wigglesPerSecond.put(wd);
uint32_t wd60s = getTotalWigglesInLast60Seconds();
Serial.print("Wiggles detected/second (");
Serial.print(minutesCounter);
Serial.print("): ");
Serial.print(wd);
Serial.print(" of ");
Serial.print(wd60s);
Serial.println(" in the last 60 seconds");
if(++minutesCounter == 60)
{
wigglesPerMinute.put(wd60s);
Serial.print("Wiggles in last minute: ");
Serial.println(wd60s);
minutesCounter = 0;
}
}
template <class TArray>
uint32_t array_sum(const TArray& array, uint16_t size)
{
uint32_t total = 0;
for(int i = 0; i < size; i++)
{
total += array[i];
}
return total;
}
uint32_t getTotalWigglesInLast60Seconds()
{
auto array = wigglesPerSecond.getUnderlyingArray();
return array_sum(array, 60);
}
| 24.279412 | 93 | 0.698365 | malachi-iot |
f106aff47a1ae4cd247c4fed7146af25c047dd6f | 2,966 | cpp | C++ | 02-functions-and-libs/readerEx.02.07/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 81 | 2018-11-15T21:23:19.000Z | 2022-03-06T09:46:36.000Z | 02-functions-and-libs/readerEx.02.07/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | null | null | null | 02-functions-and-libs/readerEx.02.07/main.cpp | heavy3/programming-abstractions | e10eab5fe7d9ca7d7d4cc96551524707214e43a8 | [
"MIT"
] | 41 | 2018-11-15T21:23:24.000Z | 2022-02-24T03:02:26.000Z | //
// main.cpp
//
// This program implements the sqrt() function for taking the square root
// of a number using the following successive approximation technique:
//
// 1. Begin by guessing that the square root is x / 2. Call that guess g.
//
// 2. The actual square root must lie between g and x / g.
// At each step in the successive approximation, generate a new guess
// by averaging g and x / g.
//
// 3. Repeat step 2 until the values g and x / g are as close together as the
// machine precision allows. In C++, the best way to check for this
// condition is to test whether the average is equal to either of the values
// used to generate it.
//
// --------------------------------------------------------------------------
// Attribution: "Programming Abstractions in C++" by Eric Roberts
// Chapter 2, Exercise 7
// Stanford University, Autumn Quarter 2012
// http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf
// --------------------------------------------------------------------------
//
// Created by Glenn Streiff on 9/18/15.
// Copyright © 2015 Glenn Streiff. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <string>
// Function prototypes
double sqrt(double n);
bool refineGuess(double n, double & nextGuess);
void error(std::string msg);
// Main program
int main(int argc, char * argv[]) {
double n = 10;
double answer = sqrt(n);
std::cout << "sqrt(" << n << ") = " << answer << std::endl;
return 0;
}
// Function definitions
//
// Function: sqrt
// Usage: double d = sqrt(9);
// --------------------------
// Returns square root of a number.
//
double sqrt(double n) {
double guess = n / 2.0;
if (n < 0) {
error("square root of a negative number is undefined");
}
if (n == 0) {
return 0; // short circuit to avoid divide by 0;
}
while(refineGuess(n, guess)) continue;
return guess;
}
//
// Function: refineGuess
// Usage: double n = 9;
// double nextGuess = n/2.0;
// while (refineGuess(n, nextGuess)) continue;
// ---------------------------------------------------
// Returns true once a successive approximation algorithm
// has convered on an answer to within the accuracy supported
// by the machine.
//
// When the routine converges on an answer and returns boolean
// false, the pass by reference variable, g, will hold the
// approximate solution.
//
bool refineGuess(double x, double & g) {
double nextG = (g + x/g) / 2.0;
if (nextG == g) {
return false;
} else {
g = nextG;
return true;
}
}
//
// Function: error
// Usage: error("Something bad happened. Exitting.");
// ---------------------------------------------------
// Exits program with the standard failure code EXIT_FAILURE
// defined in <cstdlib>.
//
void error(std::string msg) {
std::cerr << msg << std::endl;
exit(EXIT_FAILURE);
} | 26.963636 | 91 | 0.58294 | heavy3 |
f10b116eee8ffd2d0bf1142c06cb1c9e980da5e8 | 3,075 | cpp | C++ | 9.29.7.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 9.29.7.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 9.29.7.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | // merge two shorted linked list
// by using the dummy node
#include<stdio.h>
#include<stdlib.h> // for malloc function stdlib .h will support it accordingly
struct node
{
int data;
struct node* next;
};
void push(struct node **head,int data1) // here i am passing the address of the pointer to the struct node so that we can change the valueof the struct node
{
// fist of all we have to create a new node
struct node* newnode=NULL;
// now allocates memory to it
newnode=(struct node*)malloc(sizeof(struct node));
// set the data of the newnode
newnode->data=data1;
newnode->next=*head;
*head=newnode;
}
void printlinkedlist(struct node* head)
{
// now we have to print the node one by one
/* if(head==NULL)
{
return;
}*/
while(head!=NULL)
{
printf("%d",head->data);
head=head->next; // pointing to the next address
}
}
// function for merging shorted linked list
// solving by using the dummy node
// the idea behind it is taking the one sphere node
// call it dummy node
// now use the pointer to this node to create the linked list as the starting address
// in this the whole linked list is created in the sense
// that new node is created every time and then it is attached to the address of the dummy node
// at last when one list becomes empty then the address of the next node is appended to the address of the dummy node reached
// here we have to create 2 function one is the main function and second is the
// function used to move the node from source to destination
// which is the dummy node next
// now lets start
void movenode(struct node** second, struct node** first)
{
// data is moved form first to second
// we i have to use the asset
// when the first is empty list
// in the geeks for geeks it is written but i am unable to understand
struct node* newnode=*first;
*first=newnode->next;
newnode->next=*second;
*second=newnode;
}
struct node* mergeshortedlinkedlist(struct node**head1, struct node** head2)
{
struct node dummy;
struct node* tail=&dummy;
dummy.next=NULL;
while(1)
{
if(*head1==NULL)
{
tail->next=*head2;
break;
}
else if(*head2==NULL)
{
tail->next=*head1;
break;
}
if((*head1)->data<=(*head2)->data)
{
movenode(&(tail->next),head1);
}
else
{
movenode(&(tail->next),head2);
}
tail=tail->next;
}
return dummy.next;
}
int main()
{
struct node*head1=NULL;
struct node*head2=NULL;
struct node*head3=NULL;
push(&head1,8);
push(&head1,6);
push(&head1,4);
push(&head1,1);
push(&head2,7);
push(&head2,5);
push(&head2,3);
push(&head2,2);
printlinkedlist(head1);
printf("\n");
printlinkedlist(head2);
printf("\n");
printlinkedlist(head1);
printf("\n\n\n");
head3 = mergeshortedlinkedlist(&head1,&head2);
printlinkedlist(head3);
}
| 26.508621 | 157 | 0.625366 | luckylove |
f10c6dd590deb8c07b296a3e9b9a6c77a397d68a | 1,079 | cpp | C++ | codes/HDU/hdu4649.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu4649.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu4649.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 205;
double P[maxn], dp[maxn][2];
int N, A[maxn];
char sig[maxn][2];
double solve (int bit, double s) {
dp[0][0] = 1 - s, dp[0][1] = s;
for (int i = 1; i <= N; i++) {
for (int j = 0; j < 2; j++)
dp[i][j] = dp[i-1][j] * P[i];
double p = 1 - P[i];
int v = (A[i]>>bit)&1;
if (sig[i][0] == '&') {
dp[i][v&0] += dp[i-1][0] * p;
dp[i][v&1] += dp[i-1][1] * p;
} else if (sig[i][0] == '|') {
dp[i][v|0] += dp[i-1][0] * p;
dp[i][v|1] += dp[i-1][1] * p;
} else {
dp[i][v^0] += dp[i-1][0] * p;
dp[i][v^1] += dp[i-1][1] * p;
}
}
return dp[N][1];
}
int main () {
int cas = 1, s;
while (scanf("%d", &N) == 1) {
scanf("%d", &s);
for (int i = 1; i <= N; i++) scanf("%d", &A[i]);
for (int i = 1; i <= N; i++) scanf("%s", sig[i]);
for (int i = 1; i <= N; i++) scanf("%lf", &P[i]);
double ans = 0;
for (int i = 0; i <= 20; i++)
ans += solve(i, (s>>i)&1) * (1<<i);
printf("Case %d:\n%.6lf\n", cas++, ans);
}
return 0;
}
| 21.58 | 51 | 0.437442 | JeraKrs |
f10cec96038fa56d2dc5f19e933b1745930dca38 | 1,273 | cpp | C++ | tests/test050.cpp | mjj29/rapidcsv | d717299b59d19c421b3bb023e890b33000016a9c | [
"BSD-3-Clause"
] | 1 | 2020-01-13T17:39:20.000Z | 2020-01-13T17:39:20.000Z | tests/test050.cpp | mjj29/rapidcsv | d717299b59d19c421b3bb023e890b33000016a9c | [
"BSD-3-Clause"
] | null | null | null | tests/test050.cpp | mjj29/rapidcsv | d717299b59d19c421b3bb023e890b33000016a9c | [
"BSD-3-Clause"
] | 1 | 2019-12-14T12:07:48.000Z | 2019-12-14T12:07:48.000Z | // test050.cpp - read column header / label by index
#include <rapidcsv.h>
#include "unittest.h"
int main()
{
int rv = 0;
std::string csv =
"-,A,B,C\n"
"1,3,9,81\n"
"2,4,16,256\n"
;
std::string path = unittest::TempPath();
unittest::WriteFile(path, csv);
try
{
rapidcsv::Document doc(path);
unittest::ExpectEqual(std::string, doc.GetColumnName(0), "A");
unittest::ExpectEqual(std::string, doc.GetColumnName(1), "B");
unittest::ExpectEqual(std::string, doc.GetColumnName(2), "C");
ExpectException(doc.GetColumnName(3), std::out_of_range);
rapidcsv::Document doc2(path, rapidcsv::LabelParams(-1, -1));
ExpectException(doc2.GetColumnName(0), std::out_of_range);
rapidcsv::Document doc3(path, rapidcsv::LabelParams(0, -1));
unittest::ExpectEqual(std::string, doc3.GetColumnName(0), "-");
unittest::ExpectEqual(std::string, doc3.GetColumnName(1), "A");
unittest::ExpectEqual(std::string, doc3.GetColumnName(2), "B");
unittest::ExpectEqual(std::string, doc3.GetColumnName(3), "C");
ExpectException(doc3.GetColumnName(4), std::out_of_range);
}
catch(const std::exception& ex)
{
std::cout << ex.what() << std::endl;
rv = 1;
}
unittest::DeleteFile(path);
return rv;
}
| 26.520833 | 67 | 0.649647 | mjj29 |
f10d654211dcb5c0b5131f29e7d40ff19dd249a3 | 5,659 | cpp | C++ | STL & Sorting Algorithm/Vector.cpp | FattyMieo/Semester-3 | 29498bfca2aaca84e4595510bbc21a6043b16d77 | [
"MIT"
] | 1 | 2017-05-12T19:46:57.000Z | 2017-05-12T19:46:57.000Z | STL & Sorting Algorithm/Vector.cpp | FattyMieo/Semester-3 | 29498bfca2aaca84e4595510bbc21a6043b16d77 | [
"MIT"
] | null | null | null | STL & Sorting Algorithm/Vector.cpp | FattyMieo/Semester-3 | 29498bfca2aaca84e4595510bbc21a6043b16d77 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib> // same as stdlib.h (old)
#include <ctime> // same as time.h (old)
#include <vector>
#include <limits>
using namespace std;
vector<char> charVector;
void DisplayVector()
{
for(int i = 0; i < charVector.size(); i++)
{
cout << "[" << (i < 10 ? "0" : "") << i << "] " << charVector[i] << endl;
}
}
void PushToBackVector()
{
char character;
cout << " @ Please input a character" << endl;
cout << "> ";
cin >> character;
cout << endl;
charVector.push_back(character);
}
void PushToFrontVector()
{
char character;
cout << " @ Please input a character" << endl;
cout << "> ";
cin >> character;
cout << endl;
charVector.insert(charVector.begin(), character);
}
void PushToVector()
{
char character;
cout << " @ Please input a character" << endl;
cout << "> ";
cin >> character;
cout << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int i = -1;
while(true)
{
cout << " @ Where do you want to place it?" << endl;
cout << "> ";
cin >> i;
if(cin.good() && i >= 0)
{
if(i >= charVector.size())
{
charVector.resize(i + 1, ' ');
}
charVector.insert(charVector.begin() + i, character);
break;
}
else
{
cout << "Wrong Input!" << endl;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl;
}
}
void PopFromBackVector()
{
if(!charVector.empty())
{
charVector.pop_back();
}
else
{
cout << "Vector is empty!" << endl;
system("PAUSE");
}
}
void PopFromFrontVector()
{
if(!charVector.empty())
{
charVector.erase(charVector.begin());
}
else
{
cout << "Vector is empty!" << endl;
system("PAUSE");
}
}
void PopFromVector()
{
if(!charVector.empty())
{
int i = -1;
while(true)
{
cout << " @ Where do you want to erase?" << endl;
cout << "> ";
cin >> i;
if(cin.good() && i >= 0)
{
if(i < charVector.size())
{
charVector.erase(charVector.begin() + i);
}
else
{
cout << "Nothing to erase!" << endl;
system("PAUSE");
}
break;
}
else
{
cout << "Wrong Input!" << endl;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl;
}
}
else
{
cout << "Vector is empty!" << endl;
system("PAUSE");
}
}
void SwapCharacters()
{
int i = -1;
int j = -1;
while(true)
{
cout << " @ Which characters to be swapped?" << endl;
cout << "> ";
cin >> i >> j;
if(cin.good() && i >= 0 && j >= 0)
{
if(i == j)
{
cout << "Cannot swap with the same index." << endl;
system("PAUSE");
}
else if(i < charVector.size() && j < charVector.size())
{
char tmp = charVector[i];
charVector[i] = charVector[j];
charVector[j] = tmp;
break;
}
else if(i < charVector.size())
{
charVector.resize(j + 1, ' ');
charVector[j] = charVector[i];
charVector[i] = ' ';
break;
}
else if(j < charVector.size())
{
charVector.resize(i + 1, ' ');
charVector[i] = charVector[j];
charVector[j] = ' ';
break;
}
else
{
cout << "Both characters are not existing!" << endl;
system("PAUSE");
}
break;
}
else
{
cout << "Wrong Input!" << endl;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl;
}
}
void ReverseOrder()
{
int i = 0, j = charVector.size() - 1;
while(i < j)
{
char tmp = charVector[i];
charVector[i] = charVector[j];
charVector[j] = tmp;
i++; j--;
}
}
void DeleteEmptyCharacters()
{
for(int i = 0; i < charVector.size(); i++)
{
if(charVector[i] == ' ')
charVector.erase(charVector.begin() + i--);
}
}
void ClearVector()
{
charVector.clear();
}
void PopEmptyBehindVector()
{
for(int i = charVector.size() - 1; i >= 0; i--)
{
if(charVector[i] == ' ')
charVector.pop_back();
else
break;
}
}
void DoChoice(int choice)
{
switch(choice)
{
case 1:
PushToBackVector();
break;
case 2:
PushToFrontVector();
break;
case 3:
PushToVector();
break;
case 4:
PopFromBackVector();
break;
case 5:
PopFromFrontVector();
break;
case 6:
PopFromVector();
break;
case 7:
SwapCharacters();
break;
case 8:
ReverseOrder();
break;
case 9:
DeleteEmptyCharacters();
break;
case 10:
ClearVector();
break;
default:
break;
}
}
int main()
{
srand(time(NULL));
int randomSize = rand() % 7 + 3;
for(int i = 0; i < randomSize; i++)
{
charVector.push_back(i + 65);
}
int choice = -1;
do
{
system("CLS");
DisplayVector();
cout << "==========================================" << endl;
cout << " 1. Add character to the back" << endl;
cout << " 2. Add character to the front" << endl;
cout << " 3. Add character at specific index" << endl;
cout << " 4. Remove character from the back" << endl;
cout << " 5. Remove character from the front" << endl;
cout << " 6. Remove character at specific index" << endl;
cout << " 7. Swap character at specific indexes" << endl;
cout << " 8. Reverse order" << endl;
cout << " 9. Delete all empty characters" << endl;
cout << " 10. Delete all characters" << endl;
cout << endl;
cout << " -1. Exit Program" << endl;
cout << "==========================================" << endl;
cout << " @ What would you like to do?" << endl;
cout << "> ";
cin >> choice;
cout << endl;
if(cin.good())
{
DoChoice(choice);
PopEmptyBehindVector();
}
else
{
cout << "Wrong Input!" << endl;
system("PAUSE");
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while(choice != -1);
return 0;
}
| 17.148485 | 75 | 0.545856 | FattyMieo |
f10ddf0f79d7e4cd24e51978d40b0ce6be9cea81 | 751 | hpp | C++ | example/Timer.hpp | BetaJester/nopengl | 6220eab842db531d275e7c0f9276992d22170e3a | [
"MIT"
] | null | null | null | example/Timer.hpp | BetaJester/nopengl | 6220eab842db531d275e7c0f9276992d22170e3a | [
"MIT"
] | null | null | null | example/Timer.hpp | BetaJester/nopengl | 6220eab842db531d275e7c0f9276992d22170e3a | [
"MIT"
] | null | null | null | // Copyright (C) 2021 Glenn Duncan <[email protected]>
// See README.md, LICENSE, or go to https://github.com/BetaJester/nopengl
// for details.
#pragma once
#include <chrono>
#include <concepts>
template<std::floating_point T>
class [[nodiscard]] Timer final {
std::chrono::high_resolution_clock::time_point timeLast{ std::chrono::high_resolution_clock::now() };
std::chrono::duration<T> timeElapsed;
public:
void tick() noexcept {
std::chrono::high_resolution_clock::time_point timeNow = std::chrono::high_resolution_clock::now();
timeElapsed = timeNow - timeLast;
timeLast = timeNow;
}
T elapsed() const noexcept {
return timeElapsed.count();
}
}; | 25.896552 | 108 | 0.661784 | BetaJester |
f10e4f51bce8cc153d79154dfe45f610abe162b5 | 728 | cpp | C++ | A2OnlineJudge/Ladder_1400_1499/Median.cpp | seeva92/Competitive-Programming | 69061c5409bb806148616fe7d86543e94bf76edd | [
"Apache-2.0"
] | null | null | null | A2OnlineJudge/Ladder_1400_1499/Median.cpp | seeva92/Competitive-Programming | 69061c5409bb806148616fe7d86543e94bf76edd | [
"Apache-2.0"
] | null | null | null | A2OnlineJudge/Ladder_1400_1499/Median.cpp | seeva92/Competitive-Programming | 69061c5409bb806148616fe7d86543e94bf76edd | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
typedef long long ll;
const int mod = 1e9 + 7;
const int MAX = 1e5 + 7;
using namespace std;
typedef vector<int> vi;
class Median
{
public:
int n, x;
vector<int> arr;
void solve() {
cin >> n >> x;
int val;
for (int i = 0; i < n; i++) {
cin >> val; arr.push_back(val);
}
sort(arr.begin(), arr.end());
int cnt = 0;
while (arr[(arr.size() - 1) / 2] != x) {
cnt++;
arr.push_back(x);
sort(arr.begin(), arr.end());
}
cout << cnt;
}
};
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin);
freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
Median m; m.solve();
}
| 19.157895 | 65 | 0.596154 | seeva92 |
f111e135a21497ed46ed960a65d78879f8af88e9 | 3,253 | cpp | C++ | src/CommandHandlers.cpp | Helios-vmg/BorderlessAnimator | 6d73e1806d84e35711a4dd030f367e533e549d8b | [
"BSD-2-Clause"
] | null | null | null | src/CommandHandlers.cpp | Helios-vmg/BorderlessAnimator | 6d73e1806d84e35711a4dd030f367e533e549d8b | [
"BSD-2-Clause"
] | null | null | null | src/CommandHandlers.cpp | Helios-vmg/BorderlessAnimator | 6d73e1806d84e35711a4dd030f367e533e549d8b | [
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c), Helios
All rights reserved.
Distributed under a permissive license. See COPYING.txt for details.
*/
#include "ImageViewerApplication.h"
#include "MainWindow.h"
#include "Script.h"
#include <sstream>
void ImageViewerApplication::handle_load(const QStringList &args){
if (args.size() < 4)
return;
this->main_window->load(args[2], args[3].toStdString());
}
void ImageViewerApplication::handle_scale(const QStringList &args){
if (args.size() < 4)
return;
auto name = args[2].toStdString();
auto scale = expect_real(args[3]);
auto window = this->main_window->get_window(name);
if (!window)
return;
window->set_scale(scale);
}
void ImageViewerApplication::handle_setorigin(const QStringList &args){
if (args.size() < 5)
return;
auto name = args[2].toStdString();
auto x = expect_integer(args[3]);
auto y = expect_integer(args[4]);
auto window = this->main_window->get_window(name);
if (!window)
return;
window->set_origin(x, y);
}
void ImageViewerApplication::handle_move(const QStringList &args){
if (args.size() < 5)
return;
auto name = args[2].toStdString();
auto x = expect_relabs_integer(args[3]);
auto y = expect_relabs_integer(args[4]);
auto window = this->main_window->get_window(name);
if (!window)
return;
window->move_by_command(set(window->get_position(), x, y));
}
void ImageViewerApplication::handle_rotate(const QStringList &args){
if (args.size() < 4)
return;
auto name = args[2].toStdString();
auto theta = expect_relabs_real(args[3]);
auto window = this->main_window->get_window(name);
if (!window)
return;
auto rotation = window->get_rotation();
if (theta.second)
rotation += theta.first;
else
rotation = theta.first;
window->set_rotation(rotation);
}
void ImageViewerApplication::handle_animmove(const QStringList &args){
if (args.size() < 6)
return;
auto name = args[2].toStdString();
auto x = expect_integer(args[3]);
auto y = expect_integer(args[4]);
auto speed = expect_real(args[5]);
auto window = this->main_window->get_window(name);
if (!window)
return;
window->anim_move(x, y, speed);
}
void ImageViewerApplication::handle_animrotate(const QStringList &args){
if (args.size() < 4)
return;
auto name = args[2].toStdString();
auto speed = expect_real(args[3]);
auto window = this->main_window->get_window(name);
if (!window)
return;
window->anim_rotate(speed);
}
void ImageViewerApplication::handle_fliph(const QStringList &args){
if (args.size() < 2)
return;
auto name = args[2].toStdString();
auto window = this->main_window->get_window(name);
if (!window)
return;
window->fliph();
}
void ImageViewerApplication::handle_flipv(const QStringList &args){
if (args.size() < 3)
return;
auto name = args[2].toStdString();
auto window = this->main_window->get_window(name);
if (!window)
return;
window->flipv();
}
void ImageViewerApplication::handle_loadscript(const QStringList &args){
if (args.size() < 4)
return;
auto name = args[2].toStdString();
auto &path = args[3];
auto window = this->main_window->get_window(name);
if (!window)
return;
window->load_script(path);
}
| 25.414063 | 73 | 0.682754 | Helios-vmg |
f1122b0f1c354a887a6ab28ffc007360f2f3673c | 1,213 | hpp | C++ | include/codegen/include/System/UriParser_BuiltInUriParser.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/UriParser_BuiltInUriParser.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/UriParser_BuiltInUriParser.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.UriParser
#include "System/UriParser.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Skipping declaration: UriSyntaxFlags because it is already included!
}
// Completed forward declares
// Type namespace: System
namespace System {
// Autogenerated type: System.UriParser/BuiltInUriParser
class UriParser::BuiltInUriParser : public System::UriParser {
public:
// System.Void .ctor(System.String lwrCaseScheme, System.Int32 defaultPort, System.UriSyntaxFlags syntaxFlags)
// Offset: 0x1957DA8
static UriParser::BuiltInUriParser* New_ctor(::Il2CppString* lwrCaseScheme, int defaultPort, System::UriSyntaxFlags syntaxFlags);
}; // System.UriParser/BuiltInUriParser
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::UriParser::BuiltInUriParser*, "System", "UriParser/BuiltInUriParser");
#pragma pack(pop)
| 40.433333 | 133 | 0.732069 | Futuremappermydud |
f1139c8813c05e9c131a8782cc62d19d010e4c2d | 786 | cpp | C++ | EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp | AntonioVillatoro/cpp | dbbfcbf7d31c3c0e64399a487d05398e53d9428d | [
"MIT"
] | null | null | null | EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp | AntonioVillatoro/cpp | dbbfcbf7d31c3c0e64399a487d05398e53d9428d | [
"MIT"
] | null | null | null | EJERCICIOS/EJERCICIO4-Imprimir valores de todas las variables/todas-las-variabes.cpp | AntonioVillatoro/cpp | dbbfcbf7d31c3c0e64399a487d05398e53d9428d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
// DECLARACIONES DE VARIABLES
// int para declarar varibales enteras
// double para declarar variables numeros reales
// string para delcarar cadena de caracteres
// char para declara un caracter
// bool para delcarar
bool valorBoolean= false;
int valorEntero=15;
double valorDouble=20.99;
string valorString= "Hola Como Estan";
char valorChar= 'B';
cout << "Valor Boolean: " << valorBoolean << endl;
cout << "Valor Entero: " << valorEntero << endl;
cout << "Valor Double: " << valorDouble << endl;
cout << "Valor String: " << valorString << endl;
cout << "Valor Char: " << valorChar << endl;
return 0;
}
| 25.354839 | 56 | 0.620865 | AntonioVillatoro |
47dd6b1a6ea7124288472a0a0d0021ee76da3162 | 98 | cpp | C++ | Chroma/src/Chroma/Core/Time.cpp | ttalexander2/chroma | 0e9946e66158938ebd6497d5bf3acfba8fbe9fee | [
"MIT"
] | 1 | 2022-03-07T01:54:59.000Z | 2022-03-07T01:54:59.000Z | Chroma/src/Chroma/Core/Time.cpp | ttalexander2/chroma | 0e9946e66158938ebd6497d5bf3acfba8fbe9fee | [
"MIT"
] | 20 | 2021-08-16T16:52:43.000Z | 2022-03-26T02:47:09.000Z | Chroma/src/Chroma/Core/Time.cpp | ttalexander2/chroma | 0e9946e66158938ebd6497d5bf3acfba8fbe9fee | [
"MIT"
] | null | null | null | #include "chromapch.h"
#include "Time.h"
namespace Chroma
{
Time* Time::m_Instance = nullptr;
}
| 12.25 | 34 | 0.704082 | ttalexander2 |
47df4e7e7ac69a26794d53e8fbb72b7b2611ffc9 | 2,239 | cpp | C++ | Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebCore/bindings/js/JSAnimationTimelineCustom.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) Canon Inc. 2016
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions
* are required to be 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 Canon Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY CANON INC. AND ITS 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 CANON INC. AND ITS 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 "config.h"
#if ENABLE(WEB_ANIMATIONS)
#include "JSAnimationTimeline.h"
#include "DocumentTimeline.h"
#include "JSDOMBinding.h"
#include "JSDocumentTimeline.h"
using namespace JSC;
namespace WebCore {
JSValue toJSNewlyCreated(ExecState*, JSDOMGlobalObject* globalObject, Ref<AnimationTimeline>&& value)
{
if (value->isDocumentTimeline())
return createWrapper<DocumentTimeline>(globalObject, WTFMove(value));
return createWrapper<AnimationTimeline>(globalObject, WTFMove(value));
}
JSValue toJS(ExecState* state, JSDOMGlobalObject* globalObject, AnimationTimeline& value)
{
return wrap(state, globalObject, value);
}
} // namespace WebCore
#endif // ENABLE(WEB_ANIMATIONS)
| 39.280702 | 101 | 0.770433 | ijsf |
47e1cdc967d6d730212be9ed68faf2379bd503fd | 2,152 | cpp | C++ | ENgine/Root/Assets/AssetScene.cpp | ENgineE777/OakEngine | 6890fc89a0e9d151e7a0bcc1c276c13594616e9a | [
"Zlib"
] | 13 | 2020-12-02T02:13:29.000Z | 2022-03-11T06:14:54.000Z | ENgine/Root/Assets/AssetScene.cpp | ENgineE777/OakEngine | 6890fc89a0e9d151e7a0bcc1c276c13594616e9a | [
"Zlib"
] | null | null | null | ENgine/Root/Assets/AssetScene.cpp | ENgineE777/OakEngine | 6890fc89a0e9d151e7a0bcc1c276c13594616e9a | [
"Zlib"
] | null | null | null | #include "Root/Root.h"
#ifdef OAK_EDITOR
#include "Editor/Editor.h"
#endif
namespace Oak
{
CLASSREG(Asset, AssetScene, "AssetScene")
META_DATA_DESC(AssetScene)
META_DATA_DESC_END()
void AssetScene::EnableTasks(bool set)
{
GetScene()->EnableTasks(set);
}
Scene* AssetScene::GetScene()
{
if (!scene)
{
scene = new Scene();
scene->Init();
scene->Load(path.c_str());
scene->EnableTasks(false);
}
return scene;
}
void AssetScene::Reload()
{
}
void AssetScene::LoadMetaData(JsonReader& reader)
{
reader.Read("selected_entity", selectedEntityID);
reader.Read("camera2DMode", camera2DMode);
reader.Read("camera3DAngles", camera3DAngles);
reader.Read("camera3DPos", camera3DPos);
reader.Read("camera2DPos", camera2DPos);
reader.Read("camera2DZoom", camera2DZoom);
}
#ifdef OAK_EDITOR
void AssetScene::SaveMetaData(JsonWriter& writer)
{
writer.Write("selected_entity", selectedEntityID);
writer.Write("camera2DMode", camera2DMode);
writer.Write("camera3DAngles", camera3DAngles);
writer.Write("camera3DPos", camera3DPos);
writer.Write("camera2DPos", camera2DPos);
writer.Write("camera2DZoom", camera2DZoom);
GetScene()->Save(GetScene()->projectScenePath);
}
void AssetScene::ActivateScene(bool act)
{
if (!act)
{
camera2DMode = editor.freeCamera.mode2D;
camera3DAngles = editor.freeCamera.angles;
camera3DPos = editor.freeCamera.pos;
camera2DPos = editor.freeCamera.pos2D;
camera2DZoom = editor.freeCamera.zoom2D;
selectedEntityID = editor.selectedEntity ? editor.selectedEntity->GetUID() : -1;
editor.SelectEntity(nullptr);
EnableTasks(false);
}
else
{
editor.freeCamera.mode2D = camera2DMode;
editor.freeCamera.angles = camera3DAngles;
editor.freeCamera.pos = camera3DPos;
editor.freeCamera.pos2D = camera2DPos;
editor.freeCamera.zoom2D = camera2DZoom;
EnableTasks(true);
if (selectedEntityID != -1)
{
editor.SelectEntity(scene->FindEntity(selectedEntityID));
}
}
}
const char* AssetScene::GetSceneEntityType()
{
return nullptr;
}
#endif
void AssetScene::Release()
{
DELETE_PTR(scene)
}
}; | 19.743119 | 83 | 0.71329 | ENgineE777 |
47e5c0da8f9310c17607f0b4d123db2fb0d999f8 | 510 | hpp | C++ | include/tao/pegtl/internal/eol_pair.hpp | TheBB/PEGTL | 9370da4e99e6836555321ac60fd988b5d1bcbaed | [
"BSL-1.0"
] | null | null | null | include/tao/pegtl/internal/eol_pair.hpp | TheBB/PEGTL | 9370da4e99e6836555321ac60fd988b5d1bcbaed | [
"BSL-1.0"
] | null | null | null | include/tao/pegtl/internal/eol_pair.hpp | TheBB/PEGTL | 9370da4e99e6836555321ac60fd988b5d1bcbaed | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2021 Dr. Colin Hirsch and Daniel Frey
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#ifndef TAO_PEGTL_INTERNAL_EOL_PAIR_HPP
#define TAO_PEGTL_INTERNAL_EOL_PAIR_HPP
#include <cstddef>
#include <utility>
#include "../config.hpp"
namespace TAO_PEGTL_NAMESPACE::internal
{
using eol_pair = std::pair< bool, std::size_t >;
} // namespace TAO_PEGTL_NAMESPACE::internal
#endif
| 25.5 | 91 | 0.766667 | TheBB |
47e7711fb408021c72e492e4e604f3609a06de80 | 245 | cpp | C++ | sources/SkyboxShader.cpp | HamilcarR/Echeyde | c7b177834fcabe6ac31c563edc6d4627ebb24b98 | [
"MIT"
] | 2 | 2021-08-25T08:03:07.000Z | 2021-11-20T17:00:03.000Z | sources/SkyboxShader.cpp | HamilcarR/Echeyde | c7b177834fcabe6ac31c563edc6d4627ebb24b98 | [
"MIT"
] | 2 | 2017-03-11T02:30:13.000Z | 2017-04-07T09:00:02.000Z | sources/SkyboxShader.cpp | HamilcarR/Echeyde | c7b177834fcabe6ac31c563edc6d4627ebb24b98 | [
"MIT"
] | 1 | 2018-11-16T17:08:47.000Z | 2018-11-16T17:08:47.000Z | #include "../headers/SkyboxShader.h"
SkyboxShader::SkyboxShader() :Shader()
{
}
SkyboxShader::SkyboxShader(const char* vertex, const char* fragment) : Shader(std::string(vertex), std::string(fragment)){
}
SkyboxShader::~SkyboxShader()
{
}
| 15.3125 | 122 | 0.714286 | HamilcarR |
47fa055422237635afb65e95b064a9c958d3d95d | 1,570 | hpp | C++ | remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | remodet_repository_wdh_part/include/caffe/tracker/halfmerge_layer.hpp | UrwLee/Remo_experience | a59d5b9d6d009524672e415c77d056bc9dd88c72 | [
"MIT"
] | null | null | null | #ifndef CAFFE_TRACKER_HALFMERGE_LAYER_HPP_
#define CAFFE_TRACKER_HALFMERGE_LAYER_HPP_
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* 该层用于对双通道样本进行合并。
* 计算方法:
* Input(x): [2N,C,H,W] -> Output(y): [N,2C,H,W]
* y(n,C+l,i,j) = x(N+n,l,i,j)
* 该层在Tracker中使用,用于对prev/curr特征进行融合。
*/
template <typename Dtype>
void Merge(Dtype* bottom_data, const vector<int> shape, const bool forward,
Dtype* top_data);
template <typename Dtype>
class HalfmergeLayer : public Layer<Dtype> {
public:
explicit HalfmergeLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Halfmerge"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
};
} // namespace caffe
#endif
| 31.4 | 78 | 0.703185 | UrwLee |
47fea34b9e1de67436a5ffda9629ad86a9810779 | 2,043 | hpp | C++ | include/irc/ctcp_parser.hpp | libircpp/libircpp | b7df7f3b20881c11c842b81224bc520bc742cdb1 | [
"BSL-1.0"
] | 3 | 2016-02-01T19:57:44.000Z | 2020-11-12T22:59:29.000Z | include/irc/ctcp_parser.hpp | libircpp/libircpp | b7df7f3b20881c11c842b81224bc520bc742cdb1 | [
"BSL-1.0"
] | null | null | null | include/irc/ctcp_parser.hpp | libircpp/libircpp | b7df7f3b20881c11c842b81224bc520bc742cdb1 | [
"BSL-1.0"
] | null | null | null | // Copyright Joseph Dobson, Andrea Zanellato 2014
// 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 IRC_CTCP_PARSER_HPP
#define IRC_CTCP_PARSER_HPP
//SPEEDS UP SPIRIT COMPILE TIMES
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS 1
#define BOOST_SPIRIT_USE_PHOENIX_V3 1
#include "ctcp.hpp"
#include <boost/fusion/include/vector.hpp>
#include <boost/spirit/home/qi.hpp>
#include <string>
namespace irc {
namespace fsn = boost::fusion;
namespace qi = boost::spirit::qi;
template<typename Iterator>
struct ctcp_parser : qi::grammar<Iterator,
fsn::vector<ctcp::command, std::string>(),
qi::space_type>
{
template<typename Val>
using rule = qi::rule<Iterator, Val(), qi::space_type>;
// Space sensitive
template<typename Val>
using rule_ss = qi::rule<Iterator, Val()>;
ctcp_parser() : ctcp_parser::base_type(ctcp_msg)
{
qi::attr_type attr;
qi::char_type char_;
qi::lit_type lit;
ctcp_cmd.add
("ACTION", ctcp::command::action)("CLIENTINFO", ctcp::command::clientinfo)
("DCC", ctcp::command::dcc) ("ERRMSG", ctcp::command::errmsg)
("FINGER", ctcp::command::finger)("PING", ctcp::command::ping)
("SED", ctcp::command::sed) ("SOURCE", ctcp::command::source)
("TIME", ctcp::command::time) ("USERINFO", ctcp::command::userinfo)
("VERSION", ctcp::command::version);
ctcp_args %= +~char_('\001');
ctcp_msg %= ( (lit('\001') >> ctcp_cmd) >> -ctcp_args )
| ( attr(ctcp::command::none) >> attr(std::string{}) );
}
private:
rule_ss<std::string> ctcp_args;
qi::symbols<char, ctcp::command> ctcp_cmd;
rule<fsn::vector<ctcp::command, std::string>> ctcp_msg;
};
} // namespace irc
#endif // IRC_CTCP_PARSER_HPP
| 31.430769 | 83 | 0.605972 | libircpp |
9a00f9184b5d906a9a36bbcebec68a8c2b83c024 | 7,041 | cpp | C++ | Src/Editor/FrEdToolBar.cpp | VladGordienko28/FluorineEngine-I | 31114c41884d41ec60d04dba7965bc83be47d229 | [
"MIT"
] | null | null | null | Src/Editor/FrEdToolBar.cpp | VladGordienko28/FluorineEngine-I | 31114c41884d41ec60d04dba7965bc83be47d229 | [
"MIT"
] | null | null | null | Src/Editor/FrEdToolBar.cpp | VladGordienko28/FluorineEngine-I | 31114c41884d41ec60d04dba7965bc83be47d229 | [
"MIT"
] | null | null | null | /*=============================================================================
FrEdToolBar.cpp: An editor main toolbar.
Copyright Aug.2016 Vlad Gordienko.
=============================================================================*/
#include "Editor.h"
/*-----------------------------------------------------------------------------
WEditorToolBar implementation.
-----------------------------------------------------------------------------*/
//
// ToolBar constructor.
//
WEditorToolBar::WEditorToolBar( WContainer* InOwner, WWindow* InRoot )
: WToolBar( InOwner, InRoot )
{
// Initialize own fields.
SetSize( 150, 35 );
// Create buttons.
NewProjectButton = new WPictureButton( this, InRoot );
NewProjectButton->Tooltip = L"New Project";
NewProjectButton->Scale = TSize( 16, 16 );
NewProjectButton->Offset = TPoint( 0, 64 );
NewProjectButton->Picture = Root->Icons;
NewProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonNewProjectClick);
NewProjectButton->SetSize( 25, 25 );
this->AddElement( NewProjectButton );
OpenProjectButton = new WPictureButton( this, InRoot );
OpenProjectButton->Tooltip = L"Open Project";
OpenProjectButton->Scale = TSize( 16, 16 );
OpenProjectButton->Offset = TPoint( 16, 64 );
OpenProjectButton->Picture = Root->Icons;
OpenProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonOpenProjectClick);
OpenProjectButton->SetSize( 25, 25 );
this->AddElement( OpenProjectButton );
SaveProjectButton = new WPictureButton( this, InRoot );
SaveProjectButton->Tooltip = L"Save Project";
SaveProjectButton->Scale = TSize( 16, 16 );
SaveProjectButton->Offset = TPoint( 32, 64 );
SaveProjectButton->Picture = Root->Icons;
SaveProjectButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonSaveProjectClick);
SaveProjectButton->SetSize( 25, 25 );
this->AddElement( SaveProjectButton );
this->AddElement( nullptr );
UndoButton = new WPictureButton( this, InRoot );
UndoButton->Tooltip = L"Undo";
UndoButton->Scale = TSize( 16, 16 );
UndoButton->Offset = TPoint( 48, 64 );
UndoButton->Picture = Root->Icons;
UndoButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonUndoClick);
UndoButton->SetSize( 25, 25 );
this->AddElement( UndoButton );
RedoButton = new WPictureButton( this, InRoot );
RedoButton->Tooltip = L"Redo";
RedoButton->Scale = TSize( 16, 16 );
RedoButton->Offset = TPoint( 64, 64 );
RedoButton->Picture = Root->Icons;
RedoButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonRedoClick);
RedoButton->SetSize( 25, 25 );
this->AddElement( RedoButton );
this->AddElement( nullptr );
PlayModeCombo = new WComboBox( this, InRoot );
PlayModeCombo->SetSize( 96, 25 );
PlayModeCombo->AddItem( L"Debug", nullptr );
PlayModeCombo->AddItem( L"Release", nullptr );
PlayModeCombo->SetItemIndex( 0, false );
this->AddElement( PlayModeCombo );
PlayButton = new WPictureButton( this, InRoot );
PlayButton->Tooltip = L"Play Level!";
PlayButton->Scale = TSize( 16, 16 );
PlayButton->Offset = TPoint( 80, 64 );
PlayButton->Picture = Root->Icons;
PlayButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonPlayClick);
PlayButton->SetSize( 25, 25 );
this->AddElement( PlayButton );
this->AddElement(nullptr);
PauseButton = new WPictureButton( this, InRoot );
PauseButton->Tooltip = L"Pause Level";
PauseButton->Scale = TSize( 16, 16 );
PauseButton->Offset = TPoint( 96, 64 );
PauseButton->Picture = Root->Icons;
PauseButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonPauseClick);
PauseButton->SetSize( 25, 25 );
this->AddElement( PauseButton );
StopButton = new WPictureButton( this, InRoot );
StopButton->Tooltip = L"Stop Level";
StopButton->Scale = TSize( 16, 16 );
StopButton->Offset = TPoint( 112, 64 );
StopButton->Picture = Root->Icons;
StopButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonStopClick);
StopButton->SetSize( 25, 25 );
this->AddElement( StopButton );
this->AddElement( nullptr );
BuildButton = new WPictureButton( this, InRoot );
BuildButton->Tooltip = L"Build Game...";
BuildButton->Scale = TSize( 16, 16 );
BuildButton->Offset = TPoint( 128, 64 );
BuildButton->Picture = Root->Icons;
BuildButton->EventClick = WIDGET_EVENT(WEditorToolBar::ButtonBuildClick);
BuildButton->SetSize( 25, 25 );
this->AddElement( BuildButton );
}
//
// Toolbar paint.
//
void WEditorToolBar::OnPaint( CGUIRenderBase* Render )
{
// Call parent.
WToolBar::OnPaint(Render);
WEditorPage* Page = GEditor->GetActivePage();
EPageType Type = Page ? Page->PageType : PAGE_None;
// Turn on, or turn off buttons.
SaveProjectButton->bEnabled = GProject != nullptr;
UndoButton->bEnabled = Type == PAGE_Level || Type == PAGE_Script;
RedoButton->bEnabled = Type == PAGE_Level || Type == PAGE_Script;
PlayModeCombo->bEnabled = Type == PAGE_Level;
PlayButton->bEnabled = Type == PAGE_Level || (Type == PAGE_Play && ((FLevel*)Page->GetResource())->bIsPause);
PauseButton->bEnabled = Type == PAGE_Play && !((FLevel*)Page->GetResource())->bIsPause;
StopButton->bEnabled = Type == PAGE_Play;
BuildButton->bEnabled = GProject != nullptr && Type != PAGE_Play;
}
/*-----------------------------------------------------------------------------
Buttons click.
-----------------------------------------------------------------------------*/
void WEditorToolBar::ButtonNewProjectClick( WWidget* Sender )
{
GEditor->NewProject();
}
void WEditorToolBar::ButtonOpenProjectClick( WWidget* Sender )
{
GEditor->OpenProject();
}
void WEditorToolBar::ButtonSaveProjectClick( WWidget* Sender )
{
GEditor->SaveProject();
}
void WEditorToolBar::ButtonUndoClick( WWidget* Sender )
{
WEditorPage* EdPage = GEditor->GetActivePage();
if( EdPage )
EdPage->Undo();
}
void WEditorToolBar::ButtonRedoClick( WWidget* Sender )
{
WEditorPage* EdPage = GEditor->GetActivePage();
if( EdPage )
EdPage->Redo();
}
void WEditorToolBar::ButtonPlayClick( WWidget* Sender )
{
WEditorPage* EdPage = GEditor->GetActivePage();
if( EdPage )
{
if( EdPage->PageType == PAGE_Level )
GEditor->PlayLevel( ((WLevelPage*)EdPage)->Level );
if( EdPage->PageType == PAGE_Play )
((FLevel*)EdPage->GetResource())->bIsPause = false;
}
}
void WEditorToolBar::ButtonPauseClick( WWidget* Sender )
{
WEditorPage* EdPage = GEditor->GetActivePage();
if( EdPage && EdPage->PageType == PAGE_Play )
((FLevel*)EdPage->GetResource())->bIsPause = true;
}
void WEditorToolBar::ButtonStopClick( WWidget* Sender )
{
WEditorPage* EdPage = GEditor->GetActivePage();
if( EdPage && EdPage->PageType == PAGE_Play )
EdPage->Close();
}
void WEditorToolBar::ButtonBuildClick( WWidget* Sender )
{
GEditor->GameBuilder->Show();
}
/*-----------------------------------------------------------------------------
The End.
-----------------------------------------------------------------------------*/ | 32.901869 | 111 | 0.635989 | VladGordienko28 |
9a0136876639975c58b343745082aad130f868bc | 250 | hpp | C++ | src/parser/Expression.hpp | rlucca/aslan | 1f283c22fb72f717c590cf11482ac97c171f8518 | [
"Unlicense"
] | null | null | null | src/parser/Expression.hpp | rlucca/aslan | 1f283c22fb72f717c590cf11482ac97c171f8518 | [
"Unlicense"
] | null | null | null | src/parser/Expression.hpp | rlucca/aslan | 1f283c22fb72f717c590cf11482ac97c171f8518 | [
"Unlicense"
] | null | null | null | #pragma once
class Expression : public Symbol
{
public:
Expression(Symbol *left);
virtual ~Expression();
void setOp(int operation);
int op();
virtual void add(Symbol *);
protected:
Symbol *m_left;
Symbol *m_right;
int m_op;
};
| 12.5 | 32 | 0.668 | rlucca |
9a047c7f52d0b8ef23a63c442c700759dc8f7b82 | 9,712 | cpp | C++ | src/glCompact/MemoryBarrier.cpp | PixelOfDeath/glCompact | 68334cc9c3aa20255e8986ad1ee5fa8e23df354d | [
"MIT"
] | null | null | null | src/glCompact/MemoryBarrier.cpp | PixelOfDeath/glCompact | 68334cc9c3aa20255e8986ad1ee5fa8e23df354d | [
"MIT"
] | null | null | null | src/glCompact/MemoryBarrier.cpp | PixelOfDeath/glCompact | 68334cc9c3aa20255e8986ad1ee5fa8e23df354d | [
"MIT"
] | null | null | null | #include "glCompact/MemoryBarrier.hpp"
#include "glCompact/Context_.hpp"
#include "glCompact/threadContext_.hpp"
#include "glCompact/gl/Constants.hpp"
/**
MEMORY BARRIER COMMANDS
Memory barriers got introduced with image load/store operations.
To be lightwight and performant there is no automatic ordering or syncronisation provided by OpenGL.
Its design entierly relies on the developer to take care of this.
are used since the inclusion of image load/store operations to order different
- between image load/store operations themself
- between image load/store operations and other OpenGL commands.
GL_ARB_shader_image_load_store (Core since 4.2) introduces glMemoryBarrier(GLbitfield barriers)
GL_ARB_shader_atomic_counters (Core since 4.2)
GL_ARB_shader_storage_buffer_object (Core since 4.3)
GL_ARB_ES3_1_compatibility (Core since 4.5) introduces glMemoryBarrierByRegion(GLbitfield barriers)
Only applies to memory transactions that may be read by or written by a fragment shader (Also other laod/store operations in other shader stages???)
Seems to be mainly aimed at tilled hardware!?
and bindless textures (Not Core)
and bindless buffers (Not Core, Nvidia only)
glMemoryBarrier
| glMemoryBarrierByRegion
| |
y GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT GL_VERTEX_ATTRIB_ARRAY_BUFFER
y GL_ELEMENT_ARRAY_BARRIER_BIT GL_ELEMENT_ARRAY_BUFFER
y GL_COMMAND_BARRIER_BIT GL_DRAW_INDIRECT_BUFFER, GL_DISPATCH_INDIRECT_BUFFER
y GL_PIXEL_BUFFER_BARRIER_BIT GL_PIXEL_PACK_BUFFER, GL_PIXEL_UNPACK_BUFFER
y GL_TEXTURE_UPDATE_BARRIER_BIT Tex(Sub)Image*, ClearTex*Image, CopyTex*, or CompressedTex*, and reads via GetTexImage after the barrier will not execute until all shader writes initiated prior to the barrier complete.
y GL_BUFFER_UPDATE_BARRIER_BIT
y GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT
y GL_QUERY_BUFFER_BARRIER_BIT
y GL_TRANSFORM_FEEDBACK_BARRIER_BIT
y y GL_FRAMEBUFFER_BARRIER_BIT
y y GL_UNIFORM_BARRIER_BIT All uniform buffers
y y GL_TEXTURE_FETCH_BARRIER_BIT Textures and buffer textures
y y GL_SHADER_IMAGE_ACCESS_BARRIER_BIT image load, store, and atomic functions
y y GL_ATOMIC_COUNTER_BARRIER_BIT
y y GL_SHADER_STORAGE_BARRIER_BIT
y y GL_ALL_BARRIER_BITS (In case of glMemoryBarrierByRegion, only includes all other values that are supported by it)
Simple upload functions like TexSubImage* or BufferSubData are automatically synchronized by OpenGL?
For performance reasons writes to directly mapped memory or by shaders (Excluding FB or FBO rendering) are NOT synchronised by OpenGL.
They need explicit synchronization (memory barriers) before commands are issues that access data that is written by previous commands or before changing data that may still is accessed by previous commands!
GL Docs:
Calling memoryBarrier guarantees that any memory transactions issued by the shader invocation prior to the call
complete prior to the memory transactions issued after the call.
"To permit cases where textures or buffers may
be read or written in different pipeline stages without the overhead of automatic
synchronization, buffer object and texture stores performed by shaders are not automatically synchronized with other GL operations using the same memory.
Explicit synchronization is required to ensure that the effects of buffer and texture data stores performed by shaders will be visible to subsequent operations using
the same objects and will not overwrite data still to be read by previously requested operations."
*/
/*enum class MemoryBarrierType : GLenum {
attributeBuffer = GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT,
attributeIndexBuffer = GL_ELEMENT_ARRAY_BARRIER_BIT,
uniformBuffer = GL_UNIFORM_BARRIER_BIT,
textureFetch = GL_TEXTURE_FETCH_BARRIER_BIT, //also texture-buffer objects
imageShaderAccess = GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
parameterBuffer = GL_COMMAND_BARRIER_BIT,
bufferUploadDownloadImage = GL_PIXEL_BUFFER_BARRIER_BIT,
imageUploadClearDownload = GL_TEXTURE_UPDATE_BARRIER_BIT,
bufferCreateClearCopyInvalidate = GL_BUFFER_UPDATE_BARRIER_BIT, //copy only means from/to another buffer, not upload download to unmanaged client memory(?!)
frame = GL_FRAMEBUFFER_BARRIER_BIT,
= GL_TRANSFORM_FEEDBACK_BARRIER_BIT,
= GL_QUERY_BUFFER_BARRIER_BIT,
= GL_ATOMIC_COUNTER_BARRIER_BIT,
= GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT,
shaderStorage = GL_SHADER_STORAGE_BARRIER_BIT,
all = GL_ALL_BARRIER_BITS
};*/
using namespace glCompact::gl;
namespace glCompact {
//read access after barrier
void MemoryBarrier::attributeBuffer() {
threadContext_->memoryBarrierMask |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
}
void MemoryBarrier::attributeIndexBuffer() {
threadContext_->memoryBarrierMask |= GL_ELEMENT_ARRAY_BARRIER_BIT;
}
//GL_DRAW_INDIRECT_BUFFER and GL_DISPATCH_INDIRECT_BUFFER
//Also GL_PARAMETER_BUFFER_ARB if the extension GL_ARB_indirect_parameters (Not part of Core) is present
void MemoryBarrier::parameterBuffer() {
threadContext_->memoryBarrierMask |= GL_COMMAND_BARRIER_BIT;
}
void MemoryBarrier::uniformBuffer() {
threadContext_->memoryBarrierMask |= GL_UNIFORM_BARRIER_BIT;
}
//This also affects bufferTexture objects!
//NOT for glTex(Sub)Image*, glCopyTex(Sub)Image*, glClearTex*Image, glCompressedTex(Sub)Image* !
void MemoryBarrier::texture() {
threadContext_->memoryBarrierMask |= GL_TEXTURE_FETCH_BARRIER_BIT;
}
//read/write access after barrier
void MemoryBarrier::image() {
threadContext_->memoryBarrierMask |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
}
//needs GL_ARB_shader_storage_buffer_object (Core since 4.3) or throws error if glMemoryBarrier is called with it
void MemoryBarrier::shaderStorageBuffer() {
threadContext_->memoryBarrierMask |= GL_SHADER_STORAGE_BARRIER_BIT;
}
//the barrier is for buffers only, that are involved in copys from/to images
void MemoryBarrier::bufferImageTransfer() {
threadContext_->memoryBarrierMask |= GL_PIXEL_BUFFER_BARRIER_BIT;
}
//also delete?; Only copy from/to other buffers?!
void MemoryBarrier::bufferCreateClearCopyInvalidate() {
threadContext_->memoryBarrierMask |= GL_BUFFER_UPDATE_BARRIER_BIT;
}
//Barrier for textures that was or will be changed by:
//glTex(Sub)Image*, glCopyTex(Sub)Image*, glClearTex*Image, glCompressedTex(Sub)Image*
//TODO: also need this as a barrier in the image download function! (glGetTexImage)
//not sure if glGetTexImage needs its own explecite barrier or if a previous barrier on a shader call is enough?!?!?!
void MemoryBarrier::imageUploadDownloadClear() {
threadContext_->memoryBarrierMask |= GL_TEXTURE_UPDATE_BARRIER_BIT;
}
void MemoryBarrier::frame() {
threadContext_->memoryBarrierMask |= GL_FRAMEBUFFER_BARRIER_BIT;
}
void MemoryBarrier::transformFeedback() {
threadContext_->memoryBarrierMask |= GL_TRANSFORM_FEEDBACK_BARRIER_BIT;
}
void MemoryBarrier::query() {
threadContext_->memoryBarrierMask |= GL_QUERY_BUFFER_BARRIER_BIT;
}
void MemoryBarrier::atomicCounterBuffer() {
threadContext_->memoryBarrierMask |= GL_ATOMIC_COUNTER_BARRIER_BIT;
}
/*
For server->client this one is needed for persistenly mapped buffers that do NOT have the MAP_COHERENT_BIT set and then waiting for a sync object (or glFinish).
For client->server data without MAP_COHERENT_BIT one must use a FlushMapped*BufferRange command before issuing commands using the data changed by the client side.
*/
void MemoryBarrier::stagingBufferFlushWrites() {
threadContext_->memoryBarrierMask |= GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT;
}
void MemoryBarrier::all() {
threadContext_->memoryBarrierMask |= GL_ALL_BARRIER_BITS;
}
void MemoryBarrier::RasterizationRegion::uniformBuffer() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_UNIFORM_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::texture() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_TEXTURE_FETCH_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::image() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::shaderStorageBuffer() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_SHADER_STORAGE_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::atomicCounterBuffer() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_ATOMIC_COUNTER_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::frame() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_FRAMEBUFFER_BARRIER_BIT;
}
void MemoryBarrier::RasterizationRegion::all() {
threadContext_->memoryBarrierRasterizationRegionMask |= GL_ALL_BARRIER_BITS;
}
}
| 48.56 | 234 | 0.727759 | PixelOfDeath |
9a04bd03ec8aaed321813bc2040d7831823579b4 | 1,851 | cpp | C++ | 3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp | krowe-alcf/nekBench | d314ca6b942076620dd7dab8f11df97be977c5db | [
"BSD-3-Clause"
] | 4 | 2020-02-26T19:33:16.000Z | 2020-12-06T07:50:11.000Z | 3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp | krowe-alcf/nekBench | d314ca6b942076620dd7dab8f11df97be977c5db | [
"BSD-3-Clause"
] | 12 | 2020-05-13T03:50:11.000Z | 2021-09-16T16:26:06.000Z | 3rdParty/occa/src/lang/expr/leftUnaryOpNode.cpp | krowe-alcf/nekBench | d314ca6b942076620dd7dab8f11df97be977c5db | [
"BSD-3-Clause"
] | 10 | 2020-03-02T15:55:02.000Z | 2021-12-03T02:44:10.000Z | #include <occa/lang/expr/leftUnaryOpNode.hpp>
namespace occa {
namespace lang {
leftUnaryOpNode::leftUnaryOpNode(token_t *token_,
const unaryOperator_t &op_,
const exprNode &value_) :
exprOpNode(token_, op_),
value(value_.clone()) {}
leftUnaryOpNode::leftUnaryOpNode(const leftUnaryOpNode &node) :
exprOpNode(node.token, node.op),
value(node.value->clone()) {}
leftUnaryOpNode::~leftUnaryOpNode() {
delete value;
}
udim_t leftUnaryOpNode::type() const {
return exprNodeType::leftUnary;
}
exprNode* leftUnaryOpNode::clone() const {
return new leftUnaryOpNode(token,
(const unaryOperator_t&) op,
*value);
}
bool leftUnaryOpNode::canEvaluate() const {
if (op.opType & (operatorType::dereference |
operatorType::address)) {
return false;
}
return value->canEvaluate();
}
primitive leftUnaryOpNode::evaluate() const {
primitive pValue = value->evaluate();
return ((unaryOperator_t&) op)(pValue);
}
exprNode* leftUnaryOpNode::endNode() {
return value->endNode();
}
void leftUnaryOpNode::setChildren(exprNodeRefVector &children) {
children.push_back(&value);
}
variable_t* leftUnaryOpNode::getVariable() {
return value->getVariable();
}
void leftUnaryOpNode::print(printer &pout) const {
pout << op << *value;
}
void leftUnaryOpNode::debugPrint(const std::string &prefix) const {
printer pout(io::stderr);
io::stderr << prefix << "|\n"
<< prefix << "|---[";
pout << op;
io::stderr << "] (leftUnary)\n";
value->childDebugPrint(prefix);
}
}
}
| 27.220588 | 71 | 0.572663 | krowe-alcf |
9a081e4dc68491ed31f03c11bdf8d26f976b979c | 521 | hpp | C++ | include/mi/NonCopyable.hpp | tmichi/mibase | 0ab614901cfedeba523f48170c717da8b445d851 | [
"MIT"
] | 4 | 2017-11-24T13:28:52.000Z | 2019-12-09T19:52:51.000Z | include/mi/NonCopyable.hpp | tmichi/mibase | 0ab614901cfedeba523f48170c717da8b445d851 | [
"MIT"
] | 2 | 2015-07-09T09:53:04.000Z | 2016-05-06T05:09:04.000Z | include/mi/NonCopyable.hpp | tmichi/mibase | 0ab614901cfedeba523f48170c717da8b445d851 | [
"MIT"
] | null | null | null | #ifndef MI_NON_COPYABLE_HPP
#define MI_NON_COPYABLE_HPP 1
namespace mi
{
class NonCopyable
{
private:
NonCopyable ( const NonCopyable& that );
void operator = ( const NonCopyable& that );
public:
NonCopyable ( void )
{
return;
}
virtual ~NonCopyable ( void )
{
return;
}
};
}
#endif //MI_NON_COPYABLE_HPP
| 23.681818 | 60 | 0.435701 | tmichi |
9a12f9e2dacf00922a37a060eb6e641f28ba8564 | 2,003 | cpp | C++ | RealVariable.cpp | Sarah-han/solver-a-b | 5ac1f434dc7e3e0b1780d95bd2d6674366178045 | [
"MIT"
] | null | null | null | RealVariable.cpp | Sarah-han/solver-a-b | 5ac1f434dc7e3e0b1780d95bd2d6674366178045 | [
"MIT"
] | null | null | null | RealVariable.cpp | Sarah-han/solver-a-b | 5ac1f434dc7e3e0b1780d95bd2d6674366178045 | [
"MIT"
] | null | null | null | #include "RealVariable.hpp"
#include <math.h>
solver::RealVariable solver::operator==(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
return ls - rs;
}
// support only form (x)^2
solver::RealVariable solver::operator^(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
if (ls._degree != 1 || ls._len != 1 || rs._degree != 0 || rs._len != 1 || rs._c != 2)
{
throw std::runtime_error("ERR: Function support only (bx)^2 form");
}
double a, b, c;
a = std::pow(ls._b, rs._c);
b = 0;
c = 0;
return RealVariable(a, b, c);
}
// Done
solver::RealVariable solver::operator*(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
if (ls._degree + rs._degree > 2)
throw std::runtime_error("ERR: Can't solve a function higher then a quadric function");
double a, b, c;
a = ls._a * rs._c + ls._b * rs._b + ls._c * rs._a;
b = ls._b * rs._c + ls._c * rs._b;
c = ls._c * rs._c;
return RealVariable(a, b, c);
}
// Done
solver::RealVariable solver::operator-(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
double a, b, c;
a = ls._a - rs._a;
b = ls._b - rs._b;
c = ls._c - rs._c;
return RealVariable(a, b, c);
}
// Done
solver::RealVariable solver::operator+(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
double a, b, c;
a = ls._a + rs._a;
b = ls._b + rs._b;
c = ls._c + rs._c;
return RealVariable(a, b, c);
}
// support only devision by double
solver::RealVariable solver::operator/(const solver::RealVariable &ls, const solver::RealVariable &rs)
{
if (rs._degree != 0)
{
throw std::runtime_error("ERR: Function can divide only by a simple double");
}
double a, b, c;
a = ls._a / rs._c;
b = ls._b / rs._c;
c = ls._c / rs._c;
return RealVariable(a, b, c);
}
// Done
std::ostream &solver::operator<<(std::ostream &os, const solver::RealVariable &r)
{
return (os << r._a << "(x)^2 + " << r._b << "x + " << r._c);
}
| 28.614286 | 103 | 0.61358 | Sarah-han |
9a137fcea951ae14652ec074252709c2f52eb4c2 | 21,636 | cpp | C++ | IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 2 | 2020-01-20T11:08:13.000Z | 2020-09-01T17:35:56.000Z | IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 1 | 2020-08-20T01:24:57.000Z | 2020-08-20T01:24:57.000Z | IPStreamingCPP/IPStreamingCPP/MainPage.xaml.cpp | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 1 | 2022-01-25T08:30:15.000Z | 2022-01-25T08:30:15.000Z | //
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
#include "StreamingPageParam.h"
#include "StreamingPage.xaml.h"
using namespace IPStreamingCPP;
using namespace AmcrestMotionDetection;
using namespace FFmpegInteropExtRT;
using namespace OnVifServicesRunTime;
using namespace concurrency;
using namespace Platform;
using namespace Windows::System::Threading;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Media::Core;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Networking;
using namespace Windows::Networking::Connectivity;
using namespace Windows::UI::Xaml::Interop;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
MainPage::MainPage()
{
InitializeComponent();
m_OnVifCameraViewModel = nullptr;
m_displayRequest = ref new Windows::System::Display::DisplayRequest();
m_displayRequestCnt = 0;
m_StreamingPageParamControl = ref new StreamingPageParamControl();
m_applicationSuspendingEventToken =
Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending);
m_applicationResumingEventToken =
Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming);
m_CodecReader = ref new FFmpegInteropExtRT::CodecReader();
// srw2ho: crashin case of first call, but only one computer m_CodecReader->ReadInstalledVideoDecoderCodecsAsync();
// readonly used Video codecs
m_CodecReader->ReadUsedVideoDecoderCodecsAsync();
m_CodecReader->ReadUsedAudioDecoderCodecsAsync();
}
MainPage::~MainPage()
{
Application::Current->Suspending -= m_applicationSuspendingEventToken;
Application::Current->Resuming -= m_applicationResumingEventToken;
// clearRecording();
// ReleaseAllRequestedDisplay();
delete m_StreamingPageParamControl;
}
void MainPage::PivotMediaLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
StreamingPageParam^ streamingPageParam = dynamic_cast<StreamingPageParam^>(PivotCameras->SelectedItem);
if (streamingPageParam != nullptr) {
MediaElement^ media = safe_cast<MediaElement^>(sender);
if (media != nullptr) {
streamingPageParam->MediaStreamElement = media;
streamingPageParam->MediaCurrentStateChangedRegister = streamingPageParam->MediaStreamElement->CurrentStateChanged += ref new Windows::UI::Xaml::RoutedEventHandler(this, &MainPage::MediaElement_OnCurrentStateChanged);
streamingPageParam->MediaFailedRegister = streamingPageParam->MediaStreamElement->MediaFailed += ref new Windows::UI::Xaml::ExceptionRoutedEventHandler(this, &MainPage::MediaElement_OnMediaFailed);
}
}
}
void MainPage::DisplayErrorMessage(Platform::String^ message)
{
// Display error message
this->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([this, message]() {
auto errorDialog = ref new MessageDialog(message);
errorDialog->ShowAsync();
}));
}
void MainPage::ActivateDisplay()
{
//create the request instance if needed
//make request to put in active state
m_displayRequest->RequestActive();
m_displayRequestCnt++;
}
void MainPage::ReleaseAllRequestedDisplay()
{
//must be same instance, so quit if it doesn't exist
if (m_displayRequest == nullptr)
return;
while (m_displayRequestCnt > 0) {
//undo the request
m_displayRequest->RequestRelease();
m_displayRequestCnt--;
}
}
void MainPage::ReleaseDisplay()
{
//must be same instance, so quit if it doesn't exist
if (m_displayRequest == nullptr)
return;
if (m_displayRequestCnt > 0) {
//undo the request
m_displayRequest->RequestRelease();
m_displayRequestCnt--;
}
}
void MainPage::WriteToAppData()
{
for each (auto var in this->m_StreamingPageParamControl->Items)
{
var->WriteToAppData();
}
}
void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e)
{
// Handle global application events only if this page is active
if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
{
this->ClearRessources();
this->clearRecording();
this->ReleaseAllRequestedDisplay();
this->WriteToAppData(); // write App data in case of Suspending
}
}
void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args)
{
// Handle global application events only if this page is active
if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
{
// this->ActivateDisplay();
}
}
void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
IPStreamingCPP::App^ app = safe_cast<IPStreamingCPP::App^>(e->Parameter);
m_app = app;
//OnVifCameraViewModel^ onVifCameraViewModel = safe_cast<OnVifCameraViewModel^>(e->Parameter);
if (app != nullptr) {
this->m_OnVifCameraViewModel = app->CameraViewModel;
}
if (this->m_OnVifCameraViewModel == nullptr) return;
if (this->m_OnVifCameraViewModel->Cameras->Size == 0) // lesen aus local Storage
{
this->m_OnVifCameraViewModel->readDatafromLocalStorage();
}
m_StreamingPageParamControl->ClearRessources(); // all previous events unregister
m_StreamingPageParamControl->Items->Clear();
wchar_t buffer[200];
for (unsigned int ncount = 0; ncount < this->m_OnVifCameraViewModel->Cameras->Size; ncount++)
//for each (auto var in this->m_OnVifCameraViewModel->Cameras)
{
OnVifCamera^ var = this->m_OnVifCameraViewModel->Cameras->GetAt(ncount);
IPStreamingCPP::StreamingPageParam^ param = ref new StreamingPageParam();
swprintf(&buffer[0], sizeof(buffer) / sizeof(buffer[0]), L"Camera_%03d", ncount);
param->createStreamingPageParam(ref new Platform::String(buffer), this->Frame);
param->OnVifCamera = var; // OnVif-Camera
param->PropertyChangedEventRegister = param->OnVifCamera->PropertyChanged += ref new PropertyChangedEventHandler(this, &MainPage::ScenarioPropertyChanged);
param->CameraServerFailedRegister = param->CameraServer->Failed += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, FFmpegInteropExtRT::CameraServerFailedEventArgs^>(this, &MainPage::CameraServerOnFailed);
// Movement-Recording On
param->OnStartMovementStreaming = param->MovementRecording->startStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnstartMovementStreaming);
param->OnStopMovementStreaming = param->MovementRecording->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String^>(this, &IPStreamingCPP::MainPage::OnStopMovementStreaming);
param->OnChangeMovementStreaming = param->MovementRecording->ChangeMovement += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnChangeMovement);
param->OnStartAMCRESEventStreaming = param->AmcrestMotion->startStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnstartMovementStreaming);
param->OnStopAMCRESEventStreaming = param->AmcrestMotion->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String^>(this, &IPStreamingCPP::MainPage::OnStopMovementStreaming);
param->OnChangeAMCRESEventStreaming = param->AmcrestMotion->ChangeMovement += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^>(this, &IPStreamingCPP::MainPage::OnChangeMovement);
param->MovementRecording->HostName = "WilliRaspiPlus";
param->MovementRecording->Port = 3000;
param->CodecReader = this->m_CodecReader;
// Movement-Recording On
param->ScenarioView = ref new IPStreamingCPP::ScenarioViewControl();
Windows::UI::Xaml::Interop::TypeName tt = Windows::UI::Xaml::Interop::TypeName(StreamingPage::typeid);
ScenarioItem^ item = ref new ScenarioItem("Streaming", tt, Symbol::AttachCamera, param);
param->ScenarioView->Items->Append(item);
tt = Windows::UI::Xaml::Interop::TypeName(OnVifServicesRunTime::OnVifSingleCameraPage::typeid);
item = ref new ScenarioItem("OnVifCamera", tt, Symbol::Edit, param->OnVifCamera);
param->ScenarioView->Items->Append(item);
param->takeParametersFromCamera(); // Camera-Parameter werden übernommen
m_StreamingPageParamControl->Items->Append(param);
}
m_StreamingPageParamControl->readSettingsfromLocalStorage();
if (this->m_StreamingPageParamControl->Items->Size == 0) m_StreamingPageParamControl->SelectedIndex = -1;
else if (m_StreamingPageParamControl->SelectedIndex < 0) m_StreamingPageParamControl->SelectedIndex = 0;
Page::OnNavigatedTo(e);
}
void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
{
this->ClearRessources();
this->clearRecording();
this->ReleaseAllRequestedDisplay();
this->WriteToAppData();
m_StreamingPageParamControl->writeSettingsToLocalStorage();
Page::OnNavigatingFrom(e);
}
void MainPage::startUriStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data)
{
IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data);
auto tsk= streamingPageParam->startUriStreaming();
Splitter->IsPaneOpen = false;
}
void MainPage::startFileStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data)
{
IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data);
auto boK = streamingPageParam->startFileStreaming();
Splitter->IsPaneOpen = false;
}
void MainPage::stopStreaming(Platform::Object^ sender, IPStreamingCPP::StreamingPageParam^ data)
{
IPStreamingCPP::StreamingPageParam^ streamingPageParam = safe_cast<IPStreamingCPP::StreamingPageParam^>(data);
streamingPageParam->clearMediaElem();
streamingPageParam->stopStreaming();
}
void MainPage::stopallRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
auto tsk = clearRecordingAsync();
tsk.then([this]()->void {
//this->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([this]() {
// for each (auto var in m_StreamingPageParamControl->Items)
// {
// StackPanel^ panel = getStackPanelByStreamingParam(var);
// if (panel != nullptr) {
// panel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
// }
// }
// }));
//return ;
}
);
}
void MainPage::stopRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem();
if (streamingPageParam != nullptr) {
streamingPageParam->clearMediaElem();
streamingPageParam->stopStreaming();
}
}
void MainPage::startRecording_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem();
if (streamingPageParam != nullptr) {
auto boK = streamingPageParam->startUriStreaming();
Splitter->IsPaneOpen = false;
}
}
void MainPage::PivotCameras_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
{
Pivot^ pivot = dynamic_cast<Pivot^>(sender); // Pivot
if (pivot != nullptr) {
StreamingPageParam^ param = dynamic_cast<StreamingPageParam^>(pivot->SelectedItem); // Property-Changed by OnVifCamera-Page
if (param != nullptr) {
ScenarioControl->ItemsSource = param->ScenarioView->Items;
ScenarioControl->SelectedIndex = 0;
if (param->MovementRecording->IsMoment || param->AmcrestMotion->IsMoment) {
this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible;
}
else
{
this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
}
}
else {
this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
}
}
}
void MainPage::ScenarioPropertyChanged(Platform::Object^ sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^ e)
{
OnVifCamera^ camera = dynamic_cast<OnVifCamera^>(sender); // Property-Changed by OnVifCamera-Page
if (camera != nullptr) {
if (e->PropertyName == "IsProfilesReaded")
{
if (camera->IsProfilesReaded) { // only when reading
StreamingPageParam^ param = this->m_StreamingPageParamControl->getItemByOnVifCamera(camera);
if (param != nullptr) {
param->takeParametersFromCamera(); // Camera-Parameter werden übernommen
}
}
}
}
}
void MainPage::ScenarioControl_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
{
//NotifyUser(String.Empty, NotifyType.StatusMessage);
ListView^ scenarioListBox = dynamic_cast<ListView^>(sender);
ScenarioItem^ item = dynamic_cast<ScenarioItem^>(scenarioListBox->SelectedItem);
if (item != nullptr) {
// if (ScenarioFrame->CurrentSourcePageType.Name != item->TypeClassName.Name)
{
if (item->TypeClassName.Name == Windows::UI::Xaml::Interop::TypeName(OnVifSingleCameraPage::typeid).Name) {
VisualStateManager::GoToState(this, "SetOpenPaneBig", true);
}
else {
VisualStateManager::GoToState(this, "SetOpenPaneDefault", true);
}
ScenarioFrame->Navigate(item->TypeClassName, item->Object);
StreamingPage^ page = dynamic_cast<StreamingPage^>(ScenarioFrame->Content);
if (page != nullptr) {
page->startUriStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::startUriStreaming);
page->startFileStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::startFileStreaming);
page->stopStreaming += ref new Windows::Foundation::TypedEventHandler<Platform::Object^, IPStreamingCPP::StreamingPageParam^>(this, &MainPage::stopStreaming);
}
}
}
}
void MainPage::CameraServerOnFailed(Platform::Object^ sender, FFmpegInteropExtRT::CameraServerFailedEventArgs^ args)
{
Platform::String^ message = args->Message;
DisplayErrorMessage(message);
// throw ref new Platform::NotImplementedException();
}
void MainPage::MediaElement_OnCurrentStateChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
MediaElement^ mediaElement = (MediaElement^)sender;
if (mediaElement != nullptr && mediaElement->IsAudioOnly == false)
{
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Playing)
{
this->ActivateDisplay();
}
else // CurrentState is Buffering, Closed, Opening, Paused, or Stopped.
{
bool bRelease = true;
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Opening) {
bRelease = false;
}
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Paused) {
}
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Closed) {
}
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Stopped) {
}
if (mediaElement->CurrentState == Windows::UI::Xaml::Media::MediaElementState::Buffering) {
bRelease = false;
}
if (bRelease) {
this->ReleaseDisplay();
}
}
}
// throw ref new Platform::NotImplementedException();
}
void MainPage::MediaElement_OnMediaFailed(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e)
{
if (m_displayRequest != nullptr)
{
// Deactivate the display request and set the var to null.
this->ReleaseDisplay();
}
Platform::String^ message = e->ErrorMessage;
DisplayErrorMessage(message);
// throw ref new Platform::NotImplementedException();
}
void MainPage::clearRecording()
{
for each (auto var in this->m_StreamingPageParamControl->Items)
{
auto tsk = var->clearRecording();
}
}
concurrency::task<void> MainPage::clearRecordingAsync()
{
for each (auto var in this->m_StreamingPageParamControl->Items)
{
var->clearMediaElem();
}
auto tsk = create_task([this]()->void {
try {
for each (auto var in this->m_StreamingPageParamControl->Items)
{
auto tsk = var->clearRecording();
tsk.wait();
}
}
catch (Exception^ exception)
{
bool bexception = true;
}
});
return tsk;
// this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
}
void MainPage::ClearRessources()
{
m_StreamingPageParamControl->ClearRessources(); // all previous events unregister
}
void IPStreamingCPP::MainPage::OnStopMovementStreaming(Platform::Object^ sender, Platform::String^ args)
{
AmcrestMotion^ Amcrestrecording = dynamic_cast<AmcrestMotion^>(sender);
RecordingListener::Recording^ recording = dynamic_cast<RecordingListener::Recording^>(sender);
if (args != nullptr) { // stop movement with error
Platform::String^ message = "undefinded Watcher: " + args;
if (Amcrestrecording) {
message = "AMCREST-Event Watcher: " + args;
}
else {
message = "Movement-Watcher: " + args;
}
DisplayErrorMessage(message);
}
// throw ref new Platform::NotImplementedException();
}
void IPStreamingCPP::MainPage::OnstartMovementStreaming(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args)
{
// throw ref new Platform::NotImplementedException();
}
//void IPStreamingCPP::MainPage::OnStopAMCRESTEventStreaming(Platform::Object^ sender, Platform::String^ args)
//{
// if (args != nullptr) { // stop movement with error
// Platform::String^ message = "AMCREST-Event Watcher: " + args;
// DisplayErrorMessage(message);
// }
//
//}
void IPStreamingCPP::MainPage::OnChangeMovement(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args)
{
//AmcrestMotion^ recording = dynamic_cast<AmcrestMotion^>(sender);
bool dodetect = false;
//if (recording != nullptr)
{
StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem();
if (streamingPageParam != nullptr) {
//if (streamingPageParam->AmcrestMotion == recording)
{
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, streamingPageParam, args]()
{
bool IsMoment = (streamingPageParam->MovementRecording->IsMoment || streamingPageParam->AmcrestMotion->IsMoment);
if (IsMoment) {
this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible;
}
else
{
this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
}
// not activated checkForEvents(streamingPageParam);
}));
}
}
}
}
bool IPStreamingCPP::MainPage::checkForEvents(StreamingPageParam^ streamingPageParam) {
Platform::String^ eventset = ref new Platform::String(L"");
Windows::Foundation::Collections::IObservableVector<Platform::String^ >^ events = streamingPageParam->AmcrestMotion->Events;
for (unsigned int i = 0; i < events->Size; i++) {
eventset = events->GetAt(i);
eventset+= "\\r\\n";
}
if (eventset->Length() > 0) {
DisplayErrorMessage(eventset);
}
return (events->Size>0);
}
//bool IPStreamingCPP::MainPage::checkForMovement(Windows::Foundation::Collections::PropertySet^ args) {
//
// if (args->HasKey("m_MovementActiv") && args->HasKey("m_MovementActivated") && args->HasKey("m_RecordingActivTimeinSec")) {
// Platform::Object^ isActivvalue = args->Lookup("m_MovementActiv");
// //Platform::Object^ isActatedvalue = args->Lookup("m_MovementActivated");
// Platform::Object^ RecordingTime = args->Lookup("m_RecordingActivTimeinSec");
// bool isActiv = safe_cast<IPropertyValue^>(isActivvalue)->GetBoolean();
// // int isActived = safe_cast<IPropertyValue^>(isActatedvalue)->GetInt32();
// //if (isActived > 0)
// {
// return (isActiv);
// }
// }
//
// return false;
//
//}
//
//void IPStreamingCPP::MainPage::OnChangeMovement(Platform::Object^ sender, Windows::Foundation::Collections::PropertySet^ args)
//{
//
// RecordingListener::Recording^ recording = dynamic_cast<RecordingListener::Recording^>(sender);
// bool dodetect = false;
// if (recording != nullptr) {
// StreamingPageParam^ streamingPageParam = m_StreamingPageParamControl->getSelectedItem();
// if (streamingPageParam != nullptr) {
// if (streamingPageParam->MovementRecording == recording)
// {
// Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
// CoreDispatcherPriority::Normal,
// ref new Windows::UI::Core::DispatchedHandler([this, recording, args]()
// {
// bool IsMoment = recording->IsMoment;
//
// // checkForMovement(args);
// if (IsMoment) {
// this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Visible;
// }
// else
// {
// this->detectMovement->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
// }
//
// }));
//
// }
// }
// }
//
//}
| 30.008322 | 253 | 0.742235 | srw2ho |
9a147a08302fe45eddfb77567e7489f88065ce5c | 644 | hpp | C++ | smart_tales_ii/game/ui/informationcard.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | smart_tales_ii/game/ui/informationcard.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 11 | 2018-02-08T14:50:16.000Z | 2022-01-21T19:54:24.000Z | smart_tales_ii/game/ui/informationcard.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | /*
informationcard.hpp
Simple helper class used in winoverlay.hpp / .cpp.
Counts down its timeout and after that it starts fading
in the subtitle and image.
*/
#pragma once
#include <SFML/Graphics.hpp>
class InformationCard : public sf::Drawable
{
private:
float fadeTimeOut;
int colorValue;
sf::Sprite image;
sf::Text subtitle;
protected:
void draw(sf::RenderTarget & target, sf::RenderStates states) const override;
public:
void Update(const sf::Time & elapsed);
void SetPosition(const float x, const float y);
InformationCard(const std::string & textureFile, const std::string & description, const float _fadeTimeOut);
}; | 21.466667 | 109 | 0.75 | TijmenUU |
9a14e84c937df5ce584001d2231706c81e90f695 | 1,211 | cpp | C++ | basic/inherit/singleInherit.cpp | Marveliu/learn-cpp | e1f121fb1d5d7decc5712817a3f4751f43fea1b8 | [
"Apache-2.0"
] | null | null | null | basic/inherit/singleInherit.cpp | Marveliu/learn-cpp | e1f121fb1d5d7decc5712817a3f4751f43fea1b8 | [
"Apache-2.0"
] | null | null | null | basic/inherit/singleInherit.cpp | Marveliu/learn-cpp | e1f121fb1d5d7decc5712817a3f4751f43fea1b8 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
class Animal //定义基类
{
public:
Animal(int con_weight, int con_age); //声明带参构造函数
~Animal()
{
cout << "Animal destructor!" << endl;
}
int get_age() { return m_nAge; } //获取m_nAge属性值
void speak() { cout << "animal language!" << endl; }
private:
int m_nWeight, m_nAge;
};
Animal::Animal(int con_weight, int con_age) //定义基类带参构造函数
{
m_nWeight = con_weight;
m_nAge = con_age;
cout << "Animal constructor with param!" << endl;
}
class Cat : public Animal
{ //定义派生类
public:
//声明带参构造函数
Cat(string con_name, int con_weight, int con_age);
~Cat() { cout << "Cat destructor!" << endl; } //定义析构函数
void speak() { cout << "cat language: miaomiao!" << endl; }
private:
string m_strName;
};
//定义派生类带参的构造函数
Cat::Cat(string con_name, int con_weight, int con_age) : Animal(con_weight, con_age)
{
m_strName = con_name;
cout << "Cat constructor with param!" << endl;
}
int main()
{
Cat cat("Persian", 3, 4); //定义派生类对象
cout << "cat age = " << cat.get_age() << endl; //调用get_age()函数
cat.speak(); //通过派生类调用speak()函数
cat.Animal::speak(); //调用基类同名函数
return 0;
}
| 22.849057 | 84 | 0.601156 | Marveliu |
9a177211feed7e22ba2a45509653d9bd2010a525 | 2,248 | hpp | C++ | src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp | gabrielevi10/bsn | 2d42aa006933caf75365bb327fd7d79ae30c88b7 | [
"MIT"
] | 8 | 2020-01-26T15:26:27.000Z | 2022-01-05T15:38:07.000Z | src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp | gabrielevi10/bsn | 2d42aa006933caf75365bb327fd7d79ae30c88b7 | [
"MIT"
] | 50 | 2019-08-29T23:52:43.000Z | 2021-01-24T19:09:54.000Z | src/libbsn/include/libbsn/configuration/SensorConfiguration.hpp | gabrielevi10/bsn | 2d42aa006933caf75365bb327fd7d79ae30c88b7 | [
"MIT"
] | 4 | 2019-06-15T17:23:57.000Z | 2020-10-16T20:09:41.000Z | #ifndef SENSORCONFIGURATION_HPP
#define SENSORCONFIGURATION_HPP
#include <string>
#include <math.h>
#include <iostream>
#include <array>
#include <sstream>
#include "libbsn/range/Range.hpp"
namespace bsn {
namespace configuration {
class SensorConfiguration {
public:
SensorConfiguration();
SensorConfiguration(int32_t i, bsn::range::Range,
std::array<bsn::range::Range, 2>,
std::array<bsn::range::Range, 2>,
std::array<bsn::range::Range, 3>);
SensorConfiguration(const SensorConfiguration & /*obj*/);
SensorConfiguration &operator=(const SensorConfiguration & /*obj*/);
private:
int32_t id;
bsn::range::Range lowRisk;
std::array<bsn::range::Range, 2> mediumRisk;
std::array<bsn::range::Range, 2> highRisk;
bsn::range::Range lowPercentage, midPercentage, highPercentage;
public:
// Retorna o estado de risco a partir dos intervalos
double evaluateNumber(double number);
// Retorna o quão deslocado do meio um valor está
double getDisplacement(bsn::range::Range, double, std::string );
// Converte para o percentual final( {var}_percentage )
double convertRealPercentage(bsn::range::Range range, double number);
// Verifica se valor passado é de baixo risco
bool isLowRisk(double/*val*/);
// Verifica se valor passado é de médio risco
bool isMediumRisk(double/*val*/);
// Verifica se valor passado é de alto risco
bool isHighRisk(double/*val*/);
int32_t getId() const;
void setId(const int32_t);
bsn::range::Range getLowRisk() const;
void setLowRisk(const bsn::range::Range);
std::array<bsn::range::Range, 2> getMediumRisk() const;
void setMediumRisk(const std::array<bsn::range::Range, 2>);
std::array<bsn::range::Range, 2> getHighRisk() const;
void setHighRisk(const std::array<bsn::range::Range, 2>);
bsn::range::Range getLowPercentage() const;
void setLowPercentage(const bsn::range::Range);
bsn::range::Range getMidPercentage() const;
void setMidPercentage(const bsn::range::Range);
bsn::range::Range getHighPercentage() const;
void setHighPercentage(const bsn::range::Range);
const std::string toString() ;
};
}
}
#endif | 27.084337 | 73 | 0.683274 | gabrielevi10 |
9a17d0c7f6a0cf1624878b9d909425202934b4f2 | 380 | cpp | C++ | turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp | RoboticsLabURJC/2021-tfg-carlos-caminero | e23991616cb971b9a0bd95b653789c54f571a930 | [
"Apache-2.0"
] | null | null | null | turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp | RoboticsLabURJC/2021-tfg-carlos-caminero | e23991616cb971b9a0bd95b653789c54f571a930 | [
"Apache-2.0"
] | null | null | null | turtlebot2/kobuki_base/kobuki_ros/kobuki_node/src/kobuki_ros_node.cpp | RoboticsLabURJC/2021-tfg-carlos-caminero | e23991616cb971b9a0bd95b653789c54f571a930 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "kobuki_node/kobuki_ros.hpp"
int main(int argc, char** argv)
{
// Configures stdout stream for no buffering
setvbuf(stdout, nullptr, _IONBF, BUFSIZ);
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<kobuki_node::KobukiRos>(rclcpp::NodeOptions()));
rclcpp::shutdown();
return 0;
}
| 18.095238 | 80 | 0.707895 | RoboticsLabURJC |
9a20107c36410583cd9701568f1da690d1b6aa45 | 4,072 | cpp | C++ | Socket.cpp | marcaddeo/MAMClient | c3d91a55e25a70347401071fd9d5a26afacfe361 | [
"MIT"
] | null | null | null | Socket.cpp | marcaddeo/MAMClient | c3d91a55e25a70347401071fd9d5a26afacfe361 | [
"MIT"
] | null | null | null | Socket.cpp | marcaddeo/MAMClient | c3d91a55e25a70347401071fd9d5a26afacfe361 | [
"MIT"
] | null | null | null | /*
* Socket.cpp
* MAMClient
*
* Created by Marc Addeo on 10/7/08.
* Copyright 2008 __MyCompanyName__. All rights reserved.
*
*/
#include "Socket.h"
Socket::Socket( CryptoStuff *crypt ) : m_sock( -1 )
{
memset( &this->m_addr, 0, sizeof( this->m_addr ) );
this->crypto = crypt;
}
Socket::~Socket( void )
{
}
bool Socket::create( void )
{
int on = 1;
this->m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP );
if ( !this->is_valid() )
return false;
if ( setsockopt( this->m_sock, SOL_SOCKET, SO_REUSEADDR, ( const char * )&on, sizeof( on ) ) == -1 )
return false;
return true;
}
bool Socket::connect( const char *host, const int port )
{
int status;
if ( !this->create() )
return false;
if ( !this->is_valid() )
return false;
this->m_addr.sin_family = AF_INET;
this->m_addr.sin_port = htons( port );
status = inet_pton( AF_INET, host, &this->m_addr.sin_addr );
if ( errno == EAFNOSUPPORT )
return false;
status = ::connect( this->m_sock, ( sockaddr * )&this->m_addr, sizeof( this->m_addr ) );
if ( status == 0 )
return true;
return false;
}
void Socket::select( void )
{
struct timeval tv;
tv.tv_sec = 30;
tv.tv_usec = 0;
FD_ZERO( &this->readfds );
FD_SET( this->m_sock, &this->readfds );
::select( this->m_sock + 1, &this->readfds, NULL, NULL, &tv );
}
bool Socket::is_readable( void )
{
if ( FD_ISSET( this->m_sock, &this->readfds ) )
return true;
return false;
}
bool Socket::send( const char *data, int size ) const
{
int status;
int nSent = 0;
while ( nSent < size )
{
status = ::send( this->m_sock, data + nSent, size - nSent, 0 );
if ( status == -1 )
break;
nSent += status;
}
if ( status == -1 )
return false;
return true;
}
int Socket::read( const char *buffer, int size ) const
{
int status;
char rBuffer[0x1000];
int nRecieved = 0;
memset( rBuffer, 0, 0x1000 );
while ( nRecieved < size )
{
status = ::recv( this->m_sock, rBuffer + nRecieved, size - nRecieved, 0 );
if ( status == -1 )
break;
nRecieved += status;
}
if ( status == -1 || status == 0 )
return status;
memcpy( ( void * )buffer, ( void * )rBuffer, size );
return status;
}
CPacket Socket::read_packet( void )
{
CPacket packet;
char pHeader[4];
int status;
status = this->read( pHeader, sizeof( pHeader ) );
if ( status == 0 )
{
std::cout << "Error in read_packet() ... Empty packet..." << std::endl;
packet.header.size = 0;
packet.header.id = 0;
return packet;
}
if ( status == -1 )
std::cout << "Error in read_packet() ... " << errno << std::endl;
this->crypto->incoming( pHeader, sizeof( pHeader ) );
packet.header = *( CPacketHeader * )pHeader;
if ( packet.header.size < 0 || packet.header.size > MAXPACKETSIZE )
{
packet.header.size = 0;
packet.header.id = 0;
return packet;
}
status = this->read( packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) );
this->crypto->incoming( packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) );
return packet;
}
bool Socket::send_packet( CPacket packet )
{
char buffer[MAXPACKETSIZE];
bool sent;
printf("Send_packet Packet %s: ", packet.data);
hexdump( ( void * )packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) );
memcpy( ( void * )buffer, ( void * )&packet, packet.header.size );
printf("Send_packet Buffer %s: ", buffer);
hexdump( ( void * )buffer, 52);
this->crypto->outgoing( buffer, packet.header.size );
sent = this->send( buffer, packet.header.size );
if ( !sent )
std::cout << "Error in send_packet() ... " << errno << std::endl;
return sent;
} | 21.775401 | 104 | 0.5528 | marcaddeo |
9a3086bfcbea92e16f880f88b1a15e046b21ce41 | 11,633 | cpp | C++ | TicTacToeVsCPU.cpp | anubhawbhalotia/TicTacToe-Vs-CPU | 2bb37dbfbd20075196ad859c5309e77c61d1e8f7 | [
"MIT"
] | null | null | null | TicTacToeVsCPU.cpp | anubhawbhalotia/TicTacToe-Vs-CPU | 2bb37dbfbd20075196ad859c5309e77c61d1e8f7 | [
"MIT"
] | null | null | null | TicTacToeVsCPU.cpp | anubhawbhalotia/TicTacToe-Vs-CPU | 2bb37dbfbd20075196ad859c5309e77c61d1e8f7 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<time.h>
void ar(int*);
void tictctoe(int,int*,char,char);
int checkwin(int*,int);
void cpuplay(int*,char);
int checkcpunextmove(int*);
int checkplayernextmove(int*);
int checknextmove(int*);
int checkcpunextmoveadv(int*);
int checknextmoveadv(int*);
int clone(int*,int);
int checktwozeroone(int*,int);
int playerplay(int*,char);
void add(int,char);
void gotoxy(int anubhaw, int y)
{
COORD c;
c.X = anubhaw;
c.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void ar(int *a)
{
int anubhaw=50,y=2,i,j;
for(i=0;i<=2;i++)
{
gotoxy(anubhaw,y);
for(j=0;j<=2;j++)
{
printf("%d ",*(a+(3*i)+j));
}
y++;
printf("\n");
}
}
void tictactoe(int t,int *a,char s1,char s2)
{
int z,i,j,win0,win1;
for(i=t;;i++)
{
//ar(a);
if(i%2==0)
cpuplay(a,s2);
else
{
z=playerplay(a,s1);
if(z==0)
{
i=0;
continue;
}
}
win0=checkwin(a,0);
win1=checkwin(a,1);
if(win1==1)
{
gotoxy(23,17);
printf("You Won");
break;
}
else if(win0==1)
{
gotoxy(22,17);
printf("You lose");
break;
}
for(j=0;j<=8;j++)
{
if(*(a+j)==2)
break;
}
if(j>8)
{
gotoxy(24,17);
printf("Draw");
break;
}
//ar(a);
}
}
int checkwin(int *a,int fn)
{
int i,j,d;
//printf("\ninside checkwin");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(*(a+(3*i)+j)!=fn)
break;
}
if(j>2)
return 1;
// printf("not in rows\n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(*(a+(3*j)+i)!=fn)
break;
}
if(j>2)
return 1;
// printf("not in columns\n");
}
for(i=0;i<=2;i++)
{
if(*(a+(3*i)+i)!=fn)
break;
}
if(i>2)
return 1;
//printf("not in leading diagonal\n");
if(*(a+2)==fn && *(a+4)==fn && *(a+6)==fn)
return 1;
//printf("not in other diagonal\n");
return 0;
}
void cpuplay(int *a,char s2)
{
int d,p,i;
p=checktwozeroone(a,0); //checks for direct winning case finds single empty box to put 0 (banana)
if(p<10)
goto c;
p=checktwozeroone(a,1); //finds single emppty box to put 0 (bigadna)
if(p<10)
goto c;
p=checknextmoveadv(a); //checks whether in the next chance, player doesn't win clarly
if(p<10)
goto c;
p=checkcpunextmoveadv(a); //checks whether in next chance cpu can win clearly
if(p<10)
goto c;
p=checknextmove(a); //checks whether in next chance
if(p<10)
goto c;
p=checkplayernextmove(a); //keeps 1 check form or not. keeps 0 check form or not
if(p<10)
goto c;
p=checkcpunextmove(a); //keeps 0 and check cpu form or not
if(p<10)
goto c;
d=rand();
for(i=0;i<=4;i++)
{
if(d%5==i)
{
if(*(a+(2*i))==2)
{
p=(2*i)+1;
break;
}
}
}
if(i<=4)
goto c;
if(*(a+4)==2)
{
p=5;
goto c;
}
for(i=0;;i++)
{
if(*(a+i)==2)
{
//printf("general\n");
p=i+1;
break;
}
}
c:
//printf(" value of p after cpu play : %d\n",p);
*(a+p-1)=0;
add(p,s2);
}
int checkcpunextmove(int *a)
{
int i,b[9],count=0;
for(i=0;i<=8;i++)
b[i]=*(a+i);
if(b[4]==2)
{
b[4]=0;
count=clone(b,0);
b[4]=2;
if(count>0)
return 5;
}
for(i=0;i<=8;i++)
{
count=0;
if(b[i]==2)
{
b[i]=0;
count=clone(b,0);
b[i]=2;
if(count>0)
{
//printf("\ncheckcpunextmove\n");
return i+1;
}
}
}
return 10;
}
int checkplayernextmove(int *a)
{
int i,b[9],count=0;
for(i=0;i<=8;i++)
b[i]=*(a+i);
if(b[4]==2)
{
b[4]=1;
count=clone(b,1);
b[4]=2;
if(count>0)
return 5;
}
for(i=0;i<=8;i++)
{
count=0;
if(b[i]==2)
{
b[i]=1;
count=clone(b,1);
b[i]=2;
if(count>0)
{
//printf("\ncheckplayernextmove\n");
return i+1;
}
}
}
return 10;
}
int checknextmove(int *a)
{
int i,b[9],count1=0,count0=0;
for(i=0;i<=8;i++)
b[i]=*(a+i);
if(b[4]==2)
{
b[4]=1;
count1=clone(b,1);
b[4]=0;
count0=clone(b,0);
b[4]=2;
if(count1>0 && count0>0)
return 5;
}
for(i=0;i<=8;i++)
{
count1=0;
count0=0;
if(b[i]==2)
{
b[i]=1;
count1=clone(b,1);
b[i]=0;
count0=clone(b,0);
b[i]=2;
if(count1>0 && count0>0)
{
//printf("\nchecknextmove\n");
return i+1;
}
}
}
return 10;
}
int checkcpunextmoveadv(int *a)
{
int i,b[9],count;
for(i=0;i<=8;i++)
b[i]=*(a+i);
for(i=0;i<=8;i++)
{
count=0;
if(b[i]==2)
{
b[i]=0;
count=clone(b,0);
b[i]=2;
if(count>1)
{
//printf("\ncheckcpunextmoveadv\n");
return i+1;
}
}
}
return 10;
}
int checknextmoveadv(int *a)
{
int i,b[9],count;
for(i=0;i<=8;i++)
b[i]=*(a+i);
for(i=0;i<=8;i++)
{
count=0;
if(b[i]==2)
{
b[i]=1;
count=clone(b,1);
b[i]=2;
if(count>1)
{
//printf("\nchecknextmoveadv");
return i+1;
}
}
}
return 10;
}
int clone(int *b,int fn)
{
int i,j,empty,zero,count=0,p;
for(i=0;i<=2;i++)
{
empty=0;
zero=0;
for(j=0;j<=2;j++)
{
if(*(b+(3*i)+j)==2)
empty++;
if(*(b+(3*i)+j)==fn)
zero++;
}
if(empty==1 && zero==2)
count++;
}
for(i=0;i<=2;i++)
{
empty=0;
zero=0;
for(j=0;j<=2;j++)
{
if(*(b+(3*j)+i)==2)
empty++;
if(*(b+(3*j)+i)==fn)
zero++;
}
if(empty==1 && zero==2)
count++;
}
empty=0;
zero=0;
for(i=0;i<=2;i++)
{
if(*(b+(3*i)+i)==2)
{
p=(3*i)+i+1;
empty++;
}
if(*(b+(3*i)+i)==fn)
zero++;
}
if(empty==1 && zero==2)
count++;
empty=0;
zero=0;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(i+j==2)
{
if(*(b+(3*i)+j)==2)
{
p=(3*i)+j+1;
empty++;
}
if(*(b+(3*i)+j)==fn)
zero++;
}
}
}
if(empty==1 && zero==2)
count++;
return count;
}
int checktwozeroone(int *a,int fn)
{
int i,j,empty,zero,p;
for(i=0;i<=2;i++)
{
empty=0;
zero=0;
for(j=0;j<=2;j++)
{
if(*(a+(3*i)+j)==2)
{
p=(3*i)+j+1;
empty++;
}
if(*(a+(3*i)+j)==fn)
zero++;
}
if(empty==1 && zero==2)
return p;
}
for(i=0;i<=2;i++)
{
empty=0;
zero=0;
for(j=0;j<=2;j++)
{
if(*(a+(3*j)+i)==2)
{
p=(3*j)+i+1;
empty++;
}
if(*(a+(3*j)+i)==fn)
zero++;
}
if(empty==1 && zero==2)
return p;
}
empty=0;
zero=0;
for(i=0;i<=2;i++)
{
if(*(a+(3*i)+i)==2)
{
p=(3*i)+i+1;
empty++;
}
if(*(a+(3*i)+i)==fn)
zero++;
}
if(empty==1 && zero==2)
return p;
empty=0;
zero=0;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(i+j==2)
{
if(*(a+(3*i)+j)==2)
{
p=(3*i)+j+1;
empty++;
}
if(*(a+(3*i)+j)==fn)
zero++;
}
}
}
if(empty==1 && zero==2)
return p;
return 10;
}
int playerplay(int *a,char s1)
{
int p;
gotoxy(84,17);
printf(" ");
gotoxy(86,17);
//printf("Make your play");
fflush(stdin);
scanf("%d",&p);
if(p<1 || p>9)
{
gotoxy(82,5);
printf("Invalid Input\n");
return 0;
}
gotoxy(82,5);
printf(" ");
if(*(a+p-1)==2)
*(a+p-1)=1;
else
{
gotoxy(82,5);
printf("Wrong move\n");
return 0;
}
add(p,s1);
gotoxy(84,17);
return 1;
}
void add(int p,char c)
{
int anubhaw,y;
//printf("Adding at : %d",p);
anubhaw=47+((p-1)%3)*7;
y=15+((p-1)/3)*3;
gotoxy(anubhaw,y);
printf("%c%c%c",c,c,c);
gotoxy(anubhaw,y+1);
printf("%c%c%c",c,c,c);
}
int main()
{
int i,t,a[9],anubhaw=50,y=5,j,z=1;
printf("Developer - Anubhaw Bhalotia");
d:
gotoxy(52,0);
printf("TIC-TAC-TOE");
gotoxy(50,1);
printf("---------------");
gotoxy(0,3);
for(i=0;i<=8;i++)
a[i]=2;
char s1,s2,toss;
srand(time(NULL));
printf("Choose your symbol (X or O) : ");
fflush(stdin);
scanf("%c",&s1);
if(s1!='X' && s1!='x' && s1!='O' && s1!='o' && s1!='0')
{
printf("\nInvalid Character");
printf("\nType any character and press 'Enter' to continue\n");
fflush(stdin);
scanf("%c",&toss);
fflush(stdin);
system("cls");
goto d;
}
if(s1=='x')
s1='X';
if(s1=='o' || s1=='0')
s1='O';
(s1=='X')?s2='O':(s2='X');
printf("\n\nEnter any Character to begin Toss : ");
fflush(stdin);
scanf("%c",&toss);
if(rand()%2==0)
{
printf("\n\nYou won the toss");
t=1;
}
else
{
printf("\n\nYou lose the toss");
t=0;
}
for(i=0;i<=2;i++)
{
gotoxy(anubhaw,y);
for(j=0;j<=2;j++)
{
printf("%d ",z);
z++;
}
y+=2;
}
for(i=6;i<=8;i=i+2)
{
gotoxy(48,i);
printf("----------------");
}
for(i=53;i<=60;i=i+4)
{
for(j=4;j<=10;j++)
{
gotoxy(i,j);
printf("|");
}
}
for(i=17;i<=21;i=i+3)
{
gotoxy(45,i);
printf("---------------------");
}
for(i=52;i<=60;i=i+6)
{
for(j=14;j<=23;j++)
{
gotoxy(i,j);
printf("|");
}
}
gotoxy(80,14);
printf("Make your Move(1-9)");
gotoxy(83,16);
printf("--------");
for(i=16;i<=18;i++)
{
gotoxy(82,i);
printf("|");
gotoxy(82+9,i);
printf("|");
}
gotoxy(83,18);
printf("--------");
gotoxy(0,4);
tictactoe(t,a,s1,s2);
gotoxy(17,16);
printf("-----------------");
gotoxy(17,18);
printf("-----------------");
for(i=16;i<=18;i++)
{
gotoxy(17,i);
printf("|");
gotoxy(33,i);
printf("|");
}
gotoxy(0,25);
printf("Type any Character and press 'Enter' to exit : ");
fflush(stdin);
scanf("%c",&toss);
}
| 18.494436 | 101 | 0.376945 | anubhawbhalotia |
9a34a83de7464a3f9e10ed962cec0cf28f8fcd2c | 381 | cpp | C++ | src/stkdata/ColumnDefInt.cpp | s-takeuchi/YaizuComLib | de1c881a4b743bafec22f7ea2d263572c474cbfe | [
"MIT"
] | 4 | 2017-02-21T23:25:23.000Z | 2022-01-30T20:17:22.000Z | src/stkdata/ColumnDefInt.cpp | Aekras1a/YaizuComLib | 470d33376add0d448002221b75f7efd40eec506f | [
"MIT"
] | 161 | 2015-05-16T14:26:36.000Z | 2021-11-25T05:07:56.000Z | src/stkdata/ColumnDefInt.cpp | Aekras1a/YaizuComLib | 470d33376add0d448002221b75f7efd40eec506f | [
"MIT"
] | 1 | 2019-12-06T10:24:45.000Z | 2019-12-06T10:24:45.000Z | #include "stkdata.h"
#include "../stkpl/StkPl.h"
// Constructor
ColumnDefInt::ColumnDefInt()
{
}
// Constructor
ColumnDefInt::ColumnDefInt(const wchar_t* ColumnName)
{
StkPlWcsNCpy(m_ColumnName, COLUMN_NAME_SIZE, ColumnName, COLUMN_NAME_SIZE - 1);
m_ColumnName[COLUMN_NAME_SIZE - 1] = L'\0';
m_ColumnType = COLUMN_TYPE_INT;
}
// Destructor
ColumnDefInt::~ColumnDefInt()
{
}
| 18.142857 | 80 | 0.745407 | s-takeuchi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.