hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ff86a2e64d951722dc911e9b13622784d0d31d7 | 505 | cpp | C++ | MGR_PBR/src/Main.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | MGR_PBR/src/Main.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | MGR_PBR/src/Main.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "engine/Renderer.h"
#include "engine/Container.h"
#include "engine/Object.h"
#include "engine/Skybox.h"
#include "engine/render/Helpers.h"
#include "Stage.h"
#include "MilkyWayStage.h"
int main() {
CAT::Renderer renderer;
Stage stage;
renderer.AddChild(stage);
//MilkyWayStage milkyStage;
//renderer.AddChild(milkyStage);
renderer.StartMainLoop();
return 0;
} | 17.413793 | 34 | 0.726733 | [
"render",
"object"
] |
b00944e1bcc6b42a9eae7d9170fd402421a38d37 | 3,394 | cpp | C++ | src/compute_pair.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | 1 | 2018-11-28T15:04:55.000Z | 2018-11-28T15:04:55.000Z | src/compute_pair.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | null | null | null | src/compute_pair.cpp | luwei0917/GlpG_Nature_Communication | a7f4f8b526e633b158dc606050e8993d70734943 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include <mpi.h>
#include <string.h>
#include "compute_pair.h"
#include "update.h"
#include "force.h"
#include "pair.h"
#include "error.h"
using namespace LAMMPS_NS;
enum{EPAIR,EVDWL,ECOUL};
/* ---------------------------------------------------------------------- */
ComputePair::ComputePair(LAMMPS *lmp, int narg, char **arg) :
Compute(lmp, narg, arg),
pstyle(NULL), pair(NULL), one(NULL)
{
if (narg < 4 || narg > 5) error->all(FLERR,"Illegal compute pair command");
scalar_flag = 1;
extscalar = 1;
peflag = 1;
timeflag = 1;
int n = strlen(arg[3]) + 1;
if (lmp->suffix) n += strlen(lmp->suffix) + 1;
pstyle = new char[n];
strcpy(pstyle,arg[3]);
if (narg == 5) {
if (strcmp(arg[4],"epair") == 0) evalue = EPAIR;
if (strcmp(arg[4],"evdwl") == 0) evalue = EVDWL;
if (strcmp(arg[4],"ecoul") == 0) evalue = ECOUL;
} else evalue = EPAIR;
// check if pair style with and without suffix exists
pair = force->pair_match(pstyle,1);
if (!pair && lmp->suffix) {
strcat(pstyle,"/");
strcat(pstyle,lmp->suffix);
pair = force->pair_match(pstyle,1);
}
if (!pair)
error->all(FLERR,"Unrecognized pair style in compute pair command");
npair = pair->nextra;
if (npair) {
vector_flag = 1;
size_vector = npair;
extvector = 1;
one = new double[npair];
vector = new double[npair];
} else one = vector = NULL;
}
/* ---------------------------------------------------------------------- */
ComputePair::~ComputePair()
{
delete [] pstyle;
delete [] one;
delete [] vector;
}
/* ---------------------------------------------------------------------- */
void ComputePair::init()
{
// recheck for pair style in case it has been deleted
pair = force->pair_match(pstyle,1);
if (!pair)
error->all(FLERR,"Unrecognized pair style in compute pair command");
}
/* ---------------------------------------------------------------------- */
double ComputePair::compute_scalar()
{
invoked_scalar = update->ntimestep;
if (update->eflag_global != invoked_scalar)
error->all(FLERR,"Energy was not tallied on needed timestep");
double eng;
if (evalue == EPAIR) eng = pair->eng_vdwl + pair->eng_coul;
else if (evalue == EVDWL) eng = pair->eng_vdwl;
else if (evalue == ECOUL) eng = pair->eng_coul;
MPI_Allreduce(&eng,&scalar,1,MPI_DOUBLE,MPI_SUM,world);
return scalar;
}
/* ---------------------------------------------------------------------- */
void ComputePair::compute_vector()
{
invoked_vector = update->ntimestep;
if (update->eflag_global != invoked_vector)
error->all(FLERR,"Energy was not tallied on needed timestep");
for (int i = 0; i < npair; i++)
one[i] = pair->pvector[i];
MPI_Allreduce(one,vector,npair,MPI_DOUBLE,MPI_SUM,world);
}
| 28.049587 | 77 | 0.563936 | [
"vector"
] |
b01eec413ef53de56a7f0e65cde865245287d9c0 | 453 | cpp | C++ | lib/sequence/lis.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | lib/sequence/lis.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | lib/sequence/lis.cpp | mdstoy/atcoder-cpp | 5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// verifying : https://atcoder.jp/contests/abc006/submissions/22157599
int lis(vector<int> a) {
int n = (int)a.size();
vector<int> dp(n, 1 << 30);
for (int i = 0; i < n; i++) {
auto itr = lower_bound(dp.begin(), dp.end(), a[i]);
*itr = a[i];
}
int ret = 0;
for (int i = 0; i < n; i++) {
if (dp[i] == (1 << 30)) break;
ret++;
}
return ret;
}
| 22.65 | 70 | 0.492274 | [
"vector"
] |
b0226c9218d5a535ada564804a8257528c45568e | 3,399 | cc | C++ | Algorithms/VideoInterpolation/VideoInterpolation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/VideoInterpolation/VideoInterpolation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | Algorithms/VideoInterpolation/VideoInterpolation.cc | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #include "boost/bind.hpp"
#include "Logger/Log.h"
#include "Messages/RadarConfig.h"
#include "Messages/Video.h"
#include "Utils/VsipVector.h"
#include "VideoInterpolation.h"
#include "VideoInterpolation_defaults.h"
using namespace SideCar::Algorithms;
using namespace SideCar::Messages;
VideoInterpolation::VideoInterpolation(Controller& controller, Logger::Log& log) :
Algorithm(controller, log), interpolationCount_(Parameter::PositiveIntValue::Make(
"interpolationCount", "Interpolation Count", kDefaultInterpolationCount)),
past_(2)
{
;
}
bool
VideoInterpolation::startup()
{
registerProcessor<VideoInterpolation, Video>(&VideoInterpolation::process);
return registerParameter(interpolationCount_) && Algorithm::startup();
}
bool
VideoInterpolation::reset()
{
past_.clear();
return true;
}
bool
VideoInterpolation::process(const Messages::Video::Ref& in)
{
Logger::ProcLog log("process", getLog());
const float kEncoded2PI = RadarConfig::GetShaftEncodingMax() + 1.0;
const float kEncodedPI = kEncoded2PI / 2.0;
past_.add(in);
if (!past_.full()) { return send(in); }
// Convention: i indexes the input shaft encoding, j indexes the output shaft encoding
//
float iNew = past_[0]->getShaftEncoding();
float iOld = past_[1]->getShaftEncoding();
LOGDEBUG << "iNew: " << iNew << " iOld: " << iOld << std::endl;
if (iNew < iOld) {
iOld -= kEncoded2PI;
LOGDEBUG << "unwrapping iOld: " << iOld << std::endl;
}
float delta = iNew - iOld;
LOGDEBUG << "delta: " << delta << std::endl;
// Block time reversals (i.e. out-of-order packets)
//
if (delta > kEncodedPI) {
LOGERROR << "detected backward movement" << std::endl;
past_.add(past_[1]);
return true;
}
int emitCount = interpolationCount_->getValue() + 1;
delta /= emitCount;
LOGDEBUG << "interpolation delta: " << delta << std::endl;
// VSIP bindings for the inputs
VsipVector<Video> vNew(*past_[0]);
VsipVector<Video> vOld(*past_[1]);
vNew.admit(true);
vOld.admit(true);
vsip::Vector<float> tmp(in->size(), 0.0);
for (int index = 1; index <= emitCount; ++index) {
float shaftEncoding = iOld + delta * index;
if (shaftEncoding < 0.0)
shaftEncoding += kEncoded2PI;
else if (shaftEncoding >= kEncoded2PI)
shaftEncoding -= kEncoded2PI;
LOGDEBUG << "shaftEncoding: " << shaftEncoding << std::endl;
Video::Ref out(Video::Make(getName(), in));
out->resize(in->size(), 0);
out->getRIUInfo().shaftEncoding = size_t(::rint(shaftEncoding));
VsipVector<Video> vOut(*out);
vOut.admit(false);
float weight = float(index) / float(emitCount);
LOGDEBUG << "index: " << index << " weight: " << weight << std::endl;
tmp = mul(vOld.v, 1.0 - weight);
tmp = ma(vNew.v, weight, tmp);
vOut.v = vsip::impl::view_cast<Video::DatumType>(tmp);
vOut.release(true);
if (!send(out)) return false;
}
vNew.release(false);
vOld.release(false);
LOGDEBUG << "done" << std::endl;
return true;
}
// DLL support
//
extern "C" ACE_Svc_Export Algorithm*
VideoInterpolationMake(Controller& controller, Logger::Log& log)
{
return new VideoInterpolation(controller, log);
}
| 27.41129 | 110 | 0.629303 | [
"vector"
] |
b023af9158be28883014194009811440b6a31f60 | 2,821 | cpp | C++ | src/putstlclass.cpp | NULLCT/BlackJackOP | 6807b41204a14115db02e64fdb1bac5d4fff23a3 | [
"MIT"
] | 3 | 2021-06-11T08:39:25.000Z | 2022-01-21T13:44:41.000Z | src/putstlclass.cpp | NULLCT/BlackJackOP | 6807b41204a14115db02e64fdb1bac5d4fff23a3 | [
"MIT"
] | null | null | null | src/putstlclass.cpp | NULLCT/BlackJackOP | 6807b41204a14115db02e64fdb1bac5d4fff23a3 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <tuple>
#include <map>
#include <set>
using namespace std;
template <typename T>
ostream &operator<<(ostream &_ostr, const vector<T> &_v);
template <typename T>
ostream &operator<<(ostream &_ostr, const deque<T> &_v);
template <typename T>
ostream &operator<<(ostream &_ostr, const list<T> &_v);
template <typename T, typename Y>
ostream &operator<<(ostream &_ostr, const pair<T, Y> &_v);
template <class... Ts>
ostream &operator<<(ostream &_ostr, const tuple<Ts...> &t);
template <typename T, typename Y>
ostream &operator<<(ostream &_ostr, const map<T, Y> &_v);
template <typename T>
ostream &operator<<(ostream &_ostr, const set<T> &_v);
template <typename T>
ostream &operator<<(ostream &_ostr, const vector<T> &_v) {
_ostr << "v";
if (_v.empty()) {
_ostr << "{ }";
return _ostr;
}
_ostr << "{" << *_v.begin();
for (auto itr = ++_v.begin(); itr != _v.end(); itr++) {
_ostr << ", " << *itr;
}
_ostr << "}";
return _ostr;
}
template <typename T>
ostream &operator<<(ostream &_ostr, const deque<T> &_v) {
_ostr << "d";
if (_v.empty()) {
_ostr << "{ }";
return _ostr;
}
_ostr << "{" << *_v.begin();
for (auto itr = ++_v.begin(); itr != _v.end(); itr++) {
_ostr << ", " << *itr;
}
_ostr << "}";
return _ostr;
}
template <typename T>
ostream &operator<<(ostream &_ostr, const list<T> &_v) {
_ostr << "l";
if (_v.empty()) {
_ostr << "{ }";
return _ostr;
}
_ostr << "{" << *_v.begin();
for (auto itr = ++_v.begin(); itr != _v.end(); itr++) {
_ostr << ", " << *itr;
}
_ostr << "}";
return _ostr;
}
template <typename T, typename Y>
ostream &operator<<(ostream &_ostr, const pair<T, Y> &_v) {
_ostr << "p(" << _v.first << ", " << _v.second << ")";
return _ostr;
}
template <class... Ts>
ostream &operator<<(ostream &_ostr, const tuple<Ts...> &_v) {
_ostr << "t[";
bool first = true;
apply([&_ostr, &first](auto &&... args) {
auto print = [&](auto &&val) {
if (!first)
_ostr << ",";
(_ostr << val);
first = false;
};
(print(args), ...);
},
_v);
_ostr << "]";
return _ostr;
}
template <typename T, typename Y>
ostream &operator<<(ostream &_ostr, const map<T, Y> &_v) {
_ostr << "m{";
for (auto itr = _v.begin(); itr != _v.end(); itr++) {
_ostr << "(" << itr->first << ", " << itr->second << ")";
itr++;
if (itr != _v.end())
_ostr << ", ";
itr--;
}
_ostr << "}";
return _ostr;
}
template <typename T>
ostream &operator<<(ostream &_ostr, const set<T> &_v) {
_ostr << "s{";
for (auto itr = _v.begin(); itr != _v.end(); itr++) {
_ostr << *itr;
++itr;
if (itr != _v.end())
_ostr << ", ";
itr--;
}
_ostr << "}";
return _ostr;
}
| 23.90678 | 61 | 0.545551 | [
"vector"
] |
b02a558b502181882579c30f7da950a293e85caf | 3,403 | cpp | C++ | src/data-structures/ranged-fenwick-tree.cpp | Jyang772/umb-trd | 012b74472bf394624c0d7d7835cabd3c737a6fa0 | [
"MIT"
] | 10 | 2015-05-13T01:28:44.000Z | 2021-08-17T15:43:07.000Z | src/data-structures/ranged-fenwick-tree.cpp | Jyang772/umb-trd | 012b74472bf394624c0d7d7835cabd3c737a6fa0 | [
"MIT"
] | null | null | null | src/data-structures/ranged-fenwick-tree.cpp | Jyang772/umb-trd | 012b74472bf394624c0d7d7835cabd3c737a6fa0 | [
"MIT"
] | 3 | 2016-07-16T01:36:58.000Z | 2020-10-15T22:35:48.000Z | #include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
// Implementation based on the code provided at Petr's blog. Nevertheless,
// an easy and helpful explanation can be found in TopCoder's forums
// http://petr-mitrichev.blogspot.com/2013/05/fenwick-tree-range-updates.html
// http://apps.topcoder.com/forums/?module=RevisionHistory&messageID=1407869
template <typename T>
class RangedFenwickTree {
public:
RangedFenwickTree() {}
RangedFenwickTree(unsigned int n) { Init(n); }
T Query(int at) const {
T mul = 0, add = 0;
int start = at;
while (at >= 0) {
mul += dataMul[at];
add += dataAdd[at];
at = (at & (at + 1)) - 1;
}
return mul * start + add;
}
T QueryInterval(int x, int y) const { return Query(y) - Query(x - 1); }
void Update(int x, int y, T delta) {
InternalUpdate(x, delta, -delta * (x - 1));
if (y + 1 < (int)this->size()) InternalUpdate(y + 1, -delta, delta * y);
}
unsigned int size() const { return dataMul.size(); }
void Init(unsigned int n) {
dataMul.assign(n, 0);
dataAdd.assign(n, 0);
}
vector<T> dataMul, dataAdd;
private:
void InternalUpdate(int x, T mul, T add) {
for (int i = x; i < (int)this->size(); i = (i | (i + 1))) {
dataMul[i] += mul;
dataAdd[i] += add;
}
}
};
// Extension of the Ranged Fenwick Tree to 2D
template <typename T>
class RangedFenwickTree2D {
public:
RangedFenwickTree2D() {}
RangedFenwickTree2D(unsigned int m, unsigned int n) { Init(m, n); }
T Query(int x, int y) const {
T mul = 0, add = 0;
for (int i = x; i >= 0; i = (i & (i + 1)) - 1) {
mul += dataMul[i].Query(y);
add += dataAdd[i].Query(y);
}
return mul * x + add;
}
T QuerySubmatrix(int x1, int y1, int x2, int y2) const {
T result = Query(x2, y2);
if (x1 > 0) result -= Query(x1 - 1, y2);
if (y1 > 0) result -= Query(x2, y1 - 1);
if (x1 > 0 && y1 > 0) result += Query(x1 - 1, y1 - 1);
return result;
}
void Update(int x1, int y1, int x2, int y2, T delta) {
for (int i = x1; i < (int)dataMul.size(); i |= i + 1) {
dataMul[i].Update(y1, y2, delta);
dataAdd[i].Update(y1, y2, -delta * (x1 - 1));
}
for (int i = x2 + 1; i < (int)dataMul.size(); i |= i + 1) {
dataMul[i].Update(y1, y2, -delta);
dataAdd[i].Update(y1, y2, delta * x2);
}
}
void Init(unsigned int m, unsigned int n) {
// dataMul efficient initialization
if (dataMul.size() == m) {
for (int i = 0; i < (int)m; i++) dataMul[i].Init(n);
} else {
dataMul.assign(m, RangedFenwickTree<T>(n));
}
// dataAdd efficient initialization
if (dataAdd.size() == m) {
for (int i = 0; i < (int)m; i++) dataAdd[i].Init(n);
} else {
dataAdd.assign(m, RangedFenwickTree<T>(n));
}
}
vector<RangedFenwickTree<T> > dataMul, dataAdd;
};
int main() {
// EXAMPLE USAGE
// Solution for http://www.spoj.com/problems/USUBQSUB/
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
RangedFenwickTree2D<long long> f(n + 1, n + 1);
while (m--) {
int kind, x1, y1, x2, y2;
cin >> kind >> x1 >> y1 >> x2 >> y2;
if (kind == 1) {
cout << f.QuerySubmatrix(x1, y1, x2, y2) << '\n';
} else {
int value;
cin >> value;
f.Update(x1, y1, x2, y2, value);
}
}
return 0;
}
| 25.780303 | 77 | 0.566853 | [
"vector"
] |
b035c12d81704db9c2a937a46d46442b6f7bc5f8 | 1,078 | cpp | C++ | example/example_str_str.cpp | DaikiShimada/kadare | 95d546586c16933bb534a49b928458936e25557e | [
"MIT"
] | null | null | null | example/example_str_str.cpp | DaikiShimada/kadare | 95d546586c16933bb534a49b928458936e25557e | [
"MIT"
] | null | null | null | example/example_str_str.cpp | DaikiShimada/kadare | 95d546586c16933bb534a49b928458936e25557e | [
"MIT"
] | null | null | null | #include "../include/kadare/kadare.hpp"
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
std::string data_file = "data/test_str_str.data";
kadare::DataManager<std::string, std::string> dm(data_file);
std::cout << "Input file name: " << dm.getDbfile() << std::endl;
std::cout << "# of Records: " << dm.getRecords() << std::endl;
std::cout << "Key dimension: " << dm.getKey_dim() << std::endl;
std::cout << "Value dimension: " << dm.getValue_dim() << std::endl;
// load data
std::cout << "Data: " << std::endl;
for (int i=0; i<dm.getRecords(); ++i)
{
std::pair<std::vector<std::string>, std::vector<std::string> > d = dm.load();
std::vector<std::string>::iterator key_itr = d.first.begin();
std::vector<std::string>::iterator value_itr = d.second.begin();
for (key_itr=d.first.begin(); key_itr!=d.first.end(); ++key_itr)
std::cout << *key_itr << " ";
std::cout << "-> ";
for (value_itr=d.second.begin(); value_itr!=d.second.end(); ++value_itr)
std::cout << *value_itr << " ";
std::cout << std::endl;
}
return 0;
}
| 29.944444 | 79 | 0.611317 | [
"vector"
] |
b03b6fcd9d79117efe541c1cfd1f1bfe1f8e4859 | 6,787 | hh | C++ | contrib/fluxbox/src/FbTk/MenuTheme.hh | xk2600/lightbox | 987d901366fe706de1a8bbd1efd49b87abff3e0b | [
"BSD-2-Clause"
] | null | null | null | contrib/fluxbox/src/FbTk/MenuTheme.hh | xk2600/lightbox | 987d901366fe706de1a8bbd1efd49b87abff3e0b | [
"BSD-2-Clause"
] | 2 | 2017-05-30T05:21:59.000Z | 2018-03-14T07:21:33.000Z | src/FbTk/MenuTheme.hh | antix-skidoo/fluxbox | b83ee923f4ab2ab51f3b8c14343bda0579e538c6 | [
"MIT"
] | null | null | null | // MenuTheme.hh for FbTk
// Copyright (c) 2002 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot 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.
#ifndef FBTK_MENUTHEME_HH
#define FBTK_MENUTHEME_HH
#include "Theme.hh"
#include "Color.hh"
#include "Font.hh"
#include "Shape.hh"
#include "Texture.hh"
#include "PixmapWithMask.hh"
#include "GContext.hh"
namespace FbTk {
class MenuTheme: public Theme, public ThemeProxy<MenuTheme> {
public:
enum BulletType { EMPTY, SQUARE, TRIANGLE, DIAMOND};
MenuTheme(int screen_num);
virtual ~MenuTheme();
void reconfigTheme();
bool fallback(ThemeItem_base &item);
/**
@name text colors
*/
///@{
const Color &titleTextColor() const { return *t_text; }
const Color &frameTextColor() const { return *f_text; }
const Color &frameUnderlineColor() const { return *u_text; }
const Color &highlightTextColor() const { return *h_text; }
const Color &disableTextColor() const { return *d_text; }
///@}
/**
@name textures
*/
///@{
const Texture &titleTexture() const { return *title; }
const Texture &frameTexture() const { return *frame; }
const Texture &hiliteTexture() const { return *hilite; }
///@}
const PixmapWithMask &bulletPixmap() const { return *m_bullet_pixmap; }
const PixmapWithMask &selectedPixmap() const { return *m_selected_pixmap; }
const PixmapWithMask &unselectedPixmap() const { return *m_unselected_pixmap; }
const PixmapWithMask &highlightBulletPixmap() const { return *m_hl_bullet_pixmap; }
const PixmapWithMask &highlightSelectedPixmap() const { return *m_hl_selected_pixmap; }
const PixmapWithMask &highlightUnselectedPixmap() const { return *m_hl_unselected_pixmap; }
/**
@name fonts
*/
///@{
const Font &titleFont() const { return *titlefont; }
Font &titleFont() { return *titlefont; }
const Font &frameFont() const { return *framefont; }
Font &frameFont() { return *framefont; }
const Font &hiliteFont() const { return *hilitefont; }
Font &hiliteFont() { return *hilitefont; }
///@}
Justify frameFontJustify() const { return *framefont_justify; }
Justify hiliteFontJustify() const { return *hilitefont_justify; }
Justify titleFontJustify() const { return *titlefont_justify; }
/**
@name graphic contexts
*/
///@{
const GContext &titleTextGC() const { return t_text_gc; }
const GContext &frameTextGC() const { return f_text_gc; }
const GContext &hiliteUnderlineGC() const { return u_text_gc; }
const GContext &hiliteTextGC() const { return h_text_gc; }
const GContext &disableTextGC() const { return d_text_gc; }
const GContext &hiliteGC() const { return hilite_gc; }
GContext &titleTextGC() { return t_text_gc; }
GContext &frameTextGC() { return f_text_gc; }
GContext &hiliteUnderlineGC() { return u_text_gc; }
GContext &hiliteTextGC() { return h_text_gc; }
GContext &disableTextGC() { return d_text_gc; }
GContext &hiliteGC() { return hilite_gc; }
///@}
BulletType bullet() const { return *m_bullet; }
Justify bulletPos() const { return *bullet_pos; }
unsigned int titleHeight(bool fontConstrained = false) const {
return fontConstrained ? m_real_title_height : *m_title_height;
}
unsigned int itemHeight() const { return m_real_item_height; }
unsigned int borderWidth() const { return *m_border_width; }
unsigned int bevelWidth() const { return *m_bevel_width; }
unsigned char alpha() const { return m_alpha; }
void setAlpha(int alpha) { m_alpha = alpha; }
// this isn't actually a theme item
// but we'll let it be here for now, until there's a better way to
// get resources into menu
void setDelay(int msec) { m_delay = msec; }
int getDelay() const { return m_delay; }
const Color &borderColor() const { return *m_border_color; }
Shape::ShapePlace shapePlaces() const { return *m_shapeplace; }
// special override
void setSelectedPixmap(Pixmap pm, bool is_imagecached) {
m_selected_pixmap->pixmap() = pm;
if (is_imagecached)
m_selected_pixmap->pixmap().dontFree();
}
void setHighlightSelectedPixmap(Pixmap pm, bool is_imagecached) {
m_hl_selected_pixmap->pixmap() = pm;
if (is_imagecached)
m_hl_selected_pixmap->pixmap().dontFree();
}
virtual Signal<> &reconfigSig() { return Theme::reconfigSig(); }
virtual MenuTheme &operator *() { return *this; }
virtual const MenuTheme &operator *() const { return *this; }
private:
ThemeItem<Color> t_text, f_text, h_text, d_text, u_text;
ThemeItem<Texture> title, frame, hilite;
ThemeItem<Font> titlefont, framefont, hilitefont;
ThemeItem<Justify> framefont_justify, hilitefont_justify, titlefont_justify;
ThemeItem<Justify> bullet_pos;
ThemeItem<BulletType> m_bullet;
ThemeItem<Shape::ShapePlace> m_shapeplace;
ThemeItem<unsigned int> m_title_height, m_item_height;
ThemeItem<unsigned int> m_border_width;
ThemeItem<unsigned int> m_bevel_width;
ThemeItem<Color> m_border_color;
ThemeItem<PixmapWithMask> m_bullet_pixmap, m_selected_pixmap, m_unselected_pixmap;
ThemeItem<PixmapWithMask> m_hl_bullet_pixmap, m_hl_selected_pixmap, m_hl_unselected_pixmap;
Display *m_display;
GContext t_text_gc, f_text_gc, u_text_gc, h_text_gc, d_text_gc, hilite_gc;
int m_alpha;
unsigned int m_delay; ///< in msec
unsigned int m_real_title_height; ///< the calculated item height (from font and menu.titleHeight)
unsigned int m_real_item_height; ///< the calculated item height (from font and menu.itemHeight)
};
} // end namespace FbTk
#endif // FBTK_MENUTHEME_HH
| 39.923529 | 102 | 0.705908 | [
"shape"
] |
b0473fb58065136a6e3fa3472912a5b82fe26132 | 57,652 | cp | C++ | Sources_Common/Plugins/Security/CSecurityPlugin.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2015-03-23T13:45:09.000Z | 2021-11-06T08:37:42.000Z | Sources_Common/Plugins/Security/CSecurityPlugin.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | Sources_Common/Plugins/Security/CSecurityPlugin.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-03-27T09:10:59.000Z | 2022-01-19T12:12:48.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// CSecurityPlugin.cp
//
// Copyright 2006, Cyrus Daboo. All Rights Reserved.
//
// Created: 04-May-1998
// Author: Cyrus Daboo
// Platforms: Mac OS, Win32
//
// Description:
// This class implements a wrapper for DLL based security plug-ins in Mulberry.
//
// History:
// CD: 04-May-1998: Created initial header and implementation.
//
//#define VISIBLE_TEMP_FILES
#include "CSecurityPlugin.h"
#include "CAddressList.h"
#include "CAttachment.h"
#include "CAttachmentList.h"
#include "CCertificateManager.h"
#include "CDataAttachment.h"
#include "CErrorHandler.h"
#include "CFileAttachment.h"
#include "CGeneralException.h"
#include "CGetPassphraseDialog.h"
#include "CLocalAttachment.h"
#include "CLocalCommon.h"
#include "CLocalMessage.h"
#include "CMailControl.h"
#include "CMbox.h"
#include "CMessage.h"
#include "CMessageWindow.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CNetworkException.h"
#include "CPluginManager.h"
#include "CPreferences.h"
#include "CPreferenceVersions.h"
#include "CRFC822Parser.h"
#include "CSSLPlugin.h"
#include "CStreamAttachment.h"
#include "CStreamFilter.h"
#include "CStreamType.h"
#include "CStreamUtils.h"
#if __dest_os == __mac_os || __dest_os == __mac_os_x
#include "CStringResources.h"
#endif
#include "CStringUtils.h"
#include "CTextListChoice.h"
#include "CUtils.h"
#include "mimefilters.h"
#include "cdfstream.h"
#if __dest_os == __mac_os_x
#include "MyCFString.h"
#include <SysCFURL.h>
#endif
#include <algorithm>
#include <strstream>
#include <typeinfo>
CSecurityPlugin::SSecurityPluginHandlers CSecurityPlugin::sSecurityPlugins;
cdstring CSecurityPlugin::sPreferredPlugin;
cdstrmap CSecurityPlugin::sCanVerify;
cdstrmap CSecurityPlugin::sCanDecrypt;
cdstrmap CSecurityPlugin::sPassphrases;
cdstring CSecurityPlugin::sLastPassphraseUID;
const unsigned long cFileThreshold = 0x10000;
const char* cGPGName = "GPG Plugin";
const char* cPGPName = "PGP Plugin";
const char* cSMIMEName = "SMIME Plugin";
// Register a security plugin
void CSecurityPlugin::RegisterSecurityPlugin(CSecurityPlugin* plugin)
{
// Add it to the list
sSecurityPlugins.insert(SSecurityPluginHandlers::value_type(plugin->GetName(), plugin));
}
CSecurityPlugin* CSecurityPlugin::GetRegisteredPlugin(const cdstring& descriptor)
{
SSecurityPluginHandlers::const_iterator found = sSecurityPlugins.find(descriptor);
if (found != sSecurityPlugins.end())
return (*found).second;
else
return NULL;
}
// Plugin used for sign/encrypt operations
CSecurityPlugin* CSecurityPlugin::GetDefaultPlugin()
{
// Prompt user to choose if no preferred item and more than one is loaded
if ((sSecurityPlugins.size() > 1) && CPreferences::sPrefs->mPreferredPlugin.GetValue().empty())
{
// Get list of available plugins
cdstrvect plugins;
for(SSecurityPluginHandlers::const_iterator iter = sSecurityPlugins.begin(); iter != sSecurityPlugins.end(); iter++)
plugins.push_back((*iter).first);
// Allow user to choose the one they want
ulvector selected;
if (CTextListChoice::PoseDialog("Alerts::General::ChooseCryptoPluginTitle", NULL, NULL, false, true, false, true, plugins, cdstring::null_str, selected, NULL))
{
// Save the choice in the preferences
CPreferences::sPrefs->mPreferredPlugin.SetValue(plugins.at(selected.front()));
}
else
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
// Now try to find the appropriate plugin
CSecurityPlugin* plugin = NULL;
if (sSecurityPlugins.size() > 1)
{
// Look for one that matches the chosen name
plugin = GetRegisteredPlugin(CPreferences::sPrefs->mPreferredPlugin.GetValue());
if (plugin == NULL)
{
// Use alternate PGP/GPG depending on what is present
if (CPreferences::sPrefs->mPreferredPlugin.GetValue() == cGPGName)
plugin = GetRegisteredPlugin(cPGPName);
else if (CPreferences::sPrefs->mPreferredPlugin.GetValue() == cPGPName)
plugin = GetRegisteredPlugin(cGPGName);
}
}
// Just use the first one in the list
if (!plugin && sSecurityPlugins.size())
plugin = sSecurityPlugins.begin()->second;
return plugin;
}
// Make sure version matches
bool CSecurityPlugin::VerifyVersion() const
{
// New API >= 3.1b5
if (VersionTest(GetVersion(), VERS_3_1_0_B_5) >= 0)
return true;
else
{
CErrorHandler::PutStopAlertRsrcStr("Alerts::General::IllegalPluginCryptoVersion", GetName().c_str());
return false;
}
}
// Load information
void CSecurityPlugin::LoadPlugin()
{
// Do inherited then set callback if all OK
CPlugin::LoadPlugin();
SetCallback();
if (GetName() == cSMIMEName)
SetContext();
}
#pragma mark ____________________________High Level
bool CSecurityPlugin::ProcessMessage(CMessage* msg, ESecureMessage mode, const char* key)
{
// Only bother if something actually required
if (mode == eNone)
return true;
// Cannot sign without key
if (((mode == eSign) || (mode == eEncryptSign)) &&
(!key || !*key))
return false;
// Load plugin
StLoadPlugin load(this);
bool result = false;
while(true)
{
long err = 0;
try
{
if (UseMIME())
ProcessBody(msg, mode, key);
else
// Sign each part
ProcessAttachment(msg, msg->GetBody(), mode, key);
result = true;
}
catch (...)
{
CLOG_LOGCATCH(...);
err = HandleError();
result = false;
}
// Try it again if error was bad passphrase
if (result || (err != eSecurity_BadPassphrase))
break;
}
return result;
}
#if __dest_os == __mac_os || __dest_os == __mac_os_x
void CSecurityPlugin::CreateTempFile(PPx::FSObject* ftemp, ESecureMessage mode, const cdstring& name)
#else
void CSecurityPlugin::CreateTempFile(cdstring& ftemp, ESecureMessage mode, const cdstring& name)
#endif
{
// Generate a suitable name
cdstring new_name = name;
if (new_name.empty())
{
static unsigned long sCtr = 0;
new_name.reserve(L_tmpnam);
::snprintf(new_name.c_str_mod(), L_tmpnam, "Temp_%lx%03ld", ::time(NULL), sCtr++ % 256);
}
switch(mode)
{
case eSign:
new_name += ".sig";
break;
case eEncrypt:
case eEncryptSign:
new_name += ".asc";
break;
default:
new_name += ".tmp";
}
#if __dest_os == __mac_os || __dest_os == __mac_os_x
::TempFileSpecSecurity(*ftemp, new_name);
// Must create the file on Mac OS to ensure file path conversion will work
LFile fileTemp(*ftemp);
fileTemp.CreateNewFile('Mlby', 'SECR', smCurrentScript);
ftemp->Update();
#else
::TempFileSpecSecurity(ftemp, new_name);
#endif
}
void CSecurityPlugin::ApplyMIME(CAttachment* part, SMIMEInfo* info)
{
// Add content type
if (info->type)
part->GetContent().SetContentType(info->type);
// Add content subtype
if (info->subtype)
part->GetContent().SetContentSubtype(info->subtype);
// Add parameters
const char** p = info->params;
while(p && *p)
{
const char* name = *p++;
const char* value = *p++;
if (name && *name && value && *value)
part->GetContent().SetContentParameter(name, value);
}
}
bool CSecurityPlugin::DoesEncryptSignAllInOne() const
{
return GetName() != cSMIMEName;
}
bool CSecurityPlugin::UseMIME() const
{
return (GetName() == cSMIMEName) || CPreferences::sPrefs->mUseMIMESecurity.GetValue();
}
#pragma mark ____________________________Operations on entire body
void CSecurityPlugin::ProcessBody(CMessage* msg, ESecureMessage mode, const char* key)
{
// Special processing for Encrypt&Sign separate
if ((mode == eEncryptSign) && !DoesEncryptSignAllInOne())
{
// Do signature first
ProcessBody(msg, eSign, key);
// Change mode to encrypt for second operation
mode = eEncrypt;
}
// Sign entire message
CAttachment* part = msg->GetBody();
CAttachment* generated_part = NULL;
// Special processing for crypto - only needed for broken PGP implementations
part->ProcessSendCrypto(mode, true);
unsigned long size = 0;
if (FileBody(part, size))
{
#if __dest_os == __mac_os || __dest_os == __mac_os_x
// Create temporary input file
PPx::FSObject fs_fin;
PPx::FSObject* fin = &fs_fin;
CreateTempFile(fin, mode, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path(fin->GetPath());
// Create temporary output file
PPx::FSObject fs_fout;
PPx::FSObject* fout = &fs_fout;
CreateTempFile(fout, mode, cdstring::null_str);
StRemoveFileSpec _remove_fout(fout);
PPx::CFURL fout_url = fout->GetURL();
#else
cdstring fin;
CreateTempFile(fin, mode, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path = fin;
cdstring fout;
CreateTempFile(fout, mode, cdstring::null_str);
StRemoveFileSpec _remove_fout(fout);
#endif
// Write it to a stream
{
cdofstream outs(fin_path, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
unsigned long level = 0;
costream stream_out(&outs, lendl);
part->WriteToStream(stream_out, level, false, nil);
}
// Now process file
Process(msg, mode, NULL, fin, key, NULL, fout, NULL, true, false);
// Create part containing PGP data - this takes ownership of the temp file
#if __dest_os == __mac_os || __dest_os == __mac_os_x
*fout = PPx::FSObject(fout_url);
generated_part = new CFileAttachment(*fout);
#else
generated_part = new CFileAttachment(fout);
#endif
static_cast<CFileAttachment*>(generated_part)->SetDeleteFile(true);
// Always NULL the file name to prevent temp file names leaking into MIME parameters
generated_part->GetContent().SetMappedName(cdstring::null_str);
// Make sure output file is not deleted via stack remove
_remove_fout.release();
}
else
{
cdstring data;
// Write it to a stream
{
std::ostrstream outs;
unsigned long level = 0;
costream stream_out(&outs, lendl);
part->WriteToStream(stream_out, level, false, nil);
outs << std::ends;
data.steal(outs.str());
}
char* out = nil;
unsigned long out_len = 0;
Process(msg, mode, data, NULL, key, &out, NULL, &out_len, true, false);
// Make a copy of the data
char* local = new char[out_len + 1];
::memcpy(local, out, out_len);
local[out_len] = 0;
DisposeData(out);
// Create part containg PGP data
generated_part = new CDataAttachment;
generated_part->SetData(local);
}
// Now pocess into PGP/MIME
// Get appropriate MIME params
SMIMEMultiInfo mime;
switch(mode)
{
case eSign:
GetMIMESign(&mime);
break;
case eEncrypt:
GetMIMEEncrypt(&mime);
break;
case eEncryptSign:
GetMIMEEncryptSign(&mime);
break;
default:;
}
// Determine whether multipart format can be used
bool use_multi_part = !::strcmpnocase(mime.multipart.type, "multipart");
// Process PGP data part
ApplyMIME(generated_part, &mime.second);
// The content in the generated part is already transfer encoded so we must
// not re-apply the encoding
generated_part->GetContent().SetDontEncode();
// Create actual message structure
if (use_multi_part)
{
// Create the top-level multipart
CAttachment* multi_part = new CAttachment;
ApplyMIME(multi_part, &mime.multipart);
// Give it to the message
msg->SetBody(multi_part, false);
// Now add subparts to top part
switch(mode)
{
case eSign:
// multipart/signed
// type/subtype
// application/pgp-signature
multi_part->AddPart(part);
multi_part->AddPart(generated_part);
break;
case eEncrypt:
case eEncryptSign:
{
// multipart/encrypted
// application/pgp-encrypted
// application/octet-stream
// Delete original part
delete part;
// Create new encryption part
CDataAttachment* version_part = new CDataAttachment;
ApplyMIME(version_part, &mime.first);
cdstring temp("Version: 1");
temp += os_endl;
version_part->SetData(temp.grab_c_str());
// Add the parts now
multi_part->AddPart(version_part);
multi_part->AddPart(generated_part);
// NB last part must be set to CTE of 7bit
generated_part->GetContent().SetTransferEncoding(e7bitEncoding);
}
break;
default:;
}
}
else
{
// Delete original part
delete part;
// Give new generated part to the message
msg->SetBody(generated_part, false);
}
}
// Determine whether body needs to be spooled to file
bool CSecurityPlugin::FileBody(const CAttachment* part, unsigned long& size) const
{
// See if multipart
if (part->IsMultipart() && !part->IsMessage() && part->GetParts())
{
for(CAttachmentList::iterator iter = part->GetParts()->begin(); iter != part->GetParts()->end(); iter++)
{
if (FileBody(*iter, size))
return true;
}
return false;
}
else if (part->IsMessage())
return FileBody(part->GetMessage()->GetBody(), size);
else
{
// Files always require file processing
if (FileAttachment(part))
return true;
// Total size > 64K require file processing
size += part->GetSize();
return (size >= cFileThreshold);
}
}
#pragma mark ____________________________Operations on single parts
bool CSecurityPlugin::CanSecureAttachment(const CAttachment* part) const
{
return part->CanChange();
}
bool CSecurityPlugin::FileAttachment(const CAttachment* part) const
{
return typeid(*part) == typeid(CFileAttachment);
}
void CSecurityPlugin::ProcessAttachment(CMessage* msg, CAttachment* part, ESecureMessage mode, const char* key)
{
// See if multipart
if (part->IsMultipart() && !part->IsMessage() && !part->IsApplefile() && part->GetParts())
{
for(CAttachmentList::iterator iter = part->GetParts()->begin(); iter != part->GetParts()->end(); iter++)
ProcessAttachment(msg, *iter, mode, key);
}
else if (part->IsMessage())
ProcessAttachment(part->GetMessage(), part->GetMessage()->GetBody(), mode, key);
else
{
// Only do those that are modifiable
if (!CanSecureAttachment(part))
return;
// Special processing for crypto - only needed for broken PGP implementations
part->ProcessSendCrypto(mode, false);
// Check for memory or file based attachment
if (FileAttachment(part))
{
#if __dest_os == __mac_os || __dest_os == __mac_os_x
// Create temporary output file
PPx::FSObject fs_fout;
PPx::FSObject* fout = &fs_fout;
cdstring old_name = static_cast<CFileAttachment*>(part)->GetFSSpec()->GetName();
CreateTempFile(fout, mode, old_name);
StRemoveFileSpec _remove_fout(fout);
PPx::CFURL fout_url = fout->GetURL();
#else
// Create temporary output file
cdstring fout;
cdstring old_path = static_cast<CFileAttachment*>(part)->GetFilePath();
cdstring old_name;
if (::strrchr(old_path.c_str(), os_dir_delim) != NULL)
old_name = ::strrchr(old_path.c_str(), os_dir_delim) + 1;
else
old_name = old_path;
CreateTempFile(fout, mode, old_name);
StRemoveFileSpec _remove_fout(fout);
#endif
// For file attachments we always create a detatched signature of the original file data on disk
// allowing users to save the file part and the signature part to disk and to then verify that using
// the desktop PGP tool. Thus we need to turn on the PGP/MIME behaviour for signing here to get the
// detached signature.
#if __dest_os == __mac_os || __dest_os == __mac_os_x
Process(msg, mode, NULL, static_cast<CFileAttachment*>(part)->GetFSSpec(), key, NULL, fout, NULL, mode == eSign, !part->IsText());
#else
Process(msg, mode, NULL, static_cast<CFileAttachment*>(part)->GetFilePath(), key, NULL, fout, NULL, mode == eSign, !part->IsText());
#endif
// Get appropriate MIME params
SMIMEMultiInfo mime;
switch(mode)
{
case eSign:
GetMIMESign(&mime);
break;
case eEncrypt:
GetMIMEEncrypt(&mime);
break;
case eEncryptSign:
GetMIMEEncryptSign(&mime);
break;
default:;
}
// Now have detached file - decide what to do
switch(mode)
{
case eSign:
{
// Turn into multipart and add detached signature
CDataAttachment* mattach = new CDataAttachment;
mattach->GetContent().SetContent(eContentMultipart, eContentSubMixed);
// Attachment takes ownership of temp file
#if __dest_os == __mac_os || __dest_os == __mac_os_x
*fout = PPx::FSObject(fout_url);
CFileAttachment* fattach = new CFileAttachment(*fout);
#else
CFileAttachment* fattach = new CFileAttachment(fout);
#endif
fattach->SetDeleteFile(true);
// Always NULL the file name to prevent temp file names leaking into MIME parameters
fattach->GetContent().SetMappedName(cdstring::null_str);
// Make sure output file is not deleted via stack remove
_remove_fout.release();
ApplyMIME(fattach, &mime.second);
// See if it has a parent
if (part->GetParent())
{
CAttachment* pattach = part->GetParent();
// Get index of part within parent
unsigned long index = pattach->GetParts() ? pattach->GetParts()->FetchIndexOf(part) : 0;
if (index)
{
// Remove existing part
index--;
pattach->RemovePart(part, false);
// Add in multipart at old position
pattach->AddPart(mattach, index);
// Now add the sub-parts
mattach->AddPart(part);
mattach->AddPart(fattach);
}
}
else
{
// Give multipart to message
msg->SetBody(mattach, false);
// Now add the sub-parts
mattach->AddPart(part);
mattach->AddPart(fattach);
}
break;
}
case eEncrypt:
case eEncryptSign:
// Special for AppleDouble - must do before setting FSSpec
if (part->IsMultipart() && part->IsApplefile() && part->GetParts())
{
part->RemovePart(part->GetParts()->front());
part->RemovePart(part->GetParts()->front());
}
// Replace existing part with new file - takes ownership of temp file
#if __dest_os == __mac_os || __dest_os == __mac_os_x
*fout = PPx::FSObject(fout_url);
static_cast<CFileAttachment*>(part)->SetFSSpec(*fout);
#else
static_cast<CFileAttachment*>(part)->SetFilePath(fout);
#endif
static_cast<CFileAttachment*>(part)->SetDeleteFile(true);
// Always NULL the file name to prevent temp file names leaking into MIME parameters
part->GetContent().SetMappedName(cdstring::null_str);
// Make sure output file is not deleted via stack remove
_remove_fout.release();
// Convert to stand alone application/pgp-encrypted
ApplyMIME(part, &mime.first);
break;
default:;
}
}
else
{
// Process data through plugin
char* out = nil;
unsigned long out_len = 0;
Process(msg, mode, part->GetData(), NULL, key, &out, NULL, &out_len, false, !part->IsText());
// Make a copy of the data
char* local = new char[out_len + 1];
::memcpy(local, out, out_len);
local[out_len] = 0;
DisposeData(out);
part->SetData(local);
}
}
}
#pragma mark ____________________________Process some data
void CSecurityPlugin::Process(const CMessage* msg,
ESecureMessage mode,
const char* in,
fspec fin,
const char* key,
char** out,
fspec fout,
unsigned long* out_len,
bool useMIME,
bool binary)
{
bool do_data = (in != NULL);
switch(mode)
{
case eSign:
if (do_data)
{
// Clear sign data
if (SignData(in, key, out, out_len, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
else
{
// Clear sign file
if (SignFile(fin, key, fout, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
break;
case eEncrypt:
{
// Create array of keys
cdstrvect keylist;
// Now add all keys
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetTo()->begin(); iter != msg->GetEnvelope()->GetTo()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetCC()->begin(); iter != msg->GetEnvelope()->GetCC()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetBcc()->begin(); iter != msg->GetEnvelope()->GetBcc()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
if (CPreferences::sPrefs->mEncryptToSelf.GetValue())
keylist.push_back(key);
// Eliminate duplicates then create pointer array
std::sort(keylist.begin(), keylist.end());
keylist.erase(std::unique(keylist.begin(), keylist.end()), keylist.end());
const char** key_list = cdstring::ToArray(keylist);
try
{
if (do_data)
{
// Clear sign data
if (EncryptData(in, key_list, out, out_len, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
else
{
// Clear sign data
if (EncryptFile(fin, key_list, fout, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
}
catch (...)
{
CLOG_LOGCATCH(...);
// Always delete key list
cdstring::FreeArray(key_list);
CLOG_LOGRETHROW;
throw;
}
// Delete key list
cdstring::FreeArray(key_list);
}
break;
case eEncryptSign:
{
// Create array of keys
cdstrvect keylist;
// Now add all keys
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetTo()->begin(); iter != msg->GetEnvelope()->GetTo()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetCC()->begin(); iter != msg->GetEnvelope()->GetCC()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
for(CAddressList::const_iterator iter = msg->GetEnvelope()->GetBcc()->begin(); iter != msg->GetEnvelope()->GetBcc()->end(); iter++)
keylist.push_back((*iter)->GetMailAddress().c_str());
if (CPreferences::sPrefs->mEncryptToSelf.GetValue())
keylist.push_back(key);
// Eliminate duplicates then create pointer array
std::sort(keylist.begin(), keylist.end());
keylist.erase(std::unique(keylist.begin(), keylist.end()), keylist.end());
const char** key_list = cdstring::ToArray(keylist);
try
{
if (do_data)
{
// Clear sign data
if (EncryptSignData(in, key_list, key, out, out_len, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
else
{
// Clear sign data
if (EncryptSignFile(fin, key_list, key, fout, useMIME, binary) != 1)
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
}
}
catch (...)
{
CLOG_LOGCATCH(...);
// Always delete key list
cdstring::FreeArray(key_list);
CLOG_LOGRETHROW;
throw;
}
// Delete key list
cdstring::FreeArray(key_list);
}
break;
default:;
}
}
#pragma mark ____________________________Verify/decrypt static apis
// Only called for inline parts
bool CSecurityPlugin::VerifyDecryptPart(CMessage* msg, CAttachment* part, CMessageCryptoInfo& info)
{
CSecurityPlugin* splugin = NULL;
try
{
// Is message top part multipart/signed
if (msg->GetBody() && msg->GetBody()->IsSigned() &&
msg->GetBody()->GetParts() && (msg->GetBody()->GetParts()->size() == 2))
{
// Get the protocol parameter
const cdstring& protocol = msg->GetBody()->GetContent().GetContentParameter(cMIMEParameter[eCryptoProtocol]);
// Get suitable plugin for verify
splugin = GetVerifyPlugin(protocol);
// Check for valid sigtype
if (!splugin)
{
// Provide sensible indication for missing parameter
cdstring err_protocol(protocol);
if (err_protocol.empty())
err_protocol = "missing protocol parameter";
// Do error to indicate unsupported protocol
cdstring errstr;
errstr.FromResource("Alerts::Message::UNKNOWN_CRYPTO_SHORT");
errstr.Substitute(err_protocol);
info.SetError(errstr);
// Only show alert if requested by user
if (CPreferences::sPrefs->mUseErrorAlerts.GetValue())
CErrorHandler::PutStopAlertRsrcStr("Alerts::Message::UNKNOWN_CRYPTO", err_protocol);
return false;
}
}
// Is parent a multipart/encrypted
else if (msg->GetBody() && msg->GetBody()->IsEncrypted() &&
msg->GetBody()->GetParts() && (msg->GetBody()->GetParts()->size() == 2))
{
// Get the protocol parameter
const cdstring& protocol = msg->GetBody()->GetContent().GetContentParameter(cMIMEParameter[eCryptoProtocol]);
// Get suitable plugin for verify
splugin = GetDecryptPlugin(protocol);
// Check for valid sigtype
if (!splugin)
{
// Provide sensible indication for missing parameter
cdstring err_protocol(protocol);
if (err_protocol.empty())
err_protocol = "missing protocol parameter";
// Do error to indicate unsupported protocol
cdstring errstr;
errstr.FromResource("Alerts::Message::UNKNOWN_CRYPTO_SHORT");
errstr.Substitute(err_protocol);
info.SetError(errstr);
// Only show alert if requested by user
if (CPreferences::sPrefs->mUseErrorAlerts.GetValue())
CErrorHandler::PutStopAlertRsrcStr("Alerts::Message::UNKNOWN_CRYPTO", err_protocol);
return false;
}
}
// Is parent application/(x-)pkcs7-mime
else if (msg->GetBody() && msg->GetBody()->IsDecryptable())
{
// Get the protocol parameter
cdstring type = CMIMESupport::GenerateContentHeader(msg->GetBody(), false, lendl, false);
// Get suitable plugin for verify
splugin = GetDecryptPlugin(type);
// Check for valid sigtype
if (!splugin)
{
// Provide sensible indication for missing parameter
cdstring err_protocol(type);
if (err_protocol.empty())
err_protocol = "missing content type";
// Do error to indicate unsupported protocol
cdstring errstr;
errstr.FromResource("Alerts::Message::UNKNOWN_CRYPTO_SHORT");
errstr.Substitute(err_protocol);
info.SetError(errstr);
// Only show alert if requested by user
if (CPreferences::sPrefs->mUseErrorAlerts.GetValue())
CErrorHandler::PutStopAlertRsrcStr("Alerts::Message::UNKNOWN_CRYPTO", err_protocol);
return false;
}
}
else if (part)
{
// Must be inline PGP/GPG
splugin = GetRegisteredPlugin(cGPGName);
if (!splugin)
splugin = GetRegisteredPlugin(cPGPName);
// Check for valid sigtype
if (!splugin)
{
// Provide sensible indication for missing parameter
cdstring err_protocol("cannot process inline content");
// Do error to indicate unsupported protocol
cdstring errstr;
errstr.FromResource("Alerts::Message::UNKNOWN_CRYPTO_SHORT");
errstr.Substitute(err_protocol);
info.SetError(errstr);
// Only show alert if requested by user
if (CPreferences::sPrefs->mUseErrorAlerts.GetValue())
CErrorHandler::PutStopAlertRsrcStr("Alerts::Message::UNKNOWN_CRYPTO", err_protocol);
return false;
}
}
}
catch(...)
{
CLOG_LOGCATCH(...);
}
return splugin ? splugin->VerifyDecryptPartInternal(msg, part, info) : false;
}
CSecurityPlugin* CSecurityPlugin::GetVerifyPlugin(const cdstring& type)
{
// Force reset of cache if preferred plugin has changed
if (sPreferredPlugin != CPreferences::sPrefs->mPreferredPlugin.GetValue())
{
sCanVerify.clear();
sPreferredPlugin = CPreferences::sPrefs->mPreferredPlugin.GetValue();
}
// See whether result is already cached
cdstrmap::const_iterator found = sCanVerify.find(type);
if (found != sCanVerify.end())
{
if ((*found).second.length())
return GetRegisteredPlugin((*found).second);
else
return NULL;
}
// First try the default plugin specified in the preferences. This will ensure that if both PGP and GPG
// are installed, then the one from the prefs will be picked for PGP verifications
CSecurityPlugin* splugin = GetRegisteredPlugin(CPreferences::sPrefs->mPreferredPlugin.GetValue());
if ((splugin != NULL) && (splugin->CanVerifyThis(type) == 0))
{
// cache it and return
sCanVerify.insert(cdstrmap::value_type(type, splugin->GetName()));
return splugin;
}
// Must do lookup using each plugin
for(SSecurityPluginHandlers::iterator iter = sSecurityPlugins.begin(); iter != sSecurityPlugins.end(); iter++)
{
// Try each one
splugin = (*iter).second;
if (splugin->CanVerifyThis(type) == 0)
{
// cache it and return
sCanVerify.insert(cdstrmap::value_type(type, (*iter).first));
return splugin;
}
}
// No handler found - cache this as NULL to prevent testing again
sCanVerify.insert(cdstrmap::value_type(type, cdstring::null_str));
return NULL;
}
CSecurityPlugin* CSecurityPlugin::GetDecryptPlugin(const cdstring& type)
{
// Force reset of cache if preferred plugin has changed
if (sPreferredPlugin != CPreferences::sPrefs->mPreferredPlugin.GetValue())
{
sCanDecrypt.clear();
sPreferredPlugin = CPreferences::sPrefs->mPreferredPlugin.GetValue();
}
// See whether result is already cached
cdstrmap::const_iterator found = sCanDecrypt.find(type);
if (found != sCanDecrypt.end())
{
if ((*found).second.length())
return GetRegisteredPlugin((*found).second);
else
return NULL;
}
// First try the default plugin specified in the preferences. This will ensure that if both PGP and GPG
// are installed, then the one from the prefs will be picked for PGP decryptions
CSecurityPlugin* splugin = GetRegisteredPlugin(CPreferences::sPrefs->mPreferredPlugin.GetValue());
if ((splugin != NULL) && (splugin->CanDecryptThis(type) == 0))
{
// cache it and return
sCanDecrypt.insert(cdstrmap::value_type(type, splugin->GetName()));
return splugin;
}
// Must do lookup using each plugin
for(SSecurityPluginHandlers::iterator iter = sSecurityPlugins.begin(); iter != sSecurityPlugins.end(); iter++)
{
// Try each one
splugin = (*iter).second;
if (splugin->CanDecryptThis(type) == 0)
{
// cache it and return
sCanDecrypt.insert(cdstrmap::value_type(type, (*iter).first));
return splugin;
}
}
// No handler found - cache this as NULL to prevent testing again
sCanDecrypt.insert(cdstrmap::value_type(type, cdstring::null_str));
return NULL;
}
#pragma mark ____________________________Verify/decrypt local apis
// Only called for inline parts
bool CSecurityPlugin::VerifyDecryptPartInternal(CMessage* msg, CAttachment* part, CMessageCryptoInfo& info)
{
// Load plugin
StLoadPlugin load(this);
bool result = false;
const char* old_data = NULL;
CAttachment* temp_attach = NULL;
bool remove_temp_data = false;
try
{
// Is message top part multipart/signed
if (msg->GetBody() &&
(msg->GetBody()->GetContent().GetContentType() == eContentMultipart) &&
(msg->GetBody()->GetContent().GetContentSubtype() == eContentSubSigned) &&
msg->GetBody()->GetParts() &&
(msg->GetBody()->GetParts()->size() == 2))
{
// Check message size first
if (!CMailControl::CheckSizeWarning(msg, true))
return false;
// Do verification
result = VerifyMessage(msg, info);
// Now see if signature failed
if (!result)
HandleError(&info);
}
// Is parent a multipart/encrypted
else if (msg->GetBody() &&
(msg->GetBody()->GetContent().GetContentType() == eContentMultipart) &&
(msg->GetBody()->GetContent().GetContentSubtype() == eContentSubEncrypted) &&
msg->GetBody()->GetParts() &&
(msg->GetBody()->GetParts()->size() == 2))
{
// Check message size first
if (!CMailControl::CheckSizeWarning(msg, true))
return false;
// Do decrypt
result = DecryptMessage(msg, info, true);
// Now see if signature failed
if (!result)
HandleError(&info);
}
// Is parent application/(x-)pkcs7-mime
else if (msg->GetBody() && msg->GetBody()->IsDecryptable())
{
// Check message size first
if (!CMailControl::CheckSizeWarning(msg, true))
return false;
// Do decrypt
result = DecryptMessage(msg, info, false);
// Now see if signature failed
if (!result)
HandleError(&info);
}
else if (part)
{
cdstring from;
if (msg->GetEnvelope() && msg->GetEnvelope()->GetFrom() && (msg->GetEnvelope()->GetFrom()->size() != 0))
from = msg->GetEnvelope()->GetFrom()->front()->GetMailAddress();
// Just use current data in this part
const char* in = part->GetData();
char* out = NULL;
unsigned long out_len = 0;
char* signed_by = NULL;
char* encrypted_to = NULL;
bool did_signature = false;
bool signature_ok = false;
if (DecryptVerifyData(in, NULL, from, &out, &out_len, &signed_by, &encrypted_to, &result, &did_signature, &signature_ok, !part->IsText()) != 1)
{
info.SetSuccess(false);
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
info.SetSuccess(result);
info.SetDidSignature(did_signature);
info.SetSignatureOK(signature_ok);
// Get signed by info
if (info.GetDidSignature() && signed_by)
cdstring::FromArray((const char**) signed_by, info.GetSignedBy());
// Get encrypted to info
cdstrvect encryptedTo;
if (encrypted_to)
{
info.SetDidDecrypt(true);
cdstring::FromArray((const char**) encrypted_to, info.GetEncryptedTo());
}
// Add data to part, remove any old cached data
if (result)
{
// Replace existing part data with output
if (out)
part->SetData(::strdup(out));
}
else
HandleError(&info);
DisposeData(out);
}
}
catch(CNetworkException& ex)
{
CLOG_LOGCATCH(CNetworkException&);
// Must throw out if disconnected/reconnected because
// message object is no longer valid
if (ex.disconnected() || ex.reconnected())
throw;
}
catch (...)
{
CLOG_LOGCATCH(...);
HandleError(&info);
result = false;
}
return result;
}
// Determine whether body needs to be spooled to file
bool CSecurityPlugin::FileVerifyDecrypt(const CMessage* msg) const
{
// Do based on size of message
return (msg->GetSize() > cFileThreshold);
}
// Verify multipart/signed
bool CSecurityPlugin::VerifyMessage(CMessage* msg, CMessageCryptoInfo& info)
{
bool result = false;
const char* old_data = NULL;
CAttachment* temp_attach = NULL;
bool remove_temp_data = false;
// See whether to use file or not
if (FileVerifyDecrypt(msg))
{
#if __dest_os == __mac_os || __dest_os == __mac_os_x
// Create temporary input file
PPx::FSObject fs_fin;
PPx::FSObject* fin = &fs_fin;
CreateTempFile(fin, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path(fin->GetPath());
// Create temporary data file
PPx::FSObject fs_fin_d;
PPx::FSObject* fin_d = &fs_fin_d;
CreateTempFile(fin_d, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin_d(fin_d);
cdstring fin_d_path(fin_d->GetPath());
#else
// Create temporary input file
cdstring fin;
CreateTempFile(fin, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path = fin;
// Create temporary data file
cdstring fin_d;
CreateTempFile(fin_d, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin_d(fin_d);
cdstring fin_d_path = fin_d;
#endif
{
// Create the temporary file
cdofstream finstream(fin_path, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
costream stream_out(&finstream, eEndl_CRLF);
msg->WriteToStream(stream_out, false, NULL);
}
// Try to parse it out as a local message
cdstring sig;
{
cdifstream buf_in(fin_path, std::ios_base::in|std::ios_base::binary);
CRFC822Parser parser;
std::auto_ptr<CLocalMessage> lmsg(parser.MessageFromStream(buf_in));
buf_in.clear();
// Must have message
if (!lmsg.get() ||
!lmsg->GetBody()->GetParts() ||
(lmsg->GetBody()->GetParts()->size() != 2))
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
// Now get pointers to relevant bits
CAttachmentList* parts = lmsg->GetBody()->GetParts();
unsigned long data_start = static_cast<CLocalAttachment*>(parts->at(0))->GetIndexStart();
unsigned long data_length = static_cast<CLocalAttachment*>(parts->at(0))->GetIndexLength();
unsigned long sig_start = static_cast<CLocalAttachment*>(parts->at(1))->GetIndexBodyStart();
unsigned long sig_length = static_cast<CLocalAttachment*>(parts->at(1))->GetIndexBodyLength();
// Write data into another temp file
{
cdofstream buf_out(fin_d_path, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
::StreamCopy(buf_in, buf_out, data_start, data_length);
}
// Grab signature into internal buffer
// NB Must get the signature data via the message to ensure MIME decoding has taken place for PGP only
{
CAttachment* sig_part = msg->GetBody()->GetParts()->at(1);
msg->ReadAttachment(sig_part, true, GetName() != cSMIMEName);
sig = sig_part->GetData();
}
}
cdstring from;
if (msg->GetEnvelope() && msg->GetEnvelope()->GetFrom() && (msg->GetEnvelope()->GetFrom()->size() != 0))
from = msg->GetEnvelope()->GetFrom()->front()->GetMailAddress();
char* signed_by = NULL;
char* encrypted_to = NULL;
bool did_signature = false;
bool signature_ok = false;
if (DecryptVerifyFile(fin_d, sig, from, NULL, &signed_by, &encrypted_to, &result, &did_signature, &signature_ok, true) != 1)
{
info.SetSuccess(false);
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
info.SetSuccess(result);
info.SetDidSignature(did_signature);
info.SetSignatureOK(signature_ok);
// Get signed by info
if (info.GetDidSignature() && signed_by)
cdstring::FromArray((const char**) signed_by, info.GetSignedBy());
// Get encrypted to info
cdstrvect encryptedTo;
if (encrypted_to)
{
info.SetDidDecrypt(true);
cdstring::FromArray((const char**) encrypted_to, info.GetEncryptedTo());
}
}
else
{
// Read raw message data into temp buffer
std::ostrstream buf;
costream stream_out(&buf, eEndl_CRLF);
msg->WriteToStream(stream_out, false, NULL);
buf << std::ends;
const char* in = buf.str();
buf.freeze(false);
// Try to parse it out as a local message
std::istrstream buf_in(in);
CRFC822Parser parser;
std::auto_ptr<CLocalMessage> lmsg(parser.MessageFromStream(buf_in));
// Must have message
if (!lmsg.get() ||
!lmsg->GetBody()->GetParts() ||
(lmsg->GetBody()->GetParts()->size() != 2))
{
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
// Now get pointers to relevant bits
CAttachmentList* parts = lmsg->GetBody()->GetParts();
unsigned long data_start = static_cast<CLocalAttachment*>(parts->at(0))->GetIndexStart();
unsigned long data_length = static_cast<CLocalAttachment*>(parts->at(0))->GetIndexLength();
unsigned long sig_start = static_cast<CLocalAttachment*>(parts->at(1))->GetIndexBodyStart();
unsigned long sig_length = static_cast<CLocalAttachment*>(parts->at(1))->GetIndexBodyLength();
cdstring from;
if (msg->GetEnvelope() && msg->GetEnvelope()->GetFrom() && (msg->GetEnvelope()->GetFrom()->size() != 0))
from = msg->GetEnvelope()->GetFrom()->front()->GetMailAddress();
// Now form strings
const char* data = in + data_start;
const_cast<char*>(data)[data_length] = 0;
// Grab signature into internal buffer
// NB Must get the signature data via the message to ensure MIME decoding has taken place for PGP only
cdstring sig;
{
CAttachment* sig_part = msg->GetBody()->GetParts()->at(1);
msg->ReadAttachment(sig_part, true, GetName() != cSMIMEName);
sig = sig_part->GetData();
}
char* signed_by = NULL;
char* encrypted_to = NULL;
bool did_signature = false;
bool signature_ok = false;
if (DecryptVerifyData(data, sig, from, NULL, NULL, &signed_by, &encrypted_to, &result, &did_signature, &signature_ok, true) != 1)
{
info.SetSuccess(false);
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
info.SetSuccess(result);
info.SetDidSignature(did_signature);
info.SetSignatureOK(signature_ok);
// Get signed by info
if (info.GetDidSignature() && signed_by)
cdstring::FromArray((const char**) signed_by, info.GetSignedBy());
// Get encrypted to info
cdstrvect encryptedTo;
if (encrypted_to)
{
info.SetDidDecrypt(true);
cdstring::FromArray((const char**) encrypted_to, info.GetEncryptedTo());
}
}
return result;
}
// Decrypt multipart/encrypted
bool CSecurityPlugin::DecryptMessage(CMessage* msg, CMessageCryptoInfo& info, bool use_multi_part)
{
bool result = false;
const char* old_data = NULL;
CAttachment* temp_attach = NULL;
bool remove_temp_data = false;
// See whether to use file or not
if (FileVerifyDecrypt(msg))
{
#if __dest_os == __mac_os || __dest_os == __mac_os_x
// Create temporary input file
PPx::FSObject fs_fin;
PPx::FSObject* fin = &fs_fin;
CreateTempFile(fin, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path(fin->GetPath());
// Create temporary data file
PPx::FSObject fs_fin_d;
PPx::FSObject* fin_d = &fs_fin_d;
CreateTempFile(fin_d, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin_d(fin_d);
cdstring fin_d_path(fin_d->GetPath());
#else
// Create temporary input file
cdstring fin;
CreateTempFile(fin, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin(fin);
cdstring fin_path = fin;
// Create temporary data file
cdstring fin_d;
CreateTempFile(fin_d, eNone, cdstring::null_str);
StRemoveFileSpec _remove_fin_d(fin_d);
cdstring fin_d_path = fin_d;
#endif
{
// Get attachment to write to disk
CAttachment* part2 = NULL;
if (use_multi_part)
part2 = msg->GetBody()->GetParts()->at(1);
else
part2 = msg->GetBody();
// Create the temporary file
cdofstream finstream(fin_path, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
// Get encoding filter
std::auto_ptr<CStreamFilter> filter;
// May need to filter - SMIME always gets raw base64 data
if (GetName() != cSMIMEName)
{
switch(part2->GetContent().GetTransferEncoding())
{
case eNoTransferEncoding:
case e7bitEncoding:
case e8bitEncoding:
// Do nothing
break;
case eQuotedPrintableEncoding:
// Convert from QP
filter.reset(new CStreamFilter(new mime_qp_filterbuf(false)));
filter->SetStream(&finstream);
break;
case eBase64Encoding:
// Convert from base64
filter.reset(new CStreamFilter(new mime_base64_filterbuf(false)));
filter->SetStream(&finstream);
break;
default:;
}
}
costream stream_out(filter.get() ? static_cast<std::ostream*>(filter.get()) : static_cast<std::ostream*>(&finstream), eEndl_CRLF);
part2->WriteDataToStream(stream_out, false, NULL, msg);
}
cdstring from;
if (msg->GetEnvelope() && msg->GetEnvelope()->GetFrom() && (msg->GetEnvelope()->GetFrom()->size() != 0))
from = msg->GetEnvelope()->GetFrom()->front()->GetMailAddress();
char* signed_by = NULL;
char* encrypted_to = NULL;
bool did_signature = false;
bool signature_ok = false;
if (DecryptVerifyFile(fin, NULL, from, fin_d, &signed_by, &encrypted_to, &result, &did_signature, &signature_ok, false) != 1)
{
info.SetSuccess(false);
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
info.SetSuccess(result);
info.SetDidSignature(did_signature);
info.SetSignatureOK(signature_ok);
// Get signed by info
if (info.GetDidSignature() && signed_by)
cdstring::FromArray((const char**) signed_by, info.GetSignedBy());
// Get encrypted to info
cdstrvect encryptedTo;
if (encrypted_to)
{
info.SetDidDecrypt(true);
cdstring::FromArray((const char**) encrypted_to, info.GetEncryptedTo());
}
// Add data to part, remove any old cached data
if (result)
{
// Replace existing part data with output
// Create fstream data
std::auto_ptr<cdifstream> stream(new cdifstream(fin_d_path, std::ios_base::in|std::ios_base::binary));
// Parse RFC822 parts
CRFC822Parser parser(true, msg);
CAttachment* new_body = parser.AttachmentFromStream(*stream, NULL);
static_cast<CStreamAttachment*>(new_body)->SetStream(stream.get(), NULL, fin_d_path);
msg->ReplaceBody(static_cast<CStreamAttachment*>(new_body));
// Stream & temp file are now owned by attachment
_remove_fin_d.release();
stream.release();
}
else
HandleError(&info);
}
else
{
// Get the encrypted data part
CAttachment* part2 = NULL;
if (use_multi_part)
part2 = msg->GetBody()->GetParts()->at(1);
else
part2 = msg->GetBody();
// Make sure its treated as text even though its application/octet-stream
part2->SetFakeText(true);
part2->GetContent().SetDontEncode();
cdstring from;
if (msg->GetEnvelope() && msg->GetEnvelope()->GetFrom() && (msg->GetEnvelope()->GetFrom()->size() != 0))
from = msg->GetEnvelope()->GetFrom()->front()->GetMailAddress();
// Just use current data in this part
msg->ReadAttachment(part2);
const char* in = part2->GetData();
char* out = NULL;
unsigned long out_len = 0;
char* signed_by = NULL;
char* encrypted_to = NULL;
bool did_signature = false;
bool signature_ok = false;
if (DecryptVerifyData(in, NULL, from, &out, &out_len, &signed_by, &encrypted_to, &result, &did_signature, &signature_ok, false) != 1)
{
info.SetSuccess(false);
CLOG_LOGTHROW(CGeneralException, -1);
throw CGeneralException(-1);
}
info.SetSuccess(result);
info.SetDidSignature(did_signature);
info.SetSignatureOK(signature_ok);
// Get signed by info
if (info.GetDidSignature() && signed_by)
cdstring::FromArray((const char**) signed_by, info.GetSignedBy());
// Get encrypted to info
cdstrvect encryptedTo;
if (encrypted_to)
{
info.SetDidDecrypt(true);
cdstring::FromArray((const char**) encrypted_to, info.GetEncryptedTo());
}
// Add data to part, remove any old cached data
if (result)
{
// Replace existing part data with output
if (out)
{
// Create strstream data
cdstring temp(out);
std::auto_ptr<std::istrstream> stream(new std::istrstream(temp.c_str()));
// Parse RFC822 parts
CRFC822Parser parser(true, msg);
CAttachment* new_body = parser.AttachmentFromStream(*stream, NULL);
static_cast<CStreamAttachment*>(new_body)->SetStream(stream.get(), temp.grab_c_str(), cdstring::null_str);
msg->ReplaceBody(static_cast<CStreamAttachment*>(new_body));
// Stream is now owned by attachment
stream.release();
}
}
else
HandleError(&info);
DisposeData(out);
}
// Look for signed content after decrypt (i.e. original was signed then encrypted)
if (result && msg->GetBody()->IsVerifiable())
{
// First make sure the message header is cached as it will be needed when writing to stream
msg->GetHeader();
// Need to create a temporarily remove the message from its mailbox so that WriteToStream writes the parts
// to stream rather than tries to get raw message from mailbox and write that
CMbox* mboxold = msg->GetMbox();
msg->SetMbox(NULL);
try
{
// Now verify signature
CMessageCryptoInfo info2;
result = VerifyDecryptPart(msg, NULL, info2);
// Merge signature data into current info item
info.SetSuccess(info2.GetSuccess());
info.SetDidSignature(info2.GetDidSignature());
info.SetSignatureOK(info2.GetSignatureOK());
info.GetSignedBy() = info2.GetSignedBy();
if (info.GetError().empty())
info.SetError(info2.GetError());
}
catch(...)
{
CLOG_LOGCATCH(...);
// Reset old mailbox info
msg->SetMbox(mboxold);
}
msg->SetMbox(mboxold);
}
return result;
}
#pragma mark ____________________________Errors
long CSecurityPlugin::HandleError(CMessageCryptoInfo* info)
{
// Get error string from plugin
long err = eSecurity_NoErr;
char* error = NULL;
GetLastError(&err, &error);
// Put into verify/decrypt info if present
if (info)
{
// Copy only first line of error
const char* p1 = ::strchr(error, '\r');
const char* p2 = ::strchr(error, '\n');
if ((p1 != NULL) && (p2 != NULL))
p1 = (p1 > p2) ? p2 : p1;
else if (p2 != NULL)
p1 = p2;
if (p1 != NULL)
info->SetError(cdstring(error, p1 - error));
else
info->SetError(error);
if (err == eSecurity_BadPassphrase)
info->SetBadPassphrase(true);
}
// Show error alert in some cases
if ((err != 0) && (err != eSecurity_UserAbort) && ((info == NULL) || CPreferences::sPrefs->mUseErrorAlerts.GetValue()))
CErrorHandler::PutStopAlert(error, true);
// Special support for certian errors
switch(err)
{
case eSecurity_BadPassphrase:
// Remove thre last cached passphrase
if (CPreferences::sPrefs->mCachePassphrase.GetValue())
sPassphrases.erase(sLastPassphraseUID);
break;
default:;
}
return err;
}
#pragma mark ____________________________Memory based
// Sign data
long CSecurityPlugin::SignData(const char* in, const char* key,
char** out, unsigned long* out_len,
bool useMime, bool binary)
{
SSignData info;
info.mInputData = in;
info.mKey = key;
info.mOutputData = out;
info.mOutputDataLength = out_len;
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecuritySignData, &info);
}
// Encrypt data
long CSecurityPlugin::EncryptData(const char* in, const char** to,
char** out, unsigned long* out_len,
bool useMime, bool binary)
{
SEncryptData info;
info.mInputData = in;
info.mKeys = to;
info.mOutputData = out;
info.mOutputDataLength = out_len;
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecurityEncryptData, &info);
}
// Encrypt & sign data
long CSecurityPlugin::EncryptSignData(const char* in, const char** to, const char* key,
char** out, unsigned long* out_len,
bool useMime, bool binary)
{
SEncryptSignData info;
info.mInputData = in;
info.mKeys = to;
info.mSignKey = key;
info.mOutputData = out;
info.mOutputDataLength = out_len;
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecurityEncryptSignData, &info);
}
// Decrypt/verify data
long CSecurityPlugin::DecryptVerifyData(const char* in, const char* sig, const char* in_from,
char** out, unsigned long* out_len, char** out_signedby, char** out_encryptedto,
bool* success, bool* did_sig, bool* sig_ok, bool binary)
{
SDecryptVerifyData info;
info.mInputData = in;
info.mInputSignature = sig;
info.mInputFrom = in_from;
info.mOutputData = out;
info.mOutputDataLength = out_len;
info.mOutputSignedby = out_signedby;
info.mOutputEncryptedto = out_encryptedto;
info.mSuccess = success;
info.mDidSig = did_sig;
info.mSigOK = sig_ok;
info.mBinary = binary;
return CallPlugin(eSecurityDecryptVerifyData, &info);
}
#pragma mark ____________________________File based
// Sign file
long CSecurityPlugin::SignFile(fspec in, const char* key, fspec out, bool useMime, bool binary)
{
SSignFile info;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsin;
in->GetFSSpec(fsin);
info.mInputFile = &fsin;
#else
info.mInputFile = in;
#endif
info.mKey = key;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsout;
out->GetFSSpec(fsout);
info.mOutputFile = &fsout;
#else
info.mOutputFile = out;
#endif
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecuritySignFile, &info);
}
// Encrypt file
long CSecurityPlugin::EncryptFile(fspec in, const char** to, fspec out, bool useMime, bool binary)
{
SEncryptFile info;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsin;
in->GetFSSpec(fsin);
info.mInputFile = &fsin;
#else
info.mInputFile = in;
#endif
info.mKeys = to;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsout;
out->GetFSSpec(fsout);
info.mOutputFile = &fsout;
#else
info.mOutputFile = out;
#endif
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecurityEncryptFile, &info);
}
// Encrypt & sign file
long CSecurityPlugin::EncryptSignFile(fspec in, const char** to, const char* key, fspec out, bool useMime, bool binary)
{
SEncryptSignFile info;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsin;
in->GetFSSpec(fsin);
info.mInputFile = &fsin;
#else
info.mInputFile = in;
#endif
info.mKeys = to;
info.mSignKey = key;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsout;
out->GetFSSpec(fsout);
info.mOutputFile = &fsout;
#else
info.mOutputFile = out;
#endif
info.mUseMIME = useMime;
info.mBinary = binary;
return CallPlugin(eSecurityEncryptSignFile, &info);
}
// Decrypt/verify file
long CSecurityPlugin::DecryptVerifyFile(fspec in, const char* sig, const char* in_from,
fspec out, char** out_signedby, char** out_encryptedto,
bool* success, bool* did_sig, bool* sig_ok, bool binary)
{
SDecryptVerifyFile info;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsin;
in->GetFSSpec(fsin);
info.mInputFile = &fsin;
#else
info.mInputFile = in;
#endif
info.mInputSignature = sig;
info.mInputFrom = in_from;
#if __dest_os == __mac_os || __dest_os == __mac_os_x
FSSpec fsout;
if (out != NULL)
out->GetFSSpec(fsout);
info.mOutputFile = (out != NULL) ? &fsout : NULL;
#else
info.mOutputFile = out;
#endif
info.mOutputSignedby = out_signedby;
info.mOutputEncryptedto = out_encryptedto;
info.mSuccess = success;
info.mDidSig = did_sig;
info.mSigOK = sig_ok;
info.mBinary = binary;
return CallPlugin(eSecurityDecryptVerifyFile, &info);
}
#pragma mark ____________________________Others
long CSecurityPlugin::DisposeData(const char* data)
{
if (data)
return CallPlugin(eSecurityDisposeData, (void*) data);
else
return 1;
}
// Get last error from plugin
long CSecurityPlugin::GetLastError(long* errnum, char** error)
{
SGetLastError info;
info.errnum = errnum;
info.error = error;
return CallPlugin(eSecurityGetLastError, (void*) &info);
}
// Get MIME parameters for signing
long CSecurityPlugin::GetMIMESign(SMIMEMultiInfo* params)
{
return CallPlugin(eSecurityGetMIMEParamsSign, (void*) params);
}
// Get MIME parameters for encryption
long CSecurityPlugin::GetMIMEEncrypt(SMIMEMultiInfo* params)
{
return CallPlugin(eSecurityGetMIMEParamsEncrypt, (void*) params);
}
// Get MIME parameters for encryption and signing
long CSecurityPlugin::GetMIMEEncryptSign(SMIMEMultiInfo* params)
{
return CallPlugin(eSecurityGetMIMEParamsEncryptSign, (void*) params);
}
// Check that MIME type is verifiable by this plugin
long CSecurityPlugin::CanVerifyThis(const char* type)
{
// This can be called when not loaded
StLoadPlugin load(this);
return CallPlugin(eSecurityCanVerifyThis, (void*) type);
}
// Check that MIME type is decryptable by this plugin
long CSecurityPlugin::CanDecryptThis(const char* type)
{
// This can be called when not loaded
StLoadPlugin load(this);
return CallPlugin(eSecurityCanDecryptThis, (void*) type);
}
#pragma mark ____________________________Callbacks
// Set callback into Mulberry
long CSecurityPlugin::SetCallback()
{
return CallPlugin(eSecuritySetCallback, (void*) Callback);
}
// Set callback into Mulberry
long CSecurityPlugin::SetContext()
{
SSMIMEContext context;
if (CPluginManager::sPluginManager.HasSSL())
{
CPluginManager::sPluginManager.GetSSL()->InitSSL();
context.mDLL = CPluginManager::sPluginManager.GetSSL()->GetConnection();
context.mCertMgr = CCertificateManager::sCertificateManager;
return CallPlugin(eSecuritySetSMIMEContext, (void*) &context);
}
else
return 0;
}
bool CSecurityPlugin::Callback(ESecurityPluginCallback type, void* data)
{
switch(type)
{
case eCallbackPassphrase:
{
SCallbackPassphrase* context = reinterpret_cast<SCallbackPassphrase*>(data);
return GetPassphrase(context->users, context->passphrase, context->chosen);
}
default:
return false;
}
}
bool CSecurityPlugin::GetPassphrase(const char** users, char* passphrase, unsigned long& chosen)
{
// Look in passphrase cache for a user
if (CPreferences::sPrefs->mCachePassphrase.GetValue())
{
const char** p = users;
unsigned long index = 0;
while(*p)
{
cdstrmap::const_iterator found = sPassphrases.find(*p++);
if (found != sPassphrases.end())
{
sLastPassphraseUID = (*found).first;
if ((*found).second.length() < 256)
{
// Get temporary passphrase
cdstring temp((*found).second);
temp.Decrypt(cdstring::eEncryptSimplemUTF7);
::strcpy(passphrase, temp);
// Clear memory
::memset(temp.c_str_mod(), 0, temp.length());
chosen = index;
return true;
}
else
return false;
}
index++;
}
}
else
sPassphrases.clear();
// Ask user for passphrase
cdstring new_phrase;
cdstring chosen_user;
unsigned long index = 0;
if (CGetPassphraseDialog::PoseDialog(new_phrase, users, chosen_user, index))
{
if (new_phrase.length() < 256)
{
// Cache the new passphrase
if (CPreferences::sPrefs->mCachePassphrase.GetValue())
{
cdstring temp(new_phrase);
temp.Encrypt(cdstring::eEncryptSimplemUTF7);
sPassphrases.insert(cdstrmap::value_type(chosen_user, temp));
sLastPassphraseUID = chosen_user;
}
::strcpy(passphrase, new_phrase);
// Clear memory
::memset(new_phrase.c_str_mod(), 0, new_phrase.length());
chosen = index;
return true;
}
}
return false;
}
void CSecurityPlugin::ClearLastPassphrase()
{
sPassphrases.erase(sLastPassphraseUID);
}
| 27.690682 | 161 | 0.69642 | [
"object"
] |
b0486754075d6b79523202000543f5dabf0b9b26 | 4,823 | cpp | C++ | luogu/5471/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/5471/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/5471/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | /*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=70005;
const int M=150005;
int n,m;
struct Jump{
int t,L,R,D,U;
};
vector<Jump> J[N];
struct node{
int x,y;
}a[N];
int id[N];
bool cmpx(int x,int y){return a[x].x<a[y].x;}
bool cmpy(int x,int y){return a[x].y<a[y].y;}
int vis[N<<1],dis[N<<1];
struct Node{
int id,dis;
bool operator < (const Node &rhs) const{
return dis>rhs.dis;
}
};
priority_queue<Node> Q;
int sx,sy,ex,ey;
int ls[N],rs[N],tag[N];
int cnt2=0;
struct KD_Tree{
int L[N],R[N],D[N],U[N],typ[N];
void pushup(int x){
L[x]=R[x]=a[x].x; U[x]=D[x]=a[x].y;
if(ls[x]){
checkmax(R[x],R[ls[x]]); checkmin(L[x],L[ls[x]]);
checkmax(U[x],U[ls[x]]); checkmin(D[x],D[ls[x]]);
}
if(rs[x]){
checkmax(R[x],R[rs[x]]); checkmin(L[x],L[rs[x]]);
checkmax(U[x],U[rs[x]]); checkmin(D[x],D[rs[x]]);
}
}
void pushdown(int x){
if(ls[x]){
checkmin(tag[ls[x]],tag[x]);
if(dis[ls[x]]>tag[x]&&!vis[ls[x]]){
dis[ls[x]]=tag[x];
Q.push({ls[x],dis[ls[x]]});
}
}
if(rs[x]){
checkmin(tag[rs[x]],tag[x]);
if(dis[rs[x]]>tag[x]&&!vis[rs[x]]){
dis[rs[x]]=tag[x];
Q.push({rs[x],dis[rs[x]]});
}
}
}
double sqr(double x){return x*x;}
int build(int l,int r){
if(l>r) return 0;
int mid=(l+r)>>1;
double av1=0,av2=0;
for(int i=l;i<=r;i++) av1+=a[id[i]].x,av2+=a[id[i]].y;
av1/=(r-l+1); av2/=(r-l+1);
double sum1=0,sum2=0;
for(int i=l;i<=r;i++)
sum1+=sqr(a[id[i]].x-av1),sum2+=sqr(a[id[i]].y-av2);
if(sum1>sum2) nth_element(id+l,id+mid,id+r+1,cmpx),typ[id[mid]]=0;
else nth_element(id+l,id+mid,id+r+1,cmpy),typ[id[mid]]=1;
ls[id[mid]]=build(l,mid-1); rs[id[mid]]=build(mid+1,r);
pushup(id[mid]); return id[mid];
}
void query(int x,int val){
if(!x) return;
if(dis[x]<val) return;
if(sx<=L[x]&&sy<=D[x]&&ex>=R[x]&&ey>=U[x]){
if(dis[x]>val&&!vis[x]){
dis[x]=val;
Q.push({x,dis[x]});
}
checkmin(tag[x],val);
return;
}
pushdown(x);
if(sx<=a[x].x&&sy<=a[x].y&&ex>=a[x].x&&ey>=a[x].y){
if(dis[x+n]>val&&!vis[x+n]){
dis[x+n]=val;
Q.push({x+n,dis[x+n]});
}
}
if(typ[x]==0){
if(a[x].x>=sx) query(ls[x],val);
if(a[x].x<=ex) query(rs[x],val);
}
else{
if(a[x].y>=sy) query(ls[x],val);
if(a[x].y<=ey) query(rs[x],val);
}
}
}tree;
int root;
void dijkstra(){
for(int i=1;i<=n+n;i++) dis[i]=inf,vis[i]=0;
for(int i=1;i<=n;i++) tag[i]=inf;
dis[n+1]=0; Q.push({n+1,0});
while(!Q.empty()){
int u=Q.top().id; Q.pop();
if(vis[u]) continue; vis[u]=1;
if(u>n) for(auto &E : J[u-n]){
sx=E.L,ex=E.R,sy=E.D,ey=E.U;
tree.query(root,E.t+dis[u]);
}
if(u<=n){
tree.pushdown(u);
if(dis[u+n]>dis[u]&&!vis[u+n]){
dis[u+n]=dis[u];
Q.push({u+n,dis[u+n]});
}
}
}
for(int i=2;i<=n;i++) printf("%d\n",dis[i+n]);
}
void init(){
n=read(); m=read(); read(); read();
for(int i=1;i<=n;i++) a[i].x=read(),a[i].y=read();
for(int i=1;i<=n;i++) id[i]=i;
root=tree.build(1,n);
for(int i=1;i<=m;i++){
int P=read(),T=read(),L=read(),R=read(),D=read(),U=read();
J[P].push_back({T,L,R,D,U});
}
}
int main()
{
init();
dijkstra();
return 0;
} | 28.204678 | 98 | 0.460709 | [
"vector"
] |
b04fa6650b747307163571c41e4c87e7e8a86cbb | 7,962 | cpp | C++ | services/se_standard/src/access_rule_application_controller.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | services/se_standard/src/access_rule_application_controller.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | services/se_standard/src/access_rule_application_controller.cpp | dawmlight/communication_nfc | 84a10d69eb9cb3128e864230c53d5a5e6660dfb9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* 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 "access_rule_application_controller.h"
#include "access_rule_cache.h"
#include "channel_access_rule.h"
#include "context.h"
#include "general-data-objects/ar_do.h"
#include "general-data-objects/ref_ar_do.h"
#include "general-data-objects/ref_do.h"
#include "general-data-objects/response_all_ar_do.h"
#include "general-data-objects/response_refresh_tag_do.h"
#include "loghelper.h"
#include "resources.h"
#include "se_channel.h"
#include "se_common_exception.h"
#include "terminal.h"
namespace OHOS::se::security {
AccessRuleApplicationController::AccessRuleApplicationController(std::weak_ptr<AccessRuleCache> accessRuleCache,
std::weak_ptr<Terminal> terminal)
: accessRuleCache_(accessRuleCache), terminal_(terminal), accessControlAid_(ARA_M_AID)
{
}
AccessRuleApplicationController::~AccessRuleApplicationController() {}
void AccessRuleApplicationController::Initialize()
{
InfoLog("AccessRuleApplicationController::Initialize");
std::shared_ptr<Terminal> terminal = terminal_.lock();
if (!terminal) {
ErrorLog("Terminal has expired");
throw AccessControlError("Terminal has expired");
}
std::shared_ptr<AccessRuleCache> accessRuleCache = accessRuleCache_.lock();
if (!accessRuleCache) {
ErrorLog("AccessRuleCache has expired");
throw AccessControlError("AccessRuleCache has expired");
}
std::shared_ptr<OHOS::se::SeChannel> channel = std::shared_ptr<OHOS::se::SeChannel>();
// Get aid list from resource
std::vector<std::string> aidList;
if (terminal->GetName().substr(0, 3) == "eSE") {
std::shared_ptr<osal::Context> context = (terminal->GetContext()).lock();
std::shared_ptr<osal::Resources> resources = context->GetResources().lock();
// ese config ara aid
std::string* pStr = resources->GetStringArray(osal::R::config_ara_aid_list_ese);
aidList.assign(pStr, pStr + (resources->GetInt(osal::R::config_ara_aid_list_ese_length)));
}
for (std::string aid : aidList) {
try {
channel = terminal->OpenLogicalChannelForAccessControl(aid);
if (!channel) {
ErrorLog("Could not open channel");
throw MissingResourceError("Could not open channel");
}
accessControlAid_ = aid;
break;
} catch (const NoSuchElementError& e) {
ErrorLog("Applet %s is not accessible", aid.c_str());
continue;
}
}
if (!channel) {
channel = (terminal->OpenLogicalChannelForAccessControl(ARA_M_AID));
if (!channel) {
ErrorLog("Could not open channel");
throw MissingResourceError("Could not open channel");
}
}
try {
std::shared_ptr<ChannelAccessRule> channelAccessRule = std::make_shared<ChannelAccessRule>();
channelAccessRule->SetAccessRule(ChannelAccessRule::ACCESSRULE::ALWAYS, "");
channelAccessRule->SetApduAccessRule(ChannelAccessRule::ACCESSRULE::ALWAYS);
channel->SetChannelAccess(channelAccessRule);
// Retrieve a refresh tag indicating whether any access rules have been updated.
std::string refreshTag = this->GetRefreshTag(channel);
if (accessRuleCache->CompareRefreshTag(refreshTag)) {
InfoLog("RefreshTag has not changed");
channel->Close();
return;
}
// update refresh tag, re-read all access rules
InfoLog("RefreshTag has changed");
accessRuleCache->ClearAccessRules();
std::vector<RefArDo> refArDoArray = this->GetAllAccessRules(channel);
for (size_t i = 0; i < refArDoArray.size(); i++) {
accessRuleCache->AddAccessRule((refArDoArray.at(i)).GetRefDo(), (refArDoArray.at(i)).GetArDo());
}
accessRuleCache->SetRefreshTag(refreshTag);
channel->Close();
} catch (const std::runtime_error& error) {
channel->Close();
throw error;
}
}
std::string AccessRuleApplicationController::GetAraMAid()
{
return ARA_M_AID;
}
std::string AccessRuleApplicationController::GetAccessControlAid()
{
return accessControlAid_;
}
std::string AccessRuleApplicationController::GetRefreshTag(std::shared_ptr<OHOS::se::SeChannel> channel)
{
InfoLog("AccessRuleApplicationController::GetRefreshTag");
std::string responseRefreshTag = this->GetDataRefreshTag(channel);
std::shared_ptr<BerTlv> bt = BerTlv::StrToBerTlv(responseRefreshTag);
std::shared_ptr<ResponseRefreshTagDo> rrtd = ResponseRefreshTagDo::BerTlvToResponseRefreshTagDo(bt);
return rrtd->GetRefreshTag();
}
std::vector<RefArDo> AccessRuleApplicationController::GetAllAccessRules(std::shared_ptr<OHOS::se::SeChannel> channel)
{
InfoLog("AccessRuleApplicationController::GetAllAccessRules");
// GET DATA [All]: Fetches the first bytes of the Response-ALL-AR-DO
std::string responseAll = this->GetDataAll(channel);
std::shared_ptr<BerTlv> bt = BerTlv::StrToBerTlv(responseAll);
int valueLength = bt->GetValue().length();
while (valueLength < bt->GetLength()) {
// GET DATA [Next]: Fetches the next (succeeding) bytes of the Response-ALL-AR-DO
std::string responseNext = this->GetDataNext(channel);
responseAll += responseNext;
valueLength += responseNext.length();
}
bt = BerTlv::StrToBerTlv(responseAll);
std::shared_ptr<ResponseAllArDo> raad = ResponseAllArDo::BerTlvToResponseAllArDo(bt);
return raad->GetRefArDoArray();
}
std::string AccessRuleApplicationController::GetDataRefreshTag(std::shared_ptr<OHOS::se::SeChannel> channel)
{
DebugLog("GET DATA [Refresh Tag]");
std::string response = channel->Transmit(GET_DATA_REFRESH_TAG);
if (this->ResponseIsSuccess(response)) {
return response.substr(0, response.length() - 2);
}
ErrorLog("GET DATA [Refresh Tag] not success");
throw AccessControlError("GET DATA [Refresh Tag] not success");
}
std::string AccessRuleApplicationController::GetDataAll(std::shared_ptr<OHOS::se::SeChannel> channel)
{
DebugLog("GET DATA [All]");
std::string response = channel->Transmit(GET_DATA_ALL);
if (this->ResponseIsSuccess(response)) {
return response.substr(0, response.length() - 2);
}
ErrorLog("GET DATA [All] not success");
throw AccessControlError("GET DATA [All] not success");
}
std::string AccessRuleApplicationController::GetDataNext(std::shared_ptr<OHOS::se::SeChannel> channel)
{
DebugLog("GET DATA [Next]");
std::string response = channel->Transmit(GET_DATA_NEXT);
if (this->ResponseIsSuccess(response)) {
return response.substr(0, response.length() - 2);
}
ErrorLog("GET DATA [Next] not success");
throw AccessControlError("GET DATA [Next] not success");
}
bool AccessRuleApplicationController::ResponseIsSuccess(std::string response)
{
if (response.size() < 2) {
return false;
}
int sw1 = response.at(response.length() - 2);
int sw2 = response.at(response.length() - 1);
int status = (sw1 << 8) | sw2;
if (status == 0x9000) {
DebugLog("Response is success");
return true;
} else {
DebugLog("Reponse is not success, status=0x%04X", status);
return false;
}
}
} // namespace OHOS::se::security | 40.212121 | 117 | 0.684878 | [
"vector"
] |
b05579d95c765d248d3bab9092583e3767a8ec72 | 2,885 | hpp | C++ | src/engine/processing/ConvolutionPyramid.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 399 | 2019-05-25T16:05:59.000Z | 2022-03-31T23:38:04.000Z | src/engine/processing/ConvolutionPyramid.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 3 | 2019-07-23T21:03:33.000Z | 2020-12-14T12:47:51.000Z | src/engine/processing/ConvolutionPyramid.hpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 20 | 2019-06-08T17:15:01.000Z | 2022-03-21T11:20:14.000Z | #pragma once
#include "graphics/Framebuffer.hpp"
#include "resources/ResourcesManager.hpp"
#include "Common.hpp"
/**
\brief Implements a multiscale scheme for approximating convolution with large filters.
This is the basis of the technique described in Convolution Pyramids, Farbman et al., 2011.
A set of filter parameters can be estimated through an offline optimization for each desired task:
gradient field integration, seamless image cloning, background filling, or scattered data interpolation.
\ingroup Processing
*/
class ConvolutionPyramid {
public:
/** Constructor.
\param width internal processing width
\param height internal processing height
\param inoutPadding additional padding applied everywhere except on the final result texture
\note This is mainly used for the gradient integration task.
*/
ConvolutionPyramid(unsigned int width, unsigned int height, unsigned int inoutPadding);
/** Setup the filters parameters for a given task.
\param h1 the 5 coefficients of h1
\param h2 the multiplier coefficient h2
\param g the 3 coefficients of g
\note See Convolution Pyramids, Farbman et al., 2011 for the notation details.
*/
void setFilters(const float h1[5], float h2, const float g[3]);
/** Filter a given input texture.
\param texture the GPU ID of the texture
*/
void process(const Texture * texture);
/** Resize the internal buffers.
\param width the new width
\param height the new height
*/
void resize(unsigned int width, unsigned int height);
/** The GPU ID of the filter result.
\return the ID of the result texture
*/
const Texture * texture() const { return _shifted->texture(); }
/** Returns the width expected for the input texture.
\return the width expected
*/
unsigned int width() { return _resolution[0]; }
/** Returns the height expected for the input texture.
\return the height expected
*/
unsigned int height() { return _resolution[1]; }
private:
Program * _downscale; ///< Pyramid descending pass shader.
Program * _upscale; ///< Pyramid ascending pass shader.
Program * _filter; ///< Filtering shader for the last pyramid level.
Program * _padder; ///< Padding helper shader.
std::unique_ptr<Framebuffer> _shifted; ///< Contains the input data padded to the right size.
std::vector<std::unique_ptr<Framebuffer>> _levelsIn; ///< The initial levels of the pyramid.
std::vector<std::unique_ptr<Framebuffer>> _levelsOut; ///< The filtered levels of the pyramid.
float _h1[5] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; ///< h1 filter coefficients.
float _h2 = 0.0f; ///< h2 filter multiplier.
float _g[3] = {0.0f, 0.0f, 0.0f}; ///< g filter coefficients.
glm::ivec2 _resolution = glm::ivec2(0); ///< Resolution expected for the input texture.
const int _size = 5; ///< Size of the filter.
int _padding = 0; ///< Additional padding.
};
| 37.960526 | 105 | 0.721664 | [
"vector"
] |
b056381bfc5771b8ac1f946090b155cdd8e15ea4 | 20,815 | cpp | C++ | src/tools/ControllerTest.cpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 399 | 2019-05-25T16:05:59.000Z | 2022-03-31T23:38:04.000Z | src/tools/ControllerTest.cpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 3 | 2019-07-23T21:03:33.000Z | 2020-12-14T12:47:51.000Z | src/tools/ControllerTest.cpp | kosua20/Rendu | 6b8e730f16658738572bc2f49e08fc4a2c59df07 | [
"MIT"
] | 20 | 2019-06-08T17:15:01.000Z | 2022-03-21T11:20:14.000Z | #include "input/Input.hpp"
#include "system/System.hpp"
#include "system/Config.hpp"
#include "system/Window.hpp"
#include "resources/ResourcesManager.hpp"
#include "input/controller/RawController.hpp"
#include "graphics/Framebuffer.hpp"
#include "graphics/GPU.hpp"
#include "Common.hpp"
/**
\defgroup ControllerTest Controller Test
\brief Configuration tool to generate and test controller mappings.
\ingroup Tools
*/
/** \brief Display a numbered combo list for a given button or axis mapping.
\param label title of the combo
\param count number of items
\param prefix prefix to apply to each item in the list
\param currentId the currently selected item
\ingroup ControllerTest
*/
void showCombo(const std::string & label, const int count, const std::string & prefix, int & currentId) {
const std::string currentLabel = currentId >= 0 ? (prefix + std::to_string(currentId)) : "None";
if(ImGui::BeginCombo(label.c_str(), currentLabel.c_str())) {
for(int i = -1; i < count; i++) {
const bool itemSelected = currentId == i;
const std::string lS = i < 0 ? "None" : (prefix + std::to_string(i));
ImGui::PushID(reinterpret_cast<void *>(static_cast<intptr_t>(i)));
if(ImGui::Selectable(lS.c_str(), itemSelected)) {
currentId = i;
}
if(itemSelected)
ImGui::SetItemDefaultFocus();
ImGui::PopID();
}
ImGui::EndCombo();
}
}
/** \brief Draw raw geometry for highlighting a given controller button.
\param drawList the ImGui drawing list to use
\param bid the ID of the button to draw
\param pos the reference position on screen (upper-left corner of the controller overlay)
\param highlightColor the color to use for the highlight
\ingroup ControllerTest
*/
void drawButton(ImDrawList * drawList, const Controller::Input bid, const ImVec2 & pos, const ImU32 highlightColor) {
switch(bid) {
case Controller::Input::ButtonX:
drawList->AddCircleFilled(ImVec2(pos.x + 326, pos.y + 118), 12, highlightColor);
break;
case Controller::Input::ButtonY:
drawList->AddCircleFilled(ImVec2(pos.x + 351, pos.y + 93), 12, highlightColor);
break;
case Controller::Input::ButtonA:
drawList->AddCircleFilled(ImVec2(pos.x + 351, pos.y + 143), 12, highlightColor);
break;
case Controller::Input::ButtonB:
drawList->AddCircleFilled(ImVec2(pos.x + 376, pos.y + 118), 12, highlightColor);
break;
case Controller::Input::BumperL1:
drawList->AddRectFilled(ImVec2(pos.x + 69, pos.y + 43), ImVec2(pos.x + 137, pos.y + 67), highlightColor, 5.0);
break;
case Controller::Input::TriggerL2: {
const std::vector<ImVec2> pointsL2 = {
ImVec2(pos.x + 67, pos.y + 36),
ImVec2(pos.x + 75, pos.y + 20),
ImVec2(pos.x + 90, pos.y + 11),
ImVec2(pos.x + 111, pos.y + 10),
ImVec2(pos.x + 126, pos.y + 19),
ImVec2(pos.x + 137, pos.y + 36)};
drawList->AddConvexPolyFilled(&pointsL2[0], int(pointsL2.size()), highlightColor);
break;
}
case Controller::Input::ButtonL3:
drawList->AddCircleFilled(ImVec2(pos.x + 154, pos.y + 179), 26, highlightColor);
break;
case Controller::Input::BumperR1:
drawList->AddRectFilled(ImVec2(pos.x + 316, pos.y + 43), ImVec2(pos.x + 384, pos.y + 67), highlightColor, 5.0);
break;
case Controller::Input::TriggerR2: {
const std::vector<ImVec2> pointsR2 = {
ImVec2(pos.x + 67 + 248, pos.y + 36),
ImVec2(pos.x + 75 + 248, pos.y + 20),
ImVec2(pos.x + 90 + 248, pos.y + 11),
ImVec2(pos.x + 111 + 248, pos.y + 10),
ImVec2(pos.x + 126 + 248, pos.y + 19),
ImVec2(pos.x + 137 + 248, pos.y + 36)};
drawList->AddConvexPolyFilled(&pointsR2[0], int(pointsR2.size()), highlightColor);
} break;
case Controller::Input::ButtonR3:
drawList->AddCircleFilled(ImVec2(pos.x + 296, pos.y + 179), 26, highlightColor);
break;
case Controller::Input::ButtonUp:
drawList->AddRectFilled(ImVec2(pos.x + 90, pos.y + 82), ImVec2(pos.x + 107, pos.y + 106), highlightColor, 5.0);
break;
case Controller::Input::ButtonLeft:
drawList->AddRectFilled(ImVec2(pos.x + 62, pos.y + 110), ImVec2(pos.x + 87, pos.y + 126), highlightColor, 5.0);
break;
case Controller::Input::ButtonDown:
drawList->AddRectFilled(ImVec2(pos.x + 90, pos.y + 132), ImVec2(pos.x + 107, pos.y + 156), highlightColor, 5.0);
break;
case Controller::Input::ButtonRight:
drawList->AddRectFilled(ImVec2(pos.x + 112, pos.y + 110), ImVec2(pos.x + 137, pos.y + 126), highlightColor, 5.0);
break;
case Controller::Input::ButtonLogo:
drawList->AddCircleFilled(ImVec2(pos.x + 225, pos.y + 120), 24, highlightColor);
break;
case Controller::Input::ButtonMenu:
drawList->AddCircleFilled(ImVec2(pos.x + 275, pos.y + 96), 13, highlightColor);
break;
case Controller::Input::ButtonView:
drawList->AddCircleFilled(ImVec2(pos.x + 175, pos.y + 96), 13, highlightColor);
break;
default:
break;
}
}
/**
\brief Draw a target circle and threshold along with the current pad position.
\param idX the ID of the horizontal axis
\param idY the ID of the vertical axis
\param axesValues the axes raw values
\param threshRadius the radius of the filtering threshold
\ingroup ControllerTest
*/
void drawPadTarget(const int idX, const int idY, const std::vector<float> & axesValues, const float threshRadius) {
const ImU32 whiteColor = IM_COL32(255, 255, 255, 255);
const int aidRX = idX;
const int aidRY = idY;
const float magRX = aidRX >= 0 ? axesValues[aidRX] : 0.0f;
const float magRY = aidRY >= 0 ? axesValues[aidRY] : 0.0f;
// Detect overflow on each axis.
const bool overflow = (std::abs(magRX) > 1.0) || (std::abs(magRY) > 1.0);
// Get current rendering position on screen.
const ImVec2 posR = ImGui::GetCursorScreenPos();
ImDrawList * drawListR = ImGui::GetWindowDrawList();
// Draw "safe" region.
drawListR->AddRectFilled(posR, ImVec2(posR.x + 200, posR.y + 200), overflow ? IM_COL32(30, 0, 0, 255) : IM_COL32(0, 30, 0, 255));
drawListR->AddCircleFilled(ImVec2(posR.x + 100, posR.y + 100), threshRadius, IM_COL32(0, 0, 0, 255), 32);
// Draw frame and cross lines.
drawListR->AddRect(posR, ImVec2(posR.x + 200, posR.y + 200), overflow ? IM_COL32(255, 0, 0, 255) : whiteColor);
drawListR->AddLine(ImVec2(posR.x + 100, posR.y), ImVec2(posR.x + 100, posR.y + 200), whiteColor);
drawListR->AddLine(ImVec2(posR.x, posR.y + 100), ImVec2(posR.x + 200, posR.y + 100), whiteColor);
// Draw threshold and unit radius circles.
drawListR->AddCircle(ImVec2(posR.x + 100, posR.y + 100), threshRadius, IM_COL32(0, 255, 0, 255), 32);
drawListR->AddCircle(ImVec2(posR.x + 100, posR.y + 100), 100, whiteColor, 32);
// Current axis position.
drawListR->AddCircleFilled(ImVec2(posR.x + magRX * 100 + 100, posR.y + magRY * 100 + 100), 10, whiteColor);
}
/**
\brief Draw a target line and threshold along with the current trigger position.
\param idT the ID of the trigger axis
\param axesValues the axes raw values
\param threshRadius the value of the filtering threshold
\ingroup ControllerTest
*/
void drawTriggerTarget(const int idT, const std::vector<float> & axesValues, const float threshRadius) {
const ImU32 whiteColor = IM_COL32(255, 255, 255, 255);
const int aidLT = idT;
const float magLT = aidLT >= 0 ? axesValues[aidLT] * 0.5f + 0.5f : 0.0f;
// Detect overflow.
const bool overflow = (magLT > 1.0f || magLT < 0.0f);
// Get current rendering position on screen.
const ImVec2 posR = ImGui::GetCursorScreenPos();
ImDrawList * drawListR = ImGui::GetWindowDrawList();
const float thresholdY = (200.0f - 2.0f * threshRadius);
const float currentY = 200 * (1.0f - magLT);
// Draw "safe" region.
drawListR->AddRectFilled(posR, ImVec2(posR.x + 40, posR.y + thresholdY), overflow ? IM_COL32(30, 0, 0, 255) : IM_COL32(0, 30, 0, 255));
// Draw threshold line.
drawListR->AddLine(ImVec2(posR.x, posR.y + thresholdY), ImVec2(posR.x + 40, posR.y + thresholdY), IM_COL32(0, 255, 0, 255));
// Draw frame.
drawListR->AddRect(posR, ImVec2(posR.x + 40, posR.y + 200), overflow ? IM_COL32(255, 0, 0, 255) : whiteColor);
// Current axis position.
drawListR->AddLine(ImVec2(posR.x, posR.y + currentY), ImVec2(posR.x + 40, posR.y + currentY), whiteColor, 4.0f);
}
/**
The main function of the controller tester.
\param argc the number of input arguments.
\param argv a pointer to the raw input arguments.
\return a general error code.
\ingroup ControllerTest
*/
int main(int argc, char ** argv) {
// First, init/parse/load configuration.
RenderingConfig config(std::vector<std::string>(argv, argv + argc));
if(config.showHelp()) {
return 0;
}
// Override window dimensions.
config.initialWidth = 800;
config.initialHeight = 800;
Window window("Controller test", config);
// Enable raw mode for the input, that way all controllers will be raw controllers.
Input::manager().preferRawControllers(true);
// Will contain reference button/axes to raw input mappings.
std::vector<int> buttonsMapping(uint(Controller::InputCount), -1);
std::vector<int> axesMapping(uint(Controller::InputCount), -1);
// Controller texture.
const Texture * controllerTex = Resources::manager().getTexture("ControllerLayout", Layout::RGBA8, Storage::GPU);
bool firstFrame = true;
const ImU32 highlightColor = IM_COL32(172, 172, 172, 255);
float threshold = 0.02f;
// Start the display/interaction loop.
while(window.nextFrame()) {
// Detect either a new connected controller or a first frame with an already connected controller.
if(Input::manager().controllerConnected() || (firstFrame && Input::manager().controllerAvailable())) {
firstFrame = false;
const RawController * controller = dynamic_cast<RawController *>(Input::manager().controller());
const int axesCount = int(controller->allAxes.size());
const int buttonsCount = int(controller->allButtons.size());
// Check if some elements were already modified.
bool wereEmpty = true;
for(int & button : buttonsMapping) {
if(wereEmpty && button >= 0) {
wereEmpty = false;
}
// Update mapping for extraneous button IDs.
if(button >= buttonsCount) {
button = -1;
}
}
for(int & axe : axesMapping) {
if(wereEmpty && axe >= 0) {
wereEmpty = false;
}
if(axe >= axesCount) {
axe = -1;
}
}
// If everything was -1 (first launch), attribute the buttons and axes sequentially, just to help with the visualisation and assignment.
if(wereEmpty) {
for(int i = 0; i < std::min(int(buttonsMapping.size()), buttonsCount); ++i) {
buttonsMapping[i] = i;
}
// Start from the end for the axes.
for(int i = 0; i < std::min(int(axesMapping.size()), axesCount); ++i) {
const int actionId = int(axesMapping.size()) - 1 - i;
// Avoid double mappings.
if(buttonsMapping[actionId] >= 0) {
continue;
}
axesMapping[actionId] = i;
}
}
}
// Render nothing.
const glm::ivec2 screenSize = Input::manager().size();
Framebuffer::backbuffer()->bind(glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), Framebuffer::Operation::DONTCARE, Framebuffer::Operation::DONTCARE);
GPU::setViewport(0, 0, screenSize[0], screenSize[1]);
// Set a fullscreen fixed window.
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowBgAlpha(1.0f);
ImGui::SetNextWindowSize(ImGui::GetIO().DisplaySize);
const ImGuiWindowFlags windowOptions = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar;
if(ImGui::Begin("Controller", nullptr, windowOptions)) {
if(!Input::manager().controllerAvailable()) {
ImGui::Text("No controller connected.");
} else {
// Load/save configuration files.
if(ImGui::Button("Load...")) {
std::string inputPath;
const bool res = System::showPicker(System::Picker::Load, "", inputPath);
if(res && !inputPath.empty()) {
const std::string settingsContent = Resources::loadStringFromExternalFile(inputPath);
Controller::parseConfiguration(settingsContent, axesMapping, buttonsMapping);
}
}
ImGui::SameLine();
if(ImGui::Button("Save...")) {
std::string outputPath;
const bool res = System::showPicker(System::Picker::Save, "", outputPath);
if(res && !outputPath.empty()) {
const Controller * controller = Input::manager().controller();
Controller::saveConfiguration(outputPath, controller->guid(), controller->name(), axesMapping, buttonsMapping);
}
}
ImGui::Separator();
// Infos on the controller.
RawController * controller = dynamic_cast<RawController *>(Input::manager().controller());
const int axesCount = int(controller->allAxes.size());
const int buttonsCount = int(controller->allButtons.size());
ImGui::Text("%s, id: %d, axes: %d, buttons: %d", controller->name().c_str(), controller->id(), axesCount, buttonsCount);
// Display raw axes and buttons and update their display when the user interacts with them.
if(ImGui::CollapsingHeader("Raw inputs##HEADER", ImGuiTreeNodeFlags_DefaultOpen)) {
ImGui::Columns(2);
for(int aid = 0; aid < axesCount; ++aid) {
const std::string axisName = "A" + std::to_string(aid);
ImGui::SliderFloat(axisName.c_str(), &controller->allAxes[aid], -1.0f, 1.0f);
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::Columns(10);
for(int bid = 0; bid < buttonsCount; ++bid) {
const std::string buttonName = "B" + std::to_string(bid);
ImGui::RadioButton(buttonName.c_str(), controller->allButtons[bid].pressed);
ImGui::NextColumn();
}
ImGui::Columns(1);
}
if(ImGui::CollapsingHeader("Assignment##HEADER", ImGuiTreeNodeFlags_DefaultOpen)) {
// Display the controller layout, highlight pressed buttons.
ImGui::BeginChild("##ControllerLayout", ImVec2(450, 300));
// Get current rnedering position on screen.
const ImVec2 pos = ImGui::GetCursorScreenPos();
ImDrawList * drawList = ImGui::GetWindowDrawList();
// Render the left pad first.
const int aidLX = axesMapping[Controller::PadLeftX];
const int aidLY = axesMapping[Controller::PadLeftY];
const float magLX = aidLX >= 0 ? controller->allAxes[aidLX] : 0.0f;
const float magLY = aidLY >= 0 ? controller->allAxes[aidLY] : 0.0f;
if((aidLX >= 0 || aidLY >= 0) && (magLX * magLX + magLY * magLY > threshold)) {
drawList->AddCircleFilled(ImVec2(pos.x + 154, pos.y + 179), 34, highlightColor);
drawList->AddCircleFilled(ImVec2(pos.x + 154, pos.y + 179), 26, IM_COL32(0, 0, 0, 255));
}
// Then the right pad.
const int aidRX = axesMapping[Controller::PadRightX];
const int aidRY = axesMapping[Controller::PadRightY];
const float magRX = aidRX >= 0 ? controller->allAxes[aidRX] : 0.0f;
const float magRY = aidRY >= 0 ? controller->allAxes[aidRY] : 0.0f;
if((aidRX >= 0 || aidRY >= 0) && (magRX * magRX + magRY * magRY > threshold)) {
drawList->AddCircleFilled(ImVec2(pos.x + 296, pos.y + 179), 34, highlightColor);
drawList->AddCircleFilled(ImVec2(pos.x + 296, pos.y + 179), 26, IM_COL32(0, 0, 0, 255));
}
// Render the left trigger (assuming its default value is -1.0).
const int aidLT = axesMapping[Controller::TriggerL2];
const float magLT = aidLT >= 0 ? controller->allAxes[aidLT] * 0.5f + 0.5f : 0.0f;
if(aidLT >= 0 && (magLT * magLT > threshold)) {
drawButton(drawList, Controller::TriggerL2, pos, highlightColor);
}
// And the right trigger (assuming its default value is -1.0).
const int aidRT = axesMapping[Controller::TriggerR2];
const float magRT = aidRT >= 0 ? controller->allAxes[aidRT] * 0.5f + 0.5f : 0.0f;
if(aidRT >= 0 && (magRT * magRT > threshold)) {
drawButton(drawList, Controller::TriggerR2, pos, highlightColor);
}
// Render each button if active.
for(int bid = 0; bid < int(buttonsMapping.size()); ++bid) {
const int bmid = buttonsMapping[bid];
if(bmid >= 0 && controller->allButtons[bmid].pressed) {
drawButton(drawList, Controller::Input(bid), pos, highlightColor);
}
}
// Overlay the controller transparent texture.
ImGui::Image(*controllerTex, ImVec2(450, 300));
ImGui::EndChild();
ImGui::SameLine();
// Display combo selectors to assign raw input to each button.
ImGui::BeginChild("##Layout selection", ImVec2(0, 300));
ImGui::PushItemWidth(80);
const float spacing = 160.0f;
showCombo("A", buttonsCount, "B", buttonsMapping[Controller::ButtonA]);
ImGui::SameLine(spacing);
showCombo("B", buttonsCount, "B", buttonsMapping[Controller::ButtonB]);
showCombo("X", buttonsCount, "B", buttonsMapping[Controller::ButtonX]);
ImGui::SameLine(spacing);
showCombo("Y", buttonsCount, "B", buttonsMapping[Controller::ButtonY]);
showCombo("Up", buttonsCount, "B", buttonsMapping[Controller::ButtonUp]);
ImGui::SameLine(spacing);
showCombo("Left", buttonsCount, "B", buttonsMapping[Controller::ButtonLeft]);
showCombo("Down", buttonsCount, "B", buttonsMapping[Controller::ButtonDown]);
ImGui::SameLine(spacing);
showCombo("Right", buttonsCount, "B", buttonsMapping[Controller::ButtonRight]);
showCombo("L1", buttonsCount, "B", buttonsMapping[Controller::BumperL1]);
ImGui::SameLine(spacing);
showCombo("R1", buttonsCount, "B", buttonsMapping[Controller::BumperR1]);
showCombo("L2", buttonsCount, "B", buttonsMapping[Controller::TriggerL2]);
ImGui::SameLine(spacing);
showCombo("R2", buttonsCount, "B", buttonsMapping[Controller::TriggerR2]);
showCombo("L3", buttonsCount, "B", buttonsMapping[Controller::ButtonL3]);
ImGui::SameLine(spacing);
showCombo("R3", buttonsCount, "B", buttonsMapping[Controller::ButtonR3]);
showCombo("Menu", buttonsCount, "B", buttonsMapping[Controller::ButtonMenu]);
ImGui::SameLine(spacing);
showCombo("View", buttonsCount, "B", buttonsMapping[Controller::ButtonView]);
showCombo("Logo", buttonsCount, "B", buttonsMapping[Controller::ButtonLogo]);
ImGui::Separator();
showCombo("Left X", axesCount, "A", axesMapping[Controller::PadLeftX]);
ImGui::SameLine(spacing);
showCombo("Left Y", axesCount, "A", axesMapping[Controller::PadLeftY]);
showCombo("Right X", axesCount, "A", axesMapping[Controller::PadRightX]);
ImGui::SameLine(spacing);
showCombo("Right Y", axesCount, "A", axesMapping[Controller::PadRightY]);
showCombo("L. trigger", axesCount, "A", axesMapping[Controller::TriggerL2]);
ImGui::SameLine(spacing);
showCombo("R. trigger", axesCount, "A", axesMapping[Controller::TriggerR2]);
ImGui::PopItemWidth();
ImGui::EndChild();
}
// Display targets with the current axis positions.
if(ImGui::CollapsingHeader("Calibration##HEADER", ImGuiTreeNodeFlags_DefaultOpen)) {
const float threshRadius = sqrt(threshold) * 100;
// Titles.
ImGui::Text("Threshold");
ImGui::SameLine(100);
ImGui::Text("Left pad & trigger");
ImGui::SameLine(300+100);
ImGui::Text("Right pad & trigger");
// Add threshold setup slider.
ImGui::VSliderFloat("##threshold", ImVec2(50, 200), &threshold, 0.0f, 1.0f, "%.3f");
ImGui::SameLine(100);
// Left pad.
ImGui::BeginChild("PadLeftTarget", ImVec2(200, 200));
drawPadTarget(axesMapping[Controller::PadLeftX], axesMapping[Controller::PadLeftY], controller->allAxes, threshRadius);
ImGui::EndChild();
ImGui::SameLine(320);
// Left trigger
ImGui::BeginChild("TriggerL2", ImVec2(40, 200));
drawTriggerTarget(axesMapping[Controller::TriggerL2], controller->allAxes, threshRadius);
ImGui::EndChild();
ImGui::SameLine(400);
// Right pad.
ImGui::BeginChild("PadRightTarget", ImVec2(200, 200));
drawPadTarget(axesMapping[Controller::PadRightX], axesMapping[Controller::PadRightY], controller->allAxes, threshRadius);
ImGui::EndChild();
// Right trigger
ImGui::SameLine(620);
ImGui::BeginChild("TriggerR2", ImVec2(40, 200));
drawTriggerTarget(axesMapping[Controller::TriggerR2], controller->allAxes, threshRadius);
ImGui::EndChild();
}
}
}
ImGui::End();
}
return 0;
}
| 43.455115 | 189 | 0.658419 | [
"geometry",
"render",
"vector"
] |
b05efda814c41271143b643670599f167e289fa0 | 1,267 | cxx | C++ | examples/example2.cxx | PeteLealiieeJ/MultiVariateRNG | 30f0bbba65e0173eb54ef52b244376328831dc4d | [
"MIT"
] | null | null | null | examples/example2.cxx | PeteLealiieeJ/MultiVariateRNG | 30f0bbba65e0173eb54ef52b244376328831dc4d | [
"MIT"
] | null | null | null | examples/example2.cxx | PeteLealiieeJ/MultiVariateRNG | 30f0bbba65e0173eb54ef52b244376328831dc4d | [
"MIT"
] | null | null | null | #include <MultiVariRNG.h>
#include <vector>
#include <Eigen/Dense>
// CHECKING/PROVING COVARIANCE TRANSFORM
int main(){
int nsamp = 10000;
Eigen::Matrix3d covar;
// SAMPLE COVARIANVE FROM UNNAMED SIMULATED SENSOR
covar << 3.74594018895874e-05, 1.07418247112003e-05, -6.33235754470261e-06,
1.07418247112003e-05, 0.000115064443419884 ,-4.66088712363351e-05,
-6.33235754470261e-06, -4.66088712363351e-05, 6.34761546905283e-05;
Eigen::Vector3d mean{1,2,3};
MultiVariRNG<Eigen::Vector3d,Eigen::Matrix3d> mvrng(mean,covar);
std::vector<Eigen::Vector3d> ppl;
Eigen::Vector3d vecSum = Eigen::MatrixXd::Zero(3,1);
for(size_t i = 0; i<nsamp; i++){
Eigen::Vector3d randVec = mvrng.MVRNGenerate();
ppl.push_back( randVec );
vecSum += randVec;
}
Eigen::Vector3d vecMean = vecSum/ppl.size();
std::cout << "Ouput Mean: \n" << vecMean << "\n" << std::endl;
Eigen::Matrix3d sigmaSum = Eigen::MatrixXd::Zero(3,3);
for(size_t i = 0; i<ppl.size(); i++){
sigmaSum += (ppl[i]-vecMean)*( (ppl[i]-vecMean).adjoint() );
}
Eigen::Matrix3d Sigma = sigmaSum/(ppl.size()-1);
std::cout << "Ouput Covariance: \n" << Sigma << std::endl;
return 0;
} | 26.395833 | 79 | 0.625099 | [
"vector",
"transform"
] |
b063d595d575fdbda741199f6909073fe3b06df8 | 16,701 | hpp | C++ | FruitNinjaGL/src/fn/ecs/Database.hpp | CncGpp/FruitNinjaGL | 90435c9e19733aece4a334c2d889ae5975f7706e | [
"Apache-2.0"
] | null | null | null | FruitNinjaGL/src/fn/ecs/Database.hpp | CncGpp/FruitNinjaGL | 90435c9e19733aece4a334c2d889ae5975f7706e | [
"Apache-2.0"
] | null | null | null | FruitNinjaGL/src/fn/ecs/Database.hpp | CncGpp/FruitNinjaGL | 90435c9e19733aece4a334c2d889ae5975f7706e | [
"Apache-2.0"
] | null | null | null | #pragma once
#include"ecs_types.hpp"
#include"Entity.hpp"
namespace fn {
/**
* @brief Classe che gestisce la costruzione, recupero e accesso delle entità.
*
* Rappresenta appunto un database di tutte le possibili entità e consente di effettuare 'query'
* - recuperare una specifica entità dato il suo eid.
* - recuperare un sottoinsieme delle componenti di un entità dato il suo eid
* - restituire tutte le entità con una specifica firma o sottoinsieme di componenti.
* - iterare lungo i component array applicando funzioni lambda
*/
class Database {
public:
Database();
/** @brief La copia di un oggetto Database non è consentita */
Database(Database const&) = delete;
/** @brief L'assegnazione di un oggetto Database non è consentita */
Database& operator=(Database const&) = delete;
/**
* @brief Registra la componente nel database.
*
* Aggiunge un nuovo ComponentArray<T> al database.
*
* @tparam T dtype della componente da registrare.
*/
template<typename T>
constexpr void register_component() {
const Cid cid = ComponentArray<T>::cid;
m_components.insert({ cid, std::make_shared<ComponentArray<T>>() });
}
/**
* @brief Verifica se la componente è registrata.
*
* @tparam T componente da verificare.
* \return @code{.cpp} true @endcode se la componente è registrata.
*/
template<typename T>
[[nodiscard]] constexpr bool registered() {
const Cid cid = ComponentArray<T>::cid;
return m_components.find(cid) != m_components.end();
}
/**
* @brief Setta una componente di una entità.
*
* Consente di settare una componente per una specifica entità.
* La componente da settare è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* fn::Eid e = database.create_entity();
* database.set<C::Movement>(e, glm::vec3{1.0f, 16.0f, -2.5f},
* glm::vec3{2.0f, -1.0f, 2.0f});
* @endcode
*
* Tutti i parametri in args saranno utilizzati per costruire la componente.
*
* @tparam T componente da settare.
* @tparam Args parametri da inoltrare al costruttore di @code{.cpp} T @endcode.
* \param eid identificativo dell'entità a cui si vuole settare la componente.
* \param args argomenti da inoltrare al costruttore di @code{.cpp} T @endcode.
*/
template<typename T, class... Args>
constexpr void set(const Eid eid, Args&&... args) {
[[unlikely]] if (!this->registered<T>())
register_component<T>();
assert(this->registered<T>() && "set<T> di un componente non registrato nel database.");
getComponentArray<T>()->set(eid, T{ std::forward<Args>(args)... });
}
/**
* @brief Setta una componente di una entità.
*
* Consente di settare una componente per una specifica entità.
* La componente da settare è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* fn::Eid e = database.create_entity();
* database.set<C::Movement>(e, {
* .velocity = glm::vec3{1.0f, 16.0f, -2.5f},
* .spin = glm::vec3{2.0f, -1.0f, 2.0f}
* });
* @endcode
*
*
* @tparam T componente da settare.
* \param eid identificativo dell'entità a cui si vuole settare la componente.
* \param component componente da settare.
*/
template<typename T>
constexpr void set(const Eid eid, T& component) {
if (!this->registered<T>()) [[unlikely]]
register_component<T>();
assert(this->registered<T>() && "set<T> di un componente non registrato nel database.");
getComponentArray<T>()->set(eid, component);
}
/**
* @brief Recupera il puntatore a una singola componente di un entità.
*
* Consente di ottenere il puntatore ad una componente per una entità.
* La componente è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* auto* pos = database.get<C::Position>(eid);
* pos->position; // accesso alla posizione della componente
* pos->rotation; // accesso alla rotazione della componente
* pos->translate({1.0f, 1.0f}); // accesso alle funzioni della componente
* @endcode
*
* @tparam T componente a cui si vuole accedere.
* \param eid identificativo dell'entità a cui si vuole accedere.
* \return puntatore ad una componente T dell'entità eid.
*/
template<typename T>
[[nodiscard]] constexpr T* get(const Eid eid) {
return getComponentArray<T>()->get(eid);
}
/**
* @brief Recupera il puntatore a molteplici componenti di un entità.
*
* Consente di ottenere il puntatore a più componenti per una entità.
* Le componenti sono specificabili attraverso il template @code{.cpp} T1 @endcode,
* @code{.cpp} T2 @endcode, @code{.cpp} ...Ts @endcode. La funzione è un template ricorsivo
* definito in termini di Database::get<T>.
*
* @code{.cpp}
* // Accedo alle tre componenti dividendo la tupla con un unpacking
* auto [pos, mov, ren] = database.get<C::Position, C::Movement, C::Render>(eid);
* pos->translate({1.0f, 1.0f, 1.0f});
* pos->rotate({1.0f, 1.0f, 1.0f});
* mov->accelerate({0.0f, 1.0f, 0.0f});
* ren->model->draw(...);
* @endcode
*
* @tparam T1 prima componente a cui si vuole accedere.
* @tparam T2 seconda componente a cui si vuole accedere.
* @tparam Ts altre componenti a cui si vuole accedere.
* \param eid identificativo dell'entità a cui si vuole accedere.
* \return una std::tuple contenente i puntatori alle componenti.
*/
template<typename T1, typename T2, typename ...Ts> [[nodiscard]] constexpr std::tuple<T1*, T2*, Ts*...> get(const Eid eid);
/**
* @brief Verifica se un'entità ha una componente.
*
* Consente di verificare la presenza di una componente per una entità.
* La componente è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* bool has = database.has<C::AABB>(eid);
* @endcode
*
* \param eid identificativo dell'entità.
* \return @code{.cpp} true @endcode se l'entità ha una componente @code{.cpp} T @endcode valida.
*/
template<typename T>
[[nodiscard]] constexpr bool has(const Eid eid) {
if (this->registered<T>()) {
std::shared_ptr<ComponentArray<T>> x = getComponentArray<T>();
bool y = x->has(eid);
}
return this->registered<T>() && getComponentArray<T>()->has(eid);
}
/**
* @brief Verifica se un'entità ha molteplici componenti.
*
* Consente di verificare la presenza di più componenti per una entità.
* Le componenti sono specificabili attraverso il template @code{.cpp} T1 @endcode,
* @code{.cpp} T2 @endcode, @code{.cpp} ...Ts @endcode. La funzione è un template ricorsivo
* definito in termini di Database::has<T>.
*
* @code{.cpp}
* bool has = database.has<C::Position, C::Movement, C::Render>(eid);
* @endcode
*
* @tparam T1 prima componente.
* @tparam T2 seconda componente.
* @tparam Ts eventuali altre componenti.
* \param eid identificativo dell'entità.
* \return @code{.cpp} true @endcode se l'entità ha tutte le componenti specificate.
*/
template<typename T1, typename T2, typename ...Ts> [[nodiscard]] constexpr bool has(const Eid eid);
/**
* @brief Rimuove una componente di una entità.
*
* Consente di rimuovere una componente per una entità.
* La componente da rimuovere è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* database.remove<C::Sprite>(e)
* @endcode
*
* @tparam T componente da rimuovere.
* \param eid identificativo dell'entità a cui si vuole settare la componente.
*/
template<typename T>
constexpr void remove(const Eid eid) {
getComponentArray<T>()->remove(eid);
}
Signature signature(const Eid eid);
/**
* @brief Crea una nuova entità.
*
* \return un nuovo oggetto fn::Entity che wrappa l'enntità creata.
*/
[[nodiscard]] Entity create_entity();
/** @brief distrugge una entità */
void destroy_entity(Eid eid);
//Query
[[nodiscard]] std::vector<Entity> having(const Signature signature);
template<typename T, typename ...Ts> [[nodiscard]] std::vector<Entity> having();
void for_each(const Signature signature, std::function<void(Eid e)> fun);
void for_each(const Signature signature, std::function<void(Entity& e)> fun);
/**
* @brief Applica una lambda a tutte le entità con una specifica componente.
*
* Consente applicare una funzione lambda iterando su tutte le entità che hanno una specifica
* componente. La funzione applicata è del tipo @code{.cpp} void(Entity& e) @endcode dunque consente
* di accedere completamente all'entità.
* La componente richiesta è specificabile attraverso il template @code{.cpp} T @endcode.
*
* @code{.cpp}
* database.for_each<C::Particle>([](Entity& e){
* // fai qualcosa con `e` ...
* });
* @endcode
*
* La funzione si divide in due parti, la query per individuare nel database le entità coinvolte
* e l'applicazione di fun a ciascuna di queste.
*
* @tparam T componente.
* @param fun funzione da applicare.
*/
template<typename T> void for_each(std::function<void(Entity& e)> fun);
/**
* @brief Applica una lambda a tutte le entità con un insieme di componenti.
*
* Consente applicare una funzione lambda iterando su tutte le entità che hanno le
* componenti specificate. La funzione applicata è del tipo @code{.cpp} void(Entity& e) @endcode dunque consente
* l'accesso completo all'entità.
* Le componenti richiesta sono specificabili attraverso i template @code{.cpp} T1 @endcode,
* @code{.cpp} T2 @endcode, @code{.cpp} ...Ts @endcode.
*
* @code{.cpp}
* database.for_each<C::Position, C::Movement>([](Entity& e){
* // fai qualcosa con `e` ...
* });
* @endcode
*
* La funzione si divide in due parti, la query per individuare nel database le entità coinvolte
* e l'applicazione di fun a ciascuna di queste.
*
* @tparam T1 prima componente.
* @tparam T2 seconda componente.
* @tparam Ts eventuali altre componenti.
* @param fun funzione da applicare.
*/
template<typename T1, typename T2, typename ...Ts> void for_each(std::function<void(Entity& e)> fun);
/**
* @brief Applica una lambda a tutte le entità con un insieme di componenti.
*
* @code{.cpp}
* database.for_each<C::Render>([](C::Render& r){
* // fai qualcosa con `r` ...
* });
* @endcode
*
* Simile alle precedenti, ma la funzione lambda è del tipo @code{.cpp} void(T&) @endcode ovvero
* fornisce direttamente un reference alla componente quando si itera piuttosto che una entità.
*/
template<typename T> void for_each(std::function<void(T& e)> fun);
/**
* @brief Applica una lambda a tutte le entità con un insieme di componenti.
*
* Simile alle precedenti, ma la funzione lambda è del tipo @code{.cpp} void(T&, Ts&...) @endcode ovvero
* fornisce direttamente un reference alle componenti quando si itera piuttosto che una entità.
*/
template<typename T, typename ...Ts> void for_each(std::function<void(T&, Ts&...)> fun);
/**
* @brief Applica una lambda a tutte le entità con un insieme di componenti.
*
* Simile alle precedenti, ma la funzione lambda è del tipo @code{.cpp} void(fn::Eid, Ts&...) @endcode ovvero
* fornisce anche il fn::Eid insieme ai reference alle componenti quando si itera.
*/
template<typename ...Ts> void for_each(std::function<void(fn::Eid, Ts&...)> fun);
private:
std::unordered_map<Cid, std::shared_ptr<IComponentArray>> m_components{};
template<typename T>
[[nodiscard]] std::shared_ptr<ComponentArray<T>> getComponentArray() {
assert(this->registered<T>() && "Errore, componente non registrato nel database.");
const Cid cid = ComponentArray<T>::cid;
return std::static_pointer_cast<ComponentArray<T>>(m_components[cid]);
}
// Funzioni e template di utility
// Effettua una call di una funzione unpackando una tupla
template<typename Function, typename Tuple, size_t ... I>
inline auto call(Function f, fn::Eid eid, Tuple t, std::index_sequence<I ...>){ return f(eid, *std::get<I>(t) ...); }
template<typename Function, typename Tuple, size_t ... I>
inline auto call(Function f, Tuple t, std::index_sequence<I ...>) { return f(*std::get<I>(t) ...); }
// Per la gestione delle entità:
std::stack<Eid> eid_pool{}; //Pool di id disponibili, contiene inizialmente MAX_ENTITY_COUNT valori
};
template<typename T1, typename T2, typename ...Ts>
constexpr inline bool Database::has(const Eid eid)
{
return this->has<T1>(eid) && this->has<T2, Ts...>(eid);
}
template<typename T1, typename T2, typename ...Ts>
constexpr inline std::tuple<T1*, T2*, Ts*...> Database::get(const Eid eid)
{
//TODO: Ritornare errore se non ha il valore quell'entità? Ora torna nullptr...
if constexpr (sizeof...(Ts) > 0)
return std::tuple_cat(
std::make_tuple(get<T1>(eid)),
get<T2, Ts...>(eid)
);
else return std::make_tuple(get<T1>(eid), get<T2>(eid));
}
template<typename T, typename ...Ts>
inline std::vector<Entity> Database::having()
{
const Signature sign = Sign<T, Ts...>;
return std::move(this->having(sign));
}
template<typename T>
inline void Database::for_each(std::function<void(Entity& e)> fun)
{
const Cid cid = ComponentArray<T>::cid;
auto ca = this->getComponentArray<T>();
for (unsigned int i = 0; i < ca->validity().size(); i++) {
if (ca->validity()[i]) [[unlikely]] {
Entity e{i, this};
fun(e);
}
}
}
template<typename T1, typename T2, typename ...Ts>
inline void Database::for_each(std::function<void(Entity& e)> fun)
{
const Signature sign = Sign<T1, T2, Ts...>;
this->for_each(sign, fun);
}
template<typename T>
inline void Database::for_each(std::function<void(T& e)> fun)
{
const Cid cid = ComponentArray<T>::cid;
auto ca = this->getComponentArray<T>();
for (unsigned int i = 0; i < ca->validity().size(); i++) {
if (ca->validity()[i]) [[unlikely]] {
fun(*this->get<T>(i));
}
}
}
template<typename T, typename ...Ts>
inline void Database::for_each(std::function<void(T&, Ts&...)> fun)
{
static constexpr auto size = sizeof...(Ts) + 1;
const Signature signature = Sign<T, Ts...>;
auto bitmap = std::move(std::bitset<ecs::MAX_ENTITY_COUNT>{}.set());
for (auto& [cid, component_array] : this->m_components) {
if ((signature & cid).any()) //Se nella firma ci sta il cid allora posso procedere
bitmap = bitmap & component_array->validity();
}
for (unsigned int i = 0; i < bitmap.size(); i++) {
if (bitmap[i]) [[unlikely]] {
call(fun, this->get<T, Ts...>(i), std::make_index_sequence<size>{});
}
}
}
template<typename ...Ts>
inline void Database::for_each(std::function<void(fn::Eid, Ts&...)> fun)
{
static constexpr auto size = sizeof...(Ts);
const Signature signature = Sign<Ts...>;
auto bitmap = std::move(std::bitset<ecs::MAX_ENTITY_COUNT>{}.set());
for (auto& [cid, component_array] : this->m_components) {
if ((signature & cid).any()) //Se nella firma ci sta il cid allora posso procedere
bitmap = bitmap & component_array->validity();
}
for (unsigned int i = 0; i < bitmap.size(); i++) {
if (bitmap[i]) [[unlikely]] {
call(fun, i, this->get<Ts...>(i), std::make_index_sequence<size>{});
}
}
}
}
/***************************************************************************************/
namespace fn {
template<typename T>
constexpr inline bool Entity::has() {
return m_database->has<T>(m_eid);
}
template<typename T1, typename T2, typename ...Ts>
constexpr inline bool Entity::has()
{
return has<T1>() && has<T2, Ts...>();
}
template<typename T, class ...Args>
constexpr inline Entity& Entity::set(Args && ...args)
{
m_database->set<T>(m_eid, args);
m_update_signature();
return *this;
}
template<typename T>
constexpr inline Entity& Entity::set(T component)
{
m_database->set<T>(m_eid, component);
m_update_signature();
return *this;
}
template<typename T>
constexpr inline Entity& fn::Entity::remove()
{
m_database->remove<T>(m_eid);
m_update_signature();
return *this;
}
template<typename T>
constexpr inline T* fn::Entity::get()
{
//TODO: Ritornare errore se non ha il valore quell'entità? Ora torna nullptr...
return m_database->get<T>(m_eid);
}
template<typename T1, typename T2, typename ...Ts>
constexpr inline std::tuple<T1*, T2*, Ts*...> fn::Entity::get()
{
//TODO: Ritornare errore se non ha il valore quell'entità? Ora torna nullptr...
return std::make_tuple(m_database->get<T1>(m_eid), m_database->get<T2, Ts...>(m_eid));
}
}
| 34.153374 | 125 | 0.657685 | [
"render",
"vector",
"model"
] |
b06bab1ab217324d013fbd72e0e748c947f95f57 | 12,933 | cpp | C++ | src/del/managers/Errors.cpp | NablaVM/Del | d353bc40a225635fc5b6efd0134b797c161acc11 | [
"MIT"
] | null | null | null | src/del/managers/Errors.cpp | NablaVM/Del | d353bc40a225635fc5b6efd0134b797c161acc11 | [
"MIT"
] | null | null | null | src/del/managers/Errors.cpp | NablaVM/Del | d353bc40a225635fc5b6efd0134b797c161acc11 | [
"MIT"
] | null | null | null | #include "Errors.hpp"
#include "del_driver.hpp"
#include <libnabla/termcolor.hpp>
namespace DEL
{
// ----------------------------------------------------------
//
// ----------------------------------------------------------
Errors::Errors(DEL_Driver & driver) : driver(driver)
{
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
Errors::~Errors()
{
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_previously_declared(std::string id, int line_no)
{
display_error_start(true, line_no); std::cerr << "Symbol \"" << id << "\" already defined" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_unknown_id(std::string id, int line_no, bool is_fatal)
{
display_error_start(is_fatal, line_no); std::cerr << "Unknown ID \"" << id << "\"" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
if(is_fatal)
{
exit(EXIT_FAILURE);
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_out_of_memory(std::string symbol, uint64_t size, int max_memory)
{
display_error_start(true); std::cerr
<< "Allocation of \"" << symbol << "\" (size:" << size
<< ") causes mapped memory to exceed target's maximum allowable memory of ("
<< max_memory << ") bytes.";
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_custom(std::string from, std::string error, bool is_fatal)
{
display_error_start(is_fatal); std::cerr << "[" << from << "]" << error << std::endl;
if(is_fatal)
{
exit(EXIT_FAILURE);
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_unallowed_type(std::string id, int line_no, bool is_fatal)
{
display_error_start(is_fatal, line_no); std::cerr << "Type of \""
<< id
<< "\" Forbids current operation"
<< std::endl;
if(line_no > 0)
{
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, is_fatal, false);
}
if(is_fatal)
{
exit(EXIT_FAILURE);
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_unable_to_open_result_out(std::string name_used, bool is_fatal)
{
display_error_start(is_fatal); std::cerr << "Unable to open \"" << name_used << "\" for resulting output!" << std::endl;
if(is_fatal)
{
exit(EXIT_FAILURE);
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_callee_doesnt_exist(std::string name_called, int line_no)
{
display_error_start(true, line_no); std::cerr << "Call to unknown function \"" << name_called << "\"" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_mismatched_param_length(std::string caller, std::string callee, uint64_t caller_params, uint64_t callee_params, int line_no)
{
display_error_start(true, line_no); std::cerr << "Function \"" << callee << "\" expects (" << callee_params
<< ") parameters, but call from function \"" << caller << "\" gave (" << caller_params << ")" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::display_error_start(bool is_fatal, int line_no)
{
std::cerr << "[" << termcolor::red << "Error" << termcolor::reset << "] <";
if(is_fatal){ std::cerr << termcolor::red << "FATAL" << termcolor::reset ;}
else { std::cerr << termcolor::yellow << "WARNING" << termcolor::reset ;}
if(line_no == 0)
{
std::cerr << "> (" << termcolor::green << driver.current_file_from_directive << termcolor::reset << ") : ";
}
else
{
std::cerr << "> (" << termcolor::green << driver.current_file_from_directive << termcolor::reset << "@"
<< termcolor::magenta << driver.preproc.fetch_user_line_number(line_no) << termcolor::reset
<< ") : ";
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_calls_return_value_unhandled(std::string caller_function, std::string callee, int line_no, bool is_fatal)
{
display_error_start(is_fatal, line_no); std::cerr << "Function call to \"" << callee << "\" in function \"" << caller_function << "\" has a return value that is not handled" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, false, false);
if(is_fatal)
{
exit(EXIT_FAILURE);
}
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_no_return(std::string f, int line_no)
{
display_error_start(true, line_no); std::cerr << "Expected 'return <type>' for function : " << f << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_no_main_function()
{
display_error_start(true); std::cerr << "No 'main' method found" << std::endl;
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_syntax_error(int line, int column, std::string error_message, std::string line_in_question)
{
display_error_start(true, line); std::cerr << error_message << std::endl;
display_line_and_error_pointer(line_in_question, column, true);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_range_invalid_start_gt_end(int line_no, std::string start, std::string end)
{
display_error_start(true, line_no); std::cerr << "Start position greater than end position in given range" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_range_ineffective(int line_no, std::string start, std::string end)
{
display_error_start(true, line_no); std::cerr << "Range does nothing" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_invalid_step(int line_no)
{
display_error_start(true, line_no); std::cerr << "Step is ineffective" << std::endl;
std::string line = driver.preproc.fetch_line(line_no);
display_line_and_error_pointer(line, line.size()/2, true, false);
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_preproc_file_read_fail(std::vector<std::string> include_crumbs, std::string file_in_question)
{
display_error_start(true); std::cerr << "Unable to open file : " << file_in_question << std::endl;
if(include_crumbs.size() > 0)
{
std::cerr << std::endl << "Include history:" << std::endl;
}
for(auto i = include_crumbs.rbegin(); i != include_crumbs.rend(); i++)
{
std::cerr << "\t " << (*i) << std::endl;
}
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_preproc_include_path_not_dir(std::string path)
{
display_error_start(true); std::cerr << "Given include path does not exist : " << path << std::endl;
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::report_preproc_file_not_found(std::string info, std::string file, std::string from)
{
display_error_start(true); std::cerr << info << " \"" << file << "\" " << "requested by \"" << from << "\"" << std::endl;
exit(EXIT_FAILURE);
}
// ----------------------------------------------------------
//
// ----------------------------------------------------------
void Errors::display_line_and_error_pointer(std::string line, int column, bool is_fatal, bool show_arrow)
{
// Weird case
if(line.size() == 1)
{
std::cerr << termcolor::white << line << termcolor::reset << std::endl;
std::cerr << termcolor::red << "^" << termcolor::reset << std::endl;
return;
}
std::string pointer_line;
if(show_arrow)
{
int start = (column < 5) ? 0 : column-5;
int end = ((uint64_t)(column + 5) > line.size()) ? line.size() : column+5;
for(uint64_t i = 0; i < line.size(); i++)
{
if(i == column)
{
pointer_line += "^";
}
else if(i >= start && i <= end )
{
if(i != column)
{
pointer_line += "~";
}
}
else
{
pointer_line += " ";
}
}
}
else
{
// Place tilde under the line , but not until actual data starts ( skip ws in front of the line )
bool found_item = false;
for(uint64_t i = 0; i < line.size(); i++)
{
if(!found_item && !isspace(line[i]))
{
found_item = true;
}
if(found_item)
{
pointer_line += "~";
}
else
{
pointer_line += " ";
}
}
}
std::cerr << termcolor::white << line << termcolor::reset << std::endl;
if(is_fatal)
{
std::cerr << termcolor::red << pointer_line << termcolor::reset << std::endl;
}
else
{
std::cerr << termcolor::yellow << pointer_line << termcolor::reset << std::endl;
}
}
} | 35.628099 | 196 | 0.418232 | [
"vector"
] |
b06ef32e1de7393b4888e365c9073d72698665d9 | 5,226 | cpp | C++ | Plugins/VulkanRendering/VulkanPipelineBuilder.cpp | fraqqer/Hall-Guys-CSC8503 | 8507b09588944f661553bb9d9cdef2338ec87fda | [
"MIT"
] | null | null | null | Plugins/VulkanRendering/VulkanPipelineBuilder.cpp | fraqqer/Hall-Guys-CSC8503 | 8507b09588944f661553bb9d9cdef2338ec87fda | [
"MIT"
] | null | null | null | Plugins/VulkanRendering/VulkanPipelineBuilder.cpp | fraqqer/Hall-Guys-CSC8503 | 8507b09588944f661553bb9d9cdef2338ec87fda | [
"MIT"
] | null | null | null | #include "VulkanPipelineBuilder.h"
#include "VulkanMesh.h"
#include "VulkanShader.h"
using namespace NCL;
using namespace Rendering;
VulkanPipelineBuilder::VulkanPipelineBuilder() {
dynamicStateEnables[0] = vk::DynamicState::eViewport;
dynamicStateEnables[1] = vk::DynamicState::eScissor;
dynamicCreate.setDynamicStateCount(2);
dynamicCreate.setPDynamicStates(dynamicStateEnables);
sampleCreate.setRasterizationSamples(vk::SampleCountFlagBits::e1);
viewportCreate.setViewportCount(1);
viewportCreate.setScissorCount(1);
pipelineCreate.setPViewportState(&viewportCreate);
depthStencilCreate.setDepthCompareOp(vk::CompareOp::eAlways)
.setDepthTestEnable(false)
.setDepthWriteEnable(false)
.setStencilTestEnable(false)
.setDepthBoundsTestEnable(false);
//blendAttachState.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)
// .setBlendEnable(false)
// .setAlphaBlendOp(vk::BlendOp::eAdd)
// .setColorBlendOp(vk::BlendOp::eAdd)
// .setSrcAlphaBlendFactor(vk::BlendFactor::eSrcAlpha)
// .setSrcColorBlendFactor(vk::BlendFactor::eSrcAlpha)
// .setDstAlphaBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha)
// .setDstColorBlendFactor(vk::BlendFactor::eOneMinusSrcAlpha);
//blendCreate.setAttachmentCount(1);
//blendCreate.setPAttachments(&blendAttachState);
rasterCreate.setCullMode(vk::CullModeFlagBits::eNone)
.setPolygonMode(vk::PolygonMode::eFill)
.setFrontFace(vk::FrontFace::eCounterClockwise)
.setLineWidth(1.0f);
}
VulkanPipelineBuilder::~VulkanPipelineBuilder()
{
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithDepthState(vk::CompareOp op, bool depthEnabled, bool writeEnabled, bool stencilEnabled) {
depthStencilCreate.setDepthCompareOp(op)
.setDepthTestEnable(depthEnabled)
.setDepthWriteEnable(writeEnabled)
.setStencilTestEnable(stencilEnabled);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithBlendState(vk::BlendFactor srcState, vk::BlendFactor dstState, bool enabled) {
vk::PipelineColorBlendAttachmentState pipeBlend;
pipeBlend.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)
.setBlendEnable(enabled)
.setAlphaBlendOp(vk::BlendOp::eAdd)
.setColorBlendOp(vk::BlendOp::eAdd)
.setSrcAlphaBlendFactor(srcState)
.setSrcColorBlendFactor(srcState)
.setDstAlphaBlendFactor(dstState)
.setDstColorBlendFactor(dstState);
blendAttachStates.emplace_back(pipeBlend);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithRaster(vk::CullModeFlagBits cullMode, vk::PolygonMode polyMode) {
rasterCreate.setCullMode(cullMode).setPolygonMode(polyMode);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithVertexSpecification(VulkanVertexSpecification* mesh, vk::PrimitiveTopology topology) {
pipelineCreate.setPVertexInputState(&mesh->vertexInfo);
inputAsmCreate.setTopology(topology);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithShaderState(VulkanShader* shader) {
shader->FillShaderStageCreateInfo(pipelineCreate);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithLayout(vk::PipelineLayout layout) {
this->layout = layout;
pipelineCreate.setLayout(layout);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithPushConstant(vk::PushConstantRange layout) {
allPushConstants.emplace_back(layout);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithPass(vk::RenderPass& renderPass) {
pipelineCreate.setRenderPass(renderPass);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithDescriptorSetLayout(vk::DescriptorSetLayout layout) {
allLayouts.emplace_back(layout);
return *this;
}
VulkanPipelineBuilder& VulkanPipelineBuilder::WithDebugName(const string& name) {
debugName = name;
return *this;
}
VulkanPipeline VulkanPipelineBuilder::Build(VulkanRenderer& renderer) {
vk::PipelineLayoutCreateInfo pipeLayoutCreate = vk::PipelineLayoutCreateInfo()
.setSetLayoutCount((uint32_t)allLayouts.size())
.setPSetLayouts(allLayouts.data())
.setPPushConstantRanges(allPushConstants.data())
.setPushConstantRangeCount((uint32_t)allPushConstants.size());
if (blendAttachStates.empty()) {
WithBlendState(vk::BlendFactor::eSrcAlpha, vk::BlendFactor::eOneMinusSrcAlpha, false);
}
blendCreate.setAttachmentCount((uint32_t)blendAttachStates.size());
blendCreate.setPAttachments(blendAttachStates.data());
vk::PipelineLayout pipelineLayout = renderer.device.createPipelineLayout(pipeLayoutCreate);
pipelineCreate.setPColorBlendState(&blendCreate)
.setPDepthStencilState(&depthStencilCreate)
.setPDynamicState(&dynamicCreate)
.setPInputAssemblyState(&inputAsmCreate)
.setPMultisampleState(&sampleCreate)
.setPRasterizationState(&rasterCreate)
.setLayout(pipelineLayout);
VulkanPipeline output;
output.layout = pipelineLayout;
output.pipeline = renderer.device.createGraphicsPipeline(renderer.pipelineCache, pipelineCreate).value;
if (!debugName.empty()) {
renderer.SetDebugName(vk::ObjectType::ePipeline, (uint64_t)(VkPipeline)output.pipeline, debugName);
}
return output;
} | 33.716129 | 168 | 0.809797 | [
"mesh"
] |
b071425364395bf8bde2e80ddef1c6c8557b06ed | 1,184 | hpp | C++ | lib/include/cppgui/Boxed.hpp | JPGygax68/libCppGUI | 9484b6b4e544a522019276fcd49eb8495b04e60d | [
"Apache-2.0"
] | 2 | 2017-03-28T14:11:47.000Z | 2021-05-31T07:31:43.000Z | lib/include/cppgui/Boxed.hpp | JPGygax68/libCppGUI | 9484b6b4e544a522019276fcd49eb8495b04e60d | [
"Apache-2.0"
] | null | null | null | lib/include/cppgui/Boxed.hpp | JPGygax68/libCppGUI | 9484b6b4e544a522019276fcd49eb8495b04e60d | [
"Apache-2.0"
] | 1 | 2021-05-31T07:31:44.000Z | 2021-05-31T07:31:44.000Z | #pragma once
#include "./Box.hpp"
namespace cppgui {
/*
* Note: the Boxed<> decorator MUST NOT be used on abstract classes - for example, it is not
* possible to apply it to Container_base.
* (The reason for this is that Boxed<> modifieds the two main layouting methods by overriding
* and super-calling them.)
*/
template<class WidgetC, class BoxStyles>
class Boxed: public WidgetC, public Box<BoxStyles>
{
public:
void render(Canvas *c, const Point &offset) override
{
auto p = offset + this->position();
draw_background_and_border(c, p, this->bounds(), this->visual_states());
WidgetC::render(c, offset);
}
#ifndef CPPGUI_EXCLUDE_LAYOUTING
public:
//void init_layout() override;
auto get_minimal_bounds() -> Bbox override
{
auto bbox = WidgetC::get_minimal_bounds();
return this->adjust_box_bounds(bbox);
}
void compute_layout(Bbox_cref b)
{
WidgetC::compute_layout(this->adjust_box_bounds(b, -1));
}
#endif // !CPPGUI_EXCLUDE_LAYOUTING
};
} // ns cppui | 25.191489 | 98 | 0.605574 | [
"render"
] |
b0720374c768a211b7b1ea0c1dcdfdb1002d5e66 | 4,882 | cpp | C++ | test/hard.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | 1 | 2018-10-09T03:52:16.000Z | 2018-10-09T03:52:16.000Z | test/hard.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | null | null | null | test/hard.cpp | lkeegan/CTCI | 1f15dabaf85aaa6d2f8bd21b5451d55173cf8ad4 | [
"MIT"
] | null | null | null | #include "hard.hpp"
#include "catch.hpp"
// Unit tests
using namespace ctci::hard;
TEST_CASE("17.1 add_without_plus", "[hard]") {
REQUIRE(add_without_plus(0, 0) == 0);
REQUIRE(add_without_plus(1, 0) == 1);
REQUIRE(add_without_plus(0, 1) == 1);
REQUIRE(add_without_plus(1, 1) == 2);
REQUIRE(add_without_plus(123, 568561) == 123 + 568561);
REQUIRE(add_without_plus(127647543, 2423) == 127647543 + 2423);
}
TEST_CASE("17.2 shuffle_cards", "[hard]") {
constexpr int N_CARDS_IN_DECK = 52;
int N_SAMPLES = 10000;
// start with ordered deck
std::array<int, N_CARDS_IN_DECK> deck;
int index = 0;
for (auto& d : deck) {
d = index++;
}
// sum card_index at each location for 1000 shuffles
std::array<int, N_CARDS_IN_DECK> count{};
for (int i_samples = 0; i_samples < N_SAMPLES; ++i_samples) {
shuffle_cards(deck, i_samples);
for (std::size_t i = 0; i < deck.size(); ++i) {
count[i] += deck[i];
}
}
// count at each location should be (stochastically) equal to
// average_index * N_SAMPLES
double average_index = 0;
for (int i = 0; i < N_CARDS_IN_DECK; ++i) {
average_index += static_cast<double>(i);
}
average_index /= static_cast<double>(N_CARDS_IN_DECK);
int sum = 0;
for (auto c : count) {
sum += c;
double stoch_one = static_cast<double>(c) / (average_index * N_SAMPLES);
CAPTURE(stoch_one);
REQUIRE(stoch_one == Approx(1.0).margin(0.05));
}
REQUIRE(sum == N_SAMPLES * N_CARDS_IN_DECK * average_index);
}
TEST_CASE("17.3 sub_set", "[hard]") {
std::vector<int> v1{1, -3, 9, 14, 833, 71, 732, 10};
int set_size = 3;
int N_SAMPLES = 10000 * v1.size();
// count how many times each value occurs in each element of the subset
std::vector<std::unordered_map<int, int>> counts(3);
for (int i_samples = 0; i_samples < N_SAMPLES; ++i_samples) {
auto v1_sub = sub_set(v1, set_size, i_samples);
for (int i = 0; i < set_size; ++i) {
++counts[i][v1_sub[i]];
}
}
// compare to expected equal frequency for all values in v1
// for every element of the subset
for (int i = 0; i < set_size; ++i) {
for (auto v : v1) {
REQUIRE(counts[i][v] == Approx(N_SAMPLES / v1.size()).margin(50));
}
}
}
TEST_CASE("17.4 missing_number", "[hard]") {
std::vector<unsigned int> A{0, 1, 2, 4, 5, 6};
REQUIRE(missing_number(A) == 3);
std::vector<unsigned int> B{1, 2, 3, 4};
REQUIRE(missing_number(B) == 0);
std::vector<unsigned int> C{0, 1, 2, 3, 4};
REQUIRE(missing_number(C) == 5);
std::vector<unsigned int> D{0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 14, 15, 16, 17, 18, 19, 20};
REQUIRE(missing_number(D) == 13);
}
TEST_CASE("17.5 longest_even_substring", "[hard]") {
REQUIRE(longest_even_substring("") == "");
REQUIRE(longest_even_substring("a") == "");
REQUIRE(longest_even_substring("9") == "");
REQUIRE(longest_even_substring("a7") == "a7");
REQUIRE(longest_even_substring("a7a") == "7a");
REQUIRE(longest_even_substring("a77") == "a7");
REQUIRE(longest_even_substring("99a7b") == "9a7b");
REQUIRE(longest_even_substring("asdf345") == "sdf345");
REQUIRE(longest_even_substring("aab") == "");
REQUIRE(longest_even_substring("462") == "");
REQUIRE(longest_even_substring("aadfsgsdg6fgjjg") == "6f");
REQUIRE(longest_even_substring("60aaaaa66") == "60aa");
}
TEST_CASE("17.6 count_of_twos", "[hard]") {
std::vector<int> n_vals{0, 1, 2, 4, 11, 12, 19, 20, 21,
22, 31, 32, 99, 341, 4631, 74437, 2345234, 12421312};
for (auto n : n_vals) {
CAPTURE(n);
REQUIRE(count_of_twos(n) == count_of_twos_debug(n));
}
}
TEST_CASE("17.7 merge_synonyms", "[hard]") {
using string_pair = std::pair<std::string, std::string>;
std::unordered_map<std::string, int> frequencies;
frequencies["Jon"] = 42;
frequencies["John"] = 142;
frequencies["Sam"] = 3;
frequencies["Samuel"] = 32;
std::vector<string_pair> name_pairs;
name_pairs.push_back({"Jon", "John"});
name_pairs.push_back({"Sam", "Samuel"});
merge_synonyms(frequencies, name_pairs);
REQUIRE(frequencies["Jon"] == 184);
REQUIRE(frequencies["Sam"] == 35);
REQUIRE(frequencies["Samuel"] == false);
REQUIRE(frequencies["John"] == false);
}
TEST_CASE("17.9 kth_multiple", "[hard]") {
for (int k : {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 20, 55}) {
CAPTURE(k)
REQUIRE(kth_multiple(k) == kth_multiple_debug(k));
}
}
TEST_CASE("17.10 majority_element", "[hard]") {
std::vector<int> v;
v = {8};
REQUIRE(majority_element(v) == 8);
v = {8, 1};
REQUIRE(majority_element(v) == -1);
v = {5, 2, 5};
REQUIRE(majority_element(v) == 5);
v = {2, 5, 2, 4, 2, 3};
REQUIRE(majority_element(v) == -1);
v = {2, 5, 2, 4, 2, 3, 2};
REQUIRE(majority_element(v) == 2);
v = {1, 1, 5, 1, 9, 1, 4, 7, 7, 7, 1, 1, 1};
REQUIRE(majority_element(v) == 1);
} | 33.210884 | 79 | 0.619009 | [
"vector"
] |
b07882bb011e549df54651f70a0cec0fd3de9756 | 2,111 | cpp | C++ | coverage/cpp/cov7.cpp | 0152la/z3test | 0b9c5cbefb457aced86b3914c1f7f9de221eb8b1 | [
"MIT"
] | 23 | 2015-04-20T08:51:00.000Z | 2021-11-15T12:20:59.000Z | coverage/cpp/cov7.cpp | 0152la/z3test | 0b9c5cbefb457aced86b3914c1f7f9de221eb8b1 | [
"MIT"
] | 18 | 2016-03-02T15:17:42.000Z | 2021-12-16T22:10:05.000Z | coverage/cpp/cov7.cpp | 0152la/z3test | 0b9c5cbefb457aced86b3914c1f7f9de221eb8b1 | [
"MIT"
] | 30 | 2015-05-30T15:29:17.000Z | 2022-02-25T15:58:58.000Z | #include <vector>
#include "z3++.h"
z3::expr
mod_by_sub(z3::expr t1, z3::expr t2)
{
z3::expr t1_div_t2 = z3::ite(t2 == 0, t1, t1 / t2);
return z3::ite(t2 == 0, t1, t1 - t2 * t1_div_t2);
}
int main()
{
z3::context ctx;
std::vector<z3::expr> vars;
for (size_t i = 0; i < 65; ++i) {
std::string new_var_name = "x" + std::to_string(i);
z3::expr new_expr = ctx.int_const(new_var_name.c_str());
vars.push_back(new_expr);
}
/* Create in_0 */
z3::expr x_50 = vars.at(50);
z3::expr x_32 = vars.at(32);
z3::expr t_1 = -x_50;
z3::expr t_2 = z3::abs(x_50);
z3::expr t_3 = z3::max(-x_32, t_2);
z3::expr t_4 = z3::ite(t_3 != 0, z3::rem(t_1, t_3), t_1);
z3::expr in_0 = z3::abs(t_4);
/* Create in_1 */
z3::expr x_22 = vars.at(22);
z3::expr x_64 = vars.at(64);
z3::expr zero = ctx.int_val(0);
z3::expr t_6 = z3::min(x_22, zero);
z3::expr t_7 = t_6 - x_22;
z3::expr t_8 = z3::min(t_6, t_7);
z3::expr t_9 = z3::ite(t_6 != 0, t_8 / t_6, t_8);
z3::expr t_10 = z3::ite(t_9 != 0, z3::rem(t_7, t_9), t_7);
z3::expr t_11 = z3::max(zero, t_10);
z3::expr t_12 = z3::ite(t_10 != 0, z3::mod(x_22, t_10), x_22);
z3::expr t_13 = z3::ite(t_11 != 0, z3::rem(t_11, t_11), t_11);
z3::expr t_14 = z3::max(x_22, zero);
z3::expr t_15 = t_14 + t_11;
z3::expr t_16 = t_15 - t_15 - t_15;
z3::expr t_17 = z3::ite(t_12 != 0, t_12 / t_12, t_12);
z3::expr t_18 = t_17 - t_8;
z3::expr t_19 = z3::max(t_18, x_64);
z3::expr in_1 = z3::ite(t_19 != 0, z3::rem(t_16, t_19), t_16);
assert(ctx.check_error() == Z3_OK);
// r_0 and r_1 are expected to be equivalent by construction
z3::expr r_0 = z3::ite(in_1 == 0, in_0, z3::mod(in_0, in_1));
r_0 = r_0 + in_1;
r_0 = z3::ite(in_0 == ctx.int_val(0), r_0, r_0 / in_0);
z3::expr r_1 = mod_by_sub(in_0, in_1);
r_1 = r_1 + in_1;
r_1 = z3::ite(in_0 == ctx.int_val(0), r_1, r_1 / in_0);
z3::solver solver(ctx);
solver.add(r_1 != r_0);
assert(solver.check() != z3::sat);
assert(ctx.check_error() == Z3_OK);
}
| 31.507463 | 66 | 0.553292 | [
"vector"
] |
b07bbbb49afc22e83794b334ff61a531049d5eee | 1,060 | cpp | C++ | ECS/Components/TurretController.cpp | Excelsus4/DirectX2DPortfolio | ffc77a412366c7da5bd8585e49ca97b5fc735010 | [
"MIT"
] | null | null | null | ECS/Components/TurretController.cpp | Excelsus4/DirectX2DPortfolio | ffc77a412366c7da5bd8585e49ca97b5fc735010 | [
"MIT"
] | null | null | null | ECS/Components/TurretController.cpp | Excelsus4/DirectX2DPortfolio | ffc77a412366c7da5bd8585e49ca97b5fc735010 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "TurretController.h"
#include "ECS/Entity.h"
#include "ECS/World.h"
#include "ECS/Components/Transform.h"
TurretController::TurretController(Entity * entity, float rotSpeed, float fireDelay, float cooltime):
Component(entity), rotSpeed(rotSpeed), fireDelay(fireDelay), cooltime(cooltime)
{
}
TurretController::TurretController(Entity * entity):
Component(entity), rotSpeed(1.0f), fireDelay(0.5f), cooltime(0.0f)
{
}
TurretController::~TurretController()
{
}
void TurretController::PhysicsUpdate(World * world)
{
Transform* transform = parent->GetTransform();
Entity* user = world->GetUserEntity();
if (user != nullptr) {
// Aim Toward User Entity
D3DXVECTOR2 delta = user->GetTransform()->Position() - transform->Position();
float a = atan(delta.x / delta.y) + ((delta.y > 0) ? Math::PI : 0.0f);
// Linear rotation...
transform->RotationRadLerp(-a, rotSpeed*Timer->Elapsed());
}
cooltime += Timer->Elapsed();
if (cooltime >= fireDelay) {
cooltime -= fireDelay;
parent->SpecialScript(world, 0x744);
}
}
| 26.5 | 101 | 0.710377 | [
"transform"
] |
b08551017cc76351c5e5fbeaf73c55741f413573 | 11,747 | cxx | C++ | inetsrv/query/query/bindexp.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/query/bindexp.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/query/bindexp.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 2000.
//
// File: bindexp.cxx
//
// Contents: IFilter binding functions
//
// Functions: BindIFilterFromStorage
// BindIFilterFromStream
// LoadIFilter
// LoadTextFilter
// LoadBHIFilter
//
// History: 30-Jan-96 KyleP Created
//
//----------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <ciregkey.hxx>
#include <ciole.hxx>
#include <queryexp.hxx>
//
// Local prototypes and data
//
SCODE Bind( IFilter * pIFilter, WCHAR const * pwszPath, IFilter ** ppIFilter );
static GUID const CLSID_CNullIFilter = {
0xC3278E90,
0xBEA7,
0x11CD,
{ 0xB5, 0x79, 0x08, 0x00, 0x2B, 0x30, 0xBF, 0xEB }
};
//+-------------------------------------------------------------------------
//
// Function: BindIFilterFromStorage, public
//
// Synopsis: Binds an embedding (IStorage) to IFilter
//
// Arguments: [pStg] -- IStorage
// [pUnkOuter] -- Outer unknown for aggregation
// [ppIUnk] -- IFilter returned here
//
// Returns: Status code
//
// History: 30-Jan-96 KyleP Created
// 28-Jun-96 KyleP Added support for aggregation
//
//--------------------------------------------------------------------------
SCODE BindIFilterFromStorage(
IStorage * pStg,
IUnknown * pUnkOuter,
void ** ppIUnk )
{
SCODE sc = S_OK;
if ( 0 == pStg )
return E_INVALIDARG;
CTranslateSystemExceptions xlate;
TRY
{
sc = CCiOle::BindIFilter( pStg, pUnkOuter, (IFilter **)ppIUnk, FALSE );
}
CATCH( CException, e )
{
sc = GetOleError( e );
}
END_CATCH
return sc;
} //BindIFilterFromStorage
//+-------------------------------------------------------------------------
//
// Function: BindIFilterFromStream, public
//
// Synopsis: Binds an embedding (IStream) to IFilter
//
// Arguments: [pStm] -- IStream
// [pUnkOuter] -- Outer unknown for aggregation
// [ppIUnk] -- IFilter returned here
//
// Returns: Status code
//
// History: 28-Jun-96 KyleP Created
//
//--------------------------------------------------------------------------
SCODE BindIFilterFromStream(
IStream * pStm,
IUnknown * pUnkOuter,
void ** ppIUnk )
{
SCODE sc = S_OK;
if ( 0 == pStm )
return E_INVALIDARG;
CTranslateSystemExceptions xlate;
TRY
{
sc = CCiOle::BindIFilter( pStm, pUnkOuter, (IFilter **)ppIUnk, FALSE );
}
CATCH( CException, e )
{
sc = GetOleError( e );
}
END_CATCH
return sc;
} //BindIFilterFromStream
//+-------------------------------------------------------------------------
//
// Function: LoadIFilter, public
//
// Synopsis: Loads an object (path) and binds to IFilter
//
// Arguments: [pwcsPath] -- Full path to file.
// [pUnkOuter] -- Outer unknown for aggregation
// [ppIUnk] -- IFilter returned here
//
// Returns: Status code
//
// History: 30-Jan-96 KyleP Created
// 28-Jun-96 KyleP Added support for aggregation
//
//--------------------------------------------------------------------------
SCODE LoadIFilter(
WCHAR const * pwcsPath,
IUnknown * pUnkOuter,
void ** ppIUnk )
{
if ( 0 == pwcsPath )
return E_INVALIDARG;
SCODE sc = S_OK;
CTranslateSystemExceptions xlate;
TRY
{
sc = CCiOle::BindIFilter( pwcsPath, pUnkOuter, (IFilter **)ppIUnk, FALSE );
}
CATCH( CException, e )
{
sc = GetOleError( e );
}
END_CATCH
return sc;
} //LoadIFilter
//+-------------------------------------------------------------------------
//
// Function: LoadIFilterEx, public
//
// Synopsis: Loads an object (path) and binds to IFilter. Depending on
// flags, falls back to the plain text filter if no filter is
// found.
//
// Arguments: [pwcsPath] -- Full path to file.
// [dwFlags] -- Whether to fall back on the text filter
// [riid] -- Interface requested
// [ppIUnk] -- IFilter returned here
//
// Returns: Status code
//
// History: 20-Aug-01 dlee created
//
//--------------------------------------------------------------------------
SCODE LoadIFilterEx(
WCHAR const * pwcsPath,
DWORD dwFlags,
REFIID riid,
void ** ppIUnk )
{
if ( 0 == pwcsPath || 0 == ppIUnk )
return E_INVALIDARG;
SCODE sc = S_OK;
CTranslateSystemExceptions xlate;
TRY
{
XInterface<IFilter> xFilter;
sc = CCiOle::BindIFilter( pwcsPath, 0, xFilter.GetPPointer(), FALSE );
if ( FAILED( sc ) )
{
if ( LIFF_FORCE_TEXT_FILTER_FALLBACK == dwFlags )
sc = LoadTextFilter( pwcsPath, xFilter.GetPPointer() );
else if ( LIFF_IMPLEMENT_TEXT_FILTER_FALLBACK_POLICY == dwFlags )
{
DWORD fUseTextFilter = CI_FFILTER_FILES_WITH_UNKNOWN_EXTENSIONS_DEFAULT;
HKEY hKey;
DWORD dwError = RegOpenKeyW( HKEY_LOCAL_MACHINE, wcsRegAdminSubKey, &hKey );
if ( ERROR_SUCCESS == dwError )
{
DWORD dwType;
DWORD cb = sizeof fUseTextFilter;
dwError = RegQueryValueExW( hKey,
wcsFilterFilesWithUnknownExtensions,
0,
&dwType,
( BYTE * ) & fUseTextFilter,
&cb );
RegCloseKey( hKey );
}
if ( fUseTextFilter )
sc = LoadTextFilter( pwcsPath, xFilter.GetPPointer() );
}
}
// Now go get the interface requested
if ( SUCCEEDED( sc ) )
sc = xFilter->QueryInterface( riid, ppIUnk );
}
CATCH( CException, e )
{
sc = GetOleError( e );
}
END_CATCH
return sc;
} //LoadIFilterEx
static const GUID CLSID_CTextIFilter = CLSID_TextIFilter;
//+---------------------------------------------------------------------------
//
// Function: LoadTextFilter
//
// Synopsis: Creates a text filter and returns its pointer.
//
// Arguments: [pwszPath] -- File to bind
// [ppIFilter] -- IFilter returned here
//
// Returns: Status
//
// History: 2-27-97 srikants Created
//
//----------------------------------------------------------------------------
SCODE LoadTextFilter( WCHAR const * pwszPath, IFilter ** ppIFilter )
{
if ( 0 == ppIFilter )
return E_INVALIDARG;
IFilter * pIFilter = 0;
SCODE sc = CoCreateInstance( CLSID_CTextIFilter,
NULL,
CLSCTX_INPROC_SERVER,
IID_IFilter,
(void **) &pIFilter );
if ( FAILED(sc) )
{
ciDebugOut(( DEB_WARN,
"CoCreateInstance of CLSID_CTextIFilter failed with error 0x%X\n",
sc ));
return sc;
}
return Bind( pIFilter, pwszPath, ppIFilter );
} //LoadTextFilter
//+---------------------------------------------------------------------------
//
// Function: LoadBinaryFilter
//
// Synopsis: Creates a binary filter and returns its pointer.
//
// Arguments: [pwszPath] -- File to bind
// [ppIFilter] -- IFilter returned here
//
// Returns: Status
//
// History: 03-Nov-1998 KyleP Lifted from LoadTextFilter
//
//----------------------------------------------------------------------------
SCODE LoadBinaryFilter( WCHAR const * pwszPath, IFilter ** ppIFilter )
{
if ( 0 == ppIFilter )
return E_INVALIDARG;
IFilter * pIFilter = 0;
SCODE sc = CoCreateInstance( CLSID_CNullIFilter,
NULL,
CLSCTX_INPROC_SERVER,
IID_IFilter,
(void **) &pIFilter );
if ( FAILED(sc) )
{
ciDebugOut(( DEB_WARN,
"CoCreateInstance of CLSID_CTextIFilter failed with error 0x%X\n",
sc ));
return sc;
}
return Bind( pIFilter, pwszPath, ppIFilter );
} //LoadBinaryFilter
//+---------------------------------------------------------------------------
//
// Function: Bind, private
//
// Synopsis: Worker for common portion of Load*Filter.
//
// Arguments: [pIFilter] -- Filter instance to bind
// [pwszPath] -- File to bind to
// [ppIFilter] -- IFilter returned here
//
// Returns: Status
//
// History: 03-Nov-1998 KyleP Lifted from LoadTextFilter
//
//----------------------------------------------------------------------------
SCODE Bind( IFilter * pIFilter, WCHAR const * pwszPath, IFilter ** ppIFilter )
{
XInterface<IFilter> xFilter(pIFilter);
IPersistFile * pf = 0;
SCODE sc = pIFilter->QueryInterface( IID_IPersistFile,
(void **) &pf );
if ( FAILED(sc) )
{
ciDebugOut(( DEB_WARN,
"QI for IID_IPersistFile on text filter failed. Error 0x%X\n",
sc ));
return sc;
}
XInterface<IPersistFile> xpf(pf);
sc = pf->Load( pwszPath, 0 );
if ( FAILED(sc) )
{
ciDebugOut(( DEB_WARN,
"IPersistFile->Load failed with error 0x%X\n", sc ));
return sc;
}
*ppIFilter = xFilter.Acquire();
return S_OK;
} //Bind
//+-------------------------------------------------------------------------
//
// Function: LoadBHIFilter, public
//
// Synopsis: Loads an object (path) and binds to IFilter. This is the
// 'BoneHead' version. Can be made to refuse load of single-
// threaded filter.
//
// Arguments: [pwcsPath] -- Full path to file.
// [pUnkOuter] -- Outer unknown for aggregation
// [ppIUnk] -- IFilter returned here
// [fBHOk] -- TRUE --> Allow load of single-threaded filter.
//
// Returns: Status code. S_FALSE if filter found but could not be
// loaded because it is free-threaded.
//
// History: 12-May-97 KyleP Created from the smart version
//
//--------------------------------------------------------------------------
SCODE LoadBHIFilter( WCHAR const * pwcsPath,
IUnknown * pUnkOuter,
void ** ppIUnk,
BOOL fBHOk )
{
if ( 0 == pwcsPath )
return E_INVALIDARG;
SCODE sc = S_OK;
CTranslateSystemExceptions xlate;
TRY
{
sc = CCiOle::BindIFilter( pwcsPath, pUnkOuter, (IFilter **)ppIUnk, !fBHOk );
}
CATCH( CException, e )
{
sc = GetOleError( e );
}
END_CATCH
return sc;
} //LoadBHIFilter
| 28.374396 | 93 | 0.455861 | [
"object"
] |
b09d12e9d4af913c6a05747aa80175b2bba9b6ac | 2,614 | hpp | C++ | framework/assets.hpp | zakorgy/vulkan-sdk | bb2cdcfd8c0d7769462beb0e5f5c14c14d156280 | [
"MIT"
] | 196 | 2017-03-02T23:58:12.000Z | 2022-03-23T07:19:50.000Z | framework/assets.hpp | zakorgy/vulkan-sdk | bb2cdcfd8c0d7769462beb0e5f5c14c14d156280 | [
"MIT"
] | 27 | 2017-03-04T01:20:46.000Z | 2022-03-10T03:42:10.000Z | framework/assets.hpp | zakorgy/vulkan-sdk | bb2cdcfd8c0d7769462beb0e5f5c14c14d156280 | [
"MIT"
] | 53 | 2017-03-02T11:48:51.000Z | 2022-03-25T02:47:41.000Z | /* Copyright (c) 2016-2017, ARM Limited and Contributors
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FRAMEWORK_ASSETS_HPP
#define FRAMEWORK_ASSETS_HPP
#include "common.hpp"
#include "libvulkan-stub.h"
#include <stdint.h>
#include <vector>
namespace MaliSDK
{
/// @brief Loads a SPIR-V shader module from assets.
/// @param device The Vulkan device.
/// @param path Path to the SPIR-V shader.
/// @returns A newly allocated shader module or VK_NULL_HANDLE on error.
VkShaderModule loadShaderModule(VkDevice device, const char *pPath);
/// @brief Loads texture data from assets.
///
/// @param pPath Path to texture.
/// @param[out] pBuffer Output buffer where VK_FORMAT_R8G8B8A8_UNORM is placed.
/// @param[out] pWidth Width of the loaded texture.
/// @param[out] pHeight Height of the loaded texture.
///
/// @returns Error code.
Result loadRgba8888TextureFromAsset(const char *pPath, std::vector<uint8_t> *pBuffer, unsigned *pWidth,
unsigned *pHeight);
/// @brief Loads an ASTC texture from assets.
///
/// Loads files created by astcenc tool.
///
/// @param pPath Path to texture.
/// @param[out] pBuffer Output buffer where an ASTC payload is placed.
/// @param[out] pWidth Width of the loaded texture.
/// @param[out] pHeight Height of the loaded texture.
/// @param[out] pFormat The format of the loaded texture.
Result loadASTCTextureFromAsset(const char *pPath, std::vector<uint8_t> *pBuffer, unsigned *pWidth, unsigned *pHeight,
VkFormat *pFormat);
}
#endif
| 42.16129 | 129 | 0.732976 | [
"vector"
] |
b0a87eff92ac39e4f2db2e745b8aa729501f30df | 3,729 | cc | C++ | tools/mkramdisk/create.cc | SmartPolarBear/dionysus-lite | 9f02e7a4e1ed983368aa5967bd8412244fc469d9 | [
"MIT"
] | 24 | 2020-02-05T15:20:31.000Z | 2022-03-29T03:49:06.000Z | tools/mkramdisk/create.cc | SmartPolarBear/dionysus-lite | 9f02e7a4e1ed983368aa5967bd8412244fc469d9 | [
"MIT"
] | null | null | null | tools/mkramdisk/create.cc | SmartPolarBear/dionysus-lite | 9f02e7a4e1ed983368aa5967bd8412244fc469d9 | [
"MIT"
] | 1 | 2021-10-15T10:14:39.000Z | 2021-10-15T10:14:39.000Z | // Copyright (c) 2021 SmartPolarBear
//
// 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.
//
// Created by bear on 7/7/21.
//
#include <ramdisk.hpp>
#include "create.hpp"
#include "config.hpp"
#include "round.hpp"
#include <filesystem>
#include <span>
#include <tuple>
#include <queue>
#include <fstream>
#include <iostream>
#include <gsl/gsl>
using namespace std;
using namespace std::filesystem;
using namespace mkramdisk;
using namespace mkramdisk::configuration;
std::optional<tuple<ramdisk_header*, size_t, uint64_t>> mkramdisk::create_ramdisk(const shared_ptr<char[]>& buf,
const vector<path>& items)
{
size_t size_total{ sizeof(ramdisk_header) + sizeof(ramdisk_item) * items.size() };
uint64_t sum{ 0 };
auto header = reinterpret_cast<ramdisk_header*>(buf.get());
{
auto rd_item = reinterpret_cast<ramdisk_item*>(buf.get() + sizeof(ramdisk_header));
for (const auto& item : items)
{
auto fsize = file_size(item);
strncpy(rd_item->name, item.filename().c_str(), item.filename().string().size());
rd_item->offset = size_total;
rd_item->size = fsize;
size_total += roundup(fsize, sizeof(uint64_t));
if (item.filename().string().find("ap_boot") != string::npos)
{
rd_item->flags |= FLAG_AP_BOOT;
}
cout << "Proceeded " << item.string() << " offset:" << rd_item->offset << endl;
rd_item++;
}
}
span<uint64_t> header_qwords{ (uint64_t*)buf.get(),
roundup(sizeof(ramdisk_header) + sizeof(ramdisk_item) * items.size(),
sizeof(uint64_t)) / sizeof(uint64_t) };
for (const auto& qw:header_qwords)
{
sum += qw;
}
for (const auto& p:items)
{
auto size = file_size(p);
auto rbuf = make_unique<char[]>(roundup(size, sizeof(uint64_t)));
ifstream ifs{ p, ios::binary };
auto _2 = gsl::finally([&ifs]
{
if (ifs.is_open())
{
ifs.close();
}
});
try
{
ifs.read(reinterpret_cast<char*>(rbuf.get()), size);
span<uint64_t> fqwords{ (uint64_t*)rbuf.get(), roundup(size, sizeof(uint64_t)) / sizeof(uint64_t) };
for (const auto& qw:fqwords)
{
sum += qw;
}
if (!ifs)
{
cout << "Error reading " << p << endl;
return std::nullopt;
}
}
catch (const std::exception& e)
{
cout << e.what() << endl;
return std::nullopt;
}
}
return make_tuple(header, size_total, sum);
}
[[nodiscard]]bool mkramdisk::clear_target(const path& p)
{
ofstream out_file{ p, ios::binary };
auto _ = gsl::finally([&out_file]
{
if (out_file.is_open())
{ out_file.close(); }
});
try
{
out_file << 0;
}
catch (const std::exception& e)
{
cout << e.what() << endl;
return false;
}
return !out_file.fail();
}
| 24.86 | 112 | 0.667203 | [
"vector"
] |
b0a9461f50cd4a3d5577b445176b0813c8f687f1 | 774 | cpp | C++ | bindings/python/src/serialization.cpp | jcfr/diy | 23599226078c426c1d469b32981ee9166f142ebf | [
"BSD-3-Clause-LBNL"
] | 43 | 2016-10-23T14:52:59.000Z | 2022-03-18T20:47:06.000Z | bindings/python/src/serialization.cpp | jcfr/diy | 23599226078c426c1d469b32981ee9166f142ebf | [
"BSD-3-Clause-LBNL"
] | 39 | 2016-11-25T22:14:09.000Z | 2022-01-13T21:44:51.000Z | bindings/python/src/serialization.cpp | jcfr/diy | 23599226078c426c1d469b32981ee9166f142ebf | [
"BSD-3-Clause-LBNL"
] | 21 | 2016-11-28T22:08:36.000Z | 2022-03-16T10:31:32.000Z | #include "serialization.h"
#include <diy/serialization.hpp>
using namespace diy;
void PyObjectSerialization::save(BinaryBuffer& bb, const py::object& o)
{
// TODO: find a way to avoid this overhead on every call
py::module pickle = py::module::import("pickle");
py::object dumps = pickle.attr("dumps");
py::bytes data = dumps(o);
auto data_str = std::string(data);
diy::save(bb, data_str);
}
void PyObjectSerialization::load(BinaryBuffer& bb, py::object& o)
{
// TODO: find a way to avoid this overhead on every call
py::module pickle = py::module::import("pickle");
py::object loads = pickle.attr("loads");
std::string data_str;
diy::load(bb, data_str);
py::bytes data_bytes = data_str;
o = loads(data_bytes);
}
| 25.8 | 71 | 0.665375 | [
"object"
] |
b0a98b711f7b59daabc4351579cd685b582c47f7 | 2,002 | hpp | C++ | tests/app/src/opengles2/mordaren/OpenGLES2ShaderBase.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | 1 | 2018-10-27T05:07:05.000Z | 2018-10-27T05:07:05.000Z | tests/app/src/opengles2/mordaren/OpenGLES2ShaderBase.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | tests/app/src/opengles2/mordaren/OpenGLES2ShaderBase.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | #pragma once
#include <utki/config.hpp>
#include <utki/debug.hpp>
#include <utki/Exc.hpp>
#include <utki/Buf.hpp>
#include <kolme/Matrix4.hpp>
#include <vector>
#include <morda/render/VertexArray.hpp>
#if M_OS_NAME == M_OS_NAME_IOS
# include <OpenGlES/ES2/glext.h>
#else
# include <GLES2/gl2.h>
#endif
#include "OpenGLES2_util.hpp"
namespace mordaren{
struct ShaderWrapper{
GLuint s;
ShaderWrapper(const char* code, GLenum type);
~ShaderWrapper()noexcept{
glDeleteShader(this->s);
}
};
struct ProgramWrapper{
ShaderWrapper vertexShader;
ShaderWrapper fragmentShader;
GLuint p;
ProgramWrapper(const char* vertexShaderCode, const char* fragmentShaderCode);
virtual ~ProgramWrapper()noexcept{
glDeleteProgram(this->p);
}
};
class OpenGLES2ShaderBase {
ProgramWrapper program;
const GLint matrixUniform;
static const OpenGLES2ShaderBase* boundShader;
public:
OpenGLES2ShaderBase(const char* vertexShaderCode, const char* fragmentShaderCode);
OpenGLES2ShaderBase(const OpenGLES2ShaderBase&) = delete;
OpenGLES2ShaderBase& operator=(const OpenGLES2ShaderBase&) = delete;
virtual ~OpenGLES2ShaderBase()noexcept{}
protected:
GLint getUniform(const char* n);
void bind()const{
glUseProgram(program.p);
assertOpenGLNoError();
boundShader = this;
}
bool isBound()const noexcept{
return this == boundShader;
}
void setUniformMatrix4f(GLint id, const kolme::Matr4f& m)const{
glUniformMatrix4fv(id, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(&m));
assertOpenGLNoError();
}
void setUniform4f(GLint id, float x, float y, float z, float a)const{
glUniform4f(id, x, y, z, a);
assertOpenGLNoError();
}
void setMatrix(const kolme::Matr4f& m)const{
this->setUniformMatrix4f(this->matrixUniform, m);
assertOpenGLNoError();
}
static GLenum modeMap[];
static GLenum modeToGLMode(morda::VertexArray::Mode_e mode){
return modeMap[unsigned(mode)];
}
void render(const kolme::Matr4f& m, const morda::VertexArray& va)const;
};
}
| 20.222222 | 83 | 0.744755 | [
"render",
"vector"
] |
b0ab3f066d533e49b125f1ff9f059337fd44b200 | 2,646 | cpp | C++ | codes/HDU/HDU_2222.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 2 | 2021-03-07T03:34:02.000Z | 2021-03-09T01:22:21.000Z | codes/HDU/HDU_2222.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T15:01:23.000Z | 2021-03-27T15:55:34.000Z | codes/HDU/HDU_2222.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T05:02:33.000Z | 2021-03-27T05:02:33.000Z | //gyrating cat enthusiast
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <random>
#include <chrono>
#include <queue>
#include <set>
#define ll long long
#define lb long double
#define pii pair<int, int>
#define pb push_back
#define mp make_pair
#define ins insert
#define cont continue
#define siz(vec) ((int)(vec.size()))
#define LC(n) (((n) << 1) + 1)
#define RC(n) (((n) << 1) + 2)
#define init(arr, val) memset(arr, val, sizeof(arr))
#define bckt(arr, val, sz) memset(arr, val, sizeof(arr[0]) * (sz+5))
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
#define tern(a, b, c) ((a) ? (b) : (c))
#define feq(a, b) (fabs(a - b) < eps)
#define abs(x) tern((x) > 0, x, -(x))
#define moo printf
#define oom scanf
#define mool puts("")
#define orz assert
#define fll fflush(stdout)
const lb eps = 1e-9;
const ll mod = 1e9 + 7, ll_max = (ll)1e18;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int g[600000][26], e[600000], fail[600000], n, sz;
string s, t[20000];
void construct(){
sz = 1;
for(int i = 0; i < 26; i++) g[0][i] = 0;
e[0] = 0;
for(int i = 0; i < n; i++){
int cur = 0;
for(int j = 0; j < (int)t[i].length(); j++){
int x = t[i][j] - 'a';
if(!g[cur][x]){
e[sz] = 0;
for(int k = 0; k < 26; k++) g[sz][k] = 0;
g[cur][x] = sz++;
}
cur = g[cur][x];
}
e[cur]++;
}
queue<int> q;
for(int i = 0; i < 26; i++){
if(g[0][i]){
q.push(g[0][i]);
fail[g[0][i]] = 0;
}
}
while(!q.empty()){
int st = q.front();
q.pop();
for(int i = 0; i < 26; i++){
if(g[st][i]){
fail[g[st][i]] = g[fail[st]][i];
q.push(g[st][i]);
} else {
g[st][i] = g[fail[st]][i];
}
}
}
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
int T;
cin >> T;
while(T--){
cin >> n;
for(int i = 0; i < n; i++) cin >> t[i];
string s;
cin >> s;
construct();
int cur = 0, x = 0, ans = 0;
for(int i = 0; i < (int)s.length(); i++){
cur = x = g[cur][s[i] - 'a'];
while(x){
ans += e[x];
e[x] = 0;
x = fail[x];
}
}
cout << ans << endl;
}
return 0;
}
| 23.415929 | 71 | 0.463719 | [
"vector"
] |
b0b951e62af33dd00cf41fe9633feb6c94ab11ee | 3,328 | cpp | C++ | sources/headers.cpp | Push0CHKA/lab_2 | 15fcdfaaad0de5c828e10a3008a6ad3c7332beb6 | [
"MIT"
] | null | null | null | sources/headers.cpp | Push0CHKA/lab_2 | 15fcdfaaad0de5c828e10a3008a6ad3c7332beb6 | [
"MIT"
] | null | null | null | sources/headers.cpp | Push0CHKA/lab_2 | 15fcdfaaad0de5c828e10a3008a6ad3c7332beb6 | [
"MIT"
] | null | null | null | //Copyright 2021 pushochka
#include <stdexcept>
#include <chrono>
#include <cmath>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;
class Experiment{
int k;
public:
void experiments(const int mem, const int travel_order, int id){
int * arr1 = new int[mem];
for (int i = 0; i < mem * 1024 * 1024; i += 16)
arr1[i] = 0;
auto t1 = high_resolution_clock::now();
if (travel_order == 1){
for (int j = 0; j < 10000000; j++) {
for (int i = 0; i < mem * 1024 * 1024; i += 16) k = arr1[i];
}
}
if (travel_order == 2){
for (int j = 0; j < 10000000; j++) {
for (int i = mem * 1024 * 1024; i > 0; i -= 16) k = arr1[i];
}
}
if (travel_order == 3){
vector<int> numbs;
for (int j = 0; j < mem * 1024 * 1024 / 16; j++)
numbs.push_back(pow(2, j));
for (int j = 0; j < mem * 1024 * 1024 / 16; j++)
std::swap(numbs[j], numbs[rand() % numbs.size() - 1]);
for (int j = 0; j < 10000000; j++) {
int count = 0;
while (count < mem * 1024 * 1024 / 16){
k = arr1[numbs[count]];
count++;
}
}
}
auto t2 = high_resolution_clock::now();
duration<double, std::nano> ns_double = t2 - t1;
cout << " - experiment:\n number: " << id << "\n input data: "<<
"\n buffer_size: " << mem / 1024 / 1024 << " mb"<<
"\n result: "<< "\n duration: "<< ns_double.count() << " ns"
<< endl;
}
};
class Investigaion{
public:
void make_exp(const int mem, const int travel_order, int id){
Experiment exp;
exp.experiments(mem, travel_order, id);
}
};
void start(){
vector<int> size;
int i = 1;
int last = 1;
int travel_order;
int count;
while (i > 0){
cin >> i;
if ((i < 0) || (last > i))
break;
else
size.push_back(i);
last = i;
}
Investigaion inv1;
travel_order = 1;
count = 0;
cout << "investigation:\n travel_order: \"direct\"\n experiments:"
<< endl;
inv1.make_exp(pow(2, count) * 1024 * 1024, travel_order,
count);
for (int j = size[0]/2; pow(2, j) < ((3 / 2) * size[size.size() - 1]); j++){
count++;
inv1.make_exp(pow(2, j) * 1024 * 1024, travel_order,
count);
}
Investigaion inv2;
travel_order = 2;
count = 0;
cout << endl;
cout << "investigation:\n travel_order: \"reverse\"\n experiments:"
<< endl;
inv2.make_exp(pow(2, count) * 1024 * 1024, travel_order,
count);
for (int j = size[0]/2; pow(2, j) < 3 * size[size.size() - 1] / 2; j++){
count++;
inv2.make_exp(pow(2, j) * 1024 * 1024, travel_order,
count);
}
Investigaion inv3;
travel_order = 3;
count = 0;
cout << endl;
cout << "investigation:\n travel_order: \"random\"\n experiments:"
<< endl;
inv3.make_exp(pow(2, count) * 1024 * 1024, travel_order,
count);
for (int j = size[0]/2; pow(2, j) < 3 * size[size.size() - 1] / 2; j++){
count++;
inv3.make_exp(pow(2, j) * 1024 * 1024, travel_order,
count);
}
}
| 25.79845 | 79 | 0.528546 | [
"vector"
] |
b0babbfa1014e0eae4900ca5ca1c8203831ad475 | 104,579 | cpp | C++ | src/words/word5.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 3 | 2021-01-08T19:14:43.000Z | 2021-06-08T04:52:22.000Z | src/words/word5.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 62 | 2020-06-04T02:37:12.000Z | 2022-03-12T12:43:39.000Z | src/words/word5.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 7 | 2019-07-18T19:58:27.000Z | 2022-02-02T13:21:20.000Z | // AUTOMATICALLY GENERATED BY wordarrays ANALYZER.
#include "StdAfx.h"
_TCHAR *word5[]={0,
_T("aahed"),_T("aalii"),_T("aargh"),_T("abaca"),_T("abaci"),_T("aback"),_T("abaft"),_T("abaka"),_T("abamp"),_T("abase"),
_T("abash"),_T("abate"),_T("abbas"),_T("abbes"),_T("abbey"),_T("abbot"),_T("abeam"),_T("abele"),_T("abets"),_T("abhor"),
_T("abide"),_T("abler"),_T("ables"),_T("abmho"),_T("abode"),_T("abohm"),_T("aboil"),_T("aboma"),_T("aboon"),_T("abort"),
_T("about"),_T("above"),_T("abris"),_T("abuse"),_T("abuts"),_T("abuzz"),_T("abyes"),_T("abysm"),_T("abyss"),_T("acari"),
_T("acerb"),_T("aceta"),_T("ached"),_T("aches"),_T("achoo"),_T("acids"),_T("acidy"),_T("acing"),_T("acini"),_T("ackee"),
_T("acmes"),_T("acmic"),_T("acned"),_T("acnes"),_T("acock"),_T("acold"),_T("acorn"),_T("acred"),_T("acres"),_T("acrid"),
_T("acted"),_T("actin"),_T("actor"),_T("acute"),_T("acyls"),_T("adage"),_T("adapt"),_T("addax"),_T("added"),_T("adder"),
_T("addle"),_T("adeem"),_T("adept"),_T("adieu"),_T("adios"),_T("adits"),_T("adman"),_T("admen"),_T("admit"),_T("admix"),
_T("adobe"),_T("adobo"),_T("adopt"),_T("adore"),_T("adorn"),_T("adown"),_T("adoze"),_T("adult"),_T("adunc"),_T("adust"),
_T("adyta"),_T("adzes"),_T("aecia"),_T("aedes"),_T("aegis"),_T("aeons"),_T("aerie"),_T("afars"),_T("affix"),_T("afire"),
_T("afoot"),_T("afore"),_T("afoul"),_T("afrit"),_T("after"),_T("again"),_T("agama"),_T("agape"),_T("agars"),_T("agate"),
_T("agave"),_T("agaze"),_T("agene"),_T("agent"),_T("agers"),_T("agger"),_T("aggie"),_T("aggro"),_T("aghas"),_T("agile"),
_T("aging"),_T("agios"),_T("agism"),_T("agist"),_T("aglee"),_T("aglet"),_T("agley"),_T("aglow"),_T("agmas"),_T("agone"),
_T("agons"),_T("agony"),_T("agora"),_T("agree"),_T("agria"),_T("agues"),_T("ahead"),_T("ahold"),_T("ahull"),_T("aided"),
_T("aider"),_T("aides"),_T("ailed"),_T("aimed"),_T("aimer"),_T("aioli"),_T("aired"),_T("airer"),_T("airns"),_T("airth"),
_T("airts"),_T("aisle"),_T("aitch"),_T("aiver"),_T("ajiva"),_T("ajuga"),_T("akees"),_T("akela"),_T("akene"),_T("alack"),
_T("alamo"),_T("aland"),_T("alane"),_T("alang"),_T("alans"),_T("alant"),_T("alarm"),_T("alary"),_T("alate"),_T("albas"),
_T("album"),_T("alcid"),_T("alder"),_T("aldol"),_T("alecs"),_T("alefs"),_T("aleph"),_T("alert"),_T("alfas"),_T("algae"),
_T("algal"),_T("algas"),_T("algid"),_T("algin"),_T("algor"),_T("algum"),_T("alias"),_T("alibi"),_T("alien"),_T("alifs"),
_T("align"),_T("alike"),_T("aline"),_T("alist"),_T("alive"),_T("aliya"),_T("alkyd"),_T("alkyl"),_T("allay"),_T("allee"),
_T("alley"),_T("allod"),_T("allot"),_T("allow"),_T("alloy"),_T("allyl"),_T("almah"),_T("almas"),_T("almeh"),_T("almes"),
_T("almud"),_T("almug"),_T("aloes"),_T("aloft"),_T("aloha"),_T("aloin"),_T("alone"),_T("along"),_T("aloof"),_T("aloud"),
_T("alpha"),_T("altar"),_T("alter"),_T("altho"),_T("altos"),_T("alula"),_T("alums"),_T("alway"),_T("amahs"),_T("amain"),
_T("amass"),_T("amaze"),_T("amber"),_T("ambit"),_T("amble"),_T("ambos"),_T("ambry"),_T("ameba"),_T("ameer"),_T("amend"),
_T("amens"),_T("ament"),_T("amias"),_T("amice"),_T("amici"),_T("amide"),_T("amido"),_T("amids"),_T("amies"),_T("amiga"),
_T("amigo"),_T("amine"),_T("amino"),_T("amins"),_T("amirs"),_T("amiss"),_T("amity"),_T("ammos"),_T("amnia"),_T("amnic"),
_T("amoks"),_T("amole"),_T("among"),_T("amort"),_T("amour"),_T("ample"),_T("amply"),_T("ampul"),_T("amuck"),_T("amuse"),
_T("amyls"),_T("ancon"),_T("anear"),_T("anele"),_T("anent"),_T("angas"),_T("angel"),_T("anger"),_T("angle"),_T("angry"),
_T("angst"),_T("anile"),_T("anils"),_T("anima"),_T("anime"),_T("animi"),_T("anion"),_T("anise"),_T("ankhs"),_T("ankle"),
_T("ankus"),_T("anlas"),_T("annal"),_T("annas"),_T("annex"),_T("annoy"),_T("annul"),_T("anoas"),_T("anode"),_T("anole"),
_T("anomy"),_T("ansae"),_T("antae"),_T("antas"),_T("anted"),_T("antes"),_T("antic"),_T("antis"),_T("antra"),_T("antre"),
_T("antsy"),_T("anvil"),_T("aorta"),_T("apace"),_T("apart"),_T("apeak"),_T("apeek"),_T("apers"),_T("apery"),_T("aphid"),
_T("aphis"),_T("apian"),_T("aping"),_T("apish"),_T("apnea"),_T("apods"),_T("aport"),_T("appal"),_T("appel"),_T("apple"),
_T("apply"),_T("apres"),_T("apron"),_T("apses"),_T("apsis"),_T("apter"),_T("aptly"),_T("aquae"),_T("aquas"),_T("araks"),
_T("arbor"),_T("arced"),_T("arcus"),_T("ardeb"),_T("ardor"),_T("areae"),_T("areal"),_T("areas"),_T("areca"),_T("areic"),
_T("arena"),_T("arete"),_T("argal"),_T("argil"),_T("argle"),_T("argol"),_T("argon"),_T("argot"),_T("argue"),_T("argus"),
_T("arhat"),_T("arias"),_T("ariel"),_T("arils"),_T("arise"),_T("arles"),_T("armed"),_T("armer"),_T("armet"),_T("armor"),
_T("aroid"),_T("aroma"),_T("arose"),_T("arpen"),_T("arras"),_T("array"),_T("arris"),_T("arrow"),_T("arses"),_T("arsis"),
_T("arson"),_T("artal"),_T("artel"),_T("artsy"),_T("arums"),_T("arval"),_T("arvos"),_T("aryls"),_T("asana"),_T("ascot"),
_T("ascus"),_T("asdic"),_T("ashed"),_T("ashen"),_T("ashes"),_T("aside"),_T("asked"),_T("asker"),_T("askew"),_T("askoi"),
_T("askos"),_T("aspen"),_T("asper"),_T("aspic"),_T("aspis"),_T("assai"),_T("assay"),_T("asses"),_T("asset"),_T("aster"),
_T("astir"),_T("asyla"),_T("ataps"),_T("ataxy"),_T("atilt"),_T("atlas"),_T("atman"),_T("atmas"),_T("atoll"),_T("atoms"),
_T("atomy"),_T("atone"),_T("atony"),_T("atopy"),_T("atria"),_T("atrip"),_T("attar"),_T("attic"),_T("audad"),_T("audio"),
_T("audit"),_T("auger"),_T("aught"),_T("augur"),_T("aulic"),_T("aunts"),_T("aunty"),_T("aurae"),_T("aural"),_T("aurar"),
_T("auras"),_T("aurei"),_T("aures"),_T("auric"),_T("auris"),_T("aurum"),_T("autos"),_T("auxin"),_T("avail"),_T("avant"),
_T("avast"),_T("avens"),_T("avers"),_T("avert"),_T("avgas"),_T("avian"),_T("avion"),_T("aviso"),_T("avoid"),_T("avows"),
_T("await"),_T("awake"),_T("award"),_T("aware"),_T("awash"),_T("awful"),_T("awing"),_T("awned"),_T("awoke"),_T("awols"),
_T("axels"),_T("axial"),_T("axile"),_T("axils"),_T("axing"),_T("axiom"),_T("axion"),_T("axite"),_T("axled"),_T("axles"),
_T("axman"),_T("axmen"),_T("axone"),_T("axons"),_T("ayahs"),_T("ayins"),_T("azans"),_T("azide"),_T("azido"),_T("azine"),
_T("azlon"),_T("azoic"),_T("azole"),_T("azons"),_T("azote"),_T("azoth"),_T("azure"),_T("baaed"),_T("baals"),_T("babas"),
_T("babel"),_T("babes"),_T("babka"),_T("baboo"),_T("babul"),_T("babus"),_T("bacca"),_T("backs"),_T("bacon"),_T("baddy"),
_T("badge"),_T("badly"),_T("baffs"),_T("baffy"),_T("bagel"),_T("baggy"),_T("bahts"),_T("bails"),_T("bairn"),_T("baith"),
_T("baits"),_T("baiza"),_T("baize"),_T("baked"),_T("baker"),_T("bakes"),_T("balas"),_T("balds"),_T("baldy"),_T("baled"),
_T("baler"),_T("bales"),_T("balks"),_T("balky"),_T("balls"),_T("bally"),_T("balms"),_T("balmy"),_T("balsa"),_T("banal"),
_T("banco"),_T("bands"),_T("bandy"),_T("baned"),_T("banes"),_T("bangs"),_T("banjo"),_T("banks"),_T("banns"),_T("banty"),
_T("barbe"),_T("barbs"),_T("barde"),_T("bards"),_T("bared"),_T("barer"),_T("bares"),_T("barfs"),_T("barge"),_T("baric"),
_T("barks"),_T("barky"),_T("barms"),_T("barmy"),_T("barns"),_T("barny"),_T("baron"),_T("barre"),_T("barye"),_T("basal"),
_T("based"),_T("baser"),_T("bases"),_T("basic"),_T("basil"),_T("basin"),_T("basis"),_T("basks"),_T("bassi"),_T("basso"),
_T("bassy"),_T("baste"),_T("basts"),_T("batch"),_T("bated"),_T("bates"),_T("bathe"),_T("baths"),_T("batik"),_T("baton"),
_T("batts"),_T("battu"),_T("batty"),_T("bauds"),_T("baulk"),_T("bawds"),_T("bawdy"),_T("bawls"),_T("bawty"),_T("bayed"),
_T("bayou"),_T("bazar"),_T("bazoo"),_T("beach"),_T("beads"),_T("beady"),_T("beaks"),_T("beaky"),_T("beams"),_T("beamy"),
_T("beano"),_T("beans"),_T("beard"),_T("bears"),_T("beast"),_T("beats"),_T("beaus"),_T("beaut"),_T("beaux"),_T("bebop"),
_T("becap"),_T("becks"),_T("bedel"),_T("bedew"),_T("bedim"),_T("beech"),_T("beefs"),_T("beefy"),_T("beeps"),_T("beers"),
_T("beery"),_T("beets"),_T("befit"),_T("befog"),_T("began"),_T("begat"),_T("beget"),_T("begin"),_T("begot"),_T("begum"),
_T("begun"),_T("beige"),_T("beigy"),_T("being"),_T("belay"),_T("belch"),_T("belga"),_T("belie"),_T("belle"),_T("bells"),
_T("belly"),_T("below"),_T("belts"),_T("bemas"),_T("bemix"),_T("bench"),_T("bends"),_T("bendy"),_T("benes"),_T("benne"),
_T("benni"),_T("benny"),_T("bents"),_T("beret"),_T("bergs"),_T("berme"),_T("berms"),_T("berry"),_T("berth"),_T("beryl"),
_T("beset"),_T("besom"),_T("besot"),_T("bests"),_T("betas"),_T("betel"),_T("beths"),_T("beton"),_T("betta"),_T("bevel"),
_T("bevor"),_T("bewig"),_T("bezel"),_T("bezil"),_T("bhang"),_T("bhoot"),_T("bhuts"),_T("biali"),_T("bialy"),_T("bibbs"),
_T("bible"),_T("bices"),_T("biddy"),_T("bided"),_T("bider"),_T("bides"),_T("bidet"),_T("bield"),_T("biers"),_T("biffs"),
_T("biffy"),_T("bifid"),_T("bight"),_T("bigly"),_T("bigot"),_T("bijou"),_T("biked"),_T("biker"),_T("bikes"),_T("bikie"),
_T("bilbo"),_T("biles"),_T("bilge"),_T("bilgy"),_T("bilks"),_T("bills"),_T("billy"),_T("bimah"),_T("bimas"),_T("bimbo"),
_T("binal"),_T("bindi"),_T("binds"),_T("bines"),_T("binge"),_T("bingo"),_T("binit"),_T("bints"),_T("biome"),_T("biont"),
_T("biota"),_T("biped"),_T("bipod"),_T("birch"),_T("birds"),_T("birks"),_T("birle"),_T("birls"),_T("birrs"),_T("birse"),
_T("birth"),_T("bises"),_T("bisks"),_T("bison"),_T("bitch"),_T("biter"),_T("bites"),_T("bitsy"),_T("bitts"),_T("bitty"),
_T("bizes"),_T("blabs"),_T("black"),_T("blade"),_T("blahs"),_T("blain"),_T("blame"),_T("blams"),_T("bland"),_T("blank"),
_T("blare"),_T("blase"),_T("blast"),_T("blate"),_T("blats"),_T("blawn"),_T("blaws"),_T("blaze"),_T("bleak"),_T("blear"),
_T("bleat"),_T("blebs"),_T("bleed"),_T("bleep"),_T("blend"),_T("blent"),_T("bless"),_T("blest"),_T("blets"),_T("blimp"),
_T("blimy"),_T("blind"),_T("blini"),_T("blink"),_T("blips"),_T("bliss"),_T("blite"),_T("blitz"),_T("bloat"),_T("blobs"),
_T("block"),_T("blocs"),_T("bloke"),_T("blond"),_T("blood"),_T("bloom"),_T("bloop"),_T("blots"),_T("blown"),_T("blows"),
_T("blowy"),_T("blubs"),_T("blued"),_T("bluer"),_T("blues"),_T("bluet"),_T("bluey"),_T("bluff"),_T("blume"),_T("blunt"),
_T("blurb"),_T("blurs"),_T("blurt"),_T("blush"),_T("blype"),_T("board"),_T("boars"),_T("boart"),_T("boast"),_T("boats"),
_T("bobby"),_T("bocce"),_T("bocci"),_T("boche"),_T("bocks"),_T("boded"),_T("bodes"),_T("boffo"),_T("boffs"),_T("bogan"),
_T("bogey"),_T("boggy"),_T("bogie"),_T("bogle"),_T("bogus"),_T("bohea"),_T("boils"),_T("boing"),_T("boite"),_T("bolar"),
_T("bolas"),_T("bolds"),_T("boles"),_T("bolls"),_T("bolos"),_T("bolts"),_T("bolus"),_T("bombe"),_T("bombs"),_T("bonds"),
_T("boned"),_T("boner"),_T("bones"),_T("boney"),_T("bongo"),_T("bongs"),_T("bonks"),_T("bonne"),_T("bonny"),_T("bonus"),
_T("bonze"),_T("boobs"),_T("booby"),_T("booed"),_T("boogy"),_T("books"),_T("booms"),_T("boomy"),_T("boons"),_T("boors"),
_T("boost"),_T("booth"),_T("boots"),_T("booty"),_T("booze"),_T("boozy"),_T("boral"),_T("boras"),_T("borax"),_T("bored"),
_T("borer"),_T("bores"),_T("boric"),_T("borne"),_T("boron"),_T("borts"),_T("borty"),_T("bortz"),_T("bosks"),_T("bosky"),
_T("bosom"),_T("boson"),_T("bossy"),_T("bosun"),_T("botas"),_T("botch"),_T("botel"),_T("bothy"),_T("botts"),_T("bough"),
_T("boule"),_T("bound"),_T("bourg"),_T("bourn"),_T("bouse"),_T("bousy"),_T("bouts"),_T("bovid"),_T("bowed"),_T("bowel"),
_T("bower"),_T("bowls"),_T("bowse"),_T("boxed"),_T("boxer"),_T("boxes"),_T("boyar"),_T("boyla"),_T("boyos"),_T("bozos"),
_T("brace"),_T("brach"),_T("bract"),_T("brads"),_T("braes"),_T("brags"),_T("braid"),_T("brail"),_T("brain"),_T("brake"),
_T("braky"),_T("brand"),_T("brank"),_T("brans"),_T("brant"),_T("brash"),_T("brass"),_T("brats"),_T("brava"),_T("brave"),
_T("bravi"),_T("bravo"),_T("brawl"),_T("brawn"),_T("braws"),_T("braxy"),_T("brays"),_T("braza"),_T("braze"),_T("bread"),
_T("break"),_T("bream"),_T("brede"),_T("breed"),_T("brees"),_T("brens"),_T("brent"),_T("breve"),_T("brews"),_T("briar"),
_T("bribe"),_T("brick"),_T("bride"),_T("brief"),_T("brier"),_T("bries"),_T("brigs"),_T("brill"),_T("brims"),_T("brine"),
_T("bring"),_T("brink"),_T("brins"),_T("briny"),_T("brios"),_T("brisk"),_T("brits"),_T("britt"),_T("broad"),_T("brock"),
_T("broil"),_T("broke"),_T("brome"),_T("bromo"),_T("bronc"),_T("brood"),_T("brook"),_T("broom"),_T("broos"),_T("brose"),
_T("brosy"),_T("broth"),_T("brown"),_T("brows"),_T("brugh"),_T("bruin"),_T("bruit"),_T("brume"),_T("brunt"),_T("brush"),
_T("brusk"),_T("brute"),_T("bubal"),_T("bubby"),_T("bucko"),_T("bucks"),_T("buddy"),_T("budge"),_T("buffi"),_T("buffo"),
_T("buffs"),_T("buffy"),_T("buggy"),_T("bugle"),_T("buhls"),_T("buhrs"),_T("build"),_T("built"),_T("bulbs"),_T("bulge"),
_T("bulgy"),_T("bulks"),_T("bulky"),_T("bulla"),_T("bulls"),_T("bully"),_T("bumfs"),_T("bumph"),_T("bumps"),_T("bumpy"),
_T("bunch"),_T("bunco"),_T("bunds"),_T("bundt"),_T("bungs"),_T("bunko"),_T("bunks"),_T("bunns"),_T("bunny"),_T("bunts"),
_T("bunya"),_T("buoys"),_T("buran"),_T("buras"),_T("burbs"),_T("burds"),_T("buret"),_T("burgh"),_T("burgs"),_T("burin"),
_T("burke"),_T("burls"),_T("burly"),_T("burns"),_T("burnt"),_T("burps"),_T("burro"),_T("burrs"),_T("burry"),_T("bursa"),
_T("burse"),_T("burst"),_T("busby"),_T("bused"),_T("buses"),_T("bushy"),_T("busks"),_T("busts"),_T("busty"),_T("butch"),
_T("buteo"),_T("butle"),_T("butte"),_T("butts"),_T("butty"),_T("butut"),_T("butyl"),_T("buxom"),_T("buyer"),_T("bwana"),
_T("bylaw"),_T("byres"),_T("byrls"),_T("byssi"),_T("bytes"),_T("byway"),_T("cabal"),_T("cabby"),_T("caber"),_T("cabin"),
_T("cable"),_T("cabob"),_T("cacao"),_T("cacas"),_T("cache"),_T("cacti"),_T("caddy"),_T("cades"),_T("cadet"),_T("cadge"),
_T("cadgy"),_T("cadis"),_T("cadre"),_T("caeca"),_T("cafes"),_T("caffs"),_T("caged"),_T("cager"),_T("cages"),_T("cagey"),
_T("cahow"),_T("caids"),_T("cains"),_T("caird"),_T("cairn"),_T("cajon"),_T("caked"),_T("cakes"),_T("cakey"),_T("calfs"),
_T("calif"),_T("calix"),_T("calks"),_T("calla"),_T("calls"),_T("calms"),_T("calve"),_T("calyx"),_T("camas"),_T("camel"),
_T("cameo"),_T("cames"),_T("campi"),_T("campo"),_T("camps"),_T("campy"),_T("canal"),_T("candy"),_T("caned"),_T("caner"),
_T("canes"),_T("canid"),_T("canna"),_T("canny"),_T("canoe"),_T("canon"),_T("canso"),_T("canst"),_T("canto"),_T("cants"),
_T("canty"),_T("caped"),_T("caper"),_T("capes"),_T("caphs"),_T("capon"),_T("capos"),_T("caput"),_T("carat"),_T("carbo"),
_T("carbs"),_T("cards"),_T("cared"),_T("carer"),_T("cares"),_T("caret"),_T("carex"),_T("cargo"),_T("carks"),_T("carle"),
_T("carls"),_T("carns"),_T("carny"),_T("carob"),_T("carol"),_T("carom"),_T("carpi"),_T("carps"),_T("carrs"),_T("carry"),
_T("carse"),_T("carte"),_T("carts"),_T("carve"),_T("casas"),_T("cased"),_T("cases"),_T("casks"),_T("casky"),_T("caste"),
_T("casts"),_T("casus"),_T("catch"),_T("cater"),_T("cates"),_T("catty"),_T("cauld"),_T("caulk"),_T("cauls"),_T("cause"),
_T("caved"),_T("caver"),_T("caves"),_T("cavie"),_T("cavil"),_T("cawed"),_T("cease"),_T("cebid"),_T("cecal"),_T("cecum"),
_T("cedar"),_T("ceded"),_T("ceder"),_T("cedes"),_T("cedis"),_T("ceiba"),_T("ceils"),_T("celeb"),_T("cella"),_T("celli"),
_T("cello"),_T("cells"),_T("celom"),_T("celts"),_T("cense"),_T("cento"),_T("cents"),_T("ceorl"),_T("cepes"),_T("cerci"),
_T("cered"),_T("ceres"),_T("ceria"),_T("ceric"),_T("ceros"),_T("cesta"),_T("cesti"),_T("cetes"),_T("chads"),_T("chafe"),
_T("chaff"),_T("chain"),_T("chair"),_T("chalk"),_T("champ"),_T("chams"),_T("chang"),_T("chant"),_T("chaos"),_T("chape"),
_T("chaps"),_T("chapt"),_T("chard"),_T("chare"),_T("chark"),_T("charm"),_T("charr"),_T("chars"),_T("chart"),_T("chary"),
_T("chase"),_T("chasm"),_T("chats"),_T("chaws"),_T("chays"),_T("cheap"),_T("cheat"),_T("check"),_T("cheek"),_T("cheep"),
_T("cheer"),_T("chefs"),_T("chela"),_T("chert"),_T("chess"),_T("chest"),_T("cheth"),_T("chevy"),_T("chews"),_T("chewy"),
_T("chiao"),_T("chias"),_T("chick"),_T("chico"),_T("chics"),_T("chide"),_T("chief"),_T("chiel"),_T("child"),_T("chile"),
_T("chili"),_T("chill"),_T("chimb"),_T("chime"),_T("chimp"),_T("china"),_T("chine"),_T("chink"),_T("chino"),_T("chins"),
_T("chips"),_T("chirk"),_T("chirm"),_T("chiro"),_T("chirp"),_T("chirr"),_T("chits"),_T("chive"),_T("chivy"),_T("chock"),
_T("choir"),_T("choke"),_T("choky"),_T("cholo"),_T("chomp"),_T("chook"),_T("chops"),_T("chord"),_T("chore"),_T("chose"),
_T("chott"),_T("chows"),_T("chubs"),_T("chuck"),_T("chufa"),_T("chuff"),_T("chugs"),_T("chump"),_T("chums"),_T("chunk"),
_T("churl"),_T("churn"),_T("churr"),_T("chute"),_T("chyle"),_T("chyme"),_T("cibol"),_T("cider"),_T("cigar"),_T("cilia"),
_T("cimex"),_T("cinch"),_T("cines"),_T("cions"),_T("circa"),_T("cires"),_T("cirri"),_T("cisco"),_T("cissy"),_T("cists"),
_T("cited"),_T("citer"),_T("cites"),_T("civet"),_T("civic"),_T("civie"),_T("civil"),_T("civvy"),_T("clach"),_T("clack"),
_T("clade"),_T("clads"),_T("clags"),_T("claim"),_T("clamp"),_T("clams"),_T("clang"),_T("clank"),_T("clans"),_T("claps"),
_T("clapt"),_T("claro"),_T("clary"),_T("clash"),_T("clasp"),_T("class"),_T("clast"),_T("clave"),_T("clavi"),_T("claws"),
_T("clays"),_T("clean"),_T("clear"),_T("cleat"),_T("cleek"),_T("clefs"),_T("cleft"),_T("clepe"),_T("clept"),_T("clerk"),
_T("clews"),_T("click"),_T("cliff"),_T("clift"),_T("climb"),_T("clime"),_T("cline"),_T("cling"),_T("clink"),_T("clips"),
_T("clipt"),_T("cloak"),_T("clock"),_T("clods"),_T("clogs"),_T("clomb"),_T("clomp"),_T("clone"),_T("clonk"),_T("clons"),
_T("cloot"),_T("clops"),_T("close"),_T("cloth"),_T("clots"),_T("cloud"),_T("clour"),_T("clout"),_T("clove"),_T("clown"),
_T("cloys"),_T("cloze"),_T("clubs"),_T("cluck"),_T("clued"),_T("clues"),_T("clump"),_T("clung"),_T("clunk"),_T("coach"),
_T("coact"),_T("coala"),_T("coals"),_T("coaly"),_T("coapt"),_T("coast"),_T("coati"),_T("coats"),_T("cobbs"),_T("cobby"),
_T("cobia"),_T("coble"),_T("cobra"),_T("cocas"),_T("cocci"),_T("cocks"),_T("cocky"),_T("cocoa"),_T("cocos"),_T("codas"),
_T("codec"),_T("coded"),_T("coden"),_T("coder"),_T("codes"),_T("codex"),_T("codon"),_T("coeds"),_T("coffs"),_T("cogon"),
_T("cohog"),_T("cohos"),_T("coifs"),_T("coign"),_T("coils"),_T("coins"),_T("coirs"),_T("coked"),_T("cokes"),_T("colas"),
_T("colds"),_T("coled"),_T("coles"),_T("colic"),_T("colin"),_T("colly"),_T("colog"),_T("colon"),_T("color"),_T("colts"),
_T("colza"),_T("comae"),_T("comal"),_T("comas"),_T("combe"),_T("combo"),_T("combs"),_T("comer"),_T("comes"),_T("comet"),
_T("comfy"),_T("comic"),_T("comix"),_T("comma"),_T("commy"),_T("compo"),_T("comps"),_T("compt"),_T("comte"),_T("conch"),
_T("condo"),_T("coned"),_T("cones"),_T("coney"),_T("conga"),_T("conge"),_T("congo"),_T("conic"),_T("conin"),_T("conks"),
_T("conky"),_T("conns"),_T("conte"),_T("conto"),_T("conus"),_T("cooch"),_T("cooed"),_T("cooee"),_T("cooer"),_T("cooey"),
_T("coofs"),_T("cooks"),_T("cooky"),_T("cools"),_T("cooly"),_T("coomb"),_T("coons"),_T("coops"),_T("coopt"),_T("coots"),
_T("copal"),_T("coped"),_T("copen"),_T("coper"),_T("copes"),_T("copra"),_T("copse"),_T("coral"),_T("corby"),_T("cords"),
_T("cored"),_T("corer"),_T("cores"),_T("corgi"),_T("coria"),_T("corks"),_T("corky"),_T("corms"),_T("corns"),_T("cornu"),
_T("corny"),_T("corps"),_T("corse"),_T("cosec"),_T("coses"),_T("coset"),_T("cosey"),_T("cosie"),_T("costa"),_T("costs"),
_T("cotan"),_T("coted"),_T("cotes"),_T("cotta"),_T("couch"),_T("coude"),_T("cough"),_T("could"),_T("count"),_T("coupe"),
_T("coups"),_T("court"),_T("couth"),_T("coved"),_T("coven"),_T("cover"),_T("coves"),_T("covet"),_T("covey"),_T("covin"),
_T("cowed"),_T("cower"),_T("cowls"),_T("cowry"),_T("coxae"),_T("coxal"),_T("coxed"),_T("coxes"),_T("coyed"),_T("coyer"),
_T("coyly"),_T("coypu"),_T("cozen"),_T("cozes"),_T("cozey"),_T("cozie"),_T("craal"),_T("crabs"),_T("crack"),_T("craft"),
_T("crags"),_T("crake"),_T("cramp"),_T("crams"),_T("crane"),_T("crank"),_T("crape"),_T("craps"),_T("crash"),_T("crass"),
_T("crate"),_T("crave"),_T("crawl"),_T("craws"),_T("craze"),_T("crazy"),_T("creak"),_T("cream"),_T("credo"),_T("creed"),
_T("creek"),_T("creel"),_T("creep"),_T("creme"),_T("crepe"),_T("crept"),_T("crepy"),_T("cress"),_T("crest"),_T("crews"),
_T("cribs"),_T("crick"),_T("cried"),_T("crier"),_T("cries"),_T("crime"),_T("crimp"),_T("cripe"),_T("crisp"),_T("croak"),
_T("croci"),_T("crock"),_T("crocs"),_T("croft"),_T("crone"),_T("crony"),_T("crook"),_T("croon"),_T("crops"),_T("crore"),
_T("cross"),_T("croup"),_T("crowd"),_T("crown"),_T("crows"),_T("croze"),_T("cruck"),_T("crude"),_T("cruds"),_T("cruel"),
_T("cruet"),_T("crumb"),_T("crump"),_T("cruor"),_T("crura"),_T("cruse"),_T("crush"),_T("crust"),_T("crwth"),_T("crypt"),
_T("cubby"),_T("cubeb"),_T("cubed"),_T("cuber"),_T("cubes"),_T("cubic"),_T("cubit"),_T("cuddy"),_T("cuffs"),_T("cuifs"),
_T("cuing"),_T("cuish"),_T("cukes"),_T("culch"),_T("culet"),_T("culex"),_T("culls"),_T("cully"),_T("culms"),_T("culpa"),
_T("culti"),_T("cults"),_T("cumin"),_T("cunts"),_T("cupel"),_T("cupid"),_T("cuppa"),_T("cuppy"),_T("curbs"),_T("curch"),
_T("curds"),_T("curdy"),_T("cured"),_T("curer"),_T("cures"),_T("curet"),_T("curfs"),_T("curia"),_T("curie"),_T("curio"),
_T("curls"),_T("curly"),_T("curns"),_T("currs"),_T("curry"),_T("curse"),_T("curst"),_T("curve"),_T("curvy"),_T("cusec"),
_T("cushy"),_T("cusks"),_T("cusps"),_T("cusso"),_T("cutch"),_T("cuter"),_T("cutes"),_T("cutey"),_T("cutie"),_T("cutin"),
_T("cutis"),_T("cutty"),_T("cutup"),_T("cyano"),_T("cyans"),_T("cycad"),_T("cycas"),_T("cycle"),_T("cyclo"),_T("cyder"),
_T("cylix"),_T("cymae"),_T("cymar"),_T("cymas"),_T("cymes"),_T("cymol"),_T("cynic"),_T("cysts"),_T("cyton"),_T("czars"),
_T("daces"),_T("dacha"),_T("dadas"),_T("daddy"),_T("dados"),_T("daffs"),_T("daffy"),_T("dagga"),_T("dagos"),_T("dahls"),
_T("daily"),_T("dairy"),_T("daisy"),_T("dales"),_T("dally"),_T("daman"),_T("damar"),_T("dames"),_T("damns"),_T("damps"),
_T("dance"),_T("dandy"),_T("dangs"),_T("danio"),_T("darbs"),_T("dared"),_T("darer"),_T("dares"),_T("daric"),_T("darks"),
_T("darky"),_T("darns"),_T("darts"),_T("dashi"),_T("dashy"),_T("dated"),_T("dater"),_T("dates"),_T("datos"),_T("datto"),
_T("datum"),_T("daube"),_T("daubs"),_T("dauby"),_T("daunt"),_T("dauts"),_T("daven"),_T("davit"),_T("dawed"),_T("dawen"),
_T("dawks"),_T("dawns"),_T("dawts"),_T("dazed"),_T("dazes"),_T("deads"),_T("deair"),_T("deals"),_T("dealt"),_T("deans"),
_T("dears"),_T("deary"),_T("deash"),_T("death"),_T("deave"),_T("debar"),_T("debit"),_T("debts"),_T("debug"),_T("debut"),
_T("debye"),_T("decaf"),_T("decal"),_T("decay"),_T("decks"),_T("decor"),_T("decos"),_T("decoy"),_T("decry"),_T("dedal"),
_T("deeds"),_T("deedy"),_T("deems"),_T("deeps"),_T("deers"),_T("deets"),_T("defat"),_T("defer"),_T("defis"),_T("defog"),
_T("degas"),_T("degum"),_T("deice"),_T("deify"),_T("deign"),_T("deils"),_T("deism"),_T("deist"),_T("deity"),_T("deked"),
_T("dekes"),_T("dekko"),_T("delay"),_T("deled"),_T("deles"),_T("delfs"),_T("delft"),_T("delis"),_T("dells"),_T("delly"),
_T("delta"),_T("delve"),_T("demes"),_T("demit"),_T("demob"),_T("demon"),_T("demos"),_T("demur"),_T("denes"),_T("denim"),
_T("dense"),_T("dents"),_T("deoxy"),_T("depot"),_T("depth"),_T("derat"),_T("deray"),_T("derby"),_T("derma"),_T("derms"),
_T("derry"),_T("desex"),_T("desks"),_T("deter"),_T("detox"),_T("deuce"),_T("devas"),_T("devel"),_T("devil"),_T("devon"),
_T("dewan"),_T("dewar"),_T("dewax"),_T("dewed"),_T("dexes"),_T("dexie"),_T("dhaks"),_T("dhals"),_T("dhobi"),_T("dhole"),
_T("dhoti"),_T("dhows"),_T("dhuti"),_T("dials"),_T("diary"),_T("diazo"),_T("diced"),_T("dicer"),_T("dices"),_T("dicey"),
_T("dicks"),_T("dicky"),_T("dicot"),_T("dicta"),_T("dicty"),_T("didie"),_T("didos"),_T("didst"),_T("diene"),_T("diets"),
_T("dight"),_T("digit"),_T("diked"),_T("diker"),_T("dikes"),_T("dikey"),_T("dildo"),_T("dills"),_T("dilly"),_T("dimer"),
_T("dimes"),_T("dimly"),_T("dinar"),_T("dined"),_T("diner"),_T("dines"),_T("dinge"),_T("dingo"),_T("dings"),_T("dingy"),
_T("dinks"),_T("dinky"),_T("dints"),_T("diode"),_T("diols"),_T("dippy"),_T("dipso"),_T("direr"),_T("dirge"),_T("dirks"),
_T("dirls"),_T("dirts"),_T("dirty"),_T("disci"),_T("disco"),_T("discs"),_T("dishy"),_T("disks"),_T("disme"),_T("ditas"),
_T("ditch"),_T("dites"),_T("ditsy"),_T("ditto"),_T("ditty"),_T("ditzy"),_T("divan"),_T("divas"),_T("dived"),_T("diver"),
_T("dives"),_T("divot"),_T("divvy"),_T("diwan"),_T("dixit"),_T("dizen"),_T("dizzy"),_T("djinn"),_T("djins"),_T("doats"),
_T("dobby"),_T("dobie"),_T("dobla"),_T("dobra"),_T("docks"),_T("dodge"),_T("dodgy"),_T("dodos"),_T("doers"),_T("doest"),
_T("doeth"),_T("doffs"),_T("doges"),_T("dogey"),_T("doggo"),_T("doggy"),_T("dogie"),_T("dogma"),_T("doily"),_T("doing"),
_T("doits"),_T("dojos"),_T("dolce"),_T("dolci"),_T("doled"),_T("doles"),_T("dolls"),_T("dolly"),_T("dolma"),_T("dolor"),
_T("dolts"),_T("domal"),_T("domed"),_T("domes"),_T("domic"),_T("donas"),_T("donee"),_T("donga"),_T("dongs"),_T("donna"),
_T("donne"),_T("donor"),_T("donsy"),_T("donut"),_T("dooly"),_T("dooms"),_T("doomy"),_T("doors"),_T("doozy"),_T("dopas"),
_T("doped"),_T("doper"),_T("dopes"),_T("dopey"),_T("dorks"),_T("dorky"),_T("dorms"),_T("dormy"),_T("dorps"),_T("dorrs"),
_T("dorsa"),_T("dorty"),_T("dosed"),_T("doser"),_T("doses"),_T("dotal"),_T("doted"),_T("doter"),_T("dotes"),_T("dotty"),
_T("doubt"),_T("douce"),_T("dough"),_T("douma"),_T("doums"),_T("doura"),_T("douse"),_T("doven"),_T("doves"),_T("dowdy"),
_T("dowed"),_T("dowel"),_T("dower"),_T("dowie"),_T("downs"),_T("downy"),_T("dowry"),_T("dowse"),_T("doxie"),_T("doyen"),
_T("doyly"),_T("dozed"),_T("dozen"),_T("dozer"),_T("dozes"),_T("drabs"),_T("draff"),_T("draft"),_T("drags"),_T("drail"),
_T("drain"),_T("drake"),_T("drama"),_T("drams"),_T("drank"),_T("drape"),_T("drats"),_T("drave"),_T("drawl"),_T("drawn"),
_T("draws"),_T("drays"),_T("dread"),_T("dream"),_T("drear"),_T("dreck"),_T("dreed"),_T("drees"),_T("dregs"),_T("dreks"),
_T("dress"),_T("drest"),_T("dribs"),_T("dried"),_T("drier"),_T("dries"),_T("drift"),_T("drill"),_T("drily"),_T("drink"),
_T("drips"),_T("dript"),_T("drive"),_T("droit"),_T("droll"),_T("drone"),_T("drool"),_T("droop"),_T("drops"),_T("dropt"),
_T("dross"),_T("drouk"),_T("drove"),_T("drown"),_T("drubs"),_T("drugs"),_T("druid"),_T("drums"),_T("drunk"),_T("drupe"),
_T("druse"),_T("dryad"),_T("dryer"),_T("dryly"),_T("duads"),_T("duals"),_T("ducal"),_T("ducat"),_T("duces"),_T("duchy"),
_T("ducks"),_T("ducky"),_T("ducts"),_T("duddy"),_T("duded"),_T("dudes"),_T("duels"),_T("duets"),_T("duffs"),_T("duits"),
_T("duked"),_T("dukes"),_T("dulia"),_T("dulls"),_T("dully"),_T("dulse"),_T("dumas"),_T("dumbs"),_T("dumka"),_T("dumky"),
_T("dummy"),_T("dumps"),_T("dumpy"),_T("dunam"),_T("dunce"),_T("dunch"),_T("dunes"),_T("dungs"),_T("dungy"),_T("dunks"),
_T("dunts"),_T("duomi"),_T("duomo"),_T("duped"),_T("duper"),_T("dupes"),_T("duple"),_T("dural"),_T("duras"),_T("dured"),
_T("dures"),_T("durns"),_T("duroc"),_T("duros"),_T("durra"),_T("durrs"),_T("durst"),_T("durum"),_T("dusks"),_T("dusky"),
_T("dusts"),_T("dusty"),_T("dutch"),_T("duvet"),_T("dwarf"),_T("dweeb"),_T("dwell"),_T("dwelt"),_T("dwine"),_T("dyads"),
_T("dyers"),_T("dying"),_T("dyked"),_T("dykes"),_T("dykey"),_T("dynel"),_T("dynes"),_T("eager"),_T("eagle"),_T("eagre"),
_T("eared"),_T("earls"),_T("early"),_T("earns"),_T("earth"),_T("eased"),_T("easel"),_T("eases"),_T("easts"),_T("eaten"),
_T("eater"),_T("eaved"),_T("eaves"),_T("ebbed"),_T("ebbet"),_T("ebons"),_T("ebony"),_T("eched"),_T("eches"),_T("echos"),
_T("eclat"),_T("ecrus"),_T("edema"),_T("edged"),_T("edger"),_T("edges"),_T("edict"),_T("edify"),_T("edile"),_T("edits"),
_T("educe"),_T("educt"),_T("eerie"),_T("egads"),_T("egers"),_T("egest"),_T("eggar"),_T("egged"),_T("egger"),_T("egret"),
_T("eider"),_T("eidos"),_T("eight"),_T("eikon"),_T("eject"),_T("eking"),_T("elain"),_T("eland"),_T("elans"),_T("elate"),
_T("elbow"),_T("elder"),_T("elect"),_T("elegy"),_T("elemi"),_T("elfin"),_T("elide"),_T("elint"),_T("elite"),_T("eloin"),
_T("elope"),_T("elude"),_T("elute"),_T("elver"),_T("elves"),_T("embar"),_T("embay"),_T("embed"),_T("ember"),_T("embow"),
_T("emcee"),_T("emeer"),_T("emend"),_T("emery"),_T("emeus"),_T("emirs"),_T("emits"),_T("emmer"),_T("emmet"),_T("emote"),
_T("empty"),_T("emyde"),_T("emyds"),_T("enact"),_T("enate"),_T("ended"),_T("ender"),_T("endow"),_T("endue"),_T("enema"),
_T("enemy"),_T("enjoy"),_T("ennui"),_T("enoki"),_T("enols"),_T("enorm"),_T("enows"),_T("enrol"),_T("ensky"),_T("ensue"),
_T("enter"),_T("entia"),_T("entry"),_T("enure"),_T("envoi"),_T("envoy"),_T("enzym"),_T("eosin"),_T("epact"),_T("epees"),
_T("ephah"),_T("ephas"),_T("ephod"),_T("ephor"),_T("epics"),_T("epoch"),_T("epode"),_T("epoxy"),_T("equal"),_T("equid"),
_T("equip"),_T("erase"),_T("erect"),_T("ergot"),_T("erica"),_T("ernes"),_T("erode"),_T("erose"),_T("erred"),_T("error"),
_T("erses"),_T("eruct"),_T("erugo"),_T("erupt"),_T("ervil"),_T("escar"),_T("escot"),_T("eskar"),_T("esker"),_T("essay"),
_T("esses"),_T("ester"),_T("estop"),_T("etape"),_T("ether"),_T("ethic"),_T("ethos"),_T("ethyl"),_T("etnas"),_T("etude"),
_T("etuis"),_T("etwee"),_T("etyma"),_T("euros"),_T("evade"),_T("evens"),_T("event"),_T("evert"),_T("every"),_T("evict"),
_T("evils"),_T("evite"),_T("evoke"),_T("ewers"),_T("exact"),_T("exalt"),_T("exams"),_T("excel"),_T("execs"),_T("exert"),
_T("exile"),_T("exine"),_T("exist"),_T("exits"),_T("exons"),_T("expat"),_T("expel"),_T("expos"),_T("extol"),_T("extra"),
_T("exude"),_T("exult"),_T("exurb"),_T("eyers"),_T("eying"),_T("eyras"),_T("eyres"),_T("eyrie"),_T("eyrir"),_T("fable"),
_T("faced"),_T("facer"),_T("faces"),_T("facet"),_T("facia"),_T("facts"),_T("faddy"),_T("faded"),_T("fader"),_T("fades"),
_T("fadge"),_T("fados"),_T("faena"),_T("faery"),_T("faggy"),_T("fagin"),_T("fagot"),_T("fails"),_T("faint"),_T("fairs"),
_T("fairy"),_T("faith"),_T("faked"),_T("faker"),_T("fakes"),_T("fakey"),_T("fakir"),_T("falls"),_T("false"),_T("famed"),
_T("fames"),_T("fancy"),_T("fanes"),_T("fanga"),_T("fangs"),_T("fanny"),_T("fanon"),_T("fanos"),_T("fanum"),_T("faqir"),
_T("farad"),_T("farce"),_T("farci"),_T("farcy"),_T("fards"),_T("fared"),_T("farer"),_T("fares"),_T("farle"),_T("farls"),
_T("farms"),_T("faros"),_T("farts"),_T("fasts"),_T("fatal"),_T("fated"),_T("fates"),_T("fatly"),_T("fatso"),_T("fatty"),
_T("fatwa"),_T("faugh"),_T("fauld"),_T("fault"),_T("fauna"),_T("fauns"),_T("fauve"),_T("favas"),_T("faves"),_T("favor"),
_T("favus"),_T("fawns"),_T("fawny"),_T("faxed"),_T("faxes"),_T("fayed"),_T("fazed"),_T("fazes"),_T("fears"),_T("fease"),
_T("feast"),_T("feats"),_T("feaze"),_T("fecal"),_T("feces"),_T("fecks"),_T("feeds"),_T("feels"),_T("feeze"),_T("feign"),
_T("feint"),_T("feist"),_T("felid"),_T("fella"),_T("fells"),_T("felly"),_T("felon"),_T("felts"),_T("femes"),_T("femme"),
_T("femur"),_T("fence"),_T("fends"),_T("fenny"),_T("feods"),_T("feoff"),_T("feral"),_T("feres"),_T("feria"),_T("ferly"),
_T("fermi"),_T("ferns"),_T("ferny"),_T("ferry"),_T("fesse"),_T("fetal"),_T("fetas"),_T("fetch"),_T("feted"),_T("fetes"),
_T("fetid"),_T("fetor"),_T("fetus"),_T("feuar"),_T("feuds"),_T("feued"),_T("fever"),_T("fewer"),_T("feyer"),_T("feyly"),
_T("fezes"),_T("fiars"),_T("fiats"),_T("fiber"),_T("fibre"),_T("fices"),_T("fiche"),_T("fichu"),_T("ficin"),_T("ficus"),
_T("fidge"),_T("fidos"),_T("fiefs"),_T("field"),_T("fiend"),_T("fiery"),_T("fifed"),_T("fifer"),_T("fifes"),_T("fifth"),
_T("fifty"),_T("fight"),_T("filar"),_T("filch"),_T("filed"),_T("filer"),_T("files"),_T("filet"),_T("fille"),_T("fillo"),
_T("fills"),_T("filly"),_T("films"),_T("filmy"),_T("filos"),_T("filth"),_T("filum"),_T("final"),_T("finch"),_T("finds"),
_T("fined"),_T("finer"),_T("fines"),_T("finis"),_T("finks"),_T("finny"),_T("finos"),_T("fiord"),_T("fique"),_T("fired"),
_T("firer"),_T("fires"),_T("firms"),_T("firns"),_T("firry"),_T("first"),_T("firth"),_T("fiscs"),_T("fishy"),_T("fists"),
_T("fitch"),_T("fitly"),_T("fiver"),_T("fives"),_T("fixed"),_T("fixer"),_T("fixes"),_T("fixit"),_T("fizzy"),_T("fjeld"),
_T("fjord"),_T("flabs"),_T("flack"),_T("flags"),_T("flail"),_T("flair"),_T("flake"),_T("flaky"),_T("flame"),_T("flams"),
_T("flamy"),_T("flank"),_T("flans"),_T("flaps"),_T("flare"),_T("flash"),_T("flask"),_T("flats"),_T("flaws"),_T("flawy"),
_T("flaxy"),_T("flays"),_T("fleam"),_T("fleas"),_T("fleck"),_T("fleer"),_T("flees"),_T("fleet"),_T("flesh"),_T("flews"),
_T("fleys"),_T("flick"),_T("flics"),_T("flied"),_T("flier"),_T("flies"),_T("fling"),_T("flint"),_T("flips"),_T("flirt"),
_T("flite"),_T("flits"),_T("float"),_T("flock"),_T("flocs"),_T("floes"),_T("flogs"),_T("flong"),_T("flood"),_T("floor"),
_T("flops"),_T("flora"),_T("floss"),_T("flota"),_T("flour"),_T("flout"),_T("flown"),_T("flows"),_T("flubs"),_T("flued"),
_T("flues"),_T("fluff"),_T("fluid"),_T("fluke"),_T("fluky"),_T("flume"),_T("flump"),_T("flung"),_T("flunk"),_T("fluor"),
_T("flush"),_T("flute"),_T("fluty"),_T("fluyt"),_T("flyby"),_T("flyer"),_T("flyte"),_T("foals"),_T("foams"),_T("foamy"),
_T("focal"),_T("focus"),_T("foehn"),_T("fogey"),_T("foggy"),_T("fogie"),_T("fohns"),_T("foils"),_T("foins"),_T("foist"),
_T("folds"),_T("folia"),_T("folio"),_T("folks"),_T("folky"),_T("folly"),_T("fonds"),_T("fondu"),_T("fonts"),_T("foods"),
_T("fools"),_T("foots"),_T("footy"),_T("foram"),_T("foray"),_T("forbs"),_T("forby"),_T("force"),_T("fordo"),_T("fords"),
_T("fores"),_T("forge"),_T("forgo"),_T("forks"),_T("forky"),_T("forme"),_T("forms"),_T("forte"),_T("forth"),_T("forts"),
_T("forty"),_T("forum"),_T("fossa"),_T("fosse"),_T("fouls"),_T("found"),_T("fount"),_T("fours"),_T("fovea"),_T("fowls"),
_T("foxed"),_T("foxes"),_T("foyer"),_T("frags"),_T("frail"),_T("frame"),_T("franc"),_T("frank"),_T("fraps"),_T("frass"),
_T("frats"),_T("fraud"),_T("frays"),_T("freak"),_T("freed"),_T("freer"),_T("frees"),_T("fremd"),_T("frena"),_T("frere"),
_T("fresh"),_T("frets"),_T("friar"),_T("fried"),_T("frier"),_T("fries"),_T("frigs"),_T("frill"),_T("frise"),_T("frisk"),
_T("frith"),_T("frits"),_T("fritt"),_T("fritz"),_T("frizz"),_T("frock"),_T("froes"),_T("frogs"),_T("frond"),_T("frons"),
_T("front"),_T("frore"),_T("frosh"),_T("frost"),_T("froth"),_T("frown"),_T("frows"),_T("froze"),_T("frugs"),_T("fruit"),
_T("frump"),_T("fryer"),_T("fubsy"),_T("fucks"),_T("fucus"),_T("fudge"),_T("fuels"),_T("fugal"),_T("fuggy"),_T("fugio"),
_T("fugle"),_T("fugue"),_T("fugus"),_T("fujis"),_T("fulls"),_T("fully"),_T("fumed"),_T("fumer"),_T("fumes"),_T("fumet"),
_T("fundi"),_T("funds"),_T("fungi"),_T("fungo"),_T("funks"),_T("funky"),_T("funny"),_T("furan"),_T("furls"),_T("furor"),
_T("furry"),_T("furze"),_T("furzy"),_T("fused"),_T("fusee"),_T("fusel"),_T("fuses"),_T("fusil"),_T("fussy"),_T("fusty"),
_T("futon"),_T("fuzed"),_T("fuzee"),_T("fuzes"),_T("fuzil"),_T("fuzzy"),_T("fyces"),_T("fykes"),_T("fytte"),_T("gabby"),
_T("gable"),_T("gaddi"),_T("gadid"),_T("gadis"),_T("gaffe"),_T("gaffs"),_T("gaged"),_T("gager"),_T("gages"),_T("gaily"),
_T("gains"),_T("gaits"),_T("galah"),_T("galas"),_T("galax"),_T("galea"),_T("gales"),_T("galls"),_T("gally"),_T("galop"),
_T("gamas"),_T("gamay"),_T("gamba"),_T("gambe"),_T("gambs"),_T("gamed"),_T("gamer"),_T("games"),_T("gamey"),_T("gamic"),
_T("gamin"),_T("gamma"),_T("gammy"),_T("gamps"),_T("gamut"),_T("ganef"),_T("ganev"),_T("gangs"),_T("ganja"),_T("ganof"),
_T("gaols"),_T("gaped"),_T("gaper"),_T("gapes"),_T("gappy"),_T("garbs"),_T("garni"),_T("garth"),_T("gases"),_T("gasps"),
_T("gassy"),_T("gasts"),_T("gated"),_T("gates"),_T("gator"),_T("gauds"),_T("gaudy"),_T("gauge"),_T("gault"),_T("gaums"),
_T("gaunt"),_T("gaurs"),_T("gauss"),_T("gauze"),_T("gauzy"),_T("gavel"),_T("gavot"),_T("gawks"),_T("gawky"),_T("gawps"),
_T("gawsy"),_T("gayal"),_T("gayer"),_T("gayly"),_T("gazar"),_T("gazed"),_T("gazer"),_T("gazes"),_T("gears"),_T("gecko"),
_T("gecks"),_T("geeks"),_T("geeky"),_T("geese"),_T("geest"),_T("gelds"),_T("gelee"),_T("gelid"),_T("gelts"),_T("gemma"),
_T("gemmy"),_T("gemot"),_T("genes"),_T("genet"),_T("genic"),_T("genie"),_T("genii"),_T("genip"),_T("genoa"),_T("genom"),
_T("genre"),_T("genro"),_T("gents"),_T("genua"),_T("genus"),_T("geode"),_T("geoid"),_T("gerah"),_T("germs"),_T("germy"),
_T("gesso"),_T("geste"),_T("gests"),_T("getas"),_T("getup"),_T("geums"),_T("ghast"),_T("ghats"),_T("ghaut"),_T("ghazi"),
_T("ghees"),_T("ghost"),_T("ghoul"),_T("ghyll"),_T("giant"),_T("gibed"),_T("giber"),_T("gibes"),_T("giddy"),_T("gifts"),
_T("gigas"),_T("gighe"),_T("gigot"),_T("gigue"),_T("gilds"),_T("gills"),_T("gilly"),_T("gilts"),_T("gimel"),_T("gimme"),
_T("gimps"),_T("gimpy"),_T("ginks"),_T("ginny"),_T("gipon"),_T("gipsy"),_T("girds"),_T("girls"),_T("girly"),_T("girns"),
_T("giron"),_T("giros"),_T("girsh"),_T("girth"),_T("girts"),_T("gismo"),_T("gists"),_T("given"),_T("giver"),_T("gives"),
_T("gizmo"),_T("glace"),_T("glade"),_T("glads"),_T("glady"),_T("glair"),_T("gland"),_T("glans"),_T("glare"),_T("glary"),
_T("glass"),_T("glaze"),_T("glazy"),_T("gleam"),_T("glean"),_T("gleba"),_T("glebe"),_T("glede"),_T("gleds"),_T("gleed"),
_T("gleek"),_T("glees"),_T("gleet"),_T("glens"),_T("gleys"),_T("glial"),_T("glias"),_T("glide"),_T("gliff"),_T("glime"),
_T("glims"),_T("glint"),_T("glitz"),_T("gloam"),_T("gloat"),_T("globe"),_T("globs"),_T("glogg"),_T("gloms"),_T("gloom"),
_T("glops"),_T("glory"),_T("gloss"),_T("glost"),_T("glout"),_T("glove"),_T("glows"),_T("gloze"),_T("glued"),_T("gluer"),
_T("glues"),_T("gluey"),_T("glugs"),_T("glume"),_T("gluon"),_T("gluts"),_T("glyph"),_T("gnarl"),_T("gnarr"),_T("gnars"),
_T("gnash"),_T("gnats"),_T("gnawn"),_T("gnaws"),_T("gnome"),_T("goads"),_T("goals"),_T("goats"),_T("goban"),_T("gobos"),
_T("godet"),_T("godly"),_T("goers"),_T("gofer"),_T("gogos"),_T("going"),_T("golds"),_T("golem"),_T("golfs"),_T("golly"),
_T("gombo"),_T("gonad"),_T("gonef"),_T("goner"),_T("gongs"),_T("gonia"),_T("gonif"),_T("gonof"),_T("gonzo"),_T("goods"),
_T("goody"),_T("gooey"),_T("goofs"),_T("goofy"),_T("gooks"),_T("gooky"),_T("goons"),_T("goony"),_T("goops"),_T("goopy"),
_T("goose"),_T("goosy"),_T("goral"),_T("gored"),_T("gores"),_T("gorge"),_T("gorps"),_T("gorse"),_T("gorsy"),_T("gouge"),
_T("gourd"),_T("gouts"),_T("gouty"),_T("gowan"),_T("gowds"),_T("gowks"),_T("gowns"),_T("goxes"),_T("goyim"),_T("graal"),
_T("grabs"),_T("grace"),_T("grade"),_T("grads"),_T("graft"),_T("grail"),_T("grain"),_T("grama"),_T("gramp"),_T("grams"),
_T("grana"),_T("grand"),_T("grans"),_T("grant"),_T("grape"),_T("graph"),_T("grapy"),_T("grasp"),_T("grass"),_T("grate"),
_T("grave"),_T("gravy"),_T("grays"),_T("graze"),_T("great"),_T("grebe"),_T("greed"),_T("greek"),_T("green"),_T("grees"),
_T("greet"),_T("grego"),_T("greys"),_T("gride"),_T("grids"),_T("grief"),_T("griff"),_T("grift"),_T("grigs"),_T("grill"),
_T("grime"),_T("grimy"),_T("grind"),_T("grins"),_T("griot"),_T("gripe"),_T("grips"),_T("gript"),_T("gripy"),_T("grist"),
_T("grith"),_T("grits"),_T("groan"),_T("groat"),_T("grogs"),_T("groin"),_T("groom"),_T("grope"),_T("gross"),_T("grosz"),
_T("grots"),_T("group"),_T("grout"),_T("grove"),_T("growl"),_T("grown"),_T("grows"),_T("grubs"),_T("gruel"),_T("grues"),
_T("gruff"),_T("grume"),_T("grump"),_T("grunt"),_T("guaco"),_T("guano"),_T("guans"),_T("guard"),_T("guars"),_T("guava"),
_T("gucks"),_T("gudes"),_T("guess"),_T("guest"),_T("guffs"),_T("guide"),_T("guids"),_T("guild"),_T("guile"),_T("guilt"),
_T("guiro"),_T("guise"),_T("gulag"),_T("gular"),_T("gulch"),_T("gules"),_T("gulfs"),_T("gulfy"),_T("gulls"),_T("gully"),
_T("gulps"),_T("gulpy"),_T("gumbo"),_T("gumma"),_T("gummy"),_T("gunks"),_T("gunky"),_T("gunny"),_T("guppy"),_T("gurge"),
_T("gurry"),_T("gursh"),_T("gurus"),_T("gushy"),_T("gussy"),_T("gusto"),_T("gusts"),_T("gusty"),_T("gutsy"),_T("gutta"),
_T("gutty"),_T("guyed"),_T("guyot"),_T("gybed"),_T("gybes"),_T("gypsy"),_T("gyral"),_T("gyred"),_T("gyres"),_T("gyron"),
_T("gyros"),_T("gyrus"),_T("gyved"),_T("gyves"),_T("haafs"),_T("haars"),_T("habit"),_T("habus"),_T("hacek"),_T("hacks"),
_T("hadal"),_T("haded"),_T("hades"),_T("hadji"),_T("hadst"),_T("haems"),_T("haets"),_T("hafis"),_T("hafiz"),_T("hafts"),
_T("hahas"),_T("haika"),_T("haiks"),_T("haiku"),_T("hails"),_T("hairs"),_T("hairy"),_T("hajes"),_T("hajis"),_T("hajji"),
_T("hakes"),_T("hakim"),_T("haled"),_T("haler"),_T("hales"),_T("halid"),_T("hallo"),_T("halls"),_T("halma"),_T("halms"),
_T("halos"),_T("halts"),_T("halva"),_T("halve"),_T("hamal"),_T("hames"),_T("hammy"),_T("hamza"),_T("hance"),_T("hands"),
_T("handy"),_T("hangs"),_T("hanks"),_T("hanky"),_T("hansa"),_T("hanse"),_T("hants"),_T("haole"),_T("hapax"),_T("haply"),
_T("happy"),_T("hards"),_T("hardy"),_T("hared"),_T("harem"),_T("hares"),_T("harks"),_T("harls"),_T("harms"),_T("harps"),
_T("harpy"),_T("harry"),_T("harsh"),_T("harts"),_T("hasps"),_T("haste"),_T("hasty"),_T("hatch"),_T("hated"),_T("hater"),
_T("hates"),_T("haugh"),_T("haulm"),_T("hauls"),_T("haunt"),_T("haute"),_T("haven"),_T("haver"),_T("haves"),_T("havoc"),
_T("hawed"),_T("hawks"),_T("hawse"),_T("hayed"),_T("hayer"),_T("hazan"),_T("hazed"),_T("hazel"),_T("hazer"),_T("hazes"),
_T("heads"),_T("heady"),_T("heals"),_T("heaps"),_T("heard"),_T("hears"),_T("heart"),_T("heath"),_T("heats"),_T("heave"),
_T("heavy"),_T("hebes"),_T("hecks"),_T("heder"),_T("hedge"),_T("hedgy"),_T("heeds"),_T("heels"),_T("heeze"),_T("hefts"),
_T("hefty"),_T("heigh"),_T("heils"),_T("heirs"),_T("heist"),_T("helio"),_T("helix"),_T("hello"),_T("hells"),_T("helms"),
_T("helos"),_T("helot"),_T("helps"),_T("helve"),_T("hemal"),_T("hemes"),_T("hemic"),_T("hemin"),_T("hemps"),_T("hempy"),
_T("hence"),_T("henna"),_T("henry"),_T("hents"),_T("herbs"),_T("herby"),_T("herds"),_T("heres"),_T("herls"),_T("herma"),
_T("herms"),_T("herns"),_T("heron"),_T("heros"),_T("herry"),_T("hertz"),_T("hests"),_T("heths"),_T("heuch"),_T("heugh"),
_T("hewed"),_T("hewer"),_T("hexad"),_T("hexed"),_T("hexer"),_T("hexes"),_T("hexyl"),_T("hicks"),_T("hided"),_T("hider"),
_T("hides"),_T("highs"),_T("hight"),_T("hiked"),_T("hiker"),_T("hikes"),_T("hilar"),_T("hillo"),_T("hills"),_T("hilly"),
_T("hilts"),_T("hilum"),_T("hilus"),_T("hinds"),_T("hinge"),_T("hinny"),_T("hints"),_T("hippo"),_T("hippy"),_T("hired"),
_T("hirer"),_T("hires"),_T("hissy"),_T("hists"),_T("hitch"),_T("hived"),_T("hives"),_T("hoagy"),_T("hoard"),_T("hoars"),
_T("hoary"),_T("hobby"),_T("hobos"),_T("hocks"),_T("hocus"),_T("hodad"),_T("hoers"),_T("hogan"),_T("hoggs"),_T("hoick"),
_T("hoise"),_T("hoist"),_T("hoked"),_T("hokes"),_T("hokey"),_T("hokku"),_T("hokum"),_T("holds"),_T("holed"),_T("holes"),
_T("holey"),_T("holks"),_T("holla"),_T("hollo"),_T("holly"),_T("holms"),_T("holts"),_T("homed"),_T("homer"),_T("homes"),
_T("homey"),_T("homos"),_T("honan"),_T("honda"),_T("honed"),_T("honer"),_T("hones"),_T("honey"),_T("hongs"),_T("honks"),
_T("honky"),_T("honor"),_T("hooch"),_T("hoods"),_T("hoody"),_T("hooey"),_T("hoofs"),_T("hooka"),_T("hooks"),_T("hooky"),
_T("hooly"),_T("hoops"),_T("hoots"),_T("hooty"),_T("hoped"),_T("hoper"),_T("hopes"),_T("hoppy"),_T("horah"),_T("horal"),
_T("horas"),_T("horde"),_T("horns"),_T("horny"),_T("horse"),_T("horst"),_T("horsy"),_T("hosed"),_T("hosel"),_T("hosen"),
_T("hoses"),_T("hosta"),_T("hosts"),_T("hotch"),_T("hotel"),_T("hotly"),_T("hound"),_T("houri"),_T("hours"),_T("house"),
_T("hovel"),_T("hover"),_T("howdy"),_T("howes"),_T("howff"),_T("howfs"),_T("howks"),_T("howls"),_T("hoyas"),_T("hoyle"),
_T("hubby"),_T("hucks"),_T("huffs"),_T("huffy"),_T("huger"),_T("hulas"),_T("hulks"),_T("hulky"),_T("hullo"),_T("hulls"),
_T("human"),_T("humic"),_T("humid"),_T("humor"),_T("humph"),_T("humps"),_T("humpy"),_T("humus"),_T("hunch"),_T("hunks"),
_T("hunky"),_T("hunts"),_T("hurds"),_T("hurls"),_T("hurly"),_T("hurry"),_T("hurst"),_T("hurts"),_T("husks"),_T("husky"),
_T("hussy"),_T("hutch"),_T("huzza"),_T("hydra"),_T("hydro"),_T("hyena"),_T("hying"),_T("hylas"),_T("hymen"),_T("hymns"),
_T("hyoid"),_T("hyped"),_T("hyper"),_T("hypes"),_T("hypha"),_T("hypos"),_T("hyrax"),_T("hyson"),_T("iambi"),_T("iambs"),
_T("ichor"),_T("icier"),_T("icily"),_T("icing"),_T("icker"),_T("icons"),_T("ictic"),_T("ictus"),_T("ideal"),_T("ideas"),
_T("idiom"),_T("idiot"),_T("idled"),_T("idler"),_T("idles"),_T("idols"),_T("idyll"),_T("idyls"),_T("igloo"),_T("iglus"),
_T("ihram"),_T("ikats"),_T("ikons"),_T("ileac"),_T("ileal"),_T("ileum"),_T("ileus"),_T("iliac"),_T("iliad"),_T("ilial"),
_T("ilium"),_T("image"),_T("imago"),_T("imams"),_T("imaum"),_T("imbed"),_T("imbue"),_T("imide"),_T("imido"),_T("imids"),
_T("imine"),_T("imino"),_T("immix"),_T("imped"),_T("impel"),_T("impis"),_T("imply"),_T("inane"),_T("inapt"),_T("inarm"),
_T("inbye"),_T("incog"),_T("incur"),_T("incus"),_T("index"),_T("indie"),_T("indol"),_T("indow"),_T("indri"),_T("indue"),
_T("inept"),_T("inert"),_T("infer"),_T("infix"),_T("infos"),_T("infra"),_T("ingle"),_T("ingot"),_T("inion"),_T("inked"),
_T("inker"),_T("inkle"),_T("inlay"),_T("inlet"),_T("inned"),_T("inner"),_T("input"),_T("inset"),_T("inter"),_T("intis"),
_T("intro"),_T("inure"),_T("inurn"),_T("invar"),_T("iodic"),_T("iodid"),_T("iodin"),_T("ionic"),_T("iotas"),_T("irade"),
_T("irate"),_T("irids"),_T("iring"),_T("irked"),_T("iroko"),_T("irone"),_T("irons"),_T("irony"),_T("isbas"),_T("isled"),
_T("isles"),_T("islet"),_T("issei"),_T("issue"),_T("istle"),_T("itchy"),_T("items"),_T("ither"),_T("ivied"),_T("ivies"),
_T("ivory"),_T("ixias"),_T("ixora"),_T("ixtle"),_T("izars"),_T("jabot"),_T("jacal"),_T("jacks"),_T("jacky"),_T("jaded"),
_T("jades"),_T("jager"),_T("jaggs"),_T("jaggy"),_T("jagra"),_T("jails"),_T("jakes"),_T("jalap"),_T("jalop"),_T("jambe"),
_T("jambs"),_T("jammy"),_T("janes"),_T("janty"),_T("japan"),_T("japed"),_T("japer"),_T("japes"),_T("jarls"),_T("jatos"),
_T("jauks"),_T("jaunt"),_T("jaups"),_T("javas"),_T("jawan"),_T("jawed"),_T("jazzy"),_T("jeans"),_T("jebel"),_T("jeeps"),
_T("jeers"),_T("jefes"),_T("jehad"),_T("jehus"),_T("jells"),_T("jelly"),_T("jemmy"),_T("jenny"),_T("jerid"),_T("jerks"),
_T("jerky"),_T("jerry"),_T("jesse"),_T("jests"),_T("jetes"),_T("jeton"),_T("jetty"),_T("jewed"),_T("jewel"),_T("jibbs"),
_T("jibed"),_T("jiber"),_T("jibes"),_T("jiffs"),_T("jiffy"),_T("jihad"),_T("jills"),_T("jilts"),_T("jimmy"),_T("jimpy"),
_T("jingo"),_T("jinks"),_T("jinni"),_T("jinns"),_T("jisms"),_T("jived"),_T("jiver"),_T("jives"),_T("jivey"),_T("jnana"),
_T("jocko"),_T("jocks"),_T("joeys"),_T("johns"),_T("joins"),_T("joint"),_T("joist"),_T("joked"),_T("joker"),_T("jokes"),
_T("jokey"),_T("joles"),_T("jolly"),_T("jolts"),_T("jolty"),_T("jones"),_T("joram"),_T("jorum"),_T("jotas"),_T("jotty"),
_T("joual"),_T("jouks"),_T("joule"),_T("joust"),_T("jowar"),_T("jowed"),_T("jowls"),_T("jowly"),_T("joyed"),_T("jubas"),
_T("jubes"),_T("judas"),_T("judge"),_T("judos"),_T("jugal"),_T("jugum"),_T("juice"),_T("juicy"),_T("jujus"),_T("juked"),
_T("jukes"),_T("julep"),_T("jumbo"),_T("jumps"),_T("jumpy"),_T("junco"),_T("junks"),_T("junky"),_T("junta"),_T("junto"),
_T("jupes"),_T("jupon"),_T("jural"),_T("jurat"),_T("jurel"),_T("juror"),_T("justs"),_T("jutes"),_T("jutty"),_T("kabab"),
_T("kabar"),_T("kabob"),_T("kadis"),_T("kafir"),_T("kagus"),_T("kaiak"),_T("kaifs"),_T("kails"),_T("kains"),_T("kakas"),
_T("kakis"),_T("kalam"),_T("kales"),_T("kalif"),_T("kalpa"),_T("kames"),_T("kamik"),_T("kanas"),_T("kanes"),_T("kanji"),
_T("kaons"),_T("kapas"),_T("kaphs"),_T("kapok"),_T("kappa"),_T("kaput"),_T("karat"),_T("karma"),_T("karns"),_T("karoo"),
_T("karst"),_T("karts"),_T("kasha"),_T("katas"),_T("kauri"),_T("kaury"),_T("kavas"),_T("kayak"),_T("kayos"),_T("kazoo"),
_T("kbars"),_T("kebab"),_T("kebar"),_T("kebob"),_T("kecks"),_T("kedge"),_T("keefs"),_T("keeks"),_T("keels"),_T("keens"),
_T("keeps"),_T("keets"),_T("keeve"),_T("kefir"),_T("keirs"),_T("kelep"),_T("kelim"),_T("kelly"),_T("kelps"),_T("kelpy"),
_T("kemps"),_T("kempt"),_T("kenaf"),_T("kench"),_T("kendo"),_T("kenos"),_T("kepis"),_T("kerbs"),_T("kerfs"),_T("kerne"),
_T("kerns"),_T("kerry"),_T("ketch"),_T("ketol"),_T("kevel"),_T("kevil"),_T("kexes"),_T("keyed"),_T("khadi"),_T("khafs"),
_T("khaki"),_T("khans"),_T("khaph"),_T("khats"),_T("kheda"),_T("kheth"),_T("khets"),_T("khoum"),_T("kiang"),_T("kibbe"),
_T("kibbi"),_T("kibei"),_T("kibes"),_T("kibla"),_T("kicks"),_T("kicky"),_T("kiddo"),_T("kiddy"),_T("kiefs"),_T("kiers"),
_T("kikes"),_T("kilim"),_T("kills"),_T("kilns"),_T("kilos"),_T("kilts"),_T("kilty"),_T("kinas"),_T("kinds"),_T("kines"),
_T("kings"),_T("kinin"),_T("kinks"),_T("kinky"),_T("kinos"),_T("kiosk"),_T("kirks"),_T("kirns"),_T("kissy"),_T("kists"),
_T("kited"),_T("kiter"),_T("kites"),_T("kithe"),_T("kiths"),_T("kitty"),_T("kivas"),_T("kiwis"),_T("klong"),_T("kloof"),
_T("kluge"),_T("klutz"),_T("knack"),_T("knaps"),_T("knars"),_T("knaur"),_T("knave"),_T("knead"),_T("kneed"),_T("kneel"),
_T("knees"),_T("knell"),_T("knelt"),_T("knife"),_T("knish"),_T("knits"),_T("knobs"),_T("knock"),_T("knoll"),_T("knops"),
_T("knosp"),_T("knots"),_T("knout"),_T("known"),_T("knows"),_T("knurl"),_T("knurs"),_T("koala"),_T("koans"),_T("koels"),
_T("kohls"),_T("koine"),_T("kolas"),_T("kolos"),_T("konks"),_T("kooks"),_T("kooky"),_T("kopek"),_T("kophs"),_T("kopje"),
_T("koppa"),_T("korai"),_T("korat"),_T("korun"),_T("kotos"),_T("kotow"),_T("kraal"),_T("kraft"),_T("krait"),_T("kraut"),
_T("kreep"),_T("krill"),_T("krona"),_T("krone"),_T("kroon"),_T("krubi"),_T("kudos"),_T("kudus"),_T("kudzu"),_T("kugel"),
_T("kukri"),_T("kulak"),_T("kumys"),_T("kurta"),_T("kurus"),_T("kusso"),_T("kvass"),_T("kyack"),_T("kyaks"),_T("kyars"),
_T("kyats"),_T("kylix"),_T("kyrie"),_T("kytes"),_T("kythe"),_T("laari"),_T("label"),_T("labia"),_T("labor"),_T("labra"),
_T("laced"),_T("lacer"),_T("laces"),_T("lacey"),_T("lacks"),_T("laded"),_T("laden"),_T("lader"),_T("lades"),_T("ladle"),
_T("laevo"),_T("lagan"),_T("lager"),_T("lahar"),_T("laich"),_T("laics"),_T("laigh"),_T("laird"),_T("lairs"),_T("laith"),
_T("laity"),_T("laked"),_T("laker"),_T("lakes"),_T("lakhs"),_T("lalls"),_T("lamas"),_T("lambs"),_T("lamby"),_T("lamed"),
_T("lamer"),_T("lames"),_T("lamia"),_T("lamps"),_T("lanai"),_T("lance"),_T("lands"),_T("lanes"),_T("lanky"),_T("lapel"),
_T("lapin"),_T("lapis"),_T("lapse"),_T("larch"),_T("lards"),_T("lardy"),_T("laree"),_T("lares"),_T("large"),_T("largo"),
_T("laris"),_T("larks"),_T("larky"),_T("larum"),_T("larva"),_T("lased"),_T("laser"),_T("lases"),_T("lasso"),_T("lasts"),
_T("latch"),_T("lated"),_T("laten"),_T("later"),_T("latex"),_T("lathe"),_T("lathi"),_T("laths"),_T("lathy"),_T("latke"),
_T("lauan"),_T("lauds"),_T("laugh"),_T("laura"),_T("lavas"),_T("laved"),_T("laver"),_T("laves"),_T("lawed"),_T("lawns"),
_T("lawny"),_T("laxer"),_T("laxly"),_T("layed"),_T("layer"),_T("layup"),_T("lazar"),_T("lazed"),_T("lazes"),_T("leach"),
_T("leads"),_T("leady"),_T("leafs"),_T("leafy"),_T("leaks"),_T("leaky"),_T("leans"),_T("leant"),_T("leaps"),_T("leapt"),
_T("learn"),_T("lears"),_T("leary"),_T("lease"),_T("leash"),_T("least"),_T("leave"),_T("leavy"),_T("leben"),_T("ledge"),
_T("ledgy"),_T("leech"),_T("leeks"),_T("leers"),_T("leery"),_T("leets"),_T("lefts"),_T("lefty"),_T("legal"),_T("leger"),
_T("leges"),_T("leggy"),_T("legit"),_T("lehrs"),_T("lehua"),_T("leman"),_T("lemma"),_T("lemon"),_T("lemur"),_T("lends"),
_T("lenes"),_T("lenis"),_T("lenos"),_T("lense"),_T("lento"),_T("leone"),_T("leper"),_T("lepta"),_T("letch"),_T("lethe"),
_T("letup"),_T("leuds"),_T("levee"),_T("level"),_T("lever"),_T("levin"),_T("lewis"),_T("lexes"),_T("lexis"),_T("lezes"),
_T("lezzy"),_T("liana"),_T("liane"),_T("liang"),_T("liard"),_T("liars"),_T("libel"),_T("liber"),_T("libra"),_T("libri"),
_T("lichi"),_T("licht"),_T("licit"),_T("licks"),_T("lidar"),_T("lidos"),_T("liege"),_T("liens"),_T("liers"),_T("lieus"),
_T("lieve"),_T("lifer"),_T("lifts"),_T("ligan"),_T("liger"),_T("light"),_T("liked"),_T("liken"),_T("liker"),_T("likes"),
_T("lilac"),_T("lilts"),_T("liman"),_T("limas"),_T("limba"),_T("limbi"),_T("limbo"),_T("limbs"),_T("limby"),_T("limed"),
_T("limen"),_T("limes"),_T("limey"),_T("limit"),_T("limns"),_T("limos"),_T("limpa"),_T("limps"),_T("linac"),_T("lindy"),
_T("lined"),_T("linen"),_T("liner"),_T("lines"),_T("liney"),_T("linga"),_T("lingo"),_T("lings"),_T("lingy"),_T("linin"),
_T("links"),_T("linky"),_T("linns"),_T("linos"),_T("lints"),_T("linty"),_T("linum"),_T("lions"),_T("lipid"),_T("lipin"),
_T("lippy"),_T("liras"),_T("lirot"),_T("lisle"),_T("lisps"),_T("lists"),_T("litai"),_T("litas"),_T("liter"),_T("lithe"),
_T("litho"),_T("litre"),_T("lived"),_T("liven"),_T("liver"),_T("lives"),_T("livid"),_T("livre"),_T("llama"),_T("llano"),
_T("loach"),_T("loads"),_T("loafs"),_T("loams"),_T("loamy"),_T("loans"),_T("loath"),_T("lobar"),_T("lobby"),_T("lobed"),
_T("lobes"),_T("lobos"),_T("local"),_T("lochs"),_T("locks"),_T("locos"),_T("locum"),_T("locus"),_T("loden"),_T("lodes"),
_T("lodge"),_T("loess"),_T("lofts"),_T("lofty"),_T("logan"),_T("loges"),_T("loggy"),_T("logia"),_T("logic"),_T("logoi"),
_T("logos"),_T("loins"),_T("lolls"),_T("lolly"),_T("loner"),_T("longe"),_T("longs"),_T("looby"),_T("looed"),_T("looey"),
_T("loofa"),_T("loofs"),_T("looie"),_T("looks"),_T("looms"),_T("loons"),_T("loony"),_T("loops"),_T("loopy"),_T("loose"),
_T("loots"),_T("loped"),_T("loper"),_T("lopes"),_T("loppy"),_T("loral"),_T("loran"),_T("lords"),_T("lores"),_T("loris"),
_T("lorry"),_T("losel"),_T("loser"),_T("loses"),_T("lossy"),_T("lotah"),_T("lotas"),_T("lotic"),_T("lotos"),_T("lotte"),
_T("lotto"),_T("lotus"),_T("lough"),_T("louie"),_T("louis"),_T("loupe"),_T("loups"),_T("lours"),_T("loury"),_T("louse"),
_T("lousy"),_T("louts"),_T("lovat"),_T("loved"),_T("lover"),_T("loves"),_T("lowed"),_T("lower"),_T("lowes"),_T("lowly"),
_T("lowse"),_T("loxed"),_T("loxes"),_T("loyal"),_T("luaus"),_T("lubes"),_T("luces"),_T("lucid"),_T("lucks"),_T("lucky"),
_T("lucre"),_T("ludes"),_T("ludic"),_T("luffa"),_T("luffs"),_T("luged"),_T("luger"),_T("luges"),_T("lulls"),_T("lulus"),
_T("lumen"),_T("lumps"),_T("lumpy"),_T("lunar"),_T("lunas"),_T("lunch"),_T("lunes"),_T("lunet"),_T("lunge"),_T("lungi"),
_T("lungs"),_T("lunks"),_T("lunts"),_T("lupin"),_T("lupus"),_T("lurch"),_T("lured"),_T("lurer"),_T("lures"),_T("lurid"),
_T("lurks"),_T("lusts"),_T("lusty"),_T("lusus"),_T("lutea"),_T("luted"),_T("lutes"),_T("luxes"),_T("lweis"),_T("lyard"),
_T("lyart"),_T("lyase"),_T("lycea"),_T("lycee"),_T("lying"),_T("lymph"),_T("lynch"),_T("lyres"),_T("lyric"),_T("lysed"),
_T("lyses"),_T("lysin"),_T("lysis"),_T("lyssa"),_T("lytic"),_T("lytta"),_T("maars"),_T("mabes"),_T("macaw"),_T("maced"),
_T("macer"),_T("maces"),_T("mache"),_T("macho"),_T("machs"),_T("macks"),_T("macle"),_T("macon"),_T("macro"),_T("madam"),
_T("madly"),_T("madre"),_T("mafia"),_T("mafic"),_T("mages"),_T("magic"),_T("magma"),_T("magot"),_T("magus"),_T("mahoe"),
_T("maids"),_T("maile"),_T("maill"),_T("mails"),_T("maims"),_T("mains"),_T("mairs"),_T("maist"),_T("maize"),_T("major"),
_T("makar"),_T("maker"),_T("makes"),_T("makos"),_T("malar"),_T("males"),_T("malic"),_T("malls"),_T("malms"),_T("malmy"),
_T("malts"),_T("malty"),_T("mamas"),_T("mamba"),_T("mambo"),_T("mamey"),_T("mamie"),_T("mamma"),_T("mammy"),_T("manas"),
_T("maned"),_T("manes"),_T("mange"),_T("mango"),_T("mangy"),_T("mania"),_T("manic"),_T("manly"),_T("manna"),_T("manor"),
_T("manos"),_T("manse"),_T("manta"),_T("manus"),_T("maple"),_T("maqui"),_T("march"),_T("marcs"),_T("mares"),_T("marge"),
_T("maria"),_T("marks"),_T("marls"),_T("marly"),_T("marry"),_T("marse"),_T("marsh"),_T("marts"),_T("marvy"),_T("maser"),
_T("mashy"),_T("masks"),_T("mason"),_T("massa"),_T("masse"),_T("massy"),_T("masts"),_T("match"),_T("mated"),_T("mater"),
_T("mates"),_T("matey"),_T("maths"),_T("matin"),_T("matte"),_T("matts"),_T("matza"),_T("matzo"),_T("mauds"),_T("mauls"),
_T("maund"),_T("mauts"),_T("mauve"),_T("maven"),_T("mavie"),_T("mavin"),_T("mavis"),_T("mawed"),_T("maxes"),_T("maxim"),
_T("maxis"),_T("mayan"),_T("mayas"),_T("maybe"),_T("mayed"),_T("mayor"),_T("mayos"),_T("mayst"),_T("mazed"),_T("mazer"),
_T("mazes"),_T("mbira"),_T("meads"),_T("meals"),_T("mealy"),_T("means"),_T("meant"),_T("meany"),_T("meats"),_T("meaty"),
_T("mecca"),_T("medal"),_T("media"),_T("medic"),_T("medii"),_T("meeds"),_T("meets"),_T("meiny"),_T("melds"),_T("melee"),
_T("melic"),_T("mells"),_T("melon"),_T("melts"),_T("memos"),_T("menad"),_T("mends"),_T("mensa"),_T("mense"),_T("menta"),
_T("menus"),_T("meous"),_T("meows"),_T("mercy"),_T("merde"),_T("merer"),_T("meres"),_T("merge"),_T("merit"),_T("merks"),
_T("merle"),_T("merls"),_T("merry"),_T("mesas"),_T("meshy"),_T("mesic"),_T("mesne"),_T("meson"),_T("messy"),_T("metal"),
_T("meted"),_T("meter"),_T("metes"),_T("meths"),_T("metis"),_T("metre"),_T("metro"),_T("mewed"),_T("mewls"),_T("mezes"),
_T("mezzo"),_T("miaou"),_T("miaow"),_T("miasm"),_T("miaul"),_T("micas"),_T("miche"),_T("micks"),_T("micra"),_T("micro"),
_T("middy"),_T("midge"),_T("midis"),_T("midst"),_T("miens"),_T("miffs"),_T("miffy"),_T("miggs"),_T("might"),_T("miked"),
_T("mikes"),_T("mikra"),_T("milch"),_T("miler"),_T("miles"),_T("milia"),_T("milks"),_T("milky"),_T("mille"),_T("mills"),
_T("milos"),_T("milpa"),_T("milts"),_T("milty"),_T("mimed"),_T("mimeo"),_T("mimer"),_T("mimes"),_T("mimic"),_T("minae"),
_T("minas"),_T("mince"),_T("mincy"),_T("minds"),_T("mined"),_T("miner"),_T("mines"),_T("mingy"),_T("minim"),_T("minis"),
_T("minke"),_T("minks"),_T("minny"),_T("minor"),_T("mints"),_T("minty"),_T("minus"),_T("mired"),_T("mires"),_T("mirex"),
_T("mirks"),_T("mirky"),_T("mirth"),_T("mirza"),_T("misdo"),_T("miser"),_T("mises"),_T("misos"),_T("missy"),_T("mists"),
_T("misty"),_T("miter"),_T("mites"),_T("mitis"),_T("mitre"),_T("mitts"),_T("mixed"),_T("mixer"),_T("mixes"),_T("mixup"),
_T("mizen"),_T("moans"),_T("moats"),_T("mocha"),_T("mocks"),_T("modal"),_T("model"),_T("modem"),_T("modes"),_T("modus"),
_T("moggy"),_T("mogul"),_T("mohel"),_T("mohur"),_T("moils"),_T("moira"),_T("moire"),_T("moist"),_T("mojos"),_T("mokes"),
_T("molal"),_T("molar"),_T("molas"),_T("molds"),_T("moldy"),_T("moles"),_T("molls"),_T("molly"),_T("molto"),_T("molts"),
_T("momes"),_T("momma"),_T("mommy"),_T("momus"),_T("monad"),_T("monas"),_T("monde"),_T("mondo"),_T("money"),_T("mongo"),
_T("monie"),_T("monks"),_T("monos"),_T("monte"),_T("month"),_T("mooch"),_T("moods"),_T("moody"),_T("mooed"),_T("moola"),
_T("mools"),_T("moons"),_T("moony"),_T("moors"),_T("moory"),_T("moose"),_T("moots"),_T("moped"),_T("moper"),_T("mopes"),
_T("mopey"),_T("morae"),_T("moral"),_T("moras"),_T("moray"),_T("morel"),_T("mores"),_T("morns"),_T("moron"),_T("morph"),
_T("morro"),_T("morse"),_T("morts"),_T("mosey"),_T("mosks"),_T("mosso"),_T("mossy"),_T("moste"),_T("mosts"),_T("motel"),
_T("motes"),_T("motet"),_T("motey"),_T("moths"),_T("mothy"),_T("motif"),_T("motor"),_T("motte"),_T("motto"),_T("motts"),
_T("mouch"),_T("moues"),_T("mould"),_T("moult"),_T("mound"),_T("mount"),_T("mourn"),_T("mouse"),_T("mousy"),_T("mouth"),
_T("moved"),_T("mover"),_T("moves"),_T("movie"),_T("mowed"),_T("mower"),_T("moxas"),_T("moxie"),_T("mozos"),_T("mucid"),
_T("mucin"),_T("mucks"),_T("mucky"),_T("mucor"),_T("mucro"),_T("mucus"),_T("muddy"),_T("mudra"),_T("muffs"),_T("mufti"),
_T("muggs"),_T("muggy"),_T("muhly"),_T("mujik"),_T("mulch"),_T("mulct"),_T("muled"),_T("mules"),_T("muley"),_T("mulla"),
_T("mulls"),_T("mumms"),_T("mummy"),_T("mumps"),_T("mumus"),_T("munch"),_T("mungo"),_T("munis"),_T("muons"),_T("mural"),
_T("muras"),_T("mured"),_T("mures"),_T("murex"),_T("murid"),_T("murks"),_T("murky"),_T("murra"),_T("murre"),_T("murrs"),
_T("murry"),_T("musca"),_T("mused"),_T("muser"),_T("muses"),_T("mushy"),_T("music"),_T("musks"),_T("musky"),_T("mussy"),
_T("musth"),_T("musts"),_T("musty"),_T("mutch"),_T("muted"),_T("muter"),_T("mutes"),_T("muton"),_T("mutts"),_T("muzzy"),
_T("mynah"),_T("mynas"),_T("myoid"),_T("myoma"),_T("myope"),_T("myopy"),_T("myrrh"),_T("mysid"),_T("myths"),_T("mythy"),
_T("naans"),_T("nabes"),_T("nabis"),_T("nabob"),_T("nacho"),_T("nacre"),_T("nadas"),_T("nadir"),_T("naevi"),_T("naggy"),
_T("naiad"),_T("naifs"),_T("nails"),_T("naira"),_T("naive"),_T("naked"),_T("naled"),_T("named"),_T("namer"),_T("names"),
_T("nanas"),_T("nance"),_T("nancy"),_T("nanny"),_T("napes"),_T("nappe"),_T("nappy"),_T("narco"),_T("narcs"),_T("nards"),
_T("nares"),_T("naric"),_T("naris"),_T("narks"),_T("narky"),_T("nasal"),_T("nasty"),_T("natal"),_T("natch"),_T("nates"),
_T("natty"),_T("naval"),_T("navar"),_T("navel"),_T("naves"),_T("navvy"),_T("nawab"),_T("nazis"),_T("neaps"),_T("nears"),
_T("neath"),_T("neats"),_T("necks"),_T("needs"),_T("needy"),_T("neems"),_T("neeps"),_T("negus"),_T("neifs"),_T("neigh"),
_T("neist"),_T("nelly"),_T("nemas"),_T("neons"),_T("nerds"),_T("nerdy"),_T("nerol"),_T("nerts"),_T("nertz"),_T("nerve"),
_T("nervy"),_T("nests"),_T("netop"),_T("netts"),_T("netty"),_T("neuks"),_T("neume"),_T("neums"),_T("never"),_T("neves"),
_T("nevus"),_T("newel"),_T("newer"),_T("newie"),_T("newly"),_T("newsy"),_T("newts"),_T("nexus"),_T("ngwee"),_T("nicad"),
_T("nicer"),_T("niche"),_T("nicks"),_T("nicol"),_T("nidal"),_T("nided"),_T("nides"),_T("nidus"),_T("niece"),_T("nieve"),
_T("nifty"),_T("nighs"),_T("night"),_T("nihil"),_T("nills"),_T("nimbi"),_T("nines"),_T("ninja"),_T("ninny"),_T("ninon"),
_T("ninth"),_T("nipas"),_T("nippy"),_T("nisei"),_T("nisus"),_T("niter"),_T("nites"),_T("nitid"),_T("niton"),_T("nitre"),
_T("nitro"),_T("nitty"),_T("nival"),_T("nixed"),_T("nixes"),_T("nixie"),_T("nizam"),_T("nobby"),_T("noble"),_T("nobly"),
_T("nocks"),_T("nodal"),_T("noddy"),_T("nodes"),_T("nodus"),_T("noels"),_T("noggs"),_T("nohow"),_T("noils"),_T("noily"),
_T("noirs"),_T("noise"),_T("noisy"),_T("nolos"),_T("nomad"),_T("nomas"),_T("nomen"),_T("nomes"),_T("nomoi"),_T("nomos"),
_T("nonas"),_T("nonce"),_T("nones"),_T("nonet"),_T("nonyl"),_T("nooks"),_T("nooky"),_T("noons"),_T("noose"),_T("nopal"),
_T("noria"),_T("noris"),_T("norms"),_T("north"),_T("nosed"),_T("noses"),_T("nosey"),_T("notal"),_T("notch"),_T("noted"),
_T("noter"),_T("notes"),_T("notum"),_T("nouns"),_T("novae"),_T("novas"),_T("novel"),_T("noway"),_T("nowts"),_T("nubby"),
_T("nubia"),_T("nucha"),_T("nuder"),_T("nudes"),_T("nudge"),_T("nudie"),_T("nudzh"),_T("nuked"),_T("nukes"),_T("nulls"),
_T("numbs"),_T("numen"),_T("nurds"),_T("nurls"),_T("nurse"),_T("nutsy"),_T("nutty"),_T("nyala"),_T("nylon"),_T("nymph"),
_T("oaken"),_T("oakum"),_T("oared"),_T("oases"),_T("oasis"),_T("oasts"),_T("oaten"),_T("oater"),_T("oaths"),_T("oaves"),
_T("obeah"),_T("obeli"),_T("obese"),_T("obeys"),_T("obias"),_T("obits"),_T("objet"),_T("oboes"),_T("obole"),_T("oboli"),
_T("obols"),_T("occur"),_T("ocean"),_T("ocher"),_T("ochre"),_T("ochry"),_T("ocker"),_T("ocrea"),_T("octad"),_T("octal"),
_T("octan"),_T("octet"),_T("octyl"),_T("oculi"),_T("odder"),_T("oddly"),_T("odeon"),_T("odeum"),_T("odist"),_T("odium"),
_T("odors"),_T("odour"),_T("odyle"),_T("odyls"),_T("ofays"),_T("offal"),_T("offed"),_T("offer"),_T("often"),_T("ofter"),
_T("ogams"),_T("ogees"),_T("ogham"),_T("ogive"),_T("ogled"),_T("ogler"),_T("ogles"),_T("ogres"),_T("ohias"),_T("ohing"),
_T("ohmic"),_T("oidia"),_T("oiled"),_T("oiler"),_T("oinks"),_T("okapi"),_T("okays"),_T("okehs"),_T("okras"),_T("olden"),
_T("older"),_T("oldie"),_T("oleic"),_T("olein"),_T("oleos"),_T("oleum"),_T("olios"),_T("olive"),_T("ollas"),_T("ology"),
_T("omasa"),_T("omber"),_T("ombre"),_T("omega"),_T("omens"),_T("omers"),_T("omits"),_T("onery"),_T("onion"),_T("onium"),
_T("onset"),_T("ontic"),_T("oohed"),_T("oomph"),_T("oorie"),_T("ootid"),_T("oozed"),_T("oozes"),_T("opahs"),_T("opals"),
_T("opens"),_T("opera"),_T("opine"),_T("oping"),_T("opium"),_T("opsin"),_T("opted"),_T("optic"),_T("orach"),_T("orals"),
_T("orang"),_T("orate"),_T("orbed"),_T("orbit"),_T("orcas"),_T("orcin"),_T("order"),_T("ordos"),_T("oread"),_T("organ"),
_T("orgic"),_T("oribi"),_T("oriel"),_T("orles"),_T("orlop"),_T("ormer"),_T("ornis"),_T("orpin"),_T("orris"),_T("ortho"),
_T("orzos"),_T("osier"),_T("osmic"),_T("osmol"),_T("ossia"),_T("ostia"),_T("other"),_T("ottar"),_T("otter"),_T("ottos"),
_T("ought"),_T("ounce"),_T("ouphe"),_T("ouphs"),_T("ourie"),_T("ousel"),_T("ousts"),_T("outby"),_T("outdo"),_T("outed"),
_T("outer"),_T("outgo"),_T("outre"),_T("ouzel"),_T("ouzos"),_T("ovals"),_T("ovary"),_T("ovate"),_T("ovens"),_T("overs"),
_T("overt"),_T("ovine"),_T("ovoid"),_T("ovoli"),_T("ovolo"),_T("ovule"),_T("owing"),_T("owlet"),_T("owned"),_T("owner"),
_T("owsen"),_T("oxbow"),_T("oxeye"),_T("oxide"),_T("oxids"),_T("oxime"),_T("oxims"),_T("oxlip"),_T("oxter"),_T("oyers"),
_T("ozone"),_T("pacas"),_T("paced"),_T("pacer"),_T("paces"),_T("pacha"),_T("packs"),_T("pacts"),_T("paddy"),_T("padis"),
_T("padle"),_T("padre"),_T("padri"),_T("paean"),_T("paeon"),_T("pagan"),_T("paged"),_T("pager"),_T("pages"),_T("pagod"),
_T("paiks"),_T("pails"),_T("pains"),_T("paint"),_T("pairs"),_T("paisa"),_T("paise"),_T("palea"),_T("paled"),_T("paler"),
_T("pales"),_T("palet"),_T("palls"),_T("pally"),_T("palms"),_T("palmy"),_T("palpi"),_T("palps"),_T("palsy"),_T("pampa"),
_T("panda"),_T("pandy"),_T("paned"),_T("panel"),_T("panes"),_T("panga"),_T("pangs"),_T("panic"),_T("panne"),_T("pansy"),
_T("panto"),_T("pants"),_T("panty"),_T("papal"),_T("papas"),_T("papaw"),_T("paper"),_T("pappi"),_T("pappy"),_T("paras"),
_T("parch"),_T("pardi"),_T("pards"),_T("pardy"),_T("pared"),_T("pareo"),_T("parer"),_T("pares"),_T("pareu"),_T("parge"),
_T("pargo"),_T("paris"),_T("parka"),_T("parks"),_T("parle"),_T("parol"),_T("parrs"),_T("parry"),_T("parse"),_T("parts"),
_T("party"),_T("parve"),_T("parvo"),_T("paseo"),_T("pases"),_T("pasha"),_T("passe"),_T("pasta"),_T("paste"),_T("pasts"),
_T("pasty"),_T("patch"),_T("pated"),_T("paten"),_T("pater"),_T("pates"),_T("paths"),_T("patin"),_T("patio"),_T("patly"),
_T("patsy"),_T("patty"),_T("pause"),_T("pavan"),_T("paved"),_T("paver"),_T("paves"),_T("pavid"),_T("pavin"),_T("pavis"),
_T("pawed"),_T("pawer"),_T("pawky"),_T("pawls"),_T("pawns"),_T("paxes"),_T("payed"),_T("payee"),_T("payer"),_T("payor"),
_T("peace"),_T("peach"),_T("peage"),_T("peags"),_T("peaks"),_T("peaky"),_T("peals"),_T("peans"),_T("pearl"),_T("pears"),
_T("peart"),_T("pease"),_T("peats"),_T("peaty"),_T("peavy"),_T("pecan"),_T("pechs"),_T("pecks"),_T("pecky"),_T("pedal"),
_T("pedes"),_T("pedro"),_T("peeks"),_T("peels"),_T("peens"),_T("peeps"),_T("peers"),_T("peery"),_T("peeve"),_T("peins"),
_T("peise"),_T("pekan"),_T("pekes"),_T("pekin"),_T("pekoe"),_T("peles"),_T("pelfs"),_T("pelon"),_T("pelts"),_T("penal"),
_T("pence"),_T("pends"),_T("penes"),_T("pengo"),_T("penis"),_T("penna"),_T("penne"),_T("penni"),_T("penny"),_T("peons"),
_T("peony"),_T("pepla"),_T("pepos"),_T("peppy"),_T("perch"),_T("perdu"),_T("perdy"),_T("perea"),_T("peril"),_T("peris"),
_T("perks"),_T("perky"),_T("perms"),_T("perry"),_T("perse"),_T("pesky"),_T("pesos"),_T("pesto"),_T("pests"),_T("pesty"),
_T("petal"),_T("peter"),_T("petit"),_T("petti"),_T("petto"),_T("petty"),_T("pewee"),_T("pewit"),_T("phage"),_T("phase"),
_T("phial"),_T("phlox"),_T("phone"),_T("phono"),_T("phons"),_T("phony"),_T("photo"),_T("phots"),_T("phpht"),_T("phuts"),
_T("phyla"),_T("phyle"),_T("piano"),_T("pians"),_T("pibal"),_T("pical"),_T("picas"),_T("picks"),_T("picky"),_T("picot"),
_T("picul"),_T("piece"),_T("piers"),_T("pieta"),_T("piety"),_T("piggy"),_T("pigmy"),_T("piing"),_T("pikas"),_T("piked"),
_T("piker"),_T("pikes"),_T("pikis"),_T("pilaf"),_T("pilar"),_T("pilau"),_T("pilaw"),_T("pilea"),_T("piled"),_T("pilei"),
_T("piles"),_T("pilis"),_T("pills"),_T("pilot"),_T("pilus"),_T("pimas"),_T("pimps"),_T("pinas"),_T("pinch"),_T("pined"),
_T("pines"),_T("piney"),_T("pingo"),_T("pings"),_T("pinko"),_T("pinks"),_T("pinky"),_T("pinna"),_T("pinny"),_T("pinon"),
_T("pinot"),_T("pinta"),_T("pinto"),_T("pints"),_T("pinup"),_T("pions"),_T("pious"),_T("pipal"),_T("piped"),_T("piper"),
_T("pipes"),_T("pipet"),_T("pipit"),_T("pique"),_T("pirns"),_T("pirog"),_T("pisco"),_T("pisos"),_T("piste"),_T("pitas"),
_T("pitch"),_T("piths"),_T("pithy"),_T("piton"),_T("pivot"),_T("pixel"),_T("pixes"),_T("pixie"),_T("pizza"),_T("place"),
_T("plack"),_T("plage"),_T("plaid"),_T("plain"),_T("plait"),_T("plane"),_T("plank"),_T("plans"),_T("plant"),_T("plash"),
_T("plasm"),_T("plate"),_T("plats"),_T("platy"),_T("playa"),_T("plays"),_T("plaza"),_T("plead"),_T("pleas"),_T("pleat"),
_T("plebe"),_T("plebs"),_T("plena"),_T("plews"),_T("plica"),_T("plied"),_T("plier"),_T("plies"),_T("plink"),_T("plods"),
_T("plonk"),_T("plops"),_T("plots"),_T("plotz"),_T("plows"),_T("ploys"),_T("pluck"),_T("plugs"),_T("plumb"),_T("plume"),
_T("plump"),_T("plums"),_T("plumy"),_T("plunk"),_T("plush"),_T("plyer"),_T("poach"),_T("pocks"),_T("pocky"),_T("podgy"),
_T("podia"),_T("poems"),_T("poesy"),_T("poets"),_T("pogey"),_T("poilu"),_T("poind"),_T("point"),_T("poise"),_T("poked"),
_T("poker"),_T("pokes"),_T("pokey"),_T("polar"),_T("poled"),_T("poler"),_T("poles"),_T("polio"),_T("polis"),_T("polka"),
_T("polls"),_T("polos"),_T("polyp"),_T("polys"),_T("pomes"),_T("pommy"),_T("pomps"),_T("ponce"),_T("ponds"),_T("pones"),
_T("pongs"),_T("pooch"),_T("poods"),_T("poofs"),_T("poofy"),_T("poohs"),_T("pools"),_T("poons"),_T("poops"),_T("poori"),
_T("poove"),_T("popes"),_T("poppa"),_T("poppy"),_T("popsy"),_T("porch"),_T("pored"),_T("pores"),_T("porgy"),_T("porks"),
_T("porky"),_T("porno"),_T("porns"),_T("porny"),_T("ports"),_T("posed"),_T("poser"),_T("poses"),_T("posit"),_T("posse"),
_T("posts"),_T("potsy"),_T("potto"),_T("potty"),_T("pouch"),_T("pouff"),_T("poufs"),_T("poult"),_T("pound"),_T("pours"),
_T("pouts"),_T("pouty"),_T("power"),_T("poxed"),_T("poxes"),_T("poyou"),_T("praam"),_T("prahu"),_T("prams"),_T("prang"),
_T("prank"),_T("praos"),_T("prase"),_T("prate"),_T("prats"),_T("praus"),_T("prawn"),_T("prays"),_T("preed"),_T("preen"),
_T("prees"),_T("preps"),_T("presa"),_T("prese"),_T("press"),_T("prest"),_T("prexy"),_T("preys"),_T("price"),_T("prick"),
_T("pricy"),_T("pride"),_T("pried"),_T("prier"),_T("pries"),_T("prigs"),_T("prill"),_T("prima"),_T("prime"),_T("primi"),
_T("primo"),_T("primp"),_T("prims"),_T("prink"),_T("print"),_T("prion"),_T("prior"),_T("prise"),_T("prism"),_T("priss"),
_T("privy"),_T("prize"),_T("proas"),_T("probe"),_T("prods"),_T("proem"),_T("profs"),_T("progs"),_T("prole"),_T("promo"),
_T("proms"),_T("prone"),_T("prong"),_T("proof"),_T("props"),_T("prose"),_T("proso"),_T("pross"),_T("prost"),_T("prosy"),
_T("proud"),_T("prove"),_T("prowl"),_T("prows"),_T("proxy"),_T("prude"),_T("prune"),_T("pruta"),_T("pryer"),_T("psalm"),
_T("pseud"),_T("pshaw"),_T("psoae"),_T("psoai"),_T("psoas"),_T("psych"),_T("pubes"),_T("pubic"),_T("pubis"),_T("puces"),
_T("pucka"),_T("pucks"),_T("pudgy"),_T("pudic"),_T("puffs"),_T("puffy"),_T("puggy"),_T("pujah"),_T("pujas"),_T("puked"),
_T("pukes"),_T("pukka"),_T("puled"),_T("puler"),_T("pules"),_T("pulik"),_T("pulis"),_T("pulls"),_T("pulps"),_T("pulpy"),
_T("pulse"),_T("pumas"),_T("pumps"),_T("punas"),_T("punch"),_T("pungs"),_T("punka"),_T("punks"),_T("punky"),_T("punny"),
_T("punto"),_T("punts"),_T("punty"),_T("pupae"),_T("pupal"),_T("pupas"),_T("pupil"),_T("puppy"),_T("purda"),_T("puree"),
_T("purer"),_T("purge"),_T("purin"),_T("puris"),_T("purls"),_T("purrs"),_T("purse"),_T("pursy"),_T("puses"),_T("pushy"),
_T("pussy"),_T("puton"),_T("putti"),_T("putto"),_T("putts"),_T("putty"),_T("pygmy"),_T("pyins"),_T("pylon"),_T("pyoid"),
_T("pyran"),_T("pyres"),_T("pyric"),_T("pyxes"),_T("pyxie"),_T("pyxis"),_T("qaids"),_T("qanat"),_T("qophs"),_T("quack"),
_T("quads"),_T("quaff"),_T("quags"),_T("quail"),_T("quais"),_T("quake"),_T("quaky"),_T("quale"),_T("qualm"),_T("quant"),
_T("quare"),_T("quark"),_T("quart"),_T("quash"),_T("quasi"),_T("quass"),_T("quate"),_T("quays"),_T("quean"),_T("queen"),
_T("queer"),_T("quell"),_T("quern"),_T("query"),_T("quest"),_T("queue"),_T("queys"),_T("quick"),_T("quids"),_T("quiet"),
_T("quiff"),_T("quill"),_T("quilt"),_T("quins"),_T("quint"),_T("quips"),_T("quipu"),_T("quire"),_T("quirk"),_T("quirt"),
_T("quite"),_T("quits"),_T("quods"),_T("quoin"),_T("quoit"),_T("quota"),_T("quote"),_T("quoth"),_T("qursh"),_T("rabat"),
_T("rabbi"),_T("rabic"),_T("rabid"),_T("raced"),_T("racer"),_T("races"),_T("racks"),_T("racon"),_T("radar"),_T("radii"),
_T("radio"),_T("radix"),_T("radon"),_T("raffs"),_T("rafts"),_T("ragas"),_T("raged"),_T("ragee"),_T("rages"),_T("raggy"),
_T("ragis"),_T("raias"),_T("raids"),_T("rails"),_T("rains"),_T("rainy"),_T("raise"),_T("rajah"),_T("rajas"),_T("rajes"),
_T("raked"),_T("rakee"),_T("raker"),_T("rakes"),_T("rakis"),_T("rales"),_T("rally"),_T("ralph"),_T("ramee"),_T("ramet"),
_T("ramie"),_T("rammy"),_T("ramps"),_T("ramus"),_T("rance"),_T("ranch"),_T("rands"),_T("randy"),_T("ranee"),_T("range"),
_T("rangy"),_T("ranid"),_T("ranis"),_T("ranks"),_T("rants"),_T("raped"),_T("raper"),_T("rapes"),_T("raphe"),_T("rapid"),
_T("rared"),_T("rarer"),_T("rares"),_T("rased"),_T("raser"),_T("rases"),_T("rasps"),_T("raspy"),_T("ratal"),_T("ratan"),
_T("ratch"),_T("rated"),_T("ratel"),_T("rater"),_T("rates"),_T("rathe"),_T("ratio"),_T("ratos"),_T("ratty"),_T("raved"),
_T("ravel"),_T("raven"),_T("raver"),_T("raves"),_T("ravin"),_T("rawer"),_T("rawin"),_T("rawly"),_T("raxed"),_T("raxes"),
_T("rayah"),_T("rayas"),_T("rayed"),_T("rayon"),_T("razed"),_T("razee"),_T("razer"),_T("razes"),_T("razor"),_T("reach"),
_T("react"),_T("readd"),_T("reads"),_T("ready"),_T("realm"),_T("reals"),_T("reams"),_T("reaps"),_T("rearm"),_T("rears"),
_T("reata"),_T("reave"),_T("rebar"),_T("rebbe"),_T("rebec"),_T("rebel"),_T("rebid"),_T("rebop"),_T("rebus"),_T("rebut"),
_T("rebuy"),_T("recap"),_T("recce"),_T("recks"),_T("recon"),_T("recta"),_T("recti"),_T("recto"),_T("recur"),_T("recut"),
_T("redan"),_T("redds"),_T("reded"),_T("redes"),_T("redia"),_T("redid"),_T("redip"),_T("redly"),_T("redon"),_T("redos"),
_T("redox"),_T("redry"),_T("redub"),_T("redux"),_T("redye"),_T("reeds"),_T("reedy"),_T("reefs"),_T("reefy"),_T("reeks"),
_T("reeky"),_T("reels"),_T("reest"),_T("reeve"),_T("refed"),_T("refel"),_T("refer"),_T("refit"),_T("refix"),_T("refly"),
_T("refry"),_T("regal"),_T("reges"),_T("regma"),_T("regna"),_T("rehab"),_T("rehem"),_T("reifs"),_T("reify"),_T("reign"),
_T("reink"),_T("reins"),_T("reive"),_T("rekey"),_T("relax"),_T("relay"),_T("relet"),_T("relic"),_T("relit"),_T("reman"),
_T("remap"),_T("remet"),_T("remex"),_T("remit"),_T("remix"),_T("renal"),_T("rends"),_T("renew"),_T("renig"),_T("renin"),
_T("rente"),_T("rents"),_T("reoil"),_T("repay"),_T("repeg"),_T("repel"),_T("repin"),_T("reply"),_T("repos"),_T("repot"),
_T("repps"),_T("repro"),_T("reran"),_T("rerig"),_T("rerun"),_T("resaw"),_T("resay"),_T("resee"),_T("reset"),_T("resew"),
_T("resid"),_T("resin"),_T("resod"),_T("resow"),_T("rests"),_T("retag"),_T("retax"),_T("retch"),_T("retem"),_T("retia"),
_T("retie"),_T("retro"),_T("retry"),_T("reuse"),_T("revel"),_T("revet"),_T("revue"),_T("rewan"),_T("rewax"),_T("rewed"),
_T("rewet"),_T("rewin"),_T("rewon"),_T("rexes"),_T("rheas"),_T("rheum"),_T("rhino"),_T("rhomb"),_T("rhumb"),_T("rhyme"),
_T("rhyta"),_T("rials"),_T("riant"),_T("riata"),_T("ribby"),_T("ribes"),_T("riced"),_T("ricer"),_T("rices"),_T("ricin"),
_T("ricks"),_T("rider"),_T("rides"),_T("ridge"),_T("ridgy"),_T("riels"),_T("rifer"),_T("riffs"),_T("rifle"),_T("rifts"),
_T("right"),_T("rigid"),_T("rigor"),_T("riled"),_T("riles"),_T("riley"),_T("rille"),_T("rills"),_T("rimed"),_T("rimer"),
_T("rimes"),_T("rinds"),_T("rings"),_T("rinks"),_T("rinse"),_T("rioja"),_T("riots"),_T("riped"),_T("ripen"),_T("riper"),
_T("ripes"),_T("risen"),_T("riser"),_T("rises"),_T("rishi"),_T("risks"),_T("risky"),_T("risus"),_T("rites"),_T("ritzy"),
_T("rival"),_T("rived"),_T("riven"),_T("river"),_T("rives"),_T("rivet"),_T("riyal"),_T("roach"),_T("roads"),_T("roams"),
_T("roans"),_T("roars"),_T("roast"),_T("robed"),_T("robes"),_T("robin"),_T("roble"),_T("robot"),_T("rocks"),_T("rocky"),
_T("rodeo"),_T("roger"),_T("rogue"),_T("roils"),_T("roily"),_T("roles"),_T("rolfs"),_T("rolls"),_T("roman"),_T("romeo"),
_T("romps"),_T("rondo"),_T("roods"),_T("roofs"),_T("rooks"),_T("rooky"),_T("rooms"),_T("roomy"),_T("roose"),_T("roost"),
_T("roots"),_T("rooty"),_T("roped"),_T("roper"),_T("ropes"),_T("ropey"),_T("roque"),_T("rosed"),_T("roses"),_T("roset"),
_T("rosin"),_T("rotas"),_T("rotch"),_T("rotes"),_T("rotis"),_T("rotls"),_T("rotor"),_T("rotos"),_T("rotte"),_T("rouen"),
_T("roues"),_T("rouge"),_T("rough"),_T("round"),_T("roups"),_T("roupy"),_T("rouse"),_T("roust"),_T("route"),_T("routh"),
_T("routs"),_T("roved"),_T("roven"),_T("rover"),_T("roves"),_T("rowan"),_T("rowdy"),_T("rowed"),_T("rowel"),_T("rowen"),
_T("rower"),_T("rowth"),_T("royal"),_T("ruana"),_T("rubes"),_T("ruble"),_T("rubus"),_T("ruche"),_T("rucks"),_T("rudds"),
_T("ruddy"),_T("ruder"),_T("ruers"),_T("ruffe"),_T("ruffs"),_T("rugae"),_T("rugal"),_T("rugby"),_T("ruing"),_T("ruins"),
_T("ruled"),_T("ruler"),_T("rules"),_T("rumba"),_T("rumen"),_T("rummy"),_T("rumor"),_T("rumps"),_T("runes"),_T("rungs"),
_T("runic"),_T("runny"),_T("runts"),_T("runty"),_T("rupee"),_T("rural"),_T("ruses"),_T("rushy"),_T("rusks"),_T("rusts"),
_T("rusty"),_T("ruths"),_T("rutin"),_T("rutty"),_T("ryked"),_T("rykes"),_T("rynds"),_T("ryots"),_T("sabed"),_T("saber"),
_T("sabes"),_T("sabin"),_T("sabir"),_T("sable"),_T("sabot"),_T("sabra"),_T("sabre"),_T("sacks"),_T("sacra"),_T("sades"),
_T("sadhe"),_T("sadhu"),_T("sadis"),_T("sadly"),_T("safer"),_T("safes"),_T("sagas"),_T("sager"),_T("sages"),_T("saggy"),
_T("sagos"),_T("sagum"),_T("sahib"),_T("saice"),_T("saids"),_T("saiga"),_T("sails"),_T("sains"),_T("saint"),_T("saith"),
_T("sajou"),_T("saker"),_T("sakes"),_T("sakis"),_T("salad"),_T("salal"),_T("salep"),_T("sales"),_T("salic"),_T("sally"),
_T("salmi"),_T("salol"),_T("salon"),_T("salpa"),_T("salps"),_T("salsa"),_T("salts"),_T("salty"),_T("salve"),_T("salvo"),
_T("samba"),_T("sambo"),_T("samek"),_T("samps"),_T("sands"),_T("sandy"),_T("saned"),_T("saner"),_T("sanes"),_T("sanga"),
_T("sangh"),_T("santo"),_T("sapid"),_T("sapor"),_T("sappy"),_T("saran"),_T("sards"),_T("saree"),_T("sarge"),_T("sarin"),
_T("saris"),_T("sarks"),_T("sarky"),_T("sarod"),_T("saros"),_T("sasin"),_T("sassy"),_T("satay"),_T("sated"),_T("satem"),
_T("sates"),_T("satin"),_T("satis"),_T("satyr"),_T("sauce"),_T("sauch"),_T("saucy"),_T("saugh"),_T("sauls"),_T("sault"),
_T("sauna"),_T("saury"),_T("saute"),_T("saved"),_T("saver"),_T("saves"),_T("savin"),_T("savor"),_T("savoy"),_T("savvy"),
_T("sawed"),_T("sawer"),_T("saxes"),_T("sayer"),_T("sayid"),_T("sayst"),_T("scabs"),_T("scads"),_T("scags"),_T("scald"),
_T("scale"),_T("scall"),_T("scalp"),_T("scaly"),_T("scamp"),_T("scams"),_T("scans"),_T("scant"),_T("scape"),_T("scare"),
_T("scarf"),_T("scarp"),_T("scars"),_T("scart"),_T("scary"),_T("scats"),_T("scatt"),_T("scaup"),_T("scaur"),_T("scena"),
_T("scend"),_T("scene"),_T("scent"),_T("schav"),_T("schmo"),_T("schul"),_T("schwa"),_T("scion"),_T("scoff"),_T("scold"),
_T("scone"),_T("scoop"),_T("scoot"),_T("scope"),_T("scops"),_T("score"),_T("scorn"),_T("scots"),_T("scour"),_T("scout"),
_T("scowl"),_T("scows"),_T("scrag"),_T("scram"),_T("scrap"),_T("scree"),_T("screw"),_T("scrim"),_T("scrip"),_T("scrod"),
_T("scrub"),_T("scrum"),_T("scuba"),_T("scudi"),_T("scudo"),_T("scuds"),_T("scuff"),_T("sculk"),_T("scull"),_T("sculp"),
_T("scums"),_T("scups"),_T("scurf"),_T("scuta"),_T("scute"),_T("scuts"),_T("seals"),_T("seams"),_T("seamy"),_T("sears"),
_T("seats"),_T("sebum"),_T("secco"),_T("sects"),_T("sedan"),_T("seder"),_T("sedge"),_T("sedgy"),_T("sedum"),_T("seeds"),
_T("seedy"),_T("seeks"),_T("seels"),_T("seely"),_T("seems"),_T("seeps"),_T("seepy"),_T("seers"),_T("segni"),_T("segno"),
_T("segos"),_T("segue"),_T("seifs"),_T("seine"),_T("seise"),_T("seism"),_T("seize"),_T("selah"),_T("selfs"),_T("selle"),
_T("sells"),_T("selva"),_T("semen"),_T("semes"),_T("semis"),_T("sends"),_T("sengi"),_T("senna"),_T("senor"),_T("sensa"),
_T("sense"),_T("sente"),_T("senti"),_T("sepal"),_T("sepia"),_T("sepic"),_T("sepoy"),_T("septa"),_T("septs"),_T("serac"),
_T("serai"),_T("seral"),_T("sered"),_T("serer"),_T("seres"),_T("serfs"),_T("serge"),_T("serif"),_T("serin"),_T("serow"),
_T("serry"),_T("serum"),_T("serve"),_T("servo"),_T("setae"),_T("setal"),_T("seton"),_T("setts"),_T("setup"),_T("seven"),
_T("sever"),_T("sewan"),_T("sewar"),_T("sewed"),_T("sewer"),_T("sexed"),_T("sexes"),_T("sexto"),_T("sexts"),_T("shack"),
_T("shade"),_T("shads"),_T("shady"),_T("shaft"),_T("shags"),_T("shahs"),_T("shake"),_T("shako"),_T("shaky"),_T("shale"),
_T("shall"),_T("shalt"),_T("shaly"),_T("shame"),_T("shams"),_T("shank"),_T("shape"),_T("shard"),_T("share"),_T("shark"),
_T("sharn"),_T("sharp"),_T("shaul"),_T("shave"),_T("shawl"),_T("shawm"),_T("shawn"),_T("shaws"),_T("shays"),_T("sheaf"),
_T("sheal"),_T("shear"),_T("sheas"),_T("sheds"),_T("sheen"),_T("sheep"),_T("sheer"),_T("sheet"),_T("sheik"),_T("shelf"),
_T("shell"),_T("shend"),_T("shent"),_T("sheol"),_T("sherd"),_T("shewn"),_T("shews"),_T("shied"),_T("shiel"),_T("shier"),
_T("shies"),_T("shift"),_T("shill"),_T("shily"),_T("shims"),_T("shine"),_T("shins"),_T("shiny"),_T("ships"),_T("shire"),
_T("shirk"),_T("shirr"),_T("shirt"),_T("shist"),_T("shits"),_T("shiva"),_T("shive"),_T("shivs"),_T("shlep"),_T("shoal"),
_T("shoat"),_T("shock"),_T("shoed"),_T("shoer"),_T("shoes"),_T("shogs"),_T("shoji"),_T("shone"),_T("shook"),_T("shool"),
_T("shoon"),_T("shoos"),_T("shoot"),_T("shops"),_T("shore"),_T("shorl"),_T("shorn"),_T("short"),_T("shote"),_T("shots"),
_T("shott"),_T("shout"),_T("shove"),_T("shown"),_T("shows"),_T("showy"),_T("shoyu"),_T("shred"),_T("shrew"),_T("shris"),
_T("shrub"),_T("shrug"),_T("shtik"),_T("shuck"),_T("shuln"),_T("shuls"),_T("shuns"),_T("shunt"),_T("shush"),_T("shute"),
_T("shuts"),_T("shyer"),_T("shyly"),_T("sials"),_T("sibbs"),_T("sibyl"),_T("sices"),_T("sicko"),_T("sicks"),_T("sided"),
_T("sides"),_T("sidle"),_T("siege"),_T("sieur"),_T("sieve"),_T("sifts"),_T("sighs"),_T("sight"),_T("sigil"),_T("sigma"),
_T("signs"),_T("siker"),_T("sikes"),_T("silds"),_T("silex"),_T("silks"),_T("silky"),_T("sills"),_T("silly"),_T("silos"),
_T("silts"),_T("silty"),_T("silva"),_T("simar"),_T("simas"),_T("simps"),_T("since"),_T("sines"),_T("sinew"),_T("singe"),
_T("sings"),_T("sinhs"),_T("sinks"),_T("sinus"),_T("siped"),_T("sipes"),_T("sired"),_T("siree"),_T("siren"),_T("sires"),
_T("sirra"),_T("sirup"),_T("sisal"),_T("sises"),_T("sissy"),_T("sitar"),_T("sited"),_T("sites"),_T("situp"),_T("situs"),
_T("siver"),_T("sixes"),_T("sixmo"),_T("sixte"),_T("sixth"),_T("sixty"),_T("sizar"),_T("sized"),_T("sizer"),_T("sizes"),
_T("skags"),_T("skald"),_T("skate"),_T("skats"),_T("skean"),_T("skeed"),_T("skeen"),_T("skees"),_T("skeet"),_T("skegs"),
_T("skein"),_T("skelm"),_T("skelp"),_T("skene"),_T("skeps"),_T("skews"),_T("skids"),_T("skied"),_T("skier"),_T("skies"),
_T("skiey"),_T("skiff"),_T("skill"),_T("skimo"),_T("skimp"),_T("skims"),_T("skink"),_T("skins"),_T("skint"),_T("skips"),
_T("skirl"),_T("skirr"),_T("skirt"),_T("skite"),_T("skits"),_T("skive"),_T("skoal"),_T("skosh"),_T("skuas"),_T("skulk"),
_T("skull"),_T("skunk"),_T("skyed"),_T("skyey"),_T("slabs"),_T("slack"),_T("slags"),_T("slain"),_T("slake"),_T("slams"),
_T("slang"),_T("slank"),_T("slant"),_T("slaps"),_T("slash"),_T("slate"),_T("slats"),_T("slaty"),_T("slave"),_T("slaws"),
_T("slays"),_T("sleds"),_T("sleek"),_T("sleep"),_T("sleet"),_T("slept"),_T("slews"),_T("slice"),_T("slick"),_T("slide"),
_T("slier"),_T("slily"),_T("slime"),_T("slims"),_T("slimy"),_T("sling"),_T("slink"),_T("slipe"),_T("slips"),_T("slipt"),
_T("slits"),_T("slobs"),_T("sloes"),_T("slogs"),_T("sloid"),_T("slojd"),_T("sloop"),_T("slope"),_T("slops"),_T("slosh"),
_T("sloth"),_T("slots"),_T("slows"),_T("sloyd"),_T("slubs"),_T("slued"),_T("slues"),_T("sluff"),_T("slugs"),_T("slump"),
_T("slums"),_T("slung"),_T("slunk"),_T("slurb"),_T("slurp"),_T("slurs"),_T("slush"),_T("sluts"),_T("slyer"),_T("slyly"),
_T("slype"),_T("smack"),_T("small"),_T("smalt"),_T("smarm"),_T("smart"),_T("smash"),_T("smaze"),_T("smear"),_T("smeek"),
_T("smell"),_T("smelt"),_T("smerk"),_T("smews"),_T("smile"),_T("smirk"),_T("smite"),_T("smith"),_T("smock"),_T("smogs"),
_T("smoke"),_T("smoky"),_T("smolt"),_T("smote"),_T("smuts"),_T("snack"),_T("snafu"),_T("snags"),_T("snail"),_T("snake"),
_T("snaky"),_T("snaps"),_T("snare"),_T("snark"),_T("snarl"),_T("snash"),_T("snath"),_T("snaws"),_T("sneak"),_T("sneap"),
_T("sneck"),_T("sneds"),_T("sneer"),_T("snell"),_T("snibs"),_T("snick"),_T("snide"),_T("sniff"),_T("snipe"),_T("snips"),
_T("snits"),_T("snobs"),_T("snogs"),_T("snood"),_T("snook"),_T("snool"),_T("snoop"),_T("snoot"),_T("snore"),_T("snort"),
_T("snots"),_T("snout"),_T("snows"),_T("snowy"),_T("snubs"),_T("snuck"),_T("snuff"),_T("snugs"),_T("snyes"),_T("soaks"),
_T("soaps"),_T("soapy"),_T("soars"),_T("soave"),_T("sober"),_T("socko"),_T("socks"),_T("socle"),_T("sodas"),_T("soddy"),
_T("sodic"),_T("sodom"),_T("sofar"),_T("sofas"),_T("softa"),_T("softs"),_T("softy"),_T("soggy"),_T("soils"),_T("sojas"),
_T("sokes"),_T("sokol"),_T("solan"),_T("solar"),_T("soldi"),_T("soldo"),_T("soled"),_T("solei"),_T("soles"),_T("solid"),
_T("solon"),_T("solos"),_T("solum"),_T("solus"),_T("solve"),_T("somas"),_T("sonar"),_T("sonde"),_T("sones"),_T("songs"),
_T("sonic"),_T("sonly"),_T("sonny"),_T("sonsy"),_T("sooey"),_T("sooks"),_T("sooth"),_T("soots"),_T("sooty"),_T("sophs"),
_T("sophy"),_T("sopor"),_T("soppy"),_T("soras"),_T("sorbs"),_T("sords"),_T("sorel"),_T("sorer"),_T("sores"),_T("sorgo"),
_T("sorns"),_T("sorry"),_T("sorts"),_T("sorus"),_T("soths"),_T("sotol"),_T("sough"),_T("souks"),_T("souls"),_T("sound"),
_T("soups"),_T("soupy"),_T("sours"),_T("souse"),_T("south"),_T("sowar"),_T("sowed"),_T("sower"),_T("soyas"),_T("soyuz"),
_T("sozin"),_T("space"),_T("spacy"),_T("spade"),_T("spado"),_T("spaed"),_T("spaes"),_T("spahi"),_T("spail"),_T("spait"),
_T("spake"),_T("spale"),_T("spall"),_T("spang"),_T("spank"),_T("spans"),_T("spare"),_T("spark"),_T("spars"),_T("spasm"),
_T("spate"),_T("spats"),_T("spawn"),_T("spays"),_T("speak"),_T("spean"),_T("spear"),_T("speck"),_T("specs"),_T("speed"),
_T("speel"),_T("speer"),_T("speil"),_T("speir"),_T("spell"),_T("spelt"),_T("spend"),_T("spent"),_T("sperm"),_T("spews"),
_T("spica"),_T("spice"),_T("spick"),_T("spics"),_T("spicy"),_T("spied"),_T("spiel"),_T("spier"),_T("spies"),_T("spiff"),
_T("spike"),_T("spiks"),_T("spiky"),_T("spile"),_T("spill"),_T("spilt"),_T("spine"),_T("spins"),_T("spiny"),_T("spire"),
_T("spirt"),_T("spiry"),_T("spite"),_T("spits"),_T("spitz"),_T("spivs"),_T("splat"),_T("splay"),_T("split"),_T("spode"),
_T("spoil"),_T("spoke"),_T("spoof"),_T("spook"),_T("spool"),_T("spoon"),_T("spoor"),_T("spore"),_T("sport"),_T("spots"),
_T("spout"),_T("sprag"),_T("sprat"),_T("spray"),_T("spree"),_T("sprig"),_T("sprit"),_T("sprue"),_T("sprug"),_T("spuds"),
_T("spued"),_T("spues"),_T("spume"),_T("spumy"),_T("spunk"),_T("spurn"),_T("spurs"),_T("spurt"),_T("sputa"),_T("squab"),
_T("squad"),_T("squat"),_T("squaw"),_T("squeg"),_T("squib"),_T("squid"),_T("stabs"),_T("stack"),_T("stade"),_T("staff"),
_T("stage"),_T("stags"),_T("stagy"),_T("staid"),_T("staig"),_T("stain"),_T("stair"),_T("stake"),_T("stale"),_T("stalk"),
_T("stall"),_T("stamp"),_T("stand"),_T("stane"),_T("stang"),_T("stank"),_T("staph"),_T("stare"),_T("stark"),_T("stars"),
_T("start"),_T("stash"),_T("state"),_T("stats"),_T("stave"),_T("stays"),_T("stead"),_T("steak"),_T("steal"),_T("steam"),
_T("steed"),_T("steek"),_T("steel"),_T("steep"),_T("steer"),_T("stein"),_T("stela"),_T("stele"),_T("stems"),_T("steno"),
_T("steps"),_T("stere"),_T("stern"),_T("stets"),_T("stews"),_T("stich"),_T("stick"),_T("stied"),_T("sties"),_T("stiff"),
_T("stile"),_T("still"),_T("stilt"),_T("stime"),_T("stimy"),_T("sting"),_T("stink"),_T("stint"),_T("stipe"),_T("stirk"),
_T("stirp"),_T("stirs"),_T("stoae"),_T("stoai"),_T("stoas"),_T("stoat"),_T("stobs"),_T("stock"),_T("stogy"),_T("stoic"),
_T("stoke"),_T("stole"),_T("stoma"),_T("stomp"),_T("stone"),_T("stony"),_T("stood"),_T("stook"),_T("stool"),_T("stoop"),
_T("stope"),_T("stops"),_T("stopt"),_T("store"),_T("stork"),_T("storm"),_T("story"),_T("stoss"),_T("stoup"),_T("stour"),
_T("stout"),_T("stove"),_T("stowp"),_T("stows"),_T("strap"),_T("straw"),_T("stray"),_T("strep"),_T("strew"),_T("stria"),
_T("strid"),_T("strip"),_T("strop"),_T("strow"),_T("stroy"),_T("strum"),_T("strut"),_T("stubs"),_T("stuck"),_T("studs"),
_T("study"),_T("stuff"),_T("stull"),_T("stump"),_T("stums"),_T("stung"),_T("stunk"),_T("stuns"),_T("stunt"),_T("stupa"),
_T("stupe"),_T("sturt"),_T("styed"),_T("styes"),_T("style"),_T("styli"),_T("stymy"),_T("suave"),_T("subah"),_T("subas"),
_T("suber"),_T("sucks"),_T("sucre"),_T("sudds"),_T("sudor"),_T("sudsy"),_T("suede"),_T("suers"),_T("suets"),_T("suety"),
_T("sugar"),_T("sughs"),_T("suing"),_T("suint"),_T("suite"),_T("suits"),_T("sulci"),_T("sulfa"),_T("sulfo"),_T("sulks"),
_T("sulky"),_T("sully"),_T("sulus"),_T("sumac"),_T("summa"),_T("sumos"),_T("sumps"),_T("sunna"),_T("sunns"),_T("sunny"),
_T("sunup"),_T("super"),_T("supes"),_T("supra"),_T("surah"),_T("sural"),_T("suras"),_T("surds"),_T("surer"),_T("surfs"),
_T("surfy"),_T("surge"),_T("surgy"),_T("surly"),_T("surra"),_T("sushi"),_T("sutra"),_T("sutta"),_T("swabs"),_T("swage"),
_T("swags"),_T("swail"),_T("swain"),_T("swale"),_T("swami"),_T("swamp"),_T("swamy"),_T("swang"),_T("swank"),_T("swans"),
_T("swaps"),_T("sward"),_T("sware"),_T("swarf"),_T("swarm"),_T("swart"),_T("swash"),_T("swath"),_T("swats"),_T("sways"),
_T("swear"),_T("sweat"),_T("swede"),_T("sweep"),_T("sweer"),_T("sweet"),_T("swell"),_T("swept"),_T("swift"),_T("swigs"),
_T("swill"),_T("swims"),_T("swine"),_T("swing"),_T("swink"),_T("swipe"),_T("swirl"),_T("swish"),_T("swiss"),_T("swith"),
_T("swive"),_T("swobs"),_T("swoon"),_T("swoop"),_T("swops"),_T("sword"),_T("swore"),_T("sworn"),_T("swots"),_T("swoun"),
_T("swung"),_T("sycee"),_T("syces"),_T("sykes"),_T("sylis"),_T("sylph"),_T("sylva"),_T("synch"),_T("syncs"),_T("synod"),
_T("synth"),_T("syphs"),_T("syren"),_T("syrup"),_T("sysop"),_T("tabby"),_T("taber"),_T("tabes"),_T("tabid"),_T("tabla"),
_T("table"),_T("taboo"),_T("tabor"),_T("tabun"),_T("tabus"),_T("taces"),_T("tacet"),_T("tache"),_T("tachs"),_T("tacit"),
_T("tacks"),_T("tacky"),_T("tacos"),_T("tacts"),_T("taels"),_T("taffy"),_T("tafia"),_T("tahrs"),_T("taiga"),_T("tails"),
_T("tains"),_T("taint"),_T("tajes"),_T("taken"),_T("taker"),_T("takes"),_T("takin"),_T("talar"),_T("talas"),_T("talcs"),
_T("taler"),_T("tales"),_T("talks"),_T("talky"),_T("tally"),_T("talon"),_T("taluk"),_T("talus"),_T("tamal"),_T("tamed"),
_T("tamer"),_T("tames"),_T("tamis"),_T("tammy"),_T("tamps"),_T("tango"),_T("tangs"),_T("tangy"),_T("tanka"),_T("tanks"),
_T("tansy"),_T("tanto"),_T("tapas"),_T("taped"),_T("taper"),_T("tapes"),_T("tapir"),_T("tapis"),_T("tardo"),_T("tardy"),
_T("tared"),_T("tares"),_T("targe"),_T("tarns"),_T("taroc"),_T("tarok"),_T("taros"),_T("tarot"),_T("tarps"),_T("tarre"),
_T("tarry"),_T("tarsi"),_T("tarts"),_T("tarty"),_T("tasks"),_T("tasse"),_T("taste"),_T("tasty"),_T("tatar"),_T("tater"),
_T("tates"),_T("tatty"),_T("taunt"),_T("taupe"),_T("tauts"),_T("tawed"),_T("tawer"),_T("tawie"),_T("tawny"),_T("tawse"),
_T("taxed"),_T("taxer"),_T("taxes"),_T("taxis"),_T("taxon"),_T("taxus"),_T("tazza"),_T("tazze"),_T("teach"),_T("teaks"),
_T("teals"),_T("teams"),_T("tears"),_T("teary"),_T("tease"),_T("teats"),_T("techy"),_T("tecta"),_T("teddy"),_T("teels"),
_T("teems"),_T("teens"),_T("teeny"),_T("teeth"),_T("teffs"),_T("tegua"),_T("teiid"),_T("teind"),_T("telae"),_T("teles"),
_T("telex"),_T("telia"),_T("telic"),_T("tells"),_T("telly"),_T("teloi"),_T("telos"),_T("tempi"),_T("tempo"),_T("temps"),
_T("tempt"),_T("tench"),_T("tends"),_T("tenet"),_T("tenia"),_T("tenon"),_T("tenor"),_T("tense"),_T("tenth"),_T("tents"),
_T("tenty"),_T("tepal"),_T("tepas"),_T("tepee"),_T("tepid"),_T("tepoy"),_T("terai"),_T("terce"),_T("terga"),_T("terms"),
_T("terne"),_T("terns"),_T("terra"),_T("terry"),_T("terse"),_T("tesla"),_T("testa"),_T("tests"),_T("testy"),_T("teths"),
_T("tetra"),_T("teuch"),_T("teugh"),_T("tewed"),_T("texas"),_T("texts"),_T("thack"),_T("thane"),_T("thank"),_T("tharm"),
_T("thaws"),_T("thebe"),_T("theca"),_T("theft"),_T("thegn"),_T("thein"),_T("their"),_T("theme"),_T("thens"),_T("there"),
_T("therm"),_T("these"),_T("theta"),_T("thews"),_T("thewy"),_T("thick"),_T("thief"),_T("thigh"),_T("thill"),_T("thine"),
_T("thing"),_T("think"),_T("thins"),_T("thiol"),_T("third"),_T("thirl"),_T("thole"),_T("thong"),_T("thorn"),_T("thoro"),
_T("thorp"),_T("those"),_T("thous"),_T("thraw"),_T("three"),_T("threw"),_T("thrip"),_T("throb"),_T("throe"),_T("throw"),
_T("thrum"),_T("thuds"),_T("thugs"),_T("thuja"),_T("thumb"),_T("thump"),_T("thunk"),_T("thurl"),_T("thuya"),_T("thyme"),
_T("thymi"),_T("thymy"),_T("tiara"),_T("tibia"),_T("tical"),_T("ticks"),_T("tidal"),_T("tided"),_T("tides"),_T("tiers"),
_T("tiffs"),_T("tiger"),_T("tight"),_T("tigon"),_T("tikes"),_T("tikis"),_T("tilak"),_T("tilde"),_T("tiled"),_T("tiler"),
_T("tiles"),_T("tills"),_T("tilth"),_T("tilts"),_T("timed"),_T("timer"),_T("times"),_T("timid"),_T("tinct"),_T("tinea"),
_T("tined"),_T("tines"),_T("tinge"),_T("tings"),_T("tinny"),_T("tints"),_T("tipis"),_T("tippy"),_T("tipsy"),_T("tired"),
_T("tires"),_T("tirls"),_T("tiros"),_T("titan"),_T("titer"),_T("tithe"),_T("titis"),_T("title"),_T("titre"),_T("titty"),
_T("tizzy"),_T("toads"),_T("toady"),_T("toast"),_T("today"),_T("toddy"),_T("toffs"),_T("toffy"),_T("tofts"),_T("tofus"),
_T("togae"),_T("togas"),_T("togue"),_T("toile"),_T("toils"),_T("toits"),_T("tokay"),_T("toked"),_T("token"),_T("toker"),
_T("tokes"),_T("tolan"),_T("tolas"),_T("toled"),_T("toles"),_T("tolls"),_T("tolus"),_T("tolyl"),_T("toman"),_T("tombs"),
_T("tomes"),_T("tommy"),_T("tonal"),_T("tondi"),_T("tondo"),_T("toned"),_T("toner"),_T("tones"),_T("toney"),_T("tonga"),
_T("tongs"),_T("tonic"),_T("tonne"),_T("tonus"),_T("tools"),_T("toons"),_T("tooth"),_T("toots"),_T("topaz"),_T("toped"),
_T("topee"),_T("toper"),_T("topes"),_T("tophe"),_T("tophi"),_T("tophs"),_T("topic"),_T("topis"),_T("topoi"),_T("topos"),
_T("toque"),_T("torah"),_T("toras"),_T("torch"),_T("torcs"),_T("tores"),_T("toric"),_T("torii"),_T("toros"),_T("torot"),
_T("torse"),_T("torsi"),_T("torsk"),_T("torso"),_T("torte"),_T("torts"),_T("torus"),_T("total"),_T("toted"),_T("totem"),
_T("toter"),_T("totes"),_T("touch"),_T("tough"),_T("tours"),_T("touse"),_T("touts"),_T("towed"),_T("towel"),_T("tower"),
_T("towie"),_T("towns"),_T("towny"),_T("toxic"),_T("toxin"),_T("toyed"),_T("toyer"),_T("toyon"),_T("toyos"),_T("trace"),
_T("track"),_T("tract"),_T("trade"),_T("tragi"),_T("traik"),_T("trail"),_T("train"),_T("trait"),_T("tramp"),_T("trams"),
_T("trank"),_T("tranq"),_T("trans"),_T("traps"),_T("trapt"),_T("trash"),_T("trass"),_T("trave"),_T("trawl"),_T("trays"),
_T("tread"),_T("treat"),_T("treed"),_T("treen"),_T("trees"),_T("treks"),_T("trend"),_T("tress"),_T("trets"),_T("trews"),
_T("treys"),_T("triac"),_T("triad"),_T("trial"),_T("tribe"),_T("trice"),_T("trick"),_T("tried"),_T("trier"),_T("tries"),
_T("trigo"),_T("trigs"),_T("trike"),_T("trill"),_T("trims"),_T("trine"),_T("triol"),_T("trios"),_T("tripe"),_T("trips"),
_T("trite"),_T("troak"),_T("trock"),_T("trode"),_T("trois"),_T("troke"),_T("troll"),_T("tromp"),_T("trona"),_T("trone"),
_T("troop"),_T("trooz"),_T("trope"),_T("troth"),_T("trots"),_T("trout"),_T("trove"),_T("trows"),_T("troys"),_T("truce"),
_T("truck"),_T("trued"),_T("truer"),_T("trues"),_T("trugs"),_T("trull"),_T("truly"),_T("trump"),_T("trunk"),_T("truss"),
_T("trust"),_T("truth"),_T("tryma"),_T("tryst"),_T("tsade"),_T("tsadi"),_T("tsars"),_T("tsked"),_T("tsuba"),_T("tubae"),
_T("tubal"),_T("tubas"),_T("tubby"),_T("tubed"),_T("tuber"),_T("tubes"),_T("tucks"),_T("tufas"),_T("tuffs"),_T("tufts"),
_T("tufty"),_T("tules"),_T("tulip"),_T("tulle"),_T("tumid"),_T("tummy"),_T("tumor"),_T("tumps"),_T("tunas"),_T("tuned"),
_T("tuner"),_T("tunes"),_T("tungs"),_T("tunic"),_T("tunny"),_T("tupik"),_T("tuque"),_T("turbo"),_T("turds"),_T("turfs"),
_T("turfy"),_T("turks"),_T("turns"),_T("turps"),_T("tushy"),_T("tusks"),_T("tutee"),_T("tutor"),_T("tutti"),_T("tutty"),
_T("tutus"),_T("tuxes"),_T("tuyer"),_T("twaes"),_T("twain"),_T("twang"),_T("twats"),_T("tweak"),_T("tweed"),_T("tween"),
_T("tweet"),_T("twerp"),_T("twice"),_T("twier"),_T("twigs"),_T("twill"),_T("twine"),_T("twins"),_T("twiny"),_T("twirl"),
_T("twirp"),_T("twist"),_T("twits"),_T("twixt"),_T("twyer"),_T("tyees"),_T("tyers"),_T("tying"),_T("tykes"),_T("tyned"),
_T("tynes"),_T("typal"),_T("typed"),_T("types"),_T("typey"),_T("typic"),_T("typos"),_T("typps"),_T("tyred"),_T("tyres"),
_T("tyros"),_T("tythe"),_T("tzars"),_T("udder"),_T("uhlan"),_T("ukase"),_T("ulama"),_T("ulans"),_T("ulcer"),_T("ulema"),
_T("ulnad"),_T("ulnae"),_T("ulnar"),_T("ulnas"),_T("ulpan"),_T("ultra"),_T("ulvas"),_T("umbel"),_T("umber"),_T("umbos"),
_T("umbra"),_T("umiac"),_T("umiak"),_T("umiaq"),_T("umped"),_T("unais"),_T("unapt"),_T("unarm"),_T("unary"),_T("unaus"),
_T("unban"),_T("unbar"),_T("unbid"),_T("unbox"),_T("uncap"),_T("uncia"),_T("uncle"),_T("uncos"),_T("uncoy"),_T("uncus"),
_T("uncut"),_T("undee"),_T("under"),_T("undid"),_T("undue"),_T("unfed"),_T("unfit"),_T("unfix"),_T("ungot"),_T("unhat"),
_T("unhip"),_T("unify"),_T("union"),_T("unite"),_T("units"),_T("unity"),_T("unlay"),_T("unled"),_T("unlet"),_T("unlit"),
_T("unman"),_T("unmet"),_T("unmew"),_T("unmix"),_T("unpeg"),_T("unpen"),_T("unpin"),_T("unrig"),_T("unrip"),_T("unsay"),
_T("unset"),_T("unsew"),_T("unsex"),_T("untie"),_T("until"),_T("unwed"),_T("unwit"),_T("unwon"),_T("unzip"),_T("upbow"),
_T("upbye"),_T("updos"),_T("updry"),_T("upend"),_T("uplit"),_T("upped"),_T("upper"),_T("upset"),_T("uraei"),_T("urare"),
_T("urari"),_T("urase"),_T("urate"),_T("urban"),_T("urbia"),_T("ureal"),_T("ureas"),_T("uredo"),_T("ureic"),_T("urged"),
_T("urger"),_T("urges"),_T("urial"),_T("urine"),_T("ursae"),_T("usage"),_T("users"),_T("usher"),_T("using"),_T("usnea"),
_T("usque"),_T("usual"),_T("usurp"),_T("usury"),_T("uteri"),_T("utile"),_T("utter"),_T("uveal"),_T("uveas"),_T("uvula"),
_T("vacua"),_T("vagal"),_T("vague"),_T("vagus"),_T("vails"),_T("vairs"),_T("vakil"),_T("vales"),_T("valet"),_T("valid"),
_T("valor"),_T("valse"),_T("value"),_T("valve"),_T("vamps"),_T("vanda"),_T("vaned"),_T("vanes"),_T("vangs"),_T("vapid"),
_T("vapor"),_T("varas"),_T("varia"),_T("varix"),_T("varna"),_T("varus"),_T("varve"),_T("vasal"),_T("vases"),_T("vasts"),
_T("vasty"),_T("vatic"),_T("vatus"),_T("vault"),_T("vaunt"),_T("veals"),_T("vealy"),_T("veena"),_T("veeps"),_T("veers"),
_T("veery"),_T("vegan"),_T("vegie"),_T("veils"),_T("veins"),_T("veiny"),_T("velar"),_T("velds"),_T("veldt"),_T("velum"),
_T("venae"),_T("venal"),_T("vends"),_T("venge"),_T("venin"),_T("venom"),_T("vents"),_T("venue"),_T("verbs"),_T("verge"),
_T("verse"),_T("verso"),_T("verst"),_T("verts"),_T("vertu"),_T("verve"),_T("vesta"),_T("vests"),_T("vetch"),_T("vexed"),
_T("vexer"),_T("vexes"),_T("vexil"),_T("vials"),_T("viand"),_T("vibes"),_T("vicar"),_T("viced"),_T("vices"),_T("vichy"),
_T("video"),_T("viers"),_T("views"),_T("viewy"),_T("vigas"),_T("vigil"),_T("vigor"),_T("viler"),_T("villa"),_T("villi"),
_T("vills"),_T("vimen"),_T("vinal"),_T("vinas"),_T("vinca"),_T("vined"),_T("vines"),_T("vinic"),_T("vinos"),_T("vinyl"),
_T("viola"),_T("viols"),_T("viper"),_T("viral"),_T("vireo"),_T("vires"),_T("virga"),_T("virid"),_T("virls"),_T("virtu"),
_T("virus"),_T("visas"),_T("vised"),_T("vises"),_T("visit"),_T("visor"),_T("vista"),_T("vitae"),_T("vital"),_T("vitta"),
_T("vivas"),_T("vivid"),_T("vixen"),_T("vizir"),_T("vizor"),_T("vocal"),_T("voces"),_T("vodka"),_T("vodun"),_T("vogie"),
_T("vogue"),_T("voice"),_T("voids"),_T("voila"),_T("voile"),_T("volar"),_T("voled"),_T("voles"),_T("volta"),_T("volte"),
_T("volti"),_T("volts"),_T("volva"),_T("vomer"),_T("vomit"),_T("voted"),_T("voter"),_T("votes"),_T("vouch"),_T("vowed"),
_T("vowel"),_T("vower"),_T("vroom"),_T("vrouw"),_T("vrows"),_T("vuggs"),_T("vuggy"),_T("vughs"),_T("vulgo"),_T("vulva"),
_T("vying"),_T("wacke"),_T("wacko"),_T("wacks"),_T("wacky"),_T("waddy"),_T("waded"),_T("wader"),_T("wades"),_T("wadis"),
_T("wafer"),_T("waffs"),_T("wafts"),_T("waged"),_T("wager"),_T("wages"),_T("wagon"),_T("wahoo"),_T("waifs"),_T("wails"),
_T("wains"),_T("wairs"),_T("waist"),_T("waits"),_T("waive"),_T("waked"),_T("waken"),_T("waker"),_T("wakes"),_T("waled"),
_T("waler"),_T("wales"),_T("walks"),_T("walla"),_T("walls"),_T("wally"),_T("waltz"),_T("wames"),_T("wamus"),_T("wands"),
_T("waned"),_T("wanes"),_T("waney"),_T("wanly"),_T("wants"),_T("wards"),_T("wared"),_T("wares"),_T("warks"),_T("warms"),
_T("warns"),_T("warps"),_T("warts"),_T("warty"),_T("washy"),_T("wasps"),_T("waspy"),_T("waste"),_T("wasts"),_T("watap"),
_T("watch"),_T("water"),_T("watts"),_T("waugh"),_T("wauks"),_T("wauls"),_T("waved"),_T("waver"),_T("waves"),_T("wavey"),
_T("wawls"),_T("waxed"),_T("waxen"),_T("waxer"),_T("waxes"),_T("weald"),_T("weals"),_T("weans"),_T("wears"),_T("weary"),
_T("weave"),_T("webby"),_T("weber"),_T("wecht"),_T("wedel"),_T("wedge"),_T("wedgy"),_T("weeds"),_T("weedy"),_T("weeks"),
_T("weens"),_T("weeny"),_T("weeps"),_T("weepy"),_T("weest"),_T("weets"),_T("wefts"),_T("weigh"),_T("weird"),_T("weirs"),
_T("wekas"),_T("welch"),_T("welds"),_T("wells"),_T("welly"),_T("welsh"),_T("welts"),_T("wench"),_T("wends"),_T("wenny"),
_T("wests"),_T("wetly"),_T("whack"),_T("whale"),_T("whamo"),_T("whams"),_T("whang"),_T("whaps"),_T("wharf"),_T("whats"),
_T("whaup"),_T("wheal"),_T("wheat"),_T("wheel"),_T("wheen"),_T("wheep"),_T("whelk"),_T("whelm"),_T("whelp"),_T("whens"),
_T("where"),_T("whets"),_T("whews"),_T("wheys"),_T("which"),_T("whids"),_T("whiff"),_T("whigs"),_T("while"),_T("whims"),
_T("whine"),_T("whins"),_T("whiny"),_T("whips"),_T("whipt"),_T("whirl"),_T("whirr"),_T("whirs"),_T("whish"),_T("whisk"),
_T("whist"),_T("white"),_T("whits"),_T("whity"),_T("whizz"),_T("whole"),_T("whomp"),_T("whoof"),_T("whoop"),_T("whops"),
_T("whore"),_T("whorl"),_T("whort"),_T("whose"),_T("whoso"),_T("whump"),_T("wicks"),_T("widdy"),_T("widen"),_T("wider"),
_T("wides"),_T("widow"),_T("width"),_T("wield"),_T("wifed"),_T("wifes"),_T("wifty"),_T("wigan"),_T("wiggy"),_T("wight"),
_T("wilco"),_T("wilds"),_T("wiled"),_T("wiles"),_T("wills"),_T("willy"),_T("wilts"),_T("wimps"),_T("wimpy"),_T("wince"),
_T("winch"),_T("winds"),_T("windy"),_T("wined"),_T("wines"),_T("winey"),_T("wings"),_T("wingy"),_T("winks"),_T("winos"),
_T("winze"),_T("wiped"),_T("wiper"),_T("wipes"),_T("wired"),_T("wirer"),_T("wires"),_T("wirra"),_T("wised"),_T("wiser"),
_T("wises"),_T("wisha"),_T("wisps"),_T("wispy"),_T("wists"),_T("witan"),_T("witch"),_T("wited"),_T("wites"),_T("withe"),
_T("withy"),_T("witty"),_T("wived"),_T("wiver"),_T("wives"),_T("wizen"),_T("wizes"),_T("woads"),_T("woald"),_T("wodge"),
_T("woful"),_T("woken"),_T("wolds"),_T("wolfs"),_T("woman"),_T("wombs"),_T("womby"),_T("women"),_T("wonks"),_T("wonky"),
_T("wonts"),_T("woods"),_T("woody"),_T("wooed"),_T("wooer"),_T("woofs"),_T("wools"),_T("wooly"),_T("woops"),_T("woosh"),
_T("woozy"),_T("words"),_T("wordy"),_T("works"),_T("world"),_T("worms"),_T("wormy"),_T("worry"),_T("worse"),_T("worst"),
_T("worth"),_T("worts"),_T("would"),_T("wound"),_T("woven"),_T("wowed"),_T("wrack"),_T("wrang"),_T("wraps"),_T("wrapt"),
_T("wrath"),_T("wreak"),_T("wreck"),_T("wrens"),_T("wrest"),_T("wrick"),_T("wried"),_T("wrier"),_T("wries"),_T("wring"),
_T("wrist"),_T("write"),_T("writs"),_T("wrong"),_T("wrote"),_T("wroth"),_T("wrung"),_T("wryer"),_T("wryly"),_T("wurst"),
_T("wussy"),_T("wyled"),_T("wyles"),_T("wynds"),_T("wynns"),_T("wyted"),_T("wytes"),_T("xebec"),_T("xenia"),_T("xenic"),
_T("xenon"),_T("xeric"),_T("xerox"),_T("xerus"),_T("xylan"),_T("xylem"),_T("xylol"),_T("xylyl"),_T("xysti"),_T("xysts"),
_T("yacht"),_T("yacks"),_T("yaffs"),_T("yager"),_T("yagis"),_T("yahoo"),_T("yaird"),_T("yamen"),_T("yamun"),_T("yangs"),
_T("yanks"),_T("yapok"),_T("yapon"),_T("yards"),_T("yarer"),_T("yarns"),_T("yauds"),_T("yauld"),_T("yaups"),_T("yawed"),
_T("yawls"),_T("yawns"),_T("yawps"),_T("yeans"),_T("yearn"),_T("years"),_T("yeast"),_T("yecch"),_T("yechs"),_T("yechy"),
_T("yeggs"),_T("yelks"),_T("yells"),_T("yelps"),_T("yenta"),_T("yente"),_T("yerba"),_T("yerks"),_T("yeses"),_T("yetis"),
_T("yetts"),_T("yeuks"),_T("yeuky"),_T("yield"),_T("yikes"),_T("yills"),_T("yince"),_T("yipes"),_T("yirds"),_T("yirrs"),
_T("yirth"),_T("ylems"),_T("yobbo"),_T("yocks"),_T("yodel"),_T("yodhs"),_T("yodle"),_T("yogas"),_T("yogee"),_T("yoghs"),
_T("yogic"),_T("yogin"),_T("yogis"),_T("yoked"),_T("yokel"),_T("yokes"),_T("yolks"),_T("yolky"),_T("yomim"),_T("yonic"),
_T("yonis"),_T("yores"),_T("young"),_T("yourn"),_T("yours"),_T("youse"),_T("youth"),_T("yowed"),_T("yowes"),_T("yowie"),
_T("yowls"),_T("yuans"),_T("yucas"),_T("yucca"),_T("yucch"),_T("yucks"),_T("yucky"),_T("yugas"),_T("yulan"),_T("yules"),
_T("yummy"),_T("yupon"),_T("yurta"),_T("yurts"),_T("zaire"),_T("zamia"),_T("zanza"),_T("zappy"),_T("zarfs"),_T("zaxes"),
_T("zayin"),_T("zazen"),_T("zeals"),_T("zebec"),_T("zebra"),_T("zebus"),_T("zeins"),_T("zerks"),_T("zeros"),_T("zests"),
_T("zesty"),_T("zetas"),_T("zibet"),_T("zilch"),_T("zills"),_T("zincs"),_T("zincy"),_T("zineb"),_T("zings"),_T("zingy"),
_T("zinky"),_T("zippy"),_T("ziram"),_T("zitis"),_T("zizit"),_T("zlote"),_T("zloty"),_T("zoeae"),_T("zoeal"),_T("zoeas"),
_T("zombi"),_T("zonal"),_T("zoned"),_T("zoner"),_T("zones"),_T("zonks"),_T("zooid"),_T("zooks"),_T("zooms"),_T("zoons"),
_T("zooty"),_T("zoril"),_T("zoris"),_T("zowie"),_T("zymes"),
0};
| 120.344074 | 120 | 0.578644 | [
"shape",
"model",
"solid"
] |
37d06b7274bb0894051f98fdd51d5b23d136615e | 2,308 | cpp | C++ | 23-mergeKLists.cpp | zjukk/LeetCode-is-my-son | d8851bd2a76f77e4bec89c6a5947acb435fff074 | [
"Apache-2.0"
] | null | null | null | 23-mergeKLists.cpp | zjukk/LeetCode-is-my-son | d8851bd2a76f77e4bec89c6a5947acb435fff074 | [
"Apache-2.0"
] | 1 | 2019-08-15T16:55:04.000Z | 2019-08-15T16:55:04.000Z | 23-mergeKLists.cpp | zjukk/LeetCode-is-my-son | d8851bd2a76f77e4bec89c6a5947acb435fff074 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <limits>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
public:
//sol1:Brute force
ListNode* mergeLists(vector<ListNode*>& lists) {
ListNode* ans = new ListNode(0);
ListNode* res = ans;
vector<int> v;
for (int i = 0; i < lists.size(); i++) {
while (lists[i] != NULL) {
v.push_back(lists[i]->val);
lists[i] = lists[i]->next;
}
}
stable_sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++) {
ans->next = new ListNode(v[i]);
ans = ans->next;
}
return res->next;
}
//sol2:recursion divide&conquer
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(0);
ListNode* res = ans;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
ans->next = l1;
l1 = l1->next;
ans = ans->next;
} else {
ans->next = l2;
l2 = l2->next;
ans = ans->next;
}
}
while (l1 != NULL) {
ans->next = l1;
l1 = l1->next;
ans = ans->next;
}
while (l2 != NULL) {
ans->next = l2;
l2 = l2->next;
ans = ans->next;
}
return res->next;
}
ListNode* process(vector<ListNode*>& lists, int L, int R) {
int mid = (L+R)/2;
ListNode* leftNode = process(lists, L, mid);
ListNode* rightNode = process(lists, mid+1, right);
return mergeTwoLisrs(leftNode,rightNode);
}
ListNode* mergeLists2(vector<ListNode*>& lists) {
return process(lists, 0, lists.size() - 1);
}
//sol3:
ListNode* mergeKLists3(vector<ListNode*>& lists) {
if(lists.size() == 0)
return NULL;
if (lists.size() == 1)
return lists[0];
ListNode* ans = mergeTwoLists(lists[0], lists[1]);
for (int i = 2; i < lists.size(); i++) {
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
} | 28.493827 | 63 | 0.470971 | [
"vector"
] |
37d6ae94a8e3a9303ac1bd1252570a3f0ecf4315 | 491 | cpp | C++ | Problemset/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2020-10-06T01:06:45.000Z | 2020-10-06T01:06:45.000Z | Problemset/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | null | null | null | Problemset/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2021-11-17T13:52:51.000Z | 2021-11-17T13:52:51.000Z |
// @Title: 数组中数字出现的次数 (数组中数字出现的次数 LCOF)
// @Author: Singularity0909
// @Date: 2020-07-20 02:39:10
// @Runtime: 36 ms
// @Memory: 15.7 MB
class Solution {
public:
vector<int> singleNumbers(vector<int>& nums)
{
int res = 0;
for (int n : nums) res ^= n;
int a = 0, b = 0, mask = 1;
while ((mask & res) == 0) mask <<= 1;
for (int n : nums) {
if (n & mask) a ^= n;
else b ^= n;
}
return { a, b };
}
};
| 21.347826 | 48 | 0.468432 | [
"vector"
] |
37dfd6e463814e2a2149cc7d95d839bc9e725ef9 | 3,133 | hpp | C++ | ThirdParty-mod/java2cpp/java/lang/TypeNotPresentException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/lang/TypeNotPresentException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/lang/TypeNotPresentException.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.lang.TypeNotPresentException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_DECL
#define J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class RuntimeException; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Throwable; } } }
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/Throwable.hpp>
namespace j2cpp {
namespace java { namespace lang {
class TypeNotPresentException;
class TypeNotPresentException
: public object<TypeNotPresentException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit TypeNotPresentException(jobject jobj)
: object<TypeNotPresentException>(jobj)
{
}
operator local_ref<java::lang::RuntimeException>() const;
TypeNotPresentException(local_ref< java::lang::String > const&, local_ref< java::lang::Throwable > const&);
local_ref< java::lang::String > typeName();
}; //class TypeNotPresentException
} //namespace lang
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_IMPL
#define J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_IMPL
namespace j2cpp {
java::lang::TypeNotPresentException::operator local_ref<java::lang::RuntimeException>() const
{
return local_ref<java::lang::RuntimeException>(get_jobject());
}
java::lang::TypeNotPresentException::TypeNotPresentException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Throwable > const &a1)
: object<java::lang::TypeNotPresentException>(
call_new_object<
java::lang::TypeNotPresentException::J2CPP_CLASS_NAME,
java::lang::TypeNotPresentException::J2CPP_METHOD_NAME(0),
java::lang::TypeNotPresentException::J2CPP_METHOD_SIGNATURE(0)
>(a0, a1)
)
{
}
local_ref< java::lang::String > java::lang::TypeNotPresentException::typeName()
{
return call_method<
java::lang::TypeNotPresentException::J2CPP_CLASS_NAME,
java::lang::TypeNotPresentException::J2CPP_METHOD_NAME(1),
java::lang::TypeNotPresentException::J2CPP_METHOD_SIGNATURE(1),
local_ref< java::lang::String >
>(get_jobject());
}
J2CPP_DEFINE_CLASS(java::lang::TypeNotPresentException,"java/lang/TypeNotPresentException")
J2CPP_DEFINE_METHOD(java::lang::TypeNotPresentException,0,"<init>","(Ljava/lang/String;Ljava/lang/Throwable;)V")
J2CPP_DEFINE_METHOD(java::lang::TypeNotPresentException,1,"typeName","()Ljava/lang/String;")
} //namespace j2cpp
#endif //J2CPP_JAVA_LANG_TYPENOTPRESENTEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 29.838095 | 150 | 0.719438 | [
"object"
] |
37e240d71d8a53a0a256043ee6b26e2c6f6184bd | 1,967 | cpp | C++ | src/control_system/src/lqr_controller.cpp | duckstarr/controller | ed8020a4ba010981a6ea7377f39f0d1490359450 | [
"MIT"
] | 7 | 2021-05-15T21:58:46.000Z | 2022-02-03T04:34:54.000Z | src/control_system/src/lqr_controller.cpp | duckstarr/controller | ed8020a4ba010981a6ea7377f39f0d1490359450 | [
"MIT"
] | null | null | null | src/control_system/src/lqr_controller.cpp | duckstarr/controller | ed8020a4ba010981a6ea7377f39f0d1490359450 | [
"MIT"
] | null | null | null | /**
* @file lqr_controller.cpp
* @brief Infinite-horizon Linear Quadratic Regulator.
*
*/
#include <lqr_controller.hpp>
#include <Eigen/Dense>
using namespace controller;
LQR::LQR(
const Eigen::MatrixXd& Q,
const Eigen::MatrixXd& R
):
Q(Q),
R(R)
{
P.setZero(Q.rows(), Q.cols());
cmd_vel.setZero(1, R.rows()); // [translation rate, rotation rate].
}
Eigen::MatrixXd LQR::computeHamiltonian(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E)
{
// Set Hamilton matrix.
Ham = Eigen::MatrixXd::Zero(2 * A.rows(), 2 * A.rows());
Ham << A, -B * R.inverse() * B.transpose(), -Q, -A.transpose();
// Get eigenvalues and eigenvectors from Hamilton matrix.
Eigen::EigenSolver<Eigen::MatrixXd> eigen(Ham);
// Form a 2nxn matrix whos columns from a basis of the corresponding subspace.
Eigen::MatrixXcd eigenVec = Eigen::MatrixXcd::Zero(2 * A.rows(), A.rows());
// Iterate over the Hamilton matrix and extract a stable Eigenvector.
int j = 0;
for(unsigned int i = 0; i < 2 * A.rows(); ++i)
{
// Get the negative real part: a stable value in the Laplace domain.
if(eigen.eigenvalues()[i].real() < 0)
{
eigenVec.col(j) = eigen.eigenvectors().block(0, i, 2 * A.rows(), 1);
++j;
}
}
// Compute the solution to the Riccati equation.
Eigen::MatrixXcd U11, U21;
U11 = eigenVec.block(0, 0, A.rows(), A.rows());
U21 = eigenVec.block(A.rows(), 0, A.rows(), A.rows());
P = (U21 * U11.inverse()).real();
// Update LQR gain.
K = R.inverse() * B.transpose() * P;
controlUpdate = K * E;
// Compute magnitude of velocity vector.
cmd_vel <<
sqrt(pow(controlUpdate(0, 0), 2.0) + pow(controlUpdate(0, 1), 2.0) + pow(controlUpdate(0, 2), 2.0)),
sqrt(pow(controlUpdate(1, 0), 2.0) + pow(controlUpdate(1, 1), 2.0) + pow(controlUpdate(1, 2), 2.0));
return cmd_vel;
} | 30.734375 | 117 | 0.601423 | [
"vector"
] |
37e39641c833cf202d3d6dba92323fd8e9cd4e10 | 11,626 | cpp | C++ | LibFoundation/ComputationalGeometry/Wm4TriangulateEC.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | LibFoundation/ComputationalGeometry/Wm4TriangulateEC.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | LibFoundation/ComputationalGeometry/Wm4TriangulateEC.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4FoundationPCH.h"
#include "Wm4TriangulateEC.h"
#include "Wm4Query2Filtered.h"
#include "Wm4Query2Int64.h"
#include "Wm4Query2TInteger.h"
#include "Wm4Query2TRational.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
TriangulateEC<Real>::TriangulateEC (int iQuantity,
const Vector2<Real>* akPosition, Query::Type eQueryType, Real fEpsilon,
int*& raiIndex)
{
assert(iQuantity >= 3 && akPosition);
if (eQueryType == Query::QT_FILTERED)
{
assert((Real)0.0 <= fEpsilon && fEpsilon <= (Real)1.0);
}
Vector2<Real>* akSPosition = 0;
Vector2<Real> kMin, kMax, kRange;
Real fScale;
int i;
switch (eQueryType)
{
case Query::QT_INT64:
// Transform the vertices to the square [0,2^{20}]^2.
Vector2<Real>::ComputeExtremes(iQuantity,akPosition,kMin,kMax);
kRange = kMax - kMin;
fScale = (kRange[0] >= kRange[1] ? kRange[0] : kRange[1]);
fScale *= (Real)(1 << 20);
akSPosition = WM4_NEW Vector2<Real>[iQuantity];
for (i = 0; i < iQuantity; i++)
{
akSPosition[i] = (akPosition[i] - kMin)*fScale;
}
m_pkQuery = WM4_NEW Query2Int64<Real>(iQuantity,akSPosition);
break;
case Query::QT_INTEGER:
// Transform the vertices to the square [0,2^{24}]^2.
Vector2<Real>::ComputeExtremes(iQuantity,akPosition,kMin,kMax);
kRange = kMax - kMin;
fScale = (kRange[0] >= kRange[1] ? kRange[0] : kRange[1]);
fScale *= (Real)(1 << 24);
akSPosition = WM4_NEW Vector2<Real>[iQuantity];
for (i = 0; i < iQuantity; i++)
{
akSPosition[i] = (akPosition[i] - kMin)*fScale;
}
m_pkQuery = WM4_NEW Query2TInteger<Real>(iQuantity,akSPosition);
break;
case Query::QT_REAL:
// Transform the vertices to the square [0,1]^2.
Vector2<Real>::ComputeExtremes(iQuantity,akPosition,kMin,kMax);
kRange = kMax - kMin;
fScale = (kRange[0] >= kRange[1] ? kRange[0] : kRange[1]);
akSPosition = WM4_NEW Vector2<Real>[iQuantity];
for (i = 0; i < iQuantity; i++)
{
akSPosition[i] = (akPosition[i] - kMin)*fScale;
}
m_pkQuery = WM4_NEW Query2<Real>(iQuantity,akSPosition);
break;
case Query::QT_RATIONAL:
// No transformation of the input data.
m_pkQuery = WM4_NEW Query2TRational<Real>(iQuantity,akPosition);
break;
case Query::QT_FILTERED:
// No transformation of the input data.
m_pkQuery = WM4_NEW Query2Filtered<Real>(iQuantity,akPosition,
fEpsilon);
break;
}
int iQm1 = iQuantity - 1;
raiIndex = WM4_NEW int[3*iQm1];
int* piIndex = raiIndex;
m_akVertex = WM4_NEW Vertex[iQuantity];
m_iCFirst = -1;
m_iCLast = -1;
m_iRFirst = -1;
m_iRLast = -1;
m_iEFirst = -1;
m_iELast = -1;
// Create a circular list of the polygon vertices for dynamic removal of
// vertices. Keep track of two linear sublists, one for the convex
// vertices and one for the reflex vertices. This is an O(N) process
// where N is the number of polygon vertices.
for (i = 0; i <= iQm1; i++)
{
// link the vertices
Vertex& rkV = V(i);
rkV.VPrev = (i > 0 ? i-1 : iQm1);
rkV.VNext = (i < iQm1 ? i+1 : 0);
// link the convex/reflex vertices
if (IsConvex(i))
{
InsertAfterC(i);
}
else
{
InsertAfterR(i);
}
}
if (m_iRFirst == -1)
{
// polygon is convex, just triangle fan it
for (i = 1; i < iQm1; i++)
{
*piIndex++ = 0;
*piIndex++ = i;
*piIndex++ = i+1;
}
return;
}
// Identify the ears and build a circular list of them. Let V0, V1, and
// V2 be consecutive vertices forming a triangle T. The vertex V1 is an
// ear if no other vertices of the polygon lie inside T. Although it is
// enough to show that V1 is not an ear by finding at least one other
// vertex inside T, it is sufficient to search only the reflex vertices.
// This is an O(C*R) process where C is the number of convex vertices and
// R is the number of reflex vertices, N = C+R. The order is O(N^2), for
// example when C = R = N/2.
for (i = m_iCFirst; i != -1; i = V(i).SNext)
{
if (IsEar(i))
{
InsertEndE(i);
}
}
V(m_iEFirst).EPrev = m_iELast;
V(m_iELast).ENext = m_iEFirst;
// Remove the ears, one at a time.
while (true)
{
// add triangle of ear to output
int iVPrev = V(m_iEFirst).VPrev;
int iVNext = V(m_iEFirst).VNext;
*piIndex++ = iVPrev;
*piIndex++ = m_iEFirst;
*piIndex++ = iVNext;
// remove the vertex corresponding to the ear
RemoveV(m_iEFirst);
if (--iQuantity == 3)
{
// Only one triangle remains, just remove the ear and copy it.
RemoveE();
iVPrev = V(m_iEFirst).VPrev;
iVNext = V(m_iEFirst).VNext;
*piIndex++ = iVPrev;
*piIndex++ = m_iEFirst;
*piIndex++ = iVNext;
break;
}
// removal of the ear can cause an adjacent vertex to become an ear
bool bWasReflex;
Vertex& rkVPrev = V(iVPrev);
if (!rkVPrev.IsEar)
{
bWasReflex = !rkVPrev.IsConvex;
if (IsConvex(iVPrev))
{
if (bWasReflex)
{
RemoveR(iVPrev);
}
if (IsEar(iVPrev))
{
InsertBeforeE(iVPrev);
}
}
}
Vertex& rkVNext = V(iVNext);
if (!rkVNext.IsEar)
{
bWasReflex = !rkVNext.IsConvex;
if (IsConvex(iVNext))
{
if (bWasReflex)
{
RemoveR(iVNext);
}
if (IsEar(iVNext))
{
InsertAfterE(iVNext);
}
}
}
// remove the ear
RemoveE();
}
WM4_DELETE[] akSPosition;
WM4_DELETE m_pkQuery;
}
//----------------------------------------------------------------------------
template <class Real>
TriangulateEC<Real>::~TriangulateEC ()
{
}
//----------------------------------------------------------------------------
template <class Real>
bool TriangulateEC<Real>::IsConvex (int i)
{
Vertex& rkV = V(i);
rkV.IsConvex = (m_pkQuery->ToLine(i,rkV.VPrev,rkV.VNext) > 0);
return rkV.IsConvex;
}
//----------------------------------------------------------------------------
template <class Real>
bool TriangulateEC<Real>::IsEar (int i)
{
Vertex& rkV = V(i);
if (m_iRFirst == -1)
{
// The remaining polygon is convex.
rkV.IsEar = true;
return true;
}
// Search the reflex vertices and test if any are in the triangle
// <V[prev],V[i],V[next]>.
rkV.IsEar = true;
for (int j = m_iRFirst; j != -1; j = V(j).SNext)
{
if (m_pkQuery->ToTriangle(j,rkV.VPrev,i,rkV.VNext) < 0)
{
rkV.IsEar = false;
break;
}
}
return rkV.IsEar;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::InsertAfterC (int i)
{
if (m_iCFirst == -1)
{
// add first convex vertex
m_iCFirst = i;
}
else
{
V(m_iCLast).SNext = i;
V(i).SPrev = m_iCLast;
}
m_iCLast = i;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::InsertAfterR (int i)
{
if (m_iRFirst == -1)
{
// add first reflex vertex
m_iRFirst = i;
}
else
{
V(m_iRLast).SNext = i;
V(i).SPrev = m_iRLast;
}
m_iRLast = i;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::InsertEndE (int i)
{
if (m_iEFirst == -1)
{
// add first ear
m_iEFirst = i;
m_iELast = i;
}
V(m_iELast).ENext = i;
V(i).EPrev = m_iELast;
m_iELast = i;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::InsertAfterE (int i)
{
Vertex& rkVFirst = V(m_iEFirst);
int iCurrENext = rkVFirst.ENext;
Vertex& rkV = V(i);
rkV.EPrev = m_iEFirst;
rkV.ENext = iCurrENext;
rkVFirst.ENext = i;
V(iCurrENext).EPrev = i;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::InsertBeforeE (int i)
{
Vertex& rkVFirst = V(m_iEFirst);
int iCurrEPrev = rkVFirst.EPrev;
Vertex& rkV = V(i);
rkV.EPrev = iCurrEPrev;
rkV.ENext = m_iEFirst;
rkVFirst.EPrev = i;
V(iCurrEPrev).ENext = i;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::RemoveV (int i)
{
int iCurrVPrev = V(i).VPrev;
int iCurrVNext = V(i).VNext;
V(iCurrVPrev).VNext = iCurrVNext;
V(iCurrVNext).VPrev = iCurrVPrev;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::RemoveE ()
{
int iCurrEPrev = V(m_iEFirst).EPrev;
int iCurrENext = V(m_iEFirst).ENext;
V(iCurrEPrev).ENext = iCurrENext;
V(iCurrENext).EPrev = iCurrEPrev;
m_iEFirst = iCurrENext;
}
//----------------------------------------------------------------------------
template <class Real>
void TriangulateEC<Real>::RemoveR (int i)
{
assert(m_iRFirst != -1 && m_iRLast != -1);
if (i == m_iRFirst)
{
m_iRFirst = V(i).SNext;
if (m_iRFirst != -1)
{
V(m_iRFirst).SPrev = -1;
}
V(i).SNext = -1;
}
else if (i == m_iRLast)
{
m_iRLast = V(i).SPrev;
if (m_iRLast != -1)
{
V(m_iRLast).SNext = -1;
}
V(i).SPrev = -1;
}
else
{
int iCurrSPrev = V(i).SPrev;
int iCurrSNext = V(i).SNext;
V(iCurrSPrev).SNext = iCurrSNext;
V(iCurrSNext).SPrev = iCurrSPrev;
V(i).SNext = -1;
V(i).SPrev = -1;
}
}
//----------------------------------------------------------------------------
template <class Real>
typename TriangulateEC<Real>::Vertex& TriangulateEC<Real>::V (int i)
{
return m_akVertex[i];
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_FOUNDATION_ITEM
class TriangulateEC<float>;
template WM4_FOUNDATION_ITEM
class TriangulateEC<double>;
//----------------------------------------------------------------------------
}
| 28.848635 | 78 | 0.493119 | [
"transform"
] |
37f12ce004332428d588347dd3010ace0495e357 | 10,281 | cpp | C++ | addons/ofxGuido/lib/guidolib-code/src/graphic/GRMeter.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 18 | 2015-01-18T22:34:22.000Z | 2020-09-06T20:30:30.000Z | addons/ofxGuido/lib/guidolib-code/src/graphic/GRMeter.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 2 | 2015-08-04T00:07:46.000Z | 2017-05-10T15:53:51.000Z | addons/ofxGuido/lib/guidolib-code/src/graphic/GRMeter.cpp | k4rm/AscoGraph | 9038ae785b6f4f144a3ab5c4c5520761c0cd08f2 | [
"MIT"
] | 10 | 2015-01-18T23:46:10.000Z | 2019-08-25T12:10:04.000Z | /*
GUIDO Library
Copyright (C) 2002 Holger Hoos, Juergen Kilian, Kai Renz
Copyright (C) 2002-2013 Grame
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
research@grame.fr
*/
#include <iostream>
#include <sstream>
#include <string.h>
#include "GRMeter.h"
#include "GRDefine.h"
#include "GRMusic.h"
#include "GRStaff.h"
#include "VGDevice.h"
#include "VGFont.h"
#include "GUIDOInternal.h" // for gGlobalSettings.gDevice
#include "FontManager.h"
#include "secureio.h"
using namespace std;
NVPoint GRMeter::refposC;
NVPoint GRMeter::refposC2;
GRMeter::GRMeter( ARMeter * abstractRepresentationOfMeter, GRStaff * curstaff, bool p_ownsAR )
: GRTagARNotationElement(abstractRepresentationOfMeter, curstaff->getStaffLSPACE(),p_ownsAR),
numerator(0), denominator(1)
{
assert(abstractRepresentationOfMeter);
assert(curstaff);
curLSPACE = curstaff->getStaffLSPACE();
mtype = getARMeter()->getMeterType();
if (mtype == ARMeter::NUMERIC)
{
numeratorsVector = getARMeter()->getNumeratorsVector();
denominator = getARMeter()->getDenominator();
}
numerator = getARMeter()->getNumerator();
//spacing= LSPACE;
mNeedsSpring = 1;
sconst = SCONST_METER;
// obsolete
// spacing = 0;
mBoundingBox.left = 0;
mBoundingBox.top = 0;
float extent = 0;
if (mtype == ARMeter::NUMERIC)
{
std::stringstream bufferDenominatorSStream;
bufferDenominatorSStream << denominator;
std::string bufferDenominator = bufferDenominatorSStream.str();
std::vector<float> extentsNumeratorsVector;
float extentDenominator = 0;
float x = 0, y = 0;
float extentPlus = 0;
if (numeratorsVector.size() > 1)
{
char bufferPlus = '+';
FontManager::gFontScriab->GetExtent(bufferPlus, &x, &y, gGlobalSettings.gDevice );
extentPlus = x;
}
if( gGlobalSettings.gDevice )
{
for(size_t i = 0; i < numeratorsVector.size(); i++)
{
if (i)
extentsNumeratorsVector.push_back(extentPlus);
std::stringstream bufferNumeratorTmpSStream;
bufferNumeratorTmpSStream << numeratorsVector[i];
std::string bufferNumeratorTmp = bufferNumeratorTmpSStream.str();
FontManager::gFontScriab->GetExtent(bufferNumeratorTmp.c_str(), bufferNumeratorTmp.size(), &x, &y, gGlobalSettings.gDevice);
bufferNumeratorTmpSStream.clear();
extentsNumeratorsVector.push_back(x);
}
FontManager::gFontScriab->GetExtent(bufferDenominator.c_str(), bufferDenominator.size(), &x, &y, gGlobalSettings.gDevice);
extentDenominator = x;
}
totalNumeratorExtent = 0;
for(size_t i = 0; i < extentsNumeratorsVector.size(); i++)
totalNumeratorExtent += extentsNumeratorsVector[i];
extent = totalNumeratorExtent > extentDenominator ? totalNumeratorExtent : extentDenominator;
mBoundingBox.left = (GCoord)(-extent * 0.5f - LSPACE / 5);
mBoundingBox.right = (GCoord)(extent * 0.5f + LSPACE);
}
else if (mtype == ARMeter::C || mtype == ARMeter::C2)
{
extent = GetSymbolExtent( kCSymbol);
mBoundingBox.left = (GCoord)(-extent * 0.5f - LSPACE / 5);
mBoundingBox.right = (GCoord)(extent * 0.5f + LSPACE);
}
mTagSize *= curstaff->getSizeRatio() * abstractRepresentationOfMeter->getSize();
mBoundingBox.bottom = (GCoord)(5*curLSPACE);
// set leftSpace, rightSpace
mLeftSpace = (GCoord)(- mBoundingBox.left * 2 * mTagSize);
mRightSpace = 100; //hardcoded -> initially was (GCoord)(mBoundingBox.right * mTagSize)
switch (mtype)
{
case ARMeter::C :
refposC.x = (GCoord)(- extent * 0.5f - LSPACE / 5.0);
refposC.y = (GCoord)(2*LSPACE); // no break ?
case ARMeter::C2:
refposC2.x = (GCoord)(- extent * 0.5f - LSPACE / 5.0);
refposC2.y = (GCoord)(2*LSPACE); // no break
case ARMeter::NUMERIC:
refpos.x = (GCoord)(- extent * 0.5f - LSPACE / 5.0);
refpos.y = 0;
break;
default:
break;
}
// y position correction according to staff lines count - DF sept. 23 2009
if( curstaff ) {
const float curLSPACE = curstaff->getStaffLSPACE();
int linesOffset = curstaff->getNumlines() - 5;
if (linesOffset) {
mPosition.y += curLSPACE * linesOffset / 2;
}
}
// what about reference-position?
}
GRMeter::~GRMeter()
{
}
void GRMeter::GGSOutput() const
{
char buffer[20];
char buf[100];
if (error) return;
if (mtype == ARMeter::NUMERIC)
{
snprintf(buf,100,"\\draw_image<\"%d\",%ld,%d,%d>\n",
numerator,
getID(),
(int)(mPosition.x + ggsoffsetx),
(int)(LSPACE + ggsoffsety));
AddGGSOutput(buf);
snprintf(buf,100,"\\draw_image<\"%d\",%ld,%d,%d>\n",
denominator,
getID(),
(int)(mPosition.x + ggsoffsetx),
(int)(3*LSPACE + ggsoffsety));
AddGGSOutput(buf);
}
else if (mtype == ARMeter::C)
{
snprintf(buffer,20,"c" /*SCR_ALLABREVE*/ );
snprintf(buf,100,"\\draw_image<\"%s\",%ld,%d,%d>\n",
buffer,
getID(),
(int)(mPosition.x + ggsoffsetx),
(int)(mPosition.y + 2 * LSPACE + ggsoffsety));
AddGGSOutput(buf);
}
else if (mtype == ARMeter::C2)
{
snprintf(buffer,20,"C" /* SCR_ALLABREVE2 */ );
snprintf(buf,100,"\\draw_image<\"%s\",%ld,%d,%d>\n",
buffer,
getID(),
(int)(mPosition.x + ggsoffsetx),
(int)(mPosition.y + 2 * LSPACE + ggsoffsety));
AddGGSOutput(buf);
}
}
void GRMeter::OnDraw(VGDevice & hdc) const
{
if (error) return;
if(!mDraw)
return;
if (mtype == ARMeter::NUMERIC)
{
/**** Numerator ****/
float currentDx = 0;
float totalExtent = mBoundingBox.right - mBoundingBox.left;
float emptyNumeratorSpace;
bool hastwo = false;
const char charPlus= '+';
float extentCharPlusx;
float extentCharPlusy;
FontManager::gFontScriab->GetExtent(charPlus, &extentCharPlusx, &extentCharPlusy, gGlobalSettings.gDevice );
float dx2 = 0;
for (size_t i = 0; i < numeratorsVector.size(); i++)
{
if (i == 0)
{
emptyNumeratorSpace = totalExtent - totalNumeratorExtent;
currentDx = mBoundingBox.left + emptyNumeratorSpace / 2;
}
else
{
OnDrawSymbol(hdc, charPlus, currentDx, curLSPACE, mTagSize);
currentDx += extentCharPlusx;
}
std::stringstream bufferSStream;
bufferSStream << numeratorsVector[i];
std::string buffer = bufferSStream.str();
float extentBufferx;
float extentBuffery;
FontManager::gFontScriab->GetExtent(buffer.c_str(), buffer.size(), &extentBufferx, &extentBuffery, gGlobalSettings.gDevice );
if (numerator > 9)
{
hastwo = true;
float extentFirstCharx;
float extentFirstChary;
FontManager::gFontScriab->GetExtent(buffer.c_str()[0], &extentFirstCharx, &extentFirstChary, gGlobalSettings.gDevice );
dx2 = currentDx + extentFirstCharx;
}
OnDrawSymbol(hdc, buffer.c_str()[0], currentDx, curLSPACE, mTagSize);
if (buffer.c_str()[1])
OnDrawSymbol(hdc, buffer.c_str()[1], dx2, curLSPACE, mTagSize);
currentDx += extentBufferx;
}
/*******************/
/**** Denominator ****/
std::stringstream bufferSStream;
bufferSStream << denominator;
std::string buffer = bufferSStream.str();
dx2 = 0;
float extentBufferx;
float extentBuffery;
FontManager::gFontScriab->GetExtent(buffer.c_str(), buffer.size(), &extentBufferx, &extentBuffery, gGlobalSettings.gDevice );
float emptyDenominatorSpace = totalExtent - extentBufferx;
currentDx = mBoundingBox.left + emptyDenominatorSpace / 2;
if (denominator > 9)
{
hastwo = true;
float extentFirstCharx;
float extentFirstChary;
FontManager::gFontScriab->GetExtent(buffer.c_str()[0], &extentFirstCharx, &extentFirstChary, gGlobalSettings.gDevice );
dx2 = currentDx + extentFirstCharx;
}
OnDrawSymbol(hdc, buffer.c_str()[0], currentDx, (3 * curLSPACE), mTagSize);
if (buffer.c_str()[1])
OnDrawSymbol(hdc, buffer.c_str()[1], dx2, (3 * curLSPACE), mTagSize);
/*********************/
}
else if (mtype == ARMeter::C)
{
float extentBufferx;
float extentBuffery;
FontManager::gFontScriab->GetExtent(kCSymbol, &extentBufferx, &extentBuffery, gGlobalSettings.gDevice );
OnDrawSymbol( hdc, kCSymbol, 0, - 200 * (mTagSize - 1) / 2, mTagSize );
}
else if (mtype == ARMeter::C2)
{
float extentBufferx;
float extentBuffery;
FontManager::gFontScriab->GetExtent(kC2Symbol, &extentBufferx, &extentBuffery, gGlobalSettings.gDevice );
OnDrawSymbol( hdc, kC2Symbol, 0, - 200 * (mTagSize - 1) / 2, mTagSize );
}
}
void GRMeter::print() const
{
fprintf(stderr,"(M%.2f,%.2f)",float(getRelativeTimePosition()),float(getDuration()));
}
ARMeter* GRMeter::getARMeter()
{
return /*dynamic*/static_cast<ARMeter*>(getAbstractRepresentation());
}
const ARMeter* GRMeter::getARMeter() const
{
return /*dynamic*/static_cast<const ARMeter*>(getAbstractRepresentation());
}
bool GRMeter::operator==(const GRMeter & meter) const
{
return (mtype == meter.mtype
&& numerator == meter.numerator
&& denominator == meter.denominator);
}
bool GRMeter::operator==(const GRTag &tag) const
{
const GRMeter * meter = dynamic_cast<const GRMeter *>(&tag);
if (meter)
return this->operator ==(*meter);
return false;
}
const NVPoint & GRMeter::getReferencePosition() const
{
const ARMeter::metertype mtype = getARMeter()->getMeterType();
switch (mtype)
{
case ARMeter::C: return refposC;
case ARMeter::C2: return refposC2;
case ARMeter::NUMERIC: return refpos;
default:
break;
}
return refpos;
}
| 27.786486 | 141 | 0.629413 | [
"vector"
] |
37f285c850ab9a23f5ea3f82f31310e28c1448ee | 5,339 | cpp | C++ | tests/core/test_tlsf_heap.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 15 | 2020-01-15T13:04:36.000Z | 2022-02-18T17:08:25.000Z | tests/core/test_tlsf_heap.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 3 | 2015-09-09T08:16:30.000Z | 2015-11-24T16:22:48.000Z | tests/core/test_tlsf_heap.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 1 | 2021-12-06T07:19:05.000Z | 2021-12-06T07:19:05.000Z | #include <catch2/catch_all.hpp>
#include <higanbana/core/platform/definitions.hpp>
#include <higanbana/core/allocators/heap_allocator_raw.hpp>
//#include <css/utils/dynamic_allocator.hpp>
TEST_CASE("some basic allocation tests") {
constexpr size_t size = 1024;
void* heap = malloc(size);
higanbana::HeapAllocatorRaw tlsf(heap, size);
auto block = tlsf.allocate(512);
REQUIRE(block);
auto block2 = tlsf.allocate(512);
REQUIRE_FALSE(block2);
tlsf.free(block);
block = tlsf.allocate(128);
REQUIRE(block);
block2 = tlsf.allocate(512);
REQUIRE(block2);
tlsf.free(block);
block = tlsf.allocate(256);
REQUIRE(block);
tlsf.free(block);
tlsf.free(block2);
block = tlsf.allocate(1024 - 16);
REQUIRE(block);
free(heap);
}
TEST_CASE("some basic allocation tests 2") {
constexpr size_t size = 70000;
void* heap = malloc(size);
higanbana::HeapAllocatorRaw tlsf(heap, size);
auto block = tlsf.allocate(50000);
REQUIRE(block);
auto block2 = tlsf.allocate(20000);
REQUIRE(block2 == nullptr);
block2 = tlsf.allocate(20000 - 32);
REQUIRE(block2);
free(heap);
}
/*
TEST_CASE("some basic allocation tests 3") {
constexpr size_t size = 80000;
css::DynamicHeapAllocator tlsf(1, size);
auto writeTrash = [](void* ptr, size_t size) {
memset(ptr, 254, size);
};
for (int i = 0; i < 2; i++) {
auto block = tlsf.allocate(316);
writeTrash(block, 316);
REQUIRE(block);
{
std::vector<void*> ptrs;
for (int k = 0; k < 5; ++k)
{
auto ptr = tlsf.allocate(216);
writeTrash(ptr, 216);
ptrs.push_back(ptr);
}
for (int k = 0; k < 5; ++k)
tlsf.deallocate(ptrs[k]);
}
tlsf.deallocate(block);
}
}
TEST_CASE("some basic allocation tests 4") {
constexpr size_t size = 80000;
css::DynamicHeapAllocator tlsf(1, size);
auto writeTrash = [](void* ptr, size_t size) {
memset(ptr, 254, size);
};
auto block = tlsf.allocate(14912);
writeTrash(block, 14912);
REQUIRE(block);
auto block2 = tlsf.allocate(7240);
writeTrash(block2, 7240);
REQUIRE(block2);
{
std::vector<void*> ptrs;
for (int k = 0; k < 4; ++k)
{
auto ptr = tlsf.allocate(2168);
writeTrash(ptr, 2168);
ptrs.push_back(ptr);
}
for (int k = 0; k < 4; ++k)
tlsf.deallocate(ptrs[k]);
}
auto block3 = tlsf.allocate(3512);
writeTrash(block3, 3512);
REQUIRE(block3);
auto block4 = tlsf.allocate(104);
writeTrash(block4, 104);
REQUIRE(block4);
auto block5 = tlsf.allocate(696);
writeTrash(block5, 696);
REQUIRE(block5);
//tlsf.deallocate(block5);
auto block6 = tlsf.allocate(696);
writeTrash(block6, 696);
REQUIRE(block6);
auto block7 = tlsf.allocate(368);
writeTrash(block7, 368);
REQUIRE(block7);
auto block8 = tlsf.allocate(696);
writeTrash(block8, 696);
REQUIRE(block8);
auto block9 = tlsf.allocate(128);
writeTrash(block9, 128);
REQUIRE(block9);
tlsf.deallocate(block9);
tlsf.deallocate(block8);
tlsf.deallocate(block7);
tlsf.deallocate(block6);
tlsf.deallocate(block4);
tlsf.deallocate(block3);
tlsf.deallocate(block2);
tlsf.deallocate(block);
block = tlsf.allocate(14912);
writeTrash(block, 14912);
REQUIRE(block);
block2 = tlsf.allocate(7240);
writeTrash(block2, 7240);
REQUIRE(block2);
{
std::vector<void*> ptrs;
for (int k = 0; k < 4; ++k)
{
auto ptr = tlsf.allocate(2168);
writeTrash(ptr, 2168);
ptrs.push_back(ptr);
}
for (int k = 0; k < 4; ++k)
tlsf.deallocate(ptrs[k]);
}
}
TEST_CASE("some basic allocation tests 5") {
constexpr size_t size = 80000;
css::DynamicHeapAllocator tlsf(1, size);
auto writeTrash = [](void* ptr, size_t size) {
memset(ptr, 254, size);
};
for (int i = 0; i < 3; ++i) {
auto block = tlsf.allocate(14912);
writeTrash(block, 14912);
REQUIRE(block);
auto block2 = tlsf.allocate(7240);
writeTrash(block2, 7240);
REQUIRE(block2);
{
std::vector<void*> ptrs;
for (int k = 0; k < 4; ++k)
{
auto ptr = tlsf.allocate(2168);
writeTrash(ptr, 2168);
ptrs.push_back(ptr);
}
for (int k = 0; k < 4; ++k)
tlsf.deallocate(ptrs[k]);
}
auto block3 = tlsf.allocate(3512);
writeTrash(block3, 3512);
REQUIRE(block3);
auto block4 = tlsf.allocate(104);
writeTrash(block4, 104);
REQUIRE(block4);
auto block5 = tlsf.allocate(696);
writeTrash(block5, 696);
REQUIRE(block5);
tlsf.deallocate(block5);
auto block6 = tlsf.allocate(696);
writeTrash(block6, 696);
REQUIRE(block6);
auto block7 = tlsf.allocate(368);
writeTrash(block7, 368);
REQUIRE(block7);
auto block8 = tlsf.allocate(696);
writeTrash(block8, 696);
REQUIRE(block8);
auto block9 = tlsf.allocate(128);
writeTrash(block9, 128);
REQUIRE(block9);
tlsf.deallocate(block9);
tlsf.deallocate(block8);
tlsf.deallocate(block7);
tlsf.deallocate(block6);
tlsf.deallocate(block4);
tlsf.deallocate(block3);
tlsf.deallocate(block2);
tlsf.deallocate(block);
}
}
*/
/*
TEST_CASE("failed real world case 1") {
void* heap = malloc(50331648);
higanbana::HeapAllocatorRaw tlsf(heap, 50331648, 131072);
auto block = tlsf.allocate(50200588, 131072);
REQUIRE(block);
free(heap);
}*/
| 25.183962 | 59 | 0.636449 | [
"vector"
] |
37fa52f372500ffb5825feb7c2653df387c6c05b | 3,660 | cpp | C++ | src/txt/SystemFonts.cpp | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 5 | 2018-08-10T18:49:03.000Z | 2019-10-22T18:04:47.000Z | src/txt/SystemFonts.cpp | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 2 | 2019-09-27T17:29:35.000Z | 2020-03-17T11:16:09.000Z | src/txt/SystemFonts.cpp | Potion/Cinder-Text | c08210a45d384b9461bf01c2ba6a1e06ed84053b | [
"MIT"
] | 3 | 2018-08-06T01:35:10.000Z | 2021-05-12T03:16:29.000Z | #include "txt/SystemFonts.h"
#include "cinder/Font.h"
//#if defined( cinder_msw_desktop )
//#include <windows.h>
//#define max(a, b) (((a) > (b)) ? (a) : (b))
//#define min(a, b) (((a) < (b)) ? (a) : (b))
//#include <gdiplus.h>
//#undef min
//#undef max
//#include "cinder/msw/cindermsw.h"
//#include "cinder/msw/cindermswgdiplus.h"
//#pragma comment(lib, "gdiplus")
//#endif
#include "cinder/msw/cindermsw.h"
#include "cinder/msw/cindermswgdiplus.h"
#include "cinder/Unicode.h"
#include "cinder/app/App.h"
#include <unordered_map>
#include <strsafe.h>
namespace txt
{
// Windows
#if defined( CINDER_MSW_DESKTOP )
HDC mFontDC = nullptr;
SystemFonts::SystemFonts()
{
mFontDC = ::CreateCompatibleDC( NULL );
mDefaultFamily = "Arial";
mDefaultStyle = "Regular";
mDefaultSize = 12;
}
int CALLBACK EnumFacesExProc( ENUMLOGFONTEX* lpelfe, NEWTEXTMETRICEX* lpntme, int FontType, LPARAM lParam )
{
std::string familyName = ci::toUtf8( ( char16_t* )lpelfe->elfLogFont.lfFaceName );
std::string style = ci::toUtf8( ( char16_t* )lpelfe->elfStyle );
( *reinterpret_cast<std::map<std::string, std::vector<std::string>>*>( lParam ) )[familyName].push_back( style );
return 1;
}
struct HFontRequest {
LOGFONT logfont;
std::string family;
std::string style;
bool fontFound = false;
};
HFontRequest mHFontRequest;
int CALLBACK LoadHFontExProc( ENUMLOGFONTEX* lpelfe, NEWTEXTMETRICEX* lpntme, int FontType, LPARAM lParam )
{
HFontRequest* request = reinterpret_cast<HFontRequest*>( lParam );
std::string familyName = ci::toUtf8( ( char16_t* )lpelfe->elfLogFont.lfFaceName );
std::transform( familyName.begin(), familyName.end(), familyName.begin(), ::tolower );
std::string style = ci::toUtf8( ( char16_t* )lpelfe->elfStyle );
std::transform( style .begin(), style.end(), style.begin(), ::tolower );
if( familyName == request->family && style == request->style ) {
request->logfont = lpelfe->elfLogFont;
request->fontFound = true;
}
return 1;
}
void SystemFonts::listFaces()
{
mFaces.clear();
::LOGFONT lf;
lf.lfCharSet = ANSI_CHARSET;
lf.lfFaceName[0] = '\0';
::EnumFontFamiliesEx( mFontDC, &lf, ( FONTENUMPROC )EnumFacesExProc, reinterpret_cast<LPARAM>( &mFaces ), 0 );
for( auto& family : mFaces ) {
ci::app::console() << family.first << std::endl;
ci::app::console() << "---------------------" << std::endl;
for( auto& style : family.second ) {
ci::app::console() << style << std::endl;
}
ci::app::console() << std::endl;
}
}
ci::BufferRef SystemFonts::getFontBuffer( std::string family, std::string style )
{
::LOGFONT lf;
lf.lfCharSet = ANSI_CHARSET;
lf.lfFaceName[0] = '\0';
std::u16string faceName = ci::toUtf16( family );
::StringCchCopy( lf.lfFaceName, LF_FACESIZE, ( LPCTSTR )faceName.c_str() );
mHFontRequest.family = family;
mHFontRequest.style = style;
::EnumFontFamiliesEx( mFontDC, &lf, ( FONTENUMPROC )LoadHFontExProc, reinterpret_cast<LPARAM>( &mHFontRequest ), 0 );
HFONT hFont;
if( mHFontRequest.fontFound ) {
hFont = ::CreateFontIndirectW( &mHFontRequest.logfont );
if( hFont ) {
::SelectObject( mFontDC, hFont );
DWORD fontSize = ::GetFontData( mFontDC, 0, 0, NULL, 0 );
void* fontBuffer = new BYTE[fontSize];
DWORD length = ::GetFontData( mFontDC, 0, 0, fontBuffer, fontSize );
return ci::Buffer::create( fontBuffer, ( unsigned int )length );
}
else {
return nullptr;
}
}
else {
return nullptr;
}
}
#endif
} | 25.594406 | 120 | 0.63388 | [
"vector",
"transform"
] |
5303d46c80481ab54de33b12520aecd4771400fc | 15,670 | cpp | C++ | src/stolen_cpp_code/Server.cpp | kim3-sudo/developers-against-humanity | 5e8e2bb86c3ab3b1d2dd2e899d94bd7bcd1d27f5 | [
"Apache-2.0"
] | null | null | null | src/stolen_cpp_code/Server.cpp | kim3-sudo/developers-against-humanity | 5e8e2bb86c3ab3b1d2dd2e899d94bd7bcd1d27f5 | [
"Apache-2.0"
] | null | null | null | src/stolen_cpp_code/Server.cpp | kim3-sudo/developers-against-humanity | 5e8e2bb86c3ab3b1d2dd2e899d94bd7bcd1d27f5 | [
"Apache-2.0"
] | null | null | null | /*
* The server implementation of Cards Against Humanity
* This handles communication between clients and runs the game.
*
* Written by: Sean Brown
* UCID: 10062604
*
* Features:
* + Accepts any client connection
* + Sends messages to clients
* + Can receive messages from client
* + Implements all steps of the game
* + New players are added once current turn is finished.
*
*
*/
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fstream>
#include "Card.h"
#include "Player.h"
using namespace std;
const int MAXPLAYERS = 10;
// for select Server
int maxDesc = 0;
fd_set recvSockSet;
bool terminated = false;
int bytesRecv;
int bytesSent;
char inBuffer[200];
char outBuffer[200];
int serverSock;
int clientSock;
struct sockaddr_in clientAddr;
struct timeval timeout = {0, 10};
struct timeval selectTime;
fd_set tempRecvSockSet;
Player judge, winner;
Card blackCard;
vector<Card> answers;
vector<Card> discard;
vector<Card> blackDeck;
vector<Card> whiteDeck;
vector<Player> players;
int step = 0;
void initServer(int&, int);
int countChars(string, char);
int parseAnswer(string, vector<Card>&);
int parseMessage(string);
vector<Card> shuffle(vector<Card>, int);
string composeSENDMessage(char, Card);
vector<Player> shuffle(vector<Player>, int);
string composeNOTIFYMessage(char, string);
void shutdown();
void refill();
Player getPlayer(string);
int getPlayerIndex(string);
void deletePlayer(string);
void splitString(char**, char*, const char*);
int main(int argc, char *argv[]) {
blackDeck.clear();
whiteDeck.clear();
discard.clear();
players.clear();
if (argc != 4) {
printf("Usage: %s <Listening Port> <Black Deck File> <White Deck File>\n", argv[0]);
exit(1);
}
initServer(serverSock, atoi(argv[1]));
string line;
ifstream blackCardReader, whiteCardReader;
blackCardReader.open(argv[2]);
whiteCardReader.open(argv[3]);
if (!blackCardReader.is_open() || !whiteCardReader.is_open()) {
printf("File open failed\n");
blackCardReader.close();
whiteCardReader.close();
exit(1);
}
while(getline(blackCardReader, line)) {
char* lineDiv[2];
if (line[0] == 'q') {
splitString(lineDiv, (char*)line.c_str(), "\"");
string temp(lineDiv[1]);
Card nBlack(temp, 'b', 1);
blackDeck.push_back(nBlack);
}
else if (line[0] == 's') {
splitString(lineDiv, (char*)line.c_str(), "\"");
string temp(lineDiv[1]);
int answers = countChars(lineDiv[1], '_');
Card nBlack(temp, 'b', answers);
blackDeck.push_back(nBlack);
}
}
while (getline(whiteCardReader, line)) {
Card nWhite(line, 'w', 0);
whiteDeck.push_back(nWhite);
}
blackDeck = shuffle(blackDeck, atoi(argv[1]));
whiteDeck = shuffle(whiteDeck, atoi(argv[1]));
FD_ZERO(&recvSockSet);
FD_SET(serverSock, &recvSockSet);
maxDesc = max(maxDesc, serverSock);
while (!terminated) {
memcpy(&tempRecvSockSet, &recvSockSet, sizeof(recvSockSet));
selectTime = timeout;
int ready = select(maxDesc + 1, &tempRecvSockSet, NULL, NULL, &selectTime);
if (ready < 0) {
printf("select() failed\n");
break;
}
if (FD_ISSET(serverSock, &tempRecvSockSet)) {
unsigned int size = sizeof(clientAddr);
if ((clientSock = accept(serverSock, (struct sockaddr *) &clientAddr, &size)) < 0) {
break;
}
printf("A new player has connected.\n");
bool nameOK = false;
bool foundName = false;
while (!nameOK) {
memset(&inBuffer, 0, sizeof(inBuffer));
bytesRecv = 0;
while (bytesRecv <= 0) {
bytesRecv = recv(clientSock, (char*)&inBuffer, 20, 0);
}
printf("%s\n", inBuffer);
if (players.size() < 1) {
printf("Players is Empty.\n");
outBuffer[0] = 'y';
printf("Name hasn't been taken.\n");
bytesSent = send(clientSock, (char*)&outBuffer, 1, 0);
if (bytesSent <= 0) {
printf("Couldn't send confirmation.\n");
exit(1);
}
nameOK = !nameOK;
}
else {
printf("Players isn't empty.\n");
foundName = false;
for (int i = 0; i < players.size(); i++) {
if (players[i].getName().compare(inBuffer) == 0) {
outBuffer[0] = 'n';
bytesSent = 0;
printf("Name is already taken.\n");
bytesSent = send(clientSock, (char*)&outBuffer, 1, 0);
if (bytesSent <= 0) {
printf("Couldn't send denial.\n");
exit(1);
}
foundName = true;
break;
}
}
if (!foundName) {
outBuffer[0] = 'y';
printf("Name hasn't been taken.\n");
bytesSent = send(clientSock, (char*)&outBuffer, 1, 0);
if (bytesSent <= 0) {
printf("Couldn't send confirmation.\n");
exit(1);
}
nameOK = !nameOK;
}
}
}
printf("Name checks out.\n");
string n(inBuffer);
Player newPlayer(n, clientSock);
players.push_back(newPlayer);
printf("About to send Cards.\n");
for (int i = 0; i < 10; i++) {
bytesSent = 0;
if (whiteDeck.size() == 0) {
refill();
}
string out = composeSENDMessage('d', whiteDeck[whiteDeck.size()-1]);
players[players.size()-1].addCard(whiteDeck[whiteDeck.size()-1]);
whiteDeck.pop_back();
bytesSent = send(clientSock, (char*)out.c_str(), 100, 0);
if (bytesSent <= 0) {
printf("No Card was sent.\n");
exit(1);
}
}
FD_SET(clientSock, &recvSockSet);
maxDesc = max(maxDesc, clientSock);
}
else {
if(players.size() > 3) {
string message;
switch (step % 3) {
// Choose judge and NOTIFY the others
case 0:
printf("Choosing a judge.\n");
players = shuffle(players, atoi(argv[1])-step);
judge = players[0];
message = composeNOTIFYMessage('j', judge.getName());
for (int i = 0; i < players.size(); i++) {
bytesSent = send(players[i].getSocket(), (char*)message.c_str(), 100, 0);
if (bytesSent <= 0) {
printf("Judge message couldn't be sent.\n");
exit(1);
}
}
step++;
break;
// choose black card and POST it
case 1:
if (blackDeck.size() == 0) {
shutdown();
}
printf("Choosing a black card.\n");
blackCard = blackDeck[blackDeck.size() - 1];
blackDeck.pop_back();
message = composeSENDMessage('p', blackCard);
for (int i = 0; i < players.size(); i++) {
bytesSent = send(players[i].getSocket(), (char*)message.c_str(), 300, 0);
if(bytesSent <= 0) {
printf("Couldn't post black card.\n");
exit(1);
}
}
step++;
break;
// Handles answers and requests
case 2:
answers.clear();
// Receive answers from others
for (int i = 1; i < players.size(); i++) {
for (int j = 0; j < blackCard.numOfAnswers; j++) {
memset(&inBuffer, 0, sizeof(inBuffer));
bytesRecv = 0;
while(bytesRecv <= 0) {
bytesRecv = recv(players[i].getSocket(), (char*)&inBuffer, 100, 0);
}
printf("player %d sent:\n%s.\n", i, (char*)string(inBuffer).c_str());
parseAnswer(string(inBuffer), answers);
}
}
printf("Received all answers.\n");
// send expected # of answers to judge
message = composeNOTIFYMessage('n', string("Server"));
printf("About to send:\n%s\n", message.c_str());
bytesSent = send(judge.getSocket(), (char*)message.c_str(), 100, 0);
if(bytesSent <= 0) {
printf("Failed to send NOTIFY to judge.\n");
exit(1);
}
printf("Sent answers size.\n");
// Send answers to judge
for (int i = 0; i < answers.size(); i++) {
message = composeSENDMessage('n', answers[i]);
printf("About to send ANSWER to judge:\n%s\n", message.c_str());
bytesSent = send(judge.getSocket(), (char*)message.c_str(), 100, 0);
if(bytesSent <= 0) {
printf("Failed to send ANSWER to judge.\n");
i--;
}
}
printf("Sent Answers to judge.\n");
// Receive requests
for (int i = 1; i < players.size(); i++) {
for (int j = 0; j < blackCard.numOfAnswers; j++) {
memset(&inBuffer, 0, sizeof(inBuffer));
bytesRecv = 0;
while (bytesRecv <= 0) {
bytesRecv = recv(players[i].getSocket(), (char*)&inBuffer, 100, 0);
}
parseMessage(string(inBuffer));
}
}
printf("Received all of the requests from clients.\n");
// receives winner
bytesRecv = 0;
memset(&inBuffer, 0, sizeof(inBuffer));
while (bytesRecv <= 0) {
bytesRecv = recv(judge.getSocket(), (char*)&inBuffer, 100, 0);
}
parseMessage(string(inBuffer));
// Tell everybody else
for (int i = 1; i < players.size(); i++) {
string winningMesssage = composeNOTIFYMessage('w', winner.getName());
bytesSent = send(players[i].getSocket(), (char*)winningMesssage.c_str(), 100, 0);
if(bytesSent <= 0) {
printf("Failed to winner message.\n");
exit(1);
}
}
step++;
break;
default:
break;
}
}
}
}
}
// Initializes the server
// Needs the socket and port
void initServer(int& serverSock, int port) {
struct sockaddr_in serverAddr;
if((serverSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
printf("socket() failed\n");
exit(1);
}
int yes = 1;
if(setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
printf("setsockopt() failed\n");
exit(1);
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(serverSock, (sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
printf("bind() failed\n");
exit(1);
}
if(listen(serverSock, MAXPLAYERS) < 0) {
printf("listen() failed\n");
exit(1);
}
}
// counts instances of a character in a string
// Ingame: Used to find the number of answers required for statement
int countChars(string l, char s) {
int elements = 0;
for (int i = 0; i < l.length(); i++) {
if(l[i] == s) {
elements++;
}
}
return elements;
}
// Parses ANSWER message
int parseAnswer(string message, vector<Card> &answers) {
char* messageDiv[2]; // [0] has first half, [1] has content
char* getCommand[2]; // [0] has command, [1] has source
splitString(messageDiv, (char*)message.c_str(), "\n");
splitString(getCommand, messageDiv[0], " ");
if(strcmp((const char*)getCommand[0], "ANSWER") == 0 || strcmp((const char*)getCommand[0], "NSWER") == 0) {
players[getPlayerIndex(string(getCommand[1]))].takeCard(string(messageDiv[1]));
answers.push_back(Card(string(messageDiv[1]), string(getCommand[1])));
return 1;
}
else {
return -1;
}
}
int parseMessage(string message) {
char* notifyMessage[2]; // [0] has option, [1] has name
char* messageDiv[2]; // [0] has type and source, [1] has content
char* getCommand[2]; // [0] has command, [1] has source
splitString(messageDiv, (char*)message.c_str(), "\n");
splitString(getCommand, messageDiv[0], " ");
if(strcmp((const char*)getCommand[0], "REQUEST") == 0) {
Player newP = getPlayer(string(getCommand[1]));
if (whiteDeck.size() == 0) {
refill();
}
string add = composeSENDMessage('d', whiteDeck[whiteDeck.size() - 1]);
whiteDeck.pop_back();
bytesSent = send(newP.getSocket(), (char*)add.c_str(), 100, 0);
return 1;
}
else if(strcmp((const char*)getCommand[0], "NOTIFY") == 0) {
splitString(notifyMessage, messageDiv[1], " ");
if (strcmp(notifyMessage[0], "winner:") == 0) {
for (int i = 0; i < answers.size(); i++) {
discard.push_back(answers[i]);
}
answers.clear();
winner = getPlayer(string(notifyMessage[1]));
}
else if(strcmp(notifyMessage[0], "quit:") == 0) {
Player temp = getPlayer(string(notifyMessage[1]));
for(int i = 0; i < temp.getHand().size(); i++) {
discard.push_back(temp.getHand()[i]);
}
close(temp.getSocket());
deletePlayer(string(notifyMessage[1]));
if (players.size() == 0)
exit(1);
}
return 1;
}
else {
return -1;
}
}
// shuffles the elements in the deck
vector<Card> shuffle(vector<Card> deck, int seed) {
vector<Card> newDeck;
newDeck.clear();
for (int i = 1; i < deck.size(); i+=2) {
newDeck.push_back(deck[i]);
}
for (int i = 0; i < deck.size(); i+=2) {
newDeck.push_back(deck[i]);
}
if(seed == 0) {
return newDeck;
}
else {
return shuffle(newDeck, seed - 1);
}
}
// composes a message to send, made of the card and source
/*
* messag types: 'p' for post, 'n' for answer, 'd' for add
*/
string composeSENDMessage(char type, Card cardToSend) {
if(type == 'p') {
//printf("About to send POST:\n%s\n", cardToSend.content.c_str());
return "POST Server\n" + cardToSend.content;
}
else if(type == 'n') {
//printf("About to send ANSWER:\n%s %s\n", cardToSend.owner.c_str(), cardToSend.content.c_str());
return "ANSWER " + cardToSend.owner + "\n" + cardToSend.content;
}
else if (type == 'd') {
//printf("About to send ADD:\n%s\n", cardToSend.content.c_str());
return "ADD Server\n" + cardToSend.content;
}
else {
return "";
}
}
// shuffles the elements in the deck
vector<Player> shuffle(vector<Player> deck, int seed) {
vector<Player> newDeck;
newDeck.clear();
for (int i = 1; i < deck.size(); i+=2) {
newDeck.push_back(deck[i]);
}
for (int i = 0; i < deck.size(); i+=2) {
newDeck.push_back(deck[i]);
}
if (seed == 0) {
return newDeck;
}
else {
return shuffle(newDeck, seed - 1);
}
}
// Composes a message to notify, made of the info to send
/*
*
*/
string composeNOTIFYMessage(char purpose, string playerName) {
if (purpose == 'j') {
return "NOTIFY Server\nCP: " + playerName;
}
else if (purpose == 'w') {
return "NOTIFY Server\nwinner: " + playerName;
}
else if(purpose == 'n') {
stringstream s;
s << answers.size();
return "NOTIFY Server\nplayers: " + s.str();
}
else if(purpose == 'q') {
return "NOTIFY Server\nquit: Server";
}
else {
return "";
}
}
void shutdown() {
for (int i = 0; i < players.size(); i++) {
string quit = composeNOTIFYMessage('q', "");
bytesSent = send(players[i].getSocket(), (char*)quit.c_str(), 100, 0);
if(bytesSent <= 0) {
printf("Couldn't send quit.\n");
exit(1);
}
}
exit(1);
}
// finds player in a the list of Players
Player getPlayer(string name) {
for (int i = 0; i < players.size(); i++) {
if (strcmp(players[i].getName().c_str(), name.c_str()) == 0) {
return players[i];
}
}
return Player();
}
int getPlayerIndex(string name) {
for (int i = 0; i < players.size(); i++) {
if (strcmp(players[i].getName().c_str(), name.c_str()) == 0) {
return i;
}
}
return -1;
}
void deletePlayer(string playerName) {
vector<Player> temp;
for (int i = 0; i < players.size(); i++) {
if (strcmp(players[i].getName().c_str(), playerName.c_str()) != 0) {
temp.push_back(players[i]);
}
else {
delete &players[i];
}
}
players = temp;
}
// refills the white deck when it runs out
void refill() {
whiteDeck = discard;
whiteDeck = shuffle(whiteDeck, blackDeck.size());
discard.clear();
}
// splits the string "target" into the "parts" array by the "delim" characters
// note: must know the size of "parts" you will need before calculation
// otherwise provide a bigger than necessary array for parts
void splitString(char* parts[], char* target, const char* delim) {
char* tok;
tok = std::strtok(target, delim);
int i = 0;
while (tok != NULL) {
parts[i] = tok;
tok = strtok(NULL, delim);
i++;
}
}
| 25.943709 | 108 | 0.608998 | [
"vector"
] |
530a67dbf1f63cb6b6df35eeb0c5a9272ac79cbf | 2,701 | cpp | C++ | Google Code Jam/2019/kick start Round C/Circuit Board.cpp | Sohieeb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | 1 | 2020-01-30T20:08:24.000Z | 2020-01-30T20:08:24.000Z | Google Code Jam/2019/kick start Round C/Circuit Board.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | Google Code Jam/2019/kick start Round C/Circuit Board.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using namespace __gnu_cxx;
typedef double db;
typedef long long ll;
typedef pair<db, db> pdd;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;
#define F first
#define S second
#define pnl printf("\n")
#define sz(x) (int)x.size()
#define sf(x) scanf("%d",&x)
#define pf(x) printf("%d\n",x)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define rep(i, n) for(int i = 0; i < n; ++i)
const db eps = 1e-9;
const db pi = acos(-1);
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1000 * 1000 * 1000 + 7;
int T;
int n, m, k;
int arr[303][303];
int logV[100100];
int spMin[303][303][17],spMax[303][303][17];
void spBuild(int z){
for(int i = 0; i <= m; ++i)
logV[i] = log2(i);
for(int i = 1; i <= m; ++i)
spMin[z][i][0] = spMax[z][i][0] = arr[z][i];
for(int j = 1; (1 << j) <= m; ++j)
for(int i = 1; i + (1 << j) <= m + 1; ++i){
spMin[z][i][j] = min(spMin[z][i][j-1], spMin[z][i+(1<<(j-1))][j-1]);
spMax[z][i][j] = max(spMax[z][i][j-1], spMax[z][i+(1<<(j-1))][j-1]);
}
}
int getMn(int z, int l, int r){
int lg = logV[r-l+1];
return min(spMin[z][l][lg], spMin[z][r-(1<<lg)+1][lg]);
}
int getMx(int z, int l, int r){
int lg = logV[r-l+1];
return max(spMax[z][l][lg], spMax[z][r-(1<<lg)+1][lg]);
}
int main() {
scanf("%d", &T);
for (int C = 1; C <= T; ++C) {
memset(spMin, 0, sizeof spMin);
memset(spMax, 0, sizeof spMax);
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)
scanf("%d", &arr[i][j]);
spBuild(i);
}
int ans = 0;
for (int i = 1; i <= m; ++i)
for (int j = i; j <= m; ++j) {
vector<int> v;
for (int w = 1; w <= n; ++w) {
pii q;
q.F = getMn(w, i, j);
q.S = getMx(w, i, j);
// cout << i << " " << j << " " << q.F << " " << q.S << endl;
if (q.S - q.F <= k)
v.push_back(1);
else
v.push_back(0);
}
int mxSum = 0, cur = 0;
for (int w = 0; w < n; ++w) {
cur += v[w];
mxSum = max(mxSum, cur);
if (v[w] == 0) cur = 0;
}
ans = max(ans, mxSum * (j - i + 1));
}
printf("Case #%d: %d\n", C, ans);
}
return 0;
}
| 28.135417 | 81 | 0.413551 | [
"vector"
] |
531975b1212b9e43f4de153904d634b956d0f7bc | 3,747 | cpp | C++ | aws-cpp-sdk-customer-profiles/source/model/AppflowIntegrationWorkflowStep.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-customer-profiles/source/model/AppflowIntegrationWorkflowStep.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-customer-profiles/source/model/AppflowIntegrationWorkflowStep.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/customer-profiles/model/AppflowIntegrationWorkflowStep.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CustomerProfiles
{
namespace Model
{
AppflowIntegrationWorkflowStep::AppflowIntegrationWorkflowStep() :
m_flowNameHasBeenSet(false),
m_status(Status::NOT_SET),
m_statusHasBeenSet(false),
m_executionMessageHasBeenSet(false),
m_recordsProcessed(0),
m_recordsProcessedHasBeenSet(false),
m_batchRecordsStartTimeHasBeenSet(false),
m_batchRecordsEndTimeHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false)
{
}
AppflowIntegrationWorkflowStep::AppflowIntegrationWorkflowStep(JsonView jsonValue) :
m_flowNameHasBeenSet(false),
m_status(Status::NOT_SET),
m_statusHasBeenSet(false),
m_executionMessageHasBeenSet(false),
m_recordsProcessed(0),
m_recordsProcessedHasBeenSet(false),
m_batchRecordsStartTimeHasBeenSet(false),
m_batchRecordsEndTimeHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false)
{
*this = jsonValue;
}
AppflowIntegrationWorkflowStep& AppflowIntegrationWorkflowStep::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("FlowName"))
{
m_flowName = jsonValue.GetString("FlowName");
m_flowNameHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = StatusMapper::GetStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("ExecutionMessage"))
{
m_executionMessage = jsonValue.GetString("ExecutionMessage");
m_executionMessageHasBeenSet = true;
}
if(jsonValue.ValueExists("RecordsProcessed"))
{
m_recordsProcessed = jsonValue.GetInt64("RecordsProcessed");
m_recordsProcessedHasBeenSet = true;
}
if(jsonValue.ValueExists("BatchRecordsStartTime"))
{
m_batchRecordsStartTime = jsonValue.GetString("BatchRecordsStartTime");
m_batchRecordsStartTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("BatchRecordsEndTime"))
{
m_batchRecordsEndTime = jsonValue.GetString("BatchRecordsEndTime");
m_batchRecordsEndTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("CreatedAt"))
{
m_createdAt = jsonValue.GetDouble("CreatedAt");
m_createdAtHasBeenSet = true;
}
if(jsonValue.ValueExists("LastUpdatedAt"))
{
m_lastUpdatedAt = jsonValue.GetDouble("LastUpdatedAt");
m_lastUpdatedAtHasBeenSet = true;
}
return *this;
}
JsonValue AppflowIntegrationWorkflowStep::Jsonize() const
{
JsonValue payload;
if(m_flowNameHasBeenSet)
{
payload.WithString("FlowName", m_flowName);
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", StatusMapper::GetNameForStatus(m_status));
}
if(m_executionMessageHasBeenSet)
{
payload.WithString("ExecutionMessage", m_executionMessage);
}
if(m_recordsProcessedHasBeenSet)
{
payload.WithInt64("RecordsProcessed", m_recordsProcessed);
}
if(m_batchRecordsStartTimeHasBeenSet)
{
payload.WithString("BatchRecordsStartTime", m_batchRecordsStartTime);
}
if(m_batchRecordsEndTimeHasBeenSet)
{
payload.WithString("BatchRecordsEndTime", m_batchRecordsEndTime);
}
if(m_createdAtHasBeenSet)
{
payload.WithDouble("CreatedAt", m_createdAt.SecondsWithMSPrecision());
}
if(m_lastUpdatedAtHasBeenSet)
{
payload.WithDouble("LastUpdatedAt", m_lastUpdatedAt.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace CustomerProfiles
} // namespace Aws
| 22.572289 | 94 | 0.752869 | [
"model"
] |
531b876e07d30b2b705f84ac58caa564ece26ef7 | 4,818 | cpp | C++ | tests/06-network/network.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 81 | 2018-12-11T20:48:41.000Z | 2022-03-18T22:24:11.000Z | tests/06-network/network.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 7 | 2020-04-19T11:50:39.000Z | 2021-11-12T16:08:53.000Z | tests/06-network/network.cpp | kochol/ari2 | ca185191531acc1954cd4acfec2137e32fdb5c2d | [
"MIT"
] | 4 | 2019-04-24T11:51:29.000Z | 2021-03-10T05:26:33.000Z | #include "gfx/gfx.hpp"
#include "gfx/Application.hpp"
#include "en/World.hpp"
#include "3d/RenderSystem.hpp"
#include "3d/SceneSystem.hpp"
#include "3d/Camera.hpp"
#include "3d/BoxShape.hpp"
#include "net/ServerSystem.hpp"
#include "net/ClientSystem.hpp"
#include "core/log.h"
void RpcServerTest(int i)
{
log_debug("RpcServerTest %d client_index %d", i, ari::net::GetLastRpcClientIndex());
}
void RpcClientTest(float i)
{
log_debug("RpcClientTest %f", i);
}
void RpcMultiCastTest(float i)
{
log_debug("RpcMultiCastTest %f", i);
}
void RpcMultiCastTest2(uint32_t i, float x, float y)
{
log_debug("RpcMultiCastTest2 %u, %f, %f", i, x, y);
}
ari::net::RPC * g_rpc_server = nullptr,
* g_rpc_client = nullptr,
* g_rpc_multicast = nullptr,
* g_rpc_multicast2 = nullptr;
struct Client
{
ari::en::World m_world;
ari::en::RenderSystem m_renderer;
ari::en::SceneSystem m_scene_mgr;
ari::net::ClientSystem m_client_system;
void Init()
{
// Create a new window
ari::io::Window window;
m_scene_mgr.TargetWindow = m_renderer.TargetWindow = ari::io::CreateAriWindow(window, "Client");
// Add systems
m_world.AddSystem(&m_renderer);
m_world.AddSystem(&m_scene_mgr);
m_world.AddSystem(&m_client_system);
m_client_system.Connect(yojimbo::Address("127.0.0.1", 55223));
}
void Update(float _elasped)
{
m_world.Update(_elasped);
}
void Shutdown()
{
m_client_system.StopClient();
}
};
class NetworkApp : public ari::Application
{
public:
~NetworkApp() = default;
ari::gfx::GfxSetup* GetGfxSetup() override
{
return &m_setup;
}
void OnInit() override
{
// Init network
ari::net::InitNetwork();
// Add systems
m_world.AddSystem(&m_renderer);
m_world.AddSystem(&m_scene_mgr);
m_world.AddSystem(&m_server_system);
m_server_system.CreateServer(yojimbo::Address("127.0.0.1", 55223));
// Create entity and add box and camera
ari::en::EntityHandle entity = m_world.CreateEntity();
auto camera = m_world.CreateComponent<ari::en::Camera, ari::en::Node3D>();
camera.Component->Position.x = 3.f;
camera.Component->Position.y = 3.f;
camera.Component->Position.z = 3.f;
camera.Component->Target.z = 0.0f;
m_world.AddDerivedComponent<ari::en::Camera, ari::en::Node3D>(entity, camera);
auto box = m_world.CreateComponent<ari::en::BoxShape, ari::en::Node3D>();
m_pBox = box.Component;
m_world.AddDerivedComponent<ari::en::BoxShape, ari::en::Node3D>(entity, box);
// Create PropertyReplicator component to sync the rotation
auto replicator = m_world.CreateComponent<ari::net::PropertyReplicator>();
replicator.Component->AddProperty(box, "Rotation");
m_world.AddComponent(entity, replicator);
// Add entity to the world
entity->bReplicates = true;
m_world.AddEntity(entity);
// Add RPC functions
g_rpc_server = ari::net::AddRPC("RpcServerTest", ari::net::RpcType::Server, RpcServerTest);
g_rpc_client = ari::net::AddRPC("RpcClientTest", ari::net::RpcType::Client, RpcClientTest);
g_rpc_multicast = ari::net::AddRPC("RpcMultiCastTest", ari::net::RpcType::MultiCast, RpcMultiCastTest);
g_rpc_multicast2 = ari::net::AddRPC("RpcMultiCastTest2", ari::net::RpcType::MultiCast, RpcMultiCastTest2);
}
void OnFrame(float _elapsedTime) override
{
if (m_bRotate)
{
m_pBox->Rotation.x += 0.3f * _elapsedTime;
m_pBox->Rotation.y += 0.3f * _elapsedTime;
}
m_world.Update(_elapsedTime);
for (auto c: m_aClients)
{
c->Update(_elapsedTime);
}
}
void OnCleanup() override
{
// Shutdown Network
for (auto c : m_aClients)
c->Shutdown();
m_server_system.StopServer();
ari::net::ShutdownNetwork();
}
void OnEvent(ari_event* event, ari::io::WindowHandle _window) override
{
if (event->type == ARI_EVENTTYPE_KEY_UP)
{
switch (event->key_code)
{
case ARI_KEYCODE_C:
{
Client* client = ari::core::Memory::New<Client>();
m_aClients.Add(client)->Init();
}
break;
case ARI_KEYCODE_S:
m_bRotate = !m_bRotate;
break;
case ARI_KEYCODE_Q:
if (_window.Index > 0)
m_aClients[_window.Index - 1]->m_client_system.CallRPC(g_rpc_server, 7);
break;
case ARI_KEYCODE_W:
if (_window.Index == 0) // On main window
{
m_server_system.CallRPC(0, g_rpc_client, 12.5f);
}
break;
case ARI_KEYCODE_E:
if (_window.Index == 0) // On main window
{
m_server_system.CallRPC(g_rpc_multicast, 12.5f);
m_server_system.CallRPC(g_rpc_multicast2, 785, 12.0005f, 12.00001f);
}
break;
}
}
}
private:
ari::gfx::GfxSetup m_setup;
ari::en::World m_world;
ari::en::RenderSystem m_renderer;
ari::en::SceneSystem m_scene_mgr;
ari::en::BoxShape * m_pBox = nullptr;
ari::net::ServerSystem m_server_system;
ari::core::Array<Client*> m_aClients;
bool m_bRotate = true;
};
ARI_MAIN(NetworkApp)
| 25.09375 | 108 | 0.695102 | [
"3d"
] |
5322133886d184b07b8393fc8a200ca4b81295a9 | 58,332 | cpp | C++ | example_quadruped_leg_kinematics/src/ikfast.cpp | ajshort/cdrm | d5140740555a56c1e17518c3f6ab882275c530d7 | [
"MIT"
] | 4 | 2020-04-19T13:03:19.000Z | 2020-09-10T04:43:52.000Z | example_quadruped_leg_kinematics/src/ikfast.cpp | ajshort/cdrm | d5140740555a56c1e17518c3f6ab882275c530d7 | [
"MIT"
] | 1 | 2020-05-14T08:25:56.000Z | 2020-05-31T00:14:11.000Z | example_quadruped_leg_kinematics/src/ikfast.cpp | ajshort/cdrm | d5140740555a56c1e17518c3f6ab882275c530d7 | [
"MIT"
] | null | null | null | /// autogenerated analytical inverse kinematics code from ikfast program part of OpenRAVE
/// \author Rosen Diankov
///
/// 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.
///
/// ikfast version 0x10000049 generated on 2017-01-24 12:24:38.816652
/// To compile with gcc:
/// gcc -lstdc++ ik.cpp
/// To compile without any main function as a shared object (might need -llapack):
/// gcc -fPIC -lstdc++ -DIKFAST_NO_MAIN -DIKFAST_CLIBRARY -shared -Wl,-soname,libik.so -o libik.so ik.cpp
#define IKFAST_HAS_LIBRARY
#include "ikfast.h" // found inside share/openrave-X.Y/python/ikfast.h
using namespace ikfast;
// check if the included ikfast version matches what this file was compiled with
#define IKFAST_COMPILE_ASSERT(x) extern int __dummy[(int)x]
IKFAST_COMPILE_ASSERT(IKFAST_VERSION==0x10000049);
#include <cmath>
#include <vector>
#include <limits>
#include <algorithm>
#include <complex>
#ifndef IKFAST_ASSERT
#include <stdexcept>
#include <sstream>
#include <iostream>
#ifdef _MSC_VER
#ifndef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __FUNCDNAME__
#endif
#endif
#ifndef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __func__
#endif
#define IKFAST_ASSERT(b) { if( !(b) ) { std::stringstream ss; ss << "ikfast exception: " << __FILE__ << ":" << __LINE__ << ": " <<__PRETTY_FUNCTION__ << ": Assertion '" << #b << "' failed"; throw std::runtime_error(ss.str()); } }
#endif
#if defined(_MSC_VER)
#define IKFAST_ALIGNED16(x) __declspec(align(16)) x
#else
#define IKFAST_ALIGNED16(x) x __attribute((aligned(16)))
#endif
#define IK2PI ((IkReal)6.28318530717959)
#define IKPI ((IkReal)3.14159265358979)
#define IKPI_2 ((IkReal)1.57079632679490)
#ifdef _MSC_VER
#ifndef isnan
#define isnan _isnan
#endif
#ifndef isinf
#define isinf _isinf
#endif
//#ifndef isfinite
//#define isfinite _isfinite
//#endif
#endif // _MSC_VER
// lapack routines
extern "C" {
void dgetrf_ (const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info);
void zgetrf_ (const int* m, const int* n, std::complex<double>* a, const int* lda, int* ipiv, int* info);
void dgetri_(const int* n, const double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info);
void dgesv_ (const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info);
void dgetrs_(const char *trans, const int *n, const int *nrhs, double *a, const int *lda, int *ipiv, double *b, const int *ldb, int *info);
void dgeev_(const char *jobvl, const char *jobvr, const int *n, double *a, const int *lda, double *wr, double *wi,double *vl, const int *ldvl, double *vr, const int *ldvr, double *work, const int *lwork, int *info);
}
using namespace std; // necessary to get std math routines
#ifdef IKFAST_NAMESPACE
namespace IKFAST_NAMESPACE {
#endif
inline float IKabs(float f) { return fabsf(f); }
inline double IKabs(double f) { return fabs(f); }
inline float IKsqr(float f) { return f*f; }
inline double IKsqr(double f) { return f*f; }
inline float IKlog(float f) { return logf(f); }
inline double IKlog(double f) { return log(f); }
// allows asin and acos to exceed 1. has to be smaller than thresholds used for branch conds and evaluation
#ifndef IKFAST_SINCOS_THRESH
#define IKFAST_SINCOS_THRESH ((IkReal)1e-7)
#endif
// used to check input to atan2 for degenerate cases. has to be smaller than thresholds used for branch conds and evaluation
#ifndef IKFAST_ATAN2_MAGTHRESH
#define IKFAST_ATAN2_MAGTHRESH ((IkReal)1e-7)
#endif
// minimum distance of separate solutions
#ifndef IKFAST_SOLUTION_THRESH
#define IKFAST_SOLUTION_THRESH ((IkReal)1e-6)
#endif
// there are checkpoints in ikfast that are evaluated to make sure they are 0. This threshold speicfies by how much they can deviate
#ifndef IKFAST_EVALCOND_THRESH
#define IKFAST_EVALCOND_THRESH ((IkReal)0.00001)
#endif
inline float IKasin(float f)
{
IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver
if( f <= -1 ) return float(-IKPI_2);
else if( f >= 1 ) return float(IKPI_2);
return asinf(f);
}
inline double IKasin(double f)
{
IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver
if( f <= -1 ) return -IKPI_2;
else if( f >= 1 ) return IKPI_2;
return asin(f);
}
// return positive value in [0,y)
inline float IKfmod(float x, float y)
{
while(x < 0) {
x += y;
}
return fmodf(x,y);
}
// return positive value in [0,y)
inline double IKfmod(double x, double y)
{
while(x < 0) {
x += y;
}
return fmod(x,y);
}
inline float IKacos(float f)
{
IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver
if( f <= -1 ) return float(IKPI);
else if( f >= 1 ) return float(0);
return acosf(f);
}
inline double IKacos(double f)
{
IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver
if( f <= -1 ) return IKPI;
else if( f >= 1 ) return 0;
return acos(f);
}
inline float IKsin(float f) { return sinf(f); }
inline double IKsin(double f) { return sin(f); }
inline float IKcos(float f) { return cosf(f); }
inline double IKcos(double f) { return cos(f); }
inline float IKtan(float f) { return tanf(f); }
inline double IKtan(double f) { return tan(f); }
inline float IKsqrt(float f) { if( f <= 0.0f ) return 0.0f; return sqrtf(f); }
inline double IKsqrt(double f) { if( f <= 0.0 ) return 0.0; return sqrt(f); }
inline float IKatan2Simple(float fy, float fx) {
return atan2f(fy,fx);
}
inline float IKatan2(float fy, float fx) {
if( isnan(fy) ) {
IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned
return float(IKPI_2);
}
else if( isnan(fx) ) {
return 0;
}
return atan2f(fy,fx);
}
inline double IKatan2Simple(double fy, double fx) {
return atan2(fy,fx);
}
inline double IKatan2(double fy, double fx) {
if( isnan(fy) ) {
IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned
return IKPI_2;
}
else if( isnan(fx) ) {
return 0;
}
return atan2(fy,fx);
}
template <typename T>
struct CheckValue
{
T value;
bool valid;
};
template <typename T>
inline CheckValue<T> IKatan2WithCheck(T fy, T fx, T epsilon)
{
CheckValue<T> ret;
ret.valid = false;
ret.value = 0;
if( !isnan(fy) && !isnan(fx) ) {
if( IKabs(fy) >= IKFAST_ATAN2_MAGTHRESH || IKabs(fx) > IKFAST_ATAN2_MAGTHRESH ) {
ret.value = IKatan2Simple(fy,fx);
ret.valid = true;
}
}
return ret;
}
inline float IKsign(float f) {
if( f > 0 ) {
return float(1);
}
else if( f < 0 ) {
return float(-1);
}
return 0;
}
inline double IKsign(double f) {
if( f > 0 ) {
return 1.0;
}
else if( f < 0 ) {
return -1.0;
}
return 0;
}
template <typename T>
inline CheckValue<T> IKPowWithIntegerCheck(T f, int n)
{
CheckValue<T> ret;
ret.valid = true;
if( n == 0 ) {
ret.value = 1.0;
return ret;
}
else if( n == 1 )
{
ret.value = f;
return ret;
}
else if( n < 0 )
{
if( f == 0 )
{
ret.valid = false;
ret.value = (T)1.0e30;
return ret;
}
if( n == -1 ) {
ret.value = T(1.0)/f;
return ret;
}
}
int num = n > 0 ? n : -n;
if( num == 2 ) {
ret.value = f*f;
}
else if( num == 3 ) {
ret.value = f*f*f;
}
else {
ret.value = 1.0;
while(num>0) {
if( num & 1 ) {
ret.value *= f;
}
num >>= 1;
f *= f;
}
}
if( n < 0 ) {
ret.value = T(1.0)/ret.value;
}
return ret;
}
/// solves the forward kinematics equations.
/// \param pfree is an array specifying the free joints of the chain.
IKFAST_API void ComputeFk(const IkReal* j, IkReal* eetrans, IkReal* eerot) {
IkReal x0,x1,x2,x3,x4,x5,x6,x7,x8,x9;
x0=IKcos(j[0]);
x1=IKcos(j[1]);
x2=IKcos(j[2]);
x3=IKsin(j[0]);
x4=IKsin(j[1]);
x5=IKsin(j[2]);
x6=((0.324)*x5);
x7=((0.324)*x2);
x8=(x1*x3);
x9=(x0*x1);
eetrans[0]=(((x7*x9))+(((-1.0)*x0*x4*x6))+(((0.066)*x0))+(((0.109)*x9)));
eetrans[1]=(((x7*x8))+(((-1.0)*x3*x4*x6))+(((0.066)*x3))+(((0.109)*x8)));
eetrans[2]=((((-1.0)*x4*x7))+(((-0.109)*x4))+(((-1.0)*x1*x6)));
}
IKFAST_API int GetNumFreeParameters() { return 0; }
IKFAST_API int* GetFreeParameters() { return NULL; }
IKFAST_API int GetNumJoints() { return 3; }
IKFAST_API int GetIkRealSize() { return sizeof(IkReal); }
IKFAST_API int GetIkType() { return 0x33000003; }
class IKSolver {
public:
IkReal j0,cj0,sj0,htj0,j0mul,j1,cj1,sj1,htj1,j1mul,j2,cj2,sj2,htj2,j2mul,new_px,px,npx,new_py,py,npy,new_pz,pz,npz,pp;
unsigned char _ij0[2], _nj0,_ij1[2], _nj1,_ij2[2], _nj2;
IkReal j100, cj100, sj100;
unsigned char _ij100[2], _nj100;
bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) {
j0=numeric_limits<IkReal>::quiet_NaN(); _ij0[0] = -1; _ij0[1] = -1; _nj0 = -1; j1=numeric_limits<IkReal>::quiet_NaN(); _ij1[0] = -1; _ij1[1] = -1; _nj1 = -1; j2=numeric_limits<IkReal>::quiet_NaN(); _ij2[0] = -1; _ij2[1] = -1; _nj2 = -1;
for(int dummyiter = 0; dummyiter < 1; ++dummyiter) {
solutions.Clear();
px = eetrans[0]; py = eetrans[1]; pz = eetrans[2];
new_px=px;
new_py=py;
new_pz=pz;
px = new_px; py = new_py; pz = new_pz;
pp=((px*px)+(py*py)+(pz*pz));
{
IkReal j0eval[1];
j0eval[0]=((IKabs(px))+(IKabs(py)));
if( IKabs(j0eval[0]) < 0.0000010000000000 )
{
{
IkReal evalcond[1];
bool bgotonextstatement = true;
do
{
evalcond[0]=((IKabs(px))+(IKabs(py)));
if( IKabs(evalcond[0]) < 0.0000050000000000 )
{
bgotonextstatement=false;
{
IkReal j2array[2], cj2array[2], sj2array[2];
bool j2valid[2]={false};
_nj2 = 2;
cj2array[0]=((-1.59277664514668)+(((14.1578887756258)*(pz*pz))));
if( cj2array[0] >= -1-IKFAST_SINCOS_THRESH && cj2array[0] <= 1+IKFAST_SINCOS_THRESH )
{
j2valid[0] = j2valid[1] = true;
j2array[0] = IKacos(cj2array[0]);
sj2array[0] = IKsin(j2array[0]);
cj2array[1] = cj2array[0];
j2array[1] = -j2array[0];
sj2array[1] = -sj2array[0];
}
else if( isnan(cj2array[0]) )
{
// probably any value will work
j2valid[0] = true;
cj2array[0] = 1; sj2array[0] = 0; j2array[0] = 0;
}
for(int ij2 = 0; ij2 < 2; ++ij2)
{
if( !j2valid[ij2] )
{
continue;
}
_ij2[0] = ij2; _ij2[1] = -1;
for(int iij2 = ij2+1; iij2 < 2; ++iij2)
{
if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH )
{
j2valid[iij2]=false; _ij2[1] = iij2; break;
}
}
j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2];
{
IkReal j1eval[3];
px=0;
py=0;
pp=pz*pz;
IkReal x10=pz*pz;
IkReal x11=((81000.0)*pz);
j1eval[0]=((1.0)+(((229.568411386593)*x10)));
j1eval[1]=((IKabs(((-1798.5)+(((-1.0)*sj2*x11))+(((-5346.0)*cj2)))))+(IKabs(((((5346.0)*sj2))+(((-27250.0)*pz))+(((-1.0)*cj2*x11))))));
j1eval[2]=IKsign(((1089.0)+(((250000.0)*x10))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
{
IkReal j1eval[3];
px=0;
py=0;
pp=pz*pz;
IkReal x12=pz*pz;
j1eval[0]=((1.0)+(((229.568411386593)*x12)));
j1eval[1]=IKsign(((118701.0)+(((27250000.0)*x12))));
j1eval[2]=((IKabs(((((11092375.0)*pz))+(((-125000000.0)*(pz*pz*pz)))+(((582714.0)*sj2)))))+(IKabs(((732096.75)+(((-8829000.0)*pz*sj2))+(((-8250000.0)*x12))))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
{
IkReal j1eval[3];
px=0;
py=0;
pp=pz*pz;
IkReal x13=(cj2*pz);
j1eval[0]=((((15.1515151515152)*x13))+sj2+(((5.09726898615788)*pz)));
j1eval[1]=((IKabs(((13122.0)+(((-13122.0)*(cj2*cj2)))+(((-125000.0)*(pz*pz))))))+(IKabs(((((-4414.5)*sj2))+(((-13122.0)*cj2*sj2))+(((-8250.0)*pz))))));
j1eval[2]=IKsign(((((13625.0)*pz))+(((40500.0)*x13))+(((2673.0)*sj2))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
{
IkReal evalcond[1];
bool bgotonextstatement = true;
do
{
IkReal x14=pz*pz;
IkReal x15=((15.1515151515152)*pz);
IkReal x16=((1.0)+(((229.568411386593)*x14)));
IkReal x23 = x16;
if(IKabs(x23)==0){
continue;
}
IkReal x17=pow(x23,-0.5);
if((x16) < -0.00001)
continue;
IkReal x18=IKabs(IKsqrt(x16));
CheckValue<IkReal> x24=IKPowWithIntegerCheck(x18,-1);
if(!x24.valid){
continue;
}
IkReal x19=x24.value;
IkReal x20=((5.09726898615788)*pz*x19);
if((((1.0)+(((-25.9821511172469)*x14*(x19*x19))))) < -0.00001)
continue;
IkReal x21=IKsqrt(((1.0)+(((-25.9821511172469)*x14*(x19*x19)))));
IkReal x22=(x17*x21);
CheckValue<IkReal> x25 = IKatan2WithCheck(IkReal(x15),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x25.valid){
continue;
}
if( (x20) < -1-IKFAST_SINCOS_THRESH || (x20) > 1+IKFAST_SINCOS_THRESH )
continue;
IkReal gconst0=((((-1.0)*(x25.value)))+(((-1.0)*(IKasin(x20)))));
IkReal gconst1=((((-1.0)*x17*x20))+(((-1.0)*x15*x22)));
IkReal gconst2=((((-77.2313482751193)*x14*x17*x19))+x22);
if((((1.0)+(((229.568411386593)*(pz*pz))))) < -0.00001)
continue;
CheckValue<IkReal> x26=IKPowWithIntegerCheck(IKabs(IKsqrt(((1.0)+(((229.568411386593)*(pz*pz)))))),-1);
if(!x26.valid){
continue;
}
if( (((5.09726898615788)*pz*(x26.value))) < -1-IKFAST_SINCOS_THRESH || (((5.09726898615788)*pz*(x26.value))) > 1+IKFAST_SINCOS_THRESH )
continue;
CheckValue<IkReal> x27 = IKatan2WithCheck(IkReal(((15.1515151515152)*pz)),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x27.valid){
continue;
}
evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((IKasin(((5.09726898615788)*pz*(x26.value))))+j2+(x27.value))))), 6.28318530717959)));
if( IKabs(evalcond[0]) < 0.0000050000000000 )
{
bgotonextstatement=false;
{
IkReal j1eval[2];
IkReal x28=pz*pz;
IkReal x29=((15.1515151515152)*pz);
CheckValue<IkReal> x38 = IKatan2WithCheck(IkReal(x29),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x38.valid){
continue;
}
IkReal x30=((1.0)*(x38.value));
IkReal x31=x16;
IkReal x39 = x31;
if(IKabs(x39)==0){
continue;
}
IkReal x32=pow(x39,-0.5);
if((x31) < -0.00001)
continue;
IkReal x33=IKabs(IKsqrt(x31));
CheckValue<IkReal> x40=IKPowWithIntegerCheck(x33,-1);
if(!x40.valid){
continue;
}
IkReal x34=x40.value;
IkReal x35=(pz*x34);
if((((1.0)+(((-25.9821511172469)*x28*(x34*x34))))) < -0.00001)
continue;
IkReal x36=IKsqrt(((1.0)+(((-25.9821511172469)*x28*(x34*x34)))));
IkReal x37=(x32*x36);
px=0;
py=0;
pp=x28;
sj2=gconst1;
cj2=gconst2;
if( (((5.09726888842685)*x35)) < -1-IKFAST_SINCOS_THRESH || (((5.09726888842685)*x35)) > 1+IKFAST_SINCOS_THRESH )
continue;
j2=((((-1.0)*(IKasin(((5.09726888842685)*x35)))))+(((-1.0)*x30)));
if( (((5.09726898615788)*x35)) < -1-IKFAST_SINCOS_THRESH || (((5.09726898615788)*x35)) > 1+IKFAST_SINCOS_THRESH )
continue;
IkReal gconst0=((((-1.0)*x30))+(((-1.0)*(IKasin(((5.09726898615788)*x35))))));
IkReal gconst1=((((-1.0)*x29*x37))+(((-5.09726898615788)*x32*x35)));
IkReal gconst2=(x37+(((-77.2313482751193)*x28*x32*x34)));
IkReal x41=pz*pz;
j1eval[0]=((1.0)+(((229.568411386593)*x41)));
j1eval[1]=IKsign(((1089.0)+(((250000.0)*x41))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 )
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x42=(gconst1*pz);
CheckValue<IkReal> x43=IKPowWithIntegerCheck(((1.199)+(((-54.0)*x42))+(((3.564)*gconst2))),-1);
if(!x43.valid){
continue;
}
CheckValue<IkReal> x44=IKPowWithIntegerCheck(((599.5)+(((-27000.0)*x42))+(((1782.0)*gconst2))),-1);
if(!x44.valid){
continue;
}
if( IKabs(((x43.value)*(((((-11.0)*pz))+(((17.496)*gconst1*gconst2))+(((5.886)*gconst1)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((x44.value)*(((-363.0)+(((8748.0)*(gconst1*gconst1))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((x43.value)*(((((-11.0)*pz))+(((17.496)*gconst1*gconst2))+(((5.886)*gconst1))))))+IKsqr(((x44.value)*(((-363.0)+(((8748.0)*(gconst1*gconst1)))))))-1) <= IKFAST_SINCOS_THRESH )
continue;
j1array[0]=IKatan2(((x43.value)*(((((-11.0)*pz))+(((17.496)*gconst1*gconst2))+(((5.886)*gconst1))))), ((x44.value)*(((-363.0)+(((8748.0)*(gconst1*gconst1)))))));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x45=IKsin(j1);
IkReal x46=IKcos(j1);
IkReal x47=((0.324)*gconst2);
IkReal x48=((0.324)*gconst1);
IkReal x49=(pz*x45);
evalcond[0]=(((pz*x46))+(((-0.066)*x45))+x48);
evalcond[1]=((0.109)+x49+x47+(((0.066)*x46)));
evalcond[2]=((0.088739)+(((-0.014388)*x46))+(((-1.0)*(pz*pz)))+(((-0.218)*x49)));
evalcond[3]=(((x46*x48))+pz+((x45*x47))+(((0.109)*x45)));
evalcond[4]=((0.066)+((x46*x47))+(((-1.0)*x45*x48))+(((0.109)*x46)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x50=((81000.0)*pz);
CheckValue<IkReal> x51=IKPowWithIntegerCheck(IKsign(((1089.0)+(((250000.0)*(pz*pz))))),-1);
if(!x51.valid){
continue;
}
CheckValue<IkReal> x52 = IKatan2WithCheck(IkReal(((((-27250.0)*pz))+(((-1.0)*gconst2*x50))+(((5346.0)*gconst1)))),IkReal(((-1798.5)+(((-1.0)*gconst1*x50))+(((-5346.0)*gconst2)))),IKFAST_ATAN2_MAGTHRESH);
if(!x52.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x51.value)))+(x52.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x53=IKsin(j1);
IkReal x54=IKcos(j1);
IkReal x55=((0.324)*gconst2);
IkReal x56=((0.324)*gconst1);
IkReal x57=(pz*x53);
evalcond[0]=((((-0.066)*x53))+x56+((pz*x54)));
evalcond[1]=((0.109)+(((0.066)*x54))+x55+x57);
evalcond[2]=((0.088739)+(((-0.218)*x57))+(((-1.0)*(pz*pz)))+(((-0.014388)*x54)));
evalcond[3]=((((0.109)*x53))+pz+((x53*x55))+((x54*x56)));
evalcond[4]=((0.066)+(((-1.0)*x53*x56))+(((0.109)*x54))+((x54*x55)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
}
} while(0);
if( bgotonextstatement )
{
bool bgotonextstatement = true;
do
{
IkReal x58=pz*pz;
IkReal x59=((15.1515151515152)*pz);
IkReal x60=((1.0)+(((229.568411386593)*x58)));
if((x60) < -0.00001)
continue;
IkReal x61=IKabs(IKsqrt(x60));
IkReal x67 = x60;
if(IKabs(x67)==0){
continue;
}
IkReal x62=pow(x67,-0.5);
CheckValue<IkReal> x68=IKPowWithIntegerCheck(x61,-1);
if(!x68.valid){
continue;
}
IkReal x63=x68.value;
IkReal x64=((5.09726898615788)*pz*x63);
if((((1.0)+(((-25.9821511172469)*x58*(x63*x63))))) < -0.00001)
continue;
IkReal x65=IKsqrt(((1.0)+(((-25.9821511172469)*x58*(x63*x63)))));
IkReal x66=(x62*x65);
if( (x64) < -1-IKFAST_SINCOS_THRESH || (x64) > 1+IKFAST_SINCOS_THRESH )
continue;
CheckValue<IkReal> x69 = IKatan2WithCheck(IkReal(x59),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x69.valid){
continue;
}
IkReal gconst3=((3.14159265358979)+(IKasin(x64))+(((-1.0)*(x69.value))));
IkReal gconst4=(((x59*x66))+(((-1.0)*x62*x64)));
IkReal gconst5=((((-77.2313482751193)*x58*x62*x63))+(((-1.0)*x66)));
if((((1.0)+(((229.568411386593)*(pz*pz))))) < -0.00001)
continue;
CheckValue<IkReal> x70=IKPowWithIntegerCheck(IKabs(IKsqrt(((1.0)+(((229.568411386593)*(pz*pz)))))),-1);
if(!x70.valid){
continue;
}
if( (((5.09726898615788)*pz*(x70.value))) < -1-IKFAST_SINCOS_THRESH || (((5.09726898615788)*pz*(x70.value))) > 1+IKFAST_SINCOS_THRESH )
continue;
CheckValue<IkReal> x71 = IKatan2WithCheck(IkReal(((15.1515151515152)*pz)),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x71.valid){
continue;
}
evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j2+(((-1.0)*(IKasin(((5.09726898615788)*pz*(x70.value))))))+(x71.value))))), 6.28318530717959)));
if( IKabs(evalcond[0]) < 0.0000050000000000 )
{
bgotonextstatement=false;
{
IkReal j1eval[2];
IkReal x72=pz*pz;
IkReal x73=((15.1515151515152)*pz);
CheckValue<IkReal> x82 = IKatan2WithCheck(IkReal(x73),IkReal(1.0),IKFAST_ATAN2_MAGTHRESH);
if(!x82.valid){
continue;
}
IkReal x74=((1.0)*(x82.value));
IkReal x75=x60;
if((x75) < -0.00001)
continue;
IkReal x76=IKabs(IKsqrt(x75));
IkReal x83 = x75;
if(IKabs(x83)==0){
continue;
}
IkReal x77=pow(x83,-0.5);
CheckValue<IkReal> x84=IKPowWithIntegerCheck(x76,-1);
if(!x84.valid){
continue;
}
IkReal x78=x84.value;
IkReal x79=(pz*x78);
if((((1.0)+(((-25.9821511172469)*x72*(x78*x78))))) < -0.00001)
continue;
IkReal x80=IKsqrt(((1.0)+(((-25.9821511172469)*x72*(x78*x78)))));
IkReal x81=(x77*x80);
px=0;
py=0;
pp=x72;
sj2=gconst4;
cj2=gconst5;
if( (((5.09726888842685)*x79)) < -1-IKFAST_SINCOS_THRESH || (((5.09726888842685)*x79)) > 1+IKFAST_SINCOS_THRESH )
continue;
j2=((3.14159265)+(IKasin(((5.09726888842685)*x79)))+(((-1.0)*x74)));
if( (((5.09726898615788)*x79)) < -1-IKFAST_SINCOS_THRESH || (((5.09726898615788)*x79)) > 1+IKFAST_SINCOS_THRESH )
continue;
IkReal gconst3=((3.14159265358979)+(((-1.0)*x74))+(IKasin(((5.09726898615788)*x79))));
IkReal gconst4=(((x73*x81))+(((-5.09726898615788)*x77*x79)));
IkReal gconst5=((((-1.0)*x81))+(((-77.2313482751193)*x72*x77*x78)));
IkReal x85=pz*pz;
j1eval[0]=((1.0)+(((229.568411386593)*x85)));
j1eval[1]=IKsign(((1089.0)+(((250000.0)*x85))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 )
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
CheckValue<IkReal> x86=IKPowWithIntegerCheck(IKsign(((((13625.0)*pz))+(((40500.0)*gconst5*pz))+(((2673.0)*gconst4)))),-1);
if(!x86.valid){
continue;
}
CheckValue<IkReal> x87 = IKatan2WithCheck(IkReal(((((13122.0)*(gconst4*gconst4)))+(((-125000.0)*(pz*pz))))),IkReal(((((-13122.0)*gconst4*gconst5))+(((-4414.5)*gconst4))+(((-8250.0)*pz)))),IKFAST_ATAN2_MAGTHRESH);
if(!x87.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x86.value)))+(x87.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x88=IKsin(j1);
IkReal x89=IKcos(j1);
IkReal x90=((0.324)*gconst5);
IkReal x91=((0.324)*gconst4);
IkReal x92=((0.324)*x89);
IkReal x93=(pz*x88);
evalcond[0]=(((pz*x89))+x91+(((-0.066)*x88)));
evalcond[1]=((0.109)+(((0.066)*x89))+x90+x93);
evalcond[2]=((0.088739)+(((-0.014388)*x89))+(((-0.218)*x93))+(((-1.0)*(pz*pz))));
evalcond[3]=(((x89*x91))+((x88*x90))+pz+(((0.109)*x88)));
evalcond[4]=((0.066)+((x89*x90))+(((0.109)*x89))+(((-1.0)*x88*x91)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x94=((81000.0)*pz);
CheckValue<IkReal> x95=IKPowWithIntegerCheck(IKsign(((1089.0)+(((250000.0)*(pz*pz))))),-1);
if(!x95.valid){
continue;
}
CheckValue<IkReal> x96 = IKatan2WithCheck(IkReal(((((-1.0)*gconst5*x94))+(((-27250.0)*pz))+(((5346.0)*gconst4)))),IkReal(((-1798.5)+(((-1.0)*gconst4*x94))+(((-5346.0)*gconst5)))),IKFAST_ATAN2_MAGTHRESH);
if(!x96.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x95.value)))+(x96.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x97=IKsin(j1);
IkReal x98=IKcos(j1);
IkReal x99=((0.324)*gconst5);
IkReal x100=((0.324)*gconst4);
IkReal x101=((0.324)*x98);
IkReal x102=(pz*x97);
evalcond[0]=(x100+((pz*x98))+(((-0.066)*x97)));
evalcond[1]=((0.109)+x102+x99+(((0.066)*x98)));
evalcond[2]=((0.088739)+(((-0.014388)*x98))+(((-1.0)*(pz*pz)))+(((-0.218)*x102)));
evalcond[3]=(((x100*x98))+((x97*x99))+(((0.109)*x97))+pz);
evalcond[4]=((0.066)+(((0.109)*x98))+((x98*x99))+(((-1.0)*x100*x97)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
}
} while(0);
if( bgotonextstatement )
{
bool bgotonextstatement = true;
do
{
if( 1 )
{
bgotonextstatement=false;
continue; // branch miss [j0, j1]
}
} while(0);
if( bgotonextstatement )
{
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
CheckValue<IkReal> x103 = IKatan2WithCheck(IkReal(((13122.0)+(((-13122.0)*(cj2*cj2)))+(((-125000.0)*(pz*pz))))),IkReal(((((-4414.5)*sj2))+(((-13122.0)*cj2*sj2))+(((-8250.0)*pz)))),IKFAST_ATAN2_MAGTHRESH);
if(!x103.valid){
continue;
}
CheckValue<IkReal> x104=IKPowWithIntegerCheck(IKsign(((((13625.0)*pz))+(((40500.0)*cj2*pz))+(((2673.0)*sj2)))),-1);
if(!x104.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(x103.value)+(((1.5707963267949)*(x104.value))));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x105=IKsin(j1);
IkReal x106=IKcos(j1);
IkReal x107=((0.324)*cj2);
IkReal x108=((0.324)*sj2);
IkReal x109=(pz*x105);
evalcond[0]=(((pz*x106))+x108+(((-0.066)*x105)));
evalcond[1]=((0.109)+x109+x107+(((0.066)*x106)));
evalcond[2]=((0.088739)+(((-1.0)*(pz*pz)))+(((-0.218)*x109))+(((-0.014388)*x106)));
evalcond[3]=(((x106*x108))+pz+(((0.109)*x105))+((x105*x107)));
evalcond[4]=((0.066)+((x106*x107))+(((0.109)*x106))+(((-1.0)*x105*x108)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x110=pz*pz;
CheckValue<IkReal> x111=IKPowWithIntegerCheck(IKsign(((118701.0)+(((27250000.0)*x110)))),-1);
if(!x111.valid){
continue;
}
CheckValue<IkReal> x112 = IKatan2WithCheck(IkReal(((((11092375.0)*pz))+(((-125000000.0)*(pz*pz*pz)))+(((582714.0)*sj2)))),IkReal(((732096.75)+(((-8250000.0)*x110))+(((-8829000.0)*pz*sj2)))),IKFAST_ATAN2_MAGTHRESH);
if(!x112.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x111.value)))+(x112.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x113=IKsin(j1);
IkReal x114=IKcos(j1);
IkReal x115=((0.324)*cj2);
IkReal x116=((0.324)*sj2);
IkReal x117=(pz*x113);
evalcond[0]=(((pz*x114))+(((-0.066)*x113))+x116);
evalcond[1]=((0.109)+x117+x115+(((0.066)*x114)));
evalcond[2]=((0.088739)+(((-1.0)*(pz*pz)))+(((-0.218)*x117))+(((-0.014388)*x114)));
evalcond[3]=(((x114*x116))+((x113*x115))+pz+(((0.109)*x113)));
evalcond[4]=((0.066)+((x114*x115))+(((-1.0)*x113*x116))+(((0.109)*x114)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x118=((81000.0)*pz);
CheckValue<IkReal> x119=IKPowWithIntegerCheck(IKsign(((1089.0)+(((250000.0)*(pz*pz))))),-1);
if(!x119.valid){
continue;
}
CheckValue<IkReal> x120 = IKatan2WithCheck(IkReal(((((-1.0)*cj2*x118))+(((5346.0)*sj2))+(((-27250.0)*pz)))),IkReal(((-1798.5)+(((-5346.0)*cj2))+(((-1.0)*sj2*x118)))),IKFAST_ATAN2_MAGTHRESH);
if(!x120.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x119.value)))+(x120.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x121=IKsin(j1);
IkReal x122=IKcos(j1);
IkReal x123=((0.324)*cj2);
IkReal x124=((0.324)*sj2);
IkReal x125=(pz*x121);
evalcond[0]=((((-0.066)*x121))+x124+((pz*x122)));
evalcond[1]=((0.109)+x125+x123+(((0.066)*x122)));
evalcond[2]=((0.088739)+(((-0.014388)*x122))+(((-1.0)*(pz*pz)))+(((-0.218)*x125)));
evalcond[3]=(((x121*x123))+((x122*x124))+(((0.109)*x121))+pz);
evalcond[4]=((0.066)+((x122*x123))+(((0.109)*x122))+(((-1.0)*x121*x124)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
IkReal j0array[1], cj0array[1], sj0array[1];
bool j0valid[1]={false};
_nj0 = 1;
j0array[0]=0;
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
for(int ij0 = 0; ij0 < 1; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 1; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
}
}
}
} while(0);
if( bgotonextstatement )
{
bool bgotonextstatement = true;
do
{
if( 1 )
{
bgotonextstatement=false;
continue; // branch miss [j0, j1, j2]
}
} while(0);
if( bgotonextstatement )
{
}
}
}
} else
{
{
IkReal j0array[2], cj0array[2], sj0array[2];
bool j0valid[2]={false};
_nj0 = 2;
CheckValue<IkReal> x127 = IKatan2WithCheck(IkReal(((-1.0)*py)),IkReal(px),IKFAST_ATAN2_MAGTHRESH);
if(!x127.valid){
continue;
}
IkReal x126=x127.value;
j0array[0]=((-1.0)*x126);
sj0array[0]=IKsin(j0array[0]);
cj0array[0]=IKcos(j0array[0]);
j0array[1]=((3.14159265358979)+(((-1.0)*x126)));
sj0array[1]=IKsin(j0array[1]);
cj0array[1]=IKcos(j0array[1]);
if( j0array[0] > IKPI )
{
j0array[0]-=IK2PI;
}
else if( j0array[0] < -IKPI )
{ j0array[0]+=IK2PI;
}
j0valid[0] = true;
if( j0array[1] > IKPI )
{
j0array[1]-=IK2PI;
}
else if( j0array[1] < -IKPI )
{ j0array[1]+=IK2PI;
}
j0valid[1] = true;
for(int ij0 = 0; ij0 < 2; ++ij0)
{
if( !j0valid[ij0] )
{
continue;
}
_ij0[0] = ij0; _ij0[1] = -1;
for(int iij0 = ij0+1; iij0 < 2; ++iij0)
{
if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH )
{
j0valid[iij0]=false; _ij0[1] = iij0; break;
}
}
j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0];
{
IkReal j2array[2], cj2array[2], sj2array[2];
bool j2valid[2]={false};
_nj2 = 2;
cj2array[0]=((-1.59277664514668)+(((14.1578887756258)*(px*px)))+(((14.1578887756258)*(pz*pz)))+(((14.1578887756258)*(py*py)))+(((-1.8688413183826)*cj0*px))+(((-1.8688413183826)*py*sj0)));
if( cj2array[0] >= -1-IKFAST_SINCOS_THRESH && cj2array[0] <= 1+IKFAST_SINCOS_THRESH )
{
j2valid[0] = j2valid[1] = true;
j2array[0] = IKacos(cj2array[0]);
sj2array[0] = IKsin(j2array[0]);
cj2array[1] = cj2array[0];
j2array[1] = -j2array[0];
sj2array[1] = -sj2array[0];
}
else if( isnan(cj2array[0]) )
{
// probably any value will work
j2valid[0] = true;
cj2array[0] = 1; sj2array[0] = 0; j2array[0] = 0;
}
for(int ij2 = 0; ij2 < 2; ++ij2)
{
if( !j2valid[ij2] )
{
continue;
}
_ij2[0] = ij2; _ij2[1] = -1;
for(int iij2 = ij2+1; iij2 < 2; ++iij2)
{
if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH )
{
j2valid[iij2]=false; _ij2[1] = iij2; break;
}
}
j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2];
{
IkReal j1eval[3];
IkReal x128=((20250.0)*cj2);
IkReal x129=(py*sj0);
IkReal x130=(cj0*px);
IkReal x131=((20250.0)*sj2);
j1eval[0]=((1.6544484086533)+cj2);
j1eval[1]=IKsign(((7303.5625)+(((4414.5)*cj2))));
j1eval[2]=((IKabs(((((-6812.5)*pz))+(((-1.0)*pz*x128))+(((1336.5)*sj2))+(((-1.0)*x129*x131))+(((-1.0)*x130*x131)))))+(IKabs(((-449.625)+(((-1.0)*pz*x131))+(((-1336.5)*cj2))+(((6812.5)*x130))+((x128*x130))+(((6812.5)*x129))+((x128*x129))))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
{
IkReal j1eval[3];
IkReal x132=(cj0*px);
IkReal x133=(py*sj0);
IkReal x134=((250.0)*pz);
IkReal x135=(pz*sj2);
IkReal x136=((45.0375312760634)*cj2);
IkReal x137=((81.0)*cj2);
j1eval[0]=((1.0)+(((-45.0375312760634)*x135))+(((-15.1515151515152)*x132))+(((-15.1515151515152)*x133))+(((-1.0)*x133*x136))+(((2.97247706422018)*cj2))+(((-1.0)*x132*x136)));
j1eval[1]=IKsign(((1.7985)+(((-81.0)*x135))+(((5.346)*cj2))+(((-1.0)*x133*x137))+(((-1.0)*x132*x137))+(((-27.25)*x133))+(((-27.25)*x132))));
j1eval[2]=((IKabs(((((26.244)*cj2*sj2))+((x133*x134))+((x132*x134))+(((8.829)*sj2))+(((-16.5)*pz)))))+(IKabs(((-2.97025)+(((-26.244)*(cj2*cj2)))+(((-17.658)*cj2))+((pz*x134))))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
{
IkReal j1eval[3];
IkReal x138=py*py;
IkReal x139=cj0*cj0;
IkReal x140=px*px;
IkReal x141=pz*pz;
IkReal x142=(py*sj0);
IkReal x143=((81.0)*sj2);
IkReal x144=(cj0*px);
IkReal x145=((81.0)*cj2);
IkReal x146=((229.568411386593)*x138);
IkReal x147=((250.0)*x138);
IkReal x148=(x139*x140);
j1eval[0]=((-1.0)+(((-1.0)*x146))+(((30.3030303030303)*x144))+(((30.3030303030303)*x142))+(((-459.136822773186)*x142*x144))+(((-229.568411386593)*x148))+(((-229.568411386593)*x141))+((x139*x146)));
j1eval[1]=((IKabs((((pz*x145))+((x142*x143))+(((27.25)*pz))+(((-5.346)*sj2))+((x143*x144)))))+(IKabs(((1.7985)+((pz*x143))+(((-1.0)*x142*x145))+(((5.346)*cj2))+(((-1.0)*x144*x145))+(((-27.25)*x144))+(((-27.25)*x142))))));
j1eval[2]=IKsign(((-1.089)+(((-1.0)*x147))+(((33.0)*x144))+(((33.0)*x142))+(((-500.0)*x142*x144))+(((-250.0)*x148))+(((-250.0)*x141))+((x139*x147))));
if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 )
{
continue; // no branches [j1]
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x149=cj0*cj0;
IkReal x150=py*py;
IkReal x151=(cj0*px);
IkReal x152=(py*sj0);
IkReal x153=((81.0)*sj2);
IkReal x154=((81.0)*cj2);
IkReal x155=((250.0)*x150);
CheckValue<IkReal> x156=IKPowWithIntegerCheck(IKsign(((-1.089)+((x149*x155))+(((-1.0)*x155))+(((33.0)*x151))+(((33.0)*x152))+(((-500.0)*x151*x152))+(((-250.0)*x149*(px*px)))+(((-250.0)*(pz*pz))))),-1);
if(!x156.valid){
continue;
}
CheckValue<IkReal> x157 = IKatan2WithCheck(IkReal((((x152*x153))+(((27.25)*pz))+((x151*x153))+(((-5.346)*sj2))+((pz*x154)))),IkReal(((1.7985)+(((-1.0)*x151*x154))+(((5.346)*cj2))+(((-1.0)*x152*x154))+(((-27.25)*x152))+(((-27.25)*x151))+((pz*x153)))),IKFAST_ATAN2_MAGTHRESH);
if(!x157.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x156.value)))+(x157.value));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x158=IKsin(j1);
IkReal x159=IKcos(j1);
IkReal x160=(py*sj0);
IkReal x161=((0.324)*sj2);
IkReal x162=(cj0*px);
IkReal x163=((0.324)*cj2);
IkReal x164=((0.218)*x159);
IkReal x165=(pz*x158);
IkReal x166=((1.0)*x159);
evalcond[0]=(pz+((x158*x163))+((x159*x161))+(((0.109)*x158)));
evalcond[1]=((((-0.066)*x158))+x161+((x158*x162))+((x158*x160))+((pz*x159)));
evalcond[2]=((0.066)+(((-1.0)*x158*x161))+(((-1.0)*x160))+(((-1.0)*x162))+((x159*x163))+(((0.109)*x159)));
evalcond[3]=((0.109)+(((-1.0)*x160*x166))+x163+x165+(((-1.0)*x162*x166))+(((0.066)*x159)));
evalcond[4]=((0.088739)+(((-1.0)*(px*px)))+(((-0.014388)*x159))+((x162*x164))+(((0.132)*x160))+(((0.132)*x162))+(((-1.0)*(pz*pz)))+(((-0.218)*x165))+(((-1.0)*(py*py)))+((x160*x164)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x167=(py*sj0);
IkReal x168=((250.0)*pz);
IkReal x169=(cj0*px);
IkReal x170=((81.0)*cj2);
CheckValue<IkReal> x171 = IKatan2WithCheck(IkReal(((((26.244)*cj2*sj2))+((x168*x169))+((x167*x168))+(((8.829)*sj2))+(((-16.5)*pz)))),IkReal(((-2.97025)+(((-26.244)*(cj2*cj2)))+((pz*x168))+(((-17.658)*cj2)))),IKFAST_ATAN2_MAGTHRESH);
if(!x171.valid){
continue;
}
CheckValue<IkReal> x172=IKPowWithIntegerCheck(IKsign(((1.7985)+(((5.346)*cj2))+(((-27.25)*x169))+(((-27.25)*x167))+(((-81.0)*pz*sj2))+(((-1.0)*x169*x170))+(((-1.0)*x167*x170)))),-1);
if(!x172.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(x171.value)+(((1.5707963267949)*(x172.value))));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x173=IKsin(j1);
IkReal x174=IKcos(j1);
IkReal x175=(py*sj0);
IkReal x176=((0.324)*sj2);
IkReal x177=(cj0*px);
IkReal x178=((0.324)*cj2);
IkReal x179=((0.218)*x174);
IkReal x180=(pz*x173);
IkReal x181=((1.0)*x174);
evalcond[0]=(((x173*x178))+((x174*x176))+pz+(((0.109)*x173)));
evalcond[1]=(((pz*x174))+((x173*x175))+((x173*x177))+x176+(((-0.066)*x173)));
evalcond[2]=((0.066)+(((-1.0)*x177))+(((-1.0)*x175))+((x174*x178))+(((0.109)*x174))+(((-1.0)*x173*x176)));
evalcond[3]=((0.109)+x178+x180+(((-1.0)*x177*x181))+(((-1.0)*x175*x181))+(((0.066)*x174)));
evalcond[4]=((0.088739)+(((-1.0)*(px*px)))+(((-0.014388)*x174))+((x175*x179))+(((-0.218)*x180))+(((-1.0)*(pz*pz)))+(((0.132)*x177))+(((0.132)*x175))+(((-1.0)*(py*py)))+((x177*x179)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
} else
{
{
IkReal j1array[1], cj1array[1], sj1array[1];
bool j1valid[1]={false};
_nj1 = 1;
IkReal x182=((20250.0)*cj2);
IkReal x183=(py*sj0);
IkReal x184=(cj0*px);
IkReal x185=((20250.0)*sj2);
CheckValue<IkReal> x186 = IKatan2WithCheck(IkReal(((((-6812.5)*pz))+(((-1.0)*pz*x182))+(((-1.0)*x184*x185))+(((1336.5)*sj2))+(((-1.0)*x183*x185)))),IkReal(((-449.625)+(((6812.5)*x184))+(((6812.5)*x183))+(((-1.0)*pz*x185))+(((-1336.5)*cj2))+((x182*x183))+((x182*x184)))),IKFAST_ATAN2_MAGTHRESH);
if(!x186.valid){
continue;
}
CheckValue<IkReal> x187=IKPowWithIntegerCheck(IKsign(((7303.5625)+(((4414.5)*cj2)))),-1);
if(!x187.valid){
continue;
}
j1array[0]=((-1.5707963267949)+(x186.value)+(((1.5707963267949)*(x187.value))));
sj1array[0]=IKsin(j1array[0]);
cj1array[0]=IKcos(j1array[0]);
if( j1array[0] > IKPI )
{
j1array[0]-=IK2PI;
}
else if( j1array[0] < -IKPI )
{ j1array[0]+=IK2PI;
}
j1valid[0] = true;
for(int ij1 = 0; ij1 < 1; ++ij1)
{
if( !j1valid[ij1] )
{
continue;
}
_ij1[0] = ij1; _ij1[1] = -1;
for(int iij1 = ij1+1; iij1 < 1; ++iij1)
{
if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH )
{
j1valid[iij1]=false; _ij1[1] = iij1; break;
}
}
j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1];
{
IkReal evalcond[5];
IkReal x188=IKsin(j1);
IkReal x189=IKcos(j1);
IkReal x190=(py*sj0);
IkReal x191=((0.324)*sj2);
IkReal x192=(cj0*px);
IkReal x193=((0.324)*cj2);
IkReal x194=((0.218)*x189);
IkReal x195=(pz*x188);
IkReal x196=((1.0)*x189);
evalcond[0]=(((x188*x193))+((x189*x191))+pz+(((0.109)*x188)));
evalcond[1]=(((pz*x189))+((x188*x190))+((x188*x192))+x191+(((-0.066)*x188)));
evalcond[2]=((0.066)+(((-1.0)*x188*x191))+(((-1.0)*x192))+(((-1.0)*x190))+((x189*x193))+(((0.109)*x189)));
evalcond[3]=((0.109)+(((-1.0)*x192*x196))+(((-1.0)*x190*x196))+x193+x195+(((0.066)*x189)));
evalcond[4]=((0.088739)+(((-1.0)*(px*px)))+(((-0.014388)*x189))+(((-0.218)*x195))+((x192*x194))+(((-1.0)*(pz*pz)))+((x190*x194))+(((0.132)*x190))+(((0.132)*x192))+(((-1.0)*(py*py))));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH )
{
continue;
}
}
{
std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(3);
vinfos[0].jointtype = 1;
vinfos[0].foffset = j0;
vinfos[0].indices[0] = _ij0[0];
vinfos[0].indices[1] = _ij0[1];
vinfos[0].maxsolutions = _nj0;
vinfos[1].jointtype = 1;
vinfos[1].foffset = j1;
vinfos[1].indices[0] = _ij1[0];
vinfos[1].indices[1] = _ij1[1];
vinfos[1].maxsolutions = _nj1;
vinfos[2].jointtype = 1;
vinfos[2].foffset = j2;
vinfos[2].indices[0] = _ij2[0];
vinfos[2].indices[1] = _ij2[1];
vinfos[2].maxsolutions = _nj2;
std::vector<int> vfree(0);
solutions.AddSolution(vinfos,vfree);
}
}
}
}
}
}
}
}
}
}
}
}
return solutions.GetNumSolutions()>0;
}
};
/// solves the inverse kinematics equations.
/// \param pfree is an array specifying the free joints of the chain.
IKFAST_API bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) {
IKSolver solver;
return solver.ComputeIk(eetrans,eerot,pfree,solutions);
}
IKFAST_API bool ComputeIk2(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions, void* pOpenRAVEManip) {
IKSolver solver;
return solver.ComputeIk(eetrans,eerot,pfree,solutions);
}
IKFAST_API const char* GetKinematicsHash() { return "<robot:GenericRobot - example_quadruped_leg (e76e47ad216738094b34264ed20a8b14)>"; }
IKFAST_API const char* GetIkFastVersion() { return "0x10000049"; }
#ifdef IKFAST_NAMESPACE
} // end namespace
#endif
#ifndef IKFAST_NO_MAIN
#include <stdio.h>
#include <stdlib.h>
#ifdef IKFAST_NAMESPACE
using namespace IKFAST_NAMESPACE;
#endif
int main(int argc, char** argv)
{
if( argc != 12+GetNumFreeParameters()+1 ) {
printf("\nUsage: ./ik r00 r01 r02 t0 r10 r11 r12 t1 r20 r21 r22 t2 free0 ...\n\n"
"Returns the ik solutions given the transformation of the end effector specified by\n"
"a 3x3 rotation R (rXX), and a 3x1 translation (tX).\n"
"There are %d free parameters that have to be specified.\n\n",GetNumFreeParameters());
return 1;
}
IkSolutionList<IkReal> solutions;
std::vector<IkReal> vfree(GetNumFreeParameters());
IkReal eerot[9],eetrans[3];
eerot[0] = atof(argv[1]); eerot[1] = atof(argv[2]); eerot[2] = atof(argv[3]); eetrans[0] = atof(argv[4]);
eerot[3] = atof(argv[5]); eerot[4] = atof(argv[6]); eerot[5] = atof(argv[7]); eetrans[1] = atof(argv[8]);
eerot[6] = atof(argv[9]); eerot[7] = atof(argv[10]); eerot[8] = atof(argv[11]); eetrans[2] = atof(argv[12]);
for(std::size_t i = 0; i < vfree.size(); ++i)
vfree[i] = atof(argv[13+i]);
bool bSuccess = ComputeIk(eetrans, eerot, vfree.size() > 0 ? &vfree[0] : NULL, solutions);
if( !bSuccess ) {
fprintf(stderr,"Failed to get ik solution\n");
return -1;
}
printf("Found %d ik solutions:\n", (int)solutions.GetNumSolutions());
std::vector<IkReal> solvalues(GetNumJoints());
for(std::size_t i = 0; i < solutions.GetNumSolutions(); ++i) {
const IkSolutionBase<IkReal>& sol = solutions.GetSolution(i);
printf("sol%d (free=%d): ", (int)i, (int)sol.GetFree().size());
std::vector<IkReal> vsolfree(sol.GetFree().size());
sol.GetSolution(&solvalues[0],vsolfree.size()>0?&vsolfree[0]:NULL);
for( std::size_t j = 0; j < solvalues.size(); ++j)
printf("%.15f, ", solvalues[j]);
printf("\n");
}
return 0;
}
#endif
| 29.490394 | 402 | 0.638226 | [
"object",
"vector"
] |
53228af6c3c12e93257a5e932cdccb0c40685bc6 | 5,852 | cpp | C++ | src/Frontend/ParseDecl.cpp | mshockwave/gross | 4cf048bbdf41a03a083b99c5dbaf14c249eaf407 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 47 | 2019-03-26T01:50:04.000Z | 2022-02-16T21:25:39.000Z | src/Frontend/ParseDecl.cpp | mshockwave/gross | 4cf048bbdf41a03a083b99c5dbaf14c249eaf407 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/Frontend/ParseDecl.cpp | mshockwave/gross | 4cf048bbdf41a03a083b99c5dbaf14c249eaf407 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2019-04-04T14:08:44.000Z | 2019-06-18T14:04:25.000Z | #include "gross/Support/Log.h"
#include "gross/Graph/Graph.h"
#include "gross/Graph/NodeUtils.h"
#include "gross/Graph/NodeMarker.h"
#include "Parser.h"
using namespace gross;
template<IrOpcode::ID OC>
bool Parser::ParseTypeDecl(NodeBuilder<OC>& NB) {
gross_unreachable("Unimplemented");
return false;
}
namespace gross {
template<>
bool Parser::ParseTypeDecl(NodeBuilder<IrOpcode::SrcVarDecl>& NB) {
(void) NextTok();
return true;
}
template<>
bool Parser::ParseTypeDecl(NodeBuilder<IrOpcode::SrcArrayDecl>& NB) {
Lexer::Token Tok;
while(true) {
Tok = NextTok();
if(Tok != Lexer::TOK_L_BRACKET) break;
(void) NextTok();
Node* ExprNode = ParseExpr();
NB.AddDim(ExprNode);
Tok = CurTok();
if(Tok != Lexer::TOK_R_BRACKET) {
Log::E() << "Expecting close bracket\n";
return false;
}
}
return true;
}
} // end namespace gross
template<IrOpcode::ID OC>
bool Parser::ParseVarDecl(std::vector<Node*>* Results) {
NodeBuilder<OC> NB(&G);
if(!ParseTypeDecl(NB)) return false;
Lexer::Token Tok = CurTok();
std::string SymName;
while(true) {
if(Tok != Lexer::TOK_IDENT) {
Log::E() << "Expecting identifier\n";
return false;
}
SymName = TokBuffer();
SymbolLookup Lookup(*this, SymName);
if(Lookup.InCurrentScope()) {
Log::E() << "variable already declared in this scope\n";
return false;
}
auto* VarDeclNode = NB.SetSymbolName(SymName)
.Build();
CurSymTable().insert({SymName, VarDeclNode});
if(Results) Results->push_back(VarDeclNode);
Tok = NextTok();
if(Tok == Lexer::TOK_SEMI_COLON)
break;
else if(Tok != Lexer::TOK_COMMA) {
Log::E() << "Expecting semicolomn or comma\n";
return false;
}
Tok = NextTok();
}
assert(Tok == Lexer::TOK_SEMI_COLON &&
"Expecting semi-colon");
(void) NextTok();
return true;
}
bool Parser::ParseVarDeclTop(std::vector<Node*>* Results) {
while(true) {
auto Tok = CurTok();
if(Tok == Lexer::TOK_VAR) {
if(!ParseVarDecl<IrOpcode::SrcVarDecl>(Results))
return false;
} else if(Tok == Lexer::TOK_ARRAY) {
if(!ParseVarDecl<IrOpcode::SrcArrayDecl>(Results))
return false;
} else {
break;
}
}
return true;
}
/// placeholder function to avoid link time error
/// for un-specialized decl template functions
void Parser::__SupportedParseVarDecls() {
(void) ParseVarDecl<IrOpcode::SrcVarDecl>();
(void) ParseVarDecl<IrOpcode::SrcArrayDecl>();
}
Node* Parser::ParseFuncDecl() {
auto Tok = CurTok();
if(Tok != Lexer::TOK_FUNCTION &&
Tok != Lexer::TOK_PROCEDURE) {
Log::E() << "Expecting 'function' or 'procedure' here\n";
return nullptr;
}
Tok = NextTok();
if(Tok != Lexer::TOK_IDENT) {
Log::E() << "Expect identifier for function\n";
return nullptr;
}
auto FName = TokBuffer();
NodeBuilder<IrOpcode::VirtFuncPrototype> FB(&G);
FB.FuncName(FName);
// for the entire function
NodeMarker<uint16_t> NodeIdxMarker(G, 10000);
SetNodeIdxMarker(&NodeIdxMarker);
SymbolLookup FuncLookup(*this, FName);
// 'CurrentScope' is global scope
if(FuncLookup.InCurrentScope()) {
Log::E() << "function has already declared in this scope\n";
return nullptr;
}
// start of function scope
NewSymScope();
// start a new control point record
NewLastControlPoint();
NewLastModified();
NewLastMemAccess();
Tok = NextTok();
if(Tok == Lexer::TOK_L_PARAN) {
// Argument list
Tok = NextTok();
while(Tok != Lexer::TOK_R_PARAN) {
if(Tok != Lexer::TOK_IDENT) {
Log::E() << "Expecting identifier in an argument list\n";
return nullptr;
}
const auto& ArgName = TokBuffer();
SymbolLookup ArgLookup(*this, ArgName);
if(ArgLookup.InCurrentScope()) {
Log::E() << "argument name has already been taken in this scope\n";
return nullptr;
}
auto* ArgNode = NodeBuilder<IrOpcode::Argument>(&G, ArgName)
.Build();
FB.AddParameter(ArgNode);
CurSymTable().insert({ArgName, ArgNode});
Tok = NextTok();
if(Tok == Lexer::TOK_COMMA)
Tok = NextTok();
}
Tok = NextTok();
}
if(Tok != Lexer::TOK_SEMI_COLON) {
Log::E() << "Expect ';' at the end of function header\n";
return nullptr;
}
auto* FuncNode = FB.Build();
// wind back to previous(global) scope and insert
// function symbol
auto ItPrevScope = CurSymTableIt();
MoveToPrevSymTable(ItPrevScope);
ItPrevScope->insert({FName, FuncNode});
setLastCtrlPoint(FuncNode);
(void) NextTok();
if(!ParseVarDeclTop()) return nullptr;
Tok = CurTok();
if(Tok != Lexer::TOK_L_CUR_BRACKET) {
Log::E() << "Expecting '{' here\n";
return nullptr;
}
(void) NextTok();
std::vector<Node*> FuncBodyStmts;
if(!ParseStatements(FuncBodyStmts)) return nullptr;
NodeBuilder<IrOpcode::End> EB(&G, FuncNode);
EB.AddTerminator(getLastCtrlPoint());
// must 'wait' after all side effects terminate
// if there is no consumers
auto MAE = LastMemAccess.end();
for(auto& P : LastModified) {
auto* LastMod = P.second;
// for non-memory access, if there is no consumers,
// well, then it's dead code
if(LastMemAccess.find(LastMod) == MAE)
EB.AddEffectDep(LastMod);
}
auto* EndNode = EB.Build();
Tok = CurTok();
if(Tok != Lexer::TOK_R_CUR_BRACKET) {
Log::E() << "Expecting '}' here\n";
return nullptr;
}
Tok = NextTok();
if(Tok != Lexer::TOK_SEMI_COLON) {
Log::E() << "Expect ';' at the end of function decl\n";
return nullptr;
}
(void) NextTok();
PopSymScope();
// Add function sub-graph
SubGraph SG(EndNode);
G.AddSubRegion(SG);
(void) NodeBuilder<IrOpcode::FunctionStub>(&G, SG).Build();
ClearNodeIdxMarker();
return EndNode;
}
| 26.479638 | 75 | 0.634313 | [
"vector"
] |
532c16de95410451f37832716be108c2b65421a1 | 983 | cpp | C++ | Atcoder/ABC188/D.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 4 | 2021-01-27T11:51:30.000Z | 2021-01-30T17:02:55.000Z | Atcoder/ABC188/D.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | null | null | null | Atcoder/ABC188/D.cpp | python-programmer1512/Code_of_gunwookim | e72e6724fb9ee6ccf2e1064583956fa954ba0282 | [
"MIT"
] | 5 | 2021-01-27T11:46:12.000Z | 2021-05-06T05:37:47.000Z | #include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define all(v) v.begin(),v.end()
#pragma gcc optimize("O3")
#pragma gcc optimize("Ofast")
#pragma gcc optimize("unroll-loops")
using namespace std;
const int INF = 1e9;
const int TMX = 1 << 18;
const long long llINF = 2e18;
const long long mod = 1e9+7;
const long long hashmod = 100003;
const int MAXN = 100000;
const int MAXM = 1000000;
typedef long long ll;
typedef long double ld;
typedef pair <int,int> pi;
typedef pair <ll,ll> pl;
typedef vector <int> vec;
typedef vector <pi> vecpi;
typedef long long ll;
int n,la;
ll C;
map <int,ll> M;
struct L {
int l,r; ll val;
}a[200005];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> C;
for(int i = 1;i <= n;i++) {
cin >> a[i].l >> a[i].r >> a[i].val;
M[a[i].l] += a[i].val;
M[a[i].r+1] -= a[i].val;
}
ll ans = 0,sum = 0;
for(auto i : M) {
ans += 1LL*min(C,sum)*(i.x-la);
la = i.x;
sum += i.y;
}
cout << ans;
} | 20.914894 | 46 | 0.620549 | [
"vector"
] |
53326601903f744507f893c4c512a73878b374e1 | 1,407 | cc | C++ | dbus-binding-generator/chromeos-dbus-bindings/method_name_generator.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | dbus-binding-generator/chromeos-dbus-bindings/method_name_generator.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | dbus-binding-generator/chromeos-dbus-bindings/method_name_generator.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | // Copyright 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos-dbus-bindings/method_name_generator.h"
#include <base/files/file_path.h>
#include <base/strings/stringprintf.h>
#include "chromeos-dbus-bindings/indented_text.h"
#include "chromeos-dbus-bindings/interface.h"
#include "chromeos-dbus-bindings/name_parser.h"
using std::string;
using std::vector;
namespace chromeos_dbus_bindings {
// static
string MethodNameGenerator::GenerateMethodNameConstant(
const string& method_name) {
return "k" + method_name + "Method";
}
// static
bool MethodNameGenerator::GenerateMethodNames(
const vector<Interface>& interfaces,
const base::FilePath& output_file) {
string contents;
IndentedText text;
for (const auto& interface : interfaces) {
text.AddBlankLine();
NameParser parser{interface.name};
parser.AddOpenNamespaces(&text, true);
for (const auto& method : interface.methods) {
text.AddLine(
base::StringPrintf("const char %s[] = \"%s\";",
GenerateMethodNameConstant(method.name).c_str(),
method.name.c_str()));
}
parser.AddCloseNamespaces(&text, true);
}
return HeaderGenerator::WriteTextToFile(output_file, text);
}
} // namespace chromeos_dbus_bindings
| 29.93617 | 76 | 0.7086 | [
"vector"
] |
5332c604d6408f6b11a16cf3ba1a19e384edd33f | 5,280 | cpp | C++ | tasks/CodeForces/R366/TaskC.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 39 | 2018-08-26T05:53:19.000Z | 2021-12-11T07:47:24.000Z | tasks/CodeForces/R366/TaskC.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 1 | 2018-06-21T00:40:41.000Z | 2018-06-21T00:40:46.000Z | tasks/CodeForces/R366/TaskC.cpp | ducaddepar/ProgrammingContest | 4c47cada50ed23bd841cfea06a377a4129d4d88f | [
"MIT"
] | 8 | 2018-08-27T00:34:23.000Z | 2020-09-27T12:51:22.000Z | #include "global.hpp"
#include "Scanner.hpp"
struct Edge {
int edgeId;
int begin, end;
bool signBegin, signEnd;
Edge(int edgeId, int begin, int end, bool signBegin, bool signEnd) :
edgeId(edgeId), begin(begin), end(end), signBegin(signBegin), signEnd(signEnd) {
}
};
struct Graph {
int nVertex;
int nEdge;
vector< vector<Edge> > adjList;
vector <int> degree;
Graph(int nVertex) : nVertex(nVertex) {
adjList.clear();
adjList.resize(nVertex);
degree.resize(nVertex);
nEdge = 0;
FOR_INC(i, nVertex) {
degree[i] = 0;
}
}
void addEdge(int begin, int end, bool signBegin, bool signEnd) {
begin--;
end--;
int edgeId = nEdge;
Edge edge(edgeId, begin, end, signBegin, signEnd);
adjList[begin].push_back(edge);
Edge invEdge(edgeId, end, begin, signEnd, signBegin);
adjList[end].push_back(invEdge);
degree[begin]++;
degree[end]++;
nEdge++;
}
vector<bool> edgeVisited;
vector<bool> nodeVisited;
vector<Edge> chain;
void initDfs() {
edgeVisited.resize(nEdge);
nodeVisited.resize(nVertex);
FOR_INC(i, nVertex) {
nodeVisited[i] = false;
}
FOR_INC(i, nEdge) {
edgeVisited[i] = false;
}
}
void initNewChain() {
chain.clear();
}
void dfs(int start) {
nodeVisited[start] = true;
for (auto &e : adjList[start]) {
if (!edgeVisited[e.edgeId]) {
chain.push_back(e);
edgeVisited[e.edgeId] = true;
dfs(e.end);
}
}
}
void logChain() {
LOG(1, "New chain");
for (auto &e : chain) {
LOG(1, e.begin + 1 << " - " << e.end + 1<< " signBegin: " << e.signBegin << ", signEnd: " << e.signEnd);
}
}
};
int getVal(int val, int sign) {
return sign ? val : (1-val);
}
int f[2][2][2][100100];
int knownVal[100100];
struct ChainSolver {
const vector<Edge> &chain;
int n;
vector <int> f;
ChainSolver(const vector<Edge> &chain) : chain(chain) {
n = chain.size();
}
int solve(int target, int offset, int beginVal, int endVal) {
int firstPos = offset;
int lastPos = chain.size() - 1 - offset;
Edge firstEdge = chain[firstPos];
Edge lastEdge = chain[lastPos];
int signedBeginVal = getVal(beginVal, firstEdge.signBegin);
int signedEndVal = getVal(endVal, lastEdge.signEnd);
knownVal[firstEdge.begin] = beginVal;
if (knownVal[lastEdge.end] != -1 && knownVal[lastEdge.end] != endVal) {
return 0;
}
knownVal[lastEdge.end] = endVal;
int result = 0;
FOR_INC(nextBeginVal, 2) {
if (knownVal[firstEdge.end] != -1 && nextBeginVal != knownVal[firstEdge.end]) {
continue;
}
int signedNextBeginVal = getVal(nextBeginVal, firstEdge.signEnd);
int signFirstEdgeVal = signedBeginVal ^ signedNextBeginVal;
FOR_INC(nextEndVal, 2) {
if (knownVal[lastEdge.begin] != -1 && nextEndVal != knownVal[lastEdge.begin]) {
continue;
}
int signedNextEndVal = getVal(nextEndVal, lastEdge.signBegin);
int signLastEdgeVal = signedEndVal ^ signedNextEndVal;
result += solve();
}
}
}
int solve(int target) {
FILL0(f);
return solve(target, 0, 0, 0) + solve(target, 0, 0, 1) + solve(target, 0, 1, 0) + solve(target, 0, 1, 1);
}
};
class TaskC {
public:
void solve(std::istream& inStream, std::ostream& outStream) {
Scanner in(inStream);
int nEdge, nVertex;
in >> nEdge >> nVertex;
Graph graph(nVertex);
FOR_INC(i, nVertex) {
knownVal[i] = -1;
}
REPEAT(nEdge) {
int k;
in >> k;
assert(k <= 2);
int begin, end, signBegin, signEnd;
in >> begin;
signBegin = (begin > 0);
begin = abs(begin);
if (k == 2) {
in >> end;
signEnd = (end > 0);
end = abs(end);
} else {
end = begin;
signEnd = signBegin;
}
graph.addEdge(begin, end, signBegin, signEnd);
}
graph.initDfs();
// Path
for (int i = 0; i < nVertex; i++) {
if (graph.degree[i] == 1 && !graph.nodeVisited[i]) {
graph.initNewChain();
graph.dfs(i);
graph.logChain();
ChainSolver cs(graph.chain);
}
}
// Cycle
for (int i = 0; i < nVertex; i++) {
if (graph.degree[i] > 0 && !graph.nodeVisited[i]) {
graph.initNewChain();
graph.dfs(i);
graph.logChain();
}
}
for (int i = 0; i < nVertex; i++) {
if (graph.degree[i] == 0) {
// TODO:
}
}
Writer out(outStream);
}
};
| 23.571429 | 117 | 0.491098 | [
"vector"
] |
533b3fc51ca8206e61bb0f52f68b3fc41900b72b | 644 | cpp | C++ | bonsai/test/semi_persistent_vector.cpp | rsk0315/codefolio | 1de990978489f466e1fd47884d4a19de9cc30e02 | [
"MIT"
] | 1 | 2020-03-20T13:24:30.000Z | 2020-03-20T13:24:30.000Z | bonsai/test/semi_persistent_vector.cpp | rsk0315/codefolio | 1de990978489f466e1fd47884d4a19de9cc30e02 | [
"MIT"
] | null | null | null | bonsai/test/semi_persistent_vector.cpp | rsk0315/codefolio | 1de990978489f466e1fd47884d4a19de9cc30e02 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <utility>
#include <vector>
#include <random>
#include "../../DataStructure/semi_persistent_vector.cpp"
int main() {
size_t n = 10;
semi_persistent_vector<int> spa(n);
size_t t = 10;
std::mt19937 rsk(0315);
std::uniform_int_distribution<size_t> neko(0, n-1);
std::uniform_int_distribution<int> nya(0, 99);
for (size_t i = 0; i < t; ++i) {
size_t j = neko(rsk);
int x = nya(rsk);
fprintf(stderr, "[%zu]: %d\n", j, x);
spa.set(j, x);
}
for (size_t i = 0; i < t; ++i)
for (size_t j = 0; j < n; ++j)
printf("%2d%c", spa.get(j, i), j+1<n? ' ':'\n');
}
| 23.851852 | 57 | 0.582298 | [
"vector"
] |
c727d4c958df75528cc023b0f0155dfb5a890d20 | 4,773 | cpp | C++ | main.cpp | sfan5/dnshammer | 06f783ea304d6e6975049712405d9f172bedd5d4 | [
"MIT"
] | 2 | 2018-05-26T14:44:17.000Z | 2018-05-27T03:35:58.000Z | main.cpp | sfan5/dnshammer | 06f783ea304d6e6975049712405d9f172bedd5d4 | [
"MIT"
] | null | null | null | main.cpp | sfan5/dnshammer | 06f783ea304d6e6975049712405d9f172bedd5d4 | [
"MIT"
] | null | null | null | #include <getopt.h>
#include <iostream>
#include <fstream>
#include <set>
#include "common.hpp"
#include "socket.hpp"
#include "dns.hpp"
#include "query.hpp"
static void usage();
static bool parse_resolver_list(std::istream &s, std::vector<SocketAddress> &res);
static bool parse_query_list(std::istream &s, std::vector<DNSQuestion> &res);
static void trim(std::string &s, const std::set<char> &trimchars);
int main(int argc, char *argv[])
{
const struct option long_options[] = {
{"concurrent", required_argument, 0, 'c'},
{"help", no_argument, 0, 'h'},
{"output-file", required_argument, 0, 'o'},
{"quiet", no_argument, 0, 'q'},
{"resolvers", required_argument, 0, 'r'},
{0,0,0,0},
};
std::ostream *outfile = &std::cout;
std::vector<SocketAddress> resolvers;
bool quiet = false;
unsigned concurrent = 2;
std::vector<DNSQuestion> queries;
while(1) {
int c = getopt_long(argc, argv, "c:ho:qr:", long_options, NULL);
if(c == -1)
break;
switch(c) {
case 'c': {
std::istringstream iss(optarg);
concurrent = -1;
iss >> concurrent;
if(concurrent < 1) {
std::cerr << "Invalid value for --concurrent." << std::endl;
return 1;
}
break;
}
case 'h':
usage();
return 1;
case 'o':
outfile = new std::ofstream(optarg);
if(!outfile->good()) {
std::cerr << "Failed to open output file." << std::endl;
return 1;
}
break;
case 'q':
quiet = true;
break;
case 'r': {
std::ifstream f(optarg);
if(!f.good()) {
std::cerr << "Failed to open file." << std::endl;
return 1;
}
if(!parse_resolver_list(f, resolvers))
return 1;
break;
}
default:
break;
}
}
if(argc - optind != 1) {
usage();
return 1;
}
{
std::ifstream f(argv[optind]);
if(!f.good()) {
std::cerr << "Failed to open file." << std::endl;
return 1;
}
if(!parse_query_list(f, queries))
return 1;
}
if(queries.empty()) {
std::cerr << "At least one query is required." << std::endl;
return 1;
}
if(resolvers.empty()) {
std::cerr << "At least one resolver is required." << std::endl;
return 1;
}
resolvers.shrink_to_fit();
queries.shrink_to_fit();
int ret = query_main(*outfile, quiet, concurrent, resolvers, queries);
outfile->flush();
return ret;
}
static void usage(void)
{
std::cout
<< "DNSHammer completes lots of DNS queries asynchronously" << std::endl
<< "Usage: dnshammer [options] <file with queries>" << std::endl
<< "Options:" << std::endl
<< " -h|--help This text" << std::endl
<< " -r|--resolvers <file> List of resolvers to query" << std::endl
<< " -o|--output-file <file> Output file (defaults to standard output)" << std::endl
<< " -c|--concurrent <n> Number of concurrent requests per resolver (defaults to 2)" << std::endl
<< " -q|--quiet Disable periodic status message" << std::endl
;
}
static const std::set<char> whitespace{' ', '\t', '\r', '\n'};
static inline bool is_ip_duplicate(const SocketAddress &search, const std::vector<SocketAddress> &in)
{
for(const auto &addr : in) {
if(!memcmp(&addr.addr.sin6_addr.s6_addr, &search.addr.sin6_addr.s6_addr, 16))
return true;
}
return false;
}
static bool parse_resolver_list(std::istream &s, std::vector<SocketAddress> &res)
{
while(1) {
char buf[1024] = {0};
bool ok = !!s.getline(buf, sizeof(buf) - 1);
if(!ok)
break;
std::string s(buf);
trim(s, whitespace);
if(s.empty() || s[0] == '#')
continue; // skip comments and empty lines
SocketAddress addr;
if(!addr.parseIP(s)) {
std::cerr << "\"" << s << "\" is not a valid IP." << std::endl;
return false;
}
addr.setPort(53); // TODO: make this configurable?
if(is_ip_duplicate(addr, res)) {
std::cerr << "Resolver addresses maybe not be duplicate" << std::endl;
return false;
}
res.emplace_back(addr);
}
return true;
}
static bool parse_query_list(std::istream &s, std::vector<struct DNSQuestion> &res)
{
while(1) {
char buf[1024] = {0};
bool ok = !!s.getline(buf, sizeof(buf) - 1);
if(!ok)
break;
std::string s(buf);
trim(s, whitespace);
if(s.empty() || s[0] == '#')
continue; // skip comments and empty lines
struct DNSQuestion q;
try {
q.parse(s);
} catch(DecodeException &e) {
std::cerr << "\"" << s << "\" is not a valid DNS question." << std::endl;
return false;
}
res.emplace_back(q);
}
return true;
}
static void trim(std::string &s, const std::set<char> &trimchars)
{
// front
size_t i = 0;
while(i < s.size() && trimchars.find(s[i]) != trimchars.cend())
i++;
if(i > 0)
s = s.substr(i, s.size() - i);
// back
i = s.size() - 1;
while(i >= 0 && trimchars.find(s[i]) != trimchars.cend())
i--;
s.resize(i + 1);
}
| 23.057971 | 104 | 0.602556 | [
"vector"
] |
c72ac655123cf6e4678ab6d59eb1af3649ab8823 | 859 | cpp | C++ | cpp_snippet/dp/D-Knapsack1.cpp | hsmtknj/programming-contest | b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab | [
"MIT"
] | null | null | null | cpp_snippet/dp/D-Knapsack1.cpp | hsmtknj/programming-contest | b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab | [
"MIT"
] | null | null | null | cpp_snippet/dp/D-Knapsack1.cpp | hsmtknj/programming-contest | b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
int main()
{
// 入力 (1-based indexing)
long long N;
long long W;
std::cin >> N >> W;
std::vector<long long> w(N+1, 0);
std::vector<long long> v(N+1, 0);
for (int i = 0; i < N; i++) std::cin >> w[i+1] >> v[i+1];
// 問題を解く
std::vector<std::vector<long long>> dp(N+1, std::vector<long long>(W+1, 0));
// i = 0 のアイテムを選択していないときは既に 0 で初期化されているので飛ばす
for (int i = 1; i <= N; i++)
{
// 各アイテムに対して部分和毎に計算
for (int sum_w = 0; sum_w <= W; sum_w++)
{
// 選ぶとき(部分和が足りるときのみ)
if (sum_w - w[i] >= 0) dp[i][sum_w] = std::max(dp[i][sum_w], dp[i-1][sum_w - w[i]] + v[i]);
// 選ばないとき
dp[i][sum_w] = std::max(dp[i][sum_w], dp[i-1][sum_w]);
}
}
long long ans = dp[N][W];
std::cout << ans << std::endl;
return 0;
} | 26.030303 | 103 | 0.472643 | [
"vector"
] |
c7381c8b4ebfbaf8823db6808c6b7b1eea54bcc8 | 643 | cpp | C++ | 1000-1100/1002. Find Common Characters.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1000-1100/1002. Find Common Characters.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1000-1100/1002. Find Common Characters.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | class Solution
{
public:
vector<string> commonChars(vector<string> &words)
{
vector<int> cnt(26, 0);
for (auto &c : words[0])
{
cnt[c - 'a']++;
}
for (int i = 1; i < words.size(); i++)
{
vector<int> tmp(26, 0);
for (auto &c : words[i])
{
tmp[c - 'a']++;
}
for (int j = 0; j < 26; j++)
{
cnt[j] = min(cnt[j], tmp[j]);
}
}
vector<string> ret;
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < cnt[i]; j++)
{
string s;
s.push_back(char('a' + i));
ret.push_back(s);
}
}
return ret;
}
}; | 18.371429 | 51 | 0.402799 | [
"vector"
] |
c738f6375950cf3cda5d9325e4e4af220b9829b2 | 15,581 | cpp | C++ | libmevent/meventmgr.cpp | stardog-union/rocks_snmp | 7fa1a752957c7b4999833d89e5a8023d855d8ce8 | [
"Apache-2.0"
] | null | null | null | libmevent/meventmgr.cpp | stardog-union/rocks_snmp | 7fa1a752957c7b4999833d89e5a8023d855d8ce8 | [
"Apache-2.0"
] | null | null | null | libmevent/meventmgr.cpp | stardog-union/rocks_snmp | 7fa1a752957c7b4999833d89e5a8023d855d8ce8 | [
"Apache-2.0"
] | 1 | 2020-11-14T16:41:51.000Z | 2020-11-14T16:41:51.000Z | /**
* @file meventmgr.cpp
* @author matthewv
* @date Created February 22, 2010
* @date Copyright 2011
*
* @brief Event object and event list (manager)
*/
#include <errno.h>
#include <fcntl.h>
#include <memory.h>
#include <sys/epoll.h>
#include <unistd.h>
#include "meventmgr.h"
#include "logging.h"
// exists in 2.6.17 and after, but not in all headers
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0
#endif
/**
* Initialize the data members. On ERROR, leave m_EpollFd set to -1 as flag
* @date 02/26/10 matthewv Created
*/
MEventMgr::MEventMgr() {
m_Running = false;
m_EndStatus = true;
m_SelfPipe[0] = -1;
m_SelfPipe[1] = -1;
m_TaskCount = 0;
// step one, create epoll kernel object
m_EpollFd = epoll_create(100);
if (-1 == m_EpollFd) {
Logging(LOG_ERR, "%s: error creating epoll descriptor (errno=%d)", __func__,
errno);
m_EndStatus = false;
} // if
// step two, create an administrative pipe
if (IsValid()) {
int ret_val;
ret_val = pipe(m_SelfPipe);
// two point five, pipe needs to be installed in epoll
if (0 == ret_val) {
struct epoll_event event;
ret_val = fcntl(m_SelfPipe[0], F_SETFL, O_NONBLOCK);
ret_val = fcntl(m_SelfPipe[1], F_SETFL, O_NONBLOCK);
memset(&event, 0, sizeof(event));
event.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP;
event.data.fd = m_SelfPipe[0];
ret_val = epoll_ctl(m_EpollFd, EPOLL_CTL_ADD, m_SelfPipe[0], &event);
if (0 != ret_val) {
Logging(LOG_ERR, "%s: error adding control pipe (errno=%d)", __func__,
errno);
Close();
} // if
} // if
else {
Logging(LOG_ERR, "%s: error creating admin pipe (errno=%d)", __func__,
errno);
Close();
} // else
} // if
return;
} // MEventMgr::MEventMgr
/**
* Release resources
* @date 02/26/10 matthewv Created
*/
MEventMgr::~MEventMgr() {
Close();
PurgeEvents();
return;
} // MEventMgr::~MEventMgr
/**
* Clear event objects
* @date 02/12/12 Created
* @author matthewv
*/
void MEventMgr::PurgeEvents() {
// clear all nodes on object and timing lists
m_Events.clear();
m_Timeouts.clear();
return;
} // MEventMgr::PurgeEvents
/**
* Place an event on the thread safe add list
* i.e. this is an asynchronous add
* @date 03/01/11 matthewv Created
*/
bool MEventMgr::AddEvent(MEventPtr &Ptr) {
bool ret_flag;
ret_flag = true;
if (Ptr) {
std::lock_guard<std::mutex> lock(m_AddMutex);
int ret_val;
// debug: m_ThreadedAdd.DumpObjList();
m_ThreadedAdd.push_back(Ptr);
// debug: m_ThreadedAdd.DumpObjList();
ret_val = write(m_SelfPipe[1], "a", 1);
if (-1 == ret_val) {
ret_flag = false;
Logging(LOG_ERR, "%s: write to manager pipe failed (errno=%d)", __func__,
errno);
} // if
} // if
else {
ret_flag = false;
Logging(LOG_ERR, "%s: bad function param", __func__);
} // else
return (ret_flag);
} // MEventMgr::AddEvent
bool MEventMgr::TimerCreate(MEventPtr Obj) {
bool ret_flag = {true};
std::chrono::steady_clock::time_point new_point;
if (0 != Obj->GetIntervalMS() ) {
Logging(LOG_ERR, "MEventMgr::%s: GetIntervalMS %u", __func__, Obj->GetIntervalMS());
new_point = std::chrono::steady_clock::now() + Obj->GetInterval();
auto it = m_Timeouts.insert(
std::pair<std::chrono::steady_clock::time_point, MEventPtr>(new_point,
Obj));
// we do NOT remove previous timepoints for this object.
// that occurs during a walk of m_TimePoints later
if (m_Timeouts.end() != it) {
Obj->SetNextTimeout(new_point);
} else {
ret_flag = false;
}
}
return ret_flag;
} // MEventMgr::TimerCreate
bool MEventMgr::TimerRepeat(MEventPtr &Obj) {
bool ret_flag = {true};
std::chrono::steady_clock::time_point new_point;
if (0 != Obj->GetIntervalMS() ) {
Logging(LOG_ERR, "MEventMgr::%s: GetIntervalMS %u", __func__, Obj->GetIntervalMS());
new_point = Obj->GetNextTimeout() + Obj->GetInterval();
auto it = m_Timeouts.insert(
std::pair<std::chrono::steady_clock::time_point, MEventPtr>(new_point,
Obj));
// we do NOT remove previous timepoints for this object.
// that occurs during a walk of m_TimePoints later
if (m_Timeouts.end() != it) {
Obj->SetNextTimeout(new_point);
} else {
ret_flag = false;
}
}
return ret_flag;
} // MEventMgr::TimerRepeat
/**
* Close the file descriptor related resources (epoll and pipe)
* @date 02/26/10 matthewv Created
*/
void MEventMgr::Close() {
if (-1 != m_SelfPipe[0]) {
close(m_SelfPipe[0]);
m_SelfPipe[0] = -1;
} // if
if (-1 != m_SelfPipe[1]) {
close(m_SelfPipe[1]);
m_SelfPipe[1] = -1;
} // if
if (-1 != m_EpollFd) {
close(m_EpollFd);
m_EpollFd = -1;
} // if
return;
} // MEventMgr::Close
/**
* @brief Begin event loop processing. Caller's thread operates the loop.
* @returns false if exit due to an error
* @date 03/18/10 matthewv Created
*/
bool MEventMgr::StartSingle() {
bool ret_flag;
ret_flag = true;
if (IsValid()) {
std::chrono::steady_clock::time_point now;
int num_ready;
struct epoll_event events[10];
// make sure epoll has "self" object for breaking loop
// - in case of signals
// - other threads requesting stop
// - other threads requesting objects added
// callbacks can set running to "false" to stop execution
m_Running = true;
num_ready = 0;
// test run flag on each cycle
while (m_Running && m_EndStatus) {
int loop;
// 1. all pending epoll events from prior loop
for (loop = 0; loop < num_ready; ++loop) {
// is this a message to the manager
if (m_SelfPipe[0] == events[loop].data.fd) {
ReceiveMgrMessage(events[loop].events);
} // if
// assume there is a pointer for us to use
else {
MEventPtr event;
bool again;
again = true;
// hold an MEventObjPtr in case object releases self
event = ((MEventObj *)(events[loop].data.ptr))->GetMEventPtr();
// First: call error on flag (1st because it may overpower read /
// write)
if (EPOLLERR & events[loop].events)
again = event->ErrorCallback();
// Second: call read avail on flag (2nd because input can overrun)
if (again && (EPOLLIN & events[loop].events))
again = event->ReadAvailCallback();
// Third: call write avail on flag because
if (again && (EPOLLOUT & events[loop].events))
again = event->WriteAvailCallback();
// Fourth: call connection close
if ((EPOLLRDHUP | EPOLLHUP) & events[loop].events)
again = event->CloseCallback((EPOLLRDHUP | EPOLLHUP) &
events[loop].events);
} // else
} // if
// 2. get time, any timed events overdue?
// (supports potential, non-MEventObj items)
// Process only ONE event per loop. Assumption is that
// fd based events are more critical than timeouts
now = std::chrono::steady_clock::now();
while (m_Timeouts.size() && m_Timeouts.begin()->first < now) {
std::chrono::steady_clock::time_point point = m_Timeouts.begin()->first;
MEventPtr event = m_Timeouts.begin()->second;
m_Timeouts.erase(m_Timeouts.begin());
// this might be an old timeout, check first
if (point == event->GetNextTimeout()) {
event->SetLastTimeout(now);
// execute timer callback
event->TimerExpired();
} // if
} // if
num_ready = 0;
// 3. set up timed call to epoll
int milliseconds;
// use closest timeout
milliseconds = -1;
if (m_Timeouts.size()) {
now = std::chrono::steady_clock::now();
std::chrono::milliseconds ms;
if (now < m_Timeouts.begin()->first) {
ms = std::chrono::duration_cast<std::chrono::milliseconds>(
m_Timeouts.begin()->first - now);
milliseconds = ms.count();
} // if
else {
milliseconds = 0;
} // else
} // if
if (m_Running && m_EndStatus)
num_ready = epoll_wait(m_EpollFd, events, 10, milliseconds);
} // while
} // if
else {
Logging(LOG_ERR, "%s: Start called on bad MEventMgr object.", __func__);
ret_flag = false;
} // else
m_EndStatus = m_EndStatus && ret_flag;
// purge objects
PurgeEvents();
return (m_EndStatus);
} // MEventMgr::StartSingle
/**
* Kill the loop. No more processing.
* @date 02/19/11 matthewv Created
*/
void MEventMgr::Stop(
bool EndStatus) //<! optional true/false to report at object level
{
int ret_val;
m_Running = false;
m_EndStatus = EndStatus;
// this write is likely NOT needed, but redundancy does not hurt here
// (ok, will help if sent by independent thread)
ret_val = write(m_SelfPipe[1], "x", 1);
if (1 != ret_val) {
Logging(LOG_ERR, "%s: write failed (errno=%d)", __func__, errno);
} // if
return;
} // MEventMgr::Stop
bool MEventMgr::StartThreaded() {
std::thread new_thread(&MEventMgr::StartSingle, this);
m_Thread = std::move(new_thread);
return true;
}
/**
* Spawn a thread that executes Start()
* @date 03/01/11 matthewv Created
*/
void *MEventMgr::ThreadStart() {
return (StartSingle() ? NULL : (void *)1);
} // MEventMgr::ThreadStart
/**
* Read on or more command messages off the pipe
* @date 03/01/11 matthewv Created
*/
void MEventMgr::ReceiveMgrMessage(unsigned Flags) {
if (Flags & EPOLLERR) {
Logging(LOG_ERR, "%s: epoll stated error management pipe", __func__);
m_Running = false;
m_EndStatus = false;
} // if
// a series of one byte commands
else if (Flags & EPOLLIN) {
char command;
int ret_val;
do {
ret_val = read(m_SelfPipe[0], &command, 1);
if (1 == ret_val) {
switch (command) {
case 'x':
m_Running = false;
break;
case 'a':
AddEventList();
break;
default:
m_Running = false;
m_EndStatus = false;
Logging(LOG_ERR, "%s: unknown management command \'%c\'", __func__,
command);
break;
} // switch
} // if
else {
if (EAGAIN != errno) {
m_Running = false;
m_EndStatus = false;
Logging(LOG_ERR, "%s: error reading management pipe (errno=%d)",
__func__, errno);
} // if
} // else
} while (1 == ret_val);
} // else
return;
} // MEventMgr::ReceiveMgrMessage
/**
* Move new events from m_ThreadAdd list to active list
* @date 03/01/11 matthewv Created
*/
void MEventMgr::AddEventList() {
MEventPtr ptr;
MEventMgrPtr mgr = GetMEventMgrPtr();
std::lock_guard<std::mutex> lock(m_AddMutex);
for (auto it : m_ThreadedAdd) {
// object will init itself to "this" as parent
it->ThreadInit(mgr);
m_Events.insert(it);
} // for
m_ThreadedAdd.clear();
return;
} // MEventMgr::ReceiveMgrMessage
/**
* Update epoll for current monitoring requirements
* @date Created 03/02/11
* @author matthewv
*/
bool MEventMgr::UpdateEpoll(
MEventPtr &Obj, //!< event object with active handle
bool NewReadState, //!< potentially changed read monitoring state
bool NewWriteState) //!< potentially changed write monitoring state
{
bool ret_flag;
int handle;
ret_flag = true;
// validate parameters
if (Obj)
handle = Obj->GetFileHandle();
else
handle = -1;
ret_flag = (-1 != handle && this == Obj->GetMgrPtr().get());
// only do this work with good data, and different states
if (ret_flag && (Obj->IsForRead() != NewReadState ||
Obj->IsForWrite() != NewWriteState)) {
struct epoll_event event;
int ret_val, operation, command;
bool old_read, old_write;
command = EPOLLERR | EPOLLHUP;
if (NewReadState)
command |= EPOLLIN | EPOLLRDHUP;
if (NewWriteState)
command |= EPOLLOUT;
old_read = Obj->IsForRead();
old_write = Obj->IsForWrite();
// modify existing epoll
if ((old_read || old_write) && (NewReadState || NewWriteState)) {
operation = EPOLL_CTL_MOD;
} // if
// delete
else if (!NewReadState && !NewWriteState) {
operation = EPOLL_CTL_DEL;
} // else if
// add
else {
operation = EPOLL_CTL_ADD;
} // else
// all handles non-blocking by this library
if (EPOLL_CTL_ADD == operation)
ret_val = fcntl(handle, F_SETFL, O_NONBLOCK);
else
ret_val = 0;
if (0 == ret_val) {
memset(&event, 0, sizeof(event));
event.events = command;
event.data.ptr = Obj.get();
ret_val = epoll_ctl(m_EpollFd, operation, handle, &event);
if (0 != ret_val) {
ret_flag = false;
Logging(LOG_ERR,
"%s: epoll_ctl failed (errno=%d, operation=0x%x, handle=%d, "
"command=0x%x)",
__func__, errno, operation, handle, event.events);
} // if
} // if
else {
ret_flag = false;
Logging(LOG_ERR, "%s: fcntl failed to set O_NONBLOCK (errno=%d)",
__func__, errno);
} // else
} // if
else if (!ret_flag) {
ret_flag = false;
Logging(LOG_ERR, "%s: function param bad or in bad state", __func__);
} // else if
return (ret_flag);
} // MEventMgr::UpdateEpoll
/**
* Remove object
* @date 03/02/11 matthewv Created
*/
bool MEventMgr::ReleaseRequests(MEventPtr &Obj) {
bool ret_flag;
int handle;
ret_flag = true;
if (NULL != Obj)
handle = Obj->GetFileHandle();
else
handle = -1;
if (-1 != handle && this == Obj->GetMgrPtr().get()) {
ret_flag = UpdateEpoll(Obj, false, false);
} // if
#if 0
// can be called on incomplete objects as part of close
else
{
ret_flag=false;
Logging(LOG_ERR, "%s: function param bad or in bad state", __func__);
} // else
#endif
return (ret_flag);
} // MEventMgr::ReleaseRequests
#if 0
/**
* Receive "edge" messages from other objects
* @date Created 06/15/11
* @author matthewv
*/
bool
MEventMgr::EdgeNotification(
unsigned int EdgeId, //!< what just happened, what graph edge are we walking
StateMachinePtr & Caller, //!< what state machine object initiated the edge
bool PreNotify) //!< for watchers, is the before or after owner processes
{
bool used;
used=false;
switch(EdgeId)
{
case MM_EDGE_TASK_START:
++m_TaskCount;
used=true;
break;
case MM_EDGE_TASK_END:
if (0<m_TaskCount) --m_TaskCount;
if (0==m_TaskCount && m_Running) m_Running=false;
used=true;
break;
default:
// send down a level. If not used then it is an error
used=StateMachine::EdgeNotification(EdgeId, Caller, PreNotify);
if (!used)
{
Logging(LOG_ERR, "%s: unknown edge value passed [EdgeId=%u]",
__func__, EdgeId);
// m_MgrPtr->Stop();
} // if
break;
} // switch
return(used);
} // UserStatus::EdgeNotification
#endif
| 24.81051 | 96 | 0.592067 | [
"object"
] |
c73ea329a12bcbf5b09c9d2cfa594ac5d60ce1d0 | 680 | cpp | C++ | graph-source-code/29-C/126862.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/29-C/126862.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/29-C/126862.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <cstdio>
#include <vector>
#include <map>
using namespace std;
int n,x,y,z,k,i,s[222222];
vector <int> g[222222];
map <int, int> m;
int main() {
scanf("%d",&n);
for (i=0; i<n; i++) {
scanf("%d",&x); y=m[x];
if (y==0) { m[x]=y=++k; s[k]=x; }
scanf("%d",&x); z=m[x];
if (z==0) { m[x]=z=++k; s[k]=x; }
g[y].push_back(z);
g[z].push_back(y);
}
for (i=1; i<=k; i++) if (g[i].size()==1) {
y=i; printf("%d",s[i]);
for (x=g[i][0]; g[x].size()==2; y=z) {
printf(" %d",s[x]); z=x;
if (g[x][0]==y) x=g[x][1]; else x=g[x][0];
}
printf(" %d\n",s[x]); break;
}
return 0;
}
| 21.935484 | 49 | 0.426471 | [
"vector"
] |
c742cdf0417165fb70872415abd66830b384bbcf | 9,243 | cpp | C++ | src/objects/Pickup.cpp | ashleygwinnell/foh-ld42 | 4ed004c193087d936337d6365493e3397ca99137 | [
"MIT"
] | null | null | null | src/objects/Pickup.cpp | ashleygwinnell/foh-ld42 | 4ed004c193087d936337d6365493e3397ca99137 | [
"MIT"
] | null | null | null | src/objects/Pickup.cpp | ashleygwinnell/foh-ld42 | 4ed004c193087d936337d6365493e3397ca99137 | [
"MIT"
] | null | null | null | /*
* Pickup.cpp
*
* Created on: 29 Jan 2011
* Author: Ashley
*/
#include "Pickup.h"
#include "MyParticle.h"
#include "Enemy.h"
#include "Player.h"
#include "../DefaultGame.h"
#include "EightWayMovementComponent.h"
#include <ARK2D/Core/+.h>
#include <ARK2D/Audio/Sound.h>
#include <ARK2D/Util/CameraShake.h>
AnimationFrameList* Pickup::s_animCoin = NULL;
Image* Pickup::s_ladder = NULL;
Pickup::Pickup():
Object()
{
DefaultGame* dg = DefaultGame::getInstance();
if (s_animCoin == NULL) {
s_animCoin = AnimationFrameList::create("sprites/coin-*.png", 1, 6, dg->spritesheet, dg->desc);
s_ladder = SpriteSheetStore::getImage("sprites/ladder.png");
}
m_animation = new Animation();
m_animation->setFrames(s_animCoin);
m_animation->setFrameTime(0.1f);
m_bounds = new ARK::Core::Geometry::Rectangle(0, 0, 7.0f, 9.0f);
m_bounds->setLocationByCenter(64, 32);
m_velocity->set(0, 0);
m_velocityMax->set(100, 100);
m_acceleration->set(0, 0);
reset();
}
void Pickup::reset() {
Object::reset();
m_grounded = false;
m_tumbling = false;
m_rotation = 0.0f;
m_introTimer = 0.0f;
m_introDuration = 0.5f;
m_lightingRadius = 5;
}
float Pickup::getScale() {
float scWidth = 1.0f;
float scHeight = 1.0f;
if (m_introTimer >= 0.01f) {
//scWidth = Easing::easebetween(Easing::QUADRATIC_OUT, m_introTimer, 1.25f, 1.0f, m_introDuration);
//scHeight = Easing::easebetween(Easing::QUADRATIC_OUT, m_introTimer, 0.75f, 1.0f, m_introDuration);
scWidth = Easing::easebetween(Easing::QUADRATIC_OUT, m_introTimer, 0.0f, 1.0f, m_introDuration);
scHeight = Easing::easebetween(Easing::QUADRATIC_OUT, m_introTimer, 0.0f, 1.0f, m_introDuration);
}
return scWidth;
}
void Pickup::start(PickupType type) {
m_type = type;
if (type == PU_COIN) {
m_tumbling = false;
m_animation->setFrames(s_animCoin);
m_bounds->asRectangle()->setSize(7.0f, 9.0f);
m_velocity->set(0.0f, 0.0f);
MathUtil::moveAngle<float>(m_velocity, MathUtil::randBetweenf(-120, -60), MathUtil::randBetweenf(50.0f, 80.0f));
m_introTimer = 0.01f;
}
else if (type == PU_LADDER) {
m_lightingRadius = 10;
m_tumbling = false;
m_animation->clear();
m_animation->addFrame(s_ladder);
m_bounds->asRectangle()->setSize(4.0f, 4.0f);
m_velocity->set(0.0f, 0.0f);
m_introTimer = 0.01f;
m_grounded = true;
}
}
void Pickup::update(GameContainer* container, GameTimer* timer) {
Object::update(container, timer);
if (m_introTimer > 0.0f) {
m_introTimer += timer->getDelta();
if (m_introTimer >= m_introDuration) {
m_introTimer = 0.0f;
}
}
m_animation->update(timer);
if (!m_grounded) {
m_zSpeed += m_zAcceleration * timer->getDelta();
m_z -= m_zSpeed * timer->getDelta();
if (m_z < 0) {
m_z = 0;
m_zSpeed *= -0.5f;
if (m_zSpeed < 3) {
m_z = 0;
m_zSpeed = 0;
m_zAcceleration = 0;
m_grounded = true;
}
}
}
m_velocity->frictionX(200 * timer->getDelta());
m_velocity->frictionY(200 * timer->getDelta());
DefaultGame* dg = DefaultGame::getInstance();
if (m_type == PU_COIN && dg->stateUpgrades->hasMagnet()) {
InGameState* igs = dg->stateInGame;
float angle = MathUtil::anglef(m_bounds->getCenterX(), m_bounds->getCenterY(), igs->m_player->m_bounds->getCenterX(), igs->m_player->m_bounds->getCenterY() );
float distance = MathUtil::distance(m_bounds->getCenterX(), m_bounds->getCenterY(), igs->m_player->m_bounds->getCenterX(), igs->m_player->m_bounds->getCenterY() );
float m_movementSpeedMin = 1.0f;
float m_movementSpeedMax = 60.0f;
float m_movementSpeedDistance = 100.0f;
float movementSpeedMax = m_movementSpeedMax; // 250.0f
if (dg->stateUpgrades->hasMagnet()) {
//movementSpeedMax = m_movementSpeedMax * 1.4f; //350.0f;
}
// if (m_size == 1 && dg->stateUpgrades->getUpgradeById(Upgrade::UPGRADE_MISC_MAGNET_STRONG)->purchased) {
// movementSpeedMax = m_movementSpeedMax * 2.0f * 1.4f; //350.0f;
// }
// was 250.
// now 350
// it should be an upgrade!
float speed = Easing::easebetween(Easing::QUADRATIC_OUT, distance, m_movementSpeedMax, m_movementSpeedMin, m_movementSpeedDistance);
m_velocity->set(0, 0);
MathUtil::moveAngle<float>(m_velocity, angle, speed);
}
m_rotation = 0;
// if (!m_grounded) {
// //Object::gravity(1.0f);
// if (m_tumbling) {
// m_rotation += 360.0f * timer->getDelta();
// }
// } else {
// m_rotation = 0.0f;
// m_velocity->set(0.0f, 0.0f);
// }
Object::move(1.0f);
keepInBounds();
//DefaultGame* dg = DefaultGame::getInstance();
//InGameState* igs = dg->stateInGame;
// m_bounds->asRectangle()->setLocationByCenter(
// m_bounds->getCenterX() + (m_velocity->getX() * timer->getDelta()),
// m_bounds->getCenterY() + (m_velocity->getY() * timer->getDelta())
// );
}
void Pickup::collision(Object* other) {
}
void Pickup::collected(Player* player) {
DefaultGame* dg = DefaultGame::getInstance();
dg->m_coins += 1;
//igs->onScoreChange();
DefaultGame::getInstance()->m_sfxMenuBuy->play();
explode();
}
void Pickup::explode() {
InGameState* igs = DefaultGame::getInstance()->stateInGame;
setPendingRemoval(true);
// MyParticle* particle = igs->m_particles->get();
// particle->reset();
// particle->start(MyParticle::TYPE_PRESENT_COLLECT);
// particle->m_bounds->setLocationByCenter(m_bounds->getCenterX(), m_bounds->getCenterY());
// particle->m_animation->addFrame(m_sprite);
MyParticle* particle;
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX(), m_bounds->getCenterY());
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX(), m_bounds->getCenterY());
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX(), m_bounds->getCenterY() - 4);
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
// box bits
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX() - 2, m_bounds->getCenterY() - 2);
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX() + 2, m_bounds->getCenterY() - 2);
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX() - 2, m_bounds->getCenterY() + 2);
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
particle = igs->m_particles->get();
particle->reset();
particle->m_type = MyParticle::TYPE_PLAYER_GIB;
particle->m_bounds->setLocationByCenter(m_bounds->getCenterX() + 2, m_bounds->getCenterY() + 2);
particle->m_animation->reset();
particle->m_animation->addFrame(MyParticleSprites::s_cloud11);
MathUtil::moveAngle<float>(particle->m_velocity, -180 + MathUtil::randBetweenf(0,180), MathUtil::randBetweenf(50, 100));
}
void Pickup::render(GameContainer* container, Renderer* r)
{
InGameState* igs = DefaultGame::getInstance()->stateInGame;
r->setDrawColor(Color::white);
float scale = 1.0f;
float rotation = m_rotation;
if (m_introTimer > 0.0f) {
scale = Easing::easebetween(Easing::QUADRATIC_OUT, m_introTimer, 0.0f, 1.0f, m_introDuration);
}
Image* img = m_animation->getCurrentFrame();
img->setAlpha(1.0f);
if (!m_grounded) {
img->setRotation(rotation);
img->drawCenteredScaled(float(m_bounds->getCenterX()), float(ceil(m_bounds->getCenterY())), scale, scale);
} else {
img->setRotation(rotation);
img->drawAligned(m_bounds->getCenterX(), m_bounds->getMaxY(), Renderer::ALIGN_CENTER, Renderer::ALIGN_BOTTOM, scale, scale);
}
//r->drawRect(m_bounds->getMinX(), m_bounds->getMinY(), m_bounds->getWidth(), m_bounds->getHeight());
}
Pickup::~Pickup() {
}
| 30.404605 | 165 | 0.706156 | [
"geometry",
"render",
"object"
] |
c744793472c1f93276e69208581c2939726bc1f5 | 1,479 | cc | C++ | 2021/21/main1.cc | coffee-addict/AOC | f2a8da10970b085d01dc1df995764d297219a427 | [
"CC0-1.0"
] | null | null | null | 2021/21/main1.cc | coffee-addict/AOC | f2a8da10970b085d01dc1df995764d297219a427 | [
"CC0-1.0"
] | null | null | null | 2021/21/main1.cc | coffee-addict/AOC | f2a8da10970b085d01dc1df995764d297219a427 | [
"CC0-1.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,s,e) for(int i=(s);(i)<(int)(e);++(i))
#define REP(i,e) FOR(i,0,e)
#define all(o) (o).begin(), (o).end()
#define epb(x) emplace_back((x))
#define psb(x) push_back((x))
#define ppb(x) pop_back((x))
#define mkp(x,y) make_pair((x),(y))
#define mkt(x,y,z) make_tuple((x),(y),(z))
#define nth(x,n) get<(n)>((x))
using ll = long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<ll>;
using VVL = vector<VL>;
using VD = vector<double>;
using VLD = vector<long double>;
template<typename T>
struct edge {
int from;
int to;
T cost;
edge(int from, int to, T cost) {
this->from = from;
this->to = to;
this->cost = cost;
}
};
using VVE = vector<vector<edge<int>>>;
int main() {
cin.tie(0);
cout << fixed << setprecision(10);
ios::sync_with_stdio(false);
int pa, pb; cin >> pa >> pb;
pa--; pb--;
int sa = 0, sb = 0;
int v = 1;
int c = 0, ws = 0, ls = 0;
while (ws < 1000) {
REP(i,3) {
pa += v;
v++;
if (v > 100) v = 1;
}
c += 3;
pa = pa%10;
sa += pa + 1;
if (sa >= 1000) {
ws = sa;
ls = sb;
break;
}
REP(i,3) {
pb += v;
v++;
if (v > 100) v = 1;
}
c += 3;
pb = pb%10;
sb += pb + 1;
if (sb >= 1000) {
ws = sb;
ls = sa;
break;
}
}
cout << "c, ws, ls = " << c << ", " << ws << ", " << ls << endl;
cout << ls*c << endl;
return 0;
}
| 19.460526 | 66 | 0.485463 | [
"vector"
] |
c74faf0fb3fc095fbaede1718dea961effaa4681 | 4,305 | hpp | C++ | include/uit/ducts/proc/impl/backend/impl/InletMemoryAccumulatingPool.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 15 | 2020-07-31T23:06:09.000Z | 2022-01-13T18:05:33.000Z | include/uit/ducts/proc/impl/backend/impl/InletMemoryAccumulatingPool.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 137 | 2020-08-13T23:32:17.000Z | 2021-10-16T04:00:40.000Z | include/uit/ducts/proc/impl/backend/impl/InletMemoryAccumulatingPool.hpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 3 | 2020-08-09T01:52:03.000Z | 2020-10-02T02:13:47.000Z | #pragma once
#ifndef UIT_DUCTS_PROC_IMPL_BACKEND_IMPL_INLETMEMORYACCUMULATINGPOOL_HPP_INCLUDE
#define UIT_DUCTS_PROC_IMPL_BACKEND_IMPL_INLETMEMORYACCUMULATINGPOOL_HPP_INCLUDE
#include <algorithm>
#include "../../../../../../../third-party/Empirical/include/emp/base/assert.hpp"
#include "../../../../../../../third-party/Empirical/include/emp/base/optional.hpp"
#include "../../../../../../../third-party/Empirical/include/emp/base/vector.hpp"
#include "../../../../../fixtures/Sink.hpp"
#include "../../../../../setup/InterProcAddress.hpp"
#include "../../../../../spouts/Inlet.hpp"
#include "../RuntimeSizeBackEnd.hpp"
namespace uit {
template<typename PoolSpec>
class InletMemoryAccumulatingPool {
using address_t = uit::InterProcAddress;
emp::vector<address_t> addresses;
template<typename T>
using inlet_wrapper_t = typename PoolSpec::template inlet_wrapper_t<T>;
emp::optional<inlet_wrapper_t<uit::Inlet<PoolSpec>>> inlet;
using T = typename PoolSpec::T;
T buffer{};
// incremented every time TryFlush is called
// then reset to zero once every member of the pool has called
size_t pending_flush_counter{};
#ifndef NDEBUG
std::unordered_set<size_t> flush_index_checker;
#endif
using value_type = typename PoolSpec::T::value_type;
bool PutPool() {
emp_assert( IsInitialized() );
pending_flush_counter = 0;
#ifndef NDEBUG
flush_index_checker.clear();
#endif
// should we also flush the inlet?
const bool res = inlet->TryPut( std::move(buffer) );
buffer.resize( GetSize() );
if (res) std::fill( std::begin(buffer), std::end(buffer), value_type{} );
return res;
}
void CheckCallingProc() const {
[[maybe_unused]] const auto& rep = addresses.front();
emp_assert( rep.GetInletProc() == uitsl::get_rank( rep.GetComm() ) );
}
public:
bool IsInitialized() const { return inlet.has_value(); }
size_t GetSize() const { return addresses.size(); }
/// Retister a duct for an entry in the pool.
void Register(const address_t& address) {
emp_assert( !IsInitialized() );
emp_assert( std::find(
std::begin( addresses ), std::end( addresses ), address
) == std::end( addresses ) );
addresses.push_back(address);
}
/// Get index of this duct's entry in the pool.
size_t Lookup(const address_t& address) const {
emp_assert( IsInitialized() );
emp_assert( std::find(
std::begin(addresses), std::end(addresses), address
) != std::end(addresses) );
emp_assert( std::is_sorted( std::begin(addresses), std::end(addresses) ) );
CheckCallingProc();
return std::distance(
std::begin( addresses ),
std::lower_bound( // get address by binary search
std::begin( addresses ), std::end( addresses ), address
)
);
}
/// Get the querying duct's current value from the underlying duct.
bool TryPut(const value_type& val, const size_t index) {
emp_assert( IsInitialized() );
CheckCallingProc();
buffer[index] += val;
return true;
}
// TODO add move overload?
bool TryFlush(const size_t index) {
emp_assert( IsInitialized() );
CheckCallingProc();
emp_assert( flush_index_checker.insert(index).second );
if ( ++pending_flush_counter == GetSize() ) return PutPool();
else return true;
}
/// Call after all members have requested a position in the pool.
void Initialize() {
emp_assert( !IsInitialized() );
emp_assert( std::adjacent_find(
std::begin(addresses), std::end(addresses),
[](const auto& a, const auto& b){
return a.WhichProcsThreads() != b.WhichProcsThreads()
|| a.GetComm() != b.GetComm()
;
}
) == std::end(addresses) );
std::sort( std::begin( addresses ), std::end( addresses ) );
buffer.resize( addresses.size() );
auto backend = std::make_shared<
typename PoolSpec::ProcBackEnd
>( GetSize() );
auto sink = uit::Sink<PoolSpec>{
std::in_place_type_t<
typename PoolSpec::ProcInletDuct
>{},
addresses.front(),
backend
};
backend->Initialize();
inlet = sink.GetInlet();
emp_assert( IsInitialized() );
}
};
} // namespace uit
#endif // #ifndef UIT_DUCTS_PROC_IMPL_BACKEND_IMPL_INLETMEMORYACCUMULATINGPOOL_HPP_INCLUDE
| 26.73913 | 90 | 0.659233 | [
"vector"
] |
c75596030bcd9985bd586b266b0eb1ce6bcf43ea | 3,308 | cpp | C++ | src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/cameras/free_camera.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_shaders_store.h>
#include <babylon/materials/shader_material.h>
#include <babylon/meshes/mesh.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
class ShaderMaterialSkyboxScene : public IRenderableScene {
public:
/** Vertex Shader **/
static constexpr const char* gradientVertexShader
= R"ShaderCode(
#ifdef GL_ES
precision mediump float;
#endif
// Attributes
attribute vec3 position;
attribute vec3 normal;
attribute vec2 uv;
// Uniforms
uniform mat4 worldViewProjection;
// Varying
varying vec4 vPosition;
varying vec3 vNormal;
void main(void) {
vec4 p = vec4(position,1.);
vPosition = p;
vNormal = normal;
gl_Position = worldViewProjection * p;
}
)ShaderCode";
/** Pixel (Fragment) Shader **/
static constexpr const char* gradientPixelShader
= R"ShaderCode(
#ifdef GL_ES
precision mediump float;
#endif
// Uniforms
uniform float offset;
uniform mat4 worldView;
uniform vec3 topColor;
uniform vec3 bottomColor;
// Varying
varying vec4 vPosition;
varying vec3 vNormal;
void main(void)
{
float h = normalize(vPosition+offset).y;
gl_FragColor = vec4(mix(bottomColor,topColor,
max(pow(max(h,0.0),0.6),0.0)),1.0);
}
)ShaderCode";
public:
ShaderMaterialSkyboxScene(ICanvas* iCanvas) : IRenderableScene(iCanvas), _shaderMaterial{nullptr}
{
// Vertex shader
Effect::ShadersStore()["gradientVertexShader"] = gradientVertexShader;
// Pixel (Fragment) Shader
Effect::ShadersStore()["gradientFragmentShader"] = gradientPixelShader;
}
~ShaderMaterialSkyboxScene() override = default;
const char* getName() override
{
return "Shader Material Skybox Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// Create a FreeCamera
auto camera = FreeCamera::New("cam", Vector3(0.f, 0.f, -500.f), scene);
// Target the camera to scene origin
camera->setTarget(Vector3::Zero());
// Attach the camera to the canvas
camera->attachControl(canvas, true);
// Hemispheric light to light the scene
HemisphericLight::New("hemi", Vector3(0.f, 1.f, 0.f), scene);
// The skybox creation
auto skybox = Mesh::CreateSphere("skyBox", 10u, 1000.f, scene);
// Create shader material
IShaderMaterialOptions shaderMaterialOptions;
shaderMaterialOptions.attributes = {"position", "normal", "uv"};
shaderMaterialOptions.uniforms = {"worldViewProjection"};
_shaderMaterial = ShaderMaterial::New("gradient", scene, "gradient", shaderMaterialOptions);
_shaderMaterial->setFloat("offset", 0.f);
_shaderMaterial->setColor3("topColor", Color3::FromInts(0, 119, 255));
_shaderMaterial->setColor3("bottomColor", Color3::FromInts(240, 240, 255));
_shaderMaterial->backFaceCulling = false;
// box + sky = skybox !
skybox->material = _shaderMaterial;
}
private:
ShaderMaterialPtr _shaderMaterial;
}; // end of class ShaderMaterialSkyboxScene
BABYLON_REGISTER_SAMPLE("Shader Material", ShaderMaterialSkyboxScene)
} // end of namespace Samples
} // end of namespace BABYLON | 26.894309 | 99 | 0.724909 | [
"mesh"
] |
c75ef7289d77dec7c6895dea4a32275a4153718a | 28,018 | cpp | C++ | python/py-parse.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 10 | 2016-12-28T22:06:31.000Z | 2021-05-24T13:42:30.000Z | python/py-parse.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 4 | 2015-10-09T23:55:10.000Z | 2020-04-04T08:09:22.000Z | python/py-parse.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | null | null | null | // -*- coding: us-ascii-unix -*-
// Copyright 2014 Lukas Kemmer
//
// 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 "app/canvas.hh"
#include "app/frame.hh"
#include "bitmap/bitmap.hh"
#include "bitmap/bitmap-exception.hh"
#include "bitmap/color-span.hh"
#include "bitmap/gradient.hh"
#include "bitmap/paint.hh"
#include "bitmap/pattern.hh"
#include "geo/arc.hh"
#include "geo/calibration.hh"
#include "geo/int-rect.hh"
#include "geo/limits.hh"
#include "geo/line.hh"
#include "geo/pathpt.hh"
#include "geo/rect.hh"
#include "python/py-include.hh"
#include "python/py-function-error.hh"
#include "python/py-canvas.hh"
#include "python/py-color.hh"
#include "python/py-gradient.hh"
#include "python/py-grid.hh"
#include "python/py-util.hh"
#include "python/py-parse.hh"
#include "python/py-pattern.hh"
#include "python/py-settings.hh"
#include "python/py-shape.hh"
#include "python/py-something.hh"
#include "python/py-tri.hh"
#include "python/py-frame.hh"
#include "text/text-line.hh"
#include "util/grid.hh"
#include "util/key-press.hh"
#include "util/settings.hh"
#include "util/plain-type.hh"
#include "util-wx/file-path.hh"
namespace faint{
const TypeName arg_traits<Object>::name("Object");
const TypeName arg_traits<Object*>::name("Object");
const TypeName arg_traits<BoundObject<Object>>::name(arg_traits<Object>::name);
const TypeName arg_traits<bitmapObject>::name("Bitmap");
const TypeName arg_traits<Canvas>::name("Canvas");
const TypeName arg_traits<coord>::name("coordinate");
const TypeName arg_traits<BoundObject<ObjRaster>>::name("Raster object");
const TypeName arg_traits<BoundObject<ObjText>>::name("Text object");
const TypeName arg_traits<Grid>::name("Grid");
const TypeName arg_traits<Image>::name("Image");
const TypeName arg_traits<Index>::name("Index");
const TypeName arg_traits<IntLineSegment>::name("Line");
const TypeName arg_traits<LineSegment>::name("Line");
const TypeName arg_traits<Paint>::name("Paint");
const TypeName arg_traits<Settings>::name("Settings");
const TypeName arg_traits<Tri>::name("Tri");
const TypeName arg_traits<utf8_string>::name("str");
template<typename T>
TypeName type_name(const T&){
return arg_traits<T>::name;
}
template<typename T>
TypeName type_name(const T* const){
return arg_traits<T>::name;
}
template<typename T>
TypeName type_name(T*&){
return arg_traits<T>::name;
}
static PyObject* build_gradient(const Gradient& gradient){
if (gradient.IsLinear()){
linearGradientObject* py_gradient =
(linearGradientObject*)LinearGradientType.tp_alloc(&LinearGradientType, 0);
py_gradient->gradient = new LinearGradient(gradient.GetLinear());
return (PyObject*)py_gradient;
}
else if (gradient.IsRadial()){
radialGradientObject* py_gradient =
(radialGradientObject*)RadialGradientType.tp_alloc(&RadialGradientType, 0);
py_gradient->gradient = new RadialGradient(gradient.GetRadial());
return (PyObject*)py_gradient;
}
else{
assert(false);
return Py_BuildValue("");
}
}
static PyObject* build_pattern(const Pattern& pattern){
return pythoned(pattern);
}
static PyObject* build_color(const Color& color){
return pythoned(color);
}
static PyObject* build_paint(const Paint& paint){
return visit(paint, build_color, build_pattern, build_gradient);
}
bool parse_item(PyObject*& item, PyObject* args, Py_ssize_t&, Py_ssize_t, bool){
item = args;
return true;
}
static bool long_to_int(long src, int* dst){
if (can_represent<int>(src)){
*dst = static_cast<int>(src);
return true;
}
else{
return false;
}
}
bool parse_int(PyObject* args, Py_ssize_t n, int* value){
scoped_ref obj(PySequence_GetItem(args, n));
long temp = PyLong_AsLong(obj.get());
if (temp == -1 && PyErr_Occurred()){
return false;
}
return long_to_int(temp, value);
}
bool parse_bool(PyObject* args, Py_ssize_t n, bool* value){
scoped_ref obj(PySequence_GetItem(args, n));
*value = (1 == PyObject_IsTrue(obj.get()));
return true;
}
bool parse_Index(PyObject* args, Py_ssize_t n, Index* value){
scoped_ref obj(PySequence_GetItem(args, n));
long temp = PyLong_AsLong(obj.get());
if (temp == -1 && PyErr_Occurred()){
return false;
}
if (temp < 0){
throw ValueError("Negative index specified.", n);
}
int v;
if (long_to_int(temp, &v)){
*value = Index(v);
return true;
}
return false;
}
bool parse_coord(PyObject* args, Py_ssize_t n, coord* value){
if (PySequence_Check(args)){
scoped_ref obj(PySequence_GetItem(args, n));
coord temp = PyFloat_AsDouble(obj.get());
if (PyErr_Occurred()){
return false;
}
*value = temp;
return true;
}
else if (PyNumber_Check(args)){
// Fixme: This is a weird special case to support setters. Instead
// figure out when an arg-list is being parsed, vs. a type.
*value = PyFloat_AsDouble(args);
if (*value == -1.0){
if (PyErr_Occurred()){
return false;
}
}
return true;
}
else{
throw TypeError(arg_traits<coord>::name, n);
}
}
bool parse_bytes(PyObject* args, Py_ssize_t, std::string* value){
Py_ssize_t size = 0;
char* buffer = nullptr;
int result = PyBytes_AsStringAndSize(args, &buffer, &size);
if (result == -1){
// PyBytes_AsString will have raised TypeError
return false;
}
*value = std::string(buffer, size);
return true;
}
bool parse_flat(bitmapObject*& bmp, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "bitmap");
scoped_ref ref(PySequence_GetItem(args, n));
if (!PyObject_IsInstance(ref.get(), (PyObject*)&BitmapType)){
throw TypeError(type_name(bmp), n);
}
bmp = (bitmapObject*)(ref.get()); // Fixme: Looks dangerous
return true;
}
bool parse_flat(Object*& obj, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
// Fixme: This variant was added for parsing from PyShape,
// Should probably have a specific C++-side object for this.
throw_insufficient_args_if(len - n < 1, "Object");
if (!PySequence_Check(args)){
obj = shape_get_object(args);
if (obj == nullptr){
throw TypeError(type_name(obj), n);
}
return true;
}
scoped_ref ref(PySequence_GetItem(args, n));
obj = shape_get_object(ref.get());
if (obj == nullptr){
throw TypeError(arg_traits<Object>::name, n);
}
return true;
}
bool parse_flat(BoundObject<Object>& obj, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "Object");
if (!PySequence_Check(args)){
if (!is_Something(args)){
throw TypeError(type_name(obj), n);
}
obj = Something_as_BoundObject(args);
return true;
}
scoped_ref ref(PySequence_GetItem(args, n));
if (!is_Something(ref.get())){
throw TypeError(arg_traits<Object>::name, n);
}
obj = Something_as_BoundObject(ref.get());
return true;
}
bool parse_flat(Calibration& calibration, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 3, "Calibration");
coord x0, y0, x1, y1, lineLength;
PyObject* unitStr;
if (!PyArg_ParseTuple(args, "(dddd)dO",
&x0, &y0, &x1, &y1,
&lineLength,
&unitStr)){
throw PresetFunctionError();
}
PyObject* utf8 = PyUnicode_AsUTF8String(unitStr);
if (utf8 == nullptr){
throw PresetFunctionError();
}
char* bytes = PyBytes_AsString(utf8);
utf8_string unit(bytes);
calibration = Calibration(LineSegment(Point(x0,y0), Point(x1,y1)), lineLength,
unit);
return true;
}
bool parse_flat(Canvas*& canvas, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "Canvas");
scoped_ref ref(PySequence_GetItem(args, n));
if (!is_Canvas(ref.get())){
throw TypeError(arg_traits<Canvas>::name, n);
}
if (!canvas_ok(ref.get())){
throw ValueError("Operation on closed canvas.");
}
n += 1;
canvas = get_Canvas(ref.get());
return true;
}
bool parse_flat(Grid& grid, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "grid");
if (!is_Grid(args)){
throw TypeError(type_name(grid), n);
}
Optional<Grid> maybeGrid = get_grid(args);
if (!maybeGrid.IsSet()){
return false;
}
grid = maybeGrid.Get();
n += 1;
return true;
}
bool parse_flat(DefaultConstructible<Angle>& angle,
PyObject* args,
Py_ssize_t& n, Py_ssize_t len)
{
throw_insufficient_args_if(len - n < 1, "Angle");
coord radians;
if (parse_coord(args, n, &radians)){
n += 1;
angle.Set(Angle::Rad(radians));
return true;
}
return false;
}
bool parse_flat(DefaultConstructible<Delay>& delay,
PyObject* args,
Py_ssize_t& n, Py_ssize_t len)
{
// Fixme: Allow specifying e.g. seconds somehow from Python.
throw_insufficient_args_if(len - n < 1, "Delay");
int jiffies = 0;
if (parse_int(args, n, &jiffies)){
n += 1;
delay.Set(Delay(jiffies_t(jiffies)));
return true;
}
return false;
}
bool parse_flat(DefaultConstructible<FilePath>& p,
PyObject* args,
Py_ssize_t& n,
Py_ssize_t len)
{
throw_insufficient_args_if(len - n < 1, "File path");
// Fixme: Check error handling behavior
scoped_ref utf8(PyUnicode_AsUTF8String(args));
if (utf8 == nullptr){
throw PresetFunctionError();
}
const char* bytes = PyBytes_AsString(utf8.get());
if (bytes == nullptr){
throw PresetFunctionError();
}
utf8_string str(bytes);
if (!is_absolute_path(str)){
throw ValueError(space_sep(quoted(str), "is not absolute."));
}
if (!is_file_path(str)){
throw ValueError(space_sep(quoted(str), "is not a valid file name."));
}
p.Set(FilePath::FromAbsolute(str));
return true;
}
bool parse_flat(const Image*& image,
PyObject* args,
Py_ssize_t& n,
Py_ssize_t len)
{
throw_insufficient_args_if(len - n < 1, "Canvas");
scoped_ref ref(PySequence_GetItem(args, n));
if (!is_Frame(ref.get())){
throw TypeError(type_name(image), n);
}
if (expired_Frame(ref.get())){
throw ValueError("Operation on closed Frame.");
}
image = get_Frame(ref.get());
return true;
}
bool parse_flat(bool& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "boolean");
if (PySequence_Check(args)){
if (!parse_bool(args, n, &value)){
return false;
}
n += 1;
return true;
}
else{
value = (1 == PyObject_IsTrue(args));
n += 1;
return true;
}
}
bool parse_flat(int& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "integer");
if (PySequence_Check(args)){
if (!parse_int(args, n, &value)){
return false;
}
n += 1;
return true;
}
long temp = PyLong_AsLong(args);
if (temp == -1 && PyErr_Occurred()){
return false;
}
if (long_to_int(temp, &value)){
n += 1;
return true;
}
return false;
}
bool parse_flat(Index& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "index");
if (PySequence_Check(args)){
if (!parse_Index(args, n, &value)){
return false;
}
n += 1;
return true;
}
long temp = PyLong_AsLong(args);
if (temp == -1 && PyErr_Occurred()){
return false;
}
if (temp < 0){
throw ValueError("Negative index specified.", n);
}
int v;
if (long_to_int(temp, &v)){
value = Index(v);
n += 1;
return true;
}
return false;
}
bool parse_flat(coord& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "float");
if (parse_coord(args, n, &value)){
n += 1;
return true;
}
return false;
}
bool parse_flat(IntSize& size, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "size");
int w, h;
if (!parse_int(args, n, &w) ||!parse_int(args, n+1, &h)){
return false;
}
if (w <= 0 || h <= 0){
throw ValueError("Size must be positive", n);
}
size.w = w;
size.h = h;
return true;
}
bool parse_flat(IntRect& r, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 4, "IntRect");
int x, y, w, h;
if (!parse_int(args, n, &x) ||
!parse_int(args, n + 1, &y) ||
!parse_int(args, n + 2, &w) ||
!parse_int(args, n + 3, &h)){
// Note: PyErr already set by parse_int
return false;
}
if (w < 0){
throw ValueError("Negative rectangle width specified.");
}
if (h < 0){
throw ValueError("Negative rectangle height specified.");
}
n += 4;
r.x = x;
r.y = y;
r.w = w;
r.h = h;
return true;
}
bool parse_flat(Tri& tri, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "Tri");
if (is_Tri(args)){
tri = as_Tri(args);
return true;
}
scoped_ref ref(PySequence_GetItem(args, n));
if (!is_Tri(ref.get())){
throw TypeError(type_name(tri), n);
}
Tri t = as_Tri(ref.get());
if (!valid(t)){
throw ValueError("Invalid Tri.");
}
tri = t;
n += 1;
return true;
}
bool parse_flat(Radii& radii, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "Radii");
coord rx, ry;
if (!parse_coord(args, n, &rx) || !parse_coord(args, n+1, &ry)){
return false;
}
radii.x = rx;
radii.y = ry;
return true;
}
bool parse_flat(Color& color, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
const auto items = len - n;
throw_insufficient_args_if(items < 1, "color");
{
scoped_ref ref(PySequence_GetItem(args, n));
auto* c = as_Color(ref.get());
if (c != nullptr){
color = *c;
n += 1;
return true;
}
}
throw_insufficient_args_if(items < 3, "color");
int readItems = 0;
int r, g, b;
int a = 255;
if (!parse_int(args, n, &r) ||
!parse_int(args, n + 1, &g) ||
!parse_int(args, n + 2, &b)){
return false;
}
readItems += 3;
if (items >= 4){
if (!parse_int(args, n + 3, &a)){
return false;
}
readItems += 1;
}
if (!valid_color(r,g,b,a)){
throw ValueError("Invalid color", n);
}
n += readItems;
color = color_from_ints(r,g,b,a);
return true;
}
bool parse_flat(ColorSpan& colorSpan, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
const auto numItems = len - n;
throw_insufficient_args_if(numItems < 2, "ColorSpan");
scoped_ref maybeColor(PySequence_GetItem(args, n));
scoped_ref maybeSize(PySequence_GetItem(args, n + 1));
Color color;
Py_ssize_t n2 = 0;
if (!parse_flat(color, maybeColor.get(), n2,
PySequence_Length(maybeColor.get())))
{
throw TypeError("First item of ColorSpan must be a color.");
}
IntSize size;
Py_ssize_t n3 = 0;
if (!parse_flat(size, maybeSize.get(), n3, PySequence_Length(maybeSize.get()))){
throw TypeError("Second item of ColorSpan must be a size.");
}
colorSpan = ColorSpan(color, size);
n += 2;
return true;
}
bool parse_flat(Rect& r, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 4, "Rect");
coord x, y, w, h;
if (!parse_coord(args, n, &x) ||
!parse_coord(args, n + 1, &y) ||
!parse_coord(args, n + 2, &w) ||
!parse_coord(args, n + 3, &h)){
// Note: PyErr already set by parse_coord
return false;
}
if (w < 0){
throw ValueError("Negative rectangle width specified.");
}
if (h < 0){
throw ValueError("Negative rectangle height specified.");
}
n += 4;
r.x = x;
r.y = y;
r.w = w;
r.h = h;
return true;
}
static Optional<Gradient> as_Gradient(PyObject* obj){
if (PyObject_IsInstance(obj, (PyObject*)&LinearGradientType)){
linearGradientObject* pyGradient = (linearGradientObject*)(obj);
return option(Gradient(*pyGradient->gradient));
}
else if (PyObject_IsInstance(obj, (PyObject*)&RadialGradientType)){
radialGradientObject* pyGradient = (radialGradientObject*)(obj);
return option(Gradient(*pyGradient->gradient));
}
PyErr_SetString(PyExc_TypeError,
"The argument must be a LinearGradient or a RadialGradient object");
return no_option();
}
static bool parse_non_sequence(Paint& paint, PyObject* arg){
Color* color = as_Color(arg);
if (color != nullptr){
paint = Paint(*color);
return true;
}
Optional<Gradient> gradient = as_Gradient(arg);
if (gradient.IsSet()){
paint = Paint(gradient.Get());
return true;
}
// Try parsing as pattern instead
PyErr_Clear();
Pattern* pattern = as_Pattern(arg);
if (pattern != nullptr){
paint = Paint(*pattern);
return true;
}
return false;
}
bool parse_flat(Paint& paint, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
if (!PySequence_Check(args)){
if (parse_non_sequence(paint, args)){
return true;
}
else{
throw TypeError("Expected a color, pattern or gradient.");
}
}
scoped_ref ref(PySequence_GetItem(args, n));
Optional<Gradient> gradient = as_Gradient(ref.get());
if (gradient.IsSet()){
paint = Paint(gradient.Get());
n += 1;
return true;
}
PyErr_Clear();
Pattern* pattern = as_Pattern(ref.get());
if (pattern != nullptr){
paint = Paint(*pattern);
n += 1;
return true;
}
PyErr_Clear();
Color c;
if (parse_flat(c, args, n, len)){ // Fixme: For some reason wrong n if error
paint = Paint(c);
return true;
}
throw TypeError(type_name(paint), n);
}
bool parse_flat(IntLineSegment& line, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 4, "line segment");
int x0;
int y0;
int x1;
int y1;
if (!parse_int(args, n, &x0) ||
!parse_int(args, n + 1, &y0) ||
!parse_int(args, n + 2, &x1) ||
!parse_int(args, n + 3, &y1)){
throw TypeError(type_name(line), "requires four coordinates", n);
}
n += 4;
line.p0.x = x0;
line.p0.y = y0;
line.p1.x = x1;
line.p1.y = y1;
return true;
}
bool parse_flat(IntPoint& pt, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "IntPoint");
int x, y;
if (!parse_int(args, n, &x) ||
!parse_int(args,n+1, &y)){
return false;
}
pt.x = x;
pt.y = y;
return true;
}
bool parse_flat(ColorStop& stop, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "color stop");
double offset;
int r,g,b;
int a = 255;
if (!PyArg_ParseTuple(args + n, "d(iii)", &offset, &r, &g, &b)){
PyErr_Clear();
if (!PyArg_ParseTuple(args + n, "d(iiii)", &offset, &r, &g, &b, &a)){
PyErr_Clear();
throw ValueError("Invalid color stop", n);
}
}
if (offset < 0.0 || 1.0 < offset){
throw ValueError("Offset must be in range 0.0-1.0", n);
}
if (invalid_color(r,g,b,a)){
throw ValueError("Invalid color specified", n);
}
stop = ColorStop(color_from_ints(r,g,b,a), offset);
return true;
}
bool parse_flat(LineSegment& line, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 4, "line segment");
coord x0;
coord y0;
coord x1;
coord y1;
if (!parse_coord(args, n, &x0) ||
!parse_coord(args, n + 1, &y0) ||
!parse_coord(args, n + 2, &x1) ||
!parse_coord(args, n + 3, &y1)){
throw TypeError(type_name(line), "requires four coordinates", n);
}
n += 4;
line.p0.x = x0;
line.p0.y = y0;
line.p1.x = x1;
line.p1.y = y1;
return true;
}
bool parse_flat(Point& pt, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "IntPoint");
coord x, y;
if (!parse_coord(args, n, &x) ||
!parse_coord(args,n+1, &y)){
return false;
}
pt.x = x;
pt.y = y;
return true;
}
bool parse_flat(ColRGB& color, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 3, "RGB-color");
int r, g, b;
if (!parse_int(args, n, &r) ||
!parse_int(args, n + 1, &g) ||
!parse_int(args, n + 2, &b)){
return false;
}
if (!valid_color(r,g,b)){
throw ValueError("Color component outside valid range", n);
}
color = rgb_from_ints(r,g,b);
return true;
}
bool parse_flat(std::string& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "byte string");
if (parse_bytes(args, n, &value)){
n += 1;
return true;
}
return false;
}
bool parse_flat(utf8_string& value, PyObject* args, Py_ssize_t& n,
Py_ssize_t /*len*/){
if (n != 0){
throw ValueError("Flat string parse not starting at 0?");
}
return parse_py_unicode(args).Visit(
[&value, &n](const utf8_string& s){
value = s;
n += 1;
return true;
},
[&value, &n]() -> bool{
PyErr_Clear(); // Fixme: Remove error-setting in parse_py_unicode
throw TypeError(type_name(value), n);
});
}
bool parse_flat(Settings& s, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "Settings");
scoped_ref ref(PySequence_GetItem(args, n));
if (!is_Settings(ref.get())){
throw TypeError(type_name(s), n);
}
s = *as_Settings(ref.get());
n += 1;
return true;
}
static Bitmap* as_Bitmap(PyObject* obj, Py_ssize_t n){
if (!PyObject_IsInstance(obj, (PyObject*)&BitmapType)){
throw TypeError(TypeName("Bitmap"), n);
}
bitmapObject* py_bitmap = (bitmapObject*)obj;
return &(py_bitmap->bmp);
}
bool parse_flat(Bitmap& bmp, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 1, "Bitmap");
scoped_ref ref(PySequence_GetItem(args, n));
Bitmap* tempBmp = as_Bitmap(ref.get(), n);
assert(tempBmp != nullptr);
n += 1;
bmp = *tempBmp; // Fixme: Unnecessary copy
return true;
}
bool parse_flat(AngleSpan& span, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "angle span");
coord a1;
coord a2;
if (!parse_coord(args, n, &a1) || !parse_coord(args, n + 1, &a2)){
return false;
}
n += 2;
span.start = Angle::Rad(a1);
span.stop = Angle::Rad(a2);
return true;
}
bool parse_flat(KeyPress& value, PyObject* args, Py_ssize_t& n, Py_ssize_t len){
throw_insufficient_args_if(len - n < 2, "KeyPress");
int keyCode, modifier;
if (!parse_int(args, n, &keyCode) || !parse_int(args, n + 1, &modifier)){
return false;
}
// Fixme: Add sanity check for code and modifiers
n += 2;
value = KeyPress(Mod::Create(modifier), Key(keyCode));
return true;
}
PyObject* build_result(const Angle& angle){
return build_result(angle.Rad());
}
PyObject* build_result(const AngleSpan& angleSpan){
return build_result(std::pair(angleSpan.start, angleSpan.stop));
}
PyObject* build_result(const Delay& delay){
// Fixme: Would be better to return a Python type.
return build_result(delay.Get().count());
}
PyObject* build_result(bool value){
if (value){
Py_RETURN_TRUE;
}
else{
Py_RETURN_FALSE;
}
}
PyObject* build_result(const Bitmap& bmp){
static const auto set_out_of_memory_error =
[](){
PyErr_SetString(PyExc_MemoryError,
"Insufficient memory for allocating Bitmap");
return nullptr;
};
assert(bitmap_ok(bmp));
try{
bitmapObject* py_bitmap = (bitmapObject*)BitmapType.tp_alloc(&BitmapType, 0);
if (py_bitmap == nullptr){
return nullptr;
}
py_bitmap->bmp = bmp;
return (PyObject*)py_bitmap;
}
catch(const BitmapOutOfMemory&){
return set_out_of_memory_error();
}
catch(const std::bad_alloc&){
return set_out_of_memory_error();
}
}
PyObject* build_result(const BoundObject<Object>& obj){
return pythoned(obj.obj, *obj.ctx, obj.canvas, obj.frameId);
}
PyObject* build_result(const Bound<Canvas>& canvas){
return pythoned(canvas.item, canvas.ctx);
}
PyObject* build_result(const Calibration& c){
PyObject* list(PyList_New(3));
PyList_SetItem(list, 0, build_result(c.pixelLine));
PyList_SetItem(list, 1, build_result(c.length));
PyList_SetItem(list, 2, build_result(c.unit));
return list;
}
PyObject* build_result(const CanvasGrid& grid){
return py_grid(grid);
}
PyObject* build_result(const Color& color){
return pythoned(color);
}
PyObject* build_result(const ColorStop& stop){
Color c(stop.GetColor());
double offset(stop.GetOffset());
return Py_BuildValue("d(iiii)", offset, c.r, c.g, c.b, c.a);
}
PyObject* build_result(coord value){
return Py_BuildValue("d", value);
}
PyObject* build_result(const DirPath& dirPath){
return build_unicode(dirPath.Str());
}
PyObject* build_result(const FilePath& filePath){
return build_unicode(filePath.Str());
}
PyObject* build_result(const Frame& frame){
return build_Frame(frame.ctx, frame.canvas, frame.frameId);
}
PyObject* build_result(const Index& index){
return build_result(index.Get());
}
PyObject* build_result(int value){
return Py_BuildValue("i", value);
}
PyObject* build_result(const IntPoint& pos){
return Py_BuildValue("ii", pos.x, pos.y);
}
PyObject* build_result(const IntRect& rect){
return Py_BuildValue("iiii",rect.x, rect.y, rect.w, rect.h);
}
PyObject* build_result(const IntSize& size){
return Py_BuildValue("ii", size.w, size.h);
}
PyObject* build_result(const LinearGradient& lg){
return build_result(Paint(lg));
}
PyObject* build_result(const LineSegment& l){
return Py_BuildValue("dddd", l.p0.x, l.p0.y, l.p1.x, l.p1.y);
}
PyObject* build_result(const TextLine& line){
int hardBreak = line.hardBreak ? 1 : 0;
return Py_BuildValue("(iOd)", hardBreak, build_result(line.text),
line.width);
}
PyObject* build_result(const Pattern& pattern){
return build_result(Paint(pattern));
}
PyObject* build_result(const Paint& paint){
return build_paint(paint);
}
PyObject* build_result(const PathPt& pt){
return pt.Visit(
[](const ArcTo& arc){
return make_py_list({PyUnicode_FromString("A"),
PyFloat_FromDouble(arc.p.x),
PyFloat_FromDouble(arc.p.y),
PyFloat_FromDouble(arc.r.x),
PyFloat_FromDouble(arc.r.y),
PyFloat_FromDouble(arc.axisRotation.Deg()),
PyLong_FromLong(arc.largeArcFlag),
PyLong_FromLong(arc.sweepFlag)});
},
[](const Close&){
return make_py_list({PyUnicode_FromString("Z")});
},
[](const CubicBezier& bezier){
return make_py_list({PyUnicode_FromString("C"),
PyFloat_FromDouble(bezier.p.x),
PyFloat_FromDouble(bezier.p.y),
PyFloat_FromDouble(bezier.c.x),
PyFloat_FromDouble(bezier.c.y),
PyFloat_FromDouble(bezier.d.x),
PyFloat_FromDouble(bezier.d.y)});
},
[](const LineTo& line){
return make_py_list({
PyUnicode_FromString("L"),
PyFloat_FromDouble(line.p.x),
PyFloat_FromDouble(line.p.y)});
},
[](const MoveTo& move){
return make_py_list({
PyUnicode_FromString("M"),
PyFloat_FromDouble(move.p.x),
PyFloat_FromDouble(move.p.y)});
});
}
PyObject* build_result(const Point& pos){
return Py_BuildValue("dd", pos.x, pos.y);
}
PyObject* build_result(PyObject* obj){
return obj;
}
PyObject* build_result(const RadialGradient& rg){
return build_result(Paint(rg));
}
PyObject* build_result(const Radii& r){
return Py_BuildValue("dd", r.x, r.y);
}
PyObject* build_result(const Rect& rect){
return Py_BuildValue("dddd", rect.x, rect.y, rect.w, rect.h);
}
PyObject* build_result(const Settings& s){
return pythoned(s);
}
PyObject* build_result(const std::string& str){
return PyBytes_FromStringAndSize(str.c_str(), resigned(str.size()));
}
PyObject* build_result(const Tri& tri){
return pythoned(tri);
}
PyObject* build_result(const utf8_string& s){
return build_unicode(s);
}
} // namespace
| 24.750883 | 89 | 0.662181 | [
"object",
"shape"
] |
c762ace0d86333d9f70158a27e45b7eeac0e5d7e | 568 | cpp | C++ | Problemset/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/cong-shang-dao-xia-da-yin-er-cha-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2020-10-06T01:06:45.000Z | 2020-10-06T01:06:45.000Z | Problemset/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/cong-shang-dao-xia-da-yin-er-cha-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | null | null | null | Problemset/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/cong-shang-dao-xia-da-yin-er-cha-shu-lcof.cpp | Singularity0909/LeetCode | d46fb1c8ed9b16339d46d5c37f69d44e5c178954 | [
"MIT"
] | 1 | 2021-11-17T13:52:51.000Z | 2021-11-17T13:52:51.000Z |
// @Title: 从上到下打印二叉树 (从上到下打印二叉树 LCOF)
// @Author: Singularity0909
// @Date: 2020-07-21 20:26:09
// @Runtime: 4 ms
// @Memory: 12 MB
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
if (!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* now = q.front();
q.pop();
res.push_back(now->val);
if (now->left) q.push(now->left);
if (now->right) q.push(now->right);
}
return res;
}
};
| 22.72 | 47 | 0.503521 | [
"vector"
] |
c7657a6e15ad44a8f5c1bbe39e244ad3c29c2ee2 | 6,098 | cpp | C++ | src/Pipeline.cpp | chao-mu/vidrevolt | d7be4ed7a30ef9cec794c54ca1a06e4117420604 | [
"MIT"
] | null | null | null | src/Pipeline.cpp | chao-mu/vidrevolt | d7be4ed7a30ef9cec794c54ca1a06e4117420604 | [
"MIT"
] | null | null | null | src/Pipeline.cpp | chao-mu/vidrevolt | d7be4ed7a30ef9cec794c54ca1a06e4117420604 | [
"MIT"
] | null | null | null | #include "Pipeline.h"
// STL
#include <stdexcept>
// Ours
#include "midi/Device.h"
#include "KeyboardManager.h"
#include "osc/Server.h"
#include "gl/ParamSet.h"
namespace vidrevolt {
Pipeline::Pipeline() : rand_gen_(rand_dev_()) {}
void Pipeline::load(const Resolution& resolution) {
resolution_ = resolution;
renderer_->setResolution(resolution_);
for (auto& vid_kv : videos_) {
vid_kv.second->waitForLoaded();
}
}
void Pipeline::restartAudio() {
music_.stop();
music_.play();
}
void Pipeline::playAudio(const std::string& path) {
if (!music_.openFromFile(path)) {
throw std::runtime_error("Unable to load audio file: " + path);
}
music_.play();
}
void Pipeline::setBPMSync(const std::string& key, std::shared_ptr<BPMSync> sync) {
setController(key, sync);
bpm_syncs_[key] = sync;
}
Pipeline::ObjID Pipeline::addKeyboard() {
ObjID id = next_id("keyboard");
setController(id, KeyboardManager::makeKeyboard());
return id;
}
Pipeline::ObjID Pipeline::addBPMSync() {
ObjID id = next_id("bpm_sync");
setBPMSync(id, std::make_shared<BPMSync>());
return id;
}
Pipeline::ObjID Pipeline::addOSC(int port, const std::string& path) {
ObjID id = next_id(path);
auto osc = std::make_shared<osc::Server>(port, path);
osc->start();
setController(id, std::move(osc));
return id;
}
Pipeline::ObjID Pipeline::addVideo(const std::string& path, bool auto_reset, Video::Playback pb) {
ObjID id = next_id(path);
auto vid = std::make_unique<Video>(path, auto_reset, pb);
vid->start();
setVideo(id, std::move(vid));
return id;
}
Pipeline::ObjID Pipeline::addWebcam(int device) {
ObjID id = next_id("webcam(" + std::to_string(device) + ")");
auto vid = std::make_unique<Webcam>(device);
vid->start();
setWebcam(id, std::move(vid));
return id;
}
Pipeline::ObjID Pipeline::addMidi(const std::string& path) {
ObjID id = next_id(path);
auto dev = std::make_shared<midi::Device>(path);
dev->start();
setController(id, dev);
return id;
}
Pipeline::ObjID Pipeline::addImage(const std::string& path) {
ObjID id = next_id(path);
cv::Mat frame = Image::load(path);
renderer_->render(id, frame);
return id;
}
void Pipeline::tap(const std::string& sync_id) {
if (!bpm_syncs_.count(sync_id)) {
throw std::runtime_error("Attempt to tap non-existent BPM sync");
}
bpm_syncs_.at(sync_id)->tap();
}
void Pipeline::reconnectControllers() {
for (auto& kv : controllers_) {
kv.second->reconnect();
}
}
void Pipeline::addRenderStep(const std::string& target, const std::string& path, gl::ParamSet params, std::vector<Address> video_deps) {
for (const auto& addr : video_deps) {
in_use_[addr] = true;
FrameSource* source = nullptr;
if (videos_.count(addr) > 0) {
source = videos_.at(addr).get();
} else if (webcams_.count(addr) > 0) {
source = webcams_.at(addr).get();
}
if (source != nullptr) {
auto frame_opt = source->nextFrame();
if (frame_opt) {
renderer_->render(addr, frame_opt.value());
}
}
}
renderer_->render(target, path, params);
render_steps_.push_back(RenderStep{target, path});
}
void Pipeline::setFPS(const std::string& id, double fps) {
if (!videos_.count(id)) {
throw std::runtime_error("Attempt to set fps on non-existent video");
}
videos_.at(id)->setFPS(fps);
}
void Pipeline::flipPlayback(const std::string& id) {
if (!videos_.count(id)) {
throw std::runtime_error("Attempt to flip non-existent video");
}
videos_.at(id)->flipPlayback();
}
std::map<std::string, std::shared_ptr<Controller>> Pipeline::getControllers() const {
return controllers_;
}
RenderResult Pipeline::render(std::function<void()> f) {
last_in_use_ = in_use_;
in_use_.clear();
for (const auto& kv : controllers_) {
kv.second->poll();
}
render_steps_.clear();
// Perform render
f();
// Trigger out/in focus
for (const auto& kv : videos_) {
const auto& addr = kv.first;
auto& vid = kv.second;
bool was_in_use = last_in_use_.count(addr) > 0 ? last_in_use_.at(addr) : false;
bool is_in_use = in_use_.count(addr) > 0 ? in_use_.at(addr) : false;
if (was_in_use && !is_in_use) {
vid->outFocus();
} else if (!was_in_use && is_in_use) {
vid->inFocus();
}
}
RenderResult res;
res.primary = renderer_->getLast();
res.aux = renderer_->getLastAux();
return res;
}
void Pipeline::setWebcam(const std::string& key, std::unique_ptr<Webcam> vid) {
webcams_[key] = std::move(vid);
}
void Pipeline::setVideo(const std::string& key, std::unique_ptr<Video> vid) {
videos_[key] = std::move(vid);
}
void Pipeline::setController(const std::string& key, std::shared_ptr<Controller> controller) {
controllers_[key] = controller;
}
Pipeline::ObjID Pipeline::next_id(const std::string& comment) {
obj_id_cursor_++;
return "ObjID:" + std::to_string(obj_id_cursor_) + ":" + comment;
}
Resolution Pipeline::getResolution() {
return resolution_;
}
std::vector<RenderStep> Pipeline::getRenderSteps() {
return render_steps_;
}
float Pipeline::rand() {
return std::generate_canonical<float, 10>(rand_gen_);
}
}
| 27.102222 | 140 | 0.566087 | [
"render",
"vector"
] |
c768d271c8133a095f151b46fbbf215e987d8999 | 5,870 | cpp | C++ | BenchElise/bench/b_0_1.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 451 | 2016-11-25T09:40:28.000Z | 2022-03-30T04:20:42.000Z | BenchElise/bench/b_0_1.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 143 | 2016-11-25T20:35:57.000Z | 2022-03-01T11:58:02.000Z | BenchElise/bench/b_0_1.cpp | kikislater/micmac | 3009dbdad62b3ad906ec882b74b85a3db86ca755 | [
"CECILL-B"
] | 139 | 2016-12-02T10:26:21.000Z | 2022-03-10T19:40:29.000Z | /*eLiSe06/05/99
Copyright (C) 1999 Marc PIERROT DESEILLIGNY
eLiSe : Elements of a Linux Image Software Environment
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Author: Marc PIERROT DESEILLIGNY IGN/MATIS
Internet: Marc.Pierrot-Deseilligny@ign.fr
Phone: (33) 01 43 98 81 28
eLiSe06/05/99*/
#include "StdAfx.h"
#include "bench.h"
void verif_som_x_rect(Pt2di p1,Pt2di p2)
{
int res,res_sel;
ELISE_COPY(rectangle(p1,p2),FX,sigma(res));
ELISE_COPY(select(rectangle(p1,p2),1),FX,sigma(res_sel));
BENCH_ASSERT(res == ElAbs(som_x(p1.x,p2.x)*(p1.y-p2.y)));
BENCH_ASSERT(res == res_sel);
}
void verif_som_y_rect(Pt2di p1,Pt2di p2)
{
int res,res_sel;
ELISE_COPY(rectangle(p1,p2),FY,sigma(res));
ELISE_COPY(select(rectangle(p1,p2),1),FY,sigma(res_sel));
BENCH_ASSERT(res == ElAbs(som_x(p1.y,p2.y)*(p1.x-p2.x)));
BENCH_ASSERT(res == res_sel);
}
void verif_som_coord_rect(Pt2di p1,Pt2di p2)
{
verif_som_x_rect(p1,p2);
verif_som_y_rect(p1,p2);
}
void verif_som_coord_rect()
{
All_Memo_counter MC_INIT;
stow_memory_counter(MC_INIT);
{
verif_som_coord_rect(Pt2di(-10,-13),Pt2di(103,105));
verif_som_coord_rect(Pt2di(0,0),Pt2di(10,10));
{
INT res;
ELISE_COPY(rectangle(Pt2di(-10,-13),Pt2di(103,105)),FY+FX*3,sigma(res));
}
}
verif_memory_state(MC_INIT);
}
//=============================================
template <class Type> void verif_max_or_min_x
( const OperAssocMixte & op,
Type expected,
Pt2di p1,
Pt2di p2,
bool reel
)
{
Type v;
ELISE_COPY(rectangle(p1,p2),reel ? Rconv(FX) : FX,reduc(op,v));
BENCH_ASSERT(v == expected);
}
template <class Type> void verif_max_and_min_x(Pt2di p1,Pt2di p2,Type *,bool reel)
{
verif_max_or_min_x(OpMax,(Type) (p2.x-1),p1,p2,reel);
verif_max_or_min_x(OpMin,(Type) (p1.x),p1,p2,reel);
}
void verif_max_min_x(Pt2di p1,Pt2di p2)
{
verif_max_and_min_x(p1,p2,(INT *) 0,false);
verif_max_and_min_x(p1,p2,(REAL *) 0,true);
}
void verif_witch_max_min()
{
INT imin,imax;
REAL rmin,rmax;
ELISE_COPY
(
rectangle(0,10),
FX,
WhichMin(imin) | WhichMax (imax)
| WhichMin(rmin) | WhichMax (rmax)
);
BENCH_ASSERT
(
(imin==0) && (imax==9)
&& (rmin==0) && (rmax==9)
);
Pt2di pimin,pimax;
Pt2dr prmin,prmax;
Pt2dr q;
ELISE_COPY
(
rectangle(Pt2di(-20,-20),Pt2di(12,10)).chc(Virgule(FX+0.1,FY+0.1)),
Virgule
(
sqrt(Square(FX)+Square(FY)),
FX+FY
),
Virgule
(
pimin.WhichMin() | pimax.WhichMax ()
| prmin.WhichMin() | prmax.WhichMax ()
, q.WhichMax()
)
);
BENCH_ASSERT
(
(euclid(pimin,Pt2di((INT)0.1,(INT)0.1) ) < epsilon)
&& (euclid(pimax,Pt2di((INT)-19.9,(INT)-19.9) ) < epsilon)
&& (euclid(prmin,Pt2dr(0.1,0.1) ) < epsilon)
&& (euclid(prmax,Pt2dr(-19.9,-19.9)) < epsilon)
&& (euclid( q,Pt2dr(11.1,9.1) ) < epsilon)
);
}
void verif_max_min()
{
verif_witch_max_min();
verif_max_min_x(Pt2di(2,2),Pt2di(10,10));
}
void bench_cmpFN()
{
std::vector <Fonc_Num> vF;
cVarSpec aVX(1,"X");
cVarSpec aVY(2,"Y");
vF.push_back(FX);
vF.push_back(FY);
vF.push_back(cos(1+FY));
vF.push_back(cos(2+FY));
for (INT k=0 ; k< 3; k++)
vF.push_back(cos(1+FZ));
for (INT k=0 ; k< 3; k++)
vF.push_back(1.0);
vF.push_back(2.0);
for (INT k=0 ; k< 3; k++)
vF.push_back(aVX*aVY);
vF.push_back(2.0);
INT aNB = vF.size();
// Reflexivite
for (INT aK=0 ; aK < aNB ; aK++)
{
Fonc_Num F = vF[aK];
BENCH_ASSERT(F.CmpFormel(F)==0);
}
INT NbEq =0;
// Anti symetrie
for (INT aK1=0 ; aK1 < aNB ; aK1++)
{
for (INT aK2=aK1+1 ; aK2 < aNB ; aK2++)
{
Fonc_Num F1 = vF[aK1];
Fonc_Num F2 = vF[aK2];
INT C12 = F1.CmpFormel(F2);
INT C21 = F2.CmpFormel(F1);
BENCH_ASSERT(C12+C21==0);
BENCH_ASSERT(ElAbs(C12)<2);
if (C12 == 0)
{
NbEq ++;
PtsKD aP(8);
for (INT aD =0 ; aD<8 ; aD++)
aP(aD) = NRrandom3();
REAL aV1 = F1.ValFonc(aP);
REAL aV2 = F2.ValFonc(aP);
BENCH_ASSERT(ElAbs(aV1-aV2)<epsilon);
}
}
}
BENCH_ASSERT(NbEq==10);
// Reflexivite
for (INT aK1=0 ; aK1 < aNB ; aK1++)
{
for (INT aK2=aK1+1 ; aK2 < aNB ; aK2++)
{
for (INT aK3=aK2+1 ; aK3 < aNB ; aK3++)
{
Fonc_Num F1 = vF[aK1];
Fonc_Num F2 = vF[aK2];
Fonc_Num F3 = vF[aK3];
INT C12 = F1.CmpFormel(F2);
INT C23 = F2.CmpFormel(F3);
INT C31 = F3.CmpFormel(F1);
BENCH_ASSERT(ElAbs(C12+C23+C31)<2);
INT NbEq = (C12==0) + (C23==0) + (C31==0);
BENCH_ASSERT(NbEq != 2);
}
}
}
}
| 23.574297 | 84 | 0.550256 | [
"vector"
] |
c773f5c5b883e193b0d0327e4819f81a810fd4f5 | 1,632 | cpp | C++ | OTHER/PlyProgram/PlyVisualization/src/ply/readPly.cpp | Magic-Xin/Luogu | d8f1b4461f33f946c0a9ce4d36f1e5369518b7a6 | [
"MIT"
] | 15 | 2020-10-08T06:59:38.000Z | 2021-11-30T11:20:22.000Z | OTHER/PlyProgram/PlyVisualization/src/ply/readPly.cpp | Magic-Xin/Luogu | d8f1b4461f33f946c0a9ce4d36f1e5369518b7a6 | [
"MIT"
] | 1 | 2022-03-12T01:00:59.000Z | 2022-03-12T01:00:59.000Z | OTHER/PlyProgram/PlyVisualization/src/ply/readPly.cpp | Magic-Xin/Luogu | d8f1b4461f33f946c0a9ce4d36f1e5369518b7a6 | [
"MIT"
] | 2 | 2021-02-08T11:30:20.000Z | 2021-05-31T06:47:34.000Z | //
// Created by MagicXin on 2021/4/9.
//
#include "readPly.h"
void read_ply_file(const std::string filepath, std::vector<float3> &verts) {
try {
std::ifstream ss(filepath);
if (ss.fail()) {
throw std::runtime_error("Failed to open: " + filepath);
}
tinyply::PlyFile file;
file.parse_header(ss);
std::shared_ptr<tinyply::PlyData> vertices;
try {
vertices = file.request_properties_from_element("vertex", {"x", "y", "z"});
}
catch (const std::exception &e) {
std::cerr << "tinyply exception: " << e.what() << std::endl;
}
manual_timer read_timer;
read_timer.start();
file.read(ss);
read_timer.stop();
const float parsing_time = static_cast<float>(read_timer.get()) / 1000.f;
std::cout << "\tparsing in " << parsing_time << " seconds" << std::endl;
if (vertices) std::cout << "\tRead " << vertices->count << " total vertices " << std::endl;
const size_t numVerticesBytes = vertices->buffer.size_bytes();
verts.resize(vertices->count);
std::memcpy(verts.data(), vertices->buffer.get(), numVerticesBytes);
}
catch (const std::exception &e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
}
void manual_timer::start() {
t0 = std::chrono::high_resolution_clock::now();
}
void manual_timer::stop() {
timestamp = std::chrono::duration<double>(
std::chrono::high_resolution_clock::now() - t0).count() * 1000.0;
}
const double &manual_timer::get() {
return timestamp;
} | 28.631579 | 99 | 0.580882 | [
"vector"
] |
c78115e430e6d191571ea7114a5e08619713d819 | 540 | cpp | C++ | C++/1431. KidsWithTheGreatesNumberOfCandies.cpp | nizD/LeetCode-Solutions | 7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349 | [
"MIT"
] | 263 | 2020-10-05T18:47:29.000Z | 2022-03-31T19:44:46.000Z | C++/1431. KidsWithTheGreatesNumberOfCandies.cpp | nizD/LeetCode-Solutions | 7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349 | [
"MIT"
] | 1,264 | 2020-10-05T18:13:05.000Z | 2022-03-31T23:16:35.000Z | C++/1431. KidsWithTheGreatesNumberOfCandies.cpp | nizD/LeetCode-Solutions | 7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349 | [
"MIT"
] | 760 | 2020-10-05T18:22:51.000Z | 2022-03-29T06:06:20.000Z | /**
* Solution to Kids With the Greatest Number of Candies in CPP
*
* author: ITES7321
* ref:https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
*/
class Solution {
public:
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
int m = *max_element(candies.begin(),candies.end());
vector<bool> v(candies.size());
for(int i=0;i<candies.size();i++)
{
if(candies[i] + extraCandies >= m)
v[i] = true;
}
return v;
}
}; | 27 | 78 | 0.583333 | [
"vector"
] |
c784521bc1c5c8a34b6707aa3fd9665e76dbc6bc | 9,201 | cpp | C++ | SGL_BRP/src/BRP_Cube.cpp | Jesseblast/SGL | 0ad1302ae024853e322fd1f0ad366059379a5fb0 | [
"Zlib"
] | null | null | null | SGL_BRP/src/BRP_Cube.cpp | Jesseblast/SGL | 0ad1302ae024853e322fd1f0ad366059379a5fb0 | [
"Zlib"
] | null | null | null | SGL_BRP/src/BRP_Cube.cpp | Jesseblast/SGL | 0ad1302ae024853e322fd1f0ad366059379a5fb0 | [
"Zlib"
] | null | null | null |
#include "BRP_Cube.h"
namespace SGL {
/* ***************************************************************************************** */
BRP_Cube::BRP_Cube(
const BRP_Camera& camera,
const BRP_Shader& shader,
const Vector3<float>& size,
const Texture* diffuseMap,
const Texture* specularMap,
const bool setStatic
) {
m_pBRP_Camera = &camera;
m_pBRP_Shader = &shader;
m_pBRP_ShaderUniformManager = new BRP_ShaderUniformManager();
m_IsStatic = setStatic;
m_pDiffuseMap = nullptr;
m_pSpecularMap = nullptr;
m_ObjectColor = COLOR::White;
m_Shininess = 16.0f;
const float halfX = size.x / 2.0f;
const float halfY = size.y / 2.0f;
const float halfZ = size.z / 2.0f;
std::vector<Drawable::BufferDataType> vertex = {
-halfX, -halfY, -halfZ,
halfX, -halfY, -halfZ,
halfX, halfY, -halfZ,
halfX, halfY, -halfZ,
-halfX, halfY, -halfZ,
-halfX, -halfY, -halfZ,
-halfX, -halfY, halfZ,
halfX, -halfY, halfZ,
halfX, halfY, halfZ,
halfX, halfY, halfZ,
-halfX, halfY, halfZ,
-halfX, -halfY, halfZ,
-halfX, halfY, halfZ,
-halfX, halfY, -halfZ,
-halfX, -halfY, -halfZ,
-halfX, -halfY, -halfZ,
-halfX, -halfY, halfZ,
-halfX, halfY, halfZ,
halfX, halfY, halfZ,
halfX, halfY, -halfZ,
halfX, -halfY, -halfZ,
halfX, -halfY, -halfZ,
halfX, -halfY, halfZ,
halfX, halfY, halfZ,
-halfX, -halfY, -halfZ,
halfX, -halfY, -halfZ,
halfX, -halfY, halfZ,
halfX, -halfY, halfZ,
-halfX, -halfY, halfZ,
-halfX, -halfY, -halfZ,
-halfX, halfY, -halfZ,
halfX, halfY, -halfZ,
halfX, halfY, halfZ,
halfX, halfY, halfZ,
-halfX, halfY, halfZ,
-halfX, halfY, -halfZ,
};
std::vector<Drawable::BufferDataType> normals = {
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f
};
std::vector<Drawable::BufferDataType> texCoords = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
1.0f, 1.0f,
0.0f, 1.0f,
0.0f, 0.0f,
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
1.0f, 1.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
};
std::vector<Drawable::IndicesDataType> indices = {
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35
};
m_Drawable.setBufferData(0, 3, std::move(vertex));
m_Drawable.setBufferData(1, 3, std::move(normals));
m_Drawable.setBufferData(2, 2, std::move(texCoords));
m_Drawable.setIndices(std::move(indices));
m_Drawable.setDrawMethod(m_IsStatic ? DrawMethod::Static : DrawMethod::Dynamic);
m_Drawable.setDrawMode(DrawMode::Triangles);
m_Drawable.configure();
// Create placeholder texture if none was provided
if (!diffuseMap) {
m_pDiffuseMap = new Texture(Vector2<std::uint32_t>(1, 1), TextureType::Color, TextureFilter::Point);
const_cast<Texture*>(m_pDiffuseMap)->beginDrawing(true, true, true, SGL::Color(255, 255, 255));
const_cast<Texture*>(m_pDiffuseMap)->endDrawing();
}
else {
m_pDiffuseMap = diffuseMap;
}
// Placeholder for diffuse map
if (!specularMap) {
m_pSpecularMap = new Texture(Vector2<std::uint32_t>(1, 1), TextureType::Color, TextureFilter::Point);
const_cast<Texture*>(m_pSpecularMap)->beginDrawing(true, true, true, SGL::Color(64, 64, 64));
const_cast<Texture*>(m_pSpecularMap)->endDrawing();
}
else {
m_pSpecularMap = specularMap;
}
m_pBRP_Shader->setActive();
const_cast<Texture*>(m_pDiffuseMap)->setTextureUnit(TextureUnit::Texture0);
m_pBRP_Shader->setTextureUnit("material.diffuse", TextureUnit::Texture0);
const_cast<Texture*>(m_pSpecularMap)->setTextureUnit(TextureUnit::Texture1);
m_pBRP_Shader->setTextureUnit("material.specular", TextureUnit::Texture1);
}
/* ***************************************************************************************** */
BRP_Cube::~BRP_Cube(
) noexcept {
if (m_pBRP_ShaderUniformManager) {
delete m_pBRP_ShaderUniformManager;
m_pBRP_ShaderUniformManager = nullptr;
}
if (m_pDiffuseMap) {
m_pDiffuseMap = nullptr; // TODO: potential memory leak
}
if (m_pSpecularMap) {
m_pDiffuseMap = nullptr; // TODO: potential memory leak
}
}
/* ***************************************************************************************** */
auto BRP_Cube::setColor(
const Color& color
) noexcept -> void {
m_ObjectColor = color;
}
/* ***************************************************************************************** */
auto BRP_Cube::getColor(
) const noexcept -> Color {
return m_ObjectColor;
}
/* ***************************************************************************************** */
auto BRP_Cube::setShininess(
const float shininess
) noexcept -> void {
m_Shininess = shininess;
}
/* ***************************************************************************************** */
auto BRP_Cube::getShininess(
) const noexcept -> float {
return m_Shininess;
}
/* ***************************************************************************************** */
auto BRP_Cube::getBRP_ShaderUniformManager(
) const noexcept -> BRP_ShaderUniformManager* {
return m_pBRP_ShaderUniformManager;
}
/* ***************************************************************************************** */
auto BRP_Cube::draw(
) const noexcept -> void {
m_pBRP_Shader->setActive();
m_pBRP_Shader->setMatrix4("matrix.transform", m_pBRP_Camera->getMatrix4() * m_WorldMatrix4);
m_pBRP_Shader->setMatrix4("matrix.world", m_WorldMatrix4);
m_pBRP_Shader->setMatrix4("matrix.inversedWorld", Matrix4::inverse(m_WorldMatrix4));
m_pBRP_Shader->setVector3("material.color", glm::vec3(
m_ObjectColor.getRedf<float>(),
m_ObjectColor.getGreenf<float>(),
m_ObjectColor.getBluef<float>()
));
m_pBRP_Shader->setFloat("material.shininess", m_Shininess);
// TODO: not very convenient to update camera viewPos for every drawable and every frame
// TODO: what if camera could do it itself?
m_pBRP_Shader->setVector3("viewPos", glm::vec3(
m_pBRP_Camera->getPosition().x,
m_pBRP_Camera->getPosition().y,
m_pBRP_Camera->getPosition().z
));
m_pDiffuseMap->use();
m_pSpecularMap->use();
m_pBRP_ShaderUniformManager->activateAll(m_pBRP_Shader);
m_Drawable.draw();
}
} | 30.875839 | 113 | 0.44843 | [
"vector",
"transform"
] |
c784cb2abfad4c61521d2fa541f78c46102784de | 18,596 | cpp | C++ | docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/flow2d3d/src/dd/mapper/mapper_config.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | 3 | 2021-01-06T03:01:18.000Z | 2022-03-21T03:02:55.000Z | docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/flow2d3d/src/dd/mapper/mapper_config.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | docker/water/delft3d/tags/v6686/src/engines_gpl/flow2d3d/packages/flow2d3d/src/dd/mapper/mapper_config.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | //---- GPL ---------------------------------------------------------------------
//
// Copyright (C) Stichting Deltares, 2011-2016.
//
// 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 version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// contact: delft3d.support@deltares.nl
// Stichting Deltares
// P.O. Box 177
// 2600 MH Delft, The Netherlands
//
// All indications and logos of, and references to, "Delft3D" and "Deltares"
// are registered trademarks of Stichting Deltares, and remain the property of
// Stichting Deltares. All rights reserved.
//
//------------------------------------------------------------------------------
// $Id: mapper_config.cpp 878 2011-10-07 12:58:46Z mourits $
// $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/branches/research/Deltares/20110420_OnlineVisualisation/src/engines_gpl/flow2d3d/packages/flow2d3d/src/dd/mapper/mapper_config.cpp $
//------------------------------------------------------------------------------
// Configuration object for Flow2D3D Domain Decomposition
//
// Stef.Hummel@deltares.nl
// Adri.Mourits@deltares.nl
// 1 jun 11
//-------------------------------------------------------------------------------
#include "flow2d3d.h"
#define LOG_CELLS 0
//////////////////////////////////////////////////////////////////////
//
// Parse configuration string
//
int
ParseMapperConfigString (
char * configString, // config string in DD-Bound file
EdgeType edgeType [NR_CNTXTS], // Out: edge types left / right domein
int firstCell [NR_CNTXTS], // Out: first cell left / right domein
int lastCell [NR_CNTXTS], // Out: last cell left / right domein
int normalCell[NR_CNTXTS], // Out: normal cell left / right domein
int refine [NR_CNTXTS], // Out: refinement of contexts
int echoRefinement // In : 1: echo refinement to file
)
{
int iii; // auxiliary integer variable
int retVal = HY_OK; // return value
FILE * refinementFile; // file to pass refinement factor to flow
char * refFileName = "TMP_refinement";
int mStartLeft , nStartLeft , mEndLeft , nEndLeft;
int mStartRight, nStartRight, mEndRight, nEndRight;
char dumNameLeft[200], dumNameRight[200];
int numRead = sscanf(configString, "%s %d %d %d %d %s %d %d %d %d",
dumNameLeft , &mStartLeft , &nStartLeft , &mEndLeft , &nEndLeft,
dumNameRight, &mStartRight, &nStartRight, &mEndRight, &nEndRight );
if (numRead != 10)
throw new Exception (true, "Cannot parse configString \"%s\" (numRead = %d)", configString, numRead);
else
{
if ( mStartLeft == mEndLeft )
{
if ( mStartRight == mStartRight )
{
edgeType[C_0] = Edge_Right;
edgeType[C_1] = Edge_Left;
}
else
{
throw new Exception (true, "Inconstistent Mapper direction configString \"%s\"", configString);
}
}
else if ( nStartLeft == nEndLeft )
{
if ( nStartRight == nStartRight )
{
edgeType[C_0] = Edge_Top;
edgeType[C_1] = Edge_Bottom;
}
else
{
throw new Exception (true, "Inconstistent napper direction configString \"%s\"", configString);
}
}
else
{
throw new Exception (true, "M1/M2 or N1/N2 must be equal in configString \"%s\"", configString);
}
}
//
// Set mapper start/end/normal cell indices
//
switch ( edgeType[C_0] )
{
case Edge_Top:
//
// top->bottom mapper
//
normalCell[C_0] = nStartLeft ;
normalCell[C_1] = nStartRight;
firstCell [C_0] = mStartLeft ;
lastCell [C_0] = mEndLeft ;
firstCell [C_1] = mStartRight;
lastCell [C_1] = mEndRight ;
break;
case Edge_Right:
//
// right->left mapper
//
normalCell[C_0] = mStartLeft ;
normalCell[C_1] = mStartRight;
firstCell [C_0] = nStartLeft ;
lastCell [C_0] = nEndLeft ;
firstCell [C_1] = nStartRight;
lastCell [C_1] = nEndRight ;
break;
default:
throw new Exception (true, "Error: Determined wrong edgeType from configString \"%s\"", configString);
break;
}
// if firstCell>lastCell then switch coordinates of firstCell and lastCell
{
if ( firstCell [C_0] > lastCell [C_0] )
{
iii = firstCell [C_0];
firstCell [C_0] = lastCell [C_0];
lastCell [C_0] = iii;
printf("switch coordinates-1: (%2d,%2d)\n", firstCell[C_0],lastCell[C_0]);
fflush (stdout);
}
if ( firstCell [C_1] > lastCell [C_1] )
{
iii = firstCell [C_1];
firstCell [C_1] = lastCell [C_1];
lastCell [C_1] = iii;
printf("switch coordinates-2: (%2d,%2d)\n", firstCell[C_1],lastCell[C_1]);
fflush (stdout);
}
}
if ( echoRefinement == 1) {
if ((refinementFile = fopen (refFileName, "a")) == NULL) {
throw new Exception (true, "Cannot open refinement file \"%s\" for writing.", refFileName);
}
}
for ( int ctx = 0 ; ctx < NR_CNTXTS ; ctx++ )
{
int oCtx = 1 - ctx;
if ( lastCell[oCtx] == firstCell[oCtx] )
{
throw new Exception (true, "Error in determining refinements, configString\"%s\"", configString);
}
refine[ctx] = B_MAX ( 1, ( lastCell[ ctx] - firstCell[ ctx] ) /
( lastCell[oCtx] - firstCell[oCtx] ) );
if ( echoRefinement == 1 ) {
fprintf(refinementFile, "%d :%s", refine[ctx], configString);
}
}
if ( echoRefinement == 1 ) {
fclose (refinementFile);
}
return retVal;
}
//////////////////////////////////////////////////////////////////////
//
// D3dFlowMapper Configuration functions
//
int D3dFlowMapper::InitAndParseConfigString(
char * configString // config string
)
{
int retVal = HY_OK; // return value
//
// Set Valid defaults
//
// Values for Block Jacobi convergence criterion:
this->EpsMap[Eq_U] = 1.0e-4;
this->EpsMap[Eq_V] = 1.0e-4;
this->EpsMap[Eq_Zeta] = 1.0e-2; // used for concentrations and not for the
// water elevation because of Wang Algorithm
this->MaxIter_Vel = 5;
this->MaxIter_Conc = 5;
this->MaxIter_2DAD = 5;
for ( ctx = 0 ; ctx < NR_CNTXTS ; ctx++ )
{
//
// Valid defaults
//
this->Ref[ctx] = 1;
//
// Defaults indicating "Not Read from config file"
//
this->Edge[ctx] = NR_EDGETYPES;
this->FirstCell[ctx] = YET_TO_INIT;
this->LastCell[ctx] = YET_TO_INIT;
this->NormalCell[ctx]= YET_TO_INIT;
}
retVal = ParseMapperConfigString( configString, this->Edge,
this->FirstCell, this->LastCell,
this->NormalCell, this->Ref, 1);
if ( retVal != HY_OK )
{
throw new Exception (true, "Call to configStringParser failed for configString \"%s\"", configString);
}
//
// TODORE: Check for config errors (see old conf-parser)
//
return retVal;
}
int D3dFlowMapper::CheckConfig()
{
int retVal = HY_OK;
int check[NR_CNTXTS] = { HY_OK, HY_OK };
int checkBoth = HY_OK;
MAPDBG_FUN2("D3dFlowMapper::CheckConfig");
//
// Check configuration information
//
for ( ctx = 0 ; ctx < NR_CNTXTS ; ctx++ )
{
check[ctx] = CheckConfigContext(ctx);
}
checkBoth = CheckConfigBothContexts();
if ( check[C_0] == HY_ERR
|| check[C_1] == HY_ERR
|| checkBoth == HY_ERR )
{
throw new Exception (true, "Errors found in config file %s", this->confFile);
retVal = HY_ERR;
}
return retVal;
}
int D3dFlowMapper::GetStartCell(
int aCtx, // current context
int eq // equation type
)
{
int startCell=YET_TO_INIT; // last map-cell-nr for this aCtx/eq
Vel orient; // orientation indicating Norm.-Vel.
// or Tang.-Vel., or Zeta
orient = GetVelocityOrientation(aCtx, eq);
switch (orient)
{
case Vel_Zeta:
case Vel_Norm:
case Vel_Tang:
startCell = FirstCell[aCtx] + 1;
break;
default:
throw new Exception (true, "Unexpected case (%d) in GetStartCell", orient);
break;
}
#if LOG_CELLS
FLOW2D3D->dd->log->Write (Log::DDMAPPER_MINOR, "StartCell for eq %d: %3d", eq, startCell);
#endif
return startCell;
}
int D3dFlowMapper::GetEndCell(
int aCtx, // current context
int eq // equation type
)
{
int endCell=YET_TO_INIT; // last map-cell-nr for this aCtx/eq
Vel orient; // orientation indicating Norm.-Vel.
// or Tang.-Vel., or Zeta
orient = GetVelocityOrientation(aCtx, eq);
switch (orient)
{
case Vel_Zeta:
case Vel_Norm:
endCell = LastCell[aCtx];
break;
case Vel_Tang:
endCell = LastCell[aCtx] - 1;
break;
default:
throw new Exception (true, "Unexpected case (%d) in GetEndCell", orient);
break;
}
#if LOG_CELLS
FLOW2D3D->dd->log->Write (Log::DDMAPPER_MINOR, "EndCell for eq %d: %3d", eq, endCell);
#endif
return endCell;
}
int D3dFlowMapper::GetNormalCell(
int aCtx, // current context
int eq, // equation type
CtxType type // source or target
)
{
int normCell=YET_TO_INIT; // cell-nr in normal direction
Vel orient; // orientation indicating Norm.-Vel.
// or Tang.-Vel.
MAPDBG_FUN2("D3dFlowMapper::GetNormalCell");
orient = GetVelocityOrientation(aCtx, eq);
if ( orient == Vel_Norm )
{
// set virtual point on Right/Top edge *ON* the interface
if ( Edge[aCtx] == Edge_Left
|| Edge[aCtx] == Edge_Bottom )
{
if ( type == CtxType_Source )
{
normCell = NormalCell[aCtx];
}
else // target
{
normCell = NormalCell[aCtx] - 1;
}
}
else // Right or Top Edge
{
if ( type == CtxType_Source )
{
normCell = NormalCell[aCtx] - 1;
}
else // target
{
normCell = NormalCell[aCtx];
}
}
}
else if ( orient == Vel_Tang || orient == Vel_Zeta )
{
if ( ( ( Edge[aCtx] == Edge_Left
|| Edge[aCtx] == Edge_Bottom )
&& ( type == CtxType_Source ) )
||
( ( Edge[aCtx] == Edge_Right
|| Edge[aCtx] == Edge_Top )
&& ( type == CtxType_Target ) ) )
{
normCell = NormalCell[aCtx] + 1;
}
else
{
normCell = NormalCell[aCtx];
}
}
if ( normCell == YET_TO_INIT )
{
throw new Exception (true, "Invalid NormalCell in GetNormalCell");
}
return normCell;
}
int D3dFlowMapper::CheckConfigContext(
int aCtx // current context
)
{
int retVal = HY_OK;
int domMaxCell; // domains maximum cell for mapper (mMax/nMax)
MAPDBG_FUN2("D3dFlowMapper::CheckConfigContext");
if ( Edge[aCtx] == NR_EDGETYPES )
{
retVal = HY_ERR;
FLOW2D3D->dd->log->Write (Log::WARN, "Edge type not available in config file (ctx %d)", aCtx);
}
if ( ( FirstCell[aCtx] < 1 )
|| ( LastCell[aCtx] < 1 ) )
{
retVal = HY_ERR;
FLOW2D3D->dd->log->Write (Log::WARN, "Couldn't get First or Last cell from config file (ctx %d)", aCtx);
}
if ( Edge[aCtx] == Edge_Bottom
|| Edge[aCtx] == Edge_Top )
{
domMaxCell = C[aCtx]->mMax;
}
else
{
domMaxCell = C[aCtx]->nMax;
}
FLOW2D3D->dd->log->Write (Log::DDMAPPER_MAJOR, "Checking configuration for Context %d", aCtx );
if ( (Edge[aCtx] < 0) || (Edge[aCtx] >= NR_EDGETYPES) )
{
retVal = HY_ERR;
FLOW2D3D->dd->log->Write (Log::WARN, "Couldn't get Edge type from config file (ctx %d)", aCtx);
}
if ( FirstCell[aCtx] >= LastCell[aCtx] )
{
retVal = HY_ERR;
FLOW2D3D->dd->log->Write (Log::WARN, "FirstCell must be < LastCell");
}
if ( NormalCell[aCtx] == YET_TO_INIT )
{
retVal = HY_ERR;
FLOW2D3D->dd->log->Write (Log::WARN, "NormalCell must be Specified");
}
if ( FirstCell[aCtx] < 1 )
{
FLOW2D3D->dd->log->Write (Log::WARN, "First Cell (%d) < 1", FirstCell[aCtx]);
retVal = HY_ERR;
}
if ( LastCell[aCtx] > domMaxCell )
{
FLOW2D3D->dd->log->Write (Log::WARN, "Last Cell (%d) for \"%s\"-\"%s\" exceeds maximum (%d)", LastCell[aCtx],
this->C[aCtx]->mapperIterator->name,
this->C[aCtx]->flowIterator->name,
domMaxCell );
retVal = HY_ERR;
}
return retVal;
}
int D3dFlowMapper::CheckConfigBothContexts(void)
{
int retVal = HY_OK; // return value
MAPDBG_FUN2("D3dFlowMapper::CheckConfigBothContexts");
FLOW2D3D->dd->log->Write (Log::DDMAPPER_MAJOR, "Checking configuration between Contexts");
if ( (Ref[C_0] != 1) && (Ref[C_1] != 1) )
{
FLOW2D3D->dd->log->Write (Log::WARN, "One of the Refinement factors must be 1");
retVal = HY_ERR;
}
if ( ( (Edge[C_0] == Edge_Left) && (Edge[C_1] != Edge_Right ) )
|| ( (Edge[C_0] == Edge_Right) && (Edge[C_1] != Edge_Left ) )
|| ( (Edge[C_0] == Edge_Top) && (Edge[C_1] != Edge_Bottom ) )
|| ( (Edge[C_0] == Edge_Bottom) && (Edge[C_1] != Edge_Top ) )
)
{
FLOW2D3D->dd->log->Write (Log::WARN, "Inconsistent Edges");
retVal = HY_ERR;
}
return retVal;
}
Vel D3dFlowMapper::GetVelocityOrientation(
int aCtx, // current context
int eq // equation type
)
{
Vel retVal;
MAPDBG_FUN2("D3dFlowMapper::GetVelocityOrientation");
//
// Determine the orientation of the equation to be solved
//
// Left or Right: U: tangential
// V: normal
//
// Top or Bottom: U: normal
// V: tangential
//
if ( eq == Eq_Zeta )
{
retVal = Vel_Zeta;
}
else
{
if ( Edge[aCtx] == Edge_Left || Edge[aCtx] == Edge_Right )
{
retVal = ( eq == Eq_U ) ? Vel_Norm : Vel_Tang ;
}
else
{
retVal = ( eq == Eq_U ) ? Vel_Tang : Vel_Norm ;
}
}
return retVal;
}
void D3dFlowMapper::CentreCellOtherContext(
int aCtx, // current context
int curCentre, // current centre cell
int * otherCentre // O: centre cell other context
)
{
MAPDBG_FUN2("D3dFlowMapper::CentreCellOtherContext");
//
// Determine centre cells (zeta direction and M/N direction)
// in other context
//
*otherCentre = Other_MN_Centre( aCtx, curCentre);
}
int D3dFlowMapper::Other_MN_Centre(
int aCtx, // current context
int curCentre // current centre cell
)
{
int oCtx = 1 - aCtx; // other context
int relCell; // relative number of current cell
// in other context
// (i.e. as offset from start cell)
int otherCentre; // centre cell in other context
int shift = 0 ; // should indices be shifted?
// (Yes in case of refinement)
Vel orient; // orientation indicating Norm.-Vel.
// or Tang.-Vel.
MAPDBG_FUN2("D3dFlowMapper::Other_MN_Centre");
// Determine centre cell (M/N-direction) in other context
// If there is a refinement, the cells for Norm.-Vel. or
// for zeta points are shifted with half the refinement
// factor, to take care that the relevant 'neigbor-cells'
// are delivered.
//
orient = GetVelocityOrientation(aCtx, Eq_Zeta);
assert( orient == Vel_Zeta );
shift = 1;
relCell = curCentre - FirstCell[aCtx];
if ( Ref[oCtx] > Ref[aCtx] )
{
//
// Other context is fine one
// Centre Cell in other context is found by multiplication.
// If Norm.-Vel. or Zeta stencil is required,
// shift stencil down with half of the Refinement factor.
//
otherCentre = FirstCell[oCtx] + relCell * Ref[oCtx];
if ( shift )
{
otherCentre -= Ref[oCtx] / 2;
}
}
else if ( Ref[oCtx] < Ref[aCtx] )
{
//
// other context is coarse one
//
// If Norm.-Vel. or Zeta stencil is required,
// shift incoming centre cell with half of the Refinement factor.
// Centre Cell in other context is found by devision.
//
if ( shift )
{
relCell -= Ref[aCtx] / 2 ;
}
otherCentre = FirstCell[oCtx] + relCell / Ref[aCtx];
}
else
{
//
// One to one
// Centre Cell in current context is equivelent to cell in
// other context
//
otherCentre = FirstCell[oCtx] + relCell;
}
return otherCentre;
}
| 28.434251 | 187 | 0.523769 | [
"object",
"3d"
] |
c7901634f0edafcd2b3437559d99bf5cedb2d270 | 6,680 | cpp | C++ | Lab03/code/main.cpp | jz1371/COURSE_NYU_Operating-System | e79424b5e054c94cc9d65d54c7b815f01e157061 | [
"MIT"
] | null | null | null | Lab03/code/main.cpp | jz1371/COURSE_NYU_Operating-System | e79424b5e054c94cc9d65d54c7b815f01e157061 | [
"MIT"
] | null | null | null | Lab03/code/main.cpp | jz1371/COURSE_NYU_Operating-System | e79424b5e054c94cc9d65d54c7b815f01e157061 | [
"MIT"
] | 7 | 2019-02-18T15:11:38.000Z | 2021-11-02T17:26:51.000Z | /*
* File: a.cpp
* ------------------
* By : Jingxin Zhu
* Date : 04/2014
* Usage:
* 1. to compile,
g++ -o mmu a.cpp FaultHandler.cpp HandlerFIFO.cpp HandlerSC.cpp
HandlerClock.cpp HandlerRandom.cpp HandlerLRU.cpp HandlerNRU.cpp
HandlerAging.cpp
Or type 'make' to take advantage of the makefile
2. to run,
In last step, 'mmu' file will be generated. Then please type,
./mmu -af -f32 in1K4 rfile
This will call FIFO algorithm, set size of physical frame to 32,
take in1K4 and rfile as input files.
3. to test,
./test2.sh will generate various output files for testing.
*
* ------------------
*/
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include "PTE.h"
#include "FaultHandler.h"
#include "HandlerFIFO.h"
#include "HandlerSC.h"
#include "HandlerClock.h"
#include "HandlerRandom.h"
#include "HandlerNRU.h"
#include "HandlerLRU.h"
#include "HandlerAging.h"
using namespace std;
struct INSTRUCTION {
int type;
int page;
} instruction;
/* Private Functions */
void readInstructionFile(string filename);
void readRandomFile(string randfile);
void initSystem(string name, int size, string rand);
/* Private Instances */
vector<INSTRUCTION> instrList;
vector<int> randVals;
FaultHandler* sys;
int main(int argc, char *argv[]) {
/* ---------------------- */
/* Part I: Initialization */
/* ---------------------- */
int O = 0; // 1 for printing out instructions, 0 otherwise.
int P = 0; // 1 for printing out P, 0 otherwise.
int F = 0; // 1 for printing out F, 0 otherwise.
int S = 0; // 1 for printing out S, 0 otherwise.
string algo = "l"; // "l" by default
int PHYSICAL_SPACE_SIZE = 32; // 32 by default
// Step 1: parse command line
vector<string> paras;
for (int i=0; i< argc; i++) {
paras.push_back(string(argv[i]));
}
vector<string>::iterator it;
for (int i=0; i<argc; i++) {
if (paras[i].find("-a") != string::npos){
algo = paras[i].substr(2);
}
if (paras[i].find("-f") != string::npos){
PHYSICAL_SPACE_SIZE = atoi(paras[i].substr(2).c_str());
}
if (paras[i].find("-o") != string::npos) {
string s = paras[i].substr(2);
if (s.find("O") != string::npos)
O = 1;
if (s.find("P") != string::npos)
P = 1;
if (s.find("F") != string::npos)
F = 1;
if (s.find("S") != string::npos)
S = 1;
}
}
string filename = paras[paras.size()-2];
string randfile = paras.back();
// Step 2: read in instruction file and
// intialize system.
readInstructionFile(filename);
initSystem(algo, PHYSICAL_SPACE_SIZE, randfile);
long long unmapCt = 0;
long long mapCt = 0;
long long inCt = 0;
long long outCt = 0;
long long zeroCt = 0;
unsigned long long cost = 0;
bool OO = false;
sys->initialize();
/* --------------------- */
/* Part II: SIMULATION */
/* --------------------- */
// Read in instruction file
unsigned long long counter = 0;
unsigned long long instruSize = instrList.size();
int type;
int page;
int oldPage;
int newFrame;
while ( counter < instruSize ) {
// Step 1: get instruction
instruction = instrList[counter];
type = instrList[counter].type;
page = instrList[counter].page;
if ( O == 1) {
//cout << "==> inst: " << type << " " << page << endl;
printf("==> inst: %d %d\n", type, page);
}
// Step 2: if the page is in physical frame, upate mapping, goes to next turn
// otherwise, deal with this page.
if ( !sys->isPresent(page) ) {
/* If page is not present, check frame table.
* If frame table has available frame, get a free one.
* Otherwise, replacement algorithm will select an old
* page to remove, then make room for the coming new page.
*/
sys->setModified(type, page);
if ( sys->hasFree() ){
newFrame = sys->getFreeFrame();
} else {
oldPage = sys->getOldPage();
newFrame = sys->getFreshFrame();
if ( O == 1) {
printf("%llu: UNMAP %3d %3d\n", counter, oldPage, newFrame );
}
sys->unmap(oldPage);
unmapCt++;
if ( sys->isDirty(oldPage)) {
if ( O == 1) {
printf("%llu: OUT%4d %3d\n", counter, oldPage, newFrame);
}
outCt++;
}
sys->resetModified(oldPage);
}
if ( sys->hasPagedout(page) ) {
if ( O == 1) {
printf("%llu: IN %6d %3d\n", counter,page, newFrame);
}
inCt++;
} else {
if ( O == 1) {
printf("%llu: ZERO %8d\n", counter, newFrame);
}
zeroCt++;
}
if ( O == 1) {
printf("%llu: MAP%6d%4d\n", counter, page, newFrame);
}
sys->setMap(newFrame, page);
mapCt++;
} else {
sys->updateMap(type, page);
}
if (OO == true) {
sys->printPageTable();
sys->printFrameTable();
sys->printSequence();
}
counter++;
}
if (P==1) { sys->printPageTable();}
if (F==1) {
sys->printFrameTable();
printf("\n");
}
if (S==1) {
cost = (unmapCt+mapCt) * 400 + (inCt+outCt) * 3000 + zeroCt * 150 + instruSize;
printf("SUM %llu U=%llu M=%llu I=%llu O=%llu Z=%llu ===> %llu\n",
instruSize, unmapCt, mapCt, inCt, outCt, zeroCt, cost);
}
return 0;
}
/* Private Functions */
/*
* Line starts with # is comment and should be ignored.
* For uncommented lines, it has two integers,
* the first is R/W, 0 for READ and 1 for WRITE;
* the second is virtual page index.
*/
void readInstructionFile(string filename) {
/*pte.present = 0;*/
/*pte.pagedout = 0;*/
int type, index;
ifstream input;
input.open(filename.c_str());
string line;
while (getline(input, line)) {
if (line[0] == '#') continue;
istringstream tokens(line);
tokens >> type >> index;
instruction.type = type;
instruction.page= index;
instrList.push_back(instruction);
}
input.close();
}
void readRandomFile(string randfile){
int scale;
int number;
string line;
ifstream input;
input.open(randfile.c_str());
getline(input, line);
istringstream tokens(line);
tokens >> scale;
while(getline(input, line)){
istringstream tokens(line);
tokens >> number;
randVals.push_back(number);
}
input.close();
}
void initSystem(string name, int size, string rand){
if (name == "a")
sys = new HandlerAging(size,1);
if (name == "A")
sys = new HandlerAging(size,2);
if (name == "l")
sys = new HandlerLRU(size);
if (name == "N") {
readRandomFile(rand);
sys = new HandlerNRU(size, randVals);
}
if (name == "r") {
readRandomFile(rand);
sys = new HandlerRandom(size, randVals);
}
if (name == "f")
sys = new HandlerFIFO(size);
if (name == "s")
sys = new HandlerSC(size);
if (name == "c")
sys = new HandlerClock(size, 1);
if (name == "C")
sys = new HandlerClock(size, 2);
}
| 24.832714 | 81 | 0.605689 | [
"vector",
"3d"
] |
c798f69442873c9abfae31d083e9db31d940e83d | 5,865 | cpp | C++ | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView1/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 834 | 2017-06-24T10:40:36.000Z | 2022-03-31T19:48:51.000Z | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView1/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 7,042 | 2017-06-23T22:34:47.000Z | 2022-03-31T23:05:23.000Z | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView1/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 1,640 | 2017-06-23T22:31:39.000Z | 2022-03-31T02:45:37.000Z |
// The following Snippet code example demonstrates using the:
// ListView.MultiSelect, ListView.SelectedItems,
// ListView.SelectIndices, SelectedIndexCollection,
// SelectedListViewItemCollection ListView.SelectedIndexChanged event,
// and ListView.HeaderStyle members and the SelectedIndexCollection and
// SelectedListViewItemCollection classes.
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System::Windows::Forms;
using namespace System::Drawing;
using namespace System;
public ref class Form1: public System::Windows::Forms::Form
{
public:
Form1()
: Form()
{
InitializeComponent();
InitializeListView();
HookupEvents();
}
internal:
System::Windows::Forms::ListView^ ListView1;
System::Windows::Forms::TextBox^ TextBox1;
System::Windows::Forms::Label ^ Label1;
private:
void InitializeComponent()
{
this->TextBox1 = gcnew System::Windows::Forms::TextBox;
this->Label1 = gcnew System::Windows::Forms::Label;
this->SuspendLayout();
this->TextBox1->Location = System::Drawing::Point( 88, 168 );
this->TextBox1->Name = "TextBox1";
this->TextBox1->Size = System::Drawing::Size( 120, 20 );
this->TextBox1->TabIndex = 1;
this->TextBox1->Text = "";
this->Label1->Location = System::Drawing::Point( 32, 168 );
this->Label1->Name = "Label1";
this->Label1->Size = System::Drawing::Size( 48, 23 );
this->Label1->TabIndex = 2;
this->Label1->Text = "Total: $";
this->ClientSize = System::Drawing::Size( 292, 266 );
this->Controls->Add( this->Label1 );
this->Controls->Add( this->TextBox1 );
this->Name = "Form1";
this->Text = "Breakfast Menu";
this->ResumeLayout( false );
}
//<snippet1>
// This method adds two columns to the ListView, setting the Text
// and TextAlign, and Width properties of each ColumnHeader. The
// HeaderStyle property is set to NonClickable since the ColumnClick
// event is not handled. Finally the method adds ListViewItems and
// SubItems to each column.
void InitializeListView()
{
this->ListView1 = gcnew System::Windows::Forms::ListView;
this->ListView1->BackColor = System::Drawing::SystemColors::Control;
this->ListView1->Dock = System::Windows::Forms::DockStyle::Top;
this->ListView1->Location = System::Drawing::Point( 0, 0 );
this->ListView1->Name = "ListView1";
this->ListView1->Size = System::Drawing::Size( 292, 130 );
this->ListView1->TabIndex = 0;
this->ListView1->View = System::Windows::Forms::View::Details;
this->ListView1->MultiSelect = true;
this->ListView1->HideSelection = false;
this->ListView1->HeaderStyle = ColumnHeaderStyle::Nonclickable;
ColumnHeader^ columnHeader1 = gcnew ColumnHeader;
columnHeader1->Text = "Breakfast Item";
columnHeader1->TextAlign = HorizontalAlignment::Left;
columnHeader1->Width = 146;
ColumnHeader^ columnHeader2 = gcnew ColumnHeader;
columnHeader2->Text = "Price Each";
columnHeader2->TextAlign = HorizontalAlignment::Center;
columnHeader2->Width = 142;
this->ListView1->Columns->Add( columnHeader1 );
this->ListView1->Columns->Add( columnHeader2 );
array<String^>^foodList = {"Juice","Coffee","Cereal & Milk","Fruit Plate","Toast & Jelly","Bagel & Cream Cheese"};
array<String^>^foodPrice = {"1.09","1.09","2.19","2.49","1.49","1.49"};
for ( int count = 0; count < foodList->Length; count++ )
{
ListViewItem^ listItem = gcnew ListViewItem( foodList[ count ] );
listItem->SubItems->Add( foodPrice[ count ] );
ListView1->Items->Add( listItem );
}
this->Controls->Add( ListView1 );
}
//</snippet1>
void HookupEvents()
{
this->ListView1->SelectedIndexChanged += gcnew EventHandler( this, &Form1::ListView1_SelectedIndexChanged_UsingItems );
this->ListView1->SelectedIndexChanged += gcnew EventHandler( this, &Form1::ListView1_SelectedIndexChanged_UsingIndices );
}
// You can access the selected items directly with the SelectedItems
// property or you can access them through the items' indices,
// using the SelectedIndices property. The following methods show
// the two approaches.
//<snippet2>
// Uses the SelectedItems property to retrieve and tally the price
// of the selected menu items.
void ListView1_SelectedIndexChanged_UsingItems( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
ListView::SelectedListViewItemCollection^ breakfast = this->ListView1->SelectedItems;
double price = 0.0;
System::Collections::IEnumerator^ myEnum = breakfast->GetEnumerator();
while ( myEnum->MoveNext() )
{
ListViewItem^ item = safe_cast<ListViewItem^>(myEnum->Current);
price += Double::Parse( item->SubItems[ 1 ]->Text );
}
// Output the price to TextBox1.
TextBox1->Text = price.ToString();
}
//</snippet2>
//<snippet3>
// Uses the SelectedIndices property to retrieve and tally the
// price of the selected menu items.
void ListView1_SelectedIndexChanged_UsingIndices( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
ListView::SelectedIndexCollection^ indexes = this->ListView1->SelectedIndices;
double price = 0.0;
System::Collections::IEnumerator^ myEnum1 = indexes->GetEnumerator();
while ( myEnum1->MoveNext() )
{
int index = safe_cast<int>(myEnum1->Current);
price += Double::Parse( this->ListView1->Items[ index ]->SubItems[ 1 ]->Text );
}
// Output the price to TextBox1.
TextBox1->Text = price.ToString();
}
//</snippet3>
};
[System::STAThreadAttribute]
int main()
{
Application::Run( gcnew Form1 );
}
| 38.084416 | 127 | 0.663427 | [
"object"
] |
c7aa6d21adb785240d197ae96afc5384786ed677 | 634 | hpp | C++ | median-finder/median_finder.hpp | lmdamato/median-finder | 82eb239db34e627e78e478c7e84b882840f025f1 | [
"MIT"
] | null | null | null | median-finder/median_finder.hpp | lmdamato/median-finder | 82eb239db34e627e78e478c7e84b882840f025f1 | [
"MIT"
] | null | null | null | median-finder/median_finder.hpp | lmdamato/median-finder | 82eb239db34e627e78e478c7e84b882840f025f1 | [
"MIT"
] | null | null | null | //
// median_finder.hpp
// median-finder
//
// Copyright © 2016 Luigi Damato. All rights reserved.
//
#ifndef median_finder_hpp
#define median_finder_hpp
#include <queue>
#include <vector>
#include <functional>
template<class T>
class median_finder {
private:
std::priority_queue<T, std::vector<T>, std::less<T>> _left;
std::priority_queue<T, std::vector<T>, std::greater<T>> _right;
void _push(const T& elem);
bool _is_balanced();
void _balance();
void _debug();
public:
median_finder();
void add(const T& elem);
double get();
size_t size();
};
#endif /* median_finder_hpp */
| 18.114286 | 67 | 0.656151 | [
"vector"
] |
c7c68c6bc0269087c5e6fce2f9d938d30249d9d9 | 13,440 | cpp | C++ | code/editors/xrECoreLite/EditMesh.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/editors/xrECoreLite/EditMesh.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/editors/xrECoreLite/EditMesh.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2019-10-20T19:35:34.000Z | 2022-02-28T01:42:10.000Z | //----------------------------------------------------
// file: StaticMesh.cpp
//----------------------------------------------------
#include "xrCore\xrCore.h"
#include "files_list.hpp"
#pragma hdrstop
#include "EditMesh.h"
#include "EditObject.h"
#include "../../utils/common/itterate_adjacents.h"
#include "itterate_adjacents_dynamic.h"
#ifdef _EDITOR
# include "UI_ToolsCustom.h"
#endif
CEditableMesh::~CEditableMesh()
{
Clear();
#ifdef _EDITOR
R_ASSERT2(0 == m_RenderBuffers, "Render buffer still referenced.");
#endif
}
void CEditableMesh::Construct()
{
m_Box.set(0, 0, 0, 0, 0, 0);
m_Flags.assign(flVisible);
m_Name = "";
m_CFModel = 0;
m_Vertices = 0;
m_SmoothGroups = 0;
m_Adjs = 0;
m_Faces = 0;
m_FaceNormals = 0;
m_VertexNormals = 0;
m_SVertices = 0;
m_SVertInfl = 0;
#ifdef _EDITOR
m_RenderBuffers = 0;
#endif
m_FNormalsRefs = 0;
m_VNormalsRefs = 0;
m_AdjsRefs = 0;
m_SVertRefs = 0;
}
void CEditableMesh::Clear()
{
#ifdef _EDITOR
UnloadRenderBuffers();
#endif
UnloadAdjacency();
UnloadCForm();
UnloadFNormals();
UnloadVNormals();
UnloadSVertices();
VERIFY(m_FNormalsRefs == 0 && m_VNormalsRefs == 0 && m_AdjsRefs == 0 && m_SVertRefs == 0);
xr_free(m_Vertices);
xr_free(m_Faces);
for (auto vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); ++vm_it)
xr_delete(*vm_it);
m_VMaps.clear();
m_SurfFaces.clear();
for (auto ref_it = m_VMRefs.begin(); ref_it != m_VMRefs.end(); ++ref_it)
xr_free(ref_it->pts);
m_VMRefs.clear();
}
#include "..\XTools\ETools.h"
void CEditableMesh::UnloadCForm()
{
ETOOLS::destroy_model(m_CFModel);
}
void CEditableMesh::UnloadFNormals(bool force)
{
--m_FNormalsRefs;
if (force || m_FNormalsRefs <= 0)
{
xr_free(m_FaceNormals);
m_FNormalsRefs = 0;
}
}
void CEditableMesh::UnloadVNormals(bool force)
{
--m_VNormalsRefs;
if (force || m_VNormalsRefs <= 0)
{
xr_free(m_VertexNormals);
m_VNormalsRefs = 0;
}
}
void CEditableMesh::UnloadSVertices(bool force)
{
--m_SVertRefs;
if (force || m_SVertRefs <= 0)
{
xr_free(m_SVertices);
m_SVertRefs = 0;
}
}
void CEditableMesh::UnloadAdjacency(bool force)
{
--m_AdjsRefs;
if (force || m_AdjsRefs <= 0)
{
xr_delete(m_Adjs);
m_AdjsRefs = 0;
}
}
void CEditableMesh::RecomputeBBox()
{
if (0 == m_VertCount)
{
m_Box.set(0, 0, 0, 0, 0, 0);
return;
}
m_Box.set(m_Vertices[0], m_Vertices[0]);
for (u32 k = 1; k < m_VertCount; ++k)
m_Box.modify(m_Vertices[k]);
}
void CEditableMesh::GenerateFNormals()
{
++m_FNormalsRefs;
if (m_FaceNormals)
return;
m_FaceNormals = xr_alloc<Fvector>(m_FaceCount);
// face normals
for (u32 k = 0; k < m_FaceCount; ++k)
m_FaceNormals[k].mknormal(m_Vertices[m_Faces[k].pv[0].pindex],
m_Vertices[m_Faces[k].pv[1].pindex],
m_Vertices[m_Faces[k].pv[2].pindex]);
}
BOOL CEditableMesh::m_bDraftMeshMode = 0;
void CEditableMesh::GenerateVNormals(const Fmatrix* parent_xform)
{
++m_VNormalsRefs;
if (m_VertexNormals)
return;
m_VertexNormals = xr_alloc<Fvector>(m_FaceCount * 3);
// gen req
GenerateFNormals();
GenerateAdjacency();
for (u32 f_i = 0; f_i < m_FaceCount; ++f_i)
{
for (int k = 0; k < 3; ++k)
{
Fvector& N = m_VertexNormals[f_i * 3 + k];
IntVec& a_lst = (*m_Adjs)[m_Faces[f_i].pv[k].pindex];
auto face_adj_it = std::find(a_lst.begin(), a_lst.end(), f_i);
VERIFY(face_adj_it != a_lst.end());
//
N.set(m_FaceNormals[a_lst.front()]);
if (m_bDraftMeshMode)
continue;
typedef itterate_adjacents< itterate_adjacents_params_dynamic<st_FaceVert> > iterate_adj;
iterate_adj::recurse_tri_params p(N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount);
iterate_adj::RecurseTri(face_adj_it - a_lst.begin(), p);
float len = N.magnitude();
if (len > EPS_S)
N.div(len);
else
{
//. Msg ("!Invalid smooth group found (Maya type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex]));
#ifdef _EDITOR
if (parent_xform)
{
Fvector p0;
parent_xform->transform_tiny(p0, m_Vertices[m_Faces[f_i].pv[k].pindex]);
Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL");
}
#endif
N.set(m_FaceNormals[a_lst.front()]);
}
}
}
UnloadFNormals();
UnloadAdjacency();
}
/*
void CEditableMesh::GenerateVNormals(const Fmatrix* parent_xform)
{
m_VNormalsRefs++;
if (m_VertexNormals) return;
m_VertexNormals = xr_alloc<Fvector>(m_FaceCount*3);
// gen req
GenerateFNormals ();
GenerateAdjacency ();
// vertex normals
if (m_Flags.is(flSGMask))
{
for (u32 f_i=0; f_i<m_FaceCount; f_i++ )
{
u32 sg = m_SmoothGroups[f_i];
Fvector& FN = m_FaceNormals[f_i];
for (int k=0; k<3; k++)
{
Fvector& N = m_VertexNormals[f_i*3+k];
IntVec& a_lst=(*m_Adjs)[m_Faces[f_i].pv[k].pindex];
//
typedef itterate_adjacents< itterate_adjacents_params_dynamic<st_FaceVert> > iterate_adj ;
iterate_adj::recurse_tri_params p( N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount );
iterate_adj::RecurseTri( 0, p );
//
if (sg)
{
N.set (0,0,0);
VERIFY(a_lst.size());
for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++)
if (sg&m_SmoothGroups[*i_it])
N.add (m_FaceNormals[*i_it]);
float len = N.magnitude();
if (len>EPS_S)
{
N.div (len);
}else
{
//. Msg ("!Invalid smooth group found (MAX type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex]));
#ifdef _EDITOR
Fvector p0;
p0 = m_Vertices[m_Faces[f_i].pv[k].pindex];
Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL");
#endif
N.set (m_FaceNormals[a_lst.front()]);
}
}else
{
N.set (FN);
}
}
}
}else{
for (u32 f_i=0; f_i<m_FaceCount; f_i++ )
{
u32 sg = m_SmoothGroups[f_i];
Fvector& FN = m_FaceNormals[f_i];
for (int k=0; k<3; k++)
{
Fvector& N = m_VertexNormals[f_i*3+k];
if (sg!=-1)
{
N.set (0,0,0);
IntVec& a_lst=(*m_Adjs)[m_Faces[f_i].pv[k].pindex];
//
typedef itterate_adjacents< itterate_adjacents_params_dynamic<st_FaceVert> > iterate_adj ;
iterate_adj::recurse_tri_params p( N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount );
iterate_adj::RecurseTri( 0, p );
//
VERIFY (a_lst.size());
for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++)
{
if (sg != m_SmoothGroups[*i_it])
continue;
N.add (m_FaceNormals[*i_it]);
}
float len = N.magnitude();
if (len>EPS_S)
{
N.div (len);
}else
{
//. Msg ("!Invalid smooth group found (Maya type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex]));
#ifdef _EDITOR
if(parent_xform)
{
Fvector p0;
parent_xform->transform_tiny(p0, m_Vertices[m_Faces[f_i].pv[k].pindex]);
Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL");
}
#endif
N.set (m_FaceNormals[a_lst.front()]);
}
}
else
{
N.set (FN);
//IntVec& a_lst=(*m_Adjs)[m_Faces[f_i].pv[k].pindex];
//VERIFY(a_lst.size());
//for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++)
// N.add (m_FNormals[*i_it]);
// float len = N.magnitude();
// if (len>EPS_S){
// N.div (len);
// }else{
// Msg ("!Invalid smooth group found (No smooth). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Verts[m_Faces[f_i].pv[k].pindex]));
// N.set (m_FNormals[a_lst.front()]);
// }
}
}
}
}
UnloadFNormals ();
UnloadAdjacency ();
}
*/
void CEditableMesh::GenerateSVertices(u32 influence)
{
if (!m_Parent->IsSkeleton())
return;
++m_SVertRefs;
if (m_SVertInfl != influence)
UnloadSVertices(true);
if (m_SVertices)
return;
m_SVertices = xr_alloc<st_SVert>(m_FaceCount * 3);
m_SVertInfl = influence;
// CSMotion* active_motion=m_Parent->ResetSAnimation();
m_Parent->CalculateAnimation(0);
// generate normals
GenerateFNormals();
GenerateVNormals(0);
for (u32 f_id = 0; f_id < m_FaceCount; ++f_id)
{
st_Face& F = m_Faces[f_id];
for (int k = 0; k < 3; ++k)
{
st_SVert& SV = m_SVertices[f_id * 3 + k];
const Fvector& N = m_VertexNormals[f_id * 3 + k];
const st_FaceVert& fv = F.pv[k];
const Fvector& P = m_Vertices[fv.pindex];
const st_VMapPtLst& vmpt_lst = m_VMRefs[fv.vmref];
st_VertexWB wb;
for (u8 vmpt_id = 0; vmpt_id != vmpt_lst.count; ++vmpt_id)
{
const st_VMap& VM = *m_VMaps[vmpt_lst.pts[vmpt_id].vmap_index];
if (VM.type == vmtWeight)
{
wb.push_back(st_WB(m_Parent->GetBoneIndexByWMap(VM.name.c_str()), VM.getW(vmpt_lst.pts[vmpt_id].index)));
R_ASSERT3(wb.back().bone != BI_NONE, "Can't find bone assigned to weight map %s", *VM.name);
}
else if (VM.type == vmtUV)
SV.uv.set(VM.getUV(vmpt_lst.pts[vmpt_id].index));
}
VERIFY(m_SVertInfl <= 4);
wb.prepare_weights(m_SVertInfl);
SV.offs = P;
SV.norm = N;
SV.bones.resize(wb.size());
for (u8 k = 0; k < (u8)SV.bones.size(); ++k)
{
SV.bones[k].id = wb[k].bone;
SV.bones[k].w = wb[k].weight;
}
}
}
// restore active motion
UnloadFNormals();
UnloadVNormals();
}
void CEditableMesh::GenerateAdjacency()
{
++m_AdjsRefs;
if (m_Adjs)
return;
m_Adjs = xr_new<AdjVec>();
VERIFY(m_Faces);
m_Adjs->resize(m_VertCount);
//. Log (".. Update adjacency");
for (u32 f_id = 0; f_id < m_FaceCount; ++f_id)
for (int k = 0; k < 3; k++) (*m_Adjs)[m_Faces[f_id].pv[k].pindex].push_back(f_id);
}
CSurface* CEditableMesh::GetSurfaceByFaceID(u32 fid)
{
R_ASSERT(fid < m_FaceCount);
for (auto sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); ++sp_it)
{
IntVec& face_lst = sp_it->second;
auto f_it = std::lower_bound(face_lst.begin(), face_lst.end(), (int)fid);
if ((f_it != face_lst.end()) && (*f_it == (int)fid))
return sp_it->first;
//. if (std::find(face_lst.begin(),face_lst.end(),fid)!=face_lst.end()) return sp_it->first;
}
return 0;
}
void CEditableMesh::GetFaceTC(u32 fid, const Fvector2* tc[3])
{
R_ASSERT(fid < m_FaceCount);
st_Face& F = m_Faces[fid];
for (int k = 0; k < 3; ++k)
{
st_VMapPt& vmr = m_VMRefs[F.pv[k].vmref].pts[0];
tc[k] = &(m_VMaps[vmr.vmap_index]->getUV(vmr.index));
}
}
void CEditableMesh::GetFacePT(u32 fid, const Fvector* pt[3])
{
R_ASSERT(fid < m_FaceCount);
st_Face& F = m_Faces[fid];
for (int k = 0; k < 3; ++k)
pt[k] = &m_Vertices[F.pv[k].pindex];
}
int CEditableMesh::GetFaceCount(bool bMatch2Sided) {
int f_cnt = 0;
for (auto sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); ++sp_it)
{
if (bMatch2Sided)
{
if (sp_it->first->m_Flags.is(CSurface::sf2Sided))
f_cnt += sp_it->second.size() * 2;
else
f_cnt += sp_it->second.size();
}
else
f_cnt += sp_it->second.size();
}
return f_cnt;
}
float CEditableMesh::CalculateSurfaceArea(CSurface* surf, bool bMatch2Sided)
{
auto sp_it = m_SurfFaces.find(surf);
if (sp_it == m_SurfFaces.end())
return 0;
float area = 0;
IntVec& pol_lst = sp_it->second;
for (int k = 0; k<int(pol_lst.size()); ++k)
{
st_Face& F = m_Faces[pol_lst[k]];
Fvector c, e01, e02;
e01.sub(m_Vertices[F.pv[1].pindex], m_Vertices[F.pv[0].pindex]);
e02.sub(m_Vertices[F.pv[2].pindex], m_Vertices[F.pv[0].pindex]);
area += c.crossproduct(e01, e02).magnitude() / 2.f;
}
if (bMatch2Sided&&sp_it->first->m_Flags.is(CSurface::sf2Sided))
area *= 2;
return area;
}
float CEditableMesh::CalculateSurfacePixelArea(CSurface* surf, bool bMatch2Sided)
{
auto sp_it = m_SurfFaces.find(surf);
if (sp_it == m_SurfFaces.end())
return 0;
float area = 0;
IntVec& pol_lst = sp_it->second;
for (int k = 0; k<int(pol_lst.size()); ++k)
{
//st_Face& F = m_Faces[pol_lst[k]];
Fvector c, e01, e02;
const Fvector2* tc[3];
GetFaceTC(pol_lst[k], tc);
e01.sub(Fvector().set(tc[1]->x, tc[1]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0));
e02.sub(Fvector().set(tc[2]->x, tc[2]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0));
area += c.crossproduct(e01, e02).magnitude() / 2.f;
}
if (bMatch2Sided&&sp_it->first->m_Flags.is(CSurface::sf2Sided))
area *= 2;
return area;
}
int CEditableMesh::GetSurfFaceCount(CSurface* surf, bool bMatch2Sided)
{
auto sp_it = m_SurfFaces.find(surf);
if (sp_it == m_SurfFaces.end())
return 0;
int f_cnt = sp_it->second.size();
if (bMatch2Sided&&sp_it->first->m_Flags.is(CSurface::sf2Sided))
f_cnt *= 2;
return f_cnt;
}
void CEditableMesh::DumpAdjacency()
{
Log("Adjacency dump.");
Log("------------------------------------------------------------------------");
}
//----------------------------------------------------------------------------
int CEditableMesh::FindVMapByName(VMapVec& vmaps, const char* name, u8 t, bool polymap)
{
for (auto vm_it = vmaps.begin(); vm_it != vmaps.end(); ++vm_it)
if (((*vm_it)->type == t) && (stricmp((*vm_it)->name.c_str(), name) == 0) && (polymap == (*vm_it)->polymap))
return vm_it - vmaps.begin();
return -1;
}
//----------------------------------------------------------------------------
bool CEditableMesh::Validate()
{
return true;
}
//---------------------------------------------------------------------------- | 24.303797 | 183 | 0.615699 | [
"render",
"object"
] |
c7ca956c21340e832ff37fe5aa47090b830f6eaa | 19,591 | cpp | C++ | Calib_2d/main.cpp | Hxxawl499295/Drareni-Calibration-Algorithm-for-Line-Scan-Camera | cf2e25e8147e0e6350d8f819dbe6e5ad717c6ff0 | [
"MIT"
] | 2 | 2021-08-24T08:39:16.000Z | 2022-01-11T12:46:55.000Z | Calib_2d/main.cpp | Hxxawl499295/Drareni-Calibration-Algorithm-for-Line-Scan-Camera | cf2e25e8147e0e6350d8f819dbe6e5ad717c6ff0 | [
"MIT"
] | 1 | 2021-12-07T07:26:15.000Z | 2021-12-07T07:26:15.000Z | Calib_2d/main.cpp | Hxxawl499295/Drareni-Calibration-Algorithm-for-Line-Scan-Camera | cf2e25e8147e0e6350d8f819dbe6e5ad717c6ff0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/aruco.hpp> //用opencv自带的aruco模块
#include <opencv2/aruco/dictionary.hpp>
#include <string>
#include <vector>
#include <regex>
#include "calibration.h"
using namespace std;
using namespace cv;
int main()
{
string imgFolder = "./img/"; //图片存放文件夹的路径
int view_num = 4; //关于同一标定板拍了多少张不同角度的照片(view)
Size corner_point_size = Size(11,8); //标定板上每行和每列各包含多少个角点
Size actual_grid_size = Size(60, 60); //在3D真实世界中,每个棋盘格子的实际(宽x高),单位:mm
//********************task 1. 探测角点 + 相机标定(求内参)+ 位姿估计********************
cout<<"*****************Task 1: 角点检测+相机标定+位姿估计*****************"<<endl;
//1.手动添加view
vector<string> imgList; //所有待求位姿的view(手动添加)
// imgList.push_back(imgFolder + "chessboard_org2.png");
// for(int i=0; i< view_num ; i++)
// {
// string imgname = imgFolder+"chessboard"+to_string(i+1)+".png";
// imgList.push_back(imgname);
// }
string testImgFile = "lineScanImage2"; //test3.3要用的测试图像的名字(**********************)
imgList.push_back(imgFolder+testImgFile+".jpg");
//手动添加view完毕
Mat cameraMatrix = Mat(3, 3, CV_64FC1, Scalar::all(0));
Mat distCoeffs = Mat(1, 5, CV_64FC1, Scalar::all(0));
//************task 2.获取(其实就是自己指定)各个角点在3d世界坐标系中的位置(以第一个角点为原点,宽为x轴正向,整个标定板为xoy平面建系)
vector<vector<Point3f>> objectPoints_seq; //用于保存 各个view中 各个角点 在3D世界坐标系中的坐标
int viewNum = imgList.size();
for(int i=0; i<viewNum; i++) //每轮循环代表一个view
{
vector<Point3f> object_points;
for(int j=0; j<corner_point_size.height; j++)
{
for(int k=0; k<corner_point_size.width; k++)
{
Point3f obj_point;
obj_point.x = (double)k*actual_grid_size.width;
obj_point.y = (double)j*actual_grid_size.height;
obj_point.z = 0.0;
object_points.push_back(obj_point);
}
}
objectPoints_seq.push_back(object_points);
}
//3.执行相机标定(会先进行角点检测),求取并保存相机内参、畸变系数向量、外参到.yml文件
vector<vector<Point2f>> cornerPoints_seq; //用于接收检测到的每个view上的各个角点的坐标
string intr_file = "./data/calibrationData/intrinsic.yml"; //相机内参的存储文件
string extr_file = "./data/calibrationData/extrinsic.yml"; //相机外参的存储文件
vector<Mat> rvecs;
vector<Mat> tvecs;
cameraCalibration(imgList, corner_point_size, actual_grid_size, cornerPoints_seq, objectPoints_seq,
cameraMatrix, distCoeffs, rvecs, tvecs, intr_file, extr_file); //***
//4.用PnP方法求解相机外参(位姿),并保存到.yml文件
string extr_file_pnp = "./data/calibrationData/extrinsic_pnp.yml";
//4.1位姿估计,注:在etPose_pnp()会用cameraCalibration()得到的rvecs和tvecs的值作为初值,利用Levenberg-Marquardt优化算法进行更新
getPose_pnp(objectPoints_seq, cornerPoints_seq, intr_file, rvecs, tvecs, extr_file_pnp); //***
//******************** End of task 1 ********************
// //********************task 2.计算两幅图像之间的单应矩阵,并用重投影误差评估测试结果********************
// cout<<endl;
// cout<<"*****************Task 2: 计算两幅图像之间的单应矩阵,并用重投影误差评估测试结果*****************"<<endl;
//
// Mat mask; //用于储存哪几组点对应是inlier(值不为0),哪几组点对应是outlier(值为0).
// string source_img_name = imgFolder+"chessboard_org.png"; //源图片
// string target_img_name = imgFolder+"chessboard4.png"; //目标图片
//
// //2.1 计算单应矩阵,并返回源图像和目标图像中inliers的坐标
// vector<Point2f> src_points_inliers; //用于存放源图像中属于inlier的场景点
// vector<Point2f> trgt_points_inliers; //用于存放目标图像中属于inlier的场景点
// Mat homography = computeHomography_2d(source_img_name, target_img_name, corner_point_size, mask,
// src_points_inliers, trgt_points_inliers); //***
// //至此,得到了src_points_inliers、trgt_points_inliers中的值
//
// //2.2 计算对称转移误差(Symmetric Transfer Error, STE)
// vector<Point2f> src_points_proj; //用于存放源图像上的点投影(到目标图像上)之后的点的坐标
// vector<Point2f> trgt_points_proj; //用于存放目标图像上的点投影(到源图像上)之后的点的坐标
// symmetricTransfer_error(src_points_inliers, trgt_points_inliers, homography,
// src_points_proj, trgt_points_proj ); //***
//
// //2.3 (在转移后的图片上)绘制转移点
// //画圈圈(绘制转移过来的inlier点)
// cout<< "********开始绘制带转移点的 源图像 和 目标图像******"<<endl;
// cout << "绘制源图片(带目标图片上转移过来的点):" << endl;
// drawCircleOnImage(source_img_name, trgt_points_proj, Scalar(0,0,255), "Source Image with transfered points");
//
// cout << "绘制目标图片(带源图片上转移过来的点):" << endl;
// drawCircleOnImage(target_img_name, src_points_proj, Scalar(255,0,0), "Target Image with transfered points");
// //******************** End of task 2 ********************
//********************task 3.使用Drareni算法计算单应矩阵H(3X6)、标准化矩阵T_img、T_wrld,并评估实验结果********************
cout<<endl;
cout<<"*****************Task 3: 使用Drareni算法计算单应矩阵H(3X6)、标准化矩阵T_img、T_wrld,并评估实验结果*****************"<<endl;
//(20210129记录)目前还没有拿到线阵相机所拍的图像,用的是面阵相机所拍的图像测的
// (20210205记录) 线扫相机成像已经ok,现在用的是线扫相机+厚的12x9的标定板成的图像
//3.1 选定一张测试用的图像,同时把测试要用到的角点坐标转换成指定形式
//指定用来测试的图像: view[0],即在line30左右添加到imgList中的第一张图
vector<Point2f> imagePoints = cornerPoints_seq[0]; //view[0]中的所有角点的图像坐标
vector<Point3f> worldPoints_3d = objectPoints_seq[0];
vector<Point2f> worldPoints; //所有角点在 世界平面坐标系 中的坐标(手动赋值的)
for(int i=0; i<imagePoints.size(); i++)
{
worldPoints.emplace_back(worldPoints_3d[i].x, worldPoints_3d[i].y );
}
//在测试图像中选定多少个角点参与运算
int wrldPts_num = corner_point_size.width*corner_point_size.height;
vector<Point2f> imgPoints_atd;
vector<Point2f> wrldPoints_atd;
for(int i=0; i<wrldPts_num; i++)
{
imgPoints_atd.push_back(imagePoints[ i ]);
wrldPoints_atd.push_back(worldPoints[ i ]);
}
//3.2 计算Drareni算法的转换矩阵H(3X6) (normalized World coord -> normalized Image coord)、
// 图像平面的标准化矩阵T_img(3X3)、世界平面的标准化矩阵T_wrld(3X3)
//3.2.1 计算H、T_img、T_wrld
Mat T_img, T_wrld;
Mat H = Drareni_computeHomography(wrldPoints_atd, imgPoints_atd, T_img, T_wrld); //***标定
cout<<"H( normalized World coord -> normalized Image coord): "<<endl<<H<<endl;
cout<<"T_img( Image Plane coord -> normalized Image Plane coord ): "<<endl<<T_img<<endl;
cout<<"T_wrld( World Plane coord -> normalized Iorld Plane coord ): "<<endl<<T_wrld<<endl;
//3.2.2 将H、T_img、T_wrld存储到.yml文件中
cv::FileStorage imageToWorld("./data/calibrationData/imageToWorld.yml", FileStorage::WRITE);
imageToWorld << "H" <<H;
imageToWorld << "T_img" << T_img;
imageToWorld << "T_wrld" << T_wrld;
imageToWorld.release();
cout<<"Drareni算法算出的结果矩阵:H(3X6)、T_img(3X3)、T_wrld(3X3)已经存储完毕。"<<endl;
// //3.3 在图像平面上选择一个点,看看用转换矩阵把它转换到 世界平面坐标系 中得到的坐标与其 在世界平面坐标系中的真是坐标 差多少
// // 3.3.1 直接输出计算后的坐标与真实世界坐标对比
//// int test_point_ptId = 21; //被选中的测试点的id:我看看把这个图像平面上的点坐标用Drareni方法求出的 H矩阵 反映射到世界平面,得到的坐标是多少
//// Point2f p_test = imagePoints[test_point_ptId];
// Point2f p_test = Point2f(226.0,196.0); //测试点(1号黑点) 在图像平面的真实坐标(单位:pixel)
//
// Point2f p_computed = Drareni_computWorldCoord(p_test.x, p_test.y, H, T_img, T_wrld); //***
// cout<<"computed coordinate of the Test Point in World Plane (denormalized): "<<p_computed<<endl;
//
// Point2f p_test_actual = Point2f(47.0,31.5); //测试点 在世界平面上的真实坐标(单位:mm)
//// cout<<"actual coordinate in World Plane (denormalized): "<<worldPo ints[test_point_ptId]<<endl;
// cout<<"actual coordinate of the Test Point in World Plane (denormalized): ("<<p_test_actual.x<<", "<<p_test_actual.y<<")"<<endl;
//
// //3.3.2 测试结果可视化
// // 可视化说明: 在 标准的chessboard图像 上绘制点来模拟在 世界平面 上识别出点(注意:第一个角点是3D世界坐标系的原点);
// // 红色圆圈 表示测试点在世界平面上的 真实坐标,
// // 蓝色圆圈 表示输入图像平面坐标,利用Drareni方法转换矩阵 求出的测试点在世界平面中的坐标。
// cout<<endl<<"###################### 可视化Test ######################"<<endl;
//
// //3.3.2 (1): 从txt文件中读出测试点的 图像平面坐标 和 世界平面坐标
// vector<Point2f> img_coords;
// vector<Point2f> wrld_coords;
// ifstream inFile;
// inFile.open("./data/"+testImgFile+".txt", ios::in); //存储当前这个测试图像上测试点坐标的txt文件
// string str, temp; //str:用于存储从文件中读取的每一行的内容
// smatch result;
// regex pattern("([-]?[0-9]+[.][0-9]+,[-]?[0-9]+[.][0-9]+)"); //匹配括号内的内容
// int count = 0;
//
// //迭代器声明
// string::const_iterator iterStart;
// string::const_iterator iterEnd;
//
// while(getline(inFile, str))
// {
// iterStart = str.begin();
// iterEnd = str.end();
//
// while (regex_search(iterStart, iterEnd, result, pattern))
// {
// count++; //每匹配到一次就计数
// temp = result[0];
// vector<string> substrings = string_split(temp,",");
// Point2f p = Point2f(atof(substrings[0].c_str()), atof(substrings[1].c_str()) );
// if(count%2==1)
// {
// img_coords.push_back(p);
// }
// else
// {
// wrld_coords.push_back(p);
// }
// iterStart = result[0].second; //更新搜索起始位置,搜索剩下的字符串
// }
// }
// //end 3.3.2 (1)(至此,testPoints.txt中所有测试点的图像坐标和在3D世界中的坐标已被读取到vector<Point2f>中)
// int testPoint_num = img_coords.size();
//
// //3.3.2 (2): 正式进行可视化绘制
// string chsbd_std = imgFolder + "chessboard_standard.png"; //标准棋盘格图像(用于作为参照)
// Mat imgTest = imread(chsbd_std);
// Size img_grid_size = Size(89, 90); //标准棋盘格图像平面上一个格子的尺寸:宽x高(单位:pixel)
//
// for(int i=0; i<testPoint_num; i++)
// {
// Point2f p_test_actual_i = wrld_coords[i];
// Point2f p_computed_i = Drareni_computWorldCoord(img_coords[i].x, img_coords[i].y, H, T_img, T_wrld);
// cout<<endl<<"测试点"+to_string(i+1)+": ";
// cout<<"它在世界平面的真实坐标为("+to_string(p_test_actual_i.x)+","+to_string(p_test_actual_i.y)+"); ";
// cout<<"它由图像平面坐标计算出的在世界平面的坐标为("+to_string(p_computed_i.x)+","+to_string(p_computed_i.y)+")。 "<<endl;
//
// Point2f p_test_actual_draw = worldCoord_to_stdImageCoord(p_test_actual_i, actual_grid_size, img_grid_size);
// Point2f p_computed_draw = worldCoord_to_stdImageCoord(p_computed_i, actual_grid_size, img_grid_size);;
//
// circle(imgTest, p_test_actual_draw, 2, Scalar(0, 0, 255), 2); //绘制真实坐标(Red)
// circle(imgTest, p_computed_draw, 2, Scalar(255, 0, 0), 2); //绘制计算出的坐标(Blue)
// }
// imshow("Actual coord and computed coord on the Test Image", imgTest);
// imwrite("./img/result/testPointsCompar_"+testImgFile+".png", imgTest); //将测试点的 计算出的世界平面坐标 和 真实世界平面坐标 的可视化对比图保存
// while( (char)waitKey(0)!=27 )
// ;
// //end 3.3
//******************** End of task 3 ********************
//********************task 4.计算 世界平面坐标系 到 机器人平面坐标系 的转换关系(一劳永逸)********************
cout<< "********************task 4.加上世界平面坐标系到机器人坐标系的转换关系(一劳永逸)********************" <<endl;
//4.1 建立世界坐标系和机器人坐标系的关系(计算出转换矩阵H_v,并保存到.yml文件中)
//4.1.1 testPoints_Robot.txt中走的点在机器人坐标系下的坐标
vector<Point2i> testPoints_robot_id; //用来存储这些走的角点的行列号
vector<Point2f> testPoints_robot_coord; //用来存储这些走的角点在机器人坐标系下的坐标
ifstream inFile2;
inFile2.open("./data/tsk4_testPoints_Robot2.txt", ios::in); //该文件存储了走的点在 机器人平面坐标系 中的坐标
string str2; //str2:用于存储从文件中读取的每一行的内容
vector<string> splitted_substring;
vector<string> splitted_substring_num;
vector<string> splitted_substring_coord;
//迭代器声明
while(getline(inFile2, str2))
{
if(str2.empty())
continue;
splitted_substring = string_split(str2,";");
splitted_substring_num = string_split(splitted_substring[0], ",");
splitted_substring_coord = string_split(splitted_substring[1], ",");
Point2i rowAndCol_num = Point2i( stoi(splitted_substring_num[0]), stoi(splitted_substring_num[1]) );
Point2f pt_coord = Point2f( stof(splitted_substring_coord[0]), stof(splitted_substring_coord[1]) );
testPoints_robot_id.push_back(rowAndCol_num);
testPoints_robot_coord.push_back(pt_coord);
//每轮循环结束记得清空那三个临时的vector<string>
splitted_substring.clear();
splitted_substring_num.clear();
splitted_substring_coord.clear();
}
//4.1.2 将对应点的世界坐标提取到一个vetor<Point2f>中
vector<Point2f> testPoints_world_coord; //用来存储这些走的点的世界坐标(这些坐标就是 行号、列号 乘上 格子的宽、高 得来的)
int verifyingPoint_num = testPoints_robot_id.size(); //一共走了多少个点
for(int i=0; i<verifyingPoint_num; i++)
{
Point2f verifyingPoint = Point2f( actual_grid_size.width*testPoints_robot_id[i].y,
actual_grid_size.height*testPoints_robot_id[i].x );
// cout<<"第"+to_string(i+1)+"个走的点在 世界平面 的坐标:"<<verifyingPoint<<endl;
testPoints_world_coord.push_back(verifyingPoint);
}
//至此,testPoints_world_coord填充完毕
//4.1.3 由于世界坐标系和机器人坐标系的手性是不同的,所以这里我们要把 世界坐标系 先转换到 过渡世界坐标系,
//过渡世界坐标系 其实就是把原来的 世界坐标系 的x轴和y轴互换了一下
vector<Point2f> testPoints_interimWorld_coord = chirality_transformation(testPoints_world_coord);
cout<<"世界平面坐标系 到 过渡世界平面坐标系 的转换已完成!"<<endl;
//4.1.4 计算两组2D点之间的单应:H_v(src:过渡世界坐标系,trgt:机器人坐标系)
Mat mask_verifing;
vector<Point2f> verifying_inliers_src;
vector<Point2f> verifying_inliers_trgt;
Mat H_v = computeHomography2_2d(testPoints_interimWorld_coord, testPoints_robot_coord, corner_point_size,
mask_verifing, verifying_inliers_src, verifying_inliers_trgt );
// H_v(v表示verify):从 过渡世界坐标系 到 机器人坐标系 的坐标转换矩阵
//4.1.5 保存H_v到.yml文件
cv::FileStorage wrldToRbt("./data/calibrationData/worldToRobot.yml", FileStorage::WRITE);
wrldToRbt << "H_v" <<H_v;
wrldToRbt.release();
cout<<"过渡世界平面坐标系 到 机器人(平面)坐标系 的单应矩阵H_v已经存储完毕。"<<endl;
//******************** End of task 4 ********************
//********************task 5.(Test) 最终测试********************
//给定一些(待抓取)物体(可能很大)在 图像平面 上的坐标(去图像中用PS量),利用H、T_img、T_wrld、H_v计算出它们在 机器人坐标系(平面)
//中的坐标,并将计算出的 机器人坐标(简称) 与它们真实的 机器人坐标(用走点的方法测量出来的)对比,看差多少。
cout<<endl<<"******************** task 5.(Test) 最终测试********************" <<endl;
//5.1 从.yml文件中读取需要用到的矩阵
//这些变量分别用来存储从xxx.yml文件中读出来的矩阵
Mat H1(3,6,CV_64FC1);
Mat T_img1(3,3,CV_64FC1);
Mat T_wrld1(3,3,CV_64FC1);
Mat H_v1(3,3,CV_64FC1);
string file_imageToWorld = "./data/calibrationData/imageToWorld.yml";
string file_worldToRobot = "./data/calibrationData/worldToRobot.yml";
FileStorage fs_imgToWorld(file_imageToWorld, FileStorage::READ);
FileStorage fs_worldToRobot(file_worldToRobot, FileStorage::READ);
fs_imgToWorld["H"]>>H1;
fs_imgToWorld["T_img"]>>T_img1;
fs_imgToWorld["T_wrld"]>>T_wrld1;
fs_worldToRobot["H_v"]>>H_v1;
cout<<endl<<"test task5"<<endl;
cout<<"H"<<endl<<H1<<endl;
cout<<"T_img"<<endl<<T_img1<<endl;
cout<<"T_wrld"<<endl<<T_wrld1<<endl;
cout<<"H_v"<<endl<<H_v1<<endl;
//test:测试一下H_v求得怎么样
cout<<endl<<"插入Test: 测试一下求得的从 过渡世界平面坐标系 到 机器人坐标系 的转换矩阵H_v准不准:"<<endl;
vector<Point2f> src_points_proj; //源平面(过渡世界平面)上的点投影到目标平面(机器人平面)的点坐标(待填充)
vector<Point2f> trgt_points_proj; //目标平面(机器人平面)上的点投影回源平面(过渡世界平面)的点坐标(待填充)
double symError = symmetricTransfer_error(testPoints_interimWorld_coord, testPoints_robot_coord, H_v, src_points_proj, trgt_points_proj);
cout<<"接下来输出走的点在 源平面(过渡世界平面)上的坐标,和从目标平面(机器人平面)投影到源平面 的坐标"<<endl;
for(int i=0; i<verifyingPoint_num; i++)
{
cout<<"srcPoint "+to_string(i+1)+":"<<testPoints_interimWorld_coord[i]<<" ; "<<trgt_points_proj[i]<<endl;
}
cout<<"接下来输出走的点在 目标平面(机器人平面)上的坐标,和从源平面(过渡世界平面)投影到目标平面 的坐标"<<endl;
for(int i=0; i<verifyingPoint_num; i++)
{
cout<<"targetPoint "+to_string(i+1)+":"<<testPoints_robot_coord[i]<<" ; "<<src_points_proj[i]<<endl;
}
cout<<"插入Test结束!"<<endl;
// end test:测试一下H_v求得怎么样
//5.2 从.txt文件中读出 待抓物体的 图像平面坐标系的坐标 和 机器人坐标系的坐标
string fileToBeLoaded = "./data/tsk5_objectToBeGrasped2.txt"; //待加载文件目录(包含待抓物体的 图像平面坐标系的坐标 和 机器人坐标系的坐标)
vector<Point2f> obj_img_coords;
vector<Point2f> obj_robot_coords;
ifstream imgAndRobot_coord;
imgAndRobot_coord.open(fileToBeLoaded, ios::in);
string str5, temp5; //str:用于存储从文件中读取的每一行的内容
smatch result5;
regex pattern5("([-]?[0-9]+[.][0-9]+,[-]?[0-9]+[.][0-9]+)"); //匹配括号内的内容
int count5 = 0;
//迭代器声明
string::const_iterator iterStart5, iterEnd5;
while(getline(imgAndRobot_coord, str5))
{
iterStart5 = str5.begin();
iterEnd5 = str5.end();
while (regex_search(iterStart5, iterEnd5, result5, pattern5))
{
count5++; //每匹配到一次就计数
temp5 = result5[0];
vector<string> substrings = string_split(temp5,",");
Point2f p = Point2f(atof(substrings[0].c_str()), atof(substrings[1].c_str()) );
if(count5%2==1)
{
obj_img_coords.push_back(p);
}
else
{
obj_robot_coords.push_back(p);
}
iterStart5 = result5[0].second; //更新搜索起始位置,搜索剩下的字符串
}
}
//end 5.2 读取正常,obj_img_coords和obj_robot_coords填充完毕
//5.3(版本一) 用待抓取的那几个物体的图像坐标来测
//5.3.1 计算。
// 用(5.1)从.yml文件中读取出来的矩阵 和 (5.2)从.txt文件中读取出来的 待抓物体在图像平面坐标系的坐标 计算待抓物体在 机器人坐标系中的坐标
vector<Point2f> worldCoords;
vector<Point2f> to_robot = imageToRobot(obj_img_coords, H1, T_img1, T_wrld1, H_v1, worldCoords);
// //这是另一种写法,用symmetricTransfer_error()函数来得到映射后的坐标
// vector<Point2f> to_interimWorld, to_robot;
// double err2 = symmetricTransfer_error(obj_interimWorld_coords, obj_robot_coords, H_v1, to_robot, to_interimWorld);
cout<<endl<<"接下来输出这些物体在 机器人坐标系的真实坐标 和 计算出的机器人坐标系坐标:"<<endl;
int objNum = to_robot.size();
for(int i=0; i<objNum; i++)
{
cout<<"Object "+to_string(i+1)+": "<<obj_robot_coords[i]<<" ; "<<to_robot[i]<<endl;
}
//5.3.2 可视化。根据待抓取物体在 世界平面坐标系 的坐标,在lineScan_cut.png上绘制出位置,看看是不是在物体的范围内
vector<Point2f> stdImg_coords;
stdImg_coords.reserve(objNum);
for(int i=0; i<objNum; i++)
{
if(worldCoords[i].x<-60||worldCoords[i].y<-60)
continue; //这里我们只绘制x和y坐标都大于-60的物体
Point2f stdImg_coord = worldCoord_to_stdImageCoord(worldCoords[i], actual_grid_size, Size(140,142) );
stdImg_coords.emplace_back(stdImg_coord);
}
drawCircleOnImage("./img/lineScanImage2_cut.png", stdImg_coords, Scalar(0,0,255), "Object to be grasped", 40, 20);
//end 5.3(版本一)
// //5.3(版本二) 用走点时的那几个点 的图像坐标来测
// vector<Point2f> obj_img_coords2; //走点的点 在图片坐标系中的坐标
// obj_img_coords2.reserve(9);
// obj_img_coords2.emplace_back( Point2f(1256.0,6095.0) );
// obj_img_coords2.emplace_back( Point2f(1256.0,5551.0) );
// obj_img_coords2.emplace_back( Point2f(1256.0,5013.0) );
// obj_img_coords2.emplace_back( Point2f(1684.0,6105.0) );
// obj_img_coords2.emplace_back( Point2f(1686.0,5552.0) );
// obj_img_coords2.emplace_back( Point2f(1685.0,5008.0) );
// obj_img_coords2.emplace_back( Point2f(2112.0,6107.0) );
// obj_img_coords2.emplace_back( Point2f(2106.0,5559.0) );
// obj_img_coords2.emplace_back( Point2f(2102.0,5019.0) );
// vector<Point2f> obj_robot2=testPoints_robot_coord; //走点的点
//
// vector<Point2f> worldCoords;
// vector<Point2f> obj_interimWorld_coords = imageToRobot(obj_img_coords2, H1, T_img1, T_wrld1, H_v1, worldCoords);
// vector<Point2f> to_interimWorld, to_robot;
// double err2 = symmetricTransfer_error(obj_interimWorld_coords, obj_robot2, H_v1, to_robot, to_interimWorld);
// cout<<endl<<"我他妈倒要看看是哪里不对:"<<endl;
// cout<<"在机器人坐标系下的真实的坐标, 转移到机器人坐标系下的坐标"<<endl;
// for(int i=0; i<to_robot.size(); i++)
// {
// cout<<"Obj "+to_string(i+1)+": "<<obj_robot2[i]<<" ; "<<to_robot[i]<<endl;
// }
// //end 5.3(版本二):测出来效果还可以,只差了几个像素
return 0;
} | 42.962719 | 141 | 0.641417 | [
"object",
"vector"
] |
c7cb4db658557710f5778612c5a5cb3b8a6772c2 | 2,592 | cpp | C++ | PlatformerEngine/main.cpp | pixelpicosean/PlatformerEngine | 2093289bac9fd7de53bfa64a445c05c3d30dff86 | [
"MIT"
] | 1 | 2020-11-03T16:04:25.000Z | 2020-11-03T16:04:25.000Z | PlatformerEngine/main.cpp | pixelpicosean/PlatformerEngine | 2093289bac9fd7de53bfa64a445c05c3d30dff86 | [
"MIT"
] | null | null | null | PlatformerEngine/main.cpp | pixelpicosean/PlatformerEngine | 2093289bac9fd7de53bfa64a445c05c3d30dff86 | [
"MIT"
] | null | null | null |
//
// Disclaimer:
// ----------
//
// This code will work only if you selected window, graphics and audio.
//
// Note that the "Run Script" build phase will copy the required frameworks
// or dylibs to your application bundle so you can execute it on any OS X
// computer.
//
// Your resource files (images, sounds, fonts, ...) are also copied to your
// application bundle. To get the path to these resources, use the helper
// function `resourcePath()` from ResourcePath.hpp
//
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
// Here is a small helper for you! Have a look.
#include "ResourcePath.hpp"
// Engine headers
#include "game/Character.hpp"
#include "core/Map.hpp"
int main(int, char const**) {
// Setup window
sf::RenderWindow window(sf::VideoMode(320, 320), "PlatformerEngine");
// Initialize
Map map(8, 8, {
{ 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,1,1,1, 2,2,2,2,2, 2,2,2,2,2, 1,1,1,0,1 },
{ 1,0,1,0,1, 0,0,0,0,0, 0,0,0,0,0, 1,0,1,0,1 },
{ 1,0,1,1,1, 0,0,0,0,0, 0,0,0,0,0, 1,1,1,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,1,1, 1,1,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,1,1, 1,1,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,1 },
{ 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1 },
});
Character player(100, 100, 30, 40, map);
// Game loop
sf::Clock clock;
while (window.isOpen()) {
// Handle events
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
// Update
sf::Time dt = clock.restart();
// - Update player
player.Update(dt);
// Draw
window.clear();
// - Draw map
map.Draw(window);
// - Draw player
player.Draw(window);
// Flush and render to screen
window.display();
}
return EXIT_SUCCESS;
}
| 26.721649 | 90 | 0.528164 | [
"render"
] |
c7cd4477970a99ed1ab4f46fa564c208e09da6de | 2,520 | cpp | C++ | inetsrv/iis/svcs/smtp/aqueue/aqadmin/src/dllmain.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/svcs/smtp/aqueue/aqadmin/src/dllmain.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/svcs/smtp/aqueue/aqadmin/src/dllmain.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //-----------------------------------------------------------------------------
//
//
// File: dllmain.cpp
//
// Description: DLL main for aqadmin.dll
//
// Author: Alex Wetmore (Awetmore)
//
// History:
// 12/10/98 - MikeSwa Updated for initial checkin
//
// Copyright (C) 1998 Microsoft Corporation
//
//-----------------------------------------------------------------------------
#include "stdinc.h"
#include "resource.h"
#include "initguid.h"
#include "aqadmin.h"
HANDLE g_hTransHeap = NULL;
CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_AQAdmin, CAQAdmin)
END_OBJECT_MAP()
BOOL g_fHeapInit = FALSE;
BOOL g_fModuleInit = FALSE;
/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) {
if (dwReason == DLL_PROCESS_ATTACH) {
if (!TrHeapCreate())
return FALSE;
g_fHeapInit = TRUE;
_Module.Init(ObjectMap,hInstance);
g_fModuleInit = TRUE;
DisableThreadLibraryCalls(hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH) {
if (g_fModuleInit)
_Module.Term();
if (g_fHeapInit)
TrHeapDestroy();
g_fHeapInit = FALSE;
g_fModuleInit = FALSE;
}
return (TRUE); // ok
}
/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE
STDAPI DllCanUnloadNow(void) {
HRESULT hRes = (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
return (hRes);
}
/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
HRESULT hRes = _Module.GetClassObject(rclsid,riid,ppv);
return (hRes);
}
/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void) {
// registers object, typelib and all interfaces in typelib
HRESULT hRes = _Module.RegisterServer();
return (hRes);
}
/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void) {
_Module.UnregisterServer();
return (S_OK);
}
| 25.2 | 82 | 0.512302 | [
"object"
] |
c7ce6e0859f4f0d8dedd986a1d1be440231eb0b0 | 4,023 | cpp | C++ | src/tests/ascent/t_ascent_mpi_multi_topo.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/tests/ascent/t_ascent_mpi_multi_topo.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/tests/ascent/t_ascent_mpi_multi_topo.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_mpi_render_2d.cpp
///
//-----------------------------------------------------------------------------
#include "gtest/gtest.h"
#include <ascent.hpp>
#include <iostream>
#include <math.h>
#include <mpi.h>
#include <conduit_blueprint.hpp>
#include "t_config.hpp"
#include "t_utils.hpp"
using namespace std;
using namespace conduit;
using ascent::Ascent;
//-----------------------------------------------------------------------------
// note: this example was a reproducer for tricky case
// involving multiple topos, pipelines + rendering.
TEST(ascent_mpi_mult_topo, test_multi_semi_madness)
{
Node n;
ascent::about(n);
// only run this test if ascent was built with vtkm support
if(n["runtimes/ascent/vtkm/status"].as_string() == "disabled")
{
ASCENT_INFO("Ascent support disabled, skipping MPI multi topo "
"runtime test");
return;
}
//
// Set Up MPI
//
int par_rank;
int par_size;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm, &par_rank);
MPI_Comm_size(comm, &par_size);
ASCENT_INFO("Rank "
<< par_rank
<< " of "
<< par_size
<< " reporting");
//
// Create the data.
//
Node data, verify_info;
create_example_multi_domain_multi_topo_dataset(data,par_rank,par_size);
EXPECT_TRUE(conduit::blueprint::mesh::verify(data,verify_info));
// make sure the _output dir exists
string output_path = "";
if(par_rank == 0)
{
output_path = prepare_output_dir();
}
else
{
output_path = output_dir();
}
string output_file = conduit::utils::join_file_path(output_path,
"tout_render_mpi_multi_domain_multi_topo");
// remove old images before rendering
remove_test_image(output_file);
//
// Create the actions.
//
conduit::Node actions;
conduit::Node &add_plines = actions.append();
add_plines["action"] = "add_pipelines";
conduit::Node &pipelines = add_plines["pipelines"];
pipelines["pl1/f1/type"] = "threshold";
pipelines["pl1/f1/params/field"] = "ele_example";
pipelines["pl1/f1/params/min_value"] = 2.0;
pipelines["pl1/f1/params/max_value"] = 11112.0;
conduit::Node &add_plots = actions.append();
add_plots["action"] = "add_scenes";
conduit::Node &scenes = add_plots["scenes"];
scenes["s1/plots/p1/type"] = "pseudocolor";
scenes["s1/plots/p1/field"] = "ele_example";
scenes["s1/plots/p1/pipeline"] = "pl1";
scenes["s1/plots/p2/type"] = "pseudocolor";
scenes["s1/plots/p2/field"] = "braid";
scenes["s1/image_prefix"] = output_file;
std::cout << actions.to_yaml() << std::endl;
//
// Run Ascent
//
Ascent ascent;
Node ascent_opts;
// we use the mpi handle provided by the fortran interface
// since it is simply an integer
ascent_opts["mpi_comm"] = MPI_Comm_c2f(comm);
ascent_opts["runtime"] = "ascent";
ascent.open(ascent_opts);
ascent.publish(data);
ascent.execute(actions);
ascent.close();
MPI_Barrier(comm);
// check that we created an image
// EXPECT_TRUE(check_test_image(output_file));
}
//-----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
| 27.182432 | 79 | 0.56003 | [
"mesh"
] |
93acfc12c793ab63ed14c50ca213cb6792f9e2da | 1,056 | cpp | C++ | boboleetcode/Play-Leetcode-master/0954-canReorderDoubled/cpp-0954/main.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0954-canReorderDoubled/cpp-0954/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0954-canReorderDoubled/cpp-0954/main.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/array-of-doubled-pairs/
/// Author : liuyubobobo
/// Time : 2018-12-12
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Greedy, from large absolute value to small absolute value
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
public:
bool canReorderDoubled(vector<int>& A) {
unordered_map<int, int> freq;
for(int a: A)
freq[a] ++;
sort(A.begin(), A.end(), [](int a, int b){return abs(a) < abs(b);});
// for(int a: A)
// cout << a << " ";
// cout << endl;
for(int a: A){
if(freq[a]){
if(!freq[2 * a])
return false;
freq[a] --;
if(!freq[2 * a])
return false;
freq[2 * a] --;
}
}
return true;
}
};
int main() {
vector<int> A1 = {4, -2, 2, -4};
cout << Solution().canReorderDoubled(A1) << endl;
return 0;
} | 21.55102 | 76 | 0.482008 | [
"vector"
] |
93b1fd3f8ce6176a6089a61a50ed7c2b6b2d0151 | 736 | cpp | C++ | test/data_structure/range_minimum_query_and_range_add_query.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 1 | 2021-12-26T14:17:29.000Z | 2021-12-26T14:17:29.000Z | test/data_structure/range_minimum_query_and_range_add_query.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | 3 | 2020-07-13T06:23:02.000Z | 2022-02-16T08:54:26.000Z | test/data_structure/range_minimum_query_and_range_add_query.test.cpp | emthrm/library | 0876ba7ec64e23b5ec476a7a0b4880d497a36be1 | [
"Unlicense"
] | null | null | null | /*
* @brief データ構造/遅延伝播セグメント木 (range minimum query and range add query)
*/
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_H"
#include <iostream>
#include <limits>
#include <vector>
#include "../../data_structure/lazy_segment_tree.hpp"
int main() {
int n, q;
std::cin >> n >> q;
LazySegmentTree<monoid::RangeMinimumAndAddQuery<long long, std::numeric_limits<long long>::max()>> rmq(std::vector<long long>(n, 0));
while (q--) {
int query, s, t;
std::cin >> query >> s >> t;
if (query == 0) {
int x;
std::cin >> x;
rmq.apply(s, t + 1, x);
} else if (query == 1) {
std::cout << rmq.get(s, t + 1) << '\n';
}
}
return 0;
}
| 26.285714 | 136 | 0.567935 | [
"vector"
] |
93c1d3dae30ef8fa4630fd953f16aa250c1e8904 | 4,694 | cpp | C++ | src/d3d12/render_pass/d3d12_render_pass_postprocess.cpp | jimbi-o/illuminate | 4dc75c927a4ce1f722f42f84e4b1a1524e9958e3 | [
"MIT"
] | null | null | null | src/d3d12/render_pass/d3d12_render_pass_postprocess.cpp | jimbi-o/illuminate | 4dc75c927a4ce1f722f42f84e4b1a1524e9958e3 | [
"MIT"
] | null | null | null | src/d3d12/render_pass/d3d12_render_pass_postprocess.cpp | jimbi-o/illuminate | 4dc75c927a4ce1f722f42f84e4b1a1524e9958e3 | [
"MIT"
] | null | null | null | #include "d3d12_render_pass_postprocess.h"
#include "d3d12_render_pass_util.h"
namespace illuminate {
namespace {
struct Param {
BufferSizeRelativeness size_type{BufferSizeRelativeness::kPrimaryBufferRelative};
uint32_t rtv_index{0};
void** cbv_ptr{nullptr};
uint32_t cbv_size{0};
};
auto UpdatePingpongA(RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass) {
auto pass_vars = static_cast<const Param*>(args_per_pass->pass_vars_ptr);
float c[4]{0.0f,1.0f,1.0f,1.0f};
memcpy(pass_vars->cbv_ptr[args_common->frame_index], c, GetUint32(sizeof(float)) * 4);
}
auto UpdatePingpongB(RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass) {
auto pass_vars = static_cast<const Param*>(args_per_pass->pass_vars_ptr);
float c[4]{1.0f,0.0f,1.0f,1.0f};
memcpy(pass_vars->cbv_ptr[args_common->frame_index], c, GetUint32(sizeof(float)) * 4);
}
auto UpdatePingpongC(RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass) {
auto pass_vars = static_cast<const Param*>(args_per_pass->pass_vars_ptr);
float c[4]{1.0f,1.0f,1.0f,1.0f};
memcpy(pass_vars->cbv_ptr[args_common->frame_index], c, GetUint32(sizeof(float)) * 4);
}
} // namespace anonymous
void* RenderPassPostprocess::Init(RenderPassFuncArgsInit* args, const uint32_t render_pass_index) {
auto param = Allocate<Param>(args->allocator);
*param = {};
if (args->json && args->json->contains("size_type")) {
param->size_type = (GetStringView(args->json->at("size_type")).compare("swapchain_relative") == 0) ? BufferSizeRelativeness::kSwapchainRelative : BufferSizeRelativeness::kPrimaryBufferRelative;
}
const auto& buffer_list = args->render_pass_list[render_pass_index].buffer_list;
for (uint32_t i = 0; i < args->render_pass_list[render_pass_index].buffer_num; i++) {
if (buffer_list[i].state == ResourceStateType::kRtv) {
param->rtv_index = i;
break;
}
}
for (uint32_t i = 0; i < args->render_pass_list[render_pass_index].buffer_num; i++) {
if (buffer_list[i].state == ResourceStateType::kCbv) {
const auto buffer_config_index = args->render_pass_list[render_pass_index].buffer_list[i].buffer_index;
param->cbv_size = static_cast<uint32_t>(args->buffer_config_list[buffer_config_index].width);
param->cbv_ptr = AllocateArray<void*>(args->allocator, args->frame_buffer_num);
for (uint32_t j = 0; j < args->frame_buffer_num; j++) {
param->cbv_ptr[j] = MapResource(GetResource(*args->buffer_list, buffer_config_index, j), param->cbv_size);
}
break;
}
}
return param;
}
void RenderPassPostprocess::Update([[maybe_unused]]RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass) {
switch (GetRenderPass(args_common, args_per_pass).name) {
case SID("pingpong-a"): {
UpdatePingpongA(args_common, args_per_pass);
break;
}
case SID("pingpong-b"): {
UpdatePingpongB(args_common, args_per_pass);
break;
}
case SID("pingpong-c"): {
UpdatePingpongC(args_common, args_per_pass);
break;
}
}
}
void RenderPassPostprocess::Render(RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass) {
auto pass_vars = static_cast<const Param*>(args_per_pass->pass_vars_ptr);
const auto& buffer_size = (pass_vars->size_type == BufferSizeRelativeness::kPrimaryBufferRelative) ? args_common->main_buffer_size->primarybuffer : args_common->main_buffer_size->swapchain;
auto& width = buffer_size.width;
auto& height = buffer_size.height;
auto command_list = args_per_pass->command_list;
command_list->SetGraphicsRootSignature(GetRenderPassRootSig(args_common, args_per_pass));
D3D12_VIEWPORT viewport{0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height), D3D12_MIN_DEPTH, D3D12_MAX_DEPTH};
command_list->RSSetViewports(1, &viewport);
D3D12_RECT scissor_rect{0L, 0L, static_cast<LONG>(width), static_cast<LONG>(height)};
command_list->RSSetScissorRects(1, &scissor_rect);
command_list->SetPipelineState(GetRenderPassPso(args_common, args_per_pass));
command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
command_list->OMSetRenderTargets(1, &args_per_pass->cpu_handles[pass_vars->rtv_index], true, nullptr);
if (args_per_pass->gpu_handles_view) {
command_list->SetGraphicsRootDescriptorTable(0, args_per_pass->gpu_handles_view[0]);
}
if (args_per_pass->gpu_handles_sampler) {
command_list->SetGraphicsRootDescriptorTable(1, args_per_pass->gpu_handles_sampler[0]);
}
command_list->DrawInstanced(3, 1, 0, 0);
}
} // namespace illuminate
| 51.021739 | 197 | 0.758415 | [
"render"
] |
93cd438e5b5c693570fac4b8de6eb613015a408e | 2,573 | cpp | C++ | middleware/common/source/buffer/transport.cpp | tompis/casual | d838716c7052a906af8a19e945a496acdc7899a2 | [
"MIT"
] | null | null | null | middleware/common/source/buffer/transport.cpp | tompis/casual | d838716c7052a906af8a19e945a496acdc7899a2 | [
"MIT"
] | null | null | null | middleware/common/source/buffer/transport.cpp | tompis/casual | d838716c7052a906af8a19e945a496acdc7899a2 | [
"MIT"
] | null | null | null | //!
//! transport.cpp
//!
//! Created on: Dec 27, 2014
//! Author: Lazan
//!
#include "common/buffer/transport.h"
#include "common/buffer/pool.h"
#include "common/algorithm.h"
namespace casual
{
namespace common
{
namespace buffer
{
namespace transport
{
bool operator < ( const Context::Callback& lhs, const Context::Callback& rhs)
{
return lhs.order < rhs.order;
}
Context& Context::instance()
{
static Context singleton;
return singleton;
}
Context::Context()
{
}
void Context::registration( std::size_t order, std::vector< Lifecycle> lifecycles, std::vector< buffer::Type> types, dispatch_type callback)
{
m_callbacks.emplace_back( order, std::move( lifecycles), std::move( types), std::move( callback));
range::stable_sort( m_callbacks);
}
void Context::dispatch(
platform::raw_buffer_type& buffer,
platform::raw_buffer_size& size,
const std::string& service,
Lifecycle lifecycle,
const buffer::Type& type)
{
auto predicate = [&]( const Callback& c){
return (c.lifecycles.empty() || range::find( c.lifecycles, lifecycle))
&& (c.types.empty() || range::find( c.types, type));
};
auto found = range::find_if( m_callbacks, predicate);
while( found)
{
found->dispatch( buffer, size, service, lifecycle, type);
found++;
found = range::find_if( found, predicate);
}
}
void Context::dispatch(
platform::raw_buffer_type& buffer,
platform::raw_buffer_size& size,
const std::string& service,
Lifecycle lifecycle)
{
dispatch( buffer, size, service, lifecycle, buffer::pool::Holder::instance().type( buffer));
}
Context::Callback::Callback( std::size_t order, std::vector< Lifecycle> lifecycles, std::vector< buffer::Type> types, dispatch_type callback)
: order( order), lifecycles( std::move( lifecycles)), types( std::move( types)), dispatch( std::move( callback)) {}
} // transport
} // buffer
} // common
} // casual
| 28.588889 | 153 | 0.508745 | [
"vector"
] |
93cdf672a4feebd2414d7e9e9b1cdbef9ee46b40 | 5,075 | cc | C++ | tools/em.cc | MIRTK/NeoSeg | d2ff4e307638727d66aff3ece25496677bbd8df1 | [
"Apache-2.0"
] | 16 | 2016-03-25T22:39:48.000Z | 2021-07-07T09:35:23.000Z | tools/em.cc | MIRTK/NeoSeg | d2ff4e307638727d66aff3ece25496677bbd8df1 | [
"Apache-2.0"
] | 24 | 2016-02-24T16:22:11.000Z | 2021-10-05T12:34:39.000Z | tools/em.cc | MIRTK/NeoSeg | d2ff4e307638727d66aff3ece25496677bbd8df1 | [
"Apache-2.0"
] | 13 | 2016-03-17T03:41:01.000Z | 2021-11-13T02:43:49.000Z | /*
* Developing brain Region Annotation With Expectation-Maximization (Draw-EM)
*
* Copyright 2013-2020 Imperial College London
*
* 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 "mirtk/Common.h"
#include "mirtk/Options.h"
#include "mirtk/IOConfig.h"
#include "mirtk/GenericImage.h"
#include "mirtk/EMBase.h"
#include <vector>
#include <sstream>
using namespace mirtk;
using namespace std;
// =============================================================================
// Help
// =============================================================================
// -----------------------------------------------------------------------------
void PrintHelp(const char *name)
{
std::cout << std::endl;
std::cout << "Usage: " << name << " <input> <N> <prob1> .. <probN> <output> [options]" << std::endl;
std::cout << std::endl;
std::cout << "Description:" << std::endl;
std::cout << " Runs EM segmentation at the input image with the provided N probability maps of structures. " << std::endl;
std::cout << " e.g. " << name << " input.nii.gz 5 bg.nii.gz csf.nii.gz gm.nii.gz wm.nii.gz dgm.nii.gz segmentation.nii.gz" << std::endl;
std::cout << std::endl;
std::cout << "Input options:" << std::endl;
std::cout << " -mask <mask> run EM inside the provided mask" << std::endl;
std::cout << " -padding <number> run EM where input > padding value" << std::endl;
std::cout << " -iterations <number> maximum number of iterations (default: 50)" << std::endl;
std::cout << " -saveprob <number> <file> save posterior probability of structure with number <number> to file "<<std::endl;
std::cout << " (0-indexed i.e. structure 1 has number 0)"<<std::endl;
std::cout << " -saveprobs <basename> save posterior probability of structures to files with basename <basename>"<<std::endl;
std::cout << std::endl;
PrintStandardOptions(std::cout);
std::cout << std::endl;
}
// =============================================================================
// Main
// =============================================================================
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
REQUIRES_POSARGS(4);
InitializeIOLibrary();
int a=1;
int i, n, padding, iterations;
// Input image
RealImage image;
image.Read(POSARG(a++));
char *output_name;
// Number of tissues
n = atoi(POSARG(a++));
// Probabilistic atlas
char **atlas_names=new char*[n];
for (i = 0; i < n; i++) {
atlas_names[i] = POSARG(a++);
}
// Probabilistic atlas
// File name for output
output_name = POSARG(a);
// Default parameters
iterations = 50;
padding = -1;//MIN_GREY;
bool usemask = false;
ByteImage mask;
int ss=0;
vector<string> savesegs;
vector<int> savesegsnr;
for (ALL_OPTIONS) {
if (OPTION("-mask")){
usemask = true;
mask.Read(ARGUMENT);
}
else if (OPTION("-padding")){
padding=atoi(ARGUMENT);
}
else if (OPTION("-iterations")){
iterations=atoi(ARGUMENT);
}
else if (OPTION("-saveprobs")) {
char* probsBase = ARGUMENT;
savesegsnr.clear();
savesegs.clear();
for (i = 0; i < n; i++){
ostringstream sstr;
sstr<<probsBase<<i<<".nii.gz";
savesegsnr.push_back(i);
savesegs.push_back(sstr.str());
}
ss=n;
}
else if (OPTION("-saveprob")) {
savesegsnr.push_back(atoi(ARGUMENT));
savesegs.push_back(ARGUMENT);
ss++;
}
else HANDLE_STANDARD_OR_UNKNOWN_OPTION();
}
EMBase *classification = new EMBase();
double atlasmin, atlasmax;
for (i = 0; i < n; i++) {
std::cout << "Image " << i <<" = " << atlas_names[i];
RealImage atlas(atlas_names[i]);
classification->addProbabilityMap(atlas);
atlas.GetMinMaxAsDouble(&atlasmin, &atlasmax);
std::cout << " with range: "<< atlasmin <<" - "<<atlasmax<<std::endl;
}
if (usemask) classification->SetMask(mask);
classification->SetPadding(padding);
classification->SetInput(image);
classification->Initialise();
double rel_diff;
i=0;
do {
std::cout << "Iteration = " << i+1 << " / " << iterations << std::endl;
rel_diff = classification->Iterate(i);
i++;
} while ((rel_diff>0.001)&&(i<iterations));
GenericImage<int> segmentation;
classification->ConstructSegmentation(segmentation);
segmentation.Write(output_name);
for (int i = 0; i < ss; ++i) {
std::cout<<"saving probability map of structure "<<savesegsnr[i]<<" to "<<savesegs[i]<<std::endl;
classification->WriteProbMap(savesegsnr[i],savesegs[i].c_str());
}
delete classification;
}
| 29.678363 | 138 | 0.592709 | [
"vector"
] |
93ce1ad647255b082fb1bca18f75e150786b729e | 1,549 | cc | C++ | base/test/statistics_delta_reader.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | base/test/statistics_delta_reader.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | base/test/statistics_delta_reader.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/statistics_delta_reader.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/stl_util.h"
namespace base {
StatisticsDeltaReader::StatisticsDeltaReader() {
StatisticsRecorder::Initialize(); // Safe to call multiple times.
// Record any histogram data that exists when the object is created so it can
// be subtracted later.
StatisticsRecorder::Histograms histograms;
StatisticsRecorder::GetSnapshot(std::string(), &histograms);
for (size_t i = 0; i < histograms.size(); ++i) {
original_samples_[histograms[i]->histogram_name()] =
histograms[i]->SnapshotSamples().release();
}
}
StatisticsDeltaReader::~StatisticsDeltaReader() {
STLDeleteValues(&original_samples_);
}
scoped_ptr<HistogramSamples>
StatisticsDeltaReader::GetHistogramSamplesSinceCreation(
const std::string& histogram_name) {
HistogramBase* histogram = StatisticsRecorder::FindHistogram(histogram_name);
if (!histogram)
return scoped_ptr<HistogramSamples>();
scoped_ptr<HistogramSamples> named_samples(histogram->SnapshotSamples());
HistogramSamples* named_original_samples = original_samples_[histogram_name];
if (named_original_samples)
named_samples->Subtract(*named_original_samples);
return named_samples.Pass();
}
} // namespace base
| 34.422222 | 79 | 0.764364 | [
"object"
] |
93d077054dd3000b73b907938cafd232bf586f76 | 354 | cpp | C++ | CodeRed/DirectX12/DirectX12RenderPass.cpp | LinkClinton/Code-Red | 491621144aba559f068c7f91d71e3d0d7c87761e | [
"MIT"
] | 34 | 2019-09-11T09:12:16.000Z | 2022-02-13T12:50:25.000Z | CodeRed/DirectX12/DirectX12RenderPass.cpp | LinkClinton/Code-Red | 491621144aba559f068c7f91d71e3d0d7c87761e | [
"MIT"
] | 7 | 2019-09-22T14:21:26.000Z | 2020-03-24T10:36:20.000Z | CodeRed/DirectX12/DirectX12RenderPass.cpp | LinkClinton/Code-Red | 491621144aba559f068c7f91d71e3d0d7c87761e | [
"MIT"
] | 6 | 2019-10-21T18:05:55.000Z | 2021-04-22T05:07:30.000Z | #pragma once
#include "DirectX12RenderPass.hpp"
#ifdef __ENABLE__DIRECTX12__
using namespace CodeRed::DirectX12;
CodeRed::DirectX12RenderPass::DirectX12RenderPass(
const std::shared_ptr<GpuLogicalDevice>& device,
const std::vector<Attachment>& colors,
const std::optional<Attachment>& depth) :
GpuRenderPass(device, colors, depth)
{
}
#endif
| 18.631579 | 50 | 0.779661 | [
"vector"
] |
93d5b87bb017e188c9bc2e477de66e31ddf86a8f | 580 | cpp | C++ | cf/1140/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | cf/1140/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | cf/1140/c.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
int n, k;
long long ans, tmp;
int lenth, beauty;
vector<int> BB[1000010];
int main() {
scanf("%d%d", &n, &k);
for(int i = 1; i <= n; ++i) {
scanf("%d%d", &lenth, &beauty);
BB[beauty].push_back(lenth);
}
multiset<int> st;
for(int mx = 1000000; mx >= 1; --mx) {
for(int i = 0; i < BB[mx].size(); ++i) {
st.insert(BB[mx][i]);
tmp += BB[mx][i];
}
while(st.size() > k) {
tmp -= *st.begin();
st.erase(st.begin());
}
ans = max(ans, tmp * mx);
}
printf("%lld\n", ans);
return 0;
} | 18.125 | 42 | 0.52931 | [
"vector"
] |
93d8e87bd8cef4a47293edf8a7d1b035cef0ecd9 | 2,513 | cc | C++ | tests/ampcor.lib/correlators/coarse_gamma.cc | aivazis/ampcor | a673e6fd12ac29086c88002ce999a8eabdf406cd | [
"BSD-2-Clause"
] | 3 | 2018-12-16T14:16:51.000Z | 2020-11-12T17:33:02.000Z | tests/ampcor.lib/correlators/coarse_gamma.cc | aivazis/ampcor | a673e6fd12ac29086c88002ce999a8eabdf406cd | [
"BSD-2-Clause"
] | null | null | null | tests/ampcor.lib/correlators/coarse_gamma.cc | aivazis/ampcor | a673e6fd12ac29086c88002ce999a8eabdf406cd | [
"BSD-2-Clause"
] | null | null | null | // -*- c++ -*-
//
// michael a.g. aïvázis <michael.aivazis@para-sim.com>
// parasim
// (c) 1998-2021 all rights reserved
// support
#include <cassert>
#include <algorithm>
// get the header
#include <ampcor/dom.h>
// the plan details
#include "plan.h"
// type aliases
using arena_const_raster_t = ampcor::dom::arena_const_raster_t<float>;
using spec_t = arena_const_raster_t::spec_type;
using pixel_t = spec_t::pixel_type;
using index_t = arena_const_raster_t::index_type;
using shape_t = arena_const_raster_t::shape_type;
using layout_t = arena_const_raster_t::layout_type;
// load the product that has the coarse correlation surface
int main(int argc, char *argv[]) {
// initialize the journal
pyre::journal::init(argc, argv);
pyre::journal::application("coarse_gamma");
// make a channel
pyre::journal::debug_t channel("ampcor.correlators.gamma");
// the pair portion of the arena origin
spec_t::id_layout_type::index_type none { 0 };
// the number of pairs as an index part
spec_t::id_layout_type::index_type pairs { plan.gridShape.cells() };
// term that help form all possible placements of ref tiles in the secondary window
ampcor::dom::slc_raster_t::shape_type one { 1, 1 };
// arena: the name of the product
std::string arenaName = "coarse_gamma.dat";
// the origin
index_t arenaOrigin = none * (-1 * plan.seedMargin);
// the shape: all possible placements of a {ref} tile within a {sec} tile
shape_t arenaShape = pairs * (2 * plan.seedMargin + one);
// build the layout
layout_t arenaLayout { arenaShape, arenaOrigin };
// the product specification
spec_t arenaSpec { arenaLayout };
// build the product
arena_const_raster_t arena { arenaSpec, arenaName };
// go through the tiles
for (auto tid = 0; tid < pairs[0]; ++tid) {
// show me the tile number
channel << "tile " << tid << pyre::journal::newline;
// and the contents
for (auto i = arenaOrigin[1]; i < arenaOrigin[1] + arenaShape[1]; ++i) {
for (auto j = arenaOrigin[2]; j < arenaOrigin[2] + arenaShape[2]; ++j) {
// form the index
index_t idx { tid, i, j };
// show me
channel << " " << std::setprecision(3) << std::setw(10) << arena[idx];
}
channel << pyre::journal::newline;
}
}
// flush
channel << pyre::journal::endl(__HERE__);
// all done
return 0;
}
// end of file
| 31.810127 | 87 | 0.635097 | [
"shape"
] |
93e56b2a4d738b72aeef6223b84184567cd90642 | 7,569 | cpp | C++ | src/Shared/Core/FCKeys.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | null | null | null | src/Shared/Core/FCKeys.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | null | null | null | src/Shared/Core/FCKeys.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | 2 | 2015-04-13T10:07:14.000Z | 2019-05-16T11:14:18.000Z | /*
Copyright (C) 2011-2012 by Martin Linklater
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 "FCKeys.h"
std::string kFCKeyId = "id";
std::string kFCKeyTexture = "texture";
std::string kFCKeyAtlas = "atlas";
std::string kFCKeyName = "name";
std::string kFCKeySize = "size";
std::string kFCKeyNull = "null";
// Physics
std::string kFCKeyBody = "body";
std::string kFCKeyMaterial = "material";
std::string kFCKeyPhysics = "physics";
std::string kFCKeyDensity = "density";
std::string kFCKeyFriction = "friction";
std::string kFCKeyRestitution = "restitution";
std::string kFCKeyJointType = "type";
std::string kFCKeyJointTypeRevolute = "revolute";
std::string kFCKeyJointTypeDistance = "distance";
std::string kFCKeyJointTypePrismatic = "prismatic";
std::string kFCKeyJointTypePulley = "pulley";
std::string kFCKeyJointAnchorId = "anchorid";
std::string kFCKeyJointAnchorOffsetX = "anchorOffsetX";
std::string kFCKeyJointAnchorOffsetY = "anchorOffsetY";
std::string kFCKeyJointAnchorGroundX = "anchorgroundx";
std::string kFCKeyJointAnchorGroundY = "anchorgroundy";
std::string kFCKeyJointOffsetX = "offsetX";
std::string kFCKeyJointOffsetY = "offsetY";
std::string kFCKeyJointLowerAngle = "lowerangle";
std::string kFCKeyJointUpperAngle = "upperangle";
std::string kFCKeyJointLowerTranslation = "lowertranslation";
std::string kFCKeyJointUpperTranslation = "uppertranslation";
std::string kFCKeyJointMaxMotorTorque = "maxmotortorque";
std::string kFCKeyJointMaxMotorForce = "maxmotorforce";
std::string kFCKeyJointMotorSpeed = "motorspeed";
std::string kFCKeyJointAxisX = "axisx";
std::string kFCKeyJointAxisY = "axisy";
std::string kFCKeyJointGroundX = "groundx";
std::string kFCKeyJointGroundY = "groundy";
std::string kFCKeyJointRatio = "ratio";
std::string kFCKeyJointMaxLength1 = "maxlength1";
std::string kFCKeyJointMaxLength2 = "maxlength2";
std::string kFCKeyRndSeed = "rndseed";
std::string kFCKeyModel = "model";
std::string kFCKeyDebugShape = "debugshape";
std::string kFCKeyNumVertices = "numvertices";
std::string kFCKeyNumTriangles = "numtriangles";
std::string kFCKeyNumEdges = "numedges";
std::string kFCKeyType = "type";
std::string kFCKeyX = "x";
std::string kFCKeyY = "y";
std::string kFCKeyWidth = "width";
std::string kFCKeyHeight = "height";
std::string kFCKeyOffset = "offset";
std::string kFCKeyOffsetX = "offsetX";
std::string kFCKeyOffsetY = "offsetY";
std::string kFCKeyOffsetZ = "offsetZ";
std::string kFCKeyRotation = "rotation";
std::string kFCKeyRotationX = "rotationX";
std::string kFCKeyRotationY = "rotationY";
std::string kFCKeyRotationZ = "rotationZ";
std::string kFCKeyAngle = "angle";
std::string kFCKeyRadius = "radius";
std::string kFCKeyShape = "shape";
std::string kFCKeyCircle = "circle";
std::string kFCKeyRectangle = "rectangle";
std::string kFCKeyBox = "box";
std::string kFCKeyXSize = "xSize";
std::string kFCKeyYSize = "ySize";
std::string kFCKeyZSize = "zSize";
std::string kFCKeyHull = "hull";
std::string kFCKeyPolygon = "polygon";
std::string kFCKeyLinearDamping = "lineardamping";
std::string kFCKeyDynamic = "dynamic";
std::string kFCKeyColor = "color";
std::string kFCKeyRed = "red";
std::string kFCKeyGreen = "green";
std::string kFCKeyBlue = "blue";
std::string kFCKeyYellow = "yellow";
std::string kFCKeyWhite = "white";
std::string kFCKeyCount = "count";
// Graphics
std::string kFCKeyShaderWireframe = "wireframe";
std::string kFCKeyShaderDebug = "debug";
std::string kFCKeyShaderFlatUnlit = "flatunlit";
std::string kFCKeyShaderNoTexVLit = "notex_vlit";
std::string kFCKeyShaderNoTexPLit = "notex_plit";
std::string kFCKeyShader1TexVLit = "1tex_vlit";
std::string kFCKeyShader1TexPLit = "1tex_plit";
std::string kFCKeyShaderTest = "test";
std::string kFCKeyDiffuseColor = "diffusecolor";
// File types
std::string kFCKeyPNG = "png";
std::string kFCKeyVertexFormat = "vertexformat";
std::string kFCKeyVertexPosition = "vertexposition";
std::string kFCKeyVertexNormal = "vertexnormal";
std::string kFCKeyVertexTexCoord0 = "vertextexcoord0";
std::string kFCKeyVertexBuffer = "vertexbuffer";
std::string kFCKeyIndexBuffer = "indexbuffer";
std::string kFCKeyNormalArray = "normalarray";
std::string kFCKeyVertexArray = "vertexarray";
std::string kFCKeyTexcoord0Array = "texcoord0array";
std::string kFCKeyTexcoord1Array = "texcoord1array";
std::string kFCKeyTexcoord2Array = "texcoord2array";
std::string kFCKeyTexcoord3Array = "texcoord3array";
std::string kFCKeyIndexArray = "indexarray";
std::string kFCKeyMaterialDiffuseColor = "materialdiffusecolor";
std::string kFCKeyMaterialDiffuseTexture = "materialdiffusetexture";
std::string kFCKeyShader = "shader";
std::string kFCKeyShaderProgramName = "shaderprogramname";
std::string kFCKeyStride = "stride";
std::string kFCKeyVersion = "version";
std::string kFCKeyInput = "input";
std::string kFCKeyOutput = "output";
std::string kFCKeyBinaryPayload = "binarypayload";
std::string kFCKeyTextures = "textures";
std::string kFCKeyGameplay = "gameplay";
std::string kFCKeyGame = "game";
std::string kFCKeyModels = "models";
std::string kFCKeyBuffers = "buffers";
std::string kFCKeyMesh = "mesh";
std::string kFCKeyCamera = "camera";
// Caps
std::string kFCDeviceTrue = "true";
std::string kFCDeviceFalse = "false";
std::string kFCDevicePresent = "present";
std::string kFCDeviceNotPresent = "not present";
std::string kFCDeviceUnknown = "unknown";
std::string kFCDevicePlatformiOS = "iOS";
std::string kFCDevicePlatformOSX = "OSX";
std::string kFCDevicePlatformWindows8 = "Windows8";
std::string kFCDevicePlatformAndroid = "Android";
//------- keys
std::string kFCDeviceDisplayAspectRatio = "display_aspect_ratio";
std::string kFCDeviceDisplayLogicalXRes = "display_logical_xres";
std::string kFCDeviceDisplayLogicalYRes = "display_logical_yres";
std::string kFCDeviceDisplayPhysicalXRes = "display_physical_xres";
std::string kFCDeviceDisplayPhysicalYRes = "display_physical_yres";
std::string kFCDeviceDisplayScale = "display_scale";
std::string kFCDeviceHardwareModelID = "hardware_model_id";
std::string kFCDeviceHardwareModel = "hardware_model";
std::string kFCDeviceHardwareUDID = "hardware_udid";
std::string kFCDeviceHardwareName = "hardware_name";
std::string kFCDeviceLocale = "locale";
std::string kFCDeviceOSVersion = "os_version";
std::string kFCDeviceOSName = "os_name";
std::string kFCDeviceOSGameCenter = "os_gamecenter";
std::string kFCDevicePlatform = "platform";
std::string kFCDeviceSimulator = "simulator";
std::string kFCDeviceAppPirated = "pirated";
std::string kFCDeviceGameCenterID = "gamecenterid";
| 37.285714 | 78 | 0.771436 | [
"mesh",
"shape",
"model"
] |
93e5b6c1523655e5c395e529eec68f4cdf762738 | 1,016 | hpp | C++ | third_party/boost/simd/function/cumsum.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/function/cumsum.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/function/cumsum.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_CUMSUM_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_CUMSUM_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-reduction
This function object returns the cumulate sum of the argument elements
@par Header <boost/simd/function/cumsum.hpp>
@see cumprod, cummin, cummax
@par Example:
@snippet cumsum.cpp cumsum
@par Possible output:
@snippet cumsum.txt cumsum
**/
Value cumsum(Value const& x);
} }
#endif
#include <boost/simd/function/scalar/cumsum.hpp>
#include <boost/simd/function/simd/cumsum.hpp>
#endif
| 23.627907 | 100 | 0.583661 | [
"object"
] |
93eba84053d1a718fcab2c8867edf40bc7336d0e | 1,735 | cpp | C++ | matog/util/ml/None.cpp | mergian/matog | d03de27b92a0772ceac1c556293217ff91d405eb | [
"BSD-3-Clause"
] | 1 | 2021-06-10T13:09:57.000Z | 2021-06-10T13:09:57.000Z | matog/util/ml/None.cpp | mergian/matog | d03de27b92a0772ceac1c556293217ff91d405eb | [
"BSD-3-Clause"
] | null | null | null | matog/util/ml/None.cpp | mergian/matog | d03de27b92a0772ceac1c556293217ff91d405eb | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2015 Nicolas Weber / GCC / TU-Darmstadt. All rights reserved.
// Use of this source code is governed by the BSD 3-Clause license that can be
// found in the LICENSE file.
#include <matog/util/ml/None.h>
#include <matog/util/ml/Type.h>
#include <matog/util/Mem.h>
#include <matog/log.h>
#include <sstream>
#include <map>
namespace matog {
namespace util {
namespace ml {
//-------------------------------------------------------------------
None::None(void) : Model(Type::NONE), m_value(0) {
}
//-------------------------------------------------------------------
None::~None(void) {
}
//-------------------------------------------------------------------
uint32_t None::predict(const float*) const {
return m_value;
}
//-------------------------------------------------------------------
blob None::save(void) const {
uint32_t* ptr = NEW_A(uint32_t, 1);
ptr[0] = m_value;
return blob(ptr, sizeof(uint32_t));
}
//-------------------------------------------------------------------
void None::train(const float* input, const int32_t* output, const int cols, const int rows, const uint32_t* counts) {
std::map<int32_t, uint32_t> tmp;
for(int i = 0; i < rows; i++) {
tmp[output[i]] += counts[i];
}
int maxValue = 0;
uint32_t maxCount = 0;
for(const auto& it : tmp) {
if(it.second > maxCount || (it.second == maxCount && it.first < maxValue)) {
maxValue = it.first;
maxCount = it.second;
}
}
m_value = maxValue;
}
//-------------------------------------------------------------------
void None::load(const blob model) {
assert(model.size == sizeof(uint32_t));
m_value = ((uint32_t*)model.ptr)[0];
}
//-------------------------------------------------------------------
}
}
} | 26.692308 | 117 | 0.473775 | [
"model"
] |
93ede0095243b4bfad6bfffc3f1708bd3610eab3 | 1,818 | cpp | C++ | 2020codes/codeforces/1291/B - Array Sharpening.cpp | TieWay59/HappyACEveryday | 6474a05a9eafc83e9c185ba8e6d716f7d44eade0 | [
"MIT"
] | 3 | 2019-08-27T19:38:23.000Z | 2020-10-08T17:47:21.000Z | 2020codes/codeforces/1291/B - Array Sharpening.cpp | TieWay59/HappyACEveryday | 6474a05a9eafc83e9c185ba8e6d716f7d44eade0 | [
"MIT"
] | 15 | 2019-08-27T18:15:58.000Z | 2019-09-28T03:28:05.000Z | 2020codes/codeforces/1291/B - Array Sharpening.cpp | TieWay59/HappyACEveryday | 6474a05a9eafc83e9c185ba8e6d716f7d44eade0 | [
"MIT"
] | 1 | 2020-09-19T22:11:15.000Z | 2020-09-19T22:11:15.000Z | /**
* █████╗ ██████╗ ██████╗ ██╗ ███████╗
* ██╔══██╗██╔════╝ ██╔══██╗██║ ╚══███╔╝
* ███████║██║ ██████╔╝██║ ███╔╝
* ██╔══██║██║ ██╔═══╝ ██║ ███╔╝
* ██║ ██║╚██████╗▄█╗ ██║ ███████╗███████╗
* ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚══════╝╚══════╝
*
* @Author: TieWay59
* @Created: 2020/2/3 2:08
* @Link: https://codeforces.com/contest/1291/problem/B
* @Tags:
*
*******************************************************/
#include <bits/stdc++.h>
#ifdef DEBUG
# include "libs59/debugers.h"
// #define debug(x) cerr <<#x << " = "<<x<<endl;
#else
# define endl '\n'
# define debug(...)
#endif
#define STOPSYNC ios::sync_with_stdio(false);cin.tie(nullptr)
#define MULTIKASE int Kase=0;cin>>Kase;for(int kase=1;kase<=Kase;kase++)
typedef long long ll;
const int MAXN = 2e5 + 59;
const int MOD = 1e9 + 7;
const int INF = 0x3F3F3F3F;
const ll llINF = 0x3F3F3F3F3F3F3F3F;
using namespace std;
void solve(int kaseId = -1) {
int n;
cin >> n;
vector<int> a(n);
vector<bool> b(n, false);
vector<bool> c(n, false);
for (auto &ai:a) {
cin >> ai;
}
for (int i = 0; i < n; ++i) {
if (a[i] >= i) {
b[i] = true;
}
if (a[i] >= n - 1 - i) {
c[i] = true;
}
}
int i, j;
for (i = 0; i < n; ++i) {
if (b[i] == false) {
i--;
break;
}
}
for (j = n - 1; j >= 0; --j) {
if (c[j] == false) {
j++;
break;
}
}
if (i < j) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
}
void solves() {
MULTIKASE {
solve(kase);
}
}
int main() {
STOPSYNC;
solves();
return 0;
}
/*
*/ | 19.548387 | 72 | 0.360286 | [
"vector"
] |
93ee7e9903f297e36acab922a3b7fbcd53a8e805 | 11,882 | cpp | C++ | src/mac_time_tracker.cpp | yoshito-n-students/mac_time_tracker | 0532b0c71635bad343ae06b09818156024ff39f5 | [
"MIT"
] | null | null | null | src/mac_time_tracker.cpp | yoshito-n-students/mac_time_tracker | 0532b0c71635bad343ae06b09818156024ff39f5 | [
"MIT"
] | null | null | null | src/mac_time_tracker.cpp | yoshito-n-students/mac_time_tracker | 0532b0c71635bad343ae06b09818156024ff39f5 | [
"MIT"
] | null | null | null | #include <chrono>
#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp> // for parse_command_line()
#include <boost/program_options/value_semantic.hpp> // for value<>() and bool_swich()
#include <boost/program_options/variables_map.hpp> // for variables_map, store() and notify()
#include <mac_time_tracker/address.hpp>
#include <mac_time_tracker/address_map.hpp>
#include <mac_time_tracker/period_map.hpp>
#include <mac_time_tracker/set.hpp>
#include <mac_time_tracker/time.hpp>
namespace mtt = mac_time_tracker;
////////////////////////
// Command line options
struct Parameters {
std::string known_addr_csv, tracked_addr_html_in;
std::vector<std::string> tracked_addr_csv_fmts, tracked_addr_html_fmts;
std::string arp_scan_options;
std::chrono::minutes scan_interval, track_interval, max_fill;
bool verbose;
// Get parameters from command line args.
// If help is requested via command line, non-empty help_msg is also provided.
static Parameters fromCommandLine(const int argc, const char *const argv[],
std::string *const help_msg) {
namespace bpo = boost::program_options;
Parameters params;
bool help;
// define command line options
bpo::options_description arg_desc(
"mac_time_tracker",
/* line length in help msg = */ bpo::options_description::m_default_line_length,
/* desc length in help msg = */ bpo::options_description::m_default_line_length * 6 / 10);
static const std::string default_tracked_addr_csv_fmt =
"tracked_addresses_%Y-%m-%d-%H-%M-%S.csv",
default_tracked_addr_html_fmt =
"tracked_addresses_%Y-%m-%d-%H-%M-%S.html";
arg_desc.add_options()
// key, correspinding variable, description
("known-addr-csv", bpo::value(¶ms.known_addr_csv)->default_value("known_addresses.csv"),
"path to input .csv file that contains known MAC addresses\n"
" format: <addr>, <category>, <description>\n"
" ex.: 00:11:22:33:44:55, John Doe, PC\n"
" 66:77:88:99:AA:BB, John Doe, Phone\n"
" CC:DD:EE:FF:00:11, Jane Smith, Tablet") //
("tracked-addr-csv",
bpo::value(¶ms.tracked_addr_csv_fmts)
->default_value(std::vector<std::string>(1, default_tracked_addr_csv_fmt),
default_tracked_addr_csv_fmt)
->multitoken()
->zero_tokens(),
"path(s) to output .csv file that contains tracked MAC addresses."
" will be formatted by std::put_time().") //
("tracked-addr-html-in",
bpo::value(¶ms.tracked_addr_html_in)->default_value("tracked_addresses.html.in"),
"path to input .html file that will be used as a template") //
("tracked-addr-html",
bpo::value(¶ms.tracked_addr_html_fmts)
->default_value(std::vector<std::string>(1, default_tracked_addr_html_fmt),
default_tracked_addr_html_fmt)
->multitoken()
->zero_tokens(),
"path(s) to output .html file. will be formatted by std::put_time().") //
("arp-scan-options",
bpo::value(¶ms.arp_scan_options)->default_value(mtt::Set::defaultOptions()),
"options for arp-scan") //
("scan-interval",
bpo::value<unsigned int>()->default_value(5)->notifier([¶ms](const unsigned int val) {
params.scan_interval = std::chrono::minutes(val);
}),
"interval between MAC address scans in minutes") //
("track-interval",
bpo::value<unsigned int>()
->default_value(60 * 24, "60 * 24")
->notifier([¶ms](const unsigned int val) {
params.track_interval = std::chrono::minutes(val);
}),
"interval to rotate output .csv and .html files in minutes") //
("max-fill",
bpo::value<unsigned int>()->default_value(60)->notifier(
[¶ms](const unsigned int val) { params.max_fill = std::chrono::minutes(val); }),
"fill empty slots on .html equal to or less than this value in minutes") //
("verbose,v", bpo::bool_switch(¶ms.verbose), "verbose console output") //
("help,h", bpo::bool_switch(&help), "print help message");
// parse command line args
bpo::variables_map arg_map;
bpo::store(bpo::parse_command_line(argc, argv, arg_desc), arg_map);
bpo::notify(arg_map);
// return results
*help_msg = help ? boost::lexical_cast<std::string>(arg_desc) : std::string("");
return params;
}
};
///////////////////
// Console outputs
void printKnownAddresses(std::ostream &os, const std::string &filename,
const mtt::AddressMap &known_addrs) {
if (!known_addrs.empty()) {
os << "Known addresses from '" << filename << "'" << std::endl;
for (const mtt::AddressMap::value_type &entry : known_addrs) {
os << " " << entry.first << " ('" << entry.second.category << "' > '"
<< entry.second.description << "')" << std::endl;
}
} else {
os << "No known addresses from '" << filename << "'" << std::endl;
}
}
void printTrackedAddresses(std::ostream &os, const mtt::PeriodMap &tracked_addrs,
const mtt::PeriodMap::Period &period) {
const std::pair<mtt::PeriodMap::const_iterator, mtt::PeriodMap::const_iterator> range =
tracked_addrs.equal_range(period);
if (range.first != range.second) {
os << "Tracked addresses" << std::endl;
for (mtt::PeriodMap::const_iterator it = range.first; it != range.second; ++it) {
os << " " << it->second.address << " ('" << it->second.category << "' > '"
<< it->second.description << "')" << std::endl;
}
} else {
os << "No tracked addresses" << std::endl;
}
}
//////////
// String
std::string readFile(const std::string &filename) {
std::ifstream ifs(filename);
if (!ifs) {
throw std::runtime_error("Cannot open '" + filename + "' to read");
}
return std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
std::vector<std::string> format(const mtt::Time &formatter, const std::vector<std::string> &exprs) {
std::vector<std::string> formatted;
for (const std::string &expr : exprs) {
formatted.push_back(formatter.toStr(expr));
}
return formatted;
}
///////////////
// Time period
// returns a time point representing today's 0:00 am
// that can be used as a reasonable base time for findPresentPeriod()
mtt::Time getLocal0AMToday() {
const std::time_t ut_now = std::time(NULL); // now in the universal time
std::tm *const lt_0am = std::localtime(&ut_now); // 0:00 am in the local time
lt_0am->tm_hour = lt_0am->tm_min = lt_0am->tm_sec = 0;
return mtt::Time(std::chrono::seconds(std::mktime(lt_0am)));
}
// returns a present period p that meets (p.first <= now < p.second)
// where (p.first = base + n * interval) and (p.second = p.first + interval).
// i.e. returns {5:00, 6:00} if now is 5:10 and interval is 60 minutes,
// or {10:20, 10:30} if now is 10:21 and interval is 10 minutes.
mtt::PeriodMap::Period findPresentPeriod(const mtt::Time &base,
const std::chrono::minutes &interval) {
const mtt::Time now = mtt::Time::now();
const int n = (now - base) / interval;
if (now >= base) {
// <---- period ---->
// --@-------------------@========@=======@----------->
// base base + n*i now base + (n+1)*i
return {base + n * interval, base + (n + 1) * interval};
} else {
// <---- period ---->
// --------@==========@=====@-------------------@----->
// base + (n-1)*i now base + n*i base
return {base + (n - 1) * interval, base + n * interval};
}
}
////////
// Main
int main(int argc, char *argv[]) {
// Parse command line args
std::string help_msg;
const Parameters params = Parameters::fromCommandLine(argc, argv, &help_msg);
if (!help_msg.empty()) {
std::cout << help_msg << std::endl;
return 0;
}
// Tracking loop (never returns)
const mtt::Time base_time = getLocal0AMToday();
for (int i_track = 0;; ++i_track) {
// Constants and storage for this tracking period
const mtt::PeriodMap::Period track_period = findPresentPeriod(base_time, params.track_interval);
const std::vector<std::string> tracked_addr_csvs =
format(track_period.first, params.tracked_addr_csv_fmts); // output .csv filenames
const std::vector<std::string> tracked_addr_htmls =
format(track_period.first, params.tracked_addr_html_fmts); // output .html filenames
mtt::PeriodMap tracked_addrs; // storage
if (params.verbose) {
std::cout << "Tracking period #" << i_track << "\n"
<< " start: " << track_period.first << "\n"
<< " end: " << track_period.second << "\n"
<< " output: (csv) " << boost::algorithm::join(tracked_addr_csvs, ", ") << "\n"
<< " (html) " << boost::algorithm::join(tracked_addr_htmls, ", ")
<< std::endl;
}
// Step 1: Load known addresses and a template of output .html from files
mtt::AddressMap known_addrs;
std::string tracked_addr_html_in;
try {
known_addrs = mtt::AddressMap::fromFile(params.known_addr_csv);
if (params.verbose) {
printKnownAddresses(std::cout, params.known_addr_csv, known_addrs);
}
if (!tracked_addr_htmls.empty()) {
tracked_addr_html_in = readFile(params.tracked_addr_html_in);
}
} catch (const std::exception &err) {
std::cerr << err.what() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
// Scanning loop that will repeat until the end of this tracking period
for (int i_scan = 0; mtt::Time::now() < track_period.second; ++i_scan) {
// Constants for this scanning period
const mtt::PeriodMap::Period scan_period = findPresentPeriod(base_time, params.scan_interval);
if (params.verbose) {
std::cout << "Scanning period #" << i_track << "." << i_scan << "\n"
<< " start: " << scan_period.first << "\n"
<< " end: " << scan_period.second << std::endl;
}
try {
// Step 2: Scan addresses in network and match them to the known addresses
const mtt::Set present_addrs = mtt::Set::fromARPScan(params.arp_scan_options);
for (const mtt::Address &addr : present_addrs) {
const mtt::AddressMap::const_iterator it = known_addrs.find(addr);
if (it != known_addrs.end()) {
tracked_addrs.insert(
{scan_period, {addr, it->second.category, it->second.description}});
}
}
if (params.verbose) {
printTrackedAddresses(std::cout, tracked_addrs, scan_period);
}
// Step 3: Save scan results
for (const std::string &csv : tracked_addr_csvs) {
tracked_addrs.toFile(csv);
}
const mtt::PeriodMap filled = tracked_addrs.filled(params.max_fill);
for (const std::string &html : tracked_addr_htmls) {
filled.toHTML(html, tracked_addr_html_in);
}
} catch (const std::exception &err) {
std::cerr << err.what() << std::endl;
}
// Step 4: Sleep until the next scanning period
std::this_thread::sleep_until(scan_period.second);
}
}
return 0;
} | 42.587814 | 100 | 0.600741 | [
"vector"
] |
93fe2d749f2d8669ebe462118e2abc7335cc752d | 5,862 | cpp | C++ | 3rdparty/meshlab-master/src/plugins_unsupported/render_rfx/rfx_uniform.cpp | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/meshlab/src/meshlabplugins/render_rfx/rfx_uniform.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/meshlab/src/meshlabplugins/render_rfx/rfx_uniform.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* MeshLab o o *
* A versatile mesh processing toolbox o o *
* _ O _ *
* Copyright(C) 2005-2008 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include "rfx_uniform.h"
RfxUniform::RfxUniform(const QString &_name, const QString &_type)
{
value = NULL;
identifier = _name;
type = GetUniformType(_type);
textureLoaded = false;
textureNotFound = false;
textureRendered = false;
_isRmColorVariable = false;
minVal = 0.0;
maxVal = 0.0;
}
RfxUniform::~RfxUniform()
{
if (value) {
if (type == INT || type == BOOL || type == FLOAT)
delete value;
else
delete[] value;
}
// render targets are deleted by rfx_shader
if (textureLoaded && !textureRendered)
glDeleteTextures(1, &textureId);
}
void RfxUniform::UpdateUniformLocation(GLuint programId)
{
location = glGetUniformLocation(programId, identifier.toLocal8Bit().data());
}
// static member initialization
const char *RfxUniform::UniformTypeString[] = {
"int", "float", "bool",
"vec2", "vec3", "vec4",
"ivec2", "ivec3", "ivec4",
"bvec2", "bvec3", "bvec4",
"mat2", "mat3", "mat4",
"sampler1D", "sampler2D", "sampler3D", "samplerCube",
"sampler1DShadow", "sampler2DShadow"
};
RfxUniform::UniformType RfxUniform::GetUniformType(const QString& stringType)
{
int i;
for (i = 0; i < TOTAL_TYPES; ++i) {
if (stringType == UniformTypeString[i])
break;
}
return (UniformType)i;
}
void RfxUniform::SetValue(float _value[16])
{
switch (type) {
case INT:
case BOOL:
case FLOAT:
value = new float;
*value = _value[0];
break;
case VEC2:
case IVEC2:
case BVEC2:
value = new float[2];
memcpy(value, _value, sizeof(float) * 2);
break;
case VEC3:
case IVEC3:
case BVEC3:
value = new float[3];
memcpy(value, _value, sizeof(float) * 3);
break;
case VEC4:
case IVEC4:
case BVEC4:
case MAT2:
value = new float[4];
memcpy(value, _value, sizeof(float) * 4);
break;
case MAT3:
value = new float[9];
memcpy(value, _value, sizeof(float) * 9);
break;
case MAT4:
value = new float[16];
memcpy(value, _value, sizeof(float) * 16);
break;
default:
break;
}
}
void RfxUniform::SetValue(const QString &texFileName)
{
textureFile = texFileName;
}
void RfxUniform::LoadTexture()
{
if (textureRendered) {
textureNotFound = false;
textureLoaded = true;
textureTarget = GL_TEXTURE_2D;
return;
}
if (!QFileInfo(textureFile).exists()) {
textureNotFound = true;
return;
} else {
textureNotFound = false;
}
switch (type) {
case SAMPLER2D:
textureTarget = GL_TEXTURE_2D;
break;
case SAMPLER3D:
textureTarget = GL_TEXTURE_3D;
break;
case SAMPLERCUBE:
textureTarget = GL_TEXTURE_CUBE_MAP;
break;
default:
return;
}
glGetIntegerv(GL_MAX_TEXTURE_COORDS, &maxTexUnits);
textureLoaded = (RfxTextureLoader::LoadTexture(textureFile,
textureStates,
&textureId)
&& texUnit < maxTexUnits);
}
void RfxUniform::PassToShader()
{
switch (type) {
case INT:
case BOOL:
glUniform1i(location, (GLint)*value);
break;
case FLOAT:
glUniform1f(location, *value);
break;
case IVEC2:
case BVEC2:
glUniform2i(location, (GLint)value[0], (GLint)value[1]);
break;
case VEC2:
glUniform2f(location, value[0], value[1]);
break;
case IVEC3:
case BVEC3:
glUniform3i(location, (GLint)value[0], (GLint)value[1], (GLint)value[2]);
break;
case VEC3:
glUniform3f(location, value[0], value[1], value[2]);
break;
case IVEC4:
case BVEC4:
glUniform4i(location, (GLint)value[0], (GLint)value[1], (GLint)value[2], (GLint)value[3]);
break;
case VEC4:
glUniform4f(location, value[0], value[1], value[2], value[3]);
break;
case MAT2:
glUniformMatrix2fv(location, 1, GL_FALSE, value);
break;
case MAT3:
glUniformMatrix3fv(location, 1, GL_FALSE, value);
break;
case MAT4:
glUniformMatrix4fv(location, 1, GL_FALSE, value);
break;
case SAMPLER2D:
case SAMPLER3D:
case SAMPLERCUBE:
if (textureLoaded) {
if (textureRendered)
textureId = rTarget->GetTexture();
glActiveTexture(GL_TEXTURE0 + texUnit);
glBindTexture(textureTarget, textureId);
glUniform1i(location, texUnit);
}
break;
default:
qDebug("don't know what to do with %s", UniformTypeString[type]);
}
}
| 24.02459 | 92 | 0.562607 | [
"mesh",
"render"
] |
93fe7a4a8ec7549da5017f247099eb78bf7e91db | 2,395 | cxx | C++ | direct/src/distributed/config_distributed.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | direct/src/distributed/config_distributed.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | direct/src/distributed/config_distributed.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: config_distributed.cxx
// Created by: drose (19May04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_distributed.h"
#include "dconfig.h"
Configure(config_distributed);
NotifyCategoryDef(distributed, "");
ConfigureFn(config_distributed) {
init_libdistributed();
}
ConfigVariableInt game_server_timeout_ms
("game-server-timeout-ms", 20000,
PRC_DESC("This represents the amount of time to block waiting for the TCP "
"connection to the game server. It is only used when the connection "
"method is NSPR."));
ConfigVariableDouble min_lag
("min-lag", 0.0,
PRC_DESC("This represents the time in seconds by which to artificially lag "
"inbound messages. It is useful to test a game's tolerance of "
"network latency."));
ConfigVariableDouble max_lag
("max-lag", 0.0,
PRC_DESC("This represents the time in seconds by which to artificially lag "
"inbound messages. It is useful to test a game's tolerance of "
"network latency."));
ConfigVariableBool handle_datagrams_internally
("handle-datagrams-internally", true,
PRC_DESC("When this is true, certain datagram types can be handled "
"directly by the C++ cConnectionRepository implementation, "
"for performance reasons. When it is false, all datagrams "
"are handled by the Python implementation."));
////////////////////////////////////////////////////////////////////
// Function: init_libdistributed
// Description: Initializes the library. This must be called at
// least once before any of the functions or classes in
// this library can be used. Normally it will be
// called by the static initializers and need not be
// called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libdistributed() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
}
| 35.220588 | 80 | 0.619207 | [
"3d"
] |
9e05d35ee86cf07924f84c23748f2683dd5e6c13 | 10,866 | cpp | C++ | src/main.cpp | lukapozega/FinalThesis | 6e7f9784b0d0335a9be48f836489de27f0751bd1 | [
"MIT"
] | null | null | null | src/main.cpp | lukapozega/FinalThesis | 6e7f9784b0d0335a9be48f836489de27f0751bd1 | [
"MIT"
] | null | null | null | src/main.cpp | lukapozega/FinalThesis | 6e7f9784b0d0335a9be48f836489de27f0751bd1 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <tuple>
#include <algorithm>
#include <unordered_map>
#include "Config.h"
#include "bioparser/bioparser.hpp"
#include "PAFObject.cpp"
#include "FASTAQObject.cpp"
#include "repeats_parser.h"
struct option options[] = {
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
std::unordered_map<char, char> complement_map = {
{'A', 'T'},
{'T', 'A'},
{'G', 'C'},
{'C', 'G'},
};
class Vertex {
public:
PAFObject read;
std::vector<Vertex*> vertices;
Vertex* parent = NULL;
Vertex(PAFObject read) : read(read) {
this->read = read;
}
};
void add_breakpoints(std::vector<std::unique_ptr<PAFObject>> &paf_objects, std::vector<std::tuple<std::string, int, int>> &repeats) {
std::vector<std::unique_ptr<PAFObject>>::iterator it = paf_objects.begin();
std::vector<std::unique_ptr<PAFObject>>::iterator to_remove;
while (it != paf_objects.end()) {
for (auto const& r : repeats) {
if ((*it)->t_begin > std::get<1>(r) && (*it)->t_end < std::get<2>(r)) {
to_remove = it++;
(*to_remove) = NULL;
if (it == paf_objects.end()) {
paf_objects.erase(std::remove_if(paf_objects.begin(), paf_objects.end(), [](std::unique_ptr<PAFObject> &p) {return p == NULL;}), paf_objects.end());
return;
}
}
}
it++;
}
paf_objects.erase(std::remove_if(paf_objects.begin(), paf_objects.end(), [](std::unique_ptr<PAFObject> &p) {return p == NULL;}), paf_objects.end());
}
std::unordered_map<std::string, std::vector<Vertex*>> create_graph(std::vector<Vertex> &vertices, std::vector<std::unique_ptr<PAFObject>> &paf_objects) {
for (auto const& paf: paf_objects) {
vertices.emplace_back(Vertex(*paf));
}
std::vector<Vertex>::iterator it = vertices.begin();
std::vector<Vertex>::iterator next;
std::vector<Vertex*> heads;
std::unordered_map<std::string, std::vector<Vertex*>> re;
heads.emplace_back(&(*it));
while(it != --vertices.end()) {
next = std::next(it);
if ((*next).read.t_name != (*it).read.t_name) {
re[(*it).read.t_name] = heads;
heads.clear();
heads.emplace_back(&(*next));
it++;
continue;
}
while ((*next).read.t_begin <= (*it).read.t_end && (*next).read.t_name == (*it).read.t_name) {
it->vertices.emplace_back(&(*next));
next++;
if(next == vertices.end()) break;
}
if (next == std::next(it)){
heads.emplace_back(&(*next));
}
it++;
}
re[(*it).read.t_name] = heads;
heads.clear();
FILE* file = fopen ("network.gfa","w");
for (auto const& vertex : vertices) {
fprintf (file, "S\t%s\t%c\tLN:i:%u\n", vertex.read.q_name.c_str(), '*', vertex.read.q_length);
for (auto const& next: vertex.vertices) {
fprintf (file, "L\t%s\t%c\t%s\t%c\t%c\n", vertex.read.q_name.c_str(), vertex.read.orientation, next->read.q_name.c_str(), next->read.orientation, '*');
}
}
fclose (file);
return re;
}
std::vector<Vertex*> DepthFirstSearch(std::unordered_map<std::string, std::vector<Vertex*>> heads) {
Vertex* max;
Vertex* head;
Vertex* longest;
std::vector<Vertex*> ends;
int begin;
for (auto const& seq: heads) {
int length=0;
for (int i = 0; i < seq.second.size(); i++) {
head = seq.second[i];
begin = head->read.t_begin;
while(!head->vertices.empty()) {
max = head->vertices[0];
for (auto const& vertex : head->vertices) {
if (vertex->read.t_begin > max->read.t_begin) max = vertex;
}
max->parent = head;
head = max;
}
if (length < head->read.t_begin - begin) {
length = head->read.t_begin - begin;
longest = head;
}
}
ends.emplace_back(longest);
}
return ends;
}
bool paf_unique(const std::unique_ptr<PAFObject>& a, const std::unique_ptr<PAFObject>& b) {
return a->q_name == b->q_name;
}
void clear_contained_reads(std::vector<std::unique_ptr<PAFObject>> &paf_objects) {
auto long_cmp = [](const std::unique_ptr<PAFObject>& a, const std::unique_ptr<PAFObject>& b) {
if (a->q_name == b->q_name) {
return (a->t_end - a->t_begin > b->t_end - b->t_begin);
}
return (a->q_name > b->q_name);
};
std::sort(paf_objects.begin(), paf_objects.end(), long_cmp);
std::vector<std::unique_ptr<PAFObject>>::iterator it = paf_objects.begin();
it = std::unique (paf_objects.begin(), paf_objects.end(), paf_unique);
paf_objects.resize(std::distance(paf_objects.begin(), it));
paf_objects.erase(std::remove_if(paf_objects.begin(), paf_objects.end(), [](std::unique_ptr<PAFObject> &p){return p->q_end - p->q_begin < 0.9 * p->q_length;}), paf_objects.end());
auto paf_cmp = [](const std::unique_ptr<PAFObject>& a, const std::unique_ptr<PAFObject>& b) {
if (a->t_name == b->t_name) {
if (a->t_begin == b->t_begin) {
return (a->t_end > b->t_end);
}
return (a->t_begin < b->t_begin);
}
return (a->t_name > b->t_name);
};
std::sort(paf_objects.begin(), paf_objects.end(), paf_cmp);
it = paf_objects.begin();
std::vector<std::unique_ptr<PAFObject>>::iterator next;
std::vector<std::unique_ptr<PAFObject>>::iterator to_remove;
while (it != --paf_objects.end()) {
do {
next = std::next(it);
} while ((*next) == NULL && (*next)->t_name == (*it)->t_name);
while ((*next)->t_end <= (*it)->t_end && (*next)->t_name == (*it)->t_name) {
to_remove = next;
do {
next++;
} while ((*next) == NULL && next != paf_objects.end());
(*to_remove) = NULL;
if(next == paf_objects.end()) {
paf_objects.erase(std::remove_if(paf_objects.begin(), paf_objects.end(), [](std::unique_ptr<PAFObject> &p) {return p == NULL;}), paf_objects.end());
return;
}
}
it = next;
}
paf_objects.erase(std::remove_if(paf_objects.begin(), paf_objects.end(), [](std::unique_ptr<PAFObject> &p) {return p == NULL;}), paf_objects.end());
}
bool file_format(const std::string &str, const std::string &suffix) {
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
std::string complement(std::string const &sequence){
std::string comp = "";
for (char const & c : sequence) {
comp = complement_map.at(c) + comp;
}
return comp;
}
void statistics(std::vector<Vertex*> ends, std::vector<std::unique_ptr<FASTAQEntity>> & ref_objects, std::string const &file_path) {
std::vector<std::unique_ptr<FASTAQEntity>> reads;
if (file_format(file_path, ".fastq") || file_format(file_path, ".fastq.gz")) {
auto reads_parser = bioparser::createParser<bioparser::FastqParser, FASTAQEntity>(file_path);
reads_parser->parse(reads, -1);
} else {
auto reads_parser = bioparser::createParser<bioparser::FastaParser, FASTAQEntity>(file_path);
reads_parser->parse(reads, -1);
}
std::string part;
printf("Writing to files...\n\n");
FILE* file = fopen ("used_reads.txt","w");
FILE* genome = fopen ("genome.fasta","w");
int startIndex, endIndex, last_index, overlap, used_reads;
std::string seq;
Vertex* curr;
for (auto const& end : ends) {
startIndex = end->read.q_begin;
endIndex = end->read.q_end;
last_index = end->read.t_end;
overlap = 0;
used_reads = 0;
curr = end;
fprintf (genome, ">%s\n", end->read.t_name.c_str());
while (curr->parent != NULL) {
used_reads++;
for (auto const& r : reads) {
if (r->name == curr->read.q_name) {
if (curr->read.orientation == '+') {
seq = complement(r->sequence);
} else {
seq = r->sequence;
}
part.assign(seq, startIndex + overlap, endIndex - (startIndex + overlap));
break;
}
}
fprintf (genome, "%s", part.c_str());
endIndex = curr->read.q_begin;
fprintf (file, "%s %s %d %d\n", curr->read.q_name.c_str(), curr->read.t_name.c_str(), curr->read.t_begin, curr->read.t_end);
overlap = curr->read.t_begin;
curr = curr->parent;
overlap = curr->read.t_end - overlap;
startIndex = curr->read.q_begin;
}
fprintf(genome, "\n");
printf("%s coverage: %f%%\n", end->read.t_name.c_str(), (last_index-curr->read.t_begin) / (float) curr->read.t_length * 100);
printf("Number of used reads: %d\n",used_reads);
}
fclose (file);
fclose (genome);
}
void help() {
std::cout <<
"usage: assembly [options ...] <overlaps> <reference> <repeats> <sequences>\n"
"\n"
" <overlaps>\n"
" input file in PAF format (can be compressed with gzip)\n"
" containing overlaps between sequences and reference\n"
" <reference>\n"
" input file in FASTA/FASTQ format (can be compressed with gzip)\n"
" containing the reference genome\n"
" <repeats>\n"
" input file in format generated by RED tool\n"
" <sequences>\n"
" input file in FASTA/FASTQ format (can be compressed with gzip)\n"
" containing third generation sequences\n"
"\n"
" options:\n"
" -v, --version\n"
" prints the version number\n"
" -h, --help\n"
" prints the usage\n";
}
void version() {
printf("Version %d.%d\n", assembly_VERSION_MAJOR, assembly_VERSION_MINOR);
}
int main(int argc, char** argv) {
char optchr;
int option_index = 0;
while((optchr = getopt_long(argc, argv, "hv", options, &option_index)) != -1) {
switch (optchr) {
case 'h': {
help();
return 1;
}
case 'v': {
version();
return 1;
}
default: {
fprintf(stderr, "Unknown option -%c\n", optchr);
return 1;
}
}
}
if(argc - optind != 4) {
fprintf(stderr, "Program requires four arguments.\n");
fprintf(stderr, "Use \"-h\" or \"--help\" for more information.\n");
return 1;
}
std::vector<std::unique_ptr<PAFObject>> paf_objects;
auto paf_parser = bioparser::createParser<bioparser::PafParser, PAFObject>(argv[optind]);
paf_parser->parse(paf_objects, -1);
clear_contained_reads(paf_objects);
std::vector<std::unique_ptr<FASTAQEntity>> ref_objects;
auto fasta_parser = bioparser::createParser<bioparser::FastaParser, FASTAQEntity>(argv[optind + 1]);
fasta_parser->parse(ref_objects, -1);
std::vector<std::tuple<std::string, int, int>> repeats;
if (!repeats_parser::parse(repeats, argv[3])) {
fprintf(stderr, "Error reading file %s\n", argv[optind + 2]);
return 1;
}
repeats_parser::remove_covered(repeats, paf_objects);
repeats_parser::check_repeats(repeats, ref_objects);
add_breakpoints(paf_objects, repeats);
std::vector<Vertex> vertices;
std::unordered_map<std::string, std::vector<Vertex*>> heads = create_graph(vertices, paf_objects);
std::vector<Vertex*> ends = DepthFirstSearch(heads);
statistics(ends, ref_objects, argv[optind + 3]);
return 0;
} | 32.630631 | 180 | 0.622768 | [
"vector"
] |
9e0d948043195b9bc2c99f2b47f7ff23947e2533 | 2,022 | hpp | C++ | include/task_orchestrator/task_orchestrator.hpp | Rishabh96M/Swarm-Automation-for-Warehouses | 904b8edba394cde65a68059648c1727cc2c70190 | [
"MIT"
] | null | null | null | include/task_orchestrator/task_orchestrator.hpp | Rishabh96M/Swarm-Automation-for-Warehouses | 904b8edba394cde65a68059648c1727cc2c70190 | [
"MIT"
] | null | null | null | include/task_orchestrator/task_orchestrator.hpp | Rishabh96M/Swarm-Automation-for-Warehouses | 904b8edba394cde65a68059648c1727cc2c70190 | [
"MIT"
] | 2 | 2021-12-03T19:55:22.000Z | 2021-12-11T15:20:22.000Z | /**
* Copyright (c) 2021 Prannoy Namala, Rishabh Mukund, Dani Lerner
*
* @file task.hpp
* @author Dani Lerner (dalerner@umd.edu)
* @author Prannoy Namala (pnamala@umd.edu)
* @author Rishabh Mukund (rmukund@umd.edu)
* @brief TaskOrchestrator class declaration
* @version 3.0.1
* @date 2021-12-03
*
* MIT License
*
* 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.
*
*/
#pragma once
#include <vector>
#include <ros/ros.h>
#include <string>
#include "../structs/crate.hpp"
class TaskOrchestrator {
private:
ros::Publisher payload_pub;
ros::NodeHandle nh;
public:
/**
* @brief Constructor for TaskOrchestrator
*/
TaskOrchestrator(/* args */) {
payload_pub = nh.advertise<warehouse_swarm::Crate>("/payload_details",
1000);
}
~TaskOrchestrator() {}
/**
* @brief Publishes full task list to task service
*
* @return true
* @return false
*/
bool publish_full_task_list(const std::vector<Crate>& crates);
};
| 31.107692 | 79 | 0.710682 | [
"vector"
] |
9e207829d3eb419a5d306e8442cfab54748114d2 | 3,514 | cpp | C++ | lib/libcpp/Mesh/nodesandnodesofcells.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcpp/Mesh/nodesandnodesofcells.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcpp/Mesh/nodesandnodesofcells.cpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #include "Alat/sparsitypattern.hpp"
#include "Mesh/nodesandnodesofcells.hpp"
#include <cassert>
#include <mpi.h>
using namespace mesh;
/*--------------------------------------------------------------------------*/
NodesAndNodesOfCells::~NodesAndNodesOfCells() {}
NodesAndNodesOfCells::NodesAndNodesOfCells(): GeometryObject(){}
NodesAndNodesOfCells::NodesAndNodesOfCells( const NodesAndNodesOfCells& nodesandnodesofcells): GeometryObject(nodesandnodesofcells)
{
_nodes = nodesandnodesofcells._nodes;
_nodes_of_cells = nodesandnodesofcells._nodes_of_cells;
}
NodesAndNodesOfCells& NodesAndNodesOfCells::operator=( const NodesAndNodesOfCells& nodesandnodesofcells)
{
_nodes = nodesandnodesofcells._nodes;
_nodes_of_cells = nodesandnodesofcells._nodes_of_cells;
return *this;
}
std::string NodesAndNodesOfCells::getClassName() const
{
return "NodesAndNodesOfCells";
}
std::unique_ptr<GeometryObject> NodesAndNodesOfCells::clone() const
{
return std::unique_ptr<mesh::GeometryObject>(new NodesAndNodesOfCells(*this));
}
/*--------------------------------------------------------------------------*/
const arma::mat& NodesAndNodesOfCells::getNodes() const {return _nodes;}
arma::mat& NodesAndNodesOfCells::getNodes() {return _nodes;}
const alat::armaimat& NodesAndNodesOfCells::getNodesOfCells() const {return _nodes_of_cells;}
alat::armaimat& NodesAndNodesOfCells::getNodesOfCells() {return _nodes_of_cells;}
/*--------------------------------------------------------------------------*/
alat::armaivec NodesAndNodesOfCells::getSizes() const
{
alat::armaivec sizes(4);
sizes[0] = _nodes.n_rows;
sizes[1] = _nodes.n_cols;
sizes[2] = _nodes_of_cells.n_rows;
sizes[3] = _nodes_of_cells.n_cols;
// std::cerr << "NodesAndNodesOfCells sizes="<<sizes.t()<<"\n";
return sizes;
}
void NodesAndNodesOfCells::setSizes(alat::armaivec::const_iterator sizes)
{
// int nrows = sizes[0];
// int ncols = sizes[1];
// std::cerr << "nrows="<<nrows << " ncols="<<ncols<<"\n";
// nrows = sizes[2];
// ncols = sizes[3];
// std::cerr << "nrows="<<nrows << " ncols="<<ncols<<"\n";
_nodes.set_size(sizes[0], sizes[1]);
_nodes_of_cells.set_size(sizes[2], sizes[3]);
}
void NodesAndNodesOfCells::send(int neighbor, int tag) const
{
MPI_Request request;
MPI_Isend(_nodes.begin(), _nodes.size(), MPI_DOUBLE, neighbor, tag, MPI_COMM_WORLD, &request);
MPI_Isend(_nodes_of_cells.begin(), _nodes_of_cells.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request);
}
void NodesAndNodesOfCells::recv(int neighbor, int tag)
{
MPI_Status status;
MPI_Request request;
MPI_Irecv(_nodes.begin(), _nodes.size(), MPI_DOUBLE, neighbor, tag, MPI_COMM_WORLD, &request);
MPI_Wait(&request, &status);
MPI_Irecv(_nodes_of_cells.begin(), _nodes_of_cells.size(), MPI_INT, neighbor, tag, MPI_COMM_WORLD, &request);
MPI_Wait(&request, &status);
}
/*--------------------------------------------------------------------------*/
void NodesAndNodesOfCells::loadH5(const arma::hdf5_name& spec)
{
arma::hdf5_name h5name(spec.filename, spec.dsname+"/nodes", spec.opts);
arma::hdf5_name h5name2(spec.filename, spec.dsname+"/nodes_of_cells", spec.opts);
_nodes.load(h5name);
_nodes_of_cells.load(h5name2);
}
void NodesAndNodesOfCells::saveH5(const arma::hdf5_name& spec) const
{
arma::hdf5_name h5name(spec.filename, spec.dsname+"/nodes", spec.opts);
arma::hdf5_name h5name2(spec.filename, spec.dsname+"/nodes_of_cells", spec.opts);
_nodes.save(h5name);
_nodes_of_cells.save(h5name2);
}
| 38.615385 | 131 | 0.682413 | [
"mesh"
] |
9e2382a07cb1afe916118396a02f65a58a8d7530 | 11,242 | cpp | C++ | bangc-ops/test/mlu_op_gtest/src/runtime.cpp | Alaskra/mlu-ops | 68f167f06bd0fecdb650346de1770ba0e6e1cf2e | [
"Apache-2.0"
] | 25 | 2021-11-17T12:48:58.000Z | 2022-03-14T13:22:24.000Z | bangc-ops/test/mlu_op_gtest/src/runtime.cpp | Alaskra/mlu-ops | 68f167f06bd0fecdb650346de1770ba0e6e1cf2e | [
"Apache-2.0"
] | 4 | 2021-11-02T11:08:22.000Z | 2022-03-25T07:46:42.000Z | bangc-ops/test/mlu_op_gtest/src/runtime.cpp | Alaskra/mlu-ops | 68f167f06bd0fecdb650346de1770ba0e6e1cf2e | [
"Apache-2.0"
] | 14 | 2021-12-02T03:25:55.000Z | 2022-03-30T07:38:34.000Z | /*************************************************************************
* Copyright (C) 2021 by Cambricon, Inc. All rights reserved.
*
* 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 <string>
#include <memory>
#include <algorithm>
#include "runtime.h"
#ifdef __AVX__
const int AVX_ALIGN = 32;
#endif
namespace mluoptest {
// CPURuntime part
CPURuntime::CPURuntime() {}
CPURuntime::~CPURuntime() {}
// all member variable are shared_ptr.
cnrtRet_t CPURuntime::destroy() {
return CNRT_RET_SUCCESS;
}
void *CPURuntime::allocate(void *ptr, std::string name) {
if (ptr == NULL) {
return NULL; // can't free NULL, don't push NULL into vector.
} else {
memory_blocks_.push_back(std::make_shared<MemBlock<void *>>(ptr, free, name));
return ptr;
}
}
void *CPURuntime::allocate(size_t num_bytes, std::string name) {
if (num_bytes == 0) {
return NULL;
}
#ifdef __AVX__
void *ptr = _mm_malloc(num_bytes, AVX_ALIGN); // avx need align to 32
#else
void *ptr = malloc(num_bytes);
#endif
if (ptr != NULL) {
#ifdef __AVX__
memory_blocks_.push_back(std::make_shared<MemBlock<void *>>(ptr, _mm_free, name));
#else
memory_blocks_.push_back(std::make_shared<MemBlock<void *>>(ptr, free, name));
#endif
return ptr;
} else {
LOG(ERROR) << "CPURuntime: Failed to allocate " << num_bytes << " bytes.";
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return NULL;
}
}
// MLURuntime part
MLURuntime::MLURuntime() {
check_enable_ = getEnv("MLUOP_GTEST_OVERWRITTEN_CHECK", true);
if (true == check_enable_) {
header_mask_ = std::shared_ptr<char>(new char[mask_bytes_], [](char *p) { delete[] p; });
footer_mask_ = std::shared_ptr<char>(new char[mask_bytes_], [](char *p) { delete[] p; });
rand_set_mask();
header_check_ = std::shared_ptr<char>(new char[mask_bytes_], [](char *p) { delete[] p; });
footer_check_ = std::shared_ptr<char>(new char[mask_bytes_], [](char *p) { delete[] p; });
}
}
MLURuntime::~MLURuntime() {}
cnrtRet_t MLURuntime::destroy() {
cnrtRet_t ret = CNRT_RET_SUCCESS;
bool ok = true;
for (int i = 0; i < memory_blocks_.size(); ++i) {
char *header = memory_blocks_[i].header;
if (true == check_enable_) {
reset_check();
char *footer = header + memory_blocks_[i].raw_bytes - mask_bytes_;
ret =
cnrtMemcpy((void *)header_check_.get(), header, mask_bytes_, CNRT_MEM_TRANS_DIR_DEV2HOST);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: cnrtFree failed. Addr = " << header;
ok = false;
}
ret =
cnrtMemcpy((void *)footer_check_.get(), footer, mask_bytes_, CNRT_MEM_TRANS_DIR_DEV2HOST);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: cnrtFree failed. Addr = " << header;
ok = false;
}
void *mlu_addr = (void *)(header + mask_bytes_);
std::string name = memory_blocks_[i].name;
if (!check_byte((void *)header_check_.get(), (void *)header_mask_.get(), mask_bytes_)) {
LOG(ERROR) << "MLURuntime: Addr " << mlu_addr << "(" << name << ") has been overwritten.";
ok = false;
}
if (!check_byte((void *)footer_check_.get(), (void *)footer_mask_.get(), mask_bytes_)) {
LOG(ERROR) << "MLURuntime: Addr " << mlu_addr << "(" << name << ") has been overwritten.";
ok = false;
}
} // endif (true == check_enable_)
ret = cnrtFree(header);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: cnrtFree failed. Addr = " << header;
ok = false;
}
}
if (!ok) {
return CNRT_RET_ERR_INVALID;
} else {
return ret;
}
}
void *MLURuntime::allocate(size_t num_bytes, std::string name) {
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [allocate] malloc for [" << name << "] " << num_bytes << " bytes.";
#endif
if (num_bytes == 0) {
return NULL;
}
if (false == check_enable_) {
char *raw_addr = NULL;
cnrtRet_t ret = cnrtMalloc((void **)&raw_addr, num_bytes);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to allocate " << num_bytes << " bytes.";
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return NULL;
}
memory_blocks_.push_back(MemBlock(num_bytes, raw_addr, name));
return raw_addr;
}
cnrtRet_t ret = CNRT_RET_SUCCESS;
size_t raw_bytes = num_bytes + 2 * mask_bytes_;
// malloc big space
char *raw_addr = NULL;
ret = cnrtMalloc((void **)&raw_addr, raw_bytes);
char *header = raw_addr;
char *footer = raw_addr + mask_bytes_ + num_bytes;
char *mlu_addr = header + mask_bytes_;
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [allocate] malloc [" << (void *)mlu_addr << ", " << (void *)footer << ")";
#endif
ret = cnrtMemcpy(header, (void *)header_mask_.get(), mask_bytes_, CNRT_MEM_TRANS_DIR_HOST2DEV);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to allocate " << num_bytes << " bytes.";
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return NULL;
}
ret = cnrtMemcpy(footer, (void *)footer_mask_.get(), mask_bytes_, CNRT_MEM_TRANS_DIR_HOST2DEV);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to allocate " << num_bytes << " bytes.";
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return NULL;
}
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to allocate " << num_bytes << " bytes.";
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return NULL;
}
memory_blocks_.push_back(MemBlock(raw_bytes, header, name));
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [allocate] return ptr is " << (void *)(mlu_addr);
#endif
return mlu_addr;
}
cnrtRet_t MLURuntime::deallocate(void *mlu_addr) {
if (mlu_addr == NULL) {
return CNRT_RET_SUCCESS;
}
if (false == check_enable_) {
auto it = std::find_if(memory_blocks_.begin(), memory_blocks_.end(),
[=](MemBlock b) { return b.header == mlu_addr; });
if (it == memory_blocks_.end()) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return CNRT_RET_ERR_INVALID;
}
memory_blocks_.erase(it);
cnrtRet_t ret = cnrtFree(mlu_addr);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return ret;
}
return ret;
}
cnrtRet_t ret = CNRT_RET_SUCCESS;
// get header and footer
char *header = (char *)mlu_addr - mask_bytes_;
auto it = std::find_if(memory_blocks_.begin(), memory_blocks_.end(),
[=](MemBlock b) { return b.header == header; });
if (it == memory_blocks_.end()) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return CNRT_RET_ERR_INVALID;
}
size_t raw_bytes = it->raw_bytes;
char *footer = (char *)header + raw_bytes - mask_bytes_;
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [deallocate] get ptr " << (void *)(mlu_addr) << " for [" << it->name
<< "]";
VLOG(4) << "MLURuntime: [deallocate] free [" << (void *)(mlu_addr) << ", " << (void *)(footer)
<< ")";
#endif
reset_check();
ret = cnrtMemcpy((void *)header_check_.get(), header, mask_bytes_, CNRT_MEM_TRANS_DIR_DEV2HOST);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return ret;
}
ret = cnrtMemcpy((void *)footer_check_.get(), footer, mask_bytes_, CNRT_MEM_TRANS_DIR_DEV2HOST);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return ret;
}
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [deallocate] check " << (void *)header << " begin.";
#endif
if (!check_byte((void *)header_check_.get(), (void *)header_mask_.get(), mask_bytes_)) {
LOG(ERROR) << "MLURuntime: Addr " << mlu_addr << "(" << it->name << ") has been overwritten.";
return CNRT_RET_ERR_INVALID;
}
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [deallocate] check " << (void *)header << " end.";
#endif
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [deallocate] check " << (void *)footer << " begin.";
#endif
if (!check_byte((void *)footer_check_.get(), (void *)footer_mask_.get(), mask_bytes_)) {
LOG(ERROR) << "MLURuntime: Addr " << mlu_addr << "(" << it->name << ") has been overwritten.";
return CNRT_RET_ERR_INVALID;
}
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: [deallocate] check " << (void *)footer << " end.";
#endif
memory_blocks_.erase(it);
ret = cnrtFree(header);
if (ret != CNRT_RET_SUCCESS) {
LOG(ERROR) << "MLURuntime: Failed to deallocate " << mlu_addr;
throw std::invalid_argument(std::string(__FILE__) + " +" + std::to_string(__LINE__));
return ret;
}
return ret;
}
bool MLURuntime::check_byte(void *new_mask, void *org_mask, size_t mask_bytes) {
return (0 == memcmp(new_mask, org_mask, mask_bytes));
}
void MLURuntime::reset_check() {
memset((void *)header_check_.get(), 0, mask_bytes_);
memset((void *)footer_check_.get(), 0, mask_bytes_);
}
// set mask to nan/inf due to date
// if date is even, set nan or set inf
void MLURuntime::rand_set_mask() {
auto now = time(0);
struct tm now_time;
auto *ltm = localtime_r(&now, &now_time);
auto mday = ltm->tm_mday;
auto mask_value = nan("");
auto *user_mask_value = getenv("MLUOP_GTEST_SET_GDRAM");
auto set_mask = [&](float *mask_start) {
if (!user_mask_value) {
mask_value = (mday % 2) ? INFINITY : nan("");
} else if (strcmp(user_mask_value, "NAN") == 0) {
mask_value = nan("");
} else if (strcmp(user_mask_value, "INF") == 0) {
mask_value = INFINITY;
} else {
LOG(WARNING) << "env MLUOP_GTEST_SET_GDRAM only supports NAN or INF"
<< ", now it is set " << user_mask_value;
}
std::fill(mask_start, mask_start + (mask_bytes_ / sizeof(float)), mask_value);
};
set_mask((float *)footer_mask_.get());
set_mask((float *)header_mask_.get());
#ifdef GTEST_DEBUG_LOG
VLOG(4) << "MLURuntime: set " << mask_value << " before and after input/output gdram.";
#endif
}
} // namespace mluoptest
| 34.590769 | 100 | 0.634051 | [
"vector"
] |
9e2ac2f0abdab80d3ac7b370440adeb6869b21c6 | 3,944 | cpp | C++ | geometry/path.cpp | huangjund/path_planner | 79892899ffa39a6368ae8b70ff4742b6d618ae14 | [
"BSD-3-Clause"
] | null | null | null | geometry/path.cpp | huangjund/path_planner | 79892899ffa39a6368ae8b70ff4742b6d618ae14 | [
"BSD-3-Clause"
] | null | null | null | geometry/path.cpp | huangjund/path_planner | 79892899ffa39a6368ae8b70ff4742b6d618ae14 | [
"BSD-3-Clause"
] | null | null | null | #include "path.h"
using namespace HybridAStar;
//###################################################
// CLEAR PATH
//###################################################
void Path::clear() {
std::shared_ptr<Common::SE2State> node;
path.poses.clear();
pathNodes.markers.clear();
pathVehicles.markers.clear();
// addNode(node, 0);
// addVehicle(node, 1);
publishPath();
publishPathNodes();
publishPathVehicles();
}
////###################################################
//// TRACE PATH
////###################################################
//// __________
//// TRACE PATH
//void Path::tracePath(const Common::SE2State* node, int i) {
// if (i == 0) {
// path.header.stamp = ros::Time::now();
// }
// if (node == nullptr) { return; }
// addSegment(node);
// addNode(node, i);
// i++;
// addVehicle(node, i);
// i++;
// tracePath(node->getPred(), i);
//}
//###################################################
// TRACE PATH
//###################################################
// __________
// TRACE PATH
void Path::updatePath(std::vector<std::shared_ptr<Common::SE2State>> nodePath) {
path.header.stamp = ros::Time::now();
int k = 0;
for (auto i = nodePath.cbegin(); i != nodePath.cend(); ++i) {
addSegment(*i);
addNode(*i, k);
k++;
addVehicle(*i, k);
k++;
}
}
// ___________
// ADD SEGMENT
void Path::addSegment(const std::shared_ptr<Common::SE2State>& node) {
geometry_msgs::PoseStamped vertex;
// TODO: should this x multiply a collision cell size
vertex.pose.position.x = node->getX();
vertex.pose.position.y = node->getY();
vertex.pose.position.z = 0;
vertex.pose.orientation.x = 0;
vertex.pose.orientation.y = 0;
vertex.pose.orientation.z = 0;
vertex.pose.orientation.w = 0;
path.poses.push_back(vertex);
}
// ________
// ADD NODE
void Path::addNode(const std::shared_ptr<Common::SE2State>& node, int i) {
visualization_msgs::Marker pathNode;
// delete all previous markers
if (i == 0) {
pathNode.action = 3;
}
pathNode.header.frame_id = "path";
pathNode.header.stamp = ros::Time(0);
pathNode.id = i;
pathNode.type = visualization_msgs::Marker::SPHERE;
pathNode.scale.x = 0.1;
pathNode.scale.y = 0.1;
pathNode.scale.z = 0.1;
pathNode.color.a = 1.0;
if (smoothed) {
pathNode.color.r = Constants::pink.red;
pathNode.color.g = Constants::pink.green;
pathNode.color.b = Constants::pink.blue;
} else {
pathNode.color.r = Constants::purple.red;
pathNode.color.g = Constants::purple.green;
pathNode.color.b = Constants::purple.blue;
}
pathNode.pose.position.x = node->getX();
pathNode.pose.position.y = node->getY();
pathNodes.markers.push_back(pathNode);
}
void Path::addVehicle(const std::shared_ptr<Common::SE2State>& node, int i) {
visualization_msgs::Marker pathVehicle;
// delete all previous markersg
if (i == 1) {
pathVehicle.action = 3;
}
pathVehicle.header.frame_id = "path";
pathVehicle.header.stamp = ros::Time(0);
pathVehicle.id = i;
pathVehicle.type = visualization_msgs::Marker::CUBE;
pathVehicle.scale.x = carPlant_->length_ - carPlant_->bloating_ * 2;
pathVehicle.scale.y = carPlant_->width_ - carPlant_->bloating_ * 2;
pathVehicle.scale.z = 1;
pathVehicle.color.a = 0.1;
if (smoothed) {
pathVehicle.color.r = Constants::orange.red;
pathVehicle.color.g = Constants::orange.green;
pathVehicle.color.b = Constants::orange.blue;
} else {
pathVehicle.color.r = Constants::teal.red;
pathVehicle.color.g = Constants::teal.green;
pathVehicle.color.b = Constants::teal.blue;
}
pathVehicle.pose.position.x = node->getX();
pathVehicle.pose.position.y = node->getY();
pathVehicle.pose.orientation = tf::createQuaternionMsgFromYaw(node->getT());
pathVehicles.markers.push_back(pathVehicle);
}
| 27.971631 | 80 | 0.590517 | [
"vector"
] |
9e2f1e0622e7f207f314150ce21e7d32011f6a32 | 16,019 | cpp | C++ | Xcode/tamgugui/Tamgu/interface.cpp | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 192 | 2019-07-10T15:47:11.000Z | 2022-03-10T09:26:31.000Z | Xcode/tamgugui/Tamgu/interface.cpp | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 5 | 2019-10-01T13:17:28.000Z | 2021-01-05T15:31:39.000Z | Xcode/tamgugui/Tamgu/interface.cpp | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 14 | 2019-09-23T03:39:59.000Z | 2021-09-02T12:20:14.000Z | /*
* Tamgu (탐구)
*
* Copyright 2019-present NAVER Corp.
* under BSD 3-clause
*/
/* --- CONTENTS ---
Project : Tamgu (탐구)
Version : See tamgu.cxx for the version number
filename : interface.cpp
Date : 2017/09/01
Purpose : Functions and Methods to communicate with Tamgu API
Programmer : Claude ROUX (claude.roux@naverlabs.com)
Reviewer :
*/
#include <stdio.h>
#include "tamgu.h"
#include "compilecode.h"
#include "x_node.h"
#include "globaltamgu.h"
#include "tamgustring.h"
#include "x_tokenize.h"
#include "tamgudebug.h"
const char* tmgelse ="else";
extern "C" {
void Rappel(char threading, const char* txt);
void displaydebug(const char* localvariables, const char* allvariables, const char* sstack, const char* filename, long currentline);
const char* Inputtext(const char* msg);
char WindowModeActivated(void);
void Inittamgulibspath();
}
//------------------------------------------------------------------------------------------------DEBUG
static Debuginfo infodebug;
static string displaybuffer;
Tamgu* Debug_callback(vector<Tamgu*>& stack, short idthread, void* data) {
Tamgu* res = infodebug.debugger(stack, idthread, data);
if (res == aTRUE) {
//We release our main debugger window...
displaydebug(STR(infodebug.localvariables), STR(infodebug.allvariables), STR(infodebug.sstack), STR(infodebug.filename), infodebug.currentline);
infodebug.loquet.Blocked();
}
return res;
}
//The following functions are called from within the GUI to handle debugging
static bool debugmode = false;
extern "C" {
void Shortname(char v) {
infodebug.shortname=v;
}
void addabreakpoint(const char* filename, long numline, char add) {
infodebug.addabreakpoint(filename, numline, add);
}
const char* Getcurrentfilename(void) {
return STR(infodebug.filename);
}
void clearallbreakpoints(void) {
infodebug.clearbreakpoints();
}
void Setdebugmode(char d) {
infodebug.displaymode = false;
debugmode = d;
}
char NextLine(void) {
return infodebug.next();
}
char Gotonextbreak(void) {
return infodebug.gotonext();
}
char Getin(void) {
return infodebug.getin();
}
char Getout(void) {
return infodebug.getout();
}
char StopDebug(void) {
infodebug.stopexecution();
return 1;
}
char Gotoend(void) {
return infodebug.gotoend();
}
void Blocked(void) {
infodebug.loquet.Blocked();
}
void Released(void) {
if (executionbreak)
return;
infodebug.loquet.Released();
}
}
//------------------------------------------------------------------------------------------------RUN AND COMPILE
static void display_result(string s, void* object) {
string e;
s_latin_to_utf8(e, USTR(s), s.size());
displaybuffer+=e;
}
static void send_result(string s, void* object) {
//we cannot have both console and windows accessed...
s_latin_to_utf8(displaybuffer, USTR(s), s.size());
if (WindowModeActivated())
return;
char threading=*((bool*)object);
Rappel(threading, STR(displaybuffer));
}
static void final_display() {
Rappel(1, STR(displaybuffer));
}
//In the case of a mac GUI, we need to call a specific version of kget, which is based on alert...
//This function is only called if we are not implementing a FLTK GUI, in that case we use ProcEditor (in tamgufltk.cxx)
Tamgu* ProcMacEditor(Tamgu* contextualpattern, short idthread, TamguCall* callfunc) {
string label("Enter your text:");
if (callfunc->Size())
label = callfunc->Evaluate(0, aNULL, idthread)->String();
const char* buff = Inputtext(STR(label));
if (buff == NULL)
return aNULL;
string res=buff;
return globalTamgu->Providestring(res);
}
extern "C" {
char IsRunning(void) {
return TamguRunning();
}
///Users/roux/Documents/GitHub/TAMGU/bin/Examples/word2vec
void settamgupath(const char* homepath, const char* v) {
char* start=(char*)v;
while (start[0]<=32) start++;
long lg=strlen(start)-1;
while (start[lg]<=32)lg--;
start[lg+1]=0;
setenv("TAMGULIBS",start,1);
char path[4096];
sprintf(path,"%s/.tamgu",homepath);
ofstream savepath(path);
savepath.write(start,strlen(start));
savepath.write("\n",1);
savepath.close();
}
void inittamgupath(const char* homepath) {
char path[4096];
sprintf(path,"%s/.tamgu",homepath);
ifstream getpath(path);
if (getpath.fail()) {
getpath.close();
ofstream savepath(path);
strcpy(path,"/usr/local/lib/tamgu");
savepath.write(path,strlen(path));
savepath.write("\n",1);
savepath.close();
setenv("TAMGULIBS",path,1);
return;
}
memset(path,0,4096);
getpath.read(path,4096);
char* start=path;
while (start[0]<=32) start++;
long lg=strlen(start)-1;
while (start[lg]<=32)lg--;
start[lg+1]=0;
setenv("TAMGULIBS",start,1);
}
const char* Listing(void) {
displaybuffer=TamguListing();
return STR(displaybuffer);
}
const char* Readfile(const char* path) {
ifstream f(path, openMode);
if (f.fail())
return NULL;
displaybuffer="";
string line;
while (!f.eof()) {
getline(f,line);
displaybuffer+=line;
displaybuffer += "\n";
}
s_latin_to_utf8(line, USTR(displaybuffer), displaybuffer.size());
displaybuffer=line;
cr_normalise(displaybuffer);
return STR(displaybuffer);
}
char StopExecution(void) {
return TamguStop();
}
void InitialisationDisplay(short id, char th) {
static bool threading;
threading=th;
displaybuffer="";
TamguGlobal* g = GlobalTamgu(id);
if (g!=NULL) {
g->displayfunction = send_result;
g->displayobject = &threading;
g->doubledisplay = false;
}
}
void Initdisplay(short id) {
displaybuffer="";
TamguGlobal* g = GlobalTamgu(id);
if (g!=NULL) {
g->displayfunction = display_result;
g->doubledisplay = false;
}
}
const char* Getdisplay(void) {
static string buff;
buff=displaybuffer;
buff+="\r";
displaybuffer="";
return STR(buff);
}
void CleanGlobal(void) {
TamguDeleteGlobal(0);
}
int Compilecode(const char* cde, const char* filename, char console) {
Inittamgulibspath();
if (cde==NULL)
return -1;
if (!TamguSelectglobal(0)) {
TamguCreateGlobal();
}
if (debugmode == true) {
globalTamgu->Setdebugmode(true);
globalTamgu->Setdebugfunction(Debug_callback);
}
else {
globalTamgu->Setdebugmode(false);
globalTamgu->Setdebugfunction(NULL);
}
int idcode=-1;
string code=cde;
try {
globalTamgu->threads[0].currentinstruction = NULL;
idcode = TamguCompile(code, filename, console);
if (idcode==-1)
displaybuffer=TamguErrorMessage();
}
catch (TamguRaiseError* err) {
displaybuffer = err->message;
globalTamgu->Cleanerror(0);
return -1;
}
return idcode;
}
long CurrentLine(void) {
return TamguCurrentLine();
}
const char* Currentfilename(void) {
static string filename;
filename=TamguCurrentFilename();
return filename.c_str();
}
char Run(short idcode) {
#ifdef MULTIGLOBALTAMGU
//In that case, especially when we are running from within a thread, we need to activate our local thread version of globalTamgu...
TamguSelectglobal(0);
#endif
bool finaldisplay = false;
if (WindowModeActivated()) {
finaldisplay = true;
}
else
globalTamgu->RecordOneProcedure("kget", ProcMacEditor, P_NONE | P_ONE);
if (debugmode == true) {
globalTamgu->Setdebugmode(true);
globalTamgu->Setdebugfunction(Debug_callback);
infodebug.clearall();
}
TamguCode* a = globalTamgu->Getcode(idcode);
if (a == NULL)
return false;
globalTamgu->spaceid = idcode;
a->Run(debugmode);
if (globalTamgu->GenuineError(0)) {
displaybuffer=TamguErrorMessage();
return false;
}
if (finaldisplay)
final_display();
return true;
}
char** Getnames(int* nb) {
bool tobecleaned=false;
if (!TamguSelectglobal(0)) {
TamguCreateGlobal();
tobecleaned=true;
}
vector<string> vs;
TamguAllObjects(vs);
if (tobecleaned)
TamguDeleteGlobal(0);
if (vs.size() == 0)
return NULL;
char** liste=new char*[vs.size()];
for (int i = 0; i < vs.size(); i++) {
liste[i] = new char[vs[i].size()+1];
strcpy(liste[i], STR(vs[i]));
}
*nb= (int)vs.size();
return liste;
}
void TamguFinalClean() {
TamguExtinguish();
}
long indentationVirtuel(char* cr, char* acc) {
if (cr == NULL)
return 0;
string codestr(cr);
return VirtualIndentation(codestr);
}
const char* lindentation(char* basecode, int blancs) {
static string codeindente;
string codestr = basecode;
Trimright(codestr);
codestr+="\n";
bool lisp = false;
if (codestr[0] == '(' && codestr[1] == ')')
lisp = true;
cr_normalise(codestr);
codeindente = "";
IndentationCode(codestr, codeindente, lisp);
if (codeindente.find("/@") != string::npos || codeindente.find("@\"") != string::npos)
cr_normalise(codeindente);
codeindente += "\n";
return codeindente.c_str();
}
void Keywwords(hmap<wstring,bool>& names) {
bool tobecleaned=false;
if (!TamguSelectglobal(0)) {
TamguCreateGlobal();
tobecleaned=true;
}
vector<string> vs;
TamguAllObjects(vs);
if (tobecleaned)
TamguDeleteGlobal(0);
wstring token;
for (int i = 0; i < vs.size(); i++) {
sc_utf8_to_unicode(token, USTR(vs[i]), vs[i].size());
names[token]=true;
}
}
void Keywords(hmap<string,bool>& names) {
bool tobecleaned=false;
if (!TamguSelectglobal(0)) {
TamguCreateGlobal();
tobecleaned=true;
}
vector<string> vs;
TamguAllObjects(vs);
if (tobecleaned)
TamguDeleteGlobal(0);
for (int i = 0; i < vs.size(); i++)
names[vs[i]]=true;
}
long* colorparser(const char* txt, long from, long upto) {
static hmap<string,bool> keys;
static vector<long> limits;
static x_coloringrule xr;
static bool init=false;
if (!init) {
init=true;
Keywords(keys);
}
xr.tokenize(txt, true);
char type;
long gauche = 0,droite = 0,i, droiteutf16 = 0;
long sz=xr.stack.size();
string sub;
long offsetdrift = 0;
limits.clear();
for (i=0;i<sz;i++) {
type=xr.stacktype[i];
if (!type)
continue;
gauche=xr.cpos[i] + offsetdrift;
if (type == 5) {
if (xr.stack[i][1] == '/') {
if (gauche < from || gauche > upto)
continue;
}
}
else {
if (type != 3 && (gauche < from || gauche > upto))
continue;
}
//The strings in the mac GUI are encoded in UTF16
droiteutf16 = size_utf16(USTR(xr.stack[i]), xr.stack[i].size(), droite);
if (droiteutf16 > droite) {
//if droiteutf16 is larger, then it means that a wide UTF16 character was detected
//we keep the difference in offsetdrift to propagate it
offsetdrift += droiteutf16 - droite;
droite = droiteutf16;
}
switch(type) {
case 1:
case 2:
case 3:
//strings
limits.push_back(type);
limits.push_back(gauche);
limits.push_back(droite);
break;
case 4://regular token
if (keys.find(xr.stack[i])!=keys.end()) {
limits.push_back(5);
limits.push_back(gauche);
limits.push_back(droite);
break;
}
break;
case 5://comments
limits.push_back(7);
limits.push_back(gauche);
limits.push_back(droite);
break;
case 10:
//special variables: #d+ ?label $d+
limits.push_back(8);
limits.push_back(gauche);
limits.push_back(droite);
break;
case 11:
// .method(
limits.push_back(4);
limits.push_back(gauche+1);
limits.push_back(droite-2);
break;
case 12:
// function(
sub=xr.stack[i].substr(0,xr.stack[i].size()-1);
if (keys.find(sub)!=keys.end()) {
limits.push_back(5);
limits.push_back(gauche);
limits.push_back(droite-1);
break;
}
limits.push_back(6);
limits.push_back(gauche);
limits.push_back(droite-1);
break;
case 13:
// <function
sub=xr.stack[i].substr(1,xr.stack[i].size()-1);
if (keys.find(sub)!=keys.end()) {
limits.push_back(5);
limits.push_back(gauche);
limits.push_back(droite-1);
break;
}
limits.push_back(6);
limits.push_back(gauche+1);
limits.push_back(droite);
break;
case 14:
//annotation lexicon head rule
sub=xr.stack[i];
limits.push_back(6);
limits.push_back(gauche);
limits.push_back(droite);
break;
}
}
long* res=new long[limits.size()+1];
for (i=0;i<limits.size();i++)
res[i]=limits[i];
res[limits.size()]=-1;
return res;
}
void deletion(long* l) {
delete[] l;
}
}
| 28.103509 | 152 | 0.501717 | [
"object",
"vector"
] |
9e2f935013df347f5c601e712aa58ef6813332e9 | 1,873 | cpp | C++ | inference-engine/tests/unit/transformations/sub_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | 1 | 2020-08-26T02:37:00.000Z | 2020-08-26T02:37:00.000Z | inference-engine/tests/unit/transformations/sub_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | null | null | null | inference-engine/tests/unit/transformations/sub_test.cpp | FengYen-Chang/dldt | 1a7ab8871de68bef05c959ea20191d8242761635 | [
"Apache-2.0"
] | 1 | 2018-12-14T07:52:51.000Z | 2018-12-14T07:52:51.000Z | // Copyright (C) 2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <string.h>
#include <transform/transform_network.hpp>
#include <transform/transformations/sub.hpp>
#include <ie_builders.hpp>
#include "tranformations_test.hpp"
using namespace testing;
using namespace InferenceEngine;
class TransformNetworkTest: public TransformationTestCommon {};
TEST_F(TransformationTestCommon, Sub) {
Builder::Network builder("sub");
idx_t firstInputId = builder.addLayer(Builder::InputLayer("FirstInput").setPort(Port({1,3, 227, 227})));
idx_t secondInputId = builder.addLayer(Builder::InputLayer("SecondInput").setPort(Port({1,3, 227, 227})));
idx_t eltwiseSubId = builder.addLayer({firstInputId, secondInputId}, Builder::EltwiseLayer("Sub").setEltwiseType(Builder::EltwiseLayer::EltwiseType::SUB));
idx_t clampId = builder.addLayer({eltwiseSubId}, Builder::ClampLayer("clamp"));
auto network = Transform::Network(builder);
Transform::TransformationSub transformationSub;
transformationSub.execute(network);
ASSERT_THROW(network.getLayer("Sub"), InferenceEngine::details::InferenceEngineException);
auto sumLayer = network.getLayer(firstInputId).getOutPort().getConnection().getDestination().getLayer();
auto powerLayer = network.getLayer(secondInputId).getOutPort().getConnection().getDestination().getLayer();
ASSERT_EQ(sumLayer.getType(), "Eltwise");
ASSERT_EQ(sumLayer.getParameter("operation").as<std::string>(), "sum");
ASSERT_EQ(powerLayer.getType(), "Power");
ASSERT_EQ(powerLayer.getParameter("power").as<float>(), 1.0f);
ASSERT_EQ(powerLayer.getParameter("scale").as<float>(), -1.0f);
ASSERT_EQ(powerLayer.getParameter("shift").as<float>(), 0.0f);
ASSERT_EQ(sumLayer.getOutPort().getConnection().getDestination().getLayer().getId(), clampId);
} | 48.025641 | 159 | 0.748532 | [
"transform"
] |
9e30b434358f3a99dcf3919f5d698ac8431a35dc | 4,315 | cpp | C++ | src/backend/opencl/qr.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-06-14T23:49:18.000Z | 2018-06-14T23:49:18.000Z | src/backend/opencl/qr.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2015-07-02T15:53:02.000Z | 2015-07-02T15:53:02.000Z | src/backend/opencl/qr.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-02-26T17:11:03.000Z | 2018-02-26T17:11:03.000Z | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <qr.hpp>
#include <err_common.hpp>
#include <blas.hpp>
#include <copy.hpp>
#include <identity.hpp>
#include <err_opencl.hpp>
#include <magma/magma.h>
#include <magma/magma_helper.h>
#include <magma/magma_data.h>
#include <kernel/triangle.hpp>
#if defined(WITH_OPENCL_LINEAR_ALGEBRA)
namespace opencl
{
template<typename T>
void qr(Array<T> &q, Array<T> &r, Array<T> &t, const Array<T> &orig)
{
try {
initBlas();
dim4 iDims = orig.dims();
int M = iDims[0];
int N = iDims[1];
dim4 pDims(M, std::max(M, N));
Array<T> in = padArray<T, T>(orig, pDims, scalar<T>(0)); //copyArray<T>(orig);
in.resetDims(iDims);
int MN = std::min(M, N);
int NB = magma_get_geqrf_nb<T>(M);
int NUM = (2*MN + ((N+31)/32)*32)*NB;
Array<T> tmp = createEmptyArray<T>(dim4(NUM));
std::vector<T> h_tau(MN);
int info = 0;
cl::Buffer *in_buf = in.get();
cl::Buffer *dT = tmp.get();
magma_geqrf3_gpu<T>(M, N,
(*in_buf)(), in.getOffset(), in.strides()[1],
&h_tau[0], (*dT)(), tmp.getOffset(), getQueue()(), &info);
r = createEmptyArray<T>(in.dims());
kernel::triangle<T, true, false>(r, in);
cl::Buffer *r_buf = r.get();
magmablas_swapdblk<T>(MN - 1, NB,
( *r_buf)(), r.getOffset(),
r.strides()[1], 1,
(*dT)(), tmp.getOffset() + MN * NB,
NB, 0, getQueue()());
q = in; // No need to copy
q.resetDims(dim4(M, M));
cl::Buffer *q_buf = q.get();
magma_ungqr_gpu<T>(q.dims()[0], q.dims()[1], std::min(M, N),
(*q_buf)(), q.getOffset(), q.strides()[1],
&h_tau[0],
(*dT)(), tmp.getOffset(), NB, getQueue()(), &info);
t = createHostDataArray(dim4(MN), &h_tau[0]);
} catch(cl::Error &err) {
CL_TO_AF_ERROR(err);
}
}
template<typename T>
Array<T> qr_inplace(Array<T> &in)
{
try {
initBlas();
dim4 iDims = in.dims();
int M = iDims[0];
int N = iDims[1];
int MN = std::min(M, N);
getQueue().finish(); // FIXME: Does this need to be here?
cl::CommandQueue Queue2(getContext(), getDevice());
cl_command_queue queues[] = {getQueue()(), Queue2()};
std::vector<T> h_tau(MN);
cl::Buffer *in_buf = in.get();
int info = 0;
magma_geqrf2_gpu<T>(M, N, (*in_buf)(),
in.getOffset(), in.strides()[1],
&h_tau[0], queues, &info);
Array<T> t = createHostDataArray(dim4(MN), &h_tau[0]);
return t;
} catch(cl::Error &err) {
CL_TO_AF_ERROR(err);
}
}
#define INSTANTIATE_QR(T) \
template Array<T> qr_inplace<T>(Array<T> &in); \
template void qr<T>(Array<T> &q, Array<T> &r, Array<T> &t, const Array<T> &in);
INSTANTIATE_QR(float)
INSTANTIATE_QR(cfloat)
INSTANTIATE_QR(double)
INSTANTIATE_QR(cdouble)
}
#else
namespace opencl
{
template<typename T>
void qr(Array<T> &q, Array<T> &r, Array<T> &t, const Array<T> &in)
{
AF_ERROR("Linear Algebra is disabled on OpenCL", AF_ERR_NOT_CONFIGURED);
}
template<typename T>
Array<T> qr_inplace(Array<T> &in)
{
AF_ERROR("Linear Algebra is disabled on OpenCL", AF_ERR_NOT_CONFIGURED);
}
#define INSTANTIATE_QR(T) \
template Array<T> qr_inplace<T>(Array<T> &in); \
template void qr<T>(Array<T> &q, Array<T> &r, Array<T> &t, const Array<T> &in);
INSTANTIATE_QR(float)
INSTANTIATE_QR(cfloat)
INSTANTIATE_QR(double)
INSTANTIATE_QR(cdouble)
}
#endif
| 28.576159 | 101 | 0.503129 | [
"vector"
] |
9e3a321e58d530e1292e6beea7ffd3ef7bdd556b | 6,346 | cpp | C++ | tests/src/openvino_blob_test.cpp | slitcch/depthai-core | b6e5f3bc9ac1473c0a91012611a6f7f9d97c384d | [
"MIT"
] | 1 | 2022-03-22T07:15:47.000Z | 2022-03-22T07:15:47.000Z | tests/src/openvino_blob_test.cpp | slitcch/depthai-core | b6e5f3bc9ac1473c0a91012611a6f7f9d97c384d | [
"MIT"
] | null | null | null | tests/src/openvino_blob_test.cpp | slitcch/depthai-core | b6e5f3bc9ac1473c0a91012611a6f7f9d97c384d | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
// std
#include <atomic>
#include <fstream>
#include <iostream>
// Include depthai library
#include <depthai/depthai.hpp>
// setBlob
void checkBlob(dai::OpenVINO::Blob& blob) {
printf("Blob: ");
for(const auto& in : blob.networkInputs) {
std::string name = in.first;
auto tensor = in.second;
printf("'%s - dims: %d - order: %04x - type: %d' ", name.c_str(), tensor.numDimensions, tensor.order, tensor.dataType);
}
for(const auto& out : blob.networkOutputs) {
std::string name = out.first;
auto tensor = out.second;
printf("'%s - dims: %d - order: %04x - type: %d' ", name.c_str(), tensor.numDimensions, tensor.order, tensor.dataType);
}
printf("(%u %u %u %u)\n", blob.stageCount, blob.numShaves, blob.numSlices, blob.version);
REQUIRE(blob.networkInputs.size() == 1);
REQUIRE(blob.networkInputs.at("0").numDimensions == 4);
REQUIRE(blob.networkInputs.at("0").order == dai::TensorInfo::StorageOrder::NCHW);
// REQUIRE(blob.networkInputs.at("0").dataType == dai::TensorInfo::DataType::U8F);
REQUIRE(blob.networkOutputs.size() == 1);
REQUIRE(blob.networkOutputs.at("14").numDimensions == 4);
REQUIRE(blob.networkOutputs.at("14").order == dai::TensorInfo::StorageOrder::NCHW);
REQUIRE(blob.networkOutputs.at("14").dataType == dai::TensorInfo::DataType::FP16);
}
TEST_CASE("OpenVINO 2020.3 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2020_3_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2020_3);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2020_3);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2020.4 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2020_4_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2020_4);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2020_4);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.1 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2021_1_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2021_1);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_1);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.2 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2021_2_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2021_2);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_2);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.3 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2021_3_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2021_3);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_3);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.4 setBlob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
dai::OpenVINO::Blob blob(OPENVINO_2021_4_BLOB_PATH);
REQUIRE(blob.version == dai::OpenVINO::VERSION_2021_4);
checkBlob(blob);
nn->setBlob(std::move(blob));
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_4);
dai::Device d(p);
}
// setBlobPath
TEST_CASE("OpenVINO 2020.3 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2020_3_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2020_3);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2020.4 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2020_4_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2020_4);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.1 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2021_1_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_1);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.2 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2021_2_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_2);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.3 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2021_3_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_3);
dai::Device d(p);
}
TEST_CASE("OpenVINO 2021.4 blob") {
dai::Pipeline p;
auto nn = p.create<dai::node::NeuralNetwork>();
nn->setBlobPath(OPENVINO_2021_4_BLOB_PATH);
auto networkOpenvinoVersion = p.getOpenVINOVersion();
REQUIRE(networkOpenvinoVersion == dai::OpenVINO::VERSION_2021_4);
dai::Device d(p);
}
// Check if an exception is thrown if blob is corrupted
TEST_CASE("OpenVINO corrupted blob") {
std::ifstream stream(OPENVINO_2021_4_BLOB_PATH, std::ios::in | std::ios::binary);
std::vector<std::uint8_t> blobData(std::istreambuf_iterator<char>(stream), {});
// Corrupt blob by removing half the file size
blobData.resize(blobData.size() / 2);
REQUIRE_THROWS(dai::OpenVINO::Blob(blobData));
}
| 33.57672 | 127 | 0.689253 | [
"vector"
] |
9e4238c284ddb3c3c992672e6f108c1b95648569 | 3,447 | cpp | C++ | chap7/chap7-1.3.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | chap7/chap7-1.3.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | chap7/chap7-1.3.cpp | liangzai90/Amazing-Algorithm-With-C | d1e992517eafd9197075d85591ed5270d945b5e3 | [
"Apache-2.0"
] | null | null | null | /*
数据结构趣题
在原表空间进行链表的归并
有两个按元素值递增有序排列的链表L1,L2,
编写一个程序将L1,L2,归并为一个按元素值递增有序的链表L3
要求:
1.链表中允许有相同元素,只要链表L1,L2,L3单调不减即可
2.要利用原表空间(即L1,L2,L3)的结点空间构造表L3.
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <vector>
#include <malloc.h>
using namespace std;
typedef int ElementType;
typedef struct node
{
ElementType data;//数据域
struct node* next;//指针域
}LNode,*LinkList;
LinkList CreateLink(int count)
{
LinkList pNewNode = NULL;//新加入的元素
LinkList pMove = NULL;////定义一个可移动的指针,用来串联各个元素
LinkList list = NULL;//保存头结点指针
ElementType numb;
for (int i = 1; i <= count; i++)
{
scanf("%d", &numb);
pNewNode = (LNode*)malloc(sizeof(LNode));
pNewNode->data = numb;
pNewNode->next = NULL;
if (list == NULL)
{
list = pNewNode;//保存第1个结点的指针地址
}
else
{
pMove->next = pNewNode;
}
// pMove 串联起整个链表
pMove = pNewNode;//在第一次创建的时候,r也指向了p,这就让后续所有 元素 都串联起来了
}
return list;
}
void PrintLink(LinkList list)
{
printf("\r\nprintLinkList:");
while (list != NULL)
{
printf("%3d,", list->data);
list = list->next;
}
printf("\r\n");
}
//除非传入的是一个LinkList的引用,否则,必须传入LinkList*,指向指针的指针
// 函数参数,总是会把当前参数做一个拷贝,而且当前参数的修改是无意义的,跳出了函数,是不会生效的
// 因此,这里需要传入指针的指针,这样,函数就拷贝了指针的指针,但是我们在函数里面是修改的指针指向的值,,因此这里的修改会生效,跳出了函数依然生效
void inserNode(LinkList* list, ElementType data)
{
LNode* p = (LNode*)malloc(sizeof(LNode));
p->data = data;
p->next = NULL;
LinkList listTail = (*list);
while (listTail != NULL && listTail->next != NULL)
{
listTail = listTail->next;
}
if ((*list) == NULL)
{
*list = p;
}
else
{
p->next = listTail->next;
listTail->next = p;
}
}
void destroyList(LinkList* list)
{
while ((*list) != NULL)
{
LNode* p = (*list);
(*list) = (*list)->next;
free(p);
}
(*list) = NULL;
}
//合并2个链表,将1合并到2里面
void mergeTwoLinkList(LinkList* listOne, LinkList* listTwo)
{
LinkList* listAHead = listOne;
LinkList* listBHead = listTwo;
LNode* nodeA = NULL;
LNode* nodeB = NULL;
LNode* nodeTemp = NULL;
nodeA = (*listAHead);
nodeB = (*listBHead);
while (nodeA != NULL)
{
//头部插入元素
if (nodeA->data <= nodeB->data)
{
nodeTemp = nodeA->next;
nodeA->next = nodeB;//结点A加入到表头
(*listBHead) = nodeA;//更新链表头
nodeA = nodeTemp;//nodeA 往下移
nodeB = (*listBHead);/////****此处记得修改nodeB的值
}
else
{
if (nodeB->next == NULL)
{
//直接插入后面所有元素
nodeB->next = nodeA;
break;//退出while循环,否则会死循环
}
else
{
///寻找nodeA插入的位置,就是nodeB->next的地方
while (nodeB->next != NULL)
{
if (nodeA->data > nodeB->next->data)
{
nodeB = nodeB->next;
}
else
{
break;//退出while循环,否则会死循环
}
}
if (nodeB->next != NULL)
{
//在nodeB之后插入NodeA
nodeTemp = nodeA->next;
nodeA->next = nodeB->next;
nodeB->next = nodeA;
nodeA = nodeTemp;
nodeB = nodeB->next;
}
else
{
//直接插入后面所有元素
nodeB->next = nodeA;
break;//退出while循环,否则会死循环
}
}
}
}
}
int main()
{
LinkList listOne = NULL;
LinkList listTwo = NULL;
listOne = CreateLink(8);
PrintLink(listOne);
printf("Please input some integer.and type 0 for end. \r\n");
int n;
scanf("%d", &n);
while (n)
{
inserNode(&listTwo, n);
scanf("%d", &n);
}
PrintLink(listTwo);
mergeTwoLinkList(&listOne, &listTwo);
PrintLink(listTwo);
cout << endl;
cout << "Hello World C Algorithm." << endl;
system("pause");
return 0;
}
| 15.668182 | 74 | 0.616478 | [
"vector",
"3d"
] |
9e4476b1119699bd9c845dc7e80a6b964609bdcf | 32,321 | cc | C++ | src/amuse/community/smalln/src/analyze.cc | rknop/amuse | 85d5bdcc29cfc87dc69d91c264101fafd6658aec | [
"Apache-2.0"
] | 131 | 2015-06-04T09:06:57.000Z | 2022-02-01T12:11:29.000Z | src/amuse/community/smalln/src/analyze.cc | rknop/amuse | 85d5bdcc29cfc87dc69d91c264101fafd6658aec | [
"Apache-2.0"
] | 690 | 2015-10-17T12:18:08.000Z | 2022-03-31T16:15:58.000Z | src/amuse/community/smalln/src/analyze.cc | rieder/amuse | 3ac3b6b8f922643657279ddee5c8ab3fc0440d5e | [
"Apache-2.0"
] | 102 | 2015-01-22T10:00:29.000Z | 2022-02-09T13:29:43.000Z |
// Analysis routines for use with smallN. Based on the Starlab
// version, with a custom class to make it self-contained. The only
// externally visible functions are
//
// int check_structure(hdyn *bin, bool verbose = true)
// hdyn *get_tree(hdyn *bin)
//
// NOTES: The original code code used Starlab stories to track
// critical information. Stories are handy, but maybe too much to
// implement here. The relevant story quantities are "E",
// "escaping_cpt", "escaper", "periastron ratio", and "stable":
//
// - in a CM node, E is the relative energy (per unit reduced
// mass) of the two (bound) components
//
// - in a CM node, escaping_cpt is true if one or more daughter
// nodes is escaping; in practice, the CM node is the root node
//
// - a (top-level) node is flagged with escaper = true if it is
// escaping
//
// - in a multiple CM node, periastron_ratio is the ratio of outer
// periastron to inner semi-major axis (forms the basis for a
// simple stability criterion)
//
// - in a multiple CM node, stable = true means that the multiple
// can be regarded as stable; a multiple with stable = false
// may be promoted to stable if its configuration remains
// unchanged for an extended quarantine period
//
// Implement these here as extra public variables in the derived hdyn2
// class.
//
// The code also uses labels in addition to indices to represent node
// names. Again, these are implemented in class hdyn2, which is local
// to this file.
#include "hdyn.h"
#include <cstring>
#include "nstab.h"
#ifndef TOOLBOX
#define local static
class hdyn2 : public hdyn
{
private:
string name;
public:
real relative_energy;
real periastron_ratio;
bool escaping_cpt;
bool escaper;
bool stable;
hdyn2() : hdyn() {
relative_energy = periastron_ratio = 0;
escaping_cpt = escaper = stable = false;
}
hdyn2 *get_parent() const {return (hdyn2*)parent;}
hdyn2 *get_oldest_daughter() const {return (hdyn2*)oldest_daughter;}
hdyn2 *get_younger_sister() const {return (hdyn2*)younger_sister;}
hdyn2 *get_older_sister() const {return (hdyn2*)older_sister;}
void set_name(char *id) {name = id;}
void set_name(string id) {name = id;}
const string get_name() const {return name;}
const char *format_label() const;
int n_leaves() {int n = 0; for_all_leaves(hdyn2, this, b) n++; return n;}
};
#define BUF_SIZE 1024
static char format_string[BUF_SIZE];
const char* hdyn2::format_label() const
{
// Precedence: print name string if defined
// otherwise, print index if non-negative
// otherwise, print '?'
if (name.size() > 0) {
strncpy(format_string, name.c_str(), BUF_SIZE-1);
format_string[BUF_SIZE-1] = '\0';
} else if(index >= 0)
sprintf(format_string, "%d", index);
else
sprintf(format_string, "?");
return format_string;
}
const char *string_index_of_node(hdyn2 *n)
{
if (n->get_name().size() > 0) {
return n->get_name().c_str();
} else {
static char integer_id[20];
sprintf(integer_id, "%d", n->get_index());
n->set_name(integer_id);
return n->get_name().c_str();
}
}
local const char *construct_binary_label(hdyn2 *ni, hdyn2 *nj)
{
static char new_name[256];
sprintf(new_name,"(%s,%s)", string_index_of_node(ni),
string_index_of_node(nj));
return new_name;
}
local void label_binary_node(hdyn2 *n)
{
if (n->is_root()) return;
for_all_daughters(hdyn2, n, nn) label_binary_node(nn);
if (!n->is_leaf()) {
hdyn2* od = n->get_oldest_daughter();
hdyn2* yd = od->get_younger_sister();
n->set_name(construct_binary_label(od, yd));
}
}
hdyn2 *flat_copy_tree(hdyn *bin)
{
// Flatten the input tree into a new tree, and return a pointer to
// the result.
hdyn2 *b = new hdyn2(), *bo = NULL, *by = NULL;
b->set_parent(NULL);
b->set_mass(0);
b->set_name((char*)"root");
for_all_leaves(hdyn, bin, bb) { // bb is hdyn, others are hdyn2
bo = by;
by = new hdyn2();
if (!b->get_oldest_daughter())
b->set_oldest_daughter(by);
if (bo)
bo->set_younger_sister(by);
by->set_parent(b);
by->set_older_sister(bo);
by->set_younger_sister(NULL);
by->set_index(bb->get_index());
by->set_mass(bb->get_mass());
b->set_mass(b->get_mass()+bb->get_mass());
by->set_pos(bb->get_pos());
by->set_vel(bb->get_vel());
by->set_radius(bb->get_radius());
hdyn *pp = bb->get_parent();
while (pp != bin) {
by->inc_pos(pp->get_pos());
by->inc_vel(pp->get_vel());
pp = pp->get_parent();
}
}
b->set_system_time(bin->get_system_time());
return b;
}
hdyn *flat_copy(hdyn *b) {return (hdyn*)flat_copy_tree(b);}
local vec relative_pos(hdyn2 *b, hdyn2 *bb)
{
// Return the position of bb relative to its ancestor b.
vec pos = bb->get_pos();
while (bb != b) {
hdyn2 *p = bb->get_parent();
pos += p->get_pos();
bb = p;
}
return pos;
}
local vec relative_vel(hdyn2 *b, hdyn2 *bb)
{
// Return the velocity of bb relative to its ancestor b.
vec vel = bb->get_vel();
while (bb != b) {
hdyn2 *p = bb->get_parent();
vel += p->get_vel();
bb = p;
}
return vel;
}
local inline real get_potential(hdyn2 *bi, hdyn2 *bj)
{
// Compute the total potential energy of node bi relative to its
// sister node node bj. Compute the potential energy exactly, by
// including all leaves, not using the center of mass
// approximation.
real phi = 0;
hdyn2 *p = bi->get_parent(); // should also be bj->get_parent()
for_all_leaves(hdyn2, bi, ii) {
vec posi = relative_pos(p, ii);
for_all_leaves(hdyn2, bj, jj) {
vec posj = relative_pos(p, jj);
phi -= ii->get_mass()*jj->get_mass()/abs(posi-posj);
}
}
return phi;
}
local real get_relative_energy(hdyn2 *bi, hdyn2 *bj)
{
// Return the relative energy (per unit reduced mass) of nodes bi
// and bj.
hdyn2 *p = bi->get_parent(); // p should be root
//vec xi = relative_pos(p, bi);
//vec xj = relative_pos(p, bj);
vec vi = relative_vel(p, bi);
vec vj = relative_vel(p, bj);
real mi = bi->get_mass();
real mj = bj->get_mass();
real mu_inv = (mi+mj)/(mi*mj);
return 0.5*square(vi-vj) + mu_inv*get_potential(bi, bj);
}
local void combine_nodes(hdyn2 *bi, hdyn2 *bj)
{
// Make these particles into a binary node.
// Create the CM node.
real mtot = bi->get_mass() + bj->get_mass();
vec cmpos = (bi->get_mass()*bi->get_pos()
+ bj->get_mass()*bj->get_pos()) / mtot;
vec cmvel = (bi->get_mass()*bi->get_vel()
+ bj->get_mass()*bj->get_vel()) / mtot;
hdyn2 *cm = new hdyn2();
cm->set_mass(mtot);
cm->set_pos(cmpos);
cm->set_vel(cmvel);
// Offset components to the center of mass frame.
bi->inc_pos(-cm->get_pos());
bj->inc_pos(-cm->get_pos());
bi->inc_vel(-cm->get_vel());
bj->inc_vel(-cm->get_vel());
// Restructure the tree to create the binary (bi,bj). The new CM
// node is cm.
create_binary_node(cm, bi, bj);
label_binary_node(cm);
}
local inline real separation_squared(hdyn2 *bi, hdyn2 *bj)
{
return square(bi->get_pos()-bj->get_pos());
}
local inline real size_squared(hdyn2 *b)
{
if (!b->is_parent()) return 0;
hdyn2 *od = b->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
return separation_squared(od, yd);
}
local bool is_lightly_perturbed(hdyn2 *b, hdyn2 *bi, hdyn2 *bj,
real pmax2 = MAX_PERT_SQ)
{
real mtot = bi->get_mass() + bj->get_mass();
vec cm = (bi->get_mass()*bi->get_pos() + bj->get_mass()*bj->get_pos())
/ mtot;
real mr3_ij_sq = 0.25 * mtot * mtot
/ pow(square(bi->get_pos()-bj->get_pos()), 3);
real max_pert_sq = 0;
// hdyn2 *max_pert_bb = NULL;
for_all_daughters(hdyn2, b, bb)
if (bb != bi && bb != bj) {
real r3_sq = square(bb->get_pos() - cm);
real pert_sq = pow(bb->get_mass(), 2) / pow(r3_sq, 3);
if (pert_sq > max_pert_sq) {
max_pert_sq = pert_sq;
// max_pert_bb = bb;
}
}
return (max_pert_sq < pmax2*mr3_ij_sq);
}
#define PRINT_DETAILS 0
local void decompose(hdyn2 *b, real pmax2 = MAX_PERT_SQ)
{
// Construct a binary tree by recursively pairing the top-level
// particles with the greatest binding energy. Don't pair if
// strongly perturbed.
while (true) {
// Look for the most bound pair among the current top-level nodes.
if (PRINT_DETAILS) {
cout << "top level:";
for_all_daughters(hdyn2, b, bi)
cout << " " << bi->format_label();
cout << endl << flush;
}
real min_energy = 0;
hdyn2 *bimin = NULL;
hdyn2 *bjmin = NULL;
// Slightly wasteful to recompute all pairwise energies every
// time around (really only a problem for N >> 3)...
for_all_daughters(hdyn2, b, bi)
for (hdyn2 *bj = bi->get_younger_sister(); bj != NULL;
bj = bj->get_younger_sister()) {
real Eij = get_relative_energy(bi, bj);
if (PRINT_DETAILS) {
cout << " " << bi->format_label();
cout << " " << bj->format_label() << " ";
PRL(Eij);
}
if (Eij < min_energy
&& is_lightly_perturbed(b, bi, bj, pmax2)) {
min_energy = Eij;
bimin = bi;
bjmin = bj;
}
}
if (bimin && bjmin) combine_nodes(bimin, bjmin);
else break;
}
}
local void compute_relative_energy(hdyn2 *b)
{
for_all_nodes(hdyn2, b, bb)
if (bb->get_parent() && bb->is_parent()) { // bb may be root, note
hdyn2 *od = bb->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
// Note: 2-body energy will be too crude if (e.g.) the
// components of one sister node are widely separated and
// the CM happens to lie close to the other sister.
// Better to compute the relative potential energy
// exactly. Note also that the energies stored are per
// unit reduced mass.
real mu_inv = bb->get_mass()/(od->get_mass()*yd->get_mass());
real E = 0.5*square(od->get_vel()-yd->get_vel())
+ mu_inv*get_potential(od, yd);
bb->relative_energy = E; // STORY
}
}
#define TOL 1.e-12
local bool is_escaper(hdyn2 *b, hdyn2 *bi)
{
// An escaper is a (top-level) particle having positive energy
// relative to all other top-level nodes as well as their CM, and
// moving away from the CM. Also, all top-level nodes should be
// receding (Steve, 1/2017).
bool esc1 = true;
bool receding = true;
real mi = bi->get_mass();
vec xi = bi->get_pos();
vec vi = bi->get_vel();
float mcm = 0;
vec rcm = 0; // CM of all other top-level particles
vec vcm = 0;
real phicm = 0;
real Emin = 0;
hdyn2 *bmin = NULL;
for_all_daughters(hdyn2, b, bj)
if (bj != bi) {
real mj = bj->get_mass();
vec xj = bj->get_pos();
vec vj = bj->get_vel();
mcm += mj;
rcm += mj*bj->get_pos();
vcm += mj*vj;
real mu_inv = (mi+mj)/(mi*mj);
real dphi = get_potential(bi, bj);
phicm += dphi;
real Eij = 0.5*square(vi-vj) + mu_inv*dphi;
esc1 &= (Eij > 0);
if (Eij < 0 && Eij < Emin) {
Emin = Eij;
bmin = bj;
}
receding &= ((vj-vi)*(xj-xi) > 0); // new 1/2017
}
bool esc = esc1 && receding; // new 1/2017
if (esc && mcm > 0) {
rcm = rcm/mcm;
vcm = vcm/mcm;
real r2 = square(xi-rcm);
real v2 = square(vi-vcm);
real vr = (vi-vcm)*(xi-rcm);
esc &= (vr > -TOL*sqrt(v2*r2)
&& 0.5*mi*mcm*square(vi-vcm)/(mi+mcm) + phicm > 0);
}
#if 0
if (!esc) {
if (!esc1) {
cout << "particle " << bi->format_label() << " is bound to ";
cout << bmin->format_label() << " (" << Emin << ")"
<< endl << flush;
} else {
cout << "particle " << bi->format_label()
<< " is bound to the system CM"
<< endl << flush;
}
}
#endif
return esc;
}
local void flag_escapers(hdyn2 *b)
{
for_all_daughters(hdyn2, b, bi)
if (is_escaper(b, bi)) {
b->escaping_cpt = true; // STORY
bi->escaper = true; // STORY
}
}
local real get_semi(hdyn2 *b)
{
// Return the semi-major-axis of the binary formed by the
// (presumably bound) components of b. By construction, we should
// have an energy already stored in the hdyn2 "story."
real semi = -1;
if (b->is_parent()) {
if (b->relative_energy != 0) {
real E = b->relative_energy; // STORY
if (E < 0) semi = -0.5*b->get_mass()/E;
} else {
// Looks like we have to compute the energy from scratch.
// Really do use the 2-body expression here.
hdyn2 *od = b->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
real E = 0.5*square(od->get_vel()-yd->get_vel())
- b->get_mass()/abs(od->get_pos()-yd->get_pos());
if (E < 0) semi = -0.5*b->get_mass()/E;
}
}
return semi;
}
// Code from Starlab:
local inline bool harrington_stable(real m12, real m3,
real peri_fac, real cos_i)
{
// Use a simple distance criterion with an extra mass term that
// goes to 1 for equal-mass systems. The Harrington (1972)
// criterion ranges from outer_peri/inner_semi ~ 3.5 for planar
// prograde orbits (cos_i = 1) to ~2.75 for planar retrograde
// (cos_i = -1). The overall factor can be adjusted, but the
// inclination variation preserves this ratio.
const real HARRINGTON_FAC = 3.5; // (NB Starlab uses 3.25)
const real HARRINGTON_RATIO = 25.0/3;
// Ratio quantifies "closeness to stability."
real ratio = (peri_fac * pow(m12/m3, 1./3))
/ (HARRINGTON_FAC * (HARRINGTON_RATIO+cos_i)
/ (HARRINGTON_RATIO+1));
return (ratio > 1);
}
local inline bool aarseth_stable(real m12, real m3,
real e_outer, real peri_fac, real cos_i)
{
// The Mardling and Aarseth (1999) stability criterion is
//
// outer_peri/inner_semi > AARSETH_STABLE_FAC
// * [ (1 + q_outer)
// * (1 + e_outer)
// / sqrt(1 - e_outer) ] ^(2/5).
//
// This criterion omits an inclination factor that should
// effectively reduce the critical outer periastron by about 30%
// for retrograde orbits relative to prograde orbits. Aarseth
// (2003) recommends an additional factor linear in the
// inclination to correct this.
const real AARSETH_FAC = 2.8; // don't change!
const real AARSETH_RATIO = 23.0/3; // (basically the same as the
// Harrington ratio above)
real q_outer = m3/m12;
real ratio = (peri_fac * pow((1+q_outer)*(1+e_outer)/sqrt(1-e_outer), -0.4))
/ (AARSETH_FAC * (AARSETH_RATIO+cos_i) / (AARSETH_RATIO+1));
return (ratio > 1);
}
local inline bool mardling_stable(kepler& outerkep, kepler& innerkep,
real m1, real m2, real m3, real cos_i)
{
// Apply the Mardling (2007) criterion. No free parameters!
// First apply a couple of extra checks not in the Mardling
// function, but included in the Aarseth nbody6 version:
// 1. Reject outer pericenter inside inner apocenter.
if (outerkep.get_periastron() < innerkep.get_apastron()) return false;
// 2. Reject period ratio < 1.
real sigma = outerkep.get_period()/innerkep.get_period();
if (sigma < 1) return false;
// Create parameters for the Mardling function:
//
// sigma = period ratio (outer/inner) ** should be > 1 **
// ei0 = initial inner eccentricity
// eo = outer eccentricity
// relinc = relative inclination (radians)
// m1, m2, m3 = masses (any units; m3=outer body)
real ei0 = innerkep.get_eccentricity();
real eo = outerkep.get_eccentricity();
real relinc = acos(cos_i);
// A return value of 1 from nstab_ means that we can't treat this
// object as stable. No in between!
return (nstab_(&sigma, &ei0, &eo, &relinc, &m1, &m2, &m3) != 1);
}
local bool is_stable(hdyn2 *b)
{
// Determine the stability of the multiple with top-level center
// of mass b.
hdyn2 *od = b->get_oldest_daughter();
if (!od) return false;
hdyn2 *yd = od->get_younger_sister();
if (!yd) return false;
// Identify an "inner" binary. Presumably any multiples under b
// are stable. However, both components could be multiples, so
// choose the wider one. This stability criterion should perhaps
// be improved.
hdyn2 *b_in = od;
real a_in = get_semi(od);
if (get_semi(yd) > a_in) {
b_in = yd;
a_in = get_semi(yd);
}
if (a_in < 0) return false;
// Create a kepler structure describing the outer orbit...
kepler outerkep;
outerkep.set_time(0);
outerkep.set_total_mass(b->get_mass());
outerkep.set_rel_pos(yd->get_pos()-od->get_pos());
outerkep.set_rel_vel(yd->get_vel()-od->get_vel());
outerkep.initialize_from_pos_and_vel(true);
b->periastron_ratio = outerkep.get_periastron() / a_in; // STORY
// ...and another describing the inner orbit.
hdyn2 *od_in = b_in->get_oldest_daughter();
if (!od_in) return false;
hdyn2 *yd_in = od_in->get_younger_sister();
if (!yd_in) return false;
kepler innerkep;
innerkep.set_time(0);
innerkep.set_total_mass(b_in->get_mass());
innerkep.set_rel_pos(od_in->get_pos() - yd_in->get_pos());
innerkep.set_rel_vel(od_in->get_vel() - yd_in->get_vel());
innerkep.initialize_from_pos_and_vel();
real cos_i = innerkep.get_normal_unit_vector()
* outerkep.get_normal_unit_vector();
// Harrington criterion.
bool hstable = harrington_stable(od->get_mass(), yd->get_mass(),
b->periastron_ratio, cos_i);
// Aarseth criterion.
bool astable = aarseth_stable(od->get_mass(), yd->get_mass(),
outerkep.get_eccentricity(),
b->periastron_ratio, cos_i);
// Mardling criterion.
bool mstable = mardling_stable(outerkep, innerkep,
od_in->get_mass(), yd_in->get_mass(),
b_in->get_binary_sister()->get_mass(),
cos_i);
if ((mstable && (!hstable || !astable)) // flag discrepancy
|| (!mstable && (hstable || astable))) {
PRC(hstable); PRC(astable); PRL(mstable);
}
// Choose Mardling.
return mstable;
}
local bool check_stability(hdyn2 *b)
{
// Stablility criterion for a CM node is that both daughters are
// stable and sufficiently widely separated. We currently don't
// include external perturbations explicitly in the decision, but
// note that we have already applied a perturbation condition in
// constructing the tree.
bool stable = false;
b->stable = false;
if (b->is_leaf()) // single stars are stable
stable = true;
else {
hdyn2 *od = b->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
if (od->is_leaf() && yd->is_leaf()) {
if (b->relative_energy < 0) // STORY
stable = true;
} else {
// Check both daughters (don't && these tests in the if
// statement because this could skip the second check).
bool od_stab = check_stability(od);
bool yd_stab = check_stability(yd);
if (od_stab && yd_stab)
if (b->relative_energy < 0) { // STORY
stable = is_stable(b);
}
}
}
if (stable) b->stable = true; // STORY
return stable;
}
local void check_stability_master(hdyn2 *b)
{
for_all_daughters(hdyn2, b, bd) {
//cout << "checking "; PRL(bd->format_label());
bd->stable = false;
if (bd->is_leaf()) {
if (is_escaper(b, bd)) bd->stable = true; // STORY
} else
if (check_stability(bd)) bd->stable = true; // STORY
//PRL(bd->stable);
}
}
local void print_recursive(hdyn2 *b, bool verbose, int indent = 0)
{
for (int i = 0; i < indent; i++) cout << " ";
cout << b->format_label() << ":";
// Notes: (1) relative_energy is stored in a binary CM and refers
// to the components
// (2) escaping_cpt means that one or more components of
// a binary CM is escaping
// (3) stable refers to the CM
if (b->is_parent()) {
if (b->n_leaves() > 2) cout << " multiple";
else if (b->n_leaves() == 2) cout << " binary";
if (b->escaping_cpt) // STORY
cout << " escaping_components";
real E = b->relative_energy; // STORY
if (E < 0) {
cout << " bound_components E = " << E;
real sep = b->periastron_ratio; // STORY
if (sep > 0) cout << " (" << sep << ")";
} else if (E > 0)
cout << " unbound_components E = " << E;
if (b->stable && b->n_leaves() > 2) // STORY
cout << " stable";
} else
cout << " single";
if (b->escaper) // STORY
cout << " escaper";
if (verbose && b->is_parent() && !b->is_root()) {
hdyn2 *od = b->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
if (od && yd) {
cout << endl; PRI(indent);
print_orbital_elements(od, yd, false);
}
} else
cout << endl;
cout << flush;
for_all_daughters(hdyn2, b, bb) print_recursive(bb, verbose, indent+2);
}
local inline void set_string_node_name(hdyn2 *b, char *s)
{
if (b->get_name().size() > 0)
strcpy(s, b->get_name().c_str()); // NB no size check...
else if (b->get_index() >= 0)
sprintf(s, "%d", b->get_index());
else
strcpy(s, "-");
}
local const char *string_index_copy(hdyn2 *n)
{
if (n->get_name().size() == 0) {
char integer_id[20];
sprintf(integer_id, "%d", n->get_index());
n->set_name(integer_id);
}
return n->get_name().c_str();
}
local void create_summary_strings(hdyn2 *b,
string& summary, string& this_state)
{
// Construct summary and state strings describing the system.
for_all_daughters(hdyn2, b, bi) {
if (!bi->is_parent()) {
string index = string_index_copy(bi);
this_state += "s";
this_state += index;
this_state += " ";
if (bi->relative_energy >= 0) { // STORY
summary += "<";
summary += index;
summary += "> ";
} else if (bi->stable) { // STORY
summary += "[";
summary += index;
summary += "] ";
} else {
summary += "(";
summary += index;
summary += ") ";
}
} else {
int mult = bi->n_leaves();
if (mult==2) this_state += "b";
if (mult==3) this_state += "t";
if (mult==4) this_state += "q";
if (mult==5) this_state += "v";
if (mult >5) this_state += "x";
int low = 10000;
int last = 0;
int track = 0;
while (track == 0) {
track = 1;
string next_num;
for_all_leaves(hdyn2, bi, l) {
if (l->get_index() < low && l->get_index() > last) {
low = l->get_index();
track = 0;
next_num = string_index_copy(l);
}
}
last = low;
low = 10000;
this_state += next_num;
}
this_state += " ";
if (bi->relative_energy >= 0) // STORY
summary += "<";
else if (bi->stable || bi->n_leaves() <=2) // STORY
summary += "[";
else
summary += "(";
hdyn2 *od = bi->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
int index_od = od->get_index();
int index_yd = yd->get_index();
string name1 = string_index_copy(od);
string name2 = string_index_copy(yd);
if ( index_od > 0 && index_yd > 0) {
summary += name1;
summary += ",";
summary += name2;
} else if ( index_od > 0) {;
summary += name1;
summary += ",";
summary += yd->get_name();
} else if ( index_yd > 0) {
summary += od->get_name();
summary += ",";
summary += name2;
} else {;
summary += od->get_name();
summary += ",";
summary += yd->get_name();
}
if (bi->relative_energy >= 0) // STORY
summary += "> ";
else if (bi->stable || bi->n_leaves() <= 2) // STORY
summary += "] ";
else
summary += ") ";
}
}
}
local hdyn2 *get_tree2(hdyn *bin, real pmax2 = MAX_PERT_SQ)
{
// Determine the current structure and return the annotated tree.
// Start by copying the tree to a flat hdyn2 tree; then identify
// structure by proximity (actually potential) and dynamics (bound
// or not). Then classify bound systems by their stability
// properties.
hdyn2 *b = flat_copy_tree(bin);
decompose(b, pmax2);
// Determine the binding energy of each node. Note that the order
// of for_all_nodes() means that this function and the next could
// probably be merged, but don't assume that here. Function sets
// the relative_energy "story" value.
for_all_daughters(hdyn2, b, bi) compute_relative_energy(bi);
// Descend the tree to look for escapers (simply unbound, since
// that is what the dynamical code will care about). Note that we
// use the softening from the external program in making this
// decision. Function sets the escaping_cpt and escaper "story"
// values.
flag_escapers(b);
// Ascend the tree looking for widely separated binaries.
// Function sets the stable and periastron_ratio "story" values.
check_stability_master(b);
return b;
}
// Manage quarantining of quasi-stable systems. If a multiple cannot
// be confirmed as stable, but the interaction is otherwise over,
// declare the multiple quasi-stable if the system configuration
// survives without changing state for some specified period of time.
// Currently, we simply count calls to check_structure, but probably
// we want to follow the system for some number of outer multiple
// periods. TODO.
static string last_state;
static int state_count = 0;
static real state_time = 0;
const int min_qstable_count = 15;
local inline bool is_quasi_stable(hdyn2 *b)
{
bool verbose = true;
if (state_count >= min_qstable_count) {
real max_period = 0;
if (verbose) cout << "checking quasistability..." << endl << flush;
for_all_daughters(hdyn2, b, bi) {
if (!bi->stable) { // STORY
if (verbose)
cout << bi->format_label() << " is not stable"
<< endl << flush;
hdyn2 *od = bi->get_oldest_daughter();
hdyn2 *yd = od->get_younger_sister();
kepler k;
k.set_time(0);
k.set_total_mass(od->get_mass()+yd->get_mass());
k.set_rel_pos(yd->get_pos()-od->get_pos());
k.set_rel_vel(yd->get_vel()-od->get_vel());
k.initialize_from_pos_and_vel(true);
//PRC(k.get_separation()); PRL(k.get_period());
//PRC(k.get_semi_major_axis()); PRL(k.get_apastron());
if (k.get_period() > max_period) max_period = k.get_period();
}
//PRL(max_period);
}
// The basic requirement for quasistability was that the
// configuration remain unchanged for 10 times the maximum
// orbital period in the system -- 10 outer orbits, in
// practice. Better just to look for repeat configurations.
// bool quasi = b->get_system_time()-state_time > 10*max_period;
bool quasi = state_count > min_qstable_count;
if (verbose) {
PRC(b->get_system_time()); PRL(state_time);
PRC(b->get_system_time()-state_time); PRL(max_period);
cout << "quasi-stable = " << quasi << endl << flush;
}
return quasi;
}
return false;
}
local inline int is_over(hdyn2 *b, bool verbose)
{
int over = 1;
// print_recursive(b, verbose);
for_all_daughters(hdyn2, b, bi) {
//PRL(bi->format_label());
if (!is_escaper(b, bi)) over = 0;
}
//PRC(1); PRL(over);
bool stable = true;
for_all_daughters(hdyn2, b, bi)
if (!bi->stable) stable = false; // STORY
//PRC(2); PRL(stable);
if (over) { // over here means all top level are escaping
if (stable) {
//if (verbose)
cout << "is_over: normal termination: "
<< last_state << endl << flush;
} else {
if (is_quasi_stable(b))
over = 2;
else
over = 0;
//if (over && verbose)
if (over)
cout << "is_over: quasi-stable termination: "
<< last_state << endl << flush;
}
}
return over; // return 0-2
}
//----------------------------------------------------------------------
// Externally visible functions:
int check_structure(hdyn *bin, // input root node
real rlimit2, // default = _INFINITY_
int verbose) // default = 1
{
if (verbose)
cout << endl << "checking structure at time "
<< bin->get_system_time() << endl;
// Decompose the system.
hdyn2 *b = get_tree2(bin);
string summary, curr_state;
create_summary_strings(b, summary, curr_state);
if (verbose > 1) {
// Print the results:
// Overall structure.
print_recursive(b, verbose > 1);
// Summary strings.
cout << "summary: " << summary << endl;
cout << "state: " << curr_state << endl << flush;
} else
if (verbose)
cout << "summary: " << summary << endl << flush;
// Count the latest run of unchanged state strings.
if (curr_state == last_state)
state_count += 1; // # times state unchanged
else {
state_count = 0;
state_time = bin->get_system_time(); // time state last changed
}
last_state = curr_state;
//PRC(curr_state); PRC(last_state); PRC(state_count); PRL(state_time);
// See if the interaction is over.
int over = is_over(b, verbose);
if (over && verbose) cout << endl << "interaction is over" << endl << flush;
#if 0
for_all_daughters(hdyn2, b, bb) {
cout << bb->get_index() << " " << bb->get_pos()
<< " " << bb->get_vel() << endl << flush;
}
#endif
if (!over && rlimit2 < _INFINITY_) // *same* test as in smallN
for_all_daughters(hdyn, bin, bi) {
real r2 = square(bi->get_pos());
// PRC(r2); PRL(rlimit2);
if (r2 > rlimit2) {
over = 3;
cout << "is_over: termination at rlimit" << endl << flush;
}
}
// Note: If over = 3, it is possible that get_tree2() didn't
// return usable hierarchical structure (e.g. an outer body
// escapes during an inner triple resonance). We will try to
// impose usable structure in the calling function by relaxing the
// perturbation criterion on the components, but no need to do
// anything here, since only the value of over is returned.
if (verbose && over) {
cout << "over = " << over << endl;
print_recursive(b, true);
cout << flush;
}
// Clean up and exit.
rmtree(b); // hdyn function OK (with virtual destructor)?
return over; // return 0-3
}
local hdyn *copy_tree2(hdyn2 *from_b)
{
// Make an hdyn copy of (the hdyn parts) of an hdyn2 tree, and
// return a pointer to it. Is there an easier way to extract the
// hdyn part of an hdyn2...?
hdyn *b = new hdyn();
b->copy_data_from((hdyn*)from_b); // cast is OK here to access data
if (from_b->get_parent() == NULL) b->set_parent(NULL);
hdyn *od = NULL;
for_all_daughters(hdyn2, from_b, bb)
if (!od) {
od = copy_tree2(bb);
od->set_parent(b);
b->set_oldest_daughter(od);
} else {
hdyn *yd = copy_tree2(bb);
yd->set_parent(b);
od->set_younger_sister(yd);
yd->set_older_sister(od);
od = yd;
}
return b;
}
hdyn *get_tree(hdyn *bin, real pmax2) // default = MAX_PERT_SQ
{
// Need to return an hdyn pointer from an hdyn2 object. A cast
// would return the correct data, but when rmtree() is called on
// the cast pointer there may be problems removing the hdyn2 part.
// Better to make an hdyn copy here and return that.
hdyn2 *b = get_tree2(bin, pmax2);
hdyn *bb = copy_tree2(b);
rmtree(b);
return bb;
}
#else
//#include <string>
//#include <unistd.h>
template <class Q>
bool get_quantity(string s, const char *q, Q& value)
{
size_t i = s.find(q);
if (i != string::npos) {
i = s.find("=", i);
if (i != string::npos) {
s = s.substr(i+1);
istringstream ss(s);
ss >> value;
return true;
}
}
return false;
}
void initialize(hdyn *b) // b = root node
{
int n = 0;
hdyn *bp = NULL, *bb = NULL;
string s;
while (getline(cin, s)) {
if (s[0] != ';') {
istringstream ss(s);
int i = -1;
real m;
vec x, v;
ss >> i >> m >> x >> v;
if (i < 0) break;
bb = new hdyn();
n++;
if (bp) {
bp->set_younger_sister(bb);
bb->set_older_sister(bp);
} else
b->set_oldest_daughter(bb);
bb->set_parent(b);
bb->set_index(i);
bb->set_mass(m);
bb->set_pos(x);
bb->set_vel(v);
bp = bb;
} else {
real t;
if (get_quantity(s, "system_time", t)) b->set_system_time(t);
int seed;
if (get_quantity(s, "seed", seed)) {PRL(seed); b->set_seed(seed);}
}
}
PRC(n); PRL(b->get_system_time());
}
int main(int argc, char *argv[])
{
hdyn *b = new hdyn;
initialize(b);
check_structure(b, true);
return 0;
}
#endif
| 27.092205 | 80 | 0.614121 | [
"object"
] |
eafb0cfa474057a5c97ff4c47fb11371a623c5d5 | 27,732 | cpp | C++ | src/Arabic/parse/ar_ChartDecoder.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Arabic/parse/ar_ChartDecoder.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Arabic/parse/ar_ChartDecoder.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
#include "Generic/parse/LanguageSpecificFunctions.h"
#include "Arabic/parse/ar_ChartDecoder.h"
#include "Arabic/parse/ar_WordSegment.h"
#include "Arabic/common/ar_ArabicSymbol.h"
#include "Arabic/parse/ar_ChartEntry.h"
#include "Generic/common/SessionLogger.h"
#include "Generic/theories/Entity.h"
#include "Generic/theories/EntityType.h"
#include "Arabic/common/ar_StringTransliterator.h"
#include <stdio.h>
#include <iostream>
#include "math.h"
char str[10000];
int buf_len = 10000;
/* return a parse that is (FRAG w w w w) except for Names, which have NPPs
*/
ParseNode* ArabicChartDecoder::_makeFlatParse(Symbol* sentence, int length,
Constraint* _constraints, int _numConstraints){
ParseNode* flat_parse = new ParseNode(ArabicSTags::FRAG);
int word = 0;
int curr_const =0;
flat_parse->headNode = new ParseNode();
ParseNode* currNode = flat_parse->headNode;
ParseNode* lastNode;
if(_numConstraints >0){
if(_constraints[0].left==0){
//add a NPP
addNPPNode(currNode, _constraints[0], sentence);
word = word+_constraints[0].right-_constraints[0].left+1;
curr_const++;
}
else{
addWordNode(currNode, sentence[word]);
word++;
}
}
else{
addWordNode(currNode, sentence[word]);
word++;
}
//ParseNode* currNode = flat_parse->postmods;
flat_parse->postmods = new ParseNode();
currNode = flat_parse->postmods;
while(word<length){
if((curr_const < _numConstraints) && (_constraints[curr_const].left == word)){
addNPPNode(currNode, _constraints[curr_const], sentence);
word = word+_constraints[curr_const].right-_constraints[curr_const].left+1;
curr_const++;
}
else{
addWordNode(currNode, sentence[word]);
word++;
}
currNode->next = new ParseNode();
lastNode = currNode;
currNode= currNode->next;
}
lastNode->next = NULL;
delete currNode;
highest_scoring_final_theory = 0;
theory_scores[0] = .1f;
return flat_parse;
}
void ArabicChartDecoder::addWordNode(ParseNode* currNode, Symbol word){
currNode->label = ArabicSTags::UNKNOWN;
currNode->headNode = new ParseNode(word);
}
void ArabicChartDecoder::addNPPNode(ParseNode* currNode, Constraint constraint, Symbol* sentence){
currNode->label = ArabicSTags::NPP;
currNode->headNode = new ParseNode(LanguageSpecificFunctions::getDefaultNamePOStag(constraint.entityType));
ParseNode* p = currNode->headNode;
p->headNode=new ParseNode(sentence[constraint.left]);
if(constraint.left != constraint.right){
currNode->postmods = new ParseNode(LanguageSpecificFunctions::getDefaultNamePOStag(constraint.entityType));
p = currNode->postmods;
for(int i =constraint.left+1; i<constraint.right; i++){
p->headNode = new ParseNode(sentence[i]);
p->next = new ParseNode(LanguageSpecificFunctions::getDefaultNamePOStag(constraint.entityType));
p = p->next;
}
p->headNode = new ParseNode(sentence[constraint.right]);
}
}
/* decode a sentence using bw derived tokenization */
ParseNode* ArabicChartDecoder::decode(SplitTokenSequence* bw_tokens, bool collapseNPlabels)
{
// make sure that the maximally segmented version still fits in the chart
// -- SRS
WordSegment seg;
// std::cout<<"D 1"<<std::endl;
int num_segments = 0;
for (int i = 0; i < bw_tokens->getNTokens(); i++)
num_segments += bw_tokens->getWordSegment(i)->maxLength();
// std::cout<<"D 2"<<std::endl;
if (num_segments >= MAX_SENTENCE_LENGTH) {
SessionLogger::logger->beginWarning();
*SessionLogger::logger << "Using a flat parse because there are"
"too many possible segments.\n";
//Returning an empty parse here leaves us without a name theory
//instead build a flat "FRAGMENT" parse with NPP for names
throw UnexpectedInputException(
"ArabicChartDecoder::Decode()","SplitTokenSequence has too many segments");
}
if(bw_tokens ==NULL){
std::cerr<<"bw_tokens is NULL"<<std::endl;
}
if(bw_tokens->getWordSegment(bw_tokens->getNTokens()-1) ==NULL){
std::cerr<<"bw_tokens last word is NULL"<<
bw_tokens->getNTokens()<<" tokens "<<
std::endl;
}
if(bw_tokens->getWordSegment(bw_tokens->getNTokens()-1)->getPossibility(0).segments ==NULL){
std::cerr<<"bw_tokens last word first segment segments is NULL"
<<bw_tokens->getNTokens()<< " tokens "<<std::endl;
}
bool lastIsPunct = LanguageSpecificFunctions::isSentenceEndingPunctuation(bw_tokens->getWordSegment(
bw_tokens->getNTokens()-1)->getPossibility(0).segments[0]->getText());
// std::cout<<"D 3"<<std::endl;
Symbol split_sentence[MAX_SENTENCE_LENGTH];
int chart_size = initChart(bw_tokens, split_sentence);
// std::cout<<"D 4"<<std::endl;
initPunctuationUpperBound(split_sentence, chart_size);
// std::cout<<"D 5"<<std::endl;
// std::cout<<"chart_size: "<<chart_size<<" \n";
for (int span = 2; span <= chart_size; span++) {
for (int start = 0; start <= (chart_size - span); start++) {
int end = start + span;
numTheories = 0;
if(DEBUG1){
_debugStream <<"---------start: "<<start<<" end: "<<end<<"\n";
_debugStream.flush();
}
for (int mid = (start + 1); mid < end; mid++) {
if ((end == chart_size) && lastIsPunct &&
!((mid == (chart_size - 1)) && (start == 0))) {
continue;
}
if (punctuationCrossing(start, end, chart_size)) {
continue;
}
leftClosable = !crossingConstraintViolation(start, mid);
rightClosable = !crossingConstraintViolation(mid, end);
for (ChartEntry** leftEntry = chart[start][mid - 1];
*leftEntry; ++leftEntry)
{
for (ChartEntry** rightEntry = chart[mid][end - 1];
*rightEntry; ++rightEntry)
{
addKernelTheories(*leftEntry, *rightEntry);
addExtensionTheories(*leftEntry, *rightEntry);
}
}
}
transferTheoriesToChart(start, end);
}
}
float finalScore;
postProcessChart();
ParseNode* returnValue = getBestParse(finalScore, 0, chart_size, false);
// std::cout<<"D 6"<<std::endl;
// diversity parsing iteration
ParseNode* iterReturnValue = returnValue;
while (iterReturnValue != 0) {
int replacementPosition = 0;
postprocessParse(iterReturnValue, collapseNPlabels);
addNameToParse(iterReturnValue, replacementPosition);
iterReturnValue = iterReturnValue->next;
}
// std::cout<<"D 7"<<std::endl;
cleanupChart(chart_size);
// std::cout<<"D 8"<<std::endl;
/* if(returnValue == NULL){
std::cout<<"EMPTY RETURN!!!\n";
}
else{
std::cout<<"RETURN VALUE EXISTS !! "<<finalScore<<"\n";
}
*/
//if(DEBUG2){
// _parseStream << returnValue->toWString();
// _parseStream <<"\n\n";
//}
std::wstring resultNoSpace = returnValue->readLeaves();
// std::cout<<"D 9"<<std::endl;
std::wstring sentNoSpace = L"";
for(int i =0; i< bw_tokens->getNTokens(); i++){
sentNoSpace += bw_tokens->getWordSegment(i)->getOriginalWord().to_string();
}
// std::cout<<"D 10"<<std::endl;
if(wcscmp(resultNoSpace.c_str(),sentNoSpace.c_str())!=0){
std::cerr<<"\nToken Sequence After Parsing is wrong Because of Marjorie\n";
Symbol sns = Symbol(sentNoSpace.c_str());
Symbol rns = Symbol(resultNoSpace.c_str());
std::cerr<<"Initial: "<<sns.to_debug_string()<<"\n";
std::cerr<<"After: "<<rns.to_debug_string()<<"\n";
}
return returnValue;
}
ParseNode* ArabicChartDecoder::decode(Symbol* sentence, int length,
Constraint* _constraints, int _numConstraints,
bool collapseNPlabels)
{
// make sure that the maximally segmented version still fits in the chart
// -- SRS
WordSegment seg;
int max_segments = 0;
for (int i = 0; i < length; i++)
max_segments += seg.getMaxSegments(sentence[i].to_string());
if( (max_segments >= MAX_SENTENCE_LENGTH) ) {
//if( (max_segments >=5)){
SessionLogger::logger->beginWarning();
*SessionLogger::logger << "Using a flat parse because there are"
"too many possible segments.\n";
//Returning an empty parse here leaves us without a name theory
//instead build a flat "FRAGMENT" parse with NPP for names
ParseNode* flatParse = _makeFlatParse(sentence, length, _constraints, _numConstraints);
return flatParse;
}
constraints = _constraints;
numConstraints = _numConstraints;
bool lastIsPunct = LanguageSpecificFunctions::isSentenceEndingPunctuation(sentence[length - 1]);
Symbol split_sentence[MAX_SENTENCE_LENGTH];
int chart_size = initChart(sentence, split_sentence, length);
initPunctuationUpperBound(split_sentence, chart_size);
for (int span = 2; span <= chart_size; span++) {
for (int start = 0; start <= (chart_size - span); start++) {
int end = start + span;
numTheories = 0;
for (int mid = (start + 1); mid < end; mid++) {
if ((end == chart_size) && lastIsPunct &&
!((mid == (chart_size - 1)) && (start == 0))) {
continue;
}
if (punctuationCrossing(start, end, chart_size)) {
continue;
}
leftClosable = !crossingConstraintViolation(start, mid);
rightClosable = !crossingConstraintViolation(mid, end);
for (ChartEntry** leftEntry = chart[start][mid - 1];
*leftEntry; ++leftEntry)
{
for (ChartEntry** rightEntry = chart[mid][end - 1];
*rightEntry; ++rightEntry)
{
addKernelTheories(*leftEntry, *rightEntry);
addExtensionTheories(*leftEntry, *rightEntry);
}
}
}
transferTheoriesToChart(start, end);
}
}
float finalScore;
postProcessChart();
ParseNode* returnValue = getBestParse(finalScore, 0, chart_size, false);
if(returnValue == NULL){
SessionLogger::logger->beginWarning();
*SessionLogger::logger << "Using a flat parse because parser failed\n";
ParseNode* flatParse = _makeFlatParse(sentence, length, _constraints, _numConstraints);
return flatParse;
}
// diversity parsing iteration
ParseNode* iterReturnValue = returnValue;
while (iterReturnValue != 0) {
int replacementPosition = 0;
postprocessParse(iterReturnValue, collapseNPlabels);
addNameToParse(iterReturnValue, replacementPosition);
iterReturnValue = iterReturnValue->next;
}
cleanupChart(chart_size);
//if(DEBUG2){
// _parseStream << returnValue->toWString();
// _parseStream <<"\n\n";
//}
std::wstring resultNoSpace = returnValue->readLeaves();
std::wstring sentNoSpace = L"";
for(int i =0; i< length; i++){
sentNoSpace += sentence[i].to_string();
}
if(wcscmp(resultNoSpace.c_str(),sentNoSpace.c_str())!=0){
std::cerr<<"\nToken Sequence After Parsing is wrong Because of Marjorie\n";
Symbol sns = Symbol(sentNoSpace.c_str());
Symbol rns = Symbol(resultNoSpace.c_str());
std::cerr<<"Initial: "<<sns.to_debug_string()<<"\n";
std::cerr<<"After: "<<rns.to_debug_string()<<"\n";
}
return returnValue;
}
/* For now ignore constraints....
* This is only used by the standalone parser when reading in BW input
*
*/
int ArabicChartDecoder::initChart(SplitTokenSequence* words, Symbol* split_sentence){
int m = 0; //m is the index into the original sentence
int chart_index = 0; //chart index is the current position in the chart
while(m < words->getNTokens()){
WordSegment* word_parts = words->getWordSegment(m);
//std::cout<<"Initialize: ";
//word_parts->printSegment();
//std::cout<<std::endl;
WordAnalysis longword = word_parts->getLongest();
for(int i = 0; i<word_parts->maxLength(); i++){
split_sentence[chart_index+i] = longword.segments[i]->getText();
}
chart_index = initChartWordMultiple(word_parts, chart_index, m ==0);
//chart_index+=word_parts->maxLength();
m++;
//delete word_parts; //reset would be better!
}
return chart_index;
}
/* simultaneously add constraints and morph analysis
returns the maximum number of tokens in the chart
*/
int ArabicChartDecoder::initChart(Symbol* sentence, Symbol* split_sentence, int length)
{
//initialize entire chart to 0 in preparation of post processing
/*
for(int i = 0; i < MAX_SENTENCE_LENGTH; i++){
for(int j = 0; j< MAX_SENTENCE_LENGTH; j++){
for(int k = 0; k<MAX_ENTRIES_PER_CELL; k++){
chart[i][j][k] = 0;
}
}
}
*/
//Assume constraints are in increasing order ?
int curr_const = 0;
int left = -1, right = -1;
Symbol type;
EntityType entityType;
if(numConstraints >0){
left = constraints[curr_const].left;
right = constraints[curr_const].right;
type = constraints[curr_const].type;
entityType = constraints[curr_const].entityType;
}
int chart_index = 0; //chart index is the current position in the chart
_numNameWords = 0;
int m = 0; //m is the index into the original sentence
while(m < length){
if(m ==left){
int name_len = right - left;
if(DEBUG1)
_debugStream<<"Adding Name Tokens: ";
int i = left;
int k = 0;
for(; i<=right; i++, k++){
//for postprocessing
_nameWords[_numNameWords++] =sentence[i];
split_sentence[chart_index+k] = sentence[i];
//debugging
if(DEBUG1){
Symbol debugSym = ArabicSymbol::BWSymbol(sentence[i].to_string());
_debugStream<<debugSym.to_debug_string()<<" ";
}
}
if(DEBUG1){
_debugStream<<"\n";
}
addConstraintEntry(left, right,chart_index, chart_index + name_len, sentence, type, entityType);
m = right +1;
curr_const++;
if(curr_const < numConstraints){
left = constraints[curr_const].left;
right = constraints[curr_const].right;
type = constraints[curr_const].type;
}
chart_index = chart_index+name_len +1;
}
else{
if(DEBUG1){
Symbol debugSym = ArabicSymbol::BWSymbol(sentence[m].to_string());
_debugStream<<"Adding Token: "<<m<<" "<<debugSym.to_debug_string()<<"\n";
}
WordSegment* word_parts = new WordSegment();
word_parts->getSegments(sentence[m]);
WordAnalysis longword = word_parts->getLongest();
for(int i = 0; i<word_parts->maxLength(); i++){
split_sentence[chart_index+i] = longword.segments[i]->getText();
}
chart_index = initChartWordMultiple(word_parts, chart_index, m ==0);
//chart_index+=word_parts->maxLength();
m++;
delete word_parts; //reset would be better!
}
}
return chart_index;
}
int ArabicChartDecoder::initChartWordMultiple(const WordSegment* word,
int chart_index, bool firstWord){
const int maxSegs = word->maxLength();
int currentEntries[MAX_ENTRIES_PER_CELL][MAX_ENTRIES_PER_CELL];
for (int a = 0; a < maxSegs+1; a++) {
possiblePunctuationOrConjunction[chart_index + a] = false;
for (int b = 0; b < maxSegs+1; b++) {
currentEntries[a][b] = 0;
}
}
int next_chart_index = chart_index+1;
for(int j = 0; j< word->getNumPossibilities(); j++){
//std::cout<<"InitChartMultiple word: "<<j<<std::endl;
WordAnalysis segs = word->getPossibility(j);
int numSegs = segs.numSeg;
Segment* thisSeg;
for(int k = 0; k< numSegs; k++){
thisSeg = segs.segments[k];
Symbol seg_word = thisSeg->getText();
Symbol original_seg = seg_word;
int numTags = 0;
const Symbol* tags;
if (vocabularyTable->find(seg_word)) {
tags = partOfSpeechTable->lookup(seg_word, numTags);
} else {
seg_word = wordFeatures.features(original_seg, firstWord);
tags = partOfSpeechTable->lookup(seg_word, numTags);
if (numTags == 0) {
seg_word = wordFeatures.reducedFeatures(original_seg, firstWord);
tags = partOfSpeechTable->lookup(seg_word, numTags);
}
}
bool foundValid = false;
for(int m = 0; m <numTags; m++){
if(thisSeg->isValidPOS(tags[m])){
foundValid = true;
break;
}
}
//WARNING: This is very much a hack, if we separate a pronoun
//that we have not seen in training, we will be unable to give it
//a pronoun POS tag, b/c pronouns are not open class.
//This is only a problem for Pronouns! we see enough of all of the
//prefixes in training
//In this case switch Tags = 3MascSing pron suffix tags
//and print an error msg to STD::ERR
bool substitution = false;
if(!foundValid){
tags = thisSeg->validPOSList();
numTags = thisSeg->posListSize();
substitution = true;
if(numTags == 4){
std::cerr<<"Substituting pron taglist for unknown pronoun"<<std::endl;
}
else{
std::cerr<<"Substituting taglist for non pronoun"<<std::endl;
}
}
//add the segment to clean words for postprocessing
_cleanWords[chart_index+thisSeg->getStart()][chart_index+thisSeg->getEnd()] =
thisSeg->getText();
for (int m = 0; m < numTags; m++) {
Symbol tag = tags[m];
//ignore invalid POS tags
if(thisSeg->isValidPOS(tag)){
if (LanguageSpecificFunctions::isBasicPunctuationOrConjunction(tag))
{
possiblePunctuationOrConjunction[chart_index+k] = true;
}
ChartEntry *entry = _new ChartEntry();
entry->nameType = ParserTags::nullSymbol;
int start = thisSeg->getStart();
int end = thisSeg->getEnd();
/// FOR DEBUGGING MSG
if(DEBUG1){
Symbol debugSym = ArabicSymbol::BWSymbol(original_seg.to_string());
_debugStream<<"segment "<<debugSym.to_debug_string();
_debugStream<<" tag "<<tag.to_debug_string();
int p = start+ chart_index;
int q = end+chart_index;
int r = currentEntries[start][end];
_debugStream<<"Chart Place "<<p<<", "<<q<<", "<<r<<"\n";
_debugStream.flush();
//std::cout<<"segment "<<debugSym.to_debug_string();
//std::cout<<" tag "<<tag.to_debug_string();
//std::cout<<"Chart Place "<<p<<", "<<q<<", "<<r<<"\n";
}
/// END DEBUGGING MSG
fillWordEntry(entry, tag, seg_word, original_seg, chart_index+start-1, chart_index+end+1);
//The nasty pronoun hack continues, if we set the prononun substitution, also need to set the ranking
//score to 1/numposs
if(substitution)
entry->rankingScore= log(1.0f / numTags);
//debugging
/*
Symbol debugSym = ArabicSymbol::BWSymbol(original_seg.to_string());
//_debugStream<<"segment "<<debugSym.to_debug_string();
//_debugStream<<" tag "<<tag.to_debug_string();
int p = start+ chart_index;
int q = end+chart_index;
int r = currentEntries[start][end];
std::cout<<"segment "<<debugSym.to_debug_string();
std::cout<<" tag "<<tag.to_debug_string();
std::cout<<"Chart Place "<<p<<", "<<q<<", "<<r<<"\n";
std::cout<<"RankingScore "<<entry->rankingScore<<std::endl;
*/
//end debugging
//end hack
chart[chart_index+start][chart_index+end][currentEntries[start][end]++] = entry;
//always make the next entry 0?
chart[chart_index+start][chart_index+end][currentEntries[start][end]] = 0;
if(( chart_index+end +1) >next_chart_index){
next_chart_index = chart_index+end+1;
}
}
}
}
}
for (int k = 0; k < maxSegs; k++) {
chart[chart_index+k][chart_index+k][currentEntries[k][k]] = 0;
}
return next_chart_index;
}
//This is mostly the same as the generic method,
//left, right_word refer to locations in sentence
//left, right_chart refer to placement in the chart
//in the generic version these are the same
void ArabicChartDecoder::addConstraintEntry(int left_word, int right_word,
int left_chart, int right_chart,
Symbol* sentence, Symbol type, EntityType entityType) {
Symbol word = sentence[right_word];
const Symbol* tags;
int numTags;
bool is_unknown_word = false;
if (vocabularyTable->find(word)) {
tags = partOfSpeechTable->lookup(word, numTags);
} else {
is_unknown_word = true;
word = wordFeatures.features(sentence[right_word], 0);
tags = partOfSpeechTable->lookup(word, numTags);
if (numTags == 0) {
word = wordFeatures.reducedFeatures(sentence[right_word], 0);
tags = partOfSpeechTable->lookup(word, numTags);
}
}
unsigned index = 0;
ChartEntry *entry;
bool found_primary_tag = false;
for (int k = 0; k < numTags; k++) {
Symbol tag = tags[k];
if (index < maxEntriesPerCell &&
(!entityType.isRecognized() ||
LanguageSpecificFunctions::isPrimaryNamePOStag(tag, entityType)))
{
entry = _new ChartEntry();
entry->nameType = type;
fillWordEntry(entry, tag, word, sentence[right_word], left_chart, right_chart);
if(DEBUG1){
_debugStream<<"Constarained Entry: "<<word.to_debug_string()<<": ";
_debugStream<<left_chart<<", "<<right_chart<<", "<<index<<"\n";
}
chart[left_chart][right_chart][index++] = entry;
found_primary_tag = true;
}
}
if (index == 0) {
ChartEntry *entry = _new ChartEntry();
entry->nameType = type;
// don't bother calculating real ranking score, as we're making it up
fillWordEntry(entry, LanguageSpecificFunctions::getDefaultNamePOStag(entityType),
word, sentence[right_word], left_chart, right_chart, false);
if(DEBUG1){
_debugStream<<"Constarained Entry: "<<word.to_debug_string()<<": ";
_debugStream<<left_chart<<", "<<right_chart<<", "<<index<<"\n";
}
chart[left_chart][right_chart][index++] = entry;
}
// So -- now we let word vectors also pick up secondary tags.... but sometimes
// that leads to worse parses. So, if an unknown word vector has a primary tag
// in the POS table, use ONLY that.
//
// If we continue to expand the set of things we want to use this for (in
// particular, non-named entities), perhaps we should make the
// LanguageSpecificFunctions functions used here be particular to the type
// of tag: clearly, nuclear substances should have different primary/
// secondary/default tags than person names. For now, though, we just
// hope for the best.
if (found_primary_tag && is_unknown_word)
numTags = 0;
for (int j = 0; j < numTags; j++) {
Symbol tag = tags[j];
if (LanguageSpecificFunctions::isSecondaryNamePOStag(tag, entityType) &&
index < maxEntriesPerCell)
{
entry = _new ChartEntry();
entry->nameType = type;
fillWordEntry(entry, tag, word, sentence[right_word], left_chart, right_chart);
if(DEBUG1){
_debugStream<<"Constarained Entry: "<<word.to_debug_string()<<": ";
_debugStream<<left_chart<<", "<<right_chart<<", "<<index<<"\n";
}
chart[left_chart][right_chart][index++] = entry;
break;
}
}
chart[left_chart][right_chart][index] = 0;
}
void ArabicChartDecoder::transferTheoriesToChart(int start, int end)
{
if (numTheories == 0) {
//std::cout<<"NOTHING FROM "<<start<<" to "<<end<<"\n";
return;
}
else if(DEBUG1){
_debugStream<<"add theory from "<<start<<" to "<<end;
}
size_t j = 0;
// Skip preterminals already in chart
while (chart[start][end - 1][j] != 0) {
j++;
}
if(j > maxEntriesPerCell){
// std::cout<<"Too many entries in a cell!"<<start<<" "<<end<<"\n";
}
if (numTheories == 0) {
chart[start][end - 1][j] = 0;
return;
}
// Remove extra theories that will not fit in chart
while (j + numTheories > maxEntriesPerCell) {
int lowestScoring = 0;
for (int l = 1; l < numTheories; l++) {
if (theories[l]->rankingScore < theories[lowestScoring]->rankingScore) {
lowestScoring = l;
}
}
theories[lowestScoring] = theories[numTheories - 1];
numTheories--;
}
// Find highest scoring theory to determine threshold
int highestScoring = 0;
for (int i = 1; i < numTheories; i++) {
if (theories[i]->rankingScore > theories[highestScoring]->rankingScore)
highestScoring = i;
}
float threshold = theories[highestScoring]->rankingScore + lambda;
// Put theories in chart
for (int k = 0; k < numTheories; k++) {
if (theories[k]->rankingScore > threshold) {
chart[start][end - 1][j++] = theories[k];
if(DEBUG1){
_debugStream<<"\t "<<theories[k]->constituentCategory.to_debug_string()
<<"->"<<theories[k]->leftChild->constituentCategory.to_debug_string()
<<" "<<theories[k]->rightChild->constituentCategory.to_debug_string()
<<"\n";
_debugStream.flush();
}
}else {
delete theories[k];
}
}
chart[start][end - 1][j] = 0;
}
void ArabicChartDecoder::postProcessChart(){
for (int i = 0; i < MAX_SENTENCE_LENGTH; i++) {
int k = 0;
while((k < MAX_TAGS_PER_WORD) && (chart[i][i][k] != 0)){
if((chart[i][i][k])&&
chart[i][i][k]->isPreterminal &&
(chart[i][i][k]->nameType==ParserTags::nullSymbol)){
chart[i][i][k]->headWord = _cleanWords[i][i];
}
k++;
}
}
for(int i = 0; i< MAX_SENTENCE_LENGTH; i++){
for (int j = i + 1; j < MAX_SENTENCE_LENGTH; j++) {
int k =0;
while((k < MAX_ENTRIES_PER_CELL) && (chart[i][j][k] != 0)){
if((chart[i][j][k])&&
chart[i][j][k]->isPreterminal &&
(chart[i][j][k]->nameType==ParserTags::nullSymbol)){
chart[i][j][k]->headWord = _cleanWords[i][j];
}
k++;
}
}
}
}
void ArabicChartDecoder::addNameToParse(ParseNode* node, int& currentPosition)
{ if(node->isName){
addNameToNode(node, currentPosition);
}
if ((node->headNode == 0)) {
node->label = LanguageSpecificFunctions::getSymbolForParseNodeLeaf(node->label);
}
else{
addNameToPremods(node->premods, currentPosition);
addNameToParse(node->headNode, currentPosition);
addNameToPostmods(node->postmods, currentPosition);
}
}
void ArabicChartDecoder::addNameToPremods(ParseNode* premod, int& currentPosition)
{
if (premod) {
addNameToPremods(premod->next, currentPosition);
addNameToParse(premod, currentPosition);
}
}
void ArabicChartDecoder::addNameToPostmods(ParseNode* postmod, int& currentPosition)
{
if (postmod) {
addNameToParse(postmod, currentPosition);
addNameToPostmods(postmod->next, currentPosition);
}
}
void ArabicChartDecoder::postprocessParse(ParseNode* node, bool collapseNPlabels)
{
if ((node->headNode == 0)) {
node->label = LanguageSpecificFunctions::getSymbolForParseNodeLeaf(node->label);
} else {
LanguageSpecificFunctions::modifyParse(node);
if (collapseNPlabels && LanguageSpecificFunctions::isNPtypeLabel(node->label)) {
node->label = LanguageSpecificFunctions::getNPlabel();
}
postprocessPremods(node->premods, collapseNPlabels);
postprocessParse(node->headNode, collapseNPlabels);
postprocessPostmods(node->postmods, collapseNPlabels);
}
}
void ArabicChartDecoder::addNameToNode(ParseNode* node, int& currentPosition){
//node will be pre-preterminal name span
//namewords need to be put in premods and headNode
ParseNode* pm = node->premods;
ParseNode* hn;
//count premods
int numPM = 0;
while(pm){
pm = pm->next;
numPM++;
}
pm = node->premods;
int premod_counter = numPM -1;
while(pm){
hn = pm->headNode;
if(hn->headNode==0){
hn->label =
LanguageSpecificFunctions::getSymbolForParseNodeLeaf(_nameWords[currentPosition+premod_counter]);
premod_counter--;
}
else{
std::cerr<<"PROBLEM WITH NAME WORD- premods\n";
}
pm = pm->next;
}
currentPosition+=numPM;
hn = node->headNode; //nameWords POS
if(hn->headNode->headNode == 0){
hn->headNode->label =
LanguageSpecificFunctions::getSymbolForParseNodeLeaf(_nameWords[currentPosition++]);
}
else{
std::cerr<<"PROBLEM WITH NAME WORD\n";
}
}
| 32.74144 | 110 | 0.653144 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.