blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25d7cf960d317655c0d547dc2ba42c2b4765afcd | 8f277acc83b41879426fa8ac19fcef3dad8d9009 | /Desktop/taller3/punto13.cpp | 5c2c6b2a43b363907e10ffc88ddecea32ff9a1cd | [] | no_license | vyeso3151/taller3 | b7ee374deb4577d5196ea9ff98fe52bdd20410ce | 0d373a18385597c03021e7a20d7741d9d1fc68d0 | refs/heads/master | 2021-07-09T04:27:15.499717 | 2017-10-04T00:17:56 | 2017-10-04T00:17:56 | 105,716,473 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 463 | cpp | punto13.cpp |
//taller funciones
// punto Nš13
// hecho por Victor Bruno
// fecha 26/09/2017
#include <stdio.h>
void vect(int vec[]){
int l,i,n;
;
printf("Ingresa la longitud del vector.");
scanf("%d",&l);
for(i=1;i<=l;i++){
printf("ingresa un numero: ");
scanf("%d",&vec[i]);
}
for(i=1;i<=l;i++){
if (vec[i]%2==1){
printf("Los numeros impares del vector son: %d\n",vec[i]);
}
}
}
int main() {
int vec[100];
vect(vec);
return 0;
}
|
43ec3b5c94314690754b51c2fa5e0fe2ff33d494 | ca94010aea48ed4db12bfcdd71cafa55bac452f1 | /Common/Utility.h | 8b9cd8c0a8b421d9e530261d0b0dc9af761f92eb | [] | no_license | zhangzhi7216/RadarSim | 87542e0919289d10fdf574836f098b84078194fe | fcab2181bfa7cdde78a939a8e0d8917e3f3ce47c | refs/heads/master | 2020-05-28T01:02:59.469055 | 2015-06-03T07:40:28 | 2015-06-03T07:40:28 | 34,791,114 | 1 | 0 | null | 2015-04-29T11:54:35 | 2015-04-29T11:54:35 | null | UTF-8 | C++ | false | false | 986 | h | Utility.h | #pragma once
#include "DataPacket.h"
#include "Target.h"
namespace Utility
{
__declspec(dllexport) double Distance(const Position &rel);
__declspec(dllexport) double Theta(const Position &rel);
__declspec(dllexport) double Phi(const Position &rel);
__declspec(dllexport) double Distance(const Position &src, const Position &dst);
__declspec(dllexport) double Theta(const Position &src, const Position &dst);
__declspec(dllexport) double Phi(const Position &src, const Position &dst);
__declspec(dllexport) Position Rel(double dis, double theta, double phi);
__declspec(dllexport) double WhiteNoise(double value, double var);
__declspec(dllexport) double ColorNoise(double value, double var);
__declspec(dllexport) double MultNoise(double value, double var);
__declspec(dllexport) wstring string2wstring(string str);
__declspec(dllexport) string wstring2string(wstring wstr);
__declspec(dllexport) void PromptLastErrorMessage();
};
|
54be9d09b6ff0357e6a4bd97c73c2927a7e8aeaa | 5af96302146b002eaabc4e70b4a7b47b1d9c5f20 | /include/kmeans.h | 465327b2453c419a2fed9ae6a98a7f2584533d24 | [] | no_license | EricJeffrey/kmeans_visualize | 4c0623a85be7b58ec06a2202f636701117d998d0 | ca2a9b0e203a28523ceee2e64509f49b26660689 | refs/heads/master | 2021-01-08T21:18:59.532872 | 2020-02-24T01:48:51 | 2020-02-24T01:48:51 | 242,146,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,965 | h | kmeans.h | #include "kmeans_oop.h"
using std::cin;
using std::cout;
using std::initializer_list;
using std::runtime_error;
class NDimenPoint : public VirtualPoint {
private:
int dimension;
vector<double> xs;
public:
NDimenPoint(const int d) : dimension(d) { xs.resize(d); }
NDimenPoint(const int d, vector<double> l) : dimension(d), xs(l){};
NDimenPoint(const NDimenPoint &p) : dimension(p.dimension), xs(p.xs) {}
~NDimenPoint(){};
bool operator==(const VirtualPoint &p) override {
auto pp = static_cast<const NDimenPoint &>(p);
if (dimension != pp.dimension) return false;
for (size_t i = 0; i < xs.size(); i++)
if (xs[i] != pp.xs[i]) return false;
return true;
}
bool operator!=(const VirtualPoint &p) override {
auto pp = static_cast<const NDimenPoint &>(p);
if (dimension != pp.dimension) return true;
for (size_t i = 0; i < xs.size(); i++)
if (xs[i] != pp.xs[i]) return true;
return false;
}
void add(const NDimenPoint &p) {
if (p.dimension != dimension) throw runtime_error("dimension mismatch");
for (size_t i = 0; i < xs.size(); i++)
xs[i] += p.xs[i];
}
NDimenPoint operator/(const int n) {
if (n == 0) throw std::runtime_error("divisor zero error!");
NDimenPoint res(dimension);
for (size_t i = 0; i < dimension; i++) {
res.xs[i] = xs[i] / n;
}
return res;
}
double disTo(const NDimenPoint &p) {
double tmp = 0;
for (size_t i = 0; i < dimension; i++) tmp += pow(xs[i] - p.xs[i], 2);
return sqrt(tmp);
}
string toString() override {
stringstream ss;
ss << "[";
for (size_t i = 0; i < dimension; i++) {
if (i > 0) ss << ", ";
ss << xs[i];
}
ss << "]";
return ss.str();
}
static double calcDisToCluster(const VirtualPoint &p, const Cluster &c) {
auto pp = static_cast<const NDimenPoint &>(p);
auto cp = static_cast<const NDimenPoint &>(*(c.getCentroid()));
return pp.disTo(cp);
}
static sharedVPoint avgPoints(const vector<sharedVPoint> &points) {
if (points.size() <= 0) return nullptr;
NDimenPoint resPoint(static_cast<const NDimenPoint &>(*points[0]).dimension);
for (auto &&p : points)
resPoint.add(static_cast<const NDimenPoint &>(*p));
resPoint = resPoint / points.size();
// cerr << "DEBUG\t" << resPoint.toString() << ", POINTS.SIZE " << points.size() << endl;
return make_shared<NDimenPoint>(resPoint);
};
};
vector<NDimenPoint> geneData(int num, const int dimension, double maxVal = 1000) {
std::default_random_engine generator(time(NULL));
std::uniform_real_distribution<double> distribution(0, maxVal);
vector<NDimenPoint> points;
for (size_t i = 0; i < num; i++) {
vector<double> tmpVec;
for (size_t j = 0; j < dimension; j++) tmpVec.push_back(distribution(generator));
points.push_back(NDimenPoint(dimension, tmpVec));
}
return points;
}
void output(const vector<Cluster> &clusters, const int dimension) {
cout << "{"
<< "\"dimension\":" << dimension << "," << endl
<< "\"clusters\":[";
for (int i = 0; i < clusters.size(); i++) {
if (i > 0) cout << ", ";
std::cout << clusters[i].toString() << std::endl;
}
cout << "]}" << endl;
}
void kmeans_work() {
const int maxRound = 10000;
int pointCnt = 150;
int dimension = 1;
int k = 0;
cerr << "dimension, k, point_count: ";
cin >> dimension >> k >> pointCnt;
vector<sharedVPoint> points;
for (auto &&p : geneData(pointCnt, dimension))
points.push_back(make_shared<NDimenPoint>(p));
auto clusters = KmeansAlg::run(points, k, NDimenPoint::calcDisToCluster, NDimenPoint::avgPoints, maxRound);
output(clusters, dimension);
}
|
5a25b01e3bbc4cfebda94ec134aad5fd6da34aae | 679287ceb238a82f08b61b6753961cc1f6ffebb6 | /Source/HappyHunting/MoveAround.cpp | 9910a9275c57138688ec77ef381838bca8032922 | [] | no_license | etherealchain/HappyHunting | 3b5c854c3d5d8f66bd52df03dee892204235df0e | 667f86289a32ab959b29893539e38e259dd5d9ab | refs/heads/master | 2021-10-11T09:28:12.059155 | 2018-08-03T08:17:17 | 2018-08-03T08:17:17 | 113,535,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,219 | cpp | MoveAround.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "MoveAround.h"
#include "Runtime/Engine/Classes/Kismet/GameplayStatics.h"
#include "NavigationSystem.h"
void AMoveAround::BeginPlay() {
Super::BeginPlay();
GotoPoint();
}
void AMoveAround::Tick(float DeltaSeconds) {
Super::Tick(DeltaSeconds);
}
void AMoveAround::GotoPoint() {
FNavLocation* result = new FNavLocation;
while (!FNavigationSystem::GetCurrent<UNavigationSystemV1>(GetWorld())->GetRandomReachablePointInRadius(GetNavAgentLocation(), 5000, *result)) {
}
MoveToLocation(result->Location);
/*if (GetWorld()->GetNavigationSystem()->GetRandomReachablePointInRadius(GetNavAgentLocation(), 2000, *result)) {
MoveToLocation(result->Location);
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, result->Location.ToString());
}
else {
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("2"));
}*/
//MoveToActor(Cast<ATargetPoint>(targetPoints[currentIndex]));
}
void AMoveAround::OnMoveCompleted(FAIRequestID id, const FPathFollowingResult& result) {
Super::OnMoveCompleted(id, result);
GetWorldTimerManager().SetTimer(timerHandle, this, &AMoveAround::GotoPoint, 3.0f, false);
} |
1966dcf1a3ba93d6fd5758d2393cf0079e8e4525 | 2fc62aef960dc18f4b2d34be2f69cb86afc75933 | /src/alpaka/test/alpaka/clustering_t.cc | 2466d32fe0c79aedc045ac49895c2af1c76dbeea | [
"Apache-2.0"
] | permissive | ChrisSandever/pixeltrack-standalone | 34d9f956c31d27395f39b2695209ea3d73d702f7 | d26e4c31db144b0068824ee77b681bd0dd8447c1 | refs/heads/master | 2023-08-28T18:41:10.096271 | 2021-10-28T22:36:25 | 2021-10-28T22:36:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,690 | cc | clustering_t.cc | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <memory>
#include <numeric>
#include <set>
#include <vector>
#include "AlpakaCore/alpakaConfig.h"
#include "AlpakaCore/alpakaWorkDivHelper.h"
// dirty, but works
#include "plugin-SiPixelClusterizer/alpaka/gpuClustering.h"
#include "plugin-SiPixelClusterizer/alpaka/gpuClusterChargeCut.h"
int main(void) {
const DevHost host(alpaka::getDevByIdx<PltfHost>(0u));
const ::ALPAKA_ACCELERATOR_NAMESPACE::Device device(
alpaka::getDevByIdx<::ALPAKA_ACCELERATOR_NAMESPACE::Platform>(0u));
::ALPAKA_ACCELERATOR_NAMESPACE::Queue queue(device);
constexpr unsigned int numElements = 256 * 2000;
// these in reality are already on GPU
auto h_id_buf = alpaka::allocBuf<uint16_t, Idx>(host, numElements);
auto h_id = alpaka::getPtrNative(h_id_buf);
auto h_x_buf = alpaka::allocBuf<uint16_t, Idx>(host, numElements);
auto h_x = alpaka::getPtrNative(h_x_buf);
auto h_y_buf = alpaka::allocBuf<uint16_t, Idx>(host, numElements);
auto h_y = alpaka::getPtrNative(h_y_buf);
auto h_adc_buf = alpaka::allocBuf<uint16_t, Idx>(host, numElements);
auto h_adc = alpaka::getPtrNative(h_adc_buf);
auto h_clus_buf = alpaka::allocBuf<int, Idx>(host, numElements);
auto h_clus = alpaka::getPtrNative(h_clus_buf);
auto d_id_buf = alpaka::allocBuf<uint16_t, Idx>(device, numElements);
auto d_x_buf = alpaka::allocBuf<uint16_t, Idx>(device, numElements);
auto d_y_buf = alpaka::allocBuf<uint16_t, Idx>(device, numElements);
auto d_adc_buf = alpaka::allocBuf<uint16_t, Idx>(device, numElements);
auto d_clus_buf = alpaka::allocBuf<int, Idx>(device, numElements);
auto d_moduleStart_buf = alpaka::allocBuf<uint32_t, Idx>(device, gpuClustering::MaxNumModules + 1);
auto d_clusInModule_buf = alpaka::allocBuf<uint32_t, Idx>(device, gpuClustering::MaxNumModules);
auto d_moduleId_buf = alpaka::allocBuf<uint32_t, Idx>(device, gpuClustering::MaxNumModules);
// later random number
unsigned int n = 0;
int ncl = 0;
int y[10] = {5, 7, 9, 1, 3, 0, 4, 8, 2, 6};
auto generateClusters = [&](int kn) {
auto addBigNoise = 1 == kn % 2;
if (addBigNoise) {
constexpr int MaxPixels = 1000;
int id = 666;
for (int x = 0; x < 140; x += 3) {
for (int yy = 0; yy < 400; yy += 3) {
h_id[n] = id;
h_x[n] = x;
h_y[n] = yy;
h_adc[n] = 1000;
++n;
++ncl;
if (MaxPixels <= ncl)
break;
}
if (MaxPixels <= ncl)
break;
}
}
{
// isolated
int id = 42;
int x = 10;
++ncl;
h_id[n] = id;
h_x[n] = x;
h_y[n] = x;
h_adc[n] = kn == 0 ? 100 : 5000;
++n;
// first column
++ncl;
h_id[n] = id;
h_x[n] = x;
h_y[n] = 0;
h_adc[n] = 5000;
++n;
// first columns
++ncl;
h_id[n] = id;
h_x[n] = x + 80;
h_y[n] = 2;
h_adc[n] = 5000;
++n;
h_id[n] = id;
h_x[n] = x + 80;
h_y[n] = 1;
h_adc[n] = 5000;
++n;
// last column
++ncl;
h_id[n] = id;
h_x[n] = x;
h_y[n] = 415;
h_adc[n] = 5000;
++n;
// last columns
++ncl;
h_id[n] = id;
h_x[n] = x + 80;
h_y[n] = 415;
h_adc[n] = 2500;
++n;
h_id[n] = id;
h_x[n] = x + 80;
h_y[n] = 414;
h_adc[n] = 2500;
++n;
// diagonal
++ncl;
for (int x = 20; x < 25; ++x) {
h_id[n] = id;
h_x[n] = x;
h_y[n] = x;
h_adc[n] = 1000;
++n;
}
++ncl;
// reversed
for (int x = 45; x > 40; --x) {
h_id[n] = id;
h_x[n] = x;
h_y[n] = x;
h_adc[n] = 1000;
++n;
}
++ncl;
h_id[n++] = gpuClustering::InvId; // error
// messy
int xx[5] = {21, 25, 23, 24, 22};
for (int k = 0; k < 5; ++k) {
h_id[n] = id;
h_x[n] = xx[k];
h_y[n] = 20 + xx[k];
h_adc[n] = 1000;
++n;
}
// holes
++ncl;
for (int k = 0; k < 5; ++k) {
h_id[n] = id;
h_x[n] = xx[k];
h_y[n] = 100;
h_adc[n] = kn == 2 ? 100 : 1000;
++n;
if (xx[k] % 2 == 0) {
h_id[n] = id;
h_x[n] = xx[k];
h_y[n] = 101;
h_adc[n] = 1000;
++n;
}
}
}
{
// id == 0 (make sure it works!
int id = 0;
int x = 10;
++ncl;
h_id[n] = id;
h_x[n] = x;
h_y[n] = x;
h_adc[n] = 5000;
++n;
}
// all odd id
for (int id = 11; id <= 1800; id += 2) {
if ((id / 20) % 2)
h_id[n++] = gpuClustering::InvId; // error
for (int x = 0; x < 40; x += 4) {
++ncl;
if ((id / 10) % 2) {
for (int k = 0; k < 10; ++k) {
h_id[n] = id;
h_x[n] = x;
h_y[n] = x + y[k];
h_adc[n] = 100;
++n;
h_id[n] = id;
h_x[n] = x + 1;
h_y[n] = x + y[k] + 2;
h_adc[n] = 1000;
++n;
}
} else {
for (int k = 0; k < 10; ++k) {
h_id[n] = id;
h_x[n] = x;
h_y[n] = x + y[9 - k];
h_adc[n] = kn == 2 ? 10 : 1000;
++n;
if (y[k] == 3)
continue; // hole
if (id == 51) {
h_id[n++] = gpuClustering::InvId;
h_id[n++] = gpuClustering::InvId;
} // error
h_id[n] = id;
h_x[n] = x + 1;
h_y[n] = x + y[k] + 2;
h_adc[n] = kn == 2 ? 10 : 1000;
++n;
}
}
}
}
}; // end lambda
for (auto kkk = 0; kkk < 5; ++kkk) {
n = 0;
ncl = 0;
generateClusters(kkk);
std::cout << "created " << n << " digis in " << ncl << " clusters" << std::endl;
assert(n <= numElements);
auto h_nModules_buf = alpaka::allocBuf<uint32_t, Idx>(host, 1u);
auto nModules = alpaka::getPtrNative(h_nModules_buf);
nModules[0] = 0;
alpaka::memcpy(queue, d_moduleStart_buf, h_nModules_buf, 1u);
alpaka::memcpy(queue, d_id_buf, h_id_buf, n);
alpaka::memcpy(queue, d_x_buf, h_x_buf, n);
alpaka::memcpy(queue, d_y_buf, h_y_buf, n);
alpaka::memcpy(queue, d_adc_buf, h_adc_buf, n);
// Launch CUDA Kernels
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
const int threadsPerBlockOrElementsPerThread = (kkk == 5) ? 512 : ((kkk == 3) ? 128 : 256);
#else
// NB: can be tuned.
const int threadsPerBlockOrElementsPerThread = 256;
#endif
// COUNT MODULES
const int blocksPerGridCountModules =
(numElements + threadsPerBlockOrElementsPerThread - 1) / threadsPerBlockOrElementsPerThread;
const WorkDiv1D& workDivCountModules = ::cms::alpakatools::ALPAKA_ACCELERATOR_NAMESPACE::make_workdiv(
Vec1D::all(blocksPerGridCountModules), Vec1D::all(threadsPerBlockOrElementsPerThread));
std::cout << "CUDA countModules kernel launch with " << blocksPerGridCountModules << " blocks of "
<< threadsPerBlockOrElementsPerThread << " threads (GPU) or elements (CPU). \n";
alpaka::enqueue(
queue,
alpaka::createTaskKernel<::ALPAKA_ACCELERATOR_NAMESPACE::Acc1D>(workDivCountModules,
gpuClustering::countModules(),
alpaka::getPtrNative(d_id_buf),
alpaka::getPtrNative(d_moduleStart_buf),
alpaka::getPtrNative(d_clus_buf),
n));
// FIND CLUSTER
const WorkDiv1D& workDivMaxNumModules = ::cms::alpakatools::ALPAKA_ACCELERATOR_NAMESPACE::make_workdiv(
Vec1D::all(gpuClustering::MaxNumModules), Vec1D::all(threadsPerBlockOrElementsPerThread));
std::cout << "CUDA findModules kernel launch with " << gpuClustering::MaxNumModules << " blocks of "
<< threadsPerBlockOrElementsPerThread << " threads (GPU) or elements (CPU). \n";
alpaka::memset(queue, d_clusInModule_buf, 0, gpuClustering::MaxNumModules);
alpaka::enqueue(
queue,
alpaka::createTaskKernel<::ALPAKA_ACCELERATOR_NAMESPACE::Acc1D>(workDivMaxNumModules,
gpuClustering::findClus(),
alpaka::getPtrNative(d_id_buf),
alpaka::getPtrNative(d_x_buf),
alpaka::getPtrNative(d_y_buf),
alpaka::getPtrNative(d_moduleStart_buf),
alpaka::getPtrNative(d_clusInModule_buf),
alpaka::getPtrNative(d_moduleId_buf),
alpaka::getPtrNative(d_clus_buf),
n));
alpaka::memcpy(queue, h_nModules_buf, d_moduleStart_buf, 1u);
auto h_nclus_buf = alpaka::allocBuf<uint32_t, Idx>(host, gpuClustering::MaxNumModules);
auto nclus = alpaka::getPtrNative(h_nclus_buf);
alpaka::memcpy(queue, h_nclus_buf, d_clusInModule_buf, gpuClustering::MaxNumModules);
// Wait for memory transfers to be completed
alpaka::wait(queue);
auto h_moduleId_buf = alpaka::allocBuf<uint32_t, Idx>(host, nModules[0]);
//auto moduleId = alpaka::getPtrNative(h_moduleId_buf);
std::cout << "before charge cut found " << std::accumulate(nclus, nclus + gpuClustering::MaxNumModules, 0)
<< " clusters" << std::endl;
for (auto i = gpuClustering::MaxNumModules; i > 0; i--)
if (nclus[i - 1] > 0) {
std::cout << "last module is " << i - 1 << ' ' << nclus[i - 1] << std::endl;
break;
}
if (ncl != std::accumulate(nclus, nclus + gpuClustering::MaxNumModules, 0))
std::cout << "ERROR!!!!! wrong number of cluster found" << std::endl;
// CLUSTER CHARGE CUT
alpaka::enqueue(
queue,
alpaka::createTaskKernel<::ALPAKA_ACCELERATOR_NAMESPACE::Acc1D>(workDivMaxNumModules,
gpuClustering::clusterChargeCut(),
alpaka::getPtrNative(d_id_buf),
alpaka::getPtrNative(d_adc_buf),
alpaka::getPtrNative(d_moduleStart_buf),
alpaka::getPtrNative(d_clusInModule_buf),
alpaka::getPtrNative(d_moduleId_buf),
alpaka::getPtrNative(d_clus_buf),
n));
alpaka::memcpy(queue, h_id_buf, d_id_buf, n);
alpaka::memcpy(queue, h_clus_buf, d_clus_buf, n);
alpaka::memcpy(queue, h_nclus_buf, d_clusInModule_buf, gpuClustering::MaxNumModules);
alpaka::memcpy(queue, h_moduleId_buf, d_moduleId_buf, nModules[0]);
// Wait for memory transfers to be completed
alpaka::wait(queue);
std::cout << "found " << nModules[0] << " Modules active" << std::endl;
// CROSS-CHECK
std::set<unsigned int> clids;
for (unsigned int i = 0; i < n; ++i) {
assert(h_id[i] != 666); // only noise
if (h_id[i] == gpuClustering::InvId)
continue;
assert(h_clus[i] >= 0);
assert(h_clus[i] < int(nclus[h_id[i]]));
clids.insert(h_id[i] * 1000 + h_clus[i]);
// clids.insert(h_clus[i]);
}
// verify no hole in numbering
auto p = clids.begin();
auto cmid = (*p) / 1000;
assert(0 == (*p) % 1000);
auto c = p;
++c;
std::cout << "first clusters " << *p << ' ' << *c << ' ' << nclus[cmid] << ' ' << nclus[(*c) / 1000] << std::endl;
std::cout << "last cluster " << *clids.rbegin() << ' ' << nclus[(*clids.rbegin()) / 1000] << std::endl;
for (; c != clids.end(); ++c) {
auto cc = *c;
auto pp = *p;
auto mid = cc / 1000;
auto pnc = pp % 1000;
auto nc = cc % 1000;
if (mid != cmid) {
assert(0 == cc % 1000);
assert(nclus[cmid] - 1 == pp % 1000);
// if (nclus[cmid]-1 != pp%1000) std::cout << "error size " << mid << ": " << nclus[mid] << ' ' << pp << std::endl;
cmid = mid;
p = c;
continue;
}
p = c;
// assert(nc==pnc+1);
if (nc != pnc + 1)
std::cout << "error " << mid << ": " << nc << ' ' << pnc << std::endl;
}
std::cout << "found " << std::accumulate(nclus, nclus + gpuClustering::MaxNumModules, 0) << ' ' << clids.size()
<< " clusters" << std::endl;
for (auto i = gpuClustering::MaxNumModules; i > 0; i--)
if (nclus[i - 1] > 0) {
std::cout << "last module is " << i - 1 << ' ' << nclus[i - 1] << std::endl;
break;
}
// << " and " << seeds.size() << " seeds" << std::endl;
} /// end loop kkk
return 0;
}
|
e67f5fe1970b49f495e06e4aa7024f3b8446ad68 | cecfc49fb9254498c3b885ae947cd0d9339f2f9a | /disubstr-2.cpp | bec8838c01ea602771aa404f41ac8d66c2a34fde | [
"Unlicense"
] | permissive | t3nsor/SPOJ | f6e4755fe08654c9a166e5aaf16f6dcbb6fc5099 | 03145e8bf2cefb3e49a0cd0da5ec908e924d4728 | refs/heads/master | 2023-04-28T19:04:32.529674 | 2023-04-17T23:49:49 | 2023-04-17T23:49:49 | 24,963,181 | 279 | 130 | Unlicense | 2020-10-30T00:33:57 | 2014-10-08T22:07:33 | C++ | UTF-8 | C++ | false | false | 1,551 | cpp | disubstr-2.cpp | // 2022-12-28
// This O(N^2) time, O(N) memory (independent of alphabet size) algorithm was
// communicated to me by the late Michael B. Cohen (1992-2017).
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s;
int T; cin >> T;
while (T--) {
cin >> s;
const int N = s.size();
vector<int> L(N, 0);
// We will compute the array L, where for each i, L[i] is the length of
// the longest *non-unique* substring of s whose last character is at
// index i. A substring is non-unique if it also occurs earlier in the
// string. It will then follow that all longer such substrings are
// unique, meaning that there are (i + 1) - L[i] unique substrings with
// last character at index i. Summing over all i gives the final
// result.
//
// To compute L, we loop over all possible offsets k. At a given k, we
// will compute, for each i, the length of the longest common suffix
// of the prefixes ending at positions i and i-k. This can be used to
// improve the current value of L[i].
for (int k = 1; k < N; k++) {
int run = 0;
for (int i = k; i < N; i++) {
if (s[i] == s[i - k]) ++run; else run = 0;
L[i] = max(L[i], run);
}
}
int result = 0;
for (int i = 0; i < N; i++) {
result += (i + 1) - L[i];
}
cout << result << '\n';
}
}
|
1d25327f659fe4594d98724fd5228cdee10dc91d | 5af277b5819d74e61374d1d78c303ac93c831cf5 | /eeg_modelling/edf/parse_edf_lib.h | a66fb6bd9115f05e931359fea4ad000160a08c44 | [
"Apache-2.0"
] | permissive | Ayoob7/google-research | a2d215afb31513bd59bc989e09f54667fe45704e | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | refs/heads/master | 2022-11-11T03:10:53.216693 | 2020-06-26T17:13:45 | 2020-06-26T17:13:45 | 275,205,856 | 2 | 0 | Apache-2.0 | 2020-06-26T16:58:19 | 2020-06-26T16:58:18 | null | UTF-8 | C++ | false | false | 2,182 | h | parse_edf_lib.h | // Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_GOOGLE_RESEARCH_GOOGLE_RESEARCH_EEG_MODELLING_EDF_PARSE_EDF_LIB_H_
#define THIRD_PARTY_GOOGLE_RESEARCH_GOOGLE_RESEARCH_EEG_MODELLING_EDF_PARSE_EDF_LIB_H_
#include <string>
#include <vector>
#include "absl/time/time.h"
#include "edf/base/statusor.h"
#include "edf/edf_file.h"
#include "edf/proto/annotation.pb.h"
#include "edf/proto/segment.pb.h"
using std::string;
namespace eeg_modelling {
// Parses the .edf file and stores the output in a segment proto.
StatusOr<Segment> ParseEdfToSegmentProto(
const string& session_id, const string& filename,
const string& split_segment_by_annotation_with_prefix);
// Parses the .edf file and stores the output in a list of segment protos.
StatusOr<std::vector<Segment>> ParseEdfToSegmentProtos(
const string& session_id, const string& filename,
const string& split_segment_by_annotation_with_prefix);
// Parse all EDF annotations from the given file, in the specified time range of
// [start_time, end_time].
StatusOr<Annotation> ParseEdfToAnnotationProto(
const string& filename, const absl::Time start_time,
const absl::Time end_time,
const string& split_segment_by_annotation_with_prefix);
// Parse all EDF annotations from the given file, keyed by segment identifier.
StatusOr<std::vector<Annotation>> ParseEdfToAnnotationProtoPerSegment(
const string& session_id, const string& filename,
const string& split_segment_by_annotation_with_prefix);
} // namespace eeg_modelling
#endif // THIRD_PARTY_GOOGLE_RESEARCH_GOOGLE_RESEARCH_EEG_MODELLING_EDF_PARSE_EDF_LIB_H_
|
877ad2d43db9105bbfa44421b1d8746f8823f43e | b71096352363517ebe6330a2ef46de7a0cb9757e | /C++/Проги С++/алфавит.cpp | 519b8eadb4899636a61fdbf70b1ac9969bd938c5 | [] | no_license | shumavik/Study | 2c1ce8aa8086e88bd4535a74dbefe0f51771d8a9 | 54d5ce9548ea7709c78a320391c0512a0f9f02bc | refs/heads/master | 2020-03-19T05:27:34.434746 | 2018-09-27T09:35:22 | 2018-09-27T09:35:22 | 135,933,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | cpp | алфавит.cpp | #include <iostream>
using namespace std;
int main()
{
char letter;
for (letter='Z';letter>='A';letter--)
cout<<letter<<endl;
system("pause");
return 0;
} |
dc5b52f72d2a31dba512c42c4276ac8c386b82ae | 450917c1cb067809f019a65185fcb170b6a89c41 | /src/GameObject.cpp | 5167b765a6416b4aa92563bc610ee5b45457aaf4 | [] | no_license | gchadder3/Swarmongers | 02ff4aff498e865a1ed7ff6ec286b964f1f3b353 | 38080b838bc2b691d5e20e651f23ad4e668a9294 | refs/heads/master | 2021-01-13T07:59:45.491842 | 2016-10-24T18:59:29 | 2016-10-24T18:59:29 | 71,665,979 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,938 | cpp | GameObject.cpp | // GameObject.cpp
//
// The source for the GameObject class.
// INCLUDES
#include "GPDUMB_includes.h"
#include "Game.h"
#include "GameObject.h"
#include "GameScreen.h"
#include "Vect.h"
// Globals defined in main.cpp
extern Game *theGame;
extern GameScreen *theScreen;
// PUBLIC FUNCTIONS
void GameObject::SetPosition(float x, float y)
{
int x_min = theScreen->GetMinX();
int x_max = theScreen->GetMaxX();
int y_min = theScreen->GetMinY();
int y_max = theScreen->GetMaxY();
// Clip the position to the screen boundaries.
if ((int) x < x_min)
x = (float) x_min;
if ((int) x > x_max)
x = (float) x_max;
if ((int) y < y_min)
y = (float) y_min;
if ((int) y > y_max)
y = (float) y_max;
position.set(x, y, FALSE);
}
void GameObject::Update(BOOL wraparound)
{
Vect v(velocity);
// Only do anything if the object is alive...
if (alive)
{
int x_min = theScreen->GetMinX();
int x_max = theScreen->GetMaxX();
int y_min = theScreen->GetMinY();
int y_max = theScreen->GetMaxY();
v.div((float) theGame->GetCurrentFPS());
position.add(v);
// Handle off-the-screen motions.
if (position.get_x() > x_max)
{
if (wraparound)
position.set((float) x_min, position.get_y(), FALSE);
else
position.set((float) x_max, position.get_y(), FALSE);
}
else if (position.get_x() < x_min)
{
if (wraparound)
position.set((float) x_max, position.get_y(), FALSE);
else
position.set((float) x_min, position.get_y(), FALSE);
}
if (position.get_y() > y_max)
{
if (wraparound)
position.set(position.get_x(), (float) y_min, FALSE);
else
position.set(position.get_x(), (float) y_max, FALSE);
}
else if (position.get_y() < y_min)
{
if (wraparound)
position.set(position.get_x(), (float) y_max, FALSE);
else
position.set(position.get_x(), (float) y_min, FALSE);
}
}
}
void GameObject::PlayExplodeSound()
{
// sndManager->PlayNonCombatExplode();
}
|
97288c9073fd3532029482843a04f5d6795420c6 | 4b60937fcd43566a11d06becdd9c1792999b5ee0 | /cc3k/merchant.cpp | 08f60cd8bd6ef708d364c7394329b02325d50257 | [] | no_license | KnightArthurRen/cc3k | 128347035f3b8e71a1ed60f98aa24fe6f253695f | c4a41c37bfca2a100736bd83dba8e620080b1750 | refs/heads/master | 2020-01-23T21:44:34.316397 | 2016-11-24T17:55:41 | 2016-11-24T17:55:41 | 74,693,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | cpp | merchant.cpp | //
// merchant.cpp
// cc3k
//
// Created by Tianyi Ben on 2015-07-22.
// Copyright (c) 2015 Tianyi Ben. All rights reserved.
//
#include "merchant.h"
const int Merchant::Merchant_MaxHP = 30;
const int Merchant::Merchant_Atk = 70;
const int Merchant::Merchant_Def = 5;
bool Merchant::hostility = false;
void Merchant::resetHostility() {
hostility = false;
} // resetHostility
Merchant::Merchant() {
race = MERCHANT;
MaxHP = Merchant_MaxHP;
HP = MaxHP;
Atk = Merchant_Atk;
Def = Merchant_Def;
gold_carried = new Gold(Gold::MERCHANT);
} // default ctor
void Merchant::loseHP(int loss) {
hostility = true;
Character::loseHP(loss);
} // loseHP
bool Merchant::isHostile() const {
return hostility;
} // isHostile
|
ec2e1c8bae9c902f5fd59bec2e8b840e55242b13 | ea7de2f16405b945d5a7675fa1f7369d3360a0a2 | /simulator/export/cache/runner.h | cf0cabe454878b52e0e9a9a6c3ac5f64ad711502 | [
"MIT"
] | permissive | cesarus777/mipt-mips | 8851be844f1436613fa3a3586b136c0a162be2cc | c940a7644c4ebb72ad2022d77afdbd4d1dcda0f6 | refs/heads/master | 2020-08-14T00:55:06.560065 | 2019-12-08T09:38:41 | 2019-12-08T09:38:41 | 215,067,711 | 2 | 0 | MIT | 2020-03-22T19:02:29 | 2019-10-14T14:37:44 | C++ | UTF-8 | C++ | false | false | 1,215 | h | runner.h | /**
* Standalone cache simulator
* @author Pavel Kryukov
*/
#ifndef CACHE_RUNNER_H
#define CACHE_RUNNER_H
#include <infra/types.h>
#include <iostream>
#include <memory>
class CacheTagArray;
struct CacheRunnerResults
{
uint64 accesses = 0;
uint64 hits = 0;
uint64 compulsory_misses = 0;
auto get_hit_rate() const noexcept { return accesses == 0 ? 0 : double( hits) / accesses; }
auto get_miss_rate() const noexcept { return 1 - get_hit_rate(); }
auto get_misses() const noexcept { return accesses - hits; }
auto get_compulsory_miss_subrate() const noexcept { return get_misses() == 0 ? 0 : double( compulsory_misses) / get_misses(); }
friend std::ostream& operator<<( std::ostream& out, const CacheRunnerResults& rhs);
};
class CacheRunner
{
public:
CacheRunner() = default;
virtual ~CacheRunner() = default;
CacheRunner( const CacheRunner&) = delete;
CacheRunner( CacheRunner&&) = delete;
CacheRunner& operator=( const CacheRunner&) = delete;
CacheRunner& operator=( CacheRunner&&) = delete;
static std::unique_ptr<CacheRunner> create( CacheTagArray* cache);
virtual CacheRunnerResults run( const std::string& filename) = 0;
};
#endif
|
4efd727bee7efbb759d635ebb05f40703898ffcc | ac7e1b26f4b686d5b76bfe16c7d15137dcaf77d6 | /include/QAPlots.hpp | c29ec430a24ce195e6d62f375a0635a9711149ba | [] | no_license | mhemmer-cern/MA_Plotting | 747c5368a573608fd72c63b4ad2efbc75163cab1 | 1613e3e7364b3bece68bbf7c1a6190a2b73ede14 | refs/heads/master | 2023-04-29T17:11:00.610914 | 2021-05-14T16:10:20 | 2021-05-14T16:10:20 | 308,577,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,927 | hpp | QAPlots.hpp | #include "/home/marvin/C_Headers/Plotting_Patrick.h"
#include "/home/marvin/C_Headers/CommonHeader.h"
#include "/home/marvin/Documents/git/Header/Plot.h"
#include <vector>
void Dalitz01(std::vector<TH1D*> v, TPaveText* lSys, TString outname, TString legHead, Double_t lowX, Double_t highX)
{
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
TString legOpt = "";
for (int i = 0; i < v.size(); i++)
{
v.at(i)->Scale(1./v.at(i)->Integral());
main->Add(v.at(i));
legOpt += "lp ";
if(i < v.size()-1) legString += TString(v.at(i)->GetTitle()) + "\n ";
}
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), legOpt.Data(), legHead.Data()) );
// --- Marker ----------------------------------------------------------------
vector<Color_t> colors = {kBlack, kOrange-3, kViolet-3, kGreen-3, kRed-3, kBlue-3, 1, 1};
vector<Style_t> markers = {kFullSquare, kOpenCircle, kOpenCircle, kOpenCircle, kOpenDiamond, kOpenDiamond, 1, 1};
vector<Size_t> sizes = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1, 1};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.15, 0.5, 0.75-(v.size()+1)*0.025, 0.75);
SquarePlot square = SquarePlot(main.get(), "#it{m}^{2}_{#gamma_{0}#gamma_{1}}", "#it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes);
square.SetRanges(lowX, highX, v.at(0)->GetMinimum(), v.at(0)->GetMaximum()*1.8);
square.SetCanvasMargins(0.025, .1, 0.03, .1);
square.SetCanvasOffsets(1.2, 1.8);
square.SetLog(1, 0);
square.Draw(outname);
return;
}
void Dalitz01MC(std::vector<TH1D*> v, TPaveText* lSys, TString outname, TString legHead, Double_t lowX, Double_t highX)
{
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
TString legOpt = "";
for (int i = 0; i < v.size(); i++)
{
v.at(i)->Scale(1./v.at(i)->Integral());
main->Add(v.at(i));
legOpt += "lp ";
if(i < v.size()-1) legString += TString(v.at(i)->GetTitle()) + "\n ";
}
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), legOpt.Data(), legHead.Data()) );
// --- Marker ----------------------------------------------------------------
vector<Color_t> colors = {kBlack, kBlack, kOrange-3, kViolet-3, kGreen-3, kRed-3, kBlue-3, 1, 1};
vector<Style_t> markers = {kOpenSquare, kFullSquare, kOpenCircle, kOpenCircle, kOpenCircle, kOpenDiamond, kOpenDiamond, 1, 1};
vector<Size_t> sizes = {1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1, 1};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.15, 0.5, 0.75-(v.size()+1)*0.025, 0.75);
SquarePlot square = SquarePlot(main.get(), "#it{m}^{2}_{#gamma_{0}#gamma_{1}}", "#it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes);
square.SetRanges(lowX, highX, v.at(0)->GetMinimum(), v.at(0)->GetMaximum()*1.8);
square.SetCanvasMargins(0.025, .1, 0.03, .1);
square.SetCanvasOffsets(1.2, 1.8);
square.SetLog(1, 0);
square.Draw(outname);
return;
}
void DalitzFit(TH1D* h1, TF1* f1, TPaveText* lSys, TString outname, TString legHead, Double_t lowX, Double_t highX)
{
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
legString += TString(h1->GetTitle()) + "\n ";
legString += TString(f1->GetTitle());
main->Add(h1);
main->Add(f1);
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), "lp l", legHead.Data()) );
// --- Marker ----------------------------------------------------------------
std::vector<Color_t> colors = {kBlack, kOrange-3, 1, 1};
std::vector<Style_t> markers = {kFullSquare, 1, 1, 1};
std::vector<Size_t> sizes = {1.5, 1.5, 1, 1};
std::vector<Style_t> linestyle = {1, 1, 1, 1};
std::vector<Size_t> linewidth = {1.5, 3., 1., 1.};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.15, 0.5, 0.75-3*0.025, 0.75);
SquarePlot square = SquarePlot(main.get(), "#it{m}^{2}_{#gamma_{0}#gamma_{1}}", "#it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes, linestyle, linewidth);
square.SetRanges(lowX, highX, h1->GetMinimum(), h1->GetMaximum()*1.4);
square.SetCanvasMargins(0.025, .1, 0.03, .1);
square.SetCanvasOffsets(1.2, 1.8);
square.SetLog(1, 0);
square.Draw(outname);
return;
}
void OmegaPiZeroCosTheta(std::vector<TH1D*> v, TPaveText* lSys, TString outname, TString legHead)
{
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
TString legOpt = "";
for (int i = 0; i < v.size(); i++)
{
v.at(i)->Scale(1./v.at(i)->Integral());
main->Add(v.at(i));
legOpt += "lp ";
if(i < v.size()-1) legString += TString(v.at(i)->GetTitle()) + "\n ";
}
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), legOpt.Data(), legHead.Data()) );
// --- Marker ----------------------------------------------------------------
vector<Color_t> colors = {kBlack, kOrange-3, kViolet-3, kGreen-3, kRed-3, kBlue-3, 1, 1};
vector<Style_t> markers = {kFullSquare, kOpenSquare, kOpenCircle, kOpenDiamond, kOpenDiamond, kOpenDiamond, 1, 1};
vector<Size_t> sizes = {3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 1, 1};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.55, 0.9, 0.9-((v.size()+1)*0.035), 0.9);
SquarePlot square = SquarePlot(main.get(), "cos(#theta^{*})", "norm. #it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes);
square.SetRanges(-1., 1., v.at(1)->GetMinimum(), v.at(1)->GetMaximum()*1.6);
square.SetCanvasMargins(0.025, .1, 0.03, .1);
square.Draw(outname);
return;
}
void OpeningAngle(std::vector<TH1D*> v, TPaveText* lSys, TString outname, TString legHead, Double_t lowX, Double_t highX)
{
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
TString legOpt = "";
for (int i = 0; i < v.size(); i++)
{
v.at(i)->Scale(1./v.at(i)->Integral());
main->Add(v.at(i));
legOpt += "lp ";
if(i < v.size()-1) legString += TString(v.at(i)->GetTitle()) + "\n ";
}
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), legOpt.Data()) );
// --- Marker ----------------------------------------------------------------
vector<Color_t> colors = {kBlack, kOrange-3, kViolet-3, kGreen-3, kRed-3, kBlue-3, 1, 1};
vector<Style_t> markers = {kFullSquare, kOpenSquare, kOpenCircle, kOpenDiamond, kOpenDiamond, kOpenDiamond, 1, 1};
vector<Size_t> sizes = {3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 1, 1};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.55, 0.9, 0.9-(v.size()*0.035), 0.9);
SquarePlot square = SquarePlot(main.get(), legHead.Data(), "norm. #it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes);
square.SetRanges(lowX, highX, v.at(0)->GetMinimum(), v.at(0)->GetMaximum()*1.6);
square.SetCanvasMargins(0.025, .1, 0.03, .1);
square.Draw(outname);
return;
}
SquarePlot OmegaPiZeroCosThetaRatio(TH1D* hRatio, TPaveText* lSys)
{
// --- Create TObjArrays -----------------------------------------------------
TObjArray* main = new TObjArray();
hRatio->SetMaximum(hRatio->GetMaximum()*1.8);
main->Add(hRatio);
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
TLegend* l = Legend(main, "data/MC truth", "lp").GetLegendPointer();
// --- Marker ----------------------------------------------------------------
vector<Color_t> colors = {kBlack};
vector<Style_t> markers = {kFullCircle};
vector<Size_t> sizes = {2.};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l, 0.55, 0.9, 0.67, 0.875);
SquarePlot square = SquarePlot(main, "cos(#theta*)", "#frac{data}{MC truth}");
square.SetMode(Plot::Thesis);
square.SetRanges(0.0, 1.0, hRatio->GetMinimum(), hRatio->GetMaximum());
square.SetStyle(colors, markers, sizes);
return square;
}
void AlphaPlot(TH2D* h2, TLegend* lSys, TString outname)
{
std::unique_ptr<TObjArray> main (new TObjArray);
h2->SetContour(500);
main->Add(h2);
main->Add(lSys);
// --- Canvasses -------------------------------------------------------------
HeatMapPlot plot = HeatMapPlot(main.get(), "#it{p}_{T} (GeV/#it{c})", "#alpha", "count");
plot.SetMode(Plot::Thesis);
plot.SetPalette(109);
plot.SetRanges(h2->GetXaxis()->GetBinLowEdge(1), h2->GetXaxis()->GetBinLowEdge(-1), -1, 1, 0, h2->GetMaximum());
plot.SetCanvasMargins(0.16, .1, 0.05, .1);
// plot.SetCanvasOffsets(1.2, 1.8);
plot.SetLog(0, 0, 0);
plot.Draw(outname);
return;
}
void Pi0Plot(TH2D* h2, TLegend* lSys, TString outname)
{
std::unique_ptr<TObjArray> main (new TObjArray);
h2->SetContour(500);
main->Add(h2);
main->Add(lSys);
// --- Canvasses -------------------------------------------------------------
HeatMapPlot plot = HeatMapPlot(main.get(), TString(minv_str), TString(pt_str), TString("count"));
plot.SetMode(Plot::Thesis);
plot.SetPalette(109);
plot.SetRanges(h2->GetXaxis()->GetBinLowEdge(1), h2->GetXaxis()->GetBinLowEdge(-1), h2->GetYaxis()->GetBinLowEdge(1), h2->GetYaxis()->GetBinLowEdge(-1), h2->GetMinimum(), h2->GetMaximum());
plot.SetCanvasMargins(0.16, .12, 0.05, .1);
plot.SetLog(0, 0, 1);
plot.Draw(outname);
return;
}
void OACPlot(TH2D* h1, TF1* f1, TF1* f2, TPaveText* lSys, TString outname)
{
h1->SetContour(500);
// --- Create TObjArrays -----------------------------------------------------
std::unique_ptr<TObjArray> main (new TObjArray);
TString legString = "";
legString += TString(h1->GetTitle()) + "\n ";
legString += TString(f1->GetTitle()) + "\n ";
legString += TString(f2->GetTitle());
main->Add(h1);
main->Add(f1);
main->Add(f2);
// --- Legends ---------------------------------------------------------------
main->Add(lSys);
std::unique_ptr<Legend> l (new Legend(main.get(), legString.Data(), "p l l") );
// --- Marker ----------------------------------------------------------------
std::vector<Color_t> colors = {1, kOrange+7, kOrange+7, 1, 1};
std::vector<Style_t> markers = {1, 1, 1, 1, 1};
std::vector<Size_t> sizes = {1, 1, 1, 1, 1};
std::vector<Style_t> linestyle = {1, 1, 1, 1, 1};
std::vector<Size_t> linewidth = {1.5, 3., 3., 1., 1.};
// --- Canvasses -------------------------------------------------------------
Legend::SetPosition(l.get(), 0.55, 0.9, 0.9-3*0.035, 0.9);
HeatMapPlot square = HeatMapPlot(main.get(), pt_str, "#theta_{#pi^{0}#gamma} (rad)", "#it{count}");
square.SetMode(Plot::Thesis);
square.SetStyle(colors, markers, sizes, linestyle, linewidth);
square.SetRanges(0.0, 50.0, 0.009, 5., h1->GetMinimum(), h1->GetMaximum());
square.SetCanvasMargins(0.1, .1, 0.03, .1);
square.SetLog(0, 1, 0);
square.Draw(outname);
return;
}
|
ca4f75a08c7fafda3818acde2a364989f31e6742 | 948b7f832f248662963bf9743b2474ea27fa9c06 | /TESTS/operators/constants_quantize.hpp | b3684834a66000a1192295f6bb376664ab3b125e | [
"Apache-2.0"
] | permissive | arijitdas123student/uTensor | 2522bbebc87c9aba03ae8272e8de72e4389e69ff | b36b3677f9663f989ed1c10caf35f038151dc0f0 | refs/heads/master | 2023-03-15T11:27:11.836083 | 2021-01-16T13:07:40 | 2021-01-16T13:07:40 | 330,164,139 | 0 | 0 | Apache-2.0 | 2021-03-08T15:34:09 | 2021-01-16T13:04:12 | C++ | UTF-8 | C++ | false | false | 10,424 | hpp | constants_quantize.hpp | #ifndef _REFERENCE_0_QUANTIZE_H
#define _REFERENCE_0_QUANTIZE_H
static const float input_arr[784] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3294117748737335, 0.7254902124404907, 0.6235294342041016, 0.5921568870544434, 0.23529411852359772, 0.1411764770746231, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.8705882430076599, 0.9960784316062927, 0.9960784316062927, 0.9960784316062927, 0.9960784316062927, 0.9450980424880981, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.7764706015586853, 0.6666666865348816, 0.20392157137393951, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.26274511218070984, 0.4470588266849518, 0.2823529541492462, 0.4470588266849518, 0.6392157077789307, 0.8901960849761963, 0.9960784316062927, 0.8823529481887817, 0.9960784316062927, 0.9960784316062927, 0.9960784316062927, 0.9803921580314636, 0.8980392217636108, 0.9960784316062927, 0.9960784316062927, 0.5490196347236633, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.06666667014360428, 0.25882354378700256, 0.054901961237192154, 0.26274511218070984, 0.26274511218070984, 0.26274511218070984, 0.23137255012989044, 0.08235294371843338, 0.9254902005195618, 0.9960784316062927, 0.4156862795352936, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.32549020648002625, 0.9921568632125854, 0.8196078538894653, 0.07058823853731155, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.08627451211214066, 0.9137254953384399, 1.0, 0.32549020648002625, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5058823823928833, 0.9960784316062927, 0.9333333373069763, 0.1725490242242813, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.23137255012989044, 0.9764705896377563, 0.9960784316062927, 0.24313725531101227, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5215686559677124, 0.9960784316062927, 0.7333333492279053, 0.019607843831181526, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.03529411926865578, 0.8039215803146362, 0.9725490212440491, 0.22745098173618317, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4941176474094391, 0.9960784316062927, 0.7137255072593689, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.29411765933036804, 0.9843137264251709, 0.9411764740943909, 0.2235294133424759, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.07450980693101883, 0.8666666746139526, 0.9960784316062927, 0.6509804129600525, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0117647061124444, 0.7960784435272217, 0.9960784316062927, 0.8588235378265381, 0.13725490868091583, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14901961386203766, 0.9960784316062927, 0.9960784316062927, 0.3019607961177826, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.12156862765550613, 0.8784313797950745, 0.9960784316062927, 0.45098039507865906, 0.003921568859368563, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5215686559677124, 0.9960784316062927, 0.9960784316062927, 0.20392157137393951, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.239215686917305, 0.9490196108818054, 0.9960784316062927, 0.9960784316062927, 0.20392157137393951, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4745098054409027, 0.9960784316062927, 0.9960784316062927, 0.8588235378265381, 0.1568627506494522, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4745098054409027, 0.9960784316062927, 0.8117647171020508, 0.07058823853731155, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
static const int8_t ref_output_arr[784] = { -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -44, 57, 31, 23, -68, -92, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, 94, 126, 126, 126, 126, 113, 70, 70, 70, 70, 70, 70, 70, 70, 42, -76, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -61, -14, -56, -14, 35, 99, 126, 97, 126, 126, 126, 122, 101, 126, 126, 12, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -111, -62, -114, -61, -61, -61, -69, -107, 108, 126, -22, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -45, 125, 81, -110, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -106, 105, 127, -45, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, 1, 126, 110, -84, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -69, 121, 126, -66, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, 5, 126, 59, -123, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -119, 77, 120, -70, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -2, 126, 54, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -53, 123, 112, -71, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -109, 93, 126, 38, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -125, 75, 126, 91, -93, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -90, 126, 126, -51, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -97, 96, 126, -13, -127, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, 5, 126, 126, -76, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -67, 114, 126, 126, -76, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -7, 126, 126, 91, -88, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -7, 126, 79, -110, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128 };
#endif // _REFERENCE_0_QUANTIZE_H |
18d2408a6a25b4b2d34b13feae9842cdc6d73cf8 | 84492b0c51f667b6b676c4f7d1c89628c215b60a | /cocos2dx_plugin/cocos2d/external/bullet/BulletMultiThreaded/SpuFakeDma.cpp | 7d2eea6daaf3c0c02e5257621606142f5e3c1bf9 | [
"MIT"
] | permissive | ucreates/cocos2dx_plugin | 5010a16ebc47e9575121879085e6bc754ae89b1d | 4edb82646761fdc965222247bbf5a3fb206cbf2d | refs/heads/master | 2021-08-30T04:48:52.715410 | 2017-12-16T03:16:28 | 2017-12-16T03:16:28 | 114,429,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,477 | cpp | SpuFakeDma.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SpuFakeDma.h"
#include <bullet/LinearMath/btScalar.h> //for btAssert
// Disabling memcpy sometimes helps debugging DMA
#define USE_MEMCPY 1
#ifdef USE_MEMCPY
#endif
void* cellDmaLargeGetReadOnly(void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
#if defined(__SPU__) || defined(USE_LIBSPE2)
cellDmaLargeGet(ls, ea, size, tag, tid, rid);
return ls;
#else
return (void*)(ppu_address_t)ea;
#endif
}
void* cellDmaSmallGetReadOnly(void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
#if defined(__SPU__) || defined(USE_LIBSPE2)
mfc_get(ls, ea, size, tag, 0, 0);
return ls;
#else
return (void*)(ppu_address_t)ea;
#endif
}
void* cellDmaGetReadOnly(void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
#if defined(__SPU__) || defined(USE_LIBSPE2)
cellDmaGet(ls, ea, size, tag, tid, rid);
return ls;
#else
return (void*)(ppu_address_t)ea;
#endif
}
/// this unalignedDma should not be frequently used, only for small data. It handles alignment and performs check on size (<16 bytes)
int stallingUnalignedDmaSmallGet(void* ls, uint64_t ea, uint32_t size) {
btAssert(size < 32);
ATTRIBUTE_ALIGNED16(char tmpBuffer[32]);
char* localStore = (char*)ls;
uint32_t i;
/// make sure last 4 bits are the same, for cellDmaSmallGet
uint32_t last4BitsOffset = ea & 0x0f;
char* tmpTarget = tmpBuffer + last4BitsOffset;
#if defined(__SPU__) || defined(USE_LIBSPE2)
int remainingSize = size;
//#define FORCE_cellDmaUnalignedGet 1
#ifdef FORCE_cellDmaUnalignedGet
cellDmaUnalignedGet(tmpTarget, ea, size, DMA_TAG(1), 0, 0);
#else
char* remainingTmpTarget = tmpTarget;
uint64_t remainingEa = ea;
while (remainingSize) {
switch (remainingSize) {
case 1:
case 2:
case 4:
case 8:
case 16: {
mfc_get(remainingTmpTarget, remainingEa, remainingSize, DMA_TAG(1), 0, 0);
remainingSize = 0;
break;
}
default: {
// spu_printf("unaligned DMA with non-natural size:%d\n",remainingSize);
int actualSize = 0;
if (remainingSize > 16)
actualSize = 16;
else if (remainingSize > 8)
actualSize = 8;
else if (remainingSize > 4)
actualSize = 4;
else if (remainingSize > 2)
actualSize = 2;
mfc_get(remainingTmpTarget, remainingEa, actualSize, DMA_TAG(1), 0, 0);
remainingSize -= actualSize;
remainingTmpTarget += actualSize;
remainingEa += actualSize;
}
}
}
#endif // FORCE_cellDmaUnalignedGet
#else
char* mainMem = (char*)ea;
// copy into final destination
#ifdef USE_MEMCPY
memcpy(tmpTarget, mainMem, size);
#else
for (i = 0; i < size; i++) {
tmpTarget[i] = mainMem[i];
}
#endif // USE_MEMCPY
#endif
cellDmaWaitTagStatusAll(DMA_MASK(1));
// this is slowish, perhaps memcpy on SPU is smarter?
for (i = 0; btLikely(i < size); i++) {
localStore[i] = tmpTarget[i];
}
return 0;
}
#if defined(__SPU__) || defined(USE_LIBSPE2)
#else
int cellDmaLargeGet(void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
char* mainMem = (char*)ea;
char* localStore = (char*)ls;
#ifdef USE_MEMCPY
memcpy(localStore, mainMem, size);
#else
for (uint32_t i = 0; i < size; i++) {
localStore[i] = mainMem[i];
}
#endif
return 0;
}
int cellDmaGet(void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
char* mainMem = (char*)ea;
char* localStore = (char*)ls;
// printf("mainMem=%x, localStore=%x",mainMem,localStore);
#ifdef USE_MEMCPY
memcpy(localStore, mainMem, size);
#else
for (uint32_t i = 0; i < size; i++) {
localStore[i] = mainMem[i];
}
#endif //#ifdef USE_MEMCPY
// printf(" finished\n");
return 0;
}
int cellDmaLargePut(const void* ls, uint64_t ea, uint32_t size, uint32_t tag, uint32_t tid, uint32_t rid) {
char* mainMem = (char*)ea;
const char* localStore = (const char*)ls;
#ifdef USE_MEMCPY
memcpy(mainMem, localStore, size);
#else
for (uint32_t i = 0; i < size; i++) {
mainMem[i] = localStore[i];
}
#endif //#ifdef USE_MEMCPY
return 0;
}
void cellDmaWaitTagStatusAll(int ignore) {}
#endif
|
4ac55ab0449b061d5e6074e3a9f862e40a07fe5d | 89c09597aaef80fffc92615367bca5ca365fad3c | /duthread.cpp | fab341f294d9f56569e398eb1cceb20207cda418 | [] | no_license | Luis-Enrique-Mora/First-project-Data-Structures | 0a9ba0ed8a3d9675f304188f55f8f4a7df463824 | 61bc4ec8469de77ff9371f97fc40ca5b236b78ec | refs/heads/master | 2022-02-21T18:02:46.637628 | 2019-10-04T00:43:14 | 2019-10-04T00:43:14 | 212,514,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49 | cpp | duthread.cpp | #include "duthread.h"
DuThread::DuThread()
{
}
|
a74a8dac739e87c09ea7e7626149a28752513597 | 51bf6e8b1ad490252c3a43059ce2681c2f0b2070 | /tools/tracer/src/tool/main.cpp | d4a43a38791f31e679131a65aea1da4c30435942 | [
"Apache-2.0"
] | permissive | Bhaskers-Blu-Org1/chopstix | d9ab664e537cd530c1662c12ac392dacbe6ea651 | 1c5e0d30dc37fc8b910c899f2445752b40f22377 | refs/heads/master | 2022-03-19T08:57:50.861722 | 2019-11-20T18:58:42 | 2019-11-21T18:03:35 | 275,842,769 | 0 | 1 | Apache-2.0 | 2020-06-29T14:42:02 | 2020-06-29T14:42:01 | null | UTF-8 | C++ | false | false | 13,398 | cpp | main.cpp | /*
#
# ----------------------------------------------------------------------------
#
# Copyright 2019 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ----------------------------------------------------------------------------
#
*/
#include "arch.h"
#include "client.h"
#include "common/check.h"
#include "common/maps.h"
#include "common/filesystem.h"
#include "common/format.h"
#include "common/log.h"
#include "common/param.h"
#include "process.h"
#include <cstring>
#include <fstream>
#include <vector>
#include <algorithm>
#include <sys/syscall.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
using namespace cxtrace;
namespace fs = filesystem;
#define PERM_664 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH
static void run_child(char **argv) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execvp(*argv, argv);
}
static void run_parent(pid_t child) {
int status;
waitpid(child, &status, 0);
check(WIFSTOPPED(status), "Expected stop signal");
ptrace(PTRACE_CONT, child, 0, 0);
waitpid(child, &status, 0);
check(WIFEXITED(status), "Expected exit");
}
static long read_alt_stack() {
char fname[PATH_MAX];
fmt::format(fname, sizeof(fname), "%s/_alt_stack", getparam("trace"));
int stack_fd = ::open(fname, O_RDONLY);
stack_t alt_stack;
int n = read(stack_fd, &alt_stack, sizeof(stack_t));
log::debug("alt stack at %x-%x", (unsigned long)alt_stack.ss_sp,
(unsigned long)alt_stack.ss_sp + alt_stack.ss_size);
return (long) alt_stack.ss_sp + alt_stack.ss_size / 2;
}
#define PERM_R PROT_READ
#define PERM_W PROT_WRITE
#define PERM_X PROT_EXEC
#define PERM_RW (PROT_READ | PROT_WRITE)
#define PERM_RX (PROT_READ | PROT_EXEC)
#define PERM_WX (PROT_WRITE | PROT_EXEC)
#define PERM_RWX (PROT_READ | PROT_WRITE | PROT_EXEC)
const char *encode_perm(int prot) {
switch (prot) {
case PERM_R: return "r--";
case PERM_W: return "-w-";
case PERM_X: return "--x";
case PERM_RW: return "rw-";
case PERM_RX: return "r-x";
case PERM_WX: return "-wx";
case PERM_RWX: return "rwx";
default: return "---";
}
}
struct mmap_call {
unsigned long addr;
unsigned long length;
unsigned long prot;
};
static unsigned long upper_div(unsigned long a, unsigned long b) {
return (a + b - 1) / b;
}
static void track_mmap(Process &child, arch::regbuf_type ®s) {
std::vector<mmap_call> restrict_map;
long pagesize = sysconf(_SC_PAGESIZE);
long args[7];
while (1) {
int sig;
child.syscall();
child.wait();
checkx(child.stopped(), "Child did not stop");
sig = child.stop_sig();
if (sig == SIGUSR1) {
log::debug("System finished setup");
break;
}
checkx(sig == SIGTRAP, "Expected trap/breakpoint, found %s",
strsignal(sig));
arch::read_regs(child.pid(), regs);
long syscall_nr = arch::get_syscall(regs);
arch::get_args(regs, args);
// 0 , 1 , 2 , 3 , 4 , 5
// mmap(addr, length, prot, flags, fd, offset)
// 0 , 1
// munmap(addr, length)
child.syscall();
child.wait();
checkx(child.stopped(), "Child did not stop");
sig = child.stop_sig();
checkx(sig == SIGTRAP, "Expected trap/breakpoint, found %s",
strsignal(sig));
arch::read_regs(child.pid(), regs);
long ret = arch::get_ret(regs);
if (syscall_nr == SYS_mmap) {
mmap_call mmap;
mmap.addr = ret;
mmap.length = args[1];
mmap.prot = args[2];
log::debug("mmap %x-%x %s", mmap.addr, mmap.addr + mmap.length,
encode_perm(mmap.prot));
restrict_map.push_back(mmap);
} else if (syscall_nr == SYS_munmap) {
// TODO This is a hack!
mmap_call munmap;
munmap.addr = args[0];
munmap.length = args[1];
log::verbose("munmap %x-%x", munmap.addr, munmap.addr + munmap.length);
auto end = std::remove_if(restrict_map.begin(), restrict_map.end(),
[&](const mmap_call &mmap) {
return mmap.addr == munmap.addr
&& mmap.length == munmap.length; });
restrict_map.erase(end);
}
}
char fname[PATH_MAX];
fmt::format(fname, sizeof(fname), "%s/_restrict_map", getparam("trace"));
FILE *fp = fopen(fname, "w");
check(fp, "Unable to open restrict_map");
for (auto ® : restrict_map) {
reg.length = upper_div(reg.length, pagesize) * pagesize;
fprintf(fp, "%lx-%lx %s 0 0:0 0 [restrict]\n", reg.addr, reg.addr + reg.length,
encode_perm(reg.prot));
}
fclose(fp);
}
int main(int argc, char **argv) {
set_defaults();
int n = parse_args(argc - 1, argv + 1) + 1;
checkx(argc > n, "No command. See '%s --help'", argv[0]);
// checkx(getparam("begin"), "No begin address set");
// checkx(getparam("end"), "No end address set");
checkx(getparam("trace"), "No trace path");
bool save_regs = atoi(getparam("save", "0")) != 0;
bool drytrace = atoi(getparam("drytrace", "0")) != 0;
const char *trace_path = getparam("trace", "trace");
double sample_freq = atof(getparam("freq", "1"));
if (getparam("seed")) srandom(atoi(getparam("seed")));
bool nolib = atoi(getparam("nolib", "0")) != 0;
double tidle = atof(getparam("tidle", "0"));
double tsample = atof(getparam("tsample", "0"));
int max_traces = atoi(getparam("max-traces", "0"));
int max_pages = atoi(getparam("max-pages", "0"));
int group_iter = atoi(getparam("group-iter", "1"));
fs::mkdir(getparam("trace"));
setenv("LD_BIND_NOW", "1", 1);
preload(library_path());
Process child;
child.exec(argv + n);
child.ready();
unsetenv("LD_PRELOAD");
log::verbose("spawned child process %d", child.pid());
auto addr_begin = getaddrs("begin");
auto addr_end = getaddrs("end");
bool with_region = addr_begin.size() > 0;
auto start_trace = child.find_symbol("cxtrace_start_trace", library_path());
auto stop_trace = child.find_symbol("cxtrace_stop_trace", library_path());
Location module_offset = getparam("module")
? child.find_module(getparam("module"))
: Location::Address(0);
Location the_stack = child.find_module("[stack]");
Location vdso = child.find_module("[vdso]");
auto regs = arch::create_regs();
auto tmp_regs = arch::create_regs();
long trace_id = 0;
char fname[PATH_MAX];
bool sample_next;
track_mmap(child, regs);
// child.cont();
// child.waitfor(SIGUSR1);
log::debug("system finished setup");
long alt_stack = read_alt_stack();
long cur_pc;
while (1) {
if (tidle > 0) child.timeout(tidle);
sample_next = next_rand() < sample_freq;
if (!child.active()) break;
if (with_region) {
for (auto addr : addr_begin) {
child.set_break(addr + module_offset.addr());
}
child.cont();
child.waitfor(SIGILL);
if (!child.active()) break;
}
cur_pc = arch::get_pc(child.pid());
// arch::set_pc(child.pid(), cur_pc);
// log::verbose("enter region %x", cur_pc);
if (with_region) {
for (auto addr : addr_begin) {
child.remove_break(addr + module_offset.addr());
}
}
if (sample_next) {
log::verbose("start trace %d at 0x%x", trace_id, cur_pc);
if (save_regs || (drytrace && trace_id == 0)) {
if (trace_id % group_iter == 0) {
arch::read_regs(child.pid(), regs);
fmt::format(fname, sizeof(fname), "%s/regs.%d", trace_path, trace_id);
FILE *fp = fopen(fname, "w");
arch::dump_regs(fp, regs);
fclose(fp);
fmt::format(fname, sizeof(fname), "/proc/%d/maps", child.pid());
std::string from{fname};
fmt::format(fname, sizeof(fname), "%s/maps.%d", trace_path, trace_id);
std::string to{fname};
fs::copy(from, to);
}
}
if (!nolib) child.dyn_call(start_trace, regs, alt_stack);
}
if (tsample > 0) child.timeout(tsample);
if (!child.active()) break;
if (with_region) {
for (auto addr : addr_end) {
child.set_break(addr + module_offset.addr());
}
child.syscall();
bool inside_lib = false;
while (1) {
child.wait();
if (!child.stopped()) break;
int sig = child.stop_sig();
if (sig == SIGILL) {
// hit breakpoint
break;
// } else if (sig == SIGUSR1) {
// inside_lib = !inside_lib;
// child.syscall();
} else if (sig == SIGTRAP) {
// enter syscall
arch::read_regs(child.pid(), tmp_regs);
long sc_nr = arch::get_syscall(tmp_regs);
long lnk_reg = arch::get_lnk(child.pid());
bool in_vdso = lnk_reg >= vdso.addr();
bool in_support = start_trace.entry().contains(lnk_reg);
cur_pc = arch::get_pc(child.pid());
// finish syscall
child.syscall();
child.wait();
if (!in_support && !in_vdso) {
log::verbose("system call %d from %x", sc_nr, cur_pc);
log::verbose("split trace %d at %x", trace_id, cur_pc);
if (!nolib) child.dyn_call(stop_trace, regs, alt_stack);
++trace_id;
if (save_regs || (drytrace && trace_id == 0)) {
if (trace_id % group_iter == 0) {
arch::read_regs(child.pid(), regs);
fmt::format(fname, sizeof(fname), "%s/regs.%d", trace_path, trace_id);
FILE *fp = fopen(fname, "w");
arch::dump_regs(fp, regs);
fclose(fp);
fmt::format(fname, sizeof(fname), "/proc/%d/maps", child.pid());
std::string from{fname};
fmt::format(fname, sizeof(fname), "%s/maps.%d", trace_path, trace_id);
std::string to{fname};
fs::copy(from, to);
}
}
log::verbose("start trace %d at %x", trace_id, cur_pc);
if (!nolib) child.dyn_call(start_trace, regs, alt_stack);
}
// continue
child.syscall();
} else {
// forward signal
child.syscall(sig);
}
}
// child.cont();
// child.waitfor(SIGILL);
if (!child.active()) break;
for (auto addr : addr_end) {
child.remove_break(addr + module_offset.addr());
}
}
cur_pc = arch::get_pc(child.pid());
// arch::set_pc(child.pid(), cur_pc);
// log::verbose("exit region %x", cur_pc);
if (sample_next) {
if (!nolib) child.dyn_call(stop_trace, regs, alt_stack);
log::verbose("stop trace %d at %x", trace_id, cur_pc);
++trace_id;
}
if (max_pages > 0) {
fmt::format(fname, sizeof(fname), "%s/_page_count", trace_path);
int pagecount;
int fd = ::open(fname, O_RDONLY);
int n = ::read(fd, &pagecount, sizeof(int));
if (pagecount >= max_pages) {
log::verbose("collected enough pages");
child.cont(SIGTERM);
child.wait();
}
}
if (max_traces && trace_id == max_traces) {
log::verbose("collected enough traces");
child.cont(SIGTERM);
child.wait();
break;
}
}
log::info("collected %d traces", trace_id);
free(regs);
free(tmp_regs);
if (child.exited()) {
log::verbose("child exited with %d", child.exit_status());
}
}
|
1c613ae4c9f43795c49f0d38dd49c0eb33ece1b3 | 1a930008e9317cd360795d865102d7c7528cd871 | /Assignments/program_1/main.cpp | 24ff3f6a32355a06d53e53fbd24d188f2a44ad71 | [] | no_license | EditSokotsu/3013-Algorithms-Muskwe | 92a44a30b32246d4c01aa120035515655d73e8fc | 9d1ad41dd06abc4f377711f3aecde1184c9551ef | refs/heads/master | 2021-05-11T03:46:58.719644 | 2018-02-15T18:04:19 | 2018-02-15T18:04:19 | 117,923,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,849 | cpp | main.cpp | ///////////////////////////////////////////////////////////////////////////////
// Title: Assignment #2
// Files: main.cpp
// Semester: CMPS 3013 Spring 2018
//
// Author: Yani Muskwe
// Email: hellrazor_17@yahoo.com
// Description:
// This program runs a linked list that implements two types of
// insert methods; an ordered insert, that maintains order throughout,
// and a front insert.
/////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <ctime>
using namespace std;
//Create a container for our list data
struct node {
int data;
node* next;
};
/**
* Class: intLinkedList
* Purpose:
* Implements a singly linked list that holds integers.
* Methods:
* void frontSert(int x)
* node* find(int key)
* node* remove(int key)
* void print()
*/
class intLinkedList {
private:
node* Head;
public:
intLinkedList() {
Head = NULL;
}
void frontSert(int x) {
//empty list case
if (!Head) {
Head = new node;
Head->data = x;
Head->next = NULL;
}
else {//not empty list
node* T = new node;
T->data = x;
T->next = Head;
Head = T;
}
}
//@func: orderedSert()
//@para: int x
//@comm: inserts items to the list, in ascending order.
void orderedSert(int x) {
//empty list case
if (!Head) {
frontSert(x);
}
else {//not empty list, maintain ascending order.
node* p = Head; //temporary pointer
node* T = new node;//new node to be inserted
T->data = x;
if (p->data > T->data) {
frontSert(x);
}
else {
while (p->next != NULL &&
p->next->data < T->data)
{
p = p->next;
}
T->next = p->next;
p->next = T;
}
}
}
//@func: Find()
//@para: int key
//@comm: finds any integer in the linked list.
node* Find(int key) {
node* temp = Head;
while (temp) {
if (temp->data == key) {
return temp;
}
temp = temp->next;
}
return NULL;
}
//@func: Remove()
//@para: int key
//@comm: removes any integer from the list.
void Remove(int key) {
node* result = Find(key);
if (result) {
node* temp = Head;
while (temp->next != result) {
temp = temp->next;
}
temp->next = result->next;
delete result;
}
}
//@func: print()
//@para: none
//@comm: prints the linked list.
void print() {
node* p = Head;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
};
int main() {
// seed random number generator
srand(8734587);
// declare instance of intLinkedList turning
// a class definition into an "object"
intLinkedList mylist;
intLinkedList mylist_2;
//Load 10 random ints into our list
for (int i = 0; i<10; i++) {
mylist.frontSert(rand() % 100);
mylist_2.orderedSert(rand() % 100);
}
//print the list
mylist.print();
//print orderedSert() list
mylist_2.print();
system("pause");
} |
a66b7dd93571636565552fd3c5df8cc40d698c36 | 19b08c0a6fe68a2bc32748e6d0eb8d83f52a7aae | /CopyingMachine3/Logic files/RecognizedText.cpp | cbf44e953b087b92550aa4ee749c340713a26609 | [] | no_license | Meusesoft/Copying-Machine-3 | 95785dbfe9ff5912db5797fd74805cc5b07341cb | e3212c5d91f094259a8b182d1b065b74d3b9606c | refs/heads/main | 2023-03-31T06:33:59.332058 | 2021-03-30T20:26:27 | 2021-03-30T20:26:27 | 353,126,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,577 | cpp | RecognizedText.cpp | #include "stdafx.h"
#include "CopyingMachineCore.h"
//------------------------------------------------------------------------------
//
// Class CRecognizedText
//Constructor and destructor
CRecognizedText::CRecognizedText(Rect pcBoundingBox, LANGID pcLanguage) {
cBoundingBox = pcBoundingBox;
cLanguage = pcLanguage;
}
CRecognizedText::~CRecognizedText() {
oCharacters.clear();
}
//This function returns the language code
LANGID
CRecognizedText::GetLanguage() {
return cLanguage;
}
//This function returns the bounding box of the recognized text
Rect
CRecognizedText::GetBoundingBox() {
return cBoundingBox;
}
//Get the memory size of this text block
DWORD
CRecognizedText::GetMemorySize() {
return (DWORD)(oCharacters.size() * sizeof(sRecognizedCharacter));
}
//Move the text block
void
CRecognizedText::MoveBoundingBox(int piDeltaX, int piDeltaY) {
cBoundingBox.X += piDeltaX;
cBoundingBox.Y += piDeltaY;
}
//Cut the bounding box. This means that the bounding box will be adjuist
//so it will exactly fit into the give rectangle. Characters outside the
//bounding box will be deleted
void
CRecognizedText::CutBoundingBox(Rect pcRectangle) {
Rect cResultBox;
Rect cCharacterBox;
long lIndex;
if (cResultBox.Intersect(cResultBox, cBoundingBox, pcRectangle)) {
lIndex = oCharacters.size();
while (lIndex>0) {
lIndex--;
cCharacterBox = oCharacters[lIndex].cBoundingBox;
cCharacterBox.Offset(cBoundingBox.X, cBoundingBox.Y);
if (!cResultBox.Contains(cCharacterBox)) {
//connect the end of lines to the previous character
if (oCharacters[lIndex].iEndOfLines>0 && lIndex>0) {
oCharacters[lIndex-1].iEndOfLines += oCharacters[lIndex].iEndOfLines;
}
//remove the character
oCharacters.erase(oCharacters.begin() + lIndex);
}
else {
//reposition the character to its new position within its new bounding box
oCharacters[lIndex].cBoundingBox.Offset(cBoundingBox.X - cResultBox.X, cBoundingBox.Y - cResultBox.Y);
}
}
}
cBoundingBox = cResultBox;
}
//Subtract the bounding box. This means that the given rectangle will
//be subtracted from the bounding box. The characters inside the rectangle
//will be deleted
void
CRecognizedText::SubtractBoundingBox(Rect pcRectangle) {
Rect cResultBox;
Rect cCharacterBox;
long lIndex;
if (cResultBox.Intersect(cResultBox, cBoundingBox, pcRectangle)) {
lIndex = oCharacters.size();
while (lIndex>0) {
lIndex--;
cCharacterBox = oCharacters[lIndex].cBoundingBox;
cCharacterBox.Offset(cBoundingBox.X, cBoundingBox.Y);
if (cResultBox.IntersectsWith(cCharacterBox)) {
oCharacters.erase(oCharacters.begin() + lIndex);
}
}
}
}
//This function returns the number of recognized characters within this bounding box
int
CRecognizedText::GetCharacterCount() {
return (int)oCharacters.size();
}
//This function returns the bounding box of the requested character
Rect
CRecognizedText::GetCharacterBoundingBox(long plIndex) {
Rect cResult;
cResult = Rect(0, 0, 0, 0);
if (plIndex<(long)oCharacters.size()) cResult = oCharacters[plIndex].cBoundingBox;
return cResult;
}
//This function returns the character code of the requested character
TCHAR
CRecognizedText::GetCharacter(long plIndex) {
TCHAR cResult;
cResult = 0;
if (plIndex<(long)oCharacters.size()) cResult = oCharacters[plIndex].cCharacter;
return cResult;
}
//This function returns the character code of a character at the
//requested location
sRecognizedCharacter
CRecognizedText::GetCharacter(int piX, int piY) {
sRecognizedCharacter cResult;
SecureZeroMemory(&cResult, sizeof(cResult));
long lIndex = oCharacters.size();
while (lIndex>0) {
lIndex--;
if (oCharacters[lIndex].cBoundingBox.Contains(piX, piY)) {
cResult = oCharacters[lIndex];
lIndex=0;
}
}
return cResult;
}
//This function returns the character code of a character at the
//requested location
sRecognizedCharacter
CRecognizedText::GetCharacterStruct(long plIndex) {
sRecognizedCharacter cResult;
SecureZeroMemory(&cResult, sizeof(cResult));
if (plIndex < (long)oCharacters.size()) {
cResult = oCharacters[plIndex];
}
return cResult;
}
//This function adds a character and its bounding box to this recognized text
void
CRecognizedText::AddCharacter(TCHAR pcCharacter, Rect pcBoundingBox, long lNumberSpaces, long lNumberEndOfLines) {
sRecognizedCharacter cCharacter;
cCharacter.cCharacter = pcCharacter;
cCharacter.cBoundingBox = pcBoundingBox;
cCharacter.iEndOfLines = lNumberEndOfLines;
cCharacter.iSpaces = lNumberSpaces;
oCharacters.push_back(cCharacter);
}
//This function concatenates all the characters to a text (wstring)
std::wstring
CRecognizedText::GetText() {
std::wstring psResult;
sRecognizedCharacter cCharacter;
long lIndex;
lIndex = 0;
while (lIndex<(long)oCharacters.size()) {
for (long lSpaces=0; lSpaces<oCharacters[lIndex].iSpaces; lSpaces++) {
psResult += L" ";
}
psResult += oCharacters[lIndex].cCharacter;
for (long lNumberEndOfLines=0; lNumberEndOfLines<oCharacters[lIndex].iEndOfLines; lNumberEndOfLines++) {
psResult += L"\r\n";
}
lIndex++;
}
return psResult;
}
//This function rotates the texts within this recognition layer
void
CRecognizedText::DoRotate(DWORD pdAngle, RectF pcRectangleWithinRotation) {
long lIndex;
RectF cBoundingBoxSize;
cBoundingBoxSize = RectF(0, 0, (int)cBoundingBox.Width, (int)cBoundingBox.Height);
CMathVector::RotateRect(cBoundingBox, pcRectangleWithinRotation, pdAngle);
lIndex = oCharacters.size();
while (lIndex>0) {
lIndex--;
CMathVector::RotateRect(oCharacters[lIndex].cBoundingBox, cBoundingBoxSize, pdAngle);
}
}
//This function flips the texts within this recognition layer
void
CRecognizedText::DoFlip(DWORD pdOperation, RectF pcRectangleWithinFlip) {
long lIndex;
RectF cBoundingBoxSize;
cBoundingBoxSize = RectF(0, 0, (int)cBoundingBox.Width, (int)cBoundingBox.Height);
CMathVector::MirrorRect(cBoundingBox, pcRectangleWithinFlip, pdOperation);
lIndex = oCharacters.size();
while (lIndex>0) {
lIndex--;
CMathVector::MirrorRect(oCharacters[lIndex].cBoundingBox, cBoundingBoxSize, pdOperation);
}
}
//------------------------------------------------------------------------------
//
// Class CRecognitionLayer
//Constructor and destructor
CRecognitionLayer::CRecognitionLayer() {
}
CRecognitionLayer::~CRecognitionLayer() {
//clean up
Clear();
}
//Get the memory size of this text block
DWORD
CRecognitionLayer::GetMemorySize() {
DWORD dResult;
long lIndex;
lIndex = oTexts.size();
dResult = 0;
while (lIndex>0) {
lIndex--;
dResult += oTexts[lIndex]->GetMemorySize();
}
return dResult;
}
//This function creates a copy of the recognition layer
CRecognitionLayer*
CRecognitionLayer::Copy() {
CRecognizedText* oTextCopy;
CRecognitionLayer* oLayerCopy;
sRecognizedCharacter cCharacter;
oLayerCopy = new CRecognitionLayer();
for (long lIndex=0; lIndex<(long)oTexts.size(); lIndex++) {
oTextCopy = oLayerCopy->CreateRecognizedText(
oTexts[lIndex]->GetBoundingBox(), oTexts[lIndex]->GetLanguage());
for (long lTextIndex=0; lTextIndex<oTexts[lIndex]->GetCharacterCount(); lTextIndex++) {
cCharacter = oTexts[lIndex]->GetCharacterStruct(lTextIndex);
oTextCopy->AddCharacter(
cCharacter.cCharacter,
cCharacter.cBoundingBox,
cCharacter.iSpaces,
cCharacter.iEndOfLines);
}
}
return oLayerCopy;
}
//This functions clears this layer of all recognized texts
void
CRecognitionLayer::Clear() {
for (long lIndex=0; lIndex<(long)oTexts.size(); lIndex++) {
delete oTexts[lIndex];
}
oTexts.clear();
}
//This function created an instance of CRecognizedText and returns the pointer to it
CRecognizedText*
CRecognitionLayer::CreateRecognizedText(Rect pcBoundingBox, LANGID pcLanguage) {
CRecognizedText* oResult;
long lIndex;
Rect cBoundingBox;
bool bAdded;
oResult = new CRecognizedText(pcBoundingBox, pcLanguage);
lIndex = oTexts.size();
bAdded = false;
while (lIndex>0 && !bAdded) {
lIndex--;
cBoundingBox = oTexts[lIndex]->GetBoundingBox();
if (cBoundingBox.Y < pcBoundingBox.Y) {
oTexts.insert(oTexts.begin() + lIndex + 1, oResult);
lIndex = 0;
bAdded = true;
}
}
if (!bAdded) {
oTexts.insert(oTexts.begin(), oResult);
}
return oResult;
}
//This function returns the number of recognized texts in this layer
int
CRecognitionLayer::GetRecognizedTextCount() {
return (int)oTexts.size();
}
//This function returns the requested instance of the CRegonizedText within this layer
CRecognizedText*
CRecognitionLayer::GetRecognizedText(long plIndex) {
CRecognizedText* oResult;
if (plIndex<(long)oTexts.size()) oResult = oTexts[plIndex];
return oResult;
}
//This function returns the instance of CRecognizedText on the given location
CRecognizedText*
CRecognitionLayer::GetRecognizedText(int piX, int piY) {
CRecognizedText* oResult;
long lIndex;
oResult = NULL;
lIndex = oTexts.size();
while (lIndex>0) {
lIndex--;
if (oTexts[lIndex]->GetBoundingBox().Contains(piX, piY)) {
oResult = oTexts[lIndex];
lIndex = 0;
}
}
return oResult;
}
//This function returns the character on the requested location
sRecognizedCharacter
CRecognitionLayer::GetCharacter(int piX, int piY) {
CRecognizedText* oText;
sRecognizedCharacter cResult;
SecureZeroMemory(&cResult, sizeof(cResult));
oText = GetRecognizedText(piX, piY);
if (oText!=NULL) {
cResult = oText->GetCharacter(piX-oText->GetBoundingBox().X, piY-oText->GetBoundingBox().Y);
}
return cResult;
}
//This function rotates the texts within this recognition layer
void
CRecognitionLayer::DoRotate(DWORD pdAngle, RectF pcRectangleWithinRotation) {
long lIndex;
lIndex = oTexts.size();
while (lIndex>0) {
lIndex--;
oTexts[lIndex]->DoRotate(pdAngle, pcRectangleWithinRotation);
}
}
//This function flips the texts within this recognition layer
void
CRecognitionLayer::DoFlip(DWORD pdOperation, RectF pcRectangleWithinFlip) {
long lIndex;
lIndex = oTexts.size();
while (lIndex>0) {
lIndex--;
oTexts[lIndex]->DoFlip(pdOperation, pcRectangleWithinFlip);
}
}
//This function processes a crop operation. It will adjust the textblock
//to the new size of the page
void
CRecognitionLayer::DoFill(Rect pcFillRectangle) {
long lIndex;
CRecognizedText* oText;
Rect cBoundingBoxTextBlock;
Rect cFillRectangle;
lIndex = oTexts.size();
cFillRectangle = pcFillRectangle;
while (lIndex>0) {
lIndex--;
//Get a text block and its bounding box
oText = oTexts[lIndex];
cBoundingBoxTextBlock = oText->GetBoundingBox();
if (cFillRectangle.Contains(cBoundingBoxTextBlock)) {
//this text block is totally inside the filled rectangle,
//all the recognized characters will be lossed
DeleteRecognizedText(oText);
}
else {
if (cFillRectangle.IntersectsWith(cBoundingBoxTextBlock)) {
//this text block is partially part of the new image
//adjust it
oText->SubtractBoundingBox(cFillRectangle);
}
}
}
}
//This function processes a crop operation. It will adjust the textblock
//to the new size of the page
void
CRecognitionLayer::DoCrop(RectF pcNewPageRectangle) {
long lIndex;
CRecognizedText* oText;
Rect cBoundingBoxTextBlock;
Rect cNewPageRectangle;
lIndex = oTexts.size();
cNewPageRectangle = Rect((int)pcNewPageRectangle.X,
(int)pcNewPageRectangle.Y,
(int)pcNewPageRectangle.Width,
(int)pcNewPageRectangle.Height);
while (lIndex>0) {
lIndex--;
//Get a text block and its bounding box
oText = oTexts[lIndex];
cBoundingBoxTextBlock = oText->GetBoundingBox();
if (cNewPageRectangle.Contains(cBoundingBoxTextBlock)) {
//this text block is totally inside the new page, move
//the block to align it in the new image
oText->MoveBoundingBox((int)(-pcNewPageRectangle.X), (int)(-pcNewPageRectangle.Y));
}
else {
if (cNewPageRectangle.IntersectsWith(cBoundingBoxTextBlock)) {
//this text block is partially part of the new image
//adjust it
oText->CutBoundingBox(cNewPageRectangle);
oText->MoveBoundingBox((int)(-pcNewPageRectangle.X), (int)(-pcNewPageRectangle.Y));
}
else {
//remove this text block, since it is not part of the
//new image
DeleteRecognizedText(oText);
}
}
}
}
//Copy all the text blocks to the clipboard
void
CRecognitionLayer::DoCopyTextToClipboard(HWND phWnd) {
std::wstring sText;
long lIndex;
sText = L"";
lIndex = oTexts.size();
while (lIndex>0) {
lIndex--;
sText = oTexts[lIndex]->GetText() + L"\n\r" + sText;
}
CopyToClipboard(phWnd, sText);
}
//Copy the textblock at the given location to the clipboard
void
CRecognitionLayer::DoCopyTextBlockToClipboard(HWND phWnd, int piX, int piY) {
std::wstring sText;
CRecognizedText* oText;
sText = L"";
oText = GetRecognizedText(piX, piY);
if (oText!=NULL) {
sText = oText->GetText();
}
CopyToClipboard(phWnd, sText);
}
//This function deletes the Recognized Text Block at the given location
void
CRecognitionLayer::DeleteRecognizedText(int piX, int piY) {
CRecognizedText* oText;
//Request the text block at the given location
oText = GetRecognizedText(piX, piY);
//If an instance is found, delete it
if (oText!=NULL) {
DeleteRecognizedText(oText);
}
}
//This function deletes the given recognized text block
void
CRecognitionLayer::DeleteRecognizedText(CRecognizedText* poText) {
long lIndex;
lIndex = oTexts.size();
//Loop through the instances and if the requested instance
//is found, delete it and remove it from the vector
while (lIndex>0) {
lIndex--;
if (oTexts[lIndex] == poText) {
oTexts.erase(oTexts.begin() + lIndex);
delete poText;
lIndex = 0;
}
}
}
//Copy the given text to the clipboard
void
CRecognitionLayer::CopyToClipboard(HWND phWnd, std::wstring psText) {
long lTextLength;
HGLOBAL hMem;
void* pMem;
//Determine the length of the text in the control
lTextLength = psText.length();
//Allocate memory and get the text from the control
hMem = GlobalAlloc(GMEM_MOVEABLE, (lTextLength + 1) * sizeof(wchar_t));
pMem = GlobalLock(hMem);
wcscpy_s((wchar_t*)pMem, lTextLength+1, psText.c_str());
GlobalUnlock(hMem);
//Copy the text to the clipboard
if (OpenClipboard(phWnd)) {
SetClipboardData(CF_UNICODETEXT, hMem);
CloseClipboard();
}
else {
//Free the memory to prevent a memory leak
GlobalFree(hMem);
}
}
|
e6b1196ed1f91b303a8865eee564e2d5d5f7fdfc | a7bb4a284954d1ab85aac3ba7886accfc85b38d8 | /kswSTL/kswDequeIterator.h | a1982d30ed238368533934727a5ff41aca47a655 | [] | no_license | ITnull/MySTL | ea4431dc953b0e7f371e391e62d3ee71a4079179 | 2a98ebfedd0bd1645d22ec11759faa645ef42655 | refs/heads/master | 2021-01-17T18:31:55.395512 | 2016-08-01T13:38:58 | 2016-08-01T13:38:58 | 64,443,845 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,238 | h | kswDequeIterator.h | /*******************************************************************
* Copyright(c) 2016 Ke Shanwu
* All rights reserved.
*
* 1209016337@qq.com
*
* 功能:kswDeque的迭代器的实现代码
******************************************************************/
#ifndef _KSW_DEQUE_ITERATOR_
#define _KSW_DEQUE_ITERATOR_
#include <memory>
namespace KSW{
template<class T, class Ref, class Ptr, size_t BufSiz>
struct __deque_iterator{
#pragma region typedef和成员变量的定义
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type; // ptrdiff_t的使用要#include <memory>
typedef T** map_pointer; // 迭代器所属缓冲区,该缓冲区由kswDeque的管控中心管理
typedef __deque_iterator self;
typedef __deque_iterator<T, T&, T*, BufSiz> iterator;
T* cur; // 当前位置
T* first; // 缓冲区头部
T* last; // 缓冲区尾部
map_pointer node; // 迭代器所属缓冲区,该缓冲区由kswDeque的管控中心管理
#pragma endregion
#pragma region 迭代器管控中心和kswDeque管控中心的衔接
/*
输入参数:new_node,kswDeque传过来的缓冲区位置(管控中心的某个节点)
*/
void set_node(map_pointer new_node)
{
node = new_node; // 连接kswDeque管控中心的某个节点和迭代器缓冲区
first = *new_node; // 缓冲区头部
last = first + difference_type(buffer_size()); // 缓冲区尾部
}
#pragma endregion
#pragma region 确定每个缓冲区的大小
/*
缓冲区默认大小为512字节
1.如果BufSiz不为0,传回BufSiz,表示buffer_size由用户自定义
2.如果BufSiz,表示buffer_size使用默认值,那么如果元素大小(sizeof(T))小于512字节,传回size_t(512 / sizeof(T)
如果元素大小(sizeof(T))大于512字节,传回1
*/
size_t buffer_size()
{
return BufSiz != 0 ? BufSiz : (sizeof(T) < 512 ? size_t(512 / sizeof(T)) : size_t(1));
}
#pragma endregion
#pragma region 迭代器基本操作
#pragma region 解除引用
reference operator*() const{ return *cur; }
pointer operator->()const{ return &(operator*()); }
#pragma endregion
#pragma region 迭代器的单步移动
self& operator++()
{
++cur; // 切换至下一个元素
// 如果到所在缓冲区的尾端,注意缓冲区是前闭后开的空间,last是缓冲区结束的哨兵,到达last就该切换缓冲区了
if (cur == last)
{
set_node(node + 1); // 就切换至管控中心的下一个节点(也即缓冲区)
cur = first; // 下一个缓冲区的第一个元素
}
return *this;
}
self& operator++(int)
{
self tmp = *this;
++*this;
return tmp;
}
self& operator--()
{
if (cur == first) // 如果到达所在缓冲区的头部
{
set_node(node - 1); // 就切换至管控中心的前一个节点(也即缓冲区)
cur = last; // 下一个缓冲区的最后一个元素
}
// 注意缓冲区是前闭后开的空间,last是缓冲区结束的哨兵,本身没有意义,last的前一个元素才有正确的值域
--cur;
return *this;
}
self& operator--(int)
{
self tmp = *this;
--*this;
return tmp;
}
#pragma endregion
#pragma region 迭代器的随机移动
/*
实现随机存取(random access)
*/
self& operator+=(difference_type n)
{
difference_type offset = n + (cur - first); // 偏移
// 1.offset >= 0:向后偏移
// 2.offset < difference_type(buffer_size()):偏移小于缓冲区长度
if (offset >= 0 && offset < difference_type(buffer_size()))
{
cur += n;
}
else
{
difference_type node_offset = offset > 0
? offset / difference_type(buffer_size()) // 向后偏移:确定管控中心的偏移的节点(偏移多少个缓冲区)
: -difference_type((-offset - 1) / buffer_size()) - 1; // 向前偏移:确定管控中心的偏移的节点(偏移多少个缓冲区)
set_node(node + node_offset); // 从管控中心中选择新的节点,切换缓冲区
cur = first + (offset - node_offset*difference_type(buffer_size()));
}
return *this;
}
/*
实现随机存取(random access)
*/
self operator+(difference_type n) const
{
self tmp = *this;
return tmp += n;
}
self& operator-=(difference_type n)const{ return *this += -n; }
self operator-(difference_type n)const
{
self tmp = *this;
return tnp -= n;
}
difference_type operator-(const self& x)
{
return difference_type(buffer_size())*(node - x.node - 1) + (cur - first) + (x.last - x.cur);
}
reference operator[](difference_type n)const{ return *(*this + n); }
#pragma endregion
#pragma region 迭代器的相互比较
bool operator==(const self& x)const{ return cur == x.cur; }
bool operator!=(const self& x)const{ return cur != x.cur; }
bool operator<(const self& x)const
{
return (node == x.node) ? (cur < x.cur) : (node < x.node);
}
#pragma endregion
#pragma endregion
};
}
#endif |
caed0fb6cdbb11372f2e47ff394acb7b02c63359 | a3828b9f6e8facefbe3718e9378d86978cf2c60a | /PAT (Basic Level) Practise/1055.cpp | 7b361ecd55db6ae7c20958f1a711445b81296efe | [] | no_license | jiujiangluck/PAT-Basic-Level-Practise | 884dcfecd0cb07a9f2fec9bc45cdb1fcc56529c8 | f1cf098601faf29ea30d0a90b1422b0805758db8 | refs/heads/master | 2021-06-21T14:14:17.719741 | 2017-08-12T02:13:04 | 2017-08-12T02:13:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 944 | cpp | 1055.cpp | #include<iostream>
#include<algorithm>
using namespace std;
struct stu{
string name;
int height;
};
//height from max to min , name from min to max
bool cmp(stu a,stu b){
if(a.height != b.height)
return a.height > b.height;
else
return a.name < b.name;
}
int main(){
int count, row, max, j = 0;
cin >> count >> row;
stu stu[count];
for(int i = 0; i < count ; i++){
cin >> stu[i].name >> stu[i].height;
}
sort(stu,stu+count,cmp);
for(int i = 0;i < row && j < count; i++){
if(i == 0)
max = count/row+count%row;
else
max = count/row;
string temp[max];
int right = max/2 + 1, left = max/2 - 1 ;
temp[max/2] = stu[j++].name;
while(left >= 0 || right <= max-1){
if(left >= 0)
temp[left--] = stu[j++].name;
if(right <= max-1)
temp[right++] = stu[j++].name;
}
cout << temp[0] ;
for(int k = 1; k < max ; k++){
cout << " " << temp[k] ;
}
if(i != row -1)
cout << endl;
}
return 0;
}
|
ed959400b8fab9c5286846ed4fb20e3270f70a75 | 9f8138ef7c6994521ab0142f961e245301bb5c0b | /chapter 3/ex3.8/main.cpp | b475b878da4b70bf172e84d59670cf4891195044 | [] | no_license | OrigenesZhang/cppprimer | 39f046748bf761b46cf8197e8abf4710eab06277 | f2a9f0ec8940ff612eca165d7d2cbdec824661c0 | refs/heads/master | 2022-08-26T04:29:18.766139 | 2022-08-21T16:57:57 | 2022-08-21T16:57:57 | 117,434,632 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | main.cpp | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
using std::string;
int main(){
string s;
if(cin>>s){
decltype(s.size()) idx=0;
while(idx<s.size())
s[idx++]='X';
cout<<s<<endl;
}else{
cerr<<"No data?!"<<endl;
return -1;
}
if(cin>>s){
for(decltype(s.size()) index=0; index!=s.size(); ++index)
s[index]='X';
cout<<s<<endl;
}else{
cerr<<"No data?!"<<endl;
return -1;
}
return 0;
} |
0dd4aada404b5b306ec146330fdd2302960fd831 | 3404cb1e271f929cc063c13128d581241d4e07a8 | /392.cpp | ac90d4ef73910b4da413b4cf04a1d06117972e9e | [] | no_license | mashiuruab/leetcode | 811b08dd9bff025587e6145b3dee52ed50391f5a | 7d3adf053b1d5a50f40ec49a8c60c28998c76132 | refs/heads/master | 2020-04-17T02:23:57.391337 | 2019-01-17T00:19:12 | 2019-01-17T00:19:12 | 166,131,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cpp | 392.cpp | #include<iostream>
#include<vector>
#include<string>
using namespace std;
bool isSubsequence(string s, string t) {
int s_len = s.length();
int t_len = t.length();
int s_i = 0;
int t_i = 0;
while(s_i < s_len) {
if(t_i == t_len) {
break;
}
if(s[s_i] == t[t_i]) {
//cout << t[t_i] << ", ";
s_i++;
}
t_i++;
}
return (s_i == s_len);
}
int main(int argc, char** argv){
string s = "abc";
string t = "ahbgdc";
cout << isSubsequence(s,t) << endl;
return 0;
}
|
2f1cf3b7484f3a31ccab855034d70736174c7894 | 5f2ad8621f33ba879b95664b26480153ac479c51 | /platform/library/align/sa.hpp | ceeddb058f03e49e716ba8afa804e2bfbd3ede3e | [] | no_license | jvandebon/ORIAN | 2caee941fedee7dc8274da64b3f1d1aa157c8dc2 | 0bf44ff29adbc223d2576da9422d76791b732594 | refs/heads/master | 2022-04-12T20:43:37.938242 | 2020-02-13T10:52:24 | 2020-02-13T10:52:24 | 239,772,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | hpp | sa.hpp | /* sa.hpp ----- James Arram 2017 */
/*
* functions to query sampled suffix array
*/
#ifndef SA_HPP
#define SA_HPP
#include <stdint.h>
#include "index.hpp"
#include "utils.hpp"
#define LUT_BITS 24
// sampled suffix array structure
struct ssa_t {
uint32_t sa_pos; // index in suffix array
uint32_t t_pos; // position in text
};
/*
* Function: buildLUT
* ---------------------
*
* build look-up table for sampled suffix array
*
* [input]
* lut - look-up table
* lut_end - last populated entry in look-up table
* ssa - sampled suffix array
* ssa_len - length of suffix array
*
*/
void buildLUT(uint32_t *lut, uint32_t *lut_end, ssa_t *ssa, uint32_t ssa_len);
/*
* Function: convertPos
* ---------------------
*
* convert position in suffix array to text
*
* [input]
* pos - position in suffix array
* idx - base FM-index
* ssa - sampled suffix array
* ssa_len - length of suffix array
* lut - look-up table
* lut_end - last populated entry in look-up table
*
* [return]
* position in text
*
*/
uint32_t convertPos(uint32_t pos, idxbase_t *idx, ssa_t *ssa, uint32_t ssa_len,
uint32_t *lut, uint32_t lut_end);
#endif |
683c3143b26301652f8109288ba04433c5b845aa | af4dc9ed3b25178664d9cb97b9b41039d4ee4e35 | /RSCH_ClothSym/trunk/src/global.h | 30ad5d429f54c67c3dd555365e894c66320c6eee | [] | no_license | njoubert/UndergraduateProjects | 19dc0ba98a130e040d2594374a935954258f83ea | 7e6db9c4318a042c59c363cd4a331bbfcb908988 | refs/heads/master | 2021-01-10T06:25:49.985493 | 2015-12-31T22:57:17 | 2015-12-31T22:57:17 | 48,846,399 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,046 | h | global.h | /*
* util.h
*
* Created on: Sep 8, 2008
* Author: njoubert
*/
#ifndef UTIL_H_
#define UTIL_H_
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstdlib>
#ifdef _WIN32
# include <windows.h>
#else
# include <sys/time.h>
#endif
#ifdef OSX
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glu.h>
#include <GL/glut.h>
#endif
#include <math.h>
#include "util/Timer.h"
#include "util/TimerCollection.h"
#include "util/Profiler.h"
#include "Debug.h"
#include "math/algebra3.h"
#include "DEFAULTS.h"
extern Timer fpstimer;
extern Profiler profiler;
extern bool DEBUG;
extern double TIME;
extern double INTERSTEPTIME;
extern float GAMMA;
extern float BETA;
extern int MAX_CG_ITER;
extern float MAX_CG_ERR;
extern double TIMESTEP;
extern float MASS;
extern int MESHSIZE;
extern float Ke;
extern float Ks_comp;
extern float Kd;
extern bool BEND_FORCES;
extern bool FRICTION_FORCES;
extern bool COLLISIONS;
extern bool STATIC_CONSTRAINTS;
extern bool DYNAMIC_CONSTRAINTS;
extern bool OVERRIDE_DYNAMIC_CONSTRAINTS;
extern int FOLLOW1;
extern int FOLLOW2;
extern int FOLLOW3;
extern int FOLLOW4;
extern int LEAD1;
extern int LEAD2;
extern int LEAD3;
extern int LEAD4;
extern int HIERARCHY1;
extern int HIERARCHY2;
extern int HIERARCHY3;
extern int HIERARCHY4;
extern float KBe;
extern float KBd;
extern float Kcoll;
extern float Kcr;
extern float MUs;
extern float MUd;
extern vector<bool> DRAWMODELS;
extern bool EXITONLASTFRAME;
extern int LOWQINDEX;
extern int HIGHQINDEX;
extern double SYNCSTEP;
extern double EDAMP;
extern vec3 WIND;
extern bool isWIND;
extern double KDRAG;
extern float COLL_VEL_HAXX;
extern bool DRAWELLIPSOIDS;
extern bool WIREFRAME;
extern bool HIDDEN;
extern bool DRAWNORMALS;
extern bool DRAWMESHDIFF;
extern bool USECOLLJACOBIAN;
extern bool PLAYALLFRAMES;
extern double BIGGESTTIMESTEP;
extern bool WRITEALLFRAMES;
extern bool WRITEFILEANDEXIT;
extern bool DRAWCOLLISIONS;
#define PI 3.14159265
#endif /* UTIL_H_ */
|
f395886921f71d1a00d36d9ea26f1eb6c2867940 | f4064dbc68decb87973e0b05992d39268b0c4a1a | /AtCoder/ABC003/D.cpp | 1c5af2a16606e01a46f64cf26b81ae96242fe656 | [] | no_license | odanado/Procon | d7c75387b15e3dc860b6a813eb43b1fa1ab8ffd3 | 6f30fb4819f577df9db54ccc74765eb0ddf2119c | refs/heads/master | 2020-04-12T01:43:42.196994 | 2017-08-06T14:58:02 | 2017-08-06T14:58:02 | 48,416,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,155 | cpp | D.cpp | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
using namespace std;
using ll = long long;
#define all(c) (c).begin(), (c).end()
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
#define fr first
#define sc second
const ll INF=1e9;
const ll MOD=1e9+7;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
/*
* 前処理 O(N)
* クエリ O(1)
*
* Verified
* http://yukicoder.me/problems/184
*/
template<class T,size_t N,T MOD>
struct Combination {
typedef T int_type;
vector<int_type> fact,factr,inv;
Combination() {
fact.resize(2*N+1);
factr.resize(2*N+1);
inv.resize(2*N+1);
fact[0]=factr[0]=1;
inv[1]=1;
for(int i=2;i<=2*N;i++) inv[i] = inv[MOD % i] * (MOD - MOD / i) % MOD;
for(int i=1;i<=2*N;i++) fact[i]=fact[i-1]*i%MOD, factr[i]=factr[i-1]*inv[i]%MOD;
}
int_type C(int n, int r) {
if(n<0 || r<0 || r>n) return 0;
return factr[r]*fact[n]%MOD*factr[n-r]%MOD;
}
int_type P(int n,int r) {
if(r<0 || r>n) return 0;
return fact[n]*factr[n-r]%MOD;
}
int_type H(int n, int r) {
if(n==0 && r==0) return 1;
return C(n+r-1,r);
}
};
Combination<ll, 1003, MOD> comb;
int R,C;
int X,Y;
int D,L;
int a[31][31];
// x*yの長方形に机D個,サーバL個を敷き詰める時の場合の数
// 空白を考慮している
ll f(int x,int y) {
if(x<0||y<0) return 0;
if(x*y<D+L) return 0;
ll ret = 0;
// 机
ret += comb.C(x*y,D);
ret %= MOD;
// 残りのx*y-Dマスにサーバを置く
ret *= comb.C(x*y-D,L);
ret %= MOD;
return ret;
}
int main() {
cin>>R>>C;
cin>>X>>Y;
cin>>D>>L;
ll ans = 0;
ans = f(X,Y)-2*f(X-1,Y)-2*f(X,Y-1)+4*f(X-1,Y-1)+f(X-2,Y)+f(X,Y-2)-2*f(X-2,Y-1)-2*f(X-1,Y-2)+f(X-2,Y-2);
ans *= (R-X+1)*(C-Y+1);
ans %= MOD;
ans += MOD;
ans %= MOD;
cout<<ans<<endl;
return 0;
}
|
3855d5c7dcec4f30a13761c82817199e37e9a1a9 | b17dae51dc883d0c490dbacbe0e28d1b223b4996 | /Game/Game.hpp | f8fc9053c282d12dd88a3f15a87f9e3a8c4a1457 | [] | no_license | tandm160797/CPlusPlus-war-space-OOP | ebda89cdc500680da1cd3324871469fc382145f7 | c5a50970ddd6cf9874d44c29f99855ba6e5c9149 | refs/heads/master | 2023-03-08T18:28:08.281696 | 2021-02-27T02:02:57 | 2021-02-27T02:02:57 | 342,748,183 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | hpp | Game.hpp | #ifndef Game_hpp
#define Game_hpp
#include"Data.hpp"
#include"Enemy.hpp"
#include"Boss.hpp"
#include"Player.hpp"
#include"Animation.hpp"
#define WIDTH_WINDOW 400
#define HEIGHT_WINDOW 600
class Game {
private:
static Game* game;
RenderWindow window;
Game();
public:
~Game();
static Game* getGame();
RenderWindow& getWindow();
void run();
};
#endif //Game_hpp
|
c56fdd4a387bfc34d3395906ff98e243f06fca21 | 05df94e60cd2cdd208eb01f7ae4a6dd3816b9c8c | /BinaryTrees/Number-of-Good-Leaf-Nodes-Pairs.cpp | 24741b21c343ca0de98431ceebd3b36933314757 | [] | no_license | humblejumbo/Interview-Preparation | cf9a8ca7322b8a97d32d31f916b502daf757dca8 | abd50751d13f80daa12c87a27efed497b7e076ad | refs/heads/master | 2021-05-17T03:31:46.375443 | 2020-07-30T17:54:32 | 2020-07-30T17:54:32 | 250,595,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,627 | cpp | Number-of-Good-Leaf-Nodes-Pairs.cpp | //https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void leafNodes(TreeNode* root, vector<TreeNode*> & leaf)
{
if(root==NULL)
return;
if(root->left==NULL && root->right==NULL)
leaf.push_back(root);
leafNodes(root->left,leaf);
leafNodes(root->right,leaf);
}
bool findPath(TreeNode* root,TreeNode* node,vector<TreeNode*> &path)
{
if(root==NULL)
return false;
bool l=findPath(root->left,node,path);
bool r=findPath(root->right,node,path);
if(root==node)
{
path.push_back(root);
return true;
}
if(l || r)
{
path.push_back(root);
return true;
}
else
return false;
}
TreeNode* findLCA(TreeNode* root,TreeNode* n1,TreeNode* n2)
{
vector<TreeNode*> path1,path2;
findPath(root,n1,path1);
findPath(root,n2,path2);
reverse(path1.begin(),path1.end());
reverse(path2.begin(),path2.end());
for(int i=0;i<min(path1.size(),path2.size());i++)
{
if(path1[i]!=path2[i])
return path1[i-1];
}
return NULL;
}
int depth(TreeNode* root,TreeNode* node)
{
vector<TreeNode*> path;
findPath(root,node,path);
return path.size()-1;
}
// int countPairs(TreeNode* root, int distance) {
// vector<TreeNode*> leaf;
// leafNodes(root,leaf);
// int count=0;
// for(int i=0;i<leaf.size();i++)
// {
// for(int j=i+1;j<leaf.size();j++)
// {
// TreeNode* lca=findLCA(root,leaf[i],leaf[j]);
// int dis=depth(root,leaf[i])+depth(root,leaf[j])-2*depth(root,lca);
// //cout<<leaf[i]->val<<" "<<leaf[j]->val<<" "<<depth(root,leaf[i])<<" "<<depth(root,leaf[j])<<" "<<depth(root,lca)<<endl;
// if(dis<=distance)
// count++;
// }
// }
// return count;
// }
//************ Efficient Approach**********************
int ans=0;
vector<int> helper(TreeNode* root, int dis)
{
if(root==NULL)
return {};
if(root->left==NULL && root->right==NULL)
return {1};
auto left=helper(root->left,dis);
auto right=helper(root->right,dis);
for(auto l:left)
{
for(auto r:right)
{
if(l&&r&&(l+r<=dis))
ans++;
}
}
vector<int> res;
for(auto l:left)
{
if(l && l+1<dis)
res.push_back(l+1);
}
for(auto r:right)
{
if(r && r+1<dis)
res.push_back(r+1);
}
return res;
}
int countPairs(TreeNode* root, int distance)
{
helper(root,distance);
return ans;
}
};
|
9de441fd892c14c324c0d10bb9dd0aeb7b199021 | 6cf0d27ab4e1ef297bcdcf354e33f4c5952e4160 | /Source/Logic/GateKeeperSource/src/GateKeeper.cpp | b68d9ce60a67798ee3ae44c45bf7d75e19a6ef93 | [] | no_license | Multimedia-Team/term-project | f35e0ee7d31ec835d0f8fdae209ed73e6163896d | fb85deb9a197bba7e7655c39c4ce8e7bd0729ab4 | refs/heads/develop | 2020-12-25T09:28:21.238161 | 2015-04-05T18:37:41 | 2015-04-05T18:37:41 | 32,188,103 | 0 | 3 | null | 2015-03-31T15:48:53 | 2015-03-14T00:18:36 | C++ | UTF-8 | C++ | false | false | 4,211 | cpp | GateKeeper.cpp | /********************************************************************************
** SOURCE FILE: GateKeeper.cpp - GateKeeper class implementation. Parent class
** for the enemies.
**
** PROGRAM: Term_Project
**
** DATE: February 15, 2015
**
**
** DESIGNER: Filip Gutica A00781910
**
** PROGRAMMER: Filip Gutica A00781910
**
***********************************************************************************/
#include "GateKeeper.h"
#include "../../Event.h"
#include "../../Entities/ServerEnemyController.h"
#include <typeinfo>
#include <iostream>
// bug fix by Sanders Lee
GateKeeper::GateKeeper(SGO &sprite, Marx::Map* map, float x, float y, Marx::Controller* ctrl, float h = 1.0, float w = 1.0) :
VEntity(sprite, map, x, y, ctrl, h, w)
// _ctrl(ctrl)
{
_range = 1;
_health = 100;
_type = 1;
_attack = 1;
_attackSpeed = 1;
_movementSpeed = 1;
_incombat = false;
_cooldown = 1;
_xPos = x;
_yPos = y;
_xSpeed = 0.09;
_ySpeed = 0.09;
movingLeft = movingRight = movingUp = movingDown = _moving = false;
};
GateKeeper::~GateKeeper()
{
}
/***
-- PROGRAMMER: ???
-- Sanders Lee (Debugged synchronization problem across clients)
***/
void GateKeeper::onUpdate(float deltaTime)
{
// std::cout << "GateKeeper.cpp ON UPDATE." << std::endl;
std::vector<Marx::Event*>* eventQueue = getController()->getEvents();
for( std::vector< Marx::Event*>::iterator it = eventQueue->begin()
; it != eventQueue->end()
; ++it )
{
// switch on type
switch((*it)->type)
{
case ::Marx::MOVE:
MoveEvent* ev = (MoveEvent*) (*it);
int xDir = ev->getXDir();
int yDir = ev->getYDir();
Entity::aMove(ev->getX(), ev->getY(), false);
if (yDir < 0)
{
newYSpeed = -_ySpeed;
}
else
{
newYSpeed = _ySpeed;
}
if (xDir > 0)
{
newXSpeed = _xSpeed;
}
else
{
newXSpeed = -_xSpeed;
}
if (xDir == 0)
newXSpeed = 0;
if (yDir == 0)
newYSpeed = 0;
//old code - replaced with the if-else block above
//movingLeft = (xDir < 0);
//movingRight = (xDir > 0);
//movingUp = (yDir < 0);
//movingDown = (yDir > 0);
break;
}
}
getController()->clearEvents();
Entity::rMove(newXSpeed, newYSpeed,false);
}
bool GateKeeper::isMoving()
{
return (movingLeft || movingRight || movingUp || movingDown);
}
void GateKeeper::detectPlayers()
{
}
void GateKeeper::enterCombat()
{
}
void GateKeeper::leaveCombat()
{
}
bool GateKeeper::inCombatRange()
{
return true;
}
void GateKeeper::setRange(int r)
{
}
void GateKeeper::setHealth(int h)
{
}
void GateKeeper::setAttack(int as)
{
}
void GateKeeper::setAttackSpeed(int as)
{
}
void GateKeeper::setMovementSPed(int ms)
{
}
void GateKeeper::setTarget(/*Player*/)
{
}
void GateKeeper::setCooldown(/*Timer*/)
{
}
void GateKeeper::setPosition(float x, float y)
{
}
void GateKeeper::setXSpeed(float x)
{
}
void GateKeeper::setYSpeed(float y)
{
}
int GateKeeper::getRange()
{
return _range;
}
int GateKeeper::getHealth()
{
return _health;
}
int GateKeeper::getAttack()
{
return _attack;
}
int GateKeeper::getAttackSpeed()
{
return _attackSpeed;
}
int GateKeeper::getMovementSpeed()
{
return _movementSpeed;
}
//virtual Vessel getTarget();
time_t GateKeeper::getCooldown()
{
return _cooldown;
}
void GateKeeper::turn()
{
}
void GateKeeper::onCreate()
{
}
void GateKeeper::onDestroy()
{
}
bool GateKeeper::operator==(const VEntity&)
{
return true;
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: getEntity
--
-- DATE:
--
-- REVISIONS: (Date and Description)
--
-- DESIGNER: Calvin Rempel
--
-- PROGRAMMER: Calvin Rempel
--
-- INTERFACE: Entity *getEntity()
--
-- RETURNS: The Entity associated with the Creature
--
-- NOTES:
-- This function provides a method for retrieving the Entity from the Creature.
----------------------------------------------------------------------------------------------------------------------*/
Entity *GateKeeper::getEntity()
{
return this;
}
|
03dca83a72f95ae5c1ede057746ba75d707b86fb | dbf18505b5f04bd743a6b57b85708258ad5e0398 | /cbls/vars/flipvars/propflipvarvi.cpp | 62f1d35f7f8cc7f65f1d01ce9a218308919a0204 | [] | no_license | thanhtrunghuynh93/kangaroo | fbdbd7f14f1aa589d27a22153eca65d105bc460a | b1d1dfcd03919ec077a92ffb7056c99ad2f6418c | refs/heads/master | 2021-05-30T02:20:19.391474 | 2015-11-11T18:21:20 | 2015-11-11T18:21:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,557 | cpp | propflipvarvi.cpp | /*!
@file propflipvarvi.cpp
@brief The implementation file for PropFlipVarVi class.
@details This is the implementation file for PropFlipVarVi class.
@author Duc Nghia Pham duc-nghia.pham@nicta.com.au
@author M.A.Hakim Newton hakim.newton@nicta.com.au
@date 16.11.2009 QRL NICTA www.nicta.com.au
@see propflipvarvi.hpp
*/
#include "cbls/vars/flipvars/propflipvarvi.hpp"
openKangarooSpace
/*!
Define an integer range variable.
*/
Hdl PropFlipVarVi::def(Hdl const hdlSys)
{
WatchError
PropFlipVarVi * tVar = new PropFlipVarVi(hdlSys);
Hdl const tHdl = tVar->defSysVar();
if (tHdl != InvHdl) { delete tVar; return tHdl; }
EvalTblInt & tValueTbl = EvalTblInt::refm(hdlSys);
tValueTbl.setEvalRec(tVar->mValueRec, tVar->mValueLoc);
#if CompLazy
tVar->mValueRec->resetLateDiff(); // variables would have no backlog
tVar->mValueRec->resetLtNxDiff(); // variables would have no backlog
#endif
return tVar->TermHdl;
CatchError
}
/*!
The constructor.
*/
PropFlipVarVi::PropFlipVarVi(Hdl const hdlSys) : FlipVarVi(hdlSys)
{
WatchError
setTermCls(TermStub<PropFlipVarVi>::TermCls);
setTermHvl(calcTermHvl());
CatchError
}
/*!
The duplicator.
*/
PropFlipVarVi::PropFlipVarVi(PropFlipVarVi const & that) : FlipVarVi(that)
{
WatchError
Throw(eUndefDuplicator);
CatchError
}
/*!
The assigner.
*/
PropFlipVarVi const & PropFlipVarVi::operator = (PropFlipVarVi const & that)
{
WatchError
if (this == &that) return *this;
Throw(eUndefAssigner);
CatchError
}
/*!
The destructor.
*/
PropFlipVarVi::~PropFlipVarVi()
{
WatchError
// nothing to be done.
CatchError
}
/*!
Whether two variables are identical?
*/
Bll PropFlipVarVi::identical(Var const & that) const
{
WatchError
return (that.TermCls == TermStub<PropFlipVarVi>::TermCls);
CatchError
}
/*!
Whether two variables are identical?
*/
Bll PropFlipVarVi::identical(Var const * that) const
{
WatchError
Warn(!that, eNullPointer);
return (that->TermCls == TermStub<PropFlipVarVi>::TermCls);
CatchError
}
/*!
Wether another variable's value is assignable?
*/
Bll PropFlipVarVi::assignable(Var const & that) const
{
WatchError
return (that.TermTyp == TermStub<FlipVarVi>::TermTyp);
CatchError
}
/*!
Wether another variable's value is assignable?
*/
Bll PropFlipVarVi::assignable(Var const * that) const
{
WatchError
Warn(!that, eNullPointer);
return (that->TermTyp == TermStub<FlipVarVi>::TermTyp);
CatchError
}
/*!
Whether two variables are swappable?
*/
Bll PropFlipVarVi::swappable(Var const & that) const
{
WatchError
return (that.TermTyp == TermStub<FlipVarVi>::TermTyp);
CatchError
}
/*!
Whether two variables are swappable?
*/
Bll PropFlipVarVi::swappable(Var const * that) const
{
WatchError
Warn(!that, eNullPointer);
return (that->TermTyp == TermStub<FlipVarVi>::TermTyp);
CatchError
}
/*!
Valid with respect to the valid?
*/
Bll PropFlipVarVi::validValue(Int const & theInt) const
{
WatchError
return theInt >= 0 && theInt <= 1;
CatchError
}
/*!
Valid with respect to the static domain?
*/
Bll PropFlipVarVi::validStat(Wrp const & theWrp) const
{
WatchError
return theWrp.itemInt() >= 0 && theWrp.itemInt() <= 1;
CatchError
}
/*!
Valid with respect to the dynamic domain?
*/
Bll PropFlipVarVi::validDyna(Wrp const & theWrp) const
{
WatchError
return theWrp.itemInt() >= 0 && theWrp.itemInt() <= 1;
CatchError
}
/*!
Whether the current value is the right value?
*/
Bll PropFlipVarVi::chkCurrRight() const
{
WatchError
return mValueRec->CurrBuff;
CatchError
}
/*!
Whether the current value is the left value?
*/
Bll PropFlipVarVi::chkCurrLeft() const
{
WatchError
return !mValueRec->CurrBuff;
CatchError
}
/*!
Whether the next value is the right value?
*/
Bll PropFlipVarVi::chkNextRight() const
{
WatchError
return mValueRec->NextBuff;
CatchError
}
/*!
Whether the next value is the left value?
*/
Bll PropFlipVarVi::chkNextLeft() const
{
WatchError
return !mValueRec->NextBuff;
CatchError
}
/*!
Current state of the var.
*/
Bll PropFlipVarVi::CurrState() const
{
WatchError
return mValueRec->CurrBuff;
CatchError
}
/*!
Next state of the var.
*/
Bll PropFlipVarVi::NextState() const
{
WatchError
return mValueRec->NextData(mTermSys.SimulClk());
CatchError
}
/*!
Random state of the var.
*/
Bll PropFlipVarVi::RandState(Rnd & theRnd) const
{
WatchError
return uniform(theRnd);
CatchError
}
/*!
State for a given wrap value.
*/
Bll PropFlipVarVi::WrapState(Wrp const & theWrp) const
{
WatchError
return theWrp.itemInt();
CatchError
}
/*!
Randomly chosen value.
*/
Int PropFlipVarVi::RandValue(Rnd & theRnd) const
{
WatchError
return uniform(theRnd);
CatchError
}
/*!
The left value.
*/
Int PropFlipVarVi::LeftValue() const
{
WatchError
return false;
CatchError
}
/*!
The right value.
*/
Int PropFlipVarVi::RightValue() const
{
WatchError
return true;
CatchError
}
/*!
The state value.
*/
Int PropFlipVarVi::StateValue(Bll const RightNotLeft) const
{
WatchError
return RightNotLeft;
CatchError
}
/*!
Random value chosen from the static domain.
*/
Wrp PropFlipVarVi::StatRandWrap(Rnd & theRnd) const
{
WatchError
return Wrp(castInt(uniform(theRnd)));
CatchError
}
/*!
Random value chosen from the dynamic domain.
*/
Wrp PropFlipVarVi::DynaRandWrap(Rnd & theRnd) const
{
WatchError
return Wrp(castInt(uniform(theRnd)));
CatchError
}
/*!
Wrap for the left value.
*/
Wrp PropFlipVarVi::LeftWrap() const
{
WatchError
return Wrp(castInt(0));
CatchError
}
/*!
Wrap for the right value.
*/
Wrp PropFlipVarVi::RightWrap() const
{
WatchError
return Wrp(castInt(1));
CatchError
}
/*!
Wrap of a given state.
*/
Wrp PropFlipVarVi::StateWrap(Bll const RightNotLeft) const
{
WatchError
return Wrp(castInt(RightNotLeft));
CatchError
}
/*!
Perform anew execution with a value.
*/
void PropFlipVarVi::execAnewValue(Int const & theInt)
{
WatchError
Warn(theInt < 0 || theInt > 1, eOutOfDomain);
runPreExecAnew();
mValueRec->initCurr(theInt);
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform anew execution with a value wrap.
*/
void PropFlipVarVi::execAnewWrap(Wrp const & theWrp)
{
WatchError
Warn(theWrp.itemInt() < 0 || theWrp.itemInt() > 1, eOutOfDomain);
runPreExecAnew();
mValueRec->initCurr(theWrp.itemInt());
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform anew execution with truth value.
*/
void PropFlipVarVi::execAnewState(Bll const RightNotLeft)
{
WatchError
runPreExecAnew();
mValueRec->initCurr(RightNotLeft);
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform anew execution wth a random value from the static domain.
*/
void PropFlipVarVi::execAnewStatRand(Rnd & theRnd)
{
WatchError
runPreExecAnew();
mValueRec->initCurr(uniform(theRnd));
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform anew execution wth a random value from the dyanmic domain.
*/
void PropFlipVarVi::execAnewDynaRand(Rnd & theRnd)
{
WatchError
runPreExecAnew();
mValueRec->initCurr(uniform(theRnd));
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform anew execution with the next value.
*/
void PropFlipVarVi::execAnewFlip()
{
WatchError
runPreExecAnew();
mValueRec->initCurr(!mValueRec->CurrBuff);
#if ExecUpwdLazy
runPostExecAnew();
#endif
CatchError
}
/*!
Perform incremental execution with a value.
*/
void PropFlipVarVi::execIncrValue(Int const & theInt)
{
WatchError
Warn(theInt < 0 || theInt > 1, eOutOfDomain);
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), theInt);
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform incremental execution with a value wrap.
*/
void PropFlipVarVi::execIncrWrap(Wrp const & theWrp)
{
WatchError
Warn(theWrp.itemInt() < 0 || theWrp.itemInt() > 1, eOutOfDomain);
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), theWrp.itemInt());
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform incremental execution with a truth value.
*/
void PropFlipVarVi::execIncrState(Bll const RightNotLeft)
{
WatchError
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), RightNotLeft);
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform incremental execution with a random value from the static domain.
*/
void PropFlipVarVi::execIncrStatRand(Rnd & theRnd)
{
WatchError
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), uniform(theRnd));
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform incremental execution with a random value from the dynamic domain.
*/
void PropFlipVarVi::execIncrDynaRand(Rnd & theRnd)
{
WatchError
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), uniform(theRnd));
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform incremental execution by flipping.
*/
void PropFlipVarVi::execIncrFlip()
{
WatchError
runPreExecIncr();
mValueRec->updtCurr(mTermSys.ExecClk(), !mValueRec->CurrBuff);
#if ExecUpwdLazy
runPostExecIncr();
#endif
CatchError
}
/*!
Perform anew simulation with a random value from the static domain.
*/
void PropFlipVarVi::simulAnewStatRand(Rnd & theRnd)
{
WatchError
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), uniform(theRnd));
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform anew simulation with a random value from the dynamic domain.
*/
void PropFlipVarVi::simulAnewDynaRand(Rnd & theRnd)
{
WatchError
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), uniform(theRnd));
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform anew simulation with a value wrap.
*/
void PropFlipVarVi::simulAnewValue(Int const & theInt)
{
WatchError
Warn(theInt < 0 || theInt > 1, eOutOfDomain);
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), theInt);
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform anew simulation with a value wrap.
*/
void PropFlipVarVi::simulAnewWrap(Wrp const & theWrp)
{
WatchError
Warn(theWrp.itemInt() < 0 || theWrp.itemInt() > 1, eOutOfDomain);
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), theWrp.itemInt());
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform anew simulation with a truth value.
*/
void PropFlipVarVi::simulAnewState(Bll RightNotLeft)
{
WatchError
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), RightNotLeft);
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform anew simulation by flipping.
*/
void PropFlipVarVi::simulAnewFlip()
{
WatchError
runPreSimulAnew();
mValueRec->initNext(mTermSys.SimulClk(), !mValueRec->CurrBuff);
#if SimulUpwd
runPostSimulAnew();
#endif
CatchError
}
/*!
Perform incremental simulation with a random value from the static domain.
*/
void PropFlipVarVi::simulIncrStatRand(Rnd & theRnd)
{
WatchError
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), uniform(theRnd));
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
/*!
Perform incremental simulation with a random value from the dynamic domain.
*/
void PropFlipVarVi::simulIncrDynaRand(Rnd & theRnd)
{
WatchError
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), uniform(theRnd));
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
/*!
Perform incremental simulation with a value.
*/
void PropFlipVarVi::simulIncrValue(Int const &theInt)
{
WatchError
Warn(theInt < 0 || theInt > 1, eOutOfDomain);
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), theInt);
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
/*!
Perform incremental simulation with a value wrap.
*/
void PropFlipVarVi::simulIncrWrap(Wrp const & theWrp)
{
WatchError
Warn(theWrp.itemInt() < 0 || theWrp.itemInt() > 1, eOutOfDomain);
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), theWrp.itemInt());
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
/*!
Perform incremental simulation with a truth value.
*/
void PropFlipVarVi::simulIncrState(Bll const RightNotLeft)
{
WatchError
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), RightNotLeft);
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
/*!
Perform incremental simulation by flipping.
*/
void PropFlipVarVi::simulIncrFlip()
{
WatchError
runPreSimulIncr();
mValueRec->initNext(mTermSys.SimulClk(), !mValueRec->CurrBuff);
#if SimulUpwd
runPostSimulIncr();
#endif
CatchError
}
closeKangarooSpace
|
988a2b07de562efd9d07bd94b749cbefc2072151 | 5530889c1e70a8049ed2aff2dd6a4d42c77bf41b | /secao_05/ex41.cpp | 234d69cb988471f49ca246090021bebb52cb8a2f | [] | no_license | defauth98/exs-cpp | 40bd07e1fc0dd26efd1014909ca6f1fe5dab9b13 | 876ef553c5974ece64e90546b69af8844d33e96b | refs/heads/master | 2023-07-05T13:13:13.042757 | 2021-08-02T14:37:51 | 2021-08-02T14:37:51 | 220,782,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | ex41.cpp | #include <iostream>
using namespace std;
int main(){
float peso, altura, imc;
cout << "Peso: ";
cin >> peso;
cout << "Altura: ";
cin >> altura;
imc = peso / (altura * altura);
if (peso < 18.5){
cout << "Abaixo do peso" << endl;
}
else if((peso >= 18.6) && (peso <=24.9)){
cout << "Saudável" << endl;
}
else if((peso >= 25) && (peso <=29.9)){
cout << "Peso em execesso" << endl;
}
else if((peso >= 30) && (peso <= 34.9)){
cout << "Obesidade grau 1" << endl;
}
else if((peso >= 35) && (peso <=39.9)){
cout << "Obesidade grau 2" << endl;
}
else if(peso >= 40){
cout << "Obesidade grau 3" << endl;
}
return 0;
} |
01ca9eef684dbab11cb04d821893e37e82fb76e3 | d6372ce88cee469bf2ed926ae7cac58002b0eab3 | /CIS279/Assignment/2/componentLabelling/main.cpp | ce227d7c2e7e5f0d7123d5ebbc7a12dc4fdcca55 | [] | no_license | caoyucen/CSM | b3f125d5886691c52c322dd6dfa7609a9b2a81e2 | 955eb374a06917da7b510bbd972e3062ee2b0ed6 | refs/heads/master | 2020-04-24T17:24:44.255688 | 2019-08-30T17:45:58 | 2019-08-30T17:45:58 | 172,146,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,477 | cpp | main.cpp | //
// main.cpp
// componentLabelling
//
// Created by baobao on 2019/2/24.
// Copyright © 2019年 YUCEN CAO. All rights reserved.
//
/*
* Image Component Labeling
* Project 1
* Yucen Cao
* 2019/02/24
*
* Purpose and usage of this application
* . . .
* . . .
*
*/
// . . .
// . . .
// . . .
// global variables
#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include "queue.h"
#include "stack.h"
#include "array2d.h"
using namespace std;
class PixelObject {
public:
int label;
char order;
PixelObject(int label, char order)
:label(label), order(order) {}
friend ostream& operator<<(ostream& ost, const PixelObject& obj) {
ost << "(" << setw(2) << obj.label << "," << setw(2) << obj.order << ")";
return ost;
}
friend istream& operator>>(istream& i, PixelObject& obj) {
i >> obj.label;
i >> obj.order;
return i;
}
};
Array2D<PixelObject> arrayBFS;
Array2D<PixelObject> arrayDFS;
int size; // number of rows and columns in the image
// initialize offsets
vector<Position2D> offset;
offset.push_back(Position2D(0, 1));
offset.push_back(Position2D(1, 0));
offset.push_back(Position2D(0, -1));
offset.push_back(Position2D(-1, 0));
// functions
void welcome()
{
// Optional code goes here
}
void make2dArray(Array2D<PixelObject> pixel, int n_rows, int n_cols) {
arrayDFS = Array2D<PixelObject>(n_rows, n_cols, PixelObject(0, 0));
}
void inputImage()
{// Input the image.
cout << "Enter image size" << endl;
cin >> size;
// create and input the pixel array
make2dArray(arrayDFS, size + 2, size + 2);
float density = 0.0;
cout << "Do you want to input image label manually, or let the system randomly create one?" << endl << "Press -1 to manually enter, otherwise please input a float number between 0 - 1 as density factor:" << endl;
cin >> density;
if (density < -0.5) {
cout << "Please input the array from top left to bottom right (only labels, 1 or 0):" << endl;
for (int i = 1; i < arrayDFS.get_nrows(); i++) {
for (int j = 1; j < arrayDFS.get_ncols(); j++) {
// TODO: verify if this works
int label;
cin >> label;
arrayDFS[i][j].label = label;
}
}
}
else {
cout << "Randomizing pixel arrays" << endl;
arrayDFS.randomize(density, PixelObject(1, 'x'));
}
// Copy arrayDFS to arrayBFS
arrayBFS = Array2D<PixelObject>(arrayDFS);
}
void labelComponentsDFS() {
}
void labelComponentsBFS()
{// Label the components.
// scan all pixels labeling components
Queue<Position2D> q;
int id = 0; // component id
int currentOrder = 0;
for (int r = 1; r <= size; r++) {
for (int c = 1; c <= size; c++) {
if (arrayBFS[r][c].order == 'x' && arrayBFS[r][c].label == 1) {
Position2D current(r, c);
q.push_back(current);
id++;
currentOrder = 0;
while (!q.empty()) {
Position2D current = q.front();
arrayBFS[current.row][current.col].label = id;
arrayBFS[current.row][current.col].order = '0' + (++currentOrder);
for (int i = 0; i < offset.size(); i++) {
Position2D child(current + offset[i]);
q.push_back(child);
}
q.pop_front();
}
} // end of if, for c, and for r
}
}
}
void outputImage()
{// Output labeled image.
cout << "Labeled Image After BFS: " << endl;
cout << arrayBFS << endl;
cout << "Labeled Image After DFS:" << endl;
cout << arrayDFS << endl;
}
int main()
{
welcome();
inputImage();
labelComponentsBFS();
outputImage();
return 0;
}
|
5ff0466a770f64dc56fd1ed11dce465d07ff8d85 | 26af0437c830462913ba8ea4808c9c49d5c2a2ee | /wordShift.cpp | 15fd910427ad7f38dafeefd3f0d697dfde309b74 | [] | no_license | aceparadox95/classwork | 01c99e582fe6da30f1a498425c88fc767afbf594 | a3e1ce5f8a63655d845099d40147b15fb1a8e021 | refs/heads/master | 2021-01-23T16:12:51.374285 | 2017-04-08T17:59:39 | 2017-04-08T17:59:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,894 | cpp | wordShift.cpp | /*****************************
* Author: Ryan Cosby
* Date Created: 11/7/2014
* Last Modification Date: 11/7/2014
* File name: wordShift.cpp
*
* Overview:
* This program allows a user to interact with a string that they enter.
* Users can move the characters of the string to the right or left. They
* can also reverse the order of the characters in the string as well.
* Input:
* User enters string they wants to manipulate.
* User enters "L<num of integers>" to shift left.
* User enters "R<num of integers>" to shift right.
* User enters "rev" to reverse the string.
* User enters "quit" to exit the program.
* Output:
* Prints the manipulated string after each command.
* **************************************************************/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cctype>
using namespace std;
char *leftShift(char userString[], int shift) //Function for shifting to the left
{
for (int s = 0; s < shift; s++)// Number of shifts specified by user
{
char firstChar = userString[0]; //store the variable that will get pushed off the array
for (int i = 0; i < strlen(userString); i++)// Shift left 1 spot
{
if (i == (strlen(userString) - 1))
userString[i] = firstChar;//replace the character on the last character
else
userString[i] = userString[i + 1]; //assign the variable from the right side to left side
}
}
return userString;
}
char *rightShift(char userString[], int shift)//Function for shifting to the right
{
for (int s = 0; s < shift; s++)// Number of shifts specified by user
{
char lastChar = userString[strlen(userString)-1];//store variable that will get pushed off the array
for (int i = strlen(userString) - 1; i >= 0; i--)//shift right 1 spot
{
if (i == 0)
userString[i] = lastChar; //replace the character on the first character
else
userString[i] = userString[i - 1]; //assign the variable from the left side to right side
}
}
return userString;
}
char *revShift(char userString[])//function to reverse the string
{
for (int i = 0; i < (strlen(userString)/2); i++)//iterate through half of the string
{
char swapChar; //temp value to store swap character
swapChar = userString[i];
userString[i] = userString[(strlen(userString)- 1 - i)]; //swap characters inward
userString[(strlen(userString)- 1 - i)] = swapChar;//swap characters inward till middle
}
return userString;
}
char* command(char userString[], char comm[])//User Command Interpreter
{
if (isalpha(comm[0]))
{
int invChars = 0; //int to store number of invalid characters
char shiftWord[50]; //temp variable to store the shift word
int shift = 0; //int to store the shift value
char remWord[50];//string to hold the remainder of rev and quit commands after first character
if ((strlen(comm)> 1) && ((comm[0] == 'L')||(comm[0] == 'R')||(comm[0] == 'r')||(comm[0] == 'q')))//Test for valid first character
{
if (comm[0] == 'r')//if 'r' check and see if the remainder of the word is "ev"
{
for (int i = 1; i < strlen(comm) + 1;i++)//iterate through all characters after the first letter
remWord[i-1]= comm[i];
if ((strlen(remWord)== 2) && (remWord[0] == 'e') && (remWord[1]=='v'))
return revShift(userString);//call reverse function if it makes it this far
else
{
cout << "Invalid Reverse Command. Enter rev to reverse" << endl;
return userString;
}
}
if (comm[0] == 'q')//if 'q' check and see if the remainder of the word is "uit"
{
for (int i = 1; i < strlen(comm) + 1;i++)//iterate through all characters after the first letter
remWord[i-1]= comm[i];//store value in remainder word
if ((strlen(remWord)== 3) && (remWord[0] == 'u') && (remWord[1]=='i')&& (remWord[2]=='t'))
return comm; //returns word "quit" which ends the program
else
{
cout << "Invalid Quit Command. Enter quit to quit." << endl;
return userString;
}
}
for (int i = 1; i < strlen(comm);i++)//iterate through characters after first letter
{
if (!(isdigit(comm[i])))//check for letters after first character
invChars++;//increase invalid letter count
else
shiftWord[i-1]= comm[i];//store shift value as string
}
shift = atoi(shiftWord);//convert string value to integer
if (invChars > 0)// check for invalid characters
{
cout << "Invalid Command. Your shift value can only have numbers in it." << endl;
return userString;
}
if (comm[0] == 'L')//checks for capital L and calls the left shift function
return leftShift(userString, shift);
if (comm[0] == 'R')//checks for capital R and calls the right shift function
return rightShift(userString, shift);
}
else
{
cout << "Invalid Command. Your first character was invalid" << endl;
return userString;
}
}
else
{
cout << "Invalid Command. Your first character must be a letter" << endl;
return userString;
}
}
int main()
{
char inpString[50], commString[10]; //decalre variables to store the string and command from user
cout << "Enter a string: " << endl;//prompt for string
cin.getline(inpString, 50);//store string
string normString;// temporary string variable
while (normString != "quit")
{
cout<< "Enter a command: " <<endl;
cin >> commString;
normString = string(command(inpString, commString)); //call command function and convert to string
if (normString !="quit")//check string for "quit"
cout<< "Your string is " << inpString << endl;
for (int i = 0; i < strlen(inpString) + 1; i++) //have to make it loop one character long to hold the null terminator
inpString[i] = normString[i];//copy values back into c style string
}
return 0;
} |
348fb8b34c3e9ee872e4be0f8b323cf141a308fd | 94fb2616024ec081283a5e05fb4fab393dc0f8c4 | /LaserSff/include/YagLaser.h | b7d285c768ee29e5c3036bc7c20aef8233d2f58d | [] | no_license | skyera/lasersff | 84fd54c02a6dc5bd23b6f724d1663ad771c28a7d | 99a33b62f593d3396e0d584ec3cff2543e8c762c | refs/heads/master | 2021-05-16T03:17:59.735295 | 2017-10-19T15:14:11 | 2017-10-19T15:14:11 | 35,755,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | h | YagLaser.h | #ifndef RCAM_YAGLASER_H
#define RCAM_YAGLASER_H
#include "Laser.h"
//#include <wx/ctb/iobase.h>
//#include <wx/ctb/serport.h>
#include "SerialPort.h"
#include <string>
#include <boost/shared_ptr.hpp>
#include "PCI1200.h"
#include <wx/thread.h>
namespace rcam {
// YAG Laser
class YagLaser: public Laser
{
public:
YagLaser();
~YagLaser();
virtual bool Connect(int port);
virtual bool Disconnect();
virtual bool OpenShutter();
virtual bool CloseShutter();
virtual bool IsShutterOpen();
virtual bool IsLaserOn();
bool SetLaserOn();
bool SetLaserOff();
bool SetLaserStandby();
std::string GetLaserStatus();
std::string GetShutterStatus();
virtual std::string GetPowerPercent();
virtual std::string GetPowerWatt();
bool SetEPCOn();
bool SetEPCOff();
bool SingleShot();
virtual bool SetPower(int percent);
bool SetEPCHighValue();
bool SetEPCLowValue();
std::string GetEPCStatus();
std::string GetInterlockStatus();
virtual void SetDaqboard(const boost::shared_ptr<DaqBoard>& board);
private:
std::string Send(const std::string& cmd);
// data
bool m_connected;
boost::shared_ptr<SerialPort> m_serialPortPtr;
boost::shared_ptr<DaqBoard> m_daqboard;
bool m_shutterStatus;
bool m_laserOn;
wxMutex m_mutex;
};
}
#endif |
9ea55c8d64ac3d94fbaf70a5efd36f5c50df2b30 | 103a77857b0290f02fbb033622206db073387ef6 | /VS_2019/ConsoleFEMTest/OrthotropicElasticMaterial.cpp | 8a3fe970fefb0e554ca03ec8f1ecee2a4283dc84 | [] | no_license | rsalgad/ConsoleFEM | 13cc1600f6a3a9cc84ea76ca34eba6af1a3a9f7e | 4de4dc22298f8201da33357c4ab57ef517e971a5 | refs/heads/master | 2022-11-29T11:49:30.228033 | 2020-08-06T18:59:35 | 2020-08-06T18:59:35 | 200,882,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,068 | cpp | OrthotropicElasticMaterial.cpp | #include "pch.h"
OrthotropicElasticMaterial::OrthotropicElasticMaterial()
{
}
OrthotropicElasticMaterial::OrthotropicElasticMaterial(int ID, double Ex, double Ey, double vxy, double Gxy, double Gyz, double Gxz)
{
_ID = ID;
_Ex = Ex;
_Ey = Ey;
_vxy = vxy;
_Gxy = Gxy;
_Gyz = Gyz;
_Gxz = Gxz;
}
OrthotropicElasticMaterial::OrthotropicElasticMaterial(int ID, double Ex, double Ey)
{
_ID = ID;
_Ex = Ex;
_Ey = Ey;
}
int OrthotropicElasticMaterial::GetID() {
return _ID;
}
double OrthotropicElasticMaterial::GetStiffnessX()
{
return _Ex;
}
double OrthotropicElasticMaterial::GetStiffnessY()
{
return _Ey;
}
double OrthotropicElasticMaterial::GetShearStiffnessXY()
{
return _Gxy;
}
double OrthotropicElasticMaterial::GetShearStiffnessYZ()
{
return _Gyz;
}
double OrthotropicElasticMaterial::GetShearStiffnessXZ()
{
return _Gxz;
}
double OrthotropicElasticMaterial::GetPoissonXY()
{
return _vxy;
}
std::string OrthotropicElasticMaterial::GetType()
{
return "Orthotropic-Elastic";
}
std::string OrthotropicElasticMaterial::ToString()
{
std::string str = "";
str += "(";
str += std::to_string(_ID);
str += ")";
str += "(";
str += "Ex = ";
str += _Ex;
str += ", ";
str += "Ey = ";
str += _Ey;
str += ", ";
str += "Ex = ";
str += _Ex;
str += ", ";
str += "Vxy = ";
str += _vxy;
str += ", ";
str += "Gxy = ";
str += _Gxy;
str += ", ";
str += "Gyz = ";
str += _Gyz;
str += ", ";
str += "Gxz = ";
str += _Gxz;
str += ")";
return str;
}
OrthotropicElasticMaterial* OrthotropicElasticMaterial::FindElasticMaterialByID(const std::map<int, MaterialModel*>* listOfMaterials, int ID) {
std::map<int, MaterialModel*>::const_iterator it = listOfMaterials->begin();
while (it != listOfMaterials->end()) {//for each material
if (it->second->GetType() == "Orthotropic-Elastic") {
if (it->second->GetID() == ID) {
OrthotropicElasticMaterial* mat = static_cast<OrthotropicElasticMaterial*>(it->second);
return mat;
}
}
it++;
}
return nullptr;
}
OrthotropicElasticMaterial::~OrthotropicElasticMaterial()
{
}
|
4d94f2c9e2c803e679b65679315ddb84ecf29dad | 5f90ef28a8f2bba24289481e3c53d6b107799cd3 | /src/mapgen_demo.cpp | 2e287b120cf10e6d18829874bac2821b6c7e300c | [] | no_license | CyborgSummoners/Summoner-Wars | 18d4c09d21631ebfcdae9e1d470ce6e4d2132930 | e61a96284c3e7faf0ca24d89ea5d9d019e57dd8c | refs/heads/master | 2020-05-30T16:57:05.071888 | 2013-02-01T11:13:16 | 2013-02-01T11:13:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | cpp | mapgen_demo.cpp | #include <SFML/System.hpp>
#include <iostream>
#include <sstream>
#include <cstring>
#include "mapgen.hpp"
int main(int argc, char* argv[]) {
using namespace sum;
using namespace sum::Mapgen;
Terrain* map = new Terrain[50*20];
Map_generator* gen;
if(argc > 1) {
if(strcmp(argv[1], "caves") == 0) {
int iter = 4;
if(argc > 2) {
std::stringstream ss;
ss << argv[2];
ss >> iter;
}
if(argc > 3) {
int seed;
std::stringstream ss;
ss << argv[3];
ss >> seed;
sf::Randomizer::SetSeed(seed);
}
gen = new Caves(iter);
}
else if(strcmp(argv[1], "arena") == 0) {
gen = new Arena;
}
else {
std::cout << "Unknown map type. Valid types: arena, cave." << std::endl;
return 0;
}
} else {
gen = new Caves(3);
}
std::cout << "seed: " << sf::Randomizer::GetSeed() << std::endl;
gen->generate(map, 50, 20);
print_map(map, 50, 20, std::cout);
delete gen;
return 0;
}
|
1c238ed2737f11a76b35b1e898c8a6f4f1600a73 | 67fc67fa36cd35367506f405bbd5da605718e3a4 | /zerosum.cc | 6c9d9a2bd0bca40f87d16a68a24c0dade8126563 | [] | no_license | tuogy/usaco-solutions | 0dea33e2878d299c94ba1dc666016ed4678b2649 | 5ce3bb05fc624ab69e0f232653e3911349e5b4cd | refs/heads/master | 2022-12-07T17:08:11.421118 | 2020-09-01T04:11:35 | 2020-09-01T04:11:35 | 284,674,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | cc | zerosum.cc | /*
USER: guobich1
TASK: zerosum
LANG: C++
*/
#ifndef __clang__
#include <bits/stdc++.h>
#endif
#include <iostream>
#include <fstream>
using namespace std;
char ops[9];
int N;
void dfs(int pos, int tot, int lastn, int sign, ofstream& fout) {
if (pos == N) {
if (tot + sign * lastn == 0) {
fout << 1;
for (int i = 1; i < N; i++) {
fout << ops[i] << i + 1;
}
fout << endl;
}
return;
}
else {
ops[pos] = ' ';
dfs(pos + 1, tot, lastn * 10 + pos + 1, sign, fout);
ops[pos] = '+';
dfs(pos + 1, tot + sign * lastn, pos + 1, 1, fout);
ops[pos] = '-';
dfs(pos + 1, tot + sign * lastn, pos + 1, -1, fout);
}
}
int main() {
ifstream fin("zerosum.in");
ofstream fout("zerosum.out");
fin >> N;
dfs(1, 0, 1, 1, fout);
return 0;
} |
579eb3ab7776603b79b9d6881b1f3dc680ffc086 | 24a843551ced9e17687cf144f44894c7d7df87a4 | /ScrabbleGui/gamew.cpp | 00fb43e8c9ad9dac638bf93b87d208d02dd45b51 | [] | no_license | Nano0723/ScrabbleOficial | f0118792de7b85b1aeccb68f3da9d4023da10f45 | 9243b5d3fa23fe9efed7579c69ad497c77bff05d | refs/heads/master | 2020-05-05T05:02:34.092346 | 2019-04-11T00:55:07 | 2019-04-11T00:55:07 | 179,736,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,569 | cpp | gamew.cpp | #include "gamew.h"
#include "ui_gamew.h"
#include <iostream>
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QDebug>
#include <math.h>
#include <vector>
#include <espacios.h>
#include <mainwindow.h>
#include <sstream>
#include "Client.h"
#include <thread>
string matriz[19][19];
vector<int> posx;
vector<int> posy;
vector<string> letras;
int tempx,firstx = -1,lastx,firsty = -1,lasty;
int tempy,numFichas = 3;
int lastL;
string palabra = "";
vector<string> info;
Client* c = Client::getIntance();
using namespace std;
gameW::gameW(QWidget *parent) :
QWidget(parent),
ui(new Ui::gameW)
{
ui->setupUi(this);
llenarX();
llenarY();
connect(ui->Scrabble, SIGNAL(clicked()), this, SLOT(scrabble()));
}
gameW::~gameW()
{
delete ui;
}
void gameW::changeLabel(string name){
ui->name->setText(QString::fromStdString(name));
}
void gameW::mousePressEvent(QMouseEvent *event){
QMimeData *mimeData = new QMimeData;
if(selectFicha(event, mimeData) && event->button() == Qt::LeftButton){
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
QWidget::mousePressEvent(event);
}else if (comp(event->pos().x(),event->pos().y()) && event->button() == Qt::RightButton) {
int x = (tempx+40)/42;
int y = (tempy+40)/42;
MainWindow m;
qDebug() << y << x << QString::fromStdString(matriz[x][y]);
if(matriz[x][y] != ""){
rellenarFichas(x, y);
numFichas = numFichas + 1;
matriz[x][y] = "";
m.crearF(tempx,tempy,"");
}
}else if (comp(event->pos().x(),event->pos().y()) && event->button() == Qt::LeftButton) {
if(firstx == -1){
firstx = (tempx+40)/42;
firsty = (tempy+40)/42;
}else {
lastx = (tempx+40)/42;
lasty = (tempy+40)/42;
}
}
}
void gameW::dragEnterEvent(QDragEnterEvent *event){
if (event->mimeData()->hasFormat("text/plain")){
event->acceptProposedAction();
}
}
void gameW::dropEvent(QDropEvent *event){
if(comp(event->pos().x(),event->pos().y())){
string dato = (event->mimeData()->text()).toStdString();
MainWindow m;
int x = (tempx+40)/42;
int y = (tempy+40)/42;
if(matriz[x][y] == ""){
numFichas=numFichas-1;
cambiaFichas();
m.crearF(tempx,tempy,dato);
matriz[x][y] = dato;
}
}
}
void gameW::llenarX(){
int x = 20;
for (int i = 0; i<18 ;i++) {
posx.push_back(x);
x = x + 42;
}
}
void gameW::llenarY(){
int y = 40;
for (int i = 0; i<18 ;i++) {
posy.push_back(y);
y = y + 42;
}
}
bool gameW::comp(int pos_x, int pos_y){
int i = 0;
int j = 0;
int sizex = 18;
int sizey = 18;
while(i<posx.size()){
if(j<posy.size()){
if((pos_x>=posx[i] && pos_x<=posx[i]+42) && (pos_y>=posy[j] && pos_y<=posy[j]+42)){
tempx = posx[i];
tempy = posy[j];
return true;
}else {
j = j+1;
}
}else if(j == sizey) {
i = i+1;
j = 0;
}
}
return false;
}
//
bool gameW::selectFicha(QMouseEvent *event, QMimeData *mimeData){
if(ui->F1->geometry().contains(event->pos())){
mimeData->setText(ui->F1->text());
lastL = 1;
return true;
}if(ui->F2->geometry().contains(event->pos())){
mimeData->setText(ui->F2->text());
lastL = 2;
return true;
} if(ui->F3->geometry().contains(event->pos())){
mimeData->setText(ui->F3->text());
lastL = 3;
return true;
}if(ui->F4->geometry().contains(event->pos())){
mimeData->setText(ui->F4->text());
lastL = 4;
return true;
}if(ui->F5->geometry().contains(event->pos())){
mimeData->setText(ui->F5->text());
lastL = 5;
return true;
}if(ui->F6->geometry().contains(event->pos())){
mimeData->setText(ui->F6->text());
lastL = 6;
return true;
} if(ui->F7->geometry().contains(event->pos())){
mimeData->setText(ui->F7->text());
lastL = 7;
return true;
}
else {
return false;
}
}
void gameW::cambiaFichas(){
if(lastL == 1){
ui->F1->setText("");
}if(lastL == 2){
ui->F2->setText("");
}if(lastL == 3){
ui->F3->setText("");
}if(lastL == 4){
ui->F4->setText("");
}if(lastL == 5){
ui->F5->setText("");
}if(lastL == 6){
ui->F6->setText("");
}if(lastL == 7){
ui->F7->setText("");
}
}
void gameW::rellenarFichas(int x, int y){
if(ui->F1->text()==""){
ui->F1->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F2->text()==""){
ui->F2->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F3->text()==""){
ui->F3->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F4->text()==""){
ui->F4->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F5->text()==""){
ui->F5->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F6->text()==""){
ui->F6->setText(QString::fromStdString(matriz[x][y]));
}
else if(ui->F7->text()==""){
ui->F7->setText(QString::fromStdString(matriz[x][y]));
}
}
void gameW::generarPalabra(){
int fx = firstx;
int fy = firsty;
palabra = "";
if(lastx==firstx){
while (firsty<=lasty) {
palabra = palabra + matriz[firstx][firsty];
firsty = firsty + 1;
}firsty = fy;
}else if(lasty==firsty){
while (firstx<=lastx) {
palabra = palabra + matriz[firstx][firsty];
firstx = firstx + 1;
}firstx = fx;
}
info = {std::to_string(firstx), std::to_string(firsty), std::to_string(lastx), std::to_string(lasty), palabra};
}
void gameW::scrabble(){
MainWindow m;
if(c->connected){
//qDebug() << QString::fromStdString(palabra);
//dibujar(firstx,firsty,lastx,lasty,palabra);
c->sendMessage();
//c->sendMessage();
vector<string> mano = {"A","B","C","U"};
qDebug() << mano.size();
rellenarMano(mano);
generarPalabra();
m.setVector(info);
count++;
firstx = -1;
firsty = -1;
c->recieveMessage();
qDebug() << m.getCount();
c->connected = false;
}else{
qDebug() << "No se pudo conectar";
}
}
/*void gameW::threadSend()
{
}
void gameW::threadRecieve()
{
}
*/
void gameW::dibujar(int x1,int y1,int x2,int y2,string palabra){
MainWindow m;
int i = 0;
if(x1==x2){
while (y1<=y2) {
stringstream ss;
string letraS;
char letra = palabra[i];
ss << letra;
ss >> letraS;
m.crearF(((x1-1)*42)+20,((y1-1)*42)+40,letraS);
matriz[x1][y1] = letraS;
qDebug() << QString::fromStdString(matriz[0][0]);
i = i + 1;
y1 = y1 + 1;
}
}else if(y1==y2){
while(x1<=x2){
stringstream ss;
string letraS;
char letra = palabra[i];
ss << letra;
ss >> letraS;
m.crearF(((x1-1)*42)+20,((y1-1)*42)+40,letraS);
matriz[x1][y1] = letraS;
qDebug() << QString::fromStdString(matriz[0][0]);
i = i + 1;
x1 = x1 + 1;
}
}
}
void gameW::rellenarMano(vector<string> mano){
for (int i = 0; i<mano.size();i++) {
if(ui->F1->text()==""){
ui->F1->setText(QString::fromStdString(mano[i]));
}
else if(ui->F2->text()==""){
ui->F2->setText(QString::fromStdString(mano[i]));
}
else if(ui->F3->text()==""){
ui->F3->setText(QString::fromStdString(mano[i]));
}
else if(ui->F4->text()==""){
ui->F4->setText(QString::fromStdString(mano[i]));
}
else if(ui->F5->text()==""){
ui->F5->setText(QString::fromStdString(mano[i]));
}
else if(ui->F6->text()==""){
ui->F6->setText(QString::fromStdString(mano[i]));
}
else if(ui->F7->text()==""){
ui->F7->setText(QString::fromStdString(mano[i]));
}
}
}
|
0bcfe64ea1ae0ba675c2e896dc06e2e234270d9d | 83c87b0c52ea2a3c0f219bdc3cde9a383b988ff2 | /src/cocos2dx/cocoa/jacos2dx/DataStream.cpp | 2a73fdcb3974e9674a77925e56f9e5caa3258acd | [
"MIT"
] | permissive | superluffy/jacos2d-x | acff8f6c22f3a374aac286b26d2a915d5951bcac | 70acad79558e8e96df34c4a1db41a81c67ca23c9 | refs/heads/master | 2021-01-18T06:47:00.559771 | 2013-03-12T12:26:53 | 2013-03-12T12:26:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,816 | cpp | DataStream.cpp | /****************************************************************************
Copyright (c) 2013 Thai-Duong Nguyen
http://jacos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "JacosBaseObject.h"
#include "DataStream.h"
#include "stdlib.h"
#include "string.h"
#include "../CCString.h"
#define ASSERT JSC_ThrowException
namespace jacos2dx {
void OutputStream::writeEOL(int eol)
{
switch (eol) {
case _CR:
this->writeByte(0x0D);
break;
case _LF:
this->writeByte(0x0A);
break;
case _CR_LF:
this->writeByte(0x0D);
this->writeByte(0x0A);
break;
case _LF_CR:
this->writeByte(0x0A);
this->writeByte(0x0D);
break;
}
}
ByteArray::ByteArray(unsigned int size)
{
mLength = size;
mBuffer = (unsigned char*)malloc(size);
memset(mBuffer, 0, mLength);
}
ByteArray::ByteArray(ByteArray* data)
{
mLength = data->mLength;
mBuffer = (unsigned char*)malloc(mLength);
memcpy(mBuffer, data->mBuffer, mLength);
}
ByteArray::ByteArray(const unsigned char* data, unsigned int size)
{
mLength = size;
mBuffer = (unsigned char*)malloc(mLength);
memcpy(mBuffer, data, mLength);
}
ByteArray::ByteArray(const char* string)
{
mLength = strlen(string) + 1;
mBuffer = (unsigned char*)malloc(mLength);
memcpy(mBuffer, string, mLength);
}
ByteArray::~ByteArray()
{
free(mBuffer);
}
bool ByteArray::write(unsigned int index, int value)
{
if (index >= 0 && index < mLength)
{
mBuffer[index] = (unsigned char)(value & 0xFF);
return true;
}
return false;
}
int ByteArray::read(unsigned int index)
{
if (index >= 0 && index < mLength)
{
return mBuffer[index];
}
return -1;
}
DataBufferedOutputStream::DataBufferedOutputStream(int size)
{
mPosition = 0;
if (size == 0)
mCapacity = 10;
else mCapacity = size;
mData = (unsigned char*)malloc(mCapacity);
}
DataBufferedOutputStream::~DataBufferedOutputStream()
{
free(mData);
}
void DataBufferedOutputStream::writeByte(int value)
{
makeSureCapacity(mPosition + 1);
mData[mPosition++] = (unsigned char)(value & 0xFF) ;
}
void DataBufferedOutputStream::writeSByte(int value)
{
makeSureCapacity(mPosition + 1);
mData[mPosition++] = (char)(value & 0xFF);
}
void DataBufferedOutputStream::writeInt32(int value)
{
makeSureCapacity(mPosition + 4);
mData[mPosition++] = ((unsigned char)(value >> 24) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 16) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 8) & 0xFF);
mData[mPosition++] = ((unsigned char)(value & 0xFF));
}
void DataBufferedOutputStream::writeUInt32(unsigned int value)
{
makeSureCapacity(mPosition + 4);
mData[mPosition++] = ((unsigned char)(value >> 24) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 16) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 8) & 0xFF);
mData[mPosition++] = ((unsigned char)(value & 0xFF));
}
void DataBufferedOutputStream::writeInt16(int value)
{
makeSureCapacity(mPosition + 2);
mData[mPosition++] = ((unsigned char)(value >> 8) & 0xFF);
mData[mPosition++] = ((unsigned char)(value & 0xFF));
}
void DataBufferedOutputStream::writeUInt16(int value)
{
makeSureCapacity(mPosition + 2);
mData[mPosition++] = ((unsigned char)(value >> 8) & 0xFF);
mData[mPosition++] = ((unsigned char)(value & 0xFF));
}
void DataBufferedOutputStream::writeLong(long value)
{
makeSureCapacity(mPosition + 4);
mData[mPosition++] = ((unsigned char)(value >> 24) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 16) & 0xFF);
mData[mPosition++] = ((unsigned char)(value >> 8) & 0xFF);
mData[mPosition++] = ((unsigned char)(value & 0xFF));
}
void DataBufferedOutputStream::writeFloat(float value)
{
makeSureCapacity(mPosition + sizeof(float));
memcpy(mData + mPosition, &value, sizeof(float));
mPosition += sizeof(float);
}
void DataBufferedOutputStream::writeDouble(double value)
{
makeSureCapacity(mPosition + sizeof(double));
memcpy(mData + mPosition, &value, sizeof(double));
mPosition += sizeof(double);
}
void DataBufferedOutputStream::writeUTF8(const char* string)
{
int length = strlen(string);
makeSureCapacity(mPosition + length + 2);
writeUInt16(length);
memcpy(mData + mPosition, string, length);
mPosition += length;
}
void DataBufferedOutputStream::writeUTF8Line(const char* string, int eol)
{
int length = strlen(string);
makeSureCapacity(mPosition + length + 2);
memcpy(mData + mPosition, string, length);
mPosition += length;
writeEOL(eol);
}
void DataBufferedOutputStream::writeBoolean(bool value)
{
makeSureCapacity(mPosition + 1);
mData[mPosition++] = value?0xFF:0;
}
void DataBufferedOutputStream::writeByteArray(ByteArray *data)
{
ASSERT(data != NULL, "data cannot null");
makeSureCapacity(mPosition + data->getLength());
memcpy(mData + mPosition, data->mBuffer, data->getLength());
mPosition += data->getLength();
}
void DataBufferedOutputStream::writeByteArray(ByteArray *data, unsigned int start, unsigned int length)
{
ASSERT(data != NULL, "data cannot null");
ASSERT(length > 0, "length cannot equal 0");
ASSERT(start >= 0, "length is lesser 0");
ASSERT(start + length <= data->getLength(), "data not in range");
makeSureCapacity(mPosition + length);
memcpy(mData + mPosition, data->mBuffer + start, length);
mPosition += length;
}
void DataBufferedOutputStream::flush()
{
}
ByteArray* DataBufferedOutputStream::toByteArray()
{
return new ByteArray(mData, getLength());
}
DataBufferedInputStream::DataBufferedInputStream(ByteArray* data, bool autoRelease)
{
ASSERT(data != NULL, "Data cannot null");
mData = data;
mPosition = 0;
mAutoRelease = autoRelease;
}
DataBufferedInputStream::~DataBufferedInputStream()
{
if (mAutoRelease && mData)
delete mData;
}
int DataBufferedInputStream::readByte()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
return mData->mBuffer[mPosition++];
}
int DataBufferedInputStream::readSByte()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
return (char)mData->mBuffer[mPosition++];
}
int DataBufferedInputStream::readInt32()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val0 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val1 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val2 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val3 = mData->mBuffer[mPosition++];
return (val0 << 24) | (val1 << 16) | (val2 << 8) | val3;
}
unsigned int DataBufferedInputStream::readUInt32()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val0 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val1 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val2 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val3 = mData->mBuffer[mPosition++];
return (unsigned int)((val0 << 24) | (val1 << 16) | (val2 << 8) | val3);
}
int DataBufferedInputStream::readUByte()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
return mData->mBuffer[mPosition++];
}
int DataBufferedInputStream::readInt16()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val0 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val1 = mData->mBuffer[mPosition++];
return (short)((val0 << 8) | val1);
}
int DataBufferedInputStream::readUInt16()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val0 = mData->mBuffer[mPosition++];
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int val1 = mData->mBuffer[mPosition++];
return (unsigned short)((val0 << 8) | val1);
}
float DataBufferedInputStream::readFloat()
{
ASSERT(mPosition + sizeof(float) <= mData->getLength(), "Cannot read float!");
float ret;
memcpy(&ret, mData + mPosition, sizeof(float));
mPosition += sizeof(float);
return ret;
}
double DataBufferedInputStream::readDouble()
{
ASSERT(mPosition + sizeof(double) <= mData->getLength(), "Cannot read double!");
double ret;
memcpy(&ret, mData + mPosition, sizeof(double));
mPosition += sizeof(double);
return ret;
}
long DataBufferedInputStream::readLong()
{
return readInt32();
}
const char* DataBufferedInputStream::readUTF8()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int i = mPosition;
int strLength = readUInt16();
int length = mData->getLength() - mPosition;
ASSERT(length < strLength, "Not enough data!");
char* ret = (char*)malloc(strLength + 1);
memcpy(ret, mData->mBuffer + mPosition, strLength);
mPosition += strLength;
ret[strLength] = '\0';
cocos2d::CCString *rets = cocos2d::CCString::create(ret);
free(ret);
return rets->getCString();
}
const char* DataBufferedInputStream::readUTF8Line(int eol)
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
int i = mPosition;
int end = i;
for (; i < mData->getLength(); i++) {
if (eol == _CR && mData->mBuffer[i] == 0x0D) {
end = i;
break;
} else if (eol == _LF && mData->mBuffer[i] == 0x0A) {
end = i;
break;
} else if (eol == _CR_LF && i + 1 < mData->getLength() && mData->mBuffer[i] == 0x0D && mData->mBuffer[i + 1] == 0x0A)
{
end = i;
i++;
break;
} else if (eol == _LF_CR && i + 1 < mData->getLength() && mData->mBuffer[i] == 0x0A && mData->mBuffer[i + 1] == 0x0D)
{
end = i;
i++;
break;
}
}
int strLength = end - mPosition;
char* ret = (char*)malloc(strLength + 1);
memcpy(ret, mData->mBuffer + mPosition, strLength);
ret[strLength] = '\0';
cocos2d::CCString *rets = cocos2d::CCString::create(ret);
free(ret);
mPosition = i + 1;
return rets->getCString();
}
bool DataBufferedInputStream::readBoolean()
{
ASSERT(mPosition < mData->getLength(), "Cannot read any more!");
return mData->mBuffer[mPosition++]?true:false;
}
int DataBufferedInputStream::readByteArray(ByteArray *data)
{
//ASSERT(mPosition + data->getLength() <= mData->getLength(), "Data too large!");
unsigned int avail = mData->getLength() - mPosition;
if (avail >= data->getLength())
{
memcpy(data->mBuffer, mData->mBuffer + mPosition, data->getLength());
mPosition += data->getLength();
return data->getLength();
} else if (avail > 0)
{
memcpy(data->mBuffer, mData->mBuffer + mPosition, avail);
mPosition += avail;
return avail;
}
return 0;
}
int DataBufferedInputStream::readByteArray(ByteArray *data, unsigned int start, unsigned int length)
{
ASSERT(data != NULL, "data cannot null!");
ASSERT(start >= 0, "start cannot less than 0");
ASSERT(start < data->getLength(), "start must be lesser ByteArray's length");
ASSERT(length >= 0, "length cannot less than 0");
//ASSERT(start + length <= data->getLength(), "data not in range");
//ASSERT(mPosition + length <= mData->getLength(), "Data too large!");
unsigned int avail = mData->getLength() - mPosition;
if (avail >= length)
{
memcpy(data->mBuffer + start, mData->mBuffer + mPosition, length);
mPosition += length;
return length;
} else if (avail > 0)
{
memcpy(data->mBuffer + start, mData->mBuffer + mPosition, avail);
mPosition += avail;
return avail;
}
return 0;
}
bool DataBufferedInputStream::readByteArrayFully(ByteArray *data, unsigned int start, unsigned int length)
{
ASSERT(data != NULL, "data cannot null!");
ASSERT(start >= 0, "start cannot less than 0");
ASSERT(start < data->getLength(), "start must be lesser ByteArray's length");
ASSERT(length >= 0, "length cannot less than 0");
//ASSERT(start + length <= data->getLength(), "data not in range");
//ASSERT(mPosition + length <= mData->getLength(), "Data too large!");
unsigned int avail = mData->getLength() - mPosition;
if (avail >= length)
{
memcpy(data->mBuffer + start, mData->mBuffer + mPosition, length);
mPosition += length;
return true;
}
return false;
}
void DataBufferedInputStream::skip(unsigned int bytes)
{
ASSERT(bytes >= 0, "bytes less than 0");
ASSERT(mPosition + bytes <= mData->getLength(), "bytes too lager");
mPosition += bytes;
}
} |
4af3e8f431389b7bce31e1a120f3546b2552e71c | 6a99735bcda67e9ed2721c6ebecaa548096e3e38 | /nQueen.cpp | 4a84bfd7d35dd78aaaba7a15e0544d90cf9cb885 | [] | no_license | ghworld/algorithm | 39a89f4cbfaa5fb0a3d8c8e2818af8020df2e2a5 | cfeb1557f8b42cf28313bd9d3f2aaa0f2e986e1c | refs/heads/master | 2021-01-23T10:20:26.731427 | 2018-09-02T07:53:56 | 2018-09-02T07:53:56 | 93,052,202 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,136 | cpp | nQueen.cpp | //
// Created by mi on 7/3/17.
//
#include <iostream>
int sum,ans[8];
int solve(int n, long long mark, int *ans){
for (int i=n>8?++sum&0:0; n>8&&i<8; i!=7?std::cout << ans[i++] << " " : std::cout << ans[i++] << std::endl);
for (int i=0; i<8; !(mark>>i&1)&&!(mark>>(n+i+7)&1)&&!(mark>>(n-i+30)&1)?solve(n+(ans[n-1]=i+1)-i, mark|1ll<<i|1ll<<(n+i+7)|1ll<<(n-i+30), ans):0,i++);
return sum;
}
//int main(){
// std::cout << solve(1, 0, ans) << std::endl;
//}
using namespace std;
int c[20], n=8, cnt=0;
void print(){
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
if(j == c[i]) cout<<"1 ";
else cout<<"0 ";
}
cout<<endl;
}
cout<<endl;
}
void search(int r){
if(r == n){
print();
++cnt;
return;
}
for(int i=0; i<n; ++i){
c[r] = i;
int ok = 1;
for(int j=0; j<r; ++j)
if(c[r]==c[j] || r-j==c[r]-c[j] || r-j==c[j]-c[r]){
ok = 0;
break;
}
if(ok) search(r+1);
}
}
//int main(){
// search(0);
// cout<<cnt<<endl;
// return 0;
//} |
1bd0edb659edea8efaf70701c4b22bf7ff73f240 | 8bf71dd2883befffb1b326ad633cc2b1c03bc490 | /examples/07_module/line.h | deda1055319a6a0b9c488241c2f6d9972aefa0cd | [
"MIT"
] | permissive | acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-MahdevGiri | bd12f2379cbc33c8dae096cf20c124bea3e2a125 | 91322930bedf6897b6244c778c707231560ccb15 | refs/heads/master | 2020-04-18T10:09:38.098524 | 2019-05-16T14:47:16 | 2019-05-16T14:47:16 | 167,458,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 126 | h | line.h | //h
#include"shape.h"
#ifndef LINE_H
#define LINE_H
class Line : public Shape
{
public:
void draw();
};
#endif // !LINE_H
|
4519ae22d49728c90975e435e38e9eff76f31a5a | f955f73a923f9a9130a1cf161f9b2bc07a7fa8ed | /Module1/LA1-1/bmi.cpp | 4c74e9e036fcf8af9f76f5f33f7118493e46f346 | [] | no_license | gehrBehr/hafb-cpp-fundamentals | 76ee2261c286f9bed4dc15bb242dc066e82991e1 | 088e6a03d92282d1fb9198efa98b5c9297b8fcb1 | refs/heads/master | 2020-11-25T01:14:12.315291 | 2019-12-19T23:26:50 | 2019-12-19T23:26:50 | 228,425,159 | 0 | 0 | null | 2019-12-16T16:10:42 | 2019-12-16T16:10:41 | null | UTF-8 | C++ | false | false | 2,131 | cpp | bmi.cpp |
#include <iostream>
using namespace std;
const float kMetersToInches = 39.37;
const float kKiloToPound = 2.204;
const float kBMIImperial = 703;
const float kLowerNormalBound = 18.5;
const float kLowerOverweightBound = 25;
const float kLowerObeseBound = 30;
const float kLowerSevereBound = 35;
const float kLowerVeryBound = 40;
const float kMorbidlyObese = 45;
//Calculate the Body max index of the user.
int main()
{
float meters = 0.0;
float kilograms = 0.0;
float bmi = 0.0;
//BMI = weight(kg)/[height(m)]^2
cout << "Lets calculate your BMI." << endl;
cout << "How tall are you in meters? \n >" ;
cin >> meters;
cout << "How much do you weigh in kilograms? \n >" ;
cin >> kilograms;
bmi = kilograms / (meters * meters);
cout << "Your BMI is: " << bmi << endl;
//the
float weight_pounds = kilograms * kKiloToPound;
float height_inches = meters * kMetersToInches;
bmi = (weight_pounds * kBMIImperial) / (height_inches * height_inches);
cout << "Your BMI(imperial) is: " << bmi << endl;
// let the user know what the number means.
cout << "You are considered: ";
if (bmi < kLowerNormalBound)
{
cout << "Underweight (less than 18.5)" << endl;
}
else if (bmi > kLowerNormalBound && bmi < kLowerOverweightBound)
{
cout << "Normal (between 18.5 and 24.9)" << endl;
}
else if (bmi > kLowerOverweightBound && bmi < kLowerObeseBound)
{
cout << "Overweight (between 25 and 30)" << endl;
}
else if (bmi > kLowerObeseBound && bmi < kLowerSevereBound)
{
cout << "Moderately obese (between 30 and 35)" << endl;
}
else if (bmi > kLowerSevereBound && bmi < kLowerVeryBound)
{
cout << "Severely obese (between 35 and 40)" << endl;
}
else if (bmi > kLowerVeryBound && bmi < kMorbidlyObese)
{
cout << "Very severely obese (between 40 and 45)" << endl;
}
else if (bmi > kMorbidlyObese)
{
cout << "Morbidly obese (greater than 45)" << endl;
}
else
{
cout << "out of range\n";
}
return 0;
} |
514ee6b9bcc2467366b885751c07b5e908278ca9 | 71f5bc54e702d5cd5317161226ae9ca7860cde32 | /src/behavior_planner.cpp | 7de5b163bb832ee7ffc7cefc12ffa75b9cbb64ad | [
"MIT"
] | permissive | ValerioDISano/CarND-Path-Planning-Project | 799d158426fe5f8260c4f8d96d5cf20bfcce3a9a | 53746c5938644ecfa2defc58a52226f6eb072d3b | refs/heads/master | 2021-02-21T23:34:16.912246 | 2020-03-25T19:45:44 | 2020-03-25T19:45:44 | 247,461,981 | 1 | 0 | MIT | 2020-03-15T12:28:25 | 2020-03-15T12:28:24 | null | UTF-8 | C++ | false | false | 1,806 | cpp | behavior_planner.cpp | #include "behavior_planner.hpp"
void BehaviorPlanner::computeBehavior() const
{
int current_lane = conf().currentLane();
// target lane
if (this->last_prediction.car_ahead)
{
// evaluate a takeover
if (current_lane > 0 && !this->last_prediction.car_on_left)
{ // Left
conf().changeLaneToLeft();
} else if (current_lane < 2 && !this->last_prediction.car_on_right)
{ // Right
conf().changeLaneToRight();
} else
{
conf().slowDown();
}
} else // evaluate to speedup and to go back to the default lane
{
if (conf().currentSpeed() < conf().maxSpeed())
conf().speedUp();
if (( current_lane == 0 && !this->last_prediction.car_on_right ) ||
( current_lane == 2 && !this->last_prediction.car_on_left ))
{
conf().defaultLane();
}
}
}
void BehaviorPlanner::VehicleConfiguration::fromLocalToGlobalCoordinates(
double& local_x, double& local_y
)
{
double local_x_tmp {local_x};
double local_y_tmp {local_y};
local_x = this->car_x_ +
(local_x_tmp * cos(this->car_yaw_) - local_y_tmp * sin(this->car_yaw_));
local_y = this->car_y_ +
(local_x_tmp * sin(this->car_yaw_) + local_y_tmp * cos(this->car_yaw_));
}
void BehaviorPlanner::VehicleConfiguration::fromGlobalToLocalCoordinates(
double& global_x, double& global_y
)
{
double translated_x = global_x - this->car_x_;
double translated_y = global_y - this->car_y_;
global_x = translated_x * cos(this->car_yaw_) + translated_y * sin(this->car_yaw_);
global_y = translated_y * cos(this->car_yaw_) - translated_x * sin(this->car_yaw_);
}
|
dbebe1ea61311ec49d7cb4703bb802aec162a367 | b9c5a64360be550141efb8f4e691158be07f1b98 | /Rsa_Bloques/RSA.cpp | b364303a39bc37fcacb26c90190096b1b18adb07 | [] | no_license | pmadriana/Algebra-abstracta | 201b4e7b380a08db7793bd8855e959abe8442f40 | 87cffee57b7f70eb65186876051bfb0b4dd87f23 | refs/heads/master | 2021-01-20T00:53:05.485327 | 2017-09-29T20:58:06 | 2017-09-29T20:58:06 | 89,205,765 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,112 | cpp | RSA.cpp | #include "RSA.h"
#include <fstream>
bool se_abrio_archivo=false;
void RSA::generacion_claves(int bits)
{
while(ProbPrime(p,10)!=1)
{
p=generador(500,bits,8,3);
}
while(ProbPrime(q,10)!=1)
{
q=generador(500,bits,8,4);
}
this->p=p;
this->q=q;
// cout<<"p: "<<p<<endl;
// cout<<"q: "<<q<<endl;
this->N= p*q;
ZZ phi_N;
phi_N = (p-1)*(q-1);
ZZ e;
while(e >= phi_N || euclides(e, phi_N)!=1) //e tiene que ser menor a phi_n
e= generador(500,bits,8,4);
this->clave_publica=e;
// cout<<"N: "<<N<<endl;
// cout<<"Clave publica: "<<clave_publica<<endl;
ZZ inv_e;
this->clave_privada = modinv(e, phi_N);
// cout<<"clave privada: "<<clave_privada<<endl;
}
RSA::RSA(int bits) //emisor
{
generacion_claves(bits);
}
RSA::RSA(ZZ clave_pub, ZZ N, string nombre) //receptor
{
clave_publica = clave_pub;
this->N=N;
ofstream text ; //static?
if(se_abrio_archivo==false){
text.open("claves.txt");
}
else
text.open("claves.txt",ios::app);
if(text.is_open())
{
text<<nombre<<' '<<clave_pub<<' '<<N<<'\n';
}
se_abrio_archivo=true;
text.close();
}
string RSA::cifrado(string mensaje, string nombre)
{
ZZ clave_publica_otro, N_otro;
string buscador, clave_publica_otro1, N_otro1;
ifstream text;
text.open("claves.txt");
if(!text.is_open())
cout<<"no se encontro";
do
{
text>>buscador>>clave_publica_otro1>>N_otro1;
}while(nombre != buscador);
pasar_de(clave_publica_otro,clave_publica_otro1);
pasar_de(N_otro, N_otro1);
int pos; //pos_aux ->w;
string pos_s, originales;
ZZ digitos_len = to_ZZ(to_string(N_otro).size()-1);
for(int i=0; i<mensaje.size(); i++)
{
pos = alfabeto.find(mensaje[i]);
pos_s= to_string(to_ZZ(pos));
if(pos<10)
{
pos_s = "0"+ pos_s; //completar digitos
}
originales += pos_s;
}
while(modulo(to_ZZ(originales.size()), digitos_len)!= 0)
{
originales += to_string(to_ZZ(alfabeto.find("w")));
}
string bloques, bloque_cifrado, resultado;
ZZ a, C;
for(int i=0; i<originales.size(); i += to_int(digitos_len)){
bloques = originales.substr(i, to_int(digitos_len) );
pasar_de(a,bloques); //pasar bloques a ZZ
C= expo_modular(a,clave_publica_otro,N_otro);
bloque_cifrado = to_string(C);
string ceros(to_int(digitos_len+1)-bloque_cifrado.size(), '0'); //constructor
resultado += ceros.append(bloque_cifrado);
}
return resultado;
}
string RSA::descifrar(string mensaje_c)
{
ZZ digitos_len=to_ZZ(to_string(this->N).size());
ZZ digitos_letra= to_ZZ(to_string(to_ZZ(alfabeto[alfabeto.size()-1])).size());
ZZ bloque, r, res;
string result, results, descifra;
for(int i=0; i<mensaje_c.size(); i+= to_int(digitos_len))
{
pasar_de(bloque,mensaje_c.substr(i, to_int(digitos_len)));
r=trc(this->p,this->q,this->clave_privada,bloque);
result = to_string(r);
string ceros(to_int(digitos_len-1)-result.size(), '0');
results += ceros.append(result);
}
for(int i=0; i<results.size(); i+= to_int(digitos_letra))
{
pasar_de(res,results.substr(i, to_int(digitos_letra)) );
descifra+= alfabeto[to_int(res)];
}
return descifra;
}
void RSA::set_p(ZZ p)
{
this->p=p;
}
void RSA::set_q(ZZ q)
{
this->q=q;
}
void RSA::set_d(ZZ d)
{
this->clave_privada=d;
}
void RSA::set_N(ZZ n)
{
this->N=n;
}
|
02dcc1ef2c3839fd53d9b8fc51f96b318eecb588 | ea847b0ea9485077d5f9a8ab737001d6234a93bc | /PushOn/trunk/TreadmillUI/speedsliderwidget.cpp | 69ac44c6690d6960f6a9d7188446f37126645b28 | [] | no_license | mmcev106/maxmobility | d79386ad2b6aca9e34efaa182fa9afa76d0461f2 | 32220b22aadb40b6e212b4cdd53f54d5d9ab70c0 | refs/heads/master | 2021-01-20T09:41:30.796478 | 2012-02-29T00:27:39 | 2012-02-29T00:27:39 | 32,224,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | cpp | speedsliderwidget.cpp | #include "speedsliderwidget.h"
#include "utils.h"
SpeedSliderWidget::SpeedSliderWidget(QWidget *parent) :
SliderWidget(parent, 1, (Utils::getMAX_SPEED()))
{
}
|
9f5a8ba4fde7f07119bb7db1e3c636626f0526f1 | f1a31d010f5b8f159a175e25d515b86c7e2188af | /MagicGolens/MagicGolens/Atirador.h | d77cd7343d31442b58219dba7a328e3e5823b0d2 | [] | no_license | henriqueramalho1/MagicGolens | 6ef43eb3ce4eea6d7aac8ea6cd69ea7281f5ed97 | c7e79e73aa5a2f7d907b9d5e28dfaf4e17a219a2 | refs/heads/main | 2023-05-19T13:13:39.788691 | 2021-06-11T02:11:41 | 2021-06-11T02:11:41 | 375,801,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | h | Atirador.h | #pragma once
#include "stdafx.h"
#include "ListaEntidades.h"
#include "GerenciadorColisoes.h"
using namespace IdsCol;
class Atirador
{
protected:
float limite;
float cooldown;
bool podeAtirar;
GerenciadorColisoes* GColisoes;
ListaEntidades* LEntidades;
public:
//Construtora e Destrutora
Atirador(float t = 1);
~Atirador();
//Funcoes
void setListaEntidades(ListaEntidades* lista);
void setGerenciadorColisoes(GerenciadorColisoes* Gc);
void possoAtirar(float t);
void setLimite(float lim);
void setCooldown(float cool);
void setPodeAtir(bool pode);
};
|
b0b75a53e9007a795b5858148509244c2b7fb2f6 | fff771a3bcd6aa3a45de7cd248a80091bb22e9d8 | /Source/B2D_pch.cpp | e5b2d80a463a60b70bbdd3ea8de90ff538938136 | [] | no_license | Blodjer/B2D | ba9e495d8e662f4d882c5b903a3b8aa422e322bf | f091d1ec72b14bdfb110e2071a27a723dd1c5d4c | refs/heads/master | 2023-08-02T09:16:12.695209 | 2021-04-14T15:38:10 | 2021-04-14T15:38:10 | 115,878,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | cpp | B2D_pch.cpp | #include "B2D_pch.h"
|
7d461cdc30a7da2a16950647db2f54204bfbe5ea | 1747c8202e8e915fba72c05656df819ffb342682 | /Servo/Behaviours/T-1/B-5/B-5.hpp | cda8c86f5bb3b4f520dc7ad8241ccde1cce6b4a1 | [] | no_license | prisme-studio/SERVO | 7fd7de4ec0892237198c276718bdb5eeb34ffda4 | b231991542931cf685f0060743ef641fa81578dc | refs/heads/master | 2021-01-09T04:35:00.939465 | 2020-03-16T17:18:43 | 2020-03-16T17:18:43 | 242,246,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | hpp | B-5.hpp | //
// B-5.hpp
// Talkers
//
// Created by Valentin Dufois on 2020-02-24.
//
#ifndef B_5_hpp
#define B_5_hpp
#ifdef B5
#undef B5
#endif
#include "../../Behaviour.hpp"
class B5: public Behaviour {
public:
B5(): Behaviour(5, // ID
1, // Tree ID
1, // Is tree start ?
0, // Force start ?
{ // Expected inputs
},
{ // Expected outputs
4,
}) {}
virtual bool execute(Machine * machine) override {
/*
Action:
*/
return true;
}
};
#endif /* B_5_hpp */
|
edd2d698a00f1e956246148fece6c30f1f562b89 | ba119fb2c0aa261f99bc4509d7dd3244fa3d1e86 | /unit_test/misc_02.cpp | affc50c6c14bf6eaed1409c1039fea5a6a19dbe8 | [] | no_license | ysw1912/Cpp-Practice-Test | 91bcb2bc743c6bd714dae0aead26116a0b8be7aa | 5719701e48f1cadc91b4d143d542c75715d4b09e | refs/heads/master | 2021-12-12T17:57:17.834103 | 2021-12-11T16:17:20 | 2021-12-11T16:17:20 | 201,766,409 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,520 | cpp | misc_02.cpp | // 函数链式调用
#include <iostream>
#include <type_traits>
template<typename OuterFn, typename InnerFn>
class Composed
{
public:
explicit Composed(OuterFn outer, InnerFn inner):
outer_(outer), inner_(inner) {}
public:
//
// -> decltype(std::declval<OuterFn>()((std::declval<InnerFn>()(std::declval<T>()))))
// -> decltype(std::declval<OuterFn>()(std::result_of_t<InnerFn(T)>()))
template<typename T>
auto operator()(T arg) -> std::result_of_t<OuterFn(std::result_of_t<InnerFn(T)>)>
{
return outer_(inner_(arg));
}
private:
InnerFn inner_;
OuterFn outer_;
};
template <typename Func1, typename Func2>
Composed<Func1, Func2> Compose(Func1 f1, Func2 f2) {
return Composed<Func1, Func2>(f1, f2);
}
template <typename Func1, typename Func2, typename Func3, typename... Funcs>
auto Compose(Func1 f1, Func2 f2, Func3 f3, Funcs... fs)
-> decltype(Compose(Compose(f1, f2), f3, fs...))
{
return Compose(Compose(f1, f2), f3, fs...);
}
int main() {
auto f1 = [](int x){ return x + 1; };
auto f2 = [](int x){ return x + 2; };
auto f3 = [](int x){ return x + 3; };
auto f4 = [](int x){ return x + 4; };
auto f5 = [](int x){ return x + 5; };
auto ret = Compose(f1, f2, f3)(0);
std::cout << ret << std::endl;
ret = Compose(f1, f2, f3, f4)(0);
std::cout << ret << std::endl;
ret = Compose(f1, f2, f3, f4, f5)(0);
std::cout << ret << std::endl;
ret = Compose([](int x){ return x * 2; }, [](int x){ return x * 3; })(3);
std::cout << ret << std::endl;
return 0;
}
|
0f4c09162b8e1260b376d28194b8f20949e6e6cd | 6a0618397e6c2b246f6488c6b7f623f59073eeac | /2018/cpp/day15/Actor.h | c89c0fd2cf9590cac896fa94789c5a0037e931dc | [] | no_license | RobJenks/advent-of-code | 439be5857f389915337dc2c8a41f51bfdca08ccb | f2e6f1a6bd5a1865b633f7bd80e24bd47413838b | refs/heads/master | 2022-11-03T23:33:25.809251 | 2022-10-17T22:55:38 | 2022-10-17T22:55:38 | 161,391,858 | 0 | 0 | null | 2022-10-17T22:55:39 | 2018-12-11T20:48:02 | C++ | UTF-8 | C++ | false | false | 1,413 | h | Actor.h | #pragma once
#include <string>
class Actor
{
public:
enum class Class
{
Elf = 0,
Goblin = 1
};
Actor(Class actor_class);
inline int GetID(void) const { return m_id; }
inline void SetID(int id) { m_id = id; }
inline Class GetClass(void) const { return m_class; }
inline size_t GetLocation(void) const { return m_location; }
inline void SetLocation(size_t location) { m_location = location; }
inline int GetHP(void) const { return m_hp; }
inline bool IsAlive(void) const { return (m_hp > 0); }
inline void SetHP(int hp) { m_hp = hp; }
inline int GetAttackStrength(void) const { return m_attack; }
inline void SetAttackStrength(int attack) { m_attack = attack; }
inline void TakeDamage(int damage) { SetHP(GetHP() - damage); }
inline bool operator<(const Actor & other) const { return (m_location < other.m_location); }
static std::string ClassString(Actor::Class actor_class);
private:
inline static const int INITIAL_HP = 200;
inline static const int DEFAULT_ATTACK = 3;
int m_id;
Class m_class;
size_t m_location;
int m_hp;
int m_attack;
};
class Elf : public Actor
{
public:
Elf(void) : Actor(Actor::Class::Elf) { }
};
class Goblin : public Actor
{
public:
Goblin(void) : Actor(Actor::Class::Goblin) { }
}; |
6a5e3aa77a6bd75875740eb6234fe24de46cfe3a | b1ea23865a1a188a783af77ccea15a8f7f8456ca | /src/flapGame/flapGame/LoadPNG.h | 7fb1aa151c261ba5fc0f45312eae5c3f6bfa1df2 | [
"MIT",
"BSD-3-Clause",
"CC0-1.0",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | agile8118/FlapHero | 30b4b978bdcd955e07c29eada2630a00c84bfaba | 12c8c97e9ff0470d79cfae7111c3fd0329af9eb3 | refs/heads/main | 2023-02-11T17:30:49.441405 | 2021-01-08T17:37:06 | 2021-01-08T17:37:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | LoadPNG.h | #pragma once
#include <flapGame/Core.h>
namespace flap {
image::OwnImage loadPNG(ConstBufferView src, bool premultiply = true);
} // namespace flap
|
885d1aa443887431d2cbd690002e305bc3102c20 | c0cec0d2e7dc7f0a08cc5a3bb79f6ec6dc6f8e31 | /tests/test_c64.cpp | d1ba1de540302bb682702c00f7690f233536b7ef | [
"BSD-2-Clause"
] | permissive | jepebe/c64 | 8111bac0c679a8251d655de21a1e33e36062b574 | 89d884b03f4e05019143f1be4b46fd9b7e890ad2 | refs/heads/master | 2023-01-08T11:43:59.230285 | 2020-11-18T15:15:44 | 2020-11-18T15:15:44 | 313,972,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,982 | cpp | test_c64.cpp | #include "tools.hpp"
#include "catch2.hpp"
#include "common.hpp"
#define private public
#include "c64/c64.hpp"
static const char petscii[] = {
'?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
'p','q','r','s','t','u','v','w','x','y','z','?','?','?','?','?',
' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',
'0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?',
'@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U', 'V','W','X','Y','Z','[','?',']',' ',' ',
};
static std::vector<uint8_t> read_rom(std::string filepath) {
std::ifstream ifs(filepath, std::ios::binary | std::ios::ate);
if (!ifs)
throw std::runtime_error("Unable to open: " + filepath);
auto end = ifs.tellg();
ifs.seekg(0, std::ios::beg);
auto size = std::size_t(end - ifs.tellg());
if (size == 0) // avoid undefined behavior
throw std::runtime_error(filepath + " is empty!");
std::vector<uint8_t> data(size);
ifs.read((char *) data.data(), size);
return data;
}
TEST_CASE("C64") {
auto c64 = C64();
SECTION("Test BASIC ROM") {
auto basic = read_rom(std::string("roms/basic.bin"));
c64.write(0x0001, 0b011);
REQUIRE(basic.size() == 0x2000);
for (uint16_t i = 0; i < basic.size(); i++) {
REQUIRE(basic[i] == c64.read(0xA000 + i, true));
}
}
SECTION("Test CHAR ROM") {
auto char_rom = read_rom(std::string("roms/char.bin"));
c64.write(0x0001, 0b011);
REQUIRE(char_rom.size() == 0x1000);
for (uint16_t i = 0; i < char_rom.size(); i++) {
REQUIRE(char_rom[i] == c64.read(0xD000 + i, true));
}
}
SECTION("Test KERNAL ROM") {
auto kernal = read_rom(std::string("roms/kernal.bin"));
c64.write(0x0001, 0b010);
REQUIRE(kernal.size() == 0x2000);
for (uint16_t i = 0; i < kernal.size(); i++) {
REQUIRE(kernal[i] == c64.read(0xE000 + i, true));
}
}
SECTION("Run C64") {
c64.reset();
int count = 1;
while (true) {
while(!c64.cpu.complete()) {
c64.cpu.clock(c64);
}
// std::string status = nestools::full_cpu_status_as_string(c64.cpu, c64);
// printf("%d -> %s\n", count, status.c_str());
c64.cpu.clock(c64);
if(c64.read(0x04CD, true) == 0x2E) {
printf("Screen completed after %d instructions.\n", count);
break;
}
count++;
}
for(int y = 0; y < 25; y++) {
printf("$%04X |", 0x0400 + (y * 40));
for(int x = 0; x < 40; x++) {
auto value = c64.read(0x0400 + (y * 40) + x, true);
// printf("%02X", value);
printf("%c", petscii[value]);
}
printf("|\n");
}
}
} |
1180af520dad6eb23cca4fb8f2bed6d7e460df19 | 6f52656957840353a3e699326e6565bd894456a8 | /code/windows/HelloOpenCV/OpenCVBaseType.h | ac5441c7b31e55a42d396c40c816689497acfced | [] | no_license | BeyondVincent/OpenCV | 7e5f20f657cca3c5dc2a676cb9c23bd5d2d4afb6 | 4817c12fbd08883fc9e13196895a8153b1411b44 | refs/heads/master | 2021-01-24T06:09:14.640700 | 2013-06-02T13:54:37 | 2013-06-02T13:54:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | h | OpenCVBaseType.h | #pragma once
class OpenCVBaseType
{
public:
OpenCVBaseType(void);
~OpenCVBaseType(void);
void PointType(void);
void DrawPolygon(void);
};
|
5e513cceee78da36ef1a3cfda7bd9a724c395b4b | 2cd0a84aefb8a7141d1c8da99845a8ada0cc009c | /tensorflow/core/distributed_runtime/simple_graph_execution_state.cc | 62d1f5903cd3319e0023fc3eec904b4b47b53cf3 | [
"Apache-2.0"
] | permissive | hholst80/tensorflow-old | d466cee96eac717524ab8e4ee85275ce28bb5d68 | 79df325975402e03df89747947ff5b7f18407c52 | refs/heads/master | 2022-12-20T22:07:40.427519 | 2016-05-13T09:57:24 | 2016-05-13T09:57:24 | 58,914,336 | 1 | 1 | Apache-2.0 | 2022-12-09T21:52:14 | 2016-05-16T08:00:04 | C++ | UTF-8 | C++ | false | false | 10,022 | cc | simple_graph_execution_state.cc | /* Copyright 2016 Google Inc. 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 "tensorflow/core/distributed_runtime/simple_graph_execution_state.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/simple_placer.h"
#include "tensorflow/core/distributed_runtime/process_util.h"
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/graph/costmodel.h"
#include "tensorflow/core/graph/dot.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/subgraph.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/worker.pb.h"
#include "tensorflow/core/util/util.h"
namespace tensorflow {
SimpleGraphExecutionState::SimpleGraphExecutionState(
const OpRegistryInterface* ops,
const SimpleGraphExecutionStateOptions& options)
: ops_(ops),
device_set_(options.device_set),
session_options_(options.session_options),
base_(nullptr),
placed_(nullptr) {
// TODO(mrry): Publish placement visualizations or handle the log
// placement option.
}
SimpleGraphExecutionState::~SimpleGraphExecutionState() {
mutex_lock l(mu_);
delete base_;
delete placed_;
}
Status SimpleGraphExecutionState::Create(GraphDef* graph_def) {
if (original_graph_def_.node_size() > 0) {
return errors::InvalidArgument(
"Cannot call Create on SimpleGraphExecutionState twice");
}
original_graph_def_.Swap(graph_def);
VLOG(2) << "Incoming def: " << original_graph_def_.DebugString();
return AddDefaultAttrsToGraphDef(&original_graph_def_, *ops_, 0);
}
Status SimpleGraphExecutionState::Extend(
const GraphDef& extension_def, SimpleGraphExecutionState** out) const {
std::unordered_set<string> new_names;
// 1. Build an index of the new node names.
for (const NodeDef& node : extension_def.node()) {
new_names.insert(node.name());
}
// 2. Add the non-duplicates from the old graph to the new graph.
// Return an error if the same node name appears in both the
// old graph and the extension.
GraphDef gdef;
for (const NodeDef& node : original_graph_def_.node()) {
if (new_names.count(node.name()) == 0) {
*gdef.add_node() = node;
} else {
return errors::InvalidArgument(tensorflow::strings::Printf(
"GraphDef argument to Extend includes node '%s', which was created "
"by a previous call to Create or Extend in this session.",
node.name().c_str()));
}
}
int old_node_size = gdef.node_size();
gdef.mutable_node()->MergeFrom(extension_def.node());
TF_RETURN_IF_ERROR(AddDefaultAttrsToGraphDef(&gdef, *ops_, old_node_size));
// 3. Add the extension.
SimpleGraphExecutionStateOptions combined_options;
combined_options.device_set = device_set_;
SimpleGraphExecutionState* new_execution_state =
new SimpleGraphExecutionState(ops_, combined_options);
Status new_execution_state_status = new_execution_state->Create(&gdef);
if (!new_execution_state_status.ok()) {
delete new_execution_state;
return new_execution_state_status;
}
*out = new_execution_state;
// Ensure that any state created in the precursor is accessible in the
// new graph.
{
mutex_lock l(mu_);
for (const auto& placement : stateful_placements_) {
(*out)->stateful_placements_.insert(placement);
}
}
// TODO(mrry): This is likely to be used for non-throughput-sensitive
// interactive workloads, but in future we may want to transfer other
// parts of the placement and/or cost model.
return Status::OK();
}
Status SimpleGraphExecutionState::InitBaseGraph() {
std::unique_ptr<Graph> new_base(new Graph(ops_));
GraphConstructorOptions opts;
TF_RETURN_IF_ERROR(
ConvertGraphDefToGraph(opts, original_graph_def_, new_base.get()));
for (const Node* n : new_base->nodes()) {
VLOG(2) << "Mapping " << n->name() << " to " << n->cost_id();
node_name_to_cost_id_map_[n->name()] = n->cost_id();
}
Status status = PreliminaryPlace(*new_base);
if (!status.ok()) {
node_name_to_cost_id_map_.clear();
return status;
}
base_ = new_base.release();
return Status::OK();
}
Status SimpleGraphExecutionState::GlobalNodeDefByName(const string& name,
NodeDef* out) {
NodeNameToCostIdMap::const_iterator iter =
node_name_to_cost_id_map_.find(name);
if (iter != node_name_to_cost_id_map_.end()) {
mutex_lock l(mu_); // could use reader lock
const Node* node = placed_->FindNodeId(iter->second);
if (node) {
*out = node->def();
return Status::OK();
}
}
return errors::NotFound("Node name: ", name);
}
Status SimpleGraphExecutionState::PreliminaryPlace(const Graph& base) {
VLOG(1) << "PreliminaryPlace";
Graph* ng = new Graph(ops_);
CopyGraph(base, ng);
Status status = DoPlace(ng);
if (!status.ok()) {
delete ng;
} else {
delete placed_;
placed_ = ng;
FreezeStatefulNodes(true /*is_prelim*/);
}
return status;
}
void SimpleGraphExecutionState::FreezeStatefulNodes(bool is_prelim) {
if (is_prelim) {
// During the preliminary placement every stateful Node got placed
// somewhere, and we need to remember where, so it doesn't move.
for (Node* n : placed_->nodes()) {
if (n->op_def().is_stateful()) {
stateful_placements_[n->name()] = n->assigned_device_name();
}
}
} else {
// During later placements it's possible for new stateful nodes to
// appear. They are noticed while we're pinning the pre-existing
// stateful nodes to their prior positions, and after they've been
// placed this function is entered to record their placements.
for (Node* n : missing_stateful_placements_) {
CHECK(n->op_def().is_stateful());
stateful_placements_[n->name()] = n->assigned_device_name();
}
missing_stateful_placements_.clear();
}
}
void SimpleGraphExecutionState::PlaceStatefulNodes(Graph* graph) {
for (Node* n : graph->nodes()) {
if (n->op_def().is_stateful()) {
PlaceMap::const_iterator iter = stateful_placements_.find(n->name());
if (iter == stateful_placements_.end()) {
// NOTE(tucker): I don't understand why this can occur. So far,
// I've only seen it in eval instances, started from a checkpoint.
missing_stateful_placements_.push_back(n);
} else {
n->set_assigned_device_name(iter->second);
}
}
}
}
Status SimpleGraphExecutionState::DoPlace(Graph* graph) {
Status status;
// TODO(mrry): Port other placement algorithms from whitepaper.
return SimplePlacement(graph);
}
Status SimpleGraphExecutionState::BuildGraph(const BuildGraphOptions& options,
ClientGraph** out) {
VLOG(1) << "BuildGraph";
mutex_lock l(mu_);
// Lazily initialize the base graph.
if (base_ == nullptr) {
TF_RETURN_IF_ERROR(InitBaseGraph());
}
if (!base_ || !placed_) {
return ::tensorflow::errors::Internal(
"There was a problem building the graph.");
}
std::unique_ptr<ClientGraph> cgraph(new ClientGraph(ops_));
CopyGraph(*placed_, &cgraph->graph);
// Extract the subset of the graph that needs to be run, adding feed/fetch
// ops as needed.
TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(
&cgraph->graph, options.feed_endpoints, options.fetch_endpoints,
options.target_nodes, device_set_->client_device()->attributes()));
// Copy the extracted graph in order to make its node ids dense,
// since the local CostModel used to record its stats is sized by
// the largest node id.
{
std::unique_ptr<ClientGraph> dense_copy(new ClientGraph(ops_));
CopyGraph(cgraph->graph, &dense_copy->graph);
cgraph = std::move(dense_copy);
}
// TODO(vrv): We should check invariants of the graph here.
*out = cgraph.release();
return Status::OK();
}
Status SimpleGraphExecutionState::DeviceIsCompatible(
Node* n, const Device* device) const {
if (!n->def().device().empty()) {
DeviceNameUtils::ParsedName pname;
if (!DeviceNameUtils::ParseFullName(n->def().device(), &pname)) {
return AttachDef(
errors::InvalidArgument("Malformed device specification '",
n->def().device(), "'"),
n->def());
}
std::vector<Device*> devices;
device_set_->FindMatchingDevices(pname, &devices);
for (auto d : devices) {
if (d == device) {
return Status::OK();
}
}
return AttachDef(
errors::InvalidArgument(
"Specified device '", n->def().device(),
"' not compatible with device of ref connection: ", device->name()),
n->def());
}
return Status::OK();
}
Status SimpleGraphExecutionState::SimplePlacement(Graph* graph) {
SimplePlacer placer(graph, device_set_, &node_name_to_cost_id_map_,
session_options_);
// TODO(mrry): Consider making the SimplePlacer cancelable.
return placer.Run();
}
} // namespace tensorflow
|
9973af7d6b787e4eb1cb7c1ffeca86d3af822018 | 838a9b592c131af51ea0a186bf4ff782a74dfeeb | /src/plato/Strain.hpp | 60a31526e30810449c123e5e2d41c4e1b879aecd | [
"BSD-2-Clause"
] | permissive | tjfulle/lgrtk | 9bb6c0b1d0ba3cb8b941da32143e6e389231d6de | d29fb5595310b1d614279513ff57ee2a7e000513 | refs/heads/master | 2020-05-29T09:54:51.498350 | 2019-11-12T19:03:02 | 2019-11-12T19:07:17 | 153,124,163 | 0 | 0 | null | 2018-10-15T14:05:53 | 2018-10-15T14:05:52 | null | UTF-8 | C++ | false | false | 3,008 | hpp | Strain.hpp | #ifndef STRAIN_HPP
#define STRAIN_HPP
#include "plato/SimplexMechanics.hpp"
#include "plato/PlatoStaticsTypes.hpp"
#include <Omega_h_vector.hpp>
namespace Plato
{
/******************************************************************************/
/*! Strain functor.
given a gradient matrix and displacement array, compute the strain.
strain tensor in Voigt notation = {e_xx, e_yy, e_zz, e_yz, e_xz, e_xy}
*/
/******************************************************************************/
template<Plato::OrdinalType SpaceDim>
class Strain : public Plato::SimplexMechanics<SpaceDim>
{
private:
using Plato::SimplexMechanics<SpaceDim>::mNumVoigtTerms;
using Plato::SimplexMechanics<SpaceDim>::mNumNodesPerCell;
using Plato::SimplexMechanics<SpaceDim>::mNumDofsPerCell;
public:
template<typename ScalarType>
DEVICE_TYPE inline void
operator()( Plato::OrdinalType cellOrdinal,
Kokkos::View<ScalarType**, Kokkos::LayoutRight, Plato::MemSpace> const& strain,
Kokkos::View<ScalarType**, Kokkos::LayoutRight, Plato::MemSpace> const& u,
Omega_h::Vector<mNumVoigtTerms> const* gradientMatrix) const {
// compute strain
//
for( Plato::OrdinalType iVoigt=0; iVoigt<mNumVoigtTerms; iVoigt++){
strain(cellOrdinal,iVoigt) = 0.0;
for( Plato::OrdinalType iDof=0; iDof<mNumDofsPerCell; iDof++){
strain(cellOrdinal,iVoigt) += u(cellOrdinal,iDof)*gradientMatrix[iDof][iVoigt];
}
}
}
template<typename StrainScalarType, typename DispScalarType, typename GradientScalarType>
DEVICE_TYPE inline void
operator()( Plato::OrdinalType cellOrdinal,
Plato::ScalarMultiVectorT< StrainScalarType > const& strain,
Plato::ScalarMultiVectorT< DispScalarType > const& u,
Plato::ScalarArray3DT< GradientScalarType > const& gradient) const {
Plato::OrdinalType voigtTerm=0;
for(Plato::OrdinalType iDof=0; iDof<SpaceDim; iDof++){
strain(cellOrdinal,voigtTerm)=0.0;
for( Plato::OrdinalType iNode=0; iNode<mNumNodesPerCell; iNode++){
Plato::OrdinalType localOrdinal = iNode*SpaceDim+iDof;
strain(cellOrdinal,voigtTerm) += u(cellOrdinal,localOrdinal)*gradient(cellOrdinal,iNode,iDof);
}
voigtTerm++;
}
for (Plato::OrdinalType jDof=SpaceDim-1; jDof>=1; jDof--){
for (Plato::OrdinalType iDof=jDof-1; iDof>=0; iDof--){
for( Plato::OrdinalType iNode=0; iNode<mNumNodesPerCell; iNode++){
Plato::OrdinalType iLocalOrdinal = iNode*SpaceDim+iDof;
Plato::OrdinalType jLocalOrdinal = iNode*SpaceDim+jDof;
strain(cellOrdinal,voigtTerm) +=(u(cellOrdinal,jLocalOrdinal)*gradient(cellOrdinal,iNode,iDof)
+u(cellOrdinal,iLocalOrdinal)*gradient(cellOrdinal,iNode,jDof));
}
voigtTerm++;
}
}
}
};
} // namespace Plato
#endif
|
9a7d827a78d5d33dfe961f523181b4c6ef8b958e | 1a2836a214973b501989d184359dcf4dba4cfc00 | /spells/ModerateHeal.h | cfedbc8c6c318e027281458be5ca14bff186f6ca | [] | no_license | VasilenkoYevhenij/ArmyDevClub | 222d7747964827a9f19ceb3299cee11c83af060c | e7251e36a92790d6191543fd6072e75e095a4074 | refs/heads/master | 2023-04-09T18:09:38.044748 | 2021-04-06T13:16:42 | 2021-04-06T13:16:42 | 355,194,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | h | ModerateHeal.h | #ifndef MODERATEHEAL_H
#define MODERATEHEAL_H
#include "Spell.h"
class ModerateHeal : public Spell {
public:
ModerateHeal(int actionPoints = 40, int cost = 40, const std::string& spellName = "ModerateHeal");
virtual ~ModerateHeal();
virtual void action(Unit* target);
};
#endif // MODERATEHEAL_H
|
4f680e7b4b56a9f3a62caa80de6a8dcdf2add358 | be3bf249f3c1dfab3ed68bae7aa23b9e435008a9 | /League of Gems/lib/ADT/List.h | 215636c3fb54c0df41d8cc81da4479694cdafb51 | [] | no_license | Kraison799/League-of-Gems | a1782eff0927aac485d7d9d3c77bbcc18a5cb08f | ae9178694bfbb452c2b8a9c9dd4a89ee520e29c0 | refs/heads/master | 2020-03-30T07:11:59.336383 | 2018-11-14T20:50:07 | 2018-11-14T20:50:07 | 150,921,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,561 | h | List.h | //
// Created by ferathor on 04/10/18.
//
#include <cstdio>
#include <string.h>
#include <iostream>
using std::cout;
#ifndef LEAGUEOFGEMS_LIST_H
#define LEAGUEOFGEMS_LIST_H
#define NULL 0;
//Nodo__________________________________________________________________________________________________________________
template<class T>
class Node
{
public:
T data;
Node *next;
Node()
{
//data = NULL;
next = nullptr;
}
Node(T data);
T getData(){return data;}
void setData(T data){this->data = data;}
Node *getNext(){return next;}
void setNext(Node *node){next = node;}
};
template<class T>
Node<T>::Node(T data)
{
this->data = data;
next = nullptr;
}
//Lista_________________________________________________________________________________________________________________
template<class T>
class List
{
public:
List(){p = nullptr; u = nullptr; size = 0;}
Node<T>* getFirst(){return p;}
Node<T>* getLast(){return u;}
int getSize(){return size;}
bool isEmpty(){return p== nullptr;}
void add(T data)
{
Node<T>* nuevo = new Node<T>;
nuevo->setData(data);
if(isEmpty())
{
p = nuevo;
p->setNext(nullptr);
u = nuevo;
}
else
{
u->next = nuevo;
nuevo->next = nullptr;
u = nuevo;
}
size++;
}
void add(T data, int index)
{
Node<T>* nuevo = new Node<T>;
nuevo->data = data;
if(isEmpty())
{
p = nuevo;
p->next = nullptr;
u = nuevo;
}
else if(index >= size)
{
u->next = nuevo;
nuevo->next = nullptr;
u = nuevo;
}
else if(index <= 0)
{
nuevo->next = p;
p = nuevo;
}
else
{
Node<T>* piv = p;
while(piv!= nullptr & index > 1)
{
piv = piv->next;
index--;
}
nuevo->next = piv->next;
piv->next = nuevo;
}
size++;
}
void edit(T data, int index)
{
if(!isEmpty())
{
if(index >= size-1)
{
u->data = data;
}
else if(index <= 0)
{
p->data = data;
}
else
{
Node<T>* piv = p;
while(index > 0)
{
piv = piv->next;
index--;
}
piv->data = data;
}
}
}
bool exist(T n)
{
if(!isEmpty())
{
Node<T>* piv = new Node<T>;
piv = p;
while(piv != nullptr)
{
if(piv->data == n)
{
return true;
}
piv = piv->next;
}
free(piv);
return false;
}
}
T get(int index)
{
if(!isEmpty())
{
Node<T>* piv = p;
while(piv != nullptr & index != 0)
{
piv = piv->next;
index--;
}
return piv->data;
}
}
T* getptr(int index)
{
if(!isEmpty())
{
Node<T>* piv = p;
while(piv != nullptr & index != 0)
{
piv = piv->next;
index--;
}
return piv->data;
}
}
void delFirst()
{
if(!isEmpty())
{
Node<T>* piv = new Node<T>;
piv = p;
p = p->next;
free(piv);
size--;
}
}
void delLast()
{
if(!isEmpty())
{
Node<T>* piv = new Node<T>;
piv = p;
while(piv->next != u)
{
piv = piv->next;
}
u = piv;
free(piv->next);
piv->next = nullptr;
size--;
}
}
void del(int index)
{
if(!isEmpty())
{
if(index <= 0)
{
delFirst();
}
else if(index >= size-1)
{
delLast();
}
else
{
index--;
Node<T>* pre = p;
while(pre != nullptr & index != 0)
{
pre = pre->next;
index--;
}
if(pre != nullptr)
{
free(pre->next);
size--;
pre->next = pre->next->next;
}
}
}
}
/*void del(T _data)
{
if(!isEmpty())
{
int index = 0;
Node<T>* piv = p;
while(piv != nullptr)
{
if(piv->data == _data)
{
break;
}
index++;
piv = piv->next;
}
if(index == size)//No lo encontro
{
return;
}
if(index <= 0)
{
delFirst();
}
else if(index >= size-1)
{
delLast();
}
else
{
index--;
Node<T>* pre = p;
while(pre != nullptr & index != 0)
{
pre = pre->next;
index--;
}
if(pre != nullptr)
{
free(pre->next);
size--;
pre->next = pre->next->next;
}
}
}
}*/
void delAll()
{
int n = size;
for(int i=0; i < n; i++)
{
delFirst();
}
}
void show()
{
if(isEmpty())
{
}
else
{
cout << "[->]";
Node<T>* piv = p;
while(piv != nullptr)
{
std::cout << piv->data << "-> ";
piv = piv->next;
}
free(piv);
}
}
void showln()
{
if(isEmpty())
{
cout << "[->]";
}
else
{
Node<T>* piv = p;
while(piv != nullptr)
{
cout << piv->data << "-> ";
piv = piv->next;
}
free(piv);
}
std::cout << "\n";
}
void show2ln()
{
if(isEmpty())
{
cout << "[->]";
}
else
{
Node<T>* piv = p;
while(piv != nullptr)
{
cout << "[" << piv->data << "] ";
piv = piv->next;
}
free(piv);
}
std::cout << "\n";
}
std::string getString()
{
std::string str = "";
if(isEmpty())
{
str.append("[->]");
}
else
{
Node<T>* piv = p;
while(piv != nullptr)
{
str.append("hmm...-> ");
piv = piv->next;
}
free(piv);
}
return str;
}
Node<T>* p;
Node<T>* u;
int size;
};
#endif //LEAGUEOFGEMS_LIST_H
|
eef032e7ddace29ba904a4d3b50b775f8da609ed | c9603c7d7f83d8704b5cfabad7a28ec429af6fa0 | /test/unit_test/test_fusion_adapt_struct.cpp | 87041f933d1caa3eeb9ae01700766c5b77f01c76 | [
"BSL-1.0"
] | permissive | dan-42/spoon | 6bc5bc7bb89df4df28a19abe37828cc1f9aa93e9 | be0a8770b371fcb33fb63e6e934972cb08ace2a6 | refs/heads/master | 2021-01-22T08:02:49.138827 | 2017-09-13T19:30:23 | 2017-09-13T19:30:23 | 92,599,624 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,233 | cpp | test_fusion_adapt_struct.cpp | /**
* ninja-wooki, is a BACnet stack C++ library
*
* Copyright (C) 2015 Daniel Friedrich
*
* This file is part of ninja-wooki.
*
* ninja-wooki is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* ninja-wooki is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU General Public License for more details. You should have received a copy of the GNU
* General Public License along with Mupen64PlusAE. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Daniel Friedrich
*/
#define BOOST_TEST_MODULE test spoon binary
#include <boost/test/included/unit_test.hpp>
#include <iostream>
#include <spoon.hpp>
/*
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_binary.hpp>
#include <boost/variant.hpp>
*/
using varinat_t = mapbox::util::variant<bool, uint32_t, double>;
namespace spoon { namespace deserializer {
template <typename BaseType>
struct assign<BaseType, varinat_t> {
static auto to(BaseType base, varinat_t &attr) -> bool {
attr = base;
return true;
}
};
}}
BOOST_AUTO_TEST_SUITE( test_spoon_variant )
BOOST_AUTO_TEST_CASE( test_spoon_variant_simple_1 ) {
/*
//using variant_t = boost::variant<bool, uint32_t, int16_t, double>;
using variant_t = boost::variant<int32_t, int16_t>;
variant_t var = int32_t{1337};
std::vector<uint8_t> binary_data{};
auto sink = std::back_insert_iterator<decltype(binary_data)>(binary_data);
//auto success = boost::spirit::karma::generate(sink, (boost::spirit::karma::bool_ | boost::spirit::karma::big_dword | boost::spirit::karma::big_word | boost::spirit::karma::big_bin_double), var);
auto success = boost::spirit::karma::generate(sink, (boost::spirit::karma::big_dword | boost::spirit::karma::big_word), var);
BOOST_TEST(success == true);
BOOST_TEST( binary_data.size() == size_t{4});
BOOST_TEST(binary_data[0] == 0x00);
BOOST_TEST(binary_data[1] == 0x00);
BOOST_TEST(binary_data[2] == 0x05);
BOOST_TEST(binary_data[3] == 0x39);
*/
}
BOOST_AUTO_TEST_CASE( test_spoon_variant_simple ) {
std::vector<uint8_t> binary_data{};
{
using namespace spoon::serializer;
varinat_t var = uint32_t{1337};
//decltype(auto) engine = any_( binary::big::double_, binary::big::word32_, binary::bool_);
decltype(auto) engine = any_type_(bool{}, uint32_t{}, double{});
auto success = spoon::serialize_with(engine, binary_data, var);
BOOST_TEST(success == true);
BOOST_TEST( binary_data.size() == size_t{4} );
BOOST_TEST(binary_data[0] == 0x00);
BOOST_TEST(binary_data[1] == 0x00);
BOOST_TEST(binary_data[2] == 0x05);
BOOST_TEST(binary_data[3] == 0x39);
}
{
using namespace spoon::deserializer;
varinat_t var{};
auto start = binary_data.begin();
const auto end = binary_data.end();
decltype(auto) engine = any_(binary::big::double_, binary::big::word32_, binary::bool_);
auto success = spoon::deserialize_with(engine, start, end, var);
BOOST_TEST(success == true);
BOOST_TEST((start == end), "start != end");
struct result_visitor {
void operator()(bool r) const { BOOST_TEST(false, " it is bool"); }
void operator()(uint32_t e) const { BOOST_TEST(e == uint32_t{1337}, " it is uint but value wrong"); }
void operator()(double e) const { BOOST_TEST(false, " it is double "); }
};
result_visitor visitor;
mapbox::util::apply_visitor(visitor, var);
}
}
/*
*
*
// decltype(auto) engine = any_type_(varinat_t);
decltype(auto) engine = any_type_(bool{}, uint32_t{}, double{});
//decltype(auto) engine_fail = any_(binary::bool_, binary::big::word32_, binary::big::double_);
//decltype(auto) engine_success = any_(binary::big::double_, binary::big::word32_, binary::bool_);
* /auto success = spoon::deserialize_with(engine_fail, start, end, var);
*/
BOOST_AUTO_TEST_SUITE_END()
|
79e8ba4cbee59fcadf6b3a075d431e319f84afb1 | e45d991172d96ac89f63295c8ff7d27e66c3bd6c | /VS_Tests/Testing/Tests/Test_Null.hpp | 3a783e21fa28dcb82003a4f246297267c623ee78 | [] | no_license | TimPhoeniX/CTL | b206c238e42817d1717c689345a24e5a2e13de24 | 58bf811005befba6a51fc991211a5f53a3e768b5 | refs/heads/master | 2021-01-18T21:36:20.270055 | 2016-12-07T20:40:44 | 2016-12-07T20:40:44 | 44,741,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | hpp | Test_Null.hpp | #pragma once
#include <iostream>
class nulltest
{
public:
bool isNull() const
{
return this == nullptr;
}
};
void test_null()
{
nulltest* ptr = nullptr;
bool (nulltest::*f)() const = &nulltest::isNull;
std::cout << "ptr is " << ( (ptr->*f) () ? "nullptr" : "nulltest*") << std::endl;
std::cout << "ptr is " << ( (*ptr.*f) () ? "nullptr" : "nulltest*") << std::endl;
std::cout << "ptr is " << (ptr->isNull() ? "nullptr" : "nulltest*") << std::endl;
}
|
4bfab53c98c2162dc6d9e0e058dac9fa57ebf530 | 48b86995cddd72e5caf11a171247930ae7a77804 | /gameserver/session.h | a4c4144c8713d0301ff4cee78705c5c695de67c3 | [] | no_license | kingstop/DreamHeroes | 0250988ac583bce074336a1bae07bb0f4ab55ecd | c8299c9d3a6cca7d71cf859706fdf2d4a21a8906 | refs/heads/master | 2020-12-04T01:37:44.579005 | 2017-10-10T10:14:22 | 2017-10-10T10:14:22 | 67,582,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,669 | h | session.h | #ifndef __player_session_h__
#define __player_session_h__
class DreamHero;
class Session :PUBLIC_BASE_OBJECT(Session)
{
REGISTER_POOL_INFO(Session, 100, 0)
public:
enum
{
_session_online_,
_session_offline_,
};
void prasePBDefault(google::protobuf::Message* p);
static void registerPBCall();
public:
void praseDBQueryHeroInfo(message::MsgHeroDataDB2GS* HeroDataMsg);
void parseDBQueryNeedCreateHero();
DreamHero* get_dream_hero();
public:
Session(tran_id_type t, account_type a, u16 gate);
~Session();
void close();
void setReconnet();
void setWaitReconnet();
void setDreamHero(DreamHero* p);
DreamHero* getDreamHero() { return _dream_hero; }
u16 getGateId() const {return m_gate ;}
tran_id_type getTranId() const {return m_tranid ;}
account_type getAccount() const {return m_account ;}
void sendPBMessage(google::protobuf::Message* p);
void parsePBMessage(google::protobuf::Message* p);
void parseReqShopConfig(google::protobuf::Message* p);
void parseReqGameGlobalConfig(google::protobuf::Message* p);
void parseReqEnterGame(google::protobuf::Message* p);
void parseReqExitGame(google::protobuf::Message* p);
void parseReqUnlockChapter(google::protobuf::Message* p);
void parseReqAdvertisementApplyTask(google::protobuf::Message* p);
void parseReqAdvertisementRefreshTask(google::protobuf::Message* p);
void parseReqBuyHero(google::protobuf::Message* p);
void parseReqGoldShopConfigs(google::protobuf::Message* p);
void parseReqModifyCurrentHero(google::protobuf::Message* p);
void parseReqCrearteDeal(google::protobuf::Message* p);
void parseReqVerifyDeal(google::protobuf::Message* p);
void parseReqModifyTutorial(google::protobuf::Message* p);
void parseReqRelive(google::protobuf::Message* p);
void parseReqBuySpirit(google::protobuf::Message* p);
void parseReqBuyLotion(google::protobuf::Message* p);
void parseReqDayLottery(google::protobuf::Message* p);
void parseReqApplyDeal(google::protobuf::Message* p);
void parseReqEnterDailyGame(google::protobuf::Message* p);
void parseReqUpdateDailyGameProgress(google::protobuf::Message* p);
void parseReqReceiveDailyGamePrize(google::protobuf::Message* p);
void parseReqResetDailyGameProgress(google::protobuf::Message* p);
void parseReqDailyGameRankList(google::protobuf::Message* p);
void parseReqConcernWeiXin(google::protobuf::Message* p);
void parseReqActivityAnnouncement(google::protobuf::Message* p);
void parseReqModifyNotifyGridState(google::protobuf::Message* p);
public:
void parseCmdReqMdodifyGMLevel(google::protobuf::Message* p);
void parseCmdReqEnterGame(google::protobuf::Message* p);
void parseCmdReqResetMap(google::protobuf::Message* p);
void parseCmdReqResetGame(google::protobuf::Message* p);
void parseCmdReqModifyGold(google::protobuf::Message* p);
void parseCmdReqReplaceTask(google::protobuf::Message* p);
void parseCmdReqModifyTaskCompleteCount(google::protobuf::Message* p);
void parseCmdReqRemoveSpecialCreatureListHis(google::protobuf::Message* p);
void parseCmdReqSetSpecialCreatureHis(google::protobuf::Message* p);
void parseCmdReqModifyJewel(google::protobuf::Message* p);
void parseCmdReqModifySpirit(google::protobuf::Message* p);
void parseCmdReqResetDailyLottery(google::protobuf::Message* p);
void parseCmdReqResetResetDailyGame(google::protobuf::Message* p);
void parseCmdReqClearDailyRankList(google::protobuf::Message* p);
void parseCmdReqResetConcernWeiXin(google::protobuf::Message* p);
int getState();
void set_channel(int channel);
int get_channel();
protected:
tran_id_type m_tranid;
account_type m_account;
u16 m_gate;
u8 m_state;
DreamHero* _dream_hero;
int _channel;
private:
};
#endif
|
0e84a83c59b034d626ea3f59ab5ad78d4c132b40 | 66245c384df89909b354174b812e408a7d972bfb | /include/gridtools/common/generic_metafunctions/is_there_in_sequence_if.hpp | 16ac156cf5f0a9d2e03129d5811812313ce73bd8 | [
"BSD-3-Clause"
] | permissive | cosunae/gridtools | c2cf3d1d313784cdf0adb4519ed0db3305b3551a | fd527f77542d2e81b32fbf95c9d76ed891241ebb | refs/heads/master | 2020-05-24T08:41:57.507982 | 2019-05-16T07:48:40 | 2019-05-16T07:48:40 | 187,188,189 | 0 | 1 | NOASSERTION | 2019-08-19T20:40:43 | 2019-05-17T09:30:51 | C++ | UTF-8 | C++ | false | false | 1,006 | hpp | is_there_in_sequence_if.hpp | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <boost/mpl/fold.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/transform_view.hpp>
#include <type_traits>
namespace gridtools {
/** \ingroup common
@{
\ingroup allmeta
@{
\ingroup mplutil
@{
*/
/**
* @struct is_there_in_sequence_if
* return true if the predicate returns true when applied, for at least one of the elements in the Sequence
*/
template <typename Sequence, typename Pred>
struct is_there_in_sequence_if : boost::mpl::fold<boost::mpl::transform_view<Sequence, Pred>,
std::false_type,
boost::mpl::or_<boost::mpl::_1, boost::mpl::_2>>::type {};
/** @} */
/** @} */
/** @} */
} // namespace gridtools
|
a0b45f0d767b87e564d1e2847ab0a7021ec19e1a | 412b4c2a33d8ca5554fd607e07cee620cea9b463 | /rcore/app/rparam.cpp | e3770513fce82b4b0d0c06dd4a5847172ea983f1 | [] | no_license | pfrancq/r | 65df093d7cd31f4e5c521eadd61a54cb8da58925 | bd78f3b2da3b357ca5d21e6055f809c83b488cd5 | refs/heads/main | 2023-08-17T09:01:37.815379 | 2021-10-04T06:15:01 | 2021-10-04T06:15:01 | 404,758,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,865 | cpp | rparam.cpp | /*
R Project Library
RParam.cpp
Parameter - Implementation.
Copyright 2003-2015 by Pascal Francq (pascal@francq.info).
Copyright 2003-2008 by the Université Libre de Bruxelles (ULB).
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//------------------------------------------------------------------------------
// include files for R
#include <rparam.h>
#include <rxmlstruct.h>
#include <rnodecursor.h>
using namespace R;
//------------------------------------------------------------------------------
//
// class RParam
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
RParam::RParam(const RString& n,const RString& desc)
: Name(n), Description(desc)
{
}
//------------------------------------------------------------------------------
int RParam::Compare(const RString& name) const
{
if(Name==RString::Null)
{
if(name==RString::Null)
return(0);
else
return(-1);
}
else
if(name==RString::Null)
return(1);
return(Name.Compare(name));
}
//------------------------------------------------------------------------------
int RParam::Compare(const RParam& param) const
{
if(Name==RString::Null)
{
if(param.Name==RString::Null)
return(0);
else
return(-1);
}
else
if(param.Name==RString::Null)
return(1);
return(Name.Compare(param.Name));
}
//------------------------------------------------------------------------------
void RParam::AddTag(RXMLStruct*,RXMLTag*)
{
}
//------------------------------------------------------------------------------
bool RParam::Set(RXMLTag*)
{
return(false);
}
//------------------------------------------------------------------------------
void RParam::Reset(void)
{
}
//------------------------------------------------------------------------------
RParam::~RParam(void)
{
}
//------------------------------------------------------------------------------
//
// class RParamValue
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RXMLTag* tag)
: RParam(tag->GetAttrValue("name"),tag->GetAttrValue("desc"))
{
Value=tag->GetAttrValue("value");
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,const RString& v,const RString& desc)
: RParam(n,desc), Value(v)
{
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,const char* v,const RString& desc)
: RParam(n,desc), Value(v)
{
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,long v,const RString& desc)
: RParam(n,desc)
{
SetInt(v);
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,unsigned long v,const RString& desc)
: RParam(n,desc)
{
SetUInt(v);
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,int v,const RString& desc)
: RParam(n,desc)
{
SetInt(v);
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,unsigned int v,const RString& desc)
: RParam(n,desc)
{
SetUInt(v);
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,double v,const RString& desc)
: RParam(n,desc)
{
SetDouble(v);
}
//------------------------------------------------------------------------------
RParamValue::RParamValue(const RString& n,bool v,const RString& desc)
: RParam(n,desc)
{
SetBool(v);
}
//------------------------------------------------------------------------------
int RParamValue::GetInt(void) const
{
bool b;
int v=Value.ToInt(b);
return(v);
}
//------------------------------------------------------------------------------
unsigned int RParamValue::GetUInt(void) const
{
bool b;
unsigned int v=Value.ToUInt(b);
return(v);
}
//------------------------------------------------------------------------------
long RParamValue::GetLong(void) const
{
bool b;
long v=Value.ToLong(b);
return(v);
}
//------------------------------------------------------------------------------
unsigned long RParamValue::GetULong(void) const
{
bool b;
unsigned long v=Value.ToULong(b);
return(v);
}
//------------------------------------------------------------------------------
double RParamValue::GetDouble(void) const
{
bool b;
double v=Value.ToDouble(b);
return(v);
}
//------------------------------------------------------------------------------
RString RParamValue::Get(void) const
{
return(Value);
}
//------------------------------------------------------------------------------
bool RParamValue::GetBool(void) const
{
return(Value.ToBool(false));
}
//------------------------------------------------------------------------------
bool RParamValue::Set(RXMLTag* tag)
{
if((tag->GetName()!="param")||(tag->GetAttrValue("name")!=Name))
return(false);
Value=tag->GetAttrValue("value");
return(true);
}
//------------------------------------------------------------------------------
void RParamValue::SetInt(long long int v)
{
Value=RString::Number(v);
}
//------------------------------------------------------------------------------
void RParamValue::SetUInt(unsigned long long int v)
{
Value=RString::Number(v);
}
//------------------------------------------------------------------------------
void RParamValue::SetDouble(double v)
{
Value=RString::Number(v);
}
//------------------------------------------------------------------------------
void RParamValue::Set(const RString& v)
{
Value=v;
}
//------------------------------------------------------------------------------
void RParamValue::SetBool(bool v)
{
if(v)
Value="True";
else
Value="False";
}
//------------------------------------------------------------------------------
void RParamValue::AddTag(RXMLStruct* xml,RXMLTag* parent)
{
RXMLTag* ptr;
xml->AddTag(parent,ptr=new RXMLTag("param"));
ptr->InsertAttr(xml,"name",Name);
if(!Value.IsEmpty())
ptr->InsertAttr(xml,"value",Value);
}
//------------------------------------------------------------------------------
void RParamValue::Reset(void)
{
Value=RString::Null;
}
//------------------------------------------------------------------------------
//
// class RParamList
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
RParamList::RParamList(const RXMLTag* tag)
: RParam(tag->GetAttrValue("name"),tag->GetAttrValue("desc")), Values(tag->GetNbNodes())
{
RNodeCursor<RXMLStruct,RXMLTag> Cur(tag);
for(Cur.Start();!Cur.End();Cur.Next())
{
if(Cur()->GetName()!="item")
throw RException("Not valid XML tag");
Values.InsertPtr(new RString(Cur()->GetAttrValue("value")));
}
}
//------------------------------------------------------------------------------
RParamList::RParamList(const RString& name,const RString& desc)
: RParam(name,desc), Values(20)
{
}
//------------------------------------------------------------------------------
RCursor<RString> RParamList::GetList(void) const
{
return(RCursor<RString>(Values));
}
//------------------------------------------------------------------------------
size_t RParamList::GetPos(const RString& value) const
{
bool Find;
size_t pos=Values.GetIndex(value,Find);
if(!Find)
return(SIZE_MAX);
return(pos);
}
//------------------------------------------------------------------------------
void RParamList::Insert(const RString& value)
{
Values.GetInsertPtr(value);
}
//------------------------------------------------------------------------------
bool RParamList::Set(RXMLTag* tag)
{
if((tag->GetName()!="list")||(tag->GetAttrValue("name")!=Name))
return(false);
RNodeCursor<RXMLStruct,RXMLTag> Cur(tag);
for(Cur.Start();!Cur.End();Cur.Next())
{
if(Cur()->GetName()!="item")
throw RException("Not valid XML tag");
Insert(Cur()->GetAttrValue("value"));
}
return(true);
}
//------------------------------------------------------------------------------
void RParamList::AddTag(RXMLStruct* xml,RXMLTag* parent)
{
RXMLTag* ptr;
RXMLTag* ptr2;
xml->AddTag(parent,ptr=new RXMLTag("list"));
ptr->InsertAttr(xml,"name",Name);
RCursor<RString> Cur(Values);
for(Cur.Start();!Cur.End();Cur.Next())
{
xml->AddTag(ptr,ptr2=new RXMLTag("item"));
ptr2->InsertAttr(xml,"value",*Cur());
}
}
//------------------------------------------------------------------------------
void RParamList::Reset(void)
{
Values.Clear();
}
//------------------------------------------------------------------------------
//
// class RParamStruct
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
RParamStruct::RParamStruct(const RXMLTag* tag)
: RParam(tag->GetAttrValue("name"),tag->GetAttrValue("desc")), Parameters(tag->GetNbNodes())
{
RNodeCursor<RXMLStruct,RXMLTag> Cur(tag);
for(Cur.Start();!Cur.End();Cur.Next())
{
if(Cur()->GetName()=="param")
Parameters.InsertPtr(new RParamValue(Cur()));
if(Cur()->GetName()=="list")
Parameters.InsertPtr(new RParamList(Cur()));
if(Cur()->GetName()=="struct")
Parameters.InsertPtr(new RParamStruct(Cur()));
}
}
//------------------------------------------------------------------------------
RParamStruct::RParamStruct(const RString& name,const RString& desc)
: RParam(name,desc), Parameters(20)
{
}
//------------------------------------------------------------------------------
RCursor<RParam> RParamStruct::GetStruct(void) const
{
return(RCursor<RParam>(Parameters));
}
//------------------------------------------------------------------------------
void RParamStruct::Insert(RParam* param)
{
RParam* ptr=Parameters.GetPtr(*param);
if(ptr)
Parameters.DeletePtr(*ptr);
Parameters.InsertPtr(param);
}
//------------------------------------------------------------------------------
bool RParamStruct::Set(RXMLTag* tag)
{
if((tag->GetName()!="struct")||(tag->GetAttrValue("name")!=Name))
return(false);
RNodeCursor<RXMLStruct,RXMLTag> Cur(tag);
for(Cur.Start();!Cur.End();Cur.Next())
{
if(Cur()->GetName()=="param")
Insert(new RParamValue(Cur()));
if(Cur()->GetName()=="list")
Insert(new RParamList(Cur()));
if(Cur()->GetName()=="struct")
Insert(new RParamStruct(Cur()));
}
return(true);
}
//------------------------------------------------------------------------------
void RParamStruct::AddTag(RXMLStruct* xml,RXMLTag* parent)
{
RXMLTag* ptr;
xml->AddTag(parent,ptr=new RXMLTag("struct"));
ptr->InsertAttr(xml,"name",Name);
RCursor<RParam> Cur(Parameters);
for(Cur.Start();!Cur.End();Cur.Next())
Cur()->AddTag(xml,ptr);
}
//------------------------------------------------------------------------------
void RParamStruct::Reset(void)
{
Parameters.Clear();
}
|
8241265ee45ce0df3081b16fbd82c9a4ac7a9ebd | 2a6630dce03d4e2a68505e9706c996a5e52b9622 | /Zipf/monkeys.cpp | 090531d63c99042f7354527d4e3a3bac3d784cea | [] | no_license | aantillonl/Spotify-Puzzles | b9c514f63700fcadbbadca12bf88a4742ff64ae6 | 658259f32aca103946117989fbcb5dcfd252bf35 | refs/heads/master | 2021-01-10T14:44:01.958495 | 2015-12-13T19:40:31 | 2015-12-13T19:40:31 | 47,028,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,896 | cpp | monkeys.cpp | // reading a text file
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;
int main () {
int n, m; // Declare variables. n is number of songs in album. m is number of songs to pick from the album
string line; // variable to store each line of the file through the iterations
cin >> line;
// Extract n from first line, is a substring starting from the first char
// to the point where it finds a space, and m similar, from space to end
n = stoi(line.substr(0, line.find(" ")));
m = stoi(line.substr(line.find(" ") , line.size()- line.find("")));
// Now that n and m are known we can initialize f and q vectors, which will
// store the information of frequency palyed and quality
// names is a vector that stores the names of the songs
int f[n];
double q[n];
string names[n];
// Loop through the rest of the lines in the file to read the frequency,
// names, and compute the quality which is normalized to the freq of the frist track.
for (int i=0; i<n; ++i)
{
cin >> line;
f[i] = stoi(line.substr(0, line.find(" ")));
names[i] = line.substr(line.find(" ") , line.size()- line.find(""));
q[i] = (double)f[i]/(double)f[0]*(i+1);
}
// Initialize imax, vector that will store the index of the best songs
// max is a value that will hold the max value during iterations
// The main idea is to iterate through the vectors m times, which as many songs we
// have to pick. and evaluate if the quality is greater than var max, then we
// assign the q of that track to max, and store
int imax[m];
double max;
for(int i=0;i<m;++i){
max =0;
for(int j=0;j<n;++j){
if(q[j] >= max && (i == 0 || q[imax[i-1]]>q[j])){
imax[i]= j;
max = q[j];
}
}
}
for(int i=0;i<m;++i){
cout<<names[imax[i]]<<"\n";
}
return 0;
} |
960404248fd2ce8e2d11e3055d6ee5892d1f3932 | 4431750b1cc0062b5bbc4a1ed92929c9a8497e46 | /Maze_demo.cpp | 3568087092ac98d387ad8c4ae9ed86f84ee188f6 | [] | no_license | jpiedra/CISC3130_MazeFinal | 64e5b6fef65652b140fe741c29288afd5bdd9aca | 9057d80fe7d54fa011f697fbfefe93fea486af88 | refs/heads/master | 2016-09-06T19:43:55.088689 | 2015-07-30T00:45:12 | 2015-07-30T00:45:12 | 39,923,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | cpp | Maze_demo.cpp | #include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <cstdlib>
#include "Location.h"
#include "Maze.h"
using namespace std;
int main(int argc, char **argv){
if (argc != 2) {
cerr << "NamUsage: maze_solver <maze file>" << endl;
exit(1);
}
string mazeFileName = string(argv[1]);
Maze maze = load(mazeFileName);
cout << maze << endl;
maze.solve();
return 0;
}
|
a3eb45be24df289a6359048802886ab71fcf5bd6 | 15b001c9441df8ca0636e4c5ac3f2070dc781ef7 | /Sort/bubbleSort.h | 0be019ffffe11abff7c0a39c090728be17687444 | [] | no_license | Andyato/Play-With-Algroithms | 5d8a48fe3cbe086216bbddde2f8c50465dc3dc17 | ec2890339ff8f4431c1174737259dd8ef084a7ef | refs/heads/master | 2020-03-27T06:58:44.896168 | 2018-12-02T02:58:39 | 2018-12-02T02:58:39 | 146,152,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | bubbleSort.h | //
// Created by Andy on 2018/10/7.
//
#ifndef SORT_BUBBLESORT_H
#define SORT_BUBBLESORT_H
template <typename T>
void bubbleSort(T arr[], int n)
{
for (int i = n-1; i > 1; --i)
for (int j = 0; j < i; ++j)
if (arr[j+1] < arr[j]) swap(arr[j], arr[j+1]);
}
#endif //SORT_BUBBLESORT_H
|
96c82421d3ea839b0902968de1f515049ee56994 | cda486451e061d6f74848bcda3a99cdc11e9ca14 | /11461 - Square Numbers.cpp | 8b9a7e530f62a5abd01d793b70c72859ab4ea38d | [] | no_license | MahbubAhmedTonmoy/UVA_Problems | b7fc165c143893857c7a1354b9d10ef9e9f539a3 | 839b7059fd41197e29f30f491c586939a8bbac65 | refs/heads/master | 2020-04-14T21:33:13.370809 | 2019-01-04T16:55:36 | 2019-01-04T16:55:36 | 164,132,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | 11461 - Square Numbers.cpp | #include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
int main()
{
long int x,sqr,i,n1,n2;
while(scanf("%ld%ld",&n1,&n2)==2)
{
if(n1==0 &&n2==0)break;
sqr=0;
for(i=sqrt(n1);i<=sqrt(n2);i++) //for(i=a;i<=b;i++)
{ //c = sqrt(i);
x=pow(i,2); //if(c*c==i) count++
if(x>=n1&&x<=n2) sqr++;
if(x>n2)break;
}
printf("%ld\n",sqr);
}
return 0;
}
|
400de6878b2fb405b2636a04d2fafeab81ad2f7b | ee501fe0f835a93e66b4895f6cdbb08d969e8647 | /13_handle_files_and_directories.cpp | 790ac5d337b77794807d2b65c3e55b2923a7020d | [] | no_license | Junichi-MARUYAMA-1984/Cpp20_for_game_developers | e48432236b803624f43aa6f8e8d33c80ad25aa2c | 40d6a1f102d022c07c1b914d85d8b2a5b62f7f72 | refs/heads/main | 2023-07-08T03:31:20.386523 | 2021-04-24T13:45:57 | 2021-04-24T13:45:57 | 348,616,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | 13_handle_files_and_directories.cpp | #include <iostream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main() {
// カレントディレクトリを取得
cout << fs::current_path() << endl;
// ファイルが存在するか否かを確認
if (fs::exists("test.txt")) {
fs::copy("test.txt", "test2.txt"); // ファイルをコピー
}
// ファイルを読み込む前に、ファイルのサイズを取得
cout << fs::file_size("save.dat") << endl;
// フォルダを作成
fs::create_directories("aaa/bbb/ccc");
// カレントディレクトリに含まれる全ファイルを出力
for (const auto& entry : fs::recursive_directory_iterator("./")) {
cout << entry.path() << endl;
}
} |
565a6a0dc1f55fa1fd56f891a2836e1a4f77a09c | 65d2bb047bad2a308a4b3ad955a7a18383b9091a | /src/hotrod/impl/consistenthash/ConsistentHash.h | 8a85ac661bf88b36a870d9d9d7f3536709a1f1d0 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | infinispan/cpp-client | 6bf9cdcedaa795bea1f0751fefe6c4bd73ef4111 | 0d7f6b7bc2190ec1ece399c1b5d97e1d2770081b | refs/heads/main | 2023-09-06T00:05:18.273183 | 2023-04-18T16:01:43 | 2023-04-18T16:01:43 | 9,675,051 | 7 | 11 | NOASSERTION | 2023-04-06T08:00:59 | 2013-04-25T15:33:11 | C++ | UTF-8 | C++ | false | false | 1,530 | h | ConsistentHash.h | #ifndef ISPN_HOTROD_CONSISTENT_HASH_H
#define ISPN_HOTROD_CONSISTENT_HASH_H
#include <infinispan/hotrod/InetSocketAddress.h>
#include "infinispan/hotrod/defs.h"
#include <set>
#include <map>
#include <vector>
namespace infinispan {
namespace hotrod {
namespace consistenthash {
class ConsistentHash {
public:
virtual void init(
std::map<infinispan::hotrod::transport::InetSocketAddress,
std::set<int32_t> > & servers2Hash, int32_t numKeyOwners,
int32_t hashSpace) = 0;
virtual void init(std::vector<std::vector<transport::InetSocketAddress>> _segmentOwners, uint32_t _numSegments) = 0;
virtual const infinispan::hotrod::transport::InetSocketAddress& getServer(const std::vector<char>& key) = 0;
/**
* Computes hash code of a given int32_t and then normalizes it to ensure a positive
* value is always returned.
* @param uint32_t to hash
* @return a non-null, non-negative normalized hash code for a given object
*/
virtual int32_t getNormalizedHash(int32_t objectId) = 0;
virtual int32_t getNormalizedHash(const std::vector<char>& key) = 0;
virtual std::map<infinispan::hotrod::transport::InetSocketAddress, std::vector<int> > getSegmentsByServers(){
// No segments here. Return empty map
std::map<infinispan::hotrod::transport::InetSocketAddress, std::vector<int> > m;
return m;
}
virtual ~ConsistentHash() {}
};
}}} // namespace infinispan::hotrod::consistenthash
#endif // ISPN_HOTROD_CONSISTENT_HASH_H
|
ecb60f7fe3bd3f9446bf8dd5bceac3fcd6f1af94 | 5d44c4dbbeccf48a4b789bca37fce483abe5cf16 | /src/optimize/wpa/Stat_collector.cpp | 0c62886fc4616921b17c4c09b1b34153dbc4b7be | [] | no_license | pbiggar/phc | 13ec82817db6854e8541758a1f7e57da292ff1f1 | 96adc7bef3e222532196846c1f11ea4b2bc7930e | refs/heads/master | 2023-03-10T18:06:00.905163 | 2021-07-08T14:55:32 | 2021-07-08T14:55:32 | 2,450,161 | 121 | 41 | null | 2021-07-08T14:55:33 | 2011-09-24T14:54:32 | C++ | UTF-8 | C++ | false | false | 13,018 | cpp | Stat_collector.cpp | /*
* phc -- the open source PHP compiler
* See doc/license/README.license for licensing information
*
*
* */
#include "Whole_program.h"
#include "../CFG.h"
#include "../Def_use_web.h"
#include "Def_use.h"
#include "../ssa/HSSA.h"
#include "Callgraph.h"
#include "Aliasing.h"
#include "lib/demangle.h"
#include "lib/Set.h"
#include "Stat_collector.h"
#include <iostream>
using namespace MIR;
using namespace boost;
using namespace std;
Stat_collector::Stat_collector()
{}
Stat_collector::Stat_collector (Whole_program* wp)
: wp (wp)
{
}
void
Stat_collector::run (CFG* cfg)
{
}
void
Stat_collector::visit_basic_block (Basic_block* bb)
{
inc_stat("total_num_bbs");
}
void
Stat_collector::visit_statement_block (Statement_block* bb)
{
Context* cx = Context::non_contextual (bb);
CTS ("num_statement_blocks");
Get_var_name* gvn = new Get_var_name ();
bb->statement->visit (gvn);
foreach (MIR::VARIABLE_NAME* varname, gvn->var_names)
{
if (!get_stringset_stat ("total_num_unique_vars")->has (*varname->value))
{
add_to_stringset_stat ("total_num_unique_vars", *varname->value);
}
const Types * types = wp->get_abstract_value (cx, R_OUT, varname)->types;
foreach (string t, *types)
types_per_var[*varname->value].insert (t);
CTS ("total_num_vars");
int m = wp->aliasing->get_references (cx, R_IN, new Index_node (cx->symtable_name (), *varname->value), PTG_ALL)->size ();
if (m > peak_aliases[*varname->value])
peak_aliases[*varname->value] = m;
}
}
void
Stat_collector::visit_entry_block (Entry_block* bb)
{
}
void
Stat_collector::visit_assign_array (Statement_block* bb, MIR::Assign_array* in)
{
visit_expr(bb,in->rhs);
if (wp->get_abstract_value (Context::non_contextual (bb), R_IN, in->lhs)->types->has ("unset"))
{
CTS ("num_implicit_array_defs");
CTS ("num_array_def_sites");
}
CTS ("num_assign_array");
collect_type_stats(bb, in->rhs,"types_assign_array");
collect_type_stats(bb, in->index,"types_array_index");
collect_deref_stats (bb, in->lhs, "writes", "Assign_array");
}
void
Stat_collector::visit_assign_field (Statement_block* bb, MIR::Assign_field * in)
{
visit_expr(bb,in->rhs);
VARIABLE_NAME* varname = dynamic_cast<VARIABLE_NAME*> (in->target);
if (varname!=NULL)
{
if (wp->get_abstract_value (Context::non_contextual (bb), R_IN, varname)->types->has ("unset"))
CTS ("num_implicit_object_defs");
collect_deref_stats (bb, varname, "writes", "Assign_field");
}
}
void
Stat_collector::visit_assign_next (Statement_block* bb, MIR::Assign_next* in)
{
CTS ("num_assign_next");
collect_type_stats (bb, in->lhs, "types_assign_next");
}
void
Stat_collector::visit_assign_var (Statement_block* bb, MIR::Assign_var* in)
{
last_assignment_lhs = in->lhs;
visit_expr(bb,in->rhs);
last_assignment_lhs = NULL;
if (in->is_ref && isa<MIR::Array_access> (in->rhs))
{
if (wp->get_abstract_value (Context::non_contextual (bb), R_IN, in->lhs)->types->has ("unset"))
{
CTS ("num_implicit_array_defs");
CTS ("num_array_def_sites");
}
}
else
{
if (wp->get_abstract_value (Context::non_contextual (bb), R_OUT, in->lhs)->types->has ("array"))
CTS ("num_array_def_sites");
}
MIR::Field_access* fa;
MIR::VARIABLE_NAME* vn;
if (in->is_ref && (fa = dynamic_cast<MIR::Field_access*> (in->rhs)))
{
if ((vn = dynamic_cast<MIR::VARIABLE_NAME*> (fa->target)))
{
if (wp->get_abstract_value (Context::non_contextual (bb), R_IN, vn)->types->has ("unset"))
CTS ("num_implicit_object_defs");
}
}
collect_type_stats(bb,in->lhs,"types_assign_var");
CTS ("num_assign_var");
}
void
Stat_collector::visit_assign_var_var (Statement_block* bb, MIR::Assign_var_var* in)
{
visit_expr(bb,in->rhs);
collect_type_stats(bb,in->lhs,"types_assign_var_var");
CTS ("num_assign_var_var");
}
void
Stat_collector::visit_catch (Statement_block* bb, MIR::Catch* in)
{
}
void
Stat_collector::visit_class_alias (Statement_block* bb, MIR::Class_alias* in)
{
}
void
Stat_collector::visit_eval_expr (Statement_block* bb, MIR::Eval_expr* in)
{
visit_expr (bb,in->expr);
}
void
Stat_collector::visit_foreach_end (Statement_block* bb, MIR::Foreach_end* in)
{
collect_type_stats (bb,in->array,"types_foreach_array");
}
void
Stat_collector::visit_foreach_next (Statement_block* bb, MIR::Foreach_next* in)
{
collect_type_stats (bb,in->array,"types_foreach_array");
}
void
Stat_collector::visit_foreach_reset (Statement_block* bb, MIR::Foreach_reset* in)
{
collect_type_stats (bb,in->array,"types_foreach_array");
}
void
Stat_collector::visit_global (Statement_block* bb, MIR::Global* in)
{
}
void
Stat_collector::visit_interface_alias (Statement_block* bb, MIR::Interface_alias* in)
{
}
void
Stat_collector::visit_method_alias (Statement_block* bb, MIR::Method_alias* in)
{
}
void
Stat_collector::visit_pre_op (Statement_block* bb, MIR::Pre_op* in)
{
collect_type_stats (bb, in->variable_name, "types_pre_op_var");
CTS ("num_pre_op_var");
}
void
Stat_collector::visit_return (Statement_block* bb, MIR::Return* in)
{
collect_type_stats (bb, in->rvalue, "types_return");
CTS ("num_return");
}
void
Stat_collector::visit_static_declaration (Statement_block* bb, MIR::Static_declaration* in)
{
}
void
Stat_collector::visit_throw (Statement_block* bb, MIR::Throw* in)
{
}
void
Stat_collector::visit_try (Statement_block* bb, MIR::Try* in)
{
}
void
Stat_collector::visit_unset (Statement_block* bb, MIR::Unset* in)
{
}
void
Stat_collector::visit_array_access (Statement_block* bb, MIR::Array_access* in)
{
collect_type_stats (bb, in->variable_name, "types_array_access");
collect_type_stats (bb, in->index, "types_array_index");
CTS ("num_array_access");
collect_deref_stats (bb, in->variable_name, "reads", "Array_access");
}
void
Stat_collector::visit_array_next (Statement_block* bb, MIR::Array_next* in)
{
}
void
Stat_collector::visit_bin_op (Statement_block* bb, MIR::Bin_op* in)
{
collect_type_stats (bb, in->left, "types_bin_op_lhs");
collect_type_stats (bb, in->right, "types_bin_op_rhs");
CTS ("num_bin_op_lhs");
}
void
Stat_collector::visit_bool (Statement_block* bb, MIR::BOOL* in)
{
}
void
Stat_collector::visit_cast (Statement_block* bb, MIR::Cast* in)
{
}
void
Stat_collector::visit_constant (Statement_block* bb, MIR::Constant* in)
{
}
void
Stat_collector::visit_field_access (Statement_block* bb, MIR::Field_access* in)
{
MIR::VARIABLE_NAME* varname = dynamic_cast<VARIABLE_NAME*> (in->target);
if (varname)
collect_deref_stats (bb, varname, "reads", "Field_access");
}
void
Stat_collector::visit_foreach_get_key (Statement_block* bb, MIR::Foreach_get_key* in)
{
}
void
Stat_collector::visit_foreach_get_val (Statement_block* bb, MIR::Foreach_get_val* in)
{
}
void
Stat_collector::visit_foreach_has_key (Statement_block* bb, MIR::Foreach_has_key* in)
{
}
void
Stat_collector::visit_instanceof (Statement_block* bb, MIR::Instanceof* in)
{
}
void
Stat_collector::visit_int (Statement_block* bb, MIR::INT* in)
{
}
void
Stat_collector::visit_isset (Statement_block* bb, MIR::Isset* in)
{
}
void
Stat_collector::visit_method_invocation (Statement_block* bb, MIR::Method_invocation* in)
{
string meth_func = "function";
MIR::VARIABLE_NAME* varname;
if ((varname = dynamic_cast<VARIABLE_NAME*> (in->target)))
meth_func = "method";
CTS (meth_func + "_call_sites");
Method_info_list* minfolist = wp->get_possible_receivers (Context::non_contextual(bb),R_OUT,in);
int n = minfolist->size ();
CTS (meth_func + "s_with_" + lexical_cast<string> (n) + "_receivers");
if (minfolist->size () == 1)
{
User_method_info* info = dynamic_cast<User_method_info*> (minfolist->front ());
if (info != NULL)
{
if (info->get_method ()->statements->size () == 0 ||
(info->get_method ()->statements->size () == 1
&& info->get_method ()->statements->at (0)->classid () == Return::ID))
{
CTS ("num_inlinable_" + meth_func + "s");
}
}
}
foreach (Actual_parameter* param, *in->actual_parameters)
{
collect_type_stats (bb,param->rvalue,"types_" + meth_func + "_parameter");
CTS ("num_" + meth_func + "_parameter");
}
}
void
Stat_collector::visit_new (Statement_block* bb, MIR::New* in)
{
}
void
Stat_collector::visit_nil (Statement_block* bb, MIR::NIL* in)
{
}
void
Stat_collector::visit_param_is_ref (Statement_block* bb, MIR::Param_is_ref* in)
{
}
void
Stat_collector::visit_real (Statement_block* bb, MIR::REAL* in)
{
}
void
Stat_collector::visit_string (Statement_block* bb, MIR::STRING* in)
{
}
void
Stat_collector::visit_unary_op (Statement_block* bb, MIR::Unary_op* in)
{
collect_type_stats (bb, in->variable_name, "types_unary_op_var");
CTS ("num_unary_op_var");
}
void
Stat_collector::visit_variable_name (Statement_block* bb, MIR::VARIABLE_NAME* in)
{
}
void
Stat_collector::visit_variable_variable (Statement_block* bb, MIR::Variable_variable* in)
{
}
void
Stat_collector::collect_type_stats (Basic_block* bb, MIR::Rvalue* rval,string statname)
{
const Abstract_value* absval = wp->get_abstract_value (Context::non_contextual (bb), R_OUT, rval);
if (absval->types)
{
foreach (string type, *absval->types)
{
CTS (statname);
}
}
}
void
Stat_collector::get_number_of_statements (CFG* cfg, string beforeafter)
{
foreach (Basic_block* bb, *cfg->get_all_bbs ())
{
if ((dynamic_cast<Statement_block*> (bb)))
{
CTS ("num_statements_" + beforeafter);
}
if (isa<Branch_block> (bb))
CTS ("num_branches_"+beforeafter);
}
}
void
Stat_collector::collect_def_use_stats (CFG* cfg)
{
int starred, unstarred;
Def_use* du = wp->def_use;
if (cfg->duw)
du = cfg->duw->get_def_use ();
starred = du->get_num_vals (cfg, DEF, false);
unstarred = du->get_num_refs (cfg, DEF, false);
set_stat ("starred_defs", starred);
set_stat ("unstarred_defs", unstarred);
set_stat ("defs", starred + unstarred);
starred = du->get_num_vals (cfg, USE, false);
unstarred = du->get_num_refs (cfg, USE, false);
set_stat ("starred_uses", starred);
set_stat ("unstarred_uses", unstarred);
set_stat ("uses", starred + unstarred);
starred = du->get_num_vals (cfg, MAYDEF, false);
unstarred = du->get_num_refs (cfg, MAYDEF, false);
set_stat ("starred_may_defs", starred);
set_stat ("unstarred_may_defs", unstarred);
set_stat ("may_defs", starred + unstarred);
foreach (Basic_block* bb, *cfg->get_all_bbs ())
{
if (!((dynamic_cast<Entry_block*> (bb)) || (dynamic_cast<Exit_block*> (bb))))
{
foreach (const Alias_name* def, *du->get_defs (bb))
{
add_to_stringset_stat ("initialised_vars", def->str ());
if (def->str ()[0] == '*')
add_to_stringset_stat("starred_initialised_vars", def->str ());
}
}
}
}
void
Stat_collector::collect_method_stats ()
{
int num_functions = filter_types<User_method_info> (Oracle::get_all_methods())->size ();
int num_classes = 0;
foreach (User_class_info* cinf, *filter_types<User_class_info> (Oracle::get_all_classes ()))
{
num_functions += cinf->get_methods ()->size ();
num_classes++;
}
set_stat ("total_num_methods/functions", num_functions);
set_stat ("num_unreachable_methods/functions", num_functions - filter_types<User_method_info> (wp->callgraph->get_called_methods ())->size ());
set_stat ("total_classes_used", wp->callgraph->get_used_classes ()->size ());
set_stat ("num_unreachable_classes", num_classes - wp->callgraph->get_used_classes ()->size ());
}
void
Stat_collector::collect_alias_analysis_stats ()
{
set_stat ("num_field_edges", wp->aliasing->get_total_num_field_edges ());
set_stat ("num_points_to_edges", wp->aliasing->get_total_num_points_to_edges ());
int poss_ref_edges = wp->aliasing->get_num_possible_reference_edges ();
int def_ref_edges = wp->aliasing->get_num_definite_reference_edges ();
set_stat ("num_possible_reference_edges", poss_ref_edges);
set_stat ("num_definite_reference_edges", def_ref_edges);
set_stat ("num_reference_edges", poss_ref_edges + def_ref_edges);
}
void
Stat_collector::collect_deref_stats (Basic_block* bb, MIR::VARIABLE_NAME* in, string read_write, string node_type)
{
Context* cx = Context::non_contextual (bb);
Set<string> temp;
Path* p = P (cx->symtable_name (), in);
foreach (const Index_node* index, *wp->get_named_indices (cx, R_IN, p, true))
{
cStorage_node_list* snl = wp->aliasing->get_points_to (cx, R_IN, index);
foreach (const Storage_node* sn, *snl)
temp.insert (sn->str ());
}
CTS ("IR_Nodes_dereferenced_" + read_write + "_" + node_type);
if (temp.size () > 0)
CTS ("storage_nodes_deref_" + read_write + "_" + node_type);
foreach (string s, temp)
CTS ("storage_nodes_deref_" + read_write + "_" + node_type);
}
void
Stat_collector::register_type_stats ()
{
int n;
string s;
foreach (tie (s, n), peak_aliases)
{
CTS ("vars_with_" + lexical_cast<string> (n) + "_aliases");
}
peak_aliases.clear ();
Set<string> ss;
foreach (tie (s, ss), types_per_var)
{
CTS ("num_vars_" + lexical_cast<string> (ss.size ()) + "_types");
}
types_per_var.clear ();
}
|
abcf0f0d53da63e70aea129fa7280904bf626dbb | 63ed2deb4616e8d3b93a4aefccd21d327ba82245 | /Printer/form.cpp | 16b371786481196ccd8ea93acaa1662b8553d523 | [] | no_license | drescherjm/QtExamples | 2f49cf85b04c08c011c2c0539862bfbf613f92a5 | 129a14dabb4cda84526d2780862d32156c75ec01 | refs/heads/master | 2020-12-25T06:12:05.772601 | 2012-03-19T00:40:40 | 2012-03-19T00:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | form.cpp | #include <QtGui>
#include <QGraphicsTextItem>
#include "form.h"
Form::Form(QWidget *parent)
: QWidget(parent)
{
this->setupUi(this);
Scene = new QGraphicsScene();
this->graphicsView->setScene(Scene);
QPixmap blackPixmap(20, 20);
QColor black(0,0,0);
blackPixmap.fill(black);
QPixmap redPixmap(20, 20);
QColor red(255,0,0);
redPixmap.fill(red);
Scene->addPixmap(redPixmap);
QGraphicsPixmapItem* item = Scene->addPixmap(blackPixmap);
item->setPos(20,20);
QGraphicsTextItem* simpleTextItem = Scene->addText("test");
simpleTextItem->setPos(0, simpleTextItem->boundingRect().height());
}
void Form::on_btnSave_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this, "Save Scene", "", "PDF (*.pdf)");
QPrinter printer;
printer.setOutputFormat(QPrinter::PdfFormat);
//printer.setPaperSize(QPrinter::Letter);
printer.setOutputFileName(fileName);
QPainter painter(&printer);
Scene->render(&painter);
}
|
2639c5d0a5be82af7839f8fd51eda4ba125cdb0e | 58ab28ea5c4a862368351a7f90726eaa584022ce | /es3.cpp | 3517b1befea17d40da07e6980f841634bb79c2c4 | [] | no_license | rc2003/eserciziverifica | 46ce1880b3adf5b76e621965800e54022da9d8ee | 94c27702332f8acfc21bd6888bf579fd16204a25 | refs/heads/master | 2020-12-18T22:24:45.588157 | 2020-01-28T19:37:10 | 2020-01-28T19:37:10 | 235,537,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | es3.cpp | int main(){
int N;
freopen("input/3", "r", stdin);
freopen("output/3", "w", stdout);
scanf("%d", &N);
int A[N];
for (int i=0;i<N;i++){
scanf("%d", &A[i]);
}
for (int z=0;z<N;z++){
if(A[z]%2==0){
A[z]/=2;
}
else if(A[z]%2!=0){
A[z]*=2;
}
}
for (int v=0;v<N;v++){
printf("%d ", A[v]);
}
}
|
a1345a3fda9341a3e7697b53d677767fc8df9421 | fba5bc9c8c55a31bb1fd754525dcc72e5df14fa7 | /Cwiczenia/main.cpp | 6f609de28255eab73d6b02caecd091b1c9393004 | [] | no_license | teamon/programy | 8f090a21f9eccce063c2d56e3a7ab4a1cefd5580 | ad8be09e23c4d60bc31c3d8e88c9a19ec22f5d54 | refs/heads/master | 2021-01-21T13:36:55.063789 | 2010-01-18T13:45:06 | 2010-01-18T13:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,476 | cpp | main.cpp | #define USERS_DATA_FILE "users.txt"
#define TESTS_DATA_FILE "tests.txt"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct Test;
struct User;
struct MenuItem;
void show_menu(MenuItem * items, int count);
void show_menu(MenuItem * items, int count, bool(* break_menu)());
void load_database();
void load_users_database();
void load_tests_database();
void save_users_database();
void save_tests_database();
void save_database();
void list_tests();
void list_user_tests();
void new_user_test();
void list_users();
void add_user();
void delete_user();
void update_user();
bool deleted_user();
struct User {
unsigned int id;
string first_name;
string last_name;
};
struct Test {
int id;
int user_id;
int result;
};
struct MenuItem {
string description;
void (* function)();
};
User * users;
Test * tests;
int users_num, tests_num;
int users_max_id, tests_max_id;
User * current_user;
char operations[4] = { '+', '*', '-', '/' };
void clear_screen(){
system("clear");
}
int random(int max){
return rand() % max;
}
int main (int argc, char * const argv[]) {
load_database();
MenuItem items[] = {
"Pokaż listę użytkowników", list_users,
"Dodaj użytkownika", add_user,
"Pokaż liste testów", list_tests
};
show_menu(items, sizeof(items) / sizeof(MenuItem));
save_database();
return 0;
}
void load_database() {
load_users_database();
load_tests_database();
}
int compare_users(const void * a, const void * b){
short c = (((User *)a)->last_name).compare(((User *)b)->last_name);
if(c == 0) return (((User *)a)->first_name).compare(((User *)b)->first_name);
else return c;
}
void load_users_database(){
ifstream f(USERS_DATA_FILE);
if(f.good()){
f >> users_num;
users_max_id = 0;
users = new User[users_num];
int i=0;
while (!f.eof() && i < users_num) {
User user;
f >> user.id;
f >> user.last_name;
f >> user.first_name;
if(user.last_name != "" && user.first_name != ""){
users[i] = user;
if(user.id > users_max_id) users_max_id = user.id;
i++;
}
}
f.close();
}
qsort(users, users_num, sizeof(User), compare_users);
}
void load_tests_database(){
ifstream f(TESTS_DATA_FILE);
if(f.good()){
f >> tests_num;
tests_max_id = 0;
tests = new Test[tests_num];
int i=0;
while (!f.eof() && i < tests_num) {
Test test;
f >> test.id;
f >> test.user_id;
f >> test.result;
tests[i] = test;
if(test.id > tests_max_id) tests_max_id = test.id;
i++;
}
f.close();
}
}
void save_database() {
save_users_database();
save_tests_database();
}
void save_users_database(){
ofstream f(USERS_DATA_FILE);
if (f.good()){
f << users_num << endl;
for(User *u = users; u < users+users_num; u++){
f << u->id << endl;
f << u->last_name << endl;
f << u->first_name << endl;
}
}
else cout << "Wystąpił błąd podczas zapisu" << endl;
f.close();
}
void save_tests_database(){
ofstream f(TESTS_DATA_FILE);
if (f.good()){
f << tests_num << endl;
for(Test *t = tests; t < tests+tests_num; t++){
f << t->id << endl;
f << t->user_id << endl;
f << t->result << endl;
}
}
else cout << "Wystąpił błąd podczas zapisu" << endl;
f.close();
}
void show_menu(MenuItem * items, int count){
show_menu(items, count, NULL);
}
void show_menu(MenuItem * items, int count, bool (* break_menu)()){
int option;
while(true){
if(break_menu && break_menu()) break;
for(int i = 0; i < count; i++)
cout << "[" << i+1 << "] " << items[i].description << endl;
cout << "[0] Powrót/Zakończ" << endl;
cout << "Wybierz opcję z menu: ";
cin >> option;
if(option == 0) break;
if(option > count) {
cout << "[ERROR] Podana opcja nie istnieje" << endl;
continue;
}
clear_screen();
items[option-1].function();
}
}
User * get_user(int user_id){
for(User * u = users; u<users+users_num; u++)
if(u->id == user_id) return u;
return NULL;
}
void list_tests(){
cout << "Lista testów:" << endl;
cout << " ID | WYNIK | NAZWISKO | IMIĘ " << endl;
cout << "--------------------------------------------------" << endl;
int sum=0;
User * user;
for(int i=0; i<tests_num; i++){
cout << " ";
cout << setw(3) << tests[i].id << " | ";
cout << setw(3) << tests[i].result << "/10" << " | ";
user = get_user(tests[i].user_id);
cout << setw(20) << left << user->last_name << " | ";
cout << setw(10) << user->first_name;
cout << right << endl;
sum += tests[i].result;
}
cout << "--------------------------------------------------" << endl;
cout << "RAZEM: " << sum << "/" << tests_num*10 << " (" << setprecision(2) << (((float)sum)/tests_num*10) << "%)" << endl;
}
void list_user_tests(){
cout << "Lista testów:" << endl;
cout << " ID | WYNIK " << endl;
cout << "---------------" << endl;
int sum=0,k=0;
for(int i=0; i<tests_num; i++){
if(tests[i].user_id == current_user->id){
cout << " ";
cout << setw(3) << tests[i].id << " | ";
cout << setw(3) << tests[i].result << "/10" << endl;
k++;
sum += tests[i].result;
}
}
cout << "--------------" << endl;
cout << "RAZEM: " << sum << "/" << k*10 << " (" << setprecision(2) << (((float)sum)/k*10) << "%)" << endl;
}
void new_user_test(){
Test test;
test.user_id = current_user->id;
test.result = 0;
int a,b,c;
char oper;
for(int i=1; i<=10; i++){
cout << i << ") ";
a = random(10);
b = random(10);
oper = operations[random(4)];
if(oper == '/') cout << (a*b);
else cout << a;
cout << " " << oper << " " << b << " = ";
cin >> c;
switch(oper){
case '+':
if(a + b == c) test.result++;
break;
case '-':
if(a - b == c) test.result++;
break;
case '*':
if(a * b == c) test.result++;
break;
case '/':
if(c == a) test.result++;
break;
}
}
Test * old_tests = tests;
test.id = ++tests_max_id;
tests_num++;
tests = new Test[tests_num];
for(int i=0; i<tests_num-1; i++) tests[i] = old_tests[i];
tests[tests_num-1] = test;
save_database();
cout << "Twój wynik to: " << test.result << "/10" << endl;
cout << "Naciśnij enter aby powrócić";
cin.ignore();
cin.get();
}
void list_users(){
cout << "Lista użytkowników:" << endl;
cout << " ID | NAZWISKO | IMIĘ " << endl;
cout << "-----------------------------------------" << endl;
for(int i=0; i<users_num; ++i){
cout << " ";
cout << setw(3) << users[i].id << " | ";
cout << setw(20) << left << users[i].last_name << " | ";
cout << setw(10) << users[i].first_name;
cout << right << endl;
}
cout << endl;
int user_id;
while(true){
cout << "Podaj ID użytkownika (0 aby powrócić): ";
cin >> user_id;
if(user_id <= 0) return;
else {
current_user = get_user(user_id);
if(current_user == NULL){
cout << "[ERROR] Użytkownik o podanym ID nie istnieje!" << endl;
continue;
} else {
break;
}
}
}
MenuItem items[] = {
"Pokaż testy użytkownika", list_user_tests,
"Nowy test", new_user_test,
"Zmień dane użytkownika", update_user,
"Usuń użytkownika", delete_user
};
show_menu(items, sizeof(items) / sizeof(MenuItem), deleted_user);
}
void add_user(){
User new_user;
cout << "Podaj dane nowego użytkownika:" << endl;
cout << "Nazwisko: ";
cin >> new_user.last_name;
cout << "Imię: ";
cin >> new_user.first_name;
new_user.id = ++users_max_id;
users_num++;
User * old_users = users;
users = new User[users_num];
for(int i=0; i<users_num-1; i++) users[i] = old_users[i];
users[users_num-1] = new_user;
save_database();
}
void delete_user(){
User * old_users = users;
users_num--;
users = new User[users_num];
int i = 0;
User * u = old_users;
for(; u < current_user; u++, i++) users[i] = *u;
for(u++; u<old_users+users_num+1; u++, i++) users[i]= *u;
Test * old_tests = tests;
int count=0;
for(int j=0; j<tests_num; j++){
if(tests[j].user_id == current_user->id) count++;
}
tests = new Test[tests_num-count];
for(int j=0, k=0; j<tests_num; j++){
if(tests[j].user_id != current_user->id) {
tests[k] = old_tests[j];
k++;
}
}
tests_num -= count;
current_user = NULL;
save_database();
}
void update_user(){
cout << "Podaj nowe dane użytkownika:" << endl;
cout << "Nazwisko: ";
cin >> current_user->last_name;
cout << "Imię: ";
cin >> current_user->first_name;
save_database();
}
bool deleted_user(){
return current_user == NULL;
}
|
8e12f43363ac84443386ee5e0bfdba87d3c890dd | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/boost/simd/include/functions/scalar/logical_and.hpp | ab3c61ca6eb5854f0b3c9eaee5178b34eab824f5 | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 219 | hpp | logical_and.hpp | #ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_SCALAR_LOGICAL_AND_HPP_INCLUDED
#define BOOST_SIMD_INCLUDE_FUNCTIONS_SCALAR_LOGICAL_AND_HPP_INCLUDED
#include <boost/simd/operator/include/functions/scalar/logical_and.hpp>
#endif
|
0d8cfb47e9d4c3c2015386fd9f860584a636afba | cac78a16813b8f1320e6aaa7fa62a370e0a26816 | /code/mpma/base/Info.h | 41f4162809a793f78302282ad63872adb2149b81 | [] | no_license | psyadam/MapBuilder | e16c4eefaedb92db7efea077365a131df5126497 | 1d69e918804801866b43835f7f9594936cb8552c | refs/heads/master | 2020-04-24T17:13:58.678866 | 2019-02-23T20:46:58 | 2019-02-23T20:46:58 | 172,139,470 | 0 | 1 | null | 2019-02-23T20:46:59 | 2019-02-22T21:50:48 | C | UTF-8 | C++ | false | false | 1,232 | h | Info.h | //!\file Info.h Retrieves information about the system.
//Luke Lenhart (2007)
//See /docs/License.txt for details on how this code may be used.
#pragma once
#include <string>
#include "Types.h"
namespace MPMA
{
//!\brief Information about the system. These are readable anytime after init.
//!Values which are not possible to obtain will be populated with sane defaults.
struct SystemInfo
{
//overall cpu facts
static nuint ProcessorCount; //!<Number of logical CPUs
static std::string ProcessorName; //!<Name of the CPU
static bool ProcessorHyperthreading; //!<Whether the CPU has hyperthreading enabled
//per-cpu facts
static nuint ProcessorBogomips; //!<Very rough speed approximation of one CPU.
//mem info (in MB)
static nuint MemoryPhysicalTotal; //!<The amount of physical memory the machine has.
static nuint MemorySwapTotal; //!<The amount of swap memory the machine has.
//os info
static std::string OperatingSystemName; //!<Name of the operating system.
//heuristacal information
static bool SuggestSleepInSpinlock; //!<Heuristic: Suggestion of whether to yield in a spinlock.
};
}
|
a61f15df768bd266fe37b0f80b802e1265032570 | f5c319aee0991373c379bf67dc82379d09f0709e | /leetcode/400NthDigit.cpp | 543fe64f5ba38ef5b7a0b7bb406c488ae2b579fa | [] | no_license | ncu571633/code | c34cc9ff525861af41ad14e02194ae55d05ddd26 | a1a1435a62d9274da7b08ebd873e7cfafbc88e60 | refs/heads/main | 2023-09-01T19:43:33.297014 | 2023-08-29T03:36:23 | 2023-08-29T03:36:23 | 17,040,829 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | 400NthDigit.cpp | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
/*
i = 1: 1~9 count: 9
i = 2: 10~99 count:90
i = 3: 100~999 count:900
*/
class Solution {
public:
int findNthDigit(int n) {
int i=1;
long long first = 1;
while(n>9*first*i)
{
n = n - 9*i*first;
first = 10*first;
i++;
}
first = first+(n-1)/i;
return to_string(first)[(n-1)%i]-'0';
}
};
|
8ada1ddfb03846efa04a30bc0ffd1ee5a76f0772 | e54a8112223fd49e880247842ec259a9f334716a | /test/ext_arr_pushpop.cc | 6691d9e84a68570d52e1329e67c1ddf976dcf608 | [] | no_license | pabloem/advanced_arrays | daf2763440a4efde1bf980d75db3da230007bf68 | 2a9753b7f24afc7cfe01d95e621689a97488c682 | refs/heads/master | 2016-08-07T22:43:40.572348 | 2014-12-03T12:30:59 | 2014-12-03T12:30:59 | 25,818,060 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cc | ext_arr_pushpop.cc | #include "../include/extendible_array.h"
#define GROW 0
#define SHRINK 1
int main(){
ExtendibleArray<int> a;
for(int i = 0; i < 300; i++){
int ps_el = rand();
printf("Pushing %d\n",ps_el);
a.push(ps_el);
}
for(int i = 0; i < 300; i ++){
int pp_el = a.pop();
printf("Popping %d\n",pp_el);
}
for(int i = 0; i < 400; i ++){
int op = rand()%2;
if(op == GROW){
printf("It %d - Pushing | SZ:%d\n",i,a.number_of_elements);
a.push(rand());
}
if(op == SHRINK){
printf("It %d - Popping | SZ:%d\n",i,a.number_of_elements);
a.pop();
}
}
return 0;
}
|
d08ddf06e4c93aaa11406f9e8e46a36b7aa01fd4 | ddbb3a892d38a75902030b56fb6333752460bedc | /headers/Royal.hpp | 070d12e8cfa66faf9160dde15842125de2e5b008 | [] | no_license | kiuKisas/Plazza | b7af893d0dc32761e51b3ad11930fbdcd02971a3 | e18ca764ec1259d709ef66831e9def8c30522bde | refs/heads/master | 2021-01-10T08:26:03.997078 | 2015-06-06T00:53:48 | 2015-06-06T00:53:48 | 36,955,582 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 452 | hpp | Royal.hpp | /*
** Royal.hpp for plazza in /home/nlequain/projets/tek2/cpp/cpp_plazza/headers
**
** Made by nlequain
** Login <nlequain@epitech.net>
**
** Started on Sun Apr 26 22:36:57 2015 nlequain
** Last update Sun Apr 26 22:40:32 2015 nlequain
*/
#ifndef __ROYAL_HH__
# define __ROYAL_HH__
# include "ABurger.hpp"
class Royal : public ABurger<Royal>
{
public:
Royal(enum ARecipe::TaillePizza size = ARecipe::S);
~Royal();
};
#endif /* !__ROYAL_HH__ */ |
48b29ff79f9e9302f67d3df5b85836929dfc6111 | 3b836295e8491d8497bc6fb2260d95a8edef304f | /PE005.cpp | ab250dc8f51b8e0e128170117a3c7c50bc391f0b | [] | no_license | a-phillips/PE-CPP | ef094e4749d7775b3cd43794786ead3b546e1b98 | c8e885a740fc321451fbf6a9261efa3d9eec685b | refs/heads/master | 2021-01-19T00:14:54.463702 | 2014-12-16T05:37:10 | 2014-12-16T05:37:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cpp | PE005.cpp | #include <iostream>
using namespace std;
pencil/paper:
*1 *2 *3 *4 *5 *6 *7 *8 *9 *10
11 *12 13 *14 *15 *16 17 *18 19 *20
factors:
2^4 (covers 2, 4, 8, 16)
3^2 (covers 3, 9)
5 (covers 5, 10 w/ 2, 15 w/ 3, 20 w/ (2^2))
7 (covers 7, 14 w/ 2)
11
13
17
19
|
f2663e7e3da0da7d2ce543eeb1ba293b1466c396 | bf6c965a15f1d02eef6db442af0f5216822773d2 | /before20210628/1464. Maximum Product of Two Elements in an Array/1464. Maximum Product of Two Elements in an Array.cpp | 85350b6eeb115a859782fdddeac91647e165c41a | [] | no_license | ThornLin/My-Leetcode | cb2069dd1b4eb09d4bfd13d5027d4dff2d2d76a3 | 67b6d996423db48af087891c57fb1d9e868d46af | refs/heads/main | 2023-07-08T01:54:27.000657 | 2021-08-04T04:31:12 | 2021-08-04T04:31:12 | 384,394,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | cpp | 1464. Maximum Product of Two Elements in an Array.cpp | /*
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3
*/
/*class Solution {
public:
int maxProduct(vector<int>& nums) {
int max1=0, max2=1, temp=0;
for(int i=0; i<nums.size(); i++){
if(max1 > max2){
temp = max1;
max1 = max2;
max2 = temp;
}
if(nums[i]>max1){
max1 = nums[i];
}
else if(nums[i]>max2){
max2 = nums[i];
}
}
return (max1-1) * (max2-1);
}
};*/
class Solution {
public:
int maxProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
return (nums[nums.size()-1]-1) * (nums[nums.size()-2]-1);
}
};
|
dbb4c75cf64b244a975d1451ea7cb0a4e0d987fe | 6bfd9b7104d6db62ed19793cb93678bb29a449fa | /3-matrixadd.cpp | 34c8d29c9c3c61c8b120f905b25d1ba418f821c7 | [] | no_license | Manay97/HPC | 5452e1beb1d5d055edd7c7fdc935e4863be5ca0a | 06e350aab5ca6861a557176f6f1ffd59ccb43418 | refs/heads/main | 2023-07-31T07:25:29.789691 | 2021-09-11T17:00:41 | 2021-09-11T17:00:41 | 405,404,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | cpp | 3-matrixadd.cpp | #include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int tid;
int i,j;
int rows,cols;
/*printf("Enter Number of Rows of matrices\n");
scanf("%d",&rows);
printf("Enter Number of Columns of matrices\n");
scanf("%d",&cols);*/
rows=60;
cols=40;
int a[rows][cols];
int b[rows][cols];
int c[rows][cols];
int *d,*e,*f;
printf("Enter %d elements of first matrix\n",rows*cols);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
{
a[i][j]=1;
}
printf("Enter %d elements of second matrix\n",rows*cols);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
{
b[i][j]=2;
}
//write
double t1 = omp_get_wtime();
#pragma omp parallel for schedule(static,10)
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
#pragma omp barrier
double t2 = omp_get_wtime();
printf("Values of Resultant Matrix C are as follows:\n");
/*for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
{
printf("Value of C[%d][%d]=%d\n",i,j,c[i][j]);
}*/
cout<< fixed << setprecision(10) <<"time taken: "<<t2-t1<<endl;
return 0;
}
|
4a063d760d782461614077fb9b7a33a855e7327a | d0798eeee8b8cd664c8f459ac71dbb4aa5732545 | /src/mirrage/renderer/include/mirrage/renderer/deferred_renderer.hpp | 6dcfb048a2f31d30d3ba9cd5f35c99a01b2f6a04 | [
"MIT"
] | permissive | dwlcj/mirrage | 37cef3dd2e2ed678d3e645d68d086fc00d754dae | 7573d3322ae8a9d2b9c0a43fc4f47023a0bb0388 | refs/heads/master | 2020-03-30T00:00:10.508314 | 2018-09-22T16:53:47 | 2018-09-22T16:53:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,881 | hpp | deferred_renderer.hpp | #pragma once
#include <mirrage/renderer/camera_comp.hpp>
#include <mirrage/renderer/gbuffer.hpp>
#include <mirrage/renderer/model.hpp>
#include <mirrage/renderer/render_pass.hpp>
#include <mirrage/graphic/context.hpp>
#include <mirrage/graphic/device.hpp>
#include <mirrage/graphic/profiler.hpp>
#include <mirrage/utils/min_max.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/vec3.hpp>
#include <vulkan/vulkan.hpp>
namespace mirrage {
namespace ecs {
class Entity_manager;
}
class Engine;
} // namespace mirrage
namespace mirrage::renderer {
class Deferred_renderer_factory;
class Deferred_renderer;
struct Renderer_settings {
int shadowmap_resolution = 2048;
int shadow_quality = 99; // 0 = lowest
bool gi = true;
bool gi_highres = true;
bool gi_shadows = false;
int gi_diffuse_mip_level = 1;
int gi_min_mip_level = 0;
int gi_samples = 32;
int gi_lowres_samples = 128;
int gi_low_quality_mip_levels = 0;
bool tonemapping = true;
float exposure_override = 0.f;
float min_display_luminance = 2.f;
float max_display_luminance = 150.0f;
bool taa = true;
bool ssao = true;
bool bloom = true;
float background_intensity = 0.f;
bool shadows = true;
bool dynamic_lighting = true;
int debug_gi_layer = -1;
bool debug_geometry = true;
};
#ifdef sf2_structDef
sf2_structDef(Renderer_settings,
shadowmap_resolution,
shadow_quality,
gi,
gi_highres,
gi_shadows,
gi_diffuse_mip_level,
gi_low_quality_mip_levels,
min_display_luminance,
max_display_luminance,
taa,
ssao,
bloom,
shadows,
dynamic_lighting,
debug_geometry);
#endif
struct Global_uniforms {
glm::mat4 view_proj_mat;
glm::mat4 view_mat;
glm::mat4 proj_mat;
glm::mat4 inv_view_mat;
glm::mat4 inv_proj_mat;
glm::vec4 eye_pos;
glm::vec4 proj_planes; //< near, far, fov horizontal, fov vertical
glm::vec4 time; //< time, sin(time), delta_time
glm::vec4 proj_info;
};
template <class T, class... Args>
auto make_pass_factory(Args&&... args)
{
return std::unique_ptr<Render_pass_factory>(new T(std::forward<Args>(args)...));
}
// shared among all Deferred_renderers in all screens
class Deferred_renderer_factory {
public:
Deferred_renderer_factory(Engine& engine,
graphic::Window& window,
std::vector<std::unique_ptr<Render_pass_factory>>);
~Deferred_renderer_factory();
auto create_renderer(ecs::Entity_manager&) -> std::unique_ptr<Deferred_renderer>;
void queue_commands(vk::CommandBuffer);
auto queue_temporary_command_buffer() -> vk::CommandBuffer;
auto create_compute_command_buffer() -> vk::UniqueCommandBuffer;
auto model_material_sampler() const noexcept { return *_model_material_sampler; }
auto model_descriptor_set_layout() const noexcept { return *_model_desc_set_layout; }
auto compute_queue() const noexcept { return _compute_queue; }
void finish_frame();
auto settings() const -> auto& { return *_settings; }
void settings(const Renderer_settings& s, bool apply = true);
void save_settings();
private:
friend class Deferred_renderer;
struct Asset_loaders;
using Pass_factories = std::vector<std::unique_ptr<Render_pass_factory>>;
using Settings_ptr = asset::Ptr<Renderer_settings>;
Engine& _engine;
asset::Asset_manager& _assets;
Settings_ptr _settings;
Pass_factories _pass_factories;
graphic::Window& _window;
graphic::Device_ptr _device;
graphic::Swapchain& _swapchain;
std::uint32_t _draw_queue_family;
std::uint32_t _compute_queue_family;
vk::Queue _draw_queue;
vk::Queue _compute_queue;
vk::UniqueSemaphore _image_acquired;
vk::UniqueSemaphore _image_presented;
graphic::Command_buffer_pool _command_buffer_pool;
graphic::Command_buffer_pool _compute_command_buffer_pool;
util::maybe<std::size_t> _aquired_swapchain_image;
std::vector<vk::CommandBuffer> _queued_commands;
std::vector<Deferred_renderer*> _renderer_instances;
bool _recreation_pending = false;
vk::UniqueSampler _model_material_sampler;
vk::UniqueDescriptorSetLayout _model_desc_set_layout;
std::unique_ptr<Asset_loaders> _asset_loaders;
void _present();
auto _rank_device(vk::PhysicalDevice, util::maybe<std::uint32_t> gqueue) -> int;
auto _init_device(vk::PhysicalDevice, util::maybe<std::uint32_t> gqueue)
-> graphic::Device_create_info;
auto _aquire_next_image() -> std::size_t;
};
class Deferred_renderer {
public:
Deferred_renderer(Deferred_renderer_factory&,
std::vector<std::unique_ptr<Render_pass_factory>>&,
ecs::Entity_manager&,
Engine&);
Deferred_renderer(const Deferred_renderer&) = delete;
auto operator=(const Deferred_renderer&) -> Deferred_renderer& = delete;
~Deferred_renderer();
void recreate();
void update(util::Time dt);
void draw();
void shrink_to_fit();
auto gbuffer() noexcept -> auto& { return *_gbuffer; }
auto gbuffer() const noexcept -> auto& { return *_gbuffer; }
auto global_uniforms() const noexcept -> auto& { return _global_uniforms; }
auto global_uniforms_layout() const noexcept { return *_global_uniform_descriptor_set_layout; }
auto asset_manager() noexcept -> auto& { return _factory->_assets; }
auto device() noexcept -> auto& { return *_factory->_device; }
auto window() noexcept -> auto& { return _factory->_window; }
auto swapchain() noexcept -> auto& { return _factory->_swapchain; }
auto queue_family() const noexcept { return _factory->_draw_queue_family; }
auto compute_queue_family() const noexcept { return _factory->_compute_queue_family; }
auto compute_queue() const noexcept { return _factory->compute_queue(); }
auto create_compute_command_buffer() { return _factory->create_compute_command_buffer(); }
auto create_descriptor_set(vk::DescriptorSetLayout, std::int32_t bindings) -> graphic::DescriptorSet;
auto descriptor_pool() noexcept -> auto& { return _descriptor_set_pool; }
auto noise_descriptor_set_layout() const noexcept { return *_noise_descriptor_set_layout; }
auto noise_descriptor_set() const noexcept { return *_noise_descriptor_set; }
auto model_material_sampler() const noexcept { return _factory->model_material_sampler(); }
auto model_descriptor_set_layout() const noexcept { return _factory->model_descriptor_set_layout(); }
auto active_camera() noexcept -> util::maybe<Camera_state&>;
auto settings() const -> auto& { return _factory->settings(); }
void save_settings() { _factory->save_settings(); }
void settings(const Renderer_settings& s, bool apply = true) { _factory->settings(s, apply); }
void debug_draw(const std::vector<Debug_geometry>& lines)
{
if(_factory->settings().debug_geometry) {
auto& queue = _frame_data.debug_geometry_queue;
queue.insert(queue.end(), lines.begin(), lines.end());
}
}
auto profiler() const noexcept -> auto& { return _profiler; }
auto profiler() noexcept -> auto& { return _profiler; }
private:
friend class Deferred_renderer_factory;
Engine* _engine;
Deferred_renderer_factory* _factory;
ecs::Entity_manager* _entity_manager;
graphic::Descriptor_pool _descriptor_set_pool;
std::unique_ptr<GBuffer> _gbuffer;
Global_uniforms _global_uniforms;
graphic::Profiler _profiler;
float _time_acc = 0.f;
float _delta_time = 0.f;
std::uint32_t _frame_counter = 0;
vk::UniqueDescriptorSetLayout _global_uniform_descriptor_set_layout;
graphic::DescriptorSet _global_uniform_descriptor_set;
graphic::Dynamic_buffer _global_uniform_buffer;
graphic::Texture_ptr _blue_noise;
vk::UniqueSampler _noise_sampler;
graphic::Image_descriptor_set_layout _noise_descriptor_set_layout;
graphic::DescriptorSet _noise_descriptor_set;
std::vector<std::unique_ptr<Render_pass>> _passes;
Camera_comp::Pool* _cameras;
util::maybe<Camera_state> _active_camera;
Frame_data _frame_data;
void _write_global_uniform_descriptor_set();
void _update_global_uniforms(vk::CommandBuffer, const Camera_state& camera);
};
} // namespace mirrage::renderer
|
e0280ad1fa83c3d8b322d5f2deed084896efb8ee | 83eb8c1622bfed03395c8d11cfd12bb17ab98fac | /Codebase/NYUCodebase/AppDelegate.h | 07f26525d61ea53b44e2fe6aaec4399b9f9b3a21 | [] | no_license | sz830/ProjectDayandNight | bdfbb6535131de9befa6104cb145e07b22abd43d | 5c19f0ce90e386d4df37cf20b77b7ade7fe3ab42 | refs/heads/master | 2016-09-05T17:59:57.803882 | 2015-01-31T21:48:22 | 2015-01-31T21:48:22 | 28,732,545 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,147 | h | AppDelegate.h | #pragma once
#include "SDL\SDL.h"
#include "SDL\SDL_opengl.h"
#include "SDL\SDL_image.h"
#include <cmath>
#include <vector>
#include <string>
using namespace std;
GLuint LoadTexture(const char *image_path) {
SDL_Surface *surface = IMG_Load(image_path);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, 4, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surface);
return textureID;
}
class AppDelegate {
public:
bool done;
float lastTicks;
SDL_Window* displayWindow;
SDL_Event event;
int level; //0=day 1
Player * player;
//Worlds
World * testWorld;
//Textures
GLuint terrainID;
GLuint playerID;
GLuint fontID;
//Engine
Engine *e;
AppDelegate();
~AppDelegate();
void Init();
bool UpdateAndRender();
void Update(float elapsed);
void Render();
void InitLevel1();
void UpdateLevel1(float elapsed);
};
AppDelegate::AppDelegate(){
Init();
done = false;
lastTicks = (float)SDL_GetTicks() / 1000.0f;;
}
AppDelegate::~AppDelegate() {
SDL_Quit();
}
bool AppDelegate::UpdateAndRender(){
float ticks = (float)SDL_GetTicks() / 1000.0f;
float elapsed = ticks - lastTicks;
lastTicks = ticks;
Update(elapsed);
Render();
return done;
}
void AppDelegate::Init(){ // Load all textures and Worlds
SDL_Init(SDL_INIT_VIDEO);
displayWindow = SDL_CreateWindow("Project Day and Night", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, viewPortX, viewPortY, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
SDL_GL_MakeCurrent(displayWindow, context);
glClearColor(0.3f, .3f, .3f, 1.0f);
//Setup
glViewport(0, 0, viewPortX, viewPortY);
glMatrixMode(GL_PROJECTION);
glOrtho(-1., 1., -yTox, yTox, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
//Textures
terrainID = LoadTexture("pngs/testTerrain.png");
playerID = LoadTexture("pngs/madotsuki.png");
fontID = LoadTexture("pngs/font.png");
//Player
player = new Player(5, 5, playerID, "Mary");
//Worlds - Some people call these maps
vector<int> solids = { 7, 8, 9, 13, 14, 18, 20, 22, 31, 33, 34, 35, 36, 61, 62, 65, 66, 67, 78, 80, 91, 92, 93 };
testWorld = new World("maps/testWorld.txt", 13, 8, terrainID, solids);
//Engine
e = new Engine(fontID);
InitLevel1();
}
void AppDelegate::Update(float elapsed){
switch (level) {
case 1:
UpdateLevel1(elapsed);
break;
}
}
void AppDelegate::Render(){
glDepthMask(GL_TRUE);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-player->position->x,-player->position->y,0); // Camera follows Player
e->Render();
glDepthMask(GL_FALSE);
SDL_GL_SwapWindow(displayWindow);
}
void AppDelegate::InitLevel1(){
level = 1;
e = new Engine();
e->world = testWorld;
//Modify and Add Player
e->player = player;
//Create and add NPC's
NPC *npc1 = new NPC(7, 7, playerID, "Luke"); // uses playerID because there is no npcID yet
e->addNPC(npc1);
NPC *npc2 = new NPC(7, 12, playerID, "Johnny"); // uses playerID because there is no npcID yet
e->addNPC(npc2);
NPC *npc3 = new NPC(12, 7, playerID, "Ron"); // uses playerID because there is no npcID yet
e->addNPC(npc3);
NPC *npc4 = new NPC(12, 12, playerID, "Abe"); // uses playerID because there is no npcID yet
e->addNPC(npc4);
//Create and add Entities
}
void AppDelegate::UpdateLevel1(float elapsed){
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
done = true;
}
else if (event.type == SDL_KEYDOWN){
if (event.key.keysym.scancode == SDL_SCANCODE_Z) {
//Player interact action
}
}
}
const Uint8 *keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_UP]) {
e->moveUp();
}
else if (keys[SDL_SCANCODE_DOWN]) {
e->moveDown();
}
else if (keys[SDL_SCANCODE_LEFT]) {
e->moveLeft();
}
else if (keys[SDL_SCANCODE_RIGHT]) {
e->moveRight();
}
else {
e->noMove();
}
e->Update(elapsed);
} |
883855a2901dd107f3f9274be833b0e828fcf161 | f20e965e19b749e84281cb35baea6787f815f777 | /Online/Online/GaudiOnline/GaudiOnline/GaudiDeamon.h | 642860917abf52e8c9c6c94039641743c10bf12e | [] | no_license | marromlam/lhcb-software | f677abc9c6a27aa82a9b68c062eab587e6883906 | f3a80ecab090d9ec1b33e12b987d3d743884dc24 | refs/heads/master | 2020-12-23T15:26:01.606128 | 2016-04-08T15:48:59 | 2016-04-08T15:48:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | h | GaudiDeamon.h | #ifndef ONLINEKERNEL_GAUDIDEAMON_H
#define ONLINEKERNEL_GAUDIDEAMON_H
// Framework includes
#include "GaudiOnline/DimTaskFSM.h"
// Forward declarations
class IAppMgrUI;
/*
* LHCb namespace declaration
*/
namespace LHCb {
/** @class GaudiDeamon GaudiDeamon.h GaudiOnline/GaudiDeamon.h
*
*
* @author M.Frank
* @version 1.0
*/
class GaudiDeamon : public DimTaskFSM {
protected:
/// Main appliation manager object
IAppMgrUI* m_appMgr;
/// Property: name of runable object
std::string m_runable;
/// Property: name of event loop object
std::string m_evtloop;
/// Property: name of message service object
std::string m_msgsvcType;
/// Property: main jonb options
std::string m_mainOptions;
public:
GaudiDeamon(IInterface*);
virtual ~GaudiDeamon();
/// Run the complete job (from intialize to terminate)
virtual StatusCode run();
virtual StatusCode unload();
};
}
#endif // ONLINEKERNEL_GAUDIDEAMON_H
|
c313ff91d04d524c59f926a3271a47bcdd44cfdc | 992da250b3efd00b1b3bb2906236999bb89a5320 | /src/shader_utils.hpp | 66973d1fe9ffafda1c8d22bb2a0b706cd65bc05c | [] | no_license | nyamadan/ray_tracing | 1d083f9493d92408f00d210a0ca5d66c60d78eee | b6d251d5e19354bd656adb219d90c1f7e3b2dfbf | refs/heads/master | 2020-04-14T21:05:38.250274 | 2019-03-29T12:00:00 | 2019-03-31T14:47:32 | 164,117,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | hpp | shader_utils.hpp | #pragma once
extern const char* const GlslVersion;
int checkLinked(unsigned int program);
int checkCompiled(unsigned int shader);
|
deb452c957ae3422c017b29837b75fff53074a5e | 996821af70308e331be46805212dc2f017df3608 | /advent2016-tests/GoodIPFinderTests.cpp | 1037c5a63aa9fd9fabcf38fd65de4fa5d5a2be0f | [] | no_license | garyah/advent-of-code | 1afe815b978e8503999cd85dc3bf8e03245b52b9 | b2db187e63332ce2575a814ca03f5acdc0134aa7 | refs/heads/master | 2023-01-11T21:01:48.470568 | 2020-01-07T06:46:30 | 2020-01-07T06:46:30 | 159,916,129 | 0 | 0 | null | 2019-11-28T19:28:12 | 2018-12-01T06:28:32 | C++ | UTF-8 | C++ | false | false | 2,644 | cpp | GoodIPFinderTests.cpp | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../advent2016/GoodIPFinder.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Advent2016;
namespace advent2016tests
{
TEST_CLASS(GoodIPFinderTests)
{
public:
TEST_METHOD(TestMethod20a1)
{
GoodIPFinder finder;
finder.addBlacklistRule("5-8");
finder.addBlacklistRule("0-2");
finder.addBlacklistRule("4-7");
finder.findFirstGoodIP();
Assert::AreEqual((float)3, (float)finder.getFirstGoodIP(), 0.f);
}
TEST_METHOD(GapAtStart)
{
GoodIPFinder finder;
finder.addBlacklistRule("5-4294967295");
finder.findFirstGoodIP();
finder.findGoodIPCount();
Assert::AreEqual((float)0, (float)finder.getFirstGoodIP(), 0.f);
Assert::AreEqual((float)5, (float)finder.getGoodIPCount(), 0.f);
}
TEST_METHOD(GapMiddle)
{
GoodIPFinder finder;
finder.addBlacklistRule("0-4");
finder.addBlacklistRule("4294967291-4294967295");
finder.findFirstGoodIP();
finder.findGoodIPCount();
Assert::AreEqual((float)5, (float)finder.getFirstGoodIP(), 0.f);
Assert::AreEqual((float)4294967285, (float)finder.getGoodIPCount(), 0.f);
}
TEST_METHOD(GapAtEnd)
{
GoodIPFinder finder;
finder.addBlacklistRule("0-4294967290");
finder.findFirstGoodIP();
finder.findGoodIPCount();
Assert::AreEqual((float)4294967291, (float)finder.getFirstGoodIP(), 0.f);
Assert::AreEqual((float)5, (float)finder.getGoodIPCount(), 0.f);
}
TEST_METHOD(NoGapsSameAsAllGood)
{
GoodIPFinder finder;
finder.addBlacklistRule("0-4294967295");
finder.findFirstGoodIP();
finder.findGoodIPCount();
Assert::AreEqual((float)0, (float)finder.getFirstGoodIP(), 0.f);
Assert::AreEqual((float)0, (float)finder.getGoodIPCount(), 0.f);
}
TEST_METHOD(GapFollowingOneRangeInsideAnother)
{
GoodIPFinder finder;
finder.addBlacklistRule("0-9");
finder.addBlacklistRule("2-8");
finder.addBlacklistRule("20-4294967295");
finder.findFirstGoodIP();
finder.findGoodIPCount();
Assert::AreEqual((float)10, (float)finder.getFirstGoodIP(), 0.f);
Assert::AreEqual((float)10, (float)finder.getGoodIPCount(), 0.f);
}
};
}
|
98f08ad047de94f6a7797d6adb013d66e9784010 | 5ed9ea2b2932115b0dde88f0fbb48976468ac2fc | /include/VrsObs/VrsNtripClient.h | deaac97257840d94dac5c93b371adf31422278d6 | [] | no_license | DoubleString/RtConverter | 0c3312b1b80e36ac226bddf0fbee8cf22975d2d2 | 99d25b5a50e7acc0a1e062a56e940442fa54b93e | refs/heads/master | 2020-07-21T08:44:29.341815 | 2020-02-15T13:02:03 | 2020-02-15T13:02:03 | 240,712,186 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 925 | h | VrsNtripClient.h | #ifndef VRSNTRIPCLIENT_H_
#define VRSNTRIPCLIENT_H_
#include "../RtConverter/Deploy.h"
#include "../RtConverter/RtConverter.h"
#include "../Rtklib/rtklib_fun.h"
#include <list>
#include <map>
using namespace std;
namespace bamboo {
class VrsNtripClient {
public:
~VrsNtripClient();
void openStream();
void openStream(list<RtConverter*>);
protected:
#ifdef _WIN32
static DWORD WINAPI s_pthVrsStream_win(LPVOID lp);
#endif
RtConvItem m_makeupItems(string,rtcm_t*);
static void* s_pthVrsStream(void*);
void m_routine();
void m_sendGGAReq(stream_t*,VrsStaItem&);
void m_adaptConfigures();
void m_newConnection(VrsStaItem&);
void m_deleteConnection(string staname);
bool lcont;
time_t lastCheck;
Deploy configs_sav;
list<RtConverter*> m_svrs;
map<string, stream_t*> m_streams;
map<string, rtcm_t*> m_rtcms;
map<string, VrsStaItem> m_stas;
};
}
#endif |
2a65080b19949cecea47900b3e139ca0abf6470d | ff7f1e48dfb6ad052871b75d3f484ec94de2fe17 | /coroutine_examples/task.hpp | 096966483575a6b126c0c1eca520970ca2bbef68 | [] | no_license | srinitude/llvm | 88a96599ec8f865345a6b2a6da529823754f8cf9 | 9f59dcce9b65c57a438cdda064f5a00899e18dec | refs/heads/master | 2020-06-11T01:00:51.625328 | 2019-06-21T00:30:06 | 2019-06-22T00:19:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,773 | hpp | task.hpp | #pragma once
#include <experimental/coroutine>
#include <type_traits>
#include <utility>
#include "manual_lifetime.hpp"
template<typename T>
class task;
template<typename T>
class task_promise {
public:
task_promise() noexcept {}
~task_promise() {
clear();
}
task<T> get_return_object() noexcept;
std::experimental::suspend_always initial_suspend() {
return {};
}
auto final_suspend() noexcept {
struct awaiter {
bool await_ready() noexcept { return false; }
auto await_suspend(std::experimental::coroutine_handle<task_promise> h) noexcept {
return h.promise().continuation_;
}
void await_resume() noexcept {}
};
return awaiter{};
}
template<
typename U,
std::enable_if_t<std::is_convertible_v<U, T>, int> = 0>
void return_value(U&& value) {
clear();
value_.construct((U&&)value);
state_ = state_t::value;
}
void unhandled_exception() noexcept {
clear();
error_.construct(std::current_exception());
state_ = state_t::error;
}
T get() {
if (state_ == state_t::error) {
std::rethrow_exception(std::move(error_).get());
}
return std::move(value_).get();
}
private:
friend class task<T>;
void clear() noexcept {
switch (std::exchange(state_, state_t::empty)) {
case state_t::empty: break;
case state_t::error: error_.destruct(); break;
case state_t::value: value_.destruct(); break;
}
}
std::experimental::coroutine_handle<> continuation_;
enum class state_t { empty, value, error };
state_t state_ = state_t::empty;
union {
manual_lifetime<T> value_;
manual_lifetime<std::exception_ptr> error_;
};
};
template<>
class task_promise<void> {
public:
task_promise() noexcept {}
~task_promise() {
clear();
}
task<void> get_return_object() noexcept;
std::experimental::suspend_always initial_suspend() {
return {};
}
auto final_suspend() {
struct awaiter {
bool await_ready() { return false; }
auto await_suspend(std::experimental::coroutine_handle<task_promise> h) {
return h.promise().continuation_;
}
void await_resume() {}
};
return awaiter{};
}
void return_void() {
clear();
value_.construct();
state_ = state_t::value;
}
void unhandled_exception() noexcept {
clear();
error_.construct(std::current_exception());
state_ = state_t::error;
}
void get() {
if (state_ == state_t::error) {
std::rethrow_exception(std::move(error_).get());
}
}
private:
friend class task<void>;
void clear() noexcept {
switch (std::exchange(state_, state_t::empty)) {
case state_t::empty: break;
case state_t::error: error_.destruct(); break;
case state_t::value: value_.destruct(); break;
}
}
std::experimental::coroutine_handle<> continuation_;
enum class state_t { empty, value, error };
state_t state_ = state_t::empty;
union {
manual_lifetime<void> value_;
manual_lifetime<std::exception_ptr> error_;
};
};
template<typename T>
class task {
public:
using promise_type = task_promise<T>;
using handle_t = std::experimental::coroutine_handle<promise_type>;
explicit task(handle_t h) noexcept
: coro_(h)
{}
task(task&& t) noexcept
: coro_(std::exchange(t.coro_, {}))
{}
~task() {
if (coro_) {
coro_.destroy();
}
}
auto operator co_await() && noexcept {
struct awaiter {
public:
explicit awaiter(handle_t coro) : coro_(coro) {}
bool await_ready() noexcept {
return false;
}
auto await_suspend(std::experimental::coroutine_handle<> h) noexcept {
coro_.promise().continuation_ = h;
return coro_;
}
T await_resume() {
return coro_.promise().get();
}
private:
handle_t coro_;
};
return awaiter{coro_};
}
private:
handle_t coro_;
};
template<typename T>
task<T> task_promise<T>::get_return_object() noexcept {
return task<T>{
std::experimental::coroutine_handle<task_promise<T>>::from_promise(*this)
};
}
inline
task<void> task_promise<void>::get_return_object() noexcept {
return task<void>{
std::experimental::coroutine_handle<task_promise<void>>::from_promise(*this)
};
} |
3c34016af5fd8bcc036d1955f14227b292151599 | 5db083de28ce3d342aeba75d23e3d40112c96bb0 | /FinalFinalDB/FinalDB/player.h | cbe9c13ff22805184ada7cf91ee2e8a78e7b7048 | [] | no_license | ciclop03/FinalFinalStatement | bcb65f044a11203dacdbc3b2e7fb5b530b0722a5 | d49b6517a2be78fb504237f2cd437385e985a9ff | refs/heads/master | 2020-06-03T05:20:43.008464 | 2019-06-28T12:21:38 | 2019-06-28T12:21:38 | 191,457,918 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 796 | h | player.h | #ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include "person.h"
#include "dynarray.h"
using namespace std;
class Player : public Person
{
//friend class PersonDynArray;
public:
Player();
Player(std::string name, std::string lastname, std::string country, std::string gender, int age,
std::string nick, int wins, int looses,int top8s, int cpt_points);
//:Person(name,lastname,country, gender,age){};
void talk()
{
cout <<"i am player"<< endl;
}
void showdata();
virtual ~Player();
std::string getNick() const;
void setNick(const std::string &value);
protected:
std::string nick;
int wins, looses, top8s, cpt_points;
private:
};
#endif // PLAYER_H
|
8b0586fdc34f516edf47cacd1f414f9dc19ddc1b | 838cb4d679aa96239be04e50d2f631e81e15c4b9 | /Partition Array.cpp | 2f0abee0970b0ae44658cf119ad23196dd385204 | [] | no_license | supermarkion/LintCode | 09bf4fd02c3254c2ff4c42e07bb2930c0ab662bf | 97021364313677d3523f785cab5ead035493f000 | refs/heads/master | 2020-12-20T22:14:41.654330 | 2016-10-16T00:24:50 | 2016-10-16T00:24:50 | 47,730,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | Partition Array.cpp | /*
Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:
All elements < k are moved to the left
All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
Link: http://www.lintcode.com/en/problem/partition-array/
Example: If nums = [3,2,2,1] and k=2, a valid answer is 1.
Solution: None
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/partition-array.cpp
*/
class Solution {
public:
int partitionArray(vector<int> &nums, int k) {
// write your code here
int left = 0;
int right = nums.size();
while (left < right) {
if (nums[left] < k) { // Increase left boundary.
++left;
} else { // Put every element > k to the right.
swap(nums[left], nums[--right]);
}
}
return left;
}
}; |
0414173b10d1a6360c71a91227b6bbef67dc4a7f | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/tools/3dsMax/exportAnim/IGameExporter.h | a1e5f44ddbd677655ab18f94da651164d747fcbf | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,146 | h | IGameExporter.h |
#ifndef __GAME_EXPORTER_H
#define __GAME_EXPORTER_H
#include "globals.h"
#include "decomp.h"
#include <IGame.h>
#include <IGameObject.h>
#include <IGameProperty.h>
#include <IGameControl.h>
#include <IGameModifier.h>
#include <IConversionManager.h>
#include <IGameError.h>
#include "AnimData.h"
struct SExportOptions {
public:
enum { OPTIONS_VERSION = 20040730 };
public:
SExportOptions()
: mUnitMultiplier(0.001f),
mFramesPerSample(1),
mTolPos(0.001f), mTolRot(0.001f), mTolScale(0.01f),
mLooping(1), mDiscardLastSample(0),
mDoPos(1), mDoRot(1), mDoScale(0), mDoCamera(0), mDoColor(0),
mDoLeafs(0), mDoRoots(1), mStripBipFromBones(1),
mScaleScalar(0), mFlt16Rot(0), mFlt16Scale(0)
{
}
public:
// Multiply units from Max with this.
float mUnitMultiplier;
// Sampling rate
int mFramesPerSample;
// Collapse tolerances
float mTolPos, mTolRot, mTolScale;
// General params
int mLooping;
int mDiscardLastSample;
// Filter
int mDoPos, mDoRot, mDoScale, mDoCamera, mDoColor;
int mDoLeafs, mDoRoots;
int mStripBipFromBones;
// Components options
int mScaleScalar; // collapse scale into single float?
int mFlt16Rot, mFlt16Scale; // rotation/scale - use 16 bit floats?
};
class IGameExporter : public SceneExport {
public:
IGameExporter();
virtual ~IGameExporter();
// SceneExport interface from 3dsMax SDK
virtual int ExtCount(); // Number of extensions supported
virtual const TCHAR* Ext(int n); // Extension #n (i.e. "3DS")
virtual const TCHAR* LongDesc(); // Long ASCII description (i.e. "Autodesk 3D Studio File")
virtual const TCHAR* ShortDesc(); // Short ASCII description (i.e. "3D Studio")
virtual const TCHAR* AuthorName(); // ASCII Author name
virtual const TCHAR* CopyrightMessage(); // ASCII Copyright message
virtual const TCHAR* OtherMessage1(); // Other message #1
virtual const TCHAR* OtherMessage2(); // Other message #2
virtual unsigned int Version(); // Version number * 100 (i.e. v3.01 = 301)
virtual void ShowAbout(HWND hWnd); // Show DLL's "About..." box
virtual BOOL SupportsOptions(int ext, DWORD options);
virtual int DoExport(const TCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts=FALSE, DWORD options=0);
private:
void processNode( IGameNode* node );
void sampleAnim( IGameNode* node );
void dumpMatrix( const GMatrix& m );
void writeAllData();
void tryCollapseVec3( TVec3Tab& t, float tol );
void tryCollapseQuat( TQuatTab& t, float tol );
void tryCollapseFloat( TFloatTab& t, float tol );
void tryCollapseColor( TColorTab& t, float tol );
bool rejectName( const TSTR& name ) const;
BOOL readConfig();
void writeConfig();
TSTR getCfgFilename();
public:
static HWND hParams;
IGameScene* mGameScene;
FILE* mFile;
// export params
SExportOptions mOptions;
TSTR mNameMustStart;
TSTR mNameCantEnd;
int mCurrNodeProgress;
bool mShowPrompts;
bool mExportSelected;
TVec3AnimGroup mAnimPos;
TQuatAnimGroup mAnimRot;
TVec3AnimGroup mAnimScale;
TVec3AnimGroup mAnimCamera;
TColorAnimGroup mAnimColor;
TStringTab mAnimCurveNames;
TIntTab mAnimCurveIDs;
TIntTab mAnimCurveParents;
int mCurrCurve;
TVec3Tab mCurrCurvePos;
TQuatTab mCurrCurveRot;
TVec3Tab mCurrCurveScale;
TVec3Tab mCurrCurveCamera;
TColorTab mCurrCurveColor;
int mSampleCount;
};
#define IGAMEEXPORTER_CLASS_ID Class_ID(0x246817b6, 0x200c2eb9)
class IGameExporterClassDesc : public ClassDesc2 {
public:
int IsPublic() { return TRUE; }
void* Create(BOOL loading = FALSE) { return new IGameExporter(); }
const TCHAR * ClassName() { return GetString(IDS_CLASS_NAME); }
SClass_ID SuperClassID() { return SCENE_EXPORT_CLASS_ID; }
Class_ID ClassID() { return IGAMEEXPORTER_CLASS_ID; }
const TCHAR* Category() { return GetString(IDS_CATEGORY); }
const TCHAR* InternalName() { return _T("IMAnimExport"); } // returns fixed parsable name (scripter-visible name)
HINSTANCE HInstance() { return hInstance; } // returns owning module handle
};
#endif
|
b5f5677dbb5c40acbab4f0b31b9e7b96b147e0af | 4bfb329d8efa93b797a72cafe7f7f7d3cb8616a1 | /Teris_1/RecordDlg.cpp | 76492ba96d8753ae77081201fe8b9e49888e7ff9 | [] | no_license | dengyaolong/Teris | 517cd0bd254f8579ee1e1203e0c5335fb0955f81 | 01959bdc3fa7fd7f841b7d7239331c929faed76c | refs/heads/master | 2021-01-23T13:48:54.840212 | 2014-06-03T06:58:08 | 2014-06-03T06:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp | RecordDlg.cpp | // RecordDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Teris_1.h"
#include "RecordDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// RecordDlg dialog
RecordDlg::RecordDlg(CWnd* pParent /*=NULL*/)
: CDialog(RecordDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(RecordDlg)
m_Name = _T("");
//}}AFX_DATA_INIT
}
void RecordDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(RecordDlg)
DDX_Text(pDX, IDC_EDIT1, m_Name);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(RecordDlg, CDialog)
//{{AFX_MSG_MAP(RecordDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// RecordDlg message handlers
void RecordDlg::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}
|
78bd99ba430521b39a47dd2e7504bb7c1f663f2d | 38beb7397b822e4e509fa720292a95fded885cb2 | /Source/ShooterGame/Private/UI/Menu/Widgets/SShooterPanelWidget.h | a5abe4b0dae188aabe2bc546ee1f00d9bfda0d29 | [] | no_license | yw-dev/ASSGame | e8d13d3ab43765ce3e2934806a95da7e05d2d3d7 | bb4782996099e7f1422cad91b44692ecbe8acabd | refs/heads/master | 2023-01-30T07:34:04.749696 | 2020-11-30T10:31:16 | 2020-11-30T10:31:16 | 269,843,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | h | SShooterPanelWidget.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Slate.h"
class SShooterPanelWidget : public SCompoundWidget
{
public:
// Sets default values for this actor's properties
SShooterPanelWidget();
};
|
c9d04620ca22f5063925ad04952d9ea8cd4d9cb7 | 899e293884d1ed1896414d46e3b46a1a9bfdc490 | /ACM/2016tour/newTech/CGtemplate_POORE/problems/poj3608.cpp | 8049cd605da4def85ee6c5f6e4965dc0dff9b808 | [] | no_license | py100/University | d936dd071cca6c7db83551f15a952ffce2f4764c | 45906ae95c22597b834aaf153730196541b45e06 | refs/heads/master | 2021-06-09T05:49:23.656824 | 2016-10-27T08:22:52 | 2016-10-27T08:22:52 | 53,556,979 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,975 | cpp | poj3608.cpp | #include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
const int maxn = 1e4+20;
const double eps = 1e-6;
int dcmp(double x)
{
if (fabs(x) < eps) return 0;
return x < 0 ? -1:1;
}
struct point {
double x,y;
point(double x, double y):x(x),y(y){}
point(){}
}p[maxn], p1[maxn];
typedef point Point;
double operator * (point a, point b) {
return a.x*b.x + a.y*b.y;
}
double operator ^ (point a, point b) {
return a.x*b.y - a.y*b.x;
}
point operator + (point a, point b) {
return point (a.x+b.x, a.y+b.y);
}
point operator - (point a, point b) {
return point (a.x-b.x, a.y-b.y);
}
bool cmpxy(point a, point b) {
if (dcmp(a.x -b.x)==0) return dcmp(a.y-b.y)<0;
return dcmp(a.x-b.x)<0;
}
void show(Point p) {
printf("(%.2f, %.2f)\n", p.x, p.y);
}
double linePointDist(Point A, Point B, Point C, bool isSeg) {
/*
cout << "--------" << endl;
show(A);
show(B);
show(C);
*/
double dist = ((B-A)^(C-A)) / sqrt((B-A)*(B-A));
if (isSeg) {
double dot1 = (C-B)*(B-A);
if (dot1 > 0) return sqrt((B-C)*(B-C));
double dot2 = (C-A)*(A-B);
if (dot2 > 0) return sqrt((A-C)*(A-C));
}
return fabs(dist);
}
// s 为保存有序的凸包点的下标的栈
double rotatingCaliper(Point *p, Point *p1, int n, int m, int *s, int *s1) {
int q = 1;
double ans = 1e18;
s[n] = s1[m] = 0;
for (int i = 0; i < n; i++)
{
while( dcmp(((p[s[i+1]]-p[s[i]])^(p1[s1[q]]-p1[s1[q+1]]))) < 0)
{
//cout <<q << endl;
q = (q+1)%m;
}
/*
while( ((p[s[i+1]]-p[s[i]])^(p1[s1[q+1]]-p[s[i]])) <
((p[s[i+1]]-p[s[i]])^(p1[s1[q]] -p[s[i]])) )
q = (q+1)%m;
while( ((p[s[i+1]]-p[s[i]])^(p1[s1[(q-1+m)%m]]-p[s[i]])) <
((p[s[i+1]]-p[s[i]])^(p1[s1[q]] -p[s[i]])) )
q = (q-1+m)%m;
*/
//cout << linePointDist(p[s[i]], p[s[i+1]], p1[s1[q]], true) << endl;
//cout << linePointDist(p[s[i]], p[s[i+1]], p1[s1[q+1]], true) << endl;
ans = min(ans, linePointDist(p[s[i]], p[s[i+1]], p1[s1[q]], true));
ans = min(ans, linePointDist(p[s[i]], p[s[i+1]], p1[s1[q+1]], true));
//ans = min(ans, linePointDist(p[s[i]], p[s[i+1]], p1[s1[(q-1+m)%m]], true));
//ans = min(ans, linePointDist(p[s[i]], p[s[(i-1+n)%n]], p1[s1[q]], true));
//ans = min(ans, linePointDist(p[s[i]], p[s[(i-1+n)%n]], p1[s1[q+1]], true));
//ans = min(ans, linePointDist(p[s[i]], p[s[(i-1+n)%n]], p1[s1[(q-1+m)%m]], true));
//ans = min(ans, linePointDist(p[s[i]], p[s[(i-1+n)%n]], p1[s1[q]], true));
}
//cout << ans << endl;
return ans;
/*
int q = 1;
int ans = 0;
s[top] = 0;
for (int i = 0; i < top; i++)
{
while( ((p[s[i+1]]-p[s[i]])^(p[s[q+1]]-p[s[i]])) >
((p[s[i+1]]-p[s[i]])^(p[s[q]] -p[s[i]])) )
q = (q+1)%top;
ans = max(ans, (p[s[i]]-p[s[q]])*(p[s[i]]-p[s[q]]));
ans = max(ans, (p[s[i+1]]-p[s[q+1]])*(p[s[i+1]]-p[s[q+1]]));
}
return ans;
*/
}
int s1[maxn], s2[maxn];
// 包含边上的点就将 <= 改为 <
int convexHull(Point *p, int n, int *s) {
sort(p, p + n, cmpxy);
int top = 0;
for (int i = 0; i < n; i++) {
while(top>1 && dcmp(((p[s[top-1]]-p[s[top-2]])^(p[i]-p[s[top-2]]))) <= 0) top--;
s[top++] = i;
}
int k = top;
for (int i=n-2;i>=0;i--) {
while(top>k && dcmp(((p[s[top-1]]-p[s[top-2]])^(p[i]-p[s[top-2]]))) <= 0) top--;
s[top++] = i;
}
if (n > 1) top--;
return top;
}
int main()
{
#ifndef ONLINE_JUDGE
//freopen("data.in", "r", stdin);
//freopen("test.out", "w", stdout);
#endif
int n, m;
while(scanf("%d%d", &n, &m) == 2)
{
if (n==0 && m==0) break;
for (int i = 0; i < n; i++)
scanf("%lf%lf", &p[i].x, &p[i].y);
for (int i = 0; i < m; i++)
scanf("%lf%lf", &p1[i].x, &p1[i].y);
n = convexHull(p, n, s1);
m = convexHull(p1, m, s2);
printf("%.5f\n", min(rotatingCaliper(p, p1, n, m, s1, s2),
rotatingCaliper(p1, p, m, n, s2, s1)));
}
return 0;
}
|
e3758d13df0a28b53fe6efafedbec5a9091eb75b | 2662ee11fd9bb87d7e4178bb8a8e9a4fd8e919ad | /Linux/P_3/dev_P3/src/store.cpp | 5177df3b13c4d12d5d3b519e12c955d35c7899b3 | [] | no_license | gykim77/class_project | a0bfe4be1a68b4b8b11b5689097602c290aebf01 | 25fd1a37453e41c044d726069f5cdc8d261a18bc | refs/heads/main | 2023-01-30T10:17:02.999124 | 2020-11-24T10:06:15 | 2020-11-24T10:06:15 | 315,591,394 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,428 | cpp | store.cpp | #include "store.h"
Store::Store(){
Ingredient i_water("water", 2, 1000);
Ingredient i_bean("beans", 1, 2000);
_ingredient_v.push_back(i_water);
_ingredient_v.push_back(i_bean);
req_t req;
Coffee c_americano("Americano", 5000);
req.ingredient = i_water;
req.amount = 1;
c_americano.setRequirement(req);
req.ingredient = i_bean;
req.amount = 1;
c_americano.setRequirement(req);
Coffee c_water("Water", 2000);
req.ingredient = i_water;
req.amount = 1;
c_water.setRequirement(req);
_coffee_v.push_back(c_americano);
_coffee_v.push_back(c_water);
_sales = 0;
}
std::string Store::makeMenu(){
std::string menu("***menu***\n");
int cnt = 0;
for (int i=0;i<_coffee_v.size();i++){
Coffee c = _coffee_v[i];
if (isAvailable(c)){
menu += std::to_string(++cnt);
menu += (". " + c.getName());
menu += (":\t\tprice: " + std::to_string(c.getPrice()));
menu += "\n";
}
}
menu+="****************";
return menu;
}
bool Store::isAvailable(const Coffee& c){
for (int i=0;i<c._required_ingredient_v.size();i++){
req_t req = c._required_ingredient_v[i];
for (int j=0;j<_ingredient_v.size();j++){
Ingredient ingre = _ingredient_v[j];
if (req.ingredient.getName()==ingre.getName()){
if (req.amount > ingre.getAmount()){
return 0;
}
}
}
}
return 1;
}
int Store::take_order(std::string coffee){
for (int i=0;i<_coffee_v.size();i++){
Coffee c = _coffee_v[i];
if (coffee==c.getName()){
_sales += c.getPrice();
for (int j=0;j<c._required_ingredient_v.size();j++){
req_t req_i = c._required_ingredient_v[j];
for (int k=0;k<_ingredient_v.size();k++){
Ingredient ingredient = _ingredient_v[k];
if (req_i.ingredient.getName()==ingredient.getName()){
_ingredient_v[k].dec(req_i.amount);
}
}
}
break;
}
}
}
void Store::printAllIngredients(){
std::cout<<"Remaining Ingredients"<<std::endl;
for (int i=0;i<_ingredient_v.size();i++){
std::cout<<_ingredient_v[i].getName()<<": "<<_ingredient_v[i].getAmount()<<std::endl;
}
} |
3567c1282f62c4d7953347c2b1b6387fb036e355 | 38774bbe5122c4a4328f9a5e6e9f53e8e9b54df9 | /misc/btreetools.cpp | 1090c8c3843723f6e69599788983cf49c4f76dcd | [] | no_license | Malows/aedcode | b2964985712e4f21cc701545bb341a942e97cd55 | 1b9dc6160b989a7699e8d48049ca6ffb78b24de4 | refs/heads/master | 2021-01-18T11:01:32.422219 | 2011-10-22T00:57:05 | 2011-10-22T00:57:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,509 | cpp | btreetools.cpp | // -*- mode: c++ -*-
//__INSERT_LICENSE__
// $Id: btreetools.cpp,v 1.3 2004/04/25 21:37:33 mstorti Exp $
#include <vector>
#include <aedsrc/util.h>
#include <aedsrc/btreetools.h>
namespace aed {
//---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:
void make_random_btree(btree<int> &T,btree<int>::iterator n,
int M,int level,double siblings) {
n = T.insert(n,irand(M));
double lambda = 1.0/(siblings/double(level)+1.0);
for (int j=0; j<2; j++) {
btree<int>::iterator c = (j==0 ? n.left() : n.right());
if (drand()>lambda) make_random_btree(T,c,M,level+1,siblings);
}
}
void make_random_btree(btree<int> &T,int M,double siblings) {
T.clear();
make_random_btree(T,T.begin(),M,0,siblings);
}
//---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:
void
node_level_stat(btree<int> &T,btree<int>::iterator n,
int level,vector<int> &nod_lev) {
if (n==T.end()) return;
assert(nod_lev.size()>=level);
if (nod_lev.size()==level) nod_lev.push_back(0);
nod_lev[level]++;
node_level_stat(T,n.left(),level+1,nod_lev);
node_level_stat(T,n.right(),level+1,nod_lev);
}
//---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>---:
void node_level_stat(btree<int> &T,vector<int> &nod_lev) {
nod_lev.clear();
node_level_stat(T,T.begin(),0,nod_lev);
cout << "level/#nodes: ";
for (int j=0;j<nod_lev.size();j++)
cout << j << "/" << nod_lev[j] << ", ";
cout << endl;
}
}
|
a822bdc8ec9eef317d624adf08e4b4035c5a4df8 | 7747f00286d55230f1aa8b88bc57127406213bf1 | /source/plugin/include/hypha/plugin/pluginutil.h | 581f8ae0c61b9fb0060347c0b1bde9f307952f25 | [
"MIT"
] | permissive | hyphaproject/hypha | 80b4714b7311bf5f546380b776c8cca2e1d3fe6a | 2ab878529e859928dce0515c742368ad30a48dab | refs/heads/master | 2021-01-11T03:31:53.971350 | 2017-05-31T07:11:11 | 2017-05-31T07:11:11 | 68,947,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | h | pluginutil.h | // Copyright (c) 2017 Hypha
#pragma once
#include <hypha/plugin/hyphabaseplugin.h>
#include <hypha/plugin/plugin_api.h>
namespace hypha {
namespace plugin {
/**
* @brief The HyphaReceiver class
*/
class PLUGIN_API PluginUtil {
public:
/**
* @brief isHandler
* @param plugin The Plugin to test
* @return if plugin is instance of HyphaHandler
*/
static bool isHandler(HyphaBasePlugin* plugin);
/**
* @brief isActor
* @param plugin The Plugin to test
* @return if plugin is instance of HyphaActor
*/
static bool isActor(HyphaBasePlugin* plugin);
/**
* @brief isSensor
* @param plugin The Plugin to test
* @return if plugin is instance of HyphaSensor
*/
static bool isSensor(HyphaBasePlugin* plugin);
/**
* @brief isReceiver
* @param plugin The Plugin to test
* @return if plugin is instance of HyphaReceiver
*/
static bool isReceiver(HyphaBasePlugin* plugin);
/**
* @brief isSender
* @param plugin The Plugin to test
* @return if plugin is instance of HyphaSender
*/
static bool isSender(HyphaBasePlugin* plugin);
};
}
}
|
d65517509e8e79c9b9c02dce943707f9306fb5d6 | 9d5aa0a82ae26045a074e523aed47c92e3cca3eb | /euclide-console/source/includes.h | b4be6fe7757683584fbc50c56284fdae2988266c | [] | no_license | svart-riddare/euclide | 3a435ba0f800a96a5563aa585ab944291a451d1b | bc9a9c298c5a8d2b42b1b3dd7a5313ec7d3bea86 | refs/heads/master | 2021-11-17T20:17:49.108761 | 2021-07-11T13:01:57 | 2021-07-11T13:01:57 | 48,394,626 | 4 | 2 | null | 2021-03-20T08:35:08 | 2015-12-21T21:18:24 | C++ | UTF-8 | C++ | false | false | 1,541 | h | includes.h | #ifndef __INCLUDES_H
#define __INCLUDES_H
/* -------------------------------------------------------------------------- */
#include <cassert>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cwchar>
/* -------------------------------------------------------------------------- */
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
/* -------------------------------------------------------------------------- */
#ifdef _MSC_VER
#define EUCLIDE_WINDOWS
#endif
#ifdef EUCLIDE_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <crtdbg.h>
#include <conio.h>
#include <fcntl.h>
#include <io.h>
#undef min
#undef max
#else
#include <ncursesw/curses.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#endif
/* -------------------------------------------------------------------------- */
#define countof(array) std::extent<decltype(array)>::value
#define static_assert(expression) \
static_assert((expression), #expression)
/* -------------------------------------------------------------------------- */
#include "euclide.h"
/* -------------------------------------------------------------------------- */
#include "strings.h"
/* -------------------------------------------------------------------------- */
#endif
|
99b4154f0d46d1df0893edb6b25c4bbf1092c828 | cf833d4b6195e64e483685e4b0e21843c0eee659 | /DungeonBuilder.h | e86619475d96ff02ad3e1d733b2f07b1bb7f8d6f | [] | no_license | CyanBlob/CyanEngine | 26f65cb0e114ce86c7d36d179032556a72576b4d | f1e63e6ee99a11a4d645027ab66d222038097237 | refs/heads/master | 2021-09-11T16:26:04.704929 | 2018-01-20T03:38:41 | 2018-01-20T03:38:41 | 82,486,885 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | h | DungeonBuilder.h | class DungeonBuilder
{
public:
DungeonBuilder(){};
~DungeonBuilder(){};
static void buildRooms(int);
};
|
fc10cf6262acf12c864b590519e3cfede3b17808 | c25cf693b476b7a62752606047f725cda0947492 | /Utils.cpp | c30e955e87102179238fdbc2fb67145ce97a24f6 | [] | no_license | Kyubu-77/Matrix44 | ad7a7231219ff0fc6fb9d0fd456f1a11691ad7a9 | 579603d86539917c3c7c2653cacf124f22fc903b | refs/heads/master | 2020-03-09T00:18:15.887316 | 2018-04-12T22:27:27 | 2018-04-12T22:27:27 | 128,484,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | cpp | Utils.cpp | #include <avr\pgmspace.h>
#include "Utils.h"
uint16_t nextUInt16() {
return random(0xFFFF);
}
float nextFloat() {
return random(100000)/ 100000.0f;
}
float variance(float value, float variation_percent) {
float rndMinusOneToOne = (2 * nextFloat() - 1.0);
float variation_factor = 1 + variation_percent * rndMinusOneToOne;
return (float)(value * variation_factor); // if percent_variation = (0.5) 50% then factor will be between 0.5 and 1.5
}
// Debug output
// thx to http://www.utopiamechanicus.com/article/low-memory-serial-print/
void StreamPrint_progmem(Print &out, PGM_P format, ...)
{
// program memory version of printf - copy of format string and result share a buffer
// so as to avoid too much memory use
char formatString[128], *ptr;
strncpy_P(formatString, format, sizeof(formatString)); // copy in from program mem
// null terminate - leave last char since we might need it in worst case for result's \0
formatString[sizeof(formatString) - 2] = '\0';
ptr = &formatString[strlen(formatString) + 1]; // our result buffer...
va_list args;
va_start(args, format);
vsnprintf(ptr, sizeof(formatString) - 1 - strlen(formatString), formatString, args);
va_end(args);
formatString[sizeof(formatString) - 1] = '\0';
out.print(ptr);
}
|
00c78e47af2b50e670233e9fa5091cef54770e91 | 807df1d59c4051c2fa179de98ef9abf2aa7ea2b3 | /bachelor/year2/PSU/PSU_zappy_2017/src/clients/AI/ADrone.hpp | 2eb10555eaf22ac7c3b84e709682ebeaf3f21370 | [] | no_license | Petit-Pas/EpitechBachelor | 1624b9acbb1fa47342137469e5d735d971531b38 | 40244874e5cff14deb45cce0ce794d7249dcd852 | refs/heads/main | 2022-12-18T00:01:25.574204 | 2020-09-22T07:34:16 | 2020-09-22T07:34:16 | 296,012,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,974 | hpp | ADrone.hpp | //
// EPITECH PROJECT, 2018
// zappy
// File description:
// zappy IA definition of methods
//
#ifndef ADRONE_HPP_
#define ADRONE_HPP_
#include <map>
#include "ElementMap.hpp"
#include "Movement.hpp"
#include "Connection.hpp"
#include "ACommand.hpp"
class ACommand;
class ADrone
{
public:
ADrone(const std::string &, int, const std::string &);
ADrone(const std::shared_ptr<ADrone> &drone);
virtual ~ADrone() = default;
enum class Reality
{
REAL,
SUPPOSED
};
enum class State
{
IDLE = 0,
JOIN
};
/**
* simulate is the main loop of any ia,
* it calls the handleMessage if one was receive,
* execute the next command to be executed (in list of actions)
* then calls the findNextAction if there is space in the command list
*/
void simulate();
virtual void findNextAction() = 0;
void connect();
void setRemainingSlots(size_t);
/**
* set size of map
*/
void setSize(size_t, size_t);
void setMapTile(const Position &, const Tile &, Reality = Reality::REAL);
void setId(std::size_t);
void setMaxId(std::size_t);
void setInventory(Tile, Reality = Reality::REAL);
std::size_t getTotalTicks() const;
std::size_t getTotalCommands() const;
Position findBestSpot(const std::map<std::string, std::size_t> &, int) const;
std::map<std::string, Tile> tryWithHim(std::map<std::string, Tile>, std::pair<std::string, Tile> ) const;
std::map<std::string, Tile> addBuddies(std::map<std::string, Tile> , std::map<std::string, std::size_t> &) const;
std::vector<std::pair<std::string, Tile>> findIncantationBuddies(std::map<std::string, std::size_t> );
std::size_t usefulResourcesCount(const Tile &, const std::map<std::string, std::size_t> &) const;
Orientation &getOrientation(Reality = Reality::REAL);
int relativeToAbsoluteReception(int) const;
void addToInventory(const std::string &item, Reality reality = Reality::REAL);
void removeFromInventory(const std::string &item, Reality reality = Reality::REAL);
void editInventory(const std::string &item, size_t quantity, Reality reality = Reality::REAL);
void removeFromTile(const std::string &item, size_t quantity, Reality reality = Reality::REAL);
void removeFromTile(const std::string &item, Reality reality = Reality::REAL);
void addToTile(const std::string &item, Reality reality = Reality::REAL);
void addCommand(std::shared_ptr<ACommand>);
void move(Reality = Reality::REAL);
void addLevel();
void setObjectif(int);
void setState(State);
static Tile getInventoryFromParams(const std::string &);
/**
* getters
*/
const std::shared_ptr<Connection> getConnection() const;
const ElementMap &getMap(Reality = Reality::REAL) const;
ElementMap &getMap(Reality = Reality::REAL);
const std::string &getTeamName() const;
std::size_t getRemainingSlots() const;
const std::vector<std::shared_ptr<ACommand>> &getActions() const;
const Position &getPosition(Reality = Reality::REAL) const;
const Orientation &getDirection(Reality = Reality::REAL) const;
bool getSharedPosition() const;
const Tile &getInventory(Reality = Reality::REAL) const;
const std::unordered_map<std::string, Tile> &getCommonInventory() const;
std::size_t getLevel() const;
std::size_t getId() const;
std::size_t getGlobalId() const;
std::size_t getTicks() const;
State getState() const;
bool isConnected() const;
bool isDead() const;
private:
/**
* calls the handle server message on the list of actions until one return true
* if none return true, then the defaultMessage handling is called
*/
void handleServerMessage(const std::string &);
/**
* messages treated by the drones (common protocols)
*/
bool handleCommonsMessage(const std::string &);
/**
* called when a message is not attributed to any of the previous actions
*/
virtual void defaultMessageHandling(const std::string &);
/**
* call the execution of the next command
*/
virtual void executeCommand();
bool desiredDirection(int, std::size_t, std::size_t) const;
int getDist(std::size_t, int, std::size_t) const;
double distanceRatio(int, int, int) const;
static const int TILE_DEFAULT_VALUE = 30;
static const int MAX_DISTANCE_PRECISION_LOSS = 40;
static const int TILE_DISTANCE_PRECISION_LOSS = 5;
protected:
/**
* init the map of needed elements
*/
void initNeed();
protected:
std::shared_ptr<Connection> _com;
ElementMap _map;
ElementMap _supposedMap;
std::string _teamName;
std::size_t _remainingSlots;
Position _position;
Position _supposedPosition;
std::vector<std::shared_ptr<ACommand>> _actions;
std::queue<std::shared_ptr<ACommand>> _list;
Orientation _orientation;
Orientation _supposedOrientation;
int _objectif;
bool _sharedPosition;
Tile _inventory;
Tile _supposedInventory;
std::unordered_map<std::string, Tile> _commonInventory;
std::size_t _level;
std::size_t _id;
std::size_t _globalId;
std::size_t _ticks;
bool _connected;
bool _dead;
State _state;
std::map<std::string, size_t> _need;
};
#endif /* !ADRONE_HPP_ */
|
96b51e7b3f184a975d0bf71429a6284554881c1e | cbcedfec2347e395a13af8f5b910de9b74ea2b9c | /C++/1. Introduction/9. Variable Size Arrays/variable-sized-arrays-1.cpp | b26a027f103dbe5208f5912e01858d0c9fefd529 | [
"MIT"
] | permissive | princeofpython/HackerRank-Practice | ee4b9c05c011e180fb3d9f772340335ca62757d8 | 510bc4230c5f704eb61721d9f420f76cdabf0bd2 | refs/heads/master | 2022-04-16T00:59:04.904412 | 2020-04-15T16:58:21 | 2020-04-15T16:58:21 | 250,316,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | cpp | variable-sized-arrays-1.cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, q;
cin >> n >> q;
int** dp;
dp = new int*[n];
for(int i =0; i<n; i++)
{
int k;
cin >> k;
dp[i] = new int [k];
for (int j=0; j<k; j++)
{
int x;
cin >> x;
dp[i][j]= x;
}
}
for(int i = 0; i < q; ++i) {
int a, b;
cin >> a >> b;
cout << dp[a][b] << endl;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.