blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ccbc3febcc84a1570c0e4e6e4981ad4169ce396 | ce76dfd1a0eca63a2ee43ee4cb35c29f21572ce2 | /hittable.hpp | 7b5d607c182f3b8fa9c5c47e384b8b38e3da2a9c | [] | no_license | adilbaig/raytracing-in-a-weekend | b8c98eba8530c75834bd7f8f880b118dbd29b6f7 | ea918f1c410567fd34c113cdc0d09ab9500e1171 | refs/heads/master | 2022-06-12T23:52:16.265469 | 2020-05-08T00:36:38 | 2020-05-08T00:36:38 | 261,846,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | hpp | #ifndef HITTABLE_H
#define HITTABLE_H
#include "rtweekend.hpp"
#include "ray.hpp"
class material;
struct hit_record
{
point3 p;
vec3 normal;
shared_ptr<material> mat_ptr;
double t;
bool front_face;
inline void set_face_normal(const ray &r, const vec3 &outward_normal)
{
front_face = dot(r.direction(), outward_normal) < 0;
normal = (front_face) ? outward_normal : -outward_normal;
}
};
class hittable
{
public:
virtual bool hit(const ray &r, double t_min, double t_max, hit_record &rec) const = 0;
};
#endif | [
"adil.baig@aidezigns.com"
] | adil.baig@aidezigns.com |
7c87092f28d30b9d47c89d54bd88f54af0b97fc1 | e9762514d154dc51779c24ea31e2c811331444f6 | /Classes/Portal.cpp | 0a9c1946c5a03e305b08ed628b25b91c6fa94d93 | [
"MIT"
] | permissive | otakuidoru/Reflection | 03eeadc1c6c5c65d547b84e31f090f6f0b423ac9 | 05d55655a75813c7d4f0f5dee4d69a2c05476396 | refs/heads/master | 2022-12-10T11:37:27.651073 | 2020-08-23T20:22:50 | 2020-08-23T20:22:50 | 254,940,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,091 | cpp | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <cmath>
#include "Portal.h"
#include "ColorType.h"
USING_NS_CC;
static const float DEGTORAD = 0.0174532925199432957f;
static const float RADTODEG = 57.295779513082320876f;
/**
*
*/
Portal::Portal(int id) : GameObject(id, ColorType::NONE, 4) {
}
/**
*
*/
Portal::~Portal() {
}
/**
*
*/
Portal* Portal::create(int id) {
Portal* portal = new (std::nothrow) Portal(id);
if (portal && portal->initWithFile("portal.png")) {
portal->autorelease();
return portal;
}
CC_SAFE_DELETE(portal);
return nullptr;
}
/**
* on "init" you need to initialize your instance
*/
bool Portal::initWithFile(const std::string& filename) {
//////////////////////////////
// 1. super init first
if (!GameObject::initWithFile(filename)) {
return false;
}
this->direction = Direction::EAST;
this->setPlaneReflective(0, false);
this->setPlaneReflective(1, false);
this->setPlaneReflective(2, false);
this->setPlaneReflective(3, false);
return true;
}
/**
*
*/
Plane Portal::getPlane(unsigned int index) {
Plane plane;
const Vec2 worldPos = this->getParent()->convertToWorldSpace(this->getPosition());
const Size contentSize = this->getContentSize() * this->getScale();
switch (index) {
case 0: { // first plane - non-reflective
const float angle = -(this->getRotation() - 45.0f) * DEGTORAD;
Vec3 pos(worldPos.x, worldPos.y, 0.0f);
plane = Plane(Vec3(std::cosf(angle), std::sinf(angle), 0.0f), pos);
//log("com.zenprogramming.reflection: mirror[%d] plane[0]: pos = (%f, %f, %f) normal = (%f, %f, %f)", this->getId(), pos.x, pos.y, pos.z, plane.getNormal().x, plane.getNormal().y, plane.getNormal().z);
} break;
case 1: { // second plane - non-reflective
const float angle = -(this->getRotation() + 90.0f) * DEGTORAD;
Vec3 pos(worldPos.x + std::cosf(angle) * contentSize.width / 2.0f, worldPos.y + std::sinf(angle) * contentSize.height / 2.0f, 0.0f);
plane = Plane(Vec3(std::cosf(angle), std::sinf(angle), 0.0f), pos);
//log("com.zenprogramming.reflection: mirror[%d] plane[1]: pos = (%f, %f, %f) normal = (%f, %f, %f)", this->getId(), pos.x, pos.y, pos.z, plane.getNormal().x, plane.getNormal().y, plane.getNormal().z);
} break;
case 2: { // third plane - non-reflective
const float angle = -(this->getRotation() + 180.0f) * DEGTORAD;
Vec3 pos(worldPos.x + std::cosf(angle) * contentSize.width / 2.0f, worldPos.y + std::sinf(angle) * contentSize.height / 2.0f, 0.0f);
plane = Plane(Vec3(std::cosf(angle), std::sinf(angle), 0.0f), pos);
//log("com.zenprogramming.reflection: mirror[%d] plane[2]: pos = (%f, %f, %f) normal = (%f, %f, %f)", this->getId(), pos.x, pos.y, pos.z, plane.getNormal().x, plane.getNormal().y, plane.getNormal().z);
} break;
case 3: { // third plane - non-reflective
// TODO
} break;
}
return plane;
}
| [
"chuck.marshall@gmail.com"
] | chuck.marshall@gmail.com |
6d170ec110ab32bb7415b0fe69983e36e2fb04c4 | 99e494d9ca83ebafdbe6fbebc554ab229edcbacc | /.history/Day 3/Test/Answers/RobotAndDitch_20210306161737.cpp | 634ffd047e9cc327de6b7de7fcf643af062a0a9e | [] | no_license | Datta2901/CCC | c0364caa1e4937bc7bce68e4847c8d599aef0f59 | 4debb2c1c70df693d0e5f68b5798bd9c7a7ef3dc | refs/heads/master | 2023-04-19T10:05:12.372578 | 2021-04-23T12:50:08 | 2021-04-23T12:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long int forwardSteps, backwardSt, fd, bd, st;
std::cin >> forwardSteps >> backwardSt >> fd >> bd >> st;
bd = -bd;
if (forwardSteps == backwardSt) {
if (forwardSteps>=fd) {
std::cout << (fd*st);
} else {
std::cout << "NO";
}
} else {
int p = 0, t = 0;
while (true) {
if(p+forwardSteps >=fd) {
std::cout << "F " << (t+fd-p)*st;
break;
} else {
p = p+forwardSteps;
t = t+forwardSteps;
}
if(p-backwardSt <= bd) {
std::cout << "B " << (t-bd+p)*st;
break;
} else {
p = p-backwardSt;
t = t+backwardSt;
}
}
}
} | [
"manikanta2901@gmail.com"
] | manikanta2901@gmail.com |
62b5d1513f5daa3b3fd7b9c79fb1f3c6ee7e1355 | f6ab9a9523d4b929059bfebbfa98e8792a980acd | /acm hust/CodeForces/600B/6704359_AC_202ms_3136kB.cpp | a44f72ef6475565645585195f93cfb595fdea0ff | [] | no_license | nayemislamzr/Competitive-Programming | cba4febe6510beff393d967a9a5f90b5534ef15e | 469e9a33a6f84d250d0d398f28802f5ffb77aa6e | refs/heads/master | 2022-02-16T21:11:10.980348 | 2019-08-08T10:25:43 | 2019-08-08T10:25:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,322 | cpp |
/****************************************
Zerus97
*****************************************/
#include <bits/stdc++.h>
#define loop(i,s,e) for(int i = s;i<=e;i++) //including end point
#define pb(a) push_back(a)
#define sqr(x) ((x)*(x))
#define CIN ios_base::sync_with_stdio(0); cin.tie(0);
#define ll long long
#define ull unsigned long long
#define SZ(a) int(a.size())
#define read() freopen("input.txt", "r", stdin)
#define write() freopen("output.txt", "w", stdout)
#define ms(a,b) memset(a, b, sizeof(a))
#define all(v) v.begin(), v.end()
#define PI acos(-1.0)
#define pf printf
#define sfi(a) scanf("%d",&a);
#define sfii(a,b) scanf("%d %d",&a,&b);
#define sfl(a) scanf("%lld",&a);
#define sfll(a,b) scanf("%lld %lld",&a,&b);
#define sful(a) scanf("%llu",&a);
#define sfulul(a,b) scanf("%llu %llu",&a,&b);
#define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different
#define sfc(a) scanf("%c",&a);
#define sfs(a) scanf("%s",a);
#define mp make_pair
#define paii pair<int, int>
#define padd pair<dd, dd>
#define pall pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define mii map<int,int>
#define mlli map<ll,int>
#define mib map<int,bool>
#define fs first
#define sc second
#define CASE(t) printf("Case %d: ",++t) // t initialized 0
#define cCASE(t) cout<<"Case "<<++t<<": ";
#define D(v,status) cout<<status<<" "<<v<<endl;
#define INF 9999999999 //10e9
#define EPS 1e-9
#define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c )
#define CONTEST 1
using namespace std;
int a[2*100009];
struct b{
int v;
int idx;
};
b bb[2*100009];
int bans[2*100009];
bool comp(b cc,b dd)
{
if(cc.v<dd.v)
return true;
return false;
}
int main()
{
int n,m;
sfii(n,m);
loop(i,1,n)
sfi(a[i]);
loop(i,1,m)
{
int tmp;
sfi(tmp);
b lak;
lak.v = tmp;
lak.idx = i;
bb[i] = lak;
}
sort(a+1,a+n+1);
sort(bb+1,bb+m+1,comp);
a[n+1] = INF;
int p1 = 0;
loop(p2,1,m)
{
int val = bb[p2].v;
int ix = bb[p2].idx;
while( a[p1+1]<=val && p1<=n)
{
p1++;
}
bans[ix] = p1;
}
loop(i,1,m)
{
pf("%d ",bans[i]);
}
return 0;
}
| [
"zabiralnazi@codeassign.com"
] | zabiralnazi@codeassign.com |
ba97d2b31bdf5a46a17b0c8178a809d0788dd7bb | 9bd2b92b924d65f19bc534b543f90ae63ea23637 | /contest/CDUT2019_numberTheory/P.cpp | 7023d3d01688c079583299abc2245ca26d60622f | [] | no_license | mooleetzi/ICPC | d5196b07e860721c8a4fe41a5ccf5b58b6362678 | cd35ce7dbd340df1e652fdf2f75b35e70e70b472 | refs/heads/master | 2020-06-09T12:13:48.571843 | 2019-12-01T11:39:20 | 2019-12-01T11:39:20 | 193,435,046 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,103 | cpp | /*
神仙题呀,哭了
首先我们思考普通情况我们有K=k1*k2*...*kn种同余方程组合
如果K很大那么用孙子定理/中国剩余定理是很慢的,这时候我们可以考虑暴力枚举
暴力枚举的话我们选定一个x最大的和一个k值最小的来枚举,why
这样我们每次的增量最大而且k值更小的话对于一次增量x来说需要循环判定次数最少,保证了复杂度
要选择最大的x和最小的k的组合可以采用kc/xc<ki/xi => kc*xi<xc*ki避免除法运算不正确
如果K比较小那么可以用孙子定理求解(注意到题目说了m互质,用最简单的版本即可)
*/
#pragma optimize(3)
#include <bits/stdc++.h>
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pa = pair<int, int>;
using ld = long double;
const int maxn = 210;
template <class T>
inline T read(T &ret)
{
int f = 1;
ret = 0;
char ch = getchar();
while (!isdigit(ch))
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (isdigit(ch))
{
ret = (ret << 1) + (ret << 3) + ch - '0';
ch = getchar();
}
ret *= f;
return ret;
}
template <class T>
inline void write(T n)
{
if (n < 0)
{
putchar('-');
n = -n;
}
if (n >= 10)
{
write(n / 10);
}
putchar(n % 10 + '0');
}
int limit = 10000;
unordered_set<int> se[maxn];
int m[maxn], y[maxn][maxn], k[maxn], b[maxn];
vector<int> res;
int c, s;
ll exgcd(ll a, ll b, ll &x, ll &y) //求逆元
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
ll ret = exgcd(b, a % b, y, x);
y -= (a / b) * x;
return ret;
}
ll crt()
{
ll d, x, y, ret = 0;
ll temp;
ll M = 1;
for (int i = 0; i < c; i++)
M *= m[i]; //m是除数
for (int i = 0; i < c; i++)
{
temp = M / m[i];
d = exgcd(m[i], temp, x, y); //求temp在模mi意义下的逆元
ret = (ret + y * temp * b[i]) % M; //b是余数
}
return (ret + M) % M;
}
void dfs(int dep)
{
if (dep == c)
{
res.emplace_back(crt());
return;
}
for (int j = 0; j < k[dep]; j++)
{
b[dep] = y[dep][j];
dfs(dep + 1);
}
}
void solveCrt()
{
dfs(0);
ll lcm = 1;
sort(res.begin(), res.end());
for (int i = 0; i < c; i++)
lcm *= m[i];
for (int i = 0; s; i++)
{
int sz = res.size();
for (int j = 0; j < sz && s; j++)
{
ll now = lcm * i + res[j];
if (now > 0)
{
write(now);
puts("");
--s;
}
}
}
}
void solveEnum(int best)
{
for (int i = 0; i < c; i++)
{
if (i == best)
continue;
se[i].clear();
for (int j = 0; j < k[i]; j++)
se[i].insert(y[i][j]);
}
for (int i = 0; s; i++)
for (int j = 0; j < k[best] && s; j++)
{
ll now = m[best] * i + y[best][j];
if (!now)
continue;
int f = 1;
for (int p = 0; p < c; p++)
{
if (p != best && !se[p].count(now % m[p]))
{
f = 0;
break;
}
}
if (f)
{
write(now);
puts("");
--s;
}
}
}
int main(int argc, char const *argv[])
{
while (read(c) && read(s))
{
res.clear();
int best = 0, tot = 1;
for (int i = 0; i < c; i++)
{
read(m[i]), read(k[i]);
for (int j = 0; j < k[i]; j++)
read(y[i][j]);
sort(y[i], y[i] + k[i]);
if (m[best] * k[i] < m[i] * k[best])
best = i;
tot *= k[i];
}
if (tot >= limit)
solveEnum(best);
else
solveCrt();
puts("");
}
return 0;
}
| [
"13208308200@163.com"
] | 13208308200@163.com |
b02a4b3f0dc121ea95ac6534f91546f054df2458 | c85305610932c7826045c06e86d7c1329f16f611 | /CTN_05_Hardware_3D_DirectX/src/Camera.h | 4505a315902b402d7a71952f0cd61d3deb41b388 | [
"Apache-2.0"
] | permissive | TheUnicum/CTN_05_Hardware_3D_DirectX | 87c90985eda6ade86dd4d0c7e4a7898c9039c017 | 39940fb0466ff5b419d7f7c4cf55ee1f90784baa | refs/heads/master | 2020-12-10T02:30:32.141269 | 2020-10-29T11:32:46 | 2020-10-29T11:32:46 | 233,479,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | h | #pragma once
#include <DirectXMath.h>
#include <string>
#include "Projection.h"
#include "CameraIndicator.h"
class Graphics;
namespace Rgph
{
class RenderGraph;
}
class Camera
{
public:
Camera(Graphics& gfx, std::string name, DirectX::XMFLOAT3 homePos = { 0.0f,0.0f,0.0f }, float homePitch = 0.0f, float homeYaw = 0.0f, bool tethered = false) noexcept;
void BindToGraphics(Graphics& gfx) const;
DirectX::XMMATRIX GetMatrix() const noexcept;
DirectX::XMMATRIX GetProjection() const noexcept;
void SpawnControlWidgets(Graphics& gfx) noexcept;
void Reset(Graphics& gfx) noexcept;
void Rotate(float dx, float dy) noexcept;
void Translate(DirectX::XMFLOAT3 translation) noexcept;
DirectX::XMFLOAT3 GetPos() const noexcept;
void SetPos(const DirectX::XMFLOAT3& pos) noexcept;
const std::string& GetName() const noexcept;
void LinkTechniques(Rgph::RenderGraph& rg);
void Submit(size_t channel) const;
private:
bool tethered;
std::string name;
DirectX::XMFLOAT3 homePos;
float homePitch;
float homeYaw;
DirectX::XMFLOAT3 pos;
float pitch;
float yaw;
static constexpr float travelSpeed = 12.0f;
static constexpr float rotationSpeed = 0.004f;
bool enableCameraIndicator = false;
bool enableFrustumIndicator = false;
Projection proj;
CameraIndicator indicator;
};
| [
"tia_ben@tin.it"
] | tia_ben@tin.it |
7e62d594466e4f9a78fbfbaf8e3a43fb6b02b07c | 4f86882803909c783bb4cf49325118b15d4b4ef1 | /Projects/Project4/app/MyAVLTree.hpp | 57a62cc4164c9b22302741e4726fc556ec82d8ad | [] | no_license | hootanh/Data-Structure-Implementation-and-Analysis | 5bc843bd786a0ef3e4cc730c793b1a571e71e732 | 22b104b003f85b59182338601ed9c318bc3da4c2 | refs/heads/main | 2023-03-29T02:24:57.670973 | 2021-03-31T08:21:37 | 2021-03-31T08:21:37 | 353,237,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,793 | hpp | #ifndef __PROJ_THREE_AVL_HPP
#define __PROJ_THREE_AVL_HPP
#include "runtimeexcept.hpp"
#include <string>
#include <vector>
class ElementNotFoundException : public RuntimeException
{
public:
ElementNotFoundException(const std::string & err) : RuntimeException(err) {}
};
template<typename Key, typename Value>
class Tree_Nodes
{
private:
bool find_root;
public:
int tree_tall;
Key node_key;
Tree_Nodes<Key, Value> * child_l;
Value node_value;
Tree_Nodes<Key, Value> * child_r;
bool node_span;
Tree_Nodes<Key, Value> * child_p;
Tree_Nodes(const Key & temp_key, const Value & temp_value)
{
find_root = true;
node_value = temp_value;
child_l = nullptr;
node_key = temp_key;
child_r = nullptr;
node_span = true;
child_p = nullptr;
}
~Tree_Nodes()
{
find_root = false;
delete child_l;
node_span = false;
delete child_r;
}
};
template<typename Key, typename Value>
class MyAVLTree
{
private:
bool tree_c, inserted, is_root = true, preOrder_check = false, inOrder_check = false, postOrder_check = false, left_child, right_child;
int tree_size, tree_check = 0, insert_count = 0, find_check = true;
void recursive_inOrder(Tree_Nodes<Key,Value> * inOrder_node, std::vector<Key> & inOrder_v) const;
int recursive_tall(Tree_Nodes<Key,Value> * present_tall);
void recursive_preOrder(Tree_Nodes<Key,Value> * preOrder_node, std::vector<Key> & preOrder_v) const;
Tree_Nodes<Key, Value> * tree_root;
void recursive_postOrder(Tree_Nodes<Key,Value> * postOrder_node, std::vector<Key> & postOrder_v) const;
public:
MyAVLTree();
~MyAVLTree()
{
tree_c = false;
delete tree_root;
inserted = false;
}
size_t size() const noexcept;
bool isEmpty() const noexcept;
bool contains(const Key & k) const;
Value & find(const Key & k);
const Value & find(const Key & k) const;
void insert(const Key & k, const Value & v);
std::vector<Key> inOrder() const;
std::vector<Key> preOrder() const;
std::vector<Key> postOrder() const;
};
template<typename Key, typename Value>
MyAVLTree<Key,Value>::MyAVLTree()
{
inserted = false;
tree_root = nullptr;
tree_c = true;
tree_size = 0;
}
template<typename Key, typename Value>
size_t MyAVLTree<Key, Value>::size() const noexcept
{
return tree_size;
}
template<typename Key, typename Value>
bool MyAVLTree<Key, Value>::isEmpty() const noexcept
{
if(tree_size != 0)
{
return false;
}
else
{
return true;
}
}
template<typename Key, typename Value>
bool MyAVLTree<Key, Value>::contains(const Key & k) const
{
Tree_Nodes<Key, Value> * present_node = tree_root;
while(true)
{
if(present_node == nullptr)
{
return false;
}
if(present_node -> node_key == k)
{
return true;
}
else if(present_node -> node_key <= k)
{
present_node = present_node -> child_r;
}
else if(present_node -> node_key > k)
{
present_node = present_node -> child_l;
}
}
return false;
}
template<typename Key, typename Value>
Value & MyAVLTree<Key, Value>::find(const Key & k)
{
Tree_Nodes<Key, Value> * present_node = tree_root;
if(find_check == true && contains(k) == false)
{
throw ElementNotFoundException("Element not found in tree!!!");
}
while(true)
{
if(present_node == nullptr || present_node -> node_key == k)
{
break;
}
else if(find_check == true && present_node -> node_key <= k)
{
present_node = present_node -> child_r;
}
else if(find_check == true && present_node -> node_key > k)
{
present_node = present_node -> child_l;
}
}
return present_node -> node_value;
}
template<typename Key, typename Value>
const Value & MyAVLTree<Key, Value>::find(const Key & k) const
{
Tree_Nodes<Key, Value> * present_node = tree_root;
if(find_check == true && contains(k) == false)
{
throw ElementNotFoundException("Element not found in tree!!!");
}
while(true)
{
if(present_node == nullptr || present_node -> node_key == k)
{
break;
}
else if(find_check == true && present_node -> node_key <= k)
{
present_node = present_node -> child_r;
}
else if(find_check == true && present_node -> node_key > k)
{
present_node = present_node -> child_l;
}
}
return present_node -> node_value;
}
template<typename Key, typename Value>
void MyAVLTree<Key, Value>::insert(const Key & k, const Value & v)
{
Tree_Nodes<Key, Value> * added_node;
bool loop_check = true, is_balanced = true, check_balance, right_r, left_r, rotation_r = true, rotation_l = true;
int first_result, second_result, tree_balance;
if(tree_root != nullptr)
{
Tree_Nodes<Key, Value> * new_node = tree_root;
insert_count = tree_size + 1;
while(true)
{
if(loop_check == true && new_node -> node_key <= k)
{
if(loop_check == true && new_node -> child_r == nullptr)
{
new_node -> child_r = new Tree_Nodes<Key, Value> (k, v);
tree_size++;
insert_count += tree_size;
added_node = new_node -> child_r;
inserted = false;
added_node -> child_p = new_node;
break;
}
else if(new_node -> child_r != nullptr)
{
inserted = true;
insert_count--;
}
insert_count++;
new_node = new_node -> child_r;
inserted = true;
}
else if(loop_check == true && new_node -> node_key > k)
{
if(loop_check == true && new_node -> child_l == nullptr)
{
new_node -> child_l = new Tree_Nodes<Key, Value> (k, v);
tree_size++;
insert_count += tree_size;
added_node = new_node -> child_l;
inserted = false;
added_node -> child_p = new_node;
break;
}
else if(new_node -> child_l != nullptr)
{
inserted = true;
insert_count--;
}
insert_count++;
new_node = new_node -> child_l;
inserted = true;
}
else
{
insert_count--;
inserted = false;
continue;
}
}
recursive_tall(tree_root);
Key temp_k = added_node -> node_key;
while(loop_check == true && added_node != tree_root)
{
added_node = added_node -> child_p;
if(added_node -> child_l == nullptr)
{
insert_count++;
first_result = -1;
}
else
{
insert_count--;
first_result = added_node -> child_l -> tree_tall;
}
if (added_node -> child_r == nullptr)
{
insert_count++;
second_result = -1;
}
else
{
insert_count--;
second_result = added_node -> child_r -> tree_tall;
}
if(is_balanced == true)
{
tree_balance = first_result - second_result;
inserted = false;
check_balance = tree_balance > 1 || tree_balance < -1;
}
if(check_balance && tree_balance < -1)
{
inserted = true;
if(temp_k > added_node -> child_r -> node_key)
{
Tree_Nodes<Key,Value> * rotate_r1 = added_node -> child_r;
added_node -> child_r = rotate_r1 -> child_l;
if(rotation_r == true && added_node -> child_r != nullptr)
{
insert_count += tree_size;
added_node -> child_r -> child_p = added_node;
}
rotate_r1 -> child_l = added_node;
rotate_r1 -> child_p = added_node->child_p;
added_node -> child_p = rotate_r1;
if(rotation_r == true && rotate_r1 -> child_p != nullptr)
{
insert_count++;
if(rotation_r == true && rotate_r1 -> node_key <= rotate_r1 -> child_p -> node_key)
{
right_r = false;
rotate_r1 -> child_p -> child_l = rotate_r1;
}
else if(rotation_r == true)
{
right_r = true;
rotate_r1 -> child_p -> child_r = rotate_r1;
}
}
else
{
right_r = true;
insert_count++;
tree_root = rotate_r1;
}
break;
}
}
else if(check_balance && tree_balance > 1)
{
inserted = true;
if(temp_k < added_node -> child_l -> node_key)
{
Tree_Nodes<Key,Value> * rotate_l1 = added_node -> child_l;
added_node -> child_l = rotate_l1 -> child_r;
if(rotation_l == true && added_node -> child_l != nullptr)
{
insert_count += tree_size;
added_node -> child_l -> child_p = added_node;
}
rotate_l1 -> child_r = added_node;
rotate_l1 -> child_p = added_node -> child_p;
added_node -> child_p = rotate_l1;
if(rotation_l == true && rotate_l1 -> child_p != nullptr)
{
insert_count++;
if(rotation_l == true && rotate_l1 -> node_key <= rotate_l1 -> child_p -> node_key)
{
left_r = false;
rotate_l1 -> child_p -> child_l = rotate_l1;
}
else if(rotation_l == true)
{
left_r = true;
rotate_l1 -> child_p -> child_r = rotate_l1;
}
}
else
{
left_r = true;
insert_count++;
tree_root = rotate_l1;
}
break;
}
else if(temp_k > added_node -> child_l -> node_key)
{
Tree_Nodes<Key,Value> * rotate_r2 = added_node -> child_l -> child_r;
added_node -> child_l -> child_r = rotate_r2 -> child_l;
if(rotation_r == true && added_node -> child_l -> child_r != nullptr)
{
insert_count += tree_size;
added_node -> child_l -> child_r -> child_p = added_node -> child_l;
}
rotate_r2 -> child_l = added_node -> child_l;
rotate_r2 -> child_p = added_node -> child_l -> child_p;
added_node -> child_l -> child_p = rotate_r2;
if(rotation_r == true && rotate_r2 -> child_p != nullptr)
{
insert_count++;
if(rotation_r == true && rotate_r2 -> node_key <= rotate_r2 -> child_p -> node_key)
{
right_r = false;
rotate_r2 -> child_p -> child_l = rotate_r2;
}
else if(rotation_r == true)
{
right_r = true;
rotate_r2 -> child_p -> child_r = rotate_r2;
}
}
else
{
right_r = true;
insert_count++;
tree_root = rotate_r2;
}
Tree_Nodes<Key,Value> * rotate_l2 = added_node -> child_l;
added_node -> child_l = rotate_l2 -> child_r;
if(rotation_l == true && added_node -> child_l != nullptr)
{
insert_count += tree_size;
added_node -> child_l -> child_p = added_node;
}
rotate_l2 -> child_r = added_node;
rotate_l2 -> child_p = added_node -> child_p;
added_node -> child_p = rotate_l2;
if(rotation_l == true && rotate_l2 -> child_p != nullptr)
{
insert_count++;
if(rotation_l == true && rotate_l2 -> node_key <= rotate_l2 -> child_p -> node_key)
{
left_r = false;
rotate_l2 -> child_p -> child_l = rotate_l2;
}
else if(rotation_l == true)
{
left_r = true;
rotate_l2 -> child_p -> child_r = rotate_l2;
}
}
else
{
left_r = true;
insert_count++;
tree_root = rotate_l2;
}
break;
}
}
else if(check_balance)
{
inserted = true;
Tree_Nodes<Key,Value> * rotate_l3 = added_node -> child_r -> child_l;
added_node -> child_r -> child_l = rotate_l3 -> child_r;
if(rotation_l == true && added_node -> child_r -> child_l != nullptr)
{
insert_count += tree_size;
added_node -> child_r -> child_l -> child_p = added_node -> child_r;
}
rotate_l3 -> child_r = added_node -> child_r;
rotate_l3 -> child_p = added_node -> child_r -> child_p;
added_node -> child_r -> child_p = rotate_l3;
if(rotation_l == true && rotate_l3 -> child_p != nullptr)
{
insert_count++;
if(rotation_l == true && rotate_l3 -> node_key <= rotate_l3 -> child_p -> node_key)
{
left_r = false;
rotate_l3 -> child_p -> child_l = rotate_l3;
}
else if(rotation_l == true)
{
left_r = true;
rotate_l3 -> child_p -> child_r = rotate_l3;
}
}
else
{
left_r = true;
insert_count++;
tree_root = rotate_l3;
}
Tree_Nodes<Key,Value> * rotate_r3 = added_node -> child_r;
added_node -> child_r = rotate_r3 -> child_l;
if(rotation_r == true && added_node -> child_r != nullptr)
{
insert_count += tree_size;
added_node -> child_r -> child_p = added_node;
}
rotate_r3 -> child_l = added_node;
rotate_r3 -> child_p = added_node -> child_p;
added_node -> child_p = rotate_r3;
if(rotation_r == true && rotate_r3 -> child_p != nullptr)
{
insert_count++;
if(rotation_r == true && rotate_r3 -> node_key <= rotate_r3 -> child_p -> node_key)
{
right_r = false;
rotate_r3 -> child_p -> child_l = rotate_r3;
}
else if(rotation_r == true)
{
right_r = true;
rotate_r3 -> child_p -> child_r = rotate_r3;
}
}
else
{
right_r = true;
insert_count++;
tree_root = rotate_r3;
}
break;
}
}
recursive_tall(tree_root);
}
else if(is_root == true && tree_root == nullptr)
{
inserted = true;
tree_root = new Tree_Nodes<Key, Value> (k, v);
insert_count = tree_size + 1;
tree_size++;
return;
}
else if(is_root == true && contains(k) == true)
{
insert_count += tree_size;
inserted = false;
return;
}
else
{
inserted = true;
insert_count -= tree_size;
is_root = true;
}
}
template<typename Key, typename Value>
std::vector<Key> MyAVLTree<Key, Value>::inOrder() const
{
std::vector<Key> inOrder_v;
if(inOrder_check == false)
{
recursive_inOrder(tree_root, inOrder_v);
}
return inOrder_v;
}
template<typename Key, typename Value>
void MyAVLTree<Key, Value>::recursive_inOrder(Tree_Nodes<Key, Value> * inOrder_node, std::vector<Key> & inOrder_v) const
{
if(inOrder_check == false && inOrder_node != nullptr)
{
recursive_inOrder(inOrder_node -> child_l, inOrder_v);
inOrder_v.push_back(inOrder_node -> node_key);
recursive_inOrder(inOrder_node -> child_r, inOrder_v);
}
else if(inOrder_check == false)
{
return;
}
}
template<typename Key, typename Value>
std::vector<Key> MyAVLTree<Key, Value>::preOrder() const
{
std::vector<Key> preOrder_v;
if(preOrder_check == false)
{
recursive_preOrder(tree_root, preOrder_v);
}
return preOrder_v;
}
template<typename Key, typename Value>
void MyAVLTree<Key, Value>::recursive_preOrder(Tree_Nodes<Key, Value> * preOrder_node, std::vector<Key> & preOrder_v) const
{
if(preOrder_check == false && preOrder_node != nullptr)
{
preOrder_v.push_back(preOrder_node -> node_key);
recursive_preOrder(preOrder_node -> child_l, preOrder_v);
recursive_preOrder(preOrder_node -> child_r, preOrder_v);
}
else if(preOrder_check == false)
{
return;
}
}
template<typename Key, typename Value>
std::vector<Key> MyAVLTree<Key, Value>::postOrder() const
{
std::vector<Key> postOrder_v;
if(postOrder_check == false)
{
recursive_postOrder(tree_root, postOrder_v);
}
return postOrder_v;
}
template<typename Key, typename Value>
void MyAVLTree<Key, Value>::recursive_postOrder(Tree_Nodes<Key, Value> * postOrder_node, std::vector<Key> & postOrder_v) const
{
if(postOrder_check == false && postOrder_node != nullptr)
{
recursive_postOrder(postOrder_node -> child_l, postOrder_v);
recursive_postOrder(postOrder_node -> child_r, postOrder_v);
postOrder_v.push_back(postOrder_node -> node_key);
}
else if(postOrder_check == false)
{
return;
}
}
template<typename Key, typename Value>
int MyAVLTree<Key,Value>::recursive_tall(Tree_Nodes<Key, Value> * present_tall)
{
int left_tall, right_tall, no_tall = -1;
if(present_tall != nullptr)
{
left_tall= recursive_tall(present_tall -> child_l);
left_child = false;
right_tall = recursive_tall(present_tall -> child_r);
right_child = false;
if(left_tall <= right_tall)
{
right_child = true;
present_tall -> tree_tall = right_tall + 1;
}
else
{
left_child = true;
present_tall -> tree_tall = left_tall + 1;
}
return present_tall -> tree_tall;
}
else
{
right_child = false;
left_child = false;
return no_tall;
}
}
#endif | [
"hootanhosseinzade@gmail.com"
] | hootanhosseinzade@gmail.com |
b51736925f911c198bffe43cfd69621fc585a8e0 | b3e8fbd05754ec5c56013d3e395778cfe0c364b7 | /tensorflow/compiler/mlir/tensorflow/ir/tf_attributes.h | ba67d6cb6717eae0ca0dd6df3ae9b2120ae47b4f | [
"Apache-2.0"
] | permissive | rushabh-v/tensorflow | 46c3c67aad9367c8d68e8c52628f9c3d30e8a486 | c347830b50ecd020cfe982310afe1b37f0990fd5 | refs/heads/master | 2022-01-01T08:27:44.224885 | 2020-05-28T17:07:12 | 2020-05-28T17:07:12 | 234,374,809 | 3 | 0 | Apache-2.0 | 2020-01-16T17:31:46 | 2020-01-16T17:31:45 | null | UTF-8 | C++ | false | false | 3,535 | h | /* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
// This file defines the attributes used in the TensorFlow dialect.
#ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_ATTRIBUTES_H_
#define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_ATTRIBUTES_H_
#include "llvm/ADT/StringRef.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
namespace mlir {
namespace TF {
namespace AttrKind {
// List of supported custom TensorFlow Attributes kinds, necessary for
// isa/dyn_cast.
enum Kind {
FIRST_USED_TENSORFLOW_ATTR = Attribute::FIRST_TENSORFLOW_ATTR,
SHAPE = FIRST_USED_TENSORFLOW_ATTR,
FUNC,
LAST_USED_TENSORFLOW_ATTR,
};
} // namespace AttrKind
namespace detail {
struct ShapeAttrStorage;
struct FuncAttrStorage;
} // namespace detail
class ShapeAttr : public Attribute::AttrBase<ShapeAttr, Attribute,
detail::ShapeAttrStorage> {
public:
using Base::Base;
// Get or create a shape attribute. If shape is llvm::None, then it is
// unranked. Otherwise it is ranked. And for ranked shapes, the value of the
// dimension size must be >= -1. The value of -1 means the dimension is
// dynamic. Otherwise, the dimension is static.
static ShapeAttr get(mlir::MLIRContext* context,
llvm::Optional<ArrayRef<int64_t>> shape);
llvm::Optional<ArrayRef<int64_t>> getValue() const;
bool hasRank() const;
// If this is ranked, return the rank. Otherwise, abort.
int64_t getRank() const;
// If this is ranked, return the shape. Otherwise, abort.
ArrayRef<int64_t> getShape() const;
// If this is unranked type or any dimension has unknown size (<0), it doesn't
// have static shape. If all dimensions have known size (>= 0), it has static
// shape.
bool hasStaticShape() const;
static bool kindof(unsigned kind) { return kind == AttrKind::SHAPE; }
};
// Custom attribute to model AttrValue.value.func (NameAttrList type attribute).
// This attribute holds a SymbolRefAttr, for the NameAttrList.name string and a
// DictionaryAttr for the NameAttrList.attr map<string, AttrValue>. It is
// currently printed and parsed for the following format:
//
// #tf.func<@symbol, {attr = "value"}>
//
// where the first element is the SymbolRefAttr and the second element is the
// DictionaryAttr.
class FuncAttr
: public Attribute::AttrBase<FuncAttr, Attribute, detail::FuncAttrStorage> {
public:
using Base::Base;
static FuncAttr get(mlir::MLIRContext* context, llvm::StringRef name,
DictionaryAttr attr);
static FuncAttr get(mlir::MLIRContext* context, SymbolRefAttr symbol,
DictionaryAttr attr);
SymbolRefAttr GetName() const;
DictionaryAttr GetAttrs() const;
static bool kindof(unsigned kind) { return kind == AttrKind::FUNC; }
};
} // namespace TF
} // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_ATTRIBUTES_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
235e02b334117474849d4db823d5659774547917 | 5e35f1069a9d29fe34caa275e390459338d63d02 | /MainProg/test/byMap.cpp | dba830270ada85ef7816b76fa15a2a500c6911c1 | [] | no_license | ShidongS/EC504_Twitter | 0eb6caad0ffe7b8d8921fc733e18871509aa7c90 | ce14ac8276094bcc24c6d0a822693ac04b9916e9 | refs/heads/master | 2020-09-22T12:22:42.620444 | 2019-12-13T20:14:40 | 2019-12-13T20:14:40 | 225,192,068 | 0 | 1 | null | 2019-12-05T03:05:33 | 2019-12-01T16:25:49 | C++ | UTF-8 | C++ | false | false | 6,108 | cpp | #include<iostream>
#include<sstream>
#include<vector>
#include<map>
#include<string>
#include <algorithm>
#include <iterator>
using namespace std;
bool TestMode = true; // Print database out.
struct SentNode{
int SentNo;
int count;
//string sent;
SentNode(int i){
SentNo = i;
count = 0;
//sent = "";
}
};
class myDatabase{
private:
map<string, map<int,int> > Database;
/*
In each database node:
{
string: word;
map:
{
int #OfSentence;
int #HappenInSentence;
}
}
*/
public:
void setUpDatabase(string word, int i);
void searchWord(string word, vector<SentNode> &SentArr);
void printAll();
};
void Initialization(int sentCount, vector<SentNode> &SentArr);
void searchSent(string Sent, vector<SentNode> &SentArr, int sentCount, myDatabase myDB);
/*-------------HEAP---------------*/
int compareNode(vector<SentNode> &SentArr, int i, int j);
//void swap(vector<SentNode> &SentArr, int i, int j);
void maxHeapify(vector<SentNode> &SentArr, int n, int i);
void Heapify(vector<SentNode> &SentArr, int n);
void CheckHeapOrder(vector<SentNode> &SentArr,int n);
void HeapSort(vector<SentNode> &SentArr, int n);
/*------------END_HEAP-------------*/
void printTenSent(vector<SentNode> &SentArr, int n, vector<string> sents);
void printAllNode(vector<SentNode> &SentArr, vector<string> sents);
int main(){
myDatabase myDB;
vector<string> sents;
int sentCount;
// INSERT WORDS
myDB.setUpDatabase("word",2);
if(TestMode) myDB.printAll();
/*
string sent;
cin>>sent;
vector<SentNode> SentArr;
if(sentCount==0) {
cout<<"No sentences read, please check your input\n";
return -1;
}
Initialization(sentCount, SentArr);
searchSent(sent, SentArr, sentCount, myDB);
if(TestMode){
cout<<"-----------Before Heap Sort----------------\n";
printAllNode(SentArr, sents);
}
HeapSort(SentArr, sentCount);
if(TestMode){
cout<<"-----------After Heap Sort----------------\n";
printAllNode(SentArr, sents);
}
cout<<"--------------Results----------------\n";
printTenSent(SentArr, sentCount, sents);
*/
return 0;
}
void printTenSent(vector<SentNode> &SentArr, int n, vector<string> sents){
for(int i = n; i > (n-10)&& i > 0; i--){
cout<<sents[SentArr[i].SentNo]<<endl;
}
}
void printAllNode(vector<SentNode> &SentArr, vector<string> sents){
for(vector<SentNode>::iterator it = SentArr.begin(); it != SentArr.end(); it++){
cout<<"--------------"<<endl;
cout<<it.SentNo<<" "<<it.count<<endl;
cout<<sents[it.SentNo]<<endl;
}
}
void myDatabase::printAll(){
for(map<string, map<int,int> >::iterator it = Database.begin(); it != Database.end();it++){
cout<<it->first<<endl;
for(map<int,int>::iterator it1 = it->second.begin(); it1 != it->second.end();it1++){
cout<<it1->first<<" "<<it1->second<<endl;
}
}
}
void myDatabase::setUpDatabase(string word, int i){
map<string, map<int,int> >::iterator it;
it = Database.find(word);
if(it==Database.end()){
map<int, int> inner;
inner.insert(std::make_pair(i, 1));
Database.insert(std::make_pair(word, inner));
}
else{
map<int, int>::iterator innerIt;
innerIt = it->second.find(i);
if(innerIt != it->second.end()){
innerIt->second++;
}
else{
it->second.insert(std::make_pair(i, 1));
}
}
}
void myDatabase::searchWord(string word, vector<SentNode> &SentArr){
map<string, map<int,int> >::iterator it;
it = Database.find(word);
for(map<int,int>::iterator it1=it->second.begin(); it1!= it->second.end(); it1++){
SentArr[it1->first].count += it1->second;
}
}
void Initialization(int sentCount, vector<SentNode> &SentArr){
if(SentArr.size()==0)
for(int i = 0; i <= sentCount; i++){ // SentNode(0) is used to make index start from 1
SentNode tmp = SentNode(i);
SentArr.push_back(tmp);
}
else
for(int i = 0; i <= sentCount; i++){ // SentNode(0) is used to make index start from 1
SentArr[i].SentNo = i;
SentArr[i].count = 0;
}
}
void searchSent(string Sent, vector<SentNode> &SentArr, int sentCount, myDatabase myDB){
Initialization(sentCount, SentArr);
Sent = "Somewhere down the road";
istringstream iss(Sent);
do
{
string subs;
iss >> subs;
myDB.searchWord(subs,SentArr);
} while (iss);
}
/*-------------HEAP---------------*/
int compareNode(vector<SentNode> &SentArr, int i, int j){
if(SentArr[i].count<SentArr[j].count){
return -1;
}
else if(SentArr[i].count==SentArr[j].count){
return 0;
}
else{
return 1;
}
}
/*
void swap(vector<SentNode> &SentArr, int i, int j){
int tmpNo;
int tmpCount;
string tmpStr;
tmpNo = SentArr[i].SentNo;
tmpCount = SentArr[i].count;
tmpStr = SentArr[i].sent;
SentArr[i].SentNo = SentArr[j].SentNo;
SentArr[i].count = SentArr[j].count;
SentArr[i].sent = SentArr[j].sent;
SentArr[j].SentNo = tmpNo;
SentArr[j].count = tmpCount;
SentArr[j].sent = tmpStr;
}
*/
// Heap[l]>Heap[i] is compareNode(SentArr, l, i) > 0;
// swap(l,i) is swap(SentArr, l, i)
void maxHeapify(vector<SentNode> &SentArr, int n, int i)
{
int l = i*2;
int r = i*2+1;
int largest = -1;
if(l<=n&&(compareNode(SentArr, l, i) > 0))
largest = l;
else largest = i;
if(r<=n&&compareNode(SentArr, r, largest) > 0)
largest = r;
if(largest!=i){
iter_swap(SentArr.begin() + i, SentArr.begin() + largest);
//swap(SentArr, i, largest);
maxHeapify(SentArr, n, largest);
}
}
void Heapify(vector<SentNode> &SentArr, int n)
{
for(int i = int((n+1)/2); i > 0; i--)
maxHeapify(SentArr, n, i);
}
void CheckHeapOrder(vector<SentNode> &SentArr,int n)
{
int l;
int r;
int largest;
for(int i = 1; i < n/2; i++){
l = i*2;
r = i*2+1;
largest = i;
if(l<=n&&compareNode(SentArr, l, i)>0)
cout<<"Order Wrong"<<endl;
if(r<=n&&compareNode(SentArr, r, largest)>0)
cout<<"Order Wrong"<<endl;
}
}
void HeapSort(vector<SentNode> &SentArr, int n)
{
Heapify(SentArr, n);
CheckHeapOrder(SentArr,n);
int tmp;
for(int i = n; i >= 2; i--){
iter_swap(SentArr.begin() + 1, SentArr.begin() + i);
//swap(SentArr,1,i);
maxHeapify(SentArr, i-1, 1);
}
}
| [
"noreply@github.com"
] | ShidongS.noreply@github.com |
0c226994f40274a3096cc499fdad4c2d7fcdd48e | 7be9bd83c20183466a9e47e66e0d25a0d5f7505f | /arm9/include/_dialog/dialog.file.open.h | 05b803f2dffbfa500e7150afaed33a21c4747887 | [
"MIT"
] | permissive | Lrs121/winds | b635398b2906697f83daf07fa62b5750370fb9eb | 35f1b5fd458c527a6c372f94077e784f6fd960b2 | refs/heads/master | 2023-08-08T21:24:16.620369 | 2019-04-24T08:41:53 | 2019-04-24T08:41:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | h | #ifndef _WIN_D_FILEOPEN_
#define _WIN_D_FILEOPEN_
#include <_type/type.dialog.h>
#include <_type/type.shortstring.h>
#include <_gadget/gadget.button.h>
#include <_dialog/dialog.file.save.h>
#include <_gadget/gadget.button.action.h>
#include <_gadget/gadget.button.image.h>
#include <_gadget/gadget.label.h>
#include <_gadget/gadget.window.dialog.h>
#include <_gadget/gadget.fileview.h>
#include <_gadget/gadget.textbox.h>
#include <_gadget/gadget.select.h>
class _fileOpenDialog : public _dialog
{
private:
_button* openButton;
_button* cancelButton;
_label* fileNameLabel;
_textBox* fileNameBox;
_window* window;
_select* fileTypeChooser;
_fileView* fileView;
_textBox* fileViewAddress;
_actionButton* gotoButton;
_imageButton* folderUpButton;
_fileTypeList fileTypes;
_callbackReturn eventHandler( _event );
void executeInternal();
void cleanupInternal();
const _menuEntryList generateMenuList();
_fileExtensionList getFileMask( _int value ) const ;
public:
//! Ctor
//! @note if 'ignore'/nothing is passed as argument, the appropriate localized string is inserted instead
_fileOpenDialog( _fileTypeList possibleFileExtensions , string initialFilePath = "" , _int initialFileExtension = 0 , _optValue<wstring> openLabel = ignore , _optValue<wstring> windowLabel = ignore );
//! Get Index of the selected entry in 'possibleFileExtensions'
_int getFileType(){
return this->fileTypeChooser->getIntValue();
}
//! Get selected Mime-Type
_mimeType getMimeType(){
return _mimeType::fromExtension( std::get<1>(this->fileTypes[this->getFileType()]) );
}
//! Get Selected filename
string getFileName(){
return _direntry( this->fileView->getPath() ).getFileName() + this->fileNameBox->getStrValue().cpp_str();
}
//! Dtor
~_fileOpenDialog(){
delete this->openButton;
delete this->cancelButton;
delete this->fileNameLabel;
delete this->fileNameBox;
delete this->window;
delete this->fileTypeChooser;
delete this->fileView;
delete this->fileViewAddress;
delete this->gotoButton;
delete this->folderUpButton;
}
};
#endif | [
"DuffsDevice@users.noreply.github.com"
] | DuffsDevice@users.noreply.github.com |
41b13efe2899be9db20e7a1ec6a69b90791c254a | edfd9e9ed6f1603ea0f729d6890b736381625b2c | /ControlSystem.cpp | 326b621cd23a14a3ba01799ff2f14ad240acdd76 | [] | no_license | tanyushaaa/architect | c00e20a9663855b65cf3b8044edae9d1345804b4 | ba9b689636ec46df80121292217fa647a28cc838 | refs/heads/main | 2023-03-04T09:36:41.838810 | 2021-02-23T13:45:54 | 2021-02-23T13:45:54 | 341,568,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include "ControlSystem.h"
// Constructors/Destructors
//
ControlSystem::ControlSystem()
{
initAttributes();
}
ControlSystem::~ControlSystem()
{
}
//
// Methods
//
// Accessor methods
//
// Other methods
//
void ControlSystem::initAttributes()
{
}
| [
"noreply@github.com"
] | tanyushaaa.noreply@github.com |
dd7309f681474088b85040ff6be36886a6c871f3 | e98b8922ee3d566d7b7193bc71d269ce69b18b49 | /qpid-sys/NullSaslClient.cpp | 1c95c1d04d1bdb4962b7e5295c7dfdd9c8bee7ac | [] | no_license | QuarkCloud/qpid-lite | bfcf275eb5a99be3a1defb18331780d1b242dfa6 | 3818811d1b2eb70c9603c1e74045072b9a9b8cbc | refs/heads/master | 2020-04-14T17:18:28.441389 | 2019-02-18T02:20:56 | 2019-02-18T02:20:56 | 163,975,774 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "qpid/sys/NullSaslClient.h"
#include "qpid/sys/SecurityLayer.h"
#include "qpid/sys/Exception.h"
namespace qpid {
namespace sys {
namespace {
const std::string ANONYMOUS("ANONYMOUS");
const std::string PLAIN("PLAIN");
}
NullSaslClient::NullSaslClient(const std::string& u, const std::string& p) : username(u), password(p) {}
bool NullSaslClient::start(const std::string& mechanisms, std::string& response,
const qpid::sys::SecuritySettings*)
{
if (!username.empty() && !password.empty() && mechanisms.find(PLAIN) != std::string::npos) {
mechanism = PLAIN;
response = ((char)0) + username + ((char)0) + password;
}
else if (mechanisms.find(ANONYMOUS) != std::string::npos) {
mechanism = ANONYMOUS;
const char* u = username.empty() ? ANONYMOUS.c_str() : username.c_str();
response = ((char)0) + u;
}
else {
throw qpid::sys::Exception("No suitable mechanism!");
}
return true;
}
std::string NullSaslClient::step(const std::string&)
{
return std::string();
}
std::string NullSaslClient::getMechanism()
{
return mechanism;
}
std::string NullSaslClient::getUserId()
{
return username.empty() ? ANONYMOUS : username;
}
std::auto_ptr<qpid::sys::SecurityLayer> NullSaslClient::getSecurityLayer(uint16_t)
{
return std::auto_ptr<qpid::sys::SecurityLayer>();
}
}
} // namespace qpid
| [
"romandion@163.com"
] | romandion@163.com |
c3712306734701a4f16abcf797d4aa79db358d24 | d2c1bdd99f044a4cebd96aa6e6e0607b1c6191ba | /sodaq-nbiot-compass/examples/sodaq_explorer_nbiot_shield/sodaq_explorer_nbiot_shield.ino | 119d940ea1b15487b7dc0368544438744e6c908d | [] | no_license | DenniZr/sodaq-explorer-nbiot-compass | b5604b15731d91eb77adfc38c96d5951af978759 | 93de375e30ff4576d92f8266090de2c9d36de9e6 | refs/heads/master | 2021-08-24T01:55:20.114380 | 2017-12-07T14:55:45 | 2017-12-07T14:55:45 | 113,462,998 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,908 | ino | /**
* Author: Dennis Ruigrok
* There seems to be a bug with the x axes. so i don't use them
* use the sodaq explorer with nbiot shield as a badge, so that u use the y and z axes
* then it works fine
* */
#include <sodaq_compass.h>
NBIOT_Compass compass;
#include <Wire.h>
void setup() {
SerialUSB.begin(9600);
compass.setup();
}
float X,Y,Z;
float heading, headingDegrees, headingFiltered, geo_magnetic_declination_deg;
void loop() {
float xguass, yguass, zguass;
compass.getNewValues();
xguass = compass.getXGauss();
yguass = compass.getYGauss();
zguass = compass.getZGauss();
SerialUSB.println("The fieldstrengths are:");
SerialUSB.print("X: ");
SerialUSB.print(xguass, 6);
SerialUSB.println(" Guass.");
SerialUSB.print("Y: ");
SerialUSB.print(yguass, 6);
SerialUSB.println(" Guass.");
SerialUSB.print("Z: ");
SerialUSB.print(zguass, 6);
SerialUSB.println(" Guass.");
X = xguass / 32768; // 2^15 because one of the 16 bits is for positive negative
Y = yguass / 32768;
Z = zguass / 32768;
// Correcting the heading with the geo_magnetic_declination_deg angle depending on your location
// You can find your geo_magnetic_declination_deg angle at: http://www.ngdc.noaa.gov/geomag-web/
// At zzz location it's 4.2 degrees => 0.073 rad
// Haarlem 2017-10-20 1° 4' E ± 0° 22' changing by 0° 9' E per year
// Amsterdam 2017-10-20 1° 9' E ± 0° 22' changing by 0° 9' E per year
// Alkmaar 52.6324 4.7534 2017-10-20 1.09° E ± 0.38° changing by 0.14° E per year
geo_magnetic_declination_deg = 1.09; // for our location
headingDegrees = 180*atan2(Y, Z)/PI; // assume pitch, roll are 0
if (headingDegrees <0)
headingDegrees += 360;
//Sending the heading value through the Serial Port
SerialUSB.println(headingDegrees,6);
delay(1000);
}
| [
"dennis.ruigrok@gmail.com"
] | dennis.ruigrok@gmail.com |
5b72737055ecc2c34b32e3f928b18f45df0bcf4d | 19164bf117ecb486c94311cb8b2936309b363514 | /Dynamic_Programming/Coin_change_problem.cpp | d72feab27e425e7620b022531dd80c9f7cb24ad7 | [] | no_license | geekyanurag/Coding-Interview-Preparation | 10a3b5d9c2a9b71483846c0f51751cef24baa2e4 | 24f11e8ddc9c7c573aa961a9ebb3afd16234a27b | refs/heads/master | 2021-05-25T13:01:20.680206 | 2021-04-27T06:41:28 | 2021-04-27T06:41:28 | 253,764,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,003 | cpp | // Counting the number of ways to give change if we have infinite supply of coins
#include<bits/stdc++.h>
using namespace std;
// time is O(n*sum) and also with extra space
int change(int coins[], int n, int sum){
int count[n+1][sum+1];
//memset(count, 0, sizeof(count));
for(int i =0; i<=n; i++)
count[i][0] = 1;
for(int i = 1; i<=sum; i++)
count[0][i] = 0;
for(int i = 1; i<=n; i++){
for(int j = 1; j<=sum; j++){
if(j < coins[i-1])
count[i][j] = count[i-1][j];
if(j >= coins[i-1])
count[i][j] = count[i-1][j] + count[i][j-coins[i-1]]; //Similar to subset sum problem but only difference is count[i][j] = count[i-1][j] + count[i-1][j-coins[i-1]] in subset.
}
}
return count[n][sum];
}
int main(){
int n, k;
cin>>n>>k;
int coins[n];
for(int i = 0; i<n; i++)
cin>>coins[i];
//cout<<change(coins, n, k);
cout<<change1(coins, n, k);
} | [
"34518493+geekyanurag@users.noreply.github.com"
] | 34518493+geekyanurag@users.noreply.github.com |
23ff7222fc7bacd743287ece87c5d0ad63bde71a | 9aa648f6e18b8cd63396d34e17523020bc762aae | /src/Orbitons/core/Entity3d.h | 0a18f9ad13e6c625fe2518cd97f598e63be91adf | [] | no_license | gui2one/orbitons_cpp | 121127417d35610514f9f24d21990ca98369a3ab | 79a7d9b9d2e7cd9b54fb360abadce1a4e839086d | refs/heads/master | 2023-06-04T18:04:48.993424 | 2021-06-23T12:50:01 | 2021-06-23T12:50:01 | 342,857,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | h | #ifndef ENTITY_3D_H
#define ENTITY_3D_H
#include "../pch.h"
#include "../core.h"
#include "entt/entt.hpp"
namespace Orbitons{
class Entity3d {
public:
Entity3d();
virtual ~Entity3d(){};
size_t m_uuid;
std::string m_name;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
glm::mat4 transforms;
Ref<Entity3d> m_parent;
void applyTransforms();
void setScale(glm::vec3 _scale);
void setPosition(glm::vec3 _pos);
void setRotation(glm::vec3 _rot);
private:
entt::entity m_entityHandle;
};
}
#endif /* ENTITY_3D_H */ | [
"guillaume.rouault.fx@gmail.com"
] | guillaume.rouault.fx@gmail.com |
b6e76414b4a2f1e22b89b92bc3398d0690dad50d | 9a4145232417fdff1f91ff0fdee250025f7e69a3 | /Chapter.3/HelloWorld/main.cpp | 5aa14e8b9dcc9141acbbec0ecc2bceb719c4ecbd | [
"Apache-2.0"
] | permissive | ioriayane/startqtquick | bded4be5151109a8f2bda69d4caf350ad7536e14 | 135a18b2685251a3f42dffd1a6eef02bd75f03f8 | refs/heads/master | 2021-01-17T07:15:53.375884 | 2013-08-05T12:25:10 | 2013-08-05T12:25:10 | 11,896,904 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | cpp | #include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/HelloWorld/main.qml"));
viewer.showExpanded();
return app.exec();
}
| [
"iori.ayane@gmail.com"
] | iori.ayane@gmail.com |
99ea4f8c5e8c42212ab7c2697b972cce793a21a5 | 3a92132d74b183a9b77ca9c78bdf6e80c68a99e8 | /FCGIApps/Reflector/src/dimdim/common/ByteBufferOutputStream.h | e490235c5bd5f30ea69dd9190b9b36ba6d676f84 | [] | no_license | holdensmagicalunicorn/DimSim | d2ee09dd586b03e365bd673fd474d2934277ee90 | 4fbc916bd6e79fc91fc32614a7d83ffc6e41b421 | refs/heads/master | 2021-01-17T08:38:23.350840 | 2011-08-28T21:52:17 | 2011-08-28T21:52:17 | 2,285,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,084 | h | //$$<!--TOFUTAG-->$$//
/**************************************************************************
* *
* DDDDD iii DDDDD iii *
* DD DD mm mm mmmm DD DD mm mm mmmm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DD DD iii mmm mm mm DD DD iii mmm mm mm *
* DDDDDD iii mmm mm mm DDDDDD iii mmm mm mm *
* *
**************************************************************************/
/* *************************************************************************
THIS FILE IS PART OF THE DIMDIM CODEBASE. TO VIEW LICENSE AND EULA
FOR THIS CODE VISIT http://www.dimdim.com
************************************************************************ */
/* ------------------------------------------------------
File Name : dByteBufferOutputStream.h
Author : Saurav Mohapatra
Email : Saurav.Mohapatra@dimdim.com
Created On : Sun Jun 04 04:34:58 GMT+05:30 2006
------------------------------------------------------- */
#ifndef _DIMDIM_TOOLKIT_BYTE_BUFFER_OUTPUT_STREAM_H_
#define _DIMDIM_TOOLKIT_BYTE_BUFFER_OUTPUT_STREAM_H_
#include "OutputStream.h"
#include "ByteBuffer.h"
#include "Helper.h"
namespace dm
{
///
/// a binary big endian output stream which writes to a byte buffer in memory
///
class DSSFRAMEWORKAPI ByteBufferOutputStream : public OutputStream
{
public:
ByteBufferOutputStream();
ByteBufferOutputStream(ByteBuffer* buffer, bool deleteOnExit);
virtual ~ByteBufferOutputStream();
bool isValid() const;
bool isValid();
size_t write(const void* buf, size_t len);
ByteBuffer* get();
const ByteBuffer* get() const;
ByteBuffer* release();
private:
ScopedPointer<ByteBuffer> bufferPtr;
bool deleteBufferOnExit;
DDSS_FORCE_BY_REF_ONLY(ByteBufferOutputStream);
};
};
#endif
| [
"mattwilmott@gmail.com"
] | mattwilmott@gmail.com |
350c2fb53d57b834e821590704e28c74241f67d5 | 7ea60e50e26e7a77264320aee6506b561c08d618 | /Trans3_2/vc/tk3menu/tkplugin.cpp | cf3b9304ddb4c61c6fb614c0943ca8257028a729 | [
"BSD-2-Clause"
] | permissive | rpgtoolkit/trans3 | 96aa84a39ebb9058a35a91b8e1440efad52b0b30 | 2ff22d53c3ca99ee6caf509f99f81628341b6bdb | refs/heads/master | 2020-04-12T22:22:38.812906 | 2014-02-17T19:23:09 | 2014-02-17T19:23:09 | 5,168,034 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,880 | cpp | /*
********************************************************************
* The RPG Toolkit Version 3 Plugin Libraries
* This file copyright (C) 2003-2007 Christopher B. Matthews
********************************************************************
*
* This file is released under the AC Open License v 1.0
* See "AC Open License.txt" for details
********************************************************************
* Copyright (C) 2013 Lorie Jay C. Gutierrez
* piartsco@gmail.com
********************************************************************
*/
/*
* Includes
*/
#include "stdafx.h"
#include "sdk\tkplugin.h"
#include <string>
#include "menu.h"
//you can provide a one-line description of this plugin here:
PLUGIN_DESCRIPTION = "Full featured menu system for TK3";
//here is where you declare the capabilities of the plugin.
PLUGIN_TYPE = PT_MENU;
/*********************************************************************/
///////////////////////////////////////////////////////
// GENERAL INTERFACE
//
// For *all* plugins, you must modify:
// TKPlugBegin
// TKPlugEnd
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//
// Function: TKPlugBegin
//
// Parameters:
//
// Action: called when the Toolkit first
// sets up the plugin. Allows you to
// perform initialisations
//
// Returns:
//
///////////////////////////////////////////////////////
void APIENTRY TKPlugBegin()
{
//TBD: Add startup code here.
BeginMenu();
}
///////////////////////////////////////////////////////
//
// Function: TKPlugEnd
//
// Parameters:
//
// Action: called when the Toolkit unloads
// the plugin. Allows you to
// perform deallocations
//
// Returns:
//
///////////////////////////////////////////////////////
void APIENTRY TKPlugEnd()
{
//TBD: Add finishing code here.
vEndMenu();
} | [
"piartsco@gmail.com"
] | piartsco@gmail.com |
c88b417b19a5cda016b1fc1feefbb67f8e362520 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/shell/shell32/duidrag.cpp | 324296f747d6512d8a4bcadb5f1e9915e8802bf8 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 3,269 | cpp | #include "shellprv.h"
#include "duiview.h"
#include "duidrag.h"
CDUIDropTarget::CDUIDropTarget()
{
_cRef = 1;
_pDT = NULL;
_pNextDT = NULL;
}
CDUIDropTarget::~CDUIDropTarget()
{
_Cleanup();
}
HRESULT CDUIDropTarget::QueryInterface (REFIID riid, void **ppv)
{
static const QITAB qit[] =
{
QITABENT(CDUIDropTarget, IDropTarget),
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
ULONG CDUIDropTarget::AddRef (void)
{
return ++_cRef;
}
ULONG CDUIDropTarget::Release (void)
{
if (--_cRef == 0) {
delete this;
return 0;
}
return _cRef;
}
// Called by duser / directui to get the IDropTarget interface for the element
// the mouse just moved over. It is important to understand the sequencing
// calls. Initialize is called BEFORE DragLeave is called on the previous element's
// IDropTarget, so we can't switch out _pDT right away. Instead, we'll store the
// new IDropTarget in _pNextDT and then in DragEnter, we'll move it over to _pDT.
//
// The sequence looks like this:
//
// Initialize() for first element (bumps ref count to 2)
// DragEnter
// DragMove
// Initialize() for second element (bumps ref count to 3)
// DragLeave for first element
// Release for first element (decrements ref count to 2)
// DragEnter for second element
HRESULT CDUIDropTarget::Initialize (LPITEMIDLIST pidl, HWND hWnd, IDropTarget **pdt)
{
ASSERT(_pNextDT == NULL);
if (pidl)
{
SHGetUIObjectFromFullPIDL(pidl, hWnd, IID_PPV_ARG(IDropTarget, &_pNextDT));
}
QueryInterface (IID_PPV_ARG(IDropTarget, pdt));
return S_OK;
}
VOID CDUIDropTarget::_Cleanup ()
{
if (_pDT)
{
_pDT->Release();
_pDT = NULL;
}
}
STDMETHODIMP CDUIDropTarget::DragEnter(IDataObject *pDataObj, DWORD grfKeyState, POINTL ptl, DWORD *pdwEffect)
{
if ((_pDT != _pNextDT) || (_cRef == 2))
{
_pDT = _pNextDT;
_pNextDT = NULL;
if (_pDT)
{
_pDT->DragEnter (pDataObj, grfKeyState, ptl, pdwEffect);
}
else
{
*pdwEffect = DROPEFFECT_NONE;
}
POINT pt;
GetCursorPos(&pt);
DAD_DragEnterEx2 (NULL, pt, pDataObj);
}
return S_OK;
}
STDMETHODIMP CDUIDropTarget::DragOver(DWORD grfKeyState, POINTL ptl, DWORD *pdwEffect)
{
if (_pDT)
{
_pDT->DragOver (grfKeyState, ptl, pdwEffect);
}
else
{
*pdwEffect = DROPEFFECT_NONE;
}
POINT pt;
GetCursorPos(&pt);
DAD_DragMove (pt);
return S_OK;
}
STDMETHODIMP CDUIDropTarget::DragLeave(void)
{
if (_pDT || (_cRef == 2))
{
if (_pDT)
{
_pDT->DragLeave ();
}
DAD_DragLeave();
_Cleanup();
}
return S_OK;
}
STDMETHODIMP CDUIDropTarget::Drop(IDataObject *pDataObj, DWORD grfKeyState, POINTL ptl, DWORD *pdwEffect)
{
POINT pt = {ptl.x, ptl.y};
HRESULT hr = S_OK;
if (_pDT)
{
hr = _pDT->Drop (pDataObj, grfKeyState, ptl, pdwEffect);
}
return hr;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
91e96db1fb995eb9724ec41b122237baefa1e4c5 | 508ca425a965615f67af8fc4f731fb3a29f4665a | /Codeforces/66/D[ Petya and His Friends ].cpp | ad9537587385fed0f65248e322fb486537b34584 | [] | no_license | knakul853/ProgrammingContests | 2a1b216dfc20ef81fb666267d78be355400549e9 | 3366b6a4447dd4df117217734880199e006db5b4 | refs/heads/master | 2020-04-14T23:37:02.641774 | 2015-09-06T09:49:12 | 2015-09-06T09:49:12 | 164,209,133 | 1 | 0 | null | 2019-01-05T11:34:11 | 2019-01-05T11:34:10 | null | UTF-8 | C++ | false | false | 1,689 | cpp | /*
* Alfonso2 Peterssen(mukel)
* Codeforces Round #61 (Div. 2)
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <complex>
#include <cassert>
using namespace std;
typedef long long int64;
#define ALL(c) (c).begin, (c).end()
#define REP(i, n) for (int (i) = 0; (i) < (int)(n); ++(i))
#define FOR(i, b, e) for (int (i) = (int)(b); (i) <= (int)(e); ++(i))
const int MAXP = 10000;
int N;
int P;
int prime[MAXP];
bool mark[MAXP];
bool ans[100][MAXP];
int gcd(int a, int b)
{
REP(i, P)
if (ans[a][i] && ans[b][i])
return true;
return false;
}
typedef vector< int > big;
void norm(big & a)
{
int carry = 0;
REP(i, a.size())
{
int t = a[i] + carry;
a[i] = t % 10;
carry = t / 10;
}
while (carry > 0) a.push_back(carry % 10), carry /= 10;
}
void mul(big & a, int b)
{
REP(i, a.size()) a[i] *= b; norm(a);
}
int main()
{
for (int i = 2; i < MAXP; i++)
if (!mark[i])
{
prime[P++] = i;
for (int j = 2 * i; j < MAXP; j += i)
mark[j] = true;
}
cin >> N;
REP(i, N) ans[i][i % 2] = true;
int cur = 3;
int cnt = 0;
REP(i, N)
{
REP(j, i)
if (i != j)
if (!gcd(i, j))
{
if (cnt + 2 >= N) cur++, cnt = 0;
ans[i][cur] = true;
ans[j][cur] = true;
cnt += 2;
}
cur++;
}
if (N == 2) printf( "-1" );
else
{
REP(i, N)
{
big x; x.push_back(1);
REP(j, P)
if (ans[i][j]) mul(x, prime[j]);
printf( "%d", x.back() );
for (int i = x.size() - 2; i >= 0; i--)
printf( "%d", x[i] );
printf( "\n" );
}
}
return 0;
}
| [
"a2peterssen@gmail.com"
] | a2peterssen@gmail.com |
c7dbed88c001e654ab5a75502ca2314b852e8600 | 8b50ebaa8adde1b3694a79b7e59bf4c159d4d07c | /Pattern&Sequence/pattern2.cpp | dca3e25094c2e862c440591ca3c2b012334af00a | [] | no_license | aman-mishra-02/DS | 4abf81fe38236310af6a53cc23bf23030266bf20 | 12c3d0d26332f151bb83acae31496d364a43857f | refs/heads/master | 2023-07-15T06:12:16.696583 | 2021-09-04T06:22:12 | 2021-09-04T06:22:12 | 396,244,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 277 | cpp | #include<iostream>
using namespace std;
main() {
int i,j,n;
cin>>n;
for( i=1;i<=n;i++){
for(j=1;j<=n+1-i;j++){
cout<<" ";
}
for( j=1;j<=i;j++){
cout<<" "<<i-j+1;
}
cout<<endl;
}
return 0;
} | [
"amthgr0209@gmail.com"
] | amthgr0209@gmail.com |
5b438ab944bd338944c489a5248abcb97f1320ea | 3ac6b9e31cf0cffb6e18afe9e64dcf2d5afc3935 | /Prog4/Prog4/Prog4.cpp | b0109939de948c35fc06a786c770a6a38a4b886b | [] | no_license | TahaKhan1/DataStructures-C- | c4bad62273b6e3c9419b9b6f38caaa417cbc432f | 3a2e0c613bb38049b92a5a56ae6dd415eb3690b4 | refs/heads/master | 2020-07-25T08:33:51.050262 | 2017-10-08T23:46:17 | 2017-10-08T23:46:17 | 73,780,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,153 | cpp | /*--------------- P r o g 4 . c p p ---------------
by: George Cheney
16.322 Data Structures
ECE Department
UMASS Lowell
PURPOSE
This is an interactive polygon statistics program. A polygon may be entered from either the keyboard.
Then, upon command, the program will display the circumference and area of
the polygon.
DEMONSTRATES
Singly Linked Lists
Modified by: Taha Khan
Date:10/3/17
*/
#include <iostream>
#include <cmath>
#include <vector>
#include "Point.h"
#include "LinkedList.h"
using namespace std;
//----- c o n s t a n t d e f i n i t i o n s -----
// Command prompt
const char CmdPrompt[] = "\n>";
// Command Letters
const char AreaCmd = 'A'; // Compute and display the area of the polygon
// and its triangles.
const char CircumCmd = 'C'; // Compute and display the circumference of the polygon.
const char DeleteCmd = 'D'; // Delete the current point from the polygon.
const char EraseCmd = 'E'; // Make the polygon empty
const char ForwardCmd = 'F'; // Move the current entry forward one step.
const char InsertCmd = 'I'; // Insert a new point in the polygon.
const char PrintCmd = 'P'; // Show the polygon on the display.
const char QuitCmd = 'Q'; // Quit
const char RewindCmd = 'R'; // Rewind the polygon to the first point.
const char SearchCmd = 'S'; // Find the next entry with a given x coordinate.
const char UpdateCmd = 'U'; // Update the current entry
const unsigned MinPolySides = 3; // A polygon must have at least 3 sides.
//----- f u n c t i o n p r o t o t y p e s -----
char GetCmd(LinkedList &polygon);
void InsertPoints(LinkedList &polygon);
void ClearPolygon(LinkedList &polygon);
void DisplayPolygon(LinkedList &polygon);
void ShowArea(LinkedList &polygon);
void ShowCircum(LinkedList &polygon);
bool ValidPoly(LinkedList &polygon);
void UpdateEntry(LinkedList &polygon);
void Search(LinkedList &polygon);
double AreaofTriangle(Point pt1, Point pt2, Point pt3);
//--------------- m a i n ( ) ---------------
int main()
{
LinkedList polygon; // The polygon list
char cmd; // The command letter
// Repeatedly read a command from the keyboard and execute it.
for (;;)
{
cmd = GetCmd(polygon); // Get the command letter.
// If not empty command, execute it.
if (cmd != ' ')
{
switch (toupper(cmd))
{
case AreaCmd: // Display the areas.
ShowArea(polygon);
break;
case CircumCmd: // Display the circumference.
ShowCircum(polygon);
break;
case UpdateCmd: // Update the current entry.
UpdateEntry(polygon);
break;
case InsertCmd:// Insert a new point.
InsertPoints(polygon);
break;
case EraseCmd: // Clear the entire polygon.
ClearPolygon(polygon);
break;
case DeleteCmd: // Delete the current point.
if (!polygon.AtEnd())
polygon.Delete();
if (polygon.Empty())
cout << "The polygon is empty." << endl;
break;
case PrintCmd: // Display the polygon.
DisplayPolygon(polygon);
break;
case ForwardCmd: // Advance to the next point.
if (!polygon.AtEnd())
polygon.Skip();
if (polygon.AtEnd())
cout << "The polygon is at the end." << endl;
break;
case RewindCmd: // Rewind making the first point current.
polygon.Rewind();
break;
case SearchCmd: // Find the next point with a given x coordinate.
Search(polygon);
break;
case QuitCmd: // Terminate execution.
return 0;
case ' ': // Empty command; do nothing.
break;
default: // Bad command; display error message.
cout << "*** Error: Unknown Command" << endl;
break;
}
}
}
//system("pause");
return 0;
}
/*--------------- G e t C m d ( ) ---------------*/
/*PURPOSE
Accept a command from the keyboard.
INPUT PARAMETERS
polygon -- the polygon list.
RETURN VALUE
The command letter.
*/
char GetCmd(LinkedList &polygon)
{
// Display the current point before accepting each command.
if (!polygon.AtEnd())
{
// Display the current item.
cout << "\nCURRENT ITEM" << endl;
polygon.CurrentEntry().Show();
cout << endl;
}
// Prompt for a new command.
cout << CmdPrompt;
// initialize command empty.
char cmd = ' ';
// Read the command letter from the keyboard.
if (cin.peek() != '\n')
cmd = cin.get(); // Command line
cin.ignore(INT_MAX, '\n');
return cmd;
}
/*--------------- I n s e r t P o i n t s ( ) ---------------
PURPOSE
Insert a new point in the polygon before the current point.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void InsertPoints(LinkedList &polygon)
{
Point point; // New polygon point
for (;;)
{
// Read the new point and insert it into the polygon.
cout << "Enter point: ";
if (!point.Get())
return;
polygon.Insert(point);
}
}
/*--------------- U p d a t e E n t r y( ) ---------------
PURPOSE
Modify the current entry in the polygon.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void UpdateEntry(LinkedList &polygon)
{
Point point; // New point value
// If at end, say so.
if (polygon.AtEnd())
{
cout << "***Error: There is no current entry." << endl;
return;
}
// Read the new point and insert it into the polygon.
cout << "Enter point: ";
if (point.Get())
polygon.Update(point);
}
/*--------------- D i s p l a y P o l y g o n ( ) ---------------
PURPOSE
Display a polygon from beginning to end.
INPUT PARAMETERS
polygon -- the polygon to be displayed.
*/
void DisplayPolygon(LinkedList &polygon)
{
// If the polygon is empty, say so.
if (polygon.Empty())
cout << "The polygon is empty." << endl;
else
{
cout << "\nPOLYGON DEFINITION" << endl;
// Start at the beginning.
polygon.Rewind();
// Keep displaying until the end.
while (!polygon.AtEnd())
{
// Display the current entry..
polygon.CurrentEntry().Show();
cout << endl;
// Move to the next entry.
polygon.Skip();
}
cout << endl;
}
// Rewind when done.
polygon.Rewind();
}
/*--------------- C l e a r P o l y g o n ( ) ---------------
PURPOSE
Make the polygon empty.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void ClearPolygon(LinkedList &polygon)
{
// Delete vertexes until empty.
polygon.Rewind();
while (!polygon.Empty())
polygon.Delete();
}
/*--------------- V a l i d P o l y ( ) ---------------
PURPOSE
Make sure that there at least 3 points.
INPUT PARAMETERS
polygon -- the polygon list.
RETURN VALUE
true if there are at least 3 points,
false otherwise
*/
bool ValidPoly(LinkedList &polygon)
{
// Rewind to the first point.
polygon.Rewind();
// Make sure that there are at least 3 points.
for (unsigned i = 0; i<MinPolySides; i++)
{
if (polygon.AtEnd())
{
// If not valid, say so.
cout << "*** ERROR: At least " << MinPolySides << " points are needed to define a polygon." << endl;
return false;
}
polygon.Skip();
}
// Indicate valid.
return true;
}
/*--------------- S h o w C i r c u m ( ) ---------------
PURPOSE
Show on the screen the the circumference of the polygon.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void ShowCircum(LinkedList &polygon)
{
// Check for valid polygon.
if (!ValidPoly(polygon))
return;
// Rewind the current entry.
polygon.Rewind();
// Save the first point for computing the length of the last side.
Point p0 = polygon.CurrentEntry();
// Prepare to accumulate the circumference.
double circum = 0;
// Point 1 of the first side
Point p1 = p0;
// Repeatedly add the lengths of the polygon sides.
while (!polygon.AtEnd())
{
// Advance to the next point.
polygon.Skip();
// If no more points, done
if (polygon.AtEnd())
// Accumulate the length of the last side.
circum += p1.Length(p0);
else
{
// Accumulate the length of the next side.
Point p2 = polygon.CurrentEntry();
circum += p1.Length(p2);
// Point 2 is the next point 1.
p1 = p2;
}
}
// Show the circumference.
cout << "Circumference = " << circum << endl;
}
/*--------------- S e a r c h ( ) ---------------
PURPOSE
Starting at the current point, find the first point with the given x coordinate.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void Search(LinkedList &polygon)
{
// Get the desired x.
cout << "X Coordinate: ";
double x;
cin >> x;
// Skip ahead to the desired x.
for (;;)
{
// If at end and not found, return.
if (polygon.AtEnd())
{
cout << "Polygon at end\n";
break;
}
// If this entry is the one then done.
if (polygon.CurrentEntry().X() == x)
break;
// Keep looking.
polygon.Skip();
}
}
/*--------------- S h o w A r e a ( ) ---------------
PURPOSE
Show on the screen the areas of the triangles comprising the
polygon followed by the area of the polygon.
INPUT PARAMETERS
polygon -- the polygon list.
*/
void ShowArea(LinkedList &polygon)
{
// Check for valid polygon.
if (!ValidPoly(polygon))
return;
// Rewind the current entry.
polygon.Rewind();
// Declaration of variables
double triangleArea=0;
double polygonArea=0;
int count=1;
// Stores first point in p0//
Point p0 = polygon.CurrentEntry(); // Stores first point in p0//
polygon.Skip();
// Next point
Point p1 = polygon.CurrentEntry();
polygon.Skip();
// Next Point
Point p2 = polygon.CurrentEntry();
polygon.Skip();
// Calculation
triangleArea=AreaofTriangle(p0, p1, p2);
polygonArea=polygonArea+triangleArea;
cout << "Triangle:" << count << "Area=" << triangleArea << endl;
while(!polygon.AtEnd())
{
p1=p2;
p2= polygon.CurrentEntry();
// increment count
count=count+1;
triangleArea = AreaofTriangle(p0, p1, p2);
cout << "Triangle:" << count << "Area=" << triangleArea << endl;
polygonArea=polygonArea+triangleArea;
// Advance to next Point
polygon.Skip();
}
cout << "Polygon Area:" << polygonArea << endl;
}
//-----------------------Area of Triangle----------------------------------//
/*INPUT PARAMETERS:
p -- pt1, pt2, pt3 defining three sides of a triangle */
double AreaofTriangle(Point pt0, Point pt1, Point pt2)
{
double a = pt0.Length(pt1);
double b = pt0.Length(pt2);
double c = pt2.Length(pt1);
double s = (a + b + c) / 2;
return sqrt(s*(s - a)*(s - b)*(s - c));
}
| [
"mailfortaha@gmail.com"
] | mailfortaha@gmail.com |
aeaf2eb648aff6b71a719e3bebd6564c022e504f | 39471fab1d456ae6c102d309dadf1ae784ad7cd5 | /vbox/glue/src/string.cpp | 09c7463a670bd8f2045b70428826c43b64a05a3f | [
"Apache-2.0"
] | permissive | caidongyun/tray | 2735aa841614105a80b06808835a4295d8231588 | 8bd052ecd64696e340c28ed08981d4581e7d11ba | refs/heads/master | 2021-01-18T06:22:20.079846 | 2016-06-30T03:56:13 | 2016-06-30T03:56:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,639 | cpp | /* $Id: string.cpp $ */
/** @file
* MS COM / XPCOM Abstraction Layer - UTF-8 and UTF-16 string classes.
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "VBox/com/string.h"
#include <iprt/err.h>
#include <iprt/path.h>
#include <iprt/log.h>
namespace com
{
// BSTR representing a null wide char with 32 bits of length prefix (0);
// this will work on Windows as well as other platforms where BSTR does
// not use length prefixes
const OLECHAR g_achEmptyBstr[3] = { 0, 0, 0 };
const BSTR g_bstrEmpty = (BSTR)&g_achEmptyBstr[2];
/* static */
const Bstr Bstr::Empty; /* default ctor is OK */
void Bstr::copyFromN(const char *a_pszSrc, size_t a_cchMax)
{
/*
* Initialie m_bstr first in case of throws further down in the code, then
* check for empty input (m_bstr == NULL means empty, there are no NULL
* strings).
*/
m_bstr = NULL;
if (!a_cchMax || !a_pszSrc || !*a_pszSrc)
return;
/*
* Calculate the length and allocate a BSTR string buffer of the right
* size, i.e. optimize heap usage.
*/
size_t cwc;
int vrc = ::RTStrCalcUtf16LenEx(a_pszSrc, a_cchMax, &cwc);
if (RT_SUCCESS(vrc))
{
m_bstr = ::SysAllocStringByteLen(NULL, (unsigned)(cwc * sizeof(OLECHAR)));
if (RT_LIKELY(m_bstr))
{
PRTUTF16 pwsz = (PRTUTF16)m_bstr;
vrc = ::RTStrToUtf16Ex(a_pszSrc, a_cchMax, &pwsz, cwc + 1, NULL);
if (RT_SUCCESS(vrc))
return;
/* This should not happen! */
AssertRC(vrc);
cleanup();
}
}
else /* ASSUME: input is valid Utf-8. Fake out of memory error. */
AssertLogRelMsgFailed(("%Rrc %.*Rhxs\n", vrc, RTStrNLen(a_pszSrc, a_cchMax), a_pszSrc));
throw std::bad_alloc();
}
/* static */
const Utf8Str Utf8Str::Empty; /* default ctor is OK */
#if defined(VBOX_WITH_XPCOM)
void Utf8Str::cloneTo(char **pstr) const
{
size_t cb = length() + 1;
*pstr = (char *)nsMemory::Alloc(cb);
if (RT_LIKELY(*pstr))
memcpy(*pstr, c_str(), cb);
else
throw std::bad_alloc();
}
HRESULT Utf8Str::cloneToEx(char **pstr) const
{
size_t cb = length() + 1;
*pstr = (char *)nsMemory::Alloc(cb);
if (RT_LIKELY(*pstr))
{
memcpy(*pstr, c_str(), cb);
return S_OK;
}
return E_OUTOFMEMORY;
}
#endif
Utf8Str& Utf8Str::stripTrailingSlash()
{
if (length())
{
::RTPathStripTrailingSlash(m_psz);
jolt();
}
return *this;
}
Utf8Str& Utf8Str::stripFilename()
{
if (length())
{
RTPathStripFilename(m_psz);
jolt();
}
return *this;
}
Utf8Str& Utf8Str::stripPath()
{
if (length())
{
char *pszName = ::RTPathFilename(m_psz);
if (pszName)
{
size_t cchName = length() - (pszName - m_psz);
memmove(m_psz, pszName, cchName + 1);
jolt();
}
else
cleanup();
}
return *this;
}
Utf8Str& Utf8Str::stripSuffix()
{
if (length())
{
RTPathStripSuffix(m_psz);
jolt();
}
return *this;
}
size_t Utf8Str::parseKeyValue(Utf8Str &key, Utf8Str &value, size_t pos, const Utf8Str &pairSeparator, const Utf8Str &keyValueSeparator) const
{
size_t start = pos;
while(start == (pos = find(pairSeparator.c_str(), pos)))
start = ++pos;
size_t kvSepPos = find(keyValueSeparator.c_str(), start);
if (kvSepPos < pos)
{
key = substr(start, kvSepPos - start);
value = substr(kvSepPos + 1, pos - kvSepPos - 1);
}
else
{
key = value = "";
}
return pos;
}
/**
* Internal function used in Utf8Str copy constructors and assignment when
* copying from a UTF-16 string.
*
* As with the RTCString::copyFrom() variants, this unconditionally sets the
* members to a copy of the given other strings and makes no assumptions about
* previous contents. This can therefore be used both in copy constructors,
* when member variables have no defined value, and in assignments after having
* called cleanup().
*
* This variant converts from a UTF-16 string, most probably from
* a Bstr assignment.
*
* @param a_pbstr The source string. The caller guarantees that this
* is valid UTF-16.
* @param a_cwcMax The number of characters to be copied. If set to RTSTR_MAX,
* the entire string will be copied.
*
* @sa RTCString::copyFromN
*/
void Utf8Str::copyFrom(CBSTR a_pbstr, size_t a_cwcMax)
{
if (a_pbstr && *a_pbstr)
{
int vrc = RTUtf16ToUtf8Ex((PCRTUTF16)a_pbstr,
a_cwcMax, // size_t cwcString: translate entire string
&m_psz, // char **ppsz: output buffer
0, // size_t cch: if 0, func allocates buffer in *ppsz
&m_cch); // size_t *pcch: receives the size of the output string, excluding the terminator.
if (RT_SUCCESS(vrc))
m_cbAllocated = m_cch + 1;
else
{
if ( vrc != VERR_NO_STR_MEMORY
&& vrc != VERR_NO_MEMORY)
{
/* ASSUME: input is valid Utf-16. Fake out of memory error. */
AssertLogRelMsgFailed(("%Rrc %.*Rhxs\n", vrc, RTUtf16Len((PCRTUTF16)a_pbstr) * sizeof(RTUTF16), a_pbstr));
}
m_cch = 0;
m_cbAllocated = 0;
m_psz = NULL;
throw std::bad_alloc();
}
}
else
{
m_cch = 0;
m_cbAllocated = 0;
m_psz = NULL;
}
}
/**
* A variant of Utf8Str::copyFrom that does not throw any exceptions but returns
* E_OUTOFMEMORY instead.
*
* @param a_pbstr The source string.
* @returns S_OK or E_OUTOFMEMORY.
*/
HRESULT Utf8Str::copyFromEx(CBSTR a_pbstr)
{
if (a_pbstr && *a_pbstr)
{
int vrc = RTUtf16ToUtf8Ex((PCRTUTF16)a_pbstr,
RTSTR_MAX, // size_t cwcString: translate entire string
&m_psz, // char **ppsz: output buffer
0, // size_t cch: if 0, func allocates buffer in *ppsz
&m_cch); // size_t *pcch: receives the size of the output string, excluding the terminator.
if (RT_SUCCESS(vrc))
m_cbAllocated = m_cch + 1;
else
{
if ( vrc != VERR_NO_STR_MEMORY
&& vrc != VERR_NO_MEMORY)
{
/* ASSUME: input is valid Utf-16. Fake out of memory error. */
AssertLogRelMsgFailed(("%Rrc %.*Rhxs\n", vrc, RTUtf16Len((PCRTUTF16)a_pbstr) * sizeof(RTUTF16), a_pbstr));
}
m_cch = 0;
m_cbAllocated = 0;
m_psz = NULL;
return E_OUTOFMEMORY;
}
}
else
{
m_cch = 0;
m_cbAllocated = 0;
m_psz = NULL;
}
return S_OK;
}
/**
* A variant of Utf8Str::copyFromN that does not throw any exceptions but
* returns E_OUTOFMEMORY instead.
*
* @param a_pcszSrc The source string.
* @param a_offSrc Start offset to copy from.
* @param a_cchSrc The source string.
* @returns S_OK or E_OUTOFMEMORY.
*
* @remarks This calls cleanup() first, so the caller doesn't have to. (Saves
* code space.)
*/
HRESULT Utf8Str::copyFromExNComRC(const char *a_pcszSrc, size_t a_offSrc, size_t a_cchSrc)
{
cleanup();
if (a_cchSrc)
{
m_psz = RTStrAlloc(a_cchSrc + 1);
if (RT_LIKELY(m_psz))
{
m_cch = a_cchSrc;
m_cbAllocated = a_cchSrc + 1;
memcpy(m_psz, a_pcszSrc + a_offSrc, a_cchSrc);
m_psz[a_cchSrc] = '\0';
}
else
{
m_cch = 0;
m_cbAllocated = 0;
return E_OUTOFMEMORY;
}
}
else
{
m_cch = 0;
m_cbAllocated = 0;
m_psz = NULL;
}
return S_OK;
}
} /* namespace com */
| [
"okatkov@critical-factor.com"
] | okatkov@critical-factor.com |
9a17d18f02206058651b47dd1504a2b4e1338be7 | 6b98107d34359ea3cfb9811e4f99bd727798694e | /practise/mod_02/Warlock.cpp | e10170904db80414ef79274d4c0738792df2d7ea | [] | no_license | robijnvh/exam05 | 5d8172432d8137f2a113d3648af27e3fe49f93cc | 450a043b58388077699f4f42d5a8857b0d80853a | refs/heads/master | 2023-04-25T19:02:26.235357 | 2021-05-26T09:51:04 | 2021-05-26T09:51:04 | 343,731,826 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include "Warlock_test.hpp"
Warlock::Warlock(const std::string& name, const std::string& title) : _name(name), _title(title)
{
std::cout << _name << ": This looks like another boring day." << std::endl;
}
Warlock::~Warlock(void)
{
std::cout << _name << ": My job here is done!" << std::endl;
}
const std::string& Warlock::getName(void) const
{
return _name;
}
const std::string& Warlock::getTitle(void) const
{
return _title;
}
void Warlock::setTitle(const std::string& title)
{
_title = title;
}
void Warlock::introduce(void) const
{
std::cout << getName() << ": I am " << getName() << ", " << getTitle() << " !" << std::endl;
}
void Warlock::learnSpell(ASpell* spell)
{
_spellBook.learnSpell(spell);
}
void Warlock::forgetSpell(const std::string spell)
{
_spellBook.forgetSpell(spell);
}
void Warlock::launchSpell(const std::string spell_name, const ATarget& target)
{
ASpell* spell = _spellBook.createSpell(spell_name);
if (spell != NULL)
spell->launch(target);
} | [
"robijnvanhouts@Robijns-MacBook-Pro.local"
] | robijnvanhouts@Robijns-MacBook-Pro.local |
ccf68cb5d64b4a45b88f88e9e577c4a726a193d0 | eb13824ebccd9e25c2866a6de9745cf835df662f | /build-LR6-Desktop_Qt_5_12_3_MinGW_32_bit-Debug/ui_mainwindow.h | 48514030eedec81799867788f0f137ddbb9aed7c | [] | no_license | DmitryDankov207/labs | 4101c85f1b2b67ff775e34a546f8d9336a51179f | 6e9319bd4c02762fa756e1c53fab8677cc1f0e5d | refs/heads/master | 2022-01-31T15:41:36.225530 | 2019-06-24T22:22:14 | 2019-06-24T22:22:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,807 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.12.3
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QVBoxLayout *verticalLayout;
QTableWidget *tableWidget;
QHBoxLayout *horizontalLayout;
QPushButton *pushButton;
QPushButton *pushButton_3;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(400, 300);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
verticalLayout = new QVBoxLayout(centralWidget);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
tableWidget = new QTableWidget(centralWidget);
tableWidget->setObjectName(QString::fromUtf8("tableWidget"));
verticalLayout->addWidget(tableWidget);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
pushButton = new QPushButton(centralWidget);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
horizontalLayout->addWidget(pushButton);
verticalLayout->addLayout(horizontalLayout);
pushButton_3 = new QPushButton(centralWidget);
pushButton_3->setObjectName(QString::fromUtf8("pushButton_3"));
verticalLayout->addWidget(pushButton_3);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 400, 20));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QString::fromUtf8("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr));
pushButton->setText(QApplication::translate("MainWindow", "\321\203\320\264\320\260\320\273\320\270\321\202\321\214", nullptr));
pushButton_3->setText(QApplication::translate("MainWindow", "\320\237\321\200\320\265\320\276\320\261\321\200\320\260\320\267\320\276\320\262\320\260\321\202\321\214 \320\262 \320\264\320\265\321\200\320\265\320\262\320\276", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"12ddankov12@gmail.com"
] | 12ddankov12@gmail.com |
61c1300aae053a13f5196b2f7746212e4136d121 | 412a08f5d43fcd9dc5e06d2f587efa578ea40e8a | /BOJ/MST/boj6497_전력난.cpp | 57c8b1160078125d1e2c86ebda2bab25628fb405 | [] | no_license | onww1/Problem-Solving | 19b920f5f4caec50a3aded971e1f1e630e8b6c46 | 86cc8854ef0457f8f7741cbae401af5038f8ae05 | refs/heads/master | 2022-06-07T15:47:45.685775 | 2022-05-25T12:59:59 | 2022-05-25T12:59:59 | 130,528,244 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#define X first
#define Y second
using namespace std;
typedef pair <int, int> pii;
typedef pair<int, pii> piii;
const int MAX = 2e5 + 1;
int M, N, ans, pa[MAX];
int _find(int u) {
if (pa[u] < 0) return u;
return pa[u] = _find(pa[u]);
}
void _union(int u, int v) {
u = _find(u), v = _find(v);
if (u != v) pa[v] = u;
}
int main(int argc, char *argv[]) {
while (1) {
scanf("%d %d", &N, &M);
if (!N && !M) break;
memset(pa, -1, sizeof(pa));
ans = 0;
priority_queue <piii, vector<piii>, greater<piii>> pq;
for (int i = 0, x, y, z; i < M; ++i) {
scanf("%d %d %d", &x, &y, &z);
pq.push({z, {x, y}});
ans += z;
}
int cnt = 0;
while (cnt < N - 1 && !pq.empty()) {
int u = pq.top().Y.X;
int v = pq.top().Y.Y;
int w = pq.top().X;
pq.pop();
int pu = _find(u), pv = _find(v);
if (pu == pv) continue;
cnt++;
ans -= w;
_union(u, v);
}
printf("%d\n", ans);
}
return 0;
} | [
"sewon.dev@gmail.com"
] | sewon.dev@gmail.com |
12db1ccd134f3785173ff71ef0e81a21297ea8f0 | fc88f62fc50b35b7b1b11556d3d194d812858f6f | /src/libtsduck/dtv/tsDeliverySystem.h | 2f3a15ad31c3ad4aafcefdb84dcf1da5ce3ce415 | [
"BSD-2-Clause"
] | permissive | vvhh2002/tsduck | 9f316f8157407080ac20fb2b9b6cb937f999f554 | 555a210bbf608d8609a4e031cddd3896ddfcefd7 | refs/heads/master | 2020-04-07T12:50:38.246499 | 2020-01-30T16:29:13 | 2020-01-30T16:29:13 | 158,383,495 | 0 | 0 | NOASSERTION | 2018-11-20T12:05:59 | 2018-11-20T12:05:59 | null | UTF-8 | C++ | false | false | 7,772 | h | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2020, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
//!
//! @file
//! @ingroup hardware
//! Definition for transmission delivery systems.
//!
//----------------------------------------------------------------------------
#pragma once
#include "tsEnumeration.h"
namespace ts {
//!
//! Delivery systems.
//! Not all delivery systems are supported by TSDuck.
//! Linux and Windows may also support different systems.
//!
enum DeliverySystem {
#if defined(TS_LINUX) && !defined(DOXYGEN)
DS_UNDEFINED = ::SYS_UNDEFINED,
DS_DVB_S = ::SYS_DVBS,
DS_DVB_S2 = ::SYS_DVBS2,
DS_DVB_S_TURBO = ::SYS_TURBO,
DS_DVB_T = ::SYS_DVBT,
DS_DVB_T2 = ::SYS_DVBT2,
DS_DVB_C_ANNEX_A = ::SYS_DVBC_ANNEX_A,
DS_DVB_C_ANNEX_B = ::SYS_DVBC_ANNEX_B,
DS_DVB_C_ANNEX_C = ::SYS_DVBC_ANNEX_C,
DS_DVB_C2 = -10,
DS_DVB_H = ::SYS_DVBH,
DS_ISDB_S = ::SYS_ISDBS,
DS_ISDB_T = ::SYS_ISDBT,
DS_ISDB_C = ::SYS_ISDBC,
DS_ATSC = ::SYS_ATSC,
DS_ATSC_MH = ::SYS_ATSCMH,
DS_DTMB = ::SYS_DTMB,
DS_CMMB = ::SYS_CMMB,
DS_DAB = ::SYS_DAB,
DS_DSS = ::SYS_DSS,
#else
DS_UNDEFINED, //!< Undefined.
DS_DVB_S, //!< DVB-S.
DS_DVB_S2, //!< DVB-S2.
DS_DVB_S_TURBO, //!< DVB-S Turbo.
DS_DVB_T, //!< DVB-T.
DS_DVB_T2, //!< DVB-T2.
DS_DVB_C_ANNEX_A, //!< DVB-C ITU-T J.83 Annex A.
DS_DVB_C_ANNEX_B, //!< DVB-C ITU-T J.83 Annex B.
DS_DVB_C_ANNEX_C, //!< DVB-C ITU-T J.83 Annex C.
DS_DVB_C2, //!< DVB-C2.
DS_DVB_H, //!< DVB-H (deprecated).
DS_ISDB_S, //!< ISDB-S.
DS_ISDB_T, //!< ISDB-T.
DS_ISDB_C, //!< ISDB-C.
DS_ATSC, //!< ATSC.
DS_ATSC_MH, //!< ATSC-M/H (mobile handheld).
DS_DTMB, //!< DTMB Terrestrial.
DS_CMMB, //!< CMMB Terrestrial.
DS_DAB, //!< DAB (digital audio).
DS_DSS, //!< DSS Satellite.
#endif
DS_DVB_C = DS_DVB_C_ANNEX_A, //!< DVB-C, synonym for DVB-C Annex A.
};
//!
//! Enumeration description of ts::DeliverySystem.
//!
TSDUCKDLL extern const Enumeration DeliverySystemEnum;
//!
//! A subset of ts::DeliverySystem describing types of tuners.
//!
enum TunerType {
TT_UNDEFINED = DS_UNDEFINED,
TT_DVB_S = DS_DVB_S,
TT_DVB_T = DS_DVB_T,
TT_DVB_C = DS_DVB_C,
TT_ISDB_S = DS_ISDB_S,
TT_ISDB_T = DS_ISDB_T,
TT_ISDB_C = DS_ISDB_C,
TT_ATSC = DS_ATSC,
};
//!
//! Enumeration description for the subset of ts::DeliverySystem describing types of tuners.
//!
TSDUCKDLL extern const Enumeration TunerTypeEnum;
//!
//! Get the tuner type of a delivery system.
//! @param [in] system Delivery system.
//! @return Corresponding tuner type or DS_UNDEFINED if there is no corresponding tuner type.
//!
TSDUCKDLL TunerType TunerTypeOf(DeliverySystem system);
//!
//! Check if a delivery system is a satellite one.
//! This can be used to check if dish manipulations are required.
//! @param [in] sys The delivery system to check.
//! @return True if @a sys is a satellite system, false otherwise.
//!
TSDUCKDLL bool IsSatelliteDelivery(DeliverySystem sys);
//!
//! Check if a delivery system is a terrestrial one.
//! This can be used to validate the use of UHD and VHF bands.
//! @param [in] sys The delivery system to check.
//! @return True if @a sys is a terrestrial system, false otherwise.
//!
TSDUCKDLL bool IsTerrestrialDelivery(DeliverySystem sys);
//!
//! An ordered list of delivery system values (ts::DeliverySystem).
//!
typedef std::list<DeliverySystem> DeliverySystemList;
//!
//! A set of delivery system values (ts::DeliverySystem).
//! Typically used to indicate the list of standards which are supported by a tuner.
//!
class TSDUCKDLL DeliverySystemSet : public std::set<DeliverySystem>
{
public:
//!
//! Explicit reference to superclass.
//!
typedef std::set<DeliverySystem> SuperClass;
//! Check if a delivery system is present in the set.
//! @param [in] ds The delivery system to check.
//! @return True if the specified delivery system is present.
//!
bool contains(DeliverySystem ds) const { return find(ds) != end(); }
//!
//! Get the "preferred" delivery system in the set.
//! This can be used as default delivery system for a tuner.
//! @return The "preferred" delivery system in the set.
//!
DeliverySystem preferred() const;
//!
//! Return the content of the set in decreasing order of preference.
//! @return A list of all delivery systems in the set, in decreasing order of preference.
//!
DeliverySystemList toList() const;
//!
//! Convert to a string object.
//! @return Return all delivery systems in decreasing order of preference.
//!
UString toString() const;
#if !defined(DOXYGEN)
// Trampolines to superclass constructors.
DeliverySystemSet() : SuperClass() {}
DeliverySystemSet(const SuperClass& other) : SuperClass(other) {}
DeliverySystemSet(const SuperClass&& other) : SuperClass(other) {}
DeliverySystemSet(std::initializer_list<value_type> init) : SuperClass(init) {}
template<class InputIt> DeliverySystemSet(InputIt first, InputIt last) : SuperClass(first, last) {}
#endif
private:
// List of delivery systems, from most preferred to least preferred.
// This list is used to find the default delivery system of a tuner and
// to build the list of supported delivery systems in order of preference.
static const ts::DeliverySystemList _preferred_order;
};
}
| [
"thierry@lelegard.fr"
] | thierry@lelegard.fr |
d1dcf2f8655ab013e0b1c1bf28a295d846b745a2 | 13897ec1e719a3915a2e50d2fedfd9b6e26e2088 | /C++/C++/p15686.cpp | 740b199a54cf32a6f277ec9091b63588980778d7 | [] | no_license | hanjjm/Algorithm | 467b7bcad5ad87ccd83e2d01d5bf673ddfe8423a | 1619be3679dc980aac7d34f52c3f59aa253a6d20 | refs/heads/master | 2021-07-09T07:12:08.987088 | 2020-10-20T10:33:59 | 2020-10-20T10:33:59 | 205,190,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,072 | cpp | #include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int matrix[52][52];
int length, alive;
int arr[13] = {0, };
int check[13] = {0, };
int chickenCount = 0;
vector<int> chickenDistance;
vector<int> chickenNum;
vector<vector<int>> chicken(14);
vector<pair<int, int>> house;
int minNum = 987654321;
void inputMatrix() {
for(int i = 0; i < 52; i++) {
for(int j = 0; j < 52; j++) matrix[i][j] = 0;
}
int index = 1;
for(int i = 1; i <= length; i++) {
for(int j = 1; j <= length; j++) {
int num;
cin >> num;
if(num == 0) matrix[i][j] = num;
else if(num == 1) {
matrix[i][j] = num;
house.push_back(make_pair(i, j));
} else if(num == 2) {
matrix[i][j] = num;
chicken[index].push_back(i);
chicken[index].push_back(j);
index++;
}
}
}
}
void getHouseCount() {
for(int i = 1; i <= length; i++) {
for(int j = 1; j <= length; j++) {
if(matrix[i][j] == 2) chickenCount++;
}
}
}
bool compare(int a, int b) {
return a > b ? true : false;
}
void solve() {
int answer, eachNum;
int plus = 0;
for(int i = 0; i < house.size(); i++) {
eachNum = 987654321;
answer = 987654321;
for(int j = 0; j < chickenNum.size(); j++) {
eachNum = abs(house[i].first - chicken[chickenNum[j]][0]) + abs(house[i].second - chicken[chickenNum[j]][1]);
answer = min(answer, eachNum);
}
plus += answer;
}
minNum = min(minNum, plus);
}
void dfs(int index, int count) {
if(count == alive) {
for(int i = 0; i < chickenCount; i++) {
if(check[i] == 1) chickenNum.push_back(arr[i]);
}
solve();
chickenNum.clear();
return;
}
for(int i = index; i < chickenCount; i++) {
if(check[i] == 1) continue;
check[i] = 1;
dfs(i, count + 1);
check[i] = 0;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> length >> alive;
for(int i = 0; i < 13; i++) arr[i] = i + 1;
inputMatrix();
getHouseCount();
dfs(0, 0);
cout << minNum << endl;
}
//void solve() { // bfs는 시간초과. 오바해서 거리 구하는데 bfs 돌리지 말자~
// int eachNum;
// answer = 0;
// for(int i = 1; i <= length; i++) {
// for(int j = 1; j <= length; j++) {
// if(matrix[i][j] == 1) {
// chickenDistance.clear();
// resetVisited();
// queue<pair<int, int>> q;
// q.push(make_pair(i, j));
// visited[i][j] = 0;
// eachNum = 987654321;
// int chicken = 0;
// while(true) {
// int frontX = q.front().first, frontY = q.front().second;
// q.pop();
//
// for(int k = 0; k < 4; k++) {
// if(visited[frontX + dx[k]][frontY + dy[k]] == -1) {
// q.push(make_pair(frontX + dx[k], frontY + dy[k]));
// visited[frontX + dx[k]][frontY + dy[k]] = visited[frontX][frontY] + 1;
// for(int l = 0; l < chickenNum.size(); l++) {
// if(matrix[frontX + dx[k]][frontY + dy[k]].second == chickenNum[l]) {
// eachNum = min(eachNum, visited[frontX + dx[k]][frontY + dy[k]]);
// chicken++;
//// cout << chicken << endl;
// }
// }
// }
// }
// if(chicken == alive) {
// answer += eachNum;
// break;
// }
// }
// }
// }
// }
// minNum = min(minNum, answer);
//}
| [
"hanjjm1994@naver.com"
] | hanjjm1994@naver.com |
07dbd625cf9ec9bdf46abc56ad31363ff55fa6b5 | a8fc0eedb061ed09bfe605b67014624b23e44d9d | /amr-wind/wind_energy/actuator/turbine/turbine_utils.cpp | 3af60ee8ed2b8496bf76a50cf5cf3b944d415c98 | [
"BSD-3-Clause"
] | permissive | jrood-nrel/amr-wind | 9910459ca90310226af4b66ac8304853a30dc03e | 79be152505b90b8a09d93b4e7a4cdd2a3a04a4df | refs/heads/main | 2023-08-11T20:08:58.499868 | 2023-08-04T17:26:11 | 2023-08-04T17:26:11 | 240,058,263 | 0 | 0 | BSD-3-Clause | 2020-02-12T16:19:13 | 2020-02-12T16:19:12 | null | UTF-8 | C++ | false | false | 5,697 | cpp | #include "amr-wind/wind_energy/actuator/turbine/turbine_utils.H"
#include "amr-wind/utilities/ncutils/nc_interface.H"
#include "amr-wind/utilities/io_utils.H"
#include "amr-wind/wind_energy/actuator/FLLC.H"
namespace amr_wind::actuator::utils {
void read_inputs(
TurbineBaseData& tdata, TurbineInfo& tinfo, const utils::ActParser& pp)
{
pp.query("num_blades", tdata.num_blades);
pp.get("num_points_blade", tdata.num_pts_blade);
tdata.num_vel_pts_blade = tdata.num_pts_blade;
pp.get("num_points_tower", tdata.num_pts_tower);
pp.query("nacelle_area", tdata.nacelle_area);
pp.query("nacelle_drag_coeff", tdata.nacelle_cd);
if (!pp.contains("epsilon") && !pp.contains("epsilon_chord")) {
amrex::Abort(
"Actuator turbine simulations require specification of one or both "
"of 'epsilon' or 'epsilon_chord'");
}
pp.query("epsilon", tdata.eps_inp);
pp.query("epsilon_chord", tdata.eps_chord);
pp.query("epsilon_min", tdata.eps_min);
pp.query("epsilon_tower", tdata.eps_tower);
pp.get("base_position", tinfo.base_pos);
pp.get("rotor_diameter", tinfo.rotor_diameter);
pp.get("hub_height", tinfo.hub_height);
bool use_fllc = false;
pp.query("fllc", use_fllc);
if (use_fllc) {
for (int i = 0; i < tdata.num_blades; ++i) {
tdata.fllc.emplace_back();
FLLCParse(pp, tdata.fllc.back());
}
}
// clang-format off
const auto& bp = tinfo.base_pos;
const auto& rad = 0.5 * tinfo.rotor_diameter;
const auto& hh = tinfo.hub_height;
tinfo.bound_box = amrex::RealBox(
bp.x() - 1.25 * rad, bp.y() - 1.25 * rad, bp.z() - 1.25 * rad,
bp.x() + 1.25 * rad, bp.y() + 1.25 * rad, bp.z() + 1.25 * rad + hh
);
// clang-format on
}
void prepare_netcdf_file(
const std::string& ncfile,
const TurbineBaseData& meta,
const TurbineInfo& info,
const ActGrid& grid)
{
#ifdef AMR_WIND_USE_NETCDF
// Only root process handles I/O
if (!info.is_root_proc) return;
auto ncf = ncutils::NCFile::create(ncfile, NC_CLOBBER | NC_NETCDF4);
const std::string nt_name = "num_time_steps";
const std::string np_name = "num_actuator_points";
const std::string nvel_name = "num_vel_points";
const std::vector<std::string> two_dim{nt_name, np_name};
ncf.enter_def_mode();
ncf.put_attr("title", "AMR-Wind turbine actuator output");
ncf.put_attr("version", ioutils::amr_wind_version());
ncf.put_attr("created_on", ioutils::timestamp());
ncf.def_dim(nt_name, NC_UNLIMITED);
ncf.def_dim("ndim", AMREX_SPACEDIM);
ncf.def_dim("mat_dim", AMREX_SPACEDIM * AMREX_SPACEDIM);
auto grp = ncf.def_group(info.label);
grp.put_attr("num_blades", std::vector<int>{meta.num_blades});
grp.put_attr("num_points_blade", std::vector<int>{meta.num_pts_blade});
grp.put_attr("num_points_tower", std::vector<int>{meta.num_pts_tower});
grp.put_attr("rotor_diameter", std::vector<double>{info.rotor_diameter});
grp.put_attr("hub_height", std::vector<double>{info.hub_height});
// clang-format off
grp.put_attr("base_location", std::vector<double>{
info.base_pos.x(), info.base_pos.y(), info.base_pos.z()});
// clang-format on
const size_t nfpts = grid.force.size();
const size_t nvpts = grid.vel.size();
grp.def_dim(np_name, nfpts);
grp.def_dim(nvel_name, nvpts);
grp.def_var("time", NC_DOUBLE, {nt_name});
grp.def_var("chord", NC_DOUBLE, {np_name});
grp.def_var("epsilon", NC_DOUBLE, {np_name, "ndim"});
grp.def_var("rot_center", NC_DOUBLE, {nt_name, "ndim"});
grp.def_var("rotor_frame", NC_DOUBLE, {nt_name, "mat_dim"});
grp.def_var("xyz", NC_DOUBLE, {nt_name, np_name, "ndim"});
grp.def_var("force", NC_DOUBLE, {nt_name, np_name, "ndim"});
grp.def_var("orientation", NC_DOUBLE, {nt_name, np_name, "mat_dim"});
grp.def_var("vel_xyz", NC_DOUBLE, {nt_name, nvel_name, "ndim"});
grp.def_var("vel", NC_DOUBLE, {nt_name, nvel_name, "ndim"});
ncf.exit_def_mode();
{
auto chord = grp.var("chord");
chord.put(&(meta.chord[0]), {0}, {nfpts});
auto eps = grp.var("epsilon");
eps.put(&(grid.epsilon[0][0]), {0, 0}, {nfpts, AMREX_SPACEDIM});
}
#else
amrex::ignore_unused(ncfile, meta, info, grid);
#endif
}
void write_netcdf(
const std::string& ncfile,
const TurbineBaseData& meta,
const TurbineInfo& info,
const ActGrid& grid,
const amrex::Real time)
{
#ifdef AMR_WIND_USE_NETCDF
// Only root process handles I/O
if (!info.is_root_proc) return;
auto ncf = ncutils::NCFile::open(ncfile, NC_WRITE);
const std::string nt_name = "num_time_steps";
// Index of next timestep
const size_t nt = ncf.dim(nt_name).len();
const size_t nfpts = grid.force.size();
const size_t nvpts = grid.vel.size();
auto grp = ncf.group(info.label);
grp.var("time").put(&time, {nt}, {1});
grp.var("rot_center").put(&(meta.rot_center[0]), {nt, 0}, {1, 3});
grp.var("rotor_frame").put(&(meta.rotor_frame[0]), {nt, 0}, {1, 9});
grp.var("xyz").put(
&(grid.pos[0][0]), {nt, 0, 0}, {1, nfpts, AMREX_SPACEDIM});
grp.var("force").put(
&(grid.force[0][0]), {nt, 0, 0}, {1, nfpts, AMREX_SPACEDIM});
grp.var("orientation")
.put(&(grid.orientation[0][0]), {nt, 0, 0}, {1, nfpts, 9});
grp.var("vel_xyz").put(
&(grid.vel_pos[0][0]), {nt, 0, 0}, {1, nvpts, AMREX_SPACEDIM});
grp.var("vel").put(
&(grid.vel[0][0]), {nt, 0, 0}, {1, nvpts, AMREX_SPACEDIM});
#else
amrex::ignore_unused(ncfile, meta, info, grid, time);
#endif
}
} // namespace amr_wind::actuator::utils
| [
"noreply@github.com"
] | jrood-nrel.noreply@github.com |
1f9cf5a4d2ab3019016eec572a713fdaaa38c957 | 19d7278c6c42e3f86bd45c5035d19a0b07172315 | /linearAlgebra/test.cpp | 1422e28aa32ad17668fca32c238c11d20d5a4b18 | [] | no_license | physicshinzui/cppLinalg | 0a0e83d8a62c0ccdd10cc20d8dd1d0362defd33d | 6e5a77a426c6acf216ce71f606325be3257ab716 | refs/heads/master | 2023-04-13T15:01:34.063409 | 2021-04-20T10:47:55 | 2021-04-20T10:47:55 | 334,305,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84 | cpp | #include "test.h"
int TestAlgorithm::testGaussJordanElimination() {
return 0;
} | [
"physicshinzui@gmail.com"
] | physicshinzui@gmail.com |
8a6897cfc9a710db3794eeabb4b55c312ff8b3ec | 438180ac509e4f743e4d27236a686ee9eb545fdd | /Samples/Browser/src/SampleBrowser.cpp | fb0a9883fe113cb40e4d90d9ac8f923f42d0a8a6 | [
"MIT"
] | permissive | milram/ogre-1.7.4-osx | 15e3d14e827e3c198f7cda68872a0be26ba95e55 | adec12bc0694b9b56a8f31e91cc72f0f75dd83c7 | refs/heads/master | 2021-01-01T19:21:11.880357 | 2012-04-30T18:34:49 | 2012-04-30T18:34:49 | 7,885,095 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,707 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgrePlatform.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
# ifdef __GCCE__
# include <staticlibinit_gcce.h>
# endif
# include <e32base.h> // for Symbian classes.
# include <coemain.h> // for CCoeEnv.
#endif
#include "SampleBrowser.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "SampleBrowser_OSX.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
#include "SampleBrowser_iOS.h"
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
#elif OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
int mainWithTrap();
int main()
{
int res = 0;
__UHEAP_MARK;
// Create the control environment.
CCoeEnv* environment = new (ELeave) CCoeEnv();
TRAPD( err, environment->ConstructL( ETrue, 0 ) );
if( err != KErrNone )
{
printf( "Unable to create a CCoeEnv!\n" );
getchar();
}
TRAP( err, res = mainWithTrap());
// Close the stdout & stdin, else printf / getchar causes a memory leak.
fclose( stdout );
fclose( stdin );
// Cleanup
CCoeEnv::Static()->DestroyEnvironment();
delete CCoeEnv::Static();
__UHEAP_MARKEND;
return res;
}
int mainWithTrap()
#else
int main(int argc, char *argv[])
#endif
{
#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
[pool release];
return retVal;
#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
mAppDelegate = [[AppDelegate alloc] init];
[[NSApplication sharedApplication] setDelegate:mAppDelegate];
int retVal = NSApplicationMain(argc, (const char **) argv);
[pool release];
return retVal;
#else
try
{
OgreBites::SampleBrowser sb;
sb.go();
}
catch (Ogre::Exception& e)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
getchar();
#endif
}
#endif
return 0;
}
| [
"1991md@gmail.com"
] | 1991md@gmail.com |
5cec11ba86255923421af2182938ff37ed521948 | 8ddf7b977e699a209f4002a0909b9a6886608814 | /caffe2.msvsfix/caffe2/operators/conv_op_cudnn.cc | f879a541fbb9344ebb74cf4b84deb6bb7527cb99 | [
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | cbernt/GreenDanubeCloud_InDectSys | 7567a4d0c998efe62e512ffc0f286181bf3b655c | a3c774492b0b8d7517a0ac93b6bb12ab98b83bcf | refs/heads/master | 2023-02-23T10:32:56.765758 | 2021-01-20T16:12:56 | 2021-01-20T16:12:56 | 323,302,873 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,592 | cc | #include "caffe2/core/common_cudnn.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/operators/conv_op.h"
#include "caffe2/operators/conv_op_cache_cudnn.h"
#include "caffe2/operators/conv_pool_op_base.h"
namespace caffe2 {
// Earlier in the days Caffe sets the default cudnn workspace to 8MB. We bump
// it up to 64MB in Caffe2, as this enables the use of Winograd in many cases,
// something very beneficial to more recent CNN models.
static constexpr size_t kCONV_CUDNN_WORKSPACE_LIMIT_BYTES = 64 * 1024 * 1024;
// Manually specified number of algorithms implemented in CuDNN.
// This does not have any performance implications, as we will always find the
// fastest algorithm; setting them to the right number of algorithms will enable
// us to best report the statistics when doing an exhaustive search, though.
#if CUDNN_VERSION_MIN(7,0,0)
// Note: Double each of these due to potential
// tensorcode + non-tensorcore versions
// which are treated as seperate returned algos
static constexpr size_t kNUM_CUDNN_FWD_ALGS =
2*CUDNN_CONVOLUTION_FWD_ALGO_COUNT;
static constexpr size_t kNUM_CUDNN_BWD_FILTER_ALGS =
2*CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT;
static constexpr size_t kNUM_CUDNN_BWD_DATA_ALGS =
2*CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT;
#else
static constexpr size_t kNUM_CUDNN_FWD_ALGS = 7;
static constexpr size_t kNUM_CUDNN_BWD_FILTER_ALGS = 4;
static constexpr size_t kNUM_CUDNN_BWD_DATA_ALGS = 5;
#endif
namespace {
template <typename ArrayOfcudnnConvolutionAlgoPerf_t>
inline void LogCuDNNPerfStats(
const ArrayOfcudnnConvolutionAlgoPerf_t& perf_stat,
int returned_algo_count) {
VLOG(1) << "Perf result: (algo: stat, time, memory)";
for (int i = 0; i < returned_algo_count; ++i) {
const auto& stat = perf_stat[i];
VLOG(1) << stat.algo << ": " << stat.status << " " << stat.time << " "
<< stat.memory;
}
}
// Easier indexing into force_algo_ vector
enum {
ALGO_FWD = 0,
ALGO_WGRAD = 1,
ALGO_DGRAD = 2
} algoIndex_t;
} // namespace
class CudnnConvOpBase : public ConvPoolOpBase<CUDAContext> {
public:
CudnnConvOpBase(const OperatorDef& operator_def, Workspace* ws)
: ConvPoolOpBase<CUDAContext>(operator_def, ws),
cudnn_wrapper_(&context_),
cudnn_ws_nbytes_limit_(OperatorBase::GetSingleArgument<size_t>(
"ws_nbytes_limit",
kCONV_CUDNN_WORKSPACE_LIMIT_BYTES)),
exhaustive_search_(
OperatorBase::GetSingleArgument<int>("exhaustive_search", 0)),
deterministic_(
OperatorBase::GetSingleArgument<int>("deterministic", 0)),
cudnn_state_(OperatorBase::GetSingleArgument<int>("cudnn_state", 0)),
force_algo_(OperatorBase::GetRepeatedArgument<int>("force_algo", vector<int>{-1,-1,-1})),
enable_tensor_core_(OperatorBase::GetSingleArgument<bool>("enable_tensor_core", 1)) {
CHECK(!deterministic_ || !exhaustive_search_);
CAFFE_ENFORCE(group_ > 0);
CAFFE_ENFORCE(!deterministic_ || !exhaustive_search_);
for (int i = 0; i < kernel_.size(); ++i) {
OPERATOR_NEEDS_FEATURE(
pads_[i] == pads_[kernel_.size() + i],
"The current padding scheme leads to unequal padding on the left "
"and right, which is not supported by cudnn.");
}
// dilated convolution supported by some algorithms in cuDNN v6
#if !(CUDNN_VERSION_MIN(6,0,0))
OPERATOR_NEEDS_FEATURE(
dilation_h() == 1 && dilation_w() == 1,
"The cudnn convolution does not support dilation yet.");
#endif
bool individual_force_algo = OperatorBase::HasArgument("force_algo_fwd") ||
OperatorBase::HasArgument("force_algo_dgrad") ||
OperatorBase::HasArgument("force_algo_wgrad");
if (OperatorBase::HasArgument("force_algo")) {
CAFFE_ENFORCE(!individual_force_algo,
"Cannot specify both force_algo and any of",
"force_algo_fwd, force_algo_dgrad, force_algo_wgrad");
} else {
force_algo_ = std::vector<int>{-1,-1,-1};
force_algo_[ALGO_FWD] =
OperatorBase::GetSingleArgument<int>("force_algo_fwd", -1);
force_algo_[ALGO_DGRAD] =
OperatorBase::GetSingleArgument<int>("force_algo_dgrad", -1);
force_algo_[ALGO_WGRAD] =
OperatorBase::GetSingleArgument<int>("force_algo_wgrad", -1);
}
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_));
CUDNN_ENFORCE(cudnnCreateFilterDescriptor(&filter_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bias_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_));
CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_for_bias_));
CUDNN_ENFORCE(cudnnCreateConvolutionDescriptor(&conv_desc_));
}
~CudnnConvOpBase() {
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_));
CUDNN_ENFORCE(cudnnDestroyFilterDescriptor(filter_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bias_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_));
CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_for_bias_));
CUDNN_ENFORCE(cudnnDestroyConvolutionDescriptor(conv_desc_));
}
protected:
// A helper function to set up the tensor Nd desriptor, depending on the order
// the group and the type given.
template <typename T>
void SetTensorNdDescriptorWithGroup(
int size,
cudnnTensorDescriptor_t desc_,
int N,
int C,
int H,
int W,
int D) {
switch (order_) {
case StorageOrder::NHWC:
if (size == 4) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptorEx(
desc_,
cudnnTypeWrapper<T>::type,
N,
C / group_,
H,
W,
H * W * C,
1,
W * C,
C));
} else {
C = C / group_;
vector<int> dims = {N, H, W, D, C};
vector<int> strides = {H * W * D * C, W * D * C, D * C, C, 1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
desc_,
cudnnTypeWrapper<T>::type,
size > 3 ? size : 4,
dims.data(),
strides.data()));
}
break;
case StorageOrder::NCHW:
if (size == 4) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptorEx(
desc_,
cudnnTypeWrapper<T>::type,
N,
C / group_,
H,
W,
C * H * W,
H * W,
W,
1));
} else {
C = C / group_;
vector<int> dims = {N, C, H, W, D};
vector<int> strides = {C * H * W * D, H * W * D, W * D, D, 1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
desc_,
cudnnTypeWrapper<T>::type,
size > 3 ? size : 4,
dims.data(),
strides.data()));
}
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
}
vector<TIndex> cudnn_input_dims_;
vector<TIndex> cudnn_filter_dims_;
CuDNNWrapper cudnn_wrapper_;
cudnnTensorDescriptor_t bottom_desc_;
cudnnFilterDescriptor_t filter_desc_;
cudnnTensorDescriptor_t bias_desc_;
cudnnTensorDescriptor_t top_desc_;
// top desc for bias add in case we do group convolution
cudnnTensorDescriptor_t top_desc_for_bias_;
cudnnConvolutionDescriptor_t conv_desc_;
const size_t cudnn_ws_nbytes_limit_;
size_t cudnn_ws_nbytes_;
bool exhaustive_search_;
bool deterministic_;
size_t cudnn_state_;
vector<int> force_algo_; // stored as FWD, dFILTER, dDATA
bool enable_tensor_core_;
};
class CudnnConvOp final : public CudnnConvOpBase {
public:
CudnnConvOp(const OperatorDef& operator_def, Workspace* ws)
: CudnnConvOpBase(operator_def, ws) {}
~CudnnConvOp() {}
template <typename T_X, typename T_W, typename T_B, typename MATH, typename T_Y>
bool DoRunWithType();
bool RunOnDevice() override;
private:
cudnnConvolutionFwdAlgo_t algo_;
AlgorithmsCache<cudnnConvolutionFwdAlgo_t> algo_cache_;
// Input: X, W, b
// Output: Y
INPUT_TAGS(INPUT, FILTER, BIAS);
};
class CudnnConvGradientOp final : public CudnnConvOpBase {
public:
CudnnConvGradientOp(const OperatorDef& operator_def, Workspace* ws)
: CudnnConvOpBase(operator_def, ws),
no_bias_(OperatorBase::GetSingleArgument<int>("no_bias", 0)) {
CAFFE_ENFORCE(
!(no_bias_ && OutputSize() == 3),
"If bias is not present, you should not have 3 grad output.");
}
~CudnnConvGradientOp() {}
template <typename T_X, typename T_DY, typename T_W, typename T_B,
typename MATH,
typename T_DX, typename T_DW, typename T_DB>
bool DoRunWithType();
bool RunOnDevice() override;
private:
cudnnConvolutionBwdFilterAlgo_t bwd_filter_algo_;
cudnnConvolutionBwdDataAlgo_t bwd_data_algo_;
AlgorithmsCache<cudnnConvolutionBwdFilterAlgo_t> filter_algo_cache_;
AlgorithmsCache<cudnnConvolutionBwdDataAlgo_t> data_algo_cache_;
bool no_bias_;
// input: X, W, dY
// output: dW, db, and optionally dX
INPUT_TAGS(INPUT, FILTER, OUTPUT_GRAD);
OUTPUT_TAGS(FILTER_GRAD, BIAS_OR_INPUT_GRAD, INPUT_GRAD);
};
////////////////////////////////////////////////////////////////////////////////
// Implementations
////////////////////////////////////////////////////////////////////////////////
template <typename T_X, typename T_W, typename T_B, typename MATH, typename T_Y>
bool CudnnConvOp::DoRunWithType() {
auto& X = Input(INPUT);
auto& filter = Input(FILTER);
auto* Y = Output(0);
// Figure out the output shape
CAFFE_ENFORCE(X.ndim() >= 3 && X.ndim() <= 5);
CAFFE_ENFORCE(filter.ndim() >= 3 && filter.ndim() <= 5);
const int M = filter.dim32(0);
ConvPoolOpBase<CUDAContext>::SetOutputSize(X, Y, M);
int N = 0, C = 0, H = 0, W = 0, D = 0, H_out = 0, W_out = 0, D_out = 0;
int group_offset_X = 0, group_offset_Y = 0;
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
H_out = Y->dim32(1);
W_out = Y->ndim() > 3 ? Y->dim32(2) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(3) : 1;
for (int i = 0; i < kernel_.size(); ++i) {
CAFFE_ENFORCE_EQ(filter.dim32(i + 1), kernel_[i]);
}
CAFFE_ENFORCE_EQ(filter.dim32(filter.ndim() - 1), C / group_);
group_offset_X = C / group_;
group_offset_Y = M / group_;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
H_out = Y->dim32(2);
W_out = Y->ndim() > 3 ? Y->dim32(3) : 1;
D_out = Y->ndim() > 4 ? Y->dim32(4) : 1;
CAFFE_ENFORCE_EQ(filter.dim32(1), C / group_);
for (int i = 0; i < kernel_.size(); ++i) {
CAFFE_ENFORCE_EQ(filter.dim32(i + 2), kernel_[i]);
}
group_offset_X = C / group_ * H * W * D;
group_offset_Y = M / group_ * H_out * W_out * D_out;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
CAFFE_ENFORCE(
C % group_ == 0,
"If you set group, the number of input channels should be divisible "
"by group.");
CAFFE_ENFORCE(
M % group_ == 0,
"If you set group, the number of output channels should be divisible "
"by group.");
int group_offset_filter = filter.size() / group_;
// Set up the cudnn algorithms & workspace if necessary
bool input_changed = (X.dims() != cudnn_input_dims_);
bool filter_changed = (filter.dims() != cudnn_filter_dims_);
if (input_changed || filter_changed) {
VLOG(1) << "Changing the cudnn descriptor configurations.";
if (input_changed) {
cudnn_input_dims_ = X.dims();
SetTensorNdDescriptorWithGroup<T_X>(
X.ndim(), bottom_desc_, N, C, H, W, D);
}
if (filter_changed) {
cudnn_filter_dims_ = filter.dims();
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetFilter4dDescriptor(
filter_desc_,
cudnnTypeWrapper<T_W>::type,
GetCudnnTensorFormat(order_),
M / group_,
C / group_,
kernel_h(),
kernel_w()));
} else {
vector<int> dims(filter.dims().begin(), filter.dims().end());
dims[0] /= group_;
order_ == StorageOrder::NCHW ? dims[1] /= group_
: dims[filter.ndim() - 1] /= group_;
dims[filter.ndim() - 1] /= group_;
CUDNN_ENFORCE(cudnnSetFilterNdDescriptor(
filter_desc_,
cudnnTypeWrapper<T_W>::type,
GetCudnnTensorFormat(order_),
dims.size(),
dims.data()));
}
if (InputSize() == 3) {
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
bias_desc_,
GetCudnnTensorFormat(order_),
cudnnTypeWrapper<T_B>::type,
1,
M,
1,
1));
} else {
std::vector<int> bias_dims(X.ndim(), 1);
bias_dims[1] = M;
std::vector<int> strides = {M, 1, 1, 1, 1, 1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
bias_desc_,
cudnnTypeWrapper<T_B>::type,
X.ndim() > 3 ? X.ndim() : 4,
bias_dims.data(),
strides.data()));
}
}
}
// Set the output
SetTensorNdDescriptorWithGroup<T_Y>(
X.ndim(), top_desc_, N, M, H_out, W_out, D_out);
// Set the output with descriptor useful for bias addition in one run.
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
top_desc_for_bias_,
GetCudnnTensorFormat(order_),
cudnnTypeWrapper<T_B>::type,
N,
M,
H_out,
W_out));
} else {
vector<int> dims = {N, M, H_out, W_out, D_out};
vector<int> strides = {M * H_out * W_out * D_out,
H_out * W_out * D_out,
H_out * D_out,
D_out,
1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
top_desc_for_bias_,
cudnnTypeWrapper<T_B>::type,
X.ndim() > 3 ? X.ndim() : 4,
dims.data(),
strides.data()));
}
// Set the convolution descriptor
#if CUDNN_VERSION_MIN(6,0,0)
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetConvolution2dDescriptor(
conv_desc_,
pad_t(),
pad_l(),
stride_h(),
stride_w(),
dilation_h(),
dilation_w(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
} else {
CUDNN_ENFORCE(cudnnSetConvolutionNdDescriptor(
conv_desc_,
kernel_.size(),
pads_.data(),
stride_.data(),
dilation_.data(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
}
#else
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetConvolution2dDescriptor(
conv_desc_,
pad_t(),
pad_l(),
stride_h(),
stride_w(),
1,
1,
CUDNN_CROSS_CORRELATION));
} else {
vector<int> ones(dilation_.size(), 1);
CUDNN_ENFORCE(cudnnSetConvolutionNdDescriptor(
conv_desc_,
kernel_.size(),
pads_.data(),
stride_.data(),
ones.data(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
}
#endif
#if CUDNN_VERSION_MIN(7,0,0)
// enable TensorCore math if desired
enable_tensor_core_ &= TensorCoreAvailable();
if (enable_tensor_core_) {
CUDNN_ENFORCE(cudnnSetConvolutionMathType(
conv_desc_, CUDNN_TENSOR_OP_MATH));
}
// enable cuDNN conv groups
CUDNN_CHECK(cudnnSetConvolutionGroupCount(conv_desc_, group_));
#endif
if (force_algo_[ALGO_FWD] >= 0) {
algo_ = (cudnnConvolutionFwdAlgo_t)force_algo_[ALGO_FWD];
} else if (deterministic_) {
algo_ = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM;
} else if (exhaustive_search_) {
algo_ = algo_cache_.getAlgorithm(X.dims(), filter.dims(), [&]() {
VLOG(1) << "CUDNN Convolution: doing exhaustive search.";
// When we do an exhaustive search, we will ignore the workspace size
// limit and simply go for the fastest algorithm. If you happen to run
// out of memory later, you will be on your own...
int returned_algo_count;
std::array<cudnnConvolutionFwdAlgoPerf_t, kNUM_CUDNN_FWD_ALGS>
perf_stat;
// no need to clean up workspace,
cudnn_wrapper_.with_cudnn_state(cudnn_state_, [&](CuDNNState* state) {
// Actually run the search.
CUDNN_ENFORCE(cudnnFindConvolutionForwardAlgorithmEx(
state->cudnn_handle(),
bottom_desc_,
X.template data<T_X>(),
filter_desc_,
filter.template data<T_W>(),
conv_desc_,
top_desc_,
Y->template mutable_data<T_Y>(),
kNUM_CUDNN_FWD_ALGS,
&returned_algo_count,
perf_stat.data(),
state->workspace().get(cudnn_ws_nbytes_limit_),
cudnn_ws_nbytes_limit_));
});
LogCuDNNPerfStats(perf_stat, returned_algo_count);
return perf_stat[0].algo;
});
} else {
// Get the convolution algorithm based on the workspace limit.
CUDNN_ENFORCE(cudnnGetConvolutionForwardAlgorithm(
cudnn_wrapper_.inline_cudnn_handle(),
bottom_desc_,
filter_desc_,
conv_desc_,
top_desc_,
CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
cudnn_ws_nbytes_limit_,
&algo_));
}
CUDNN_ENFORCE(cudnnGetConvolutionForwardWorkspaceSize(
cudnn_wrapper_.inline_cudnn_handle(),
bottom_desc_,
filter_desc_,
conv_desc_,
top_desc_,
algo_,
&cudnn_ws_nbytes_));
VLOG(1) << "CuDNN algorithm: " << algo_;
VLOG(1) << "CuDNN workspace size: " << cudnn_ws_nbytes_;
}
// Now, actually run the computation.
// Run directly through cuDNN if possible
#if CUDNN_VERSION_MIN(7,0,0)
cudnn_wrapper_.with_cudnn_state(cudnn_state_, [&](CuDNNState* state) {
CUDNN_ENFORCE(cudnnConvolutionForward(
state->cudnn_handle(),
cudnnTypeWrapper<T_X>::kOne(),
bottom_desc_,
X.template data<T_X>(),
filter_desc_,
filter.template data<T_W>(),
conv_desc_,
algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_Y>::kZero(),
top_desc_,
Y->template mutable_data<T_Y>()));
});
#else
// otherwise manually run through groups
for (int i = 0; i < group_; ++i) {
cudnn_wrapper_.with_cudnn_state(cudnn_state_, [&](CuDNNState* state) {
CUDNN_ENFORCE(cudnnConvolutionForward(
state->cudnn_handle(),
cudnnTypeWrapper<T_X>::kOne(),
bottom_desc_,
X.template data<T_X>() + i * group_offset_X,
filter_desc_,
filter.template data<T_W>() + i * group_offset_filter,
conv_desc_,
algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_Y>::kZero(),
top_desc_,
Y->template mutable_data<T_Y>() + i * group_offset_Y));
});
}
#endif
// Bias
if (InputSize() == 3) {
auto& bias = Input(BIAS);
CAFFE_ENFORCE_EQ(bias.ndim(), 1);
CAFFE_ENFORCE_EQ(bias.dim32(0), M);
CUDNN_ENFORCE(cudnnAddTensor(
cudnn_wrapper_.inline_cudnn_handle(),
cudnnTypeWrapper<T_B>::kOne(),
bias_desc_,
bias.template data<T_B>(),
cudnnTypeWrapper<T_Y>::kOne(),
top_desc_for_bias_,
Y->template mutable_data<T_Y>()));
}
// Done.
return true;
}
bool CudnnConvOp::RunOnDevice() {
if (Input(0).IsType<float>()) {
return DoRunWithType<float, // X
float, // W
float, // B
float, // Math
float>(); // Y
} else if (Input(0).IsType<float16>()) {
return DoRunWithType<float16, // X
float16, // W
float16, // B
float, // Math
float16>(); // Y
} else {
LOG(FATAL) << "Only float (32bit) and float16 are supported by "
<< "cudnn convolution, but input " << debug_def().input(0)
<< " has [" << Input(0).meta().name() << "]";
}
return true;
}
template <typename T_X, typename T_DY, typename T_W, typename T_B,
typename MATH,
typename T_DX, typename T_DW, typename T_DB>
bool CudnnConvGradientOp::DoRunWithType() {
auto& X = Input(INPUT);
auto& filter = Input(FILTER);
auto& dY = Input(OUTPUT_GRAD);
auto* dfilter = Output(FILTER_GRAD);
CAFFE_ENFORCE(X.ndim() >= 3 && X.ndim() <= 5);
CAFFE_ENFORCE(filter.ndim() >= 3 && filter.ndim() <= 5);
const int M = filter.dim32(0);
int N = 0, C = 0, H = 0, W = 0, D = 0, H_out = 0, W_out = 0, D_out = 0;
int group_offset_X = 0, group_offset_Y = 0;
switch (order_) {
case StorageOrder::NHWC:
N = X.dim32(0);
H = X.dim32(1);
W = X.ndim() > 3 ? X.dim32(2) : 1;
D = X.ndim() > 4 ? X.dim32(3) : 1;
C = X.dim32(X.ndim() - 1);
H_out = dY.dim32(1);
W_out = dY.ndim() > 3 ? dY.dim32(2) : 1;
D_out = dY.ndim() > 4 ? dY.dim32(3) : 1;
for (int i = 0; i < kernel_.size(); ++i) {
CAFFE_ENFORCE_EQ(filter.dim32(i + 1), kernel_[i]);
}
CAFFE_ENFORCE_EQ(filter.dim32(filter.ndim() - 1), C / group_);
group_offset_X = C / group_;
group_offset_Y = M / group_;
break;
case StorageOrder::NCHW:
N = X.dim32(0);
C = X.dim32(1);
H = X.dim32(2);
W = X.ndim() > 3 ? X.dim32(3) : 1;
D = X.ndim() > 4 ? X.dim32(4) : 1;
H_out = dY.dim32(2);
W_out = dY.ndim() > 3 ? dY.dim32(3) : 1;
D_out = dY.ndim() > 4 ? dY.dim32(4) : 1;
CAFFE_ENFORCE_EQ(filter.dim32(1), C / group_);
for (int i = 0; i < kernel_.size(); ++i) {
CAFFE_ENFORCE_EQ(filter.dim32(i + 2), kernel_[i]);
}
group_offset_X = C / group_ * H * W * D;
group_offset_Y = M / group_ * H_out * W_out * D_out;
break;
default:
LOG(FATAL) << "Unknown storage order: " << order_;
}
CAFFE_ENFORCE(
C % group_ == 0,
"If you set group, the number of input channels should be divisible "
"by group.");
CAFFE_ENFORCE(
M % group_ == 0,
"If you set group, the number of output channels should be divisible "
"by group.");
int group_offset_filter = filter.size() / group_;
if (kernel_.size() == 1) {
ConvPoolOpBase<CUDAContext>::ComputePads({H});
} else if (kernel_.size() == 2) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W});
} else if (kernel_.size() == 3) {
ConvPoolOpBase<CUDAContext>::ComputePads({H, W, D});
} else {
CAFFE_THROW("Unsupported kernel size:", kernel_.size());
}
dfilter->ResizeLike(filter);
// Set up the cudnn algorithms & workspace if necessary
bool input_changed = (X.dims() != cudnn_input_dims_);
bool filter_changed = (filter.dims() != cudnn_filter_dims_);
if (input_changed || filter_changed) {
VLOG(1) << "Changing the cudnn descriptor configurations.";
if (input_changed) {
cudnn_input_dims_ = X.dims();
SetTensorNdDescriptorWithGroup<T_X>(
X.ndim(), bottom_desc_, N, C, H, W, D);
}
if (filter_changed) {
cudnn_filter_dims_ = filter.dims();
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetFilter4dDescriptor(
filter_desc_,
cudnnTypeWrapper<T_W>::type,
GetCudnnTensorFormat(order_),
M / group_,
C / group_,
kernel_h(),
kernel_w()));
} else {
vector<int> dims(filter.dims().begin(), filter.dims().end());
dims[0] /= group_;
order_ == StorageOrder::NCHW ? dims[1] /= group_
: dims[filter.ndim() - 1] /= group_;
CUDNN_ENFORCE(cudnnSetFilterNdDescriptor(
filter_desc_,
cudnnTypeWrapper<T_W>::type,
GetCudnnTensorFormat(order_),
dims.size(),
dims.data()));
}
if (!no_bias_) {
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
bias_desc_,
GetCudnnTensorFormat(order_),
cudnnTypeWrapper<T_B>::type,
1,
M,
1,
1));
} else {
std::vector<int> bias_dims(X.ndim(), 1);
bias_dims[1] = M;
std::vector<int> strides = {M, 1, 1, 1, 1, 1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
bias_desc_,
cudnnTypeWrapper<T_B>::type,
X.ndim() > 3 ? X.ndim() : 4,
bias_dims.data(),
strides.data()));
}
}
}
// Set the output
SetTensorNdDescriptorWithGroup<T_DX>(
X.ndim(), top_desc_, N, M, H_out, W_out, D_out);
// Set the output with descriptor useful for bias addition in one run.
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetTensor4dDescriptor(
top_desc_for_bias_,
GetCudnnTensorFormat(order_),
cudnnTypeWrapper<T_B>::type,
N,
M,
H_out,
W_out));
} else {
vector<int> dims = {N, M, H_out, W_out, D_out};
vector<int> strides = {M * H_out * W_out * D_out,
H_out * W_out * D_out,
H_out * D_out,
D_out,
1};
CUDNN_ENFORCE(cudnnSetTensorNdDescriptor(
top_desc_for_bias_,
cudnnTypeWrapper<T_B>::type,
X.ndim() > 3 ? X.ndim() : 4,
dims.data(),
strides.data()));
}
// Set the convolution descriptor
#if CUDNN_VERSION_MIN(6,0,0)
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetConvolution2dDescriptor(
conv_desc_,
pad_t(),
pad_l(),
stride_h(),
stride_w(),
dilation_h(),
dilation_w(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
} else {
CUDNN_ENFORCE(cudnnSetConvolutionNdDescriptor(
conv_desc_,
kernel_.size(),
pads_.data(),
stride_.data(),
dilation_.data(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
}
#else
if (kernel_.size() == 2) {
CUDNN_ENFORCE(cudnnSetConvolution2dDescriptor(
conv_desc_,
pad_t(),
pad_l(),
stride_h(),
stride_w(),
1,
1,
CUDNN_CROSS_CORRELATION));
} else {
vector<int> ones(dilation_.size(), 1);
CUDNN_ENFORCE(cudnnSetConvolutionNdDescriptor(
conv_desc_,
kernel_.size(),
pads_.data(),
stride_.data(),
ones.data(),
CUDNN_CROSS_CORRELATION,
cudnnTypeWrapper<MATH>::type));
}
#endif
#if CUDNN_VERSION_MIN(7,0,0)
// enable TensorCore math if desired
enable_tensor_core_ &= TensorCoreAvailable();
if (enable_tensor_core_) {
CUDNN_ENFORCE(cudnnSetConvolutionMathType(
conv_desc_, CUDNN_TENSOR_OP_MATH));
}
// set cuDNN groups if appropriate
CUDNN_CHECK(cudnnSetConvolutionGroupCount(conv_desc_, group_));
#endif
// Set the workspace
size_t bwd_filter_ws_size, bwd_data_ws_size;
// Choose dW algorithm
if (force_algo_[ALGO_WGRAD] >= 0) {
bwd_filter_algo_ = (cudnnConvolutionBwdFilterAlgo_t)force_algo_[ALGO_WGRAD];
} else if (deterministic_) {
bwd_filter_algo_ = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1;
} else if (exhaustive_search_) {
bwd_filter_algo_ =
filter_algo_cache_.getAlgorithm(X.dims(), filter.dims(), [&]() {
VLOG(1) << "CUDNN Convolution bwd: doing filter exhaustive search.";
// When we do an exhaustive search, we will ignore the workspace
// size
// limit and simply go for the fastest algorithm. If you happen to
// run
// out of memory later, you will be on your own...
int returned_algo_count;
// We clean up the current workspace memory so that the forward
// algorithm is free to allocate memory.
// Actually run the search.
std::array<
cudnnConvolutionBwdFilterAlgoPerf_t,
kNUM_CUDNN_BWD_FILTER_ALGS>
filter_perf_stat;
cudnn_wrapper_.with_cudnn_state(
cudnn_state_, [&](CuDNNState* state) {
CUDNN_ENFORCE(cudnnFindConvolutionBackwardFilterAlgorithmEx(
state->cudnn_handle(),
bottom_desc_,
X.template data<T_X>(),
top_desc_,
dY.template data<T_DY>(),
conv_desc_,
filter_desc_,
dfilter->template mutable_data<T_DW>(),
kNUM_CUDNN_BWD_FILTER_ALGS,
&returned_algo_count,
filter_perf_stat.data(),
state->workspace().get(cudnn_ws_nbytes_limit_),
cudnn_ws_nbytes_limit_));
});
LogCuDNNPerfStats(filter_perf_stat, returned_algo_count);
return filter_perf_stat[0].algo;
});
} else {
// choose backward algorithm for filter
CUDNN_ENFORCE(cudnnGetConvolutionBackwardFilterAlgorithm(
cudnn_wrapper_.inline_cudnn_handle(),
bottom_desc_,
top_desc_,
conv_desc_,
filter_desc_,
CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
cudnn_ws_nbytes_limit_,
&bwd_filter_algo_));
}
// Pick dX algo if needed
if (OutputSize() == 3 || (no_bias_ && (OutputSize() == 2))) {
if (force_algo_[ALGO_DGRAD] >= 0) {
bwd_data_algo_ = (cudnnConvolutionBwdDataAlgo_t)force_algo_[ALGO_DGRAD];
} else if (deterministic_) {
bwd_data_algo_ = CUDNN_CONVOLUTION_BWD_DATA_ALGO_1;
} else if (exhaustive_search_) {
bwd_data_algo_ =
data_algo_cache_.getAlgorithm(X.dims(), filter.dims(), [&]() {
VLOG(1) << "CUDNN Convolution bwd: doing data exhaustive search.";
int returned_algo_count;
std::array<
cudnnConvolutionBwdDataAlgoPerf_t,
kNUM_CUDNN_BWD_DATA_ALGS>
data_perf_stat;
cudnn_wrapper_.with_cudnn_state(
cudnn_state_, [&](CuDNNState* state) {
auto* dX =
Output(no_bias_ ? BIAS_OR_INPUT_GRAD : INPUT_GRAD);
dX->ResizeLike(X);
const T_W* filter_data = filter.template data<T_W>();
const T_DY* dYdata = dY.template data<T_DY>();
T_DX* dXdata = dX->template mutable_data<T_DX>();
CUDNN_ENFORCE(cudnnFindConvolutionBackwardDataAlgorithmEx(
state->cudnn_handle(),
filter_desc_,
filter_data,
top_desc_,
dYdata,
conv_desc_,
bottom_desc_,
dXdata,
kNUM_CUDNN_BWD_DATA_ALGS,
&returned_algo_count,
data_perf_stat.data(),
state->workspace().get(cudnn_ws_nbytes_limit_),
cudnn_ws_nbytes_limit_));
});
LogCuDNNPerfStats(data_perf_stat, returned_algo_count);
return data_perf_stat[0].algo;
});
} else {
CUDNN_ENFORCE(cudnnGetConvolutionBackwardDataAlgorithm(
cudnn_wrapper_.inline_cudnn_handle(),
filter_desc_,
top_desc_,
conv_desc_,
bottom_desc_,
CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
cudnn_ws_nbytes_limit_,
&bwd_data_algo_));
}
}
// get workspace for backwards filter algorithm
CUDNN_ENFORCE(cudnnGetConvolutionBackwardFilterWorkspaceSize(
cudnn_wrapper_.inline_cudnn_handle(),
bottom_desc_,
top_desc_,
conv_desc_,
filter_desc_,
bwd_filter_algo_,
&bwd_filter_ws_size));
if (OutputSize() == 3 || (no_bias_ && (OutputSize() == 2))) {
// get workspace for backwards data algorithm
CUDNN_ENFORCE(cudnnGetConvolutionBackwardDataWorkspaceSize(
cudnn_wrapper_.inline_cudnn_handle(),
filter_desc_,
top_desc_,
conv_desc_,
bottom_desc_,
bwd_data_algo_,
&bwd_data_ws_size));
} else {
bwd_data_ws_size = 0;
}
cudnn_ws_nbytes_ = std::max(bwd_filter_ws_size, bwd_data_ws_size);
VLOG(1) << "CuDNN bwd algorithm: " << bwd_filter_algo_ << ", "
<< bwd_data_algo_;
VLOG(1) << "CuDNN workspace size: " << cudnn_ws_nbytes_;
}
// Now, actually run the computation.
if (!no_bias_) {
auto* dbias = Output(BIAS_OR_INPUT_GRAD);
dbias->Resize(M);
CUDNN_ENFORCE(cudnnConvolutionBackwardBias(
cudnn_wrapper_.inline_cudnn_handle(),
cudnnTypeWrapper<T_DY>::kOne(),
top_desc_for_bias_,
dY.template data<T_DY>(),
cudnnTypeWrapper<T_DB>::kZero(),
bias_desc_,
dbias->template mutable_data<T_DB>()));
}
#if CUDNN_VERSION_MIN(7,0,0)
cudnn_wrapper_.with_cudnn_state(cudnn_state_, [&](CuDNNState* state) {
CUDNN_ENFORCE(cudnnConvolutionBackwardFilter(
state->cudnn_handle(),
cudnnTypeWrapper<T_X>::kOne(),
bottom_desc_,
X.template data<T_X>(),
top_desc_,
dY.template data<T_DY>(),
conv_desc_,
bwd_filter_algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_DW>::kZero(),
filter_desc_,
dfilter->template mutable_data<T_DW>()));
if (OutputSize() == 3 || (no_bias_ && (OutputSize() == 2))) {
// Compute the gradient w.r.t. the input.
auto* dX = Output(no_bias_ ? BIAS_OR_INPUT_GRAD : INPUT_GRAD);
dX->ResizeLike(X);
CUDNN_ENFORCE(cudnnConvolutionBackwardData(
state->cudnn_handle(),
cudnnTypeWrapper<T_W>::kOne(),
filter_desc_,
filter.template data<T_W>(),
top_desc_,
dY.template data<T_DY>(),
conv_desc_,
bwd_data_algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_DX>::kZero(),
bottom_desc_,
dX->template mutable_data<T_DX>()));
}
});
#else
for (int i = 0; i < group_; ++i) {
cudnn_wrapper_.with_cudnn_state(cudnn_state_, [&](CuDNNState* state) {
CUDNN_ENFORCE(cudnnConvolutionBackwardFilter(
state->cudnn_handle(),
cudnnTypeWrapper<T_X>::kOne(),
bottom_desc_,
X.template data<T_X>() + i * group_offset_X,
top_desc_,
dY.template data<T_DY>() + i * group_offset_Y,
conv_desc_,
bwd_filter_algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_DW>::kZero(),
filter_desc_,
dfilter->template mutable_data<T_DW>() + i * group_offset_filter));
if (OutputSize() == 3 || (no_bias_ && (OutputSize() == 2))) {
// Compute the gradient w.r.t. the input.
auto* dX = Output(no_bias_ ? BIAS_OR_INPUT_GRAD : INPUT_GRAD);
dX->ResizeLike(X);
CUDNN_ENFORCE(cudnnConvolutionBackwardData(
state->cudnn_handle(),
cudnnTypeWrapper<T_W>::kOne(),
filter_desc_,
filter.template data<T_W>() + i * group_offset_filter,
top_desc_,
dY.template data<T_DY>() + i * group_offset_Y,
conv_desc_,
bwd_data_algo_,
state->workspace().get(cudnn_ws_nbytes_),
cudnn_ws_nbytes_,
cudnnTypeWrapper<T_DX>::kZero(),
bottom_desc_,
dX->template mutable_data<T_DX>() + i * group_offset_X));
}
});
}
#endif
return true;
}
// TODO(Yangqing): a lot of the function contents are very similar. Consider
// consolidating them.
bool CudnnConvGradientOp::RunOnDevice() {
if (Input(0).IsType<float>()) {
return DoRunWithType<float, // X
float, // dY
float, // W
float, // b
float, // Math
float, // dX
float, // dW
float>(); // db
}
else if (Input(0).IsType<float16>()) {
return DoRunWithType<float16, // X
float16, // dY
float16, // W
float16, // b
float, // Math
float16, // dX
float16, // dW
float16>(); // db
} else {
LOG(FATAL) << "Unsupported input types";
}
return true;
}
REGISTER_CUDNN_OPERATOR(Conv, CudnnConvOp);
REGISTER_CUDNN_OPERATOR(ConvGradient, CudnnConvGradientOp);
REGISTER_CUDNN_OPERATOR(Conv1D, CudnnConvOp);
REGISTER_CUDNN_OPERATOR(Conv1DGradient, CudnnConvGradientOp);
REGISTER_CUDNN_OPERATOR(Conv2D, CudnnConvOp);
REGISTER_CUDNN_OPERATOR(Conv2DGradient, CudnnConvGradientOp);
REGISTER_CUDNN_OPERATOR(Conv3D, CudnnConvOp);
REGISTER_CUDNN_OPERATOR(Conv3DGradient, CudnnConvGradientOp);
} // namespace caffe2
| [
"c.bernthaler@nmrobotic.com"
] | c.bernthaler@nmrobotic.com |
6c4c8a5fb2b3ddd0a20439c799cf117c654e2e2c | bb410153dcdbfffb812711c878d3f48d40db45c6 | /src/dsp/Generators/Generator.h | 9bc6eb76ed115ce7a40b87f6406f2556dcf5a389 | [
"BSD-3-Clause"
] | permissive | krokoschlange/cr42ynth | 3228ed942caf278e4e6780be3590b27504c5a7a1 | bc03846eb1438c3fc4ac7bcae4e731b9c8df65b1 | refs/heads/master | 2021-11-28T21:51:43.998487 | 2020-12-03T18:32:11 | 2020-12-03T18:32:11 | 184,879,438 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,482 | h | /*******************************************************************************
* Copyright (c) 2020 krokoschlange and contributors.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#ifndef SRC_DSP_GENERATORS_GENERATOR_H_
#define SRC_DSP_GENERATORS_GENERATOR_H_
#include <vector>
#include <map>
#include "OSCEventListener.h"
namespace cr42y
{
class Property;
class Voice;
class Generator : public OSCEventListener
{
public:
Generator(std::vector<Voice*>* vce);
virtual ~Generator();
void addProperty(Property* ctrl);
void removeProperty(Property* ctrl);
virtual void nextSample() = 0;
virtual float getSample(Voice* vce);
virtual void voiceAdded(Voice* vce) = 0;
virtual void voiceRemoved(Voice* vce) = 0;
protected:
std::vector<Property*> controls;
std::vector<Voice*>* voices;
std::map<Voice*, float> values;
};
} /* namespace cr42y */
#endif /* SRC_DSP_GENERATORS_GENERATOR_H_ */
| [
"fabian.i.baer@gmx.de"
] | fabian.i.baer@gmx.de |
18517c6d4b85d32bc81f8bcb0a962c35733c27a5 | 92a698345cc2af7f6cea6784ea779bd594716f15 | /src/rcib_object.h | fda1289af0ce64e8f500d1bf00aade5fb48ccba7 | [
"BSD-3-Clause"
] | permissive | xtx1130/node-threadobject | 2d12a4047435df8f439da7e151e9adf176021596 | 5a4223e4f13afe5fce2f329f81bdb32e3cfdb1db | refs/heads/master | 2021-01-12T05:34:41.222894 | 2016-12-22T00:45:55 | 2016-12-22T00:45:55 | 77,132,301 | 1 | 0 | null | 2016-12-22T09:40:25 | 2016-12-22T09:40:25 | null | UTF-8 | C++ | false | false | 3,810 | h | /*
"license": "BSD"
*/
#ifndef RCIB_OBJECT_
#define RCIB_OBJECT_
#include <node.h>
#include <v8.h>
#include <uv.h>
#if defined _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <node_buffer.h>
#include <malloc.h>
#include <stdlib.h>
#include <string>
#include <memory>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include "rcib/macros.h"
#include "rcib/aligned_memory.h"
#include "rcib/lazy_instance.h"
#include "rcib/ref_counted.h"
#include "rcib/WrapperObj.h"
#include "rcib/WeakPtr.h"
#include "rcib/FastDelegateImpl.h"
#include "rcib/time/time.h"
#include "rcib/MessagePump.h"
#include "rcib/util_tools.h"
#include "rcib/Event/WaitableEvent.h"
#include "rcib/PendingTask.h"
#include "rcib/observer_list.h"
#include "rcib/MessagePumpDefault.h"
#include "rcib/MessageLoop.h"
#include "rcib/roler.h"
#include "rcib/Thread.h"
#include "rcib/at_exist.h"
namespace rcib {
struct async_t_handle{
uv_async_t handle_;
};
enum WORKTYPE{
TYPE_START = 0,
TYPE_SHA_256,
TYPE_SHA = TYPE_SHA_256,
TYPE_ED25519,
//...
TYPE_END
};
struct async_req {
std::string error;
char *out;
ssize_t result;
v8::Isolate* isolate;
v8::Persistent<v8::Function> callback;
bool finished;
WORKTYPE w_t;
};
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
virtual void* Allocate(size_t length);
virtual void* AllocateUninitialized(size_t length);
virtual void Free(void* data, size_t);
};
class RcibHelper {
public:
explicit RcibHelper();
//static
static RcibHelper* GetInstance();
static void AfterAsync(uv_async_t* h);
static void DoNopAsync(async_req* r);
static void DoNopAsync(async_req* r, size_t size);
static void EMark(async_req* req, std::string message);
static void init_async_req(async_req *req);
void Init();
void Terminate();
void Uv_Send(async_req* req, uv_async_t* h);
inline void Push(async_req *itme) {
pending_queue_.push_back(itme);
}
inline async_req* Pop() {
if (working_queue_.empty())
return NULL;
async_req * item = working_queue_.front();
working_queue_.pop_front();
return item;
}
inline void PickFinished();
inline size_t taskNum(){
return 0;
}
private:
std::list<async_req *> pending_queue_;
std::list<async_req *> working_queue_;
async_t_handle *handle_;
};
class furOfThread {
public:
furOfThread(){
}
~furOfThread(){
}
void* Wrap(v8::Local<v8::Object> object){
DCHECK_EQ(false, object.IsEmpty());
DCHECK_G(object->InternalFieldCount(), 0);
base::Thread *thread = new base::Thread();
if (!thread) return nullptr;
if (!thread->IsRunning()){
thread->set_thread_name("distribute_task_thread");
thread->StartWithOptions(base::Thread::Options());
}
object->SetAlignedPointerInInternalField(0, (void*)thread);
return thread;
}
void Wrap(v8::Local<v8::Object> object, void *tmp){
DCHECK_EQ(false, object.IsEmpty());
DCHECK_G(object->InternalFieldCount(), 0);
object->SetAlignedPointerInInternalField(0, nullptr);
}
void *Unwrap(v8::Local<v8::Object> object){
DCHECK_EQ(false, object.IsEmpty());
DCHECK_G(object->InternalFieldCount(), 0);
return object->GetAlignedPointerFromInternalField(0);
}
bool IsRunning(base::Thread* thread){
if (thread){
return thread->IsRunning();
}
return false;
}
void Close(base::Thread* thread){
if (thread){
delete thread;
}
}
base::Thread* Get(v8::Local<v8::Object> object){
return static_cast<base::Thread*>(Unwrap(object));
}
};
} //end rcib
#endif
| [
"classfellow@qq.com"
] | classfellow@qq.com |
cd5bca7e5bf26c3d6bf3dd90c37d2fac213ea2d7 | dfce82118dca209d2b70a1c2e996ec1ed3c905ce | /OpcClient/src/LocalSyncOPCCLient.cpp | 09fea86dc8b99023c3c2bb5f76b797d39b389279 | [] | no_license | wenwushq/OPCClient | 837a49cfa34d6754897ed75b28be35f3ef6c959a | 19cb54a0ece61172e9e5f5ba63ca50d2c4d38dc6 | refs/heads/main | 2023-01-07T19:54:15.423280 | 2020-11-05T10:01:00 | 2020-11-05T10:01:00 | 310,238,809 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,103 | cpp | #include "LocalSyncOPCCLient.h"
#include <Winsvc.h>
#include <algorithm>
#pragma comment(lib, "Ws2_32.lib")
URUTIL_BEGIN_NAMESPACE
LocalSyncOPCCLient::LocalSyncOPCCLient()
{
p_group_ = nullptr;
refresh_rate_ = 0;
p_host_ = nullptr;
p_opc_server_ = nullptr;
is_env_ready = false;
}
LocalSyncOPCCLient::~LocalSyncOPCCLient()
{
DisConnect();
Stop();
}
bool LocalSyncOPCCLient::Init()
{
COPCClient::init();
return true;
}
bool LocalSyncOPCCLient::Stop()
{
COPCClient::stop();
return true;
}
bool LocalSyncOPCCLient::Connect(const std::string& serverName,const std::string& groupName,const std::list<std::string>& itemNames)
{
// check if opc service runing
if (!DetectService((char*)serverName.data()))
{
// can do it when run at GuiYang! [10/24/2017 WQ]
//return false;
}
is_env_ready = true;
// create local host
p_host_ = COPCClient::makeHost("");
return MakeGroupAndAddItems(serverName,groupName,itemNames);
}
bool LocalSyncOPCCLient::Connect(const std::string& remoteHostName,const std::string& serverName,const std::string& groupName,const std::list<std::string>& itemNames)
{
// check if opc service runing
if (!DetectService((char*)remoteHostName.data(),(char*)serverName.data()))
{
// can do it when run at GuiYang! [10/24/2017 WQ]
//return false;
}
is_env_ready = true;
// create remote host
//WSADATA wsData;
//::WSAStartup(MAKEWORD(2, 2), &wsData);
//struct hostent *hp;
//hp = gethostbyname(remoteHostName.data());
p_host_ = COPCClient::makeHost(remoteHostName);
return MakeGroupAndAddItems(serverName,groupName,itemNames);
}
bool LocalSyncOPCCLient::IsConnected()
{
if (!is_env_ready)
{
return false;
}
// check is opc server runing
if (IsOPCRuning())
{
if (IsOPCConnectedPLC())
{
return true;
}
}
return false;
}
bool LocalSyncOPCCLient::DisConnect()
{
if (!is_env_ready)
{
return true;
}
CleanOPCMember();
return true;
}
bool LocalSyncOPCCLient::IsOPCRuning()
{
if (p_opc_server_ == nullptr)
{
return false;
}
ServerStatus status;
p_opc_server_->getStatus(status);
if (status.dwServerState != OPC_STATUS_RUNNING)
{
return false;
}
return true;
}
bool LocalSyncOPCCLient::IsOPCConnectedPLC()
{
return true;
}
//make group and add items
bool LocalSyncOPCCLient::MakeGroupAndAddItems(const std::string& ServerName,const std::string& GroupName,const std::list<std::string>& ItemNames)
{
// connect to server and get item names
std::vector<std::string> serverList;
p_host_->getListOfDAServers(IID_CATID_OPCDAServer20, serverList);
if (serverList.size() == 0)
// || std::find(localServerList.begin(),localServerList.end(),serverName) == localServerList.end())
{
return false;
}
p_opc_server_ = p_host_->connectDAServer(ServerName);
p_opc_server_->getItemNames(item_name_vector_);
// make group
p_group_ = p_opc_server_->makeGroup(GroupName, true, 1000, refresh_rate_, 0.0);
// add items
std::string itemName;
for (std::list<std::string>::const_iterator it = ItemNames.begin();it != ItemNames.end();it++)
{
itemName = *it;
if (ItemNameFilter(itemName))
name_item_map_[itemName] = p_group_->addItem(itemName, true);
}
if (!IsConnected())
{
CleanOPCMember();
return false;
}
VariantInit(&read_tmp_variant_);
return true;
}
// check service status
bool LocalSyncOPCCLient::DetectService(char* ServiceName)
{
// open manager
SC_HANDLE hSC = ::OpenSCManager(NULL, NULL, GENERIC_EXECUTE);
if (hSC == NULL)
{
return false;
}
// open service
WCHAR wszServiceName[256];
memset(wszServiceName,0,sizeof(wszServiceName));
MultiByteToWideChar(CP_ACP,0,ServiceName,strlen(ServiceName)+1,wszServiceName,
sizeof(wszServiceName)/sizeof(wszServiceName[0]));
SC_HANDLE hSvc = ::OpenService(hSC, wszServiceName,
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if (hSvc == NULL)
{
return false;
}
// read status
SERVICE_STATUS status;
if (::QueryServiceStatus(hSvc, &status) != FALSE)
{
return true;
}
return false;
}
// check remote service status
bool LocalSyncOPCCLient::DetectService(char* RemoteHostName,char* ServiceName)
{
// convert char* to lpcwstr
WCHAR wszRemoteHost[256];
memset(wszRemoteHost,0,sizeof(wszRemoteHost));
MultiByteToWideChar(CP_ACP,0,RemoteHostName,strlen(RemoteHostName)+1,wszRemoteHost,
sizeof(wszRemoteHost)/sizeof(wszRemoteHost[0]));
// open manager
SC_HANDLE hSC = ::OpenSCManager(wszRemoteHost, NULL, GENERIC_EXECUTE);
if (hSC == NULL)
{
return false;
}
// open service
WCHAR wszServiceName[256];
memset(wszServiceName,0,sizeof(wszServiceName));
MultiByteToWideChar(CP_ACP,0,ServiceName,strlen(ServiceName)+1,wszServiceName,
sizeof(wszServiceName)/sizeof(wszServiceName[0]));
SC_HANDLE hSvc = ::OpenService(hSC, wszServiceName,
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if (hSvc == NULL)
{
return false;
}
// read status
SERVICE_STATUS status;
if (::QueryServiceStatus(hSvc, &status) != FALSE)
{
return true;
}
return false;
}
bool LocalSyncOPCCLient::ItemNameFilter(std::string item_name)
{
std::vector<std::string>::iterator iter = find(item_name_vector_.begin(),item_name_vector_.end(),item_name);
if (iter == item_name_vector_.end())
return false;
return true;
}
bool LocalSyncOPCCLient::SyncWriteItem(std::string item_name, VARIANT* var)
{
name_item_map_[item_name]->writeSync(*var);
return true;
}
bool LocalSyncOPCCLient::SyncReadItem(std::string item_name, VARIANT* var)
{
static OPCItemData data;
if (name_item_map_.find(item_name) == name_item_map_.end())
return false;
name_item_map_[item_name]->readSync(data, OPC_DS_DEVICE);
VariantCopy(var, &data.vDataValue);
return true;
}
bool LocalSyncOPCCLient::SyncReadItems(const std::list<std::string>& item_names, std::list<VARIANT>& varList)
{
std::list<OPCItemData> dataList;
std::vector<COPCItem *> items;
COPCItem_DataMap opcData;
for (std::list<std::string>::const_iterator it = item_names.begin();it != item_names.end();it++)
{
if (name_item_map_.find(*it) == name_item_map_.end())
items.push_back(0);
else
items.push_back(name_item_map_[*it]);
}
p_group_->readSync(items,opcData,OPC_DS_DEVICE);
COPCItem_DataMap::CPair* pos;
OPCItemData* readData;
for (int num = 0;num < items.size();num++)
{
pos = opcData.Lookup(items[num]);
if (pos){
readData = opcData.GetValueAt(pos);
if (readData && !FAILED(readData->error)){
dataList.push_back(*readData);
}
else
{
qDebug() << QString("read data of item:%1 failed!").arg(QString::fromLocal8Bit(items[num]->getName().c_str()));
dataList.push_back(OPCItemData());
}
}
else
dataList.push_back(OPCItemData());
}
VARIANT var;
for (std::list<OPCItemData>::const_iterator it = dataList.begin();it != dataList.end();it++)
{
VariantCopy(&var, &(*it).vDataValue);
varList.push_back(var);
}
return true;
}
bool LocalSyncOPCCLient::ReadBool(std::string item_name)
{
SyncReadItem(item_name, &read_tmp_variant_);
return read_tmp_variant_.boolVal;
}
bool LocalSyncOPCCLient::WriteBool(std::string item_name, bool item_value)
{
static VARIANT var;
static VARTYPE a = (var.vt = VT_BOOL);
var.boolVal = item_value;
SyncWriteItem(item_name, &var);
return true;
}
float LocalSyncOPCCLient::ReadFloat(std::string item_name)
{
SyncReadItem(item_name, &read_tmp_variant_);
return read_tmp_variant_.fltVal;
}
bool LocalSyncOPCCLient::WirteFloat(std::string item_name, float item_value)
{
static VARIANT var;
static VARTYPE a = (var.vt = VT_R4);
var.fltVal = item_value;
SyncWriteItem(item_name, &var);
return true;
}
uint16_t LocalSyncOPCCLient::ReadUint16(std::string item_name)
{
SyncReadItem(item_name, &read_tmp_variant_);
return read_tmp_variant_.uiVal;
}
bool LocalSyncOPCCLient::WriteUint16(std::string item_name, uint16_t item_value)
{
static VARIANT var;
static VARTYPE a = (var.vt = VT_UI2);
var.uiVal = item_value;
SyncWriteItem(item_name, &var);
return true;
}
bool LocalSyncOPCCLient::ReadUint16Array(std::string item_name, uint16_t* item_value_array, int array_size)
{
VARIANT array_variant;
VariantInit(&array_variant);
SyncReadItem(item_name, &array_variant);
uint16_t* buf;
SafeArrayAccessData(array_variant.parray, (void **)&buf);
for (int i = 0; i < array_size; ++i)
{
item_value_array[i] = buf[i];
}
SafeArrayUnaccessData(array_variant.parray);
VariantClear(&array_variant);
return true;
}
bool LocalSyncOPCCLient::WriteUint16Array(std::string item_name, uint16_t* item_value_array, int array_size)
{
// create variant and safe array
VARIANT array_variant;
VariantInit(&array_variant);
VARTYPE a = (array_variant.vt = VT_ARRAY | VT_UI2);
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = array_size;
rgsabound[0].lLbound = 0;
array_variant.parray = SafeArrayCreate(VT_UI2, 1, rgsabound);
// copy data
uint16_t* buf;
SafeArrayAccessData(array_variant.parray, (void **)&buf);
for (int i = 0; i < array_size; ++i)
{
buf[i] = item_value_array[i];
}
SafeArrayUnaccessData(array_variant.parray);
//write variant
SyncWriteItem(item_name, &array_variant);
VariantClear(&array_variant);
return true;
}
bool LocalSyncOPCCLient::CleanOPCMember()
{
if (IsOPCRuning()) // delete heap if connected
{
for(auto iter=name_item_map_.begin();iter!=name_item_map_.end();++iter)
{
delete iter->second;
}
name_item_map_.clear();
if (p_group_)
{
delete p_group_;
p_group_ = nullptr;
}
if (p_host_)
{
delete p_host_;
p_host_ = nullptr;
}
if (p_opc_server_)
{
delete p_opc_server_;
p_opc_server_ = nullptr;
}
}
refresh_rate_ = 0;
is_env_ready = false;
return true;
}
URUTIL_END_NAMESPACE | [
"noreply@github.com"
] | wenwushq.noreply@github.com |
5fcd458d6060395c6927062b51717574b7593e9d | 694951018fc304d6dd66e0b8b7c2d133c9de071c | /lib/bit_error_rate.cpp | b575607c53f7db70aa2f13c738ab31f92d89bb23 | [] | no_license | romilpatel/LinkPlanner | 8e9e3369ae32f7d76aede341fd1d659bf1a19f91 | 6eae98a30d7386a9148a26179d259b5effd5fac1 | refs/heads/master | 2021-03-16T07:52:11.651085 | 2017-07-14T08:38:43 | 2017-07-14T08:38:43 | 95,436,638 | 0 | 0 | null | 2017-07-19T13:49:50 | 2017-06-26T10:44:05 | Matlab | UTF-8 | C++ | false | false | 3,429 | cpp | #include <algorithm>
#include <complex>
#include "netxpto.h"
#include "bit_error_rate.h"
void BitErrorRate::initialize(void){
firstTime = false;
outputSignals[0]->setSymbolPeriod(inputSignals[0]->getSymbolPeriod());
outputSignals[0]->setSamplingPeriod(inputSignals[0]->getSamplingPeriod());
outputSignals[0]->setFirstValueToBeSaved(inputSignals[0]->getFirstValueToBeSaved());
}
bool BitErrorRate::runBlock(void){
/* Computing z */ // This code converges in below 10 steps, exactness chosen in order to achieve this rapid convergence
if (firstPass)
{
firstPass = 0;
double x1 = -2;
double x2 = 2;
double x3 = x2 - (erf(x2 / sqrt(2)) + 1 - alpha)*(x2 - x1) / (erf(x2 / sqrt(2)) - erf(x1 / sqrt(2)));
double exacteness = 1e-15;
while (abs(erf(x3 / sqrt(2)) + 1 - alpha)>exacteness)
{
x3 = x2 - (erf(x2 / sqrt(2)) + 1 - alpha)*(x2 - x1) / (erf(x2 / sqrt(2)) - erf(x1 / sqrt(2)));
x1 = x2;
x2 = x3;
}
z = -x3;
}
int ready1 = inputSignals[0]->ready();
int ready2 = inputSignals[1]->ready();
int ready = min(ready1, ready2);
int space = outputSignals[0]->space();
int process = min(ready, space);
/* Outputting final report */
if (process == 0)
{
/* Calculating BER and bounds */
double BER = (recievedBits - coincidences) / recievedBits;
double UpperBound = BER + 1 / sqrt(recievedBits) * z * sqrt(BER*(1 - BER)) + 1 / (3 * recievedBits)*(2 * z * z * (1 / 2 - BER) + (2 - BER));
double LowerBound = BER - 1 / sqrt(recievedBits) * z * sqrt(BER*(1 - BER)) + 1 / (3 * recievedBits)*(2 * z * z * (1 / 2 - BER) - (1 + BER));
/* Outputting a .txt report*/
ofstream myfile;
myfile.open("BER.txt");
myfile << "BER= " << BER << "\n";
myfile << "Upper and lower confidence bounds for " << (1 - alpha)*100 << "% confidence level \n";
myfile << "Upper Bound= " << UpperBound << "\n";
myfile << "Lower Bound= " << LowerBound << "\n";
myfile << "Number of received bits =" << recievedBits << "\n";
myfile.close();
return false;
}
for (long int i = 0; i < process; i++) {
t_binary signalValue;
inputSignals[0]->bufferGet(&signalValue);
t_binary SignalValue;
inputSignals[1]->bufferGet(&SignalValue);
/* Outputting mid reports */
if (m > 0)
{
if (remainder(recievedBits, m) == 0 & recievedBits>0)
{
n++;
ostringstream oss;
oss << "midreport" << n << ".txt";
string filename = oss.str();
/* Calculating BER and bounds */
double BER;
BER = (recievedBits - coincidences) / recievedBits;
double UpperBound = BER + 1 / sqrt(recievedBits) * z * sqrt(BER*(1 - BER)) + 1 / (3 * recievedBits)*(2 * z * z * (1 / 2 - BER) + (2 - BER));
double LowerBound = BER - 1 / sqrt(recievedBits) * z * sqrt(BER*(1 - BER)) + 1 / (3 * recievedBits)*(2 * z * z * (1 / 2 - BER) - (1 + BER));
/* Outputting a .txt report*/
ofstream myfile;
myfile.open(filename);
myfile << "BER= " << BER << "\n";
myfile << "Upper and lower confidence bounds for" << 1-alpha << "confidence level \n";
myfile << "Upper Bound= " << UpperBound << "\n";
myfile << "Lower Bound= " << LowerBound << "\n";
myfile << "Number of received bits =" << recievedBits << "\n";
myfile.close();
}
}
recievedBits++;
if (signalValue == SignalValue)
{
coincidences++;
outputSignals[0]->bufferPut((t_binary) 1);
}
else
{
outputSignals[0]->bufferPut((t_binary) 0);
}
}
return true;
} | [
"danielffpereira@gmail.com"
] | danielffpereira@gmail.com |
881c7fb3437f6fce635f011bce313dec29ae60ee | 1ecc55daf99de213dec190f4a9d78070b9c217e2 | /algorithm/Leetcode/5、Median of Two Sorted Arrays.cpp | 0d3c9a8db0d53ea7cbae9c1bf78ede2d1f3dada3 | [] | no_license | RenewDo/practice | adb8a29a3c96bf2eaa5b9e6e11081b5268365830 | 2ed92e2be483747d75a4a5beb740384ea20c7587 | refs/heads/master | 2020-04-05T14:36:18.490239 | 2016-09-02T02:25:32 | 2016-09-02T02:25:32 | 58,454,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1= nums1.size(), len2 = nums2.size();
int total = len1+len2;
if(total&1)
return findk(nums1.begin(), len1, nums2.begin(), len2, total/2+1);
else return (findk(nums1.begin(), len1, nums2.begin(), len2, total/2)+
findk(nums1.begin(), len1, nums2.begin(), len2, total/2+1))/2.0;
}
private:
static int findk(vector<int>::const_iterator a, int lena, vector<int>::const_iterator b, int lenb, int k)
{
if(lena > lenb)
return findk(b,lenb, a, lena, k);
if(lena==0)
return *(b+k-1);
if(k==1)
return min(*(a), *(b));
int ka = min(k/2, lena), kb = k - ka;
if(*(a+ka-1) < *(b+kb-1))
return findk(a+ka, lena-ka, b, lenb, k-ka);
else if(*(a+ka-1) > *(b+kb-1))
return findk(a, lena, b+kb, lenb-kb, k-kb);
else return *(a+ka-1);
}
};
| [
"noreply@github.com"
] | RenewDo.noreply@github.com |
f0830f73e9bf9f117e33f9bd88d2c3bf79f78ad0 | 68a92984d8a8b911931e587950b24a9675ff01d0 | /main.cpp | bb4c70c1670af105cff11f9480cc15a34f142de7 | [] | no_license | MateuszMateo/Kalkulator- | b97002c6299dafd4ef3de1c9d137559fb617dc34 | dc26e0d204911e6305fb8f771607c459b424506d | refs/heads/master | 2021-01-10T16:16:53.940482 | 2015-10-01T09:49:14 | 2015-10-01T09:49:14 | 43,488,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | cpp | #include <iostream>
#include<cstring>
using namespace std;
int main()
{
int a, b, wynik;
char dzialanie;
cout << "Aby, wybrac dodawanie wpisz +" <<endl;
cout << "Aby wybrac odejmowanie wpisz -" <<endl;
cout << "Aby wybrac mnozenie wpisz *" <<endl;
cout << "Aby wybrac dzielenie calkowitoliczbowe wpisz /" <<endl;
cin >> dzialanie;
if (dzialanie == '+'){
cout << "wybrales dodawanie" << endl;
cout << "wpisz liczby ktore chcesz dodac do siebie aby otrzymac wynik" << endl;
cin >> a >> b;
wynik = b + a;
cout << wynik << endl;
}
else if (dzialanie == '-'){
cout << "wybrales odejmowanie"<<endl;
cout << "wpisz liczby ktore chcesz odjac od siebie aby otrzymac wynik" << endl;
cin >> a >> b;
wynik = b - a;
cout << wynik << endl;
}
else if (dzialanie == '*'){
cout << "wybrales mnozenie"<<endl;
cout << "wpisz liczby ktore chcesz pomnozyc aby otrzymac wynik" << endl;
cin >> a >> b;
wynik = b * a;
cout << wynik << endl;
}
else if (dzialanie == '/'){
cout << "wybrales dzielenie calkowitoliczbowe"<<endl;
cout << "wpisz liczby ktore chcesz podzielic aby otrzymac wynik" << endl;
cin >> a >> b;
wynik = b / a;
cout << wynik << endl;
}
}
| [
"k.mateusz120@gmail.com"
] | k.mateusz120@gmail.com |
31a3abb2801ca4b17b72fce2305a1f674e6eab5b | fc7d66d45668fa2f2af9e9f229ddc2325b8a8fbf | /old/asm2020S/session14/stopopt.cc | 0ceca33ee02ff65a9533739478e8ac6f6c268f4f | [] | no_license | StevensDeptECE/CPE390 | 3b3e3f39c47bdaa768bc01dc875abeb6d44be303 | da6e657ecb94dde9f7d933c36bf17c1f2165540e | refs/heads/master | 2023-05-03T00:22:37.816177 | 2023-05-02T17:41:42 | 2023-05-02T17:41:42 | 144,867,364 | 61 | 53 | null | 2023-05-09T01:02:52 | 2018-08-15T14:59:41 | Assembly | UTF-8 | C++ | false | false | 183 | cc | #include <iostream>
using namespace std;
void f(int n) {
for (int i = 0; i < n; i++)
cout << i;
}
void g(int n) {
int i = 0;
do {
// this happens once!
} while (i < n);
}
| [
"Dov.Kruger@gmail.com"
] | Dov.Kruger@gmail.com |
9cc857817cef0478a279b51fe7f617dc022bed5b | 510b229d9fc12935bfd5291901035d8e02a5af46 | /lib/ctrcommon/include/ctrcommon/socket.hpp | e8c35a0c10109b8a0177daffa7a9f463529fdc5a | [
"MIT"
] | permissive | astronautlevel2/BootNTR | 179c8eb8ec88176551d5b6a5c2ca216e6f8148d7 | b00762b44aa3e913e4483364fecf67ef21b74256 | refs/heads/master | 2020-04-05T14:24:53.599375 | 2017-01-05T01:00:03 | 2017-01-05T01:00:03 | 61,382,418 | 128 | 13 | null | 2016-10-25T20:52:15 | 2016-06-17T15:08:03 | C++ | UTF-8 | C++ | false | false | 394 | hpp | #ifndef __CTRCOMMON_SOCKET_HPP__
#define __CTRCOMMON_SOCKET_HPP__
#include "ctrcommon/types.hpp"
#include <stdio.h>
#include <string>
u64 htonll(u64 value);
u64 ntohll(u64 value);
u32 socketGetHostIP();
int socketListen(u16 port);
FILE* socketAccept(int listeningSocket, std::string* acceptedIp = NULL);
FILE* socketConnect(const std::string ipAddress, u16 port, int timeout = 10);
#endif
| [
"44670@44670.org"
] | 44670@44670.org |
023914c6eef20c04300f9b4909415e879cc404da | 4e87df024f179be11bc6ad91d3fda019183c9e3b | /server_trade_dispatcher/IOCPServer/recvbuffer.h | 1472202bb2a9be5e20a8d7e852df504430ee3493 | [] | no_license | lanzheng1113/game_robot | 54f03c8cb0b29ca7e38952187a45fdb00be1b508 | c8efb0770e19a9baa9fef5de3992360993847917 | refs/heads/master | 2020-07-12T14:26:25.288847 | 2019-08-28T07:23:08 | 2019-08-28T07:23:08 | 204,839,436 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,150 | h | #ifndef _RECVBUFFER_H
#define _RECVBUFFER_H
/**
* @file recvbuffer.h 定义接收缓冲区类RecvBuffer
* @author:Vincent
* @brief RecvBuffer类是IO接收缓冲区的封装
*
* 在本版本中,接收缓冲区由一个环形缓冲区CircuitQueue<BYTE>封装实现。
*/
#include <windows.h>
#include "../common/CircuitQueue.h"
#include "../common/NetBase.h"
/**
* @brief RecvBuffer类是IO接收缓冲区的封装
* 在本版本中,接收缓冲区由一个环形缓冲区CircuitQueue<BYTE>封装实现。
* 它提供了与iocp完成端口模式想对应的接口,例如Completion例程是当一个recv请求被响应时被调用的例程。
*
*/
class RecvBuffer
{
public:
/**
* default construct.
*/
RecvBuffer() { m_pQueue = NULL; }
/**
* default des.
*/
virtual ~RecvBuffer() { if( m_pQueue ) delete m_pQueue; }
/**
* 创建一个RecvBuffer缓冲区。
* @param nBufferSize:缓冲区长度
* @param dwExtraBufferSize:环形缓冲区队列的额外长度。
* @see CircuitQueue
*/
inline VOID Create( int nBufferSize, DWORD dwExtraBufferSize ) {
if( m_pQueue ) delete m_pQueue;
m_pQueue = new CircuitQueue<BYTE>;
m_pQueue->Create( nBufferSize, dwExtraBufferSize ); }
/**
* 接收缓冲区完成写入过程
* 缓冲区压入参数指定长度的字节数
* @param nBytesRecvd 写入长度
* @see WSARecv
*/
inline VOID Completion( int nBytesRecvd ) { m_pQueue->Enqueue( NULL, nBytesRecvd ); }
/**
* 清空缓冲区,长度设置为0.在缓冲区初始化时,或者回收利用时需要清空缓冲区。
*/
inline VOID Clear() { m_pQueue->Clear(); }
/**
* 获得接收缓冲区的开始指针和长度。
* @param ppRecvPtr 指向缓冲区开始地址指针的指针
* @param nLength 长度引用。<B>FIXME:改为指针更为合适,因为nLength没有任何输入意义。</B>
* @remark 当投递一个recv请求到iocp端口时,需要提供指向接收缓冲区的空闲区块指针和长度作为参数。@see WSARecv
*/
inline VOID GetRecvParam( BYTE **ppRecvPtr, int &nLength ) {
*ppRecvPtr = m_pQueue->GetWritePtr();
nLength = m_pQueue->GetWritableLen(); }
/**
* 获得收到的第一个数据包,如数据长度未满一字节则返回NULL.
* @return 指向第一个数据包的开始位置。
* @remark 接收完毕后,处理接收缓冲区收到的数据包。
*/
inline BYTE* GetFirstPacketPtr() {
PACKET_HEADER header;
//
if( !m_pQueue->Peek( (BYTE*)&header, sizeof(PACKET_HEADER) ) ) return NULL;
//
if( m_pQueue->GetLength() < (int)( sizeof(PACKET_HEADER) + header.size ) ) return NULL;
//
if( m_pQueue->GetBackDataCount() < (int)( header.size + sizeof(header) ) ) {
m_pQueue->CopyHeadDataToExtraBuffer( header.size + sizeof(header) - m_pQueue->GetBackDataCount() ); }
return m_pQueue->GetReadPtr(); }
/**
* 从缓冲区中删除第一个数据包
* @param wSize:数据包的长度。
* @remark:当处理完一个数据包时调用此函数令环形缓冲区指针指向下一个数据包。
*/
inline VOID RemoveFirstPacket( WORD wSize ) { m_pQueue->Dequeue( NULL, wSize ); }
private:
CircuitQueue<BYTE> *m_pQueue;
};
#endif | [
"lanzheng_1123@163.com"
] | lanzheng_1123@163.com |
9f4211093d1fe73d70c0552c7b8cae023dbe5478 | 4e376d3b6efd7596e094b85eb9acebbdeabab246 | /src/rpcblockchain.cpp | 777329ecf8437da63ec3502badbd851b4cbbaffe | [
"MIT"
] | permissive | N1rvash/CHAPCOIN | 53f7b893cafd14ef8f339b897c70bdd092137c7b | cde904a6f72792e127479a12c946528e5d4709c6 | refs/heads/master | 2021-08-19T18:46:56.698106 | 2017-11-27T05:19:05 | 2017-11-27T05:19:05 | 112,150,310 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,480 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = pindexBest;
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
CMerkleTx txGen(block.vtx[0]);
txGen.SetMerkleBranch(&block);
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
Array txs;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
txs.push_back(tx.GetHash().GetHex());
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
result.push_back(Pair("bits", HexBits(block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
return result;
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best (tip) block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
return GetDifficulty();
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee <amount CHA/KB>\n"
"<amount> is a real and is rounded to the nearest 0.00000001 CHA per KB");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nTransactionFee = nAmount;
return true;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [verbose=true]\n"
"If verbose is false, returns a string that is serialized, hex-encoded data for block <hash>.\n"
"If verbose is true, returns an Object with information about block <hash>."
);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex);
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
Value gettxoutsetinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"Returns statistics about the unspent transaction output set.");
Object ret;
CCoinsStats stats;
if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (boost::int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize));
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
Value gettxout(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout <txid> <n> [includemempool=true]\n"
"Returns details about an unspent transaction output.");
Object ret;
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
CCoins coins;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(*pcoinsTip, mempool);
if (!view.GetCoins(hash, coins))
return Value::null;
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
} else {
if (!pcoinsTip->GetCoins(hash, coins))
return Value::null;
}
if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
return Value::null;
ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
Object o;
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("version", coins.nVersion));
ret.push_back(Pair("coinbase", coins.fCoinBase));
return ret;
}
Value verifychain(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain [check level] [num blocks]\n"
"Verifies blockchain database.");
int nCheckLevel = GetArg("-checklevel", 3);
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
nCheckDepth = params[1].get_int();
return VerifyDB(nCheckLevel, nCheckDepth);
}
| [
"camilo@ninjas.cl"
] | camilo@ninjas.cl |
2f105dadba37f88151387fc5b323fa8c834af7b0 | 7257f9fcd1512d86c485ae2f265188b960464d32 | /src/searcher-inl.h | cdb3d14ecc36f38f300f75d67ea31a05b0e2eb16 | [
"MIT"
] | permissive | KellyJDavis/Andrews-Curtis | 46646c5921660f0bb1f3c5f56151a30c4eb2e9ee | 1838a14ae03ca2c920f68d1afcf2d8ffc7c550dc | refs/heads/master | 2020-04-22T12:07:14.990367 | 2014-09-27T21:52:49 | 2014-09-27T21:52:49 | 23,014,702 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | //
// searcher-inl.h
// Andrews-Curtis Conjecture
//
// Created by Kelly Davis on 8/19/11.
//
//
#ifndef Andrews_Curtis_Conjecture_searcher_inl_h
#define Andrews_Curtis_Conjecture_searcher_inl_h
#include <iostream>
#include <boost/mpi/communicator.hpp>
namespace andrews_curtis
{
inline bool Searcher::is_trivial() const
{
return m_is_trivial;
}
inline void Searcher::print_counterexample() const
{
// Define the world communicator in which we reside
boost::mpi::communicator communicator;
// If we are on process 0, print the counter example
if(!communicator.rank())
std::cout << m_counterexample;
}
}
#endif
| [
"kdavis@alum.mit.edu"
] | kdavis@alum.mit.edu |
7fa0f2ad505322c470e461987095f70f0d88ccd5 | d60cfe7e01b3043674049224e96d96bbf8dcfd9b | /test/json.cpp | e8221c64c6629d4cf17bdedf98771e7c6cbcfd16 | [] | no_license | shaiganhuiyi/VideoOnDemandSystem | 438890f9bff183cbd9dc316ffeb63fabd2ed526c | a0b9e459a1d952776b10a06fcda8eef72940745f | refs/heads/master | 2023-08-15T05:08:00.399541 | 2021-09-16T14:33:11 | 2021-09-16T14:33:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,010 | cpp | #include<iostream>
#include<string>
#include<jsoncpp/json/json.h>
int main(int argc,char *argv[] )
{
//1.多个数据对象组织成为json格式的字符串--序列化
Json::Value root;
root["姓名"]="张三";
root["年龄"]=18;
root["成绩"].append(33);
root["成绩"].append(44);
root["成绩"].append(55);
Json::StyledWriter writer;
std::cout<< writer.write(root)<< std::endl;
//2. json格式的字符串解析成为多个数据对象-反序列化
std::string buf = R"( {"名称": "后羿", "类型": "射手", "三围": [285, 86, 73]})";
Json::Value val;
Json::Reader reader;
bool ret = reader.parse(buf,val);
if(ret == false){
printf("parse error\n");
return -1;
}
std::cout<<"人物: "<<val["名称"].asString()<<std::endl;
std::cout<<"角色: "<<val["类型"].asString()<<std::endl;
int num = val["三围"].size();
for (int i=0;i<num;i++){
std::cout<<"属性: "<<val["三围"][i].asInt()<<std::endl;
}
return 0;
}
| [
"861585843@qq.com"
] | 861585843@qq.com |
7298c12227ec4a78714f664c94087541fe0872b0 | 4dca3b21f8d6c60601f0b71a5484dc0625299b78 | /Arduino/SharpSensorCm.ino | 52df7a8beb7171fc8d2154080a7cfd03ec5bab15 | [] | no_license | ritwikkanodia/Multi-DisciplinaryProject | 008fcd174d4182f09f98bc2e219b906bf1119660 | e1373b12fb3c46737d07a8e645e09b1064849daa | refs/heads/master | 2023-04-08T23:05:47.155767 | 2021-04-06T09:22:58 | 2021-04-06T09:22:58 | 332,398,835 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 963 | ino | #include <SharpIR.h>
#define ir A0
#define model 20150
// ir: the pin where your sensor is attached
// model: an int that determines your sensor: 1080 for GP2Y0A21Y
// 20150 for GP2Y0A02Y
// (working distance range according to the datasheets)
SharpIR SharpIR(ir, model);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
delay(2000);
unsigned long pepe1=millis(); // takes the time before the loop on the library begins
int dis=SharpIR.distance(); // this returns the distance to the object you're measuring
Serial.print("Mean distance: "); // returns it to the serial monitor
Serial.println(dis);
unsigned long pepe2=millis()-pepe1; // the following gives you the time taken to get the measurement
Serial.print("Time taken (ms): ");
Serial.println(pepe2);
}
| [
"noreply@github.com"
] | ritwikkanodia.noreply@github.com |
40a681fb8a60a0cbc05675e377bbf2d78d5c8852 | 9cb6b8d7d4625450db5f3fed5040e87bcc950832 | /diversos/spoj_jaspion.cpp | 6a4910e253cf6ccad530513fba17a71049d0eaf4 | [] | no_license | kangli-bionic/Treino-Maratona | 7ca7731142514c28880c0e463c6a8ba5d97aebb6 | c02fefbe740f8792b825faa722718cdd64c456a2 | refs/heads/master | 2021-05-30T03:28:37.094987 | 2014-09-15T18:17:01 | 2014-09-15T18:17:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 745 | cpp | #include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <sstream>
using namespace std;
char buf[500];
char buf2[500];
map<string, string> dic;
int main()
{
gets(buf);
int casos;
sscanf(buf, " %d", &casos);
while(casos--){
int m, n;
gets(buf);
sscanf(buf, " %d %d", &m, &n);
dic.clear();
while(m--){
gets(buf);
gets(buf2);
dic[buf] = buf2;
}
while(n--){
gets(buf);
istringstream iss(buf);
string s;
bool pri = true;
while(iss >> s){
if(!pri) printf(" ");
pri = false;
if(dic.find(s) == dic.end())
printf("%s",s.c_str());
else
printf("%s",dic[s].c_str());
}
puts("");
}
puts("");
}
return 0;
}
| [
"gabrielrcp@gmail.com"
] | gabrielrcp@gmail.com |
63a6f1852d34a8609b72e666268c48a1bb78669a | e52ba923f4b908255bfe8943e429e539514b3724 | /roscpp_core/rostime/include/ros/time.h | e1b65e94433e54362d9b3777979159c6256e3bed | [] | no_license | KawaiLaboratory/CartROS | 3686a5f2d0076ace7728031ffea45ce99b060e57 | aa08352a354e9d59e5c69a852634375006077ab8 | refs/heads/master | 2023-02-21T15:04:14.188618 | 2021-01-21T02:19:06 | 2021-01-21T02:19:06 | 156,093,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,919 | h | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef ROS_TIME_H_INCLUDED
#define ROS_TIME_H_INCLUDED
/*********************************************************************
** Pragmas
*********************************************************************/
#ifdef _MSC_VER
// Rostime has some magic interface that doesn't directly include
// its implementation, this just disables those warnings.
#pragma warning(disable: 4244)
#pragma warning(disable: 4661)
#endif
/*********************************************************************
** Headers
*********************************************************************/
#include <ros/platform.h>
#include <iostream>
#include <cmath>
#include <ros/exception.h>
#include "duration.h"
#include <boost/math/special_functions/round.hpp>
#include "rostime_decl.h"
/*********************************************************************
** Cross Platform Headers
*********************************************************************/
#ifdef WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif
namespace boost {
namespace posix_time {
class ptime;
class time_duration;
}
}
namespace ros
{
/*********************************************************************
** Exceptions
*********************************************************************/
/**
* @brief Thrown if the ros subsystem hasn't been initialised before use.
*/
class ROSTIME_DECL TimeNotInitializedException : public Exception
{
public:
TimeNotInitializedException()
: Exception("Cannot use ros::Time::now() before the first NodeHandle has been created or ros::start() has been called. "
"If this is a standalone app or test that just uses ros::Time and does not communicate over ROS, you may also call ros::Time::init()")
{}
};
/**
* @brief Thrown if windoze high perf. timestamping is unavailable.
*
* @sa getWallTime
*/
class ROSTIME_DECL NoHighPerformanceTimersException : public Exception
{
public:
NoHighPerformanceTimersException()
: Exception("This windows platform does not "
"support the high-performance timing api.")
{}
};
/*********************************************************************
** Functions
*********************************************************************/
ROSTIME_DECL void normalizeSecNSec(uint64_t& sec, uint64_t& nsec);
ROSTIME_DECL void normalizeSecNSec(uint32_t& sec, uint32_t& nsec);
ROSTIME_DECL void normalizeSecNSecUnsigned(int64_t& sec, int64_t& nsec);
ROSTIME_DECL void ros_walltime(uint32_t& sec, uint32_t& nsec);
ROSTIME_DECL void ros_steadytime(uint32_t& sec, uint32_t& nsec);
/*********************************************************************
** Time Classes
*********************************************************************/
/**
* \brief Base class for Time implementations. Provides storage, common functions and operator overloads.
* This should not need to be used directly.
*/
template<class T, class D>
class TimeBase
{
public:
uint32_t sec, nsec;
TimeBase() : sec(0), nsec(0) { }
TimeBase(uint32_t _sec, uint32_t _nsec) : sec(_sec), nsec(_nsec)
{
normalizeSecNSec(sec, nsec);
}
explicit TimeBase(double t) { fromSec(t); }
~TimeBase() {}
D operator-(const T &rhs) const;
T operator+(const D &rhs) const;
T operator-(const D &rhs) const;
T& operator+=(const D &rhs);
T& operator-=(const D &rhs);
bool operator==(const T &rhs) const;
inline bool operator!=(const T &rhs) const { return !(*static_cast<const T*>(this) == rhs); }
bool operator>(const T &rhs) const;
bool operator<(const T &rhs) const;
bool operator>=(const T &rhs) const;
bool operator<=(const T &rhs) const;
double toSec() const { return (double)sec + 1e-9*(double)nsec; };
T& fromSec(double t) {
int64_t sec64 = (int64_t)floor(t);
if (sec64 < 0 || sec64 > UINT_MAX)
throw std::runtime_error("Time is out of dual 32-bit range");
sec = (uint32_t)sec64;
nsec = (uint32_t)boost::math::round((t-sec) * 1e9);
// avoid rounding errors
sec += (nsec / 1000000000ul);
nsec %= 1000000000ul;
return *static_cast<T*>(this);
}
uint64_t toNSec() const {return (uint64_t)sec*1000000000ull + (uint64_t)nsec; }
T& fromNSec(uint64_t t);
inline bool isZero() const { return sec == 0 && nsec == 0; }
inline bool is_zero() const { return isZero(); }
boost::posix_time::ptime toBoost() const;
};
/**
* \brief Time representation. May either represent wall clock time or ROS clock time.
*
* ros::TimeBase provides most of its functionality.
*/
class ROSTIME_DECL Time : public TimeBase<Time, Duration>
{
public:
Time()
: TimeBase<Time, Duration>()
{}
Time(uint32_t _sec, uint32_t _nsec)
: TimeBase<Time, Duration>(_sec, _nsec)
{}
explicit Time(double t) { fromSec(t); }
/**
* \brief Retrieve the current time. If ROS clock time is in use, this returns the time according to the
* ROS clock. Otherwise returns the current wall clock time.
*/
static Time now();
/**
* \brief Sleep until a specific time has been reached.
* @return True if the desired sleep time was met, false otherwise.
*/
static bool sleepUntil(const Time& end);
static void init();
static void shutdown();
static void setNow(const Time& new_now);
static bool useSystemTime();
static bool isSimTime();
static bool isSystemTime();
/**
* \brief Returns whether or not the current time is valid. Time is valid if it is non-zero.
*/
static bool isValid();
/**
* \brief Wait for time to become valid
*/
static bool waitForValid();
/**
* \brief Wait for time to become valid, with timeout
*/
static bool waitForValid(const ros::WallDuration& timeout);
static Time fromBoost(const boost::posix_time::ptime& t);
static Time fromBoost(const boost::posix_time::time_duration& d);
};
extern ROSTIME_DECL const Time TIME_MAX;
extern ROSTIME_DECL const Time TIME_MIN;
/**
* \brief Time representation. Always wall-clock time.
*
* ros::TimeBase provides most of its functionality.
*/
class ROSTIME_DECL WallTime : public TimeBase<WallTime, WallDuration>
{
public:
WallTime()
: TimeBase<WallTime, WallDuration>()
{}
WallTime(uint32_t _sec, uint32_t _nsec)
: TimeBase<WallTime, WallDuration>(_sec, _nsec)
{}
explicit WallTime(double t) { fromSec(t); }
/**
* \brief Returns the current wall clock time.
*/
static WallTime now();
/**
* \brief Sleep until a specific time has been reached.
* @return True if the desired sleep time was met, false otherwise.
*/
static bool sleepUntil(const WallTime& end);
static bool isSystemTime() { return true; }
};
/**
* \brief Time representation. Always steady-clock time.
*
* Not affected by ROS time.
*
* ros::TimeBase provides most of its functionality.
*/
class ROSTIME_DECL SteadyTime : public TimeBase<SteadyTime, WallDuration>
{
public:
SteadyTime()
: TimeBase<SteadyTime, WallDuration>()
{}
SteadyTime(uint32_t _sec, uint32_t _nsec)
: TimeBase<SteadyTime, WallDuration>(_sec, _nsec)
{}
explicit SteadyTime(double t) { fromSec(t); }
/**
* \brief Returns the current steady (monotonic) clock time.
*/
static SteadyTime now();
/**
* \brief Sleep until a specific time has been reached.
* @return True if the desired sleep time was met, false otherwise.
*/
static bool sleepUntil(const SteadyTime& end);
static bool isSystemTime() { return true; }
};
ROSTIME_DECL std::ostream &operator <<(std::ostream &os, const Time &rhs);
ROSTIME_DECL std::ostream &operator <<(std::ostream &os, const WallTime &rhs);
ROSTIME_DECL std::ostream &operator <<(std::ostream &os, const SteadyTime &rhs);
}
#endif // ROS_TIME_H
| [
"b1504000@planet.kanazawa-it.ac.jp"
] | b1504000@planet.kanazawa-it.ac.jp |
f6af59d0fc0b1be8b8f09392204e42a37bcf9e55 | a593c5f30d0d26781307ec734dd8b48b2c581448 | /ToF/DSDaq/AthenaII.h | e12d14e2cca9e764cdb1f04f4ceeffe0f94f3017 | [] | no_license | nthallen/citcims | 5cfac1b5ef7b17c4142961414a446a2fd393a21f | 5c5fe5bbb0bed96459624338c7f340e822439213 | refs/heads/master | 2023-05-24T19:05:24.008090 | 2019-07-21T19:55:37 | 2019-07-21T19:55:37 | 65,412,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 931 | h | #ifndef ATHENAII_H_INCLUDED
#define ATHENAII_H_INCLUDED
#include "dsdaqdrv.h"
/**
* Provides methods specific to the AthenaII hardware.
*/
class AthenaII : public dsdaqdrv {
public:
AthenaII(int ad_se); // This probably needs more args...
virtual ~AthenaII();
void parse_ascii(const char *ibuf);
protected:
private:
int n_ad;
int n_dio;
int n_bio;
unsigned short da_values[4];
unsigned char dio_values[3];
int init_hardware();
int ad_read(unsigned short offset, unsigned short &data);
int da_read(unsigned short offset, unsigned short &data);
int da_write(unsigned short offset, unsigned short value);
int dio_read(unsigned short offset, unsigned short &data);
int dio_write(unsigned short offset, unsigned short value);
int bit_read(unsigned short offset, unsigned short &data);
int bit_write(unsigned short offset, unsigned short value);
};
#endif
| [
"allen@huarp.harvard.edu"
] | allen@huarp.harvard.edu |
24811afa59020c64fd1bf82cdd526c5860c54e8b | f24e7daff602a5e3f2b4909721548a9f84598a56 | /codeforces/250/A/problem.cpp | b6705c53110a78b5727c7913a7809b484af2fff5 | [] | no_license | permin/Olymp | 05b594e8c09adb04c1aa065ba6dd7f2dae8f4d6e | 51ac43fcbcc14136ed718481f64e09036f10ddf8 | refs/heads/master | 2021-01-18T23:04:00.491119 | 2017-03-08T22:22:25 | 2017-03-08T22:22:25 | 23,457,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,308 | cpp | #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <ctime>
#include <sstream>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <bitset>
#include <valarray>
using namespace std;
#ifdef LOCAL_RUN
#define debug(x) cerr << #x << ": " << (x) << "\n";
#else
#define debug(x) ;
#endif
#define all(v) (v).begin(), (v).end()
#define MP make_pair
template <class F, class S> ostream& operator << (ostream& o, const pair<F,S>& p) {
return o << "(" << p.first << ", " << p.second << ")";}
template<class C>void O__(ostream& o, const C& c) {
bool f = 1; for(const auto& x: c) {if (!f) o << ", "; f = 0; o << x;}}
template <class T>
ostream& operator << (ostream& o, const vector<T>& v) {o << "[";O__(o, v);o << "]";return o;}
template <class T, class V>
ostream& operator << (ostream& o, const map<T, V>& v) {o << "{";O__(o, v);o << "}"; return o;}
template <class T>
ostream& operator << (ostream& o, const set<T>& v) {o << "{";O__(o, v);o << "}";return o;}
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<vii> viii;
const double PI = 3.1415926535897932384626433832795;
const double EPS = 1e-9;
const int INF = std::numeric_limits<int>::max();
const long long LLINF = std::numeric_limits<ll>::max();
int main() {
int n,m;
cin >> n >> m;
vector<int> en;
vector<pii> e;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
e.push_back(pii(x,i));
en.push_back(x);
}
vii al(n);
for (int i = 0; i < m; ++i) {
int a,b;
cin >> a >> b;
--a;--b;
al[a].push_back(b);
al[b].push_back(a);
}
vector<bool> alive(n, true);
sort(all(e));
reverse(all(e));
ll res = 0;
for (int i = 0; i < n; ++i) {
int j = e[i].second;
for (int k = 0; k < al[j].size(); ++k) {
int v2 = al[j][k];
if (alive[v2])
res += en[v2];
}
alive[j] = 0;
}
cout << res << "\n";
return 0;
}
| [
"rodion.permin@gmail.com"
] | rodion.permin@gmail.com |
e8968ad517749b427ffb6e97090c9fb578d3c3e6 | 920c4ef30727f0c51b5c9f00bdd9b923b541853e | /Code_Cpp/cppserver备份资料/code/common/source/include/cfg_data/worldBossData/worldBossData.h | df3476991f3eca2161f24d7eed1ba8161368da9a | [] | no_license | fishney/TDServer | 10e50cd156b9109816ddebde241614a28546842a | 19305fc7bf649a9add86146bd1bfd253efa6e9cb | refs/heads/master | 2023-03-16T22:24:45.802339 | 2017-10-19T07:02:56 | 2017-10-19T07:02:56 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,430 | h | /*----------------- worldBossData.h
*
* Copyright (C): 2016 Mokylin¡¤Mokyqi
* Author : tanghaibo
* Version : V1.0
* Date : 2017/05/09 14:47:14
*--------------------------------------------------------------
*
*------------------------------------------------------------*/
#pragma once
#include "stl/std_map.h"
#include "cfg_data/fileData/fileData.h"
#include "worldBossModel.h"
/*************************************************************/
class CWorldBossData : public CFileData
{
public:
enum
{
Version = 20170328
};
public:
typedef stl_vector<_stworldbossModel> VECTOR_WORLDBOSS_MODEL;
typedef stl_vector<_stworldbossrankprizeModel> VECTOR_RANKPRIZE_MODEL;
public:
VECTOR_WORLDBOSS_MODEL m_vcWorldBossModel;
VECTOR_RANKPRIZE_MODEL m_vcRankPrizeModel;
public:
virtual pc_str getFileName ()const { return "worldboss.dat"; }
virtual pc_str getXmlName ()const { return "cs_world_boss.xml"; }
public:
CWorldBossData();
public:
const VECTOR_WORLDBOSS_MODEL & getAllWorldBoss()
{
return m_vcWorldBossModel;
}
uint32 findWorldBossPrizeByRank(uint32 uBossActivityId, uint32 uRank);
protected:
virtual bool onLoad (TiXmlElement&xmlRoot);
protected:
virtual bool onLoad (CFileStream&clFile);
virtual bool onSave (CFileStream&clFile);
private:
};
//-------------------------------------------------------------
extern CWorldBossData g_clWorldbossData;
| [
"haibo tang"
] | haibo tang |
112872cce9698bc62d8df4722c8a5b41f0533822 | 159a16eb7e314307e0f85b808a3c928d691d09e1 | /afl_code/Point.h | 3c8e1cf6ab3d0d158f29f4c5577a18d19b4c2887 | [] | no_license | stevehu88/Map_Render | 96789876de674e02886441fa3e3f6af487cc516b | 26278d7b226693f9aea0221989c64559fc9017b2 | refs/heads/master | 2020-06-05T07:15:20.701265 | 2015-09-10T03:37:56 | 2015-09-10T03:37:56 | 42,220,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | h | /*
* Point.h
*
* Created on: Sep 4, 2015
* Author: Steve Hu
*/
#ifndef POINT_H_
#define POINT_H_
class Point {
public:
Point();
Point(double px, double py);
virtual ~Point();
double getX() const {
return x;
}
void setX(double x) {
this->x = x;
}
double getY() const {
return y;
}
void setY(double y) {
this->y = y;
}
private:
double x,y;
};
#endif /* POINT_H_ */
| [
"root@linux-q01p.dhcp.nkg.sap.corp"
] | root@linux-q01p.dhcp.nkg.sap.corp |
88535be3318d0d16092dd8469b5b1763f3fc7a70 | e929a84dec3a6e710351261a6de895308efa6d33 | /codemp/null/null_glimp.cpp | 64c1ee8d188941d48e7ba27b5d8c055cda77d569 | [] | no_license | xLAva/JediAcademyLinux | 570d85e1e24d950ab63e9297135248362d873dbd | 1d31492a576106e104f49bd9b5fe7f7792a90e89 | refs/heads/JediAcademyLinux | 2021-01-18T21:23:43.164581 | 2014-11-29T13:52:49 | 2014-11-29T13:52:49 | 9,734,512 | 125 | 18 | null | 2013-09-24T19:02:36 | 2013-04-28T18:51:54 | C++ | UTF-8 | C++ | false | false | 1,412 | cpp | #include "../game/q_shared.h"
#include "../renderer/tr_local.h"
#ifdef __linux__
typedef unsigned int GLenum;
#endif
#ifdef _WIN32
#include <windows.h>
BOOL (WINAPI * qwglSwapIntervalEXT)( int interval );
//void (APIENTRY * qglMultiTexCoord2fARB )( GLenum texture, float s, float t );
//void (APIENTRY * qglActiveTextureARB )( GLenum texture );
//void (APIENTRY * qglClientActiveTextureARB )( GLenum texture );
void (APIENTRY * qglLockArraysEXT)( int, int);
void (APIENTRY * qglUnlockArraysEXT) ( void );
void GLimp_EndFrame( void ) {
}
void GLimp_Init( void )
{
}
void GLimp_Shutdown( void ) {
}
void GLimp_EnableLogging( qboolean enable ) {
}
void GLimp_LogComment( char *comment ) {
}
qboolean QGL_Init( const char *dllname ) {
return qtrue;
}
void QGL_Shutdown( void ) {
}
#else
qboolean ( * qwglSwapIntervalEXT)( int interval );
void ( * qglMultiTexCoord2fARB )( GLenum texture, float s, float t );
void ( * qglActiveTextureARB )( GLenum texture );
void ( * qglClientActiveTextureARB )( GLenum texture );
void ( * qglLockArraysEXT)( int, int);
void ( * qglUnlockArraysEXT) ( void );
void GLimp_EndFrame( void ) {
}
void GLimp_Init( void )
{
}
void GLimp_Shutdown( void ) {
}
void GLimp_EnableLogging( qboolean enable ) {
}
void GLimp_LogComment( char *comment ) {
}
qboolean QGL_Init( const char *dllname ) {
return qtrue;
}
void QGL_Shutdown( void ) {
}
#endif // !WIN32
| [
"willi@schinmeyer.de"
] | willi@schinmeyer.de |
a447f5d1c87423241b3580954cba681f7b5dcd04 | fd6ff690a9d2f1cf1eb8b92a96cead753369c109 | /src/backend/cpu/cpu-context.h | 0b9261a19e45c40d6efb53569e1c515f90bf66db | [
"Apache-2.0"
] | permissive | Asixa/Dragonfly | 1a8e6bab0e011a034c732071ed09f76afb601894 | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | refs/heads/master | 2021-05-20T03:32:17.525880 | 2021-02-01T15:43:12 | 2021-02-01T15:43:12 | 252,166,588 | 2 | 0 | Apache-2.0 | 2020-11-06T01:58:15 | 2020-04-01T12:19:15 | C++ | UTF-8 | C++ | false | false | 1,369 | h | #ifndef CPU_CONTEXT_H
#define CPU_CONTEXT_H
#include <string>
#include "LLVM/context.h"
class CudaDriver {
public:
llvm::GlobalValue* cuda_device,*cuda_module,*cuda_context;
llvm::Constant* ptx;
llvm::Function* init,
* driver_get_version,
* device_get_count,
* device_get,
* device_get_name,
* device_get_attribute,
* context_create,
* context_set_current,
* context_get_current,
* stream_create,
* memcpy_host_to_device,
* memcpy_device_to_host,
* memcpy_host_to_device_async,
* memcpy_device_to_host_async,
* malloc,
* malloc_managed,
* memset,
* mem_free,
* mem_advise,
* mem_get_info,
* module_get_function,
* module_load_data_ex,
* launch_kernel,
* stream_synchronize,
* event_create,
* event_record,
* event_elapsed_time;
llvm::Type* CUcontext,
*CUstream ,
* CUfunction,
* CUmodule ,
* CUevent,
* CUdevicePtr,
* CUdevice,
* CUmem_advise,
* CUjit_option,
* CUdevice_attribute,
* CUresult;
};
class CPUContext :public DFContext {
void BuiltinCudaCheck();
void BuiltinAssert();
public:
CudaDriver driver;
explicit CPUContext(std::shared_ptr<AST::Program> program);
static std::shared_ptr<CPUContext> Create(std::shared_ptr<AST::Program> program);
void BuiltIn(std::shared_ptr < DFContext> ptr) override;
};
#endif
| [
"Asixa@foxmail.com"
] | Asixa@foxmail.com |
61e37aee3f78e676d9d36ea6c75819924f9b6cd7 | 55ca8d221b40f0b626b7553363d00568c9cb5bf0 | /long/marchlunch2.cpp | cb00341dff6700c2f585a0ca003eb347d3c1d85d | [] | no_license | mukul3646/CodesPreservedDuringEngineering | 224d1638a9e033e9633dd9962a2717f94d78d31d | 19f2f85750c61fc58d28bd8f58d2d8d30ff39697 | refs/heads/master | 2022-11-26T05:22:15.432580 | 2020-08-06T12:29:58 | 2020-08-06T12:29:58 | 285,565,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | #include<bits/stdc++.h>
using namespace std;
long int printDistinct(long int arr[],long int n)
{
long int count=0;
// First sort the array so that all occurrences become consecutive
sort(arr, arr + n);
// Traverse the sorted array
for (int i=0; i<n; i++)
{
// Move the index ahead while there are duplicates
while (i < n-1 && arr[i] == arr[i+1])
i++;
// print last occurrence of the current element
count++;
}
return count;
}
int main()
{
long int t;
cin>>t;
while(t--)
{
long int n,x,i;
cin>>n>>x;
long int a[n+1];
a[0]=x;
getchar();
string s;
getline(cin,s);
long int num=x;
for(i=1;i<=n;i++)
{
if(s[i-1]=='R')
num++;
else if(s[i-1]=='L')
num--;
a[i]=num;
}
long int c=printDistinct(a,n+1);
cout<<c<<endl;
}
} | [
"mukul3646n@gmail.com"
] | mukul3646n@gmail.com |
da71ebeed49131844112f79e20274b2e25f1fc8e | 4fc8cfdbcde18d697f7aa12165a3842e62419029 | /DXUT9and10/Optional/ImeUi.cpp | a807a21f4091e04a448fa4cb7cfcf19d60836514 | [] | no_license | seanpm2001/Marselas_Zombie-Direct3D-Samples | f3de32effddcfbce5818e0d1ca5b32de6acbdd4a | 5f53dc2d6f7deb32eb2e5e438d6b6644430fe9ee | refs/heads/master | 2023-03-18T17:26:53.101653 | 2018-09-27T21:30:49 | 2018-09-27T21:30:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101,778 | cpp | //--------------------------------------------------------------------------------------
// File: ImeUi.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "dxut.h"
#include "ImeUi.h"
#include <math.h>
#include <msctf.h>
#include <malloc.h>
#include <strsafe.h>
// Ignore typecast warnings
#pragma warning( disable : 4312 )
#pragma warning( disable : 4244 )
#pragma warning( disable : 4311 )
#define MAX_CANDIDATE_LENGTH 256
#define COUNTOF(a) ( sizeof( a ) / sizeof( ( a )[0] ) )
#define POSITION_UNINITIALIZED ((DWORD)-1)
#define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL)
#define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED)
#define MAKEIMEVERSION(major,minor) ( (DWORD)( ( (BYTE)( major ) << 24 ) | ( (BYTE)( minor ) << 16 ) ) )
#define IMEID_VER(dwId) ( ( dwId ) & 0xffff0000 )
#define IMEID_LANG(dwId) ( ( dwId ) & 0x0000ffff )
#define _CHT_HKL_DAYI ( (HKL)0xE0060404 ) // DaYi
#define _CHT_HKL_NEW_PHONETIC ( (HKL)0xE0080404 ) // New Phonetic
#define _CHT_HKL_NEW_CHANG_JIE ( (HKL)0xE0090404 ) // New Chang Jie
#define _CHT_HKL_NEW_QUICK ( (HKL)0xE00A0404 ) // New Quick
#define _CHT_HKL_HK_CANTONESE ( (HKL)0xE00B0404 ) // Hong Kong Cantonese
#define _CHT_IMEFILENAME "TINTLGNT.IME" // New Phonetic
#define _CHT_IMEFILENAME2 "CINTLGNT.IME" // New Chang Jie
#define _CHT_IMEFILENAME3 "MSTCIPHA.IME" // Phonetic 5.1
#define IMEID_CHT_VER42 ( LANG_CHT | MAKEIMEVERSION( 4, 2 ) ) // New(Phonetic/ChanJie)IME98 : 4.2.x.x // Win98
#define IMEID_CHT_VER43 ( LANG_CHT | MAKEIMEVERSION( 4, 3 ) ) // New(Phonetic/ChanJie)IME98a : 4.3.x.x // Win2k
#define IMEID_CHT_VER44 ( LANG_CHT | MAKEIMEVERSION( 4, 4 ) ) // New ChanJie IME98b : 4.4.x.x // WinXP
#define IMEID_CHT_VER50 ( LANG_CHT | MAKEIMEVERSION( 5, 0 ) ) // New(Phonetic/ChanJie)IME5.0 : 5.0.x.x // WinME
#define IMEID_CHT_VER51 ( LANG_CHT | MAKEIMEVERSION( 5, 1 ) ) // New(Phonetic/ChanJie)IME5.1 : 5.1.x.x // IME2002(w/OfficeXP)
#define IMEID_CHT_VER52 ( LANG_CHT | MAKEIMEVERSION( 5, 2 ) ) // New(Phonetic/ChanJie)IME5.2 : 5.2.x.x // IME2002a(w/WinXP)
#define IMEID_CHT_VER60 ( LANG_CHT | MAKEIMEVERSION( 6, 0 ) ) // New(Phonetic/ChanJie)IME6.0 : 6.0.x.x // New IME 6.0(web download)
#define IMEID_CHT_VER_VISTA ( LANG_CHT | MAKEIMEVERSION( 7, 0 ) ) // All TSF TIP under Cicero UI-less mode: a hack to make GetImeId() return non-zero value
#define _CHS_HKL ( (HKL)0xE00E0804 ) // MSPY
#define _CHS_IMEFILENAME "PINTLGNT.IME" // MSPY1.5/2/3
#define _CHS_IMEFILENAME2 "MSSCIPYA.IME" // MSPY3 for OfficeXP
#define IMEID_CHS_VER41 ( LANG_CHS | MAKEIMEVERSION( 4, 1 ) ) // MSPY1.5 // SCIME97 or MSPY1.5 (w/Win98, Office97)
#define IMEID_CHS_VER42 ( LANG_CHS | MAKEIMEVERSION( 4, 2 ) ) // MSPY2 // Win2k/WinME
#define IMEID_CHS_VER53 ( LANG_CHS | MAKEIMEVERSION( 5, 3 ) ) // MSPY3 // WinXP
static CHAR signature[] = "%%%IMEUILIB:070111%%%";
static IMEUI_APPEARANCE gSkinIME = {
0, // symbolColor;
0x404040, // symbolColorOff;
0xff000000, // symbolColorText;
24, // symbolHeight;
0xa0, // symbolTranslucence;
0, // symbolPlacement;
NULL, // symbolFont;
0xffffffff, // candColorBase;
0xff000000, // candColorBorder;
0, // candColorText;
0x00ffff00, // compColorInput;
0x000000ff, // compColorTargetConv;
0x0000ff00, // compColorConverted;
0x00ff0000, // compColorTargetNotConv;
0x00ff0000, // compColorInputErr;
0x80, // compTranslucence;
0, // compColorText;
2, // caretWidth;
1, // caretYMargin;
};
struct _SkinCompStr
{
DWORD colorInput;
DWORD colorTargetConv;
DWORD colorConverted;
DWORD colorTargetNotConv;
DWORD colorInputErr;
};
_SkinCompStr gSkinCompStr;
// Definition from Win98DDK version of IMM.H
typedef struct tagINPUTCONTEXT2 {
HWND hWnd;
BOOL fOpen;
POINT ptStatusWndPos;
POINT ptSoftKbdPos;
DWORD fdwConversion;
DWORD fdwSentence;
union {
LOGFONTA A;
LOGFONTW W;
} lfFont;
COMPOSITIONFORM cfCompForm;
CANDIDATEFORM cfCandForm[4];
HIMCC hCompStr;
HIMCC hCandInfo;
HIMCC hGuideLine;
HIMCC hPrivate;
DWORD dwNumMsgBuf;
HIMCC hMsgBuf;
DWORD fdwInit;
DWORD dwReserve[3];
} INPUTCONTEXT2, *PINPUTCONTEXT2, NEAR *NPINPUTCONTEXT2, FAR *LPINPUTCONTEXT2;
// Class to disable Cicero in case ImmDisableTextFrameService() doesn't disable it completely
class CDisableCicero
{
public:
CDisableCicero() : m_ptim( NULL ), m_bComInit( false )
{
}
~CDisableCicero()
{
Uninitialize();
}
void Initialize()
{
if ( m_bComInit )
{
return;
}
HRESULT hr;
hr = CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );
if ( SUCCEEDED( hr ) )
{
m_bComInit = true;
hr = CoCreateInstance( CLSID_TF_ThreadMgr,
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(ITfThreadMgr),
(void**)&m_ptim );
}
}
void Uninitialize()
{
if ( m_ptim )
{
m_ptim->Release();
m_ptim = NULL;
}
if ( m_bComInit )
CoUninitialize();
m_bComInit = false;
}
void DisableCiceroOnThisWnd( HWND hwnd )
{
if ( m_ptim == NULL )
return;
ITfDocumentMgr* pdimPrev; // the dim that is associated previously.
// Associate NULL dim to the window.
// When this window gets the focus, Cicero does not work and IMM32 IME
// will be activated.
if ( SUCCEEDED( m_ptim->AssociateFocus( hwnd, NULL, &pdimPrev ) ) )
{
if ( pdimPrev )
pdimPrev->Release();
}
}
private:
ITfThreadMgr* m_ptim;
bool m_bComInit;
};
static CDisableCicero g_disableCicero;
#define _IsLeadByte(x) ( LeadByteTable[(BYTE)( x )] )
static void _PumpMessage();
static BYTE LeadByteTable[256];
#define _ImmGetContext ImmGetContext
#define _ImmReleaseContext ImmReleaseContext
#define _ImmAssociateContext ImmAssociateContext
static LONG (WINAPI* _ImmGetCompositionString)( HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen );
#define _ImmGetOpenStatus ImmGetOpenStatus
#define _ImmSetOpenStatus ImmSetOpenStatus
#define _ImmGetConversionStatus ImmGetConversionStatus
static DWORD (WINAPI* _ImmGetCandidateList)( HIMC himc, DWORD deIndex, LPCANDIDATELIST lpCandList, DWORD dwBufLen );
static LPINPUTCONTEXT2 (WINAPI* _ImmLockIMC)(HIMC hIMC);
static BOOL (WINAPI* _ImmUnlockIMC)(HIMC hIMC);
static LPVOID (WINAPI* _ImmLockIMCC)(HIMCC hIMCC);
static BOOL (WINAPI* _ImmUnlockIMCC)(HIMCC hIMCC);
#define _ImmGetDefaultIMEWnd ImmGetDefaultIMEWnd
#define _ImmGetIMEFileNameA ImmGetIMEFileNameA
#define _ImmGetVirtualKey ImmGetVirtualKey
#define _ImmNotifyIME ImmNotifyIME
#define _ImmSetConversionStatus ImmSetConversionStatus
#define _ImmSimulateHotKey ImmSimulateHotKey
#define _ImmIsIME ImmIsIME
// private API provided by CHT IME. Available on version 6.0 or later.
UINT (WINAPI*_GetReadingString)(HIMC himc, UINT uReadingBufLen, LPWSTR lpwReadingBuf, PINT pnErrorIndex, BOOL* pfIsVertical, PUINT puMaxReadingLen);
BOOL (WINAPI*_ShowReadingWindow)(HIMC himc, BOOL bShow);
// Callbacks
void (CALLBACK *ImeUiCallback_DrawRect)( int x1, int y1, int x2, int y2, DWORD color );
void (CALLBACK *ImeUiCallback_DrawFans)(const IMEUI_VERTEX* paVertex, UINT uNum);
void* (__cdecl *ImeUiCallback_Malloc)( size_t bytes );
void (__cdecl *ImeUiCallback_Free)( void* ptr );
void (CALLBACK *ImeUiCallback_OnChar)( WCHAR wc );
static void (*_SendCompString)();
static LRESULT (WINAPI* _SendMessage)(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) = SendMessageA;
static DWORD (* _GetCandidateList)(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList);
static HWND g_hwndMain;
static HWND g_hwndCurr;
static HIMC g_himcOrg;
static bool g_bImeEnabled = false;
static TCHAR g_szCompositionString[256];
static BYTE g_szCompAttrString[256];
static DWORD g_IMECursorBytes = 0;
static DWORD g_IMECursorChars = 0;
static TCHAR g_szCandidate[MAX_CANDLIST][MAX_CANDIDATE_LENGTH];
static DWORD g_dwSelection, g_dwCount;
static UINT g_uCandPageSize;
static DWORD g_bDisableImeCompletely = false;
static DWORD g_dwIMELevel;
static DWORD g_dwIMELevelSaved;
static TCHAR g_szMultiLineCompString[ 256 * ( 3 - sizeof(TCHAR) ) ];
static bool g_bReadingWindow = false;
static bool g_bHorizontalReading = false;
static bool g_bVerticalCand = true;
static UINT g_uCaretBlinkTime = 0;
static UINT g_uCaretBlinkLast = 0;
static bool g_bCaretDraw = false;
static bool g_bChineseIME;
static bool g_bInsertMode = true;
static TCHAR g_szReadingString[32]; // Used only in case of horizontal reading window
static int g_iReadingError; // Used only in case of horizontal reading window
static UINT g_screenWidth, g_screenHeight;
static DWORD g_dwPrevFloat;
static bool bIsSendingKeyMessage = false;
static bool g_bInitialized = false;
static bool g_bCandList = false;
static DWORD g_dwCandX, g_dwCandY;
static DWORD g_dwCaretX, g_dwCaretY;
static DWORD g_hCompChar;
static int g_iCandListIndexBase;
static DWORD g_dwImeUiFlags = IMEUI_FLAG_SUPPORT_CARET;
static bool g_bUILessMode = false;
static HMODULE g_hImmDll = NULL;
#define IsNT() (g_osi.dwPlatformId == VER_PLATFORM_WIN32_NT)
struct CompStringAttribute
{
UINT caretX;
UINT caretY;
CImeUiFont_Base* pFont;
DWORD colorComp;
DWORD colorCand;
RECT margins;
};
static CompStringAttribute g_CaretInfo;
static DWORD g_dwState = IMEUI_STATE_OFF;
static DWORD swirl = 0;
static double lastSwirl;
#define INDICATOR_NON_IME 0
#define INDICATOR_CHS 1
#define INDICATOR_CHT 2
#define INDICATOR_KOREAN 3
#define INDICATOR_JAPANESE 4
#define GETLANG() LOWORD(g_hklCurrent)
#define GETPRIMLANG() ((WORD)PRIMARYLANGID(GETLANG()))
#define GETSUBLANG() SUBLANGID(GETLANG())
#define LANG_CHS MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED)
#define LANG_CHT MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL)
static HKL g_hklCurrent = 0;
static UINT g_uCodePage = 0;
static LPTSTR g_aszIndicator[] =
{
TEXT("A"),
#ifdef UNICODE
L"\x7B80",
L"\x7E41",
L"\xac00",
L"\x3042",
#else
"\xd6\xd0",
"\xa4\xa4",
"\xb0\xa1",
"\x82\xa0",
#endif
};
static LPTSTR g_pszIndicatior = g_aszIndicator[0];
static void GetReadingString(HWND hWnd);
static DWORD GetImeId( UINT uIndex = 0 );
static void CheckToggleState();
static void DrawImeIndicator();
static void DrawCandidateList();
static void DrawCompositionString( bool bDrawCompAttr );
static void GetReadingWindowOrientation( DWORD dwId );
static void OnInputLangChangeWorker();
static void OnInputLangChange();
static void SetImeApi();
static void CheckInputLocale();
static void SetSupportLevel( DWORD dwImeLevel );
void ImeUi_SetSupportLevel(DWORD dwImeLevel);
//
// local helper functions
//
inline LRESULT SendKeyMsg(HWND hwnd, UINT msg, WPARAM wp)
{
bIsSendingKeyMessage = true;
LRESULT lRc = _SendMessage(hwnd, msg, wp, 1);
bIsSendingKeyMessage = false;
return lRc;
}
#define SendKeyMsg_DOWN(hwnd,vk) SendKeyMsg(hwnd, WM_KEYDOWN, vk)
#define SendKeyMsg_UP(hwnd,vk) SendKeyMsg(hwnd, WM_KEYUP, vk)
///////////////////////////////////////////////////////////////////////////////
//
// CTsfUiLessMode
// Handles IME events using Text Service Framework (TSF). Before Vista,
// IMM (Input Method Manager) API has been used to handle IME events and
// inqueries. Some IMM functions lose backward compatibility due to design
// of TSF, so we have to use new TSF interfaces.
//
///////////////////////////////////////////////////////////////////////////////
class CTsfUiLessMode
{
protected:
// Sink receives event notifications
class CUIElementSink : public ITfUIElementSink, public ITfInputProcessorProfileActivationSink, public ITfCompartmentEventSink
{
public:
CUIElementSink();
~CUIElementSink();
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// ITfUIElementSink
// Notifications for Reading Window events. We could process candidate as well, but we'll use IMM for simplicity sake.
STDMETHODIMP BeginUIElement(DWORD dwUIElementId, BOOL *pbShow);
STDMETHODIMP UpdateUIElement(DWORD dwUIElementId);
STDMETHODIMP EndUIElement(DWORD dwUIElementId);
// ITfInputProcessorProfileActivationSink
// Notification for keyboard input locale change
STDMETHODIMP OnActivated(DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid,
REFGUID guidProfile, HKL hkl, DWORD dwFlags);
// ITfCompartmentEventSink
// Notification for open mode (toggle state) change
STDMETHODIMP OnChange(REFGUID rguid);
private:
LONG _cRef;
};
static void MakeReadingInformationString(ITfReadingInformationUIElement* preading);
static void MakeCandidateStrings(ITfCandidateListUIElement* pcandidate);
static ITfUIElement* GetUIElement(DWORD dwUIElementId);
static BOOL GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode );
static BOOL SetupCompartmentSinks( BOOL bResetOnly = FALSE, ITfCompartment* pTfOpenMode = NULL, ITfCompartment* ppTfConvMode = NULL );
static ITfThreadMgrEx* m_tm;
static DWORD m_dwUIElementSinkCookie;
static DWORD m_dwAlpnSinkCookie;
static DWORD m_dwOpenModeSinkCookie;
static DWORD m_dwConvModeSinkCookie;
static CUIElementSink *m_TsfSink;
static int m_nCandidateRefCount; // Some IME shows multiple candidate lists but the Library doesn't support multiple candidate list.
// So track open / close events to make sure the candidate list opened last is shown.
CTsfUiLessMode() {} // this class can't be instanciated
public:
static BOOL SetupSinks();
static void ReleaseSinks();
static BOOL CurrentInputLocaleIsIme();
static void UpdateImeState(BOOL bResetCompartmentEventSink = FALSE);
static void EnableUiUpdates(bool bEnable);
};
ITfThreadMgrEx* CTsfUiLessMode::m_tm;
DWORD CTsfUiLessMode::m_dwUIElementSinkCookie = TF_INVALID_COOKIE;
DWORD CTsfUiLessMode::m_dwAlpnSinkCookie = TF_INVALID_COOKIE;
DWORD CTsfUiLessMode::m_dwOpenModeSinkCookie = TF_INVALID_COOKIE;
DWORD CTsfUiLessMode::m_dwConvModeSinkCookie = TF_INVALID_COOKIE;
CTsfUiLessMode::CUIElementSink* CTsfUiLessMode::m_TsfSink = NULL;
int CTsfUiLessMode::m_nCandidateRefCount = NULL;
static unsigned long _strtoul( LPCSTR psz, LPTSTR*, int )
{
if ( !psz )
return 0;
ULONG ulRet = 0;
if ( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
{
psz += 2;
ULONG ul = 0;
while ( *psz )
{
if ( '0' <= *psz && *psz <= '9' )
ul = *psz - '0';
else if ( 'A' <= *psz && *psz <= 'F' )
ul = *psz - 'A' + 10;
else if ( 'a' <= *psz && *psz <= 'f' )
ul = *psz - 'a' + 10;
else
break;
ulRet = ulRet * 16 + ul;
psz++;
}
}
else {
while ( *psz && ( '0' <= *psz && *psz <= '9' ) )
{
ulRet = ulRet * 10 + ( *psz - '0' );
psz++;
}
}
return ulRet;
}
#ifdef UNICODE
#define GetCharCount(psz) lstrlen(psz)
#define GetCharCountFromBytes(psz,iBytes) (iBytes)
static void AW_SendCompString()
{
int i, iLen;
if ( ImeUiCallback_OnChar )
{
for ( i = 0; g_szCompositionString[i]; i++ )
{
ImeUiCallback_OnChar( g_szCompositionString[i] );
}
return;
}
BYTE szCompStr[COUNTOF(g_szCompositionString) * 2];
iLen = WideCharToMultiByte(g_uCodePage, 0, g_szCompositionString, -1,
(LPSTR)szCompStr, COUNTOF(szCompStr), NULL, NULL) - 1; // don't need to send NUL terminator;
for (i = 0; i < iLen; i++)
{
SendKeyMsg(g_hwndCurr, WM_CHAR, szCompStr[i]);
}
}
// The following AW_Imm* functions are there to support Win95/98 first version.
// They can be deleted if the game doesn't supports them (i.e. games requires Win98 SE or later).
static DWORD AW_GetCandidateList(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList)
{
DWORD dwBufLen = ImmGetCandidateListA( himc, dwIndex, NULL, 0 );
if (dwBufLen)
{
LPCANDIDATELIST pCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(dwBufLen);
if (pCandList) {
dwBufLen = ImmGetCandidateListA( himc, dwIndex, pCandList, dwBufLen );
if (dwBufLen) {
int i;
int wideBufLen = 0;
for (i = 0; i < (int)pCandList->dwCount; i++) {
wideBufLen += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, NULL, 0) * sizeof(WCHAR);
}
wideBufLen += pCandList->dwOffset[0];
*ppCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(wideBufLen);
LPCANDIDATELIST pCandListW = *ppCandList;
memcpy(pCandListW, pCandList, pCandList->dwOffset[0]);
LPWSTR pwz = (LPWSTR)((LPSTR)pCandListW + pCandList->dwOffset[0]);
for (i = 0; i < (int)pCandList->dwCount; i++) {
pCandListW->dwOffset[i] = (LPSTR)pwz - (LPSTR)pCandListW;
pwz += MultiByteToWideChar(g_uCodePage, 0, (LPSTR)pCandList + pCandList->dwOffset[i], -1, pwz, 256);
}
dwBufLen = wideBufLen;
}
ImeUiCallback_Free(pCandList);
}
}
return dwBufLen;
}
static LONG WINAPI AW_ImmGetCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen)
{
char pszMb[COUNTOF(g_szCompositionString) * 2];
DWORD dwRet = ImmGetCompositionStringA(himc, dwIndex, pszMb, sizeof(pszMb));
switch (dwIndex) {
case GCS_RESULTSTR:
case GCS_COMPSTR:
if (dwRet) {
pszMb[dwRet] = 0;
dwRet = (DWORD)MultiByteToWideChar(g_uCodePage, 0, pszMb, -1, (LPWSTR)lpBuf, dwBufLen);
if (dwRet) {
// Note that ImmGetCompositionString() returns number of bytes copied, regardless of the width of character.
dwRet = (dwRet - 1) * sizeof(WCHAR);
}
}
break;
case GCS_CURSORPOS:
dwRet /= 2;
break;
case GCS_COMPATTR: {
char pszMb2[COUNTOF(g_szCompositionString) * 2];
DWORD dwRet2 = ImmGetCompositionStringA(himc, GCS_COMPSTR, pszMb2, sizeof(pszMb2));
if (!dwRet2) {
dwRet2 = ImmGetCompositionStringA(himc, GCS_RESULTSTR, pszMb2, sizeof(pszMb2));
if (!dwRet2) {
return 0;
}
}
char* pOut = (char*)lpBuf;
for (DWORD i = 0; i < dwRet; i++) {
*pOut++ = pszMb[i]; // copy attribute
if (_IsLeadByte(pszMb2[i]))
i++;
}
dwRet = pOut - (char*)lpBuf;
}
break;
}
return dwRet;
}
#else // !UNICODE
// returns number of characters from number of bytes
static int GetCharCountFromBytes(LPCSTR pszString, int iBytes)
{
int iCount = 0;
int i;
for (i = 0; pszString[i] && i < iBytes; i++) {
iCount++;
if (_IsLeadByte(pszString[i]))
i++;
}
if (i != iBytes)
iCount = -iCount; // indicate error - iBytes specifies wrong boundary (i.e. the last byte is leadbyte)
return iCount;
}
static int GetCharCount(LPTSTR psz)
{
int i = 0;
while (*psz) {
if (_IsLeadByte(*psz)) {
psz++;
}
psz++;
i++;
}
return i;
}
static DWORD WA_GetCandidateList(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList)
{
DWORD dwBufLen = ImmGetCandidateListW( himc, dwIndex, NULL, 0 );
if (dwBufLen)
{
LPCANDIDATELIST pCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(dwBufLen);
if (pCandList)
{
dwBufLen = ImmGetCandidateListW( himc, dwIndex, pCandList, dwBufLen );
if (dwBufLen)
{
int i;
int mbBufLen = 0;
for ( i = 0; i < (int)pCandList->dwCount; i++ )
{
mbBufLen += WideCharToMultiByte( g_uCodePage, 0, (LPWSTR)((LPSTR)pCandList + pCandList->dwOffset[i]), -1, NULL, 0, NULL, NULL );
}
mbBufLen += pCandList->dwOffset[0];
*ppCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(mbBufLen);
LPCANDIDATELIST pCandListA = *ppCandList;
memcpy(pCandListA, pCandList, pCandList->dwOffset[0]);
LPSTR psz = (LPSTR)pCandListA + pCandList->dwOffset[0];
for (i = 0; i < (int)pCandList->dwCount; i++)
{
pCandListA->dwOffset[i] = (LPSTR)psz - (LPSTR)pCandListA;
psz += WideCharToMultiByte( g_uCodePage, 0, (LPWSTR)((LPSTR)pCandList + pCandList->dwOffset[i]), -1, psz, 256, NULL, NULL );
}
dwBufLen = mbBufLen;
}
ImeUiCallback_Free(pCandList);
}
}
return dwBufLen;
}
static LONG WINAPI WA_ImmGetCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen)
{
WCHAR pwzUc[COUNTOF(g_szCompositionString)];
DWORD dwRet = ImmGetCompositionStringW(himc, dwIndex, pwzUc, sizeof(pwzUc));
switch (dwIndex) {
case GCS_RESULTSTR:
case GCS_COMPSTR:
if (dwRet) {
pwzUc[dwRet / sizeof(WCHAR)] = 0;
dwRet = (DWORD)WideCharToMultiByte( g_uCodePage, 0, pwzUc, -1, (LPSTR)lpBuf, dwBufLen, NULL, NULL );
if (dwRet) {
dwRet = dwRet - 1;
}
}
break;
case GCS_CURSORPOS:
{
WCHAR pwzUc2[COUNTOF(g_szCompositionString)];
DWORD dwRet2 = ImmGetCompositionStringW(himc, GCS_COMPSTR, pwzUc2, sizeof(pwzUc2));
if (!dwRet2)
{
dwRet2 = ImmGetCompositionStringW(himc, GCS_RESULTSTR, pwzUc2, sizeof(pwzUc2));
if (!dwRet2)
{
return 0;
}
}
dwRet2 /= 2;
//The return value of WideCharToMultiByte() should probably be checked/asserted for success.
//bounds violation (overflow) 'pszMb[iRc]'
const int bufSize = COUNTOF(g_szCompositionString) * 2;
char pszMb[bufSize];
int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL );
assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place
if (iRc >= bufSize) //if we wrote more bytes than the length of the buffer, we need to terminate it
{
pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer
}
else
{
pszMb[ iRc ] = 0;
}
char* psz = pszMb;
for ( dwRet2 = 0; dwRet2 != dwRet; dwRet2++ )
{
if ( _IsLeadByte( *psz ) )
psz++;
psz++;
}
dwRet = psz - pszMb;
}
break;
case GCS_COMPATTR: {
WCHAR pwzUc2[COUNTOF(g_szCompositionString)];
DWORD dwRet2 = ImmGetCompositionStringW(himc, GCS_COMPSTR, pwzUc2, sizeof(pwzUc2));
if (!dwRet2)
{
dwRet2 = ImmGetCompositionStringW(himc, GCS_RESULTSTR, pwzUc2, sizeof(pwzUc2));
if (!dwRet2)
{
return 0;
}
}
dwRet2 /= 2;
const int bufSize = COUNTOF(g_szCompositionString) * 2;
char pszMb[bufSize];
int iRc = WideCharToMultiByte( g_uCodePage, 0, pwzUc2, dwRet2, pszMb, sizeof( pszMb ), NULL, NULL );
assert( iRc > 0 ); //WideCharToMultiByte returns 0 if it failed, and it should *never* be negative in the first place
if (iRc >= bufSize) //if we wrote more bytes than the length of the buffer, we need to terminate it
{
pszMb[ bufSize - 1] = 0; //0 terminate the end of the buffer
}
else
{
pszMb[ iRc ] = 0;
}
char* pSrc = (char*)pwzUc;
char* pOut = (char*)lpBuf;
for (char* psz = pszMb; *psz; psz++, pSrc++)
{
*pOut++ = *pSrc; // copy attribute
if ( _IsLeadByte( *psz ) )
{
*pOut++ = *pSrc;
psz++;
}
// buffer overrun protection, pOut is incremented in the loop, but not part of the
// loop invariant test. To make the code more readable we have a test rather than
// rolling this into the for stmt.
if ((DWORD)(pOut-(char*)lpBuf) >=dwBufLen)
break;
}
dwRet = pOut - (char*)lpBuf;
}
break;
}
return dwRet;
}
#endif // UNICODE
static void ComposeCandidateLine( int index, LPCTSTR pszCandidate )
{
LPTSTR psz = g_szCandidate[index];
*psz++ = (TCHAR)( TEXT( '0' ) + ( ( index + g_iCandListIndexBase ) % 10 ) );
if ( g_bVerticalCand )
{
*psz++ = TEXT( ' ' );
}
while ( *pszCandidate && (COUNTOF(g_szCandidate[index]) > (psz-g_szCandidate[index])) )
{
*psz++ = *pszCandidate++;
}
*psz = 0;
}
static void SendCompString()
{
int i, iLen = lstrlen(g_szCompositionString);
if ( ImeUiCallback_OnChar )
{
LPCWSTR pwz;
#ifdef UNICODE
pwz = g_szCompositionString;
#else
WCHAR szUnicode[ COUNTOF( g_szCompositionString ) ];
pwz = szUnicode;
iLen = MultiByteToWideChar( g_uCodePage, 0, g_szCompositionString, -1, szUnicode, COUNTOF(szUnicode) ) - 1;
#endif
for ( i = 0; i < iLen; i++ )
{
ImeUiCallback_OnChar( pwz[i] );
}
return;
}
for ( i = 0; i < iLen; i++ )
{
SendKeyMsg(g_hwndCurr, WM_CHAR,
#ifdef UNICODE
(WPARAM)g_szCompositionString[i]
#else
(WPARAM)(BYTE)g_szCompositionString[i]
#endif
);
}
}
static DWORD GetCandidateList(HIMC himc, DWORD dwIndex, LPCANDIDATELIST* ppCandList)
{
DWORD dwBufLen = _ImmGetCandidateList( himc, dwIndex, NULL, 0 );
if ( dwBufLen )
{
*ppCandList = (LPCANDIDATELIST)ImeUiCallback_Malloc(dwBufLen);
dwBufLen = _ImmGetCandidateList( himc, dwIndex, *ppCandList, dwBufLen );
}
return dwBufLen;
}
static void SendControlKeys(UINT vk, UINT num)
{
if (num == 0)
return;
for (UINT i = 0; i < num ; i++) {
SendKeyMsg_DOWN(g_hwndCurr, vk);
}
SendKeyMsg_UP(g_hwndCurr, vk);
}
// send key messages to erase composition string.
static void CancelCompString(HWND hwnd, bool bUseBackSpace = true, int iNewStrLen = 0)
{
if (g_dwIMELevel != 3)
return;
int cc = GetCharCount(g_szCompositionString);
int i;
// move caret to the end of composition string
SendControlKeys(VK_RIGHT, cc - g_IMECursorChars);
if (bUseBackSpace || g_bInsertMode)
iNewStrLen = 0;
// The caller sets bUseBackSpace to false if there's possibility of sending
// new composition string to the app right after this function call.
//
// If the app is in overwriting mode and new comp string is
// shorter than current one, delete previous comp string
// till it's same long as the new one. Then move caret to the beginning of comp string.
// New comp string will overwrite old one.
if (iNewStrLen < cc)
{
for (i = 0; i < cc - iNewStrLen; i++)
{
SendKeyMsg_DOWN(hwnd, VK_BACK);
SendKeyMsg(hwnd, WM_CHAR, 8); //Backspace character
}
SendKeyMsg_UP(hwnd, VK_BACK);
}
else
iNewStrLen = cc;
SendControlKeys(VK_LEFT, iNewStrLen);
}
// initialize composition string data.
static void InitCompStringData(void)
{
g_IMECursorBytes = 0;
g_IMECursorChars = 0;
memset(&g_szCompositionString, 0, sizeof(g_szCompositionString));
memset(&g_szCompAttrString, 0, sizeof(g_szCompAttrString));
}
static void DrawCaret(DWORD x, DWORD y, DWORD height)
{
if (g_bCaretDraw && ImeUiCallback_DrawRect)
ImeUiCallback_DrawRect(x, y + gSkinIME.caretYMargin, x + gSkinIME.caretWidth, y + height - gSkinIME.caretYMargin, g_CaretInfo.colorComp);
}
//
// Apps that draw the composition string on top of composition string attribute
// in level 3 support should call this function twice in rendering a frame.
// // Draw edit box UI;
// ImeUi_RenderUI(true, false); // paint composition string attribute;
// // Draw text in the edit box;
// ImeUi_RenderUi(false, true); // paint the rest of IME UI;
//
void ImeUi_RenderUI(bool bDrawCompAttr, bool bDrawOtherUi)
{
if (!g_bInitialized || !g_bImeEnabled || !g_CaretInfo.pFont)
return;
if (!bDrawCompAttr && !bDrawOtherUi)
return; // error case
if (g_dwIMELevel == 2) {
if (!bDrawOtherUi)
return; // 1st call for level 3 support
}
if (bDrawOtherUi)
DrawImeIndicator();
DrawCompositionString( bDrawCompAttr );
if ( bDrawOtherUi )
DrawCandidateList();
}
static void DrawImeIndicator()
{
bool bOn = g_dwState != IMEUI_STATE_OFF;
IMEUI_VERTEX PieData[17];
float SizeOfPie = (float) gSkinIME.symbolHeight;
memset( PieData, 0, sizeof( PieData ) );
switch(gSkinIME.symbolPlacement)
{
case 0: // vertical centering IME indicator
{
if (SizeOfPie + g_CaretInfo.margins.right+4 > g_screenWidth)
{
PieData[0].sx=(-SizeOfPie/2) + g_CaretInfo.margins.left-4;
PieData[0].sy= (float) g_CaretInfo.margins.top + (g_CaretInfo.margins.bottom - g_CaretInfo.margins.top)/2;
}
else
{
PieData[0].sx=-(SizeOfPie/2) + g_CaretInfo.margins.right+gSkinIME.symbolHeight+4;
PieData[0].sy= (float) g_CaretInfo.margins.top + (g_CaretInfo.margins.bottom - g_CaretInfo.margins.top)/2;
}
break;
}
case 1: // upperleft
PieData[0].sx = 4+ (SizeOfPie/2);
PieData[0].sy = 4+ (SizeOfPie/2);
break;
case 2: // upperright
PieData[0].sx = g_screenWidth - (4+ (SizeOfPie/2));
PieData[0].sy = 4+ (SizeOfPie/2);
break;
case 3: // lowerright
PieData[0].sx = g_screenWidth - (4+ (SizeOfPie/2));
PieData[0].sy = g_screenHeight - (4+ (SizeOfPie/2));
break;
case 4: // lowerleft
PieData[0].sx = 4+ (SizeOfPie/2);
PieData[0].sy = g_screenHeight - (4+ (SizeOfPie/2));
break;
}
PieData[0].rhw=1.0f;
if (bOn)
{
if ( GetTickCount() - lastSwirl > 250 )
{
swirl++;
lastSwirl = GetTickCount();
if (swirl > 13)
swirl = 0;
}
}
else
swirl = 0;
for( int t1 = 1; t1 < 16; t1++ )
{
float radian = 2.0f * 3.1415926f * ( t1 - 1 + ( bOn * swirl ) ) / 14.0f;
PieData[t1].sx = (float)( PieData[0].sx + SizeOfPie / 2 * cos( radian ) );
PieData[t1].sy = (float)( PieData[0].sy + SizeOfPie / 2 * sin( radian ) );
PieData[t1].rhw = 1.0f;
}
PieData[0].color=0xffffff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
if ( !gSkinIME.symbolColor && bOn )
{
{
PieData[1].color=0xff0000 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[2].color=0xff3000 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[3].color=0xff6000 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[4].color=0xff9000 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[5].color=0xffC000 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[6].color=0xffff00 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[7].color=0xC0ff00 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[8].color=0x90ff00 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[9].color=0x60ff00 + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[10].color=0x30c0ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[11].color=0x00a0ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[12].color=0x3090ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[13].color=0x6060ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[14].color=0x9030ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
PieData[15].color=0xc000ff + (((DWORD)gSkinIME.symbolTranslucence)<<24);
}
}
else
{
DWORD dwColor = bOn ? gSkinIME.symbolColor : gSkinIME.symbolColorOff;
for( int t1=1; t1<16; t1++ )
{
PieData[t1].color= dwColor + (((DWORD)gSkinIME.symbolTranslucence)<<24);
}
}
PieData[16] = PieData[1];
if( ImeUiCallback_DrawFans )
ImeUiCallback_DrawFans( PieData, 17 );
float fHeight = gSkinIME.symbolHeight*0.625f;
// fix for Ent Gen #120 - reduce the height of character when Korean IME is on
if ( GETPRIMLANG() == LANG_KOREAN && bOn )
{
fHeight *= 0.8f;
}
if (gSkinIME.symbolFont)
{
#ifdef DS2
// save the font height here since DS2 shares editbox font and indicator font
DWORD _w, _h;
g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h );
#endif //DS2
// GOS deals height in points that is 1/72nd inch and assumes display device is 96dpi.
fHeight = fHeight * 96 / 72;
gSkinIME.symbolFont->SetHeight((UINT)fHeight);
gSkinIME.symbolFont->SetColor((((DWORD)gSkinIME.symbolTranslucence)<<24) | gSkinIME.symbolColorText);
//
// draw the proper symbol over the fan
//
DWORD w, h;
LPCTSTR cszSymbol = ( g_dwState == IMEUI_STATE_ON ) ? g_pszIndicatior : g_aszIndicator[0];
gSkinIME.symbolFont->GetTextExtent(cszSymbol, &w, &h);
gSkinIME.symbolFont->SetPosition((int)(PieData[0].sx)-w/2, (int)(PieData[0].sy)-h/2);
gSkinIME.symbolFont->DrawText( cszSymbol );
#ifdef DS2
// revert the height.
g_CaretInfo.pFont->SetHeight( _h );
// Double-check: Confirm match by testing a range of font heights to find best fit
DWORD _h2;
g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 );
if ( _h2 < _h )
{
for ( int i=1; _h2<_h && i<10; i++ )
{
g_CaretInfo.pFont->SetHeight( _h+i );
g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 );
}
}
else if ( _h2 > _h )
{
for ( int i=1; _h2>_h && i<10; i++ )
{
g_CaretInfo.pFont->SetHeight( _h-i );
g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &_w, &_h2 );
}
}
#endif //DS2
}
}
static void DrawCompositionString( bool bDrawCompAttr )
{
// Process timer for caret blink
UINT uCurrentTime = GetTickCount();
if (uCurrentTime - g_uCaretBlinkLast > g_uCaretBlinkTime)
{
g_uCaretBlinkLast = uCurrentTime;
g_bCaretDraw = !g_bCaretDraw;
}
int i = 0;
g_CaretInfo.pFont->SetColor(g_CaretInfo.colorComp);
DWORD uDummy;
int len = lstrlen(g_szCompositionString);
DWORD bgX = g_CaretInfo.caretX;
DWORD bgY = g_CaretInfo.caretY;
g_dwCaretX = POSITION_UNINITIALIZED;
g_dwCaretY = POSITION_UNINITIALIZED;
DWORD candX = POSITION_UNINITIALIZED;
DWORD candY = 0;
LPTSTR pszMlcs = g_szMultiLineCompString;
DWORD wCompChar = 0;
DWORD hCompChar = 0;
g_CaretInfo.pFont->GetTextExtent( TEXT(" "), &uDummy, &hCompChar );
if (g_dwIMELevel == 3 && g_IMECursorBytes && g_szCompositionString[0])
{
// shift starting point of drawing composition string according to the current caret position.
TCHAR temp = g_szCompositionString[g_IMECursorBytes];
g_szCompositionString[g_IMECursorBytes] = 0;
g_CaretInfo.pFont->GetTextExtent(g_szCompositionString, &wCompChar, &hCompChar);
g_szCompositionString[g_IMECursorBytes] = temp;
bgX -= wCompChar;
}
//
// Draw the background colors for IME text nuggets
//
bool saveCandPos = false;
DWORD cType = 1;
LPTSTR pszCurrentCompLine = g_szCompositionString;
DWORD dwCompLineStart = bgX;
DWORD bgXnext = bgX;
if (GETPRIMLANG() != LANG_KOREAN || g_bCaretDraw) // Korean uses composition attribute as blinking block caret
for (i = 0; i < len ; i += cType)
{
DWORD bgColor = 0x00000000;
TCHAR szChar[3];
szChar[0] = g_szCompositionString[i];
szChar[1] = szChar[2] = 0;
#ifndef UNICODE
cType = 1 + ((_IsLeadByte(g_szCompositionString[i])) ? 1 : 0);
if (cType == 2 && g_szCompositionString[i+1]) // in case we have 0 in trailbyte, we don't count it.
szChar[1] = g_szCompositionString[i+1];
#endif
bgX = bgXnext;
TCHAR cSave = g_szCompositionString[i + cType];
g_szCompositionString[i + cType] = 0;
g_CaretInfo.pFont->GetTextExtent( pszCurrentCompLine, &bgXnext, &hCompChar );
g_szCompositionString[i + cType] = cSave;
bgXnext += dwCompLineStart;
wCompChar = bgXnext - bgX;
switch(g_szCompAttrString[i])
{
case ATTR_INPUT:
bgColor = gSkinCompStr.colorInput;
break;
case ATTR_TARGET_CONVERTED:
bgColor = gSkinCompStr.colorTargetConv;
if ( IMEID_LANG( GetImeId() ) != LANG_CHS )
saveCandPos = true;
break;
case ATTR_CONVERTED:
bgColor = gSkinCompStr.colorConverted;
break;
case ATTR_TARGET_NOTCONVERTED:
//
// This is the one the user is working with currently
//
bgColor = gSkinCompStr.colorTargetNotConv;
break;
case ATTR_INPUT_ERROR:
bgColor = gSkinCompStr.colorInputErr;
break;
default:
// STOP( TEXT( "Attributes on IME characters are wrong" ) );
break;
}
if (g_dwIMELevel == 3 && bDrawCompAttr)
{
if ((LONG)bgX >= g_CaretInfo.margins.left && (LONG)bgX <= g_CaretInfo.margins.right)
{
if ( g_dwImeUiFlags & IMEUI_FLAG_SUPPORT_CARET )
{
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(bgX, bgY, bgX + wCompChar, bgY + hCompChar, bgColor);
}
else
{
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(bgX - wCompChar, bgY, bgX, bgY + hCompChar, bgColor);
}
}
}
else if (g_dwIMELevel == 2)
{
// make sure enough buffer space (possible space, NUL for current line, possible DBCS, 2 more NUL)
// are available in multiline composition string buffer
bool bWrite = ( pszMlcs - g_szMultiLineCompString <
COUNTOF( g_szMultiLineCompString ) - 5 * ( 3 - sizeof(TCHAR) ) );
if ((LONG)(bgX + wCompChar) >= g_CaretInfo.margins.right) {
bgX = dwCompLineStart = bgXnext = g_CaretInfo.margins.left;
bgY = bgY + hCompChar;
pszCurrentCompLine = g_szCompositionString + i;
if (bWrite)
{
if (pszMlcs == g_szMultiLineCompString || pszMlcs[-1] == 0)
*pszMlcs++ = ' '; // to avoid zero length line
*pszMlcs++ = 0;
}
}
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(bgX, bgY, bgX + wCompChar, bgY + hCompChar, bgColor);
if (bWrite) {
*pszMlcs++ = g_szCompositionString[i];
#ifndef UNICODE
if (cType == 2)
*pszMlcs++ = g_szCompositionString[i+1];
#endif
}
if ((DWORD)i == g_IMECursorBytes)
{
g_dwCaretX = bgX;
g_dwCaretY = bgY;
}
}
if ( ( saveCandPos && candX == POSITION_UNINITIALIZED ) ||
( IMEID_LANG( GetImeId() ) == LANG_CHS && i / ( 3 - sizeof(TCHAR) ) == (int)g_IMECursorChars ) )
{
candX = bgX;
candY = bgY;
}
saveCandPos = false;
}
bgX = bgXnext;
if (g_dwIMELevel == 2)
{
// in case the caret in composition string is at the end of it, draw it here
if (len != 0 && (DWORD)i == g_IMECursorBytes)
{
g_dwCaretX = bgX;
g_dwCaretY = bgY;
}
// Draw composition string.
//assert(pszMlcs - g_szMultiLineCompString <=
// sizeof(g_szMultiLineCompString) / sizeof(g_szMultiLineCompString[0]) - 2);
*pszMlcs++ = 0;
*pszMlcs++ = 0;
DWORD x, y;
x = g_CaretInfo.caretX;
y = g_CaretInfo.caretY;
pszMlcs = g_szMultiLineCompString;
while (*pszMlcs &&
pszMlcs - g_szMultiLineCompString < sizeof(g_szMultiLineCompString) / sizeof(g_szMultiLineCompString[0]))
{
g_CaretInfo.pFont->SetPosition(x, y);
g_CaretInfo.pFont->DrawText(pszMlcs);
pszMlcs += lstrlen( pszMlcs ) + 1;
x = g_CaretInfo.margins.left;
y += hCompChar;
}
}
// for changing z-order of caret
if ( g_dwCaretX != POSITION_UNINITIALIZED && g_dwCaretY != POSITION_UNINITIALIZED )
{
DrawCaret(g_dwCaretX, g_dwCaretY, hCompChar);
}
g_dwCandX = candX;
g_dwCandY = candY;
g_hCompChar = hCompChar;
}
static void DrawCandidateList()
{
DWORD candX = g_dwCandX;
DWORD candY = g_dwCandY;
DWORD hCompChar = g_hCompChar;
int i;
// draw candidate list / reading window
if ( !g_dwCount || g_szCandidate[0][0] == 0 )
{
return;
}
// If position of candidate list is not initialized yet, set it here.
if (candX == POSITION_UNINITIALIZED)
{
// CHT IME in Vista doesn't have ATTR_TARGET_CONVERTED attribute while typing,
// so display the candidate list near the caret in the composition string
if (GETLANG() == LANG_CHT && GetImeId() != 0 && g_dwCaretX != POSITION_UNINITIALIZED)
{
candX = g_dwCaretX;
candY = g_dwCaretY;
}
else
{
candX = g_CaretInfo.caretX;
candY = g_CaretInfo.caretY;
}
}
SIZE largest = {0,0};
static DWORD uDigitWidth = 0;
DWORD uSpaceWidth = 0;
static DWORD uDigitWidthList[10];
static CImeUiFont_Base* pPrevFont = NULL;
// find out the widest width of the digits
if ( pPrevFont != g_CaretInfo.pFont )
{
pPrevFont = g_CaretInfo.pFont;
for(int cnt=0; cnt<=9; cnt++)
{
DWORD uDW = 0;
DWORD uDH = 0;
TCHAR ss[8];
swprintf_s(ss, COUNTOF(ss), TEXT("%d"), cnt);
g_CaretInfo.pFont->GetTextExtent( ss, &uDW, &uDH );
uDigitWidthList[cnt] = uDW;
if ( uDW > uDigitWidth )
uDigitWidth = uDW;
if ( (signed)uDH > largest.cy)
largest.cy = uDH;
}
}
uSpaceWidth = uDigitWidth;
DWORD dwMarginX = (uSpaceWidth + 1) / 2;
DWORD adwCandWidth[ MAX_CANDLIST ];
// Find out the widest width of the candidate strings
DWORD dwCandWidth = 0;
if (g_bReadingWindow && g_bHorizontalReading)
g_CaretInfo.pFont->GetTextExtent(g_szReadingString, (DWORD*)&largest.cx, (DWORD*)&largest.cy);
else
{
for (i = 0; g_szCandidate[i][0] && i < (int)g_uCandPageSize; i++)
{
DWORD tx = 0;
DWORD ty = 0;
if (g_bReadingWindow)
g_CaretInfo.pFont->GetTextExtent(g_szCandidate[i], &tx, &ty);
else {
if (g_bVerticalCand)
g_CaretInfo.pFont->GetTextExtent(g_szCandidate[i]+2, &tx, &ty);
else
g_CaretInfo.pFont->GetTextExtent(g_szCandidate[i]+1, &tx, &ty);
tx = tx + uDigitWidth + uSpaceWidth;
}
if ((signed)tx > largest.cx)
largest.cx = tx;
if ((signed)ty > largest.cy)
largest.cy = ty;
adwCandWidth[ i ] = tx;
dwCandWidth += tx;
}
}
DWORD slotsUsed;
if (g_bReadingWindow && g_dwCount < g_uCandPageSize)
slotsUsed = g_dwCount;
else
slotsUsed = g_uCandPageSize;
// Show candidate list above composition string if there isn't enough room below.
DWORD dwCandHeight;
if (g_bVerticalCand && !(g_bReadingWindow && g_bHorizontalReading))
dwCandHeight = slotsUsed * largest.cy + 2;
else
dwCandHeight = largest.cy + 2;
if ( candY + hCompChar + dwCandHeight > g_screenHeight)
candY -= dwCandHeight;
else
candY += hCompChar;
if ( (int)candY < 0 )
candY = 0;
// Move candidate list horizontally to keep it inside of screen
if ( !g_bReadingWindow && IMEID_LANG( GetImeId() ) == LANG_CHS )
dwCandWidth += dwMarginX * (slotsUsed-1);
else if ( g_bReadingWindow && g_bHorizontalReading )
dwCandWidth = largest.cx + 2 + dwMarginX * 2;
else if ( g_bVerticalCand || g_bReadingWindow )
dwCandWidth = largest.cx + 2 + dwMarginX * 2;
else
dwCandWidth = slotsUsed * (largest.cx + 1) + 1;
if (candX + dwCandWidth > g_screenWidth)
candX = g_screenWidth - dwCandWidth;
if ( (int)candX < 0 )
candX = 0;
// Draw frame and background of candidate list / reading window
int seperateLineX = 0;
int left = candX;
int top = candY;
int right = candX + dwCandWidth;
int bottom = candY + dwCandHeight;
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(left, top, right, bottom, gSkinIME.candColorBorder);
left++;
top++;
right--;
bottom--;
if ( g_bReadingWindow || IMEID_LANG( GetImeId() ) == LANG_CHS )
{
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(left,top, right, bottom, gSkinIME.candColorBase);
}
else if ( g_bVerticalCand )
{
// uDigitWidth is the max width of all digits.
if ( !g_bReadingWindow )
{
seperateLineX = left + dwMarginX + uDigitWidth + uSpaceWidth / 2;
if( ImeUiCallback_DrawRect )
{
ImeUiCallback_DrawRect(left, top, seperateLineX-1, bottom, gSkinIME.candColorBase);
ImeUiCallback_DrawRect(seperateLineX, top, right, bottom, gSkinIME.candColorBase);
}
}
}
else
{
for (i = 0; (DWORD)i < slotsUsed; i++)
{
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(left, top, left + largest.cx, bottom, gSkinIME.candColorBase);
left += largest.cx + 1;
}
}
// Draw candidates / reading strings
candX++;
candY++;
if (g_bReadingWindow && g_bHorizontalReading)
{
int iStart = -1, iEnd = -1, iDummy;
candX += dwMarginX;
// draw background of error character if it exists
TCHAR szTemp[ COUNTOF( g_szReadingString ) ];
if (g_iReadingError >= 0) {
wcscpy_s(szTemp, COUNTOF(szTemp), g_szReadingString);
LPTSTR psz = szTemp + g_iReadingError;
#ifdef UNICODE
psz++;
#else
psz += ( _IsLeadByte( szTemp[g_iReadingError] ) ) ? 2 : 1;
#endif
*psz = 0;
g_CaretInfo.pFont->GetTextExtent(szTemp, (DWORD*)&iEnd, (DWORD*)&iDummy);
TCHAR cSave = szTemp[ g_iReadingError ];
szTemp[g_iReadingError] = 0;
g_CaretInfo.pFont->GetTextExtent(szTemp, (DWORD*)&iStart, (DWORD*)&iDummy);
szTemp[g_iReadingError] = cSave;
if( ImeUiCallback_DrawRect )
ImeUiCallback_DrawRect(candX + iStart, candY, candX + iEnd, candY + largest.cy, gSkinIME.candColorBorder);
}
g_CaretInfo.pFont->SetPosition(candX , candY);
g_CaretInfo.pFont->SetColor(g_CaretInfo.colorCand);
g_CaretInfo.pFont->DrawText(g_szReadingString);
// draw error character if it exists
if (iStart >= 0) {
g_CaretInfo.pFont->SetPosition(candX + iStart, candY);
if ( gSkinIME.candColorBase != 0xffffffff || gSkinIME.candColorBorder != 0xff000000 )
g_CaretInfo.pFont->SetColor(g_CaretInfo.colorCand);
else
g_CaretInfo.pFont->SetColor(0xff000000 + (~((0x00ffffff) & g_CaretInfo.colorCand)));
g_CaretInfo.pFont->DrawText(szTemp + g_iReadingError);
}
}
else
{
for (i = 0; i < (int)g_uCandPageSize && (DWORD)i < g_dwCount; i++)
{
if (g_dwSelection == (DWORD)i)
{
if ( gSkinIME.candColorBase != 0xffffffff || gSkinIME.candColorBorder != 0xff000000 )
g_CaretInfo.pFont->SetColor(g_CaretInfo.colorCand);
else
g_CaretInfo.pFont->SetColor(0xff000000 + (~((0x00ffffff) & g_CaretInfo.colorCand)));
if( ImeUiCallback_DrawRect )
{
if ( g_bReadingWindow || g_bVerticalCand )
ImeUiCallback_DrawRect( candX, candY + i * largest.cy,
candX - 1 + dwCandWidth, candY + (i + 1) * largest.cy, gSkinIME.candColorBorder );
else
ImeUiCallback_DrawRect( candX, candY,
candX + adwCandWidth[i], candY + largest.cy, gSkinIME.candColorBorder );
}
}
else
g_CaretInfo.pFont->SetColor(g_CaretInfo.colorCand);
if (g_szCandidate[i][0] != 0)
{
if (!g_bReadingWindow && g_bVerticalCand)
{
TCHAR szOneDigit[2] = { g_szCandidate[i][0], 0 };
int nOneDigit = g_szCandidate[i][0] - TEXT('0');
TCHAR *szCandidateBody = g_szCandidate[i] + 2;
int dx = candX + (seperateLineX - candX - uDigitWidthList[nOneDigit]) / 2;
int dy = candY + largest.cy * i;
g_CaretInfo.pFont->SetPosition( dx, dy );
g_CaretInfo.pFont->DrawText(szOneDigit);
g_CaretInfo.pFont->SetPosition( seperateLineX+dwMarginX, dy );
g_CaretInfo.pFont->DrawText(szCandidateBody);
}
else if ( g_bReadingWindow )
{
g_CaretInfo.pFont->SetPosition( dwMarginX + candX, candY + i * largest.cy );
g_CaretInfo.pFont->DrawText(g_szCandidate[i]);
}
else
{
g_CaretInfo.pFont->SetPosition( uSpaceWidth / 2 + candX, candY );
g_CaretInfo.pFont->DrawText(g_szCandidate[i]);
}
}
if ( !g_bReadingWindow && !g_bVerticalCand )
{
if ( IMEID_LANG( GetImeId() ) == LANG_CHS )
candX += adwCandWidth[i] + dwMarginX;
else
candX += largest.cx + 1;
}
}
}
}
static void CloseCandidateList()
{
g_bCandList = false;
if (!g_bReadingWindow) // fix for Ent Gen #120.
{
g_dwCount = 0;
memset(&g_szCandidate, 0, sizeof(g_szCandidate));
}
}
//
// ProcessIMEMessages()
// Processes IME related messages and acquire information
//
LPARAM ImeUi_ProcessMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM& lParam, bool * trapped )
{
HIMC himc;
int len;
static LPARAM lAlt = 0x80000000, lCtrl = 0x80000000, lShift = 0x80000000;
*trapped = false;
if (!g_bInitialized || g_bDisableImeCompletely)
{
return 0;
}
switch( uMsg )
{
//
// IME Handling
//
case WM_INPUTLANGCHANGE:
OnInputLangChange();
break;
case WM_IME_SETCONTEXT:
//
// We don't want anything to display, so we have to clear lParam and pass it to DefWindowProc().
// Expecially important in Vista to receive IMN_CHANGECANDIDATE correctly.
//
lParam = 0;
break;
case WM_IME_STARTCOMPOSITION:
InitCompStringData();
*trapped = true;
break;
case WM_IME_COMPOSITION:
{
LONG lRet;
TCHAR szCompStr[COUNTOF(g_szCompositionString)];
*trapped = true;
if (NULL == (himc = _ImmGetContext(hWnd)))
{
break;
}
// ResultStr must be processed before composition string.
if ( lParam & GCS_RESULTSTR )
{
lRet = (LONG)_ImmGetCompositionString( himc, GCS_RESULTSTR, szCompStr, COUNTOF( szCompStr ) ) / sizeof(TCHAR);
szCompStr[lRet] = 0;
CancelCompString( g_hwndCurr, false, GetCharCount( szCompStr ) );
wcscpy_s(g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr);
_SendCompString();
InitCompStringData();
}
//
// Reads in the composition string.
//
if ( lParam & GCS_COMPSTR )
{
//////////////////////////////////////////////////////
// Retrieve the latest user-selected IME candidates
lRet = (LONG)_ImmGetCompositionString( himc, GCS_COMPSTR, szCompStr, COUNTOF( szCompStr ) ) / sizeof(TCHAR);
szCompStr[lRet] = 0;
//
// Remove the whole of the string
//
CancelCompString(g_hwndCurr, false, GetCharCount( szCompStr ) );
wcscpy_s(g_szCompositionString, COUNTOF(g_szCompositionString), szCompStr);
lRet = _ImmGetCompositionString( himc, GCS_COMPATTR, g_szCompAttrString, COUNTOF( g_szCompAttrString ) );
g_szCompAttrString[lRet] = 0;
// Older CHT IME uses composition string for reading string
if ( GETLANG() == LANG_CHT && !GetImeId() )
{
int i, chars = lstrlen(g_szCompositionString) / (3 - sizeof(TCHAR));
if (chars)
{
g_dwCount = 4;
g_dwSelection = (DWORD)-1; // don't select any candidate
for (i = 3; i >= 0; i--)
{
if (i > chars - 1)
g_szCandidate[i][0] = 0;
else
{
#ifdef UNICODE
g_szCandidate[i][0] = g_szCompositionString[i];
g_szCandidate[i][1] = 0;
#else
g_szCandidate[i][0] = g_szCompositionString[i*2];
g_szCandidate[i][1] = g_szCompositionString[i*2+1];
g_szCandidate[i][2] = 0;
#endif
}
}
g_uCandPageSize = MAX_CANDLIST;
memset(g_szCompositionString, 0, 8);
g_bReadingWindow = true;
GetReadingWindowOrientation( 0 );
if (g_bHorizontalReading) {
g_iReadingError = -1;
g_szReadingString[0] = 0;
for (i = 0; i < (int)g_dwCount; i++) {
if (g_dwSelection == (DWORD)i)
g_iReadingError = lstrlen(g_szReadingString);
LPCTSTR pszTmp = g_szCandidate[i];
wcscat_s(g_szReadingString, COUNTOF(g_szReadingString), pszTmp);
}
}
}
else
g_dwCount = 0;
}
// get caret position in composition string
g_IMECursorBytes = _ImmGetCompositionString(himc, GCS_CURSORPOS, NULL, 0);
g_IMECursorChars = GetCharCountFromBytes(g_szCompositionString, g_IMECursorBytes);
if (g_dwIMELevel == 3)
{
// send composition string via WM_CHAR
_SendCompString();
// move caret to appropreate location
len = GetCharCount(g_szCompositionString + g_IMECursorBytes);
SendControlKeys(VK_LEFT, len);
}
}
_ImmReleaseContext(hWnd, himc);
}
break;
case WM_IME_ENDCOMPOSITION:
CancelCompString(g_hwndCurr);
InitCompStringData();
break;
case WM_IME_NOTIFY:
switch (wParam)
{
case IMN_SETCONVERSIONMODE:
{
// Disable CHT IME software keyboard.
static bool bNoReentrance = false;
if (LANG_CHT == GETLANG() && !bNoReentrance)
{
bNoReentrance = true;
DWORD dwConvMode, dwSentMode;
_ImmGetConversionStatus( g_himcOrg, &dwConvMode, &dwSentMode );
const DWORD dwFlag = IME_CMODE_SOFTKBD | IME_CMODE_SYMBOL;
if ( dwConvMode & dwFlag )
_ImmSetConversionStatus( g_himcOrg, dwConvMode & ~dwFlag, dwSentMode );
}
bNoReentrance = false;
}
// fall through
case IMN_SETOPENSTATUS:
if (g_bUILessMode)
break;
CheckToggleState();
break;
case IMN_OPENCANDIDATE:
case IMN_CHANGECANDIDATE:
if ( g_bUILessMode )
{
break;
}
{
g_bCandList = true;
*trapped = true;
if (NULL == (himc = _ImmGetContext(hWnd)))
break;
LPCANDIDATELIST lpCandList;
DWORD dwIndex, dwBufLen;
g_bReadingWindow = false;
dwIndex = 0;
dwBufLen = _GetCandidateList( himc, dwIndex, &lpCandList );
if ( dwBufLen )
{
g_dwSelection = lpCandList->dwSelection;
g_dwCount = lpCandList->dwCount;
int startOfPage = 0;
if (GETLANG() == LANG_CHS && GetImeId())
{
// MSPY (CHS IME) has variable number of candidates in candidate window
// find where current page starts, and the size of current page
const int maxCandChar = 18 * (3 - sizeof(TCHAR));
UINT cChars = 0;
UINT i;
for (i = 0; i < g_dwCount; i++)
{
UINT uLen = lstrlen(
(LPTSTR)((DWORD)lpCandList + lpCandList->dwOffset[i])) + (3 - sizeof(TCHAR));
if (uLen + cChars > maxCandChar)
{
if (i > g_dwSelection)
{
break;
}
startOfPage = i;
cChars = uLen;
}
else
{
cChars += uLen;
}
}
g_uCandPageSize = i - startOfPage;
}
else
{
g_uCandPageSize = min( lpCandList->dwPageSize, MAX_CANDLIST );
startOfPage = g_bUILessMode ? lpCandList->dwPageStart : ( g_dwSelection / g_uCandPageSize ) * g_uCandPageSize;
}
g_dwSelection = ( GETLANG() == LANG_CHS && !GetImeId() ) ? (DWORD)-1
: g_dwSelection - startOfPage;
memset(&g_szCandidate, 0, sizeof(g_szCandidate));
for (UINT i = startOfPage, j = 0;
(DWORD)i < lpCandList->dwCount && j < g_uCandPageSize;
i++, j++)
{
ComposeCandidateLine( j,
(LPTSTR)( (DWORD)lpCandList + lpCandList->dwOffset[i] ) );
}
ImeUiCallback_Free( (HANDLE)lpCandList );
_ImmReleaseContext(hWnd, himc);
// don't display selection in candidate list in case of Korean and old Chinese IME.
if ( GETPRIMLANG() == LANG_KOREAN ||
GETLANG() == LANG_CHT && !GetImeId() )
g_dwSelection = (DWORD)-1;
}
break;
}
case IMN_CLOSECANDIDATE:
if ( g_bUILessMode )
{
break;
}
CloseCandidateList();
*trapped = true;
break;
// Jun.16,2000 05:21 by yutaka.
case IMN_PRIVATE:
{
if ( !g_bCandList )
{
GetReadingString( hWnd );
}
// Trap some messages to hide reading window
DWORD dwId = GetImeId();
switch (dwId) {
case IMEID_CHT_VER42:
case IMEID_CHT_VER43:
case IMEID_CHT_VER44:
case IMEID_CHS_VER41:
case IMEID_CHS_VER42:
if ((lParam == 1) || (lParam == 2))
{
*trapped = true;
}
break;
case IMEID_CHT_VER50:
case IMEID_CHT_VER51:
case IMEID_CHT_VER52:
case IMEID_CHT_VER60:
case IMEID_CHS_VER53:
if ((lParam == 16) || (lParam == 17) || (lParam == 26) || (lParam == 27) || (lParam == 28))
{
*trapped = true;
}
break;
}
}
break;
default:
*trapped = true;
break;
}
break;
// fix for #15386 - When Text Service Framework is installed in Win2K, Alt+Shift and Ctrl+Shift combination (to switch
// input locale / keyboard layout) doesn't send WM_KEYUP message for the key that is released first. We need to check
// if these keys are actually up whenever we receive key up message for other keys.
case WM_KEYUP:
case WM_SYSKEYUP:
if ( !( lAlt & 0x80000000 ) && wParam != VK_MENU && ( GetAsyncKeyState( VK_MENU ) & 0x8000 ) == 0 )
{
PostMessageA( GetFocus(), WM_KEYUP, (WPARAM)VK_MENU, ( lAlt & 0x01ff0000 ) | 0xC0000001 );
}
else if ( !( lCtrl & 0x80000000 ) && wParam != VK_CONTROL && ( GetAsyncKeyState( VK_CONTROL ) & 0x8000 ) == 0 )
{
PostMessageA( GetFocus(), WM_KEYUP, (WPARAM)VK_CONTROL, ( lCtrl & 0x01ff0000 ) | 0xC0000001 );
}
else if ( !( lShift & 0x80000000 ) && wParam != VK_SHIFT && ( GetAsyncKeyState( VK_SHIFT ) & 0x8000 ) == 0 )
{
PostMessageA( GetFocus(), WM_KEYUP, (WPARAM)VK_SHIFT, ( lShift & 0x01ff0000 ) | 0xC0000001 );
}
// fall through WM_KEYDOWN / WM_SYSKEYDOWN
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
switch ( wParam )
{
case VK_MENU:
lAlt = lParam;
break;
case VK_SHIFT:
lShift = lParam;
break;
case VK_CONTROL:
lCtrl = lParam;
break;
}
}
break;
}
return 0;
}
void ImeUi_SetCaretPosition(UINT x, UINT y)
{
if (!g_bInitialized)
return;
g_CaretInfo.caretX = x;
g_CaretInfo.caretY = y;
}
void ImeUi_SetCompStringAppearance( CImeUiFont_Base* pFont, DWORD color, const RECT* prc )
{
if (!g_bInitialized)
return;
g_CaretInfo.pFont = pFont;
g_CaretInfo.margins = *prc;
if (0 == gSkinIME.candColorText)
g_CaretInfo.colorCand = color;
else
g_CaretInfo.colorCand = gSkinIME.candColorText;
if (0 == gSkinIME.compColorText)
g_CaretInfo.colorComp = color;
else
g_CaretInfo.colorComp = gSkinIME.compColorText;
}
void ImeUi_SetState( DWORD dwState )
{
if (!g_bInitialized)
return;
HIMC himc;
if ( dwState == IMEUI_STATE_ON )
{
ImeUi_EnableIme( true );
}
if (NULL != (himc = _ImmGetContext(g_hwndCurr)))
{
if (g_bDisableImeCompletely)
dwState = IMEUI_STATE_OFF;
bool bOn = dwState == IMEUI_STATE_ON; // for non-Chinese IME
switch ( GETPRIMLANG() ) {
case LANG_CHINESE:
{
// toggle Chinese IME
DWORD dwId;
DWORD dwConvMode = 0, dwSentMode = 0;
if ( ( g_bChineseIME && dwState == IMEUI_STATE_OFF ) || ( !g_bChineseIME && dwState != IMEUI_STATE_OFF ) )
{
_ImmSimulateHotKey( g_hwndCurr, IME_THOTKEY_IME_NONIME_TOGGLE );
_PumpMessage();
}
if ( dwState != IMEUI_STATE_OFF )
{
dwId = GetImeId();
if ( dwId )
{
_ImmGetConversionStatus( himc, &dwConvMode, &dwSentMode );
dwConvMode = ( dwState == IMEUI_STATE_ON )
? ( dwConvMode | IME_CMODE_NATIVE )
: ( dwConvMode & ~IME_CMODE_NATIVE );
_ImmSetConversionStatus( himc, dwConvMode, dwSentMode );
}
}
break;
}
case LANG_KOREAN:
// toggle Korean IME
if ( ( bOn && g_dwState != IMEUI_STATE_ON ) || ( !bOn && g_dwState == IMEUI_STATE_ON ) )
{
_ImmSimulateHotKey(g_hwndCurr, IME_KHOTKEY_ENGLISH);
}
break;
case LANG_JAPANESE:
_ImmSetOpenStatus(himc, bOn);
break;
}
_ImmReleaseContext(g_hwndCurr, himc);
CheckToggleState();
}
}
DWORD ImeUi_GetState()
{
if (!g_bInitialized)
return IMEUI_STATE_OFF;
CheckToggleState();
return g_dwState;
}
void ImeUi_EnableIme( bool bEnable )
{
if (!g_bInitialized || !g_hwndCurr)
return;
if (g_bDisableImeCompletely)
bEnable = false;
if (g_hwndCurr == g_hwndMain)
{
HIMC himcDbg;
himcDbg = _ImmAssociateContext( g_hwndCurr, bEnable? g_himcOrg : NULL );
}
g_bImeEnabled = bEnable;
if ( bEnable )
{
CheckToggleState();
}
CTsfUiLessMode::EnableUiUpdates(bEnable);
}
bool ImeUi_IsEnabled( void )
{
return g_bImeEnabled;
}
bool ImeUi_Initialize( HWND hwnd, bool bDisable )
{
if ( g_bInitialized )
{
return true;
}
g_hwndMain = hwnd;
g_disableCicero.Initialize();
bool bUnicodeImm = true;
g_hImmDll = LoadLibraryA( "imm32.dll" );
g_bDisableImeCompletely = false;
if ( g_hImmDll )
{
_ImmLockIMC = (LPINPUTCONTEXT2 (WINAPI*)(HIMC hIMC)) GetProcAddress(g_hImmDll, "ImmLockIMC");
_ImmUnlockIMC = (BOOL (WINAPI*)(HIMC hIMC)) GetProcAddress(g_hImmDll, "ImmUnlockIMC");
_ImmLockIMCC = (LPVOID (WINAPI*)(HIMCC hIMCC)) GetProcAddress(g_hImmDll, "ImmLockIMCC");
_ImmUnlockIMCC = (BOOL (WINAPI*)(HIMCC hIMCC)) GetProcAddress(g_hImmDll, "ImmUnlockIMCC");
BOOL (WINAPI* _ImmDisableTextFrameService)(DWORD) = (BOOL (WINAPI*)(DWORD))GetProcAddress(g_hImmDll, "ImmDisableTextFrameService");
if ( _ImmDisableTextFrameService )
{
_ImmDisableTextFrameService( (DWORD)-1 );
}
}
else
{
g_bDisableImeCompletely = true;
return false;
}
#ifdef UNICODE
if ( bUnicodeImm )
{
_ImmGetCompositionString = ImmGetCompositionStringW;
_ImmGetCandidateList = ImmGetCandidateListW;
_GetCandidateList = GetCandidateList;
}
else
{
_ImmGetCandidateList = ImmGetCandidateListA;
_ImmGetCompositionString = AW_ImmGetCompositionString;
_GetCandidateList = AW_GetCandidateList;
}
#else
if ( bUnicodeImm )
{
_ImmGetCompositionString = WA_ImmGetCompositionString;
_ImmGetCandidateList = ImmGetCandidateListA;
_GetCandidateList = WA_GetCandidateList;
}
else
{
_ImmGetCompositionString = ImmGetCompositionStringA;
_ImmGetCandidateList = ImmGetCandidateListA;
_GetCandidateList = GetCandidateList;
}
#endif
// There are the following combinations of code config, window type, and the method of sending characters.
// Wnd: Unicode, Code: Unicode, Method: SendMessageW (SendMessageW must be supported since RegisterClassW is successful)
// Wnd: non Uni, Code: Unicode, Method: AW_SendCompString (Send characters in multibyte after W->A conversion)
// Wnd: Unicode, Code: non Uni, Method: SendMessageA (System does A->W conversion) - possible, but unlikely to be used.
// Wnd: non Uni, Code: non Uni, Method: SendMessageA
#ifdef UNICODE
if ( !IsWindowUnicode( hwnd ) )
{
_SendCompString = AW_SendCompString;
}
else
#endif
{
_SendCompString = SendCompString;
#ifdef UNICODE
_SendMessage = SendMessageW;
#endif
}
// turn init flag on so that subsequent calls to ImeUi functions work.
g_bInitialized = true;
ImeUi_SetWindow( g_hwndMain );
g_himcOrg = _ImmGetContext( g_hwndMain );
_ImmReleaseContext( g_hwndMain, g_himcOrg );
if ( !g_himcOrg )
{
bDisable = true;
}
// the following pointers to function has to be initialized before this function is called.
if ( bDisable ||
!ImeUiCallback_Malloc ||
!ImeUiCallback_Free
)
{
g_bDisableImeCompletely = true;
ImeUi_EnableIme(false);
g_bInitialized = bDisable;
return false;
}
g_uCaretBlinkTime = GetCaretBlinkTime();
#ifndef UNICODE
// Check if system is SBCS system
CPINFO cpi;
BOOL bRc = GetCPInfo(CP_ACP, &cpi);
if (bRc) {
if (cpi.MaxCharSize == 1)
{
g_bDisableImeCompletely = true; // SBCS system. Disable IME.
}
}
#endif
g_CaretInfo.caretX = 0;
g_CaretInfo.caretY = 0;
g_CaretInfo.pFont = 0;
g_CaretInfo.colorComp = 0;
g_CaretInfo.colorCand = 0;
g_CaretInfo.margins.left = 0;
g_CaretInfo.margins.right = 640;
g_CaretInfo.margins.top = 0;
g_CaretInfo.margins.bottom = 480;
CheckInputLocale();
OnInputLangChangeWorker();
ImeUi_SetSupportLevel(2);
// SetupTSFSinks has to be called before CheckToggleState to make it work correctly.
g_bUILessMode = CTsfUiLessMode::SetupSinks() != FALSE;
CheckToggleState();
if ( g_bUILessMode )
{
g_bChineseIME = ( GETPRIMLANG() == LANG_CHINESE ) && CTsfUiLessMode::CurrentInputLocaleIsIme();
CTsfUiLessMode::UpdateImeState();
}
ImeUi_EnableIme(false);
return true;
}
void ImeUi_Uninitialize()
{
if ( !g_bInitialized )
{
return;
}
CTsfUiLessMode::ReleaseSinks();
if ( g_hwndMain )
{
ImmAssociateContext(g_hwndMain, g_himcOrg);
}
g_hwndMain = NULL;
g_himcOrg = NULL;
if ( g_hImmDll )
{
FreeLibrary(g_hImmDll);
g_hImmDll = NULL;
}
g_disableCicero.Uninitialize();
g_bInitialized = false;
}
//
// GetImeId( UINT uIndex )
// returns
// returned value:
// 0: In the following cases
// - Non Chinese IME input locale
// - Older Chinese IME
// - Other error cases
//
// Othewise:
// When uIndex is 0 (default)
// bit 31-24: Major version
// bit 23-16: Minor version
// bit 15-0: Language ID
// When uIndex is 1
// pVerFixedInfo->dwFileVersionLS
//
// Use IMEID_VER and IMEID_LANG macro to extract version and language information.
//
static DWORD GetImeId( UINT uIndex )
{
static HKL hklPrev = 0;
static DWORD dwRet[2] = {0, 0};
DWORD dwVerSize;
DWORD dwVerHandle;
LPVOID lpVerBuffer;
LPVOID lpVerData;
UINT cbVerData;
char szTmp[1024];
if ( uIndex >= sizeof( dwRet ) / sizeof( dwRet[0] ) )
return 0;
HKL kl = g_hklCurrent;
if (hklPrev == kl)
{
return dwRet[uIndex];
}
hklPrev = kl;
DWORD dwLang = static_cast<DWORD>(g_hklCurrent);
if ( g_bUILessMode && GETLANG() == LANG_CHT )
{
// In case of Vista, artificial value is returned so that it's not considered as older IME.
dwRet[0] = IMEID_CHT_VER_VISTA;
dwRet[1] = 0;
return dwRet[0];
}
if ( kl != _CHT_HKL_NEW_PHONETIC && kl != _CHT_HKL_NEW_CHANG_JIE
&& kl != _CHT_HKL_NEW_QUICK && kl != _CHT_HKL_HK_CANTONESE && kl != _CHS_HKL )
{
goto error;
}
if ( _ImmGetIMEFileNameA( kl, szTmp, sizeof( szTmp ) - 1 ) <= 0 )
{
goto error;
}
if ( !_GetReadingString ) // IME that doesn't implement private API
{
#define LCID_INVARIANT MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), SORT_DEFAULT)
if ( ( CompareStringA( LCID_INVARIANT, NORM_IGNORECASE, szTmp, -1, _CHT_IMEFILENAME, -1 ) != 2 )
&& ( CompareStringA( LCID_INVARIANT, NORM_IGNORECASE, szTmp, -1, _CHT_IMEFILENAME2, -1 ) != 2 )
&& ( CompareStringA( LCID_INVARIANT, NORM_IGNORECASE, szTmp, -1, _CHT_IMEFILENAME3, -1 ) != 2 )
&& ( CompareStringA( LCID_INVARIANT, NORM_IGNORECASE, szTmp, -1, _CHS_IMEFILENAME, -1 ) != 2 )
&& ( CompareStringA( LCID_INVARIANT, NORM_IGNORECASE, szTmp, -1, _CHS_IMEFILENAME2, -1 ) != 2 )
)
{
goto error;
}
}
dwVerSize = GetFileVersionInfoSizeA( szTmp, &dwVerHandle );
if ( dwVerSize )
{
lpVerBuffer = (LPVOID) ImeUiCallback_Malloc(dwVerSize);
if ( lpVerBuffer )
{
if ( GetFileVersionInfoA( szTmp, dwVerHandle, dwVerSize, lpVerBuffer ) )
{
if ( VerQueryValueA( lpVerBuffer, "\\", &lpVerData, &cbVerData ) )
{
#define pVerFixedInfo ((VS_FIXEDFILEINFO FAR*)lpVerData)
DWORD dwVer = pVerFixedInfo->dwFileVersionMS;
dwVer = ( dwVer & 0x00ff0000 ) << 8 | ( dwVer & 0x000000ff ) << 16;
if ( _GetReadingString ||
dwLang == LANG_CHT && (
dwVer == MAKEIMEVERSION(4, 2) ||
dwVer == MAKEIMEVERSION(4, 3) ||
dwVer == MAKEIMEVERSION(4, 4) ||
dwVer == MAKEIMEVERSION(5, 0) ||
dwVer == MAKEIMEVERSION(5, 1) ||
dwVer == MAKEIMEVERSION(5, 2) ||
dwVer == MAKEIMEVERSION(6, 0) )
||
dwLang == LANG_CHS && (
dwVer == MAKEIMEVERSION(4, 1) ||
dwVer == MAKEIMEVERSION(4, 2) ||
dwVer == MAKEIMEVERSION(5, 3) ) )
{
dwRet[0] = dwVer | dwLang;
dwRet[1] = pVerFixedInfo->dwFileVersionLS;
ImeUiCallback_Free(lpVerBuffer);
return dwRet[0];
}
#undef pVerFixedInfo
}
}
}
ImeUiCallback_Free(lpVerBuffer);
}
// The flow comes here in the following conditions
// - Non Chinese IME input locale
// - Older Chinese IME
// - Other error cases
error:
dwRet[0] = dwRet[1] = 0;
return dwRet[uIndex];
}
static void GetReadingString(HWND hWnd)
{
if ( g_bUILessMode )
{
return;
}
DWORD dwId = GetImeId();
if ( ! dwId )
{
return;
}
HIMC himc;
himc = _ImmGetContext(hWnd);
if ( !himc )
return;
DWORD dwlen = 0;
DWORD dwerr = 0;
WCHAR wzBuf[16]; // We believe 16 wchars are big enough to hold reading string after having discussion with CHT IME team.
WCHAR *wstr = wzBuf;
bool unicode = FALSE;
LPINPUTCONTEXT2 lpIMC = NULL;
if ( _GetReadingString )
{
BOOL bVertical;
UINT uMaxUiLen;
dwlen = _GetReadingString( himc, 0, NULL, (PINT)&dwerr, &bVertical, &uMaxUiLen);
if ( dwlen )
{
if ( dwlen > COUNTOF(wzBuf) )
{
dwlen = COUNTOF(wzBuf);
}
dwlen = _GetReadingString( himc, dwlen, wstr, (PINT)&dwerr, &bVertical, &uMaxUiLen);
}
g_bHorizontalReading = bVertical == 0;
unicode = true;
}
else // IMEs that doesn't implement Reading String API
{
lpIMC = _ImmLockIMC(himc);
// *** hacking code from Michael Yang ***
LPBYTE p = 0;
switch ( dwId ) {
case IMEID_CHT_VER42: // New(Phonetic/ChanJie)IME98 : 4.2.x.x // Win98
case IMEID_CHT_VER43: // New(Phonetic/ChanJie)IME98a : 4.3.x.x // WinMe, Win2k
case IMEID_CHT_VER44: // New ChanJie IME98b : 4.4.x.x // WinXP
p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 24);
if (!p) break;
dwlen = *(DWORD *)(p + 7*4 + 32*4); //m_dwInputReadStrLen
dwerr = *(DWORD *)(p + 8*4 + 32*4); //m_dwErrorReadStrStart
wstr = (WCHAR *)(p + 56);
unicode = TRUE;
break;
case IMEID_CHT_VER50: // 5.0.x.x // WinME
p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 3*4); // PCKeyCtrlManager
if (!p) break;
p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4 + 4*2 ); // = PCReading = &STypingInfo
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16); //m_dwDisplayStringLength;
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 + 1*4); //m_dwDisplayErrorStart;
wstr = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4);
unicode = FALSE;
break;
case IMEID_CHT_VER51: // 5.1.x.x // IME2002(w/OfficeXP)
case IMEID_CHT_VER52: // 5.2.x.x // (w/whistler)
case IMEID_CHS_VER53: // 5.3.x.x // SCIME2k or MSPY3 (w/OfficeXP and Whistler)
p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 4); // PCKeyCtrlManager
if (!p) break;
p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4); // = PCReading = &STypingInfo
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2); //m_dwDisplayStringLength;
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2 + 1*4); //m_dwDisplayErrorStart;
wstr = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4);
unicode = TRUE;
break;
// the code tested only with Win 98 SE (MSPY 1.5/ ver 4.1.0.21)
case IMEID_CHS_VER41:
{
int offset;
offset = ( GetImeId( 1 ) >= 0x00000002 ) ? 8 : 7;
p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + offset * 4);
if (!p) break;
dwlen = *(DWORD *)(p + 7*4 + 16*2*4);
dwerr = *(DWORD *)(p + 8*4 + 16*2*4);
dwerr = min(dwerr, dwlen);
wstr = (WCHAR *)(p + 6*4 + 16*2*1);
unicode = TRUE;
break;
}
case IMEID_CHS_VER42: // 4.2.x.x // SCIME98 or MSPY2 (w/Office2k, Win2k, WinME, etc)
{
int nTcharSize = sizeof(WCHAR);
p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIMC->hPrivate) + 1*4 + 1*4 + 6*4); // = PCReading = &STypintInfo
if (!p) break;
dwlen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize); //m_dwDisplayStringLength;
dwerr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize + 1*4); //m_dwDisplayErrorStart;
wstr = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4); //m_tszDisplayString
unicode = TRUE;
}
} // switch
g_szCandidate[0][0] = 0;
g_szCandidate[1][0] = 0;
g_szCandidate[2][0] = 0;
g_szCandidate[3][0] = 0;
}
g_dwCount = dwlen;
g_dwSelection = (DWORD)-1; // do not select any char
if ( unicode )
{
int i;
for ( i=0; (DWORD)i < dwlen ; i++ ) // dwlen > 0, if known IME : yutakah
{
if ( dwerr<=(DWORD)i && g_dwSelection==(DWORD)-1 ){ // select error char
g_dwSelection = i;
}
#ifdef UNICODE
g_szCandidate[i][0] = wstr[i];
g_szCandidate[i][1] = 0;
#else
char mbc[3];
mbc[1] = 0;
mbc[2] = 0;
WideCharToMultiByte(g_uCodePage, 0, wstr + i, 1, mbc, sizeof(mbc), NULL, NULL);
g_szCandidate[i][0] = mbc[0];
g_szCandidate[i][1] = mbc[1];
g_szCandidate[i][2] = 0;
#endif
}
g_szCandidate[i][0] = 0;
}
else
{
char *p = (char *)wstr;
int i, j;
for ( i=0, j=0; (DWORD)i < dwlen ; i++,j++ ) // dwlen > 0, if known IME : yutakah
{
if ( dwerr<=(DWORD)i && g_dwSelection==(DWORD)-1 ){
g_dwSelection = (DWORD)j;
}
#ifdef UNICODE
MultiByteToWideChar( g_uCodePage, 0, p + i, 1 + ( _IsLeadByte( p[i] ) ? 1 : 0 ),
g_szCandidate[j], 1 );
if ( _IsLeadByte( p[i] ) )
{
i++;
}
#else
g_szCandidate[j][0] = p[i];
g_szCandidate[j][1] = 0;
g_szCandidate[j][2] = 0;
if (_IsLeadByte(p[i]))
{
i++;
g_szCandidate[j][1] = p[i];
}
#endif
}
g_szCandidate[j][0] = 0;
g_dwCount = j;
}
if ( !_GetReadingString )
{
_ImmUnlockIMCC( lpIMC->hPrivate );
_ImmUnlockIMC( himc );
GetReadingWindowOrientation( dwId );
}
_ImmReleaseContext(hWnd, himc);
g_bReadingWindow = true;
if (g_bHorizontalReading) {
g_iReadingError = -1;
g_szReadingString[0] = 0;
for (UINT i = 0; i < g_dwCount; i++) {
if (g_dwSelection == (DWORD)i)
g_iReadingError = lstrlen(g_szReadingString);
LPCTSTR pszTmp = g_szCandidate[i];
wcscat_s(g_szReadingString, COUNTOF(g_szReadingString), pszTmp);
}
}
g_uCandPageSize = MAX_CANDLIST;
}
static struct {
bool m_bCtrl;
bool m_bShift;
bool m_bAlt;
UINT m_uVk;
}
aHotKeys[] = {
false, false, false, VK_APPS,
true, false, false, '8',
true, false, false, 'Y',
true, false, false, VK_DELETE,
true, false, false, VK_F7,
true, false, false, VK_F9,
true, false, false, VK_F10,
true, false, false, VK_F11,
true, false, false, VK_F12,
false, false, false, VK_F2,
false, false, false, VK_F3,
false, false, false, VK_F4,
false, false, false, VK_F5,
false, false, false, VK_F10,
false, true, false, VK_F6,
false, true, false, VK_F7,
false, true, false, VK_F8,
true, true, false, VK_F10,
true, true, false, VK_F11,
true, false, false, VK_CONVERT,
true, false, false, VK_SPACE,
true, false, true, 0xbc, // Alt + Ctrl + ',': SW keyboard for Trad. Chinese IME
true, false, false, VK_TAB, // ATOK2005's Ctrl+TAB
};
//
// Ignores specific keys when IME is on. Returns true if the message is a hot key to ignore.
// - Caller doesn't have to check whether IME is on.
// - This function must be called before TranslateMessage() is called.
//
bool ImeUi_IgnoreHotKey( const MSG* pmsg )
{
if ( !g_bInitialized || !pmsg )
return false;
if (pmsg->wParam == VK_PROCESSKEY && (pmsg->message == WM_KEYDOWN || pmsg->message == WM_SYSKEYDOWN))
{
bool bCtrl, bShift, bAlt;
UINT uVkReal = _ImmGetVirtualKey(pmsg->hwnd);
// special case #1 - VK_JUNJA toggles half/full width input mode in Korean IME.
// This VK (sent by Alt+'=' combo) is ignored regardless of the modifier state.
if ( uVkReal == VK_JUNJA )
{
return true;
}
// special case #2 - disable right arrow key that switches the candidate list to expanded mode in CHT IME.
if ( uVkReal == VK_RIGHT && g_bCandList && GETLANG() == LANG_CHT)
{
return true;
}
#ifndef ENABLE_HANJA_KEY
// special case #3 - we disable VK_HANJA key because 1. some Korean fonts don't Hanja and 2. to reduce testing cost.
if ( uVkReal == VK_HANJA && GETPRIMLANG() == LANG_KOREAN )
{
return true;
}
#endif
bCtrl = (GetKeyState(VK_CONTROL) & 0x8000) ? true : false;
bShift = (GetKeyState(VK_SHIFT) & 0x8000) ? true : false;
bAlt = (GetKeyState(VK_MENU) & 0x8000) ? true : false;
for (int i = 0; i < COUNTOF(aHotKeys); i++) {
if (aHotKeys[i].m_bCtrl == bCtrl &&
aHotKeys[i].m_bShift == bShift &&
aHotKeys[i].m_bAlt == bAlt &&
aHotKeys[i].m_uVk == uVkReal)
return true;
}
}
return false;
}
void ImeUi_FinalizeString(bool bSend)
{
HIMC himc;
static bool bProcessing = false; // to avoid infinite recursion
if ( !g_bInitialized || bProcessing || NULL == ( himc = _ImmGetContext( g_hwndCurr ) ) )
return;
bProcessing = true;
if (g_dwIMELevel == 2 && bSend)
{
// Send composition string to app.
LONG lRet = lstrlen( g_szCompositionString );
assert( lRet >= 2);
// In case of CHT IME, don't send the trailing double byte space, if it exists.
#ifdef UNICODE
if ( GETLANG() == LANG_CHT && (lRet >= 1)
&& g_szCompositionString[lRet - 1] == 0x3000 )
{
lRet--;
}
#else
if ( GETLANG() == LANG_CHT && (lRet >= 2)
&& (BYTE)( g_szCompositionString[lRet - 2] ) == 0xa1
&& (BYTE)( g_szCompositionString[lRet - 1] ) == 0x40 )
{
lRet -= 2;
}
#endif
_SendCompString();
}
InitCompStringData();
// clear composition string in IME
_ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
if (g_bUILessMode)
{
// For some reason ImmNotifyIME doesn't work on DaYi and Array CHT IMEs. Cancel composition string by setting zero-length string.
ImmSetCompositionString(himc, SCS_SETSTR, TEXT(""), sizeof(TCHAR), TEXT(""), sizeof(TCHAR));
}
// the following line is necessary as Korean IME doesn't close cand list when comp string is cancelled.
_ImmNotifyIME( himc, NI_CLOSECANDIDATE, 0, 0 );
_ImmReleaseContext(g_hwndCurr, himc);
// Zooty2 RAID #4759: Sometimes application doesn't receive IMN_CLOSECANDIDATE on Alt+Tab
// So the same code for IMN_CLOSECANDIDATE is replicated here.
CloseCandidateList();
bProcessing = false;
return;
}
static void SetCompStringColor()
{
// change color setting according to current IME level.
DWORD dwTranslucency = (g_dwIMELevel == 2) ? 0xff000000 : ((DWORD)gSkinIME.compTranslucence << 24);
gSkinCompStr.colorInput = dwTranslucency | gSkinIME.compColorInput;
gSkinCompStr.colorTargetConv = dwTranslucency | gSkinIME.compColorTargetConv;
gSkinCompStr.colorConverted = dwTranslucency | gSkinIME.compColorConverted;
gSkinCompStr.colorTargetNotConv = dwTranslucency | gSkinIME.compColorTargetNotConv;
gSkinCompStr.colorInputErr = dwTranslucency | gSkinIME.compColorInputErr;
}
static void SetSupportLevel( DWORD dwImeLevel )
{
if ( dwImeLevel < 2 || 3 < dwImeLevel )
return;
if ( GETPRIMLANG() == LANG_KOREAN )
{
dwImeLevel = 3;
}
g_dwIMELevel = dwImeLevel;
// cancel current composition string.
ImeUi_FinalizeString();
SetCompStringColor();
}
void ImeUi_SetSupportLevel(DWORD dwImeLevel)
{
if ( !g_bInitialized )
return;
g_dwIMELevelSaved = dwImeLevel;
SetSupportLevel( dwImeLevel );
}
void ImeUi_SetAppearance( const IMEUI_APPEARANCE* pia )
{
if ( !g_bInitialized || NULL == pia )
return;
gSkinIME = *pia;
gSkinIME.symbolColor &= 0xffffff; // mask translucency
gSkinIME.symbolColorOff &= 0xffffff; // mask translucency
gSkinIME.symbolColorText &= 0xffffff; // mask translucency
gSkinIME.compColorInput &= 0xffffff; // mask translucency
gSkinIME.compColorTargetConv &= 0xffffff; // mask translucency
gSkinIME.compColorConverted &= 0xffffff; // mask translucency
gSkinIME.compColorTargetNotConv &= 0xffffff; // mask translucency
gSkinIME.compColorInputErr &= 0xffffff; // mask translucency
SetCompStringColor();
}
void ImeUi_GetAppearance( IMEUI_APPEARANCE* pia )
{
if ( g_bInitialized && pia )
{
*pia = gSkinIME;
}
}
static void CheckToggleState()
{
CheckInputLocale();
// In Vista, we have to use TSF since few IMM functions don't work as expected.
// WARNING: Because of timing, g_dwState and g_bChineseIME may not be updated
// immediately after the change on IME states by user.
if ( g_bUILessMode )
{
return;
}
bool bIme = _ImmIsIME( g_hklCurrent ) != 0
&& ( ( 0xF0000000 & static_cast<DWORD>(g_hklCurrent) ) == 0xE0000000 ); // Hack to detect IME correctly. When IME is running as TIP, ImmIsIME() returns true for CHT US keyboard.
g_bChineseIME = ( GETPRIMLANG() == LANG_CHINESE ) && bIme;
HIMC himc;
if (NULL != (himc = _ImmGetContext(g_hwndCurr))) {
if (g_bChineseIME) {
DWORD dwConvMode, dwSentMode;
_ImmGetConversionStatus(himc, &dwConvMode, &dwSentMode);
g_dwState = ( dwConvMode & IME_CMODE_NATIVE ) ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH;
}
else
{
g_dwState = ( bIme && _ImmGetOpenStatus( himc ) != 0 ) ? IMEUI_STATE_ON : IMEUI_STATE_OFF;
}
_ImmReleaseContext(g_hwndCurr, himc);
}
else
g_dwState = IMEUI_STATE_OFF;
}
void ImeUi_SetInsertMode(bool bInsert)
{
if ( !g_bInitialized )
return;
g_bInsertMode = bInsert;
}
bool ImeUi_GetCaretStatus()
{
return !g_bInitialized || !g_szCompositionString[0];
}
void ImeUi_SetScreenDimension(UINT width, UINT height)
{
if ( !g_bInitialized )
return;
g_screenWidth = width;
g_screenHeight = height;
}
// this function is used only in brief time in CHT IME handling, so accelerator isn't processed.
static void _PumpMessage()
{
MSG msg;
while (PeekMessageA(&msg, NULL, 0, 0, PM_NOREMOVE)) {
if (!GetMessageA(&msg, NULL, 0, 0)) {
PostQuitMessage(msg.wParam);
return;
}
// if (0 == TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) {
TranslateMessage(&msg);
DispatchMessageA(&msg);
// }
}
}
static void GetReadingWindowOrientation( DWORD dwId )
{
g_bHorizontalReading = ( g_hklCurrent == _CHS_HKL ) || ( g_hklCurrent == _CHT_HKL_NEW_CHANG_JIE ) || ( dwId == 0 );
if (!g_bHorizontalReading && IMEID_LANG( dwId ) == LANG_CHT )
{
char szRegPath[MAX_PATH];
HKEY hkey;
DWORD dwVer = IMEID_VER( dwId );
strcpy_s(szRegPath, COUNTOF(szRegPath), "software\\microsoft\\windows\\currentversion\\");
strcat_s(szRegPath, COUNTOF(szRegPath), (dwVer >= MAKEIMEVERSION(5, 1)) ? "MSTCIPH" : "TINTLGNT");
LONG lRc = RegOpenKeyExA(HKEY_CURRENT_USER, szRegPath, 0, KEY_READ, &hkey);
if (lRc == ERROR_SUCCESS) {
DWORD dwSize = sizeof(DWORD), dwMapping, dwType;
lRc = RegQueryValueExA(hkey, "keyboard mapping", NULL, &dwType, (PBYTE)&dwMapping, &dwSize);
if (lRc == ERROR_SUCCESS) {
if (
( dwVer <= MAKEIMEVERSION( 5, 0 ) &&
((BYTE)dwMapping == 0x22 || (BYTE)dwMapping == 0x23)
) ||
( ( dwVer == MAKEIMEVERSION( 5, 1 ) || dwVer == MAKEIMEVERSION( 5, 2 ) ) &&
((BYTE)dwMapping >= 0x22 && (BYTE)dwMapping <= 0x24)
)
)
{
g_bHorizontalReading = true;
}
}
RegCloseKey( hkey );
}
}
}
void ImeUi_ToggleLanguageBar(BOOL bRestore)
{
static BOOL prevRestore = TRUE;
bool bCheck = ( prevRestore == TRUE || bRestore == TRUE );
prevRestore = bRestore;
if ( !bCheck )
return;
static int iShowStatusWindow = -1;
if ( iShowStatusWindow == -1 )
{
iShowStatusWindow = 1;
}
HWND hwndImeDef = _ImmGetDefaultIMEWnd(g_hwndCurr);
if ( hwndImeDef && bRestore && iShowStatusWindow )
SendMessageA(hwndImeDef, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
HRESULT hr;
hr = CoInitialize(NULL);
if (SUCCEEDED(hr))
{
ITfLangBarMgr* plbm = NULL;
hr = CoCreateInstance(CLSID_TF_LangBarMgr, NULL, CLSCTX_INPROC_SERVER, __uuidof(ITfLangBarMgr), (void**)&plbm);
if (SUCCEEDED(hr) && plbm)
{
DWORD dwCur;
ULONG uRc;
if (SUCCEEDED(hr))
{
if (bRestore)
{
if (g_dwPrevFloat)
hr = plbm->ShowFloating(g_dwPrevFloat);
}
else
{
hr = plbm->GetShowFloatingStatus(&dwCur);
if (SUCCEEDED(hr))
g_dwPrevFloat = dwCur;
if ( !( g_dwPrevFloat & TF_SFT_DESKBAND ) )
{
hr = plbm->ShowFloating(TF_SFT_HIDDEN);
}
}
}
uRc = plbm->Release();
}
CoUninitialize();
}
if ( hwndImeDef && !bRestore )
{
// The following OPENSTATUSWINDOW is required to hide ATOK16 toolbar (FS9:#7546)
SendMessageA(hwndImeDef, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
SendMessageA(hwndImeDef, WM_IME_CONTROL, IMC_CLOSESTATUSWINDOW, 0);
}
}
bool ImeUi_IsSendingKeyMessage()
{
return bIsSendingKeyMessage;
}
static void OnInputLangChangeWorker()
{
if ( !g_bUILessMode )
{
g_iCandListIndexBase = ( g_hklCurrent == _CHT_HKL_DAYI ) ? 0 : 1;
}
SetImeApi();
}
static void OnInputLangChange()
{
UINT uLang = GETPRIMLANG();
CheckToggleState();
OnInputLangChangeWorker();
if (uLang != GETPRIMLANG())
{
// Korean IME always uses level 3 support.
// Other languages use the level that is specified by ImeUi_SetSupportLevel()
SetSupportLevel( ( GETPRIMLANG() == LANG_KOREAN ) ? 3 : g_dwIMELevelSaved );
}
HWND hwndImeDef = _ImmGetDefaultIMEWnd(g_hwndCurr);
if ( hwndImeDef )
{
// Fix for Zooty #3995: prevent CHT IME toobar from showing up
SendMessageA(hwndImeDef, WM_IME_CONTROL, IMC_OPENSTATUSWINDOW, 0);
SendMessageA(hwndImeDef, WM_IME_CONTROL, IMC_CLOSESTATUSWINDOW, 0);
}
}
static void SetImeApi()
{
_GetReadingString = NULL;
_ShowReadingWindow = NULL;
if(g_bUILessMode)
return;
char szImeFile[MAX_PATH + 1];
HKL kl = g_hklCurrent;
if ( _ImmGetIMEFileNameA( kl, szImeFile, sizeof( szImeFile ) - 1 ) <= 0 )
return;
HMODULE hIme = LoadLibraryA( szImeFile );
if ( !hIme )
return;
_GetReadingString = (UINT (WINAPI*)(HIMC, UINT, LPWSTR, PINT, BOOL*, PUINT))
(GetProcAddress(hIme, "GetReadingString"));
_ShowReadingWindow =(BOOL (WINAPI*)(HIMC himc, BOOL))
(GetProcAddress(hIme, "ShowReadingWindow"));
if ( _ShowReadingWindow )
{
HIMC himc;
if ( NULL != ( himc = _ImmGetContext( g_hwndCurr ) ) )
{
_ShowReadingWindow( himc, false );
_ImmReleaseContext( g_hwndCurr, himc );
}
}
}
static void CheckInputLocale()
{
static HKL hklPrev = 0;
g_hklCurrent = GetKeyboardLayout( 0 );
if ( hklPrev == g_hklCurrent )
{
return;
}
hklPrev = g_hklCurrent;
switch ( GETPRIMLANG() )
{
// Simplified Chinese
case LANG_CHINESE:
g_bVerticalCand = true;
switch ( GETSUBLANG() )
{
case SUBLANG_CHINESE_SIMPLIFIED:
g_pszIndicatior = g_aszIndicator[INDICATOR_CHS];
//g_bVerticalCand = GetImeId() == 0;
g_bVerticalCand = false;
break;
case SUBLANG_CHINESE_TRADITIONAL:
g_pszIndicatior = g_aszIndicator[INDICATOR_CHT];
break;
default: // unsupported sub-language
g_pszIndicatior = g_aszIndicator[INDICATOR_NON_IME];
break;
}
break;
// Korean
case LANG_KOREAN:
g_pszIndicatior = g_aszIndicator[INDICATOR_KOREAN];
g_bVerticalCand = false;
break;
// Japanese
case LANG_JAPANESE:
g_pszIndicatior = g_aszIndicator[INDICATOR_JAPANESE];
g_bVerticalCand = true;
break;
default:
g_pszIndicatior = g_aszIndicator[INDICATOR_NON_IME];
}
char szCodePage[8];
int iRc = GetLocaleInfoA( MAKELCID( GETLANG(), SORT_DEFAULT ), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, COUNTOF( szCodePage ) ); iRc;
g_uCodePage = _strtoul( szCodePage, NULL, 0 );
for ( int i = 0; i < 256; i++ )
{
LeadByteTable[i] = (BYTE)IsDBCSLeadByteEx( g_uCodePage, (BYTE)i );
}
}
void ImeUi_SetWindow(HWND hwnd)
{
g_hwndCurr = hwnd;
g_disableCicero.DisableCiceroOnThisWnd( hwnd );
}
UINT ImeUi_GetInputCodePage()
{
return g_uCodePage;
}
DWORD ImeUi_GetFlags()
{
return g_dwImeUiFlags;
}
void ImeUi_SetFlags( DWORD dwFlags, bool bSet )
{
if ( bSet )
{
g_dwImeUiFlags |= dwFlags;
}
else
{
g_dwImeUiFlags &= ~dwFlags;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// CTsfUiLessMode methods
//
///////////////////////////////////////////////////////////////////////////////
//
// SetupSinks()
// Set up sinks. A sink is used to receive a Text Service Framework event.
// CUIElementSink implements multiple sink interfaces to receive few different TSF events.
//
BOOL CTsfUiLessMode::SetupSinks()
{
// ITfThreadMgrEx is available on Vista or later.
HRESULT hr;
hr = CoCreateInstance(CLSID_TF_ThreadMgr,
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(ITfThreadMgrEx),
(void**)&m_tm);
if (hr != S_OK)
{
return FALSE;
}
// ready to start interacting
TfClientId cid; // not used
if (FAILED(m_tm->ActivateEx(&cid, TF_TMAE_UIELEMENTENABLEDONLY)))
{
return FALSE;
}
// Setup sinks
BOOL bRc = FALSE;
m_TsfSink = new CUIElementSink();
if (m_TsfSink)
{
ITfSource *srcTm;
if (SUCCEEDED(hr = m_tm->QueryInterface(__uuidof(ITfSource), (void **)&srcTm)))
{
// Sink for reading window change
if (SUCCEEDED(hr = srcTm->AdviseSink(__uuidof(ITfUIElementSink), (ITfUIElementSink*)m_TsfSink, &m_dwUIElementSinkCookie)))
{
// Sink for input locale change
if (SUCCEEDED(hr = srcTm->AdviseSink(__uuidof(ITfInputProcessorProfileActivationSink), (ITfInputProcessorProfileActivationSink*)m_TsfSink, &m_dwAlpnSinkCookie)))
{
if (SetupCompartmentSinks()) // Setup compartment sinks for the first time
{
bRc = TRUE;
}
}
}
srcTm->Release();
}
}
return bRc;
}
void CTsfUiLessMode::ReleaseSinks()
{
HRESULT hr;
ITfSource *source;
// Remove all sinks
if ( m_tm && SUCCEEDED(m_tm->QueryInterface(__uuidof(ITfSource), (void **)&source)))
{
hr = source->UnadviseSink(m_dwUIElementSinkCookie);
hr = source->UnadviseSink(m_dwAlpnSinkCookie);
source->Release();
SetupCompartmentSinks(TRUE); // Remove all compartment sinks
m_tm->Deactivate();
SAFE_RELEASE(m_tm);
SAFE_RELEASE(m_TsfSink);
}
}
CTsfUiLessMode::CUIElementSink::CUIElementSink()
{
_cRef = 1;
}
CTsfUiLessMode::CUIElementSink::~CUIElementSink()
{
}
STDAPI CTsfUiLessMode::CUIElementSink::QueryInterface(REFIID riid, void **ppvObj)
{
if (ppvObj == NULL)
return E_INVALIDARG;
*ppvObj = NULL;
if (IsEqualIID(riid, IID_IUnknown))
{
*ppvObj = reinterpret_cast<IUnknown *>(this);
}
else if (IsEqualIID(riid, __uuidof(ITfUIElementSink)))
{
*ppvObj = (ITfUIElementSink *)this;
}
else if (IsEqualIID(riid, __uuidof(ITfInputProcessorProfileActivationSink)))
{
*ppvObj = (ITfInputProcessorProfileActivationSink*)this;
}
else if (IsEqualIID(riid, __uuidof(ITfCompartmentEventSink)))
{
*ppvObj = (ITfCompartmentEventSink*)this;
}
if (*ppvObj)
{
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
STDAPI_(ULONG) CTsfUiLessMode::CUIElementSink::AddRef()
{
return ++_cRef;
}
STDAPI_(ULONG) CTsfUiLessMode::CUIElementSink::Release()
{
LONG cr = --_cRef;
if (_cRef == 0)
{
delete this;
}
return cr;
}
STDAPI CTsfUiLessMode::CUIElementSink::BeginUIElement(DWORD dwUIElementId, BOOL *pbShow)
{
ITfUIElement *pElement = GetUIElement(dwUIElementId);
if (!pElement)
return E_INVALIDARG;
ITfReadingInformationUIElement *preading = NULL;
ITfCandidateListUIElement *pcandidate = NULL;
*pbShow = FALSE;
if (!g_bCandList && SUCCEEDED(pElement->QueryInterface(__uuidof(ITfReadingInformationUIElement),
(void **)&preading)))
{
MakeReadingInformationString(preading);
preading->Release();
}
else if (SUCCEEDED(pElement->QueryInterface(__uuidof(ITfCandidateListUIElement),
(void **)&pcandidate)))
{
m_nCandidateRefCount++;
MakeCandidateStrings(pcandidate);
pcandidate->Release();
}
pElement->Release();
return S_OK;
}
STDAPI CTsfUiLessMode::CUIElementSink::UpdateUIElement(DWORD dwUIElementId)
{
ITfUIElement *pElement = GetUIElement(dwUIElementId);
if (!pElement)
return E_INVALIDARG;
ITfReadingInformationUIElement *preading = NULL;
ITfCandidateListUIElement *pcandidate = NULL;
if (!g_bCandList && SUCCEEDED(pElement->QueryInterface(__uuidof(ITfReadingInformationUIElement),
(void **)&preading)))
{
MakeReadingInformationString(preading);
preading->Release();
}
else if (SUCCEEDED(pElement->QueryInterface(__uuidof(ITfCandidateListUIElement),
(void **)&pcandidate)))
{
MakeCandidateStrings(pcandidate);
pcandidate->Release();
}
pElement->Release();
return S_OK;
}
STDAPI CTsfUiLessMode::CUIElementSink::EndUIElement(DWORD dwUIElementId)
{
ITfUIElement *pElement = GetUIElement(dwUIElementId);
if (!pElement)
return E_INVALIDARG;
ITfReadingInformationUIElement *preading = NULL;
if (!g_bCandList && SUCCEEDED(pElement->QueryInterface(__uuidof(ITfReadingInformationUIElement),
(void **)&preading)))
{
g_dwCount = 0;
preading->Release();
}
ITfCandidateListUIElement *pcandidate = NULL;
if (SUCCEEDED(pElement->QueryInterface(__uuidof(ITfCandidateListUIElement),
(void **)&pcandidate)))
{
m_nCandidateRefCount--;
if (m_nCandidateRefCount == 0)
CloseCandidateList();
pcandidate->Release();
}
pElement->Release();
return S_OK;
}
void CTsfUiLessMode::UpdateImeState(BOOL bResetCompartmentEventSink)
{
ITfCompartmentMgr* pcm;
ITfCompartment* pTfOpenMode = NULL;
ITfCompartment* pTfConvMode = NULL;
if ( GetCompartments( &pcm, &pTfOpenMode, &pTfConvMode ) )
{
VARIANT valOpenMode;
VARIANT valConvMode;
pTfOpenMode->GetValue( &valOpenMode );
pTfConvMode->GetValue( &valConvMode );
if ( valOpenMode.vt == VT_I4 )
{
if ( g_bChineseIME )
{
g_dwState = valOpenMode.lVal != 0 && valConvMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_ENGLISH;
}
else
{
g_dwState = valOpenMode.lVal != 0 ? IMEUI_STATE_ON : IMEUI_STATE_OFF;
}
}
VariantClear( &valOpenMode );
VariantClear( &valConvMode );
if ( bResetCompartmentEventSink )
{
SetupCompartmentSinks( FALSE, pTfOpenMode, pTfConvMode ); // Reset compartment sinks
}
pTfOpenMode->Release();
pTfConvMode->Release();
pcm->Release();
}
}
STDAPI CTsfUiLessMode::CUIElementSink::OnActivated(DWORD dwProfileType, LANGID langid, REFCLSID clsid, REFGUID catid,
REFGUID guidProfile, HKL hkl, DWORD dwFlags)
{
g_iCandListIndexBase = IsEqualGUID( TF_PROFILE_DAYI, guidProfile ) ? 0 : 1;
if ( IsEqualIID( catid, GUID_TFCAT_TIP_KEYBOARD ) && ( dwFlags & TF_IPSINK_FLAG_ACTIVE ) )
{
g_bChineseIME = ( dwProfileType & TF_PROFILETYPE_INPUTPROCESSOR ) && langid == LANG_CHT;
if ( dwProfileType & TF_PROFILETYPE_INPUTPROCESSOR )
{
UpdateImeState(TRUE);
}
else
g_dwState = IMEUI_STATE_OFF;
OnInputLangChange();
}
return S_OK;
}
STDAPI CTsfUiLessMode::CUIElementSink::OnChange(REFGUID rguid)
{
UpdateImeState();
return S_OK;
}
void CTsfUiLessMode::MakeReadingInformationString(ITfReadingInformationUIElement* preading)
{
UINT cchMax;
UINT uErrorIndex = 0;
BOOL fVertical;
DWORD dwFlags;
preading->GetUpdatedFlags(&dwFlags);
preading->GetMaxReadingStringLength(&cchMax);
preading->GetErrorIndex(&uErrorIndex); // errorIndex is zero-based
preading->IsVerticalOrderPreferred(&fVertical);
g_iReadingError = (int)uErrorIndex;
g_bHorizontalReading = !fVertical;
g_bReadingWindow = true;
g_uCandPageSize = MAX_CANDLIST;
g_dwSelection = g_iReadingError ? g_iReadingError - 1 : (DWORD)-1;
g_iReadingError--; // g_iReadingError is used only in horizontal window, and has to be -1 if there's no error.
#ifndef UNICODE
if ( g_iReadingError > 0 )
{
// convert g_iReadingError to byte based
LPCSTR pszNext = g_szReadingString;
for (int i = 0; i < g_iReadingError && pszNext && *pszNext; ++i)
{
pszNext = CharNext(pszNext);
}
if (pszNext) // should be non-NULL, but just in case
{
g_iReadingError = pszNext - g_szReadingString;
}
}
#endif
BSTR bstr;
if (SUCCEEDED(preading->GetString(&bstr)))
{
if (bstr)
{
#ifndef UNICODE
char szStr[COUNTOF(g_szReadingString)*2];
szStr[0] = 0;
int iRc = WideCharToMultiByte(CP_ACP, 0, bstr, -1, szStr, sizeof(szStr), NULL, NULL);
if (iRc >= sizeof(szStr))
{
szStr[sizeof(szStr)-1] = 0;
}
wcscpy_s( g_szReadingString, COUNTOF(g_szReadingString), szStr );
#else
wcscpy_s( g_szReadingString, COUNTOF(g_szReadingString), bstr );
#endif
g_dwCount = cchMax;
LPCTSTR pszSource = g_szReadingString;
if ( fVertical )
{
// for vertical reading window, copy each character to g_szCandidate array.
for ( UINT i = 0; i < cchMax; i++ )
{
LPTSTR pszDest = g_szCandidate[i];
if ( *pszSource )
{
LPTSTR pszNextSrc = CharNext(pszSource);
SIZE_T size = (LPSTR)pszNextSrc - (LPSTR)pszSource;
CopyMemory( pszDest, pszSource, size );
pszSource = pszNextSrc;
pszDest += size;
}
*pszDest = 0;
}
}
else
{
g_szCandidate[0][0] = TEXT(' '); // hack to make rendering happen
}
SysFreeString(bstr);
}
}
}
void CTsfUiLessMode::MakeCandidateStrings(ITfCandidateListUIElement* pcandidate)
{
UINT uIndex = 0;
UINT uCount = 0;
UINT uCurrentPage = 0;
UINT *IndexList = NULL;
UINT uPageCnt = 0;
DWORD dwPageStart = 0;
DWORD dwPageSize = 0;
BSTR bstr;
pcandidate->GetSelection(&uIndex);
pcandidate->GetCount(&uCount);
pcandidate->GetCurrentPage(&uCurrentPage);
g_dwSelection = (DWORD)uIndex;
g_dwCount = (DWORD)uCount;
g_bCandList = true;
g_bReadingWindow = false;
pcandidate->GetPageIndex(NULL, 0, &uPageCnt);
if(uPageCnt > 0)
{
IndexList = (UINT *)ImeUiCallback_Malloc(sizeof(UINT)*uPageCnt);
if(IndexList)
{
pcandidate->GetPageIndex(IndexList, uPageCnt, &uPageCnt);
dwPageStart = IndexList[uCurrentPage];
dwPageSize = (uCurrentPage < uPageCnt-1) ?
min(uCount, IndexList[uCurrentPage+1]) - dwPageStart:
uCount - dwPageStart;
}
}
g_uCandPageSize = min(dwPageSize, MAX_CANDLIST);
g_dwSelection = g_dwSelection - dwPageStart;
memset(&g_szCandidate, 0, sizeof(g_szCandidate));
for (UINT i = dwPageStart, j = 0; (DWORD)i < g_dwCount && j < g_uCandPageSize; i++, j++)
{
if (SUCCEEDED(pcandidate->GetString( i, &bstr )))
{
if(bstr)
{
#ifndef UNICODE
char szStr[COUNTOF(g_szCandidate[0])*2];
szStr[0] = 0;
int iRc = WideCharToMultiByte(CP_ACP, 0, bstr, -1, szStr, sizeof(szStr), NULL, NULL);
if (iRc >= sizeof(szStr))
{
szStr[sizeof(szStr)-1] = 0;
}
ComposeCandidateLine( j, szStr );
#else
ComposeCandidateLine( j, bstr );
#endif
SysFreeString(bstr);
}
}
}
if (GETPRIMLANG() == LANG_KOREAN)
{
g_dwSelection = (DWORD)-1;
}
if(IndexList)
{
ImeUiCallback_Free(IndexList);
}
}
ITfUIElement* CTsfUiLessMode::GetUIElement(DWORD dwUIElementId)
{
ITfUIElementMgr *puiem;
ITfUIElement *pElement = NULL;
if (SUCCEEDED(m_tm->QueryInterface(__uuidof(ITfUIElementMgr), (void **)&puiem)))
{
puiem->GetUIElement(dwUIElementId, &pElement);
puiem->Release();
}
return pElement;
}
BOOL CTsfUiLessMode::CurrentInputLocaleIsIme()
{
BOOL ret = FALSE;
HRESULT hr;
ITfInputProcessorProfiles *pProfiles;
hr = CoCreateInstance(CLSID_TF_InputProcessorProfiles, NULL, CLSCTX_INPROC_SERVER, __uuidof(ITfInputProcessorProfiles), (LPVOID*)&pProfiles);
if (SUCCEEDED(hr))
{
ITfInputProcessorProfileMgr *pProfileMgr;
hr = pProfiles->QueryInterface(__uuidof(ITfInputProcessorProfileMgr), (LPVOID*)&pProfileMgr);
if (SUCCEEDED(hr))
{
TF_INPUTPROCESSORPROFILE tip;
hr = pProfileMgr->GetActiveProfile( GUID_TFCAT_TIP_KEYBOARD, &tip );
if (SUCCEEDED(hr))
{
ret = ( tip.dwProfileType & TF_PROFILETYPE_INPUTPROCESSOR ) != 0;
}
pProfileMgr->Release();
}
pProfiles->Release();
}
return ret;
}
// Sets up or removes sink for UI element.
// UI element sink should be removed when IME is disabled,
// otherwise the sink can be triggered when a game has multiple instances of IME UI library.
void CTsfUiLessMode::EnableUiUpdates(bool bEnable)
{
if ( m_tm == NULL ||
( bEnable && m_dwUIElementSinkCookie != TF_INVALID_COOKIE ) ||
( !bEnable && m_dwUIElementSinkCookie == TF_INVALID_COOKIE ) )
{
return;
}
ITfSource *srcTm = NULL;
HRESULT hr = E_FAIL;
if (SUCCEEDED(hr = m_tm->QueryInterface(__uuidof(ITfSource), (void **)&srcTm)))
{
if ( bEnable )
{
hr = srcTm->AdviseSink(__uuidof(ITfUIElementSink), (ITfUIElementSink*)m_TsfSink, &m_dwUIElementSinkCookie);
}
else
{
hr = srcTm->UnadviseSink(m_dwUIElementSinkCookie);
m_dwUIElementSinkCookie = TF_INVALID_COOKIE;
}
srcTm->Release();
}
}
// Returns open mode compartments and compartment manager.
// Function fails if it fails to acquire any of the objects to be returned.
BOOL CTsfUiLessMode::GetCompartments( ITfCompartmentMgr** ppcm, ITfCompartment** ppTfOpenMode, ITfCompartment** ppTfConvMode )
{
ITfCompartmentMgr* pcm = NULL;
ITfCompartment* pTfOpenMode = NULL;
ITfCompartment* pTfConvMode = NULL;
static GUID _GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION = { 0xCCF05DD8, 0x4A87, 0x11D7, 0xA6, 0xE2, 0x00, 0x06, 0x5B, 0x84, 0x43, 0x5C };
HRESULT hr;
if (SUCCEEDED(hr = m_tm->QueryInterface( IID_ITfCompartmentMgr, (void**)&pcm )))
{
if (SUCCEEDED(hr = pcm->GetCompartment( GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, &pTfOpenMode )))
{
if (SUCCEEDED(hr = pcm->GetCompartment( _GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION, &pTfConvMode )))
{
*ppcm = pcm;
*ppTfOpenMode = pTfOpenMode;
*ppTfConvMode = pTfConvMode;
return TRUE;
}
pTfOpenMode->Release();
}
pcm->Release();
}
return FALSE;
}
// There are three ways to call this function:
// SetupCompartmentSinks() : initialization
// SetupCompartmentSinks(FALSE, openmode, convmode) : Resetting sinks. This is necessary as DaYi and Array IME resets compartment on switching input locale
// SetupCompartmentSinks(TRUE) : clean up sinks
BOOL CTsfUiLessMode::SetupCompartmentSinks( BOOL bRemoveOnly, ITfCompartment* pTfOpenMode, ITfCompartment* pTfConvMode )
{
bool bLocalCompartments = false;
ITfCompartmentMgr* pcm = NULL;
BOOL bRc = FALSE;
HRESULT hr = E_FAIL;
if ( !pTfOpenMode && !pTfConvMode )
{
bLocalCompartments = true;
GetCompartments( &pcm, &pTfOpenMode, &pTfConvMode );
}
if ( !( pTfOpenMode && pTfConvMode ) )
{
// Invalid parameters or GetCompartments() has failed.
return FALSE;
}
ITfSource *srcOpenMode = NULL;
if (SUCCEEDED(hr = pTfOpenMode->QueryInterface( IID_ITfSource, (void**)&srcOpenMode )))
{
// Remove existing sink for open mode
if ( m_dwOpenModeSinkCookie != TF_INVALID_COOKIE )
{
srcOpenMode->UnadviseSink( m_dwOpenModeSinkCookie );
m_dwOpenModeSinkCookie = TF_INVALID_COOKIE;
}
// Setup sink for open mode (toggle state) change
if ( bRemoveOnly || SUCCEEDED(hr = srcOpenMode->AdviseSink( IID_ITfCompartmentEventSink, (ITfCompartmentEventSink*)m_TsfSink, &m_dwOpenModeSinkCookie )))
{
ITfSource *srcConvMode = NULL;
if (SUCCEEDED(hr = pTfConvMode->QueryInterface( IID_ITfSource, (void**)&srcConvMode )))
{
// Remove existing sink for open mode
if ( m_dwConvModeSinkCookie != TF_INVALID_COOKIE )
{
srcConvMode->UnadviseSink( m_dwConvModeSinkCookie );
m_dwConvModeSinkCookie = TF_INVALID_COOKIE;
}
// Setup sink for open mode (toggle state) change
if ( bRemoveOnly || SUCCEEDED(hr = srcConvMode->AdviseSink( IID_ITfCompartmentEventSink, (ITfCompartmentEventSink*)m_TsfSink, &m_dwConvModeSinkCookie )))
{
bRc = TRUE;
}
srcConvMode->Release();
}
}
srcOpenMode->Release();
}
if ( bLocalCompartments )
{
pTfOpenMode->Release();
pTfConvMode->Release();
pcm->Release();
}
return bRc;
}
WORD ImeUi_GetPrimaryLanguage()
{
return GETPRIMLANG();
};
DWORD ImeUi_GetImeId(UINT uIndex)
{
return GetImeId(uIndex);
};
WORD ImeUi_GetLanguage()
{
return GETLANG();
};
PTSTR ImeUi_GetIndicatior()
{
return g_pszIndicatior ;
};
bool ImeUi_IsShowReadingWindow()
{
return g_bReadingWindow;
};
bool ImeUi_IsShowCandListWindow()
{
return g_bCandList;
};
bool ImeUi_IsVerticalCand()
{
return g_bVerticalCand;
};
bool ImeUi_IsHorizontalReading()
{
return g_bHorizontalReading;
};
TCHAR* ImeUi_GetCandidate(UINT idx)
{
if ( idx < MAX_CANDLIST)
return g_szCandidate[idx];
else
return g_szCandidate[0];
}
DWORD ImeUi_GetCandidateSelection()
{
return g_dwSelection;
}
DWORD ImeUi_GetCandidateCount()
{
return g_dwCount;
}
TCHAR* ImeUi_GetCompositionString()
{
return g_szCompositionString;
}
BYTE* ImeUi_GetCompStringAttr()
{
return g_szCompAttrString;
}
DWORD ImeUi_GetImeCursorChars()
{
return g_IMECursorChars;
}
| [
"marselas@gmail.com"
] | marselas@gmail.com |
14c36301b395004dc03913eab38ab4a7b094f5d7 | e542e955e45277ca014430019a0188f6e85a0d3c | /HkfyCrypt/HDSerial.cpp | 8c139d7f8066cb2771a2bb8d9559ffdb9cadc57a | [] | no_license | langyastudio/sentinel-crypto | fb3eb34270dc22cb42255b8beeee3340510bf096 | 86f98f7f2149e1ff10cb3657f01144ce386b6570 | refs/heads/master | 2020-03-22T10:51:21.039366 | 2019-10-31T03:21:46 | 2019-10-31T03:21:46 | 139,931,467 | 4 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,406 | cpp | #include "stdafx.h"
#include "HDSerial.h"
void ChangeByteOrder(PCHAR szString, USHORT uscStrSize)
{
USHORT i = 0;
CHAR temp= '\0';
for (i = 0; i < uscStrSize; i+=2)
{
temp = szString[i];
szString[i] = szString[i+1];
szString[i+1] = temp;
}
}
//--------------------------------------------------------------
// 硬盘序列号
//--------------------------------------------------------------
BOOL GetHDSerial(char *lpszHD, int len/*=128*/)
{
BOOL bRtn = FALSE;
DWORD bytesRtn = 0;
char szhd[80] = {0};
PIDSECTOR phdinfo;
HANDLE hDrive = NULL;
GETVERSIONOUTPARAMS vers;
SENDCMDINPARAMS in;
SENDCMDOUTPARAMS out;
ZeroMemory(&vers, sizeof(vers));
ZeroMemory(&in , sizeof(in));
ZeroMemory(&out , sizeof(out));
//搜索四个物理硬盘,取第一个有数据的物理硬盘
for (int j=0; j<4; j++)
{
sprintf(szhd, "\\\\.\\PhysicalDrive%d", j);
hDrive = CreateFileA(szhd,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
0);
if (NULL == hDrive)
{
continue;
}
if (!DeviceIoControl(hDrive, DFP_GET_VERSION, 0, 0, &vers, sizeof(vers), &bytesRtn,0))
{
goto FOREND;
}
//If IDE identify command not supported, fails
if (!(vers.fCapabilities&1))
{
goto FOREND;
}
//Identify the IDE drives
if (j&1)
{
in.irDriveRegs.bDriveHeadReg = 0xb0;
}
else
{
in.irDriveRegs.bDriveHeadReg = 0xa0;
}
if (vers.fCapabilities&(16>>j))
{
//We don't detect a ATAPI device.
goto FOREND;
}
else
{
in.irDriveRegs.bCommandReg = 0xec;
}
in.bDriveNumber = j;
in.irDriveRegs.bSectorCountReg = 1;
in.irDriveRegs.bSectorNumberReg = 1;
in.cBufferSize = 512;
if (!DeviceIoControl(hDrive, DFP_RECEIVE_DRIVE_DATA, &in, sizeof(in), &out, sizeof(out), &bytesRtn,0))
{
//"DeviceIoControl failed:DFP_RECEIVE_DRIVE_DATA"<<endl;
goto FOREND;
}
phdinfo=(PIDSECTOR)out.bBuffer;
char s[21] = {0};
memcpy(s, phdinfo->sSerialNumber, 20);
s[20] = 0;
ChangeByteOrder(s, 20);
//删除空格字符
int ix = 0;
for (ix=0; ix<20; ix++)
{
if (s[ix] == ' ')
{
continue;
}
break;
}
memcpy(lpszHD, s+ix, 20);
bRtn = TRUE;
break;
FOREND:
CloseHandle(hDrive);
hDrive = NULL;
}
CloseHandle(hDrive);
hDrive = NULL;
return(bRtn);
} | [
"1032030048@qq.com"
] | 1032030048@qq.com |
9c173e48c8ecf8f345e47a3ec8ecbb99335c1d4e | 380061c0415ed0d76acbbd1da00d9d42a650ba15 | /src/Integrative_Phys/Anatomical_layer/Anatomical_entity.cpp | 44e29e011c8c57195e0360c16c9bd4e707ad19e9 | [] | no_license | velociraptors/physio_mist | 551d266d3fb911088d83d5b735f080f4168a47c4 | d69aed766561cfb85071304797dba23af70a4aca | refs/heads/master | 2021-01-17T04:25:00.300402 | 2009-12-04T18:21:47 | 2009-12-04T18:21:47 | 313,483 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | //////////////////////////////////////////////////////
// Implementation of Anatomical_entity
//////////////////////////////////////////////////////
#include "Anatomical_entity.h"
void Anatomical_entity::set_FMAID( FMAID* nFMAID )
{
fmaid = nFMAID;
}
FMAID* Anatomical_entity::get_FMAID()
{
return fmaid;
}
Anatomical_entity::Anatomical_entity()
{
fmaid = new FMAID();
name = new string();
}
string* Anatomical_entity::get_name()
{
return name;
}
void Anatomical_entity::set_name(string *_name){
name = _name;
} | [
"barbarajoyjones@gmail.com"
] | barbarajoyjones@gmail.com |
31344cff8c135bfc68695a188648c7a55a6987a1 | 9acc02a9aef3e41052f22f0f04d9b43d153f4722 | /book-notes/ecpp/it28-avoid-returning-handles-to-object-internals/avoid_returning_handle_to_object_internal.m.cpp | 69ddec1e4535ebf93399181839374469f6e380c3 | [] | no_license | zhehaowang/zhehao.me | be5b8786662e90060d69d14f6b32353d1fb93c61 | e223e7f234f3df8d3ca65bf27120947175389d61 | refs/heads/master | 2022-07-14T18:42:40.535116 | 2022-07-03T00:08:45 | 2022-07-03T00:08:45 | 67,072,899 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | #include <iostream>
#include <string>
// demonstrates undefined behavior of dangling reference caused by temporary
// objects + returning a handle to object internal
class MyClass {
public:
MyClass(const std::string& data) : d_data(data) {}
const std::string& data() const { return d_data; }
private:
std::string d_data;
};
MyClass createMyClass(const std::string& data) {
return MyClass(data);
}
int main() {
std::string data("data");
const std::string& rd(createMyClass(data).data());
// rd will be dangling at this point
MyClass c(createMyClass(data));
const std::string& rd1(c.data());
// rd1 will be fine
std::cout << rd << " " << rd1 << "\n";
// clang on osx does not demonstrate noticeable behavior for this UB
return 0;
} | [
"wangzhehao410305@gmail.com"
] | wangzhehao410305@gmail.com |
8ad277c9f6646ed46bf2256eb126da8f0b4658df | a6fbd31d83a34c84b95f9f33521aa49e4377b96d | /Semestre 1/Programacion y algoritmos/prog2017_Proyecto2_Alvarez_ES/image.hpp | b1024c6460c501be8129f0f5cf572c065882cb55 | [] | no_license | ericksav21/Maestria | d8732dd1670ce552bd881827c27ce0986a5b80eb | 637ef704029677f78ca614c413119ec93fedb813 | refs/heads/master | 2021-01-19T20:08:06.415345 | 2019-01-25T17:17:24 | 2019-01-25T17:17:24 | 101,221,897 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 900 | hpp | #ifndef IMAGE_H
#define IMAGE_H
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>
#include "util.hpp"
#include "point.hpp"
class Image {
private:
int width, height, scale;
vector<vector<int> > mat;
void read_from_file(string files_name);
int A_test(int i, int j);
int B_test(int i, int j);
public:
Image(int width, int height, int color);
Image(string files_name);
Image(vector<vector<int> > mat);
~Image();
vector<vector<int> > get_mat();
int get_width();
int get_height();
int get_val(int i, int j);
void set_mat(vector<vector<int> > mat);
void set_val(int i, int j, int val);
void skeletonize();
void draw_line(Point a, Point b, int color);
void draw_parabola(Point c, int p, int bound, int dir, int color);
void print();
vector<Point> get_white_points();
void save(string files_name, bool use_path);
};
#endif | [
"erickalv21@gmail.com"
] | erickalv21@gmail.com |
8ed5f2780de6dad1cf5325115861e2eaefe1cbe1 | 49b979e617619251a4d8df4c92ded34dde460aeb | /flow/MaxFlow.cpp | c5fb9bd72d60f331906e3ab0fafb5f5f54155f8a | [] | no_license | boook64/codebook | ad340438cec5983afc18bb8cfad787075d3c88dd | cb25cfd7ca0ec426e872b80fd426f38515c0b124 | refs/heads/master | 2023-01-09T23:39:38.840631 | 2020-11-05T16:28:29 | 2020-11-05T16:28:29 | 310,356,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | cpp | struct N{
int from, to;
long long cap, flow;
};
struct dinic{
int s, t, dep[maxn], use[maxn], res[maxn];
vector<int> g[maxn];
vector<N> e;
void init(){
for (int i = 0; i < maxn; ++ i)
vector<int> ().swap(g[i]);
vector<N> ().swap(e);
}
void ADDE(int f, int t, long long c){
g[f].emplace_back(e.size());
e.emplace_back(N{f, t, c, 0});
g[t].emplace_back(e.size());
e.emplace_back(N{t, f, 0, 0});
}
int BFS(){
memset(use, 0, sizeof use);
memset(dep, 0, sizeof dep);
queue<int> qu;
qu.push(s), dep[s] = use[s] = 1;
while(qu.size()){
int now = qu.front(); qu.pop();
for(auto i : g[now]){
N to = e[i];
if(use[to.to] == 0 && to.cap > to.flow){
use[to.to] = 1;
dep[to.to] = dep[now] + 1;
qu.push(to.to);
}
}
}
return use[t];
}
long long DFS(int now, long long lim){
if(lim == 0 || now == t) return lim;
long long flow = 0, tmp;
for(int &i = res[now] ; i < g[now].size() ; i ++){
N to = e[g[now][i]];
if(dep[to.to] == dep[now] + 1){
tmp = DFS(to.to, min(lim, to.cap - to.flow));
if(tmp > 0){
e[g[now][i] ^ 0].flow += tmp;
e[g[now][i] ^ 1].flow -= tmp;
flow += tmp;
lim -= tmp;
if(lim == 0) break;
}
}
}
return flow;
}
long long FLOW(int s, int t){
this -> s = s, this -> t = t;
long long flow = 0;
while(BFS()){
memset(res, 0, sizeof res);
flow += DFS(s, 1e15);
}
return flow;
}
} dc;
| [
"boook64@gmail.com"
] | boook64@gmail.com |
694c44895249d2de28307f8bf76e4427e98d7a2d | 992da214facdfe75afd595e141685a5958c256dc | /ComponentRealSenseV2Server/smartsoft/src/RealSenSeWrapper.cc | fd4e0fa2c33c58b07fc2f6d20c02c0658a0598f2 | [] | no_license | HannesBachter/ComponentRepository | e9d66bcc52108ebfa03e161122ad0e0d0042f3d6 | 71b7a90cf8b5cc91f70757b6fafbaf78d4c1b7a8 | refs/heads/master | 2023-02-16T13:17:17.161655 | 2020-08-03T14:43:54 | 2020-08-03T14:43:54 | 285,233,349 | 0 | 1 | null | 2020-08-05T08:51:59 | 2020-08-05T08:51:58 | null | UTF-8 | C++ | false | false | 25,187 | cc | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain Version 2.2
// The SmartSoft Toolchain has been developed by:
//
// Christian Schlegel (schlegel@hs-ulm.de)
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
//
// Copyright (C) 2011, 2017 Matthias Lutz, Dennis Stampfer, Matthias Rollenhagen, Nayabrasul Shaik
//
// lutz@hs-ulm.de
// stampfer@hs-ulm.de
// rollenhagen@hs-ulm.de
// shaik@hs-ulm.de
//
// ZAFH Servicerobotic Ulm
// Christian Schlegel
// University of Applied Sciences
// Prittwitzstr. 10
// 89075 Ulm
// Germany
//
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//--------------------------------------------------------------------------
#include "RealSenSeWrapper.hh"
#include <opencv2/opencv.hpp>
#include <librealsense2/h/rs_pipeline.h>
#include <librealsense2/rsutil.h>
#define TEXT_COLOR_RESET "\033[0m"
#define TEXT_COLOR_GREEN "\033[32m" /* Green */
RealSenSeWrapper::RealSenSeWrapper(int color_width, int color_height, int color_framerate,
int depth_width, int depth_height, int depth_framerate, std::string device_serial_num, float in_baseline){
std::cout << "Initializing RealSense device"<<std::endl;
color_width_ = color_width;
color_height_ = color_height;
color_framerate_ = color_framerate;
depth_width_ = depth_width;
depth_height_ = depth_height;
depth_framerate_ = depth_framerate;
device_serial_number_ = device_serial_num;
baseline = in_baseline;
while (init_Camera()==false) {
std::cout<<"Error init camera --> retry"<<std::endl;
sleep(1);
}
std::cout<<TEXT_COLOR_RESET<< TEXT_COLOR_GREEN; // make the screen output Green
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout << std::setw(25)<<"Device Name"<<": "<< rs2_device_.get_info(RS2_CAMERA_INFO_NAME)<<std::endl;
std::cout << std::setw(25)<<"Firmware Version"<<": "<<rs2_device_.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION)<<std::endl;
std::cout << std::setw(25)<<"Serial Number"<<": "<<rs2_device_.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)<<std::endl;
std::cout << std::setw(25)<<"Product Id"<<": "<<rs2_device_.get_info(RS2_CAMERA_INFO_PRODUCT_ID)<<std::endl;
std::cout << std::setw(25)<<"Realsense SDK version"<<": "<<RS2_API_MAJOR_VERSION <<"."<<RS2_API_MINOR_VERSION <<"."<<RS2_API_PATCH_VERSION<<std::endl;
std::cout << std::setw(25)<<"Baseline( in mm)"<<": "<<baseline <<std::endl;
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout<<TEXT_COLOR_RESET;
sensor_list = rs2_device_.query_sensors();
int is_depth_sensor_found = 0;
int is_rgb_sensor_found = 0;
std::string depth_sensor_name = "Stereo Module";
std::string rgb_sensor_name = "RGB Camera";
for (rs2::sensor sensor : sensor_list)
{
// Check if the given sensor can be extended to depth sensor interface
rs2_error* e = nullptr;
std::string current_sensor_name = sensor.get_info(RS2_CAMERA_INFO_NAME);
//std::cout << " current_sensor_name.c_str() =" << current_sensor_name.c_str()<<std::endl;
if(!std::strcmp(depth_sensor_name.c_str(), current_sensor_name.c_str()))
{
rs2_sensor_depth = sensor;
is_depth_sensor_found =1;
}
if(!std::strcmp(rgb_sensor_name.c_str(), current_sensor_name.c_str()))
{
rs2_sensor_rgb = sensor;
is_rgb_sensor_found =1;
}
}
// std::cout << "is_depth_sensor_found =" << is_depth_sensor_found<<std::endl;
// std::cout << "is_rgb_sensor_found =" << is_rgb_sensor_found<<std::endl;
if(!is_depth_sensor_found || !is_rgb_sensor_found )
{
std::cout<<__FUNCTION__<<" ERROR: no depth and rgb sensor found, something is wrong with the device?!"<<std::endl;
std::abort();
}
std::vector<rs2::stream_profile> rgb_stream_profiles = rs2_sensor_rgb.get_stream_profiles();
std::vector<rs2::stream_profile> depth_stream_profiles = rs2_sensor_depth.get_stream_profiles();
//////////////////////////////
// search for the correct camera configuration as is given in the ini file
uint32_t selected_rgb_profile_index=-1;
for(unsigned int i = 0; i< rgb_stream_profiles.size(); ++i)
{
rs2::stream_profile current_profile = rgb_stream_profiles.at(i);
//search for RGB8 stream only
if(current_profile.format() == RS2_FORMAT_RGB8){
// As noted, a stream is an abstraction.
// In order to get additional data for the specific type of a
// stream, a mechanism of "Is" and "As" is provided:
if (current_profile.is<rs2::video_stream_profile>()) //"Is" will test if the type tested is of the type given
{
// "As" will try to convert the instance to the given type
rs2::video_stream_profile video_stream_profile = current_profile.as<rs2::video_stream_profile>();
if(current_profile.fps() == color_framerate_ &&
video_stream_profile.width() == color_width_ &&
video_stream_profile.height() == color_height_){
std::cout<<"Found matching color stream: "<< i<<std::endl;
selected_rgb_profile_index = i;
std::cout << "FPS: "<<current_profile.fps()<<"(Video Stream: " << video_stream_profile.format() << " " <<
video_stream_profile.width() << "x" << video_stream_profile.height() << "@ " << video_stream_profile.fps() << "Hz)"<<std::endl;
break;
}
}
}
}
// search for the correct camera configuration as is given in the ini file
uint32_t selected_depth_profile_index=-1;
for(unsigned int i = 0; i< depth_stream_profiles.size(); ++i)
{
rs2::stream_profile current_profile = depth_stream_profiles.at(i);
//search for depth stream only
if(current_profile.format() == RS2_FORMAT_Z16){
// As noted, a stream is an abstraction.
// In order to get additional data for the specific type of a
// stream, a mechanism of "Is" and "As" is provided:
if (current_profile.is<rs2::video_stream_profile>()) //"Is" will test if the type tested is of the type given
{
// "As" will try to convert the instance to the given type
rs2::video_stream_profile video_stream_profile = current_profile.as<rs2::video_stream_profile>();
// After using the "as" method we can use the new data type
// for additinal operations:
if(current_profile.fps() == depth_framerate_ &&
video_stream_profile.width() == depth_width_ &&
video_stream_profile.height() == depth_height_){
std::cout<<"Found matching depth stream: "<< i<<std::endl;
selected_depth_profile_index = i;
std::cout << "FPS: "<<current_profile.fps()<<"(Video Stream: " << video_stream_profile.format() << " " <<
video_stream_profile.width() << "x" << video_stream_profile.height() << "@ " << video_stream_profile.fps() << "Hz)"<<std::endl;
break;
}
}
}
}
if(selected_rgb_profile_index == -1 || selected_depth_profile_index == -1)
{
std::cout << "streams with given configuration is not available, closing the device" <<std::endl;
std::cout << "Exiting the Component" <<std::endl;
std::exit(-1);
}
const rs2::stream_profile* rgb_stream_profile = &rgb_stream_profiles[selected_rgb_profile_index];
const rs2::stream_profile* depth_stream_profile = &depth_stream_profiles[selected_depth_profile_index];
//Out of 9 only 5 are native streams (including fish-eye), but we are using currently color and depth only
rs2_error* e = nullptr;
config.enable_stream(RS2_STREAM_COLOR, color_width_, color_height_, RS2_FORMAT_RGB8,color_framerate_);
config.enable_stream(RS2_STREAM_DEPTH, depth_width_, depth_height_, RS2_FORMAT_Z16, depth_framerate_);
//RealSense intrinsics and extrinsics
rs2_get_video_stream_intrinsics(rgb_stream_profile->get(), &color_intrinsics, &e);
rs2_get_video_stream_intrinsics(depth_stream_profile->get(), &depth_intrinsics, &e);
rs2_get_extrinsics(depth_stream_profile->get(), rgb_stream_profile->get(), &d2c_extrinsics, &e);
display_intrinsics_extrinsics();
}
RealSenSeWrapper::~RealSenSeWrapper() {
stopVideo();
}
void RealSenSeWrapper::startVideo() {
try {
pipeline_profile = pipeline.start(config);
std::cout << "Camera Started here"<<std::endl;
} catch (std::exception &e) {
std::cerr << __FILE__<<__LINE__<<"Error while Opening RealSense device : "
<< e.what() << "\n";
}
}
void RealSenSeWrapper::stopVideo() {
try {
pipeline.stop();
std::cout << "Realsense device is Closed" <<std::endl;
} catch (std::exception &e) {
std::cerr << __FILE__<<__LINE__<<"Error while closing RealSense device : "
<< e.what() << "\n";
}
}
void RealSenSeWrapper::getrgbimage(DomainVision::CommVideoImage& comm_rgb_frame)
{
rs2::video_frame current_rgb_frame = current_frameset.get_color_frame();
//std:: cout << "color_frame_number = " << current_rgb_frame.get_frame_number() <<std::endl;
const unsigned char *color_frame = (const unsigned char*) current_rgb_frame.get_data();
auto color_frame_timestamp = current_rgb_frame.get_timestamp();
auto color_frame_number = current_rgb_frame.get_frame_number();
//std:: cout << "w = " << color_intrinsics.width << " H = " << color_intrinsics.height <<std::endl;
//std:: cout << "frame w = " << current_rgb_frame.get_width() << " frame H = " << current_rgb_frame.get_height() <<std::endl;
//std:: cout << "color_frame_timestamp = " << color_frame_timestamp << " color_frame_number = " << color_frame_number <<std::endl;
comm_rgb_frame.set_parameters(current_rgb_frame.get_width(), current_rgb_frame.get_height(), DomainVision::FormatType::RGB24);
comm_rgb_frame.set_data(color_frame);
comm_rgb_frame.setIs_valid(true);
comm_rgb_frame.setSeq_count(color_frame_number);
arma::mat comm_color_intrinsic = arma::zeros(4,4);
comm_color_intrinsic(0,0) = color_intrinsics.fx;
comm_color_intrinsic(1,1) = color_intrinsics.fy;
comm_color_intrinsic(0,2) = color_intrinsics.ppx;
comm_color_intrinsic(1,2) = color_intrinsics.ppy;
comm_color_intrinsic(2,2) = 1;
comm_rgb_frame.set_intrinsic(comm_color_intrinsic);
if(color_intrinsics.model==RS2_DISTORTION_BROWN_CONRADY)
{
comm_rgb_frame.setDistortion_model(DomainVision::ImageDistortionModel::BROWN_CONRADY);
}else if(color_intrinsics.model==RS2_DISTORTION_MODIFIED_BROWN_CONRADY)
{
comm_rgb_frame.setDistortion_model(DomainVision::ImageDistortionModel::MODIFIED_BROWN_CONRADY);
}else if(color_intrinsics.model==RS2_DISTORTION_INVERSE_BROWN_CONRADY)
{
comm_rgb_frame.setDistortion_model(DomainVision::ImageDistortionModel::INVERSE_BROWN_CONRADY);
}
else{
comm_rgb_frame.setDistortion_model(DomainVision::ImageDistortionModel::NONE);
}
arma::mat comm_color_distortion = arma::zeros(1,5);
comm_color_distortion(0,0) = color_intrinsics.coeffs[0];
comm_color_distortion(0,1) = color_intrinsics.coeffs[1];
comm_color_distortion(0,2) = color_intrinsics.coeffs[2];
comm_color_distortion(0,3) = color_intrinsics.coeffs[3];
comm_color_distortion(0,4) = color_intrinsics.coeffs[4];
comm_rgb_frame.set_distortion(comm_color_distortion);
}
void RealSenSeWrapper::getdepthimage(DomainVision::CommDepthImage& comm_depth_frame)
{
rs2::depth_frame current_depth_frame = current_frameset.get_depth_frame();
/*Post processing*/
if(is_postprocess_enabled)
post_processing(current_depth_frame);
/*Read Current Frames*/
const uint16_t* depth_frame = (const uint16_t*) current_depth_frame.get_data();
//assert(rs_error_ != nullptr && "error while reading depth stream");
// BaseLine
rs2::disparity_transform disparity_transform( true );
rs2::disparity_frame disparity_frame = disparity_transform.process( current_depth_frame );
float baseline = disparity_frame.get_baseline(); // mm
// std:: cout << "baseline = " << baseline <<std::endl;
auto depth_frame_timestamp= current_depth_frame.get_timestamp();
auto depth_frame_number= current_depth_frame.get_frame_number();
int frame_height = current_depth_frame.get_height();
int frame_width = current_depth_frame.get_width();
//std:: cout << "dw = " << depth_intrinsics.width << " dH = " << depth_intrinsics.height <<std::endl;
//std:: cout << "dframe w = " << current_depth_frame.get_width() << " dframe H = " << current_depth_frame.get_height() <<std::endl;
//std:: cout << "d_frame_timestamp = " << depth_frame_timestamp << " d_frame_number = " << depth_frame_number <<std::endl;
//std::cout << "IDB =" <<calulate_invalid_depth_band()<<std::endl;
comm_depth_frame.setWidth(depth_intrinsics.width);
comm_depth_frame.setHeight(depth_intrinsics.height);
//std::cout << "depth height =" << comm_depth_frame.getHeight()<<"depth width =" << comm_depth_frame.getWidth()<<std::endl;
comm_depth_frame.setFormat(DomainVision::DepthFormatType::UINT16);
comm_depth_frame.setPixel_size(16);
comm_depth_frame.setSeq_count(depth_frame_number);
if(depth_intrinsics.model==RS2_DISTORTION_BROWN_CONRADY)
{
comm_depth_frame.setDistortion_model(DomainVision::ImageDistortionModel::BROWN_CONRADY);
}else if(depth_intrinsics.model==RS2_DISTORTION_MODIFIED_BROWN_CONRADY)
{
comm_depth_frame.setDistortion_model(DomainVision::ImageDistortionModel::MODIFIED_BROWN_CONRADY);
}else if(depth_intrinsics.model==RS2_DISTORTION_INVERSE_BROWN_CONRADY)
{
comm_depth_frame.setDistortion_model(DomainVision::ImageDistortionModel::INVERSE_BROWN_CONRADY);
}
else{
comm_depth_frame.setDistortion_model(DomainVision::ImageDistortionModel::NONE);
}
// find min and max distances from depth image
int dw = 0;
int dh = 0;
int dwh = 0;
float dp_min=20000;
float dp_max=0.0;
dw = frame_width;//depth_intrinsics.width;
dh = frame_height;//depth_intrinsics.height;
dwh = dw * dh;
// Iterate the data space
// First, iterate across columns
for( int dy = 0; dy < dh; dy++ )
{
// Second, iterate across rows
for( int dx = 0; dx < dw; dx++ )
{
uint i = dy * dw + dx;
uint16_t depth_value = static_cast<uint16_t>(depth_frame[ i ]);
uint16_t depth_in_meters = depth_value;//*scale;
if(depth_in_meters>dp_max)
dp_max=depth_in_meters;
if(depth_in_meters<dp_min)
dp_min=depth_in_meters;
}
}
comm_depth_frame.set_distances(depth_frame, frame_width, frame_height);
comm_depth_frame.setMax_distcance(dp_max);
comm_depth_frame.setMin_distcance(dp_min);
arma::mat comm_depth_distortion = arma::zeros(1,5);
comm_depth_distortion(0,0) = depth_intrinsics.coeffs[0];
comm_depth_distortion(0,1) = depth_intrinsics.coeffs[1];
comm_depth_distortion(0,2) = depth_intrinsics.coeffs[2];
comm_depth_distortion(0,3) = depth_intrinsics.coeffs[3];
comm_depth_distortion(0,4) = depth_intrinsics.coeffs[4];
comm_depth_frame.set_distortion(comm_depth_distortion);
arma::mat comm_depth_intrinsic = arma::zeros(4,4);
comm_depth_intrinsic(0,0) = depth_intrinsics.fx;
comm_depth_intrinsic(1,1) = depth_intrinsics.fy;
comm_depth_intrinsic(0,2) = depth_intrinsics.ppx;
comm_depth_intrinsic(1,2) = depth_intrinsics.ppy;
comm_depth_intrinsic(2,2) = 1;
comm_depth_frame.set_intrinsic(comm_depth_intrinsic);
arma::mat comm_depth_extrinsics = arma::zeros(1,12);
comm_depth_extrinsics(0,0) = d2c_extrinsics.rotation[0];
comm_depth_extrinsics(0,1) = d2c_extrinsics.rotation[1];
comm_depth_extrinsics(0,2) = d2c_extrinsics.rotation[2];
comm_depth_extrinsics(0,3) = d2c_extrinsics.rotation[3];
comm_depth_extrinsics(0,4) = d2c_extrinsics.rotation[4];
comm_depth_extrinsics(0,5) = d2c_extrinsics.rotation[5];
comm_depth_extrinsics(0,6) = d2c_extrinsics.rotation[6];
comm_depth_extrinsics(0,7) = d2c_extrinsics.rotation[7];
comm_depth_extrinsics(0,8) = d2c_extrinsics.rotation[8];
comm_depth_extrinsics(0,9) = d2c_extrinsics.translation[0];
comm_depth_extrinsics(0,10) = d2c_extrinsics.translation[1];
comm_depth_extrinsics(0,11) = d2c_extrinsics.translation[2];
comm_depth_frame.set_extrinsic(comm_depth_extrinsics);
comm_depth_frame.setIs_valid(true);
}
void RealSenSeWrapper::getImage(DomainVision::CommRGBDImage& image)
{
DomainVision::CommDepthImage comm_depth_frame;
DomainVision::CommVideoImage comm_rgb_frame;
/*Read Current Frames*/
try
{
current_frameset = pipeline.wait_for_frames();
//fill rgb image information
getrgbimage(comm_rgb_frame);
//fill depth image information
getdepthimage(comm_depth_frame);
//fill rgbd image with rgb, depth
image.setColor_image(comm_rgb_frame);
image.setDepth_image(comm_depth_frame);
image.setSeq_count(comm_rgb_frame.getSeq_count());
image.setIs_valid(true);
}catch (std::exception &e) {
std::cerr << "[RealSenSeWrapper] Error in wait_for_frames :" << e.what() << "\n";
image.setIs_valid(false);
}
}
bool RealSenSeWrapper::init_Camera()
{
rs2_device_ = nullptr;
device_list = rs2_context_.query_devices();
if (0 == device_list.size())
{
std::cout <<"No device detected. Is it plugged in?"<<std::endl;
return false;
}
else{
int found_device = -1;
std::cout<<" ---------------------------------------- "<<std::endl;
std::cout<<__FUNCTION__<<" found devices: "<<std::endl;
for(unsigned int i=0;i<device_list.size();i++){
std::cout<<" -------------------"<<std::endl;
std::cout<<" Name : "<<device_list[i].get_info(RS2_CAMERA_INFO_NAME)<<std::endl;
std::cout<<" Device Serial : "<<device_list[i].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)<<std::endl;
std::cout<<" Given Serial : "<<device_serial_number_<<std::endl;
std::stringstream ss_serial;
ss_serial<< device_list[i].get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);
if(!device_serial_number_.compare(ss_serial.str())){
std::cout<<" Found matching serial number."<<std::endl;
found_device = i;
}
}
std::cout<<" ---------------------------------------- "<<std::endl;
if(found_device != -1){
rs2_device_ = device_list[found_device];
assert(rs2_device_ && "Not able to connect to device");
return true;
} else {
if(device_list.size() == 1){
std::cout<<"Not able to find the correct device (serial number)."<<std::endl;
std::cout<<"Only one device found connect to this!"<<std::endl;
rs2_device_ = device_list[0];
assert(rs2_device_ && "Not able to connect to device");
return true;
} else {
std::cout<<"Not able to find the correct device (serial number)"<<std::endl;
return false;
}
}
}
}
void RealSenSeWrapper::display_intrinsics_extrinsics()
{
std::cout<<TEXT_COLOR_RESET<< TEXT_COLOR_GREEN; // make the screen output Green
std::cout <<std::setw(40)<<"Colour Intrinsics"<<std::setw(20)<<"Depth Intrinsics"<<std::endl;
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout <<std::setw(20)<< "Cx"<<std::setw(20)<< color_intrinsics.ppx<<std::setw(20)<< depth_intrinsics.ppx<<std::endl;
std::cout <<std::setw(20)<< "Cy"<<std::setw(20)<< color_intrinsics.ppy<<std::setw(20)<< depth_intrinsics.ppy<<std::endl;
std::cout <<std::setw(20)<< "Fx"<<std::setw(20)<< color_intrinsics.fx<<std::setw(20)<< depth_intrinsics.fx<<std::endl;
std::cout <<std::setw(20)<< "Fy"<<std::setw(20)<< color_intrinsics.fy<<std::setw(20)<< depth_intrinsics.fy<<std::endl;
std::stringstream rgb_size, depth_size;
rgb_size << color_intrinsics.width<<" x "<< color_intrinsics.height;
depth_size << depth_intrinsics.width<<" x "<< depth_intrinsics.height;
std::cout <<std::setw(20)<<"Size"<<std::setw(20)<< rgb_size.str()<<std::setw(20)<<depth_size.str()<<std::endl;
std::cout <<std::setw(20)<< "Distortion model"<<std::setw(20) <<rs2_distortion_to_string(color_intrinsics.model)
<< std::setw(20)<<rs2_distortion_to_string(depth_intrinsics.model)<<std::endl;
std::cout <<std::setw(20)<< "Distortion coeffs"<<std::setw(20)<<color_intrinsics.coeffs[0] <<std::setw(20)<<depth_intrinsics.coeffs[0]<<std::endl;
std::cout <<std::setw(40)<<color_intrinsics.coeffs[1] <<std::setw(20)<<depth_intrinsics.coeffs[1]<<std::endl;
std::cout <<std::setw(40)<<color_intrinsics.coeffs[2] <<std::setw(20)<<depth_intrinsics.coeffs[2]<<std::endl;
std::cout <<std::setw(40)<<color_intrinsics.coeffs[3] <<std::setw(20)<<depth_intrinsics.coeffs[3]<<std::endl;
std::cout <<std::setw(40)<<color_intrinsics.coeffs[4] <<std::setw(20)<<depth_intrinsics.coeffs[4]<<std::endl;
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout <<"Depth to Colour Extrinsics"<<std::endl;
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout <<std::setw(20)<< "Rotation"<<" = "
<<std::setw( 2)<< "[ "<<std::setw(13)<<d2c_extrinsics.rotation[0] <<std::setw(15)<< d2c_extrinsics.rotation[3]<<std::setw(15)<< d2c_extrinsics.rotation[6]<<" ]"<<std::endl
<<std::setw(25)<< "[ "<<std::setw(13)<<d2c_extrinsics.rotation[1] <<std::setw(15)<< d2c_extrinsics.rotation[4]<<std::setw(15)<< d2c_extrinsics.rotation[7]<<" ]"<<std::endl
<<std::setw(25)<< "[ "<<std::setw(13)<<d2c_extrinsics.rotation[2] <<std::setw(15)<< d2c_extrinsics.rotation[5]<<std::setw(15)<< d2c_extrinsics.rotation[8]<<" ]"<<std::endl;
std::cout <<std::endl;
std::cout <<std::setw(20)<< "Translation"<<" = "<<"[ "<<std::setw(13) << d2c_extrinsics.translation[0] <<std::setw(15) << d2c_extrinsics.translation[1]<<std::setw(15) << d2c_extrinsics.translation[2]<<" ]"<<std::endl;
std::cout <<std::endl;
std::cout << "-----------------------------------------------------------------------------------------" <<std::endl;
std::cout<< TEXT_COLOR_RESET; // make the screen output normal
}
void RealSenSeWrapper::set_baseline(float in_baseline)
{
baseline = in_baseline;
}
float RealSenSeWrapper::get_baseline()
{
return baseline;
}
float RealSenSeWrapper::get_hfov_rad()
{
return (std::atan2(depth_intrinsics.ppx + 0.5f, depth_intrinsics.fx) + std::atan2(depth_intrinsics.width - (depth_intrinsics.ppx + 0.5f), depth_intrinsics.fx));
}
float RealSenSeWrapper::get_vfov_rad()
{
return (std::atan2(depth_intrinsics.ppy + 0.5f, depth_intrinsics.fy) + std::atan2(depth_intrinsics.height - (depth_intrinsics.ppy + 0.5f), depth_intrinsics.fy));
}
/*
* Returns the number of columns in invalid depth band. Don't use these columns
* Realsense uses left imager as reference, non overlapping region on left side of depth image must be ignored.
*/
float RealSenSeWrapper::calulate_invalid_depth_band()
{
//pages 55-56 from Intel-RealSense-D400-Series-Datasheet.pdf
//DBR (ratio of Invalid depth band to total horizontal image) = B/[2*Z*tan(HFOV/2)];
//Invalid Depth Band (in pixels) = HRes*DBR
//B= baseline
//Z= distance
//HFOV= horizontal depth FOV
float Z = 1000; //mm
float HFOV = get_hfov_rad();// rad
float DBR = baseline/(2.0*Z*tan(HFOV/2.0));
float invalid_depth_band = DBR* depth_intrinsics.width;
return std::ceil(invalid_depth_band);
}
/*
* Apply post processing on depthframe
* based on realsense example: https://github.com/IntelRealSense/librealsense/blob/master/examples/post-processing/rs-post-processing.cpp
*
* */
void RealSenSeWrapper::post_processing(rs2::depth_frame& input_depth_frame)
{
//Declare filters
rs2::decimation_filter dec_filter; // Decimation - reduces depth frame density
rs2::spatial_filter spat_filter; // Spatial - edge-preserving spatial smoothing
rs2::temporal_filter temp_filter; // Temporal - reduces temporal noise
//Declare disparity transform from depth to disparity and vice versa
const std::string disparity_filter_name = "Disparity";
rs2::disparity_transform disparity_to_depth(false);
dec_filter.process(input_depth_frame);
spat_filter.process(input_depth_frame);
temp_filter.process(input_depth_frame);
disparity_to_depth.process(input_depth_frame);
}
void RealSenSeWrapper::set_is_postprocess_enabled(bool value)
{
is_postprocess_enabled = value;
}
| [
"lutz@hs-ulm.de"
] | lutz@hs-ulm.de |
16e4cf34ca9c7af4e76849219ee1980154aa1798 | 0cbf4ba563610d48109381aea7599236783f96d2 | /src/pmd/pmd.cpp | a7c7570a1783a1c2b7e30344b0b8349940a15939 | [] | no_license | xsun89/emeralddb | 6a8971bcf09952987f8f3f5e46b6996d79918f94 | 27e690bec6b6ce346b19d31879a8ff7dfa211f9c | refs/heads/master | 2016-09-05T10:25:07.495114 | 2014-12-23T00:14:03 | 2014-12-23T00:14:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | /*******************************************************************************
Copyright (C) 2013 SequoiaDB Software Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License, version 3,
as published by the Free Software Foundation.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/license/>.
*******************************************************************************/
#include "pmd.hpp"
#include "pmdOptions.hpp"
#include "pd.hpp"
EDB_KRCB pmd_krcb ;
extern char _pdDiagLogPath [ OSS_MAX_PATHSIZE+1 ] ;
int EDB_KRCB::init ( pmdOptions *options )
{
setDBStatus ( EDB_DB_NORMAL ) ;
setDataFilePath ( options->getDBPath () ) ;
setLogFilePath ( options->getLogPath () ) ;
strncpy ( _pdDiagLogPath, getLogFilePath(), sizeof(_pdDiagLogPath) ) ;
setSvcName ( options->getServiceName () ) ;
setMaxPool ( options->getMaxPool () ) ;
//return _rtnMgr.rtnInitialize() ;
return EDB_OK ;
}
| [
"sunxin89@gmail.com"
] | sunxin89@gmail.com |
1797c4623367e0d47504ec17e49ebaffa339e5c4 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/extensions/shell/app/shell_main_delegate.h | 3db8ac5084fa8bfb14219eca60117bc417ac4962 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,772 | h | // 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.
#ifndef EXTENSIONS_SHELL_APP_SHELL_MAIN_DELEGATE_H_
#define EXTENSIONS_SHELL_APP_SHELL_MAIN_DELEGATE_H_
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/app/content_main_delegate.h"
namespace content {
class BrowserContext;
class ContentBrowserClient;
class ContentClient;
class ContentRendererClient;
}
namespace extensions {
class ShellBrowserMainDelegate;
class ShellMainDelegate : public content::ContentMainDelegate {
public:
ShellMainDelegate();
virtual ~ShellMainDelegate();
virtual bool BasicStartupComplete(int* exit_code) OVERRIDE;
virtual void PreSandboxStartup() OVERRIDE;
virtual content::ContentBrowserClient* CreateContentBrowserClient() OVERRIDE;
virtual content::ContentRendererClient* CreateContentRendererClient()
OVERRIDE;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
virtual void ZygoteStarting(
ScopedVector<content::ZygoteForkDelegate>* delegates) OVERRIDE;
#endif
protected:
virtual content::ContentClient* CreateContentClient();
virtual content::ContentBrowserClient* CreateShellContentBrowserClient();
virtual content::ContentRendererClient* CreateShellContentRendererClient();
virtual void InitializeResourceBundle();
private:
static bool ProcessNeedsResourceBundle(const std::string& process_type);
scoped_ptr<content::ContentClient> content_client_;
scoped_ptr<content::ContentBrowserClient> browser_client_;
scoped_ptr<content::ContentRendererClient> renderer_client_;
DISALLOW_COPY_AND_ASSIGN(ShellMainDelegate);
};
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
cad2fa408768ccba40c4508937f4d6e5911f95e9 | 5696f7e9bb6cb18e791be3f71e8a72f9a26a0a22 | /tools/WindowsMediaPlayer/CWMPMetadataText.h | c2423776a3f9da93f13582d4a1da1594dfd0533d | [
"MIT"
] | permissive | xylsxyls/xueyelingshuang | 0fdde992e430bdee38abb7aaf868b320e48dba64 | a646d281c4b2ec3c2b27de29a67860fccce22436 | refs/heads/master | 2023-08-04T01:02:35.112586 | 2023-07-17T09:30:27 | 2023-07-17T09:30:27 | 61,338,042 | 4 | 2 | null | null | null | null | GB18030 | C++ | false | false | 866 | h | // CWMPMetadataText.h : 由 Microsoft Visual C++ 创建的 ActiveX 控件包装类的声明
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CWMPMetadataText
class CWMPMetadataText : public COleDispatchDriver
{
public:
CWMPMetadataText() {} // 调用 COleDispatchDriver 默认构造函数
CWMPMetadataText(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CWMPMetadataText(const CWMPMetadataText& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// 属性
public:
// 操作
public:
CString get_Description()
{
CString result;
InvokeHelper(0x420, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL);
return result;
}
CString get_text()
{
CString result;
InvokeHelper(0x41f, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL);
return result;
}
};
| [
"yangnan@huaiye.com"
] | yangnan@huaiye.com |
e685174b40ebd9cbf0bb2f8d3fd686e4e0a4858d | 55cd997356533e66dd1e5ad585089836982620ad | /CustomControls/UICustomSingleControl/UICustomColorViewWidget.cpp | f80ca93ab7d1b6dc5bc45047d717c35dc41ab37c | [] | no_license | douzhongqiang/EasyCanvas | f8e34ee6b60acf825cecc388c2a4a03262039d31 | 84aad331afad1a43e77fcf3bb4ce093f80a60008 | refs/heads/master | 2023-07-25T22:36:15.453873 | 2023-07-15T07:18:02 | 2023-07-15T07:18:02 | 251,264,472 | 143 | 70 | null | null | null | null | UTF-8 | C++ | false | false | 2,555 | cpp | #include "UICustomColorViewWidget.h"
#include "UICustomCore/CustomStyleConfig.h"
#include <QPainter>
#include <QMouseEvent>
#include <QMimeData>
#include <QDrag>
UICustomColorViewWidget::UICustomColorViewWidget(QWidget* parent)
:CustomWidget(parent)
, m_selectedColor(g_StyleConfig->getHighLightColor())
{
g_StyleConfig->setCurrentStyle(this, "Transparent");
this->setAcceptDrops(false);
}
UICustomColorViewWidget::~UICustomColorViewWidget()
{
}
void UICustomColorViewWidget::customPaint(QPainter* painter)
{
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
if (m_isSelected)
{
QPen pen;
pen.setColor(m_selectedColor);
pen.setWidth(2);
painter->setPen(pen);
}
else
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(m_currentColor));
painter->drawRoundedRect(this->rect().adjusted(2, 2, -2, -2), 4, 4);
painter->restore();
}
QSize UICustomColorViewWidget::sizeHint() const
{
QSize size(80, 30);
return size;
}
void UICustomColorViewWidget::mousePressEvent(QMouseEvent* event)
{
if (m_isDragVisible)
{
QDrag *drag = new QDrag(this);
QMimeData *mineData = new QMimeData;
mineData->setColorData(m_currentColor);
drag->setMimeData(mineData);
drag->exec();
}
else
{
event->accept();
emit mousePressed();
}
}
void UICustomColorViewWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasColor())
event->acceptProposedAction();
emit dragEnterSignals();
}
void UICustomColorViewWidget::dragLeaveEvent(QDragLeaveEvent *event)
{
emit dragReleaseSignals();
}
void UICustomColorViewWidget::dragMoveEvent(QDragMoveEvent *event)
{
}
void UICustomColorViewWidget::dropEvent(QDropEvent *event)
{
if (!event->mimeData()->hasColor())
return;
// 设置当前颜色
QColor color = qvariant_cast<QColor>(event->mimeData()->colorData());
this->setCurrentColor(color);
emit dropSignal();
}
void UICustomColorViewWidget::setCurrentColor(const QColor& color)
{
m_currentColor = color;
this->update();
}
const QColor& UICustomColorViewWidget::getCurrentColor(void)
{
return m_currentColor;
}
void UICustomColorViewWidget::setDragVisible(bool isVisible)
{
m_isDragVisible = isVisible;
}
void UICustomColorViewWidget::setSelected(bool isSelected)
{
m_isSelected = isSelected;
this->update();
}
bool UICustomColorViewWidget::getSelected(void)
{
return m_isSelected;
}
| [
"514200399@qq.com"
] | 514200399@qq.com |
d9f2ade4eb765bebe8d93a31928f53653e310ee4 | e9854cb02e90dab7ec0a49c65f658babba819d56 | /Curve Editor Framework/QT/src/gui/itemviews/qlistview.h | 290542935a57b7fdf66f80b310f2610298bad2c1 | [] | no_license | katzeforest/Computer-Animation | 2bbb1df374d65240ca2209b3a75a0b6a8b99ad58 | 01481111a622ae8812fb0b76550f5d66de206bab | refs/heads/master | 2021-01-23T19:46:13.455834 | 2015-06-08T21:29:02 | 2015-06-08T21:29:02 | 37,092,780 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,832 | h | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QLISTVIEW_H
#define QLISTVIEW_H
#include <QtGui/qabstractitemview.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#ifndef QT_NO_LISTVIEW
class QListViewPrivate;
class Q_GUI_EXPORT QListView : public QAbstractItemView
{
Q_OBJECT
Q_ENUMS(Movement Flow ResizeMode LayoutMode ViewMode)
Q_PROPERTY(Movement movement READ movement WRITE setMovement)
Q_PROPERTY(Flow flow READ flow WRITE setFlow)
Q_PROPERTY(bool isWrapping READ isWrapping WRITE setWrapping)
Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
Q_PROPERTY(LayoutMode layoutMode READ layoutMode WRITE setLayoutMode)
Q_PROPERTY(int spacing READ spacing WRITE setSpacing)
Q_PROPERTY(QSize gridSize READ gridSize WRITE setGridSize)
Q_PROPERTY(ViewMode viewMode READ viewMode WRITE setViewMode)
Q_PROPERTY(int modelColumn READ modelColumn WRITE setModelColumn)
Q_PROPERTY(bool uniformItemSizes READ uniformItemSizes WRITE setUniformItemSizes)
Q_PROPERTY(int batchSize READ batchSize WRITE setBatchSize)
Q_PROPERTY(bool wordWrap READ wordWrap WRITE setWordWrap)
Q_PROPERTY(bool selectionRectVisible READ isSelectionRectVisible WRITE setSelectionRectVisible)
public:
enum Movement { Static, Free, Snap };
enum Flow { LeftToRight, TopToBottom };
enum ResizeMode { Fixed, Adjust };
enum LayoutMode { SinglePass, Batched };
enum ViewMode { ListMode, IconMode };
explicit QListView(QWidget *parent = 0);
~QListView();
void setMovement(Movement movement);
Movement movement() const;
void setFlow(Flow flow);
Flow flow() const;
void setWrapping(bool enable);
bool isWrapping() const;
void setResizeMode(ResizeMode mode);
ResizeMode resizeMode() const;
void setLayoutMode(LayoutMode mode);
LayoutMode layoutMode() const;
void setSpacing(int space);
int spacing() const;
void setBatchSize(int batchSize);
int batchSize() const;
void setGridSize(const QSize &size);
QSize gridSize() const;
void setViewMode(ViewMode mode);
ViewMode viewMode() const;
void clearPropertyFlags();
bool isRowHidden(int row) const;
void setRowHidden(int row, bool hide);
void setModelColumn(int column);
int modelColumn() const;
void setUniformItemSizes(bool enable);
bool uniformItemSizes() const;
void setWordWrap(bool on);
bool wordWrap() const;
void setSelectionRectVisible(bool show);
bool isSelectionRectVisible() const;
QRect visualRect(const QModelIndex &index) const;
void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);
QModelIndex indexAt(const QPoint &p) const;
void doItemsLayout();
void reset();
void setRootIndex(const QModelIndex &index);
Q_SIGNALS:
void indexesMoved(const QModelIndexList &indexes);
protected:
QListView(QListViewPrivate &, QWidget *parent = 0);
bool event(QEvent *e);
void scrollContentsBy(int dx, int dy);
void resizeContents(int width, int height);
QSize contentsSize() const;
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
void rowsInserted(const QModelIndex &parent, int start, int end);
void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
void mouseMoveEvent(QMouseEvent *e);
void mouseReleaseEvent(QMouseEvent *e);
void timerEvent(QTimerEvent *e);
void resizeEvent(QResizeEvent *e);
#ifndef QT_NO_DRAGANDDROP
void dragMoveEvent(QDragMoveEvent *e);
void dragLeaveEvent(QDragLeaveEvent *e);
void dropEvent(QDropEvent *e);
void startDrag(Qt::DropActions supportedActions);
void internalDrop(QDropEvent *e);
void internalDrag(Qt::DropActions supportedActions);
#endif // QT_NO_DRAGANDDROP
QStyleOptionViewItem viewOptions() const;
void paintEvent(QPaintEvent *e);
int horizontalOffset() const;
int verticalOffset() const;
QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers);
QRect rectForIndex(const QModelIndex &index) const;
void setPositionForIndex(const QPoint &position, const QModelIndex &index);
void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command);
QRegion visualRegionForSelection(const QItemSelection &selection) const;
QModelIndexList selectedIndexes() const;
void updateGeometries();
bool isIndexHidden(const QModelIndex &index) const;
void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
private:
friend class QAccessibleItemView;
int visualIndex(const QModelIndex &index) const;
Q_DECLARE_PRIVATE(QListView)
Q_DISABLE_COPY(QListView)
};
#endif // QT_NO_LISTVIEW
QT_END_NAMESPACE
QT_END_HEADER
#endif // QLISTVIEW_H
| [
"sonyang@seas.upenn.edu"
] | sonyang@seas.upenn.edu |
6c1862b908afb86b80e2b8941e5481c3fc1ab832 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/services/sharing/nearby/nearby_connections.cc | 181cc5baaa42fd876266e03dd4274af2667b7bd9 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 25,030 | cc | // Copyright 2020 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 "chrome/services/sharing/nearby/nearby_connections.h"
#include "base/files/file_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/nearby_sharing/logging/logging.h"
#include "chrome/services/sharing/nearby/nearby_connections_conversions.h"
#include "chrome/services/sharing/nearby/platform/input_file.h"
#include "chromeos/services/nearby/public/mojom/nearby_connections_types.mojom.h"
#include "third_party/nearby/src/cpp/core/core.h"
#include "third_party/nearby/src/cpp/core/internal/offline_service_controller.h"
namespace location {
namespace nearby {
namespace connections {
namespace {
// Delegates all ServiceController calls to the ServiceController instance
// passed to its constructor. This proxy class is required because although we
// share one ServiceController among multiple Cores, each Core takes ownership
// of the pointer that it is provided. Using this proxy allows each Core to
// delete the pointer it is provided without deleting the shared instance.
class ServiceControllerProxy : public ServiceController {
public:
explicit ServiceControllerProxy(ServiceController* inner_service_controller)
: inner_service_controller_(inner_service_controller) {}
~ServiceControllerProxy() override = default;
// ServiceController:
Status StartAdvertising(ClientProxy* client,
const std::string& service_id,
const ConnectionOptions& options,
const ConnectionRequestInfo& info) override {
return inner_service_controller_->StartAdvertising(client, service_id,
options, info);
}
void StopAdvertising(ClientProxy* client) override {
inner_service_controller_->StopAdvertising(client);
}
Status StartDiscovery(ClientProxy* client,
const std::string& service_id,
const ConnectionOptions& options,
const DiscoveryListener& listener) override {
return inner_service_controller_->StartDiscovery(client, service_id,
options, listener);
}
void StopDiscovery(ClientProxy* client) override {
inner_service_controller_->StopDiscovery(client);
}
void InjectEndpoint(ClientProxy* client,
const std::string& service_id,
const OutOfBandConnectionMetadata& metadata) override {
inner_service_controller_->InjectEndpoint(client, service_id, metadata);
}
Status RequestConnection(ClientProxy* client,
const std::string& endpoint_id,
const ConnectionRequestInfo& info,
const ConnectionOptions& options) override {
return inner_service_controller_->RequestConnection(client, endpoint_id,
info, options);
}
Status AcceptConnection(ClientProxy* client,
const std::string& endpoint_id,
const PayloadListener& listener) override {
return inner_service_controller_->AcceptConnection(client, endpoint_id,
listener);
}
Status RejectConnection(ClientProxy* client,
const std::string& endpoint_id) override {
return inner_service_controller_->RejectConnection(client, endpoint_id);
}
void InitiateBandwidthUpgrade(ClientProxy* client,
const std::string& endpoint_id) override {
inner_service_controller_->InitiateBandwidthUpgrade(client, endpoint_id);
}
void SendPayload(ClientProxy* client,
const std::vector<std::string>& endpoint_ids,
Payload payload) override {
inner_service_controller_->SendPayload(client, endpoint_ids,
std::move(payload));
}
Status CancelPayload(ClientProxy* client, Payload::Id payload_id) override {
return inner_service_controller_->CancelPayload(client,
std::move(payload_id));
}
void DisconnectFromEndpoint(ClientProxy* client,
const std::string& endpoint_id) override {
inner_service_controller_->DisconnectFromEndpoint(client, endpoint_id);
}
private:
ServiceController* inner_service_controller_ = nullptr;
};
ConnectionRequestInfo CreateConnectionRequestInfo(
const std::vector<uint8_t>& endpoint_info,
mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener) {
mojo::SharedRemote<mojom::ConnectionLifecycleListener> remote(
std::move(listener));
return ConnectionRequestInfo{
.endpoint_info = ByteArrayFromMojom(endpoint_info),
.listener = {
.initiated_cb =
[remote](const std::string& endpoint_id,
const ConnectionResponseInfo& info) {
if (!remote)
return;
remote->OnConnectionInitiated(
endpoint_id,
mojom::ConnectionInfo::New(
info.authentication_token,
ByteArrayToMojom(info.raw_authentication_token),
ByteArrayToMojom(info.remote_endpoint_info),
info.is_incoming_connection));
},
.accepted_cb =
[remote](const std::string& endpoint_id) {
if (!remote)
return;
remote->OnConnectionAccepted(endpoint_id);
},
.rejected_cb =
[remote](const std::string& endpoint_id, Status status) {
if (!remote)
return;
remote->OnConnectionRejected(endpoint_id,
StatusToMojom(status.value));
},
.disconnected_cb =
[remote](const std::string& endpoint_id) {
if (!remote)
return;
remote->OnDisconnected(endpoint_id);
},
.bandwidth_changed_cb =
[remote](const std::string& endpoint_id, Medium medium) {
if (!remote)
return;
remote->OnBandwidthChanged(endpoint_id, MediumToMojom(medium));
},
},
};
}
} // namespace
// Should only be accessed by objects within lifetime of NearbyConnections.
NearbyConnections* g_instance = nullptr;
// static
NearbyConnections& NearbyConnections::GetInstance() {
DCHECK(g_instance);
return *g_instance;
}
NearbyConnections::NearbyConnections(
mojo::PendingReceiver<mojom::NearbyConnections> nearby_connections,
mojom::NearbyConnectionsDependenciesPtr dependencies,
scoped_refptr<base::SequencedTaskRunner> io_task_runner,
base::OnceClosure on_disconnect,
std::unique_ptr<ServiceController> service_controller)
: nearby_connections_(this, std::move(nearby_connections)),
on_disconnect_(std::move(on_disconnect)),
service_controller_(std::move(service_controller)),
thread_task_runner_(base::ThreadTaskRunnerHandle::Get()) {
nearby_connections_.set_disconnect_handler(base::BindOnce(
&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr()));
if (dependencies->bluetooth_adapter) {
bluetooth_adapter_.Bind(std::move(dependencies->bluetooth_adapter),
io_task_runner);
bluetooth_adapter_.set_disconnect_handler(
base::BindOnce(&NearbyConnections::OnDisconnect,
weak_ptr_factory_.GetWeakPtr()),
base::SequencedTaskRunnerHandle::Get());
}
socket_manager_.Bind(
std::move(dependencies->webrtc_dependencies->socket_manager),
io_task_runner);
socket_manager_.set_disconnect_handler(
base::BindOnce(&NearbyConnections::OnDisconnect,
weak_ptr_factory_.GetWeakPtr()),
base::SequencedTaskRunnerHandle::Get());
mdns_responder_.Bind(
std::move(dependencies->webrtc_dependencies->mdns_responder),
io_task_runner);
mdns_responder_.set_disconnect_handler(
base::BindOnce(&NearbyConnections::OnDisconnect,
weak_ptr_factory_.GetWeakPtr()),
base::SequencedTaskRunnerHandle::Get());
ice_config_fetcher_.Bind(
std::move(dependencies->webrtc_dependencies->ice_config_fetcher),
io_task_runner);
ice_config_fetcher_.set_disconnect_handler(
base::BindOnce(&NearbyConnections::OnDisconnect,
weak_ptr_factory_.GetWeakPtr()),
base::SequencedTaskRunnerHandle::Get());
webrtc_signaling_messenger_.Bind(
std::move(dependencies->webrtc_dependencies->messenger), io_task_runner);
webrtc_signaling_messenger_.set_disconnect_handler(
base::BindOnce(&NearbyConnections::OnDisconnect,
weak_ptr_factory_.GetWeakPtr()),
base::SequencedTaskRunnerHandle::Get());
// There should only be one instance of NearbyConnections in a process.
DCHECK(!g_instance);
g_instance = this;
// Note: Some tests pass a value for |service_controller_|, but this value is
// expected to be null during normal operation.
if (!service_controller_) {
// OfflineServiceController indirectly invokes
// NearbyConnections::GetInstance(), so it must be initialized after
// |g_instance| is set.
service_controller_ = std::make_unique<OfflineServiceController>();
}
}
NearbyConnections::~NearbyConnections() {
// Note that deleting active Core objects invokes their shutdown flows. This
// is required to ensure that Nearby cleans itself up.
service_id_to_core_map_.clear();
g_instance = nullptr;
}
void NearbyConnections::OnDisconnect() {
if (on_disconnect_)
std::move(on_disconnect_).Run();
// Note: |this| might be destroyed here.
}
void NearbyConnections::StartAdvertising(
const std::string& service_id,
const std::vector<uint8_t>& endpoint_info,
mojom::AdvertisingOptionsPtr options,
mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener,
StartAdvertisingCallback callback) {
ConnectionOptions connection_options{
.strategy = StrategyFromMojom(options->strategy),
.allowed = MediumSelectorFromMojom(options->allowed_mediums.get()),
.auto_upgrade_bandwidth = options->auto_upgrade_bandwidth,
.enforce_topology_constraints = options->enforce_topology_constraints,
.enable_bluetooth_listening = options->enable_bluetooth_listening,
.fast_advertisement_service_uuid =
options->fast_advertisement_service_uuid.canonical_value()};
GetCore(service_id)
->StartAdvertising(
service_id, std::move(connection_options),
CreateConnectionRequestInfo(endpoint_info, std::move(listener)),
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::StopAdvertising(const std::string& service_id,
StopAdvertisingCallback callback) {
GetCore(service_id)
->StopAdvertising(ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::StartDiscovery(
const std::string& service_id,
mojom::DiscoveryOptionsPtr options,
mojo::PendingRemote<mojom::EndpointDiscoveryListener> listener,
StartDiscoveryCallback callback) {
// Left as empty string if no value has been passed in |options|.
std::string fast_advertisement_service_uuid;
if (options->fast_advertisement_service_uuid) {
fast_advertisement_service_uuid =
options->fast_advertisement_service_uuid->canonical_value();
}
ConnectionOptions connection_options{
.strategy = StrategyFromMojom(options->strategy),
.allowed = MediumSelectorFromMojom(options->allowed_mediums.get()),
.is_out_of_band_connection = options->is_out_of_band_connection,
.fast_advertisement_service_uuid = fast_advertisement_service_uuid};
mojo::SharedRemote<mojom::EndpointDiscoveryListener> remote(
std::move(listener), thread_task_runner_);
DiscoveryListener discovery_listener{
.endpoint_found_cb =
[task_runner = thread_task_runner_, remote](
const std::string& endpoint_id, const ByteArray& endpoint_info,
const std::string& service_id) {
if (!remote) {
return;
}
// This call must be posted to the same sequence that |remote| was
// bound on.
task_runner->PostTask(
FROM_HERE,
base::BindOnce(
&mojom::EndpointDiscoveryListener::OnEndpointFound,
base::Unretained(remote.get()), endpoint_id,
mojom::DiscoveredEndpointInfo::New(
ByteArrayToMojom(endpoint_info), service_id)));
},
.endpoint_lost_cb =
[task_runner = thread_task_runner_,
remote](const std::string& endpoint_id) {
if (!remote) {
return;
}
// This call must be posted to the same sequence that |remote| was
// bound on.
task_runner->PostTask(
FROM_HERE,
base::BindOnce(
&mojom::EndpointDiscoveryListener::OnEndpointLost,
base::Unretained(remote.get()), endpoint_id));
},
};
ResultCallback result_callback = ResultCallbackFromMojom(std::move(callback));
GetCore(service_id)
->StartDiscovery(service_id, std::move(connection_options),
std::move(discovery_listener),
std::move(result_callback));
}
void NearbyConnections::StopDiscovery(const std::string& service_id,
StopDiscoveryCallback callback) {
GetCore(service_id)
->StopDiscovery(ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::InjectBluetoothEndpoint(
const std::string& service_id,
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info,
const std::vector<uint8_t>& remote_bluetooth_mac_address,
InjectBluetoothEndpointCallback callback) {
OutOfBandConnectionMetadata oob_metadata{
.medium = Medium::BLUETOOTH,
.endpoint_id = endpoint_id,
.endpoint_info = ByteArrayFromMojom(endpoint_info),
.remote_bluetooth_mac_address =
ByteArrayFromMojom(remote_bluetooth_mac_address)};
GetCore(service_id)
->InjectEndpoint(service_id, oob_metadata,
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::RequestConnection(
const std::string& service_id,
const std::vector<uint8_t>& endpoint_info,
const std::string& endpoint_id,
mojom::ConnectionOptionsPtr options,
mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener,
RequestConnectionCallback callback) {
ConnectionOptions connection_options{
.allowed = MediumSelectorFromMojom(options->allowed_mediums.get())};
if (options->remote_bluetooth_mac_address) {
connection_options.remote_bluetooth_mac_address =
ByteArrayFromMojom(*options->remote_bluetooth_mac_address);
}
GetCore(service_id)
->RequestConnection(
endpoint_id,
CreateConnectionRequestInfo(endpoint_info, std::move(listener)),
std::move(connection_options),
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::DisconnectFromEndpoint(
const std::string& service_id,
const std::string& endpoint_id,
DisconnectFromEndpointCallback callback) {
GetCore(service_id)
->DisconnectFromEndpoint(endpoint_id,
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::AcceptConnection(
const std::string& service_id,
const std::string& endpoint_id,
mojo::PendingRemote<mojom::PayloadListener> listener,
AcceptConnectionCallback callback) {
mojo::SharedRemote<mojom::PayloadListener> remote(std::move(listener));
// Capturing Core* is safe as Core owns PayloadListener.
PayloadListener payload_listener = {
.payload_cb =
[&, remote, core = GetCore(service_id)](
const std::string& endpoint_id, Payload payload) {
if (!remote)
return;
switch (payload.GetType()) {
case Payload::Type::kBytes: {
mojom::BytesPayloadPtr bytes_payload = mojom::BytesPayload::New(
ByteArrayToMojom(payload.AsBytes()));
remote->OnPayloadReceived(
endpoint_id,
mojom::Payload::New(payload.GetId(),
mojom::PayloadContent::NewBytes(
std::move(bytes_payload))));
break;
}
case Payload::Type::kFile: {
DCHECK(payload.AsFile());
// InputFile is created by Chrome, so it's safe to downcast.
chrome::InputFile& input_file = static_cast<chrome::InputFile&>(
payload.AsFile()->GetInputStream());
base::File file = input_file.ExtractUnderlyingFile();
if (!file.IsValid()) {
core->CancelPayload(payload.GetId(), /*callback=*/{});
return;
}
mojom::FilePayloadPtr file_payload =
mojom::FilePayload::New(std::move(file));
remote->OnPayloadReceived(
endpoint_id,
mojom::Payload::New(payload.GetId(),
mojom::PayloadContent::NewFile(
std::move(file_payload))));
break;
}
case Payload::Type::kStream:
buffer_manager_.StartTrackingPayload(std::move(payload));
break;
case Payload::Type::kUnknown:
core->CancelPayload(payload.GetId(), /*callback=*/{});
return;
}
},
.payload_progress_cb =
[&, remote](const std::string& endpoint_id,
const PayloadProgressInfo& info) {
if (!remote)
return;
DCHECK_GE(info.total_bytes, 0);
DCHECK_GE(info.bytes_transferred, 0);
remote->OnPayloadTransferUpdate(
endpoint_id,
mojom::PayloadTransferUpdate::New(
info.payload_id, PayloadStatusToMojom(info.status),
info.total_bytes, info.bytes_transferred));
if (!buffer_manager_.IsTrackingPayload(info.payload_id))
return;
switch (info.status) {
case PayloadProgressInfo::Status::kFailure:
FALLTHROUGH;
case PayloadProgressInfo::Status::kCanceled:
buffer_manager_.StopTrackingFailedPayload(info.payload_id);
break;
case PayloadProgressInfo::Status::kInProgress:
// Note that |info.bytes_transferred| is a cumulative measure of
// bytes that have been sent so far in the payload.
buffer_manager_.HandleBytesTransferred(info.payload_id,
info.bytes_transferred);
break;
case PayloadProgressInfo::Status::kSuccess:
// When kSuccess is passed, we are guaranteed to have received a
// previous kInProgress update with the same |bytes_transferred|
// value.
// Since we have completed fetching the full payload, return the
// completed payload as a "bytes" payload.
remote->OnPayloadReceived(
endpoint_id,
mojom::Payload::New(
info.payload_id,
mojom::PayloadContent::NewBytes(
mojom::BytesPayload::New(ByteArrayToMojom(
buffer_manager_
.GetCompletePayloadAndStopTracking(
info.payload_id))))));
break;
}
}};
GetCore(service_id)
->AcceptConnection(endpoint_id, std::move(payload_listener),
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::RejectConnection(const std::string& service_id,
const std::string& endpoint_id,
RejectConnectionCallback callback) {
GetCore(service_id)
->RejectConnection(endpoint_id,
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::SendPayload(
const std::string& service_id,
const std::vector<std::string>& endpoint_ids,
mojom::PayloadPtr payload,
SendPayloadCallback callback) {
Payload core_payload;
switch (payload->content->which()) {
case mojom::PayloadContent::Tag::BYTES:
core_payload =
Payload(payload->id,
ByteArrayFromMojom(payload->content->get_bytes()->bytes));
break;
case mojom::PayloadContent::Tag::FILE:
int64_t file_size = payload->content->get_file()->file.GetLength();
{
base::AutoLock al(input_file_lock_);
input_file_map_.insert_or_assign(
payload->id, std::move(payload->content->get_file()->file));
}
core_payload = Payload(payload->id, InputFile(payload->id, file_size));
break;
}
GetCore(service_id)
->SendPayload(absl::MakeSpan(endpoint_ids), std::move(core_payload),
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::CancelPayload(const std::string& service_id,
int64_t payload_id,
CancelPayloadCallback callback) {
GetCore(service_id)
->CancelPayload(payload_id, ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::StopAllEndpoints(const std::string& service_id,
StopAllEndpointsCallback callback) {
GetCore(service_id)
->StopAllEndpoints(ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::InitiateBandwidthUpgrade(
const std::string& service_id,
const std::string& endpoint_id,
InitiateBandwidthUpgradeCallback callback) {
GetCore(service_id)
->InitiateBandwidthUpgrade(endpoint_id,
ResultCallbackFromMojom(std::move(callback)));
}
void NearbyConnections::RegisterPayloadFile(
const std::string& service_id,
int64_t payload_id,
base::File input_file,
base::File output_file,
RegisterPayloadFileCallback callback) {
if (!input_file.IsValid() || !output_file.IsValid()) {
std::move(callback).Run(mojom::Status::kError);
return;
}
{
base::AutoLock al(input_file_lock_);
input_file_map_.insert_or_assign(payload_id, std::move(input_file));
}
{
base::AutoLock al(output_file_lock_);
output_file_map_.insert_or_assign(payload_id, std::move(output_file));
}
std::move(callback).Run(mojom::Status::kSuccess);
}
base::File NearbyConnections::ExtractInputFile(int64_t payload_id) {
base::AutoLock al(input_file_lock_);
auto file_it = input_file_map_.find(payload_id);
if (file_it == input_file_map_.end())
return base::File();
base::File file = std::move(file_it->second);
input_file_map_.erase(file_it);
return file;
}
base::File NearbyConnections::ExtractOutputFile(int64_t payload_id) {
base::AutoLock al(output_file_lock_);
auto file_it = output_file_map_.find(payload_id);
if (file_it == output_file_map_.end())
return base::File();
base::File file = std::move(file_it->second);
output_file_map_.erase(file_it);
return file;
}
scoped_refptr<base::SingleThreadTaskRunner>
NearbyConnections::GetThreadTaskRunner() {
return thread_task_runner_;
}
Core* NearbyConnections::GetCore(const std::string& service_id) {
std::unique_ptr<Core>& core = service_id_to_core_map_[service_id];
if (!core) {
core = std::make_unique<Core>([&]() {
// Core expects to take ownership of the pointer provided, but since we
// share a single ServiceController among all Core objects created, we
// provide a delegate which calls into our shared instance.
return new ServiceControllerProxy(service_controller_.get());
});
}
return core.get();
}
} // namespace connections
} // namespace nearby
} // namespace location
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b71e50af33cf710c2ba1980e001650fff243a38a | 3b91dfd4409513207575f2728918a1e2e484e13b | /trunk/tools/lvvfs/lvvfs.cpp | a68f4ee6121ddf802d7dd38ecae74a9c7992878b | [] | no_license | wingfiring/xirang | 16a8b10de9965b7609153acb8d4cfe878a089aa5 | eda84647cca476a29e8d785b8fd8ceda78bb952f | refs/heads/master | 2019-06-15T08:06:44.692019 | 2017-06-04T10:25:57 | 2017-06-04T10:25:57 | 6,007,811 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,279 | cpp | #include <iostream>
#include <xirang/versionedvfs.h>
#include <xirang/fsutility.h>
#include <xirang/vfs/local.h>
#include <xirang/vfs/inmemory.h>
#include <xirang/vfs/subvfs.h>
#include <xirang/io/exchs11n.h>
#include <xirang/io/path.h>
#include <xirang/io/file.h>
#include <xirang/io/memory.h>
#include <unordered_map>
using namespace xirang;
using std::cout;
using std::cerr;
using std::endl;
void cmd_init(int argc, char** argv){
if (argc != 0){
cerr << "init \n";
return;
}
file_path dir;
vfs::LocalFs vfs(dir);
dir = file_path("mygit");
vfs.createDir(dir);
vfs.createDir(dir/file_path("stage"));
auto err = vfs::initRepository(vfs, dir);
if (err == fs::er_ok){
std::cout << "OK.\n";
}
else
std::cout << "Error:" << int(err) << std::endl;
}
void log_submission(){
vfs::LocalFs vfs(file_path("mygit"));
vfs::RepoManager rpmgr;
auto repo = rpmgr.getRepo(vfs, sub_file_path());
auto sub = repo->getSubmission(version_type());
if (sub.version == version_type()){
cout << "Empty repo\n";
}
for(;;){
cout << sub.version.id << "\t" << sub.tree.id << endl;
if (!is_empty(sub.prev))
sub = repo->getSubmission(sub.prev);
else
break;
}
}
void log_file(const file_path& p){
vfs::LocalFs vfs(file_path("mygit"));
vfs::RepoManager rpmgr;
auto repo = rpmgr.getRepo(vfs, sub_file_path());
for(auto& i : repo->history(p)){
cout << i.submission.id << "\t" << i.version.id << endl;
}
}
void cmd_log(int argc, char** argv){
if (argc > 1){
cerr << "log [path]\n";
return;
}
if (argc == 0){
log_submission();
}
else {
log_file(file_path(argv[0]));
}
}
void cmd_add(int argc, char** argv){
if (argc < 1){
cout << "usage: add files ...\n";
return;
}
vfs::LocalFs wkfs(file_path("mygit/stage"));
vfs::Workspace wk(wkfs, string());
for (int i = 0; i < argc; ++i){
try{
file_path path(argv[i]);
io::file_reader rd(path);
iref<io::read_map> src(rd);
auto dest = vfs::recursive_create<io::write_map>(wk, path, io::of_create_or_open);
copy_data(src.get<io::read_map>(), dest.get<io::write_map>());
cout << "\t" << path.str() << " added\n";
}
catch(exception& e){
cout << "Failed to add file " << argv[i] << endl;
cout << e.what() << endl;
}
}
}
void cmd_rm(int argc, char** argv){
if (argc < 1){
cout << "usage: add files ...\n";
return;
}
vfs::LocalFs rpfs(file_path("mygit"));
auto f = rpfs.create<io::random, io::writer>(file_path("wkremove"), io::of_create_or_open);
auto& seek = f.get<io::random>();
seek.seek(seek.size());
auto sink = io::exchange::as_sink(f.get<io::writer>());
for (int i = 0; i < argc; ++i)
sink & file_path(argv[i]);
}
void show_file(vfs::IVfs& fs, const file_path& dir){
for (auto& i: fs.children(dir)){
file_path path = dir/i.path;
if (fs.state(path).state == fs::st_regular){
cout << "\t" << path.str() << endl;
}
else
show_file(fs, path);
}
}
void do_show_stage(){
vfs::LocalFs wkfs(file_path("mygit/stage"));
vfs::Workspace wk(wkfs, string() );
try{
vfs::LocalFs rpfs(file_path("mygit"));
auto f = rpfs.create<io::reader>(file_path("wkremove"), io::of_open);
auto source = io::exchange::as_source(f.get<io::reader>());
while(f.get<io::reader>().readable()){
wk.markRemove(load<file_path>(source));
}
}
catch(exception&){}
cout << "Added:\n";
show_file(wk, file_path());
cout << "\nRemoved:\n";
for (auto& i : wk.allRemoved()){
cout << "\t" << i.str() << endl;
}
}
void cmd_show(int argc, char** argv){
if (argc == 0){
cout << "show \n"
<< "\tstage\n"
;
return;
}
if (string((const char*)argv[0]) == string("stage")){
do_show_stage();
}
}
void cmd_checkin(int argc, char** argv){
version_type base;
vfs::LocalFs vfs(file_path("mygit"));
vfs::LocalRepository repo(vfs, file_path());
vfs::LocalFs wkfs(file_path("mygit/stage"));
vfs::Workspace wk(wkfs, string());
try{
auto f = vfs.create<io::reader>(file_path("wkremove"), io::of_open);
auto source = io::exchange::as_source(f.get<io::reader>());
while(f.get<io::reader>().readable()){
wk.markRemove(load<file_path>(source));
}
}
catch(exception&){}
if (argc != 0){
base = version_type(sha1_digest(as_range_string(argv[0])));
}
else {
base = repo.getSubmission(version_type()).version;
}
auto c = repo.commit(wk, string("test"), base);
if (c.flag == vfs::bt_none)
cout << "Commit failed\n";
else {
cout << c.version.id << endl;
}
}
void cmd_cat(int argc, char** argv){
if (argc != 1){
cout << "cat <file id>\n";
return;
}
version_type id(sha1_digest(as_range_string(argv[0])));
vfs::LocalFs vfs(file_path("mygit"));
vfs::LocalRepository repo(vfs, file_path());
auto type = repo.blobType(id);
switch(type){
case vfs::bt_file:
{
auto f = repo.create<io::read_map>(file_path(string(string("#") << id.id.to_string())), io::of_open);
io::mem_archive mar;
io::copy_data<io::read_map, io::writer>(f.get<io::read_map>(), mar);
cout.write((const char*)mar.data().begin(), mar.data().size());
cout << endl;
}
break;
case vfs::bt_tree:
{
cout << "tree:\n";
for (auto& i: repo.treeItems(id)){
cout << i.version.id << "\t" << i.name.str() << endl;
}
}
break;
case vfs::bt_submission:
{
auto s = repo.getSubmission(id);
cout << "Submission:" << s.version.id << "\t" << s.description << endl;
}
break;
default:
cout << "Not found\n";
}
}
typedef std::function<void(int, char**)> command_type;
std::unordered_map<std::string, command_type> command_table = {
{std::string("init"), cmd_init},
{std::string("log"), cmd_log},
{std::string("add"), cmd_add},
{std::string("rm"), cmd_rm},
{std::string("show"), cmd_show},
{std::string("ci"), cmd_checkin},
{std::string("cat"), cmd_cat}
};
void print_help(){
cout << "command list:\n";
for (auto& i : command_table){
cout << i.first << endl;
}
}
int do_main(int argc, char** argv){
if (argc < 2){
print_help();
return 1;
}
std::string command(argv[1]);
auto pos = command_table.find(command);
if (pos == command_table.end()){
print_help();
return 1;
}
pos->second(argc - 2, argv + 2);
return 0;
}
int main(int argc, char** argv){
try{
return do_main(argc, argv);
}catch(exception& e){
cerr << e.what() << endl;
}
}
| [
"scy@icerote.com"
] | scy@icerote.com |
b2dc64e01315a1f831f773f2fbb5f085ec524a57 | d2d6aae454fd2042c39127e65fce4362aba67d97 | /build/iOS/Debug/include/Fuse.Navigation.GoForward.h | b00df20cd5e2dfb712a5cd8029c7da22bd941b80 | [] | no_license | Medbeji/Eventy | de88386ff9826b411b243d7719b22ff5493f18f5 | 521261bca5b00ba879e14a2992e6980b225c50d4 | refs/heads/master | 2021-01-23T00:34:16.273411 | 2017-09-24T21:16:34 | 2017-09-24T21:16:34 | 92,812,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | h | // This file was generated based on '/Users/medbeji/Library/Application Support/Fusetools/Packages/Fuse.Navigation/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Navigation.BackF-9e5acfb7.h>
namespace g{namespace Fuse{namespace Navigation{struct GoForward;}}}
namespace g{namespace Fuse{struct Node;}}
namespace g{
namespace Fuse{
namespace Navigation{
// public sealed class GoForward :4542
// {
::g::Fuse::Navigation::BackForwardNavigationTriggerAction_type* GoForward_typeof();
void GoForward__Perform1_fn(GoForward* __this, uObject* ctx, ::g::Fuse::Node* node);
struct GoForward : ::g::Fuse::Navigation::BackForwardNavigationTriggerAction
{
};
// }
}}} // ::g::Fuse::Navigation
| [
"medbeji@MacBook-Pro-de-MedBeji.local"
] | medbeji@MacBook-Pro-de-MedBeji.local |
4b7e39d6bb6623f77a0c0736845f8bf2c2f187b6 | f5303bee9003fe3ace6f82fa69de0377cea45cd8 | /service/service2/sys/openfile.cpp | 751f99aeda74e014dc534e24a77387b104ba180b | [
"MIT"
] | permissive | rdmenezes/exodusdb | 82c55d8c43934c30821dd2a752e83c1d792e154a | f732e366b74ff4697890ec0682bc3697b8cb0bfb | refs/heads/master | 2021-01-16T00:27:49.522747 | 2014-12-24T18:01:51 | 2014-12-24T18:01:51 | 32,968,924 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | #include <exodus/library.h>
libraryinit()
function main(in filename, io file, in similarfilename="") {
//opens a filename and returns file variable and true
//otherwise if similar file name it tries to create in same fashion
//otherwise
file = "";
for (var tryn=1; tryn<=2; ++tryn) {
if (file.open(filename)) {
return true;
}
//option to create file if it does not exist
var tt="";
if (tt.open(similarfilename)) {
var().createfile(filename);
}
}
call mssg(filename.quote() ^ " file is missing");
return false;
}
libraryexit()
| [
"neosys.com@415b895b-543e-5d66-3bb8-6f700c98dabf"
] | neosys.com@415b895b-543e-5d66-3bb8-6f700c98dabf |
31ad1c4762ef5fd099cdaf38c4703834f8fefdc0 | d5d2719a9ff2ca4c7e24068d5b82d1434b7646b2 | /So_nhi_phan_tu_1_den_N.cpp | c24e6830ffe09e290f790367c7e660d542eb8c35 | [] | no_license | cuongdh1603/Data-structure-and-Algorithm | a3610eb92c504c7c0f6dd19cbc6ab83d4b78999d | 0285562b694573e1f2b79e2caab985ae0c170298 | refs/heads/main | 2023-07-12T04:17:36.297555 | 2021-08-21T15:06:53 | 2021-08-21T15:06:53 | 352,666,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
short t;
cin>>t;
while(t--){
int n;
cin>>n;
deque<string> dq;
dq.push_back("1");
for(int i=0;i<n;i++){
string s = dq.front();
cout<<s<<' ';
dq.pop_front();
dq.push_back(s+'0');
dq.push_back(s+'1');
}
cout<<endl;
}
}
| [
"="
] | = |
7e96bd88692fff9b3945a80f9bdb9b635b6def39 | a64b801b31be97b6a717900ab1e07579b5174d09 | /lab7/Tests.cpp | 4c77c8b3fce434c62bcf6d481ce0d49091a3615e | [] | no_license | LauraDiosan-CS/lab5-6-template-stl-TaniaVarduca | 7844a8169767aed8d8a6a85b385e09b0a3fbaa47 | 5c27773c4f7efb80bc2317d18918f8bf42917b94 | refs/heads/master | 2021-05-18T10:29:25.595452 | 2020-04-13T04:54:31 | 2020-04-13T04:54:31 | 251,211,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,595 | cpp | #include "Tests.h"
#include "Aplicatie.h"
#include "RepoFile.h"
#include"Service.h"
#include <iostream>
#include <assert.h>
#include "tests.h"
using namespace std;
//teste constructori
void testConstructors() {
Aplicatie a1; //constructor implicit
assert((a1.getName() == NULL) && (a1.getConsumMemorieKb() == 0) && (a1.getStatusV() == NULL) && (a1.getStatusN() == NULL));
char a[5] = "a"; char s[5] = "ram"; char s1[5] = "ram";
Aplicatie a2(a, 5, s, s1); //constructor cu param
assert((strstr(a2.getName(), "a")) && (a2.getConsumMemorieKb() == 5) && (strstr(a2.getStatusV(), "ram")) && (strstr(a2.getStatusN(), "ram")));
Aplicatie a3(a2); //constructor de copiere
assert(a3 == a2);
}
//teste setteri, getteri
void testSetGet() {
Aplicatie a; char b[5] = "a"; char s[5] = "ram"; char s1[5] = "swap";
a.setName(b);
a.setConsumMemorieKb(1);
a.setStatusV(s);
a.setStatusN(s1);
assert((strstr(a.getName(), "a")) && (a.getConsumMemorieKb() == 1) && (strstr(a.getStatusV(), "ram")) && (strstr(a.getStatusN(), "swap")));
}
//test operator de egalitate
void testEqual() {
char a[5] = "a"; char b[5] = "b"; char s1[5] = "ram"; char s2[5] = "swap";
Aplicatie a1(a, 3, s1, s1);
Aplicatie a2(b, 12, s2, s2);
a1 = a2;
assert((strstr(a1.getName(), "b")) && (a1.getConsumMemorieKb() == 12) && (strstr(a1.getStatusV(), "swap")) && (strstr(a1.getStatusN(), "swap")));
}
//teste repository
void testRepoFile() {
RepoFile<Aplicatie> rf;
assert(rf.getSize() == 0); //dimensiune
int ram = 0;
rf.loadFromFile("aplicatiiTest.txt", ram); //citire din fisier
assert(rf.getSize() == 2);
Aplicatie a = Aplicatie("Aplic3", 3, "swap", "ram");
rf.addAplicatie(a); //adaugare
rf.saveToFile();
assert(rf.getSize() == 3);
/*map<int, Aplicatie> aplicatii = r.getAll();
map<int, Aplicatie>::iterator itr;
cout << endl << "Aplicatiile sunt: " << endl;
for (itr = aplicatii.begin(); itr != aplicatii.end(); ++itr) {
cout << "cheia: " << itr->first << ", aplicatia: " << itr->second;
cout << endl;
}*/
rf.delAplicatie(2); //stergere
rf.saveToFile();
assert(rf.getSize() == 2);
map<int, Aplicatie> res; res = rf.getAll(); //getAll
assert(res.size() == 2);
char nume[10] = "nume", status[10] = "ram";
rf.updateAplicatie(res.at(0), 0, nume, 500, status); //update
Aplicatie c = res.at(0);
assert(strstr(res.at(0).getName(), "nume") && res.at(0).getConsumMemorieKb() == 500 && strstr(res.at(0).getStatusN(), "ram"));
int n = rf.getSize();
Aplicatie b = Aplicatie("Aplic4", 4, "ram", "swap");
rf.addAplicatie(b);
rf.saveToFile(); //save to file
assert(rf.getAll().size() == (n + 1));
rf.delAplicatie(3);
char ch[2] = "a";
rf.updateAplicatie(res.at(0), 0, ch, 1, status);
rf.saveToFile();
}
void testService() {
Service s;
assert(s.getSize() == 0);
RepoFile<Aplicatie> rf;
Repo<Aplicatie>* r = &rf; int ram = 0;;
s.setRepo(r);
r->loadFromFile("aplicatiiTest.txt", ram);
assert(s.getSize() == 2);
assert(ram == 3);
char w[5] = "swap";
int capacitate = 10;
ram += 9;
s.addRAM(ram, capacitate); // test ram la adaugarea unei aplicatii
assert(ram == 9 && strcmp(s.getAll().at(0).getStatusN(), w) == 0 && strcmp(s.getAll().at(1).getStatusN(), w) == 0);
ram -= 9;
s.delRAM(ram, capacitate, 9); //test ram la stergerea unei aplicatii
assert(ram == 3 && strcmp(s.getAll().at(0).getStatusN(), w) != 0 && strcmp(s.getAll().at(1).getStatusN(), w) != 0);
}
void tests()
{
cout << "first tests ..." << endl;
testConstructors();
testSetGet();
testEqual();
testRepoFile();
testService();
cout <<endl<< "all tests are ok ... good job!" << endl << endl;
}
| [
"tania_varduca@yahoo.com"
] | tania_varduca@yahoo.com |
d995bc6ba6992969890ef85b341e82de5931ccf8 | 1e867f11e7974fc57b03d06646a7918a064fb052 | /leetCode/Repeated DNA Sequences.cpp | 559b5129f13a4ccc509f5f005b953fc95eaadbf4 | [] | no_license | Wahed08/ACM-Problem-Solving | f4d6b3615d0f8e935583028b3642a283c502d2b1 | d7bc101b51699bc165202f201bcc791687ce4fe6 | refs/heads/master | 2023-04-17T19:46:09.620633 | 2023-04-07T05:53:40 | 2023-04-07T05:53:40 | 188,804,904 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 529 | cpp | class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int ln = s.length();
map<string, int>mapp;
vector<string>vec;
if(ln < 10)
return {};
for(int i=0; i<ln; i++){
string str = s.substr(i, 10);
mapp[str]++;
if (mapp[str] == 2)
vec.push_back(str);
}
return vec;
}
};
| [
"noreply@github.com"
] | Wahed08.noreply@github.com |
8ff44774ff0db65565ea84ef6eeadeaf96d30ab5 | 4cf362f0f761a765097a23696c6af050e5d75a7e | /AstarSolver.cpp | 4fba1a365d6ed5cc45c4d5a03e4c49bce7a72fe0 | [] | no_license | Rui1223/robust_planning_icra2020 | 372d55977497dee67b8fed88c6ebb707da5488d6 | 73f9e94fcc5cf75b5a24ef77d99665cf62fa218c | refs/heads/master | 2022-03-07T13:31:24.102931 | 2019-11-23T03:23:15 | 2019-11-23T03:23:15 | 209,879,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,600 | cpp | /* This cpp file defines A* search on a given graph
with specified start and goal */
#include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
#include "Graph.hpp"
#include "AstarSolver.hpp"
#include "Timer.hpp"
AstarSolver_t::AstarSolver_t(Graph_t &g, int start, std::vector<int> goalSet)
{
// initialize the start & goal
m_start = start;
m_goalSet = goalSet;
m_targetPoses = g.getTargetPoses();
for (int i=0; i < m_goalSet.size(); i++)
{
m_goalmap[m_goalSet[i]] = m_targetPoses[i];
}
// essential elements for Astar search
computeH(g); // heuristics
m_G = std::vector<float>(g.getnNodes(), std::numeric_limits<float>::max());
m_G[m_start] = 0.0;
m_open.push(new AstarNode_t(m_start, m_H[m_start], m_G[m_start]+m_H[m_start], nullptr));
m_expanded = std::vector<bool>(g.getnNodes(), false);
m_isFailure = false;
}
AstarSolver_t::~AstarSolver_t()
{
while (!m_open.empty())
{
AstarNode_t* a1 = m_open.top();
delete a1;
m_open.pop();
}
for (auto &e : m_closed) { delete e; }
}
void AstarSolver_t::computeH(Graph_t &g)
{
std::vector<float> goal_mean = std::vector<float>(g.getState(0).size(), 0.0);
for (auto const &goal : m_goalSet)
{
std::vector<float> v_goal = g.getState(goal);
for (int j=0; j < v_goal.size(); j++)
{
goal_mean[j] = goal_mean[j] + v_goal[j];
}
}
for (int j=0; j < goal_mean.size(); j++)
{
goal_mean[j] = goal_mean[j] / m_goalSet.size();
}
std::vector<float> temp_v;
for (int i=0; i < g.getnNodes(); i++)
{
if (std::find(m_goalSet.begin(), m_goalSet.end(), i) != m_goalSet.end())
{
m_H.push_back(0.0);
continue;
}
// compute euclidean distance
float temp_h = 0.0;
temp_v = g.getState(i);
for (int j=0; j < goal_mean.size(); j++)
{
temp_h += pow(goal_mean[j]-temp_v[j], 2);
}
temp_h = sqrt(temp_h);
m_H.push_back(temp_h);
}
}
void AstarSolver_t::Astar_search(Graph_t &g)
{
while (!m_open.empty())
{
AstarNode_t *current = m_open.top();
m_open.pop();
// Now check if the current node has been expanded
if (m_expanded[current->m_id] == true)
{
// This node has been expanded with the lowest f value for its id
// No need to put it into the closed list
delete current;
continue;
}
m_closed.push_back(current);
m_expanded[current->m_id] = true;
// a goal in the goalSet has been found
if ( std::find(m_goalSet.begin(), m_goalSet.end(), current->m_id) != m_goalSet.end() )
{
std::cout << "Goal is connected all the way to the start\n";
back_track_path(); // construct your path
pathToTrajectory(g); // get the trajectory (a sequence of configurations)
computeLabels(g); // get the labels the path carries
// printLabels();
// print the pose the goal indicates
m_goalIdxReached = m_goalmap[current->m_id];
m_pathCost = current->m_f;
// std::cout << "The reaching target pose is: " << m_goalIdxReached << "\n";
// std::cout << "The cost: " << m_pathCost << "\n";
return;
}
// get neighbors of the current node
std::vector<int> neighbors = g.getNodeNeighbors(current->m_id);
for (auto const &neighbor : neighbors)
{
// check if the neighbor node has been visited or extended before
if ( m_expanded[neighbor] ) {continue;}
if ( m_G[neighbor] > m_G[current->m_id] + g.getEdgeCost(current->m_id, neighbor) )
{
m_G[neighbor] = m_G[current->m_id] + g.getEdgeCost(current->m_id, neighbor);
m_open.push(new AstarNode_t(neighbor, m_H[neighbor],
m_G[neighbor]+m_H[neighbor], current));
}
}
}
// You are reaching here since the open list is empty and the goal is not found
std::cout << "The problem is not solvable. Search failed...\n";
m_isFailure = true;
}
void AstarSolver_t::checkPathSuccess(int nhypo)
{
m_obstaclesCollided = 0;
m_isPathSuccess = true;
// compute the obstacles collided
// loop through the m_goalLabels
for (auto const &l : m_goalLabels)
{
if (l % nhypo == 0)
{
m_obstaclesCollided += 1;
}
}
if (m_obstaclesCollided != 0 or m_goalIdxReached != 0)
{
m_isPathSuccess = false;
}
}
void AstarSolver_t::back_track_path()
{
// start from the goal
AstarNode_t *current = m_closed[m_closed.size()-1];
while (current->m_id != m_start)
{
// keep backtracking the path until you reach the start
m_path.push_back(current->m_id);
current = current->m_parent;
}
// finally put the start into the path
m_path.push_back(current->m_id);
}
void AstarSolver_t::print_path()
{
// print the path for checking purpose
std::cout << "path: \n";
for (auto const &waypoint : m_path)
{
std::cout << waypoint << " ";
}
std::cout << "\n";
}
void AstarSolver_t::printLabels()
{
std::cout << "labels: " << "< ";
for (auto const &l : m_goalLabels)
{
std::cout << l << " ";
}
std::cout << ">\n";
}
void AstarSolver_t::print_cost()
{
std::cout << "cost: " << m_pathCost << "\n";
}
void AstarSolver_t::print_goalIdxReached()
{
std::cout << "The reaching target pose is: " << m_goalIdxReached << "\n";
}
void AstarSolver_t::printAll()
{
print_path();
print_cost();
printLabels();
print_goalIdxReached();
}
void AstarSolver_t::pathToTrajectory(Graph_t &g)
{
// start from the start
for (int i=m_path.size()-1; i >=0; i--)
{
m_trajectory.push_back(g.getState(m_path[i]));
}
// // print the trajectory for checking purpose
// std::cout << "The trajectory: \n";
// for (auto const &t : m_trajectory)
// {
// for (auto const &d : t)
// {
// std::cout << d << " ";
// }
// std::cout << "\n";
// }
}
void AstarSolver_t::writeTrajectory(std::string trajectory_file)
{
m_outFile_.open(trajectory_file);
if (m_outFile_.is_open())
{
for (auto const &t : m_trajectory)
{
for (auto const &d : t)
{
m_outFile_ << d << " ";
}
m_outFile_ << "\n";
}
}
m_outFile_.close();
}
void AstarSolver_t::computeLabels(Graph_t &g)
{
std::vector<int> temp_edgelabels;
for (int i = 0; i < m_path.size()-1; i++)
{
temp_edgelabels = g.getEdgeLabels(m_path[i], m_path[i+1]);
m_goalLabels = label_union(m_goalLabels, temp_edgelabels);
}
}
std::vector<int> AstarSolver_t::label_union(std::vector<int> s1, std::vector<int> s2)
{
// sort the sets first before applying union operation
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
// Declaring resultant vector for union
std::vector<int> v(s1.size()+s2.size());
// using function set_union() to compute union of 2
// containers v1 and v2 and store result in v
auto it = std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), v.begin());
// resizing new container
v.resize(it - v.begin());
return v;
} | [
"gilbertwr2012@gmail.com"
] | gilbertwr2012@gmail.com |
a42f6e2df0de944887371cfa0deb6b0dfa9dc05e | 9fcd0caf38e4e9eea4a8db1933898f7a4be80c23 | /src/regex.hpp | fbf69ce7f980e88e4bd89142fe1e7d7e2140f4d8 | [
"LicenseRef-scancode-public-domain"
] | permissive | kalven/CodeDB | 8312cc8de663efe2da97bf856271755eaacc7b97 | d38c87c076aa4ed03721d58152e16b65a1cf7145 | refs/heads/master | 2021-01-01T19:50:59.467235 | 2014-05-19T00:12:06 | 2014-05-19T00:12:06 | 522,529 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | hpp | // CodeDB - public domain - 2010 Daniel Andersson
#ifndef CODEDB_REGEX_HPP
#define CODEDB_REGEX_HPP
#include <stdexcept>
#include <memory>
#include <string>
class match_range {
public:
match_range() : m_begin(0), m_end(0) {}
match_range(const char* begin, const char* end)
: m_begin(begin), m_end(end) {}
const char* begin() const { return m_begin; }
const char* end() const { return m_end; }
operator std::string() const { return std::string(m_begin, m_end); }
private:
const char* m_begin;
const char* m_end;
};
class regex_error : public std::runtime_error {
public:
regex_error(const std::string& msg, const std::string& expr)
: std::runtime_error(msg), m_expr(expr) {}
~regex_error() throw() {}
std::string m_expr;
};
class regex {
public:
virtual ~regex();
bool match(const std::string& str);
bool match(const char* begin, const char* end);
bool search(const std::string& str);
bool search(const char* begin, const char* end);
virtual match_range what(int n) = 0;
private:
virtual bool do_match(const char* begin, const char* end) = 0;
virtual bool do_search(const char* begin, const char* end) = 0;
};
typedef std::unique_ptr<regex> regex_ptr;
regex_ptr compile_regex(const std::string& expr, int caps = 0,
const char* flags = "");
std::string escape_regex(const std::string& text);
#endif
| [
"kalven@gmail.com"
] | kalven@gmail.com |
46dd111ad56a94eaa3bc46cceee9b8a19dc3de92 | 1a3ba7b44c67c3313b8be684b4dd8b59047755eb | /EngineRuntime/UserInterface/BinaryLoader.h | df8709a977111a82ea079ae03cb8054be2efb7a7 | [] | no_license | lineCode/VirtualUI | 85522c5845f8971a6e601089feefa0e8a44bf51a | dc33712038a906c22c0e3711a03feaee24318484 | refs/heads/master | 2020-03-24T15:58:28.077505 | 2018-07-29T22:51:35 | 2018-07-29T22:51:35 | 142,808,529 | 0 | 1 | null | 2018-07-30T01:13:20 | 2018-07-30T01:13:19 | null | UTF-8 | C++ | false | false | 349 | h | #pragma once
#include "ShapeBase.h"
#include "Templates.h"
#include "ControlClasses.h"
#include "../Streaming.h"
namespace Engine
{
namespace UI
{
namespace Loader
{
void LoadUserInterfaceFromBinary(InterfaceTemplate & Template, Streaming::Stream * Source, IResourceLoader * ResourceLoader, IResourceResolver * ResourceResolver);
}
}
} | [
"36736607+ManweMSU@users.noreply.github.com"
] | 36736607+ManweMSU@users.noreply.github.com |
cf11278965bab01836385f551fbf9c349391ef92 | e6182f4fc40cdc8952a6f622816acbadb0dcdeed | /src/qt/sendcoinsentry.cpp | 6a8f1eeb46a4ebceb9f9763649773fdec58072fc | [
"MIT"
] | permissive | easynodecoind/EasyNode | 1abe35268a5f2ee6fa9f1354459aeb6706b24598 | e1987dc48f4eca5def95fdcfc42138818572f0c1 | refs/heads/master | 2020-03-09T08:02:04.122151 | 2018-04-09T18:38:16 | 2018-04-09T18:38:16 | 128,679,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,370 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The EasyNode Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(platformStyle)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
QString theme = GUIUtil::getThemeName();
// These icons are needed on Mac also!
ui->addressBookButton->setIcon(QIcon(":/icons/" + theme + "/address-book"));
ui->pasteButton->setIcon(QIcon(":/icons/" + theme + "/editpaste"));
ui->deleteButton->setIcon(QIcon(":/icons/" + theme + "/remove"));
ui->deleteButton_is->setIcon(QIcon(":/icons/" + theme + "/remove"));
ui->deleteButton_s->setIcon(QIcon(":/icons/" + theme + "/remove"));
// normal easynode address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying easynode address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
| [
"easynode@tuta.io"
] | easynode@tuta.io |
0cb639b821ac78015446f2fc5b0daf40a78901a3 | 204ced989c16e23faa5044e3dffe90ba60e941df | /RGBWW-H801/ESPeasy/Arduino/libraries/ArduinoJson/include/ArduinoJson/Deserialization/Comments.hpp | 6586777e82d67415282ebd04b401a89c5d25ba96 | [
"MIT"
] | permissive | ranseyer/home-automatics | 332e79b1718dbeb8377514cc8e404e2dbc65733a | 8bb1e3de9b85f72f7ba5c1052990b00944f569ba | refs/heads/master | 2021-07-08T05:27:27.792518 | 2021-04-12T14:32:14 | 2021-04-12T14:32:14 | 57,380,120 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | hpp | // Copyright Benoit Blanchon 2014-2016
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!
#pragma once
namespace ArduinoJson {
namespace Internals {
template <typename TInput>
void skipSpacesAndComments(TInput& input) {
for (;;) {
switch (input.current()) {
// spaces
case ' ':
case '\t':
case '\r':
case '\n':
input.move();
continue;
// comments
case '/':
switch (input.next()) {
// C-style block comment
case '*':
input.move(); // skip '/'
input.move(); // skip '*'
for (;;) {
switch (input.current()) {
case '\0':
return;
case '*':
input.move(); // skip '*'
if (input.current() == '/') {
input.move(); // skip '/'
return;
}
break;
default:
input.move();
}
}
break;
// C++-style line comment
case '/':
input.move(); // skip '/'
for (;;) {
switch (input.current()) {
case '\0':
return;
case '\n':
input.move();
return;
default:
input.move();
}
}
return;
// not a comment, just a '/'
default:
return;
}
break;
default:
return;
}
}
}
}
}
| [
"none@easy-vdr.de"
] | none@easy-vdr.de |
ee1a63e2aea65701efbca592d04a390dcacc1f5e | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-clouddirectory/include/aws/clouddirectory/model/FacetAttributeType.h | 6d1fc9336ef28c8d9b252b6b0304c06cd68b756c | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 1,207 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/clouddirectory/CloudDirectory_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace CloudDirectory
{
namespace Model
{
enum class FacetAttributeType
{
NOT_SET,
STRING,
BINARY,
BOOLEAN,
NUMBER,
DATETIME
};
namespace FacetAttributeTypeMapper
{
AWS_CLOUDDIRECTORY_API FacetAttributeType GetFacetAttributeTypeForName(const Aws::String& name);
AWS_CLOUDDIRECTORY_API Aws::String GetNameForFacetAttributeType(FacetAttributeType value);
} // namespace FacetAttributeTypeMapper
} // namespace Model
} // namespace CloudDirectory
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
5d3faaa74e48d5fc35951e13d06f8f283a2a793c | ee4d01750ed34c070a882c64ae41968c32b43996 | /chromakey/d3dUtil.cpp | a33a4bb48a71712d7ee98195f1ec546dc9885fe5 | [] | no_license | HowsonLiu/ChromaKey | e72121f4af81131a965bf65f959b8c82c36732b8 | b02175ec09ce24ce4b93797c4710fe153944849d | refs/heads/master | 2020-08-15T02:06:57.494100 | 2019-10-15T09:58:57 | 2019-10-15T09:58:57 | 215,264,752 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,879 | cpp | #include "stdafx.h"
#include "d3dUtil.h"
#include <D3DX11async.h>
//using namespace std::experimental;
HRESULT CreateShaderFromFile(
const WCHAR* csoFileNameInOut,
const WCHAR* hlslFileName,
LPCSTR entryPoint,
LPCSTR shaderModel,
ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
// // 寻找是否有已经编译好的顶点着色器
// if (csoFileNameInOut)// && filesystem::exists(csoFileNameInOut))
// {
// return D3DReadFileToBlob(csoFileNameInOut, ppBlobOut);
// }
// else
// {
// DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
// #ifdef _DEBUG
// // 设置 D3DCOMPILE_DEBUG 标志用于获取着色器调试信息。该标志可以提升调试体验,
// // 但仍然允许着色器进行优化操作
// dwShaderFlags |= D3DCOMPILE_DEBUG;
//
// // 在Debug环境下禁用优化以避免出现一些不合理的情况
// dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
// #endif
// ID3DBlob* errorBlob = nullptr;
// hr = D3DCompileFromFile(hlslFileName, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, entryPoint, shaderModel,
// dwShaderFlags, 0, ppBlobOut, &errorBlob);
// if (FAILED(hr))
// {
// if (errorBlob != nullptr)
// {
// OutputDebugStringA(reinterpret_cast<const char*>(errorBlob->GetBufferPointer()));
// }
// SAFE_RELEASE(errorBlob);
// return hr;
// }
//
// // 若指定了输出文件名,则将着色器二进制信息输出
// if (csoFileNameInOut)
// {
// return D3DWriteBlobToFile(*ppBlobOut, csoFileNameInOut, FALSE);
// }
// }
return hr;
}
//--------------------------------------------------------------------------------------
// Find and compile the specified shader
//--------------------------------------------------------------------------------------
HRESULT DX11CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
// // find the file
// WCHAR str[MAX_PATH];
// V_RETURN(DXUTFindDXSDKMediaFileCch(str, MAX_PATH, szFileName));
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
ID3DBlob* pErrorBlob;
hr = D3DX11CompileFromFile(szFileName, NULL, NULL, szEntryPoint, szShaderModel,
dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL);
if (FAILED(hr))
{
if (pErrorBlob != NULL)
OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
SAFE_RELEASE(pErrorBlob);
return hr;
}
SAFE_RELEASE(pErrorBlob);
return S_OK;
} | [
"948470636@qq.com"
] | 948470636@qq.com |
621e9287571de73771fc599d573d0dcf47db9fcc | b70c43d17abe9337847575bc36023afcbd0e6cad | /network/arduino/shared/ip/udp/UdpHelper.cpp | 0e0bfdd4182eb5c873fd31706219a4e0aefbf6cb | [] | no_license | S3ler/CMqttSnForwarder | ca4600b7d6c85b940f7a06e42155e19c90bb56c7 | 072ddf0fe40be35cf780cb501a79550bc7b32a25 | refs/heads/master | 2020-04-25T12:03:30.930538 | 2020-01-14T12:29:19 | 2020-01-14T12:29:19 | 172,766,029 | 1 | 1 | null | 2020-01-15T16:33:57 | 2019-02-26T18:24:31 | C | UTF-8 | C++ | false | false | 3,421 | cpp | //
// Created by SomeDude on 29.04.2019.
//
#include "UdpHelper.hpp"
#include <stdint.h>
#include <platform/device_address.h>
#include <network/arduino/shared/ip/ArduinoIpAddressHelper.hpp>
#include <string.h>
int32_t arduino_init_udp(WiFiUDP *wiFiUdp, uint16_t port) {
if (wiFiUdp->begin(port) == 1) {
return 0;
}
return -1;
}
void arduino_deinit_udp(WiFiUDP *wiFiUdp) {
wiFiUdp->stop();
}
int32_t arduino_send_udp(WiFiUDP *wiFiUdp, const device_address *destination, const uint8_t *bytes, uint16_t bytes_len) {
IPAddress destination_IPAddress;
uint16_t destination_port = 0;
arduino_device_address_to_IPAddress_and_port(destination, &destination_IPAddress, &destination_port);
if (wiFiUdp->beginPacket(destination_IPAddress, destination_port) == 1) {
uint16_t write_rc = wiFiUdp->write(bytes, bytes_len);
if (wiFiUdp->endPacket()) {
return write_rc;
}
}
return -1;
}
int32_t arduino_receive_udp(WiFiUDP *wiFiUdp, device_address *from, device_address *to, uint8_t *bytes, uint16_t max_bytes_len) {
if (wiFiUdp->parsePacket() > 0) {
memset(from, 0x0, sizeof(device_address));
memset(to, 0x0, sizeof(device_address));
int available = wiFiUdp->available();
if (available > max_bytes_len) {
// too much data => ignored
wiFiUdp->flush();
return 0;
}
if (wiFiUdp->read(bytes, max_bytes_len) == available) {
IPAddress remoteIP = wiFiUdp->remoteIP();
uint16_t remotePort = wiFiUdp->remotePort();
arduino_ipv4_and_port_to_device_address(&remoteIP, remotePort, from);
// ESP32 only:
IPAddress destinationIP = wiFiUdp->remoteIP();
uint16_t destinationPort = wiFiUdp->remotePort();
// ESP8266 only:
/*
IPAddress destinationIP = wiFiUdp->destinationIP();
uint16_t destinationPort = wiFiUdp->localPort();
*/
arduino_ipv4_and_port_to_device_address(&destinationIP, destinationPort, to);
return available;
}
}
return 0;
}
#ifdef WITH_UDP_BROADCAST
int arduino_join_multicast_udp(WiFiUDP *wiFiUdp, IPAddress bc_ip, uint16_t bc_port) {
// ESP32
if (wiFiUdp->beginMulticast(bc_ip, bc_port) == 1) {
return 0;
}
// ESP8266
/*
IPAddress localIP = WiFi.localIP();
if (wiFiUdp->beginMulticast(localIP, bc_ip, bc_port) == 1) {
return 0;
}
*/
return -1;
}
int32_t arduino_send_multicast_udp(WiFiUDP *wiFiUdp, const device_address *destination, const uint8_t *bytes, uint16_t bytes_len) {
IPAddress destination_IPAddress;
uint16_t destination_port = 0;
arduino_device_address_to_IPAddress_and_port(destination, &destination_IPAddress, &destination_port);
// ESP32
if (wiFiUdp->beginMulticastPacket() == 1) {
uint16_t write_rc = wiFiUdp->write(bytes, bytes_len);
if (wiFiUdp->endPacket()) {
return write_rc;
}
}
// ESP8266
/*
if (wiFiUdp->beginPacketMulticast(destination_IPAddress, destination_port, WiFi.localIP()) == 1) {
uint16_t write_rc = wiFiUdp->write(bytes, bytes_len);
if (wiFiUdp->endPacket()) {
return write_rc;
}
}
*/
return -1;
}
#endif
| [
"GabrielNikol@web.de"
] | GabrielNikol@web.de |
2e896eade36aa47dc9706ab9462e38ddc89f304a | 8248ce72ace5ebb6da3fa08efa84d1f707de4eb3 | /LE_Out.h | f9802742d2e357175898b79a3f04a7bc2857bd82 | [] | no_license | Reisbey-1/PLC_Ladder | c4acd14cbf13482a476d2dfdafae88326433c8c7 | 12afd86b66ca0e6a66f096f2a05aab30112548ed | refs/heads/main | 2023-06-20T21:20:59.439554 | 2021-07-28T16:35:56 | 2021-07-28T16:35:56 | 390,419,873 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 687 | h | // LE_Out.h: Schnittstelle für die Klasse CLE_Out.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_LE_OUT_H__B2B8114B_A52D_4EBF_A1A7_0820DFD58AAF__INCLUDED_)
#define AFX_LE_OUT_H__B2B8114B_A52D_4EBF_A1A7_0820DFD58AAF__INCLUDED_
#include "LE_Point.h"
namespace LadderDll
{
class LADDER_API CLE_Out : public CLE_Point
{
public:
CLE_Out();
virtual ~CLE_Out();
protected:
virtual void Draw(CDC& dc, CgxDrawer* pDrawer, CCell origin = CCell(0,0));
virtual void SetCenter(CCell cntPnt );
DECLARE_SERIAL(CLE_Out)
};
}
#endif // !defined(AFX_LE_OUT_H__B2B8114B_A52D_4EBF_A1A7_0820DFD58AAF__INCLUDED_)
| [
"noreply@github.com"
] | Reisbey-1.noreply@github.com |
f3aa776982a493fe1675804ac25a3280d95d6f67 | c82d4afeabb5247daf14045effea2dce06b82d54 | /C++/2_1_1/2_1_1/2_1_1.cpp | 4e208b5dbc169cd59652bf8b35a09b9d77b58ed0 | [] | no_license | lubolib/University_Code | d9bcfefde5c7e5fd5bf50676a9f957f20e049fd3 | 092752985de849385be39a6740befbde2deab4aa | refs/heads/master | 2022-03-22T23:13:27.702527 | 2019-09-26T23:47:06 | 2019-09-26T23:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | cpp | // 2_1_1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| [
"xixuecao@gmail.com"
] | xixuecao@gmail.com |
9dd7057eb535081e74de085b95cc4862fca18ecc | eca150147dad714dcfc30df3d5c1ebba50a2a3ad | /UVA/11723/9142517_AC_0ms_0kB.cpp | dbfa7ec8d676637fcd06366afb64d0f06dbcd8b7 | [] | no_license | Abdullahfoysal/ICPC-OJ | a4c54774e2b456c62f23e85a37fa9c5947d45d71 | 394f175fbd1da86e794c5af463a952bc872fe07d | refs/heads/master | 2020-04-18T03:56:29.667072 | 2018-04-17T16:29:43 | 2018-04-17T16:29:43 | 167,219,685 | 1 | 0 | null | 2019-01-23T16:58:02 | 2019-01-23T16:58:02 | null | UTF-8 | C++ | false | false | 423 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int r,d;
int i=1;
while(cin>>r>>d)
{
if(r==0 & d==0)
break;
int Count=0;
Count=r/d;
if(Count<=26)
{
if(r%d==0)
Count--;
cout<<"Case "<<i<<": "<<Count<<endl;
}
else
cout<<"Case "<<i<<": "<<"impossible"<<endl;
i++;
}
}
| [
"avoidcloud@gmail.com"
] | avoidcloud@gmail.com |
04fb7d231aebc7e892ad24813559a25f5529bc32 | b8f72bd3b4ad1f616ad74d4c32c55b3fd2888f44 | /codeforces gym/101341B.cpp | 20cb45508071a7812cc52fbedc13e2f66f527690 | [] | no_license | OloieriAlexandru/Competitive-Programming-Training | ec0692e2860e83ca934b0ec0912722360aa8c43c | eaaa5bbc766e32c61a6eab3da38a68abb001f509 | refs/heads/master | 2020-05-29T17:50:53.841346 | 2020-04-25T15:53:08 | 2020-04-25T15:53:08 | 189,284,832 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | cpp | #include <bits/stdc++.h>
#define nmax 200005
using namespace std;
char s[nmax];
int ln, cnt, poz, poz2;
bool ok()
{
for (int i=0; i<ln; ++i)
if (!strncmp(s+i,"happiness", 9))
return false;
return true;
}
int main()
{
scanf("%s",s);
ln = strlen(s);
for (int i=0; i<ln; ++i)
{
if (!strncmp(s+i,"happiness", 9))
{
++cnt;
if (cnt == 1)
poz = i;
else
poz2 = i;
}
}
if (cnt > 2)
{
cout<<"NO\n";
return 0;
}
cout<<"YES\n";
if (cnt == 0)
{
for (int i=1; i<ln; ++i)
{
swap(s[0],s[i]);
if (ok())
{
cout<<1<<' '<<i+1<<'\n';
return 0;
}
swap(s[0],s[i]);
}
for (int i=3;i<ln;++i)
{
swap(s[1],s[i]);
if (ok())
{
cout<<2<<' '<<i+1<<'\n';
return 0;
}
swap(s[1],s[i]);
}
}
else if (cnt == 1)
cout<<poz+1<<' '<<poz+2<<'\n';
else
cout<<poz+1<<' '<<poz2+2<<'\n';
return 0;
}
| [
"aoloieri@ias.bitdefender.biz"
] | aoloieri@ias.bitdefender.biz |
7a9ef3504d6922664f04e49879c65778861472f1 | 89055544193a903880e8f7c107dc4cb2506b85f5 | /PathPlanning/Astar.cpp | 4e265ab6724277384efb8561bcbc5986e7493f38 | [] | no_license | KyuhwanYeon/AlgorithmStudy | d344121bace18ed432bc5bf9d003dbd4d7ba68cf | d9d68843c50bcd631bec46f5824f63562298c15c | refs/heads/master | 2021-11-24T11:54:01.479313 | 2021-10-24T15:04:47 | 2021-10-24T15:04:47 | 201,750,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,927 | cpp | #include <iostream>
#include <string.h>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
class Map
{
public:
vector<vector<int>> grid{
{0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 0}};
vector<vector<int>> heuristic = {
{9, 8, 7, 6, 5, 4},
{8, 7, 6, 5, 4, 3},
{7, 6, 5, 4, 3, 2},
{6, 5, 4, 3, 2, 1},
{5, 4, 3, 2, 1, 0}};
int mapWidth = grid[0].size();
int mapHeight = grid.size();
private:
};
class Planner : Map
{
public:
vector<int> start{0, 0};
vector<int> goal{mapHeight - 1, mapWidth - 1};
int cost = 1;
string movements_arrows[4] = {"^", "<", "v", ">"};
vector<vector<int>> movements{
{-1, 0},
{0, -1},
{1, 0},
{0, 1}};
private:
};
template <typename T>
void Print2DVector(T vec2d)
{
for (int i = 0; i < vec2d.size(); i++)
{
for (int j = 0; j < vec2d[0].size(); j++)
{
cout << vec2d[i][j] << " ";
}
cout << endl;
}
}
vector<vector<int>> nextList(Map map, Planner planner, vector<int> curr, vector<vector<bool>> closelist, vector<vector<int>> &action)
{
vector<vector<int>> nextList;
int i = 0;
for (vector<int> movement : planner.movements)
{
vector<int> next{curr[2] + movement[0], curr[3] + movement[1]};
if (next[0] < map.grid.size() && next[0] >= 0 && next[1] < map.grid[1].size() && next[1] >= 0 && map.grid[next[0]][next[1]] == 0)
{
if (closelist[next[0]][next[1]] == false) // 방문하지 않았고
{
action[next[0]][next[1]] = i;
nextList.push_back(next);
}
}
i++;
}
return nextList;
}
void ConvertPath2ShortestPath(Planner planner, Map map, vector<vector<int>> action, vector<vector<string>> &path)
{
int x = planner.goal[1];
int y = planner.goal[0];
int nextx = planner.goal[1];
int nexty = planner.goal[0];
path[y][x] = "*";
while (x != planner.start[1] || y != planner.start[0])
{
nextx = x - planner.movements[action[y][x]][1];
nexty = y - planner.movements[action[y][x]][0];
path[nexty][nextx] = planner.movements_arrows[action[y][x]];
x = nextx;
y = nexty;
}
}
void PrintStates(int expansion, vector<vector<int>> openlist, vector<int> curr)
{
cout << endl;
cout << "Expansion#: " << expansion << endl;
cout << "Cell Picked: [" << curr[0] << " " << curr[1] << " " << curr[2] << " " << curr[3] << "]" << endl;
cout << "Openlist: ";
for (int i = 0; i < openlist.size(); i++)
{
cout << "[ " << openlist[i][0] << " " << openlist[i][1] << " " << openlist[i][2] << " " << openlist[i][3] << "]"
<< " ";
}
cout << endl;
}
void Search(Map map, Planner planner)
{
vector<vector<int>> openlist;
vector<vector<bool>> closelist(map.mapHeight, vector<bool>(map.mapWidth, false));
vector<vector<int>> expansionvector(map.mapHeight, vector<int>(map.mapWidth, -1));
vector<vector<int>> action(map.mapHeight, vector<int>(map.mapWidth, -1));
vector<vector<string>> path(map.mapHeight, vector<string>(map.mapWidth, "-"));
closelist[planner.start[0]][planner.start[1]] = true;
int g = 0;
int nextg = 0;
openlist.push_back({map.heuristic[planner.start[0]][planner.start[1]] + g, g, planner.start[0], planner.start[1]});
bool exit = false;
int expansion = 0;
while (!exit)
{
int openlistSize = openlist.size();
for (int i = 0; i < openlistSize; i++)
{
sort(openlist.begin(), openlist.end());
reverse(openlist.begin(), openlist.end());
vector<int> curr = openlist.back();
openlist.pop_back(); // 현재지점값을 Q에서 빼주고
vector<vector<int>> nextList_ = nextList(map, planner, curr, closelist, action);
nextg = curr[1] + planner.cost;
// 현재 상태에서 Q의 크기만큼만 인접 노드 조사하고 방문!
for (vector<int> next : nextList_) // 현재 노드에 연결되어있는 노드들 중에서 탐색
{
closelist[next[0]][next[1]] = true; //방문
openlist.push_back({nextg + map.heuristic[next[0]][next[1]], nextg, next[0], next[1]}); // 방문된 지점들을 Q에 추가해서 다음번 탐색에서 이용
}
expansionvector[curr[2]][curr[3]] = expansion;
PrintStates(expansion, openlist, curr);
expansion++;
if (curr[2] == planner.goal[0] && curr[3] == planner.goal[1])
{
cout << "[" << curr[0] << ", " << curr[1] << ", " << curr[2] << ", " << curr[3] << "]" << endl;
exit = true; // End 값을 찾았으면 탈출!
break;
}
}
}
//Print2DVector(action);
//cout<<"-------------------------"<<endl;
ConvertPath2ShortestPath(planner, map, action, path);
Print2DVector(path);
//Print2DVector(expansionvector);
}
int main()
{
// Instantiate map and planner objects
Map map;
Planner planner;
// Print classes variables
// cout << "Map:" << endl;
// Print2DVector(map.grid);
// cout << "Start: " << planner.start[0] << " , " << planner.start[1] << endl;
// cout << "Goal: " << planner.goal[0] << " , " << planner.goal[1] << endl;
// cout << "Cost: " << planner.cost << endl;
// cout << "Robot Movements: " << planner.movements_arrows[0] << " , " << planner.movements_arrows[1] << " , " << planner.movements_arrows[2] << " , " << planner.movements_arrows[3] << endl;
// cout << "Delta:" << endl;
// Print2DVector(planner.movements);
Search(map, planner);
return 0;
}
| [
"KyuhwanYeon@gmail.com"
] | KyuhwanYeon@gmail.com |
452acae905efef99541142c6b1722e373c74db73 | 4810365d4c281ee3656272189e822d9d14aff504 | /Include/GeoDB/GeoWell.h | 2e8ee2385ca2438d0f7c98fa93d4389b2b8c0d8b | [] | no_license | 15831944/GeoReavealLogApp | 869d67b036e7adfe865b0fb89b99c7f009049a6b | 36be9c1d3fea4d55d5e69c8872c2eb1f2c88db8b | refs/heads/main | 2023-03-08T13:28:04.334108 | 2021-02-19T03:59:21 | 2021-02-19T03:59:21 | 478,417,611 | 1 | 1 | null | 2022-04-06T05:37:08 | 2022-04-06T05:37:07 | null | GB18030 | C++ | false | false | 4,189 | h | // GeoWell.h
/*********************************************************************/
#pragma once
#include <afxtempl.h>
#include <afxcoll.h>
#include "GeoAdo.h"
/*
CREATE TABLE Well
(
WellID bigint PRIMARY KEY IDENTITY, --井编号
WellName varchar(64) NOT NULL, --井名称 JM
Alias varchar(64), --井别名 BM
Structure varchar(64), --所属构造 GZ
Oilfield varchar(64), --所属油田 DM
Owner varchar(64), --业主单位 DW
Region varchar(128), --地区
Location varchar(128), --构造位置
Line_Location varchar(128), --测线位置
ElevationGd float, --地面海拔 HBGD
Elevation0 float, --补心海拔
DepOffset float, --补心高度 BXGD
OilOffset float, --油补距
PipeOffset float, --套补距
MagneticV float, --磁偏角
WellDepth float, --完井井深 JS
WellBottom float, --人工井底
StartDate datetime, --开钻日期 RQ
EndDate datetime, --完钻日期 WZRQ
WellX float, --井位X坐标 X
WellY float, --井位Y坐标 Y
Longitude float, --井位经度
Latitude float, --井位纬度
WellType varchar(32), --勘探分类(探井、预探井、评价井、开发井) JB
WellKind varchar(32), --工程分类(直井、斜井、水平井、丛式井)
DrillAim varchar(4096), --钻探目的
AimLayer varchar(64), --目标层位
ReservoirType varchar(32), --储层类型(常规油气、煤层气、页岩气)
Describe varchar(512), --井描述 BZ
FillUser varchar(64), --提交人
FillDate datetime, --提交日期
UpperID bigint NOT NULL --存储空间编号
)
*/
class AFX_EXT_CLASS CGeoWell :public CGeoAdo
{
public:
CString m_WellName; //井名称
CString m_Alias; //井别名
CString m_Structure; //所属构造
CString m_Oilfield; //所属油田
CString m_Owner; //业主单位
CString m_Region; //地区
CString m_Location; //构造位置
CString m_Line_Location; //测线位置
float m_ElevationGd; //地面海拔
float m_Elevation0; //基准面海拔
float m_DepOffset; //补心高度
float m_OilOffset; //油补距
float m_PipeOffset; //套补距
float m_MagneticV; //磁偏角
float m_WellDepth; //完井井深
float m_WellBottom; //人工井底
CString m_StartDate; //开钻日期
CString m_EndDate; //完钻日期
float m_WellX; //井位X坐标
float m_WellY; //井位Y坐标
double m_Longitude; //井位经度
double m_Latitude; //井位纬度
CString m_WellType; //勘探分类(探井、预探井、评价井、开发井)
CString m_WellKind; //工程分类(直井、斜井、水平井、丛式井)
CString m_DrillAim; //钻探目的
CString m_AimLayer; //目标层位
CString m_ReservoirType; //储层类型(常规油气层、煤层气、页岩气)
// 钻具信息
CArray<float,float&> a_BitSize;
CArray<float,float&> a_BitDep;
CArray<float,float&> a_CasingSize;
CArray<float,float&> a_CasingDep;
public:
CGeoWell();
virtual ~CGeoWell();
public:
CString GetDescribe();
void SetDescribe(CString cDescribe);
DWORD GetUpperID();
void SetUpperID(DWORD iUpperID);
CString GetFillUser();
void SetFillUser(CString cUser);
CString GetFillDate();
void SetFillDate(CString cDate);
public: //数据库操作
//返回新插入记录的编号
DWORD sql_insert();
BOOL sql_update(DWORD iWellID);
BOOL sql_delete(DWORD iWellID);
//根据井信息编号读取所有字段值
BOOL GetData(DWORD iWellID);
//根据井信息ID修所属构造(用于存储空间调转功能模块中)
BOOL sql_updateUpper(DWORD iUpperID);
//根据所属存储空编号读取井信息所有字段值
BOOL GetDataReferToUpperID(DWORD iUpperID);
BOOL GetDrillTool(DWORD iWellID);
DWORD InsertDrillTool(DWORD iWellID);
BOOL DeleteDrillTool(DWORD iWellID);
BOOL UpdateDrillTool(DWORD iWellID);
};
| [
"bmwmsn123@icloud.com"
] | bmwmsn123@icloud.com |
a1465d8e54539a9e6cdb77b986413b9f0f68b513 | dccc8885ff0e21721b1f4d3dbbe167f0e1d954fa | /Codeforces/Contests/299/TavasandSaDDas/main.cpp | 0b50e8a471e0e6a0f9277bd7acf10bbebce132f4 | [] | no_license | XiaoxiongZheng/Algorithms | 289721177a2336d08fe5ba29593beabbf57e3023 | 7be8767511f99c27d54076c4cc996f709efce305 | refs/heads/master | 2020-05-03T07:07:58.557835 | 2015-08-13T06:26:45 | 2015-08-13T06:26:45 | 24,021,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | #include <iostream>
#include <cmath>
using namespace std;
string n;
int main() {
cin >> n;
int len = n.size();
if (n == "4" || n == "7") {
cout << (n == "4" ? 1 : 2) << endl;
return 0;
}
int ans = 0, l = len - 1;
while (l)
{
ans += pow(2, l);
l--;
}
int temp = 1;
for (int i = 0; i < len; i++) {
if (n[i] == '7') {
temp += pow(2, len - i - 1);
}
}
cout << ans + temp << endl;
return 0;
} | [
"xxzheng.cs@gmail.com"
] | xxzheng.cs@gmail.com |
c2ede75bff9df7fb8aecf80d9737d9fe2cb7bf7f | 715febd8df093b36fd0ac41a17fcab9e40621b3e | /800/Problem71/WayTooLongWords.cpp | 36d3be3029e2d13024f9fa255be07372a7b462de | [] | no_license | idm2114/codeforces | 2892c2682172a08b6f9ab50f0af38e47c2e8014d | 0efed3f050e62014876659e355c3dd19bf352a66 | refs/heads/master | 2022-08-30T12:35:03.326465 | 2020-05-25T14:30:13 | 2020-05-25T14:30:13 | 266,800,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include <iostream>
#include <string>
using namespace std;
int main () {
int len;
cin >> len;
for(int i=0;i<len+1;i++){
string x;
getline(cin, x);
if (x.length() > 10) {
x = x.substr(0,1) + to_string(x.length()-2) + x.substr(x.length()-1, 1);
}
cout << x << endl;
}
}
| [
"noreply@github.com"
] | idm2114.noreply@github.com |
3a3e6fbff88966f7a58c3125bf23f951a2fc7b53 | 3a7d140ec93581c61c9c5680cf6bbc319266f688 | /Solved Practice problems/dubstep.cpp | 9ba94fb2a21dc3c52d61317d4fb1c3680fc413ad | [] | no_license | Ovishake1607066/Solved-Codeforces-problems | dcc6e33d471e4e92d1cf76b7c5aab4b0278fbf55 | fe038bb365bd666b2bbcad815e9ad3206d7e0988 | refs/heads/master | 2022-07-17T04:12:21.628142 | 2020-05-13T19:20:09 | 2020-05-13T19:20:09 | 263,710,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | #include<iostream>
#include<cstring>
using namespace std;
int main()
{
string s;
char s2[2000];
cin>>s;
int i,j,a=0,b=0,c,d;
for(i=0,j=0;i<s.size(); )
{
if(s[i]=='W' && s[i+1]=='U' && s[i+2]=='B')
{
i=i+3;
if(a==1)
b=1;
}
else
{
if(a==1 && b==1)
{
cout<<" ";
a=0;
b=0;
}
cout<<s[i];
i++;
a=1;
}
}
}
| [
"noreply@github.com"
] | Ovishake1607066.noreply@github.com |
4797ce0e6b791ca126676c7c8ac76b03d2a24dfa | 40e58042e635ea2a61a6216dc3e143fd3e14709c | /chopshop11/Team166Task.h | d420cc0d575b7e730fa153e1733aecdd8c371a35 | [] | no_license | chopshop-166/frc-2011 | 005bb7f0d02050a19bdb2eb33af145d5d2916a4d | 7ef98f84e544a17855197f491fc9f80247698dd3 | refs/heads/master | 2016-09-05T10:59:54.976527 | 2011-10-20T22:50:17 | 2011-10-20T22:50:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,829 | h | /*******************************************************************************
* Project : Chopshop11
* File Name : Team166Task.h
* Owner : Software Group (FIRST Chopshop Team 166)
* File Description : Header for main robot task and global paramters
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "WPILib.h"
#include <cmath>
#include <sysLib.h>
#include "Defines.h"
// Framework version number
#define FRAMEWORK_VERSION ("2010-Dec-09")
//
// task (as in kernel task)
/** Stack size 64 KB */
#define TEAM166TASK_K_STACKSIZE (64 * 1024)
/** Spawned task priority (100) */
#define TEAM166TASK_K_PRIO (100)
//
// Max tasks we support being started in Robot166
//
#define T166_MAXTASK (32)
//
// Count of times a particular task can fail to report its watchdog before
// we start to display errors.
//
#define T166_WATCHDOG_MIN (3)
//
// Wait time in each task for getting into Autonomous or Teleoperated mode
//
#define T166_TA_WAIT_LENGTH (0.050) // 50ms
class Team166Task
{
// Methods
public:
// Constructor
Team166Task(int IsEssential=1);
// Destructor
virtual ~Team166Task();
//! Sets the loop exit status
void SetStatus(const char* = ""); // Set a default to empty string for success.
const char* GetStatus();
// General start routine; needs to be called by target constructor
int Start(char *tname, unsigned int loop_interval);
// Jacket routine that leads into the actual Main routine of target
static int MainJacket(void *this_p, int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10);
// Each class needs to implement this Main function
virtual int Main(int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10) = 0;
// Wait for Robot go-ahead
void WaitForGoAhead(void);
// Wait for next lap
void WaitForNextLoop(void);
static void PrintStats(void);
// Check if all registered tasks are up
static int IfUp(void);
// Get handle to a specific task
static Team166Task *GetTaskHandle(char *name);
// Should we feed the watchdog?
static int FeedWatchDog(void);
static void PrintInactive(void);
static void PrintAllTasks(void);
// Data members
public:
int MyTaskId; // Id of our own task
int MyTaskInitialized; // This task has been initialized
int MyWatchDog; // Feeding my own watch dog
int MyTaskIsEssential; // Flag indicating if this task is essential
int MyStatus;
const char* MyStatusString;
char *MyName; // Name of this task
int MissedWatchDog; // Missed watchdog count
float MyLoopInterval; // Timing interval for loop
unsigned int MyLoopNs; // Length of loop for this
unsigned int OverRuns; // Task over runs
private:
// This array points to tasks that have requested to be initialized
static Team166Task *ActiveTasks[T166_MAXTASK + 1];
// Used for time calculations
unsigned int crate; // Clock rate
unsigned int half_tick; // Length of a half tick
struct timespec start_time; // Time when our logic starts
struct timespec next_checkin; // Time when we're expected to checkin next
unsigned int nano_left; // Nano seconds left of second
struct timespec exit_time; // Time when we left the wait call
unsigned int last_print_sec; // Last second we printed out a log message
unsigned int loop_calls; // Times we've been called to wait
};
| [
"demosthenes2k7@gmail.com"
] | demosthenes2k7@gmail.com |
470b83f2f9884b2638a6295cf47398df4cc44a02 | 08a2e70f85afd89ce06764f95785a3a3b812370e | /net/third_party/quic/core/quic_version_manager_test.cc | 43e5a06883b5b4a8666d409aeaffa6a9a21f836a | [
"BSD-3-Clause"
] | permissive | RobertPieta/chromium | 014cf3ffb3436793b2e0817874eda946779d7e2d | eda06a0b859a08d15a1ab6a6850e42e667530f0b | refs/heads/master | 2023-01-13T10:57:12.853154 | 2019-02-16T14:07:55 | 2019-02-16T14:07:55 | 171,064,555 | 0 | 0 | NOASSERTION | 2019-02-16T23:55:22 | 2019-02-16T23:55:22 | null | UTF-8 | C++ | false | false | 3,772 | cc | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quic/core/quic_version_manager.h"
#include "net/third_party/quic/core/quic_versions.h"
#include "net/third_party/quic/platform/api/quic_arraysize.h"
#include "net/third_party/quic/platform/api/quic_flags.h"
#include "net/third_party/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
class QuicVersionManagerTest : public QuicTest {};
TEST_F(QuicVersionManagerTest, QuicVersionManager) {
static_assert(QUIC_ARRAYSIZE(kSupportedTransportVersions) == 8u,
"Supported versions out of sync");
SetQuicReloadableFlag(quic_enable_version_99, false);
SetQuicReloadableFlag(quic_enable_version_47, false);
SetQuicReloadableFlag(quic_enable_version_46, false);
SetQuicReloadableFlag(quic_enable_version_45, false);
SetQuicReloadableFlag(quic_enable_version_44, false);
SetQuicReloadableFlag(quic_enable_version_43, false);
SetQuicReloadableFlag(quic_disable_version_35, true);
SetQuicReloadableFlag(quic_disable_version_39, true);
QuicVersionManager manager(AllSupportedVersions());
EXPECT_EQ(FilterSupportedTransportVersions(AllSupportedTransportVersions()),
manager.GetSupportedTransportVersions());
EXPECT_TRUE(manager.GetSupportedTransportVersions().empty());
SetQuicReloadableFlag(quic_disable_version_35, false);
EXPECT_EQ(QuicTransportVersionVector({QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_disable_version_39, false);
EXPECT_EQ(QuicTransportVersionVector({QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_43, true);
EXPECT_EQ(QuicTransportVersionVector(
{QUIC_VERSION_43, QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_44, true);
EXPECT_EQ(QuicTransportVersionVector({QUIC_VERSION_44, QUIC_VERSION_43,
QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_45, true);
EXPECT_EQ(QuicTransportVersionVector({QUIC_VERSION_45, QUIC_VERSION_44,
QUIC_VERSION_43, QUIC_VERSION_39,
QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_46, true);
EXPECT_EQ(QuicTransportVersionVector({QUIC_VERSION_46, QUIC_VERSION_45,
QUIC_VERSION_44, QUIC_VERSION_43,
QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_47, true);
EXPECT_EQ(
QuicTransportVersionVector(
{QUIC_VERSION_47, QUIC_VERSION_46, QUIC_VERSION_45, QUIC_VERSION_44,
QUIC_VERSION_43, QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
SetQuicReloadableFlag(quic_enable_version_99, true);
EXPECT_EQ(
QuicTransportVersionVector(
{QUIC_VERSION_99, QUIC_VERSION_47, QUIC_VERSION_46, QUIC_VERSION_45,
QUIC_VERSION_44, QUIC_VERSION_43, QUIC_VERSION_39, QUIC_VERSION_35}),
manager.GetSupportedTransportVersions());
// Ensure that all versions are now supported.
EXPECT_EQ(FilterSupportedTransportVersions(AllSupportedTransportVersions()),
manager.GetSupportedTransportVersions());
}
} // namespace
} // namespace test
} // namespace quic
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b20208f6d2fd065d0082cc22491430957b6ccbed | 59ce5089aad9744d7a8a7d772f8e4fbb920fe8df | /main.cxx | ced9d607ac217ed3d0292b85e33169c75bb86242 | [
"MIT"
] | permissive | aWilson41/vtkLKOpticalFlow | 8a52414e4228470934f567ac8fd466b5c61b547b | fd2f7ea15b53c45d94842dd6deea00858a65d07d | refs/heads/master | 2020-04-04T00:18:41.594570 | 2019-11-20T06:52:57 | 2019-11-20T06:52:57 | 155,646,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,017 | cxx | #include "vtkCoarseToFineOpticalFlow.h"
#include <vtkActor.h>
#include <vtkArrowSource.h>
#include <vtkColorSeries.h>
#include <vtkColorTransferFunction.h>
#include <vtkGlyph3DMapper.h>
#include <vtkImageData.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkNIFTIReader.h>
#include <vtkNIFTIWriter.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkSmartPointer.h>
#include <chrono>
// This is an example to demonstrate LK optical flow. Reads two nii images. Displays it. Writes it.
int main(int argc, char* argv[])
{
std::string input1Str = "C:/Users/Andx_/Desktop/MH3D_25_Test1.nii";
std::string input2Str = "C:/Users/Andx_/Desktop/MH3D_25_Test2.nii";
std::string outputStr = "C:/Users/Andx_/Desktop/output.nii";
double minScale = 0.6;
double maxScale = 1.0;
int numLevels = 3;
double renderArrowScale = 0.3;
vtkSmartPointer<vtkNIFTIReader> reader1 = vtkSmartPointer<vtkNIFTIReader>::New();
reader1->SetFileName(input1Str.c_str());
reader1->Update();
vtkSmartPointer<vtkNIFTIReader> reader2 = vtkSmartPointer<vtkNIFTIReader>::New();
reader2->SetFileName(input2Str.c_str());
reader2->Update();
auto start = std::chrono::steady_clock::now();
// Computes flow from 1 -> 2. Outputs is 3 component float image
vtkSmartPointer<vtkCoarseToFineOpticalFlow> filter = vtkSmartPointer<vtkCoarseToFineOpticalFlow>::New();
filter->SetScaleRange(minScale, maxScale);
filter->SetNumLevels(numLevels);
filter->SetInputData(0, reader1->GetOutput());
filter->SetInputData(1, reader2->GetOutput());
filter->Update();
auto end = std::chrono::steady_clock::now();
printf("Time: %f\n", std::chrono::duration<double, std::milli>(end - start).count() / 1000.0);
// Setup the vector field for rendering
vtkSmartPointer<vtkColorSeries> colorSeries = vtkSmartPointer<vtkColorSeries>::New();
colorSeries->SetColorScheme(vtkColorSeries::WARM);
vtkSmartPointer<vtkColorTransferFunction> lut = vtkSmartPointer<vtkColorTransferFunction>::New();
lut->SetColorSpaceToHSV();
// Use a color series to create a transfer function
int numColors = colorSeries->GetNumberOfColors();
double* scalarRange = filter->GetOutput()->GetScalarRange();
for (int i = 0; i < numColors; i++)
{
vtkColor3ub color = colorSeries->GetColor(i);
double dColor[3];
dColor[0] = static_cast<double> (color[0]) / 255.0;
dColor[1] = static_cast<double> (color[1]) / 255.0;
dColor[2] = static_cast<double> (color[2]) / 255.0;
double t = scalarRange[0] + (scalarRange[1] - scalarRange[0])
/ (numColors - 1) * i;
lut->AddRGBPoint(t, dColor[0], dColor[1], dColor[2]);
}
vtkSmartPointer<vtkGlyph3DMapper> mapper = vtkSmartPointer<vtkGlyph3DMapper>::New();
mapper->SetInputData(filter->GetOutput());
vtkSmartPointer<vtkArrowSource> glyphSource = vtkSmartPointer<vtkArrowSource>::New();
glyphSource->Update();
mapper->SetSourceData(glyphSource->GetOutput());
mapper->OrientOn();
mapper->SetOrientationArray("ImageScalars");
mapper->SetLookupTable(lut);
mapper->SetScaleFactor(renderArrowScale);
mapper->Update();
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// Create a renderer, render window, and interactor
vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWindow = vtkSmartPointer<vtkRenderWindow>::New();
renWindow->AddRenderer(ren);
vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetInteractorStyle(vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New());
iren->SetRenderWindow(renWindow);
// Add the actors to the scene
ren->AddActor(actor);
ren->SetBackground(0.55, 0.75, 0.62);
// Render and interact
renWindow->Render();
iren->Start();
vtkSmartPointer<vtkNIFTIWriter> writer = vtkSmartPointer<vtkNIFTIWriter>::New();
writer->SetFileName(outputStr.c_str());
writer->SetInputData(filter->GetOutput());
writer->Update();
return EXIT_SUCCESS;
} | [
"andx_roo@live.com"
] | andx_roo@live.com |
4b89d2c4cab4cee3a6f1d4acff6434fbdd494a17 | d05555aa4da349b8a1cc219b4c3fae881577f7ab | /A1827/1827gather 奶牛大集会.cpp | a273dbe675f82f79944b2c23851f74b72878ba02 | [
"MIT"
] | permissive | instr3/BZOJ-solution-legacy | c95cc0882d24c8b74b72a546cf9f2b84d541faea | a71f7df2241602ad744e8ca2453a8423590d5678 | refs/heads/master | 2021-01-11T05:19:01.069622 | 2016-09-26T03:19:38 | 2016-09-26T03:19:38 | 69,208,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,560 | cpp | #include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
#define each(i,n) (int i=1;i<=(n);++i)
#define every(i,a,b) (int i=(a);i<=(b);++i)
struct enode{int to,fr,w,next;long long tw,tper;}mye[200002];
struct vnode{int first,iper;long long tw,tper;}myv[100001];
bool visit[100001];
/*int test(int idp)
{
long long myvar[4];
if(idp%1000==0)cout<<idp<<endl;
test(idp+1);
}*/
void dfs(int iv)
{
visit[iv]=true;
int pt,tp;
for(int p=myv[iv].first;p;p=mye[p].next)
{
pt=mye[p].to;
if(visit[pt]){tp=p;continue;}
dfs(pt);
//res+=dfs(pt);
//res=res+mye[p].w*myv[pt].tp;
//myv[iv].tp+=myv[pt].tp;
}
if(iv==1)return;
//tp^=1;
for(int p=myv[iv].first;p;p=mye[p].next)
{
if(tp==p)continue;
mye[tp].tper+=mye[p^1].tper;
mye[tp].tw+=mye[p^1].tw;
}
mye[tp].tper+=myv[iv].iper;
mye[tp].tw+=mye[tp].tper*mye[tp].w;
//cout<<tp<<":"<<mye[tp].fr<<"->"<<mye[tp].to<<":"<<mye[tp].tper<<","<<mye[tp].tw<<endl;
}
void dfs2(int iv)
{
visit[iv]=true;
int pt,tp;
for(int p=myv[iv].first;p;p=mye[p].next)
{
myv[iv].tper+=mye[p^1].tper;
myv[iv].tw+=mye[p^1].tw;
}
myv[iv].tper+=myv[iv].iper;
//cout<<iv<<":"<<myv[iv].tper<<","<<myv[iv].tw<<endl;
for(int p=myv[iv].first;p;p=mye[p].next)
{
pt=mye[p].to;
if(visit[pt])continue;
mye[p].tw=myv[iv].tw-mye[p^1].tw;
mye[p].tper=myv[iv].tper-mye[p^1].tper;
mye[p].tw+=mye[p].tper*mye[p].w;
//cout<<iv<<"->"<<pt<<":"<<mye[p].tper<<","<<mye[p].tw<<endl;
dfs2(pt);
}
}
int main()
{
freopen("in","r",stdin);
freopen("out","w",stdout);
int n;scanf("%d",&n);
for each(i,n)scanf("%d",&myv[i].iper);
int pf,pt,pw;
for(int i=1,j=1;i<n;++i)
{
scanf("%d%d%d",&pf,&pt,&pw);
mye[++j].fr=pf;
mye[j].to=pt;
mye[j].w=pw;
mye[j].next=myv[pf].first;
myv[pf].first=j;
mye[++j].fr=pt;
mye[j].to=pf;
mye[j].w=pw;
mye[j].next=myv[pt].first;
myv[pt].first=j;
}
dfs(1);
memset(visit,0,sizeof visit);
dfs2(1);
long long tres,tmin=999999999999999LL;
for each(i,n)
{
tres=0;
for(int p=myv[i].first;p;p=mye[p].next)
{
tres+=mye[p^1].tw;
}
//cout<<i<<";"<<tres<<endl;
tmin=min(tres,tmin);
}
printf("%lld",tmin);
}
| [
"instr3@163.com"
] | instr3@163.com |
eb94a5bba9cb3c58826e14d89cb31db7b16ec388 | f4ba62961c0295743c7a8e71e69bd252336fc189 | /Arduino/MMC3316xMT.ino | eb96376ff317fb08540580358133a4c0d1dd45ca | [] | no_license | DcubeTechVentures/MMC3316xMT | 3a4315825ccf2afa832ddae224049d29309c8ce9 | be52d5812e489db75d4c1b15ad64618f5b9dde3c | refs/heads/master | 2021-01-19T05:41:18.761060 | 2016-06-20T10:50:42 | 2016-06-20T10:50:42 | 64,728,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,410 | ino | // Distributed with a free-will license.
// Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
// MMC3316xMT
// This code is designed to work with the MMC3316xMT_I2CS I2C Mini Module available from ControlEverything.com.
// https://www.controleverything.com/content/Magnetic-Sensor?sku=MMC3316xMT_I2CS
#include<Wire.h>
// MMC3316xMT I2C address is 0x30(48)
#define Addr 0x30
void setup()
{
// Initialise I2C communication as MASTER
Wire.begin();
// Initialise Serial Communication
Serial.begin(9600);
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register
Wire.write(0x07);
// Initiate measurement, continuous mode, coil set
Wire.write(0x23);
// Stop I2C Transmission
Wire.endTransmission();
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register
Wire.write(0x07);
// Coil Not set
Wire.write(0x00);
// Stop I2C Transmission
Wire.endTransmission();
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register-0
Wire.write(0x07);
// Initiate measurement, continuous mode , Coil RESET
Wire.write(0x43);
// Stop I2C Transmission
Wire.endTransmission();
delay(300);
}
void loop()
{
unsigned int data[6];
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select magnetometer data register
Wire.write(0x00);
// Stop I2C Transmission
Wire.endTransmission();
// Request 6 bytes of data
Wire.requestFrom(Addr, 6);
// Read 6 bytes of data
// xMag lsb, xMag msb, yMag lsb, yMag msb, zMag lsb, zMag msb
if(Wire.available() == 6)
{
data[0] = Wire.read();
data[1] = Wire.read();
data[2] = Wire.read();
data[3] = Wire.read();
data[4] = Wire.read();
data[5] = Wire.read();
}
// Convert the data
int xMag = (((data[1] & 0x3F) * 256) + data[0]);
if (xMag > 8191)
{
xMag -= 16384;
}
int yMag = (((data[3] & 0x3F) * 256) + data[2]);
if (yMag > 8191)
{
yMag -= 16384;
}
int zMag = (((data[5] & 0x3F) * 256) + data[4]);
if (zMag > 8191)
{
zMag -= 16384;
}
// Output data to serial monitor
Serial.print("Magnetic field in X Axis : ");
Serial.println(xMag);
Serial.print("Magnetic field in Y Axis : ");
Serial.println(yMag);
Serial.print("Magnetic field in Z Axis : ");
Serial.println(zMag);
delay(1000);
}
| [
"ryker1990@gmail.com"
] | ryker1990@gmail.com |
e5cf1827c8740501e5e392251a5425ee7ef2daba | 6e3190744c949eca539808e78e9f4e1018707b75 | /external/dysii/src/indii/ml/aux/Pdf.cpp | 33c72677040421d18e05a6e21956246de467f1d2 | [
"BSD-3-Clause"
] | permissive | micahcc/BrainID | 208de93c8167eba12b85e5abac8952ddc80223f6 | 1ae6776c6175ab72e9d45a639f3d0aa4fe7d1cf8 | refs/heads/master | 2021-05-28T14:16:31.901590 | 2015-01-06T23:39:58 | 2015-01-06T23:39:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | //#if defined(__GNUC__) && defined(GCC_PCH)
// #include "aux.hpp"
//#else
#include "Pdf.hpp"
//#endif
using namespace indii::ml::aux;
Pdf::Pdf() : N(0) {
//
}
Pdf::Pdf(const unsigned int N) : N(N) {
//
}
Pdf::~Pdf() {
//
}
| [
"micahc@b3ba8586-d01d-0410-af51-a98ec15c9dce"
] | micahc@b3ba8586-d01d-0410-af51-a98ec15c9dce |
61d1271d68ab6034d14abbf6b27d6250f55647a2 | f252f75a66ff3ff35b6eaa5a4a28248eb54840ee | /external/opencore/pvmi/recognizer/src/pvmf_recognizer_registry_impl.cpp | 94c87a92e04fdc544442453b6ccc9b803ab693db | [
"MIT",
"LicenseRef-scancode-other-permissive",
"Artistic-2.0",
"LicenseRef-scancode-philippe-de-muyter",
"Apache-2.0",
"LicenseRef-scancode-mpeg-iso",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | abgoyal-archive/OT_4010A | 201b246c6f685cf35632c9a1e1bf2b38011ff196 | 300ee9f800824658acfeb9447f46419b8c6e0d1c | refs/heads/master | 2022-04-12T23:17:32.814816 | 2015-02-06T12:15:20 | 2015-02-06T12:15:20 | 30,410,715 | 0 | 1 | null | 2020-03-07T00:35:22 | 2015-02-06T12:14:16 | C | UTF-8 | C++ | false | false | 25,696 | cpp |
#ifndef OSCL_TICKCOUNT_H_INCLUDED
#include "oscl_tickcount.h"
#endif
#ifndef PVMF_FORMAT_TYPE_H_INCLUDED
#include "pvmf_format_type.h"
#endif
#include "pvmf_recognizer_registry_impl.h"
#define LOGERROR(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_REL,iLogger,PVLOGMSG_ERR,m);
#define LOGINFOHI(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG,iLogger,PVLOGMSG_INFO,m);
#define LOGINFOMED(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_MLDBG,iLogger,PVLOGMSG_INFO,m);
#define LOGINFOLOW(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG,iLogger,PVLOGMSG_INFO,m);
#define LOGINFO(m) LOGINFOMED(m)
PVMFRecognizerRegistryImpl::PVMFRecognizerRegistryImpl() :
OsclTimerObject(OsclActiveObject::EPriorityNominal, "PVMFRecognizerRegistryImpl")
{
AddToScheduler();
iRefCount = 1;
iNextSessionId = 0;
iRecognizerSessionList.reserve(1);
iNextCommandId = 0;
iRecognizerPendingCmdList.reserve(2);
iRecognizerCurrentCmd.reserve(1);
iRecognizerCmdToCancel.reserve(1);
iDataStreamFactory = NULL;
iDataStream = NULL;
oRecognizePending = false;
iDataStreamCallBackStatus = PVMFSuccess;
// <--- Morris Yang ALPS00126974
iMaxRequiredSizeForRecognitionOverride = -1;
// --->
iLogger = PVLogger::GetLoggerObject("PVMFRecognizer");
}
PVMFRecognizerRegistryImpl::~PVMFRecognizerRegistryImpl()
{
iDataStreamFactory = NULL;
while (iRecognizerPluginFactoryList.empty() == false)
{
// The plug-in factories were not removed before shutting down the
// registry. This could lead to memory leaks since the registry
// cannot call the destructor for the derived factory class. So assert.
OSCL_ASSERT(false);
// Destroy factory using the base class
PVMFRecognizerPluginFactory* pluginfactory = iRecognizerPluginFactoryList[0];
iRecognizerPluginFactoryList.erase(iRecognizerPluginFactoryList.begin());
OSCL_DELETE(pluginfactory);
}
iLogger = NULL;
}
PVMFStatus PVMFRecognizerRegistryImpl::RegisterPlugin(PVMFRecognizerPluginFactory& aPluginFactory)
{
// Check that plug-in factory is not already registered
if (FindPluginFactory(aPluginFactory) == -1)
{
// Add the plug-in factory to the list
iRecognizerPluginFactoryList.push_back(&aPluginFactory);
}
return PVMFSuccess;
}
PVMFStatus PVMFRecognizerRegistryImpl::RemovePlugin(PVMFRecognizerPluginFactory& aPluginFactory)
{
// Find the specified plug-in factory and remove from list
int32 factoryindex = FindPluginFactory(aPluginFactory);
if (factoryindex == -1)
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::RemovePlugin Failed!"));
return PVMFErrArgument;
}
iRecognizerPluginFactoryList.erase(iRecognizerPluginFactoryList.begin() + factoryindex);
return PVMFSuccess;
}
PVMFStatus PVMFRecognizerRegistryImpl::OpenSession(PVMFSessionId& aSessionId, PVMFRecognizerCommmandHandler& aCmdHandler)
{
// TEMP: Currently only allow one session at a time
if (iRecognizerSessionList.empty() == false)
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::OpenSession Failed!"));
return PVMFErrBusy;
}
// Add this session to the list
PVMFRecRegSessionInfo recsessioninfo;
recsessioninfo.iRecRegSessionId = iNextSessionId;
recsessioninfo.iRecRegCmdHandler = &aCmdHandler;
int32 leavecode = 0;
OSCL_TRY(leavecode, iRecognizerSessionList.push_back(recsessioninfo));
OSCL_FIRST_CATCH_ANY(leavecode,
return PVMFErrNoMemory;
);
aSessionId = recsessioninfo.iRecRegSessionId;
// Increment the session ID counter
++iNextSessionId;
return PVMFSuccess;
}
PVMFStatus PVMFRecognizerRegistryImpl::CloseSession(PVMFSessionId aSessionId)
{
if (iRecognizerSessionList.empty() == true)
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::CloseSession Failed!"));
return PVMFErrInvalidState;
}
// Search for the session in the list by the ID
uint32 i;
for (i = 0; i < iRecognizerSessionList.size(); ++i)
{
if (iRecognizerSessionList[i].iRecRegSessionId == aSessionId)
{
break;
}
}
// Check if the session was not found
if (i >= iRecognizerSessionList.size())
{
return PVMFErrArgument;
}
// Erase the session from the list to close the session
iRecognizerSessionList.erase(iRecognizerSessionList.begin() + i);
return PVMFSuccess;
}
PVMFCommandId PVMFRecognizerRegistryImpl::Recognize(PVMFSessionId aSessionId, PVMFDataStreamFactory& aSourceDataStreamFactory, PVMFRecognizerMIMEStringList* aFormatHint,
Oscl_Vector<PVMFRecognizerResult, OsclMemAllocator>& aRecognizerResult, OsclAny* aCmdContext, uint32 aTimeout)
{
if ((iRecognizerSessionList.empty() == true) || (oRecognizePending == true))
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::Recognize OsclErrInvalidState"));
OSCL_LEAVE(OsclErrInvalidState);
}
if (aSessionId != iRecognizerSessionList[0].iRecRegSessionId)
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::Recognize OsclErrArgument"));
OSCL_LEAVE(OsclErrArgument);
}
// TEMP: Only allow one recognize command at a time
if (!(iRecognizerPendingCmdList.empty() == true && iRecognizerCurrentCmd.empty() == true))
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::Recognize OsclErrBusy"));
OSCL_LEAVE(OsclErrBusy);
}
// TEMP: Only allow timeout of 0
if (aTimeout > 0)
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::Recognize OsclErrArgument - aTimeout>0"));
OSCL_LEAVE(OsclErrArgument);
}
// Save the passed-in parameters in a vector
Oscl_Vector<PVMFRecRegImplCommandParamUnion, OsclMemAllocator> paramvector;
paramvector.reserve(4);
PVMFRecRegImplCommandParamUnion paramval;
paramval.pOsclAny_value = (OsclAny*) & aSourceDataStreamFactory;
paramvector.push_back(paramval);
paramval.pOsclAny_value = (OsclAny*)aFormatHint;
paramvector.push_back(paramval);
paramval.pOsclAny_value = (OsclAny*) & aRecognizerResult;
paramvector.push_back(paramval);
paramval.uint32_value = aTimeout;
paramvector.push_back(paramval);
// Add the command to the pending list
return AddRecRegCommand(aSessionId, PVMFRECREG_COMMAND_RECOGNIZE, aCmdContext, ¶mvector, true);
}
PVMFCommandId PVMFRecognizerRegistryImpl::CancelCommand(PVMFSessionId aSessionId, PVMFCommandId aCommandToCancelId, OsclAny* aCmdContext)
{
if (iRecognizerSessionList.empty() == true)
{
OSCL_LEAVE(OsclErrInvalidState);
return 0;
}
if (aSessionId != iRecognizerSessionList[0].iRecRegSessionId)
{
OSCL_LEAVE(OsclErrArgument);
return 0;
}
// Save the passed-in parameters in a vector
Oscl_Vector<PVMFRecRegImplCommandParamUnion, OsclMemAllocator> paramvector;
paramvector.reserve(1);
PVMFRecRegImplCommandParamUnion paramval;
paramval.int32_value = aCommandToCancelId;
paramvector.push_back(paramval);
// Add the command to the pending list
return AddRecRegCommand(aSessionId, PVMFRECREG_COMMAND_CANCELCOMMAND, aCmdContext, ¶mvector, true);
}
void PVMFRecognizerRegistryImpl::Run()
{
int32 leavecode = 0;
// Check if CancelCommand() request was made
if (!iRecognizerPendingCmdList.empty())
{
if (iRecognizerPendingCmdList.top().GetCmdType() == PVMFRECREG_COMMAND_CANCELCOMMAND)
{
// Process it right away
PVMFRecRegImplCommand cmd(iRecognizerPendingCmdList.top());
iRecognizerPendingCmdList.pop();
DoCancelCommand(cmd);
return;
}
}
// Handle other requests normally
if (!iRecognizerPendingCmdList.empty() && iRecognizerCurrentCmd.empty())
{
// Retrieve the first pending command from queue
PVMFRecRegImplCommand cmd(iRecognizerPendingCmdList.top());
iRecognizerPendingCmdList.pop();
// Put in on the current command queue
leavecode = 0;
OSCL_TRY(leavecode, iRecognizerCurrentCmd.push_front(cmd));
OSCL_FIRST_CATCH_ANY(leavecode,
OSCL_ASSERT(false);
// Can't complete the commmand since it cannot be added to the current command queue
return;);
// Process the command according to the cmd type
PVMFStatus cmdstatus = PVMFSuccess;
switch (cmd.GetCmdType())
{
case PVMFRECREG_COMMAND_RECOGNIZE:
DoRecognize();
break;
case PVMFRECREG_COMMAND_CANCELCOMMAND:
// CancelCommand() should not be handled here
OSCL_ASSERT(false);
// Just handle as "not supported"
cmdstatus = PVMFErrNotSupported;
break;
default:
cmdstatus = PVMFErrNotSupported;
break;
}
if (cmdstatus != PVMFSuccess)
{
CompleteCurrentRecRegCommand(cmdstatus);
}
}
else if (oRecognizePending == true)
{
CompleteRecognize(iDataStreamCallBackStatus);
}
}
int32 PVMFRecognizerRegistryImpl::FindPluginFactory(PVMFRecognizerPluginFactory& aFactory)
{
// Check if the specified factory exists in the list
for (uint32 i = 0; i < iRecognizerPluginFactoryList.size(); ++i)
{
if (iRecognizerPluginFactoryList[i] == &aFactory)
{
// Yes so return the index
return ((int32)i);
}
}
// No so return -1 meaning not found
return -1;
}
PVMFRecognizerPluginInterface* PVMFRecognizerRegistryImpl::CreateRecognizerPlugin(PVMFRecognizerPluginFactory& aFactory)
{
return aFactory.CreateRecognizerPlugin();
}
void PVMFRecognizerRegistryImpl::DestroyRecognizerPlugin(PVMFRecognizerPluginFactory& aFactory, PVMFRecognizerPluginInterface* aPlugin)
{
aFactory.DestroyRecognizerPlugin(aPlugin);
}
PVMFCommandId PVMFRecognizerRegistryImpl::AddRecRegCommand(PVMFSessionId aSessionId, int32 aCmdType, OsclAny* aContextData, Oscl_Vector<PVMFRecRegImplCommandParamUnion, OsclMemAllocator>* aParamVector, bool aAPICommand)
{
PVMFRecRegImplCommand cmd(aSessionId, aCmdType, iNextCommandId, aContextData, aParamVector, aAPICommand);
int32 leavecode = 0;
OSCL_TRY(leavecode, iRecognizerPendingCmdList.push(cmd));
OSCL_FIRST_CATCH_ANY(leavecode,
OSCL_LEAVE(OsclErrNoMemory);
return 0;);
RunIfNotReady();
++iNextCommandId;
return cmd.GetCmdId();
}
void PVMFRecognizerRegistryImpl::CompleteCurrentRecRegCommand(PVMFStatus aStatus, const uint32 aCurrCmdIndex, PVInterface* aExtInterface)
{
if (iRecognizerCurrentCmd.empty() == true)
{
// No command to complete. Assert
OSCL_ASSERT(false);
return;
}
// Save the command complete on stack and remove from queue
PVMFRecRegImplCommand cmdtocomplete(iRecognizerCurrentCmd[aCurrCmdIndex]);
iRecognizerCurrentCmd.clear();
// Make callback if API command
if (cmdtocomplete.IsAPICommand())
{
if (iRecognizerSessionList.empty() == false)
{
OSCL_ASSERT(iRecognizerSessionList[aCurrCmdIndex].iRecRegSessionId == cmdtocomplete.GetSessionId());
PVMFCmdResp cmdresp(cmdtocomplete.GetCmdId(), cmdtocomplete.GetContext(), aStatus, aExtInterface);
iRecognizerSessionList[aCurrCmdIndex].iRecRegCmdHandler->RecognizerCommandCompleted(cmdresp);
}
}
// Need to make this AO active if there are pending commands
if (iRecognizerPendingCmdList.empty() == false)
{
RunIfNotReady();
}
}
PVMFStatus PVMFRecognizerRegistryImpl::GetMaxRequiredSizeForRecognition(uint32& aMaxSize)
{
// <--- Morris Yang 20101015 ALPS00126974
if (iMaxRequiredSizeForRecognitionOverride > 0)
{
aMaxSize = iMaxRequiredSizeForRecognitionOverride;
return PVMFSuccess;
}
// --->
aMaxSize = 0;
for (uint32 i = 0; i < iRecognizerPluginFactoryList.size(); ++i)
{
uint32 bytes = 0;
// Create the recognizer plugin
PVMFRecognizerPluginInterface* recplugin =
CreateRecognizerPlugin(*(iRecognizerPluginFactoryList[i]));
if (recplugin)
{
// Perform recognition with this recognizer plug-ing
PVMFStatus status =
recplugin->GetRequiredMinBytesForRecognition(bytes);
// Done with this recognizer so release it
DestroyRecognizerPlugin(*(iRecognizerPluginFactoryList[i]), recplugin);
if (status == PVMFSuccess)
{
if (bytes > aMaxSize)
{
aMaxSize = bytes;
}
}
else
{
return status;
}
}
}
return PVMFSuccess;
}
PVMFStatus PVMFRecognizerRegistryImpl::GetMinRequiredSizeForRecognition(uint32& aMinSize)
{
aMinSize = 0x7FFFFFF;
for (uint32 i = 0; i < iRecognizerPluginFactoryList.size(); ++i)
{
uint32 bytes = 0;
// Create the recognizer plugin
PVMFRecognizerPluginInterface* recplugin =
CreateRecognizerPlugin(*(iRecognizerPluginFactoryList[i]));
if (recplugin)
{
// Perform recognition with this recognizer plug-ing
PVMFStatus status =
recplugin->GetRequiredMinBytesForRecognition(bytes);
// Done with this recognizer so release it
DestroyRecognizerPlugin(*(iRecognizerPluginFactoryList[i]), recplugin);
if (status == PVMFSuccess)
{
if (bytes < aMinSize)
{
aMinSize = bytes;
}
}
else
{
return status;
}
}
}
return PVMFSuccess;
}
PVMFStatus PVMFRecognizerRegistryImpl::CheckForDataAvailability()
{
if (iDataStreamFactory != NULL)
{
iDataStream = NULL;
PVUuid uuid = PVMIDataStreamSyncInterfaceUuid;
PVInterface* intf =
iDataStreamFactory->CreatePVMFCPMPluginAccessInterface(uuid);
iDataStream = OSCL_STATIC_CAST(PVMIDataStreamSyncInterface*, intf);
uint32 maxSize = 0;
if (GetMaxRequiredSizeForRecognition(maxSize) == PVMFSuccess)
{
if (iDataStream->OpenSession(iDataStreamSessionID, PVDS_READ_ONLY) == PVDS_SUCCESS)
{
uint32 capacity = 0;
PvmiDataStreamStatus status =
iDataStream->QueryReadCapacity(iDataStreamSessionID, capacity);
if (capacity < maxSize)
{
// Get total content size to deal with cases where file being recognized is less than maxSize
uint32 totalSize = iDataStream->GetContentLength();
if ((status == PVDS_END_OF_STREAM) || (capacity == totalSize))
{
uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
return PVMFSuccess;
}
int32 errcode = 0;
OSCL_TRY(errcode,
iRequestReadCapacityNotificationID =
iDataStream->RequestReadCapacityNotification(iDataStreamSessionID,
*this,
maxSize);
);
OSCL_FIRST_CATCH_ANY(errcode,
uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
return PVMFFailure);
return PVMFPending;
}
uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
return PVMFSuccess;
}
else
{
uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
return PVMFFailure;
}
}
}
return PVMFFailure;
}
void PVMFRecognizerRegistryImpl::CompleteRecognize(PVMFStatus aStatus)
{
oRecognizePending = false;
PVUuid uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
if (aStatus == PVMFSuccess)
{
iDataStreamFactory =
(PVMFDataStreamFactory*) iRecognizerCurrentCmd[0].GetParam(0).pOsclAny_value;
PVMFRecognizerMIMEStringList* hintlist = (PVMFRecognizerMIMEStringList*) iRecognizerCurrentCmd[0].GetParam(1).pOsclAny_value;
Oscl_Vector<PVMFRecognizerResult, OsclMemAllocator>* recresult = (Oscl_Vector<PVMFRecognizerResult, OsclMemAllocator>*) iRecognizerCurrentCmd[0].GetParam(2).pOsclAny_value;
// Validate the parameters
if (iDataStreamFactory == NULL || recresult == NULL)
{
CompleteCurrentRecRegCommand(PVMFErrArgument);
return;
}
// TEMP: Perform the recognition operation by checking with each registered recognizer once
for (uint32 i = 0; i < iRecognizerPluginFactoryList.size(); ++i)
{
// Create the recognizer plugin
PVMFRecognizerPluginInterface* recplugin =
CreateRecognizerPlugin(*(iRecognizerPluginFactoryList[i]));
if (recplugin)
{
LOGINFO((0, "PVMFRecognizerRegistryImpl::CompleteRecognize Calling recognizer i=%d", i));
uint32 currticks = OsclTickCount::TickCount();
uint32 starttime = OsclTickCount::TicksToMsec(currticks);
OSCL_UNUSED_ARG(starttime);
// Perform recognition with this recognizer plug-ing
recplugin->Recognize(*iDataStreamFactory, hintlist, *recresult);
// Done with this recognizer so release it
currticks = OsclTickCount::TickCount();
uint32 endtime = OsclTickCount::TicksToMsec(currticks);
OSCL_UNUSED_ARG(endtime);
DestroyRecognizerPlugin(*(iRecognizerPluginFactoryList[i]), recplugin);
if (!recresult->empty())
{
// Get the result of the recognizer operation from the vector
LOGINFO((0, "PVMFRecognizerRegistryImpl::CompleteRecognize Out of recognizer i=%d result=%d, time=%d",
i, (recresult->back()).iRecognitionConfidence, (endtime - starttime)));
//LOGINFO((0,"PVMFRecognizerRegistryImpl::CompleteRecognize out of recognizer i=%d result=%d, time=%d, mime=%s",
//i,(recresult->back()).iRecognitionConfidence, (endtime-starttime), (recresult->back()).iRecognizedFormat.get_cstr()));
if ((recresult->back()).iRecognitionConfidence == PVMFRecognizerConfidenceCertain)
{
CompleteCurrentRecRegCommand(PVMFSuccess);
return;
}
}
}
}
// Complete the recognizer command
CompleteCurrentRecRegCommand(PVMFSuccess);
}
else
{
// Complete the recognizer command
CompleteCurrentRecRegCommand(aStatus);
}
}
void PVMFRecognizerRegistryImpl::DoRecognize()
{
// Retrieve the command parameters
iDataStreamFactory =
(PVMFDataStreamFactory*) iRecognizerCurrentCmd[0].GetParam(0).pOsclAny_value;
PVMFRecognizerMIMEStringList* hintlist = (PVMFRecognizerMIMEStringList*) iRecognizerCurrentCmd[0].GetParam(1).pOsclAny_value;
Oscl_Vector<PVMFRecognizerResult, OsclMemAllocator>* recresult = (Oscl_Vector<PVMFRecognizerResult, OsclMemAllocator>*) iRecognizerCurrentCmd[0].GetParam(2).pOsclAny_value;
// Validate the parameters
if (iDataStreamFactory == NULL || recresult == NULL)
{
CompleteCurrentRecRegCommand(PVMFErrArgument);
return;
}
PVMFStatus status = CheckForDataAvailability();
if (status == PVMFFailure)
{
CompleteCurrentRecRegCommand(PVMFFailure);
return;
}
else if (status == PVMFSuccess)
{
// TEMP: Perform the recognition operation by checking with each registered recognizer once
for (uint32 i = 0; i < iRecognizerPluginFactoryList.size(); ++i)
{
// Create the recognizer plugin
PVMFRecognizerPluginInterface* recplugin =
CreateRecognizerPlugin(*(iRecognizerPluginFactoryList[i]));
if (recplugin)
{
LOGINFO((0, "PVMFRecognizerRegistryImpl::DoRecognize Calling recognizer i=%d", i));
uint32 currticks = OsclTickCount::TickCount();
uint32 starttime = OsclTickCount::TicksToMsec(currticks);
OSCL_UNUSED_ARG(starttime);
// Perform recognition with this recognizer plug-ing
recplugin->Recognize(*iDataStreamFactory, hintlist, *recresult);
// Done with this recognizer so release it
currticks = OsclTickCount::TickCount();
uint32 endtime = OsclTickCount::TicksToMsec(currticks);
OSCL_UNUSED_ARG(endtime);
DestroyRecognizerPlugin(*(iRecognizerPluginFactoryList[i]), recplugin);
if (!recresult->empty())
{
LOGINFO((0, "PVMFRecognizerRegistryImpl::DoRecognize Out of recognizer i=%d result=%d, time=%d",
i, (recresult->back()).iRecognitionConfidence, (endtime - starttime)));
//LOGINFO((0,"PVMFRecognizerRegistryImpl::DoRecognize out of recognizer i=%d result=%d, time=%d, mime=%s",
//i,(recresult->back()).iRecognitionConfidence, (endtime-starttime), (recresult->back()).iRecognizedFormat.get_cstr()));
if ((recresult->back()).iRecognitionConfidence == PVMFRecognizerConfidenceCertain)
{
CompleteCurrentRecRegCommand(PVMFSuccess);
return;
}
}
}
}
// Complete the recognizer command
CompleteCurrentRecRegCommand(PVMFSuccess);
}
else
{
//pending
//wait for datastream call back
oRecognizePending = true;
}
}
void PVMFRecognizerRegistryImpl::DoCancelCommand(PVMFRecRegImplCommand& aCmd)
{
// TEMP: For now only one command can be cancelled.
// Since Recognize happens in one AO call, check in the pending cmd queue
if (iRecognizerPendingCmdList.empty() == false)
{
iRecognizerCurrentCmd.push_front(iRecognizerPendingCmdList.top());
iRecognizerPendingCmdList.pop();
OSCL_ASSERT(iRecognizerCurrentCmd[0].GetCmdId() == aCmd.GetCmdId());
}
if (iRecognizerCurrentCmd.empty() == false)
{
// get the commandToCancelId
PVMFRecRegImplCommandParamUnion paramval = aCmd.GetParam(0);
PVMFCommandId commandToCancelId = paramval.int32_value;
if (FindCommandByID(iRecognizerCurrentCmd, commandToCancelId) == false) return;
CompleteCurrentRecRegCommand(PVMFErrCancelled, commandToCancelId);
// close data stream object to avoid any memory leak in case of cancel command
if (iDataStream) iDataStream->CloseSession(iDataStreamSessionID);
if (iDataStreamFactory)
{
PVUuid uuid = PVMIDataStreamSyncInterfaceUuid;
iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid,
OSCL_STATIC_CAST(PVInterface*, iDataStream));
iDataStream = NULL;
}
}
}
bool PVMFRecognizerRegistryImpl::FindCommandByID(Oscl_Vector<PVMFRecRegImplCommand, OsclMemAllocator> &aCmdQueue, const PVMFCommandId aCmdId)
{
if (aCmdQueue.empty()) return false;
for (uint32 i = 0; i < aCmdQueue.size(); i++)
{
if (aCmdQueue[i].GetCmdId() == aCmdId) return true;
}
return false;
}
void PVMFRecognizerRegistryImpl::DataStreamCommandCompleted(const PVMFCmdResp& aResponse)
{
if (aResponse.GetCmdId() == iRequestReadCapacityNotificationID)
{
iDataStreamCallBackStatus = aResponse.GetCmdStatus();
RunIfNotReady();
}
else
{
LOGERROR((0, "PVMFRecognizerRegistryImpl::DataStreamCommandCompleted failed"));
OSCL_ASSERT(false);
}
}
void PVMFRecognizerRegistryImpl::DataStreamInformationalEvent(const PVMFAsyncEvent& aEvent)
{
OSCL_UNUSED_ARG(aEvent);
OSCL_LEAVE(OsclErrNotSupported);
}
void PVMFRecognizerRegistryImpl::DataStreamErrorEvent(const PVMFAsyncEvent& aEvent)
{
OSCL_UNUSED_ARG(aEvent);
OSCL_LEAVE(OsclErrNotSupported);
}
| [
"abgoyal@gmail.com"
] | abgoyal@gmail.com |
3383bb1e76ddce61c903a3bdfb73f7466377ea58 | 6cc10675105fdb4543857b657f8f077c93158f7d | /src/unit_test/nas_acl_cps_entry_ut.cpp | a66cf5048e7c93176177fc8b3e93884a4cf6eb43 | [] | no_license | pkarashchenko/opx-nas-acl | 87a1f17209b91d2059b3cd58cd0902042450d354 | e9e77ab615dce52b2745d18163b0deb9d1f8cc5d | refs/heads/master | 2021-01-19T19:54:10.063675 | 2017-07-21T22:19:45 | 2017-07-21T22:20:08 | 83,730,446 | 1 | 1 | null | 2017-03-02T22:20:29 | 2017-03-02T22:20:29 | null | UTF-8 | C++ | false | false | 104,632 | cpp | /*
* Copyright (c) 2016 Dell Inc.
*
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
#include <net/if.h>
#include <stdarg.h>
#include <arpa/inet.h>
#include "nas_acl_cps_ut.h"
#include "cps_api_object_key.h"
#include "cps_class_map.h"
#include "std_ip_utils.h"
#include "iana-if-type.h"
#include "dell-interface.h"
#include "dell-base-if.h"
#include "dell-base-routing.h"
#include "nas_ndi_route.h"
#define UT_ARR_DATA_LEN 128
#define SYSTEM(arg) if (system(arg)) return false;
typedef enum {
_NO_OP,
_MODIFY,
_DELETE,
_ADD_LATER,
_SKIP,
} ut_field_op_t;
typedef struct _ut_filter_info_t {
BASE_ACL_MATCH_TYPE_t type;
uint64_t val1;
uint64_t val2;
ut_field_op_t mod;
uint64_t new_val1; /* Used for entry modify test */
uint64_t new_val2; /* Used for entry modify test */
} ut_filter_info_t;
typedef struct _ut_action_info_t {
BASE_ACL_ACTION_TYPE_t type;
uint64_t val1;
uint64_t val2;
ut_field_op_t mod;
uint64_t new_val1; /* Used for entry modify test */
uint64_t new_val2; /* Used for entry modify test */
} ut_action_info_t;
typedef std::vector<ut_filter_info_t> ut_filter_info_list_t;
typedef std::vector<ut_action_info_t> ut_action_info_list_t;
typedef struct _ut_entry_info_t {
uint32_t priority;
ut_field_op_t mod_priority;
uint32_t new_priority;
ut_filter_info_list_t filter_info_list;
ut_action_info_list_t action_info_list;
ut_npu_list_t npu_list;
ut_field_op_t mod_npu_list;
ut_npu_list_t new_npu_list;
} ut_entry_info_t;
std::vector<nas_obj_id_t> g_entry_id_list;
std::vector<ut_entry_t> g_validate_entry_list;
std::vector<ut_entry_t> g_validate_old_entry_list;
#define _ALL_FIELDS_ENTRY 99
#define _ALL_FIELDS_ENTRY_DEF_VAL1 79
#define _ALL_FIELDS_ENTRY_DEF_VAL2 89
struct entry_input_comp {
bool operator() (uint32_t lhs, uint32_t rhs) {
return (lhs < rhs);
}
};
static std::set<uint32_t> _optional_filter_type = {
BASE_ACL_MATCH_TYPE_SRC_IPV6,
BASE_ACL_MATCH_TYPE_DST_IPV6,
BASE_ACL_MATCH_TYPE_SRC_MAC,
BASE_ACL_MATCH_TYPE_DST_MAC,
BASE_ACL_MATCH_TYPE_SRC_IP,
BASE_ACL_MATCH_TYPE_DST_IP,
BASE_ACL_MATCH_TYPE_OUTER_VLAN_ID,
BASE_ACL_MATCH_TYPE_OUTER_VLAN_PRI,
BASE_ACL_MATCH_TYPE_INNER_VLAN_ID,
BASE_ACL_MATCH_TYPE_INNER_VLAN_PRI,
BASE_ACL_MATCH_TYPE_L4_SRC_PORT,
BASE_ACL_MATCH_TYPE_L4_DST_PORT,
BASE_ACL_MATCH_TYPE_ETHER_TYPE,
BASE_ACL_MATCH_TYPE_IP_PROTOCOL,
BASE_ACL_MATCH_TYPE_DSCP,
BASE_ACL_MATCH_TYPE_TTL,
BASE_ACL_MATCH_TYPE_TOS,
BASE_ACL_MATCH_TYPE_IP_FLAGS,
BASE_ACL_MATCH_TYPE_TCP_FLAGS,
BASE_ACL_MATCH_TYPE_IPV6_FLOW_LABEL,
BASE_ACL_MATCH_TYPE_TC,
BASE_ACL_MATCH_TYPE_ECN,
BASE_ACL_MATCH_TYPE_ICMP_TYPE,
BASE_ACL_MATCH_TYPE_ICMP_CODE
};
static std::map <uint32_t, ut_entry_info_t, entry_input_comp>
_entry_map_input =
{
{1,
{1, _MODIFY, 11,
{
{BASE_ACL_MATCH_TYPE_SRC_IP, 4, 5, _MODIFY, 6, 7},
{BASE_ACL_MATCH_TYPE_DST_IP, 14, 15, _DELETE, 0, 0},
{BASE_ACL_MATCH_TYPE_IP_PROTOCOL, 4, 1, _MODIFY, 3, 3},
{BASE_ACL_MATCH_TYPE_L4_DST_PORT, 500, 0xfff, _NO_OP, 0, 0},
},
{
{BASE_ACL_ACTION_TYPE_PACKET_ACTION, BASE_ACL_PACKET_ACTION_TYPE_DROP, 0, _NO_OP, 0, 0},
{BASE_ACL_ACTION_TYPE_SET_OUTER_VLAN_PRI, 7, 0, _MODIFY, 5, 0},
{BASE_ACL_ACTION_TYPE_FLOOD, 0, 0, _ADD_LATER, 0, 0},
},
{}, _NO_OP, {},
}
},
{_ALL_FIELDS_ENTRY,
{100, _MODIFY, 101,
{},
{},
{}, _NO_OP, {},
}
}
};
static ut_entry_t *ut_get_entry_by_entry_id (nas_acl_ut_table_t* table,
nas_obj_id_t entry_id)
{
for (auto& map_kv: table->entries) {
if (map_kv.second.entry_id == entry_id) {
return &map_kv.second;
}
}
return NULL;
}
void ut_dump_ndi_obj_id_table (nas::ndi_obj_id_table_t& ndi_obj_id_table)
{
size_t count = 0;
ut_printf ("[%s()-%d] Printing ndi_obj_id_table \r\n",
__FUNCTION__, __LINE__);
for (const auto& kvp: ndi_obj_id_table) {
ut_printf ("%ld: Npu: %d, objId: %ld\r\n",
count, (int)kvp.first, kvp.second);
count++;
}
}
static inline void ut_init_all_verified_flags (nas_acl_ut_table_t& table)
{
for (auto& map_kv: table.entries) {
map_kv.second.to_be_verified = true;
map_kv.second.verified = false;
}
}
static inline void ut_clear_all_verified_flags (nas_acl_ut_table_t& table)
{
for (auto& map_kv: table.entries) {
map_kv.second.to_be_verified = false;
map_kv.second.verified = false;
}
}
static inline bool ut_validate_verified_flags ()
{
uint32_t index;
for (index = 0; index < NAS_ACL_UT_MAX_TABLES; index++) {
nas_acl_ut_table_t& table = g_nas_acl_ut_tables [index];
for (auto& map_kv: table.entries) {
ut_entry_t& entry = map_kv.second;
if ((entry.to_be_verified == true) && (entry.verified == false)) {
ut_printf ("%s(): Entry NOT verified. Switch: %d, Table: %ld, "
"Entry Id: %ld, Entry Index: %d\r\n", __FUNCTION__,
entry.switch_id, entry.table_id, entry.entry_id,
entry.index);
return false;
}
}
}
return true;
}
static uint8_t ip_buf[sizeof(dn_ipv4_addr_t) + 1];
static uint8_t mask_buf[sizeof(dn_ipv4_addr_t) + 1];
static inline void ut_fill_all_fields_filter_val (ut_filter_t& filter, bool modify)
{
uint32_t val1;
uint32_t val2;
uint32_t increment;
increment = (modify == true) ? 1 : 0;
switch (filter.type) {
case BASE_ACL_MATCH_TYPE_IN_PORTS:
case BASE_ACL_MATCH_TYPE_OUT_PORTS:
case BASE_ACL_MATCH_TYPE_IN_PORT:
case BASE_ACL_MATCH_TYPE_OUT_PORT:
case BASE_ACL_MATCH_TYPE_IN_INTFS:
case BASE_ACL_MATCH_TYPE_OUT_INTFS:
case BASE_ACL_MATCH_TYPE_IN_INTF:
case BASE_ACL_MATCH_TYPE_OUT_INTF:
val1 = NAS_ACL_UT_MAX_NPUS; /*
* No of ports. Using Max NPUs here,
* since want to have one port picked
* from each NPU.
*/
val2 = 1 + increment; /* Start Port */
break;
case BASE_ACL_MATCH_TYPE_OUTER_VLAN_PRI:
case BASE_ACL_MATCH_TYPE_INNER_VLAN_PRI:
val1 = 5 + increment;
val2 = 5 + increment;
break;
case BASE_ACL_MATCH_TYPE_IP_FLAGS:
val1 = 3 + increment;
val2 = 0x7;
break;
case BASE_ACL_MATCH_TYPE_ECN:
val1 = 1 + increment;
val2 = 0x3;
break;
case BASE_ACL_MATCH_TYPE_TCP_FLAGS:
val1 = 54 + increment;
val2 = 0x3f;
break;
case BASE_ACL_MATCH_TYPE_IP_TYPE:
val1 = BASE_ACL_MATCH_IP_TYPE_ARP_REPLY;
val2 = val1;
break;
case BASE_ACL_MATCH_TYPE_IP_FRAG:
val1 = BASE_ACL_MATCH_IP_FRAG_NON_HEAD;
val2 = val1;
break;
case BASE_ACL_MATCH_TYPE_OUTER_VLAN_CFI:
case BASE_ACL_MATCH_TYPE_INNER_VLAN_CFI:
val1 = 0 + increment;
val2 = 0 + increment;
break;
case BASE_ACL_MATCH_TYPE_DSCP:
val1 = 50 + increment;
val2 = 50 + increment;
break;
case BASE_ACL_MATCH_TYPE_L4_SRC_PORT:
case BASE_ACL_MATCH_TYPE_L4_DST_PORT:
val1 = 500 + increment;
val2= val1;
break;
case BASE_ACL_MATCH_TYPE_SRC_IP:
case BASE_ACL_MATCH_TYPE_DST_IP:
ip_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
mask_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
val1 = (uint64_t)ip_buf;
memset(&ip_buf[1], 0x1, sizeof(dn_ipv4_addr_t));
memset(&mask_buf[1], 0xff, sizeof(dn_ipv4_addr_t));
val2 = (uint64_t)mask_buf;
break;
default:
val1 = _ALL_FIELDS_ENTRY_DEF_VAL1 + increment;
val2 = _ALL_FIELDS_ENTRY_DEF_VAL2 + increment;
}
filter.val_list.clear ();
filter.val_list.push_back (val1);
filter.val_list.push_back (val2);
}
static inline void ut_fill_all_fields_action_val (ut_action_t& action, bool modify)
{
uint32_t val1;
uint32_t val2;
uint32_t increment;
increment = (modify == true) ? 1 : 0;
switch (action.type) {
case BASE_ACL_ACTION_TYPE_REDIRECT_PORT:
val1 = 1;
val2 = 7 + increment;
break;
case BASE_ACL_ACTION_TYPE_REDIRECT_IP_NEXTHOP:
case BASE_ACL_ACTION_TYPE_MIRROR_INGRESS:
case BASE_ACL_ACTION_TYPE_MIRROR_EGRESS:
case BASE_ACL_ACTION_TYPE_SET_POLICER:
case BASE_ACL_ACTION_TYPE_SET_CPU_QUEUE:
val1 = 10 + increment;
val2 = 100 + increment;
break;
case BASE_ACL_ACTION_TYPE_SET_INNER_VLAN_PRI:
val1 = 3 + increment;
val2 = val1;
break;
case BASE_ACL_ACTION_TYPE_SET_OUTER_VLAN_PRI:
val1 = 4 + increment;
val2 = val1;
break;
case BASE_ACL_ACTION_TYPE_SET_DSCP:
val1 = 23 + increment;
val2 = val1;
break;
case BASE_ACL_ACTION_TYPE_PACKET_ACTION:
val1 = BASE_ACL_PACKET_ACTION_TYPE_DROP + increment;
val2 = val1;
break;
default:
val1 = _ALL_FIELDS_ENTRY_DEF_VAL1 + increment;
val2 = _ALL_FIELDS_ENTRY_DEF_VAL2 + increment;
}
action.val_list.clear ();
action.val_list.push_back (val1);
action.val_list.push_back (val2);
}
void ut_add_all_filter (ut_entry_t& entry)
{
ut_filter_t filter;
cps_api_attr_id_t filter_type;
for (filter_type = NAS_ACL_UT_START_FILTER;
filter_type <= NAS_ACL_UT_END_FILTER; filter_type++) {
filter.type = (BASE_ACL_MATCH_TYPE_t) filter_type;
if (!nas_acl_filter_is_type_valid (filter.type)) {
continue;
}
if (filter.type == BASE_ACL_MATCH_TYPE_IN_PORT) {
continue;
}
ut_fill_all_fields_filter_val (filter, true);
entry.filter_list.insert (filter);
}
}
void ut_add_all_action (ut_entry_t& entry)
{
ut_action_t action;
cps_api_attr_id_t action_type;
for (action_type = NAS_ACL_UT_START_ACTION;
action_type <= NAS_ACL_UT_END_ACTION; action_type++) {
action.type = (BASE_ACL_ACTION_TYPE_t) action_type;
if (!nas_acl_action_is_type_valid (action.type)) {
continue;
}
if ((action.type == BASE_ACL_ACTION_TYPE_MIRROR_EGRESS) ||
(action.type == BASE_ACL_ACTION_TYPE_MIRROR_INGRESS) ||
(action.type == BASE_ACL_ACTION_TYPE_SET_COUNTER)) {
continue;
}
ut_fill_all_fields_action_val (action, false);
entry.action_list.insert (action);
}
}
void ut_modify_all_filter (ut_entry_t& entry)
{
for (auto filter: entry.filter_list) {
ut_fill_all_fields_filter_val (filter, false);
}
}
void ut_modify_all_action (ut_entry_t& entry)
{
for (auto action: entry.action_list) {
ut_fill_all_fields_action_val (action, false);
}
}
static bool ut_add_opaque_data_to_obj (cps_api_object_t obj,
ut_attr_id_list_t& attr_list,
uint64_t in_u64)
{
int32_t npu_id;
nas::ndi_obj_id_table_t obj_id_table;
ut_printf ("[%s()-%d] in_u64: %ld\r\n", __FUNCTION__, __LINE__, in_u64);
for (npu_id = 0; npu_id < NAS_ACL_UT_MAX_NPUS; npu_id++) {
obj_id_table [npu_id] = (ndi_obj_id_t) (in_u64);
}
ut_dump_ndi_obj_id_table (obj_id_table);
return nas::ndi_obj_id_table_cps_serialize (obj_id_table, obj,
attr_list.data (),
attr_list.size ());
}
static bool ut_validate_opaque_obj_data (cps_api_object_t obj,
ut_attr_id_list_t& attr_list,
uint64_t in_u64)
{
nas::ndi_obj_id_table_t ndi_obj_id_table;
uint32_t count = 0;
bool rc;
ut_printf ("%s() in_u64: %ld\r\n", __FUNCTION__, in_u64);
rc = nas::ndi_obj_id_table_cps_unserialize (ndi_obj_id_table, obj,
attr_list.data (),
attr_list.size ());
if (rc == false) {
ut_printf ("[%s()-%d] ndi_obj_id_table_cps_unserialize failed. "
"in_u64: %ld\r\n", __FUNCTION__, __LINE__, in_u64);
return false;
}
ut_dump_ndi_obj_id_table (ndi_obj_id_table);
if (ndi_obj_id_table.size () != NAS_ACL_UT_MAX_NPUS) {
ut_printf ("[%s()-%d] ndi_obj_id_table size mismatch. "
"Size: %ld, NAS_ACL_UT_MAX_NPUS: %ld\r\n",
__FUNCTION__, __LINE__, ndi_obj_id_table.size (), in_u64);
return false;
}
for (auto elem: ndi_obj_id_table) {
auto npu_id = elem.first;
auto obj_id = elem.second;
if ((nas_obj_id_t) (in_u64) != obj_id) {
ut_printf ("[%s()-%d] Obj Id mismatch. Expected: %ld, Actual: %d.\r\n",
__FUNCTION__, __LINE__, obj_id, npu_id);
return false;
}
if ((npu_id < 0) || (npu_id >= (int32_t) NAS_ACL_UT_MAX_NPUS)) {
ut_printf ("[%s()-%d] Invalid Npu. npu_id: %d, in_u64: %ld\r\n",
__FUNCTION__, __LINE__, npu_id, in_u64);
return false;
}
count++;
}
if (count != NAS_ACL_UT_MAX_NPUS) {
ut_printf ("[%s()-%d] size mismatch. count: %d, expected count: %d\r\n",
__FUNCTION__, __LINE__, count, NAS_ACL_UT_MAX_NPUS);
return false;
}
return true;
}
static bool ut_validate_sub_data (cps_api_object_t obj,
ut_attr_id_list_t& attr_list,
uint64_t in_u64,
NAS_ACL_DATA_TYPE_t obj_data_type,
size_t obj_data_size)
{
cps_api_object_attr_t attr_val;
uint8_t *p_u8;
if (obj_data_type == NAS_ACL_DATA_OPAQUE) {
return (ut_validate_opaque_obj_data (obj, attr_list, in_u64));
}
attr_val = cps_api_object_e_get (obj, attr_list.data(), attr_list.size());
if (attr_val == NULL) {
ut_printf ("[%s()-%d] cps_api_object_e_get failed.\r\n",
__FUNCTION__, __LINE__);
return false;
}
switch (obj_data_type) {
case NAS_ACL_DATA_NONE:
return true;
break;
case NAS_ACL_DATA_U8:
p_u8 = (uint8_t *) cps_api_object_attr_data_bin (attr_val);
if (*p_u8 != (uint8_t) in_u64) {
ut_printf ("[%s()-%d] Invalid U8 data (%d). \r\n",
__FUNCTION__, __LINE__, *p_u8);
return false;
}
break;
case NAS_ACL_DATA_U16:
if (cps_api_object_attr_data_u16 (attr_val) != (uint16_t) in_u64) {
ut_printf ("[%s()-%d] Invalid U16 data (%d).\r\n",
__FUNCTION__, __LINE__,
cps_api_object_attr_data_u16 (attr_val));
return false;
}
break;
case NAS_ACL_DATA_U32:
case NAS_ACL_DATA_IFINDEX:
if (cps_api_object_attr_data_u32 (attr_val) != (uint32_t)in_u64) {
ut_printf ("[%s()-%d] cps_api_object_e_get failed.\r\n",
__FUNCTION__, __LINE__);
return false;
}
break;
case NAS_ACL_DATA_U64:
case NAS_ACL_DATA_OBJ_ID:
if (cps_api_object_attr_data_u64 (attr_val) != in_u64) {
ut_printf ("[%s()-%d] cps_api_object_e_get failed.\r\n",
__FUNCTION__, __LINE__);
return false;
}
break;
case NAS_ACL_DATA_BIN:
{
//Always return true because static buffer is used to store all bin data
return true;
}
default:
ut_printf ("[%s()-%d] cps_api_object_e_get failed.\r\n",
__FUNCTION__, __LINE__);
return false;
break;
}
return true;
}
bool ut_validate_non_iflist_data (ut_attr_id_list_t& parent_list,
const nas_acl_map_data_list_t& child_list,
cps_api_object_t obj,
NAS_ACL_DATA_TYPE_t obj_data_type,
size_t obj_data_size,
bool optional,
const ut_val_list_t& val_list)
{
uint32_t index = 0;
uint64_t flag;
if (obj_data_type != NAS_ACL_DATA_EMBEDDED) {
if (optional) {
flag = val_list.at(index++);
if (flag == 0) {
return true;
}
}
if (!ut_validate_sub_data (obj, parent_list, val_list.at (index),
obj_data_type, obj_data_size)) {
ut_printf ("[%s()-%d] ut_validate_sub_data() failed. "
"Data Type: %s\r\n", __FUNCTION__, __LINE__,
nas_acl_obj_data_type_to_str (obj_data_type));
return false;
}
return true;
}
for (auto data: child_list) {
if (data.mode == NAS_ACL_ATTR_MODE_OPTIONAL) {
flag = val_list.at(index++);
if (flag == 0) {
continue;
}
}
parent_list.push_back (data.attr_id);
if (!ut_validate_sub_data (obj, parent_list, val_list.at (index),
data.data_type, data.data_len)) {
ut_printf ("[%s()-%d] ut_validate_sub_data() failed. "
"Data Type: %s, Index: %d\r\n", __FUNCTION__, __LINE__,
nas_acl_obj_data_type_to_str (obj_data_type), index);
return false;
}
parent_list.pop_back ();
index++;
}
return true;
}
bool ut_validate_iflist_data (ut_attr_id_list_t& list,
cps_api_object_t obj,
const ut_val_list_t& val_list)
{
cps_api_object_it_t it;
cps_api_object_it_t it_if_list;
hal_ifindex_t ifindex;
hal_ifindex_t num_ifindex;
int index;
ut_val_list_t if_list_tmp;
size_t position;
bool found;
if (!cps_api_object_it (obj, list.data(), list.size(), &it)) {
ut_printf ("[%s()-%d] cps_api_object_it() failed. \r\n",
__FUNCTION__, __LINE__);
return false;
}
num_ifindex = val_list.at (0);
ifindex = val_list.at (1);
for (index = 0; index < num_ifindex; index++) {
if_list_tmp.push_back (ifindex);
ifindex += NAS_ACL_UT_NUM_PORTS_PER_NPU;
}
for (it_if_list = it;
cps_api_object_it_valid (&it_if_list);
cps_api_object_it_next (&it_if_list)) {
ifindex = cps_api_object_attr_data_u32 (it_if_list.attr);
position = 0;
found = false;
for (auto ifindex_tmp: if_list_tmp) {
if (ifindex == (int) ifindex_tmp) {
if_list_tmp.erase (if_list_tmp.begin () + position);
found = true;
break;
}
position++;
}
if (found == false) {
ut_printf ("[%s()-%d] ifIndex NOT found. \r\n",
__FUNCTION__, __LINE__);
return false;
}
}
if (if_list_tmp.size () != 0) {
ut_printf ("[%s()-%d] Could not match all ifindexes \r\n", __FUNCTION__, __LINE__);
return false;
}
return true;
}
bool ut_validate_data (ut_attr_id_list_t& parent_list,
const nas_acl_map_data_list_t& child_list,
cps_api_object_t obj,
NAS_ACL_DATA_TYPE_t data_type,
size_t data_size,
bool optional,
const ut_val_list_t& val_list)
{
bool rc;
switch (data_type) {
case NAS_ACL_DATA_NONE:
rc = true;
break;
case NAS_ACL_DATA_U8:
case NAS_ACL_DATA_U16:
case NAS_ACL_DATA_U32:
case NAS_ACL_DATA_IFINDEX:
case NAS_ACL_DATA_U64:
case NAS_ACL_DATA_BIN:
case NAS_ACL_DATA_OBJ_ID:
case NAS_ACL_DATA_EMBEDDED:
rc = ut_validate_non_iflist_data (parent_list, child_list, obj,
data_type, data_size, optional, val_list);
break;
case NAS_ACL_DATA_IFINDEX_LIST:
rc = ut_validate_iflist_data (parent_list, obj, val_list);
break;
default:
ut_printf ("%s(): Unknown Data type (%d)\r\n",
__FUNCTION__, data_type);
rc = false;
break;
}
return rc;
}
static bool ut_add_data_to_obj (cps_api_object_t obj,
ut_attr_id_list_t& attr_list,
uint64_t in_u64,
NAS_ACL_DATA_TYPE_t obj_data_type,
size_t obj_data_size)
{
cps_api_object_ATTR_TYPE_t cps_attr_type;
nas::ndi_obj_id_table_t obj_id_table;
uint8_t u8;
uint16_t u16;
uint32_t u32;
void *p_data;
size_t size;
ut_printf ("[%s()-%d] in_u64: %ld, obj_data_type: %s(%d), "
"obj_data_size: %ld\r\n", __FUNCTION__, __LINE__, in_u64,
nas_acl_obj_data_type_to_str (obj_data_type), obj_data_type, obj_data_size);
if (obj_data_type == NAS_ACL_DATA_OPAQUE) {
return (ut_add_opaque_data_to_obj (obj, attr_list, in_u64));
}
switch (obj_data_type) {
case NAS_ACL_DATA_U8:
u8 = (uint8_t) in_u64;
p_data = &u8;
size = sizeof (uint8_t);
cps_attr_type = cps_api_object_ATTR_T_BIN;
break;
case NAS_ACL_DATA_U16:
u16 = (uint16_t) in_u64;
p_data = &u16;
size = sizeof (uint16_t);
cps_attr_type = cps_api_object_ATTR_T_U16;
break;
case NAS_ACL_DATA_U32:
case NAS_ACL_DATA_IFINDEX:
u32 = (uint32_t)in_u64;
p_data = &u32;
size = sizeof (uint32_t);
cps_attr_type = cps_api_object_ATTR_T_U32;
break;
case NAS_ACL_DATA_U64:
p_data = &in_u64;
size = sizeof (uint64_t);
cps_attr_type = cps_api_object_ATTR_T_U64;
break;
case NAS_ACL_DATA_OBJ_ID:
p_data = &in_u64;
size = sizeof (nas_obj_id_t);
cps_attr_type = cps_api_object_ATTR_T_U64;
break;
case NAS_ACL_DATA_BIN:
p_data = (void *)in_u64;
size = (size_t)*((uint8_t *)p_data);
p_data = &((uint8_t *)p_data)[1];
cps_attr_type = cps_api_object_ATTR_T_BIN;
break;
default:
ut_printf ("%s(): DEFAULT case. \r\n", __FUNCTION__);
return false;
break;
}
if (obj_data_size != size) {
ut_printf ("%s(): Size mismatch. \r\n", __FUNCTION__);
return false;
}
if (cps_api_object_e_add (obj, attr_list.data(), attr_list.size(),
cps_attr_type, p_data, size) != true) {
ut_printf ("%s(): cps_api_object_e_add () failed.\r\n", __FUNCTION__);
return false;
}
return true;
}
static bool
ut_action_copy_non_iflist_data_to_obj (cps_api_object_t obj,
ut_attr_id_list_t& parent_list,
const nas_acl_map_data_list_t& child_list,
NAS_ACL_DATA_TYPE_t obj_data_type,
size_t obj_data_size,
bool optional,
const ut_val_list_t& val_list)
{
size_t index = 0;
uint64_t flag;
ut_printf ("%s(), obj_data_type: %s, obj_data_size: %ld \r\n",
__FUNCTION__, nas_acl_obj_data_type_to_str (obj_data_type),
obj_data_size);
if (obj_data_type != NAS_ACL_DATA_EMBEDDED) {
if (optional) {
flag = val_list.at(index);
if (flag == 0) {
return true;
}
index ++;
}
if (!ut_add_data_to_obj (obj, parent_list, val_list.at (index),
obj_data_type, obj_data_size)) {
ut_printf ("%s(): %d, ut_add_data_to_obj () failed. \r\n",
__FUNCTION__, __LINE__);
return false;
}
return true;
}
for (auto data: child_list) {
if (data.mode == NAS_ACL_ATTR_MODE_OPTIONAL) {
flag = val_list.at(index ++);
if (flag == 0) {
continue;
}
}
parent_list.push_back (data.attr_id);
if (!ut_add_data_to_obj (obj, parent_list, val_list.at (index),
data.data_type, data.data_len)) {
ut_printf ("%s(): %d, ut_add_data_to_obj () failed. \r\n",
__FUNCTION__, __LINE__);
return false;
}
/* Remove the processed child attr id */
parent_list.pop_back ();
index++;
}
return true;
}
static bool
ut_action_copy_iflist_data_to_obj (cps_api_object_t obj,
ut_attr_id_list_t& parent_list,
bool optional,
const ut_val_list_t& val_list)
{
uint32_t num_ifindex;
uint32_t if_index;
uint32_t index;
int idx = 0;
if (optional) {
uint64_t flag = val_list.at(idx);
if (flag == 0) {
return true;
}
idx ++;
}
num_ifindex = val_list.at (idx);
if_index = val_list.at (idx + 1);
ut_printf ("[%s()-%d] num_ifindex: %d, if_index: %d\r\n",
__FUNCTION__, __LINE__, num_ifindex, if_index);
for (index = 0; index < num_ifindex; index++) {
if (!cps_api_object_e_add (obj,
parent_list.data (),
parent_list.size (),
cps_api_object_ATTR_T_U32,
&if_index,
sizeof (uint32_t))) {
ut_printf ("[%s()-%d] cps_api_object_e_add failed\r\n",
__FUNCTION__, __LINE__);
return false;
}
if_index += NAS_ACL_UT_NUM_PORTS_PER_NPU;
}
return true;
}
bool ut_copy_data_to_obj (ut_attr_id_list_t& parent_list,
const nas_acl_map_data_list_t& child_list,
cps_api_object_t obj,
NAS_ACL_DATA_TYPE_t obj_data_type,
size_t obj_data_size,
bool optional,
const ut_val_list_t& val_list)
{
bool rc;
switch (obj_data_type) {
case NAS_ACL_DATA_NONE:
rc = true;
break;
case NAS_ACL_DATA_U8:
case NAS_ACL_DATA_U16:
case NAS_ACL_DATA_U32:
case NAS_ACL_DATA_IFINDEX:
case NAS_ACL_DATA_U64:
case NAS_ACL_DATA_OBJ_ID:
case NAS_ACL_DATA_BIN:
case NAS_ACL_DATA_EMBEDDED:
rc = ut_action_copy_non_iflist_data_to_obj (obj,
parent_list,
child_list,
obj_data_type,
obj_data_size,
optional,
val_list);
break;
case NAS_ACL_DATA_IFINDEX_LIST:
rc = ut_action_copy_iflist_data_to_obj (obj, parent_list, optional, val_list);
break;
default:
rc = false;
break;
}
return rc;
}
static inline void set_all_update_flags (ut_entry_t& entry)
{
entry.update_priority = true;
if (!entry.filter_list.empty ()) {
entry.update_filter = true;
}
if (!entry.action_list.empty ()) {
entry.update_action = true;
}
if (!entry.npu_list.empty ()) {
entry.update_npu = true;
}
}
static inline void clear_all_update_flags (ut_entry_t& entry)
{
entry.update_priority = false;
entry.update_filter = false;
entry.update_action = false;
entry.update_npu = false;
}
bool ut_clear_action (ut_entry_t& entry,
BASE_ACL_ACTION_TYPE_t type,
nas::attr_list_t& parent_attr_id_list,
const nas_acl_action_info_t& map_info,
cps_api_object_t obj,
bool *p_out_found)
{
*p_out_found = false;
for (auto& action: entry.action_list) {
if (action.type == type) {
*p_out_found = true;
if (!ut_validate_data (parent_attr_id_list,
map_info.child_list,
obj,
map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
action.val_list)) {
return false;
}
entry.action_list.erase (action);
break;
}
}
return true;
}
bool ut_validate_entry_filter_list (const cps_api_object_t obj,
const cps_api_object_it_t& it,
ut_entry_t& entry)
{
BASE_ACL_MATCH_TYPE_t match_type_val;
BASE_ACL_ENTRY_MATCH_t match_val_attr_id;
cps_api_object_it_t it_lvl_1 = it;
cps_api_attr_id_t attr_id;
cps_api_attr_id_t list_index = 0;
nas::attr_list_t parent_attr_id_list;
bool filter_found;
for (cps_api_object_it_inside (&it_lvl_1);
cps_api_object_it_valid (&it_lvl_1);
cps_api_object_it_next (&it_lvl_1)) {
parent_attr_id_list.clear ();
parent_attr_id_list.push_back (BASE_ACL_ENTRY_MATCH);
list_index = cps_api_object_attr_id (it_lvl_1.attr);
parent_attr_id_list.push_back (list_index);
cps_api_object_it_t it_lvl_2 = it_lvl_1;
cps_api_object_it_inside (&it_lvl_2);
if (!cps_api_object_it_valid (&it_lvl_2)) {
return false;
}
attr_id = cps_api_object_attr_id (it_lvl_2.attr);
/*
* TODO: Need to figure out how emptying of match parameters
* is to be handled.
*/
if (attr_id != BASE_ACL_ENTRY_MATCH_TYPE) {
ut_printf ("%s(): BASE_ACL_ENTRY_MATCH_TYPE not present.\r\n",
__FUNCTION__);
return false;
}
match_type_val = (BASE_ACL_MATCH_TYPE_t)
cps_api_object_attr_data_u32 (it_lvl_2.attr);
cps_api_object_it_next (&it_lvl_2);
if (!cps_api_object_it_valid (&it_lvl_2)) {
return false;
}
match_val_attr_id = (BASE_ACL_ENTRY_MATCH_t)
cps_api_object_attr_id (it_lvl_2.attr);
parent_attr_id_list.push_back (match_val_attr_id);
const auto& map_kv = nas_acl_get_filter_map().find (match_type_val);
if (map_kv == nas_acl_get_filter_map().end ()) {
ut_printf ("%s(): Unknown Filter (%d).\r\n",
__FUNCTION__, match_type_val);
return false;
}
const nas_acl_filter_info_t& map_info = map_kv->second;
filter_found = false;
for (auto& filter: entry.filter_list) {
if (filter.type == match_type_val) {
filter_found = true;
if (!ut_validate_data (parent_attr_id_list,
map_info.child_list,
obj,
map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
filter.val_list)) {
return false;
}
entry.filter_list.erase (filter);
break;
}
}
if (filter_found == false) {
ut_printf ("%s(): Filter (%d) NOT found\r\n",
__FUNCTION__, match_type_val);
return false;
}
}
if (entry.filter_list.size () != 0) {
ut_printf ("%s(): Unvalidated filters present\r\n", __FUNCTION__);
return false;
}
return true;
}
bool ut_validate_entry_action_list (const cps_api_object_t obj,
const cps_api_object_it_t& it,
ut_entry_t& entry)
{
BASE_ACL_ACTION_TYPE_t action_type_val;
BASE_ACL_ENTRY_ACTION_t action_val_attr_id;
cps_api_object_it_t it_lvl_1 = it;
cps_api_attr_id_t attr_id;
cps_api_attr_id_t list_index = 0;
nas::attr_list_t parent_attr_id_list;
bool action_found;
for (cps_api_object_it_inside (&it_lvl_1);
cps_api_object_it_valid (&it_lvl_1);
cps_api_object_it_next (&it_lvl_1)) {
parent_attr_id_list.clear ();
parent_attr_id_list.push_back (BASE_ACL_ENTRY_ACTION);
list_index = cps_api_object_attr_id (it_lvl_1.attr);
parent_attr_id_list.push_back (list_index);
cps_api_object_it_t it_lvl_2 = it_lvl_1;
cps_api_object_it_inside (&it_lvl_2);
if (!cps_api_object_it_valid (&it_lvl_2)) {
return false;
}
attr_id = cps_api_object_attr_id (it_lvl_2.attr);
if (attr_id != BASE_ACL_ENTRY_ACTION_TYPE) {
return false;
}
action_type_val = (BASE_ACL_ACTION_TYPE_t)
cps_api_object_attr_data_u32 (it_lvl_2.attr);
const auto& map_kv = nas_acl_get_action_map().find (action_type_val);
if (map_kv == nas_acl_get_action_map().end ()) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
const nas_acl_action_info_t& map_info = map_kv->second;
cps_api_object_it_next (&it_lvl_2);
action_found = false;
if (map_info.val.data_type == NAS_ACL_DATA_NONE) {
if (cps_api_object_it_valid (&it_lvl_2)) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
if (!ut_clear_action (entry, action_type_val, parent_attr_id_list,
map_info, obj, &action_found)) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
}
else {
if (!cps_api_object_it_valid (&it_lvl_2)) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
action_val_attr_id = (BASE_ACL_ENTRY_ACTION_t)
cps_api_object_attr_id (it_lvl_2.attr);
if (map_info.val.attr_id != action_val_attr_id) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
parent_attr_id_list.push_back (action_val_attr_id);
if (!ut_clear_action (entry, action_type_val, parent_attr_id_list,
map_info, obj, &action_found)) {
ut_printf ("%s failed at %d for %d\r\n", __FUNCTION__, __LINE__, action_type_val);
return false;
}
}
if (action_found == false) {
ut_printf ("%s(): Action (%d) NOT found\r\n",
__FUNCTION__, action_type_val);
return false;
}
}
if (entry.action_list.size () != 0) {
ut_printf ("%s(): Missing Actions present.\r\n", __FUNCTION__);
return false;
}
return true;
}
bool ut_fill_entry_match (cps_api_object_t obj, const ut_entry_t& entry)
{
ut_attr_id_list_t parent_list;
cps_api_attr_id_t list_index = 0;
for (const auto& filter: entry.filter_list) {
const auto& map_kv = nas_acl_get_filter_map().find (filter.type);
if (map_kv == nas_acl_get_filter_map().end ()) {
ut_printf ("FAILED: Could not Find filter type %d\r\n", filter.type);
return false;
}
const nas_acl_filter_info_t& map_info = map_kv->second;
parent_list.clear ();
parent_list.push_back (BASE_ACL_ENTRY_MATCH);
parent_list.push_back (list_index);
parent_list.push_back (BASE_ACL_ENTRY_MATCH_TYPE);
if (!cps_api_object_e_add (obj,
parent_list.data (),
parent_list.size (),
cps_api_object_ATTR_T_U32,
&filter.type,
sizeof (uint32_t))) {
return false;
}
parent_list.pop_back ();
parent_list.push_back (map_info.val.attr_id);
if (!ut_copy_data_to_obj (parent_list,
map_info.child_list,
obj,
map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
filter.val_list)) {
ut_printf ("Failed filter %s", nas_acl_filter_type_name (filter.type));
return false;
}
list_index++;
}
return true;
}
bool ut_fill_entry_action (cps_api_object_t obj, const ut_entry_t& entry)
{
ut_attr_id_list_t parent_list;
cps_api_attr_id_t list_index = 0;
for (const auto& action: entry.action_list) {
const auto& map_kv = nas_acl_get_action_map ().find (action.type);
if (map_kv == nas_acl_get_action_map().end ()) {
ut_printf ("FAILED: Could not Find action type %d\r\n", action.type);
return false;
}
const nas_acl_action_info_t& map_info = map_kv->second;
parent_list.clear ();
parent_list.push_back (BASE_ACL_ENTRY_ACTION);
parent_list.push_back (list_index);
parent_list.push_back (BASE_ACL_ENTRY_ACTION_TYPE);
if (!cps_api_object_e_add (obj,
parent_list.data (),
parent_list.size (),
cps_api_object_ATTR_T_U32,
&action.type,
sizeof (uint32_t))) {
return false;
}
if (map_info.val.data_type != NAS_ACL_DATA_NONE) {
parent_list.pop_back ();
parent_list.push_back (map_info.val.attr_id);
if (!ut_copy_data_to_obj (parent_list,
map_info.child_list,
obj,
map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
action.val_list)) {
ut_printf ("Failed filter %s", nas_acl_action_type_name (action.type));
return false;
}
}
list_index++;
}
return true;
}
void nas_acl_ut_extract_entry_keys (cps_api_object_t obj,
nas_switch_id_t *p_out_switch_id,
nas_obj_id_t *p_out_table_id,
nas_obj_id_t *p_out_entry_id,
uint_t *p_out_count)
{
cps_api_object_attr_t table_id_attr = cps_api_get_key_data (obj,
BASE_ACL_ENTRY_TABLE_ID);
cps_api_object_attr_t entry_id_attr = cps_api_get_key_data (obj,
BASE_ACL_ENTRY_ID);
*p_out_count = 0;
if (table_id_attr) {
(*p_out_count) ++;
*p_out_table_id = cps_api_object_attr_data_u64 (table_id_attr);
ut_printf ("%s(): Table Id: %ld \r\n", __FUNCTION__, *p_out_table_id);
}
if (entry_id_attr) {
(*p_out_count) ++;
*p_out_entry_id = cps_api_object_attr_data_u64 (entry_id_attr);
ut_printf ("%s(): Entry Id: %ld \r\n", __FUNCTION__, *p_out_entry_id);
}
}
bool ut_fill_entry_create_req (cps_api_transaction_params_t *params,
ut_entry_t& entry)
{
cps_api_return_code_t rc;
cps_api_object_t obj;
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("cps_api_object_create () failed. \r\n");
return (false);
}
cps_api_object_guard obj_guard (obj);
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof (uint64_t));
cps_api_object_attr_add_u32 (obj, BASE_ACL_ENTRY_PRIORITY, entry.priority);
for (auto npu: entry.npu_list) {
cps_api_object_attr_add_u32(obj, BASE_ACL_ENTRY_NPU_ID_LIST, npu);
}
if (ut_fill_entry_match (obj, entry) == false) {
ut_printf ("ut_fill_entry_match () failed. \r\n");
return (false);
}
if (ut_fill_entry_action (obj, entry) == false) {
ut_printf ("ut_fill_entry_action () failed. \r\n");
return (false);
}
rc = cps_api_create (params, obj);
if (rc != cps_api_ret_code_OK) {
ut_printf ("cps_api_create () failed. \r\n");
return (false);
}
obj_guard.release ();
return (true);
}
bool ut_fill_entry_modify_req (cps_api_transaction_params_t *params,
ut_entry_t& entry)
{
cps_api_return_code_t rc;
cps_api_object_t obj;
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("cps_api_object_create () failed. \r\n");
return (false);
}
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof (uint64_t));
cps_api_set_key_data (obj, BASE_ACL_ENTRY_ID, cps_api_object_ATTR_T_U64,
&entry.entry_id, sizeof (uint64_t));
if (entry.update_priority == true) {
cps_api_object_attr_add_u32 (obj,
BASE_ACL_ENTRY_PRIORITY, entry.priority);
}
if (entry.update_npu == true) {
for (auto npu: entry.npu_list) {
cps_api_object_attr_add_u32(obj, BASE_ACL_ENTRY_NPU_ID_LIST, npu);
}
}
if (entry.update_filter == true) {
if (ut_fill_entry_match (obj, entry) == false) {
cps_api_object_delete (obj);
ut_printf ("ut_fill_entry_match () failed. \r\n");
return (false);
}
}
if (entry.update_action == true) {
if (ut_fill_entry_action (obj, entry) == false) {
cps_api_object_delete (obj);
ut_printf ("ut_fill_entry_action () failed. \r\n");
return (false);
}
}
rc = cps_api_set (params, obj);
if (rc != cps_api_ret_code_OK) {
cps_api_object_delete (obj);
ut_printf ("cps_api_set () failed. \r\n");
return (false);
}
return (true);
}
bool ut_fill_entry_delete_req (cps_api_transaction_params_t *params,
ut_entry_t& entry)
{
cps_api_return_code_t rc;
cps_api_object_t obj;
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("cps_api_object_create () failed. \r\n");
return (false);
}
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_OBJ, cps_api_qualifier_TARGET);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof (uint64_t));
cps_api_set_key_data (obj, BASE_ACL_ENTRY_ID, cps_api_object_ATTR_T_U64,
&entry.entry_id, sizeof (uint64_t));
rc = cps_api_delete (params, obj);
if (rc != cps_api_ret_code_OK) {
cps_api_object_delete (obj);
ut_printf ("cps_api_delete () failed. \r\n");
return (false);
}
return (true);
}
bool validate_entry_obj (cps_api_object_t obj, ut_entry_t& entry)
{
cps_api_object_it_t it;
cps_api_attr_id_t attr_id;
nas_switch_id_t switch_id;
uint32_t npu;
nas_obj_id_t table_id;
nas_obj_id_t entry_id;
uint_t priority;
bool update_priority;
bool update_filter;
bool update_action;
bool update_npu;
bool priority_validated = false;
bool filter_validated = false;;
bool action_validated = false;
static const int num_allowed_keys = 2;
uint_t count;
nas_acl_ut_extract_entry_keys (obj, &switch_id, &table_id, &entry_id, &count);
if (count != num_allowed_keys) {
ut_printf ("%s(): FAILED. Key Count: %d\r\n", __FUNCTION__, count);
return false;
}
update_priority = entry.update_priority;
update_filter = entry.update_filter;
update_action = entry.update_action;
update_npu = entry.update_npu;
clear_all_update_flags (entry);
ut_printf ("%s(): Switch Id: %d, Table Id: %ld, Entry Id: %ld\r\n",
__FUNCTION__, switch_id, table_id, entry_id);
for (cps_api_object_it_begin (obj, &it);
cps_api_object_it_valid (&it); cps_api_object_it_next (&it)) {
attr_id = cps_api_object_attr_id (it.attr);
switch (attr_id) {
case BASE_ACL_ENTRY_TABLE_ID:
ut_printf ("%s(): Table Id NOT allowed as an attribute \r\n",
__FUNCTION__);
return false;
break;
case BASE_ACL_ENTRY_ID:
ut_printf ("%s(): Entry Id NOT allowed as an attribute \r\n",
__FUNCTION__);
return false;
break;
case BASE_ACL_ENTRY_PRIORITY:
priority = cps_api_object_attr_data_u32 (it.attr);
if ((update_priority == true) && (entry.priority != priority)) {
ut_printf ("%s(): Entry Priority mismatch. "
"Entry Priority: %d, In Priority: %d\r\n",
__FUNCTION__, entry.priority, priority);
return false;
}
priority_validated = true;
break;
case BASE_ACL_ENTRY_MATCH:
if (update_filter == true) {
if (ut_validate_entry_filter_list (obj, it, entry) != true) {
ut_printf ("%s(): Filter validation failed.\r\n",
__FUNCTION__);
return false;
}
}
filter_validated = true;
break;
case BASE_ACL_ENTRY_ACTION:
if (update_action == true) {
if (ut_validate_entry_action_list (obj, it, entry) != true) {
ut_printf ("%s(): Action validation failed.\r\n",
__FUNCTION__);
return false;
}
}
action_validated = true;
break;
case BASE_ACL_ENTRY_NPU_ID_LIST:
if (update_npu == true) {
npu = cps_api_object_attr_data_u32 (it.attr);
const_ut_npu_list_iter_t npu_it = entry.npu_list.find(npu);
if (npu_it == entry.npu_list.end ()) {
return false;
}
entry.npu_list.erase (npu);
}
break;
default:
// Unknown attribute. Ignore silently.
ut_printf ("%s(): DEFAULT Case \r\n", __FUNCTION__);
break;
}
}
if ((update_priority == true) && (priority_validated != true)) {
ut_printf ("%s(): Priority check failed.\r\n", __FUNCTION__);
return false;
}
if ((update_filter == true) && (filter_validated != true)) {
ut_printf ("%s(): Filter check failed.\r\n", __FUNCTION__);
return false;
}
if ((update_action == true) && (action_validated != true)) {
ut_printf ("%s(): Action check failed.\r\n", __FUNCTION__);
return false;
}
if ((update_npu == true) && (entry.npu_list.size () != 0)) {
ut_printf ("%s(): NPU check failed.\r\n", __FUNCTION__);
return false;
}
return true;
}
bool
validate_entry_cps_resp(uint_t op, ut_entry_t& entry, cps_api_object_t prev_obj)
{
nas_switch_id_t switch_id;
nas_obj_id_t table_id;
nas_obj_id_t entry_id;
uint_t count;
ut_printf ("Starting validation\r\n");
fflush (stdout);
nas_acl_ut_extract_entry_keys (prev_obj, &switch_id, &table_id, &entry_id, &count);
if (count != 2) {
ut_printf ("%s(): Invalid key count: %d.\r\n", __FUNCTION__, count);
return false;
}
ut_printf ("%s(): switch_id: %d, table_id: %ld, entry_id: %ld.\r\n",
__FUNCTION__, switch_id, table_id, entry_id);
fflush (stdout);
if (op == NAS_ACL_UT_CREATE) {
entry.entry_id = entry_id;
}
if ((entry.table_id != table_id) &&
(entry.entry_id != entry_id)) {
ut_printf ("%s(): Key mismatch.\r\n", __FUNCTION__);
return false;
}
if (op == NAS_ACL_UT_CREATE) {
return true;
}
if (op != NAS_ACL_UT_CREATE) {
if (validate_entry_obj (prev_obj, entry) != true) {
ut_printf ("%s(): validate_entry_obj failed.\r\n", __FUNCTION__);
return false;
}
}
return true;
}
bool nas_acl_ut_entry_get (uint_t op, ut_entry_t& entry)
{
cps_api_get_params_t params;
cps_api_object_t obj;
cps_api_return_code_t rc;
ut_printf ("%s()\r\n", __FUNCTION__);
if (cps_api_get_request_init (¶ms) != cps_api_ret_code_OK) {
ut_printf ("cps_api_get_request_init () failed. \r\n");
return (false);
}
ut_printf ("%s(): Switch Id: %d, Table Id : %ld, Entry Id: %ld \r\n",
__FUNCTION__, entry.switch_id, entry.table_id, entry.entry_id);
obj = cps_api_object_list_create_obj_and_append (params.filters);
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof (uint64_t));
cps_api_set_key_data (obj, BASE_ACL_ENTRY_ID, cps_api_object_ATTR_T_U64,
&entry.entry_id, sizeof (uint64_t));
rc = nas_acl_ut_cps_api_get (¶ms, 0);
if (op == NAS_ACL_UT_DELETE) {
if (rc != cps_api_ret_code_OK) {
return true;
}
return false;
}
if (rc != cps_api_ret_code_OK) {
ut_printf ("cps_api_get () failed. \r\n");
return (false);
}
obj = cps_api_object_list_get (params.list, 0);
if (obj == NULL) {
ut_printf ("%s(): Get resp object NOT present.\r\n",
__FUNCTION__);
return (false);
}
if (validate_entry_obj (obj, entry) == false) {
return (false);
}
if (cps_api_get_request_close (¶ms) != cps_api_ret_code_OK) {
ut_printf ("cps_api_request_close () failed. \r\n");
return (false);
}
ut_printf ("********** ACL Entry Get TEST PASSED ********** .\r\n\n");
return (true);
}
bool
validate_entry_commit_create (cps_api_transaction_params_t *params)
{
ut_entry_t tmp_entry;
cps_api_object_t obj;
size_t index;
size_t count;
count = cps_api_object_list_size (params->prev);
if (g_validate_entry_list.size () != count) {
return false;
}
for (index = 0; index < count; index++) {
ut_entry_t& entry = g_validate_entry_list.at (index);
obj = cps_api_object_list_get (params->prev, index);
if (obj == NULL) {
return false;
}
tmp_entry = entry;
if (validate_entry_cps_resp (NAS_ACL_UT_CREATE, tmp_entry, obj)
!= true) {
ut_printf ("Failed\r\n"); fflush (stdout);
return false;
}
entry.entry_id = tmp_entry.entry_id;
g_entry_id_list.push_back (entry.entry_id);
set_all_update_flags (entry);
if (nas_acl_ut_entry_get (NAS_ACL_UT_CREATE, entry) != true) {
return false;
}
}
return true;
}
bool
validate_entry_commit_modify (cps_api_transaction_params_t *params)
{
cps_api_object_t obj;
size_t index;
size_t count;
count = cps_api_object_list_size (params->prev);
if ((g_validate_entry_list.size () != count) &&
(g_validate_old_entry_list.size () != count)) {
ut_printf ("%s(): Size mismatch. \r\n", __FUNCTION__);
return false;
}
for (index = 0; index < count; index++) {
ut_entry_t& old_entry = g_validate_old_entry_list.at (index);
ut_entry_t& new_entry = g_validate_entry_list.at (index);
obj = cps_api_object_list_get (params->prev, index);
if (obj == NULL) {
ut_printf ("%s(): cps_api_object_list_get failed.\r\n",
__FUNCTION__);
return false;
}
ut_entry_t tmp_entry = old_entry;
if (validate_entry_cps_resp (NAS_ACL_UT_MODIFY, tmp_entry, obj)
!= true) {
ut_printf ("%s(): validate_entry_cps_resp failed.\r\n",
__FUNCTION__);
return false;
}
set_all_update_flags (new_entry);
tmp_entry = new_entry;
if (nas_acl_ut_entry_get (NAS_ACL_UT_MODIFY, tmp_entry) != true) {
ut_printf ("%s(): nas_acl_ut_entry_get failed.\r\n",
__FUNCTION__);
return false;
}
}
return true;
}
bool
validate_entry_commit_delete (cps_api_transaction_params_t *params)
{
cps_api_object_t obj;
uint32_t index;
uint32_t count;
count = cps_api_object_list_size (params->prev);
if (g_validate_entry_list.size () != count) {
return false;
}
for (index = 0; index < count; index++) {
ut_entry_t& entry = g_validate_entry_list.at (index);
obj = cps_api_object_list_get (params->prev, index);
if (obj == NULL) {
return false;
}
set_all_update_flags (entry);
ut_entry_t tmp_entry = entry;
if (validate_entry_cps_resp (NAS_ACL_UT_DELETE, tmp_entry, obj)
!= true) {
return false;
}
entry.entry_id = tmp_entry.entry_id;
if (nas_acl_ut_entry_get (NAS_ACL_UT_DELETE, entry) != true) {
return false;
}
}
return true;
}
bool entry_commit_create (cps_api_transaction_params_t *params,
ut_entry_t& entry,
uint32_t index,
bool force_commit,
bool rollback)
{
if (index == 0) {
if (cps_api_transaction_init (params) != cps_api_ret_code_OK) {
return cps_api_ret_code_ERR;
}
g_validate_entry_list.clear ();
}
if (ut_fill_entry_create_req (params, entry) == false) {
return false;
}
g_validate_entry_list.push_back (entry);
if (force_commit == true) {
if (nas_acl_ut_cps_api_commit (params,
rollback) != cps_api_ret_code_OK) {
return false;
}
if (validate_entry_commit_create (params) != true) {
return false;
}
if (cps_api_transaction_close (params) != cps_api_ret_code_OK) {
return false;
}
}
return true;
}
bool entry_commit_modify (cps_api_transaction_params_t *params,
ut_entry_t& old_entry,
ut_entry_t& new_entry,
uint32_t index,
bool force_commit,
bool rollback)
{
if (index == 0) {
if (cps_api_transaction_init (params) != cps_api_ret_code_OK) {
ut_printf ("%s(): cps_api_transaction_init failed \r\n",
__FUNCTION__);
return cps_api_ret_code_ERR;
}
g_validate_entry_list.clear ();
g_validate_old_entry_list.clear ();
}
if (ut_fill_entry_modify_req (params, new_entry) != true) {
ut_printf ("%s(): ut_fill_entry_modify_req failed \r\n",
__FUNCTION__);
return false;
}
g_validate_entry_list.push_back (new_entry);
g_validate_old_entry_list.push_back (old_entry);
if (force_commit == true) {
if (nas_acl_ut_cps_api_commit (params,
rollback) != cps_api_ret_code_OK) {
ut_printf ("%s(): nas_acl_ut_cps_api_commit failed \r\n",
__FUNCTION__);
return false;
}
if (validate_entry_commit_modify (params) != true) {
return false;
}
if (cps_api_transaction_close (params) != cps_api_ret_code_OK) {
return false;
}
}
return true;
}
bool entry_commit_delete (cps_api_transaction_params_t *params,
ut_entry_t& entry,
uint32_t index,
bool force_commit,
bool rollback,
bool validate)
{
if (index == 0) {
if (cps_api_transaction_init (params) != cps_api_ret_code_OK) {
return cps_api_ret_code_ERR;
}
g_validate_entry_list.clear ();
}
if (ut_fill_entry_delete_req (params, entry) == false) {
return false;
}
g_validate_entry_list.push_back (entry);
if (force_commit == true) {
if (nas_acl_ut_cps_api_commit (params,
rollback) != cps_api_ret_code_OK) {
return false;
}
if (validate && validate_entry_commit_delete (params) != true) {
return false;
}
if (cps_api_transaction_close (params) != cps_api_ret_code_OK) {
return false;
}
}
return true;
}
static inline void ut_add_filter_int (ut_entry_t& entry, ut_filter_t& filter,
uint64_t val1, bool val1_optional, bool val1_null,
uint64_t val2, bool val2_optional, bool val2_null)
{
filter.val_list.clear ();
if (val1_optional) {
if (val1_null) {
filter.val_list.push_back(0);
} else {
filter.val_list.push_back(1);
}
}
if (!val1_optional || !val1_null) {
filter.val_list.push_back (val1);
}
if (val2_optional) {
if (val1_null) {
filter.val_list.push_back(0);
} else {
filter.val_list.push_back(1);
}
}
if (!val2_optional || !val2_null) {
filter.val_list.push_back (val2);
}
entry.filter_list.insert (filter);
}
static inline void ut_add_filter (ut_entry_t& entry, ut_filter_t& filter,
uint64_t val1, uint64_t val2)
{
auto it = _optional_filter_type.find(filter.type);
ut_add_filter_int(entry, filter, val1, false, false,
val2, it == _optional_filter_type.end() ? false : true, false);
}
static inline void ut_add_action_int (ut_entry_t& entry, ut_action_t& action,
uint64_t val1, bool val1_optional, bool val1_null,
uint64_t val2, bool val2_optional, bool val2_null)
{
action.val_list.clear ();
if (val1_optional) {
if (val1_null) {
action.val_list.push_back(1);
} else {
action.val_list.push_back(0);
}
}
if (!val1_optional || !val1_null) {
action.val_list.push_back (val1);
}
if (val2_optional) {
if (val1_null) {
action.val_list.push_back(1);
} else {
action.val_list.push_back(0);
}
}
if (!val2_optional || !val2_null) {
action.val_list.push_back (val2);
}
entry.action_list.insert (action);
}
static inline void ut_add_action (ut_entry_t& entry, ut_action_t& action,
uint64_t val1, uint64_t val2)
{
ut_add_action_int(entry, action, val1, false, false, val2, false, false);
}
static bool ut_add_filter_ip_mask_val(ut_entry_t& entry, ut_filter_t& filter,
uint32_t ip_val, uint32_t mask_val)
{
ip_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
memcpy(&ip_buf[1], &ip_val, sizeof(dn_ipv4_addr_t));
mask_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
memcpy(&mask_buf[1], &mask_val, sizeof(dn_ipv4_addr_t));
ut_add_filter_int(entry, filter, (uint64_t)ip_buf, false, false,
(uint64_t)mask_buf, true, false);
return true;
}
static bool ut_add_filter_ip_mask(ut_entry_t& entry, ut_filter_t& filter,
const char *ip, const char *mask)
{
std_ip_addr_t ip_addr_holder;
if (std_str_to_ip(ip, &ip_addr_holder) == false) {
return false;
}
uint32_t ip_val = (uint32_t)ip_addr_holder.u.ipv4.s_addr;
if (std_str_to_ip(mask, &ip_addr_holder) == false) {
return false;
}
uint32_t mask_val = (uint32_t)ip_addr_holder.u.ipv4.s_addr;
return ut_add_filter_ip_mask_val(entry, filter, ip_val, mask_val);
}
static bool nas_acl_ut_entry_create (nas_acl_ut_table_t& table)
{
cps_api_transaction_params_t params;
ut_entry_t entry;
ut_filter_t filter;
ut_action_t action;
uint32_t index;
ut_printf ("---------- ACL Entry Creation TEST STARTED ------------\r\n");
for (const auto& map_kv: _entry_map_input) {
index = map_kv.first;
/* entry.entry_id will be filled once the create response is received */
entry.switch_id = table.switch_id;
entry.table_id = table.table_id;
entry.priority = map_kv.second.priority;
clear_all_update_flags (entry);
if (index == _ALL_FIELDS_ENTRY) {
if (nas_acl_ut_is_on_target ()) {
continue;
}
else {
ut_add_all_filter (entry);
ut_add_all_action (entry);
}
}
else {
for (auto& filter_info: map_kv.second.filter_info_list) {
if (filter_info.mod == _ADD_LATER) continue;
filter.type = filter_info.type;
if (filter.type == BASE_ACL_MATCH_TYPE_SRC_IP ||
filter.type == BASE_ACL_MATCH_TYPE_DST_IP) {
ut_add_filter_ip_mask_val(entry, filter,
filter_info.val1, filter_info.val2);
} else {
ut_add_filter(entry, filter, filter_info.val1, filter_info.val2);
}
}
for (auto& action_info: map_kv.second.action_info_list) {
if (action_info.mod == _ADD_LATER) continue;
action.type = action_info.type;
ut_add_action (entry, action,
action_info.val1, action_info.val2);
}
}
for (auto npu: map_kv.second.npu_list) {
entry.npu_list.insert (npu);
}
if (entry_commit_create (¶ms, entry, 0, true, false) == false) {
return false;
}
entry.index = index;
entry.entry_id = g_entry_id_list.at(0);
table.entries.insert (std::make_pair (index, std::move (entry)));
g_entry_id_list.clear ();
}
ut_printf ("********** ACL Entry Creation TEST PASSED ************\r\n\n");
return true;
}
static bool nas_acl_ut_entry_modify (nas_acl_ut_table_t& table)
{
cps_api_transaction_params_t params;
ut_filter_t filter;
ut_action_t action;
uint32_t index;
ut_printf ("---------- ACL Entry Modify TEST STARTED ------------\r\n");
for (const auto& map_kv: _entry_map_input) {
index = map_kv.first;
const ut_entry_info_t& entry_info = map_kv.second;
if (index == _ALL_FIELDS_ENTRY) {
if (nas_acl_ut_is_on_target ()) {
continue;
}
}
auto entry_kv = table.entries.find (index);
if (entry_kv == table.entries.end ()) {
return false;
}
ut_entry_t& old_entry = entry_kv->second;
ut_entry_t new_entry = old_entry;
clear_all_update_flags (old_entry);
clear_all_update_flags (new_entry);
if (entry_info.mod_priority == _MODIFY) {
new_entry.priority = entry_info.new_priority;
new_entry.update_priority = true;
old_entry.update_priority = true;
}
if (index == _ALL_FIELDS_ENTRY) {
if (nas_acl_ut_is_on_target ()) {
continue;
}
else {
ut_modify_all_filter (new_entry);
ut_modify_all_action (new_entry);
}
}
else {
for (auto& filter_info: entry_info.filter_info_list) {
if ((filter_info.mod == _NO_OP) || (filter_info.mod == _MODIFY)) {
filter.type = filter_info.type;
if (filter.type == BASE_ACL_MATCH_TYPE_SRC_IP ||
filter.type == BASE_ACL_MATCH_TYPE_DST_IP) {
ut_add_filter_ip_mask_val(new_entry, filter, filter_info.val1, filter_info.val2);
} else {
ut_add_filter(new_entry, filter, filter_info.val1, filter_info.val2);
}
new_entry.update_filter = true;
old_entry.update_filter = true;
}
}
for (auto& action_info: entry_info.action_info_list) {
if ((action_info.mod == _NO_OP) || (action_info.mod == _MODIFY)) {
action.type = action_info.type;
action.val_list.clear ();
action.val_list.push_back (action_info.val1);
action.val_list.push_back (action_info.val2);
new_entry.action_list.insert (action);
new_entry.update_action = true;
old_entry.update_action = true;
}
}
}
if ((entry_info.mod_npu_list == _MODIFY) ||
(entry_info.mod_npu_list == _DELETE)) {
for (auto npu: map_kv.second.npu_list) {
new_entry.npu_list.insert (npu);
}
new_entry.update_npu = true;
old_entry.update_npu = true;
}
if (entry_commit_modify (¶ms, old_entry,
new_entry, 0, true, false) == false) {
return false;
}
table.entries.at (index) = std::move (new_entry);
}
ut_printf ("********** ACL Entry Modify TEST PASSED ************\r\n\n");
return true;
}
static bool nas_acl_ut_entry_delete (nas_acl_ut_table_t& table, bool validate)
{
cps_api_transaction_params_t params;
ut_filter_t filter;
uint32_t index;
ut_printf ("---------- ACL Entry Delete TEST STARTED ------------\r\n");
for (const auto& map_kv: _entry_map_input) {
index = map_kv.first;
if (index == _ALL_FIELDS_ENTRY) {
if (nas_acl_ut_is_on_target ()) {
continue;
}
}
const auto& entry_kv = table.entries.find (index);
if (entry_kv == table.entries.end ()) {
return false;
}
if (entry_commit_delete (¶ms, entry_kv->second, 0, true, false, validate)
== false) {
return false;
}
table.entries.erase (index);
}
ut_printf ("********** ACL Entry Delete TEST PASSED ************\r\n\n");
return true;
}
bool nas_acl_ut_entry_create_test (nas_acl_ut_table_t& table)
{
if (!nas_acl_ut_entry_create (table)) {
return false;
}
return true;
}
bool nas_acl_ut_entry_modify_test (nas_acl_ut_table_t& table)
{
if (!nas_acl_ut_entry_modify (table)) {
return false;
}
return true;
}
bool nas_acl_ut_entry_delete_test (nas_acl_ut_table_t& table, bool validate)
{
if (!nas_acl_ut_entry_delete (table, validate)) {
return false;
}
return true;
}
bool ut_entry_get_bulk (cps_api_object_t obj)
{
static const int num_allowed_keys = 2;
nas_acl_ut_table_t *p_table;
ut_entry_t *p_entry;
cps_api_get_params_t params;
cps_api_return_code_t rc;
size_t size;
uint_t index;
uint_t resp_key_count;
nas_switch_id_t switch_id;
nas_obj_id_t table_id;
nas_obj_id_t entry_id;
ut_printf ("%s()\r\n", __FUNCTION__);
if (cps_api_get_request_init (¶ms) != cps_api_ret_code_OK) {
ut_printf ("cps_api_get_request_init () failed. \r\n");
return (false);
}
if (!cps_api_object_list_append (params.filters, obj)) {
ut_printf ("%s() Obj append failed.\n", __FUNCTION__);
cps_api_object_delete (obj);
return false;
}
rc = nas_acl_ut_cps_api_get (¶ms, 0);
if (rc != cps_api_ret_code_OK) {
ut_printf ("%s(): cps_api_get () failed. \r\n", __FUNCTION__);
return (false);
}
size = cps_api_object_list_size (params.list);
for (index = 0; index < size; index++) {
obj = cps_api_object_list_get (params.list, index);
if (obj == NULL) {
ut_printf ("%s(): Get resp object NOT present.\r\n",
__FUNCTION__);
return (false);
}
nas_acl_ut_extract_entry_keys (obj, &switch_id, &table_id,
&entry_id, &resp_key_count);
p_table = find_table (table_id);
if (p_table == NULL) {
continue;
}
if (resp_key_count != num_allowed_keys) {
ut_printf ("%s(): Invalid Key Count. Expected: %d, Received: %d\r\n",
__FUNCTION__, num_allowed_keys, resp_key_count);
return false;
}
ut_printf ("%s(): switch_id: %d, table_id: %ld, entry_id: %ld.\r\n",
__FUNCTION__, switch_id, table_id, entry_id);
p_entry = ut_get_entry_by_entry_id (p_table, entry_id);
if (p_entry == NULL) {
ut_printf ("%s(): Entry (%ld) NOT present.\r\n",
__FUNCTION__, entry_id);
return false;
}
if (p_entry->to_be_verified == false) {
ut_printf ("%s(): to_be_verified NOT set\r\n", __FUNCTION__);
return false;
}
if (validate_entry_obj (obj, *p_entry) == false) {
return (false);
}
p_entry->verified = true;
}
if (cps_api_get_request_close (¶ms) != cps_api_ret_code_OK) {
ut_printf ("cps_api_request_close () failed. \r\n");
return (false);
}
return (true);
}
bool nas_acl_ut_entry_get_by_table_test (nas_acl_ut_table_t& table)
{
cps_api_object_t obj;
ut_init_all_verified_flags (table);
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("%s() Obj creation failed. Switch Id: %d, Table Id: %ld\n",
__FUNCTION__, table.switch_id, table.table_id);
return false;
}
cps_api_key_from_attr_with_qual (cps_api_object_key (obj),
BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID,
cps_api_object_ATTR_T_U64,
&table.table_id, sizeof (uint64_t));
if (!ut_entry_get_bulk (obj)) {
ut_printf ("%s() ut_entry_get_bulk(). Switch Id: %d, Table Id: %ld\n",
__FUNCTION__, table.switch_id, table.table_id);
return false;
}
if (!ut_validate_verified_flags ()) {
ut_printf ("%s() ut_validate_verified_flags(). Switch Id: %d, "
"Table Id: %ld\n",
__FUNCTION__, table.switch_id, table.table_id);
return false;
}
ut_clear_all_verified_flags (table);
return true;
}
bool nas_acl_ut_entry_get_by_switch_test (nas_switch_id_t switch_id)
{
cps_api_object_t obj;
uint32_t index;
for (index = 0; index < NAS_ACL_UT_MAX_TABLES; index++) {
if (g_nas_acl_ut_tables [index].switch_id == switch_id) {
ut_init_all_verified_flags (g_nas_acl_ut_tables [index]);
}
}
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("%s() Obj creation failed. Switch Id: %d\n",
__FUNCTION__, switch_id);
return false;
}
cps_api_key_from_attr_with_qual (cps_api_object_key (obj),
BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
if (!ut_entry_get_bulk (obj)) {
ut_printf ("%s() ut_entry_get_bulk () failed. Switch Id: %d\n",
__FUNCTION__, switch_id);
return false;
}
if (!ut_validate_verified_flags ()) {
ut_printf ("%s() ut_validate_verified_flags () failed. Switch Id: %d\n",
__FUNCTION__, switch_id);
return false;
}
for (index = 0; index < NAS_ACL_UT_MAX_TABLES; index++) {
if (g_nas_acl_ut_tables [index].switch_id == switch_id) {
ut_clear_all_verified_flags (g_nas_acl_ut_tables [index]);
}
}
return true;
}
bool nas_acl_ut_entry_get_all_test ()
{
cps_api_object_t obj;
uint32_t index;
for (index = 0; index < NAS_ACL_UT_MAX_TABLES; index++) {
ut_init_all_verified_flags (g_nas_acl_ut_tables [index]);
}
obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("%s() Obj creation failed.\n", __FUNCTION__);
return false;
}
cps_api_key_from_attr_with_qual (cps_api_object_key (obj),
BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
if (!ut_entry_get_bulk (obj)) {
ut_printf ("%s() ut_entry_get_bulk () failed.\n", __FUNCTION__);
return false;
}
if (!ut_validate_verified_flags ()) {
ut_printf ("%s() ut_validate_verified_flags() failed.\n", __FUNCTION__);
return false;
}
for (index = 0; index < NAS_ACL_UT_MAX_TABLES; index++) {
ut_clear_all_verified_flags (g_nas_acl_ut_tables [index]);
}
return true;
}
static void _cps_fill_entry_key (cps_api_object_t obj, const ut_entry_t& entry)
{
cps_api_set_key_data (obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof (uint64_t));
cps_api_set_key_data (obj, BASE_ACL_ENTRY_ID, cps_api_object_ATTR_T_U64,
&entry.entry_id, sizeof (uint64_t));
}
static void _cps_fill_filter_upd_key (cps_api_object_t obj, const ut_entry_t& entry,
const ut_filter_info_t& filter_info)
{
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_MATCH,
cps_api_qualifier_TARGET);
_cps_fill_entry_key (obj, entry);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_MATCH_TYPE, cps_api_object_ATTR_T_U32,
&filter_info.type, sizeof (uint32_t));
}
static void _cps_fill_action_upd_key (cps_api_object_t obj, const ut_entry_t& entry,
const ut_action_info_t& action_info)
{
cps_api_key_from_attr_with_qual (cps_api_object_key (obj), BASE_ACL_ENTRY_ACTION,
cps_api_qualifier_TARGET);
_cps_fill_entry_key (obj, entry);
cps_api_set_key_data (obj, BASE_ACL_ENTRY_ACTION_TYPE, cps_api_object_ATTR_T_U32,
&action_info.type, sizeof (uint32_t));
}
static bool _cps_fill_filter_upd (cps_api_object_t obj, const ut_entry_t& entry,
const ut_filter_info_t& filter)
{
const auto& map_kv = nas_acl_get_filter_map().find (filter.type);
uint64_t val1, val2;
if (map_kv == nas_acl_get_filter_map().end ()) {
ut_printf ("FAILED: Could not Find filter type %d\r\n", filter.type);
return false;
}
const nas_acl_filter_info_t& map_info = map_kv->second;
ut_attr_id_list_t parent_list;
parent_list.push_back (map_info.val.attr_id);
ut_val_list_t val_list;
if (filter.type == BASE_ACL_MATCH_TYPE_SRC_IP ||
filter.type == BASE_ACL_MATCH_TYPE_DST_IP) {
ip_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
memcpy(&ip_buf[1], &filter.new_val1, sizeof(dn_ipv4_addr_t));
mask_buf[0] = (uint8_t)sizeof(dn_ipv4_addr_t);
memcpy(&mask_buf[1], &filter.new_val2, sizeof(dn_ipv4_addr_t));
val1 = (uint64_t)ip_buf;
val2 = (uint64_t)mask_buf;
} else {
val1 = filter.new_val1;
val2 = filter.new_val2;
}
val_list.push_back(val1);
auto it = _optional_filter_type.find(filter.type);
if (it != _optional_filter_type.end()) {
val_list.push_back(1);
}
val_list.push_back(val2);
if (!ut_copy_data_to_obj (parent_list, map_info.child_list,
obj, map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
val_list)) {
ut_printf ("Failed incr modify filter %s", nas_acl_filter_type_name (filter.type));
return false;
}
return true;
}
static bool _cps_fill_action_upd (cps_api_object_t obj, const ut_entry_t& entry,
const ut_action_info_t& action)
{
const auto& map_kv = nas_acl_get_action_map().find (action.type);
if (map_kv == nas_acl_get_action_map().end ()) {
ut_printf ("FAILED: Could not Find filter type %d\r\n", action.type);
return false;
}
const nas_acl_action_info_t& map_info = map_kv->second;
ut_attr_id_list_t parent_list;
parent_list.push_back (map_info.val.attr_id);
ut_val_list_t val_list {action.new_val1, action.new_val2};
if (!ut_copy_data_to_obj (parent_list, map_info.child_list,
obj, map_info.val.data_type,
map_info.val.data_len,
map_info.val.mode == NAS_ACL_ATTR_MODE_OPTIONAL,
val_list)) {
ut_printf ("Failed incr modify action %s", nas_acl_action_type_name (action.type));
return false;
}
return true;
}
bool nas_acl_ut_entry_incr_modify_test (nas_acl_ut_table_t& table)
{
uint32_t index;
ut_printf ("---------- ACL Entry Incremental Modify TEST STARTED ------------\r\n");
for (const auto& map_kv: _entry_map_input) {
index = map_kv.first;
const ut_entry_info_t& entry_info = map_kv.second;
if (index == _ALL_FIELDS_ENTRY) continue;
auto entry_kv = table.entries.find (index);
if (entry_kv == table.entries.end ()) {
return false;
}
ut_entry_t& entry = entry_kv->second;
cps_api_transaction_params_t params;
if (cps_api_transaction_init (¶ms) != cps_api_ret_code_OK) {
return cps_api_ret_code_ERR;
}
for (auto& filter_info: entry_info.filter_info_list) {
if (filter_info.mod == _NO_OP) continue;
cps_api_object_t obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("cps_api_object_create () failed. \r\n");
return (false);
}
cps_api_object_guard g(obj);
_cps_fill_filter_upd_key (obj, entry, filter_info);
if (filter_info.mod == _ADD_LATER) {
_cps_fill_filter_upd (obj, entry, filter_info);
cps_api_create (¶ms, obj);
}
if (filter_info.mod == _MODIFY) {
_cps_fill_filter_upd (obj, entry, filter_info);
cps_api_set (¶ms, obj);
}
if (filter_info.mod == _DELETE) {
cps_api_delete (¶ms, obj);
}
g.release();
}
for (auto& action_info: entry_info.action_info_list) {
if (action_info.mod == _NO_OP) continue;
cps_api_object_t obj = cps_api_object_create ();
if (obj == NULL) {
ut_printf ("cps_api_object_create () failed. \r\n");
return (false);
}
cps_api_object_guard g(obj);
_cps_fill_action_upd_key (obj, entry, action_info);
if (action_info.mod == _ADD_LATER) {
_cps_fill_action_upd (obj, entry, action_info);
cps_api_create (¶ms, obj);
} else if (action_info.mod == _MODIFY) {
_cps_fill_action_upd (obj, entry, action_info);
cps_api_set (¶ms, obj);
} else if (action_info.mod == _DELETE) {
cps_api_delete (¶ms, obj);
}
g.release();
}
auto rc = nas_acl_ut_cps_api_commit (¶ms, false);
if (rc != cps_api_ret_code_OK) {
ut_printf ("%s(): nas_acl_ut_cps_api_commit failed 0x%x\r\n",
__FUNCTION__, rc);
return false;
}
if (cps_api_transaction_close (¶ms) != cps_api_ret_code_OK) {
return false;
}
}
ut_printf ("********** ACL Entry Incremental Modify TEST PASSED ************\r\n\n");
return true;
}
bool nas_acl_ut_lag_create(const char *lag_name, int sub_if_num, ...)
{
va_list ap;
cps_api_object_t obj = cps_api_object_create();
ut_printf("--- Create LAG interface %s ---\n", lag_name);
cps_api_key_from_attr_with_qual(cps_api_object_key(obj),
DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_OBJ, cps_api_qualifier_TARGET);
cps_api_object_attr_add(obj,IF_INTERFACES_INTERFACE_TYPE,
(const char *)IF_INTERFACE_TYPE_IANAIFT_IANA_INTERFACE_TYPE_IANAIFT_IEEE8023ADLAG,
strlen(IF_INTERFACE_TYPE_IANAIFT_IANA_INTERFACE_TYPE_IANAIFT_IEEE8023ADLAG) + 1);
cps_api_object_attr_add(obj,IF_INTERFACES_INTERFACE_NAME,lag_name, strlen(lag_name) + 1);
cps_api_object_attr_add_u32(obj, IF_INTERFACES_INTERFACE_ENABLED, 1);
va_start(ap, sub_if_num);
const char *sub_ifname;
cps_api_attr_id_t ids[3] = {DELL_IF_IF_INTERFACES_INTERFACE_MEMBER_PORTS,0,
DELL_IF_IF_INTERFACES_INTERFACE_MEMBER_PORTS_NAME };
const int ids_len = sizeof(ids)/sizeof(ids[0]);
while(sub_if_num > 0) {
sub_ifname = va_arg(ap, const char *);
if (!sub_ifname) {
break;
}
cps_api_object_e_add(obj, ids, ids_len, cps_api_object_ATTR_T_BIN,
sub_ifname, strlen(sub_ifname) + 1);
ids[1] ++;
sub_if_num --;
}
va_end(ap);
cps_api_transaction_params_t tr;
bool rc = false;
do {
if (cps_api_transaction_init(&tr) != cps_api_ret_code_OK) {
break;
}
cps_api_create(&tr, obj);
if (cps_api_commit(&tr) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
ut_printf("*** Create LAG interface done ***\n");
} else {
ut_printf("*** Failed to create LAG ***\n");
}
cps_api_transaction_close(&tr);
return rc;
}
bool nas_acl_ut_lag_delete(const char *lag_name)
{
cps_api_object_t obj = cps_api_object_create();
ut_printf("--- Delete LAG interface name %s ---\n", lag_name);
cps_api_key_from_attr_with_qual(cps_api_object_key(obj),
DELL_BASE_IF_CMN_IF_INTERFACES_INTERFACE_OBJ,
cps_api_qualifier_TARGET);
cps_api_object_attr_add(obj, IF_INTERFACES_INTERFACE_NAME,
lag_name, strlen(lag_name) + 1);
cps_api_transaction_params_t tr;
bool rc = false;
do {
if (cps_api_transaction_init(&tr) != cps_api_ret_code_OK) {
break;
}
cps_api_delete(&tr, obj);
if (cps_api_commit(&tr) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
ut_printf("*** Delete LAG interface done ***\n");
} else {
ut_printf("*** Failed to delete LAG ***\n");
}
cps_api_transaction_close(&tr);
return rc;
}
bool nas_acl_ut_src_port_entry_create(nas_acl_ut_table_t& table,
int priority, const char *intf_name)
{
ut_entry_t entry;
ut_filter_t filter;
ut_action_t action;
cps_api_transaction_params_t params;
const char *src_ip = "1.2.3.4";
const char *ip_mask = "255.255.255.0";
ut_printf("--- Create entry to test port filtering ---\n");
entry.switch_id = table.switch_id;
entry.table_id = table.table_id;
entry.priority = priority;
filter.type = BASE_ACL_MATCH_TYPE_SRC_IP;
if (!ut_add_filter_ip_mask(entry, filter, src_ip, ip_mask)) {
return false;
}
filter.type = BASE_ACL_MATCH_TYPE_IP_PROTOCOL;
ut_add_filter(entry, filter, 17, 0xff);
filter.type = BASE_ACL_MATCH_TYPE_SRC_PORT;
uint32_t if_index = if_nametoindex(intf_name);
if (if_index == 0) {
return false;
}
ut_add_filter(entry, filter, if_index, 0);
action.type = BASE_ACL_ACTION_TYPE_PACKET_ACTION;
ut_add_action(entry, action, BASE_ACL_PACKET_ACTION_TYPE_DROP, 0);
if (cps_api_transaction_init(¶ms) != cps_api_ret_code_OK) {
return false;
}
bool rc = false;
do {
if (ut_fill_entry_create_req(¶ms, entry) == false) {
break;
}
if (nas_acl_ut_cps_api_commit(¶ms, false) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
size_t count = cps_api_object_list_size(params.prev);
if (count > 0) {
cps_api_object_t obj = cps_api_object_list_get(params.prev, 0);
cps_api_object_attr_t attr = cps_api_get_key_data(obj, BASE_ACL_ENTRY_ID);
entry.entry_id = cps_api_object_attr_data_u64(attr);
entry.index = table.entries.size();
table.entries.insert(std::make_pair(entry.index, std::move(entry)));
}
}
if (cps_api_transaction_close(¶ms) != cps_api_ret_code_OK) {
return false;
}
ut_printf("*** Entry create done ***\n");
return rc;
}
bool nas_acl_ut_nbr_dst_hit_entry_create(nas_acl_ut_table_t& table,
int priority)
{
ut_entry_t entry;
ut_filter_t filter;
ut_action_t action;
cps_api_transaction_params_t params;
const char *dst_ip = "192.168.100.1";
const char *ip_mask = "255.255.255.0";
ut_printf("--- Create entry to test neighbor destination hit filtering ---\n");
entry.switch_id = table.switch_id;
entry.table_id = table.table_id;
entry.priority = priority;
filter.type = BASE_ACL_MATCH_TYPE_DST_IP;
if (!ut_add_filter_ip_mask(entry, filter, dst_ip, ip_mask)) {
return false;
}
filter.type = BASE_ACL_MATCH_TYPE_NEIGHBOR_DST_HIT;
ut_add_filter(entry, filter, 0, 0);
action.type = BASE_ACL_ACTION_TYPE_PACKET_ACTION;
ut_add_action(entry, action, BASE_ACL_PACKET_ACTION_TYPE_DROP, 0);
if (cps_api_transaction_init(¶ms) != cps_api_ret_code_OK) {
return false;
}
bool rc = false;
do {
if (ut_fill_entry_create_req(¶ms, entry) == false) {
break;
}
if (nas_acl_ut_cps_api_commit(¶ms, false) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
size_t count = cps_api_object_list_size(params.prev);
if (count > 0) {
cps_api_object_t obj = cps_api_object_list_get(params.prev, 0);
cps_api_object_attr_t attr = cps_api_get_key_data(obj, BASE_ACL_ENTRY_ID);
entry.entry_id = cps_api_object_attr_data_u64(attr);
entry.index = table.entries.size();
table.entries.insert(std::make_pair(entry.index, std::move(entry)));
}
}
if (cps_api_transaction_close(¶ms) != cps_api_ret_code_OK) {
return false;
}
ut_printf("*** Entry create done ***\n");
return rc;
}
bool nas_acl_ut_route_dst_hit_entry_create(nas_acl_ut_table_t& table,
int priority)
{
ut_entry_t entry;
ut_filter_t filter;
ut_action_t action;
cps_api_transaction_params_t params;
const char *dst_ip = "192.168.100.2";
const char *ip_mask = "255.255.255.0";
ut_printf("--- Create entry to test routing destination hit filtering ---\n");
entry.switch_id = table.switch_id;
entry.table_id = table.table_id;
entry.priority = priority;
filter.type = BASE_ACL_MATCH_TYPE_DST_IP;
if (!ut_add_filter_ip_mask(entry, filter, dst_ip, ip_mask)) {
return false;
}
filter.type = BASE_ACL_MATCH_TYPE_ROUTE_DST_HIT;
ut_add_filter(entry, filter, 0, 0);
action.type = BASE_ACL_ACTION_TYPE_PACKET_ACTION;
ut_add_action(entry, action, BASE_ACL_PACKET_ACTION_TYPE_DROP, 0);
if (cps_api_transaction_init(¶ms) != cps_api_ret_code_OK) {
return false;
}
bool rc = false;
do {
if (ut_fill_entry_create_req(¶ms, entry) == false) {
break;
}
if (nas_acl_ut_cps_api_commit(¶ms, false) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
size_t count = cps_api_object_list_size(params.prev);
if (count > 0) {
cps_api_object_t obj = cps_api_object_list_get(params.prev, 0);
cps_api_object_attr_t attr = cps_api_get_key_data(obj, BASE_ACL_ENTRY_ID);
entry.entry_id = cps_api_object_attr_data_u64(attr);
entry.index = table.entries.size();
table.entries.insert(std::make_pair(entry.index, std::move(entry)));
}
}
if (cps_api_transaction_close(¶ms) != cps_api_ret_code_OK) {
return false;
}
ut_printf("*** Entry create done ***\n");
return rc;
}
static bool nht_add_del(void *nht_dest, uint32_t af_family, bool is_add)
{
uint32_t ip;
cps_api_transaction_params_t tr;
cps_api_object_t obj = cps_api_object_create();
cps_api_key_from_attr_with_qual(cps_api_object_key(obj),
BASE_ROUTE_NH_TRACK_OBJ,cps_api_qualifier_TARGET);
cps_api_object_attr_add_u32(obj,BASE_ROUTE_NH_TRACK_VRF_ID,0);
cps_api_object_attr_add_u32(obj,BASE_ROUTE_NH_TRACK_AF,af_family);
if (af_family == AF_INET6) {
cps_api_object_attr_add(obj,BASE_ROUTE_NH_TRACK_DEST_ADDR,(struct in6_addr *) nht_dest,
sizeof(struct in6_addr));
} else {
cps_api_object_attr_add_u32(obj,BASE_ROUTE_NH_TRACK_AF,AF_INET);
ip=((struct in_addr *) nht_dest)->s_addr;
cps_api_object_attr_add(obj,BASE_ROUTE_NH_TRACK_DEST_ADDR,&ip,sizeof(ip));
}
if (cps_api_transaction_init(&tr)!=cps_api_ret_code_OK) {
return false;
}
if (is_add) {
cps_api_create(&tr,obj);
} else {
cps_api_delete(&tr,obj);
}
if (cps_api_commit(&tr)!=cps_api_ret_code_OK) {
return false;
}
cps_api_transaction_close(&tr);
return true;
}
static bool nht_config(const char *ip_str, uint32_t af_family, bool is_add)
{
struct in_addr a;
struct in6_addr a6;
if (af_family == AF_INET6) {
inet_pton(AF_INET6, ip_str, &a6);
return nht_add_del ((void *) &a6, af_family, is_add);
} else {
inet_aton(ip_str,&a);
return nht_add_del ((void *) &a, af_family, is_add);
}
}
static bool nht_get_specific(const char *ip_str, uint32_t af_family,
nas::ndi_obj_id_table_t& nh_id_table)
{
struct in_addr a;
uint32_t ip;
cps_api_get_params_t gp;
if (cps_api_get_request_init(&gp) != cps_api_ret_code_OK)
return false;
inet_aton(ip_str, &a);
cps_api_object_t obj = cps_api_object_list_create_obj_and_append(gp.filters);
cps_api_key_from_attr_with_qual(cps_api_object_key(obj),BASE_ROUTE_NH_TRACK_OBJ,
cps_api_qualifier_TARGET);
cps_api_object_attr_add_u32(obj,BASE_ROUTE_NH_TRACK_AF,AF_INET);
ip=a.s_addr;
cps_api_object_attr_add(obj,BASE_ROUTE_NH_TRACK_DEST_ADDR,&ip,sizeof(ip));
if (cps_api_get(&gp)!=cps_api_ret_code_OK) {
ut_printf("%s: failed to get nh-track\n", __FUNCTION__);
return false;
}
if(cps_api_object_list_size(gp.list) == 0) {
ut_printf("%s: no nh-track object found\n", __FUNCTION__);
return false;
}
obj = cps_api_object_list_get(gp.list, 0);
if (obj == NULL) {
return false;
}
cps_api_object_attr_t attr;
attr = cps_api_object_attr_get(obj, BASE_ROUTE_NH_TRACK_NH_COUNT);
if (attr == NULL) {
ut_printf("%s: no nh_count attribute found\n", __FUNCTION__);
return false;
}
uint32_t nh_cnt = cps_api_object_attr_data_u32(attr);
if (nh_cnt == 0) {
ut_printf("%s: nh_count is 0\n", __FUNCTION__);
return false;
}
cps_api_attr_id_t attr_id_list[] = {BASE_ROUTE_NH_TRACK_DATA};
if (!nas::ndi_obj_id_table_cps_unserialize(nh_id_table, obj, attr_id_list,
sizeof(attr_id_list) / sizeof(attr_id_list[0]))) {
ut_printf("%s: Failed to parse opaque data\n", __FUNCTION__);
return false;
}
if (cps_api_get_request_close(&gp) != cps_api_ret_code_OK)
return false;
return true;
}
static inline void ut_add_nh_action(ut_entry_t& entry, ut_action_t& action,
uint32_t vrf_id, uint32_t af,
const char *dest_ip,
next_hop_id_t nh_id)
{
static uint8_t nh_dest_buf[64];
std_ip_addr_t ip_addr_holder;
if (std_str_to_ip(dest_ip, &ip_addr_holder) == false) {
return;
}
uint32_t ip_val = (uint32_t)ip_addr_holder.u.ipv4.s_addr;
uint8_t addr_len = sizeof(dn_ipv4_addr_t);
nh_dest_buf[0] = addr_len;
memcpy(&nh_dest_buf[1], &ip_val, addr_len);
action.val_list.clear();
action.val_list.push_back(vrf_id);
action.val_list.push_back(af);
action.val_list.push_back(1);
action.val_list.push_back((uint64_t)nh_dest_buf);
action.val_list.push_back(0);
action.val_list.push_back((uint64_t)nh_id);
entry.action_list.insert(action);
}
const char *nh_dest_ip = "30.0.0.5";
const char *nh_mac_addr = "01:02:03:04:05:06";
const char *local_if_name = "e101-028-0";
const char *local_ip_addr = "30.0.0.1";
const char *route_dest_net = "40.0.0.0";
const char *route_dest_mask = "255.255.255.0";
bool nas_acl_ut_nh_redir_entry_create(nas_acl_ut_table_t& table,
int priority)
{
ut_entry_t entry;
ut_filter_t filter;
ut_action_t action;
cps_api_transaction_params_t params;
const char *dst_ip = "192.168.100.1";
const char *ip_mask = "255.255.255.0";
char cmdbuf[512];
ut_printf("--- Create entry to test nexthop redirect action ---\n");
entry.switch_id = table.switch_id;
entry.table_id = table.table_id;
entry.priority = priority;
filter.type = BASE_ACL_MATCH_TYPE_DST_IP;
if (!ut_add_filter_ip_mask(entry, filter, dst_ip, ip_mask)) {
return false;
}
snprintf(cmdbuf, sizeof(cmdbuf), "ifconfig %s %s/24 up", local_if_name, local_ip_addr);
SYSTEM(cmdbuf);
snprintf(cmdbuf, sizeof(cmdbuf), "arp -s %s %s", nh_dest_ip, nh_mac_addr);
SYSTEM(cmdbuf);
snprintf(cmdbuf, sizeof(cmdbuf), "route add -net %s netmask %s gw %s", route_dest_net,
route_dest_mask, nh_dest_ip);
SYSTEM(cmdbuf);
if (!nht_config(nh_dest_ip, AF_INET, true)) {
return false;
}
nas::ndi_obj_id_table_t nh_id_table;
int wait_cnt = 0;
while (!nht_get_specific(nh_dest_ip, AF_INET, nh_id_table)) {
wait_cnt ++;
if (wait_cnt > 20) {
ut_printf("Failed to create nexthop tracking object\n");
return false;
}
sleep(1);
}
next_hop_id_t npu_nh_id = 0;
for (auto& id_map: nh_id_table) {
npu_nh_id = id_map.second;
break;
}
action.type = BASE_ACL_ACTION_TYPE_REDIRECT_IP_NEXTHOP;
ut_add_nh_action(entry, action, 0, AF_INET, nh_dest_ip, npu_nh_id);
if (cps_api_transaction_init(¶ms) != cps_api_ret_code_OK) {
return false;
}
bool rc = false;
do {
if (ut_fill_entry_create_req(¶ms, entry) == false) {
break;
}
if (nas_acl_ut_cps_api_commit(¶ms, false) != cps_api_ret_code_OK) {
break;
}
rc = true;
} while(0);
if (rc) {
size_t count = cps_api_object_list_size(params.prev);
if (count > 0) {
cps_api_object_t obj = cps_api_object_list_get(params.prev, 0);
cps_api_object_attr_t attr = cps_api_get_key_data(obj, BASE_ACL_ENTRY_ID);
entry.entry_id = cps_api_object_attr_data_u64(attr);
entry.index = table.entries.size();
table.entries.insert(std::make_pair(entry.index, std::move(entry)));
}
}
if (cps_api_transaction_close(¶ms) != cps_api_ret_code_OK) {
return false;
}
ut_printf("*** Entry create done ***\n");
return rc;
}
bool nas_acl_ut_table_entry_delete(nas_acl_ut_table_t& table)
{
cps_api_object_t obj;
cps_api_transaction_params_t params;
ut_printf("--- Delete all entries from table %s ---\n", table.name);
for (auto& item: table.entries) {
if (cps_api_transaction_init(¶ms) != cps_api_ret_code_OK) {
return false;
}
ut_entry_t& entry = item.second;
obj = cps_api_object_create();
cps_api_key_from_attr_with_qual(cps_api_object_key(obj), BASE_ACL_ENTRY_OBJ,
cps_api_qualifier_TARGET);
cps_api_set_key_data(obj, BASE_ACL_ENTRY_TABLE_ID, cps_api_object_ATTR_T_U64,
&entry.table_id, sizeof(uint64_t));
cps_api_set_key_data(obj, BASE_ACL_ENTRY_ID, cps_api_object_ATTR_T_U64,
&entry.entry_id, sizeof(uint64_t));
cps_api_delete(¶ms, obj);
if (cps_api_commit(¶ms) != cps_api_ret_code_OK) {
ut_printf("Failed to delete entry %d\n", item.first);
cps_api_transaction_close(¶ms);
return false;
}
cps_api_transaction_close(¶ms);
}
table.entries.clear();
ut_printf("*** Table entries delete done ***\n");
return true;
}
bool nas_acl_ut_nh_redir_entry_delete(nas_acl_ut_table_t& table)
{
char cmdbuf[512];
if (!nas_acl_ut_table_entry_delete(table)) {
return true;
}
snprintf(cmdbuf, sizeof(cmdbuf), "route del -net %s netmask %s gw %s", route_dest_net,
route_dest_mask, nh_dest_ip);
SYSTEM(cmdbuf);
snprintf(cmdbuf, sizeof(cmdbuf), "arp -d %s", nh_dest_ip);
SYSTEM(cmdbuf);
snprintf(cmdbuf, sizeof(cmdbuf), "ifconfig %s 0.0.0.0", local_if_name);
SYSTEM(cmdbuf);
snprintf(cmdbuf, sizeof(cmdbuf), "ifconfig %s down", local_if_name);
SYSTEM(cmdbuf);
return true;
}
| [
"J.T.Conklin@Dell.Com"
] | J.T.Conklin@Dell.Com |
4bcb412424855893d5c030820d084f1a6b95ff69 | 57567c1c860343c4216af46491167949a6a318a5 | /ComputerGraphics/LineScanConversion/Line.cpp | 2709a2e1cbccbf99c2f26496393681b9267ddda2 | [] | no_license | therdes/ComputerGraphics | ce64caa63fe017a36095ace0fa78307c03978a1d | 0833f0ca7d0fdca02f88ac6b27537f6bec2a0408 | refs/heads/master | 2021-01-10T02:35:03.187539 | 2016-03-14T14:46:07 | 2016-03-14T14:46:07 | 53,864,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | cpp | #include "Line.h"
using std::vector;
vector<Coordinate> Line::scanConversion()
{
vector<Coordinate> ret;
/* Step By One */
/*double x = _start.x();
double y = _start.y();
double dx = _end.x() - _start.x();
double dy = _end.y() - _start.y();
double k = (doubleEqual(dx, 0, 0.000001)) ? dy : dy / dx;
double e = -0.5;
for (int i = 0; i <= dx; i++)
{
ret.push_back(Coordinate(x, y, 0));
x += 1;
e += k;
if (e >= 0)
{
y += 1;
e -= 1;
}
}*/
double dx = _end.x() - _start.x();
double dy = _end.y() - _start.y();
double k = (doubleEqual(dx, 0, diffDouble)) ? dy : dy / dx;
double max = (abs(k) < 1) ? abs(dx) : abs(dy);
double e = (k > 0) ? -(stepBy / 2) : (stepBy / 2);
double x = _start.x();
double y = _start.y();
double xInc = stepBy;
double yInc = (k > 0) ? stepBy : -stepBy;
double eInc = (k > 0) ? stepBy : -stepBy;
for (double i = 0; i <= max; i += stepBy)
{
ret.push_back(Coordinate(x, y, 0));
if (abs(k) < 1)
{
x += xInc;
e += k * stepBy;
}
else
{
y += yInc;
e += (1 / k) * stepBy;
}
bool cond = (k > 0) ? (e >= 0) : (e <= 0);
if (cond)
{
if (abs(k) < 1)
y += yInc;
else
x += xInc;
e -= eInc;
}
}
return ret;
} | [
"therdesok@gmail.com"
] | therdesok@gmail.com |
58d28e2103b2b98452046cd51aa1ca5589cc1f15 | f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e | /sc-virt/src/projects/compiler-rt/lib/esan/cache_frag.h | 646d3f85ed97a53a7f5922a9f7e2914e20845367 | [
"NCSA",
"MIT"
] | permissive | archercreat/dta-vs-osc | 2f495f74e0a67d3672c1fc11ecb812d3bc116210 | b39f4d4eb6ffea501025fc3e07622251c2118fe0 | refs/heads/main | 2023-08-01T01:54:05.925289 | 2021-09-05T21:00:35 | 2021-09-05T21:00:35 | 438,047,267 | 1 | 1 | MIT | 2021-12-13T22:45:20 | 2021-12-13T22:45:19 | null | UTF-8 | C++ | false | false | 852 | h | //===-- cache_frag.h --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of EfficiencySanitizer, a family of performance tuners.
//
// Header for cache-fragmentation-specific code.
//===----------------------------------------------------------------------===//
#ifndef CACHE_FRAG_H
#define CACHE_FRAG_H
namespace __esan {
void processCacheFragCompilationUnitInit(void *Ptr);
void processCacheFragCompilationUnitExit(void *Ptr);
void initializeCacheFrag();
int finalizeCacheFrag();
void reportCacheFrag();
} // namespace __esan
#endif // CACHE_FRAG_H
| [
"sebi@quantstamp.com"
] | sebi@quantstamp.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.