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 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
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 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5d4902d6732354059b20d27f79b7e76e9ce86a23 | b983ae3c456019ae1e94c532619778ac660bef75 | /Programación1/Global2019/Recuperatorio/inicializarDatos.cpp | 9983988bbde4fe7ae12713dd109484cd87e3b21b | [] | no_license | Kirurai/TecnicaturaUTN | e6cdabfbce81b8dc5702fb1b640a8459a9201785 | 7dc96e401a21726f73998bd302126943f3abe173 | refs/heads/master | 2021-03-13T14:48:41.038375 | 2020-05-14T05:38:04 | 2020-05-14T05:38:04 | 246,689,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,854 | cpp | #include "inicializarDatos.h"
void cargarMatriz(vector<vector <double>> &matriz){
int dimension;
double elemento;
double desperdicio;
vector <double> fila;
dimension = dimensionMatriz();
//Abriendo Archivo.
ifstream inFile;
inFile.open("datos.txt"); //lectura de archivo
if (!inFile) {
cout << "No se puede abrir el archivo";
exit(1); // terminar con error
}
//Eliminando el primer elemto. Que ya se uso.
for (int i = 0; i < 1; i++){
inFile >> desperdicio;
}
for (int i = 0; i < dimension; i++){
for (int j = 0; j < dimension; j++){
inFile >> elemento;
if (elementoValido(elemento)){
cout << "Cargando el elemento " << i << ", " << j << " de la matriz cuadrada: " << elemento <<endl;
fila.push_back(elemento);
}else{
cout << "El numero " << elemento << " es invalido. se va a ignorar" << endl;
j--;
}
}
matriz.push_back(fila);
fila.clear();
}
}
//-------------------------------------------------------
int dimensionMatriz(){
int dimension;
//Abriendo Archivo.
ifstream inFile;
inFile.open("datos.txt"); //lectura de archivo
if (!inFile) {
cout << "No se puede abrir el archivo";
exit(1); // terminar con error
}
inFile >> dimension;
cout << "El tamaño de la matriz cuadrada: "<< dimension << endl;
if (!dimensionValida(dimension)){
cout << "Error. Dimension Invalida. Edite el archivo datos.txt y vuelva a intentarlo." << endl;
cout << endl << endl;
exit(1); //Finaliza con error
}
return dimension;
}
bool dimensionValida(int dimension){
if (dimension%2 == 0){ //Condicion que la matriz sea impar
return false;
}
if (dimension > 33){ //La matriz no uede tener más de 33 elementos.
return false;
}
if (dimension < 1){ //La matriz debe tener al menos un elemento.
return false;
}
return true;
}
bool elementoValido(double elemento){
if (abs(elemento) > 107){
return false;
}
return true;
}
void bienvenida(){
cout << "Bienvenido al ejercicio de Desviación Estandar de una matriz dado un patrón" << endl;
cout << "El patrón actual es un triangulo isoceles con 2 vertices en los extremos de la columna central y el tercero en el extremo izquierdo de la fila central. " << endl;
cout << "Se leerá un archivo de texto denominado 'datos.txt' que tendrá el siguiente formato: " << endl;
cout << "-Un primer valor T que será la dimensión cuadrada de la matriz a calcular. Deberá ser impar y estar entre 1 y 33." << endl;
cout << " De no cumplir la condición. El ejercicio finalizará en ese momento." << endl;
cout << "-Una cantidad de T cuadrado valores que serán los valores de la matriz. Si alguno es mayor a 107 se omitrá" << endl;
cout << endl << endl;
}
| [
"kd.maurii@gmail.com"
] | kd.maurii@gmail.com |
72d2e3c55afffbc3c6b3a41828865910d38d1267 | 9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d | /tc/testprograms/RecurrenceRelation.cpp | ac56395e33e350909621ee7022b6da62b4ac9fe5 | [] | no_license | rodolfo15625/algorithms | 7034f856487c69553205198700211d7afb885d4c | 9e198ff0c117512373ca2d9d706015009dac1d65 | refs/heads/master | 2021-01-18T08:30:19.777193 | 2014-10-20T13:15:09 | 2014-10-20T13:15:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,869 | cpp | #include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define sz size()
#define REP(i,a,b) for(int i=int(a);i<int(b);i++)
#define fill(x,i) memset(x,i,sizeof(x))
#define foreach(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
int A[100009];
int MAX =1000000;
class RecurrenceRelation {
public:int moduloTen(vector <int> cs, vector <int> initial, int N) {
REP(i,0,initial.sz){
A[i]=(initial[i]+MAX)%10;
}
int k=cs.sz;
REP(i,initial.sz,N+1){
A[i]=0;
int sum=0;
REP(j,0,initial.sz){
sum+=((cs[k-j-1]*A[i-j-1])+MAX)%10;
}
A[i]=sum%10;
}
return A[N];
}
//Powered by [Ziklon]
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.8 (beta) modified by pivanof
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <int> p0, vector <int> p1, int p2, bool hasAnswer, int p3) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p0[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p1[i];
}
cout << "}" << "," << p2;
cout << "]" << endl;
RecurrenceRelation *obj;
int answer;
obj = new RecurrenceRelation();
clock_t startTime = clock();
answer = obj->moduloTen(p0, p1, p2);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p3 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p3;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <int> p0;
vector <int> p1;
int p2;
int p3;
{
// ----- test 0 -----
int t0[] = {2,1};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {9,7};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 6;
p3 = 5;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 1 -----
int t0[] = {1,1};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {0,1};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 9;
p3 = 4;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 2 -----
int t0[] = {2};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {1};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 20;
p3 = 6;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 3 -----
int t0[] = {2};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {1};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 64;
p3 = 6;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 4 -----
int t0[] = {25,143};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {0,0};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 100000;
p3 = 0;
all_right = KawigiEdit_RunTest(4, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 5 -----
int t0[] = {9,8,7,6,5,4,3,2,1,0};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {1,2,3,4,5,6,7,8,9,10};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 654;
p3 = 5;
all_right = KawigiEdit_RunTest(5, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 6 -----
int t0[] = {901,492,100};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
int t1[] = {-6,-15,-39};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
p2 = 0;
p3 = 4;
all_right = KawigiEdit_RunTest(6, p0, p1, p2, true, p3) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
| [
"winftc@gmail.com"
] | winftc@gmail.com |
f4c750512e24ea7dd5701601c262d3248186cebc | 8adcca55ce05f323282d9380d234b1e06a5489f7 | /section5/5.10.cpp | 0d9219964838a69e8a1e5e526fcfd0080dcc7274 | [] | no_license | Codywei/WeiCpp | e8078dbd1a9d4b6acba2b9d12e10924948426233 | 6bb995848714557396402568d43cdb8a4fa468b2 | refs/heads/master | 2020-05-22T13:32:15.118288 | 2020-03-14T06:51:57 | 2020-03-14T06:51:57 | 186,361,639 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 972 | cpp | /**
switch语句
*/
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <cctype>
#include <cstring>
#include <cstddef>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::begin;
using std::end;
int main()
{
// 为每个元音字母初始化其计数值
unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
char ch;
while (cin >> ch) {
// 如果ch使元音字母,将其对应得计数值加1
ch = tolower(ch);
switch (ch) {
case 'a':
++aCnt;
break;
case 'e':
++eCnt;
break;
case 'i':
++iCnt;
break;
case 'o':
++oCnt;
break;
case 'u':
++uCnt;
break;
}
}
// 输出结果
cout << "Number of vowel a: \t" << aCnt << '\n'
<< "Number of vowel e: \t" << eCnt << '\n'
<< "Number of vowel i: \t" << iCnt << '\n'
<< "Number of vowel o: \t" << oCnt << '\n'
<< "Number of vowel u: \t" << uCnt << endl;
system("pause");
return 0;
} | [
"493559615@qq.com"
] | 493559615@qq.com |
f395439f89a4f3145d73738743dd51903b282c1f | 61d720c020b08faa58a1e6c82aef3e75dc58dc10 | /structure/src/Structure_1.cpp | 8e2973be9c8ffea28e4d5efaf51a73b882261c17 | [] | no_license | VinothVB/CPP | e2186b8b9d643607dd7b8de261ff54f6759e7b3c | e8a2f33a8ef9e35abb3060c6da9a73d7301789e9 | refs/heads/master | 2022-12-30T22:49:54.866457 | 2020-10-24T06:25:53 | 2020-10-24T06:25:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | /*
Structure Padding
*/
#include <stdio.h>
#include <string.h>
/* Below structure1 and structure2 are same.
They differ only in member's allignment */
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
char name;
int id2;
char c;
float percentage;
};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n",
sizeof(a));
printf("\n Address of id1 = %u", &a.id1);
printf("\n Address of id2 = %u", &a.id2);
printf("\n Address of name = %u", &a.name);
printf("\n Address of c = %u", &a.c);
printf("\n Address of percentage = %u",
&a.percentage);
printf(" \n\nsize of structure2 in bytes : %d\n",
sizeof(b));
printf("\n Address of id1 = %u", &b.id1);
printf("\n Address of name = %u", &b.name);
printf("\n Address of id2 = %u", &b.id2);
printf("\n Address of c = %u", &b.c);
printf("\n Address of percentage = %u",
&b.percentage);
getchar();
return 0;
} | [
"49783910+shreyjp5788@users.noreply.github.com"
] | 49783910+shreyjp5788@users.noreply.github.com |
a4d81090f48af0260d375f9f09218443fc39933e | cecc35c9980afb78afc9c5a27e9fb44c21c725c8 | /Robot2/robot.h | 2bc6ac13c8f43c7e4c4d2b10e9c4f4501e5287df | [] | no_license | boblandry/OpenGL | 1c5fc3d118277153c34e6c0cbab3b6f563a298a3 | e6dbc64c24119a98f2b57051b78b22c5702eac97 | refs/heads/master | 2016-09-05T17:04:18.589742 | 2015-05-20T12:20:31 | 2015-05-20T12:20:31 | 34,739,399 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,523 | h | #include <gl\glut.h>
#include <math.h>
#include <iostream>
using namespace std;
void drawpoint(int x,int y,int r,int g,int b)
{
glColor3ub(r,g,b);
glPointSize(1);
glBegin(GL_POINTS);
glVertex3f(x,y,0);
glEnd();
glFlush();
}
void gl_Point(int x,int y)
{
glPointSize(1);
glBegin(GL_POINTS);
glVertex3f(x,y,0);
glEnd();
}
void dda(int x1,int y1,int x2,int y2)//直线dda算法
{
int k,i;
float x,y,dx,dy;
k=abs(x2-x1);
if (abs(y2-y1)>k) k=abs(y2-y1);
dx=float(x2-x1)/k;
dy=float(y2-y1)/k;
x=float(x1);
y=float(y1);
for (i=0;i<k;i++)
{
gl_Point(int(x+0.5),int(y+0.5));
x=x+dx;
y=y+dy;
}
}
void midpointline(int xs,int ys,int xe,int ye)//直线正负法
{
int a,b,dt1,dt2,dt3,dt4,d,x,y;
if (ys>ye)
{
int t1,t2;
t1=xs;xs=xe;xe=t1;
t2=ys;ys=ye;ye=t2;
}
a=ys-ye;b=xe-xs;
double k=-a/double(b);
if(k<1 && k>0)
d=2*a+b;
else if(k>=1)
d=2*b+a;
else if(k<=-1)
d=2*b-a;
else
d=b-2*a;
dt1=2*a;
dt2=2*(a+b);
dt3=2*b;
dt4=2*(b-a);
x=xs;y=ys;
gl_Point(x,y);
if (k>=1 || k<=-1)
{
if(k<=-1){
while(x>xe){
if(d<0){
x--;y++;d=d+dt4;
}
else{
y++;d=d+dt3;
}
gl_Point(x,y);
}
}
else{
while(x<xe)
{
if(d>=0){
x++;y++;d=d+dt2;
}
else{
y++;d=d+dt3;
}
gl_Point(x,y);
}
}
}
else
{
if(k<0){
while(x>xe){
if(d>0){
x--;y++;d=d+dt4;
}
else{
x--;d=d-dt1;
}
gl_Point(x,y);
}
}
else{
while(x<xe){
if(d<0){
x++;y++;d=d+dt2;
}
else{
x++;d=d+dt1;
}
gl_Point(x,y);
}
}
}
}
void bresenhamline(int xs,int ys,int xe,int ye)//直线bresenham算法
{
if(xs>xe){
int t1,t2;
t1=xs;xs=xe;xe=t1;
t2=ys;ys=ye;ye=t2;
}
int dy=ye-ys;
int dx=xe-xs;
int x=xs,y=ys,i;
if(dx==0){
if(ys>ye){
int t;
t=ys;ys=ye;ye=t;
}
dy=ye-ys;y=ys;
for (i=0;i<dy;i++){
gl_Point(x,y);
y++;
}
}
else{
double m=(double)dy/(double)dx;//斜率
double e=m-0.5;
int count=0;
//cout<<e<<endl;
if (m>=0 && m<1){
for(i=0;i<dx;i++){
//cout<<e<<endl;
gl_Point(x,y);
if(e>=0){
y++;e--;
}
x++;e=e+m;
}
}
else if (m>1){
m=1/m;e=m-0.5;
for(i=0;i<dy;i++){
count++;
gl_Point(x,y);
if(e>=0){
x++;e--;
}
y++;e=e+m;
}
}
else if (m>-1){
for(i=0;i<dx;i++){
gl_Point(x,y);
//cout<<e<<endl;
if(e<0){
y--;e++;
}
x++;e=e+m;
}
}
else if (m<-1){
m=1/m;e=m-0.5;
for (i=0;i>dy;i--){
gl_Point(x,y);
if(e<0){
x++;e++;
}
y--;e=e+m;
}
}
//cout<<count<<endl;
}
}
void pnarc(int r,int x0,int y0,int num)//圆弧正负法
{
int x,y,f;
x=0;f=0;
if(num==1 || num==2)
y=r;
else if(num==3 || num==4)
y=-r;
else
num=1;
if(num==1){
while(y>0){
gl_Point(x+x0,y+y0);
if(f>0){
f=f-2*y+1;y--;
}
else{
f=f+2*x+1;x++;
}
}
if(y==0)gl_Point(x+x0,y+y0);
}
else if (num==2){
while(y>0){
gl_Point(x+x0,y+y0);
if(f>0){
f=f-2*y+1;y--;
}
else{
f=f-2*x+1;x--;
}
}
if(y==0)gl_Point(x+x0,y+y0);
}
else if (num==3){
while(y<0){
gl_Point(x+x0,y+y0);
if(f>0){
f=f+2*y+1;y++;
}
else{
f=f-2*x+1;x--;
}
}
if(y==0)gl_Point(x+x0,y+y0);
}
else{
while(y<0){
gl_Point(x+x0,y+y0);
if(f>0){
f=f+2*y+1;y++;
}
else{
f=f+2*x+1;x++;
}
}
if(y==0)gl_Point(x+x0,y+y0);
}
}
void pnarc1(int r,int x0,int y0,int num)//圆弧正负法代码简洁版
{
int x,y,f;
x=0;f=0;y=r;
if(num!=1 && num!=2 && num!=3 && num!=4)
num=1;
while(y>0){
if(num==1)
gl_Point(x+x0,y+y0);
else if(num==2)
gl_Point(x0-x,y+y0);
else if(num==3)
gl_Point(x0-x,y0-y);
else
gl_Point(x+x0,y0-y);
if(f>0){
f=f-2*y+1;y--;
}
else{
f=f+2*x+1;x++;
}
}
if(y==0){
if(num==1)
gl_Point(x+x0,y+y0);
else if(num==2)
gl_Point(x0-x,y+y0);
else if(num==3)
gl_Point(x0-x,y0-y);
else
gl_Point(x+x0,y0-y);
}
}
void bresenhamarc(int r,int x0,int y0,int num)
{
int x,y,d;
x=0;y=r;d=3-2*r;
if (num!=1 && num!=2 && num!=3 && num!=4 && num!=5 && num!=6 && num!=7 && num!=8)
num=1;
while(x<y){
if (num==2)
gl_Point(x+x0,y+y0);
if (num==1)
gl_Point(y+x0,x+y0);
if (num==3)
gl_Point(x0-x,y+y0);
if (num==4)
gl_Point(x0-y,y0+x);
if (num==5)
gl_Point(x0-y,y0-x);
if (num==6)
gl_Point(x0-x,y0-y);
if (num==7)
gl_Point(x+x0,y0-y);
if (num==8)
gl_Point(x0+y,y0-x);
if(d<0)d=d+4*x+6;
else{
d=d+4*(x-y)+10;
y--;
}
x++;
}
//if(x==y)gl_Point();
}
| [
"landry001@vip.qq.com"
] | landry001@vip.qq.com |
7263dbb287c19586fbc6cf810004e573df0cbd5e | ceb2dbf9bf5ed91bad721e2eb590c076d025165f | /src/decido.h | 38a6953cd7e540fc8f0c4776185e94c0ca5e9d44 | [
"MIT"
] | permissive | hypertidy/decido | 8fe9f935533ee535c2722ecdde5ef30427dc7c04 | 1ffdb55af3494e111178c1ff8df6d6652374466c | refs/heads/master | 2021-04-27T02:59:36.587325 | 2020-05-21T21:59:12 | 2020-05-21T21:59:12 | 122,706,089 | 15 | 3 | NOASSERTION | 2020-05-20T01:02:41 | 2018-02-24T05:24:59 | C++ | UTF-8 | C++ | false | false | 258 | h | #include <Rcpp.h>
#include <array>
#include "earcut.h"
Rcpp::IntegerVector earcut_cpp(
Rcpp::NumericVector x,
Rcpp::NumericVector y,
Rcpp::IntegerVector holes,
Rcpp::IntegerVector numholes
);
Rcpp::IntegerVector earcut_sfg( SEXP& sfg );
| [
"mark.padgham@email.com"
] | mark.padgham@email.com |
553d5ab1f17066a3c0d563f63000f7e555727d56 | 4d1fc70c9823714e1e9f66e632e2b8c09d0bd23b | /CSES/Increasing Subsequence/main.cpp | c807f69d63b23e33892416656cfa03aae01aa082 | [] | no_license | Lamoreauxaj/competitive-programming | dcdcdc5822cc346ff67230c9e5c376981c1e8cb2 | 07cc02d861a83c411f83c77bb30c59e3fb76ee5f | refs/heads/master | 2020-04-21T14:02:41.998895 | 2020-02-27T21:15:25 | 2020-02-27T21:15:25 | 169,621,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | #include <bits/stdc++.h>
using namespace std;
int N, A[200010];
int lis[200010], p[200010];
int main() {
ios_base::sync_with_stdio(false);
// freopen("1.in", "r", stdin);
// input
cin >> N;
for (int i = 0; i < N; i++)
cin >> A[i];
// run lis
p[0] = 0;
for (int i = 1; i <= N + 1; i++)
p[i] = 1000000001;
for (int i = 0; i < N; i++) {
int low = 0, high = N;
while (low < high) {
int mid = (low + high) / 2;
if (p[mid] < A[i] && p[mid + 1] >= A[i])
break;
else if (p[mid] < A[i])
low = mid + 1;
else
high = mid - 1;
}
int len = (low + high) / 2 + 1;
lis[i] = len;
p[len] = min(p[len], A[i]);
}
// find max lis
int ans = 0;
for (int i = 0; i < N; i++)
ans = max(ans, lis[i]);
// output
cout << ans << "\n";
return 0;
}
| [
"LamoreauxAJ@gmail.com"
] | LamoreauxAJ@gmail.com |
807a7b8d23181fb90b2aee46e5af291c8430e652 | df93ce63155a5ddfd054f8daba9653d1ad00eb24 | /applications/test/coupledFvPatch/testMatching/twoProcs/processor1/constant/polyMesh/points | 79617d58cce530dcbce316b09aa57fccf73d52c1 | [] | no_license | mattijsjanssens/mattijs-extensions | d4fb837e329b3372689481e9ebaac597272e0ab9 | 27b62bf191f1db59b045ce5c89c859a4737033e4 | refs/heads/master | 2023-07-19T20:57:04.034831 | 2023-07-16T20:35:12 | 2023-07-16T20:35:12 | 57,304,835 | 8 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 944 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev.feature-ACMI |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class vectorField;
location "constant/polyMesh";
object points;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
8((1 0 0) (1 1 0) (1 0 1) (1 1 1) (1.5 0 0) (1.5 1 0) (1.5 0 1) (1.5 1 1))
// ************************************************************************* //
| [
"mattijs"
] | mattijs | |
6f5214a772eaf088138d93e9a8397a8ae60301cd | 0e1b1f5e2893070ebdcb5eb15b07b89b0f31f471 | /submodules/seqan/demos/tutorial/multiple_sequence_alignment/consensus.cpp | b0143076d817896fc840fec5c6984ce33e9e2feb | [
"MIT",
"BSD-3-Clause"
] | permissive | sheffield-bioinformatics-core/STRique | 1a4a3e59e0ac66174ed5c9a4498d6d8bed40b54d | fd2df916847727b3484b2bbad839814043d7dbea | refs/heads/master | 2022-12-27T22:28:31.893074 | 2020-09-29T14:31:45 | 2020-09-29T14:31:45 | 296,618,760 | 0 | 0 | MIT | 2020-09-18T12:45:30 | 2020-09-18T12:45:29 | null | UTF-8 | C++ | false | false | 2,614 | cpp | //![align]
#include <iostream>
#include <seqan/align.h>
#include <seqan/graph_msa.h>
using namespace seqan;
int main()
{
// some variangs of sonic hedgehog exon 1
char const * strings[4] =
{
// gi|2440284|dbj|AB007129.1| Oryzias latipes
"GCGGGTCACTGAGGGCTGGGATGAGGACGGCCACCACTTCGAGGAGTCCCTTCACTACGAGGGCAGGGCC"
"GTGGACATCACCACGTCAGACAGGGACAAGAGCAAGTACGGCACCCTGTCCAGACTGGCGGTGGAAGCTG"
"GGTTCGACTGGGTCTACTATGAGTCCAAAGCGCACATCCACTGCTCTGTGAAAGCAGAAAGCTCAGTCGC"
"TGCAAAGTCGGGCGGTTGCTTCCCAGGATCCTCCACGGTCACCCTGGAAAATGGCACCCAGAGGCCCGTC"
"AAAGATCTCCAACCCGGGGACAGAGTACTGGCCGCGGATTACGACGGAAACCCGGTTTATACCGACTTCA"
"TCATGTTCAA",
// gi|1731488|gb|U51350.1|DDU51350 Devario devario
"CTACGGCAGAAGAAGACATCCGAAAAAGCTGACACCTCTCGCCTACAAGCAGTTCATACCTAATGTCGCG"
"GAGAAGACCTTAGGGGCCAGCGGCAGATACGAGGGCAAGATAACGCGCAATTCGGAGAGATTTAAAGAAC"
"TTACTCCAAATTACAATCCCGACATTATCTTTAAGGATGAGGAGAACACG",
// gi|1731504|gb|U51352.1|PTU51352 Puntius tetrazona
"CTACGGCAGAAGAAGACATCCCAAGAAGCTGACACCTCTCGCCTACAAGCAGTTTATACCTAATGTCGCG"
"GAGAAGACCTTAGGGGCCAGCGGCAGATACGAGGGCAAGATCACGCGCAATTCGGAGAGATTTAAAGAAC"
"TTACTCCAAATTACAATCCCGACATTATCTTTAAGGATGAGGAGAACACT",
// gi|54399708|gb|AY642858.1| Bos taurus
"TGCTGCTGCTGGCGAGATGTCTGCTGGTGCTGCTTGTCTCCTCGCTGTTGATGTGCTCGGGGCTGGCGTG"
"CGGACCCGGCAGGGGATTTGGCAAGAGGCGGAACCCCAAAAAGCTGACCCCTTTAGCCTACAAGCAGTTT"
"ATCCCCAACGTGGCGGAGAAGACCCTAGGGGCCAGTGGAAGATATGAGGGGAAGATCACCAGAAACTCAG"
"AGCGATTTAAGGAACTCACCCCCAATTACAACCC"
};
Align<DnaString> align;
resize(rows(align), 4);
for (int i = 0; i < 4; ++i)
assignSource(row(align, i), strings[i]);
globalMsaAlignment(align, SimpleScore(5, -3, -1, -3));
std::cout << align << "\n";
//![align]
//![profile-computation]
// create the profile string
String<ProfileChar<Dna> > profile;
resize(profile, length(row(align, 0)));
for (unsigned rowNo = 0; rowNo < 4u; ++rowNo)
for (unsigned i = 0; i < length(row(align, rowNo)); ++i)
profile[i].count[ordValue(getValue(row(align, rowNo), i))] += 1;
//![profile-computation]
//![consensus-calling]
// call consensus from this string
DnaString consensus;
for (unsigned i = 0; i < length(profile); ++i)
{
int idx = getMaxIndex(profile[i]);
if (idx < 4) // is not gap
appendValue(consensus, Dna(getMaxIndex(profile[i])));
}
std::cout << "consensus sequence is\n"
<< consensus << "\n";
return 0;
}
//![consensus-calling]
| [
"matthew.parker@sheffield.ac.uk"
] | matthew.parker@sheffield.ac.uk |
e059c52da299cafcf7e17ff86359902eca96c176 | 805a02ef19a184cc95139f137d7553e047c83706 | /src/kdtreebuilder.cpp | 6e1859e437f637255b870979fcbc5da5f8edd8a7 | [] | no_license | samanpa/raytracer | 7316e8767e71b8a089084e8c240de61f79b7bd30 | 85d65ed6f92c618c5c14708e29926d8d3ccd426e | refs/heads/master | 2021-01-25T03:54:17.733933 | 2013-04-07T02:09:10 | 2013-04-07T02:09:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,752 | cpp | #include "kdtreebuilder.h"
#include "kdnode.h"
#include "utils.h"
#include <algorithm>
#include <unordered_set>
using namespace std;
kdtreebuilder::kdtreebuilder(kdtree& kdtree
, const scene& scene)
: _kdtree(kdtree)
, _scene(scene)
, _levmgr(scene.getTriangles().size() * 12)
, _revmgr(scene.getTriangles().size() * 12)
, _bevmgr(scene.getTriangles().size() * 6)
{
_sides.resize(scene.getTriangles().size());
}
static void generateEvents(const aabb& bb, int tid, chunkmem<splitevent>& events) {
for (int k = 0; k < 3; ++k) {
if (bb.lower[k] == bb.upper[k]) {
splitevent sp(tid , bb.lower[k], k, splittype::Planar);
events.push_back(sp);
}
else {
splitevent sp1(tid , bb.lower[k], k, splittype::Start);
splitevent sp2(tid , bb.upper[k], k, splittype::End);
events.push_back(sp1);
events.push_back(sp2);
}
}
}
void kdtreebuilder::build(vec3f &lower, vec3f &upper)
{
auto bevents = _bevmgr.create();
size_t size = _scene.getTriangles().size();
for (size_t tid = 0; tid < size; ++tid) {
auto& tri = _scene.getTriangle(tid);
aabb bb;
tri.getBounds(_scene, bb);
generateEvents(bb, tid, bevents);
}
aabb bb;
bb.lower = lower;
bb.upper = upper;
std::sort(bevents.begin(), bevents.end());
recbuild(_kdtree.allocNode(), bevents, bb, size);
INFO( "kdtree build complete " << size);
}
static void splitVoxel(const aabb& voxel, int axis, float split, aabb& left, aabb &right)
{
left.lower = voxel.lower;
right.upper = voxel.upper;
left.upper[axis] = split;
right.lower[axis] = split;
left.upper[modulo3[1 + axis]] = voxel.upper[modulo3[1 + axis]];
right.lower[modulo3[axis + 1]] = voxel.lower[modulo3[axis + 1]];
left.upper[modulo3[2 + axis]] = voxel.upper[modulo3[2 + axis]];
right.lower[modulo3[axis + 2]] = voxel.lower[modulo3[axis + 2]];
}
static const int INTERSECT_COST = 50;
static const int TRAVERSAL_COST = 100;
static void sah(int nl, int nr, int np, float pl, float pr, float& cost, splitside &side)
{
float lambda = ((nl == 0) | (nr == 0)) ? 0.8f : 1.0f;
float lcost = lambda * (TRAVERSAL_COST + INTERSECT_COST * (pl * (nl + np) + pr * nr));
float rcost = lambda * (TRAVERSAL_COST + INTERSECT_COST * (pl * nl + pr * (nr + np)));
if (lcost < rcost) {
cost = lcost;
side = splitside::Left;
}
else {
cost = rcost;
side = splitside::Right;
}
}
static float getArea(const aabb & v)
{
vec3f d(v.upper - v.lower);
//We don't multiply by 2 because we end up dividing
// by another area and cancelling it out
return (d.y() *(d.x() + d.z()) + d.z() * d.x());
}
bool kdtreebuilder::findPlane(const aabb &v
, const chunkmem<splitevent>& events, split &split, size_t numtris)
{
bool dosplit = false;
float mincost = numtris * INTERSECT_COST;
float rcparea = rcp(getArea(v));
vec3<size_t> nleft(0, 0, 0);
vec3<size_t> nright(numtris, numtris, numtris);
auto end = events.end();
auto curr = events.begin();
while (curr < end) {
int k = curr->axis;
float split_k = curr->pos;
int np = 0, nend = 0, nstart = 0;
while (curr < end && curr->pos == split_k
&& curr->axis == k && curr->type == splittype::End) {
++curr; ++nend;
}
while (curr < end && curr->pos == split_k
&& curr->axis == k && curr->type == splittype::Planar) {
++curr; ++np;
}
while (curr < end && curr->pos == split_k
&& curr->axis == k && curr->type == splittype::Start) {
++curr; ++nstart;
}
aabb lv, rv;
splitVoxel(v, k, split_k, lv, rv);
nright[k] -= (np + nend);
float cost = mincost;
splitside side;
sah(nleft[k], nright[k], np, getArea(lv)*rcparea, getArea(rv)*rcparea, cost, side);
nleft[k] += (nstart + np);
if (cost < mincost
&& v.lower[k] < split_k
&& v.upper[k] > split_k) {
split.pos = split_k;
split.side = side;
split.lv = lv;
split.rv = rv;
split.axis = k;
mincost = cost;
dosplit = true;
}
}
return dosplit;
}
void kdtreebuilder::classify(eventlist& allevents, split &split
, eventlist& left, eventlist& right
, size_t& nl, size_t& nr, const aabb& voxel)
{
nl = nr = 0;
for (auto& e : allevents)
_sides[e.tri] = splitside::Both;
for (auto& e : allevents) {
if (e.axis != split.axis) continue;
switch (e.type) {
case splittype::End:
if (e.pos <= split.pos)
_sides[e.tri] = splitside::Left;
break;
case splittype::Start:
if (e.pos >= split.pos)
_sides[e.tri] = splitside::Right;
break;
default:
if (e.pos == split.pos)
_sides[e.tri] = split.side;
else if (e.pos < split.pos)
_sides[e.tri] = splitside::Left;
else if (e.pos > split.pos)
_sides[e.tri] = splitside::Right;
break;
}
}
for (auto& e : allevents) {
switch(_sides[e.tri]) {
case splitside::Left: left.push_back(e); break;
case splitside::Right: right.push_back(e); break;
default: break;
}
}
auto onlyleftsize = left.size();
auto onlyrightsize = right.size();
for (auto& e : allevents) {
switch(_sides[e.tri]) {
case splitside::Left: ++nl; break;
case splitside::Right: ++nr; break;
case splitside::Both: {
++nl;
++nr;
aabb l, r;
clip(_scene, e.tri, voxel, l, r, split.pos, split.axis);
generateEvents(l, e.tri, left);
generateEvents(r, e.tri, right);
break;
}
default: break;
}
_sides[e.tri] = splitside::Undef;
}
sort(left.begin() + onlyleftsize, left.end());
sort(right.begin() + onlyrightsize, right.end());
inplace_merge(left.begin(), left.begin() + onlyleftsize, left.end());
inplace_merge(right.begin(), right.begin() + onlyrightsize, right.end());
}
void kdtreebuilder::recbuild(nodeid node, chunkmem<splitevent>& events, aabb& voxel, size_t numtris)
{
split split;
bool hasSplit = findPlane(voxel, events, split, numtris);
if (hasSplit) {
auto left = _kdtree.allocNode();
auto right = _kdtree.allocNode();
_kdtree.initInternalNode(node, left, split.axis, split.pos);
auto levents = _levmgr.create();
auto revents = _revmgr.create();
size_t nl, nr;
classify(events, split, levents, revents, nl, nr, voxel);
recbuild(left, levents, split.lv, nl);
recbuild(right, revents, split.rv, nr);
}
else {
unordered_set<int> tris;
for (auto& e : events)
tris.insert(e.tri);
_kdtree.initLeaf(node, tris.size());
for (auto& tri : tris)
_kdtree.addPrim(tri);
}
events.destroy();
}
| [
"samanpa@gmail.com"
] | samanpa@gmail.com |
5dd2b12775834f598d1e328680d04507a505ad20 | be029ca5bbf72e513885c06292af2ec45c708d64 | /src/octa/gui/core.hh | 8725c1c6062705067c54c89250ea5f14769e1fe5 | [
"Zlib",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"NCSA"
] | permissive | OctaForge/OF-Engine | 097d9b4a517b70de7b4c81b9b358ff4250d2057d | fd2dd742024200a97b140e5530a97b2c86c873f2 | refs/heads/master | 2020-05-16T11:20:09.108300 | 2018-10-22T00:43:27 | 2018-10-22T00:43:59 | 1,606,716 | 39 | 11 | null | 2015-06-24T21:48:27 | 2011-04-12T22:51:25 | C++ | UTF-8 | C++ | false | false | 10,741 | hh | /* The GUI subsystem of OctaForge - core definitions
*
* This file is part of OctaForge. See COPYING.md for futher information.
*/
#ifndef OCTA_GUI_CORE_HH
#define OCTA_GUI_CORE_HH
#include <ostd/types.hh>
#include <ostd/event.hh>
#include <ostd/vector.hh>
#include <ostd/string.hh>
#include <ostd/algorithm.hh>
#include <ostd/vecmath.hh>
namespace octa { namespace gui {
void draw_quad(float x, float y, float w, float h,
float tx = 0, float ty = 0, float tw = 1, float th = 1);
void draw_quadtri(float x, float y, float w, float h,
float tx = 0, float ty = 0, float tw = 1, float th = 1);
enum {
ALIGN_HMASK = 0x3,
ALIGN_VMASK = 0xC,
ALIGN_MASK = ALIGN_HMASK | ALIGN_VMASK,
CLAMP_MASK = 0xF0,
ALIGN_HSHIFT = 0,
ALIGN_VSHIFT = 2,
ALIGN_HNONE = 0 << ALIGN_HSHIFT,
ALIGN_LEFT = 1 << ALIGN_HSHIFT,
ALIGN_HCENTER = 2 << ALIGN_HSHIFT,
ALIGN_RIGHT = 3 << ALIGN_HSHIFT,
ALIGN_VNONE = 0 << ALIGN_VSHIFT,
ALIGN_TOP = 1 << ALIGN_VSHIFT,
ALIGN_VCENTER = 2 << ALIGN_VSHIFT,
ALIGN_BOTTOM = 3 << ALIGN_VSHIFT,
ALIGN_CENTER = ALIGN_HCENTER | ALIGN_VCENTER,
ALIGN_NONE = ALIGN_HNONE | ALIGN_VNONE,
CLAMP_LEFT = 1 << 4,
CLAMP_RIGHT = 1 << 5,
CLAMP_TOP = 1 << 6,
CLAMP_BOTTOM = 1 << 7
};
enum class Orientation {
horizontal, vertical
};
enum {
CHANGE_SHADER = 1 << 0,
CHANGE_COLOR = 1 << 1,
CHANGE_BLEND = 1 << 2
};
enum {
BLEND_ALPHA,
BLEND_MOD
};
extern int draw_changed;
void blend_change(int type, ostd::uint src, ostd::uint dst);
void blend_reset();
void blend_mod();
class Widget;
class Root;
class ClipArea {
float p_x1, p_y1, p_x2, p_y2;
public:
ClipArea(float x, float y, float w, float h):
p_x1(x), p_y1(y), p_x2(x + w), p_y2(y + h) {}
void intersect(const ClipArea &c) {
p_x1 = ostd::max(p_x1, c.p_x1);
p_y1 = ostd::max(p_y1, c.p_y1);
p_x2 = ostd::max(p_x1, ostd::min(p_x2, c.p_x2));
p_y2 = ostd::max(p_y1, ostd::min(p_y2, c.p_y2));
}
bool is_fully_clipped(float x, float y, float w, float h) const {
return (p_x1 == p_x2) || (p_y1 == p_y2) || (x >= p_x2) ||
(y >= p_y2) || ((x + w) <= p_x1) || ((y + h) <= p_y1);
}
void scissor(Root *r);
};
class Projection {
Widget *p_obj;
float p_px = 0, p_py = 0, p_pw = 0, p_ph = 0;
ostd::Vec2f p_sscale, p_soffset;
public:
Projection(Widget *obj): p_obj(obj) {}
void calc(float &pw, float &ph);
void calc() {
float pw, ph;
calc(pw, ph);
}
void adjust_layout();
void projection();
void calc_scissor(float x1, float y1, float x2, float y2,
int &sx1, int &sy1, int &sx2, int &sy2,
bool clip = false);
void draw(float sx, float sy);
void draw();
float calc_above_hud();
};
class Color {
ostd::byte p_r, p_g, p_b, p_a;
public:
ostd::Signal<Color> red_changed = this;
ostd::Signal<Color> green_changed = this;
ostd::Signal<Color> blue_changed = this;
ostd::Signal<Color> alpha_changed = this;
Color(): p_r(0xFF), p_g(0xFF), p_b(0xFF), p_a(0xFF) {}
Color(ostd::Uint32 color): p_r((color >> 16) & 0xFF),
p_g((color >> 8) & 0xFF),
p_b( color & 0xFF),
p_a(!(color >> 24) ? 0xFF : (color >> 24)) {}
Color(ostd::Uint32 color, ostd::byte alpha):
p_r((color >> 16) & 0xFF), p_g((color >> 8) & 0xFF),
p_b(color & 0xFF), p_a(alpha) {}
Color(ostd::byte red, ostd::byte green, ostd::byte blue,
ostd::byte alpha = 0xFF):
p_r(red), p_g(green), p_b(blue), p_a(alpha) {}
ostd::byte red () const { return p_r; }
ostd::byte green() const { return p_g; }
ostd::byte blue () const { return p_b; }
ostd::byte alpha() const { return p_a; }
void set_red(ostd::byte v) {
p_r = v;
red_changed.emit();
}
void set_green(ostd::byte v) {
p_g = v;
green_changed.emit();
}
void set_blue(ostd::byte v) {
p_b = v;
blue_changed.emit();
}
void set_alpha(ostd::byte v){
p_a = v;
blue_changed.emit();
}
void init() const;
void attrib() const;
void def() const;
void get_final_rgba(const Widget *o, ostd::byte &r, ostd::byte &g,
ostd::byte &b, ostd::byte &a);
};
/* widget */
class Widget {
protected:
Widget *p_parent = nullptr;
mutable Root *p_root = nullptr;
mutable Projection *p_proj = nullptr;
ostd::Vector<Widget *> p_children;
float p_x = 0, p_y = 0, p_w = 0, p_h = 0;
ostd::byte p_adjust = ALIGN_CENTER;
bool p_floating = false, p_visible = true, p_disabled = false;
public:
friend class Root;
struct TypeTag {
TypeTag() {}
ostd::Size get() const { return (ostd::Size)this; }
};
ostd::Signal<Widget> floating_changed = this;
ostd::Signal<Widget> visible_changed = this;
ostd::Signal<Widget> disabled_changed = this;
Widget() {}
virtual ostd::Size get_type();
Root *root() const {
if (p_root) return p_root;
if (p_parent) {
Root *r = p_parent->root();
p_root = r;
return r;
}
return nullptr;
}
Projection *projection(bool nonew = false) const {
if (p_proj || nonew || ((Widget *)p_root == this)) return p_proj;
p_proj = new Projection((Widget *)this);
return p_proj;
}
void set_projection(Projection *proj) {
p_proj = proj;
}
float x() const { return p_x; }
float y() const { return p_y; }
void set_x(float v) { p_x = v; }
void set_y(float v) { p_y = v; }
float width() const { return p_w; }
float height() const { return p_h; }
bool floating() const { return p_floating; }
bool visible() const { return p_visible; }
bool disabled() const { return p_disabled; }
void set_floating(bool v) {
p_floating = v;
floating_changed.emit();
}
void set_visible(bool v) {
p_visible = v;
visible_changed.emit();
}
void set_disabled(bool v) {
p_disabled = v;
disabled_changed.emit();
}
template<typename F>
bool loop_children(F fun) {
for (auto o: p_children.iter())
if (fun(o)) return true;
return false;
}
template<typename F>
bool loop_children(F fun) const {
for (auto o: p_children.iter())
if (fun(o)) return true;
return false;
}
template<typename F>
bool loop_children_r(F fun) {
for (auto o: p_children.iter().reverse())
if (fun(o)) return true;
return false;
}
template<typename F>
bool loop_children_r(F fun) const {
for (auto o: p_children.iter().reverse())
if (fun(o)) return true;
return false;
}
virtual void layout();
void adjust_children(float px, float py, float pw, float ph) {
loop_children([px, py, pw, ph](Widget *o) {
o->adjust_layout(px, py, pw, ph);
return false;
});
}
virtual void adjust_children() {
adjust_children(0, 0, p_w, p_h);
}
virtual void adjust_layout(float px, float py, float pw, float ph);
virtual bool grabs_input() const { return true; }
virtual void start_draw() {}
virtual void end_draw() {}
void end_draw_change(int change);
void change_draw(int change = 0);
void stop_draw();
virtual void draw(float sx, float sy);
void draw() {
draw(p_x, p_y);
}
virtual bool is_root() {
return false;
}
};
/* named widget */
class NamedWidget: public Widget {
ostd::String p_name;
public:
ostd::Signal<const NamedWidget> name_changed = this;
NamedWidget(ostd::ConstCharRange s): p_name(s) {}
virtual ostd::Size get_type();
const ostd::String &name() const { return p_name; }
void set_name(ostd::ConstCharRange s) {
p_name = s;
name_changed.emit();
}
};
/* tag */
class Tag: public NamedWidget {
public:
using NamedWidget::NamedWidget;
virtual ostd::Size get_type();
};
/* window */
class Window: public NamedWidget {
bool p_input_grab, p_above_hud;
public:
ostd::Signal<const Window> input_grab_changed = this;
ostd::Signal<const Window> above_hud_changed = this;
Window(ostd::ConstCharRange name, bool input_grab = true,
bool above_hud = false):
NamedWidget(name), p_input_grab(input_grab),
p_above_hud(above_hud) {}
virtual ostd::Size get_type();
bool input_grab() const { return p_input_grab; }
bool above_hud() const { return p_above_hud; }
void set_input_grab(bool v) {
p_input_grab = v;
input_grab_changed.emit();
}
void set_above_hud(bool v) {
p_above_hud = v;
above_hud_changed.emit();
}
bool grabs_input() const { return input_grab(); }
};
/* overlay */
class Overlay: public Window {
public:
using Window::Window;
virtual ostd::Size get_type();
bool grabs_input() const { return false; }
};
/* root */
class Root: public Widget {
ostd::Vector<Window *> p_windows;
ostd::Vector<ClipArea> p_clipstack;
ostd::Vector<Widget *> p_menustack;
Widget *p_drawing = nullptr;
Widget *p_tooltip = nullptr;
Widget *p_clicked = nullptr;
Widget *p_hovering = nullptr;
Widget *p_focused = nullptr;
float p_rtxt_scale = 0;
float p_ctxt_scale = 0;
float p_curx = 0.499, p_cury = 0.499;
bool p_has_cursor = false;
float p_hovx = 0, p_hovy = 0;
float p_clickx = 0, p_clicky = 0;
ostd::sbyte p_menu_nhov = -2;
public:
friend class Widget;
friend class Projection;
Root(): Widget() {
this->p_root = this;
}
virtual ostd::Size get_type();
int get_pixel_w(bool force_aspect = false) const;
int get_pixel_h() const;
float get_aspect(bool force = false) const;
bool grabs_input() const {
return loop_children_r([](const Widget *o) {
return o->grabs_input();
});
}
void adjust_children();
void layout_dim() {
p_x = p_y = 0;
p_w = get_aspect(true);
p_h = 1.0f;
}
void layout();
void clip_push(float x, float y, float w, float h);
void clip_pop();
bool clip_is_fully_clipped(float x, float y, float w, float h);
void clip_scissor();
bool is_root() {
return true;
}
void draw(float sx, float sy);
};
} } /* namespace octa::gui */
#endif | [
"daniel@octaforge.org"
] | daniel@octaforge.org |
298628a59d0a3d7d53d4bd970f6f74a140abc5f6 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /components/open_from_clipboard/fake_clipboard_recent_content.h | 61798399dc6e4e987a9a66d19cef46f1f4c3503f | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 1,969 | h | // Copyright 2015 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 COMPONENTS_OPEN_FROM_CLIPBOARD_FAKE_CLIPBOARD_RECENT_CONTENT_H_
#define COMPONENTS_OPEN_FROM_CLIPBOARD_FAKE_CLIPBOARD_RECENT_CONTENT_H_
#include "base/macros.h"
#include "base/time/time.h"
#include "components/open_from_clipboard/clipboard_recent_content.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
// FakeClipboardRecentContent implements ClipboardRecentContent interface by
// returning configurable values for use by tests.
class FakeClipboardRecentContent : public ClipboardRecentContent {
public:
FakeClipboardRecentContent();
~FakeClipboardRecentContent() override;
// ClipboardRecentContent implementation.
base::Optional<GURL> GetRecentURLFromClipboard() override;
base::Optional<base::string16> GetRecentTextFromClipboard() override;
base::Optional<gfx::Image> GetRecentImageFromClipboard() override;
base::TimeDelta GetClipboardContentAge() const override;
void SuppressClipboardContent() override;
// Sets the URL and clipboard content age. This clears the text and image.
void SetClipboardURL(const GURL& url, base::TimeDelta content_age);
// Sets the text and clipboard content age. This clears the URL and image.
void SetClipboardText(const base::string16& text,
base::TimeDelta content_age);
// Sets the image and clipboard content age. This clears the URL and text.
void SetClipboardImage(const gfx::Image& image, base::TimeDelta content_age);
private:
base::Optional<GURL> clipboard_url_content_;
base::Optional<base::string16> clipboard_text_content_;
base::Optional<gfx::Image> clipboard_image_content_;
base::TimeDelta content_age_;
bool suppress_content_;
DISALLOW_COPY_AND_ASSIGN(FakeClipboardRecentContent);
};
#endif // COMPONENTS_OPEN_FROM_CLIPBOARD_FAKE_CLIPBOARD_RECENT_CONTENT_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
2745a69c06ca07ddfc743f43fed52b871827540f | 90b77b7151ba615cc674995758f3c549a42491d8 | /Projects/threads/src/FileReader.cpp | b5ed8085a8367bb71ad3bb6eec0ee9d730afe49a | [] | no_license | mnwallac/Projects | 7fe9baf56445454c0c43d09297282172df2e7aae | e9b2f8b7a4122fed07fdb79200ef22d4a8c9e7db | refs/heads/master | 2021-05-01T07:48:37.733832 | 2021-03-30T04:55:58 | 2021-03-30T04:55:58 | 121,165,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,876 | cpp | //Author: Craig Einstein
#include "../inc/FileReader.hpp"
#include <string.h>
#include <vector>
//constructors
FileReader::FileReader(){
this->file = 0;
this->fileName = 0;
this->fileOption = 0;
this->currentPosition = -1;
this->currentLine = -1;
this->fileOpen = 0;
}
FileReader::FileReader(const char * _fileName){
try{
this->file = fopen(_fileName, "r");
}catch(...){
printf("This file does not exist!\nInitializing empty object instead");
this->file = 0;
this->fileName = 0;
this->currentPosition = -1;
this->currentLine = -1;
this->fileOpen = 0;
return;
}
this->fileName = (char *)_fileName;
this->fileOption = (char *)"r";
this->currentPosition = 0;
this->currentLine = 0;
this->fileOpen = 1;
}
FileReader::FileReader(readOptions _option){
char * option;
this->checkOption(&option, _option);
this->file = 0;
this->fileName = 0;
this->fileOption = option;
this->currentPosition = -1;
this->currentLine = -1;
this->fileOpen = 0;
}
FileReader::FileReader(const char * _fileName, readOptions _option){
char * option;
option = (char *)malloc(sizeof(char) * 1);
switch(_option){
case FILE_READ:
option = (char *)"r";
break;
default:
printf("ERROR: Incorrect read option, defaulting to 'r'\n");
option = (char *)"r";
}
this->file = fopen(_fileName, option);
this->fileOption = option;
this->fileName = (char *)_fileName;
this->currentPosition = 0;
this->currentLine = 0;
this->fileOpen = 1;
}
//read string starting from pos into buf wihtout updating metadata
int FileReader::readFromPos(char ** _buf, long _pos){
long temp = this->currentPosition;
if(fseek(this->file, _pos, SEEK_SET) < 0){
printf("ERROR: This position is not in the file!\n");
return 1;
}
std::vector<char> strArr;
//read characters from line and put them into vector
char c = fgetc(this->file);
while(c != '\0' && c != EOF){
strArr.push_back(c);
if(c == '\n' || c == '\r'){
++this->currentLine;
break;
}
c = fgetc(this->file);
}
if(c == EOF){
return EOF;
}
unsigned long s = strArr.size();
this->currentPosition += (long)s; //update current position
*_buf = (char *)malloc(sizeof(char) * (s + 1));
int i;
for(i = 0; i < strArr.size(); ++i){
*(*_buf + i) = strArr[i];
}
*(*_buf + i) = '\0';
//clears the vector
strArr.clear();
return 0;
}
//reads a specific line in a file
int FileReader::specificReadLine(char ** _buf, long _line){
if(_line < 0){
printf("Please choose a non-negative value!\n");
return 1;
}
//to return to original position
long tempPos = this->currentPosition;
long curLine = this->currentLine;
long linePos = this->getLinePosition(_line);
if(linePos == -1){
return 1;
}
fseek(this->file, linePos, SEEK_SET);
//read string at line
long ret = this->readLine(_buf);
//restore original values
this->currentLine = curLine;
this->currentPosition = tempPos;
return ret;
}
int FileReader::readLine(char ** _buf){
return this->readFromPos(_buf, ftell(this->file));
}
int FileReader::printLine(){
char * buf;
if(this->readLine(&buf) != EOF){
printf("%s", buf);
free(buf);
return 0;
}
return EOF;
}
int FileReader::printString(long _pos){
char * buf;
if(!this->readFromPos(&buf, _pos)){
printf("%s", buf);
free(buf);
}
return 0;
}
int FileReader::printSpecificLine(long _line){
char * buf;
if(!this->specificReadLine(&buf, _line)){
printf("%s", buf);
free(buf);
}
return 0;
}
int FileReader::checkOption(char ** _optBuf, readOptions _option){
*_optBuf = (char *)malloc(sizeof(char) * 2);
switch(_option){
case FILE_READ:
*_optBuf = (char *)"r";
break;
default:
printf("ERROR: Incorrect read option, defaulting to 'r'\n");
*_optBuf = (char *)"r";
}
return 0;
}
| [
"mwallace3@ucmerced.edu"
] | mwallace3@ucmerced.edu |
2c4b72a3d71b98b38e7b0492a9e4341f24288da4 | 484f5c9d1859a3eec52e7434979c273269acef9e | /Code/Engine/Core/VertexUtils.cpp | e0b375c96612ec51aa3f2a7c7c693139602ce8db | [] | no_license | pronaypeddiraju/GGJEngine | f48d186985324d9e9b8aa1a2b772ed9f1fbda1ce | 32a3b9b69bd539b330d784a4d7fc4b0737ba18ac | refs/heads/master | 2020-04-18T20:33:10.470481 | 2019-01-26T22:00:23 | 2019-01-26T22:00:23 | 167,740,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,317 | cpp | #include "Engine/Core/VertexUtils.hpp"
#include "Engine/Math/Vec2.hpp"
#include "Engine/Math/AABB2.hpp"
#include "Engine/Math/Vertex_PCU.hpp"
#include "Engine/Renderer/Rgba.hpp"
#include "Engine/Math/MathUtils.hpp"
void AddVertsForDisc2D( std::vector<Vertex_PCU>& vertexArray, const Vec2& center, float radius, const Rgba& color, int numSides /*= 64 */ )
{
float angleToAdd = 360.f / numSides;
Vec3 baseVector = Vec3(radius, 0.f, 0.f);
Vec3 positionVector;
Rgba vertexColor = color;
for (float i = 0.f; i < 360.f; i += angleToAdd)
{
positionVector = Vec3(center.x, center.y, 0.f);
vertexArray.push_back(Vertex_PCU(positionVector, vertexColor, Vec2(0.f,0.f)));
positionVector = baseVector.GetRotatedAboutZDegrees(i);
positionVector += Vec3(center.x, center.y, 0.f);
vertexArray.push_back(Vertex_PCU(positionVector, vertexColor, Vec2(0.f,0.f)));
positionVector = baseVector.GetRotatedAboutZDegrees(i + angleToAdd);
positionVector += Vec3(center.x, center.y, 0.f);
vertexArray.push_back(Vertex_PCU(positionVector, vertexColor, Vec2(0.f,0.f)));
}
}
void AddVertsForLine2D( std::vector<Vertex_PCU>& vertexArray, const Vec2& start, const Vec2& end, float thickness, const Rgba& color )
{
Vec2 centerToBoundVector = end - start;
centerToBoundVector.SetLength(thickness/2);
Vec2 centreToBoundRotated = centerToBoundVector.GetRotated90Degrees();
//Point 1 (End left)
Vec3 lineCorner = Vec3(end.x, end.y, 0.f) + Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) + Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
//Point 2 (End Right)
lineCorner = Vec3(end.x, end.y, 0.f) + Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) - Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
//Point 3 (Start Left)
lineCorner = Vec3(start.x, start.y, 0.f) - Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) + Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
//We have our first triangle now
//Point 4 (start left)
lineCorner = Vec3(start.x, start.y, 0.f) - Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) + Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
//Point 5 (Start Right)
lineCorner = Vec3(start.x, start.y, 0.f) - Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) - Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
//Point 6 (End right)
lineCorner = Vec3(end.x, end.y, 0.f) + Vec3(centerToBoundVector.x, centerToBoundVector.y, 0.f) - Vec3(centreToBoundRotated.x, centreToBoundRotated.y, 0.f);
vertexArray.push_back(Vertex_PCU(lineCorner, color, Vec2(0.f, 0.f)));
}
void AddVertsForRing2D( std::vector<Vertex_PCU>& vertexArray, const Vec2& center, float radius, float thickness, const Rgba& color, int numSides /*= 64 */ )
{
float angleToAdd = 360.f / numSides;
float rMin = radius - thickness/2;
float rMax = radius + thickness/2;
Vec3 innerPositionVector;
Vec3 outerPositionVector;
Vec3 innerNextPosition;
Vec3 outerNextPosition;
Rgba vertexColor = color;
for (float i = 0.f; i < 360.f; i += angleToAdd)
{
innerPositionVector.x = center.x + rMin * CosDegrees(i);
innerPositionVector.y = center.y + rMin * SinDegrees(i);
innerPositionVector.z = 0.f;
outerPositionVector.x = center.x + rMax * CosDegrees(i);
outerPositionVector.y = center.y + rMax * SinDegrees(i);
outerPositionVector.z = 0.f;
innerNextPosition.x = center.x + rMin * CosDegrees(i + angleToAdd);
innerNextPosition.y = center.y + rMin * SinDegrees(i + angleToAdd);
innerNextPosition.z = 0.f;
outerNextPosition.x = center.x + rMax * CosDegrees(i + angleToAdd);
outerNextPosition.y = center.y + rMax * SinDegrees(i + angleToAdd);
outerNextPosition.z = 0.f;
//Vertex set 1
vertexArray.push_back(Vertex_PCU(innerPositionVector, vertexColor, Vec2(0.f,0.f)));
vertexArray.push_back(Vertex_PCU(outerPositionVector, vertexColor, Vec2(0.f,0.f)));
vertexArray.push_back(Vertex_PCU(outerNextPosition, vertexColor, Vec2(0.f,0.f)));
//Vertex set 2
vertexArray.push_back(Vertex_PCU(outerNextPosition, vertexColor, Vec2(0.f,0.f)));
vertexArray.push_back(Vertex_PCU(innerNextPosition, vertexColor, Vec2(0.f,0.f)));
vertexArray.push_back(Vertex_PCU(innerPositionVector, vertexColor, Vec2(0.f,0.f)));
}
}
void AddVertsForAABB2D( std::vector<Vertex_PCU>& vertexArray, const AABB2& box, const Rgba& color, const Vec2& uvAtMins /*= Vec2(0.f,0.f)*/, const Vec2& uvAtMaxs /*= Vec2(1.f,1.f) */ )
{
Vec3 boxBottomLeft = Vec3(box.m_minBounds.x, box.m_minBounds.y, 0.f);
Vec3 boxBottomRight = Vec3(box.m_maxBounds.x, box.m_minBounds.y, 0.f);
Vec3 boxTopLeft = Vec3(box.m_minBounds.x, box.m_maxBounds.y, 0.f);
Vec3 boxTopRight = Vec3(box.m_maxBounds.x, box.m_maxBounds.y, 0.f);
vertexArray.push_back(Vertex_PCU(boxBottomLeft, color, uvAtMins));
vertexArray.push_back(Vertex_PCU(boxBottomRight, color, Vec2(uvAtMaxs.x, uvAtMins.y)));
vertexArray.push_back(Vertex_PCU(boxTopRight, color, Vec2(uvAtMaxs.x, uvAtMaxs.y)));
vertexArray.push_back(Vertex_PCU(boxBottomLeft, color, uvAtMins));
vertexArray.push_back(Vertex_PCU(boxTopLeft, color, Vec2(uvAtMins.x, uvAtMaxs.y)));
vertexArray.push_back(Vertex_PCU(boxTopRight, color, Vec2(uvAtMaxs.x, uvAtMaxs.y)));
}
//Move a vertex
void TransformVertex2D( Vertex_PCU& vertex, float uniformScale, float rotationDegreesOnZ, const Vec2& translateXY )
{
//For now
UNUSED (vertex);
UNUSED (uniformScale);
UNUSED (rotationDegreesOnZ);
UNUSED (translateXY);
}
//Move an array of vertices
void TransformVertexArray2D( int numVerts, Vertex_PCU* vertices, float uniformScale, float rotationDegreesOnZ, const Vec2& translateXY )
{
for (int i = 0; i < numVerts; i++)
{
//Orientation
vertices[i].m_position = vertices[i].m_position.GetRotatedAboutZDegrees(rotationDegreesOnZ);
//Translation
vertices[i].m_position = vertices[i].m_position + Vec3(translateXY.x, translateXY.y, 0.f);
//Scaling
vertices[i].m_position.x *= uniformScale;
vertices[i].m_position.y *= uniformScale;
}
} | [
"pronay.y2k@gmail.com"
] | pronay.y2k@gmail.com |
2479137e4c0c975f989911572aba488663c3052b | 38e5b5556a1ddac0de51acc225b1dbd820009e4c | /test cases/cmake/3 advanced no dep/main.cpp | 6cc4c0ce30fed7e52bfed1b281912d9d4fdb2492 | [
"Apache-2.0"
] | permissive | talpava/meson | c0df067d115e0552b539bd2611a58b0b49804d5d | 35732dfaa14d30756358797e3dc77f75fe60bf40 | refs/heads/master | 2020-07-16T08:58:11.955464 | 2019-08-29T22:55:34 | 2019-09-01T19:58:33 | 205,759,299 | 1 | 0 | Apache-2.0 | 2019-09-02T02:05:30 | 2019-09-02T02:05:29 | null | UTF-8 | C++ | false | false | 236 | cpp | #include <iostream>
#include <cmMod.hpp>
#include "config.h"
#if CONFIG_OPT != 42
#error "Invalid value of CONFIG_OPT"
#endif
using namespace std;
int main() {
cmModClass obj("Hello");
cout << obj.getStr() << endl;
return 0;
}
| [
"daniel@mensinger-ka.de"
] | daniel@mensinger-ka.de |
84856f92561525c4c71a1eb670517837f23c2171 | e231b75394fcfc6dd6351ae413051a7bef9b2796 | /code/filestorage/include.h | eecc230af5ddf3ef78c608072028aa552663ae75 | [] | no_license | NeonWindWalker/neon_engine | 5a9dfd1258455aedaf9e05dd770e2ece80fbe4e4 | 2bd86014538d3ba04dcd037df17d1e568ee446bf | refs/heads/master | 2016-09-10T00:26:43.494393 | 2014-08-11T21:44:56 | 2014-08-11T21:44:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | h | #pragma once
#include "../base/string.h"
#include "../base/array.h"
#include "../base/smartPointers.h"
#include "../base/bindata.h"
namespace FileStorageLib
{
USING_BASE_LIB
struct FileChangedNotification
{
String name;
boolean exist;
};
class IStorage : public RefCountable
{
public:
virtual ~IStorage(){}
virtual boolean size(uint64& size, ConstString path)=0;
virtual boolean exists(ConstString path){ uint64 s; return size(s, path); }
virtual boolean read(BinaryData& data, ConstString path)=0;
virtual boolean read(BinaryDataProxy& data, ConstString path, uint64 offset)=0;
virtual boolean write(ConstString path, ConstBinaryData data)=0;
virtual boolean append(ConstString path, ConstBinaryData data)=0;
virtual boolean rewrite(ConstString path, uint64 offset, ConstBinaryData data)=0;
virtual boolean erase(ConstString path)=0;
virtual boolean list(Array<String>& files, ConstString path, ConstString basepath = ConstString())=0;
virtual uint ladleOutChangeEvents(Array<FileChangedNotification>& events) { return 0; }
virtual boolean watching(boolean on) { return false; }
virtual boolean watching() { return false; }
virtual boolean execute(ConstString workdir, ConstString path, ConstString params, boolean wait = true) { return false; }
};
extern IStorage* openStorage(ConstString rootPath);
#ifdef __ANDROID__
extern IStorage* openAssetStorage(void* jVM, void* jAssetReader);
#endif
}
| [
"NeonWindWalker@gmail.com"
] | NeonWindWalker@gmail.com |
8f79ef44e942af950f7332959c00601a5c4344b4 | 100976521ef3041b4a554b8d8e2be62afc0dab59 | /src/protocol.h | 7c4e4f23bdbfe3b73f7a71a50402e60a75196d66 | [
"MIT"
] | permissive | omnicoin/eurobit | 63a1d542116ce22fb8d502b31c0047a81fef066d | 30b7ce2c3953f66d54fdc19f8c7423f96b9e482a | refs/heads/master | 2021-01-10T19:30:52.763906 | 2013-11-28T19:21:47 | 2013-11-28T19:21:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,758 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Eurobit developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __cplusplus
# error This header can only be compiled as C++.
#endif
#ifndef __INCLUDED_PROTOCOL_H__
#define __INCLUDED_PROTOCOL_H__
#include "serialize.h"
#include "netbase.h"
#include <string>
#include "uint256.h"
extern bool fTestNet;
// EuroBit default ports are set here
static inline unsigned short GetDefaultPort(const bool testnet = fTestNet)
{
return testnet ? 16969 : 6969;
}
extern unsigned char pchMessageStart[4];
/** Message header.
* (4) message start.
* (12) command.
* (4) size.
* (4) checksum.
*/
class CMessageHeader
{
public:
CMessageHeader();
CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn);
std::string GetCommand() const;
bool IsValid() const;
IMPLEMENT_SERIALIZE
(
READWRITE(FLATDATA(pchMessageStart));
READWRITE(FLATDATA(pchCommand));
READWRITE(nMessageSize);
READWRITE(nChecksum);
)
// TODO: make private (improves encapsulation)
public:
enum {
MESSAGE_START_SIZE=sizeof(::pchMessageStart),
COMMAND_SIZE=12,
MESSAGE_SIZE_SIZE=sizeof(int),
CHECKSUM_SIZE=sizeof(int),
MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE,
CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE,
HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE
};
char pchMessageStart[MESSAGE_START_SIZE];
char pchCommand[COMMAND_SIZE];
unsigned int nMessageSize;
unsigned int nChecksum;
};
/** nServices flags */
enum
{
NODE_NETWORK = (1 << 0),
NODE_BLOOM = (1 << 1),
};
/** A CService with information about it as peer */
class CAddress : public CService
{
public:
CAddress();
explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK);
void Init();
IMPLEMENT_SERIALIZE
(
CAddress* pthis = const_cast<CAddress*>(this);
CService* pip = (CService*)pthis;
if (fRead)
pthis->Init();
if (nType & SER_DISK)
READWRITE(nVersion);
if ((nType & SER_DISK) ||
(nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH)))
READWRITE(nTime);
READWRITE(nServices);
READWRITE(*pip);
)
void print() const;
// TODO: make private (improves encapsulation)
public:
uint64 nServices;
// disk and network only
unsigned int nTime;
// memory only
int64 nLastTry;
};
/** inv message data */
class CInv
{
public:
CInv();
CInv(int typeIn, const uint256& hashIn);
CInv(const std::string& strType, const uint256& hashIn);
IMPLEMENT_SERIALIZE
(
READWRITE(type);
READWRITE(hash);
)
friend bool operator<(const CInv& a, const CInv& b);
bool IsKnownType() const;
const char* GetCommand() const;
std::string ToString() const;
void print() const;
// TODO: make private (improves encapsulation)
public:
int type;
uint256 hash;
};
enum
{
MSG_TX = 1,
MSG_BLOCK,
// Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however,
// MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata.
MSG_FILTERED_BLOCK,
};
#endif // __INCLUDED_PROTOCOL_H__
| [
"pvissers@tarantula.playground.tiv.local"
] | pvissers@tarantula.playground.tiv.local |
94118503e332a895818692b4a4a3fb8a45947a93 | 01f8171fdaf0177123866b9c8706d603e2f3c2e8 | /ui/manipulator_handle.h | 67eb48e64b4587df6b9052422047da2cb468e401 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | ppearson/ImaginePartial | 5176fb31927e09c43ece207dd3ae021274e4bd93 | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | refs/heads/master | 2020-05-21T14:08:50.162787 | 2020-01-22T08:12:23 | 2020-01-22T08:12:23 | 46,647,365 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | /*
Imagine
Copyright 2012 Peter Pearson.
Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---------
*/
#ifndef MANIPULATOR_HANDLE_H
#define MANIPULATOR_HANDLE_H
#include <string>
#include "core/point.h"
namespace Imagine
{
class Object;
class Vector;
class ManipulatorHandle
{
public:
ManipulatorHandle(Object* pObject, const std::string& name) : m_pObject(pObject), m_name(name)
{
}
virtual ~ManipulatorHandle() { }
virtual void draw() = 0;
virtual void applyDelta(Vector& delta) = 0;
virtual Point getCentreOfPosition() = 0;
protected:
Object* m_pObject;
std::string m_name;
};
class Position3DManipulatorHandle : public ManipulatorHandle
{
public:
Position3DManipulatorHandle(Object* pObject, const std::string& name, Vector& pairedValue) : ManipulatorHandle(pObject, name),
m_pairedValue(pairedValue)
{
}
virtual void draw();
virtual void applyDelta(Vector& delta);
virtual Point getCentreOfPosition();
protected:
Vector& m_pairedValue;
};
} // namespace Imagine
#endif // MANIPULATOR_HANDLE_H
| [
"peter.pearson@gmail.com"
] | peter.pearson@gmail.com |
ad9c3d1f48868ca28b4148ba439ebd40148f3446 | 1fcf175c9a2e1fa775634b385eee1b6a7f053cca | /0_LeetCode/balanced-binary-tree.cpp | 69f43d49736b8d2dd7d18c0c8f4ead4a71e6cb0e | [] | no_license | scytulip/MyCollections | e79b791ec24d320ca1fd67ab623dca3e8d10f760 | aab9084553da670386b9a0ab7ffae8817371f14d | refs/heads/master | 2020-04-10T20:31:57.407504 | 2017-07-04T13:15:00 | 2017-07-04T13:15:00 | 20,774,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp | /*
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int countLev(TreeNode *root, bool &bal) //Count level of node
{
int a,b;
if (root==NULL) return 0;
a = countLev(root->left, bal);
b = countLev(root->right, bal);
if (abs(a-b)>=2) bal = false;
return (a>b) ? a+1 : b+1;
}
public:
bool isBalanced(TreeNode *root) {
if (root==NULL) return true;
bool bal = true; // Return value
countLev(root, bal);
return bal;
}
}; | [
"scy.tulip@gmail.com"
] | scy.tulip@gmail.com |
ce3d6d63d23fb7d91b90b78a04e3d366bf4aa6a2 | 5e2a8074ede1de0416ebbd9eaf35bcb01f4d1ad3 | /Classes/ArrowShoot/PauseLayer.h | 30d8e216006c1de68b424f2690018ab6d4258a29 | [] | no_license | TricycleToyCar/Shoot | c250f2abb2105ba19b001bf0ae0df9aaf96e7af1 | b504c9780bcd5eb8f58bfe5d0cbcc4d814dc4507 | refs/heads/master | 2021-01-12T12:31:26.654843 | 2017-04-11T13:27:31 | 2017-04-11T13:27:31 | 72,527,879 | 1 | 1 | null | 2016-12-29T03:06:30 | 2016-11-01T10:53:41 | C++ | UTF-8 | C++ | false | false | 532 | h | #ifndef _PauseLayer_H_
#define _PauseLayer_H_
#include"cocos2d.h"
#include"Observer.h"
using namespace cocos2d;
class PauseLayer :public Layer{
public:
static Scene* CreateScene();
virtual bool init();
void menuAgainCallBack(cocos2d::Ref* pSender);
void menuResumeCallBack(cocos2d::Ref* pSender);
void menuExitCallBack(cocos2d::Ref* pSender);
void addObserver(PauseObserver* observer);
CREATE_FUNC(PauseLayer);
public:
static int step;
private:
Sprite* background;
PauseObserver* _observer;
public:
};
#endif | [
"923038023@qq.com"
] | 923038023@qq.com |
d7ad66ece320d81c9e87228160815ffa730be72a | a8d8c444a01bc7fb1074b8081e5c6f97fde2991b | /Lucro.cpp | 16043cf0eb10d4c23216993cefae9a93bc0c1466 | [] | no_license | willcribeiro/Programas-de-Linguagem | dd825364559950aa9d0c37ea26f71e91e4e00f4e | ca402f17cc85882e8da101473766ab4b271da737 | refs/heads/master | 2021-01-19T01:41:32.731459 | 2017-03-09T03:27:06 | 2017-03-09T03:27:06 | 84,393,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp | #include <iostream>
using namespace std;
int main ()
{
int a=0,b=0,c=0, tam=3; //Contadores para saber quantso produtos estao entre determinados valores
float porcentagem,compra[tam],venda[tam],lucro;
for(int i=0; i<tam; i++)
{
cout<<"entre com o valor de compra"<<endl;
cin>>compra[i];
cout<<"Entre com o valor de venda"<<endl;
cin>>venda[i];
lucro = venda[i]-compra[i]; //formula para o calculo do lucro em cima de cada produto
porcentagem = (lucro/compra[i])*100; //valor em porcentagem que dirá quantos porcento foi o lucro
if(porcentagem<10)
{
a++; //contador para valores menor que 10
}
else if( porcentagem<20)
{
b++; //contador para valores entre 10 e 20
}
else
{
c++; //contador para valores maior que 20
}
}
cout<<"Existe "<<a<<" produtos com lucro menor que 10"<<endl;
cout<<"Existe "<<b<<" produtos com lucro entre 10 e 20"<<endl;
cout<<"Existe "<<c<<" produtos com lucro maior que 20"<<endl;
}
| [
"william-cribeiro@hotmail.com"
] | william-cribeiro@hotmail.com |
c05691a6dcee0155c66b78b84739794ae2dd85de | 22767230dbc02c8dc0fbeb7490a297dd7098f599 | /TShine/src/TSCategoryDef.cc | 70bee226c5d0442b975ccf5bbd3254f870dd8dfb | [] | no_license | diluises/TShine | 85afb0f16708dd0f2397d51894dae1b94000cdbc | 759d9e46c821c51382d62767b9f1283dba3a3f1e | refs/heads/master | 2021-01-16T22:18:20.444606 | 2016-08-12T12:20:11 | 2016-08-12T12:20:11 | 65,551,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,383 | cc | /*
* TSCategoryDef.cc
*
* Created on: Sep 24, 2014
* Author: Silvestro di Luise
* Silvestro.Di.Luise@cern.ch
*
*/
#include <cassert>
#include <iostream>
#include <algorithm>
#include "StringUtils.h"
#include "TSCategoryDef.h"
using std::cout;
using std::endl;
TSCategoryDef::TSCategoryDef()
{
Init();
}
TSCategoryDef::TSCategoryDef(TString name, TString label, TString title)
:TSNamed(name,label,title)
{
Init();
//needed to generate name-hash
SetName(name);
}
TSCategoryDef::~TSCategoryDef() {
}
void TSCategoryDef::Clear(){
fMember.clear();
fMemLabel.clear();
fMemHash.clear();
fNumOfMems=0;
}
void TSCategoryDef::Copy(const TSCategoryDef &other){
/**
*
* Copy Members, clear old members
*
*/
Clear();
for(int i=first_ele_idx; i<other.GetNumOfMembers()+first_ele_idx; ++i){
AddMember(other.GetMemName(i),other.GetMemLabel(i));
}
//fHasAllMems=true;
}
void TSCategoryDef::AddMember(TString name, TString label)
{
if( name.IsWhitespace() ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName(),", Member name is whitespace, not added");
return;
}
for(int i=0;i<fMember.size();++i){
if( fMember.at(i)==name ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName()," Member name already used, not added, name: ",name );
return;
}
}
if( label.IsWhitespace() ) label=name;
fMember.push_back(name);
fMemLabel.push_back(label);
fMemBinLabel.push_back(StringUtils::Name(GetLabel(),":",label));
fMemHash.push_back( name.Hash() );
fNumOfMems = fMember.size();
fCheckCollisions();
fBuildHash();
fBuildHisto();
}
void TSCategoryDef::AddMembers(TString name_list, TString label_list)
{
std::vector<TString> names =StringUtils::Tokenize(name_list,token_sep);
std::vector<TString> labels = StringUtils::Tokenize(label_list,token_sep);
if(names.size() != labels.size() ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName(),", Member and Label list have different sizes");
//set missing labels equal to the member name
if(names.size() > labels.size() ){
int n=labels.size();
for(int i=n;i<names.size();++i){
labels.push_back( names.at(i) );
}
}
}
for(int i=0; i<names.size(); ++i){
AddMember(names.at(i),labels.at(i) );
}
}
void TSCategoryDef::AddMembers(const TSCategoryDef &cat, TString name_list)
{
if( name_list.IsWhitespace() ){
Clear();
Copy(cat);
fHasAllMems = true;
return;
}
std::vector<TString> names = StringUtils::Tokenize(name_list,token_sep);
std::vector<int> idx;
for(int i=first_ele_idx; i<cat.GetNumOfMembers()+first_ele_idx; ++i){
TString mem = cat.GetMemName(i);
for(int j=0;j<names.size();++j){
if( mem==names.at(j) ){
idx.push_back( i );
}
}
}
if( idx.size() == 0){
MSG::ERROR(__FILE__,"::",__FUNCTION__," Invalid member list");
return;
}
Clear();
std::sort(idx.begin(),idx.end());
//cout<<name_list<<" "<<names.size()<<" "<<idx.size()<<endl;
for(int i=0;i<idx.size();++i){
AddMember( cat.GetMemName(idx.at(i)), cat.GetMemLabel( idx.at(i) ) );
}
if( GetHash() == cat.GetHash() ){
fHasAllMems=true;
}
}
int TSCategoryDef::GetCategoryNameHash() const
{
return fNameHash;
}
TString TSCategoryDef::GetMemName(int i) const
{
TString name="";
// if i>=1 && i<=N: i<1 && i>N
// if i>=0 && i<N: i<0 && i>N-1
if( i<first_ele_idx || i>GetNumOfMembers()-1+first_ele_idx ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName()," Member id out of range: ",i);
return name;
}
return fMember[i-first_ele_idx];
}
TString TSCategoryDef::GetMemLabel(int i) const
{
if( i<first_ele_idx || i>GetNumOfMembers()-1+first_ele_idx ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName()," Member id out of range: ",i);
return "";
}
return fMemLabel[i-first_ele_idx];
}
TString TSCategoryDef::GetMemBinLabel(int i) const
{
if( i<first_ele_idx || i>GetNumOfMembers()-1+first_ele_idx ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName()," Member id out of range: ",i);
return "";
}
return fMemBinLabel[i-first_ele_idx];
}
int TSCategoryDef::GetMemHash(int i) const
{
if( i<first_ele_idx || i>GetNumOfMembers()-1+first_ele_idx ){
MSG::WARNING(__FILE__,"::",__FUNCTION__," Category: ",GetName()," Member id out of range: ",i);
return 0;
}
return fMemHash[i-first_ele_idx];
}
bool TSCategoryDef::HasMember(TString name) const
{
for(int i=0; i<fMember.size();++i){
if( fMember[i]==name ) return true;
}
return false;
}
void TSCategoryDef::Init()
{
fHasAllMems=false;
token_sep=":";
//for Getters, start to count
//elements from 0 or 1
//do not touch this (init value=0)
first_ele_idx = 0;
}
void TSCategoryDef::Print() const
{
cout<<"-Category-: "<<GetName()<<" "<<GetLabel()<<" "<<GetTitle()<<endl;
cout<<" Num. of Members: "<<fMember.size()<<endl;
for(int i=0; i<fMember.size(); ++i){
cout<<" "<<i<<" "<<fMember.at(i)<<" "<<fMemLabel.at(i)<<endl;
}
}
void TSCategoryDef::PrintHashTable() const
{
cout<<" "<<endl;
cout<<" Category: "<<GetName()<<" "<<GetLabel()<<" "<<GetTitle()<<endl;
cout<<" Name: "<<GetName()<<" "<<fNameHash<<endl;
cout<<" Num. of Members: "<<fMember.size()<<endl;
for(int i=0; i<fMember.size(); ++i){
cout<<" "<<i+1<<" "<<fMember.at(i)<<" "<<fMemHash.at(i)<<endl;
}
}
void TSCategoryDef::SetName(TString name)
{
TSNamed::SetName(name);
fNameHash = name.Hash();
}
void TSCategoryDef::fBuildHash()
{
/**
*
* Uses only member names
*
*/
TString sum="";
for(int i=0;i<fMember.size();++i){
sum += fMember.at(i);
}
fHash=sum.Hash();
}
void TSCategoryDef::fBuildHisto()
{
fHisto.SetName(StringUtils::Name("hCatCard_",GetName()));
fHisto.SetTitle(GetTitle());
int N = GetNumOfMembers();
fHisto.SetBins(N,0.5,N+0.5);
for(int i=1; i<=N; ++i){
fHisto.GetXaxis()->SetBinLabel(i,GetMemBinLabel(i-1));
}
}
bool TSCategoryDef::fCheckCollisions()
{
/**
*
*
*
*/
for(int i=0;i<fMember.size()-1;++i){
for(int j=i+1;j<fMember.size();++j){
if(fMemHash[i] == fMemHash[j]){
MSG::ERROR(" Two Members Have the Same Hash value:");
MSG::ERROR(" ",fMember[i]," ",fMember[j]);
MSG::ERROR(" ",fMemHash[i]," ",fMemHash[j]);
assert(0);
}
//return false;
}
}
return true;
}
| [
"silv@macpg3arubbia.dyndns.cern.ch"
] | silv@macpg3arubbia.dyndns.cern.ch |
dfbb7780f850c6a30eb9016eb6cd7ba8810a1375 | 884d8fd8d4e2bc5a71852de7131a7a6476bf9c48 | /grid-test/export/macos/obj/src/lime/graphics/opengl/ext/EXT_sRGB.cpp | 627930a84c0f087b21b8f6350aa4e3995e40b630 | [
"Apache-2.0"
] | permissive | VehpuS/learning-haxe-and-haxeflixel | 69655276f504748347decfea66b91a117a722f6c | cb18c074720656797beed7333eeaced2cf323337 | refs/heads/main | 2023-02-16T07:45:59.795832 | 2021-01-07T03:01:46 | 2021-01-07T03:01:46 | 324,458,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 4,778 | cpp | // Generated by Haxe 4.1.4
#include <hxcpp.h>
#ifndef INCLUDED_lime_graphics_opengl_ext_EXT_sRGB
#include <lime/graphics/opengl/ext/EXT_sRGB.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_36f3917dca2bced0_5_new,"lime.graphics.opengl.ext.EXT_sRGB","new",0x9abd0eac,"lime.graphics.opengl.ext.EXT_sRGB.new","lime/graphics/opengl/ext/EXT_sRGB.hx",5,0x7d9f60e2)
namespace lime{
namespace graphics{
namespace opengl{
namespace ext{
void EXT_sRGB_obj::__construct(){
HX_STACKFRAME(&_hx_pos_36f3917dca2bced0_5_new)
HXLINE( 10) this->FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 33296;
HXLINE( 9) this->SRGB8_ALPHA8_EXT = 35907;
HXLINE( 8) this->SRGB_ALPHA_EXT = 35906;
HXLINE( 7) this->SRGB_EXT = 35904;
}
Dynamic EXT_sRGB_obj::__CreateEmpty() { return new EXT_sRGB_obj; }
void *EXT_sRGB_obj::_hx_vtable = 0;
Dynamic EXT_sRGB_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< EXT_sRGB_obj > _hx_result = new EXT_sRGB_obj();
_hx_result->__construct();
return _hx_result;
}
bool EXT_sRGB_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x2a1af842;
}
EXT_sRGB_obj::EXT_sRGB_obj()
{
}
::hx::Val EXT_sRGB_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 8:
if (HX_FIELD_EQ(inName,"SRGB_EXT") ) { return ::hx::Val( SRGB_EXT ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"SRGB_ALPHA_EXT") ) { return ::hx::Val( SRGB_ALPHA_EXT ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"SRGB8_ALPHA8_EXT") ) { return ::hx::Val( SRGB8_ALPHA8_EXT ); }
break;
case 41:
if (HX_FIELD_EQ(inName,"FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT") ) { return ::hx::Val( FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val EXT_sRGB_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 8:
if (HX_FIELD_EQ(inName,"SRGB_EXT") ) { SRGB_EXT=inValue.Cast< int >(); return inValue; }
break;
case 14:
if (HX_FIELD_EQ(inName,"SRGB_ALPHA_EXT") ) { SRGB_ALPHA_EXT=inValue.Cast< int >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"SRGB8_ALPHA8_EXT") ) { SRGB8_ALPHA8_EXT=inValue.Cast< int >(); return inValue; }
break;
case 41:
if (HX_FIELD_EQ(inName,"FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT") ) { FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void EXT_sRGB_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("SRGB_EXT",fc,de,03,80));
outFields->push(HX_("SRGB_ALPHA_EXT",7b,08,a4,45));
outFields->push(HX_("SRGB8_ALPHA8_EXT",1d,4d,56,fa));
outFields->push(HX_("FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT",7b,67,32,0b));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo EXT_sRGB_obj_sMemberStorageInfo[] = {
{::hx::fsInt,(int)offsetof(EXT_sRGB_obj,SRGB_EXT),HX_("SRGB_EXT",fc,de,03,80)},
{::hx::fsInt,(int)offsetof(EXT_sRGB_obj,SRGB_ALPHA_EXT),HX_("SRGB_ALPHA_EXT",7b,08,a4,45)},
{::hx::fsInt,(int)offsetof(EXT_sRGB_obj,SRGB8_ALPHA8_EXT),HX_("SRGB8_ALPHA8_EXT",1d,4d,56,fa)},
{::hx::fsInt,(int)offsetof(EXT_sRGB_obj,FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT),HX_("FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT",7b,67,32,0b)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *EXT_sRGB_obj_sStaticStorageInfo = 0;
#endif
static ::String EXT_sRGB_obj_sMemberFields[] = {
HX_("SRGB_EXT",fc,de,03,80),
HX_("SRGB_ALPHA_EXT",7b,08,a4,45),
HX_("SRGB8_ALPHA8_EXT",1d,4d,56,fa),
HX_("FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT",7b,67,32,0b),
::String(null()) };
::hx::Class EXT_sRGB_obj::__mClass;
void EXT_sRGB_obj::__register()
{
EXT_sRGB_obj _hx_dummy;
EXT_sRGB_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.graphics.opengl.ext.EXT_sRGB",ba,88,15,b6);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(EXT_sRGB_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< EXT_sRGB_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = EXT_sRGB_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = EXT_sRGB_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
} // end namespace ext
| [
"vehpus@gmail.com"
] | vehpus@gmail.com |
3937cd532622239272cde2b97b8f740080ddea67 | d068a42201e8e52b925238a93a36ba8695058363 | /spoj/TRIP.cpp | c6f3e50dc4fb6ae6f79edd900032ba73b9e7ac87 | [] | no_license | nullstring/Codebase | 4f609d49e12e49d69dbfc1aaf2e724f01ad586ab | 0ff88e68ed563a9d2c49c8c302a07bcb0f9260b3 | refs/heads/master | 2021-01-22T10:24:48.632564 | 2013-09-16T06:52:53 | 2013-09-16T06:52:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,840 | cpp | //Harsh Mehta
//library includes
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>//setprecision()
#include <string>//s.length(),s.find("string"),s.find_last_of('char'),s.replace(from_pos,number_of_chars_to_replace,"string to replace"),s.c_str();
#include <cstring>//strcpy(s1,s2),strcmp(s1,s2),strcmpi(s1,s2),strstr(s1,s2) returns address location of s2,strlen()
#include <cmath>//sin,cosec,sinh,acos,sqrt,pow,sort,atoi,atof,atol,ceil,exp,itoa,sprintf,modf
#include <cctype>//isdigit(),isalnum(),isspace(),ispunct()
using namespace std;
// Usefull macros
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> ii;
typedef vector<string> vs;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const int INF = (int) 1e9;
const long long INF64 = (long long) 1e18;
const long double eps = 1e-9;
const long double pi = 3.14159265358979323846;
#define pb push_back
#define mp make_pair
#define sz(a) (int)(a).size()
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define forn(i,n) for (int i=0; i<int(n); ++i)
#define fornd(i,n) for (int i=int(n)-1; i>=0; --i)
#define forab(i,a,b) for (int i=int(a); i<int(b); ++i)
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end()) // for set/map etc
#define cpresent(c,x) (find(all(c),x) != (c).end()) // for vector
/* Old method with TLEs */
//set<string> out;
//int num;
//int max_length;
//char x[85], y[85];
//int lcs(int xi, int yi) {
//if (x[xi] == '\0' || y[yi] == '\0') return 0;
//else if (x[xi] == y[yi]) return lcs(xi+1, yi+1) + 1;
//else return max(lcs(xi+1, yi), lcs(xi, yi+1));
//}
//int get_lcs(string output_str, int xi, int yi) {
//if (x[xi] == '\0' || y[yi] == '\0') {
//if(output_str.length() == max_length)
////output[num++] = output_str;
//out.insert(output_str);
//return 0;
//}
//else if (x[xi] == y[yi]){
////arr[xi][yi] = x[xi];
//output_str += x[xi];
//return get_lcs(output_str, xi+1, yi+1) + 1;
//}
//else return max(get_lcs(output_str, xi+1, yi), get_lcs(output_str, xi, yi+1));
//}
void inline traverseAndAdd(set<string> &s, set<string> &t, string c) {
set<string>::iterator it;
for(it = s.begin(); it != s.end(); it++) t.insert((*it) + c);
}
void lcs(string x, string y) {
int m = x.length(), n = y.length();
int len[m+5][n+5];
set<string> sets[m+5][n+5];
memset(len, 0, sizeof len);
forn(i, m + 1) sets[i][0].insert("");
forn(j, n + 1) sets[0][j].insert("");
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++) {
if(x[i-1] == y[j-1]) {
len[i][j] = len[i-1][j-1] + 1;
string s = "";
traverseAndAdd(sets[i-1][j-1], sets[i][j], s + x[i-1]);
}
else if(len[i-1][j] > len[i][j-1]) {
len[i][j] = len[i-1][j];
traverseAndAdd(sets[i-1][j], sets[i][j], "");
}
else if(len[i-1][j] < len[i][j-1]) {
len[i][j] = len[i][j-1];
traverseAndAdd(sets[i][j-1], sets[i][j], "");
}
else {
len[i][j] = len[i][j-1];
traverseAndAdd(sets[i][j-1], sets[i][j], "");
traverseAndAdd(sets[i-1][j], sets[i][j], "");
}
}
}
set<string> out = sets[m][n];
set<string>::iterator it;
for(it = out.begin(); it != out.end() ; it++) {
printf("%s\n", (*it).c_str());
}
}
/* Prev method with TLEs */
/*
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%s %s", x, y);
//printf("%s %s\n", x, y);
num = 0;
max_length = lcs(0, 0);
//memset(arr, '0', sizeof arr);
get_lcs("", 0, 0);
//set<string> s(output, output + num);
//vector<string> v(all(s));
set<string>::iterator it;
for(it = out.begin(); it != out.end() ; it++) {
printf("%s\n", (*it).c_str());
}
//int i=0,j=0;
//while(x[i]) {
//j = 0;
//while(y[j]) {
//cout << arr[i][j] << " ";
//j++;
//}
//i++;
//cout << endl;
//}
printf("\n");
}
return 0;
}
*/
int main(){
int t;
scanf("%d",&t);
while(t--){
string x, y;
cin >> x >> y;
lcs(x, y);
printf("\n");
}
return 0;
}
| [
"harsh.version.1@gmail.com"
] | harsh.version.1@gmail.com |
5ad1ead4ec1b8855cbba1aa279aec750e5143d78 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_2923_squid-3.3.14.cpp | 71dff548c2915c69dabfa8a16ca5501389e1c441 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | void
HttpRequest::ignoreRange(const char *reason)
{
if (range) {
debugs(73, 3, static_cast<void*>(range) << " for " << reason);
delete range;
range = NULL;
}
// Some callers also reset isRanged but it may not be safe for all callers:
// isRanged is used to determine whether a weak ETag comparison is allowed,
// and that check should not ignore the Range header if it was present.
// TODO: Some callers also delete HDR_RANGE, HDR_REQUEST_RANGE. Should we?
} | [
"993273596@qq.com"
] | 993273596@qq.com |
2537eb83efc7edcdb3d09dd3712c1074eb13e268 | f2e38023f424ea53e270fd93e41e5ec1c8cdb2cf | /include/private/SkColorData.h | aba610eacf6a0714213fd679875ff7eadc48c886 | [
"BSD-3-Clause"
] | permissive | skui-org/skia | 3dc425dba0142390b13dcd91d2a877c604436e1c | 1698b32e63ddc8a06343e1a2f03c2916a08f519e | refs/heads/m85 | 2021-01-22T21:02:53.355312 | 2020-08-16T10:53:34 | 2020-08-16T13:53:35 | 85,350,036 | 23 | 11 | BSD-3-Clause | 2020-09-03T09:23:38 | 2017-03-17T19:59:37 | C++ | UTF-8 | C++ | false | false | 15,497 | h | /*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkColorData_DEFINED
#define SkColorData_DEFINED
#include "include/core/SkColor.h"
#include "include/core/SkColorPriv.h"
#include "include/private/SkNx.h"
#include "include/private/SkTo.h"
////////////////////////////////////////////////////////////////////////////////////////////
// Convert a 16bit pixel to a 32bit pixel
#define SK_R16_BITS 5
#define SK_G16_BITS 6
#define SK_B16_BITS 5
#define SK_R16_SHIFT (SK_B16_BITS + SK_G16_BITS)
#define SK_G16_SHIFT (SK_B16_BITS)
#define SK_B16_SHIFT 0
#define SK_R16_MASK ((1 << SK_R16_BITS) - 1)
#define SK_G16_MASK ((1 << SK_G16_BITS) - 1)
#define SK_B16_MASK ((1 << SK_B16_BITS) - 1)
#define SkGetPackedR16(color) (((unsigned)(color) >> SK_R16_SHIFT) & SK_R16_MASK)
#define SkGetPackedG16(color) (((unsigned)(color) >> SK_G16_SHIFT) & SK_G16_MASK)
#define SkGetPackedB16(color) (((unsigned)(color) >> SK_B16_SHIFT) & SK_B16_MASK)
static inline unsigned SkR16ToR32(unsigned r) {
return (r << (8 - SK_R16_BITS)) | (r >> (2 * SK_R16_BITS - 8));
}
static inline unsigned SkG16ToG32(unsigned g) {
return (g << (8 - SK_G16_BITS)) | (g >> (2 * SK_G16_BITS - 8));
}
static inline unsigned SkB16ToB32(unsigned b) {
return (b << (8 - SK_B16_BITS)) | (b >> (2 * SK_B16_BITS - 8));
}
#define SkPacked16ToR32(c) SkR16ToR32(SkGetPackedR16(c))
#define SkPacked16ToG32(c) SkG16ToG32(SkGetPackedG16(c))
#define SkPacked16ToB32(c) SkB16ToB32(SkGetPackedB16(c))
//////////////////////////////////////////////////////////////////////////////
#define SkASSERT_IS_BYTE(x) SkASSERT(0 == ((x) & ~0xFF))
// Reverse the bytes coorsponding to RED and BLUE in a packed pixels. Note the
// pair of them are in the same 2 slots in both RGBA and BGRA, thus there is
// no need to pass in the colortype to this function.
static inline uint32_t SkSwizzle_RB(uint32_t c) {
static const uint32_t kRBMask = (0xFF << SK_R32_SHIFT) | (0xFF << SK_B32_SHIFT);
unsigned c0 = (c >> SK_R32_SHIFT) & 0xFF;
unsigned c1 = (c >> SK_B32_SHIFT) & 0xFF;
return (c & ~kRBMask) | (c0 << SK_B32_SHIFT) | (c1 << SK_R32_SHIFT);
}
static inline uint32_t SkPackARGB_as_RGBA(U8CPU a, U8CPU r, U8CPU g, U8CPU b) {
SkASSERT_IS_BYTE(a);
SkASSERT_IS_BYTE(r);
SkASSERT_IS_BYTE(g);
SkASSERT_IS_BYTE(b);
return (a << SK_RGBA_A32_SHIFT) | (r << SK_RGBA_R32_SHIFT) |
(g << SK_RGBA_G32_SHIFT) | (b << SK_RGBA_B32_SHIFT);
}
static inline uint32_t SkPackARGB_as_BGRA(U8CPU a, U8CPU r, U8CPU g, U8CPU b) {
SkASSERT_IS_BYTE(a);
SkASSERT_IS_BYTE(r);
SkASSERT_IS_BYTE(g);
SkASSERT_IS_BYTE(b);
return (a << SK_BGRA_A32_SHIFT) | (r << SK_BGRA_R32_SHIFT) |
(g << SK_BGRA_G32_SHIFT) | (b << SK_BGRA_B32_SHIFT);
}
static inline SkPMColor SkSwizzle_RGBA_to_PMColor(uint32_t c) {
#ifdef SK_PMCOLOR_IS_RGBA
return c;
#else
return SkSwizzle_RB(c);
#endif
}
static inline SkPMColor SkSwizzle_BGRA_to_PMColor(uint32_t c) {
#ifdef SK_PMCOLOR_IS_BGRA
return c;
#else
return SkSwizzle_RB(c);
#endif
}
//////////////////////////////////////////////////////////////////////////////
///@{
/** See ITU-R Recommendation BT.709 at http://www.itu.int/rec/R-REC-BT.709/ .*/
#define SK_ITU_BT709_LUM_COEFF_R (0.2126f)
#define SK_ITU_BT709_LUM_COEFF_G (0.7152f)
#define SK_ITU_BT709_LUM_COEFF_B (0.0722f)
///@}
///@{
/** A float value which specifies this channel's contribution to luminance. */
#define SK_LUM_COEFF_R SK_ITU_BT709_LUM_COEFF_R
#define SK_LUM_COEFF_G SK_ITU_BT709_LUM_COEFF_G
#define SK_LUM_COEFF_B SK_ITU_BT709_LUM_COEFF_B
///@}
/** Computes the luminance from the given r, g, and b in accordance with
SK_LUM_COEFF_X. For correct results, r, g, and b should be in linear space.
*/
static inline U8CPU SkComputeLuminance(U8CPU r, U8CPU g, U8CPU b) {
//The following is
//r * SK_LUM_COEFF_R + g * SK_LUM_COEFF_G + b * SK_LUM_COEFF_B
//with SK_LUM_COEFF_X in 1.8 fixed point (rounding adjusted to sum to 256).
return (r * 54 + g * 183 + b * 19) >> 8;
}
/** Calculates 256 - (value * alpha256) / 255 in range [0,256],
* for [0,255] value and [0,256] alpha256.
*/
static inline U16CPU SkAlphaMulInv256(U16CPU value, U16CPU alpha256) {
unsigned prod = 0xFFFF - value * alpha256;
return (prod + (prod >> 8)) >> 8;
}
// The caller may want negative values, so keep all params signed (int)
// so we don't accidentally slip into unsigned math and lose the sign
// extension when we shift (in SkAlphaMul)
static inline int SkAlphaBlend(int src, int dst, int scale256) {
SkASSERT((unsigned)scale256 <= 256);
return dst + SkAlphaMul(src - dst, scale256);
}
static inline uint16_t SkPackRGB16(unsigned r, unsigned g, unsigned b) {
SkASSERT(r <= SK_R16_MASK);
SkASSERT(g <= SK_G16_MASK);
SkASSERT(b <= SK_B16_MASK);
return SkToU16((r << SK_R16_SHIFT) | (g << SK_G16_SHIFT) | (b << SK_B16_SHIFT));
}
#define SK_R16_MASK_IN_PLACE (SK_R16_MASK << SK_R16_SHIFT)
#define SK_G16_MASK_IN_PLACE (SK_G16_MASK << SK_G16_SHIFT)
#define SK_B16_MASK_IN_PLACE (SK_B16_MASK << SK_B16_SHIFT)
///////////////////////////////////////////////////////////////////////////////
/**
* Abstract 4-byte interpolation, implemented on top of SkPMColor
* utility functions. Third parameter controls blending of the first two:
* (src, dst, 0) returns dst
* (src, dst, 0xFF) returns src
* srcWeight is [0..256], unlike SkFourByteInterp which takes [0..255]
*/
static inline SkPMColor SkFourByteInterp256(SkPMColor src, SkPMColor dst,
unsigned scale) {
unsigned a = SkAlphaBlend(SkGetPackedA32(src), SkGetPackedA32(dst), scale);
unsigned r = SkAlphaBlend(SkGetPackedR32(src), SkGetPackedR32(dst), scale);
unsigned g = SkAlphaBlend(SkGetPackedG32(src), SkGetPackedG32(dst), scale);
unsigned b = SkAlphaBlend(SkGetPackedB32(src), SkGetPackedB32(dst), scale);
return SkPackARGB32(a, r, g, b);
}
/**
* Abstract 4-byte interpolation, implemented on top of SkPMColor
* utility functions. Third parameter controls blending of the first two:
* (src, dst, 0) returns dst
* (src, dst, 0xFF) returns src
*/
static inline SkPMColor SkFourByteInterp(SkPMColor src, SkPMColor dst,
U8CPU srcWeight) {
unsigned scale = SkAlpha255To256(srcWeight);
return SkFourByteInterp256(src, dst, scale);
}
/**
* 0xAARRGGBB -> 0x00AA00GG, 0x00RR00BB
*/
static inline void SkSplay(uint32_t color, uint32_t* ag, uint32_t* rb) {
const uint32_t mask = 0x00FF00FF;
*ag = (color >> 8) & mask;
*rb = color & mask;
}
/**
* 0xAARRGGBB -> 0x00AA00GG00RR00BB
* (note, ARGB -> AGRB)
*/
static inline uint64_t SkSplay(uint32_t color) {
const uint32_t mask = 0x00FF00FF;
uint64_t agrb = (color >> 8) & mask; // 0x0000000000AA00GG
agrb <<= 32; // 0x00AA00GG00000000
agrb |= color & mask; // 0x00AA00GG00RR00BB
return agrb;
}
/**
* 0xAAxxGGxx, 0xRRxxBBxx-> 0xAARRGGBB
*/
static inline uint32_t SkUnsplay(uint32_t ag, uint32_t rb) {
const uint32_t mask = 0xFF00FF00;
return (ag & mask) | ((rb & mask) >> 8);
}
/**
* 0xAAxxGGxxRRxxBBxx -> 0xAARRGGBB
* (note, AGRB -> ARGB)
*/
static inline uint32_t SkUnsplay(uint64_t agrb) {
const uint32_t mask = 0xFF00FF00;
return SkPMColor(
((agrb & mask) >> 8) | // 0x00RR00BB
((agrb >> 32) & mask)); // 0xAARRGGBB
}
static inline SkPMColor SkFastFourByteInterp256_32(SkPMColor src, SkPMColor dst, unsigned scale) {
SkASSERT(scale <= 256);
// Two 8-bit blends per two 32-bit registers, with space to make sure the math doesn't collide.
uint32_t src_ag, src_rb, dst_ag, dst_rb;
SkSplay(src, &src_ag, &src_rb);
SkSplay(dst, &dst_ag, &dst_rb);
const uint32_t ret_ag = src_ag * scale + (256 - scale) * dst_ag;
const uint32_t ret_rb = src_rb * scale + (256 - scale) * dst_rb;
return SkUnsplay(ret_ag, ret_rb);
}
static inline SkPMColor SkFastFourByteInterp256_64(SkPMColor src, SkPMColor dst, unsigned scale) {
SkASSERT(scale <= 256);
// Four 8-bit blends in one 64-bit register, with space to make sure the math doesn't collide.
return SkUnsplay(SkSplay(src) * scale + (256-scale) * SkSplay(dst));
}
// TODO(mtklein): Replace slow versions with fast versions, using scale + (scale>>7) everywhere.
/**
* Same as SkFourByteInterp256, but faster.
*/
static inline SkPMColor SkFastFourByteInterp256(SkPMColor src, SkPMColor dst, unsigned scale) {
// On a 64-bit machine, _64 is about 10% faster than _32, but ~40% slower on a 32-bit machine.
if (sizeof(void*) == 4) {
return SkFastFourByteInterp256_32(src, dst, scale);
} else {
return SkFastFourByteInterp256_64(src, dst, scale);
}
}
/**
* Nearly the same as SkFourByteInterp, but faster and a touch more accurate, due to better
* srcWeight scaling to [0, 256].
*/
static inline SkPMColor SkFastFourByteInterp(SkPMColor src,
SkPMColor dst,
U8CPU srcWeight) {
SkASSERT(srcWeight <= 255);
// scale = srcWeight + (srcWeight >> 7) is more accurate than
// scale = srcWeight + 1, but 7% slower
return SkFastFourByteInterp256(src, dst, srcWeight + (srcWeight >> 7));
}
/**
* Interpolates between colors src and dst using [0,256] scale.
*/
static inline SkPMColor SkPMLerp(SkPMColor src, SkPMColor dst, unsigned scale) {
return SkFastFourByteInterp256(src, dst, scale);
}
static inline SkPMColor SkBlendARGB32(SkPMColor src, SkPMColor dst, U8CPU aa) {
SkASSERT((unsigned)aa <= 255);
unsigned src_scale = SkAlpha255To256(aa);
unsigned dst_scale = SkAlphaMulInv256(SkGetPackedA32(src), src_scale);
const uint32_t mask = 0xFF00FF;
uint32_t src_rb = (src & mask) * src_scale;
uint32_t src_ag = ((src >> 8) & mask) * src_scale;
uint32_t dst_rb = (dst & mask) * dst_scale;
uint32_t dst_ag = ((dst >> 8) & mask) * dst_scale;
return (((src_rb + dst_rb) >> 8) & mask) | ((src_ag + dst_ag) & ~mask);
}
////////////////////////////////////////////////////////////////////////////////////////////
// Convert a 32bit pixel to a 16bit pixel (no dither)
#define SkR32ToR16_MACRO(r) ((unsigned)(r) >> (SK_R32_BITS - SK_R16_BITS))
#define SkG32ToG16_MACRO(g) ((unsigned)(g) >> (SK_G32_BITS - SK_G16_BITS))
#define SkB32ToB16_MACRO(b) ((unsigned)(b) >> (SK_B32_BITS - SK_B16_BITS))
#ifdef SK_DEBUG
static inline unsigned SkR32ToR16(unsigned r) {
SkR32Assert(r);
return SkR32ToR16_MACRO(r);
}
static inline unsigned SkG32ToG16(unsigned g) {
SkG32Assert(g);
return SkG32ToG16_MACRO(g);
}
static inline unsigned SkB32ToB16(unsigned b) {
SkB32Assert(b);
return SkB32ToB16_MACRO(b);
}
#else
#define SkR32ToR16(r) SkR32ToR16_MACRO(r)
#define SkG32ToG16(g) SkG32ToG16_MACRO(g)
#define SkB32ToB16(b) SkB32ToB16_MACRO(b)
#endif
static inline U16CPU SkPixel32ToPixel16(SkPMColor c) {
unsigned r = ((c >> (SK_R32_SHIFT + (8 - SK_R16_BITS))) & SK_R16_MASK) << SK_R16_SHIFT;
unsigned g = ((c >> (SK_G32_SHIFT + (8 - SK_G16_BITS))) & SK_G16_MASK) << SK_G16_SHIFT;
unsigned b = ((c >> (SK_B32_SHIFT + (8 - SK_B16_BITS))) & SK_B16_MASK) << SK_B16_SHIFT;
return r | g | b;
}
static inline U16CPU SkPack888ToRGB16(U8CPU r, U8CPU g, U8CPU b) {
return (SkR32ToR16(r) << SK_R16_SHIFT) |
(SkG32ToG16(g) << SK_G16_SHIFT) |
(SkB32ToB16(b) << SK_B16_SHIFT);
}
/////////////////////////////////////////////////////////////////////////////////////////
/* SrcOver the 32bit src color with the 16bit dst, returning a 16bit value
(with dirt in the high 16bits, so caller beware).
*/
static inline U16CPU SkSrcOver32To16(SkPMColor src, uint16_t dst) {
unsigned sr = SkGetPackedR32(src);
unsigned sg = SkGetPackedG32(src);
unsigned sb = SkGetPackedB32(src);
unsigned dr = SkGetPackedR16(dst);
unsigned dg = SkGetPackedG16(dst);
unsigned db = SkGetPackedB16(dst);
unsigned isa = 255 - SkGetPackedA32(src);
dr = (sr + SkMul16ShiftRound(dr, isa, SK_R16_BITS)) >> (8 - SK_R16_BITS);
dg = (sg + SkMul16ShiftRound(dg, isa, SK_G16_BITS)) >> (8 - SK_G16_BITS);
db = (sb + SkMul16ShiftRound(db, isa, SK_B16_BITS)) >> (8 - SK_B16_BITS);
return SkPackRGB16(dr, dg, db);
}
static inline SkColor SkPixel16ToColor(U16CPU src) {
SkASSERT(src == SkToU16(src));
unsigned r = SkPacked16ToR32(src);
unsigned g = SkPacked16ToG32(src);
unsigned b = SkPacked16ToB32(src);
SkASSERT((r >> (8 - SK_R16_BITS)) == SkGetPackedR16(src));
SkASSERT((g >> (8 - SK_G16_BITS)) == SkGetPackedG16(src));
SkASSERT((b >> (8 - SK_B16_BITS)) == SkGetPackedB16(src));
return SkColorSetRGB(r, g, b);
}
///////////////////////////////////////////////////////////////////////////////
typedef uint16_t SkPMColor16;
// Put in OpenGL order (r g b a)
#define SK_A4444_SHIFT 0
#define SK_R4444_SHIFT 12
#define SK_G4444_SHIFT 8
#define SK_B4444_SHIFT 4
static inline U8CPU SkReplicateNibble(unsigned nib) {
SkASSERT(nib <= 0xF);
return (nib << 4) | nib;
}
#define SkGetPackedA4444(c) (((unsigned)(c) >> SK_A4444_SHIFT) & 0xF)
#define SkGetPackedR4444(c) (((unsigned)(c) >> SK_R4444_SHIFT) & 0xF)
#define SkGetPackedG4444(c) (((unsigned)(c) >> SK_G4444_SHIFT) & 0xF)
#define SkGetPackedB4444(c) (((unsigned)(c) >> SK_B4444_SHIFT) & 0xF)
#define SkPacked4444ToA32(c) SkReplicateNibble(SkGetPackedA4444(c))
static inline SkPMColor SkPixel4444ToPixel32(U16CPU c) {
uint32_t d = (SkGetPackedA4444(c) << SK_A32_SHIFT) |
(SkGetPackedR4444(c) << SK_R32_SHIFT) |
(SkGetPackedG4444(c) << SK_G32_SHIFT) |
(SkGetPackedB4444(c) << SK_B32_SHIFT);
return d | (d << 4);
}
static inline Sk4f swizzle_rb(const Sk4f& x) {
return SkNx_shuffle<2, 1, 0, 3>(x);
}
static inline Sk4f swizzle_rb_if_bgra(const Sk4f& x) {
#ifdef SK_PMCOLOR_IS_BGRA
return swizzle_rb(x);
#else
return x;
#endif
}
static inline Sk4f Sk4f_fromL32(uint32_t px) {
return SkNx_cast<float>(Sk4b::Load(&px)) * (1 / 255.0f);
}
static inline uint32_t Sk4f_toL32(const Sk4f& px) {
Sk4f v = px;
#if !defined(SKNX_NO_SIMD) && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
// SkNx_cast<uint8_t, int32_t>() pins, and we don't anticipate giant floats
#elif !defined(SKNX_NO_SIMD) && defined(SK_ARM_HAS_NEON)
// SkNx_cast<uint8_t, int32_t>() pins, and so does Sk4f_round().
#else
// No guarantee of a pin.
v = Sk4f::Max(0, Sk4f::Min(v, 1));
#endif
uint32_t l32;
SkNx_cast<uint8_t>(Sk4f_round(v * 255.0f)).store(&l32);
return l32;
}
using SkPMColor4f = SkRGBA4f<kPremul_SkAlphaType>;
constexpr SkPMColor4f SK_PMColor4fTRANSPARENT = { 0, 0, 0, 0 };
constexpr SkPMColor4f SK_PMColor4fBLACK = { 0, 0, 0, 1 };
constexpr SkPMColor4f SK_PMColor4fWHITE = { 1, 1, 1, 1 };
constexpr SkPMColor4f SK_PMColor4fILLEGAL = { SK_FloatNegativeInfinity,
SK_FloatNegativeInfinity,
SK_FloatNegativeInfinity,
SK_FloatNegativeInfinity };
#endif
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
551482180c61329f4460cfec416e23b4cc6422b2 | 0174e914c9995eed909665cfd8c6ce0b61ac5cc7 | /src/elikos_lib/RCReceiver.cpp | 24839dd60e691a2af8103350ccd2399db4903388 | [
"MIT"
] | permissive | elikos/elikos_main | 302e77ef22e194d9624d27805fea6c40f89759f2 | b6475ed54d8540007115941a58270bb159cc6266 | refs/heads/master | 2021-03-27T10:04:06.651734 | 2018-05-30T00:57:09 | 2018-05-30T00:57:09 | 116,184,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 653 | cpp | //
// Created by tonio on 28/05/15.
//
#include <elikos_lib/RCReceiver.h>
RCReceiver::RCReceiver(ros::NodeHandle nh) : nh_(&nh) {
rc_sub_ = nh_->subscribe(TOPIC_NAMES[mavros_rc_in], 1, &RCReceiver::RCCallback, this);
rc_channels_.reserve(NUMBER_OF_CHANNELS);
}
RCReceiver::~RCReceiver() {}
void RCReceiver::RCCallback(const mavros_msgs::RCInConstPtr rc) {
for (size_t i = 0; i < NUMBER_OF_CHANNELS; i++) {
rc_channels_[i] = rc->channels[i];
}
}
std::vector<unsigned int> RCReceiver::getRCChannels() const {
return rc_channels_;
}
unsigned int RCReceiver::operator[](std::size_t i) const {
return rc_channels_[i];
}
| [
"terriault.eva@gmail.com"
] | terriault.eva@gmail.com |
e8272fa6b50b8124e656a1982369b4fcbbfd01f9 | 9727db9a455cb4967bdb16cf3f8a2e7e459beb54 | /src/files.cpp | 4dd5189d99611061527da44c33a2cce6995f083a | [] | no_license | Arenoros/opengl-experements | 39f705fd09d500593804a888b006e2643b087167 | c90db530dd6bedb1e3cb8f7f8fd9268143940ba1 | refs/heads/master | 2022-03-16T18:31:08.139224 | 2019-11-13T04:39:08 | 2019-11-13T04:40:18 | 221,292,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | cpp | #include "stdafx.h"
#include "api.h"
void test() {
File file("opengl_test.exe", "rb");
uint8_t buf[4*1024];
while(file.read(buf, sizeof(buf))) {
}
}
| [
"arenoros@gmail.com"
] | arenoros@gmail.com |
05022ba379cd48210b445ebc6d7cb7c1e04cc448 | 79a224abb4777f7590165104fe1b2c0d95df1ee1 | /MyVirust/Flu.cpp | 866b73eb8a7bebbdfcbbe67ce55ac0f7eae177f0 | [] | no_license | cntt2-linhhua/C-plus-plus | cb540016fe4f9284f12550517b8183279a3f6dba | ed9b07e9549496620f30ada15c851afd79218a25 | refs/heads/master | 2020-05-31T04:46:59.308661 | 2019-06-20T03:20:18 | 2019-06-20T03:20:18 | 190,106,033 | 0 | 0 | null | 2019-06-20T03:20:19 | 2019-06-04T01:15:18 | C++ | UTF-8 | C++ | false | false | 860 | cpp | #include"Flu.h"
Flu::Flu(){
DoBorn();
InitResistance();
}
Flu::Flu(int m_color)
{
this->m_color=m_color;
}
Flu::Flu(const Flu *flu)
{
*this=*flu;
}
Flu::~Flu()
{
DoDie();
}
void Flu::setM_color(int m_color)
{
this->m_color=m_color;
}
int Flu::GetM_color()
{
return this->m_color;
}
void Flu::DoBorn()
{
this->m_color = rand()%(2-1+1) +1;
}
std::list<MyVirust*> Flu::DoClone()
{
cout<<"Flu was clone "<<endl;
std::list<MyVirust*> vr;
MyVirust *flu = this;
vr.push_back(flu);
return vr;
}
void Flu::DoDie()
{
cout<<endl<<"Flu was die"<<endl;
}
void Flu::InitResistance()
{
if(m_color == FLU_BLUE)
{
m_resistance = 10 + rand()%(5+1);
cout<<"Flu blue was born: "<<m_resistance<<"\n";
}
else
{
m_resistance = 10 + rand()%(10+1);
cout<<"Flu red was born: "<<m_resistance<<"\n";
}
}
| [
"linhhuacntt@gmail.com"
] | linhhuacntt@gmail.com |
31ab613d23297fed8bc9ab13b5af41191d139d23 | 1f8bd66ee7245b41ba99e90e299bff1b4683ad17 | /Aula 11 - Namespace e STL/Competicao.cpp | 5eca63fdc82a5deee60c52274397f8373a3173ef | [] | no_license | CezarGab/PCS3111 | b1b37dc011f215827c892151baf69d88b6e21954 | 086c01789581ca1478e824dfc5bfef5d0ec626d7 | refs/heads/master | 2023-03-22T05:50:05.250756 | 2021-02-22T00:11:22 | 2021-02-22T00:11:22 | 296,947,694 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,371 | cpp | #include "Competicao.h"
#include <stdexcept>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
// Implemente as alteracoes
Competicao::Competicao(string nome) :
nome(nome) {
quantidadeDeEquipes = 0;
equipesVetor = new vector<Equipe*>();
modalidades = new list<Modalidade*>();
}
Competicao::~Competicao() {
delete equipesVetor;
delete[] modalidades;
}
vector<Equipe*>* Competicao::getEquipes() {
return equipesVetor;
}
list<Modalidade*>* Competicao::getModalidades() {
return modalidades;
}
void Competicao::adicionar(Equipe* e) {
// if(quantidadeDeEquipes >= maxValor){
// cout << "Vetor cheio" << endl;
// throw new overflow_error("Equipes esta cheio"); /* Por que não é mais necessario verificar? */
//
// }
for(int i = 0; i < quantidadeDeEquipes; i++) {
if((this->equipesVetor->at(i)) == e){
throw new invalid_argument("Equipe ja adicionada");
}
}
equipesVetor->push_back(e);
quantidadeDeEquipes++;
}
void Competicao::adicionar(Modalidade* m) {
list<Modalidade*>::iterator it = modalidades->begin();
it = find(modalidades->begin(), modalidades->end(), m);
if (it != modalidades->end() ){
throw new invalid_argument("Modalidade ja adicionada");
}
modalidades->push_back(m);
// quantidadeDeModalidades++;
}
| [
"58271805+CezarGab@users.noreply.github.com"
] | 58271805+CezarGab@users.noreply.github.com |
05e2ff4068cb90a8c662442a9f056a7a9c3c00b2 | cf3ef2cb7cbce88fb28b184d05f1286a17c6a09a | /ns-3.19/src/wifi/model/amrr-wifi-manager.cc | fa28482bde15a87e42ea4d09b8f1c06a6aa052bc | [] | no_license | G8XSU/ns3-pmipv6 | 4d318e39a799e2cfa8f8b8948972494d0d4ad559 | cde2da6d2476eaa5ed49580494e2788f62ddb71e | refs/heads/master | 2016-09-05T18:13:23.367968 | 2014-05-06T12:56:14 | 2014-05-06T12:56:14 | 19,178,140 | 6 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 10,778 | cc | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2003,2007 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#include "amrr-wifi-manager.h"
#include "ns3/simulator.h"
#include "ns3/log.h"
#include "ns3/uinteger.h"
#include "ns3/double.h"
#define Min(a,b) ((a < b) ? a : b)
NS_LOG_COMPONENT_DEFINE ("AmrrWifiRemoteStation");
namespace ns3 {
/**
* \brief hold per-remote-station state for AMRR Wifi manager.
*
* This struct extends from WifiRemoteStation struct to hold additional
* information required by the AMRR Wifi manager
*/
struct AmrrWifiRemoteStation : public WifiRemoteStation
{
Time m_nextModeUpdate;
uint32_t m_tx_ok;
uint32_t m_tx_err;
uint32_t m_tx_retr;
uint32_t m_retry;
uint32_t m_txrate;
uint32_t m_successThreshold;
uint32_t m_success;
bool m_recovery;
};
NS_OBJECT_ENSURE_REGISTERED (AmrrWifiManager)
;
TypeId
AmrrWifiManager::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::AmrrWifiManager")
.SetParent<WifiRemoteStationManager> ()
.AddConstructor<AmrrWifiManager> ()
.AddAttribute ("UpdatePeriod",
"The interval between decisions about rate control changes",
TimeValue (Seconds (1.0)),
MakeTimeAccessor (&AmrrWifiManager::m_updatePeriod),
MakeTimeChecker ())
.AddAttribute ("FailureRatio",
"Ratio of minimum erroneous transmissions needed to switch to a lower rate",
DoubleValue (1.0 / 3.0),
MakeDoubleAccessor (&AmrrWifiManager::m_failureRatio),
MakeDoubleChecker<double> (0.0, 1.0))
.AddAttribute ("SuccessRatio",
"Ratio of maximum erroneous transmissions needed to switch to a higher rate",
DoubleValue (1.0 / 10.0),
MakeDoubleAccessor (&AmrrWifiManager::m_successRatio),
MakeDoubleChecker<double> (0.0, 1.0))
.AddAttribute ("MaxSuccessThreshold",
"Maximum number of consecutive success periods needed to switch to a higher rate",
UintegerValue (10),
MakeUintegerAccessor (&AmrrWifiManager::m_maxSuccessThreshold),
MakeUintegerChecker<uint32_t> ())
.AddAttribute ("MinSuccessThreshold",
"Minimum number of consecutive success periods needed to switch to a higher rate",
UintegerValue (1),
MakeUintegerAccessor (&AmrrWifiManager::m_minSuccessThreshold),
MakeUintegerChecker<uint32_t> ())
;
return tid;
}
AmrrWifiManager::AmrrWifiManager ()
{
NS_LOG_FUNCTION (this);
}
WifiRemoteStation *
AmrrWifiManager::DoCreateStation (void) const
{
NS_LOG_FUNCTION (this);
AmrrWifiRemoteStation *station = new AmrrWifiRemoteStation ();
station->m_nextModeUpdate = Simulator::Now () + m_updatePeriod;
station->m_tx_ok = 0;
station->m_tx_err = 0;
station->m_tx_retr = 0;
station->m_retry = 0;
station->m_txrate = 0;
station->m_successThreshold = m_minSuccessThreshold;
station->m_success = 0;
station->m_recovery = false;
return station;
}
void
AmrrWifiManager::DoReportRxOk (WifiRemoteStation *station,
double rxSnr, WifiMode txMode)
{
NS_LOG_FUNCTION (this << station << rxSnr << txMode);
}
void
AmrrWifiManager::DoReportRtsFailed (WifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
}
void
AmrrWifiManager::DoReportDataFailed (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
AmrrWifiRemoteStation *station = (AmrrWifiRemoteStation *)st;
station->m_retry++;
station->m_tx_retr++;
}
void
AmrrWifiManager::DoReportRtsOk (WifiRemoteStation *st,
double ctsSnr, WifiMode ctsMode, double rtsSnr)
{
NS_LOG_FUNCTION (this << st << ctsSnr << ctsMode << rtsSnr);
}
void
AmrrWifiManager::DoReportDataOk (WifiRemoteStation *st,
double ackSnr, WifiMode ackMode, double dataSnr)
{
NS_LOG_FUNCTION (this << st << ackSnr << ackMode << dataSnr);
AmrrWifiRemoteStation *station = (AmrrWifiRemoteStation *)st;
station->m_retry = 0;
station->m_tx_ok++;
}
void
AmrrWifiManager::DoReportFinalRtsFailed (WifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
}
void
AmrrWifiManager::DoReportFinalDataFailed (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
AmrrWifiRemoteStation *station = (AmrrWifiRemoteStation *)st;
station->m_retry = 0;
station->m_tx_err++;
}
bool
AmrrWifiManager::IsMinRate (AmrrWifiRemoteStation *station) const
{
NS_LOG_FUNCTION (this << station);
return (station->m_txrate == 0);
}
bool
AmrrWifiManager::IsMaxRate (AmrrWifiRemoteStation *station) const
{
NS_LOG_FUNCTION (this << station);
NS_ASSERT (station->m_txrate + 1 <= GetNSupported (station));
return (station->m_txrate + 1 == GetNSupported (station));
}
bool
AmrrWifiManager::IsSuccess (AmrrWifiRemoteStation *station) const
{
NS_LOG_FUNCTION (this << station);
return (station->m_tx_retr + station->m_tx_err) < station->m_tx_ok * m_successRatio;
}
bool
AmrrWifiManager::IsFailure (AmrrWifiRemoteStation *station) const
{
NS_LOG_FUNCTION (this << station);
return (station->m_tx_retr + station->m_tx_err) > station->m_tx_ok * m_failureRatio;
}
bool
AmrrWifiManager::IsEnough (AmrrWifiRemoteStation *station) const
{
NS_LOG_FUNCTION (this << station);
return (station->m_tx_retr + station->m_tx_err + station->m_tx_ok) > 10;
}
void
AmrrWifiManager::ResetCnt (AmrrWifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
station->m_tx_ok = 0;
station->m_tx_err = 0;
station->m_tx_retr = 0;
}
void
AmrrWifiManager::IncreaseRate (AmrrWifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
station->m_txrate++;
NS_ASSERT (station->m_txrate < GetNSupported (station));
}
void
AmrrWifiManager::DecreaseRate (AmrrWifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
station->m_txrate--;
}
void
AmrrWifiManager::UpdateMode (AmrrWifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
if (Simulator::Now () < station->m_nextModeUpdate)
{
return;
}
station->m_nextModeUpdate = Simulator::Now () + m_updatePeriod;
NS_LOG_DEBUG ("Update");
bool needChange = false;
if (IsSuccess (station) && IsEnough (station))
{
station->m_success++;
NS_LOG_DEBUG ("++ success=" << station->m_success << " successThreshold=" << station->m_successThreshold <<
" tx_ok=" << station->m_tx_ok << " tx_err=" << station->m_tx_err << " tx_retr=" << station->m_tx_retr <<
" rate=" << station->m_txrate << " n-supported-rates=" << GetNSupported (station));
if (station->m_success >= station->m_successThreshold
&& !IsMaxRate (station))
{
station->m_recovery = true;
station->m_success = 0;
IncreaseRate (station);
needChange = true;
}
else
{
station->m_recovery = false;
}
}
else if (IsFailure (station))
{
station->m_success = 0;
NS_LOG_DEBUG ("-- success=" << station->m_success << " successThreshold=" << station->m_successThreshold <<
" tx_ok=" << station->m_tx_ok << " tx_err=" << station->m_tx_err << " tx_retr=" << station->m_tx_retr <<
" rate=" << station->m_txrate << " n-supported-rates=" << GetNSupported (station));
if (!IsMinRate (station))
{
if (station->m_recovery)
{
station->m_successThreshold *= 2;
station->m_successThreshold = std::min (station->m_successThreshold,
m_maxSuccessThreshold);
}
else
{
station->m_successThreshold = m_minSuccessThreshold;
}
station->m_recovery = false;
DecreaseRate (station);
needChange = true;
}
else
{
station->m_recovery = false;
}
}
if (IsEnough (station) || needChange)
{
NS_LOG_DEBUG ("Reset");
ResetCnt (station);
}
}
WifiTxVector
AmrrWifiManager::DoGetDataTxVector (WifiRemoteStation *st, uint32_t size)
{
NS_LOG_FUNCTION (this << st << size);
AmrrWifiRemoteStation *station = (AmrrWifiRemoteStation *)st;
UpdateMode (station);
NS_ASSERT (station->m_txrate < GetNSupported (station));
uint32_t rateIndex;
if (station->m_retry < 1)
{
rateIndex = station->m_txrate;
}
else if (station->m_retry < 2)
{
if (station->m_txrate > 0)
{
rateIndex = station->m_txrate - 1;
}
else
{
rateIndex = station->m_txrate;
}
}
else if (station->m_retry < 3)
{
if (station->m_txrate > 1)
{
rateIndex = station->m_txrate - 2;
}
else
{
rateIndex = station->m_txrate;
}
}
else
{
if (station->m_txrate > 2)
{
rateIndex = station->m_txrate - 3;
}
else
{
rateIndex = station->m_txrate;
}
}
return WifiTxVector (GetSupported (station, rateIndex), GetDefaultTxPowerLevel (), GetLongRetryCount (station), GetShortGuardInterval (station), Min (GetNumberOfReceiveAntennas (station),GetNumberOfTransmitAntennas()), GetNumberOfTransmitAntennas (station), GetStbc (station));
}
WifiTxVector
AmrrWifiManager::DoGetRtsTxVector (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
AmrrWifiRemoteStation *station = (AmrrWifiRemoteStation *)st;
UpdateMode (station);
/// \todo can we implement something smarter ?
return WifiTxVector (GetSupported (station, 0), GetDefaultTxPowerLevel (), GetLongRetryCount (station), GetShortGuardInterval (station), Min (GetNumberOfReceiveAntennas (station),GetNumberOfTransmitAntennas()), GetNumberOfTransmitAntennas (station), GetStbc (station));
}
bool
AmrrWifiManager::IsLowLatency (void) const
{
NS_LOG_FUNCTION (this);
return true;
}
} // namespace ns3
| [
"g8x000@gmail.com"
] | g8x000@gmail.com |
82e0ea22131ba4245d06d348785e7d2bd7112883 | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/train/cpp/9aa644f743b1b86bd83e0b110267cc39bdfef897bwm_menu.cxx | 9aa644f743b1b86bd83e0b110267cc39bdfef897 | [
"MIT"
] | permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | C++ | false | false | 2,099 | cxx | #include "bwm_menu.h"
#include "bwm_command_macros.h"
vgui_menu bwm_menu::add_to_menu (vgui_menu& top_menu)
{
vgui_menu load_menu;
load_menu.add("Create Site", create_site);
load_menu.add("Edit Site", edit_site);
load_menu.add("Load Site..." , load_site);
load_menu.add("Save Site..." , save_site);
load_menu.add("Load VideoSite..." , load_video_site);
load_menu.add("Save VideoSite..." , save_video_site);
load_menu.add("Load Depth Scene..." , load_depth_map_scene);
MENU_LOAD_TABLEAU("Load Image Tableau...", "bwm_tableau_img", load_menu);
load_menu.add("Load Video Tableau...", load_video_tableau);
MENU_LOAD_TABLEAU("Load Camera Tableau...", "bwm_tableau_rat_cam", load_menu);
MENU_LOAD_TABLEAU("Load 3D Tableau...", "bwm_tableau_coin3d", load_menu);
MENU_LOAD_TABLEAU("Load Proj2D Tableau...", "bwm_tableau_proj2d", load_menu);
MENU_LOAD_TABLEAU("Load LIDAR Tableau...", "bwm_tableau_lidar", load_menu);
load_menu.add("Remove Selected Tableau..." , remove_tableau);
load_menu.add("Zoom to Fit..." , zoom_to_fit);
load_menu.add("Scroll to Point..." , scroll_to_point);
load_menu.add("Save adjusted cameras..." , save_cameras);
load_menu.add("Exit..." , exit);
top_menu.add("SITE ", load_menu);
vgui_menu file_menu;
file_menu.add("Load shape file (.shp)", load_shape_file);
file_menu.add("Save (ply)", save_ply);
file_menu.add("Save (gml)", save_gml);
file_menu.add("Save (kml)", save_kml);
file_menu.add("Save (kml collada)", save_kml_collada);
file_menu.add("Save (x3d)", save_x3d);
file_menu.add("Save Video World Points (vrml)", save_world_points_vrml);
file_menu.add("Save Video Cameras (vrml)", save_video_cameras_vrml);
file_menu.add("Save Video Cams and Points (vrml)", save_video_cams_and_world_pts_vrml);
file_menu.add("Save World Params", save_world_params);
top_menu.add("FILE ", file_menu);
vgui_menu corr_menu;
vgui_menu process_menu;
MENU_MENU_ADD_PROCESS("correspondence", corr_menu);
process_menu.add("Correspondences",corr_menu);
top_menu.add("PROCESSES ", process_menu);
return top_menu;
}
| [
"aliostad+github@gmail.com"
] | aliostad+github@gmail.com |
cf9af92e12c700f32dd99593d6842d7e8c46d83f | 86acd48da71f0faa0642c99173b9cf31b51ca5e5 | /examples/B. Modul IO Aktif Low/03. Gerbang Logika/O6_Logika_Xor/O6_Logika_Xor.ino | 31ef05e15882b03ecfc19836f341b5d57f85359e | [] | no_license | dianartanto/PLCArduinoku | 3b48af462f567247a768d72cf544f5637c12649d | 968e515f429659de1d180aaea2cb3348b87d8893 | refs/heads/master | 2021-01-19T08:59:28.804031 | 2015-04-14T05:52:40 | 2015-04-14T05:52:40 | 33,913,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | ino | /*
1.Rangkaian:
Modul Input Output Aktif Low.
Kaki Input : X1, X2 (kaki A0 dan A1 Arduino)
Kaki Output : Y1 (kaki D2 Arduino)
Alat Input : Tombol 2x
Alat Output : Relay 1x
2.Program:
X1 X2 Y1
1 ||-------]/[--------------] [------+-------( )-------||
|| X1 X2 | ||
||-------] [--------------]/[------+ ||
Ketika tombol di X1 ditekan dan tombol di X2 dilepas,
atau ketika tombol di X1 dilepas dan tombol di X2 ditekan,
maka Relay di Y1 hidup. Di luar kondisi itu maka Relay di Y1 mati
*/
#include<PLCArduinoku.h>
unsigned int RX1, RX2, RY1;
void setup() {
setupku();
outHigh();
}
void loop() {
//bagian input
inNot(X1); out(RX1);
inNot(X2); out(RX2);
//bagian proses
in(RX1); xorBit(RX2); out(RY1);
//bagian output
in(RY1); outNot(Y1);
}
| [
"dian.artanto@gmail.com"
] | dian.artanto@gmail.com |
fd0f29c05ae9f1a2c4e60c503cdde61c1e2c62ec | 5d2244a052d57885be20c496184c2f4539880d25 | /t4/svg.cpp | 1092329f9d61bd93986e36b2b930ec101d1ead6b | [] | no_license | capmayer/paradigmas | 54aaa36e508a773c4d3678b4a585a85bf5d4c9c9 | 853dfa6d57b0818c0fc0dc74b40e75fc9b5a5b45 | refs/heads/master | 2020-05-24T10:46:39.041776 | 2017-07-06T17:46:06 | 2017-07-06T17:46:06 | 84,849,148 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,427 | cpp | #include <cmath>
#include <iostream>
#include <sstream>
const double PI = 3.14159;
class Point
{
private:
double x;
double y;
public:
Point()
{
x = 0;
y = 0;
}
Point(double x, double y)
{
this->x = x;
this->y = y;
}
void move(double dx, double dy)
{
this->x += dx;
this->y += dy;
}
double distanceTo(Point d)
{
return std::sqrt((pow((x - d.getX()), 2) + pow((y - d.getY()),2)));
}
double distanceTo(Point* d)
{
return std::sqrt((pow((x - d->getX()), 2) + pow((y - d->getY()),2)));
}
int getX()
{
return x;
}
int getY()
{
return y;
}
std::string svgLine(Point *d){
std::stringstream str;
str << "<line x1='" << x << "' y1='" << y << "' x2='" << d->getX() << "' y2='" << d->getY() << "' style='stroke:rgb(255,255,255);stroke-width:2' />";
return str.str();
}
std::string svgLine(Point d){
std::stringstream str;
str << "<line x1='" << x << "' y1='" << y << "' x2='" << d.getX() << "' y2='" << d.getY() << "' style='stroke:rgb(255,255,255);stroke-width:2' />";
return str.str();
}
};
class Circle {
private:
Point p;
double r;
public:
Circle(){
r = 0.0;
}
Circle(int x, int y, int r) : p(x, y){
this->r = r;
}
Point getPoint(){
return p;
}
double area() {
return PI * r * r;
}
double getR(){
return r;
}
double distanceTo(Circle c)
{
return p.distanceTo(c.getPoint()) - c.getR() - r;
}
double distanceTo(Circle* c)
{
return std::sqrt((pow((p.getX() - c->getPoint().getX()), 2) + pow((p.getY() - c->getPoint().getY()),2)));
}
std::string svgCircle(){
std::stringstream str;
str << "<circle cx='" << p.getX() << "' cy='" << p.getY() <<"' r='" << r <<"' stroke='black' stroke-width='3' fill='red' />";
return str.str();
}
};
int main() {
Circle* circles [5];
std::string svgOut = "<svg height='100' width='300'>";
for(int x=0; x<5; x++)
{
circles[x] = new Circle(x*40, 50 , x*3 + 5);
svgOut += circles[x]->svgCircle();
}
for(int x=0; x<4; x++)
{
svgOut += circles[x]->getPoint().svgLine(circles[x+1]->getPoint());
}
svgOut+= "</svg>";
std::cout << svgOut << std::endl;
}
| [
"henriqmayer@gmail.com"
] | henriqmayer@gmail.com |
93ed7ae5396dc0469288f62777fc5f5618a6dfcc | ef15a4a77b6e1fbb3220a5047885ba7568a80b74 | /src/logger/Logger/detail/LoggerImpl.hpp | a91284a417edf4b1d6392e927be96db3be3d2172 | [] | no_license | el-bart/ACARM-ng | 22ad5a40dc90a2239206f18dacbd4329ff8377de | de277af4b1c54e52ad96cbe4e1f574bae01b507d | refs/heads/master | 2020-12-27T09:24:14.591095 | 2014-01-28T19:24:34 | 2014-01-28T19:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,248 | hpp | /*
* LoggerImpl.hpp
*
*/
#ifndef INCLUDE_LOGGER_DETAIL_LOGGERIMPL_HPP_FILE
#define INCLUDE_LOGGER_DETAIL_LOGGERIMPL_HPP_FILE
/* public header */
#include "Logger/detail/LogNULLStream.hpp"
#include "Logger/detail/LogStream.hpp"
namespace Logger
{
namespace detail
{
// in debug mode, for gcc use pretty function. otherwise just standard __func__
// that's always present (C99 standard) and much less verbose (especially for templates)
#if defined(__GNUC__) && !defined(NDEBUG)
# define PRETTY_FUNCTION_WRAPPER __PRETTY_FUNCTION__
#else
# define PRETTY_FUNCTION_WRAPPER __func__
#endif
// log given message to given facility
#define LOGMSG_PRI_INTERNAL_IMPLEMENTATION(where, msg) \
do \
{ \
(where)(__FILE__, PRETTY_FUNCTION_WRAPPER, __LINE__, (msg)); \
} \
while(false)
// log message in stream-like manier
#define LOGMSG_PRI_INTERNAL_STREAM_IMPLEMENTATION(id, method) \
::Logger::detail::LogStream< &::Logger::Node::method >( (id), __FILE__, PRETTY_FUNCTION_WRAPPER, __LINE__ )
// debug logs are to be compiled-out from code
#ifndef NDEBUG
// log given message to given facility - debug macro
#define LOGMSG_PRI_INTERNAL_IMPLEMENTATION_DEBUG(where, msg) \
LOGMSG_PRI_INTERNAL_IMPLEMENTATION(where, msg)
// log message in stream-like manier - debug macro
#define LOGMSG_PRI_INTERNAL_STREAM_IMPLEMENTATION_DEBUG(id, method) \
LOGMSG_PRI_INTERNAL_STREAM_IMPLEMENTATION(id, method)
#else // else: NDEBUG
// log given message to given facility - debug macro
// note: do{}while(false) must stay here to prevent supprises in construcitons
// like if(...) LOG(); doSth();
#define LOGMSG_PRI_INTERNAL_IMPLEMENTATION_DEBUG(where, msg) \
do \
{ \
} \
while(false)
// log message in stream-like manier - debug macro
// note: while(false) at the begining of the strucutre gives good results giving
// obvious clue to the compiler, that this part of code should be compiled-out
// therefore skipping computation of log messages arguments.
#define LOGMSG_PRI_INTERNAL_STREAM_IMPLEMENTATION_DEBUG(id, method) \
while(false) ::Logger::detail::LogNULLStream()
#endif // NDEBUG
} // namespace detail
} // namespace Logger
#endif
| [
"bartosz.szurgot@pwr.wroc.pl"
] | bartosz.szurgot@pwr.wroc.pl |
d06d4706f18c7869d8e5c715048918f36a0021fd | 533621231aa7233de90e29c31ae721e97c29fb8b | /Codeforces/Educational/Educational Codeforces Round 89 (Rated for Div. 2)/1366B.cpp | 1d58b00aab1fd127894afcf434526a601b7a806f | [] | no_license | NatanGarcias/Competitive-Programming | 00ad96389d24040b9d69eed04af04e8da0a4feb6 | ffb7a156352432c6a246c0024522aa97b5a5f2b8 | refs/heads/master | 2021-11-29T16:35:36.476318 | 2021-08-21T00:21:08 | 2021-08-21T00:21:08 | 238,455,629 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | cpp | #include<bits/stdc++.h>
using namespace std;
template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi = v.begin(); vi != v.end(); ++vi) { if (vi != v.begin()) os << ", "; os << *vi; } os << "}"; return os; }
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; }
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
#define optimize ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define endl "\n"
#define fi first
#define se second
#define pb push_back
#define sz(x) (ll)(x.size())
#define all(x) x.begin(),x.end()
#define FOR(x,a,n) for(int x= (int)(a);(x) < int(n);(x)++)
#define ms(x,a) memset(x,a,sizeof(x))
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
#define mod 1000000007
#define MAXN 200010
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll T,N,M,K;
void solve(){
ll ans = 1;
ll menor = K, maior = K;
FOR(i,0,M){
ll a,b;
cin >> a >> b;
if(a >= menor && b <= maior) continue;
if(a <= menor && b >= maior){
ans += abs(a-menor);
menor = min(a,menor);
ans += abs(b-maior);
maior = max(b,maior);
}
else if(a <= menor && b >= menor){
ans += abs(a-menor);
menor = min(a,menor);
}else if(a <= maior && b >= maior){
ans += abs(b-maior);
maior = max(b,maior);
}
}
cout << ans << endl;
}
int main(){
cin >> T;
while(T--){
cin >> N >> K >> M;
solve();
}
return 0;
} | [
"natans.garcias@gmail.com"
] | natans.garcias@gmail.com |
2c9fe8c785472bf4bfc554a36c8efe1657f6e289 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_function_852.cpp | 53d1ab94187b4761e30a46c11c55a779241fbfe6 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,485 | cpp | static void link_idev_data(void)
{
int32 cur, from, to, start;
alloc_pool_t hlink_pool;
alloc_pool_t idev_pool = the_file_list->hlink_pool;
hlink_pool = pool_create(128 * 1024, sizeof (struct hlink),
out_of_memory, POOL_INTERN);
for (from = to = 0; from < hlink_count; from++) {
start = from;
while (1) {
cur = hlink_list[from];
if (from == hlink_count-1
|| !LINKED(cur, hlink_list[from+1]))
break;
pool_free(idev_pool, 0, FPTR(cur)->link_u.idev);
FPTR(cur)->link_u.links = pool_talloc(hlink_pool,
struct hlink, 1, "hlink_list");
FPTR(cur)->F_HLINDEX = to;
FPTR(cur)->F_NEXT = hlink_list[++from];
FPTR(cur)->link_u.links->link_dest_used = 0;
}
pool_free(idev_pool, 0, FPTR(cur)->link_u.idev);
if (from > start) {
int head = hlink_list[start];
FPTR(cur)->link_u.links = pool_talloc(hlink_pool,
struct hlink, 1, "hlink_list");
FPTR(head)->flags |= FLAG_HLINK_TOL;
FPTR(cur)->F_HLINDEX = to;
FPTR(cur)->F_NEXT = head;
FPTR(cur)->flags |= FLAG_HLINK_EOL;
FPTR(cur)->link_u.links->link_dest_used = 0;
hlink_list[to++] = head;
} else
FPTR(cur)->link_u.links = NULL;
}
if (!to) {
free(hlink_list);
hlink_list = NULL;
pool_destroy(hlink_pool);
hlink_pool = NULL;
} else {
hlink_count = to;
hlink_list = realloc_array(hlink_list, int32, hlink_count);
if (!hlink_list)
out_of_memory("init_hard_links");
}
the_file_list->hlink_pool = hlink_pool;
pool_destroy(idev_pool);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
ff3d6e1a8c3534c3df164ae3ba601337ffb1f0c0 | 09fc6f323ed5388f1f6a033b79ee09d21f074408 | /srcs/cgi/private.cpp | d679f7a2ce69177bcb2b87c99ac59155e4e5f6ef | [] | no_license | jeromelarose/webserv | e3988208ebd2e83a777ce2bd58cc9a5ad5f6a24d | d74a6cd4d22d670421d718511a31127229c6a86e | refs/heads/master | 2023-08-22T10:45:03.034697 | 2021-08-04T14:45:51 | 2021-08-04T14:45:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,681 | cpp | #include "cgi.hpp"
char **cgi::init_env(const request &req, const parser &pars, const std::string &path)
{
std::map<std::string, std::string> env_tmp;
std::string root = pars.get_block("server").conf.find("root")->second[0];
env_tmp["HTTP_X_SECRET_HEADER_FOR_TEST"] = req.get_secret();
env_tmp["AUTH_TYPE"] = req.get_auth_type();
env_tmp["CONTENT_LENGTH"] = req.get_content_length();
env_tmp["CONTENT_TYPE"] = req.get_content_type();
env_tmp["GATEWAY_INTERFACE"] = GATEWAY_INTERFACE;
env_tmp["PATH_INFO"] = req.get_uri();
env_tmp["PATH_TRANSLATED"] = path;
env_tmp["QUERY_STRING"] = req.get_query();
env_tmp["REMOTE_ADDR"] = req.get_host();
env_tmp["REMOTE_IDENT"] = req.get_user();
env_tmp["REMOTE_USER"] = req.get_user(); // user id
env_tmp["REQUEST_METHOD"] = req.get_method();
env_tmp["REQUEST_URI"] = req.get_uri();
env_tmp["SCRIPT_NAME"] = pars.get_block("cgi", get_extension(path)).conf.find("script_name")->second[0];
env_tmp["SEVER_NAME"] = pars.get_block("server").name;
env_tmp["SERVER_PORT"] = pars.get_block("server").conf.find("listen")->second[0];
env_tmp["SERVER_PROTOCOL"] = HTTP_VERSION;
env_tmp["SERVER_SOFTWARE"] = WEBSERV;
char **env = new char*[env_tmp.size() + 1];
int j = 0;
for (std::map<std::string, std::string>::const_iterator it = env_tmp.begin(); it != env_tmp.end(); ++it)
{
std::string element = it->first + "=" + it->second;
env[j] = new char[element.size() + 1];
env[j] = strcpy(env[j], (const char*)element.c_str());
j++;
}
env[j] = NULL;
return env;
}
void cgi::clear(char **env)
{
int i = 0;
if (env)
{
while (env[i])
delete[](env[i++]);
delete[](env);
env = NULL;
}
}
void cgi::son(long fdin, long fdout, FILE* file_in, FILE* file_out, int save_in, int save_out, const char *script_name, char **env)
{
char **nll = NULL;
dup2(fdout, STDOUT_FILENO);
dup2(fdin, STDIN_FILENO);
execve(script_name, nll, env);
close(fdin);
fclose(file_in);
fclose(file_out);
dup2(save_in, STDIN_FILENO);
dup2(save_out, STDOUT_FILENO);
close(save_in);
close(save_out);
clear(env);
std::cerr << "Execve crashed." << std::endl;
throw std::string("quit");
}
void cgi::father(long fdout, std::string &new_body)
{
waitpid(-1, NULL, 0);
lseek(fdout, 0, SEEK_SET);
char buffer[2048];
int ret = 1;
while (ret > 0)
{
memset(buffer, 0, 2048);
ret = read(fdout, buffer, 2048 - 1);
new_body += buffer;
}
if (!new_body.size())
new_body = "500";
close(fdout);
}
std::string cgi::exec(char **env, const request &req, const parser &pars, const std::string &path)
{
pid_t pid;
int save_in, save_out;
std::string new_body;
errno = 0;
// save stdin and stdout
save_in = dup(STDIN_FILENO);
save_out = dup(STDOUT_FILENO);
FILE* file_in = tmpfile();
FILE* file_out = tmpfile();
long fdin;
long fdout;
fdin = fileno(file_in);
fdout = fileno(file_out);
if (req.get_body().size() > 0)
{
if (write(fdin, req.get_body().c_str(), req.get_body().size()) < 0)
{
std::cout << strerror(errno) << std::endl;
sleep(10);
}
lseek(fdin, 0, SEEK_SET);
}
std::cout << "start cgi" << std::endl;
pid = fork();
if (pid == -1)
{
close(fdin);
fclose(file_in);
close(fdout);
fclose(file_out);
std::cerr << "Fork crashed." << std::endl;
}
else if (pid == 0)
{
son(fdin, fdout, file_in, file_out, save_in, save_out, pars.get_block("cgi", get_extension(path)).conf.find("script_name")->second[0].c_str(), env);
}
else
{
father(fdout, new_body);
}
close(fdin);
fclose(file_in);
fclose(file_out);
dup2(save_in, STDIN_FILENO);
dup2(save_out, STDOUT_FILENO);
close(save_in);
close(save_out);
clear(env);
return new_body;
} | [
"jelarose@student.42.fr"
] | jelarose@student.42.fr |
822d644d20fb1ecabf83a1f37755796f8cb3733f | 87c6d2695e5018b80b42ac58f51cd16a5f559918 | /lab4/interpreter.h | 652372b38a471f401cbd280eb5df5a3a8d02734b | [] | no_license | neelbhuva/FPL | 9abffa721bda683c5e745a177fd0bfceff70e464 | ebe10e580221c475a2adde1000f09998a9b0568e | refs/heads/master | 2021-01-25T05:45:02.367441 | 2017-04-12T22:16:39 | 2017-04-12T22:16:39 | 80,678,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | h | /* This code is written by Neelkumar Shailesh Bhuva
as part of CSE 6341 (Foundations of Programming Languages)
project at the Ohio State University.
*/
#ifndef INTERPRETER_H
#define INTERPRETER_H
#include <iostream>
#include <string>
#include <vector>
#include "binaryTree.h"
#include <map>
#if 0
struct dlist{
string func_name;
vector<string> formal_param;
tree_node* func_body;
};
#endif
using namespace std;
void printmap(map<string,tree_node*>);
tree_node* getFuncBody(string);
bool inalist(string,map<string,tree_node*>);
tree_node* getFormalParamValue(string,map<string,tree_node*>);
void printlast(tree_node*);
//extern vector<struct dlist*> dl;
class Interpreter{
public:
int flag;
//dlist is used to store information about DEFUN expression
//It stores formal parameter list, function name and function body
//struct dlist d_list;
//dl is the list of all such dlist throughout the program
//static struct dlist* dl[100];
//static int i;
public:
int length(tree_node*);
tree_node* car(tree_node* s);
tree_node* cdr(tree_node* s);
tree_node* cons(tree_node* s1, tree_node* s2);
tree_node* atom(tree_node* s);
tree_node* INT(tree_node* s);
tree_node* null(tree_node* s);
tree_node* eq(tree_node* s1,tree_node* s2);
tree_node* plus(tree_node* s1,tree_node* s2);
tree_node* minus(tree_node* s1,tree_node* s2);
tree_node* times(tree_node* s1,tree_node* s2);
tree_node* less(tree_node* s1,tree_node* s2);
tree_node* greater(tree_node* s1,tree_node* s2);
tree_node* createNode(string,tree_node*,tree_node*);
tree_node* eval(tree_node*,map<string,tree_node*> = map<string,tree_node*>());
bool isNumeric(tree_node*);
bool in_array(const string&, const vector<string>&);
void printSExpression(tree_node*);
bool isList(tree_node*);
void inorderPrint(tree_node*);
bool allListOfLengthTwo(tree_node*);
tree_node* COND_eval(tree_node*,map<string,tree_node*> = map<string,tree_node*>());
Interpreter();
tree_node* validate_defun_expression(tree_node*,vector<string>,vector<string>,vector<string>,vector<string>);
vector<string> isListOfLiteralAtoms(tree_node*,vector<string>,vector<string>,vector<string>,vector<string>);
void printdlist(tree_node*);
bool isFuncNameInDlist(string);
void validateFuncCall(tree_node*,string);
map<string,tree_node*> evaluateActualList(string,tree_node*);
vector<string> getFormalParam(string);
tree_node* apply(string,tree_node*,map<string,tree_node*>);
tree_node* evlist(tree_node*,map<string,tree_node*>);
map<string,tree_node*> addpairs(vector<string> formal_param, tree_node* actual_values, map<string,tree_node*> alist);
};
#endif
| [
"“[neel.7365@gmail.com]”"
] | “[neel.7365@gmail.com]” |
2c750f910fa0ef38d090ec0c10b366434d5d2342 | 875f360a9d075d1c165706f806eae3901eb7e366 | /include/OgreWidget.h | 41b9ced39db8518e3f2b829e2af0006fff9c1866 | [
"MIT"
] | permissive | lawadr/gridiron | d435483ecaac5d4d5f8f0f35bd873afed05480c2 | 950aa96a7574a825fb3eb56e802f54c311587413 | refs/heads/master | 2021-01-18T15:23:07.862350 | 2013-01-28T20:41:33 | 2020-04-18T19:46:38 | 7,512,138 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | h | /*
Copyright (c) 2012-2013 Lawrence Adranghi
See LICENSE in root directory.
*/
#pragma once
#include <QtGui/qwidget.h>
#include <OGRE/Ogre.h>
class OgreWidget : public QWidget {
Q_OBJECT
public:
OgreWidget(QWidget* parent = 0, Qt::WindowFlags flags = 0);
virtual ~OgreWidget();
QPaintEngine* paintEngine() const;
protected:
Ogre::RenderWindow* renderWindow() const;
bool isInitialised() const;
virtual void initialise() = 0;
void paintEvent(QPaintEvent* paintEvent);
void resizeEvent(QResizeEvent* resizeEvent);
void showEvent(QShowEvent* showEvent);
private:
Ogre::RenderWindow* mRenderWindow;
};
| [
"3211473+lawadr@users.noreply.github.com"
] | 3211473+lawadr@users.noreply.github.com |
ea26686b14f1196f02102aebff57d0c6a47ed1eb | 65b7dfe3f086ad5f71901e8c49b12993a7f00d9e | /SensAble/GHOST/v4.0/include/gstVRML.h | 04ed88c655f7d91f51c7fc88dd195aef79f9111b | [] | no_license | oliriley/PhantomController | 0e7c24494a32dd75206d398e7aff402f5538bd3a | 28e6468abab235c60b3132f934b5e0de190a49ac | refs/heads/master | 2020-04-05T23:11:29.017105 | 2015-12-03T23:56:43 | 2015-12-03T23:56:43 | 38,007,748 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,037 | h | //
// Copyright 1998-1999, SensAble Technologies, Inc.
//
// file: gstVRML.h
//
// Rev: 1.0
//
// Description: Public access functions to the VRML parsing
// functionality and the error reporting thereof.
//
// Author: Tim Gallagher tim@sensable.com
//
#ifndef _GST_VRML_H_
#define _GST_VRML_H_
#include <gstVRMLDllExport.h>
#include <gstVRMLError.h>
#include <gstBasic.h>
class gstSeparator;
class gstVRMLError;
// Read a VRML 2 file and convert into a GHOST scene graph.
// Given the name of a file in the VRML 2.0 format, this function
// returns a gstSeparator containing the VRML scene graph in the
// GHOST v2 format.
GHOST_VRML_DLL_IMPORT_EXPORT gstSeparator *gstReadVRMLFile(const char *filename);
// Report errors about reading or conversion.
// Errors in the reading, parsing and instantiation of the the
// input file are recorded in gstVRMLError class structures and
// placed in a stack in the order in which they occur. The stack
// is reset when gstReadVRMLFile is called.
// The following functions should can be used to retreive any
// errors encountered during parsing.
// get earliest error, return no error if none
GHOST_VRML_DLL_IMPORT_EXPORT gstVRMLError gstVRMLGetError();
// how many errors
GHOST_VRML_DLL_IMPORT_EXPORT int gstVRMLGetNumErrors();
// get earliest and remove it from list
GHOST_VRML_DLL_IMPORT_EXPORT gstVRMLError gstVRMLPopEarliestError();
// get earliest error
GHOST_VRML_DLL_IMPORT_EXPORT gstVRMLError gstVRMLGetEarliestError();
// get latest and remove it from list
GHOST_VRML_DLL_IMPORT_EXPORT gstVRMLError gstVRMLPopLatestError();
// get latest error
GHOST_VRML_DLL_IMPORT_EXPORT gstVRMLError gstVRMLGetLatestError();
// clear all errors
GHOST_VRML_DLL_IMPORT_EXPORT void gstVRMLClearErrors();
// dump errors to given filename
GHOST_VRML_DLL_IMPORT_EXPORT int gstVRMLWriteErrorsToFile(const char *filename);
// convert error type to string representation
GHOST_VRML_DLL_IMPORT_EXPORT const char *gstVRMLGetErrorTypeName(gstVRMLErrorType errType);
#endif // _GST_VRML_H_
| [
"oliriley@uw.edu"
] | oliriley@uw.edu |
82e5c298467a99b363fc48d50b2129fea26b61f7 | 97c211320795bd62240247bfcc577fbc419542fa | /WhatBox/System.h | 37de21e95ecef72a8ddb7949dbd2c16a12ed4534 | [] | no_license | NeuroWhAI/Biogram | 855c6fd4a25739aa5c416f4824cc7339d95da251 | 7e534514220673cb1971469e7b0559da3805d267 | refs/heads/master | 2021-01-17T06:01:30.016073 | 2016-06-19T05:19:30 | 2016-06-19T05:19:30 | 48,879,071 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,007 | h | #pragma once
#include <memory>
#include "SystemInfo.h"
#include "UserInputController.h"
#include "Graphic.h"
#include "ObjectViewer.h"
#include "Logger.h"
class System final
{
private:
System();
virtual ~System();
protected:
static System* s_pInstance;
// s_pInstance 메모리 해제를 위한 도움클래스
class CleanHelper
{
public:
virtual ~CleanHelper();
};
protected:
std::unique_ptr<SystemInfo> m_pSystemInfo;
std::unique_ptr<UserInputController> m_pUserInputController;
std::unique_ptr<Graphic> m_pGraphic;
std::unique_ptr<ObjectViewer> m_pObjectViewer;
std::unique_ptr<Logger> m_pLogger;
public:
static System& getInstance();
public:
SystemInfo& getSystemInfo();
UserInputController& getUserInputController();
Graphic& getGraphic();
ObjectViewer& getObjectViewer();
Logger& getLogger();
};
#define BIOGRAM_DEBUG_OFF
#ifdef BIOGRAM_DEBUG
#define LOG(...) System::getInstance().getLogger().log(__VA_ARGS__)
#else
#define LOG(...)
#endif | [
"neurowhai@gmail.com"
] | neurowhai@gmail.com |
72976fcca6c406270364ae609e8bb26b2026472a | 9486c2642ac4e7b8439592861688e452d2154ee1 | /BuildingEscape/Source/BuildingEscape/PositionReport.cpp | 3bb9592819b1562c301398173a03f3b29bf2a7f1 | [] | no_license | cyphenreal/UDM_TUEDC_Section003 | fb9c6aa2ad7d64b5e82f3906fe37f4f11c6cfe68 | 9a49324561174d41ea982f29a9ff1a17731d65d5 | refs/heads/master | 2021-05-02T07:21:20.540093 | 2018-03-21T21:02:34 | 2018-03-21T21:02:34 | 120,817,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 982 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "BuildingEscape.h"
#include "PositionReport.h"
// Sets default values for this component's properties
UPositionReport::UPositionReport()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
bWantsBeginPlay = true;
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UPositionReport::BeginPlay()
{
Super::BeginPlay();
FString ObjectName = GetOwner()->GetName();
FString ObjectPos = GetOwner()->GetActorLocation().ToString();
UE_LOG(LogTemp, Warning, TEXT("%s is at %s!"), *ObjectName, *ObjectPos);
}
// Called every frame
void UPositionReport::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
} | [
"scott.bakkila@gmail.com"
] | scott.bakkila@gmail.com |
03a9ce94eb97447d0924226b80fa0f2eea4f0ce1 | 5f49f43a343339f7bba9576245163dc1b560f02f | /Server/Server/Server.cpp | 65e20110ea1eeb9593f1c38a35fcdf627c063bd9 | [] | no_license | brendan-kellam/SimpleChat | c26f7c5e16f62a4d5e16478c91bb7288133514ad | 651ef03f63b7d716ccc1971b112933ae991e0bce | refs/heads/master | 2021-01-20T08:10:06.434516 | 2017-05-28T01:54:56 | 2017-05-28T01:54:56 | 90,110,638 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,789 | cpp |
#include "Server.h"
/* -- constructor -- */
Server::Server(int PORT, bool BroadcastPublically) {
std::cout << "server starting...\n";
// Winsock Startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
// If error occurs during WSAStartup
if (WSAStartup(DllVersion, &wsaData) != 0) {
MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
// Exit program
exit(1);
}
if (BroadcastPublically)
addr.sin_addr.s_addr = htonl(INADDR_ANY); // Broadcast publically (converts host to netowrk byte order) [Host to Network Long]
else
addr.sin_addr.s_addr = inet_addr(LOCAL_IP); // Broadcast locally
addr.sin_port = htons(PORT); // Port
addr.sin_family = AF_INET; // IPv4 Socket
// Create socket to listen for new connections
sListen = socket(AF_INET, SOCK_STREAM, NULL);
if (bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) //Bind the address to the socket, if we fail to bind the address..
{
std::string ErrorMsg = "Failed to bind the address to our listening socket. Winsock Error:" + std::to_string(WSAGetLastError());
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
/* Places the socket in a state such that it is waiting for a incoming connection
"SOMAXCONN": Socket outstanding maxiumum connectiosn
(The total amount of people that can try and connect at once) */
if (listen(sListen, SOMAXCONN) == SOCKET_ERROR) { // Handle errors while listening
std::string ErrorMsg = "Failed to listen on listening socket.";
MessageBoxA(NULL, ErrorMsg.c_str(), "Error", MB_OK | MB_ICONERROR);
exit(1);
}
serverptr = this;
// Create a new packet sender thread
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)PacketSenderThread, NULL, NULL, NULL);
}
bool Server::ListenForNewConnection() {
// Socket to hold the client's connection
SOCKET newConnectionSocket;
// Accept a new client connection (accept is most likely running on another thread)
newConnectionSocket = accept(sListen, (SOCKADDR*)&addr, &addrlen);
// Check if accepting client connection failed
if (newConnectionSocket == 0) {
std::cout << "Failed to accept client connection...\n";
return false;
}
else // If the client connection was accepted
{
std::lock_guard<std::mutex> lock(connectionMgr_mutex); // lock connection manager mutex
size_t conid = connections.size(); // Default new connection id
// TODO: Optimize!
if (UnusedConnections > 0)
{
// Loop all connections
for (size_t i = 0; i < connections.size(); i++)
{
// find first instance of inactive connection
if (!connections[i]->activeConnection)
{
connections[i]->socket = newConnectionSocket;
connections[i]->activeConnection = true;
conid = i;
UnusedConnections--;
break;
}
}
}
else
{
// Default case
std::shared_ptr<Connection> newConnection(new Connection(newConnectionSocket));
connections.push_back(newConnection);
}
std::cout << "Client connected! ID: " << conid << std::endl;
// create thread for new client
CreateThread(
NULL, NULL,
(LPTHREAD_START_ROUTINE)ClientHandlerThread,
(LPVOID)(conid),
NULL, NULL
);
return true;
}
}
bool Server::ProcessPacket(int id, PacketType _packettype) {
switch (_packettype) {
case PacketType::ChatMessage:
{
std::string message;
if (!GetString(id, message)) // Get chat message from client
return false;
// loop all connected clients
for (size_t i = 0; i < connections.size(); i++) {
if (!connections[i]->activeConnection) // If connection is not active
continue;
if (i == id)
continue; // Skip originating client
// Send message to connection i
SendString((int) i, message);
}
std::cout << "Processed chat message packet from user id: " << id << std::endl;
break;
}
// When client request a file from the server
case PacketType::FileTransferRequestFile:
{
std::string FileName;
if (!GetString(id, FileName))
return false;
// attempt to open file to read from
connections[id]->file.infileStream.open(FileName, std::ios::binary | std::ios::ate);
// check if file failed to open
if (!connections[id]->file.infileStream.is_open())
{
std::cout << "Client: " << id << " requested file: " << FileName << ". File does not exist" << std::endl;
std::string errMsg = "Requested file: " + FileName + " does not exist or was not found.";
SendString(id, errMsg); // Send error message to client
// No connection issue, so return true
return true;
}
/* -- At this point, the file exists and is ready to be sent -- */
connections[id]->file.fileName = FileName; // Set file name
connections[id]->file.fileSize = connections[id]->file.infileStream.tellg(); // Get file size
connections[id]->file.infileStream.seekg(0); // Set stream cursor position so no offest exists (start of file)
connections[id]->file.fileOffset = 0; // Update file offest for knowing when we hit EOF
/* -- Ready to send first byte buffer -- */
if (!SendFileByteBuffer(id))
return false;
break;
}
case PacketType::FileTransferRequestNextBuffer:
{
if (!SendFileByteBuffer(id))
return false;
break;
}
default:
std::cout << "Unrecognized packet: " << _packettype << std::endl;
break;
}
return true;
}
bool Server::SendFileByteBuffer(int id)
{
// If end of file is already reached
if (connections[id]->file.fileOffset >= connections[id]->file.fileSize)
return true;
connections[id]->file.remainingBytes = connections[id]->file.fileSize - connections[id]->file.fileOffset;
// CASE: # of remaining bytes is greater than our packet size
if (connections[id]->file.remainingBytes > connections[id]->file.buffersize)
{
PS::FileDataBuffer fileData; // Create new FileDataBuffer packet structure
connections[id]->file.infileStream.read(fileData.databuffer, connections[id]->file.buffersize); // Read from the connection's request file
// To the FileDataBuffer buffer
fileData.size = connections[id]->file.buffersize; // Set fileData size
connections[id]->file.fileOffset += connections[id]->file.buffersize; // Increment the FileTransferData's offset
connections[id]->pm.Append(fileData.toPacket()); // Appened created packet to packet manager
}
// CASE: # of remaining bytes is less than our packet size
else
{
PS::FileDataBuffer fileData; // -- Same procedure, but with remaining bytes -- //
connections[id]->file.infileStream.read(fileData.databuffer, connections[id]->file.remainingBytes);
fileData.size = connections[id]->file.remainingBytes;
connections[id]->file.fileOffset += connections[id]->file.remainingBytes;
connections[id]->pm.Append(fileData.toPacket());
}
// If we are at EOF
if (connections[id]->file.fileOffset == connections[id]->file.fileSize)
{
Packet EOFPacket(PacketType::FileTransfer_EndOfFile);
connections[id]->pm.Append(EOFPacket);
std::cout << std::endl << "File Sent: " << connections[id]->file.fileName << std::endl;
std::cout << "File size(bytes): " << connections[id]->file.fileSize << std::endl << std::endl;
// close stream
connections[id]->file.infileStream.close();
}
return true;
}
void Server::ClientHandlerThread(int id) { // ~~static method~~
PacketType packettype;
while (true) {
if (!serverptr->GetPacketType(id, packettype)) // Get packet type from client
break; // If error occurs, break from loop
if (!serverptr->ProcessPacket(id, packettype)) // Process packet
break; // If error occurs, break from loop
}
std::cout << "Lost connection to client id: " << id << std::endl; // Prompt when client disconnects
serverptr->DisconnectClient(id);
return;
}
void Server::PacketSenderThread()
{
while (true)
{
// Loop through all connections
for (size_t i = 0; i < serverptr->connections.size(); i++)
{
// If a given connection has a pending packet
if (serverptr->connections[i]->pm.HasPendingPackets())
{
// Get packet
Packet p = serverptr->connections[i]->pm.Retrieve();
// Attempt to send data
if (!serverptr->sendall(i, p.getBuffer(), p.getSize()))
{
std::cout << "ERROR: Function(Server::PacketSenderThread) - Failed to send packet to ID: " << i << std::endl;
}
delete p.getBuffer(); // Clean up buffer from the packet p
}
}
Sleep(5);
}
}
/* --- Getters and setters --- */
bool Server::recvall(int id, char* data, int totalbytes) {
int bytesreceived = 0; // Total # of bytes received
while (bytesreceived < totalbytes) {
/* Recieve data from Socket
Per itteration, offset pointer and the # of bytes to recieve
*/
int RetnCheck = recv(connections[id]->socket, data + bytesreceived, totalbytes - bytesreceived, NULL);
if (RetnCheck == SOCKET_ERROR) // If there was a connection issues
return false;
else if (RetnCheck == 0) // If we don't recieve any bytes
return false;
bytesreceived += RetnCheck; // Add to total bytes recieved
}
return true;
}
bool Server::sendall(int id, char* data, int totalbytes) {
int bytessent = 0; // Total # of bytes sent
while (bytessent < totalbytes) {
// Send data over socket
int RetnCheck = send(connections[id]->socket, data + bytessent, totalbytes - bytessent, NULL);
if (RetnCheck == SOCKET_ERROR) // If there was a connection issues
return false;
else if (RetnCheck == 0) // If we don't recieve any bytes
return false;
bytessent += RetnCheck;
}
return true;
}
bool Server::GetInt32_t(int id, int32_t &_int32_t) {
if (!recvall(id, (char*)&_int32_t, sizeof(int32_t)))
return false;
_int32_t = ntohl(_int32_t); // Convert long from Host Byte Order to Network byte order
return true;
}
bool Server::GetPacketType(int id, PacketType &_packettype) {
int32_t packettype; // Create a local intermediate integer
if (!GetInt32_t(id, packettype)) // Try to receive packet type..
return false; // If error occurs, return false
_packettype = (PacketType)packettype; // Case intermediate to type packet
return true;
}
void Server::SendString(int id, std::string &_string) {
PS::ChatMessage message(_string);
connections[id]->pm.Append(message.toPacket());
}
bool Server::GetString(int id, std::string &_string) {
int bufferlen;
if (!GetInt32_t(id, bufferlen)) // Get bufferlength
return false; // If error occurs
char* buffer = new char[bufferlen + 1]; // create a new recieve buffer
buffer[bufferlen] = '\0'; // set last character to null terminator
// Handle network error
if (!recvall(id, buffer, bufferlen)) {
delete[] buffer;
return false;
}
_string = buffer; // set return string
delete[] buffer; // dealocate buffer
return true;
}
/* -------------------------- */
void Server::DisconnectClient(int id) // attempt to disconnect client
{
std::lock_guard<std::mutex> lock(connectionMgr_mutex); // Lock connection manager mutex
if (!connections[id]->activeConnection) // if our client has already been disconnected
{
return;
}
connections[id]->pm.Clear(); // Clear out all remaining packets in queue for this connection
connections[id]->activeConnection = false; // Update connection's activity
closesocket(connections[id]->socket); // close the socket for this connection
if (id = (connections.size() -1)) // Check if id is last in connections
{
connections.pop_back(); // Remove client from vector
for (size_t i = (connections.size() - 1); i >= 0 && connections.size() > 0; i--)
{
if (connections[i]->activeConnection)
break;
connections.pop_back();
UnusedConnections--;
}
}
else // If our id is not the last
{
UnusedConnections++;
}
}
| [
"bshizzle1234@gmail.com"
] | bshizzle1234@gmail.com |
3465a68b74717021c9089ad5eb0100affd293b29 | c0bcb6c5497a33deee319d9a5850052962d63498 | /Library/FileWatcher/DirectoryChangeWatcher.cpp | 017eca1731e1fd82bbd50cf892a1a050a4f82ead | [] | no_license | xhyangxianjun/Corpse | aeaac56e3150856711207fefe66d2a545c1cc857 | 5896c8f73a455ba64e0b61e07a6e9919637a3b56 | refs/heads/master | 2023-05-02T20:11:22.212864 | 2020-03-07T12:39:30 | 2020-03-07T12:40:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,846 | cpp | #include "StdAfx.h"
#include "DirectoryChangeWatcher.h"
//
// Returns: bool
// true if strPath is a path to a directory
// false otherwise.
//
static BOOL IsDirectory(const CString & strPath)
{
DWORD dwAttrib = GetFileAttributes( strPath );
return static_cast<BOOL>((dwAttrib != 0xffffffff && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)));
}
//
// I think this code is from a Jeffrey Richter book...
//
// Enables user priviledges to be set for this process.
//
// Process needs to have access to certain priviledges in order
// to use the ReadDirectoryChangesW() API. See documentation.
BOOL EnablePrivilege(LPCTSTR pszPrivName, BOOL fEnable /*= TRUE*/)
{
BOOL fOk = FALSE;
// Assume function fails
HANDLE hToken;
// Try to open this process's access token
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
// privilege
TOKEN_PRIVILEGES tp = { 1 };
if( LookupPrivilegeValue(NULL, pszPrivName, &tp.Privileges[0].Luid) )
{
tp.Privileges[0].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : 0;
AdjustTokenPrivileges(hToken, FALSE, &tp,
sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
}
CloseHandle(hToken);
}
return(fOk);
}
class CPrivilegeEnabler
{
private:
CPrivilegeEnabler();//ctor
public:
~CPrivilegeEnabler(){};
static CPrivilegeEnabler & Instance();
//friend static CPrivilegeEnabler & Instance();
};
CPrivilegeEnabler::CPrivilegeEnabler()
{
LPCTSTR arPrivelegeNames[] = {
SE_BACKUP_NAME, // these two are required for the FILE_FLAG_BACKUP_SEMANTICS flag used in the call to
SE_RESTORE_NAME,// CreateFile() to open the directory handle for ReadDirectoryChangesW
SE_CHANGE_NOTIFY_NAME //just to make sure...it's on by default for all users.
//<others here as needed>
};
for(int i = 0; i < sizeof(arPrivelegeNames) / sizeof(arPrivelegeNames[0]); ++i)
{
if(!EnablePrivilege(arPrivelegeNames[i], TRUE))
{
TRACE(_T("Unable to enable privilege: %s -- GetLastError(): %d\n"), arPrivelegeNames[i], GetLastError());
TRACE(_T("CDirectoryChangeWatcher notifications may not work as intended due to insufficient access rights/process privileges.\n"));
TRACE(_T("File: %s Line: %d\n"), _T(__FILE__), __LINE__);
}
}
}
CPrivilegeEnabler & CPrivilegeEnabler::Instance()
{
static CPrivilegeEnabler theInstance;//constructs this first time it's called.
return theInstance;
}
CDirectoryChangeWatcher::CDirectoryChangeWatcher(BOOL bAppHasGUI /*= TRUE*/, DWORD dwFilterFlags/*=FILTERS_CHECK_FILE_NAME_ONLY*/)
: m_hCompPort(NULL) ,
m_hThread(NULL) ,
m_dwThreadID(0UL) ,
m_bAppHasGUI(bAppHasGUI) ,
m_dwFilterFlags(dwFilterFlags == 0? FILTERS_DEFAULT_BEHAVIOR : dwFilterFlags)
{
}
CDirectoryChangeWatcher::~CDirectoryChangeWatcher()
{
UnwatchAllDirectories();
if (m_hCompPort)
{
CloseHandle( m_hCompPort );
m_hCompPort = NULL;
}
}
DWORD CDirectoryChangeWatcher::SetFilterFlags(DWORD dwFilterFlags)
{
DWORD dwFilter = m_dwFilterFlags;
m_dwFilterFlags = dwFilterFlags;
if (m_dwFilterFlags == 0)
m_dwFilterFlags = FILTERS_DEFAULT_BEHAVIOR;//the default.
return dwFilter;
}
/*********************************************
Determines whether or not a directory is being watched
be carefull that you have the same name path name, including the backslash
as was used in the call to WatchDirectory().
ie:
"C:\\Temp"
is different than
"C:\\Temp\\"
**********************************************/
BOOL CDirectoryChangeWatcher::IsWatchingDirectory(LPCTSTR lpszDirToWatch) const
{
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT(lock.IsLocked());
int n;
if (GetDirWatchInfo(lpszDirToWatch, n))
return TRUE;
return FALSE;
}
int CDirectoryChangeWatcher::NumWatchedDirectories() const
{
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT( lock.IsLocked() );
int nCnt(0), max = m_DirectoriesToWatch.GetSize();
for(int n = 0; n < max; ++n)
{
if( m_DirectoriesToWatch[n] != NULL )//array may contain NULL elements.
nCnt++;
}
return nCnt;
}
/*************************************************************
FUNCTION: WatchDirectory(const CString & strDirToWatch, --the name of the directory to watch
DWORD dwChangesToWatchFor, --the changes to watch for see dsk docs..for ReadDirectoryChangesW
CDirectoryChangeHandler * pChangeHandler -- handles changes in specified directory
BOOL bWatchSubDirs --specified to watch sub directories of the directory that you want to watch
)
PARAMETERS:
const CString & strDirToWatch -- specifies the path of the directory to watch.
DWORD dwChangesToWatchFor -- specifies flags to be passed to ReadDirectoryChangesW()
CDirectoryChangeHandler * -- ptr to an object which will handle notifications of file changes.
BOOL bWatchSubDirs -- specifies to watch subdirectories.
LPCTSTR szIncludeFilter -- A file pattern string for files that you wish to receive notifications
for. See Remarks.
LPCTSTR szExcludeFilter -- A file pattern string for files that you do not wish to receive notifications for. See Remarks
Starts watching the specified directory(and optionally subdirectories) for the specified changes
When specified changes take place the appropriate CDirectoryChangeHandler::On_Filexxx() function is called.
dwChangesToWatchFor can be a combination of the following flags, and changes map out to the
following functions:
FILE_NOTIFY_CHANGE_FILE_NAME -- CDirectoryChangeHandler::On_FileAdded()
CDirectoryChangeHandler::On_FileNameChanged,
CDirectoryChangeHandler::On_FileRemoved
FILE_NOTIFY_CHANGE_DIR_NAME -- CDirectoryChangeHandler::On_FileNameAdded(),
CDirectoryChangeHandler::On_FileRemoved
FILE_NOTIFY_CHANGE_ATTRIBUTES -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_SIZE -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_LAST_WRITE -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_LAST_ACCESS -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_CREATION -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_SECURITY -- CDirectoryChangeHandler::On_FileModified?
Returns ERROR_SUCCESS if the directory will be watched,
or a windows error code if the directory couldn't be watched.
The error code will most likely be related to a call to CreateFile(), or
from the initial call to ReadDirectoryChangesW(). It's also possible to get an
error code related to being unable to create an io completion port or being unable
to start the worker thread.
This function will fail if the directory to be watched resides on a
computer that is not a Windows NT/2000/XP machine.
You can only have one watch specified at a time for any particular directory.
Calling this function with the same directory name will cause the directory to be
unwatched, and then watched again(w/ the new parameters that have been passed in).
**************************************************************/
DWORD CDirectoryChangeWatcher::WatchDirectory(LPCTSTR lpszDirToWatch, DWORD dwChangesToWatchFor, CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs /*=FALSE*/, LPCTSTR szIncludeFilter /*=NULL*/, LPCTSTR szExcludeFilter /*=NULL*/)
{
ASSERT( dwChangesToWatchFor != 0);
if (lpszDirToWatch == _T('\0') || dwChangesToWatchFor == 0 || pChangeHandler == NULL)
{
TRACE(_T("ERROR: You've passed invalid parameters to CDirectoryChangeWatcher::WatchDirectory()\n"));
::SetLastError(ERROR_INVALID_PARAMETER);
return ERROR_INVALID_PARAMETER;
}
//double check that it's really a directory
if (!IsDirectory(lpszDirToWatch))
{
TRACE(_T("ERROR: CDirectoryChangeWatcher::WatchDirectory() -- %s is not a directory!\n"), lpszDirToWatch);
::SetLastError(ERROR_BAD_PATHNAME);
return ERROR_BAD_PATHNAME;
}
//double check that this directory is not already being watched....
//if it is, then unwatch it before restarting it...
if (IsWatchingDirectory(lpszDirToWatch))
VERIFY(UnwatchDirectory(lpszDirToWatch));
//
//
// Reference this singleton so that privileges for this process are enabled
// so that it has required permissions to use the ReadDirectoryChangesW API, etc.
//
CPrivilegeEnabler::Instance();
//
//open the directory to watch....
HANDLE hDirectory = CreateFile(lpszDirToWatch,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE ,//| FILE_SHARE_DELETE, <-- removing FILE_SHARE_DELETE prevents the user or someone else from renaming or deleting the watched directory. This is a good thing to prevent.
NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | //<- the required priviliges for this flag are: SE_BACKUP_NAME and SE_RESTORE_NAME. CPrivilegeEnabler takes care of that.
FILE_FLAG_OVERLAPPED, NULL);
if (hDirectory == INVALID_HANDLE_VALUE)
{
DWORD dwError = GetLastError();
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory() -- Couldn't open directory for monitoring. %d\n"), dwError);
::SetLastError(dwError);//who knows if TRACE will cause GetLastError() to return success...probably won't, but set it manually just for fun.
return dwError;
}
CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDirectory, lpszDirToWatch, pChangeHandler, dwChangesToWatchFor,
bWatchSubDirs, m_bAppHasGUI, szIncludeFilter, szExcludeFilter, m_dwFilterFlags);
if( !pDirInfo )
{
TRACE(_T("WARNING: Couldn't allocate a new CDirWatchInfo() object --- File: %s Line: %d\n"), _T( __FILE__ ), __LINE__);
CloseHandle( hDirectory );
::SetLastError(ERROR_OUTOFMEMORY);
return ERROR_OUTOFMEMORY;
}
//create a IO completion port/or associate this key with
//the existing IO completion port
m_hCompPort = CreateIoCompletionPort(hDirectory,
m_hCompPort, //if m_hCompPort is NULL, hDir is associated with a NEW completion port,
//if m_hCompPort is NON-NULL, hDir is associated with the existing completion port that the handle m_hCompPort references
(DWORD)pDirInfo, //the completion 'key'... this ptr is returned from GetQueuedCompletionStatus() when one of the events in the dwChangesToWatchFor filter takes place
0);
if (m_hCompPort == NULL) {
TRACE(_T("ERROR -- Unable to create I/O Completion port! GetLastError(): %d File: %s Line: %d"), GetLastError(), _T( __FILE__ ), __LINE__ );
DWORD dwError = GetLastError();
pDirInfo->DeleteSelf( NULL );
::SetLastError(dwError);//who knows what the last error will be after i call pDirInfo->DeleteSelf(), so set it just to make sure
return dwError;
} else {//completion port created/directory associated w/ it successfully
//if the thread isn't running start it....
//when the thread starts, it will call ReadDirectoryChangesW and wait
//for changes to take place
if (m_hThread == NULL)
{
m_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MonitorDirectoryChanges, this, 0, &m_dwThreadID);
if (m_hThread == NULL)
{
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory()-- AfxBeginThread failed!\n"));
pDirInfo->DeleteSelf(NULL);
return (GetLastError() == ERROR_SUCCESS)? ERROR_MAX_THRDS_REACHED : GetLastError();
}
}
//thread is running,
//signal the thread to issue the initial call to
//ReadDirectoryChangesW()
if( m_hThread != NULL )
{
DWORD dwStarted = pDirInfo->StartMonitor(m_hCompPort);
if( dwStarted != ERROR_SUCCESS )
{//there was a problem!
TRACE(_T("Unable to watch directory: %s -- GetLastError(): %d\n"), dwStarted);
pDirInfo->DeleteSelf( NULL );
::SetLastError(dwStarted);//I think this'll set the Err object in a VB app.....
return dwStarted;
}
else
{
//ReadDirectoryChangesW was successfull!
//add the directory info to the first empty slot in the array
//associate the pChangeHandler with this object
pChangeHandler->ReferencesWatcher(this);//reference is removed when directory is unwatched.
//CDirWatchInfo::DeleteSelf() must now be called w/ this CDirectoryChangeWatcher pointer becuse
//of a reference count
//save the CDirWatchInfo* so I'll be able to use it later.
VERIFY( AddToWatchInfo(pDirInfo));
SetLastError(dwStarted);
return dwStarted;
}
}
else
{
ASSERT(FALSE);//control path shouldn't get here
::SetLastError(ERROR_MAX_THRDS_REACHED);
return ERROR_MAX_THRDS_REACHED;
}
}
ASSERT( FALSE );//shouldn't get here.
}
BOOL CDirectoryChangeWatcher::UnwatchAllDirectories()
{
if (m_hThread != NULL)
{
ASSERT(m_hCompPort != NULL);
CSingleLock lock( &m_csDirWatchInfo, TRUE);
ASSERT(lock.IsLocked());
int nMax = m_DirectoriesToWatch.GetSize();
for(int n = 0; n < nMax; ++n)
{
CDirWatchInfo * pDirInfo = m_DirectoriesToWatch[n];
if (pDirInfo != NULL )
{
VERIFY(pDirInfo->UnwatchDirectory(m_hCompPort));
m_DirectoriesToWatch.SetAt(n, NULL);
pDirInfo->DeleteSelf(this);
}
}
m_DirectoriesToWatch.RemoveAll();
//kill off the thread
PostQueuedCompletionStatus(m_hCompPort, 0, 0, NULL);//The thread will catch this and exit the thread
//wait for it to exit
WaitForSingleObject(m_hThread, INFINITE);
//CloseHandle( m_hThread );//Since thread was started w/ AfxBeginThread() this handle is closed automatically, closing it again will raise an exception
m_hThread = NULL;
m_dwThreadID = 0UL;
CloseHandle( m_hCompPort );
m_hCompPort = NULL;
return TRUE;
}
else
{
#ifdef _DEBUG
//make sure that there aren't any
//CDirWatchInfo objects laying around... they should have all been destroyed
//and removed from the array m_DirectoriesToWatch
if( m_DirectoriesToWatch.GetSize() > 0 )
{
for(int i = 0; i < m_DirectoriesToWatch.GetSize(); ++i)
{
ASSERT( m_DirectoriesToWatch[i] == NULL );
}
}
#endif
}
return FALSE;
}
/***************************************************************
FUNCTION: UnwatchDirectory(const CString & strDirToStopWatching -- if this directory is being watched, the watch is stopped
****************************************************************/
BOOL CDirectoryChangeWatcher::UnwatchDirectory(LPCTSTR lpszDirectoryToStopWatching)
{
BOOL bRetVal = FALSE;
if( m_hCompPort != NULL )//The io completion port must be open
{
ASSERT(_tcslen(lpszDirectoryToStopWatching) != 0);
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nIdx = -1;
CDirWatchInfo * pDirInfo = GetDirWatchInfo(lpszDirectoryToStopWatching, nIdx);
if (pDirInfo != NULL && nIdx != -1)
{
//stop watching this directory
VERIFY( pDirInfo->UnwatchDirectory(m_hCompPort));
//cleanup the object used to watch the directory
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
bRetVal = TRUE;
}
}
return bRetVal;
}
BOOL CDirectoryChangeWatcher::UnwatchDirectory(CDirectoryChangeHandler * pChangeHandler)
/************************************
This function is called from the dtor of CDirectoryChangeHandler automatically,
but may also be called by a programmer because it's public...
A single CDirectoryChangeHandler may be used for any number of watched directories.
Unwatch any directories that may be using this
CDirectoryChangeHandler * pChangeHandler to handle changes to a watched directory...
The CDirWatchInfo::m_pChangeHandler member of objects in the m_DirectoriesToWatch
array will == pChangeHandler if that handler is being used to handle changes to a directory....
************************************/
{
ASSERT( pChangeHandler );
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nUnwatched = 0;
int nIdx = -1;
CDirWatchInfo * pDirInfo;
//
// go through and unwatch any directory that is
// that is using this pChangeHandler as it's file change notification handler.
//
while( (pDirInfo = GetDirWatchInfo( pChangeHandler, nIdx )) != NULL )
{
VERIFY( pDirInfo->UnwatchDirectory( m_hCompPort ) );
nUnwatched++;
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
}
return (BOOL)(nUnwatched != 0);
}
BOOL CDirectoryChangeWatcher::UnwatchDirectoryBecauseOfError(CDirWatchInfo * pWatchInfo)
//
// Called in the worker thread in the case that ReadDirectoryChangesW() fails
// during normal operation. One way to force this to happen is to watch a folder
// using a UNC path and changing that computer's IP address.
//
{
ASSERT( pWatchInfo );
ASSERT( m_dwThreadID == GetCurrentThreadId() );//this should be called from the worker thread only.
BOOL bRetVal = FALSE;
if( pWatchInfo )
{
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nIdx = -1;
if( GetDirWatchInfo(pWatchInfo, nIdx) == pWatchInfo )
{
// we are actually watching this....
//
// Remove this CDirWatchInfo object from the list of watched directories.
//
m_DirectoriesToWatch.SetAt(nIdx, NULL);//mark the space as free for the next watch...
//
// and delete it...
//
pWatchInfo->DeleteSelf(this);
}
}
return bRetVal;
}
//
//
// To add the CDirWatchInfo * to an array.
// The array is used to keep track of which directories
// are being watched.
//
// Add the ptr to the first non-null slot in the array.
int CDirectoryChangeWatcher::AddToWatchInfo(CDirWatchInfo * pWatchInfo)
{
CSingleLock lock( &m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
//first try to add it to the first empty slot in m_DirectoriesToWatch
INT_PTR nMax = m_DirectoriesToWatch.GetSize();
INT_PTR n = 0;
for(n = 0; n < nMax; ++n)
{
if (m_DirectoriesToWatch[n] == NULL)
{
m_DirectoriesToWatch[n] = pWatchInfo;
break;
}
}
if (n == nMax)
{
n = m_DirectoriesToWatch.Add(pWatchInfo);
}
return n != -1;
}
UINT CDirectoryChangeWatcher::MonitorDirectoryChanges(LPVOID lParam)
{
DWORD numBytes;
CDirWatchInfo* pDirectoryInfo;
LPOVERLAPPED lpOverlapped;
CDirectoryChangeWatcher* pDirectoryWatcher = reinterpret_cast<CDirectoryChangeWatcher*>(lParam);
ASSERT(pDirectoryWatcher);
pDirectoryWatcher->OnThreadInitialize();
do
{
//The io completion request failed...
//probably because the handle to the directory that
//was used in a call to ReadDirectoryChangesW has been closed.
//
// calling pdi->CloseDirectoryHandle() will cause GetQueuedCompletionStatus() to return false.
//
//
if (GetQueuedCompletionStatus(pDirectoryWatcher->m_hCompPort, &numBytes, (PULONG_PTR)&pDirectoryInfo, &lpOverlapped, INFINITE) == FALSE)
{
//the directory handle is still open! (we expect this when after we close the directory handle )
//TRACE(_T("GetQueuedCompletionStatus() returned FALSE\nGetLastError(): %d Completion Key: %p lpOverlapped: %p\n"), GetLastError(), pdi, lpOverlapped);
}
if (pDirectoryInfo)//pdi will be null if I call PostQueuedCompletionStatus(m_hCompPort, 0,0,NULL);
{
//
// The following check to AfxIsValidAddress() should go off in the case
// that I have deleted this CDirWatchInfo object, but it was still in
// "in the Queue" of the i/o completion port from a previous overlapped operation.
//
/***********************************
The CDirWatchInfo::m_RunningState is pretty much the only member
of CDirWatchInfo that can be modified from the other thread.
The functions StartMonitor() and UnwatchDirecotry() are the functions that
can modify that variable.
So that I'm sure that I'm getting the right value,
I'm using a critical section to guard against another thread modyfying it when I want
to read it...
************************************/
BOOL bObjectShouldBeOk = TRUE;
try{
VERIFY(pDirectoryInfo->LockProperties());//don't give the main thread a chance to change this object
}
catch(...){
//any sort of exception here indicates I've
//got a hosed object.
TRACE(_T("CDirectoryChangeWatcher::MonitorDirectoryChanges() -- pdi->LockProperties() raised an exception!\n"));
bObjectShouldBeOk = FALSE;
}
//while we're working with this object...
if (bObjectShouldBeOk)
{
RUNNING_STATE RunState = pDirectoryInfo->GetRunState();
VERIFY(pDirectoryInfo->UnlockProperties());//let another thread back at the properties...
/***********************************
Unlock it so that there isn't a DEADLOCK if
somebody tries to call a function which will
cause CDirWatchInfo::UnwatchDirectory() to be called
from within the context of this thread (eg: a function called because of
the handler for one of the CDirectoryChangeHandler::On_Filexxx() functions)
************************************/
ASSERT(pDirectoryInfo->GetChangeHandler());
switch(RunState)
{
case RUNNING_STATE_START_MONITORING:
{
//Issue the initial call to ReadDirectoryChangesW()
if (!ReadDirectoryChangesW(pDirectoryInfo->m_hDirectory,
pDirectoryInfo->m_Buffer,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE,
pDirectoryInfo->m_bWatchSubDir,
pDirectoryInfo->m_dwChangeFilter,
&pDirectoryInfo->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pDirectoryInfo->m_Overlapped,
NULL))//no completion routine!
{
pDirectoryInfo->m_dwReadDirError = GetLastError();
if (pDirectoryInfo->GetChangeHandler())
pDirectoryInfo->GetChangeHandler()->OnWatchStarted(pDirectoryInfo->m_dwReadDirError, pDirectoryInfo->m_strDirName);
}
else
{//read directory changes was successful!
//allow it to run normally
pDirectoryInfo->m_RunningState = RUNNING_STATE_NORMAL;
pDirectoryInfo->m_dwReadDirError = ERROR_SUCCESS;
if (pDirectoryInfo->GetChangeHandler())
pDirectoryInfo->GetChangeHandler()->OnWatchStarted(ERROR_SUCCESS, pDirectoryInfo->m_strDirName);
}
//signall that the ReadDirectoryChangesW has been called
//check CDirWatchInfo::m_dwReadDirError to see whether or not ReadDirectoryChangesW succeeded...
pDirectoryInfo->m_StartStopEvent.SetEvent();
}
break;
case RUNNING_STATE_STOP:
{
//We want to shut down the monitoring of the directory
//that pdi is managing...
if (pDirectoryInfo->m_hDirectory != INVALID_HANDLE_VALUE)
{
pDirectoryInfo->CloseDirectoryHandle();
//back up step...GetQueuedCompletionStatus() will still need to return from the last time that ReadDirectoryChangesW() was called.....
pDirectoryInfo->m_RunningState = RUNNING_STATE_STOP_STEP2;
pDirectoryInfo->GetChangeHandler()->OnWatchStopped(pDirectoryInfo->m_strDirName);
}
else
{
//either we weren't watching this direcotry in the first place,
//or we've already stopped monitoring it....
pDirectoryInfo->m_StartStopEvent.SetEvent();//set the event that ReadDirectoryChangesW has returned and no further calls to it will be made...
}
}break;
case RUNNING_STATE_STOP_STEP2:
{
//signal that no further calls to ReadDirectoryChangesW will be made
//and this pdi can be deleted
if (pDirectoryInfo->m_hDirectory == INVALID_HANDLE_VALUE)
pDirectoryInfo->m_StartStopEvent.SetEvent();
else
pDirectoryInfo->CloseDirectoryHandle();
}
break;
case RUNNING_STATE_NORMAL:
{
if (pDirectoryInfo->GetChangeHandler())
pDirectoryInfo->GetChangeHandler()->SetChangedDirectoryName(pDirectoryInfo->m_strDirName);
DWORD dwReadBuffer_Offset = 0UL;
//process the FILE_NOTIFY_INFORMATION records:
CFileNotifyInformation FileNotify((LPBYTE)pDirectoryInfo->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE);
pDirectoryWatcher->ProcessChangeNotifications(FileNotify, pDirectoryInfo, dwReadBuffer_Offset);
if (!ReadDirectoryChangesW(pDirectoryInfo->m_hDirectory,
pDirectoryInfo->m_Buffer + dwReadBuffer_Offset,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE - dwReadBuffer_Offset,
pDirectoryInfo->m_bWatchSubDir,
pDirectoryInfo->m_dwChangeFilter,
&pDirectoryInfo->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pDirectoryInfo->m_Overlapped,
NULL))//no completion routine!
{
TRACE(_T("WARNING: ReadDirectoryChangesW has failed during normal operations...failed on directory: %s\n"), pDirectoryInfo->m_strDirName);
ASSERT(pDirectoryWatcher);
int nOldThreadPriority = GetThreadPriority(GetCurrentThread());
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
pDirectoryInfo->m_dwReadDirError = GetLastError();
pDirectoryInfo->GetChangeHandler()->OnReadDirectoryChangesError(pDirectoryInfo->m_dwReadDirError, pDirectoryInfo->m_strDirName);
//Do the shutdown
pDirectoryWatcher->UnwatchDirectoryBecauseOfError(pDirectoryInfo);
SetThreadPriority(GetCurrentThread(), nOldThreadPriority);
}
else
{
//success, continue as normal
pDirectoryInfo->m_dwReadDirError = ERROR_SUCCESS;
}
}
break;
default:
TRACE(_T("MonitorDirectoryChanges() -- how did I get here?\n"));
break;//how did I get here?
}//end switch( pdi->m_RunningState )
}//end if( bObjectShouldBeOk )
}//end if( pdi )
} while(pDirectoryInfo);
pDirectoryWatcher->OnThreadExit();
return 0; //thread is ending
}
//
// functions for retrieving the directory watch info based on different parameters
//
CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(LPCTSTR lpszDirectoryName, int & nRef) const
{
if (_tcslen(lpszDirectoryName) == 0)// can't be watching a directory if it's you don't pass in the name of it...
return NULL; //
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
INT_PTR nMax = m_DirectoriesToWatch.GetSize();
CDirWatchInfo* pWatchInfo = NULL;
for(INT_PTR n = 0; n < nMax; ++n)
{
if ((pWatchInfo = m_DirectoriesToWatch[n]) != NULL && pWatchInfo->GetDirectoryName().CompareNoCase(lpszDirectoryName) == 0)
{
nRef = n;
return pWatchInfo;
}
}
return NULL;//NOT FOUND
}
CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirWatchInfo * pWatchInfo, int & nRef)const
{
ASSERT( pWatchInfo != NULL );
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
INT_PTR nMax = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * pInfo;
for(INT_PTR n=0; n < nMax; ++n)
{
if((pInfo = m_DirectoriesToWatch[n]) != NULL && pInfo == pWatchInfo)
{
nRef = n;
return pInfo;
}
}
return NULL;//NOT FOUND
}
CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirectoryChangeHandler * pChangeHandler, int & nRef) const
{
ASSERT(pChangeHandler != NULL);
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
INT_PTR nMax = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * pWatchInfo = NULL;
for(INT_PTR n=0 ; n < nMax; ++n)
{
if ((pWatchInfo = m_DirectoriesToWatch[n]) != NULL && pWatchInfo->GetRealChangeHandler() == pChangeHandler )
{
nRef = n;
return pWatchInfo;
}
}
return NULL;//NOT FOUND
}
/////////////////////////////////////////////////////////////
//
// Processes the change notifications and dispatches the handling of the
// notifications to the CDirectoryChangeHandler object passed to WatchDirectory()
//
/////////////////////////////////////////////////////////////
void CDirectoryChangeWatcher::ProcessChangeNotifications(IN CFileNotifyInformation& FileNotify,
IN CDirWatchInfo * pDirectoryInfo,
OUT DWORD & ref_dwReadBuffer_Offset//used in case ...see case for FILE_ACTION_RENAMED_OLD_NAME
)
{
//
// Sanity check...
// this function should only be called by the worker thread.
//
ASSERT( m_dwThreadID == GetCurrentThreadId() );
// Validate parameters...
//
ASSERT(pDirectoryInfo);
if(!pDirectoryInfo)
{
TRACE(_T("Invalid arguments to CDirectoryChangeWatcher::ProcessChangeNotifications() -- pdi is invalid!\n"));
TRACE(_T("File: %s Line: %d"), _T( __FILE__ ), __LINE__ );
return;
}
DWORD dwLastAction = 0;
ref_dwReadBuffer_Offset = 0UL;
CDirectoryChangeHandler * pChangeHandler = pDirectoryInfo->GetChangeHandler();
//CDelayedDirectoryChangeHandler * pChangeHandler = pdi->GetChangeHandler();
ASSERT(pChangeHandler);
//ASSERT( AfxIsValidAddress(pChangeHandler, sizeof(CDelayedDirectoryChangeHandler)) );
if(pChangeHandler == NULL)
{
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() Unable to continue, pdi->GetChangeHandler() returned NULL!\n"));
TRACE(_T("File: %s Line: %d\n"), _T( __FILE__ ), __LINE__ );
return;
}
do
{
switch(FileNotify.GetAction())
{
case FILE_ACTION_ADDED: // a file was added!
pChangeHandler->OnFileAdded(FileNotify.GetFileNameWithPath(pDirectoryInfo->m_strDirName));
break;
case FILE_ACTION_REMOVED: //a file was removed
pChangeHandler->OnFileRemoved(FileNotify.GetFileNameWithPath(pDirectoryInfo->m_strDirName));
break;
case FILE_ACTION_MODIFIED:
pChangeHandler->OnFileModified(FileNotify.GetFileNameWithPath(pDirectoryInfo->m_strDirName));
break;
case FILE_ACTION_RENAMED_OLD_NAME:
{
CString strOldFileName = FileNotify.GetFileNameWithPath(pDirectoryInfo->m_strDirName);
if(FileNotify.GetNextNotifyInformation())
{
ASSERT(FileNotify.GetAction() == FILE_ACTION_RENAMED_NEW_NAME );//making sure that the next record after the OLD_NAME record is the NEW_NAME record
//get the new file name
CString strNewFileName = FileNotify.GetFileNameWithPath(pDirectoryInfo->m_strDirName);
pChangeHandler->OnFileNameChanged(strOldFileName, strNewFileName);
}
else
{
VERIFY(FileNotify.CopyCurrentRecordToBeginningOfBuffer(ref_dwReadBuffer_Offset));
}
break;
}
case FILE_ACTION_RENAMED_NEW_NAME:
{
ASSERT(dwLastAction == FILE_ACTION_RENAMED_OLD_NAME );
ASSERT( FALSE );//this shouldn't get here
}
default:
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() -- unknown FILE_ACTION_ value! : %d\n"), FileNotify.GetAction() );
break;//unknown action
}
dwLastAction = FileNotify.GetAction();
} while(FileNotify.GetNextNotifyInformation());
}
LONG CDirectoryChangeWatcher::ReleaseReferenceToWatcher(CDirectoryChangeHandler * pChangeHandler)
{
ASSERT(pChangeHandler);
return pChangeHandler->ReleaseReferenceToWatcher(this);
} | [
"1054457048@qq.com"
] | 1054457048@qq.com |
53d1208af48bd25193a43392ab92a739824169d7 | 0e18ce18b14894410d72afb706f4c1b7bb8b76d2 | /backtracking/PermuteString.cpp | 05c50784c65df00974bb3279e2b61235872c8d9a | [] | no_license | kai04/Programming | 5aea45665c42ded10343cbf3998a21c19805e49b | 671ae25bbb231b6e8a3e55033e3f641327affb2d | refs/heads/master | 2023-06-25T13:02:33.924742 | 2023-06-11T16:28:15 | 2023-06-11T16:28:15 | 118,023,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cpp |
//Also known as count all anagram
//https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
#include <bits/stdc++.h>
using namespace std;
bool check(map<char,int> count1){
for(auto it:count1){
if(it.second>0){
return false;
}
}
return true;
}
void printHelper(string result,map<char,int> &count1){
if(check(count1)){
cout<<result<<" ";
}
for(auto it:count1){
char c=it.first;
int cnt=it.second;
if(cnt>0){
//choose
result+=c;
count1[c]-=1;
//explore
printHelper(result,count1);
//unchoose
result.erase(result.length()-1,1);
count1[c]+=1;
}
}
}
int main() {
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int n=s.length();
map<char,int> count1;
for(int i=0;i<n;i++){
count1[s[i]]+=1;
}
printHelper("",count1);
cout<<endl;
}
//code
return 0;
}
| [
"saurav.shrivastava04@gmail.com"
] | saurav.shrivastava04@gmail.com |
e2ff2ff8fde0a81fcc63aab0bdbeb20c1039f201 | f5d15ea7eae93000eaa66ab471744732191a7419 | /DiceGame/DiceGame/ScoreSheet.h | ca8695db3bc4096c54b33b773b6af44430534f1e | [] | no_license | alibhangoo/Qwinto-Quixx-Board-Game | 0d516aded2c5df3bf9b9c6e61e06fb86229dbb8c | 16ae24cf8eb587aad9dec17983b9e178d1069518 | refs/heads/master | 2021-09-26T22:31:32.991864 | 2018-11-03T21:27:05 | 2018-11-03T21:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | h | //
// ScoreSheet.h
// DiceGame
//
// Name: Ali Bhangoo
// Student #: 7828675
#ifndef ScoreSheet_h
#define ScoreSheet_h
#include <string>
#include "Colour.h"
#include "RollOfDice.h"
class ScoreSheet{
public:
std::string playerName;
int failedAttempts;
int overallScore;
ScoreSheet(const std::string& name = "");
virtual ~ScoreSheet(); //base classes require virtual destructors
virtual bool score(RollOfDice rd, Colour colourSelected, int leftPosition = -1);
virtual int calcTotal() = 0; //virtual function
void setTotal();
virtual bool const operator!(); //overloading not operator
//overload insertion operator, behaves polymorphically
friend std::ostream& operator<<(std::ostream& os, const ScoreSheet& obj);
protected:
virtual bool validate(RollOfDice rd, Colour colourSelected, int leftPosition = -1) = 0; //score calls this function
};
#endif /* ScoreSheet_h */
| [
"gaylibanks@gmail.com"
] | gaylibanks@gmail.com |
bae1f4256726a3f614f000987b16ae0d8a5ff07a | 2e35f7b4c3b2d5fefc25a6f44e9692e964cc9ae7 | /P8/main.cpp | a40802bcde6da993cf0a75507c066ed03ec18650 | [] | no_license | jw291/Algorithm-Study | 1f3335bd5b163e55276426c0b94c299f139b0088 | be8da6fe470a1bf6dd972431c57b0688d0f1d0d2 | refs/heads/main | 2023-07-02T00:46:16.364168 | 2021-08-08T09:52:03 | 2021-08-08T09:52:03 | 377,438,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | #include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;
int main() {
char str[30];
int i , cnt =0;
//카운트 하는 이유는
//()))와 같이 )는 push를 하지 않기 때문에 empty라고 인식하기 때문에
int opencount = 0; //열린 괄호 카운트
int closecount = 0; //닫힌 괄호 카운트
stack<char> s;
scanf("%s",str);
for(i = 1; str[i] != '\0'; i++){
if(str[i] == '(')
{
s.push(str[i]);
opencount++;
}
else if(str[i] == ')')
{
closecount++;
if(!s.empty()){
s.pop();
}
}
}
if(s.empty() && closecount > 0 && opencount > 0 && opencount == closecount)
cout << "YES";
else cout << "NO";
return 0;
}
| [
"jw_29@naver.com"
] | jw_29@naver.com |
a53571a370cf76bafd9269323987cdc9ef1d7c0b | bc3f4abb517829c60f846e5cd9787ac61def945b | /cpp_boost/boost/boost/ptr_container/detail/reversible_ptr_container.hpp | 76981121a86027e8e45272faeb4cc242343395fc | [] | no_license | ngzHappy/cpc2 | f3a7a0082e7ab3bd995820384c938ef6f1904a34 | 2830d68fec95ba0afeabd9469e919f8e6deb41b3 | refs/heads/master | 2020-12-25T17:24:17.726694 | 2016-08-08T13:40:06 | 2016-08-08T13:40:07 | 58,794,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,338 | hpp | //
// Boost.Pointer Container
//
// Copyright Thorsten Ottosen 2003-2005. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//
#ifndef BOOST_PTR_CONTAINER_DETAIL_REVERSIBLE_PTR_CONTAINER_HPP
#define BOOST_PTR_CONTAINER_DETAIL_REVERSIBLE_PTR_CONTAINER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/ptr_container/detail/throw_exception.hpp>
#include <boost/ptr_container/detail/scoped_deleter.hpp>
#include <boost/ptr_container/detail/static_move_ptr.hpp>
#include <boost/ptr_container/exception.hpp>
#include <boost/ptr_container/clone_allocator.hpp>
#include <boost/ptr_container/nullable.hpp>
#ifdef BOOST_NO_SFINAE
#else
#include <boost/range/functions.hpp>
#endif
#include <boost/config.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/range/iterator.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <typeinfo>
#include <memory>
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable:4127)
#endif
namespace boost
{
namespace ptr_container_detail
{
template< class CloneAllocator >
struct clone_deleter
{
template< class T >
void operator()( const T* p ) const
{
CloneAllocator::deallocate_clone( p );
}
};
template< class T >
struct is_pointer_or_integral
{
BOOST_STATIC_CONSTANT(bool, value = is_pointer<T>::value || is_integral<T>::value );
};
struct is_pointer_or_integral_tag {};
struct is_range_tag {};
struct sequence_tag {};
struct fixed_length_sequence_tag : sequence_tag {};
struct associative_container_tag {};
struct ordered_associative_container_tag : associative_container_tag {};
struct unordered_associative_container_tag : associative_container_tag {};
template
<
class Config,
class CloneAllocator
>
class reversible_ptr_container
{
private:
BOOST_STATIC_CONSTANT( bool, allow_null = Config::allow_null );
typedef BOOST_DEDUCED_TYPENAME Config::value_type Ty_;
template< bool allow_null_values >
struct null_clone_allocator
{
template< class Iter >
static Ty_* allocate_clone_from_iterator( Iter i )
{
return allocate_clone( Config::get_const_pointer( i ) );
}
static Ty_* allocate_clone( const Ty_* x )
{
if( allow_null_values )
{
if( x == 0 )
return 0;
}
else
{
BOOST_ASSERT( x != 0 && "Cannot insert clone of null!" );
}
Ty_* res = CloneAllocator::allocate_clone( *x );
BOOST_ASSERT( typeid(*res) == typeid(*x) &&
"CloneAllocator::allocate_clone() does not clone the "
"object properly. Check that new_clone() is implemented"
" correctly" );
return res;
}
static void deallocate_clone( const Ty_* x )
{
if( allow_null_values )
{
if( x == 0 )
return;
}
CloneAllocator::deallocate_clone( x );
}
};
typedef BOOST_DEDUCED_TYPENAME Config::void_container_type Cont;
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
typedef null_clone_allocator<reversible_ptr_container::allow_null>
null_cloner_type;
#else
typedef null_clone_allocator<allow_null> null_cloner_type;
#endif
typedef clone_deleter<null_cloner_type> Deleter;
Cont c_;
public:
Cont& base() { return c_; }
protected: // having this public could break encapsulation
const Cont& base() const { return c_; }
public: // typedefs
typedef Ty_* value_type;
typedef Ty_* pointer;
typedef Ty_& reference;
typedef const Ty_& const_reference;
typedef BOOST_DEDUCED_TYPENAME Config::iterator
iterator;
typedef BOOST_DEDUCED_TYPENAME Config::const_iterator
const_iterator;
typedef boost::reverse_iterator< iterator >
reverse_iterator;
typedef boost::reverse_iterator< const_iterator >
const_reverse_iterator;
typedef BOOST_DEDUCED_TYPENAME Cont::difference_type
difference_type;
typedef BOOST_DEDUCED_TYPENAME Cont::size_type
size_type;
typedef BOOST_DEDUCED_TYPENAME Config::allocator_type
allocator_type;
typedef CloneAllocator clone_allocator_type;
typedef ptr_container_detail::static_move_ptr<Ty_,Deleter>
auto_type;
protected:
typedef ptr_container_detail::scoped_deleter<Ty_,null_cloner_type>
scoped_deleter;
typedef BOOST_DEDUCED_TYPENAME Cont::iterator
ptr_iterator;
typedef BOOST_DEDUCED_TYPENAME Cont::const_iterator
ptr_const_iterator;
private:
template< class InputIterator >
void copy( InputIterator first, InputIterator last )
{
std::copy( first, last, begin() );
}
void copy( const reversible_ptr_container& r )
{
copy( r.begin(), r.end() );
}
void copy_clones_and_release( scoped_deleter& sd ) // nothrow
{
BOOST_ASSERT( size_type( std::distance( sd.begin(), sd.end() ) ) == c_.size() );
std::copy( sd.begin(), sd.end(), c_.begin() );
sd.release();
}
template< class ForwardIterator >
void clone_assign( ForwardIterator first,
ForwardIterator last ) // strong
{
BOOST_ASSERT( first != last );
scoped_deleter sd( first, last ); // strong
copy_clones_and_release( sd ); // nothrow
}
template< class ForwardIterator >
void clone_back_insert( ForwardIterator first,
ForwardIterator last )
{
BOOST_ASSERT( first != last );
scoped_deleter sd( first, last );
insert_clones_and_release( sd, end() );
}
void remove_all()
{
remove( begin(), end() );
}
protected:
void insert_clones_and_release( scoped_deleter& sd,
iterator where ) // strong
{
//
// 'c_.insert' always provides the strong guarantee for T* elements
// since a copy constructor of a pointer cannot throw
//
c_.insert( where.base(),
sd.begin(), sd.end() );
sd.release();
}
void insert_clones_and_release( scoped_deleter& sd ) // strong
{
c_.insert( sd.begin(), sd.end() );
sd.release();
}
template< class U >
void remove( U* ptr )
{
null_policy_deallocate_clone( ptr );
}
template< class I >
void remove( I i )
{
null_policy_deallocate_clone( Config::get_const_pointer(i) );
}
template< class I >
void remove( I first, I last )
{
for( ; first != last; ++first )
remove( first );
}
static void enforce_null_policy( const Ty_* x, const char* msg )
{
if( !allow_null )
{
BOOST_PTR_CONTAINER_THROW_EXCEPTION( 0 == x && "null not allowed",
bad_pointer, msg );
}
}
static Ty_* null_policy_allocate_clone( const Ty_* x )
{
return null_cloner_type::allocate_clone( x );
}
static void null_policy_deallocate_clone( const Ty_* x )
{
null_cloner_type::deallocate_clone( x );
}
private:
template< class ForwardIterator >
ForwardIterator advance( ForwardIterator begin, size_type n )
{
ForwardIterator iter = begin;
std::advance( iter, n );
return iter;
}
template< class I >
void constructor_impl( I first, I last, std::input_iterator_tag ) // basic
{
while( first != last )
{
insert( end(), null_cloner_type::allocate_clone_from_iterator(first) );
++first;
}
}
template< class I >
void constructor_impl( I first, I last, std::forward_iterator_tag ) // strong
{
if( first == last )
return;
clone_back_insert( first, last );
}
template< class I >
void associative_constructor_impl( I first, I last ) // strong
{
if( first == last )
return;
scoped_deleter sd( first, last );
insert_clones_and_release( sd );
}
public: // foundation! should be protected!
reversible_ptr_container()
{ }
template< class SizeType >
reversible_ptr_container( SizeType n, unordered_associative_container_tag )
: c_( n )
{ }
template< class SizeType >
reversible_ptr_container( SizeType n, fixed_length_sequence_tag )
: c_( n )
{ }
template< class SizeType >
reversible_ptr_container( SizeType n, const allocator_type& a,
fixed_length_sequence_tag )
: c_( n, a )
{ }
explicit reversible_ptr_container( const allocator_type& a )
: c_( a )
{ }
template< class PtrContainer >
explicit reversible_ptr_container( std::auto_ptr<PtrContainer> clone )
{
swap( *clone );
}
reversible_ptr_container( const reversible_ptr_container& r )
{
constructor_impl( r.begin(), r.end(), std::forward_iterator_tag() );
}
template< class C, class V >
reversible_ptr_container( const reversible_ptr_container<C,V>& r )
{
constructor_impl( r.begin(), r.end(), std::forward_iterator_tag() );
}
template< class PtrContainer >
reversible_ptr_container& operator=( std::auto_ptr<PtrContainer> clone ) // nothrow
{
swap( *clone );
return *this;
}
reversible_ptr_container& operator=( reversible_ptr_container r ) // strong
{
swap( r );
return *this;
}
// overhead: null-initilization of container pointer (very cheap compared to cloning)
// overhead: 1 heap allocation (very cheap compared to cloning)
template< class InputIterator >
reversible_ptr_container( InputIterator first,
InputIterator last,
const allocator_type& a = allocator_type() ) // basic, strong
: c_( a )
{
constructor_impl( first, last,
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
#else
BOOST_DEDUCED_TYPENAME
#endif
iterator_category<InputIterator>::type() );
}
template< class Compare >
reversible_ptr_container( const Compare& comp,
const allocator_type& a )
: c_( comp, a ) {}
template< class ForwardIterator >
reversible_ptr_container( ForwardIterator first,
ForwardIterator last,
fixed_length_sequence_tag )
: c_( std::distance(first,last) )
{
constructor_impl( first, last,
std::forward_iterator_tag() );
}
template< class SizeType, class InputIterator >
reversible_ptr_container( SizeType n,
InputIterator first,
InputIterator last,
fixed_length_sequence_tag )
: c_( n )
{
constructor_impl( first, last,
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
#else
BOOST_DEDUCED_TYPENAME
#endif
iterator_category<InputIterator>::type() );
}
template< class Compare >
reversible_ptr_container( const Compare& comp,
const allocator_type& a,
associative_container_tag )
: c_( comp, a )
{ }
template< class InputIterator >
reversible_ptr_container( InputIterator first,
InputIterator last,
associative_container_tag )
{
associative_constructor_impl( first, last );
}
template< class InputIterator, class Compare >
reversible_ptr_container( InputIterator first,
InputIterator last,
const Compare& comp,
const allocator_type& a,
associative_container_tag )
: c_( comp, a )
{
associative_constructor_impl( first, last );
}
explicit reversible_ptr_container( size_type n )
: c_( n ) {}
template< class Hash, class Pred >
reversible_ptr_container( const Hash& h,
const Pred& pred,
const allocator_type& a )
: c_( h, pred, a ) {}
template< class InputIterator, class Hash, class Pred >
reversible_ptr_container( InputIterator first,
InputIterator last,
const Hash& h,
const Pred& pred,
const allocator_type& a )
: c_( h, pred, a )
{
associative_constructor_impl( first, last );
}
public:
~reversible_ptr_container()
{
remove_all();
}
public:
allocator_type get_allocator() const
{
return c_.get_allocator();
}
public: // container requirements
iterator begin()
{ return iterator( c_.begin() ); }
const_iterator begin() const
{ return const_iterator( c_.begin() ); }
iterator end()
{ return iterator( c_.end() ); }
const_iterator end() const
{ return const_iterator( c_.end() ); }
reverse_iterator rbegin()
{ return reverse_iterator( this->end() ); }
const_reverse_iterator rbegin() const
{ return const_reverse_iterator( this->end() ); }
reverse_iterator rend()
{ return reverse_iterator( this->begin() ); }
const_reverse_iterator rend() const
{ return const_reverse_iterator( this->begin() ); }
const_iterator cbegin() const
{ return const_iterator( c_.begin() ); }
const_iterator cend() const
{ return const_iterator( c_.end() ); }
const_reverse_iterator crbegin() const
{ return const_reverse_iterator( this->end() ); }
const_reverse_iterator crend() const
{ return const_reverse_iterator( this->begin() ); }
void swap( reversible_ptr_container& r ) // nothrow
{
c_.swap( r.c_ );
}
size_type size() const // nothrow
{
return c_.size();
}
size_type max_size() const // nothrow
{
return c_.max_size();
}
bool empty() const // nothrow
{
return c_.empty();
}
public: // optional container requirements
bool operator==( const reversible_ptr_container& r ) const // nothrow
{
if( size() != r.size() )
return false;
else
return std::equal( begin(), end(), r.begin() );
}
bool operator!=( const reversible_ptr_container& r ) const // nothrow
{
return !(*this == r);
}
bool operator<( const reversible_ptr_container& r ) const // nothrow
{
return std::lexicographical_compare( begin(), end(), r.begin(), r.end() );
}
bool operator<=( const reversible_ptr_container& r ) const // nothrow
{
return !(r < *this);
}
bool operator>( const reversible_ptr_container& r ) const // nothrow
{
return r < *this;
}
bool operator>=( const reversible_ptr_container& r ) const // nothrow
{
return !(*this < r);
}
public: // modifiers
iterator insert( iterator before, Ty_* x )
{
enforce_null_policy( x, "Null pointer in 'insert()'" );
auto_type ptr( x ); // nothrow
iterator res( c_.insert( before.base(), x ) ); // strong, commit
ptr.release(); // nothrow
return res;
}
template< class U >
iterator insert( iterator before, std::auto_ptr<U> x )
{
return insert( before, x.release() );
}
iterator erase( iterator x ) // nothrow
{
BOOST_ASSERT( !empty() );
BOOST_ASSERT( x != end() );
remove( x );
return iterator( c_.erase( x.base() ) );
}
iterator erase( iterator first, iterator last ) // nothrow
{
remove( first, last );
return iterator( c_.erase( first.base(),
last.base() ) );
}
template< class Range >
iterator erase( const Range& r )
{
return erase( boost::begin(r), boost::end(r) );
}
void clear()
{
remove_all();
c_.clear();
}
public: // access interface
auto_type release( iterator where )
{
BOOST_ASSERT( where != end() );
BOOST_PTR_CONTAINER_THROW_EXCEPTION( empty(), bad_ptr_container_operation,
"'release()' on empty container" );
auto_type ptr( Config::get_pointer( where ) ); // nothrow
c_.erase( where.base() ); // nothrow
return boost::ptr_container_detail::move( ptr );
}
auto_type replace( iterator where, Ty_* x ) // strong
{
BOOST_ASSERT( where != end() );
enforce_null_policy( x, "Null pointer in 'replace()'" );
auto_type ptr( x );
BOOST_PTR_CONTAINER_THROW_EXCEPTION( empty(), bad_ptr_container_operation,
"'replace()' on empty container" );
auto_type old( Config::get_pointer( where ) ); // nothrow
const_cast<void*&>(*where.base()) = ptr.release();
return boost::ptr_container_detail::move( old );
}
template< class U >
auto_type replace( iterator where, std::auto_ptr<U> x )
{
return replace( where, x.release() );
}
auto_type replace( size_type idx, Ty_* x ) // strong
{
enforce_null_policy( x, "Null pointer in 'replace()'" );
auto_type ptr( x );
BOOST_PTR_CONTAINER_THROW_EXCEPTION( idx >= size(), bad_index,
"'replace()' out of bounds" );
auto_type old( static_cast<Ty_*>( c_[idx] ) ); // nothrow
c_[idx] = ptr.release(); // nothrow, commit
return boost::ptr_container_detail::move( old );
}
template< class U >
auto_type replace( size_type idx, std::auto_ptr<U> x )
{
return replace( idx, x.release() );
}
}; // 'reversible_ptr_container'
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
#define BOOST_PTR_CONTAINER_DEFINE_RELEASE( base_type ) \
typename base_type::auto_type \
release( typename base_type::iterator i ) \
{ \
return boost::ptr_container_detail::move(base_type::release(i)); \
}
#else
#define BOOST_PTR_CONTAINER_DEFINE_RELEASE( base_type ) \
using base_type::release;
#endif
//
// two-phase lookup of template functions
// is buggy on most compilers, so we use a macro instead
//
#define BOOST_PTR_CONTAINER_DEFINE_RELEASE_AND_CLONE( PC, base_type, this_type ) \
explicit PC( std::auto_ptr<this_type> r ) \
: base_type ( r ) { } \
\
PC& operator=( std::auto_ptr<this_type> r ) \
{ \
base_type::operator=( r ); \
return *this; \
} \
\
std::auto_ptr<this_type> release() \
{ \
std::auto_ptr<this_type> ptr( new this_type );\
this->swap( *ptr ); \
return ptr; \
} \
BOOST_PTR_CONTAINER_DEFINE_RELEASE( base_type ) \
\
std::auto_ptr<this_type> clone() const \
{ \
return std::auto_ptr<this_type>( new this_type( this->begin(), this->end() ) ); \
}
#define BOOST_PTR_CONTAINER_DEFINE_COPY_CONSTRUCTORS( PC, base_type ) \
\
template< class U > \
PC( const PC<U>& r ) : base_type( r ) { } \
\
PC& operator=( PC r ) \
{ \
this->swap( r ); \
return *this; \
} \
#define BOOST_PTR_CONTAINER_DEFINE_CONSTRUCTORS( PC, base_type ) \
typedef BOOST_DEDUCED_TYPENAME base_type::iterator iterator; \
typedef BOOST_DEDUCED_TYPENAME base_type::size_type size_type; \
typedef BOOST_DEDUCED_TYPENAME base_type::const_reference const_reference; \
typedef BOOST_DEDUCED_TYPENAME base_type::allocator_type allocator_type; \
PC() {} \
explicit PC( const allocator_type& a ) : base_type(a) {} \
template< class InputIterator > \
PC( InputIterator first, InputIterator last ) : base_type( first, last ) {} \
template< class InputIterator > \
PC( InputIterator first, InputIterator last, \
const allocator_type& a ) : base_type( first, last, a ) {}
#define BOOST_PTR_CONTAINER_DEFINE_NON_INHERITED_MEMBERS( PC, base_type, this_type ) \
BOOST_PTR_CONTAINER_DEFINE_CONSTRUCTORS( PC, base_type ) \
BOOST_PTR_CONTAINER_DEFINE_RELEASE_AND_CLONE( PC, base_type, this_type )
#define BOOST_PTR_CONTAINER_DEFINE_SEQEUENCE_MEMBERS( PC, base_type, this_type ) \
BOOST_PTR_CONTAINER_DEFINE_NON_INHERITED_MEMBERS( PC, base_type, this_type ) \
BOOST_PTR_CONTAINER_DEFINE_COPY_CONSTRUCTORS( PC, base_type )
} // namespace 'ptr_container_detail'
//
// @remark: expose movability of internal move-pointer
//
namespace ptr_container
{
using ptr_container_detail::move;
}
} // namespace 'boost'
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
#endif
| [
"819869472@qq.com"
] | 819869472@qq.com |
337a9615c60d2846da1e29a22186b387bf0cff8e | a241819fff55bd11a3b0150488cb0808ef3e83a5 | /leetcode/3sum/Time Limit Exceeded/8-12-2021, 5:22:16 PM/Solution.cpp | 4df810febff77fadf16f68b522bd70243ef6db07 | [] | no_license | paulkoba/Assignments_KNU_Y2 | 289c60eae0eb0420be1037e4bfd2b4695f897cbc | 56806023e5806367713ccb6ad7d042642a496d9d | refs/heads/main | 2023-08-20T17:46:06.175683 | 2021-10-24T13:02:40 | 2021-10-24T13:02:40 | 408,717,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | // https://leetcode.com/problems/3sum
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int sz = nums.size();
set<vector<int>> output;
for(int i = 0; i < sz; ++i) {
int k = sz - 1;
for(int j = i + 1; j < sz; ++j) {
while(k > j && nums[k] + nums[i] + nums[j] > 0) --k;
if(k > j && nums[k] + nums[i] + nums[j] == 0) {
vector<int> v = {nums[i], nums[j], nums[k]};
sort(v.begin(), v.end());
output.insert(v);
}
}
}
return vector<vector<int>>(output.begin(), output.end());
}
}; | [
"paul.koba@pm.me"
] | paul.koba@pm.me |
29d0de71b01a8d66a471f11b7962ab72bedd5245 | bc8ed17f37af50bd390bc1a1630159ecca574594 | /src/qt/paymentserver.h | 46c10ef92ad9c0892a616c0a9fec22fc1b9eef48 | [
"MIT"
] | permissive | proteanx/BITCORN | aaadef311428d1f07ed584983f037a64ff5a387e | 47dee72f81f89fb4b4d0c91227e9e6c768b81213 | refs/heads/master | 2020-09-07T15:26:33.140311 | 2019-11-16T18:28:08 | 2019-11-16T18:28:08 | 220,827,206 | 0 | 0 | MIT | 2019-11-10T17:49:46 | 2019-11-10T17:49:46 | null | UTF-8 | C++ | false | false | 4,586 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_PAYMENTSERVER_H
#define BITCOIN_QT_PAYMENTSERVER_H
// This class handles payment requests from clicking on
// bitcorn: URIs
//
// This is somewhat tricky, because we have to deal with
// the situation where the user clicks on a link during
// startup/initialization, when the splash-screen is up
// but the main window (and the Send Coins tab) is not.
//
// So, the strategy is:
//
// Create the server, and register the event handler,
// when the application is created. Save any URIs
// received at or during startup in a list.
//
// When startup is finished and the main window is
// shown, a signal is sent to slot uiReady(), which
// emits a receivedURL() signal for any payment
// requests that happened during startup.
//
// After startup, receivedURL() happens as usual.
//
// This class has one more feature: a static
// method that finds URIs passed in the command line
// and, if a server is running in another process,
// sends them to the server.
//
#include "paymentrequestplus.h"
#include "walletmodel.h"
#include <QObject>
#include <QString>
class OptionsModel;
class CWallet;
QT_BEGIN_NAMESPACE
class QApplication;
class QByteArray;
class QLocalServer;
class QNetworkAccessManager;
class QNetworkReply;
class QSslError;
class QUrl;
QT_END_NAMESPACE
// BIP70 max payment request size in bytes (DoS protection)
extern const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE;
class PaymentServer : public QObject
{
Q_OBJECT
public:
// Parse URIs on command line
// Returns false on error
static void ipcParseCommandLine(int argc, char* argv[]);
// Returns true if there were URIs on the command line
// which were successfully sent to an already-running
// process.
// Note: if a payment request is given, SelectParams(MAIN/TESTNET)
// will be called so we startup in the right mode.
static bool ipcSendCommandLine();
// parent should be QApplication object
PaymentServer(QObject* parent, bool startLocalServer = true);
~PaymentServer();
// Load root certificate authorities. Pass NULL (default)
// to read from the file specified in the -rootcertificates setting,
// or, if that's not set, to use the system default root certificates.
// If you pass in a store, you should not X509_STORE_free it: it will be
// freed either at exit or when another set of CAs are loaded.
static void LoadRootCAs(X509_STORE* store = NULL);
// Return certificate store
static X509_STORE* getCertStore();
// OptionsModel is used for getting proxy settings and display unit
void setOptionsModel(OptionsModel* optionsModel);
// This is now public, because we use it in paymentservertests.cpp
static bool readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request);
signals:
// Fired when a valid payment request is received
void receivedPaymentRequest(SendCoinsRecipient);
// Fired when a valid PaymentACK is received
void receivedPaymentACK(const QString& paymentACKMsg);
// Fired when a message should be reported to the user
void message(const QString& title, const QString& message, unsigned int style);
public slots:
// Signal this when the main window's UI is ready
// to display payment requests to the user
void uiReady();
// Submit Payment message to a merchant, get back PaymentACK:
void fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);
// Handle an incoming URI, URI with local file scheme or file
void handleURIOrFile(const QString& s);
private slots:
void handleURIConnection();
void netRequestFinished(QNetworkReply*);
void reportSslErrors(QNetworkReply*, const QList<QSslError>&);
void handlePaymentACK(const QString& paymentACKMsg);
protected:
// Constructor registers this on the parent QApplication to
// receive QEvent::FileOpen and QEvent:Drop events
bool eventFilter(QObject* object, QEvent* event);
private:
bool processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient);
void fetchRequest(const QUrl& url);
// Setup networking
void initNetManager();
bool saveURIs; // true during startup
QLocalServer* uriServer;
QNetworkAccessManager* netManager; // Used to fetch payment requests
OptionsModel* optionsModel;
};
#endif // BITCOIN_QT_PAYMENTSERVER_H
| [
"root@localhost"
] | root@localhost |
9938c4626aecd94ef91b9d8c0949dbb1c985a4bb | a6b4110496cc59c4aa05f41944dcf621b6e50120 | /build-Life-Desktop_Qt_5_15_2_GCC_64bit-Debug/ui_mainwindow.h | 2c46c65192842a5865e987687ef5d84d38417ab0 | [] | no_license | ramirez-gabriela27/life | bed43341b396dcd58f933673ab3a5dd1c1f033eb | 065b32516bd0aae7d5428625a5f0a3b6432fb218 | refs/heads/main | 2023-04-05T00:06:35.679288 | 2021-04-10T03:26:05 | 2021-04-10T03:26:05 | 351,944,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,670 | h | /********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.15.2
**
** 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/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QGraphicsView>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSlider>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionNew_Game;
QAction *actionChange_Color;
QWidget *centralwidget;
QWidget *horizontalLayoutWidget;
QHBoxLayout *horizontalLayout;
QPushButton *step_button;
QPushButton *play_button;
QPushButton *pause_button;
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout_2;
QLabel *faster_label;
QSlider *speed_slider;
QLabel *slower_label;
QLabel *speed_label;
QGraphicsView *graph_view;
QGraphicsView *grid_view;
QWidget *verticalLayoutWidget_2;
QVBoxLayout *verticalLayout_3;
QLabel *population_label;
QLabel *turn_label;
QMenuBar *menubar;
QMenu *File_button;
QMenu *menuEdit;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(800, 590);
actionNew_Game = new QAction(MainWindow);
actionNew_Game->setObjectName(QString::fromUtf8("actionNew_Game"));
actionChange_Color = new QAction(MainWindow);
actionChange_Color->setObjectName(QString::fromUtf8("actionChange_Color"));
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
horizontalLayoutWidget = new QWidget(centralwidget);
horizontalLayoutWidget->setObjectName(QString::fromUtf8("horizontalLayoutWidget"));
horizontalLayoutWidget->setGeometry(QRect(10, 450, 781, 101));
horizontalLayout = new QHBoxLayout(horizontalLayoutWidget);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
step_button = new QPushButton(horizontalLayoutWidget);
step_button->setObjectName(QString::fromUtf8("step_button"));
horizontalLayout->addWidget(step_button);
play_button = new QPushButton(horizontalLayoutWidget);
play_button->setObjectName(QString::fromUtf8("play_button"));
horizontalLayout->addWidget(play_button);
pause_button = new QPushButton(horizontalLayoutWidget);
pause_button->setObjectName(QString::fromUtf8("pause_button"));
horizontalLayout->addWidget(pause_button);
verticalLayout = new QVBoxLayout();
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
faster_label = new QLabel(horizontalLayoutWidget);
faster_label->setObjectName(QString::fromUtf8("faster_label"));
horizontalLayout_2->addWidget(faster_label);
speed_slider = new QSlider(horizontalLayoutWidget);
speed_slider->setObjectName(QString::fromUtf8("speed_slider"));
speed_slider->setOrientation(Qt::Horizontal);
horizontalLayout_2->addWidget(speed_slider);
slower_label = new QLabel(horizontalLayoutWidget);
slower_label->setObjectName(QString::fromUtf8("slower_label"));
horizontalLayout_2->addWidget(slower_label);
verticalLayout->addLayout(horizontalLayout_2);
speed_label = new QLabel(horizontalLayoutWidget);
speed_label->setObjectName(QString::fromUtf8("speed_label"));
verticalLayout->addWidget(speed_label);
horizontalLayout->addLayout(verticalLayout);
graph_view = new QGraphicsView(centralwidget);
graph_view->setObjectName(QString::fromUtf8("graph_view"));
graph_view->setGeometry(QRect(10, 350, 781, 101));
grid_view = new QGraphicsView(centralwidget);
grid_view->setObjectName(QString::fromUtf8("grid_view"));
grid_view->setGeometry(QRect(10, 80, 781, 271));
verticalLayoutWidget_2 = new QWidget(centralwidget);
verticalLayoutWidget_2->setObjectName(QString::fromUtf8("verticalLayoutWidget_2"));
verticalLayoutWidget_2->setGeometry(QRect(10, 10, 781, 61));
verticalLayout_3 = new QVBoxLayout(verticalLayoutWidget_2);
verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
verticalLayout_3->setContentsMargins(0, 0, 0, 0);
population_label = new QLabel(verticalLayoutWidget_2);
population_label->setObjectName(QString::fromUtf8("population_label"));
verticalLayout_3->addWidget(population_label);
turn_label = new QLabel(verticalLayoutWidget_2);
turn_label->setObjectName(QString::fromUtf8("turn_label"));
verticalLayout_3->addWidget(turn_label);
MainWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(MainWindow);
menubar->setObjectName(QString::fromUtf8("menubar"));
menubar->setGeometry(QRect(0, 0, 800, 22));
File_button = new QMenu(menubar);
File_button->setObjectName(QString::fromUtf8("File_button"));
menuEdit = new QMenu(menubar);
menuEdit->setObjectName(QString::fromUtf8("menuEdit"));
MainWindow->setMenuBar(menubar);
menubar->addAction(File_button->menuAction());
menubar->addAction(menuEdit->menuAction());
File_button->addAction(actionNew_Game);
menuEdit->addAction(actionChange_Color);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QCoreApplication::translate("MainWindow", "MainWindow", nullptr));
actionNew_Game->setText(QCoreApplication::translate("MainWindow", "New Game", nullptr));
actionChange_Color->setText(QCoreApplication::translate("MainWindow", "Change Color", nullptr));
step_button->setText(QCoreApplication::translate("MainWindow", "Step", nullptr));
play_button->setText(QCoreApplication::translate("MainWindow", "Play", nullptr));
pause_button->setText(QCoreApplication::translate("MainWindow", "Pause", nullptr));
faster_label->setText(QCoreApplication::translate("MainWindow", "Slower", nullptr));
slower_label->setText(QCoreApplication::translate("MainWindow", "Faster", nullptr));
speed_label->setText(QCoreApplication::translate("MainWindow", "Speed: 0", nullptr));
population_label->setText(QCoreApplication::translate("MainWindow", "Population: 0 (0%)", nullptr));
turn_label->setText(QCoreApplication::translate("MainWindow", "Turn: 0", nullptr));
File_button->setTitle(QCoreApplication::translate("MainWindow", "File", nullptr));
menuEdit->setTitle(QCoreApplication::translate("MainWindow", "Edit", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| [
"tolosaramirez.gabriela12@hotmail.com"
] | tolosaramirez.gabriela12@hotmail.com |
ada68118b188eb985e25fe4d715cef868c70dfc9 | 18146d0b9af100224ccc9fa994529e66aab64944 | /src/irc.cpp | 897071cfb936ef4f420d1eb0fb06cd8de1d163d5 | [
"MIT"
] | permissive | proffilit/selitcoin | 587e9c3c9ed4183226cd7efa4e6c9a46927f34b6 | 4caaf7f463b60bf1360b4cca6613bc3ff9bc89e2 | refs/heads/master | 2021-01-17T06:48:13.434377 | 2016-06-29T17:10:17 | 2016-06-29T17:10:17 | 56,967,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,536 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
/* Dont advertise on IRC if we don't allow incoming connections */
if (mapArgs.count("-connect") || fNoListen)
return;
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
if (GetLocal(addrLocal, &addrIPv4))
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%u", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
if (addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #selitcoin2TEST3\r");
Send(hSocket, "WHO #selitcoin2TEST3\r");
} else {
// randomly join #selitcoin00-#selitcoin99
int channel_number = GetRandInt(100);
channel_number = 0; // Litecoin: for now, just use one channel
Send(hSocket, strprintf("JOIN #selitcoin2%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #selitcoin2%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
| [
"70proffilit70@gmail.com"
] | 70proffilit70@gmail.com |
bd5fa065abfb1254e587849209a756dbba4c7d6d | 41189993d1389dabc3d1d8a563c8f9327f31e008 | /C-LinkedLists2-Worksheet/merge2LinkedLists.cpp | 4311d485e3737ce6db254f17662e3c2d15061ff2 | [] | no_license | RaviTejaKomma/learn-c-programming | d445e6f015b823781f833464f6b22e717d832d3c | 1793213a89a04f6fee459d2fe5c688571ab7d9fe | refs/heads/master | 2023-03-23T08:59:21.500253 | 2021-03-06T15:59:21 | 2021-03-06T15:59:21 | 345,133,585 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | /*
OVERVIEW: Merge two sorted linked lists.
E.g.: 1->3->5 and 2->4, output is 1->2->3->4->5.
INPUTS: Two sorted linked lists.
OUTPUT: Return merged sorted linked list.
ERROR CASES: Return NULL for error cases.
NOTES:
*/
#include <stdio.h>
struct node {
int num;
struct node *next;
};
struct node * merge2LinkedLists(struct node *head1, struct node *head2)
{
struct node *result = NULL;
/* Base cases */
if (head1 == NULL)
return(head2);
else if (head2 == NULL)
return(head1);
/* Pick either a or b, and recur */
if (head1->num <= head2->num)
{
result = head1;
result->next = merge2LinkedLists(head1->next, head2);
}
else
{
result = head2;
result->next =merge2LinkedLists(head1, head2->next);
}
return result;
}
| [
"ravieee929374s@gmail.com"
] | ravieee929374s@gmail.com |
6f1bf3f313ef9264fe249e782720179ede46b589 | bb6ebff7a7f6140903d37905c350954ff6599091 | /content/renderer/media/android/renderer_demuxer_android.h | 2a92918bb7a7ea104c55958d1358b9525fab6c02 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 2,915 | h | // Copyright 2013 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 CONTENT_RENDERER_MEDIA_ANDROID_RENDERER_DEMUXER_ANDROID_H_
#define CONTENT_RENDERER_MEDIA_ANDROID_RENDERER_DEMUXER_ANDROID_H_
#include "base/atomic_sequence_num.h"
#include "base/id_map.h"
#include "ipc/message_filter.h"
#include "media/base/android/demuxer_stream_player_params.h"
namespace base {
class MessageLoopProxy;
}
namespace content {
class MediaSourceDelegate;
class ThreadSafeSender;
// Represents the renderer process half of an IPC-based implementation of
// media::DemuxerAndroid.
//
// Refer to BrowserDemuxerAndroid for the browser process half.
class RendererDemuxerAndroid : public IPC::MessageFilter {
public:
RendererDemuxerAndroid();
// Returns the next available demuxer client ID for use in IPC messages.
//
// Safe to call on any thread.
int GetNextDemuxerClientID();
// Associates |delegate| with |demuxer_client_id| for handling incoming IPC
// messages.
//
// Must be called on media thread.
void AddDelegate(int demuxer_client_id, MediaSourceDelegate* delegate);
// Removes the association created by AddDelegate().
//
// Must be called on media thread.
void RemoveDelegate(int demuxer_client_id);
// IPC::MessageFilter overrides.
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
// media::DemuxerAndroidClient "implementation".
//
// TODO(scherkus): Consider having RendererDemuxerAndroid actually implement
// media::DemuxerAndroidClient and MediaSourceDelegate actually implement
// media::DemuxerAndroid.
void DemuxerReady(int demuxer_client_id,
const media::DemuxerConfigs& configs);
void ReadFromDemuxerAck(int demuxer_client_id,
const media::DemuxerData& data);
void DemuxerSeekDone(int demuxer_client_id,
const base::TimeDelta& actual_browser_seek_time);
void DurationChanged(int demuxer_client_id, const base::TimeDelta& duration);
protected:
friend class base::RefCountedThreadSafe<RendererDemuxerAndroid>;
virtual ~RendererDemuxerAndroid();
private:
void DispatchMessage(const IPC::Message& message);
void OnReadFromDemuxer(int demuxer_client_id,
media::DemuxerStream::Type type);
void OnDemuxerSeekRequest(int demuxer_client_id,
const base::TimeDelta& time_to_seek,
bool is_browser_seek);
base::AtomicSequenceNumber next_demuxer_client_id_;
IDMap<MediaSourceDelegate> delegates_;
scoped_refptr<ThreadSafeSender> thread_safe_sender_;
scoped_refptr<base::MessageLoopProxy> media_message_loop_;
DISALLOW_COPY_AND_ASSIGN(RendererDemuxerAndroid);
};
} // namespace content
#endif // CONTENT_RENDERER_MEDIA_ANDROID_RENDERER_DEMUXER_ANDROID_H_
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
2ed24fc6a84f7ae78d609285c4eff60ecf704e2f | 7e62f0928681aaaecae7daf360bdd9166299b000 | /external/DirectXShaderCompiler/tools/clang/test/SemaTemplate/derived.cpp | fcf68452529e65ac9a2b1fe54dd564d6b1da2a1f | [
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yuri410/rpg | 949b001bd0aec47e2a046421da0ff2a1db62ce34 | 266282ed8cfc7cd82e8c853f6f01706903c24628 | refs/heads/master | 2020-08-03T09:39:42.253100 | 2020-06-16T15:38:03 | 2020-06-16T15:38:03 | 211,698,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | cpp | // RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s
template<typename T> class vector2 {};
template<typename T> class vector : vector2<T> {};
template<typename T> void Foo2(vector2<const T*> V) {} // expected-note{{candidate template ignored: can't deduce a type for 'T' that would make 'const T' equal 'int'}}
template<typename T> void Foo(vector<const T*> V) {} // expected-note {{candidate template ignored: can't deduce a type for 'T' that would make 'const T' equal 'int'}}
void test() {
Foo2(vector2<int*>()); // expected-error{{no matching function for call to 'Foo2'}}
Foo(vector<int*>()); // expected-error{{no matching function for call to 'Foo'}}
}
namespace rdar13267210 {
template < typename T > class A {
BaseTy; // expected-error{{C++ requires a type specifier for all declarations}}
};
template < typename T, int N > class C: A < T > {};
class B {
C<long, 16> ExternalDefinitions;
C<long, 64> &Record;
void AddSourceLocation(A<long> &R); // expected-note{{passing argument to parameter 'R' here}}
void AddTemplateKWAndArgsInfo() {
AddSourceLocation(Record); // expected-error{{non-const lvalue reference to type}}
}
};
}
namespace PR16292 {
class IncompleteClass; // expected-note{{forward declaration}}
class BaseClass {
IncompleteClass Foo; // expected-error{{field has incomplete type}}
};
template<class T> class DerivedClass : public BaseClass {};
void* p = new DerivedClass<void>;
}
namespace rdar14183893 {
class Typ { // expected-note {{not complete}}
Typ x; // expected-error {{incomplete type}}
};
template <unsigned C> class B : Typ {};
typedef B<0> TFP;
class A {
TFP m_p;
void Enable() { 0, A(); } // expected-warning {{unused}}
};
}
| [
"yuri410@users.noreply.github.com"
] | yuri410@users.noreply.github.com |
0b192e4e4cbc56b215a54169ead11a58265312dc | 1d5f586fe70e567606c0ad3f597edef946c2a557 | /type_traits.h | 0e484aa5abe1f424662d0dbf998f2b1cf3ea8f7f | [] | no_license | Niconiconi233/STL | 1e2b00372ecb3cd536b089644c794366efb8864d | 4983926aa42fa76a1dbf8e962fd5a1f182ee52bc | refs/heads/master | 2020-04-12T00:37:50.566748 | 2018-12-18T00:19:54 | 2018-12-18T00:19:54 | 162,206,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,152 | h | #pragma once
struct __true_type {};
struct __false_type {};
template<typename type>
struct __type_traits {
typedef __true_type this_dummy_member_must_be_first;
typedef __false_type has_trivial_default_constructor;
typedef __false_type has_trivial_copy_constructor;
typedef __false_type has_trivial_assignment_operator;
typedef __false_type has_trivial_destructor;
typedef __false_type is_POD_type;
};
template<>
struct __type_traits<char>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<signed char>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned char>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<short>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned short>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<int>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned int>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<long>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<unsigned long>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<float>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<double>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits<long double>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<typename T>
struct __type_traits<T*>
{
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_operator;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
| [
"1660994874@qq.com"
] | 1660994874@qq.com |
8035310204a5c4e27869b85d7529e1dc97c9e27c | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/skia/gm/runtimecolorfilter.cpp | 587745f6ee37482967f732a678905c3ae3f7b6da | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 7,420 | cpp | /*
* Copyright 2019 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColorFilter.h"
#include "include/core/SkColorSpace.h"
#include "include/core/SkData.h"
#include "include/core/SkImage.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRSXform.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkSurface.h"
#include "include/core/SkVertices.h"
#include "include/effects/SkRuntimeEffect.h"
#include "tools/Resources.h"
#include <stddef.h>
#include <utility>
const char* gNoop = R"(
half4 main(half4 color) {
return color;
}
)";
const char* gLumaSrc = R"(
half4 main(half4 color) {
return dot(color.rgb, half3(0.3, 0.6, 0.1)).000r;
}
)";
// Build up the same effect with increasingly complex control flow syntax.
// All of these are semantically equivalent and can be reduced in principle to one basic block.
// Simplest to run; hardest to write?
const char* gTernary = R"(
half4 main(half4 color) {
half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
half scale = luma < 0.33333 ? 0.5
: luma < 0.66666 ? (0.166666 + 2.0 * (luma - 0.33333)) / luma
: /* else */ (0.833333 + 0.5 * (luma - 0.66666)) / luma;
return half4(color.rgb * scale, color.a);
}
)";
// Uses conditional if statements but no early return.
const char* gIfs = R"(
half4 main(half4 color) {
half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
half scale = 0;
if (luma < 0.33333) {
scale = 0.5;
} else if (luma < 0.66666) {
scale = (0.166666 + 2.0 * (luma - 0.33333)) / luma;
} else {
scale = (0.833333 + 0.5 * (luma - 0.66666)) / luma;
}
return half4(color.rgb * scale, color.a);
}
)";
// Distilled from AOSP tone mapping shaders, more like what people tend to write.
const char* gEarlyReturn = R"(
half4 main(half4 color) {
half luma = dot(color.rgb, half3(0.3, 0.6, 0.1));
half scale = 0;
if (luma < 0.33333) {
return half4(color.rgb * 0.5, color.a);
} else if (luma < 0.66666) {
scale = 0.166666 + 2.0 * (luma - 0.33333);
} else {
scale = 0.833333 + 0.5 * (luma - 0.66666);
}
return half4(color.rgb * (scale/luma), color.a);
}
)";
class RuntimeColorFilterGM : public skiagm::GM {
public:
RuntimeColorFilterGM() = default;
protected:
SkString onShortName() override {
return SkString("runtimecolorfilter");
}
SkISize onISize() override {
return SkISize::Make(256 * 3, 256 * 2);
}
void onOnceBeforeDraw() override {
fImg = GetResourceAsImage("images/mandrill_256.png");
}
void onDraw(SkCanvas* canvas) override {
auto draw_filter = [&](const char* src) {
auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(src));
if (!effect) {
SkDebugf("%s\n%s\n", src, err.c_str());
}
SkASSERT(effect);
SkPaint p;
p.setColorFilter(effect->makeColorFilter(nullptr));
canvas->drawImage(fImg, 0, 0, SkSamplingOptions(), &p);
canvas->translate(256, 0);
};
for (const char* src : {gNoop, gLumaSrc}) {
draw_filter(src);
}
canvas->translate(-256*2, 256);
for (const char* src : {gTernary, gIfs, gEarlyReturn}) {
draw_filter(src);
}
}
sk_sp<SkImage> fImg;
};
DEF_GM(return new RuntimeColorFilterGM;)
DEF_SIMPLE_GM(runtimecolorfilter_vertices_atlas_and_patch, canvas, 404, 404) {
const SkRect r = SkRect::MakeWH(128, 128);
// Make a vertices that draws the same as SkRect 'r'.
SkPoint pos[4];
r.toQuad(pos);
constexpr SkColor kColors[] = {SK_ColorBLUE, SK_ColorGREEN, SK_ColorCYAN, SK_ColorYELLOW};
auto verts = SkVertices::MakeCopy(SkVertices::kTriangleFan_VertexMode, 4, pos, pos, kColors);
// Make an image from the vertices to do equivalent drawAtlas, drawPatch using an image shader.
auto info = SkImageInfo::Make({128, 128},
kRGBA_8888_SkColorType,
kPremul_SkAlphaType,
canvas->imageInfo().refColorSpace());
auto surf = SkSurfaces::Raster(info);
surf->getCanvas()->drawVertices(verts, SkBlendMode::kDst, SkPaint());
auto atlas = surf->makeImageSnapshot();
auto xform = SkRSXform::Make(1, 0, 0, 0);
// Make a patch that draws the same as the SkRect 'r'
SkVector vx = pos[1] - pos[0];
SkVector vy = pos[3] - pos[0];
vx.setLength(vx.length()/3.f);
vy.setLength(vy.length()/3.f);
const SkPoint cubics[12] = {
pos[0], pos[0] + vx, pos[1] - vx,
pos[1], pos[1] + vy, pos[2] - vy,
pos[2], pos[2] - vx, pos[3] + vx,
pos[3], pos[3] - vy, pos[0] + vy
};
auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString(gLumaSrc));
if (!effect) {
SkDebugf("%s\n%s\n", gLumaSrc, err.c_str());
}
SkASSERT(effect);
sk_sp<SkColorFilter> colorfilter = effect->makeColorFilter(nullptr);
auto makePaint = [&](bool useCF, bool useShader) {
SkPaint paint;
paint.setColorFilter(useCF ? colorfilter : nullptr);
paint.setShader(useShader ? atlas->makeShader(SkSamplingOptions{}) : nullptr);
return paint;
};
auto drawVertices = [&](float x, bool useCF, bool useShader) {
SkAutoCanvasRestore acr(canvas, /*doSave=*/true);
canvas->translate(x, 0);
// Use just the shader or just the vertex colors.
auto mode = useShader ? SkBlendMode::kSrc : SkBlendMode::kDst;
canvas->drawVertices(verts, mode, makePaint(useCF, useShader));
};
auto drawAtlas = [&](float x, bool useCF) {
SkAutoCanvasRestore acr(canvas, /*doSave=*/true);
canvas->translate(x, 0);
SkPaint paint = makePaint(useCF, /*useShader=*/false);
constexpr SkColor kColor = SK_ColorWHITE;
canvas->drawAtlas(atlas.get(),
&xform,
&r,
&kColor,
1,
SkBlendMode::kModulate,
SkSamplingOptions{},
nullptr,
&paint);
};
auto drawPatch = [&](float x, bool useCF) {
SkAutoCanvasRestore acr(canvas, true);
canvas->translate(x, 0);
SkPaint paint = makePaint(useCF, /*useShader=*/true);
canvas->drawPatch(cubics, nullptr, pos, SkBlendMode::kModulate, paint);
};
drawVertices( 0, /*useCF=*/false, /*useShader=*/false);
drawVertices( r.width() + 10, /*useCF=*/ true, /*useShader=*/false);
drawVertices(2*(r.width() + 10), /*useCF=*/ true, /*useShader=*/ true);
canvas->translate(0, r.height() + 10);
drawAtlas( 0, /*useCF=*/false);
drawAtlas(r.width() + 10, /*useCF=*/ true);
canvas->translate(0, r.height() + 10);
drawPatch( 0, /*useCF=*/false);
drawPatch(r.width() + 10, /*useCF=*/ true);
}
| [
"jengelh@inai.de"
] | jengelh@inai.de |
6ab01c4a11971a7bb6e07aa694552113b420dedb | 2d8fd39cd69eef110df23273d6092aa9b1f5f9fb | /Win10SysProgBookSamples/Chapter15/SimplePrimes2/SimplePrimes2.cpp | 7d278b4000b003930ab8b37359f93e5d334fe47e | [
"MIT"
] | permissive | Minh-An/windows-systems | 46c09f1545d476aa105501c5f1245049295e4e31 | 6390d1724a418f51d5b08495e846261ba265b46c | refs/heads/main | 2023-02-28T03:04:50.866856 | 2021-02-07T04:33:08 | 2021-02-07T04:33:08 | 334,592,948 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | // SimplePrimes2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <stdio.h>
#include "..\SimpleDll\Simple.h"
#include <delayimp.h>
bool IsLoaded() {
auto hModule = ::GetModuleHandle(L"simpledll");
printf("SimpleDll loaded: %s\n", hModule ? "Yes" : "No");
return hModule != nullptr;
}
int main() {
IsLoaded();
bool prime = IsPrime(17);
IsLoaded();
printf("17 is prime? %s\n", prime ? "Yes" : "No");
__FUnloadDelayLoadedDLL2("SimpleDll.dll");
IsLoaded();
prime = IsPrime(1234567);
IsLoaded();
return 0;
}
| [
"minh.an.doan@gmail.com"
] | minh.an.doan@gmail.com |
e83a6078b952bf444f8b6bb6e24e356e500539f9 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.007/IC4KETII | f78b8794b5377d0a32811c1651662f3d42db9ed0 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 839 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.007";
object IC4KETII;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 1.0985e-40;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
7448082a899ad2821aee56dbf8b31831ffbd2312 | 016da22e472f30a1401314ebff7048c076e18cb2 | /aws-cpp-sdk-chime/include/aws/chime/model/ListChannelModeratorsRequest.h | bd38f3aa3bb87e812fbe1a5b88391805ba18a5fd | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | meenakommo64/aws-sdk-cpp | 8637d6f42f45b9670d7275b0ce25f3595f7f4664 | 9ae103b392f08750a4091d69341f55a2607d38b7 | refs/heads/master | 2023-02-16T07:47:44.608531 | 2021-01-14T20:10:59 | 2021-01-14T20:10:59 | 329,810,141 | 0 | 0 | Apache-2.0 | 2021-01-15T04:45:34 | 2021-01-15T04:39:52 | null | UTF-8 | C++ | false | false | 5,176 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/chime/ChimeRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Http
{
class URI;
} //namespace Http
namespace Chime
{
namespace Model
{
/**
*/
class AWS_CHIME_API ListChannelModeratorsRequest : public ChimeRequest
{
public:
ListChannelModeratorsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ListChannelModerators"; }
Aws::String SerializePayload() const override;
void AddQueryStringParameters(Aws::Http::URI& uri) const override;
/**
* <p>The ARN of the channel.</p>
*/
inline const Aws::String& GetChannelArn() const{ return m_channelArn; }
/**
* <p>The ARN of the channel.</p>
*/
inline bool ChannelArnHasBeenSet() const { return m_channelArnHasBeenSet; }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetChannelArn(const Aws::String& value) { m_channelArnHasBeenSet = true; m_channelArn = value; }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetChannelArn(Aws::String&& value) { m_channelArnHasBeenSet = true; m_channelArn = std::move(value); }
/**
* <p>The ARN of the channel.</p>
*/
inline void SetChannelArn(const char* value) { m_channelArnHasBeenSet = true; m_channelArn.assign(value); }
/**
* <p>The ARN of the channel.</p>
*/
inline ListChannelModeratorsRequest& WithChannelArn(const Aws::String& value) { SetChannelArn(value); return *this;}
/**
* <p>The ARN of the channel.</p>
*/
inline ListChannelModeratorsRequest& WithChannelArn(Aws::String&& value) { SetChannelArn(std::move(value)); return *this;}
/**
* <p>The ARN of the channel.</p>
*/
inline ListChannelModeratorsRequest& WithChannelArn(const char* value) { SetChannelArn(value); return *this;}
/**
* <p>The maximum number of moderators that you want returned.</p>
*/
inline int GetMaxResults() const{ return m_maxResults; }
/**
* <p>The maximum number of moderators that you want returned.</p>
*/
inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }
/**
* <p>The maximum number of moderators that you want returned.</p>
*/
inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }
/**
* <p>The maximum number of moderators that you want returned.</p>
*/
inline ListChannelModeratorsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline ListChannelModeratorsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline ListChannelModeratorsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>The token passed by previous API calls until all requested moderators are
* returned.</p>
*/
inline ListChannelModeratorsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::String m_channelArn;
bool m_channelArnHasBeenSet;
int m_maxResults;
bool m_maxResultsHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
};
} // namespace Model
} // namespace Chime
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
0bb3f8b46332d0adaa2299920773de8bebc694a6 | 3346832d416fe9b01e70a32ec46a5e0b2e36a7d7 | /forestPlot.cpp | 47a2035cc1095f3635fce32651660cd390edd7dc | [
"MIT"
] | permissive | marcus-elia/complete-random-city | e19fe9880f0e9be55c81f8c112472b37c475bfbf | 5888cb6bb3f6487b9bf34c871980fc0a077aa279 | refs/heads/master | 2021-05-23T12:47:10.173596 | 2020-11-20T18:30:00 | 2020-11-20T18:30:00 | 253,292,352 | 2 | 0 | null | 2020-10-07T22:22:45 | 2020-04-05T17:29:04 | C++ | UTF-8 | C++ | false | false | 2,157 | cpp | #include "forestPlot.h"
ForestPlot::ForestPlot() : Plot()
{
plotType = Forest;
level = 0;
initializeTrees();
}
ForestPlot::ForestPlot(Point2D inputTopLeftChunkCoords, Point2D inputCenter, int inputSideLength, int inputLevel) :
Plot(inputTopLeftChunkCoords, inputCenter, inputSideLength)
{
plotType = Forest;
level = inputLevel;
initializeTrees();
}
void ForestPlot::initializeTrees()
{
trees = std::vector<Tree>();
//int numTreeAttempts = 2*level + (rand() % 3);
int numTreeAttempts = level*1.25;
for(int i = 0; i < numTreeAttempts; i++)
{
Point2D p = getRandomPoint();
double r = 8 + rand() % 2;
if(isValidTreeLocation(p, r) && (rand() % 100 > 80))
{
Point location = {static_cast<double>(p.x), 0, static_cast<double>(p.z)};
double trunkHeight = 25 + (rand() % 20) + 4*level;
double leavesHeight = 15 + (rand() % 14) + 3*level;
double leavesXZRadius = 3*r + 2 + (rand() % 20) + level;
trees.emplace_back(location, trunkHeight, r, leavesHeight, leavesXZRadius);
}
}
}
Point2D ForestPlot::getRandomPoint() const
{
return {center.x + (rand() % sideLength) - sideLength/2, center.z + (rand() % sideLength) - sideLength/2};
}
bool ForestPlot::isValidTreeLocation(Point2D potentialLocation, double radius) const
{
// Check edges
int x = potentialLocation.x;
int z = potentialLocation.z;
if(x - (center.x - sideLength/2) < radius || (center.x + sideLength/2) - x < radius ||
z - (center.z - sideLength/2) < radius || (center.z + sideLength/2) - z < radius)
{
return false;
}
// Check other trees
for(const Tree &t : trees)
{
Point p = {static_cast<double>(potentialLocation.x), 0, static_cast<double>(potentialLocation.z)};
if(t.conflictsWithTree(p, radius))
{
return false;
}
}
return true;
}
int ForestPlot::getLevel() const
{
return level;
}
void ForestPlot::setLevel(int inputLevel)
{
level = inputLevel;
}
void ForestPlot::draw()
{
for(Tree &t : trees)
{
t.draw();
}
} | [
"mselia@uvm.edu"
] | mselia@uvm.edu |
9a1b0485252100dafd3f4a56b1d2cc97f2cfc357 | cd213678fb67ec29df77473b4097848ed4d8f749 | /Estructura de Datos/Arbol binario AVL/node.h | 9676692977f6b555b610f2132c4ba69afce1dd90 | [] | no_license | KelvinHelmut/ULaSalle | 772739026fde72571b6cbc6eaa3a5399d4d36132 | a1915917cdbb7eba8cc8d49fc52a8c0c163870f3 | refs/heads/master | 2020-04-15T04:41:13.215220 | 2015-10-26T04:27:15 | 2015-10-26T04:27:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | h | #ifndef NODE_H
#define NODE_H
#include <iostream>
template<class T>
class Node {
public:
Node(T value) : value(value), factor(0) { childs[0] = childs[1] = 0; }
T value;
int factor;
Node *childs[2];
};
#endif
| [
"aek6.io@gmail.com"
] | aek6.io@gmail.com |
74d04eeeb0065c487e2084a5b1ea0ad1323c70c4 | 7f9700ad469107c226148d7961e5b4e4c49182b9 | /SymbolExtracting.h | 4b34c9fbdab56ea3e7a2e2bad3944e429bcc59d9 | [] | no_license | sstadelman/obfuscation-include | 3d4cde150c9e68786eb1ef6a015a621b495175c2 | 2082a42abe46809180d415e61302a757359efc3b | refs/heads/master | 2020-11-23T18:28:19.431445 | 2019-12-13T05:57:26 | 2019-12-13T05:57:26 | 227,766,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,258 | h | #ifndef SymbolExtracting_h
#define SymbolExtracting_h
#include "swift/Obfuscation/DataStructures.h"
#include "llvm/Support/Error.h"
#include <string>
namespace swift {
namespace obfuscation {
/// Performs the symbol extraction from the Swift source code files included
/// in the FilesJson structure.
///
/// It utilizes the Swift compiler to perform the semantic analysis of
/// the Swift source files. Using the information encoded in FilesJson,
/// it creates the compiler invocation for the files, then it asks for
/// semantic analysis, and then it uses the results of the analysis (AST tree)
/// to identify the symbols in the Swift source code that should be obfuscated.
///
/// It's designed to be called from the Swift compiler command line tool.
///
/// Typical usage:
/// \code
/// std::string MainExecutablePath = llvm::sys::fs::getMainExecutable(
/// argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable));
/// auto SymbolsOrError = extractSymbols(FilesJson,
/// MainExecutablePath,
/// DiagnosticStream);
/// \endcode
///
/// \param FilesJson It's the structure containing information necessary for
/// the compiler to perform analysis (such as list of Swift source
/// files, list of libraries to link, path to SDK containing
/// the system libraries etc.).
/// \param MainExecutablePath Path to the directory containing the tool calling
/// this function. This is required for the compiler to use the relative
/// paths for it's inner workings (such as finding the necessary
/// libraries to dynamically link).
/// \param DiagnosticStream Stream for writing the diagnostic information into.
///
/// \returns llvm::Expected object containing either the extracted symbols
/// in the SymbolJson structure or the llvm::Error object with
/// the information on the failure cause.
llvm::Expected<SymbolsJson> extractSymbols(const FilesJson &FilesJson,
std::string MainExecutablePath,
llvm::raw_ostream &DiagnosticStream);
} //namespace obfuscation
} //namespace swift
#endif /* SymbolExtracting_h */
| [
"sstadelman@gmail.com"
] | sstadelman@gmail.com |
5679526eef20136a93c919875b3ae4a7be69d645 | fc38a55144a0ad33bd94301e2d06abd65bd2da3c | /thirdparty/bullet3/src/BulletCollision/NarrowPhaseCollision/btMprPenetration.h | ea946e2daa7d1030859c27551c85503550fdabc8 | [
"Zlib",
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | bobpepin/dust3d | 20fc2fa4380865bc6376724f0843100accd4b08d | 6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f | refs/heads/master | 2022-11-30T06:00:10.020207 | 2020-08-09T09:54:29 | 2020-08-09T09:54:29 | 286,051,200 | 0 | 0 | MIT | 2020-08-08T13:45:15 | 2020-08-08T13:45:14 | null | UTF-8 | C++ | false | false | 22,942 | h |
/***
* ---------------------------------
* Copyright (c)2012 Daniel Fiser <danfis@danfis.cz>
*
* This file was ported from mpr.c file, part of libccd.
* The Minkoski Portal Refinement implementation was ported
* to OpenCL by Erwin Coumans for the Bullet 3 Physics library.
* The original MPR idea and implementation is by Gary Snethen
* in XenoCollide, see http://github.com/erwincoumans/xenocollide
*
* Distributed under the OSI-approved BSD License (the "License");
* see <http://www.opensource.org/licenses/bsd-license.php>.
* This software is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the License for more information.
*/
///2014 Oct, Erwin Coumans, Use templates to avoid void* casts
#ifndef BT_MPR_PENETRATION_H
#define BT_MPR_PENETRATION_H
#define BT_DEBUG_MPR1
#include "LinearMath/btTransform.h"
#include "LinearMath/btAlignedObjectArray.h"
//#define MPR_AVERAGE_CONTACT_POSITIONS
struct btMprCollisionDescription
{
btVector3 m_firstDir;
int m_maxGjkIterations;
btScalar m_maximumDistanceSquared;
btScalar m_gjkRelError2;
btMprCollisionDescription()
: m_firstDir(0, 1, 0),
m_maxGjkIterations(1000),
m_maximumDistanceSquared(1e30f),
m_gjkRelError2(1.0e-6)
{
}
virtual ~btMprCollisionDescription()
{
}
};
struct btMprDistanceInfo
{
btVector3 m_pointOnA;
btVector3 m_pointOnB;
btVector3 m_normalBtoA;
btScalar m_distance;
};
#ifdef __cplusplus
#define BT_MPR_SQRT sqrtf
#else
#define BT_MPR_SQRT sqrt
#endif
#define BT_MPR_FMIN(x, y) ((x) < (y) ? (x) : (y))
#define BT_MPR_FABS fabs
#define BT_MPR_TOLERANCE 1E-6f
#define BT_MPR_MAX_ITERATIONS 1000
struct _btMprSupport_t
{
btVector3 v; //!< Support point in minkowski sum
btVector3 v1; //!< Support point in obj1
btVector3 v2; //!< Support point in obj2
};
typedef struct _btMprSupport_t btMprSupport_t;
struct _btMprSimplex_t
{
btMprSupport_t ps[4];
int last; //!< index of last added point
};
typedef struct _btMprSimplex_t btMprSimplex_t;
inline btMprSupport_t *btMprSimplexPointW(btMprSimplex_t *s, int idx)
{
return &s->ps[idx];
}
inline void btMprSimplexSetSize(btMprSimplex_t *s, int size)
{
s->last = size - 1;
}
#ifdef DEBUG_MPR
inline void btPrintPortalVertex(_btMprSimplex_t *portal, int index)
{
printf("portal[%d].v = %f,%f,%f, v1=%f,%f,%f, v2=%f,%f,%f\n", index, portal->ps[index].v.x(), portal->ps[index].v.y(), portal->ps[index].v.z(),
portal->ps[index].v1.x(), portal->ps[index].v1.y(), portal->ps[index].v1.z(),
portal->ps[index].v2.x(), portal->ps[index].v2.y(), portal->ps[index].v2.z());
}
#endif //DEBUG_MPR
inline int btMprSimplexSize(const btMprSimplex_t *s)
{
return s->last + 1;
}
inline const btMprSupport_t *btMprSimplexPoint(const btMprSimplex_t *s, int idx)
{
// here is no check on boundaries
return &s->ps[idx];
}
inline void btMprSupportCopy(btMprSupport_t *d, const btMprSupport_t *s)
{
*d = *s;
}
inline void btMprSimplexSet(btMprSimplex_t *s, size_t pos, const btMprSupport_t *a)
{
btMprSupportCopy(s->ps + pos, a);
}
inline void btMprSimplexSwap(btMprSimplex_t *s, size_t pos1, size_t pos2)
{
btMprSupport_t supp;
btMprSupportCopy(&supp, &s->ps[pos1]);
btMprSupportCopy(&s->ps[pos1], &s->ps[pos2]);
btMprSupportCopy(&s->ps[pos2], &supp);
}
inline int btMprIsZero(float val)
{
return BT_MPR_FABS(val) < FLT_EPSILON;
}
inline int btMprEq(float _a, float _b)
{
float ab;
float a, b;
ab = BT_MPR_FABS(_a - _b);
if (BT_MPR_FABS(ab) < FLT_EPSILON)
return 1;
a = BT_MPR_FABS(_a);
b = BT_MPR_FABS(_b);
if (b > a)
{
return ab < FLT_EPSILON * b;
}
else
{
return ab < FLT_EPSILON * a;
}
}
inline int btMprVec3Eq(const btVector3 *a, const btVector3 *b)
{
return btMprEq((*a).x(), (*b).x()) && btMprEq((*a).y(), (*b).y()) && btMprEq((*a).z(), (*b).z());
}
template <typename btConvexTemplate>
inline void btFindOrigin(const btConvexTemplate &a, const btConvexTemplate &b, const btMprCollisionDescription &colDesc, btMprSupport_t *center)
{
center->v1 = a.getObjectCenterInWorld();
center->v2 = b.getObjectCenterInWorld();
center->v = center->v1 - center->v2;
}
inline void btMprVec3Set(btVector3 *v, float x, float y, float z)
{
v->setValue(x, y, z);
}
inline void btMprVec3Add(btVector3 *v, const btVector3 *w)
{
*v += *w;
}
inline void btMprVec3Copy(btVector3 *v, const btVector3 *w)
{
*v = *w;
}
inline void btMprVec3Scale(btVector3 *d, float k)
{
*d *= k;
}
inline float btMprVec3Dot(const btVector3 *a, const btVector3 *b)
{
float dot;
dot = btDot(*a, *b);
return dot;
}
inline float btMprVec3Len2(const btVector3 *v)
{
return btMprVec3Dot(v, v);
}
inline void btMprVec3Normalize(btVector3 *d)
{
float k = 1.f / BT_MPR_SQRT(btMprVec3Len2(d));
btMprVec3Scale(d, k);
}
inline void btMprVec3Cross(btVector3 *d, const btVector3 *a, const btVector3 *b)
{
*d = btCross(*a, *b);
}
inline void btMprVec3Sub2(btVector3 *d, const btVector3 *v, const btVector3 *w)
{
*d = *v - *w;
}
inline void btPortalDir(const btMprSimplex_t *portal, btVector3 *dir)
{
btVector3 v2v1, v3v1;
btMprVec3Sub2(&v2v1, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 1)->v);
btMprVec3Sub2(&v3v1, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 1)->v);
btMprVec3Cross(dir, &v2v1, &v3v1);
btMprVec3Normalize(dir);
}
inline int portalEncapsulesOrigin(const btMprSimplex_t *portal,
const btVector3 *dir)
{
float dot;
dot = btMprVec3Dot(dir, &btMprSimplexPoint(portal, 1)->v);
return btMprIsZero(dot) || dot > 0.f;
}
inline int portalReachTolerance(const btMprSimplex_t *portal,
const btMprSupport_t *v4,
const btVector3 *dir)
{
float dv1, dv2, dv3, dv4;
float dot1, dot2, dot3;
// find the smallest dot product of dir and {v1-v4, v2-v4, v3-v4}
dv1 = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, dir);
dv2 = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, dir);
dv3 = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, dir);
dv4 = btMprVec3Dot(&v4->v, dir);
dot1 = dv4 - dv1;
dot2 = dv4 - dv2;
dot3 = dv4 - dv3;
dot1 = BT_MPR_FMIN(dot1, dot2);
dot1 = BT_MPR_FMIN(dot1, dot3);
return btMprEq(dot1, BT_MPR_TOLERANCE) || dot1 < BT_MPR_TOLERANCE;
}
inline int portalCanEncapsuleOrigin(const btMprSimplex_t *portal,
const btMprSupport_t *v4,
const btVector3 *dir)
{
float dot;
dot = btMprVec3Dot(&v4->v, dir);
return btMprIsZero(dot) || dot > 0.f;
}
inline void btExpandPortal(btMprSimplex_t *portal,
const btMprSupport_t *v4)
{
float dot;
btVector3 v4v0;
btMprVec3Cross(&v4v0, &v4->v, &btMprSimplexPoint(portal, 0)->v);
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, &v4v0);
if (dot > 0.f)
{
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, &v4v0);
if (dot > 0.f)
{
btMprSimplexSet(portal, 1, v4);
}
else
{
btMprSimplexSet(portal, 3, v4);
}
}
else
{
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, &v4v0);
if (dot > 0.f)
{
btMprSimplexSet(portal, 2, v4);
}
else
{
btMprSimplexSet(portal, 1, v4);
}
}
}
template <typename btConvexTemplate>
inline void btMprSupport(const btConvexTemplate &a, const btConvexTemplate &b,
const btMprCollisionDescription &colDesc,
const btVector3 &dir, btMprSupport_t *supp)
{
btVector3 seperatingAxisInA = dir * a.getWorldTransform().getBasis();
btVector3 seperatingAxisInB = -dir * b.getWorldTransform().getBasis();
btVector3 pInA = a.getLocalSupportWithMargin(seperatingAxisInA);
btVector3 qInB = b.getLocalSupportWithMargin(seperatingAxisInB);
supp->v1 = a.getWorldTransform()(pInA);
supp->v2 = b.getWorldTransform()(qInB);
supp->v = supp->v1 - supp->v2;
}
template <typename btConvexTemplate>
static int btDiscoverPortal(const btConvexTemplate &a, const btConvexTemplate &b,
const btMprCollisionDescription &colDesc,
btMprSimplex_t *portal)
{
btVector3 dir, va, vb;
float dot;
int cont;
// vertex 0 is center of portal
btFindOrigin(a, b, colDesc, btMprSimplexPointW(portal, 0));
// vertex 0 is center of portal
btMprSimplexSetSize(portal, 1);
btVector3 zero = btVector3(0, 0, 0);
btVector3 *org = &zero;
if (btMprVec3Eq(&btMprSimplexPoint(portal, 0)->v, org))
{
// Portal's center lies on origin (0,0,0) => we know that objects
// intersect but we would need to know penetration info.
// So move center little bit...
btMprVec3Set(&va, FLT_EPSILON * 10.f, 0.f, 0.f);
btMprVec3Add(&btMprSimplexPointW(portal, 0)->v, &va);
}
// vertex 1 = support in direction of origin
btMprVec3Copy(&dir, &btMprSimplexPoint(portal, 0)->v);
btMprVec3Scale(&dir, -1.f);
btMprVec3Normalize(&dir);
btMprSupport(a, b, colDesc, dir, btMprSimplexPointW(portal, 1));
btMprSimplexSetSize(portal, 2);
// test if origin isn't outside of v1
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 1)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
// vertex 2
btMprVec3Cross(&dir, &btMprSimplexPoint(portal, 0)->v,
&btMprSimplexPoint(portal, 1)->v);
if (btMprIsZero(btMprVec3Len2(&dir)))
{
if (btMprVec3Eq(&btMprSimplexPoint(portal, 1)->v, org))
{
// origin lies on v1
return 1;
}
else
{
// origin lies on v0-v1 segment
return 2;
}
}
btMprVec3Normalize(&dir);
btMprSupport(a, b, colDesc, dir, btMprSimplexPointW(portal, 2));
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 2)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
btMprSimplexSetSize(portal, 3);
// vertex 3 direction
btMprVec3Sub2(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Sub2(&vb, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&dir, &va, &vb);
btMprVec3Normalize(&dir);
// it is better to form portal faces to be oriented "outside" origin
dot = btMprVec3Dot(&dir, &btMprSimplexPoint(portal, 0)->v);
if (dot > 0.f)
{
btMprSimplexSwap(portal, 1, 2);
btMprVec3Scale(&dir, -1.f);
}
while (btMprSimplexSize(portal) < 4)
{
btMprSupport(a, b, colDesc, dir, btMprSimplexPointW(portal, 3));
dot = btMprVec3Dot(&btMprSimplexPoint(portal, 3)->v, &dir);
if (btMprIsZero(dot) || dot < 0.f)
return -1;
cont = 0;
// test if origin is outside (v1, v0, v3) - set v2 as v3 and
// continue
btMprVec3Cross(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 3)->v);
dot = btMprVec3Dot(&va, &btMprSimplexPoint(portal, 0)->v);
if (dot < 0.f && !btMprIsZero(dot))
{
btMprSimplexSet(portal, 2, btMprSimplexPoint(portal, 3));
cont = 1;
}
if (!cont)
{
// test if origin is outside (v3, v0, v2) - set v1 as v3 and
// continue
btMprVec3Cross(&va, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 2)->v);
dot = btMprVec3Dot(&va, &btMprSimplexPoint(portal, 0)->v);
if (dot < 0.f && !btMprIsZero(dot))
{
btMprSimplexSet(portal, 1, btMprSimplexPoint(portal, 3));
cont = 1;
}
}
if (cont)
{
btMprVec3Sub2(&va, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Sub2(&vb, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&dir, &va, &vb);
btMprVec3Normalize(&dir);
}
else
{
btMprSimplexSetSize(portal, 4);
}
}
return 0;
}
template <typename btConvexTemplate>
static int btRefinePortal(const btConvexTemplate &a, const btConvexTemplate &b, const btMprCollisionDescription &colDesc,
btMprSimplex_t *portal)
{
btVector3 dir;
btMprSupport_t v4;
for (int i = 0; i < BT_MPR_MAX_ITERATIONS; i++)
//while (1)
{
// compute direction outside the portal (from v0 throught v1,v2,v3
// face)
btPortalDir(portal, &dir);
// test if origin is inside the portal
if (portalEncapsulesOrigin(portal, &dir))
return 0;
// get next support point
btMprSupport(a, b, colDesc, dir, &v4);
// test if v4 can expand portal to contain origin and if portal
// expanding doesn't reach given tolerance
if (!portalCanEncapsuleOrigin(portal, &v4, &dir) || portalReachTolerance(portal, &v4, &dir))
{
return -1;
}
// v1-v2-v3 triangle must be rearranged to face outside Minkowski
// difference (direction from v0).
btExpandPortal(portal, &v4);
}
return -1;
}
static void btFindPos(const btMprSimplex_t *portal, btVector3 *pos)
{
btVector3 zero = btVector3(0, 0, 0);
btVector3 *origin = &zero;
btVector3 dir;
size_t i;
float b[4], sum, inv;
btVector3 vec, p1, p2;
btPortalDir(portal, &dir);
// use barycentric coordinates of tetrahedron to find origin
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 2)->v);
b[0] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 3)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 2)->v);
b[1] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 0)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 0)->v,
&btMprSimplexPoint(portal, 1)->v);
b[2] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 3)->v);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 1)->v);
b[3] = btMprVec3Dot(&vec, &btMprSimplexPoint(portal, 0)->v);
sum = b[0] + b[1] + b[2] + b[3];
if (btMprIsZero(sum) || sum < 0.f)
{
b[0] = 0.f;
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 2)->v,
&btMprSimplexPoint(portal, 3)->v);
b[1] = btMprVec3Dot(&vec, &dir);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 3)->v,
&btMprSimplexPoint(portal, 1)->v);
b[2] = btMprVec3Dot(&vec, &dir);
btMprVec3Cross(&vec, &btMprSimplexPoint(portal, 1)->v,
&btMprSimplexPoint(portal, 2)->v);
b[3] = btMprVec3Dot(&vec, &dir);
sum = b[1] + b[2] + b[3];
}
inv = 1.f / sum;
btMprVec3Copy(&p1, origin);
btMprVec3Copy(&p2, origin);
for (i = 0; i < 4; i++)
{
btMprVec3Copy(&vec, &btMprSimplexPoint(portal, i)->v1);
btMprVec3Scale(&vec, b[i]);
btMprVec3Add(&p1, &vec);
btMprVec3Copy(&vec, &btMprSimplexPoint(portal, i)->v2);
btMprVec3Scale(&vec, b[i]);
btMprVec3Add(&p2, &vec);
}
btMprVec3Scale(&p1, inv);
btMprVec3Scale(&p2, inv);
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &p1);
btMprVec3Add(pos, &p2);
btMprVec3Scale(pos, 0.5);
#else
btMprVec3Copy(pos, &p2);
#endif //MPR_AVERAGE_CONTACT_POSITIONS
}
inline float btMprVec3Dist2(const btVector3 *a, const btVector3 *b)
{
btVector3 ab;
btMprVec3Sub2(&ab, a, b);
return btMprVec3Len2(&ab);
}
inline float _btMprVec3PointSegmentDist2(const btVector3 *P,
const btVector3 *x0,
const btVector3 *b,
btVector3 *witness)
{
// The computation comes from solving equation of segment:
// S(t) = x0 + t.d
// where - x0 is initial point of segment
// - d is direction of segment from x0 (|d| > 0)
// - t belongs to <0, 1> interval
//
// Than, distance from a segment to some point P can be expressed:
// D(t) = |x0 + t.d - P|^2
// which is distance from any point on segment. Minimization
// of this function brings distance from P to segment.
// Minimization of D(t) leads to simple quadratic equation that's
// solving is straightforward.
//
// Bonus of this method is witness point for free.
float dist, t;
btVector3 d, a;
// direction of segment
btMprVec3Sub2(&d, b, x0);
// precompute vector from P to x0
btMprVec3Sub2(&a, x0, P);
t = -1.f * btMprVec3Dot(&a, &d);
t /= btMprVec3Len2(&d);
if (t < 0.f || btMprIsZero(t))
{
dist = btMprVec3Dist2(x0, P);
if (witness)
btMprVec3Copy(witness, x0);
}
else if (t > 1.f || btMprEq(t, 1.f))
{
dist = btMprVec3Dist2(b, P);
if (witness)
btMprVec3Copy(witness, b);
}
else
{
if (witness)
{
btMprVec3Copy(witness, &d);
btMprVec3Scale(witness, t);
btMprVec3Add(witness, x0);
dist = btMprVec3Dist2(witness, P);
}
else
{
// recycling variables
btMprVec3Scale(&d, t);
btMprVec3Add(&d, &a);
dist = btMprVec3Len2(&d);
}
}
return dist;
}
inline float btMprVec3PointTriDist2(const btVector3 *P,
const btVector3 *x0, const btVector3 *B,
const btVector3 *C,
btVector3 *witness)
{
// Computation comes from analytic expression for triangle (x0, B, C)
// T(s, t) = x0 + s.d1 + t.d2, where d1 = B - x0 and d2 = C - x0 and
// Then equation for distance is:
// D(s, t) = | T(s, t) - P |^2
// This leads to minimization of quadratic function of two variables.
// The solution from is taken only if s is between 0 and 1, t is
// between 0 and 1 and t + s < 1, otherwise distance from segment is
// computed.
btVector3 d1, d2, a;
float u, v, w, p, q, r;
float s, t, dist, dist2;
btVector3 witness2;
btMprVec3Sub2(&d1, B, x0);
btMprVec3Sub2(&d2, C, x0);
btMprVec3Sub2(&a, x0, P);
u = btMprVec3Dot(&a, &a);
v = btMprVec3Dot(&d1, &d1);
w = btMprVec3Dot(&d2, &d2);
p = btMprVec3Dot(&a, &d1);
q = btMprVec3Dot(&a, &d2);
r = btMprVec3Dot(&d1, &d2);
btScalar div = (w * v - r * r);
if (btMprIsZero(div))
{
s = -1;
}
else
{
s = (q * r - w * p) / div;
t = (-s * r - q) / w;
}
if ((btMprIsZero(s) || s > 0.f) && (btMprEq(s, 1.f) || s < 1.f) && (btMprIsZero(t) || t > 0.f) && (btMprEq(t, 1.f) || t < 1.f) && (btMprEq(t + s, 1.f) || t + s < 1.f))
{
if (witness)
{
btMprVec3Scale(&d1, s);
btMprVec3Scale(&d2, t);
btMprVec3Copy(witness, x0);
btMprVec3Add(witness, &d1);
btMprVec3Add(witness, &d2);
dist = btMprVec3Dist2(witness, P);
}
else
{
dist = s * s * v;
dist += t * t * w;
dist += 2.f * s * t * r;
dist += 2.f * s * p;
dist += 2.f * t * q;
dist += u;
}
}
else
{
dist = _btMprVec3PointSegmentDist2(P, x0, B, witness);
dist2 = _btMprVec3PointSegmentDist2(P, x0, C, &witness2);
if (dist2 < dist)
{
dist = dist2;
if (witness)
btMprVec3Copy(witness, &witness2);
}
dist2 = _btMprVec3PointSegmentDist2(P, B, C, &witness2);
if (dist2 < dist)
{
dist = dist2;
if (witness)
btMprVec3Copy(witness, &witness2);
}
}
return dist;
}
template <typename btConvexTemplate>
static void btFindPenetr(const btConvexTemplate &a, const btConvexTemplate &b,
const btMprCollisionDescription &colDesc,
btMprSimplex_t *portal,
float *depth, btVector3 *pdir, btVector3 *pos)
{
btVector3 dir;
btMprSupport_t v4;
unsigned long iterations;
btVector3 zero = btVector3(0, 0, 0);
btVector3 *origin = &zero;
iterations = 1UL;
for (int i = 0; i < BT_MPR_MAX_ITERATIONS; i++)
//while (1)
{
// compute portal direction and obtain next support point
btPortalDir(portal, &dir);
btMprSupport(a, b, colDesc, dir, &v4);
// reached tolerance -> find penetration info
if (portalReachTolerance(portal, &v4, &dir) || iterations == BT_MPR_MAX_ITERATIONS)
{
*depth = btMprVec3PointTriDist2(origin, &btMprSimplexPoint(portal, 1)->v, &btMprSimplexPoint(portal, 2)->v, &btMprSimplexPoint(portal, 3)->v, pdir);
*depth = BT_MPR_SQRT(*depth);
if (btMprIsZero((*pdir).x()) && btMprIsZero((*pdir).y()) && btMprIsZero((*pdir).z()))
{
*pdir = dir;
}
btMprVec3Normalize(pdir);
// barycentric coordinates:
btFindPos(portal, pos);
return;
}
btExpandPortal(portal, &v4);
iterations++;
}
}
static void btFindPenetrTouch(btMprSimplex_t *portal, float *depth, btVector3 *dir, btVector3 *pos)
{
// Touching contact on portal's v1 - so depth is zero and direction
// is unimportant and pos can be guessed
*depth = 0.f;
btVector3 zero = btVector3(0, 0, 0);
btVector3 *origin = &zero;
btMprVec3Copy(dir, origin);
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v1);
btMprVec3Add(pos, &btMprSimplexPoint(portal, 1)->v2);
btMprVec3Scale(pos, 0.5);
#else
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v2);
#endif
}
static void btFindPenetrSegment(btMprSimplex_t *portal,
float *depth, btVector3 *dir, btVector3 *pos)
{
// Origin lies on v0-v1 segment.
// Depth is distance to v1, direction also and position must be
// computed
#ifdef MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v1);
btMprVec3Add(pos, &btMprSimplexPoint(portal, 1)->v2);
btMprVec3Scale(pos, 0.5f);
#else
btMprVec3Copy(pos, &btMprSimplexPoint(portal, 1)->v2);
#endif //MPR_AVERAGE_CONTACT_POSITIONS
btMprVec3Copy(dir, &btMprSimplexPoint(portal, 1)->v);
*depth = BT_MPR_SQRT(btMprVec3Len2(dir));
btMprVec3Normalize(dir);
}
template <typename btConvexTemplate>
inline int btMprPenetration(const btConvexTemplate &a, const btConvexTemplate &b,
const btMprCollisionDescription &colDesc,
float *depthOut, btVector3 *dirOut, btVector3 *posOut)
{
btMprSimplex_t portal;
// Phase 1: Portal discovery
int result = btDiscoverPortal(a, b, colDesc, &portal);
//sepAxis[pairIndex] = *pdir;//or -dir?
switch (result)
{
case 0:
{
// Phase 2: Portal refinement
result = btRefinePortal(a, b, colDesc, &portal);
if (result < 0)
return -1;
// Phase 3. Penetration info
btFindPenetr(a, b, colDesc, &portal, depthOut, dirOut, posOut);
break;
}
case 1:
{
// Touching contact on portal's v1.
btFindPenetrTouch(&portal, depthOut, dirOut, posOut);
result = 0;
break;
}
case 2:
{
btFindPenetrSegment(&portal, depthOut, dirOut, posOut);
result = 0;
break;
}
default:
{
//if (res < 0)
//{
// Origin isn't inside portal - no collision.
result = -1;
//}
}
};
return result;
};
template <typename btConvexTemplate, typename btMprDistanceTemplate>
inline int btComputeMprPenetration(const btConvexTemplate &a, const btConvexTemplate &b, const btMprCollisionDescription &colDesc, btMprDistanceTemplate *distInfo)
{
btVector3 dir, pos;
float depth;
int res = btMprPenetration(a, b, colDesc, &depth, &dir, &pos);
if (res == 0)
{
distInfo->m_distance = -depth;
distInfo->m_pointOnB = pos;
distInfo->m_normalBtoA = -dir;
distInfo->m_pointOnA = pos - distInfo->m_distance * dir;
return 0;
}
return -1;
}
#endif //BT_MPR_PENETRATION_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
b5588882b044aff0bd57907e78600a5da0cb2fe7 | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /opencv/opencv-3.4.2/modules/imgproc/src/blend.cpp | b334e141304bd3b6941108a12c68510fa9031b4d | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 18,711 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Nathan, liujun@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencl_kernels_imgproc.hpp"
#include "opencv2/core/hal/intrin.hpp"
namespace cv {
#if CV_SIMD128
static inline v_float32x4 blend(const v_float32x4& v_src1, const v_float32x4& v_src2, const v_float32x4& v_w1, const v_float32x4& v_w2)
{
const v_float32x4 v_eps = v_setall_f32(1e-5f);
v_float32x4 v_denom = v_w1 + v_w2 + v_eps;
return (v_src1 * v_w1 + v_src2 * v_w2) / v_denom;
}
static inline v_float32x4 blend(const v_float32x4& v_src1, const v_float32x4& v_src2, const float* w_ptr1, const float* w_ptr2, int offset)
{
v_float32x4 v_w1 = v_load(w_ptr1 + offset);
v_float32x4 v_w2 = v_load(w_ptr2 + offset);
return blend(v_src1, v_src2, v_w1, v_w2);
}
static inline v_uint32x4 saturate_f32_u32(const v_float32x4& vec)
{
const v_int32x4 z = v_setzero_s32();
const v_int32x4 x = v_setall_s32(255);
return v_reinterpret_as_u32(v_min(v_max(v_round(vec), z), x));
}
static inline v_uint8x16 pack_f32tou8(v_float32x4& val0, v_float32x4& val1, v_float32x4& val2, v_float32x4& val3)
{
v_uint32x4 a = saturate_f32_u32(val0);
v_uint32x4 b = saturate_f32_u32(val1);
v_uint32x4 c = saturate_f32_u32(val2);
v_uint32x4 d = saturate_f32_u32(val3);
v_uint16x8 e = v_pack(a, b);
v_uint16x8 f = v_pack(c, d);
return v_pack(e, f);
}
static inline void store_pack_f32tou8(uchar* ptr, v_float32x4& val0, v_float32x4& val1, v_float32x4& val2, v_float32x4& val3)
{
v_store((ptr), pack_f32tou8(val0, val1, val2, val3));
}
static inline void expand_u8tof32(const v_uint8x16& src, v_float32x4& dst0, v_float32x4& dst1, v_float32x4& dst2, v_float32x4& dst3)
{
v_uint16x8 a0, a1;
v_expand(src, a0, a1);
v_uint32x4 b0, b1,b2,b3;
v_expand(a0, b0, b1);
v_expand(a1, b2, b3);
dst0 = v_cvt_f32(v_reinterpret_as_s32(b0));
dst1 = v_cvt_f32(v_reinterpret_as_s32(b1));
dst2 = v_cvt_f32(v_reinterpret_as_s32(b2));
dst3 = v_cvt_f32(v_reinterpret_as_s32(b3));
}
static inline void load_expand_u8tof32(const uchar* ptr, v_float32x4& dst0, v_float32x4& dst1, v_float32x4& dst2, v_float32x4& dst3)
{
v_uint8x16 a = v_load((ptr));
expand_u8tof32(a, dst0, dst1, dst2, dst3);
}
int blendLinearSimd128(const uchar* src1, const uchar* src2, const float* weights1, const float* weights2, uchar* dst, int x, int width, int cn);
int blendLinearSimd128(const float* src1, const float* src2, const float* weights1, const float* weights2, float* dst, int x, int width, int cn);
int blendLinearSimd128(const uchar* src1, const uchar* src2, const float* weights1, const float* weights2, uchar* dst, int x, int width, int cn)
{
int step = v_uint8x16::nlanes * cn;
int weight_step = v_uint8x16::nlanes;
switch(cn)
{
case 1:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += weight_step)
{
v_float32x4 v_src10, v_src11, v_src12, v_src13;
v_float32x4 v_src20, v_src21, v_src22, v_src23;
load_expand_u8tof32(src1 + x, v_src10, v_src11, v_src12, v_src13);
load_expand_u8tof32(src2 + x, v_src20, v_src21, v_src22, v_src23);
v_float32x4 v_dst0 = blend(v_src10, v_src20, weights1, weights2, weight_offset);
v_float32x4 v_dst1 = blend(v_src11, v_src21, weights1, weights2, weight_offset + 4);
v_float32x4 v_dst2 = blend(v_src12, v_src22, weights1, weights2, weight_offset + 8);
v_float32x4 v_dst3 = blend(v_src13, v_src23, weights1, weights2, weight_offset + 12);
store_pack_f32tou8(dst + x, v_dst0, v_dst1, v_dst2, v_dst3);
}
break;
case 2:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += weight_step)
{
v_uint8x16 v_src10, v_src11, v_src20, v_src21;
v_load_deinterleave(src1 + x, v_src10, v_src11);
v_load_deinterleave(src2 + x, v_src20, v_src21);
v_float32x4 v_src100, v_src101, v_src102, v_src103, v_src110, v_src111, v_src112, v_src113;
v_float32x4 v_src200, v_src201, v_src202, v_src203, v_src210, v_src211, v_src212, v_src213;
expand_u8tof32(v_src10, v_src100, v_src101, v_src102, v_src103);
expand_u8tof32(v_src11, v_src110, v_src111, v_src112, v_src113);
expand_u8tof32(v_src20, v_src200, v_src201, v_src202, v_src203);
expand_u8tof32(v_src21, v_src210, v_src211, v_src212, v_src213);
v_float32x4 v_dst0 = blend(v_src100, v_src200, weights1, weights2, weight_offset);
v_float32x4 v_dst1 = blend(v_src110, v_src210, weights1, weights2, weight_offset);
v_float32x4 v_dst2 = blend(v_src101, v_src201, weights1, weights2, weight_offset + 4);
v_float32x4 v_dst3 = blend(v_src111, v_src211, weights1, weights2, weight_offset + 4);
v_float32x4 v_dst4 = blend(v_src102, v_src202, weights1, weights2, weight_offset + 8);
v_float32x4 v_dst5 = blend(v_src112, v_src212, weights1, weights2, weight_offset + 8);
v_float32x4 v_dst6 = blend(v_src103, v_src203, weights1, weights2, weight_offset + 12);
v_float32x4 v_dst7 = blend(v_src113, v_src213, weights1, weights2, weight_offset + 12);
v_uint8x16 v_dsta = pack_f32tou8(v_dst0, v_dst2, v_dst4, v_dst6);
v_uint8x16 v_dstb = pack_f32tou8(v_dst1, v_dst3, v_dst5, v_dst7);
v_store_interleave(dst + x, v_dsta, v_dstb);
}
break;
case 3:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += weight_step)
{
v_uint8x16 v_src10, v_src11, v_src12, v_src20, v_src21, v_src22;
v_load_deinterleave(src1 + x, v_src10, v_src11, v_src12);
v_load_deinterleave(src2 + x, v_src20, v_src21, v_src22);
v_float32x4 v_src100, v_src101, v_src102, v_src103, v_src110, v_src111, v_src112, v_src113, v_src120, v_src121, v_src122, v_src123;
v_float32x4 v_src200, v_src201, v_src202, v_src203, v_src210, v_src211, v_src212, v_src213, v_src220, v_src221, v_src222, v_src223;
expand_u8tof32(v_src10, v_src100, v_src101, v_src102, v_src103);
expand_u8tof32(v_src11, v_src110, v_src111, v_src112, v_src113);
expand_u8tof32(v_src12, v_src120, v_src121, v_src122, v_src123);
expand_u8tof32(v_src20, v_src200, v_src201, v_src202, v_src203);
expand_u8tof32(v_src21, v_src210, v_src211, v_src212, v_src213);
expand_u8tof32(v_src22, v_src220, v_src221, v_src222, v_src223);
v_float32x4 v_w10 = v_load(weights1 + weight_offset);
v_float32x4 v_w11 = v_load(weights1 + weight_offset + 4);
v_float32x4 v_w12 = v_load(weights1 + weight_offset + 8);
v_float32x4 v_w13 = v_load(weights1 + weight_offset + 12);
v_float32x4 v_w20 = v_load(weights2 + weight_offset);
v_float32x4 v_w21 = v_load(weights2 + weight_offset + 4);
v_float32x4 v_w22 = v_load(weights2 + weight_offset + 8);
v_float32x4 v_w23 = v_load(weights2 + weight_offset + 12);
v_src100 = blend(v_src100, v_src200, v_w10, v_w20);
v_src110 = blend(v_src110, v_src210, v_w10, v_w20);
v_src120 = blend(v_src120, v_src220, v_w10, v_w20);
v_src101 = blend(v_src101, v_src201, v_w11, v_w21);
v_src111 = blend(v_src111, v_src211, v_w11, v_w21);
v_src121 = blend(v_src121, v_src221, v_w11, v_w21);
v_src102 = blend(v_src102, v_src202, v_w12, v_w22);
v_src112 = blend(v_src112, v_src212, v_w12, v_w22);
v_src122 = blend(v_src122, v_src222, v_w12, v_w22);
v_src103 = blend(v_src103, v_src203, v_w13, v_w23);
v_src113 = blend(v_src113, v_src213, v_w13, v_w23);
v_src123 = blend(v_src123, v_src223, v_w13, v_w23);
v_uint8x16 v_dst0 = pack_f32tou8(v_src100, v_src101, v_src102, v_src103);
v_uint8x16 v_dst1 = pack_f32tou8(v_src110, v_src111, v_src112, v_src113);
v_uint8x16 v_dst2 = pack_f32tou8(v_src120, v_src121, v_src122, v_src123);
v_store_interleave(dst + x, v_dst0, v_dst1, v_dst2);
}
break;
case 4:
step = v_uint8x16::nlanes;
weight_step = v_float32x4::nlanes;
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += weight_step)
{
v_float32x4 v_src10, v_src11, v_src12, v_src13, v_src14, v_src15, v_src16, v_src17;
v_float32x4 v_src20, v_src21, v_src22, v_src23, v_src24, v_src25, v_src26, v_src27;
load_expand_u8tof32(src1 + x, v_src10, v_src11, v_src12, v_src13);
load_expand_u8tof32(src2 + x, v_src20, v_src21, v_src22, v_src23);
v_transpose4x4(v_src10, v_src11, v_src12, v_src13, v_src14, v_src15, v_src16, v_src17);
v_transpose4x4(v_src20, v_src21, v_src22, v_src23, v_src24, v_src25, v_src26, v_src27);
v_float32x4 v_w1 = v_load(weights1 + weight_offset);
v_float32x4 v_w2 = v_load(weights2 + weight_offset);
v_src10 = blend(v_src14, v_src24, v_w1, v_w2);
v_src11 = blend(v_src15, v_src25, v_w1, v_w2);
v_src12 = blend(v_src16, v_src26, v_w1, v_w2);
v_src13 = blend(v_src17, v_src27, v_w1, v_w2);
v_float32x4 v_dst0, v_dst1, v_dst2, v_dst3;
v_transpose4x4(v_src10, v_src11, v_src12, v_src13, v_dst0, v_dst1, v_dst2, v_dst3);
store_pack_f32tou8(dst + x, v_dst0, v_dst1, v_dst2, v_dst3);
}
break;
default:
break;
}
return x;
}
int blendLinearSimd128(const float* src1, const float* src2, const float* weights1, const float* weights2, float* dst, int x, int width, int cn)
{
int step = v_float32x4::nlanes*cn;
switch(cn)
{
case 1:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += v_float32x4::nlanes)
{
v_float32x4 v_src1 = v_load(src1 + x);
v_float32x4 v_src2 = v_load(src2 + x);
v_float32x4 v_w1 = v_load(weights1 + weight_offset);
v_float32x4 v_w2 = v_load(weights2 + weight_offset);
v_float32x4 v_dst = blend(v_src1, v_src2, v_w1, v_w2);
v_store(dst + x, v_dst);
}
break;
case 2:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += v_float32x4::nlanes)
{
v_float32x4 v_src10, v_src11, v_src20, v_src21;
v_load_deinterleave(src1 + x, v_src10, v_src11);
v_load_deinterleave(src2 + x, v_src20, v_src21);
v_float32x4 v_w1 = v_load(weights1 + weight_offset);
v_float32x4 v_w2 = v_load(weights2 + weight_offset);
v_float32x4 v_dst0 = blend(v_src10, v_src20, v_w1, v_w2);
v_float32x4 v_dst1 = blend(v_src11, v_src21, v_w1, v_w2);
v_store_interleave(dst + x, v_dst0, v_dst1);
}
break;
case 3:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += v_float32x4::nlanes)
{
v_float32x4 v_src10, v_src11, v_src12, v_src20, v_src21, v_src22;
v_load_deinterleave(src1 + x, v_src10, v_src11, v_src12);
v_load_deinterleave(src2 + x, v_src20, v_src21, v_src22);
v_float32x4 v_w1 = v_load(weights1 + weight_offset);
v_float32x4 v_w2 = v_load(weights2 + weight_offset);
v_float32x4 v_dst0 = blend(v_src10, v_src20, v_w1, v_w2);
v_float32x4 v_dst1 = blend(v_src11, v_src21, v_w1, v_w2);
v_float32x4 v_dst2 = blend(v_src12, v_src22, v_w1, v_w2);
v_store_interleave(dst + x, v_dst0, v_dst1, v_dst2);
}
break;
case 4:
for(int weight_offset = 0 ; x <= width - step; x += step, weight_offset += v_float32x4::nlanes)
{
v_float32x4 v_src10, v_src11, v_src12, v_src13, v_src20, v_src21, v_src22, v_src23;
v_load_deinterleave(src1 + x, v_src10, v_src11, v_src12, v_src13);
v_load_deinterleave(src2 + x, v_src20, v_src21, v_src22, v_src23);
v_float32x4 v_w1 = v_load(weights1 + weight_offset);
v_float32x4 v_w2 = v_load(weights2 + weight_offset);
v_float32x4 v_dst0 = blend(v_src10, v_src20, v_w1, v_w2);
v_float32x4 v_dst1 = blend(v_src11, v_src21, v_w1, v_w2);
v_float32x4 v_dst2 = blend(v_src12, v_src22, v_w1, v_w2);
v_float32x4 v_dst3 = blend(v_src13, v_src23, v_w1, v_w2);
v_store_interleave(dst + x, v_dst0, v_dst1, v_dst2, v_dst3);
}
break;
default:
break;
}
return x;
}
#endif
template <typename T>
class BlendLinearInvoker :
public ParallelLoopBody
{
public:
BlendLinearInvoker(const Mat & _src1, const Mat & _src2, const Mat & _weights1,
const Mat & _weights2, Mat & _dst) :
src1(&_src1), src2(&_src2), weights1(&_weights1), weights2(&_weights2), dst(&_dst)
{
}
virtual void operator() (const Range & range) const CV_OVERRIDE
{
int cn = src1->channels(), width = src1->cols * cn;
for (int y = range.start; y < range.end; ++y)
{
const float * const weights1_row = weights1->ptr<float>(y);
const float * const weights2_row = weights2->ptr<float>(y);
const T * const src1_row = src1->ptr<T>(y);
const T * const src2_row = src2->ptr<T>(y);
T * const dst_row = dst->ptr<T>(y);
int x = 0;
#if CV_SIMD128
x = blendLinearSimd128(src1_row, src2_row, weights1_row, weights2_row, dst_row, x, width, cn);
#endif
for ( ; x < width; ++x)
{
int x1 = x / cn;
float w1 = weights1_row[x1], w2 = weights2_row[x1];
float den = (w1 + w2 + 1e-5f);
float num = (src1_row[x] * w1 + src2_row[x] * w2);
dst_row[x] = saturate_cast<T>(num / den);
}
}
}
private:
const BlendLinearInvoker & operator= (const BlendLinearInvoker &);
BlendLinearInvoker(const BlendLinearInvoker &);
const Mat * src1, * src2, * weights1, * weights2;
Mat * dst;
};
#ifdef HAVE_OPENCL
static bool ocl_blendLinear( InputArray _src1, InputArray _src2, InputArray _weights1, InputArray _weights2, OutputArray _dst )
{
int type = _src1.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
char cvt[30];
ocl::Kernel k("blendLinear", ocl::imgproc::blend_linear_oclsrc,
format("-D T=%s -D cn=%d -D convertToT=%s", ocl::typeToStr(depth),
cn, ocl::convertTypeStr(CV_32F, depth, 1, cvt)));
if (k.empty())
return false;
UMat src1 = _src1.getUMat(), src2 = _src2.getUMat(), weights1 = _weights1.getUMat(),
weights2 = _weights2.getUMat(), dst = _dst.getUMat();
k.args(ocl::KernelArg::ReadOnlyNoSize(src1), ocl::KernelArg::ReadOnlyNoSize(src2),
ocl::KernelArg::ReadOnlyNoSize(weights1), ocl::KernelArg::ReadOnlyNoSize(weights2),
ocl::KernelArg::WriteOnly(dst));
size_t globalsize[2] = { (size_t)dst.cols, (size_t)dst.rows };
return k.run(2, globalsize, NULL, false);
}
#endif
}
void cv::blendLinear( InputArray _src1, InputArray _src2, InputArray _weights1, InputArray _weights2, OutputArray _dst )
{
CV_INSTRUMENT_REGION()
int type = _src1.type(), depth = CV_MAT_DEPTH(type);
Size size = _src1.size();
CV_Assert(depth == CV_8U || depth == CV_32F);
CV_Assert(size == _src2.size() && size == _weights1.size() && size == _weights2.size());
CV_Assert(type == _src2.type() && _weights1.type() == CV_32FC1 && _weights2.type() == CV_32FC1);
_dst.create(size, type);
CV_OCL_RUN(_dst.isUMat(),
ocl_blendLinear(_src1, _src2, _weights1, _weights2, _dst))
Mat src1 = _src1.getMat(), src2 = _src2.getMat(), weights1 = _weights1.getMat(),
weights2 = _weights2.getMat(), dst = _dst.getMat();
if (depth == CV_8U)
{
BlendLinearInvoker<uchar> invoker(src1, src2, weights1, weights2, dst);
parallel_for_(Range(0, src1.rows), invoker, dst.total()/(double)(1<<16));
}
else if (depth == CV_32F)
{
BlendLinearInvoker<float> invoker(src1, src2, weights1, weights2, dst);
parallel_for_(Range(0, src1.rows), invoker, dst.total()/(double)(1<<16));
}
}
| [
"lihuibin705@163.com"
] | lihuibin705@163.com |
773798a81f40aeb45b317f7a081397f3013a3de4 | 2834f98b53d78bafc9f765344ded24cf41ffebb0 | /components/safe_browsing/password_protection/password_protection_service.cc | 566a2d01b1542252067f16977a619eb1ed559397 | [
"BSD-3-Clause"
] | permissive | cea56/chromium | 81bffdf706df8b356c2e821c1a299f9d4bd4c620 | 013d244f2a747275da76758d2e6240f88c0165dd | refs/heads/master | 2023-01-11T05:44:41.185820 | 2019-12-09T04:14:16 | 2019-12-09T04:14:16 | 226,785,888 | 1 | 0 | BSD-3-Clause | 2019-12-09T04:40:07 | 2019-12-09T04:40:07 | null | UTF-8 | C++ | false | false | 23,018 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/safe_browsing/password_protection/password_protection_service.h"
#include <stddef.h>
#include <memory>
#include <string>
#include "base/base64.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/metrics/histogram_macros.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/password_manager/core/browser/password_reuse_detector.h"
#include "components/safe_browsing/common/utils.h"
#include "components/safe_browsing/db/database_manager.h"
#include "components/safe_browsing/features.h"
#include "components/safe_browsing/password_protection/password_protection_navigation_throttle.h"
#include "components/safe_browsing/password_protection/password_protection_request.h"
#include "components/zoom/zoom_controller.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "google_apis/google_api_keys.h"
#include "net/base/escape.h"
#include "net/base/url_util.h"
#include "third_party/blink/public/common/page/page_zoom.h"
using content::BrowserThread;
using content::WebContents;
using history::HistoryService;
using password_manager::metrics_util::PasswordType;
namespace safe_browsing {
using PasswordReuseEvent = LoginReputationClientRequest::PasswordReuseEvent;
namespace {
// Keys for storing password protection verdict into a DictionaryValue.
const int kRequestTimeoutMs = 10000;
const char kPasswordProtectionRequestUrl[] =
"https://sb-ssl.google.com/safebrowsing/clientreport/login";
} // namespace
PasswordProtectionService::PasswordProtectionService(
const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
HistoryService* history_service)
: database_manager_(database_manager),
url_loader_factory_(url_loader_factory) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (history_service)
history_service_observer_.Add(history_service);
common_spoofed_domains_ = {
"login.live.com"
"facebook.com",
"box.com",
"paypal.com",
"apple.com",
"yahoo.com",
"adobe.com",
"amazon.com",
"linkedin.com",
"att.com"};
}
PasswordProtectionService::~PasswordProtectionService() {
tracker_.TryCancelAll();
CancelPendingRequests();
history_service_observer_.RemoveAll();
weak_factory_.InvalidateWeakPtrs();
}
bool PasswordProtectionService::CanGetReputationOfURL(const GURL& url) {
if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS() || net::IsLocalhost(url))
return false;
const std::string hostname = url.HostNoBrackets();
return !net::IsHostnameNonUnique(hostname) &&
hostname.find('.') != std::string::npos;
}
#if defined(ON_FOCUS_PING_ENABLED)
void PasswordProtectionService::MaybeStartPasswordFieldOnFocusRequest(
WebContents* web_contents,
const GURL& main_frame_url,
const GURL& password_form_action,
const GURL& password_form_frame_url,
const std::string& hosted_domain) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RequestOutcome reason;
if (!base::FeatureList::IsEnabled(safe_browsing::kSendOnFocusPing)) {
return;
}
if (CanSendPing(LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE,
main_frame_url,
GetPasswordProtectionReusedPasswordAccountType(
PasswordType::PASSWORD_TYPE_UNKNOWN,
/*username=*/""),
&reason)) {
StartRequest(web_contents, main_frame_url, password_form_action,
password_form_frame_url, /* username */ "",
PasswordType::PASSWORD_TYPE_UNKNOWN,
{}, /* matching_domains: not used for this type */
LoginReputationClientRequest::UNFAMILIAR_LOGIN_PAGE, true);
}
}
#endif
#if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
void PasswordProtectionService::MaybeStartProtectedPasswordEntryRequest(
WebContents* web_contents,
const GURL& main_frame_url,
const std::string& username,
PasswordType password_type,
const std::vector<std::string>& matching_domains,
bool password_field_exists) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!base::FeatureList::IsEnabled(safe_browsing::kSendPasswordReusePing)) {
return;
}
ReusedPasswordAccountType reused_password_account_type =
GetPasswordProtectionReusedPasswordAccountType(password_type, username);
RequestOutcome reason;
// Need to populate |reason| to be passed into CanShowInterstitial.
bool can_send_ping =
CanSendPing(LoginReputationClientRequest::PASSWORD_REUSE_EVENT,
main_frame_url, reused_password_account_type, &reason);
if (IsSupportedPasswordTypeForPinging(password_type)) {
#if BUILDFLAG(FULL_SAFE_BROWSING)
// Collect metrics about typical page-zoom on login pages.
double zoom_level =
zoom::ZoomController::GetZoomLevelForWebContents(web_contents);
UMA_HISTOGRAM_COUNTS_1000(
"PasswordProtection.PageZoomFactor",
static_cast<int>(100 * blink::PageZoomLevelToZoomFactor(zoom_level)));
#endif // defined(FULL_SAFE_BROWSING)
if (can_send_ping) {
StartRequest(web_contents, main_frame_url, GURL(), GURL(), username,
password_type, matching_domains,
LoginReputationClientRequest::PASSWORD_REUSE_EVENT,
password_field_exists);
} else {
#if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
if (reused_password_account_type.is_account_syncing())
MaybeLogPasswordReuseLookupEvent(web_contents, reason, password_type,
nullptr);
#endif // defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
}
}
#if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
if (CanShowInterstitial(reason, reused_password_account_type,
main_frame_url)) {
username_for_last_shown_warning_ = username;
reused_password_account_type_for_last_shown_warning_ =
reused_password_account_type;
ShowInterstitial(web_contents, reused_password_account_type);
}
#endif // defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
}
#endif // defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
#if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
bool PasswordProtectionService::ShouldShowModalWarning(
LoginReputationClientRequest::TriggerType trigger_type,
ReusedPasswordAccountType password_type,
LoginReputationClientResponse::VerdictType verdict_type) {
if (trigger_type != LoginReputationClientRequest::PASSWORD_REUSE_EVENT ||
!IsSupportedPasswordTypeForModalWarning(password_type)) {
return false;
}
return (verdict_type == LoginReputationClientResponse::PHISHING ||
verdict_type == LoginReputationClientResponse::LOW_REPUTATION) &&
IsWarningEnabled(password_type);
}
void PasswordProtectionService::RemoveWarningRequestsByWebContents(
content::WebContents* web_contents) {
for (auto it = warning_requests_.begin(); it != warning_requests_.end();) {
if (it->get()->web_contents() == web_contents)
it = warning_requests_.erase(it);
else
++it;
}
}
bool PasswordProtectionService::IsModalWarningShowingInWebContents(
content::WebContents* web_contents) {
for (const auto& request : warning_requests_) {
if (request->web_contents() == web_contents)
return true;
}
return false;
}
#endif
LoginReputationClientResponse::VerdictType
PasswordProtectionService::GetCachedVerdict(
const GURL& url,
LoginReputationClientRequest::TriggerType trigger_type,
ReusedPasswordAccountType password_type,
LoginReputationClientResponse* out_response) {
return LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED;
}
void PasswordProtectionService::CacheVerdict(
const GURL& url,
LoginReputationClientRequest::TriggerType trigger_type,
ReusedPasswordAccountType password_type,
const LoginReputationClientResponse& verdict,
const base::Time& receive_time) {}
void PasswordProtectionService::StartRequest(
WebContents* web_contents,
const GURL& main_frame_url,
const GURL& password_form_action,
const GURL& password_form_frame_url,
const std::string& username,
PasswordType password_type,
const std::vector<std::string>& matching_domains,
LoginReputationClientRequest::TriggerType trigger_type,
bool password_field_exists) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
scoped_refptr<PasswordProtectionRequest> request(
new PasswordProtectionRequest(
web_contents, main_frame_url, password_form_action,
password_form_frame_url, username, password_type, matching_domains,
trigger_type, password_field_exists, this, GetRequestTimeoutInMS()));
request->Start();
pending_requests_.insert(std::move(request));
}
bool PasswordProtectionService::CanSendPing(
LoginReputationClientRequest::TriggerType trigger_type,
const GURL& main_frame_url,
ReusedPasswordAccountType password_type,
RequestOutcome* reason) {
*reason = RequestOutcome::UNKNOWN;
bool is_pinging_enabled =
IsPingingEnabled(trigger_type, password_type, reason);
// Pinging is enabled for password_reuse trigger level; however we need to
// make sure *reason is set appropriately.
PasswordProtectionTrigger trigger_level =
GetPasswordProtectionWarningTriggerPref(password_type);
if (trigger_level == PASSWORD_REUSE) {
*reason = RequestOutcome::PASSWORD_ALERT_MODE;
}
if (is_pinging_enabled &&
!IsURLWhitelistedForPasswordEntry(main_frame_url, reason)) {
return true;
}
LogNoPingingReason(trigger_type, *reason, password_type);
return false;
}
void PasswordProtectionService::RequestFinished(
PasswordProtectionRequest* request,
RequestOutcome outcome,
std::unique_ptr<LoginReputationClientResponse> response) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(request);
if (response) {
ReusedPasswordAccountType password_type =
GetPasswordProtectionReusedPasswordAccountType(request->password_type(),
request->username());
if (outcome != RequestOutcome::RESPONSE_ALREADY_CACHED) {
CacheVerdict(request->main_frame_url(), request->trigger_type(),
password_type, *response, base::Time::Now());
}
bool enable_warning_for_non_sync_users = base::FeatureList::IsEnabled(
safe_browsing::kPasswordProtectionForSignedInUsers);
if (!enable_warning_for_non_sync_users &&
request->password_type() == PasswordType::OTHER_GAIA_PASSWORD) {
return;
}
// If it's password alert mode and a Gsuite/enterprise account, we do not
// show a modal warning.
if (outcome == RequestOutcome::PASSWORD_ALERT_MODE &&
(password_type.account_type() == ReusedPasswordAccountType::GSUITE ||
password_type.account_type() ==
ReusedPasswordAccountType::NON_GAIA_ENTERPRISE)) {
return;
}
#if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
if (ShouldShowModalWarning(request->trigger_type(), password_type,
response->verdict_type())) {
username_for_last_shown_warning_ = request->username();
reused_password_account_type_for_last_shown_warning_ = password_type;
saved_passwords_matching_domains_ = request->matching_domains();
ShowModalWarning(request->web_contents(), request->request_outcome(),
response->verdict_type(), response->verdict_token(),
password_type);
request->set_is_modal_warning_showing(true);
}
#endif
}
request->HandleDeferredNavigations();
// If the request is canceled, the PasswordProtectionService is already
// partially destroyed, and we won't be able to log accurate metrics.
if (outcome != RequestOutcome::CANCELED) {
auto verdict =
response ? response->verdict_type()
: LoginReputationClientResponse::VERDICT_TYPE_UNSPECIFIED;
#if defined(SYNC_PASSWORD_REUSE_WARNING_ENABLED)
MaybeReportPasswordReuseDetected(
request->web_contents(), request->username(), request->password_type(),
verdict == LoginReputationClientResponse::PHISHING);
#endif
// Persist a bit in CompromisedCredentials table when saved password is
// reused on a phishing or low reputation site.
auto is_unsafe_url =
verdict == LoginReputationClientResponse::PHISHING ||
verdict == LoginReputationClientResponse::LOW_REPUTATION;
if (is_unsafe_url) {
PersistPhishedSavedPasswordCredential(request->username(),
request->matching_domains());
}
}
// Remove request from |pending_requests_| list. If it triggers warning, add
// it into the !warning_reqeusts_| list.
for (auto it = pending_requests_.begin(); it != pending_requests_.end();
it++) {
if (it->get() == request) {
if (request->is_modal_warning_showing())
warning_requests_.insert(std::move(request));
pending_requests_.erase(it);
break;
}
}
}
void PasswordProtectionService::CancelPendingRequests() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto it = pending_requests_.begin(); it != pending_requests_.end();) {
PasswordProtectionRequest* request = it->get();
// These are the requests for whom we're still waiting for verdicts.
// We need to advance the iterator before we cancel because canceling
// the request will invalidate it when RequestFinished is called.
it++;
request->Cancel(false);
}
DCHECK(pending_requests_.empty());
}
int PasswordProtectionService::GetStoredVerdictCount(
LoginReputationClientRequest::TriggerType trigger_type) {
return -1;
}
scoped_refptr<SafeBrowsingDatabaseManager>
PasswordProtectionService::database_manager() {
return database_manager_;
}
GURL PasswordProtectionService::GetPasswordProtectionRequestUrl() {
GURL url(kPasswordProtectionRequestUrl);
std::string api_key = google_apis::GetAPIKey();
DCHECK(!api_key.empty());
return url.Resolve("?key=" + net::EscapeQueryParamValue(api_key, true));
}
int PasswordProtectionService::GetRequestTimeoutInMS() {
return kRequestTimeoutMs;
}
void PasswordProtectionService::FillUserPopulation(
LoginReputationClientRequest::TriggerType trigger_type,
LoginReputationClientRequest* request_proto) {
ChromeUserPopulation* user_population = request_proto->mutable_population();
user_population->set_user_population(
IsExtendedReporting() ? ChromeUserPopulation::EXTENDED_REPORTING
: ChromeUserPopulation::SAFE_BROWSING);
user_population->set_profile_management_status(
GetProfileManagementStatus(GetBrowserPolicyConnector()));
user_population->set_is_history_sync_enabled(IsHistorySyncEnabled());
#if BUILDFLAG(FULL_SAFE_BROWSING)
user_population->set_is_under_advanced_protection(
IsUnderAdvancedProtection());
#endif
user_population->set_is_incognito(IsIncognito());
}
void PasswordProtectionService::OnURLsDeleted(
history::HistoryService* history_service,
const history::DeletionInfo& deletion_info) {
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindRepeating(&PasswordProtectionService::
RemoveUnhandledSyncPasswordReuseOnURLsDeleted,
GetWeakPtr(), deletion_info.IsAllHistory(),
deletion_info.deleted_rows()));
}
void PasswordProtectionService::HistoryServiceBeingDeleted(
history::HistoryService* history_service) {
history_service_observer_.RemoveAll();
}
std::unique_ptr<PasswordProtectionNavigationThrottle>
PasswordProtectionService::MaybeCreateNavigationThrottle(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsRendererInitiated())
return nullptr;
content::WebContents* web_contents = navigation_handle->GetWebContents();
for (scoped_refptr<PasswordProtectionRequest> request : pending_requests_) {
if (request->web_contents() == web_contents &&
request->trigger_type() ==
safe_browsing::LoginReputationClientRequest::PASSWORD_REUSE_EVENT &&
IsSupportedPasswordTypeForModalWarning(
GetPasswordProtectionReusedPasswordAccountType(
request->password_type(), username_for_last_shown_warning()))) {
return std::make_unique<PasswordProtectionNavigationThrottle>(
navigation_handle, request, /*is_warning_showing=*/false);
}
}
for (scoped_refptr<PasswordProtectionRequest> request : warning_requests_) {
if (request->web_contents() == web_contents) {
return std::make_unique<PasswordProtectionNavigationThrottle>(
navigation_handle, request, /*is_warning_showing=*/true);
}
}
return nullptr;
}
bool PasswordProtectionService::IsWarningEnabled(
ReusedPasswordAccountType password_type) {
return GetPasswordProtectionWarningTriggerPref(password_type) ==
PHISHING_REUSE;
}
// static
ReusedPasswordType
PasswordProtectionService::GetPasswordProtectionReusedPasswordType(
password_manager::metrics_util::PasswordType password_type) {
switch (password_type) {
case PasswordType::SAVED_PASSWORD:
return PasswordReuseEvent::SAVED_PASSWORD;
case PasswordType::PRIMARY_ACCOUNT_PASSWORD:
return PasswordReuseEvent::SIGN_IN_PASSWORD;
case PasswordType::OTHER_GAIA_PASSWORD:
return PasswordReuseEvent::OTHER_GAIA_PASSWORD;
case PasswordType::ENTERPRISE_PASSWORD:
return PasswordReuseEvent::ENTERPRISE_PASSWORD;
case PasswordType::PASSWORD_TYPE_UNKNOWN:
return PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN;
case PasswordType::PASSWORD_TYPE_COUNT:
break;
}
NOTREACHED();
return PasswordReuseEvent::REUSED_PASSWORD_TYPE_UNKNOWN;
}
ReusedPasswordAccountType
PasswordProtectionService::GetPasswordProtectionReusedPasswordAccountType(
password_manager::metrics_util::PasswordType password_type,
const std::string& username) const {
ReusedPasswordAccountType reused_password_account_type;
switch (password_type) {
case PasswordType::SAVED_PASSWORD:
reused_password_account_type.set_account_type(
ReusedPasswordAccountType::SAVED_PASSWORD);
return reused_password_account_type;
case PasswordType::ENTERPRISE_PASSWORD:
reused_password_account_type.set_account_type(
ReusedPasswordAccountType::NON_GAIA_ENTERPRISE);
return reused_password_account_type;
case PasswordType::PRIMARY_ACCOUNT_PASSWORD: {
reused_password_account_type.set_is_account_syncing(
IsPrimaryAccountSyncing());
if (!IsPrimaryAccountSignedIn()) {
reused_password_account_type.set_account_type(
ReusedPasswordAccountType::UNKNOWN);
return reused_password_account_type;
}
reused_password_account_type.set_account_type(
IsPrimaryAccountGmail() ? ReusedPasswordAccountType::GMAIL
: ReusedPasswordAccountType::GSUITE);
return reused_password_account_type;
}
case PasswordType::OTHER_GAIA_PASSWORD: {
AccountInfo account_info = GetSignedInNonSyncAccount(username);
if (account_info.account_id.empty()) {
reused_password_account_type.set_account_type(
ReusedPasswordAccountType::UNKNOWN);
return reused_password_account_type;
}
reused_password_account_type.set_account_type(
IsOtherGaiaAccountGmail(username)
? ReusedPasswordAccountType::GMAIL
: ReusedPasswordAccountType::GSUITE);
return reused_password_account_type;
}
case PasswordType::PASSWORD_TYPE_UNKNOWN:
case PasswordType::PASSWORD_TYPE_COUNT:
reused_password_account_type.set_account_type(
ReusedPasswordAccountType::UNKNOWN);
return reused_password_account_type;
}
NOTREACHED();
return reused_password_account_type;
}
// static
PasswordType
PasswordProtectionService::ConvertReusedPasswordAccountTypeToPasswordType(
ReusedPasswordAccountType password_type) {
if (password_type.is_account_syncing()) {
return PasswordType::PRIMARY_ACCOUNT_PASSWORD;
} else if (password_type.account_type() ==
ReusedPasswordAccountType::NON_GAIA_ENTERPRISE) {
return PasswordType::ENTERPRISE_PASSWORD;
} else if (password_type.account_type() ==
ReusedPasswordAccountType::SAVED_PASSWORD) {
return PasswordType::SAVED_PASSWORD;
} else if (password_type.account_type() ==
ReusedPasswordAccountType::UNKNOWN) {
return PasswordType::PASSWORD_TYPE_UNKNOWN;
} else {
return PasswordType::OTHER_GAIA_PASSWORD;
}
}
bool PasswordProtectionService::IsSupportedPasswordTypeForPinging(
PasswordType password_type) const {
switch (password_type) {
case PasswordType::SAVED_PASSWORD:
return true;
case PasswordType::PRIMARY_ACCOUNT_PASSWORD:
return true;
case PasswordType::ENTERPRISE_PASSWORD:
return true;
case PasswordType::OTHER_GAIA_PASSWORD:
return base::FeatureList::IsEnabled(
safe_browsing::kPasswordProtectionForSignedInUsers);
case PasswordType::PASSWORD_TYPE_UNKNOWN:
case PasswordType::PASSWORD_TYPE_COUNT:
return false;
}
NOTREACHED();
return false;
}
bool PasswordProtectionService::IsSupportedPasswordTypeForModalWarning(
ReusedPasswordAccountType password_type) const {
if (password_type.account_type() ==
ReusedPasswordAccountType::NON_GAIA_ENTERPRISE)
return true;
if (password_type.account_type() ==
ReusedPasswordAccountType::SAVED_PASSWORD &&
base::FeatureList::IsEnabled(
safe_browsing::kPasswordProtectionForSavedPasswords))
return true;
if (password_type.account_type() != ReusedPasswordAccountType::GMAIL &&
password_type.account_type() != ReusedPasswordAccountType::GSUITE)
return false;
return password_type.is_account_syncing() ||
base::FeatureList::IsEnabled(
safe_browsing::kPasswordProtectionForSignedInUsers);
}
#if BUILDFLAG(FULL_SAFE_BROWSING)
void PasswordProtectionService::GetPhishingDetector(
service_manager::InterfaceProvider* provider,
mojo::Remote<mojom::PhishingDetector>* phishing_detector) {
provider->GetInterface(phishing_detector->BindNewPipeAndPassReceiver());
}
#endif
} // namespace safe_browsing
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4d3eea9788f386c6d07f5395b17f777dec6dadb3 | 887763d02d6caddf8cc9c29be10732feaa4ca385 | /IoTRepublicPlus/IoT/IoTComponent.h | d0d39a46163dd4daf1cdb0efb1526835c1a72370 | [] | no_license | TSIoT/IoTRepublicPlus | 21bddc0c8dd54a06f3df6843b38ddf960f1cb3a3 | 8e3bd7c909d7483c487dae96330e9195a7800fc1 | refs/heads/master | 2020-04-12T05:41:28.839513 | 2016-11-08T07:38:58 | 2016-11-08T07:38:58 | 64,901,445 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 313 | h | #ifndef IoTComponent_H_INCLUDED
#define IoTComponent_H_INCLUDED
#include <iostream>
using namespace std;
class IoTComponent
{
public:
enum ComType
{
Unknown,
Content,
Button
};
string ID;
string Group;
string Name;
ComType Type;
int ReadFrequency;
IoTComponent();
~IoTComponent();
};
#endif
| [
"loki.chuang@portwell.com.tw"
] | loki.chuang@portwell.com.tw |
5cc22d20648fb3ede2de584a9597062baf637740 | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE415_Double_Free/s01/CWE415_Double_Free__new_delete_array_int64_t_16.cpp | 291e4d86102e8b7ae8f197de0d3849eb4cf64f50 | [] | no_license | Sporknugget/Juliet_prep | e9bda84a30bdc7938bafe338b4ab2e361449eda5 | 97d8922244d3d79b62496ede4636199837e8b971 | refs/heads/master | 2023-05-05T14:41:30.243718 | 2021-05-25T16:18:13 | 2021-05-25T16:18:13 | 369,334,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,856 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_array_int64_t_16.cpp
Label Definition File: CWE415_Double_Free__new_delete_array.label.xml
Template File: sources-sinks-16.tmpl.cpp
*/
/*
* @description
* CWE: 415 Double Free
* BadSource: Allocate data using new and Deallocae data using delete
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: do nothing
* BadSink : Deallocate data using delete
* Flow Variant: 16 Control flow: while(1)
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE415_Double_Free__new_delete_array_int64_t_16
{
#ifndef OMITBAD
void bad()
{
int64_t * data;
/* Initialize data */
data = NULL;
{
data = new int64_t[100];
/* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */
delete [] data;
}
{
/* POTENTIAL FLAW: Possibly deleting memory twice */
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G() - use badsource and goodsink by changing the sinks in the second while statement */
static void goodB2G()
{
int64_t * data;
/* Initialize data */
data = NULL;
{
data = new int64_t[100];
/* POTENTIAL FLAW: delete the array data in the source - the bad sink deletes the array data as well */
delete [] data;
}
{
/* do nothing */
/* FIX: Don't attempt to delete the memory */
; /* empty statement needed for some flow variants */
}
}
/* goodG2B() - use goodsource and badsink by changing the sources in the first while statement */
static void goodG2B()
{
int64_t * data;
/* Initialize data */
data = NULL;
{
data = new int64_t[100];
/* FIX: Do NOT delete the array data in the source - the bad sink deletes the array data */
}
{
/* POTENTIAL FLAW: Possibly deleting memory twice */
delete [] data;
}
}
void good()
{
goodB2G();
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE415_Double_Free__new_delete_array_int64_t_16; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"jaredzap@rams.colostate.edu"
] | jaredzap@rams.colostate.edu |
a80c7abde6b1089ef65203f9004daa7171e0f882 | 9fc7bda631fa47d4aae30a661a4547352cbe2438 | /Mandel/src/flinescheduler.h | 5dc76ed4e4d0e5a53768ac5576c23ac56153762a | [] | no_license | simon-r/MandelLab | b311e3730c3b2a79e4124f6a2df18ab52e4164c5 | 1683aa9f08d3c4186b8d28c7815a3bf2872e5b81 | refs/heads/master | 2020-04-28T11:17:59.682866 | 2010-12-31T17:49:06 | 2010-12-31T17:49:06 | 1,197,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,597 | h | // Copyright (C) 2010 Simone Riva -- em: simone [dot] rva -a- gmail com
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef FLINESCHEDULER_H
#define FLINESCHEDULER_H
#include "fcomplex.h"
#include "findex.h"
#include "fmatrix.h"
#include "fdomain.h"
#include "fabstractscheduler.h"
#include <QSemaphore>
class FLineScheduler : public FAbstractScheduler
{
public:
FLineScheduler();
virtual void setDomain( const FDomain& domain ) ;
virtual JobState getJob( FComplexVector& points , FIndiciesVector& indicies ) ;
unsigned int getJobSize() const ;
void setLineStep( unsigned int step ) { p_step = step ; }
unsigned int setAutoLineStep() ;
virtual void stop() ;
virtual void reset() ;
virtual void acquire() ;
virtual void release() ;
private:
FDomain p_domain ;
QSemaphore p_scheduler_semaphore ;
int p_job_size ;
bool p_f_stop ;
int p_step ;
unsigned int p_current_line ;
};
#endif // FLINESCHEDULER_H
| [
"simone.rva@gmail.com"
] | simone.rva@gmail.com |
e9cc8e5a894cc8b3866d034148afc13910331781 | bf26394b84c97a2365294164d0bf55de089f9489 | /src/LAMPh/dialogdevicesettings.h | bfebc085c125f03437b3c7785141bde60f963d21 | [] | no_license | llnoor/PROJECT_LAMPh | 8025592c9469325423a8783bdc785b2a6cf00697 | 5ca6eceffc6395ffdc7c8d8f464dd413fd5354bc | refs/heads/master | 2022-12-01T01:09:14.321512 | 2022-11-25T07:04:41 | 2022-11-25T07:04:41 | 140,567,218 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | h | #ifndef DIALOGDEVICESETTINGS_H
#define DIALOGDEVICESETTINGS_H
#include <QMainWindow>
#include <QDialog>
#include <QMessageBox>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QComboBox>
#define BUTTONNUM 5
QT_BEGIN_NAMESPACE
class QGroupBox;
QT_END_NAMESPACE
class DialogDeviceSettings : public QDialog
{
Q_OBJECT
public:
explicit DialogDeviceSettings(QString dllFile, int number, QWidget *parent = 0);
~DialogDeviceSettings();
Q_SIGNALS:
void signalReady();
private Q_SLOTS:
void save_data();
void delete_data();
bool setParameterButton(int row, int column);
bool setParameterLine(int row);
bool setParameterComboBox(int row, int index);
private:
QString dllFileQString;
int number_of_device=0;
QGroupBox *groupTableSettings();
QLabel *labelName;
QLabel *labelInfo; //text?
QLabel *labelRowName[BUTTONNUM];
QPushButton *pushButtonButtonName[BUTTONNUM][BUTTONNUM];
QLineEdit *lineEditRowData[BUTTONNUM];
QLabel *labelLineName[BUTTONNUM];
QLineEdit *lineEditParameterLine[BUTTONNUM];
QPushButton *pushButtonSend[BUTTONNUM];
QLabel *labelComboBoxName[BUTTONNUM];
QComboBox *comboBoxQStringList[BUTTONNUM];
private:
void accept();
};
#endif // DIALOGDEVICESETTINGS_H
| [
"llnoor@bk.ru"
] | llnoor@bk.ru |
7b20183771202f84d01fef9652eb22108af5540e | ae9a3a0e94fee1d913684c0d7f9adb91b8f5df50 | /src/timeStamp.cpp | c8d077acce61f09f980b6b4b1c2e14833431a7b8 | [
"MIT"
] | permissive | mrkraimer/pvaClientTutorialCPP | 191d0c39ca242c7dbb0d75c27baa618c4a093b28 | 6021fdaf4952f211b697c1c9131a87048b710935 | refs/heads/master | 2023-03-28T06:58:58.355870 | 2021-04-02T15:47:49 | 2021-04-02T15:47:49 | 109,140,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,435 | cpp | /*
* Copyright information and license terms for this software can be
* found in the file LICENSE that is included with the distribution
*/
/**
* @author Marty Kraimer
* @date 2017.11
*/
#include <epicsGetopt.h>
#include <iostream>
#include <pv/pvaClient.h>
using namespace std;
using namespace epics::pvData;
using namespace epics::pvAccess;
using namespace epics::pvaClient;
static void timeStamp(PvaClientPtr const &pva,string const & channelName,string const & providerName )
{
cout << "channelName " << channelName << " providerName " << providerName << endl;
PVStructurePtr pvStructure(
pva->channel(channelName,providerName,5.0)
->get("field(value,alarm,timeStamp)")
->getData()
->getPVStructure());
TimeStamp timeStamp;
PVTimeStamp pvTimeStamp;
pvTimeStamp.attach(pvStructure->getSubField("timeStamp"));
pvTimeStamp.get(timeStamp);
char timeText[32];
epicsTimeStamp epicsTS;
epicsTS.secPastEpoch = timeStamp.getEpicsSecondsPastEpoch();
epicsTS.nsec = timeStamp.getNanoseconds();
epicsTimeToStrftime(timeText, sizeof(timeText), "%Y.%m.%d %H:%M:%S.%f", &epicsTS);
cout << "time " << timeText << " userTag " << timeStamp.getUserTag() << endl;
}
int main(int argc,char *argv[])
{
int opt; /* getopt() current option */
string channelName("PVRdouble");
string providerName("pva");
while ((opt = getopt(argc, argv, "hp:")) != -1) {
switch (opt) {
case 'h':
cout << " -h -p providerName channelNames " << endl;
cout << "default" << endl;
cout << "-p " << providerName << " " << channelName
<< endl;
return 0;
case 'p' :
providerName = optarg;
break;
default :
break;
}
}
vector<string> channelNames;
int nPvs = argc - optind; /* Remaining arg list are PV names */
if (nPvs==0)
{
channelNames.push_back(channelName);
} else {
for (int n = 0; optind < argc; n++, optind++) channelNames.push_back(argv[optind]);
}
PvaClientPtr pva= PvaClient::get(providerName);
for(size_t i=0; i<channelNames.size(); ++i) {
try {
timeStamp(pva,channelNames[i],providerName);
} catch (std::exception& e) {
cerr << "exception " << e.what() << endl;
}
}
return 0;
}
| [
"mrkraimer@comcast.net"
] | mrkraimer@comcast.net |
4bce76bea7695a66b8de839c9753bb134a00f494 | 796120379f6c9ee88fb3e9ae0c7e41f880c4e69d | /cpp/src/exercise/e0200/e0124.cpp | bc09755479f6e89db6a5f5463b4587c86bf9b348 | [
"MIT"
] | permissive | ajz34/LeetCodeLearn | 45e3e15bf3b57fec0ddb9471f17134102db4c209 | 70ff8a3c17199a100819b356735cd9b13ff166a7 | refs/heads/master | 2022-04-26T19:04:11.605585 | 2020-03-29T08:43:12 | 2020-03-29T08:43:12 | 238,162,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | cpp | // https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
#include "extern.h"
class S0124 {
int max_val = -2147483648;
inline int max_3(int a, int b, int c) { return max(max(a, b), c); }
int maxPathSumInner(TreeNode* root) {
if (!root) return 0;
int res_l = maxPathSumInner(root->left);
int res_r = maxPathSumInner(root->right);
int result = max_3(root->val + res_l, root->val + res_r, root->val);
max_val = max_3(result, root->val + res_l + res_r, max_val);
return result;
}
public:
int maxPathSum(TreeNode* root) {
maxPathSumInner(root);
return max_val;
}
};
TEST(e0200, e0124) {
TreeNode* root;
root = new TreeNode("[1,2,3]");
ASSERT_EQ(S0124().maxPathSum(root), 6);
root = new TreeNode("[-10,9,20,null,null,15,7]");
ASSERT_EQ(S0124().maxPathSum(root), 42);
}
| [
"17110220038@fudan.edu.cn"
] | 17110220038@fudan.edu.cn |
ed43d37debac303b38c404e5f4fed5dd01e49d89 | 3bcd5de3ceb13c8233c2fbec0fb76c0b1a7202bd | /solutions/max_kaskevich/5/sources/5_4/template_functions.h | e500333465b5b4fc1d734f62d81d52fdf57043f5 | [] | no_license | PeterMoroz/cpp_craft_1013 | f45337d73c220bf4a231df07f3eaebad09de476d | 9b14d2da077d1dcdb11773baed30235dfb56d3f4 | refs/heads/master | 2016-09-05T09:17:10.121427 | 2015-07-17T07:39:14 | 2015-07-17T07:39:14 | 13,240,456 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,329 | h | #ifndef _TASK5_4_TEMPLATE_FUNCTIONS_H_
#define _TASK5_4_TEMPLATE_FUNCTIONS_H_
#include <functional>
namespace task5_4
{
// non-associative containers
template< typename Container, bool delete_first >
struct clear_container_class
{
static void clear_container( Container& container )
{
}
};
template< typename Container>
struct clear_container_class< Container, true >
{
static void clear_container( Container& container )
{
for( auto& elem: container )
{
delete elem;
}
}
};
template< bool delete_first, typename Container >
void clear_container( Container& container)
{
clear_container_class< Container, delete_first >::clear_container( container );
container.clear();
}
// associative containers
template< typename Container, bool delete_first, bool delete_second >
struct clear_assoc_container_class
{
static void clear_container( Container& container )
{
}
};
template< typename Container>
struct clear_assoc_container_class< Container, true, false >
{
static void clear_container( Container& container )
{
for( auto& pair: container )
{
delete pair.first;
}
}
};
template< typename Container>
struct clear_assoc_container_class< Container, false, true >
{
static void clear_container( Container& container )
{
for( auto& pair: container )
{
delete pair.second;
}
}
};
template< typename Container>
struct clear_assoc_container_class< Container, true, true >
{
static void clear_container( Container& container )
{
for( auto& pair: container )
{
delete pair.first;
delete pair.second;
}
}
};
template< bool delete_first, bool delete_second, typename Container >
void clear_container( Container& container )
{
clear_assoc_container_class< Container, delete_first, delete_second >::
clear_container( container );
container.clear();
}
}
#endif // _TASK5_4_TEMPLATE_FUNCTIONS_H_
| [
"jake@gogo.by"
] | jake@gogo.by |
56e9444ac6dfcd116f5bfa695a5b9443a6d1b10e | 86a9f72a8068f6580ed22146324fc77579dcaf95 | /store.h | 67d104f3806d564597a128ad1946937f26ed94ca | [] | no_license | AliMasarweh/Concurrency-Consumer-Producer-CPP | c37780a6faef16e1a7fd885d68f34b434c750de3 | 5dde6d1e967760a27ca50e21122194c2154f4d07 | refs/heads/master | 2022-10-03T22:56:35.808848 | 2020-03-12T07:30:50 | 2020-03-12T07:30:50 | 269,422,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | h | //
// Created by ali-masa on 3/8/20.
//
#ifndef CONSUMER_PRODUCER_STORE_H
#define CONSUMER_PRODUCER_STORE_H
#include <vector>
class Store
{
public:
Store();
virtual int addProduct(int product);
virtual int consumeProduct();
/*virtual void lock(){};
virtual void unlock(){};*/
virtual ~Store() {};
protected:
std::vector<int> m_products;
int m_products_count;
};
#endif //CONSUMER_PRODUCER_STORE_H
| [
"alis.masarwe@gmail.com"
] | alis.masarwe@gmail.com |
58ef674abd71a7f42521e261afa6e1c92194e142 | 6d475afb4d39555d9e36a0025b5cdface2ab371a | /arrarr/main.cpp | ff7bd1fff65016e61816b491567e0df4117b72f2 | [] | no_license | DaisyHax/My-Codes | dc30135f10eb880a0aeda9eb526dabeb7265ac60 | fbc517328399726994164c0298c4d18bc25ae1d7 | refs/heads/master | 2021-08-29T19:41:19.385002 | 2017-12-14T17:28:38 | 2017-12-14T17:28:38 | 114,290,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
long int n,a[100001],b[100001],c[100001];
cin>>n;
for(long int i=0;i<n;i++)
{
cin>>a[i];
}
for(long int i=0;i<n;i++)
{
cin>>b[i];
}
for(long int i=0;i<n;i++)
{
c[i]=a[i]+b[i];
cout<<c[i]<<endl;
}
return 0;
}
| [
"dishi.sarthak@gmail.com"
] | dishi.sarthak@gmail.com |
02f15ce005d38bda85fcb68312f27da79b9915d2 | 57ac85ca91d0f218be2a97e41ad7f8967728e7b9 | /blazetest/src/mathtest/smatdmatmult/MIbDDb.cpp | d93dd39e20adb5663d1afe8e63997a6467e2689d | [
"BSD-3-Clause"
] | permissive | AuroraDysis/blaze | b297baa6c96b77c3d32de789e0e3af27782ced77 | d5cacf64e8059ca924eef4b4e2a74fc9446d71cb | refs/heads/master | 2021-01-01T16:49:28.921446 | 2017-07-22T23:24:26 | 2017-07-22T23:24:26 | 97,930,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,298 | cpp | //=================================================================================================
/*!
// \file src/mathtest/smatdmatmult/MIbDDb.cpp
// \brief Source file for the MIbDDb sparse matrix/dense matrix multiplication math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/IdentityMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MIbDDb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::IdentityMatrix<TypeB> MIb;
typedef blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> > DDb;
// Creator type definitions
typedef blazetest::Creator<MIb> CMIb;
typedef blazetest::Creator<DDb> CDDb;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( i ), CDDb( i ) );
}
// Running tests with large matrices
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 31UL ), CDDb( 31UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 67UL ), CDDb( 67UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 127UL ), CDDb( 127UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 32UL ), CDDb( 32UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 64UL ), CDDb( 64UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 128UL ), CDDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
4ce01c18892b747f7e50896afd7061d07be4837c | f39aefac09229029d8dba8ad6af0b5e0eb5114a9 | /main.cpp | e5bc05f9c44d7e108ff4dfbfee8e695fb2227d44 | [] | no_license | AliKalkandelen/Pig-Latin-Program | c88a64ec5890561f44ecf53ca45326d9c030630c | 333221f05caf5bde9c61262623fafbd56891078d | refs/heads/master | 2020-05-19T10:12:46.725756 | 2014-09-23T18:09:19 | 2014-09-23T18:09:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,360 | cpp | #include <string>
#include <iostream>
#include <string.h>
#include <vector>
#include <cctype>
#include <locale>
using namespace std;
string input;
string word;
string topiglatin(string); /**< translates to pig latin */
string frompiglatin(string); /**< translates from pig latin */
string makeProper(string); /**< Capitalizes only first letter */
bool isVowel(char); /**<checks if const char is vowel*/
bool isallconstt(const std::string &str); /**<checks if word is all constants*/
int main(int argc, char *argv[])
{
enum {TOPIG, FROMPIG} mode;
if( argc == 1 )
{
mode = TOPIG;
}else if(argc != 2)
{
cout<<"Error Message(Wrong argument)"<<endl;
return 1;
}
else
{
string userArg(argv[1]);
if(userArg == "topig")
{
mode = TOPIG;
}
else if(userArg == "frompig")
{
mode = FROMPIG;
}
else
{
cout<<"Error Message(Argument needs topig or frompig)"<<endl;
return 1;
}
}
cout<<"Input String"<<endl;
getline(cin, input);
input = input + " ";
if (mode == TOPIG)
{
for(int i = 0; (unsigned)i<input.length(); i++)
{
if(isalpha(input[i]))
{
word.push_back(input[i]);
}
else
{
if(!word.empty())
{
string z = topiglatin(word);
cout<<z;
word.clear();
cout<<input[i];
}
else
{
cout<<input[i];
}
}
}
}
else if(mode == FROMPIG)
{
for(int i = 0; (unsigned)i<input.length(); i++)
{
if(isalpha(input[i]))
{
word.push_back(input[i]);
}
else
{
if(!word.empty())
{
string z = frompiglatin(word);
cout<<z;
word.clear();
cout<<input[i];
}
else
{
cout<<input[i];
}
}
}
}
else
{
cout<<"Error Message(Argument Matching Failed)"<<endl;
return 1;
}
}
bool isVowel(char ch)
{
switch(ch){
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
bool isallconstt(const std::string &str)
{
return str.find_first_not_of("bcdfghjklmnpqrstvwxyz") == std::string::npos;
}
bool hasEnding (std::string const &fullString, std::string const &ending)
{
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
string makeProper(string word)
{
int i = 0;
while(word[i])
{
word[i] = tolower(word[i]);
i++;
}
word[0] = toupper(word[0]);
return word;
}
string topiglatin(string word)
{
if(isVowel(word[0]))
{
word = word + "way";
}
else if(!isVowel(word[0]))
{
do
{
if(isallconstt(word))
{
word = word + "way";
return word;
}
else
{
word = word.substr(1,word.length()) + word[0];
}
}while(!isVowel(word[0]));
word = word + "ay";
}
else
cout<<"Error Message: isVowel error in("<<word<<")";
word = makeProper(word);
return word;
}
string frompiglatin(string word)
{
word = makeProper(word);
string ending = "way";
int h = hasEnding(word,ending);
int g = hasEnding(word,ending.substr(1,2));
if(h == 1)
{
word = word.substr(0,word.length()-3);
}
else if(g == 1)
{
if(isallconstt(word.substr(0,word.length()-2)))
{
word = word.substr(0,word.length()-2);
return word;
}
else
{
word = word.substr(0,word.length()-2);
word = word[word.length()-1] + word.substr(0,word.length()-1);
}
}
else
{
return word;
}
word = makeProper(word);
return word;
}
| [
"alikal18@gmail.com"
] | alikal18@gmail.com |
1b86a5c07cedf4b87e61d919aa7afd6a1b0eafd7 | 4461266d5010bce592d5078056dfb0e17476252f | /ME_4600/MESDK/ME-630/Vc/Sample99/ME630DemoDlg.cpp | 2a524026ea0f53dea42058145c558939c15f251b | [] | no_license | MrJustreborn/MechSys | 858a998407409006b13b21c614c26b41673ea85b | 50aa045a2da50064311d5dd82ba9007bf8c3eba4 | refs/heads/master | 2020-06-02T17:25:12.496034 | 2015-07-12T07:06:21 | 2015-07-12T07:06:21 | 32,728,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,317 | cpp | // ME630DemoDlg.cpp : implementation file
//
#include "stdafx.h"
#include "ME630Demo.h"
#include "ME630DemoDlg.h"
#include "..\me630.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CME630DemoDlg dialog
CME630DemoDlg::CME630DemoDlg(CWnd* pParent /*=NULL*/)
: CDialog(CME630DemoDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CME630DemoDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_iCurrentBoardIndex = 0;
memset(&m_bIntEnabled[0][0], 0, sizeof(BOOL) * ME_MAX_DEVICES * 2);
}
void CME630DemoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CME630DemoDlg)
DDX_Control(pDX, IDC_COMBO_DIO_SET_BIT, m_comboDIOSetBit);
DDX_Control(pDX, IDC_COMBO_DIO_GET_BIT, m_comboDIOGetBit);
DDX_Control(pDX, IDC_COMBO_SET_RELAY_BIT_NUMBER, m_comboSetRelayBitNumber);
DDX_Control(pDX, IDC_COMBO_GET_TTL_BIT_NUMBER, m_comboGetTTLBitNumber);
DDX_Control(pDX, IDC_COMBO_GET_RELAY_BIT_NUMBER, m_comboGetRelayBitNumber);
DDX_Control(pDX, IDC_COMBO_GET_OPTO_BIT_NUMBER, m_comboGetOptoBitNumber);
DDX_Control(pDX, IDC_BOARD_COMBO, m_comboBoardNumber);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CME630DemoDlg, CDialog)
//{{AFX_MSG_MAP(CME630DemoDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_CBN_SELCHANGE(IDC_BOARD_COMBO, OnSelChangeBoardCombo)
ON_BN_CLICKED(IDC_BUTTON_GET_OPTO_BIT, OnButtonGetOptoBit)
ON_BN_CLICKED(IDC_BUTTON_GET_OPTO_BYTE, OnButtonGetOptoByte)
ON_BN_CLICKED(IDC_BUTTON_GET_RELAY_BIT, OnButtonGetRelayBit)
ON_BN_CLICKED(IDC_BUTTON_GET_RELAY_WORD, OnButtonGetRelayWord)
ON_BN_CLICKED(IDC_BUTTON_GET_TTL_BIT, OnButtonGetTtlBit)
ON_BN_CLICKED(IDC_BUTTON_GET_TTL_BYTE, OnButtonGetTtlByte)
ON_BN_CLICKED(IDC_BUTTON_SET_RELAY_BIT, OnButtonSetRelayBit)
ON_BN_CLICKED(IDC_BUTTON_SET_RELAY_WORD, OnButtonSetRelayWord)
ON_BN_CLICKED(IDC_RADIO_IRQ1_DISABLE, OnRadioIRQ1Disable)
ON_BN_CLICKED(IDC_RADIO_IRQ1_ENABLE, OnRadioIRQ1Enable)
ON_BN_CLICKED(IDC_RADIO_IRQ2_DISABLE, OnRadioIRQ2Disable)
ON_BN_CLICKED(IDC_RADIO_IRQ2_ENABLE, OnRadioIRQ2Enable)
ON_BN_CLICKED(IDC_BUTTON_DIO_RESET_ALL, OnButtonDioResetAll)
ON_BN_CLICKED(IDC_BUTTON_DIO_CONFIG, OnButtonDioConfig)
ON_BN_CLICKED(IDC_BUTTON_DIO_GET_BYTE, OnButtonDioGetByte)
ON_BN_CLICKED(IDC_BUTTON_DIO_GET_BIT, OnButtonDioGetBit)
ON_BN_CLICKED(IDC_BUTTON_DIO_SET_BYTE, OnButtonDioSetByte)
ON_BN_CLICKED(IDC_BUTTON_DIO_SET_BIT, OnButtonDioSetBit)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CME630DemoDlg message handlers
BOOL CME630DemoDlg::OnInitDialog()
{
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
// Make an entry in the combo box for each board found
for (int index_board = 0; index_board < ME_MAX_DEVICES; index_board++)
{
// call _me630GetBoardVersion simply to see if the board is there
int i_version;
if( _me630GetBoardVersion(index_board, &i_version) )
{
CString cs_board;
// Build a string with the board number
cs_board.Format("Board %d", index_board);
int combo_index = m_comboBoardNumber.AddString(cs_board);
// Associate the combo entry with the board number as item data
// We will use this to get the board number every time an element
// is selected from the combo list
m_comboBoardNumber.SetItemData(combo_index, (DWORD)index_board);
}
}
// We know we must have found at least one board, otherwise we would have exited
// the application already in Cme630DemoApp::InitInstance with an error message
// Select the first combo item into the combo box
m_comboBoardNumber.SetCurSel(0);
// Set the current board index. This is the item data for the selected item
m_iCurrentBoardIndex = (int)m_comboBoardNumber.GetItemData(0);
// Reset all dialog elements to correspond to the current board.
SetDialogElements();
return TRUE; // return TRUE unless you set the focus to a control
}
void CME630DemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CME630DemoDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CME630DemoDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CME630DemoDlg::OnSelChangeBoardCombo()
{
// TODO: Add your control notification handler code here
// Find combo-box index of newly selected board
int new_index = m_comboBoardNumber.GetCurSel();
// Set the new current board
m_iCurrentBoardIndex = (int)m_comboBoardNumber.GetItemData(new_index);
// Reset all dialog elements to correspond to the current board.
SetDialogElements();
}
void CME630DemoDlg::OnButtonGetOptoBit()
{
// TODO: Add your control notification handler code here
// Get the chosen bit number
int i_bit_no = m_comboGetOptoBitNumber.GetCurSel();
int i_value;
// Get the bit value
_me630DIGetOptoBit(m_iCurrentBoardIndex, i_bit_no, &i_value);
if(i_value == 0)
{
// Bit value 0, uncheck the check box
CheckDlgButton(IDC_CHECK_GET_OPTO_BIT_VALUE, 0);
}
else
{
// Bit value 1, check the check box
CheckDlgButton(IDC_CHECK_GET_OPTO_BIT_VALUE, 1);
}
}
void CME630DemoDlg::OnButtonGetOptoByte()
{
// TODO: Add your control notification handler code here
// Read from the register of set m_iCurrentRegisterSet with an me630 call
unsigned char uc_value;
_me630DIGetOptoByte(m_iCurrentBoardIndex, &uc_value);
// Set the appropriate check boxes in the dialog
// Check the appropriate check box if the last bit of w_set is 1
// Otherwise leave the check box unchecked
CheckDlgButton(IDC_GET_OPTO_BIT_0, uc_value&0x01);
// Shift w_set left to handle the next bit
uc_value>>= 1;
// Continue in this way with each bit of w_set and the appropriate check box
CheckDlgButton(IDC_GET_OPTO_BIT_1, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_2, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_3, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_4, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_5, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_6, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_OPTO_BIT_7, uc_value&0x01);
}
void CME630DemoDlg::OnButtonGetRelayBit()
{
// TODO: Add your control notification handler code here
// Get the chosen bit number
int i_bit_no = m_comboGetRelayBitNumber.GetCurSel();
int i_value;
// Get the bit value
_me630DIGetRelayBit(m_iCurrentBoardIndex, i_bit_no, &i_value);
if(i_value == 0)
{
// Bit value 0, uncheck the check box
CheckDlgButton(IDC_CHECK_GET_RELAY_BIT_VALUE, 0);
}
else
{
// Bit value 1, check the check box
CheckDlgButton(IDC_CHECK_GET_RELAY_BIT_VALUE, 1);
}
}
void CME630DemoDlg::OnButtonGetRelayWord()
{
// TODO: Add your control notification handler code here
// Read from the register of set m_iCurrentRegisterSet with an me630 call
unsigned short us_value;
_me630DIGetRelayWord(m_iCurrentBoardIndex, &us_value);
// Set the appropriate check boxes in the dialog
// Check the appropriate check box if the last bit of us_value is 1
// Otherwise leave the check box unchecked
CheckDlgButton(IDC_GET_RELAY_BIT_0, us_value&0x01);
// Shift w_set left to handle the next bit
us_value>>= 1;
// Continue in this way with each bit of w_set and the appropriate check box
CheckDlgButton(IDC_GET_RELAY_BIT_1, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_2, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_3, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_4, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_5, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_6, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_7, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_8, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_9, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_10, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_11, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_12, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_13, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_14, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_GET_RELAY_BIT_15, us_value&0x01);
}
void CME630DemoDlg::OnButtonGetTtlBit()
{
// TODO: Add your control notification handler code here
// Get the chosen bit number
int i_bit_no = m_comboGetTTLBitNumber.GetCurSel();
int i_value;
// Get the bit value
_me630DIGetTTLBit(m_iCurrentBoardIndex, i_bit_no, &i_value);
if(i_value == 0)
{
// Bit value 0, uncheck the check box
CheckDlgButton(IDC_CHECK_GET_TTL_BIT_VALUE, 0);
}
else
{
// Bit value 1, check the check box
CheckDlgButton(IDC_CHECK_GET_TTL_BIT_VALUE, 1);
}
}
void CME630DemoDlg::OnButtonGetTtlByte()
{
// TODO: Add your control notification handler code here
// Read from the register of set m_iCurrentRegisterSet with an me630 call
unsigned char uc_value;
_me630DIGetTTLByte(m_iCurrentBoardIndex, &uc_value);
// Set the appropriate check boxes in the dialog
// Check the appropriate check box if the last bit of w_set is 1
// Otherwise leave the check box unchecked
CheckDlgButton(IDC_GET_TTL_BIT_0, uc_value&0x01);
// Shift w_set left to handle the next bit
uc_value>>= 1;
// Continue in this way with each bit of w_set and the appropriate check box
CheckDlgButton(IDC_GET_TTL_BIT_1, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_2, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_3, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_4, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_5, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_6, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_GET_TTL_BIT_7, uc_value&0x01);
}
void CME630DemoDlg::OnButtonSetRelayBit()
{
// TODO: Add your control notification handler code here
// Get the chosen bit number
int i_bit_no = m_comboSetRelayBitNumber.GetCurSel();
// Get the bit value
int i_value;
if( IsDlgButtonChecked(IDC_CHECK_SET_RELAY_BIT_VALUE) )
{
// Check box is checked - bit value = 1.
i_value = 1;
}
else
{
// Check box not checked - bit value = 0.
i_value = 0;
}
// Set the bit value
_me630DOSetRelayBit(m_iCurrentBoardIndex, i_bit_no, i_value);
}
void CME630DemoDlg::OnButtonSetRelayWord()
{
// TODO: Add your control notification handler code here
// Initialise the relay word
unsigned short us_relay = 0;
// Initialise a bit mask
unsigned short us_mask = 0x0001;
// If the check box corresponding to the first bit is checked, then set
// the first bit in our result
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_0) )
{
us_relay|= us_mask;
}
// Shift the mask to handle the next bit
us_mask<<= 1;
// Continue in this way for each check box and the appropriate bit of our result
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_1) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_2) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_3) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_4) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_5) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_6) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_7) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_8) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_9) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_10) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_11) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_12) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_13) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_14) )
{
us_relay|= us_mask;
}
us_mask<<= 1;
if( IsDlgButtonChecked(IDC_SET_RELAY_BIT_15) )
{
us_relay|= us_mask;
}
// Write the relay word to the appropriate me630 register with an me630 call
_me630DOSetRelayWord(m_iCurrentBoardIndex, us_relay);
}
void CME630DemoDlg :: UpdateIRQ1Count(void)
{
// Set int count for IRQ 1
CWnd* p_wnd = p_wnd = GetDlgItem(IDC_IRQ1_COUNT);
int i_cnt;
_me630GetIrqCnt(m_iCurrentBoardIndex, ME630_IRQ_1, &i_cnt);
CString cs_count;
cs_count.Format("%7d", i_cnt);
p_wnd->SetWindowText(cs_count);
}
void CME630DemoDlg :: UpdateIRQ2Count(void)
{
// Set int count for IRQ 2
CWnd* p_wnd = p_wnd = GetDlgItem(IDC_IRQ2_COUNT);
int i_cnt;
_me630GetIrqCnt(m_iCurrentBoardIndex, ME630_IRQ_2, &i_cnt);
CString cs_count;
cs_count.Format("%7d", i_cnt);
p_wnd->SetWindowText(cs_count);
}
void CME630DemoDlg :: ReinitialiseBoard(int board_index)
{
// Disable int in hardware
_me630DisableInt(board_index, ME630_IRQ_1);
_me630DisableInt(board_index, ME630_IRQ_2);
// Reset Relays
_me630ResetRelays(board_index);
}
void CME630DemoDlg :: SetDialogElements(void)
{
// First get the device info.
// Temporary structure for the information
DEVICEINFOSTRUCT dev_info_struct;
// Set all structure components to zero
memset( (void *)&dev_info_struct, 0, sizeof(dev_info_struct) );
// And fetch the information with an me630 call
_me630GetDevInfo(m_iCurrentBoardIndex, &dev_info_struct);
// Display the information obtained in the device info group box.
// Temporary string for formatting
CString cs_info;
// Vendor ID
// Format string with required information
cs_info.Format("%X", dev_info_struct.dwVendorID);
// Get the static text that we are going to set
CWnd* p_wnd = GetDlgItem(IDC_VENDOR_ID);
// Set the text
p_wnd->SetWindowText(cs_info);
// And do the same for all the other items in the group box
// Device ID
cs_info.Format("%X", dev_info_struct.dwDeviceID);
p_wnd = GetDlgItem(IDC_DEVICE_ID);
p_wnd->SetWindowText(cs_info);
// System slot number
cs_info.Format("%d", dev_info_struct.dwSystemSlotNumber);
p_wnd = GetDlgItem(IDC_SYSTEM_SLOT_NUMBER);
p_wnd->SetWindowText(cs_info);
// Port base
cs_info.Format("%X", dev_info_struct.dwPortBase);
p_wnd = GetDlgItem(IDC_PORT_BASE);
p_wnd->SetWindowText(cs_info);
// Port count
cs_info.Format("%d", dev_info_struct.dwPortCount);
p_wnd = GetDlgItem(IDC_PORT_COUNT);
p_wnd->SetWindowText(cs_info);
// Interrupt channel
cs_info.Format("%d", dev_info_struct.dwIntChannel);
p_wnd = GetDlgItem(IDC_INTERRUPT_CHANNEL);
p_wnd->SetWindowText(cs_info);
// PLX port base
cs_info.Format("%X", dev_info_struct.dwPortBasePLX);
p_wnd = GetDlgItem(IDC_PLX_PORT_BASE);
p_wnd->SetWindowText(cs_info);
// PLX port count
cs_info.Format("%d", dev_info_struct.dwPortCountPLX);
p_wnd = GetDlgItem(IDC_PLX_PORT_COUNT);
p_wnd->SetWindowText(cs_info);
// Serial number
cs_info.Format("%X", dev_info_struct.dwSerialNumber);
p_wnd = GetDlgItem(IDC_SERIAL_NUMBER);
p_wnd->SetWindowText(cs_info);
// Bus number
cs_info.Format("%X", dev_info_struct.dwBusNumber);
p_wnd = GetDlgItem(IDC_BUS_NUMBER);
p_wnd->SetWindowText(cs_info);
// HW revision
cs_info.Format("%d", dev_info_struct.dwHWRevision);
p_wnd = GetDlgItem(IDC_HW_REVISION);
p_wnd->SetWindowText(cs_info);
// IRQ count
cs_info.Format("%d", dev_info_struct.dwIrqCnt);
p_wnd = GetDlgItem(IDC_IRQ_COUNT);
p_wnd->SetWindowText(cs_info);
// Version
cs_info.Format("%X", dev_info_struct.dwVersion);
p_wnd = GetDlgItem(IDC_VERSION);
p_wnd->SetWindowText(cs_info);
m_comboSetRelayBitNumber.SetCurSel(0);
m_comboGetRelayBitNumber.SetCurSel(0);
m_comboGetTTLBitNumber.SetCurSel(0);
m_comboGetOptoBitNumber.SetCurSel(0);
m_comboDIOGetBit.SetCurSel(0);
m_comboDIOSetBit.SetCurSel(0);
// Fill check boxes mit current values
OnButtonGetRelayWord();
OnButtonGetRelayBit();
OnButtonGetTtlByte();
OnButtonGetTtlBit();
OnButtonGetOptoByte();
OnButtonGetOptoBit();
OnButtonDioGetByte();
OnButtonDioGetBit();
// Set the check boxes for 'Set Relay Word' to the current relay settings
unsigned short relay_word;
_me630DIGetRelayWord(m_iCurrentBoardIndex, &relay_word);
InitialiseSetRelayWordCheckBoxes(relay_word);
// Set the check box for 'Set Relay Bit' to the current relay setting
// Get the chosen bit number
int i_bit_no = m_comboSetRelayBitNumber.GetCurSel();
int i_value;
// Get the bit value
_me630DIGetRelayBit(m_iCurrentBoardIndex, i_bit_no, &i_value);
if(i_value == 0)
{
// Bit value 0, uncheck the check box
CheckDlgButton(IDC_CHECK_SET_RELAY_BIT_VALUE, 0);
}
else
{
// Bit value 1, check the check box
CheckDlgButton(IDC_CHECK_SET_RELAY_BIT_VALUE, 1);
}
CheckRadioButton(IDC_RADIO_DIO_CONFIG_PORT_C, IDC_RADIO_DIO_CONFIG_PORT_D, IDC_RADIO_DIO_CONFIG_PORT_C);
CheckRadioButton(IDC_RADIO_DIO_CONFIG_INPUT, IDC_RADIO_DIO_CONFIG_OUTPUT, IDC_RADIO_DIO_CONFIG_INPUT);
CheckRadioButton(IDC_RADIO_DIO_GET_BYTE_PORT_C, IDC_RADIO_DIO_GET_BYTE_PORT_D, IDC_RADIO_DIO_GET_BYTE_PORT_C);
CheckRadioButton(IDC_RADIO_DIO_SET_BYTE_PORT_C, IDC_RADIO_DIO_SET_BYTE_PORT_D, IDC_RADIO_DIO_SET_BYTE_PORT_C);
CheckRadioButton(IDC_RADIO_DIO_GET_BIT_PORT_C, IDC_RADIO_DIO_GET_BIT_PORT_D, IDC_RADIO_DIO_GET_BIT_PORT_C);
CheckRadioButton(IDC_RADIO_DIO_SET_BIT_PORT_C, IDC_RADIO_DIO_SET_BIT_PORT_D, IDC_RADIO_DIO_SET_BIT_PORT_C);
// Set interrupt to disabled/enabled for IRQ 1
CheckRadioButton(IDC_RADIO_IRQ1_DISABLE, IDC_RADIO_IRQ1_ENABLE,
m_bIntEnabled[m_iCurrentBoardIndex][0] ? IDC_RADIO_IRQ1_ENABLE : IDC_RADIO_IRQ1_DISABLE);
// Set interrupt to disabled/enabled for IRQ 2
CheckRadioButton(IDC_RADIO_IRQ2_DISABLE, IDC_RADIO_IRQ2_ENABLE,
m_bIntEnabled[m_iCurrentBoardIndex][1] ? IDC_RADIO_IRQ2_ENABLE : IDC_RADIO_IRQ2_DISABLE);
UpdateIRQ1Count();
UpdateIRQ2Count();
}
void CME630DemoDlg :: InitialiseSetRelayWordCheckBoxes(unsigned short us_value)
{
// Check the appropriate check box if the last bit of us_value is 1
// Otherwise leave the check box unchecked
CheckDlgButton(IDC_SET_RELAY_BIT_0, us_value&0x01);
// Shift w_set left to handle the next bit
us_value>>= 1;
// Continue in this way with each bit of w_set and the appropriate check box
CheckDlgButton(IDC_SET_RELAY_BIT_1, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_2, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_3, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_4, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_5, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_6, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_7, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_8, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_9, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_10, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_11, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_12, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_13, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_14, us_value&0x01);
us_value>>= 1;
CheckDlgButton(IDC_SET_RELAY_BIT_15, us_value&0x01);
}
void CME630DemoDlg::OnRadioIRQ1Disable()
{
// TODO: Add your control notification handler code here
m_bIntEnabled[m_iCurrentBoardIndex][0] = FALSE;
_me630DisableInt(m_iCurrentBoardIndex, ME630_IRQ_1);
}
void CME630DemoDlg::OnRadioIRQ1Enable()
{
// TODO: Add your control notification handler code here
_me630EnableInt(m_iCurrentBoardIndex, ME630_IRQ_1, CME630DemoApp::IRQ1TestFunction, m_iCurrentBoardIndex);
m_bIntEnabled[m_iCurrentBoardIndex][0] = TRUE;
}
void CME630DemoDlg::OnRadioIRQ2Disable()
{
// TODO: Add your control notification handler code here
m_bIntEnabled[m_iCurrentBoardIndex][1] = FALSE;
_me630DisableInt(m_iCurrentBoardIndex, ME630_IRQ_2);
}
void CME630DemoDlg::OnRadioIRQ2Enable()
{
// TODO: Add your control notification handler code here
_me630EnableInt(m_iCurrentBoardIndex, ME630_IRQ_2, CME630DemoApp::IRQ2TestFunction, m_iCurrentBoardIndex);
m_bIntEnabled[m_iCurrentBoardIndex][1] = TRUE;
}
void CME630DemoDlg::OnButtonDioResetAll()
{
// TODO: Add your control notification handler code here
_me630DIOResetAll(m_iCurrentBoardIndex);
}
void CME630DemoDlg::OnButtonDioConfig()
{
// TODO: Add your control notification handler code here
int i_port_number;
if(IsDlgButtonChecked(IDC_RADIO_DIO_CONFIG_PORT_C) != 0)
{
i_port_number = ME630_DIO_PORT_C;
}
else
{
i_port_number = ME630_DIO_PORT_D;
}
int i_port_dir;
if(IsDlgButtonChecked(IDC_RADIO_CONFIG_INPUT) != 0)
{
i_port_dir = ME630_DIO_PORT_INPUT;
}
else
{
i_port_dir = ME630_DIO_PORT_OUTPUT;
}
_me630DIOConfig(m_iCurrentBoardIndex, i_port_number, i_port_dir);
}
void CME630DemoDlg::OnButtonDioGetByte()
{
// TODO: Add your control notification handler code here
int i_port_number;
if(IsDlgButtonChecked(IDC_RADIO_DIO_GET_BYTE_PORT_C) != 0)
{
i_port_number = ME630_DIO_PORT_C;
}
else
{
i_port_number = ME630_DIO_PORT_D;
}
unsigned char uc_value;
_me630DIOGetByte(m_iCurrentBoardIndex, i_port_number, &uc_value);
// Set the appropriate check boxes in the dialog
// Check the appropriate check box if the last bit of w_set is 1
// Otherwise leave the check box unchecked
CheckDlgButton(IDC_DIO_GET_BYTE_0, uc_value&0x01);
// Shift w_set left to handle the next bit
uc_value>>= 1;
// Continue in this way with each bit of w_set and the appropriate check box
CheckDlgButton(IDC_DIO_GET_BYTE_1, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_2, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_3, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_4, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_5, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_6, uc_value&0x01);
uc_value>>= 1;
CheckDlgButton(IDC_DIO_GET_BYTE_7, uc_value&0x01);
}
void CME630DemoDlg::OnButtonDioGetBit()
{
// TODO: Add your control notification handler code here
int i_port_number;
if(IsDlgButtonChecked(IDC_RADIO_DIO_GET_BIT_PORT_C) != 0)
{
i_port_number = ME630_DIO_PORT_C;
}
else
{
i_port_number = ME630_DIO_PORT_D;
}
// Get the chosen bit number
int i_bit_no = m_comboDIOGetBit.GetCurSel();
int i_value;
// Get the bit value
_me630DIOGetBit(m_iCurrentBoardIndex, i_port_number, i_bit_no, &i_value);
if(i_value == 0)
{
// Bit value 0, uncheck the check box
CheckDlgButton(IDC_CHECK_DIO_GET_BIT, 0);
}
else
{
// Bit value 1, check the check box
CheckDlgButton(IDC_CHECK_DIO_GET_BIT, 1);
}
}
void CME630DemoDlg::OnButtonDioSetByte()
{
// TODO: Add your control notification handler code here
int i_port_number;
if(IsDlgButtonChecked(IDC_RADIO_DIO_SET_BYTE_PORT_C) != 0)
{
i_port_number = ME630_DIO_PORT_C;
}
else
{
i_port_number = ME630_DIO_PORT_D;
}
// Initialise the output byte
unsigned char uc_value = 0;
// Initialise a bit mask
unsigned char uc_mask = 0x01;
// If the check box corresponding to the first bit is checked, then set
// the first bit in our result
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_0) )
{
uc_value|= uc_mask;
}
// Shift the mask to handle the next bit
uc_mask<<= 1;
// Continue in this way for each check box and the appropriate bit of our result
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_1) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_2) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_3) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_4) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_5) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_6) )
{
uc_value|= uc_mask;
}
uc_mask<<= 1;
if( IsDlgButtonChecked(IDC_DIO_SET_BYTE_7) )
{
uc_value|= uc_mask;
}
// Write the relay word to the appropriate me630 register with an me630 call
_me630DIOSetByte(m_iCurrentBoardIndex, i_port_number, uc_value);
}
void CME630DemoDlg::OnButtonDioSetBit()
{
// TODO: Add your control notification handler code here
int i_port_number;
if(IsDlgButtonChecked(IDC_RADIO_DIO_SET_BIT_PORT_C) != 0)
{
i_port_number = ME630_DIO_PORT_C;
}
else
{
i_port_number = ME630_DIO_PORT_D;
}
// Get the chosen bit number
int i_bit_no = m_comboDIOSetBit.GetCurSel();
// Get the bit value
int i_value;
if( IsDlgButtonChecked(IDC_CHECK_DIO_SET_BIT) )
{
// Check box is checked - bit value = 1.
i_value = 1;
}
else
{
// Check box not checked - bit value = 0.
i_value = 0;
}
// Set the bit value
_me630DIOSetBit(m_iCurrentBoardIndex, i_port_number, i_bit_no, i_value);
}
| [
"rene.lottes@hof-university.de"
] | rene.lottes@hof-university.de |
0f57997e9ba9c77f0bad6dd63bb0d6ff4db5da3c | 290c3c0c93db33f31fc44c307c58a8a43f7193a4 | /source/device/phydevice.h | ed02711d57f8ffb17bb3dd9a3dd3dcfe84b8439d | [] | no_license | yisea123/megarobostudio | d16364087296eeaa1ae90b1178875379bcdbca34 | efb2ae438e2a73635619611232522a012e1921f8 | refs/heads/master | 2022-12-11T10:14:06.889822 | 2018-12-04T00:33:47 | 2018-12-04T00:33:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | h | #ifndef PHYDEVICE_H
#define PHYDEVICE_H
#include "vrobot.h"
class PhyDevice : public VRobot
{
public:
PhyDevice();
};
#endif // PHYDEVICE_H
| [
"wangzhiyan@megarobo.tech"
] | wangzhiyan@megarobo.tech |
754f6198e3f242224fd5195edc4b3d31fc4f5b2d | 033ce741b252ce2feb7f408e836501aac9ec36f6 | /tensorflow/compiler/tf2xla/mlir_bridge_pass.cc | 51b737e5144d1e1016603f1a981983fda6231735 | [
"Apache-2.0"
] | permissive | sagol/tensorflow | b6a13b386e2253386711b4fc3261af4cea66358c | 04f2870814d2773e09dcfa00cbe76a66a2c4de88 | refs/heads/master | 2021-01-02T05:42:33.093330 | 2020-02-10T11:50:54 | 2020-02-10T11:55:48 | 239,504,484 | 1 | 0 | Apache-2.0 | 2020-02-10T12:17:41 | 2020-02-10T12:17:40 | null | UTF-8 | C++ | false | false | 5,303 | cc | /* Copyright 2019 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.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/mlir_bridge_pass.h"
#include <string>
#include "absl/container/flat_hash_set.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_os_ostream.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/export_graphdef.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
// Dumps the MLIR module to disk.
// This require the TF_DUMP_GRAPH_PREFIX to be set to a path that exist (or can
// be created).
static void DumpModule(mlir::ModuleOp module, llvm::StringRef file_prefix) {
const char* prefix_env = getenv("TF_DUMP_GRAPH_PREFIX");
if (!prefix_env) {
LOG(WARNING)
<< "Failed to dump MLIR module because dump location is not "
<< " specified through TF_DUMP_GRAPH_PREFIX environment variable.";
return;
}
std::string prefix = prefix_env;
auto* env = tensorflow::Env::Default();
auto status = env->RecursivelyCreateDir(prefix);
if (!status.ok()) {
LOG(WARNING) << "cannot create directory '" + prefix +
"': " + status.error_message();
return;
}
prefix += "/" + file_prefix.str();
if (!tensorflow::Env::Default()->CreateUniqueFileName(&prefix, ".mlir")) {
LOG(WARNING) << "cannot create unique filename, won't dump MLIR module.";
return;
}
std::unique_ptr<WritableFile> file_writer;
status = env->NewWritableFile(prefix, &file_writer);
if (!status.ok()) {
LOG(WARNING) << "cannot open file '" + prefix +
"': " + status.error_message();
return;
}
// Print the module to a string before writing to the file.
std::string txt_module;
{
llvm::raw_string_ostream os(txt_module);
module.print(os);
}
status = file_writer->Append(txt_module);
if (!status.ok()) {
LOG(WARNING) << "error writing to file '" + prefix +
"': " + status.error_message();
return;
}
(void)file_writer->Close();
VLOG(1) << "Dumped MLIR module to " << prefix;
}
// This runs the first phase of the "bridge", transforming the graph in a form
// that can be executed with delegation of some computations to an accelerator.
// This builds on the model of XLA where a subset of the graph is encapsulated
// and attached to a "compile" operation, whose result is fed to an "execute"
// operation. The kernel for these operations is responsible to lower the
// encapsulated graph to a particular device.
Status MlirBridgePass::Run(const DeviceSet& device_set,
const ConfigProto& config_proto,
std::unique_ptr<Graph>* graph,
FunctionLibraryDefinition* flib_def,
std::vector<std::string>* control_ret_node_names,
bool* control_rets_updated) {
if (!config_proto.experimental().enable_mlir_bridge()) {
VLOG(1) << "Skipping MLIR Bridge Pass, session flag not enabled";
return Status::OK();
}
VLOG(1) << "Running MLIR Bridge Pass";
GraphDebugInfo debug_info;
mlir::MLIRContext context;
GraphImportConfig import_config;
import_config.graph_as_function = true;
import_config.control_outputs = *control_ret_node_names;
TF_ASSIGN_OR_RETURN(auto module_ref,
ConvertGraphToMlir(**graph, debug_info, *flib_def,
import_config, &context));
AddDevicesToOp(*module_ref, &device_set);
if (VLOG_IS_ON(1)) DumpModule(*module_ref, "mlir_bridge_before_");
// Run the bridge now
TF_RETURN_IF_ERROR(
mlir::TFTPU::TPUBridge(*module_ref, /*enable_logging=*/VLOG_IS_ON(1)));
if (VLOG_IS_ON(1)) DumpModule(*module_ref, "mlir_bridge_after_");
GraphExportConfig export_config;
export_config.graph_as_function = true;
absl::flat_hash_set<Node*> control_ret_nodes;
TF_RETURN_WITH_CONTEXT_IF_ERROR(
ConvertMlirToGraph(*module_ref, export_config, graph, flib_def,
&control_ret_nodes),
"Error converting MLIR module back to graph");
control_ret_node_names->clear();
control_ret_node_names->reserve(control_ret_nodes.size());
for (const auto* node : control_ret_nodes)
control_ret_node_names->push_back(node->name());
*control_rets_updated = true;
return Status::OK();
}
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
bb1739fb3196efc1e7bbfd84a7eb98263699184c | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-restsdk/generated/model/ComAdobeGraniteAcpPlatformPlatformServletInfo.h | a63d8a2a9346ef4b4ca5ec98cff8def8c51fbbe2 | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 2,913 | h | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* ComAdobeGraniteAcpPlatformPlatformServletInfo.h
*
*
*/
#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteAcpPlatformPlatformServletInfo_H_
#define ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteAcpPlatformPlatformServletInfo_H_
#include "../ModelBase.h"
#include <cpprest/details/basic_types.h>
#include "ComAdobeGraniteAcpPlatformPlatformServletProperties.h"
namespace org {
namespace openapitools {
namespace client {
namespace model {
/// <summary>
///
/// </summary>
class ComAdobeGraniteAcpPlatformPlatformServletInfo
: public ModelBase
{
public:
ComAdobeGraniteAcpPlatformPlatformServletInfo();
virtual ~ComAdobeGraniteAcpPlatformPlatformServletInfo();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
void fromJson(web::json::value& json) override;
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// ComAdobeGraniteAcpPlatformPlatformServletInfo members
/// <summary>
///
/// </summary>
utility::string_t getPid() const;
bool pidIsSet() const;
void unsetPid();
void setPid(utility::string_t value);
/// <summary>
///
/// </summary>
utility::string_t getTitle() const;
bool titleIsSet() const;
void unsetTitle();
void setTitle(utility::string_t value);
/// <summary>
///
/// </summary>
utility::string_t getDescription() const;
bool descriptionIsSet() const;
void unsetDescription();
void setDescription(utility::string_t value);
/// <summary>
///
/// </summary>
std::shared_ptr<ComAdobeGraniteAcpPlatformPlatformServletProperties> getProperties() const;
bool propertiesIsSet() const;
void unsetProperties();
void setProperties(std::shared_ptr<ComAdobeGraniteAcpPlatformPlatformServletProperties> value);
protected:
utility::string_t m_Pid;
bool m_PidIsSet;
utility::string_t m_Title;
bool m_TitleIsSet;
utility::string_t m_Description;
bool m_DescriptionIsSet;
std::shared_ptr<ComAdobeGraniteAcpPlatformPlatformServletProperties> m_Properties;
bool m_PropertiesIsSet;
};
}
}
}
}
#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteAcpPlatformPlatformServletInfo_H_ */
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
b01cff718e1300bceadab838f0f5d7afc8d1f3fb | eedd904304046caceb3e982dec1d829c529da653 | /clanlib/ClanLib-2.2.8/Sources/API/Sound/soundoutput_description.h | bc9f8463c53ca6c130c1f53cfea38484d880d8a9 | [] | no_license | PaulFSherwood/cplusplus | b550a9a573e9bca5b828b10849663e40fd614ff0 | 999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938 | refs/heads/master | 2023-06-07T09:00:20.421362 | 2023-05-21T03:36:50 | 2023-05-21T03:36:50 | 12,607,904 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | h | /*
** ClanLib SDK
** Copyright (c) 1997-2011 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
/// \addtogroup clanSound_Audio_Mixing clanSound Audio Mixing
/// \{
#pragma once
#include "api_sound.h"
#include "../Core/System/sharedptr.h"
class CL_SoundOutput_Description_Impl;
/// \brief Sound output description class.
///
/// \xmlonly !group=Sound/Audio Mixing! !header=sound.h! \endxmlonly
class CL_API_SOUND CL_SoundOutput_Description
{
/// \name Construction
/// \{
public:
/// \brief Constructs a sound output description.
CL_SoundOutput_Description();
~CL_SoundOutput_Description();
/// \}
/// \name Attributes
/// \{
public:
/// \brief Returns the mixing frequency for the sound output device.
int get_mixing_frequency() const;
/// \brief Returns the mixing latency in milliseconds.
int get_mixing_latency() const;
/// \}
/// \name Operations
/// \{
public:
/// \brief Sets the mixing frequency for the sound output device.
void set_mixing_frequency(int frequency);
/// \brief Sets the mixing latency in milliseconds.
void set_mixing_latency(int latency);
/// \}
/// \name Implementation
/// \{
private:
CL_SharedPtr<CL_SoundOutput_Description_Impl> impl;
/// \}
};
/// \}
| [
"paulfsherwood@gmail.com"
] | paulfsherwood@gmail.com |
1e372197dd6fd332f88050bc34be9ab211bd8888 | 0b84a35e2028e8e4694d4fdda8ae760f88945083 | /sources/effects.h | 2a2334a9a137a7d1cfee9a3df8262568dcd7e656 | [] | no_license | vinod-patil/Vector-Graphics-Creator | 80099a892727e5e90cb20de5a96df17bf343d9cc | 01a9c929db48585dd0051daf72c2f32101130ffd | refs/heads/master | 2021-01-16T17:44:14.150992 | 2014-04-25T05:56:42 | 2014-04-25T05:56:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | h | /*
* This source file is part of EasyPaint.
*
* Copyright (c) 2012 EasyPaint <https://github.com/Gr1N/EasyPaint>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EFFECTS_H
#define EFFECTS_H
#include <QtCore/QObject>
QT_BEGIN_NAMESPACE
class ImageArea;
QT_END_NAMESPACE
/**
* @brief Class for implementation of effects which changing view of image.
*
*/
class Effects : public QObject
{
Q_OBJECT
public:
/**
* @brief Constructor
*
* @param pImageArea A pointer to ImageArea.
* @param parent Pointer for parent.
*/
explicit Effects(ImageArea *pImageArea, QObject *parent = 0);
~Effects();
/**
* @brief Gray effect
*
*/
void gray();
/**
* @brief Negative effect
*
*/
void negative();
private:
ImageArea *mPImageArea; /**< A pointer to ImageArea. */
signals:
public slots:
};
#endif // EFFECTS_H
| [
"vinod.patil@live.com"
] | vinod.patil@live.com |
8d1b1303754180144e32ab664ceff04661c0da2b | 3db023edb0af1dcf8a1da83434d219c3a96362ba | /windows_nt_3_5_source_code/NT-782/PRIVATE/NET/RAS/SRC/UI/SETUP/SRC/FILE.CXX | 57ba3cc7f5f546a417ae3c00e57242d9843dfaf8 | [] | no_license | xiaoqgao/windows_nt_3_5_source_code | de30e9b95856bc09469d4008d76191f94379c884 | d2894c9125ff1c14028435ed1b21164f6b2b871a | refs/heads/master | 2022-12-23T17:58:33.768209 | 2020-09-28T20:20:18 | 2020-09-28T20:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,401 | cxx | /*++
Copyright (c) 1992 Microsoft Corporation
Module Name:
file.cxx
Abstract:
This module contians the routines for reading and writing
configuration information to files or registry.
Author: Ram Cherala
Revision History:
Aug 18th 93 ramc Split from the very big portscfg.cxx file
--*/
#include "precomp.hxx"
/* Dialog helper routines
*/
APIERR
GetInstalledSerialPorts( )
/*
* enumerate the list of serial ports on the local system by reading the
* registry key HARDWARE\DEVICEMAP\SERIALCOMM.
*
*/
{
APIERR err = NERR_Success;
REG_KEY_INFO_STRUCT reginfo;
REG_VALUE_INFO_STRUCT valueinfo;
ALIAS_STR nlsUnKnown = SZ("");
// Obtain the registry key for the LOCAL_MACHINE
REG_KEY *pregLocalMachine = REG_KEY::QueryLocalMachine();
// Open the SerialComm key
NLS_STR nlsSerialComm = REGISTRY_SERIALCOMM;
REG_KEY RegKeySerialComm(*pregLocalMachine,nlsSerialComm,MAXIMUM_ALLOWED);
if (( err = RegKeySerialComm.QueryError()) != NERR_Success )
{
return err;
}
REG_ENUM EnumSerial(RegKeySerialComm);
// Get the number of com ports configured in the machine
if (( err = RegKeySerialComm.QueryInfo(®info))!=NERR_Success)
{
return err;
}
ULONG ulNumValues = reginfo.ulValues;
LONG cbMaxValue;
BOOL fPortFound = FALSE;
BYTE * pbValueData = NULL;
cbMaxValue = reginfo.ulMaxValueLen;
for (ULONG ulCount = 0; ulCount < ulNumValues ; ulCount ++)
{
valueinfo.pwcData = new BYTE[cbMaxValue];
valueinfo.ulDataLength = cbMaxValue;
if(valueinfo.pwcData == NULL)
return ERROR_NOT_ENOUGH_MEMORY;
if((err=EnumSerial.NextValue(&valueinfo))!=NERR_Success)
{
return err;
}
// check to see that the registry enumeration did not return
// a null string - fix for Bug #25 - Add port dialog presents
// blank drop down combo - filed by JawadK
if(*(valueinfo.pwcData))
{
fPortFound = TRUE;
::InsertToAddPortListSorted((WCHAR*)valueinfo.pwcData);
}
}
if(fPortFound)
return (NERR_Success);
else
return (-1);
}
BOOL
IsPortInstalled(
TCHAR * pszPortName
)
/* This routine checks to see if the portname specified is
* actually installed on the system.
*
*/
{
ITER_STRLIST iterAddPortList(strAddPortList);
NLS_STR * pnls;
while(pnls = iterAddPortList())
{
if(!lstrcmpi((TCHAR*)pnls, pszPortName))
return TRUE;
}
return FALSE;
}
APIERR
GetConfiguredSerialPorts(
HWND hwndOwner,
BOOL *fConfigured,
USHORT *NumPorts,
USHORT *NumClient,
USHORT *NumServer
)
/*
* Enumerate all the serial ports previously configured for RAS by reading
* from SERIAL.INI.
*
*/
{
CHAR szPortName[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceType[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceName[RAS_MAXLINEBUFLEN +1];
CHAR szMaxConnectBps[RAS_MAXLINEBUFLEN +1];
CHAR szMaxCarrierBps[RAS_MAXLINEBUFLEN +1];
CHAR szUsage[RAS_MAXLINEBUFLEN +1];
CHAR szDefaultOff[RAS_MAXLINEBUFLEN +1];
WCHAR wszPortName[RAS_MAXLINEBUFLEN +1];
WCHAR wszDeviceType[RAS_MAXLINEBUFLEN +1];
WCHAR wszDeviceName[RAS_MAXLINEBUFLEN +1];
WCHAR wszMaxConnectBps[RAS_MAXLINEBUFLEN +1];
WCHAR wszMaxCarrierBps[RAS_MAXLINEBUFLEN +1];
WCHAR wszUsage[RAS_MAXLINEBUFLEN +1];
WCHAR wszDefaultOff[RAS_MAXLINEBUFLEN +1];
ITER_DL_OF(PORT_INFO) iterdlPortInfo(dlPortInfo);
HRASFILE hSerialIni;
hSerialIni = RasfileLoad( SerialIniPath,
RFM_LOADCOMMENTS,
NULL, //load all sections
NULL
);
if( hSerialIni == -1)
{
return(IDS_OPEN_SERIALINI);
}
*NumPorts = 0;
*NumClient = 0;
*NumServer = 0;
if(!RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_FILE))
{
RasfileClose(hSerialIni);
return (NERR_Success);
}
do
{
// Get Section Name
if( !RasfileGetSectionName( hSerialIni, szPortName ))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_SECTIONNAME);
}
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szPortName,
strlen(szPortName)+1, wszPortName,
RAS_MAXLINEBUFLEN);
// If the previously configued port is now not installed on the
// system, just nuke this entry under the covers and force an update
// of SERIAL.INI
if(!IsPortInstalled(wszPortName))
{
GfForceUpdate = TRUE;
continue;
}
*fConfigured = TRUE;
(*NumPorts)++;
// Get Device Type
if(!(RasfileFindNextKeyLine(hSerialIni, SER_DEVICETYPE_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szDeviceType)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_DEVICETYPE);
}
// Get Device Name
if (!(RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hSerialIni, SER_DEVICENAME_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szDeviceName)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_DEVICENAME);
}
// Get MaxConnectBps
if (!(RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hSerialIni, SER_MAXCONNECTBPS_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szMaxConnectBps)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_MAXCONNECTBPS);
}
// Get MaxCarrierBps
if (!(RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hSerialIni, SER_MAXCARRIERBPS_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szMaxCarrierBps)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_MAXCARRIERBPS);
}
// Get Usage
// if the ports are being configured during installation, then read
// the usage from the serial.ini file
if(GfInstallMode == FALSE)
{
if (!(RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hSerialIni, SER_USAGE_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szUsage)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_USAGE);
}
}
else // set the usage based on the installed options.
{
wcstombs(szUsage, GInstalledOption, lstrlen(GInstalledOption)+1);
}
if (!stricmp(szUsage, SER_USAGE_VALUE_CLIENT))
(*NumClient)++;
else if (!stricmp(szUsage, SER_USAGE_VALUE_SERVER))
(*NumServer)++;
else if (!stricmp(szUsage, SER_USAGE_VALUE_BOTH))
{
(*NumClient)++;
(*NumServer)++;
}
// Get DefaultOff
if (!(RasfileFindFirstLine(hSerialIni, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hSerialIni, SER_DEFAULTOFF_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hSerialIni, NULL, szDefaultOff)))
{
MsgPopup(hwndOwner, IDS_READ_SERIALINI, MPSEV_ERROR);
return(ERROR_READING_DEFAULTOFF);
}
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceType,
strlen(szDeviceType)+1, wszDeviceType,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceName,
strlen(szDeviceName)+1, wszDeviceName,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szMaxConnectBps,
strlen(szMaxConnectBps)+1, wszMaxConnectBps,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szMaxCarrierBps,
strlen(szMaxCarrierBps)+1, wszMaxCarrierBps,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szUsage,
strlen(szUsage)+1, wszUsage,
RAS_MAXLINEBUFLEN);
if(strlen(szDefaultOff))
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDefaultOff,
strlen(szDefaultOff)+1, wszDefaultOff,
RAS_MAXLINEBUFLEN);
else
lstrcpy(wszDefaultOff,SZ(""));
dlPortInfo.Append(new PORT_INFO(wszPortName,
wszDeviceType,
wszDeviceName,
wszMaxConnectBps,
wszMaxCarrierBps,
wszUsage,
wszDefaultOff
));
}while(RasfileFindNextLine(hSerialIni, RFL_SECTION, RFS_FILE));
RasfileClose(hSerialIni);
return (NERR_Success);
}
APIERR
SaveSerialPortInfo(
HWND hwndOwner,
BOOL *fConfigured,
USHORT *NumPorts,
USHORT *NumClient,
USHORT *NumServer
)
/*
* Save the configured serial port information in serial.ini
*
*/
{
HRASFILE hSerialIni;
CHAR szPortName[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceType[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceName[RAS_MAXLINEBUFLEN +1];
CHAR szMaxConnectBps[RAS_MAXLINEBUFLEN +1];
CHAR szMaxCarrierBps[RAS_MAXLINEBUFLEN +1];
CHAR szUsage[RAS_MAXLINEBUFLEN +1];
CHAR szDefaultOff[RAS_MAXLINEBUFLEN +1];
CHAR szClientDefaultOff[RAS_MAXLINEBUFLEN +1];
WCHAR wszClientDefaultOff[RAS_MAXLINEBUFLEN +1];
CHAR szInitBps[RAS_MAXLINEBUFLEN +1];
UINT ValidCarrierBps[] = {1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200};
*fConfigured = FALSE;
*NumPorts = 0;
*NumClient = 0;
*NumServer = 0;
ITER_DL_OF(PORT_INFO) iterdlPortInfo(dlPortInfo);
PORT_INFO* pPortInfo;
// make a backup copy of the file if it exists. The third parameter
// to CopyFile says it is OK to overwrite the existing backup file.
CopyFile(WSerialIniPath, WSerialIniBakPath, FALSE);
hSerialIni = RasfileLoad( SerialIniPath,
RFM_CREATE | RFM_KEEPDISKFILEOPEN,
NULL, //load all sections
NULL
);
if( hSerialIni == -1)
{
MsgPopup(hwndOwner, IDS_CREATE_SERIALINI, MPSEV_ERROR);
return(IDS_CREATE_SERIALINI);
}
// Now delete all lines in the file.
while(RasfileFindFirstLine(hSerialIni, RFL_ANY, RFS_FILE))
{
RasfileDeleteLine(hSerialIni);
}
// This blank line insertion is required to ensure that
// RasfileFindNextLine in the while loop below will work.
RasfileInsertLine(hSerialIni, "", FALSE);
RasfileFindFirstLine(hSerialIni, RFL_ANY, RFS_FILE);
while(pPortInfo = iterdlPortInfo())
{
// only write modem or pad information to serial.ini
if(lstrcmpi(pPortInfo->QueryDeviceType(), W_DEVICETYPE_MODEM) &&
lstrcmpi(pPortInfo->QueryDeviceType(), W_DEVICETYPE_PAD) )
{
continue;
}
// remember that at least one serial port was configured
*fConfigured = TRUE;
(*NumPorts)++;
// Set Section Name
wcstombs(szPortName, pPortInfo->QueryPortName(), RAS_MAXLINEBUFLEN);
if(!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutSectionName( hSerialIni, szPortName )))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_SECTIONNAME);
}
// Set Device Type
wcstombs(szDeviceType, pPortInfo->QueryDeviceType(), RAS_MAXLINEBUFLEN);
if(!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_DEVICETYPE_KEY, szDeviceType)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_DEVICETYPE);
}
// Set Device Name
wcstombs(szDeviceName, pPortInfo->QueryDeviceName(), RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_DEVICENAME_KEY, szDeviceName)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_DEVICENAME);
}
// Set MaxConnectBps
wcstombs(szMaxConnectBps, pPortInfo->QueryMaxConnectBps(), RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_MAXCONNECTBPS_KEY, szMaxConnectBps)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_MAXCONNECTBPS);
}
// Set MaxCarrierBps
wcstombs(szMaxCarrierBps, pPortInfo->QueryMaxCarrierBps(), RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_MAXCARRIERBPS_KEY, szMaxCarrierBps)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_MAXCARRIERBPS);
}
// Set Usage
wcstombs(szUsage, pPortInfo->QueryUsage(), RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_USAGE_KEY, szUsage)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_USAGE);
}
if (!stricmp(szUsage, SER_USAGE_VALUE_CLIENT))
(*NumClient)++;
else if (!stricmp(szUsage, SER_USAGE_VALUE_SERVER))
(*NumServer)++;
else if (!stricmp(szUsage, SER_USAGE_VALUE_BOTH))
{
(*NumClient)++;
(*NumServer)++;
}
// Set Server DefaultOff
wcstombs(szDefaultOff, pPortInfo->QueryDefaultOff(), RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_DEFAULTOFF_KEY, szDefaultOff)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_DEFAULTOFF);
}
// Set Client DefaultOff
wszClientDefaultOff[0] = '\0';
GetClientDefaultOff((WCHAR*)pPortInfo->QueryDeviceName(), wszClientDefaultOff);
wcstombs(szClientDefaultOff, wszClientDefaultOff, RAS_MAXLINEBUFLEN);
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_C_DEFAULTOFF_KEY,
szClientDefaultOff)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_DEFAULTOFF);
}
// InitBps value is set to either the MaxConnectBps or the
// MaxCarrierBps value based on whether the HdwFlowControl is
// ON or OFF respectively.
// find if HardwareFlowControl is disabled
char * pFlowCtrl = strstr(szDefaultOff, MXS_HDWFLOWCONTROL_KEY);
if(pFlowCtrl == (char*)NULL) // hdwflowctrl is enabled
{
strcpy(szInitBps, szMaxConnectBps);
}
else // hdwflowctrl is disabled
{
// we need to make sure that the InitBps is set to a valid
// MaxCarrierBps value. i.e., 14400 should be upped to 19200
DWORD dwCarrierBps = atoi(szMaxCarrierBps);
DWORD dwEntries = sizeof(ValidCarrierBps)/sizeof(int);
for(UINT index=0; index < dwEntries ; index++)
{
if(dwCarrierBps == ValidCarrierBps[index])
break;
if(dwCarrierBps < ValidCarrierBps[index])
{
dwCarrierBps = ValidCarrierBps[index];
break;
}
}
// if we got here through the for loop termination, set
// the carrierbps to the last entry in the valid list.
if(index == dwEntries)
dwCarrierBps = ValidCarrierBps[index-1];
itoa((INT)dwCarrierBps, szInitBps, 10);
}
if (!(RasfileInsertLine(hSerialIni, "", FALSE) &&
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE) &&
RasfilePutKeyValueFields(hSerialIni, SER_INITBPS_KEY, szInitBps)))
{
MsgPopup(hwndOwner, IDS_WRITE_SERIALINI, MPSEV_ERROR);
return(ERROR_WRITING_INITBPS);
}
RasfileInsertLine(hSerialIni, "", FALSE);
RasfileFindNextLine(hSerialIni, RFL_ANY, RFS_FILE);
}
RasfileWrite(hSerialIni, NULL);
RasfileClose(hSerialIni);
return (NERR_Success);
}
VOID
GetClientDefaultOff(WCHAR * ModemName, WCHAR * ClientDefaultOff)
/*
* given the name of the modem, gets the ClientDefaultOff value from
* the device list.
*/
{
ITER_DL_OF(DEVICE_INFO) iterdlDeviceInfo(dlDeviceInfo);
DEVICE_INFO* pDevice;
iterdlDeviceInfo.Reset();
while(pDevice = iterdlDeviceInfo())
{
if(!lstrcmpi(pDevice->QueryDeviceName(), ModemName))
{
lstrcpy(ClientDefaultOff, pDevice->QueryClientDefaultOff());
break;
}
}
return;
}
APIERR
InitializeDeviceList(
HWND hwndOwner
)
/*
* Initialize the device list dlDeviceInfo by reading in the sections
* from Modem.inf and Pad.inf files from the Ras directory.
*
*/
{
HRASFILE hInf;
APIERR err = NERR_Success;
// add a NONE device to the list of devices
RESOURCE_STR nlsDeviceNone(IDS_DEVICE_NONE);
dlDeviceInfo.Add(new DEVICE_INFO( (TCHAR*)nlsDeviceNone.QueryPch(),
(TCHAR*)nlsDeviceNone.QueryPch(),
W_NONE_MAXCONNECTBPS,
W_NONE_MAXCARRIERBPS,
SZ(""), // server DefaultOff
SZ("Compression") // Client DefaultOff
));
hInf = RasfileLoad( ModemInfPath,
RFM_READONLY,
NULL, //load all sections
NULL
);
if( hInf == -1)
{
MsgPopup(hwndOwner, IDS_OPEN_MODEMINF, MPSEV_ERROR);
return(IDS_OPEN_MODEMINF);
}
err = ReadInfFile(hInf, MODEM, hwndOwner);
RasfileClose(hInf);
if(err != NERR_Success)
{
return(err);
}
hInf = RasfileLoad( PadInfPath,
RFM_READONLY,
NULL, //load all sections
NULL
);
if( hInf == -1)
{
return(NERR_Success);
}
err = ReadInfFile(hInf, PAD, hwndOwner);
RasfileClose(hInf);
return(err);
}
APIERR
ReadInfFile(
HRASFILE hInf,
DEVICE_TYPE device,
HWND hwndOwner
)
/*
* helper function for reading the device information from modem.inf or pad.inf
*
*/
{
CHAR szDeviceType[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceName[RAS_MAXLINEBUFLEN +1];
CHAR szDeviceAlias[RAS_MAXLINEBUFLEN +1];
CHAR szMaxConnectBps[RAS_MAXLINEBUFLEN +1];
CHAR szMaxCarrierBps[RAS_MAXLINEBUFLEN +1];
CHAR szDefaultOff[RAS_MAXLINEBUFLEN +1];
CHAR szClientDefaultOff[RAS_MAXLINEBUFLEN +1];
WCHAR wszDeviceType[RAS_MAXLINEBUFLEN +1];
WCHAR wszDeviceName[RAS_MAXLINEBUFLEN +1];
WCHAR wszMaxConnectBps[RAS_MAXLINEBUFLEN +1];
WCHAR wszMaxCarrierBps[RAS_MAXLINEBUFLEN +1];
WCHAR wszDefaultOff[RAS_MAXLINEBUFLEN +1];
WCHAR wszClientDefaultOff[RAS_MAXLINEBUFLEN +1];
BOOL fAlias = FALSE;
USHORT MsgId;
APIERR err;
ITER_DL_OF(DEVICE_INFO) iterdlDeviceInfo(dlDeviceInfo);
if (device == MODEM)
{
strcpy(szDeviceType, "Modem");
MsgId = IDS_READ_MODEMINF;
}
else if (device == PAD)
{
strcpy(szDeviceType, "Pad");
MsgId = IDS_READ_PADINF;
}
// The first section is - [Modem Responses] section
// skip over the Modem Responses section
RasfileFindNextLine(hInf, RFL_SECTION, RFS_FILE);
do
{
// Get Section Name
szDeviceName[0] = '\0';
if( !RasfileGetSectionName( hInf, szDeviceName ))
{
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceName,
strlen(szDeviceName)+1, wszDeviceName,
RAS_MAXLINEBUFLEN);
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(ERROR_READING_SECTIONNAME);
}
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceName,
strlen(szDeviceName)+1, wszDeviceName,
RAS_MAXLINEBUFLEN);
if (lstrlen(wszDeviceName) > MAX_DEVICE_NAME)
{
MsgPopup(hwndOwner, IDS_INVALID_DEVICELEN,
MPSEV_INFO, MP_OK, wszDeviceName,
(device == MODEM? SZ("MODEM.INF"): SZ("PAD.INF")));
continue;
}
// Check if this is an aliased entry, if so move the curline
// to the aliased section and remember the current position
// as MARK_ALIASED_SECTION
if((RasfileFindNextKeyLine(hInf, "ALIAS", RFS_SECTION) &&
RasfileGetKeyValueFields(hInf, NULL, szDeviceAlias)))
{
fAlias = TRUE;
if(!RasfilePutLineMark(hInf, MARK_ALIASED_SECTION))
{
DPOPUP(hwndOwner, SZ("Error putting file mark"));
return(IDS_ERROR_MARKING_SECTION);
}
if(!RasfileFindSectionLine(hInf, szDeviceAlias, TRUE))
{
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(ERROR_READING_SECTIONNAME);
}
}
// Get MaxConnectBps
szMaxConnectBps[0] = '\0';
if (!(RasfileFindFirstLine(hInf, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hInf, SER_MAXCONNECTBPS_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hInf, NULL, szMaxConnectBps)))
{
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(ERROR_READING_MAXCONNECTBPS);
}
// Get MaxCarrierBps
szMaxCarrierBps[0] = '\0';
if (!(RasfileFindFirstLine(hInf, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hInf, SER_MAXCARRIERBPS_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hInf, NULL, szMaxCarrierBps)))
{
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(ERROR_READING_MAXCARRIERBPS);
}
// Get DefaultOff
szDefaultOff[0] = '\0';
if (!(RasfileFindFirstLine(hInf, RFL_SECTION, RFS_SECTION) &&
RasfileFindNextKeyLine(hInf, SER_DEFAULTOFF_KEY, RFS_SECTION) &&
RasfileGetKeyValueFields(hInf, NULL, szDefaultOff)))
{
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(ERROR_READING_DEFAULTOFF);
}
szClientDefaultOff[0] = '\0';
// Get ClientDefaultOff if present else default to MXS_COMPRESSION_KEY
// Don't complain if the key is not present.
RasfileFindFirstLine(hInf, RFL_SECTION, RFS_SECTION);
if(RasfileFindNextKeyLine(hInf, SER_C_DEFAULTOFF_KEY, RFS_SECTION))
{
RasfileGetKeyValueFields(hInf, NULL, szClientDefaultOff);
}
else
{
strcpy(szClientDefaultOff, MXS_COMPRESSION_KEY);
}
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceType,
strlen(szDeviceType)+1, wszDeviceType,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDeviceName,
strlen(szDeviceName)+1, wszDeviceName,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szMaxConnectBps,
strlen(szMaxConnectBps)+1, wszMaxConnectBps,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szMaxCarrierBps,
strlen(szMaxCarrierBps)+1, wszMaxCarrierBps,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szDefaultOff,
strlen(szDefaultOff)+1, wszDefaultOff,
RAS_MAXLINEBUFLEN);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szClientDefaultOff,
strlen(szClientDefaultOff)+1, wszClientDefaultOff,
RAS_MAXLINEBUFLEN);
if((err = dlDeviceInfo.Append(new DEVICE_INFO( wszDeviceName,
wszDeviceType,
wszMaxConnectBps,
wszMaxCarrierBps,
wszDefaultOff,
wszClientDefaultOff
))) != NERR_Success)
{
char buf[128];
wsprintfA(buf, "ReadInf: error %d appending device info\n", err);
::OutputDebugStringA(buf);
return(err);
}
if(fAlias == TRUE)
{
if(!RasfileFindMarkedLine(hInf, MARK_ALIASED_SECTION))
{
MsgPopup(hwndOwner,MsgId,MPSEV_ERROR,MP_OK,wszDeviceName);
return(IDS_ERROR_FINDING_MARK);
}
// now remove the line mark
if(!RasfilePutLineMark(hInf, 0))
{
DPOPUP(hwndOwner, SZ("Error putting file mark"));
return(IDS_ERROR_MARKING_SECTION);
}
fAlias = FALSE;
}
}while(RasfileFindNextLine(hInf, RFL_SECTION, RFS_FILE));
return (NERR_Success);
}
VOID
RemoveConfigPortsFromInstalledList(
USHORT *NumPorts,
USHORT *NumClient,
USHORT *NumServer
)
/*
* March through the configured port list.
* If a configured port is in the AddPort list, remove it from the
* AddPort list
*
*/
{
CHAR szUsage[RAS_MAXLINEBUFLEN +1];
ITER_DL_OF(PORT_INFO) iterdlPortInfo(dlPortInfo);
PORT_INFO* pPortInfo;
ITER_STRLIST iterAddPortList(strAddPortList);
NLS_STR* pNls;
// for each configured port
pPortInfo = iterdlPortInfo();
while(pPortInfo)
{
BOOL fFound = FALSE;
iterAddPortList.Reset();
while(pNls = iterAddPortList())
{
if(!lstrcmpi((TCHAR*)pNls,(TCHAR*)pPortInfo->QueryPortName()))
{
// the configured port is in the Add list
fFound = TRUE;
strAddPortList.Remove(iterAddPortList);
break;
}
}
// the previously configured port is not on the system any more
// blow it away under the covers.
if(!fFound)
{
wcstombs(szUsage, pPortInfo->QueryUsage(), RAS_MAXLINEBUFLEN);
(*NumPorts)--;
if (!stricmp(szUsage, SER_USAGE_VALUE_CLIENT))
(*NumClient)--;
else if (!stricmp(szUsage, SER_USAGE_VALUE_SERVER))
(*NumServer)--;
else if (!stricmp(szUsage, SER_USAGE_VALUE_BOTH))
{
(*NumClient)--;
(*NumServer)--;
}
// force an update because the previously configured port has
// been removed.
GfForceUpdate = TRUE;
dlPortInfo.Remove(iterdlPortInfo);
// When the current port is removed, the iterator points to the
// next port in the list. So, use QueryProp() to get the
// current port.
pPortInfo = iterdlPortInfo.QueryProp();
}
else
{
// get the next port in the list
pPortInfo = iterdlPortInfo.Next();
}
}
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
194336479d98fc568d346a9ab7283d2679003d6a | ab527b7c392b48155a11139bb5afd0adc3902a0c | /src/zimg/depth/error_diffusion_avx2.cpp | 715e3a7f55db70f95b9eac97d52c0c719611d9b2 | [
"WTFPL"
] | permissive | jeeb/zimg | 3c23b10d96d388d360135dff6123657eeac52090 | a673975492be4f09d619bc4b82fa7e65492f2544 | refs/heads/master | 2021-01-20T04:42:14.582716 | 2017-02-25T14:10:21 | 2017-02-25T14:10:21 | 83,844,590 | 2 | 0 | null | 2017-03-03T21:51:02 | 2017-03-03T21:51:01 | null | UTF-8 | C++ | false | false | 22,371 | cpp | #ifdef ZIMG_X86
#include <algorithm>
#include <climits>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <immintrin.h>
#include "common/align.h"
#include "common/ccdep.h"
#include "common/checked_int.h"
#include "common/except.h"
#include "common/make_unique.h"
#include "common/pixel.h"
#define HAVE_CPU_AVX
#include "common/x86util.h"
#undef HAVE_CPU_AVX
#include "common/zassert.h"
#include "graph/image_buffer.h"
#include "graph/image_filter.h"
#include "dither_x86.h"
#include "quantize.h"
namespace zimg {
namespace depth {
namespace {
struct error_state {
float err_left[8];
float err_top_right[8];
float err_top[8];
float err_top_left[8];
};
template <PixelType SrcType>
struct error_diffusion_traits;
template <>
struct error_diffusion_traits<PixelType::BYTE> {
typedef uint8_t type;
static float load1(const uint8_t *ptr) { return *ptr; }
static void store1(uint8_t *ptr, uint32_t x) { *ptr = static_cast<uint8_t>(x); }
static __m256 load8(const uint8_t *ptr)
{
__m256i x = _mm256_castsi128_si256(_mm_loadl_epi64((const __m128i *)ptr));
x = _mm256_unpacklo_epi8(x, _mm256_setzero_si256());
x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(0, 1, 0, 0));
x = _mm256_unpacklo_epi16(x, _mm256_setzero_si256());
return _mm256_cvtepi32_ps(x);
}
static void store8(uint8_t *ptr, __m256i x)
{
x = _mm256_packs_epi32(x, x);
x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(0, 0, 2, 0));
x = _mm256_packus_epi16(x, x);
_mm_storel_epi64((__m128i *)ptr, _mm256_castsi256_si128(x));
}
};
template <>
struct error_diffusion_traits<PixelType::WORD> {
typedef uint16_t type;
static float load1(const uint16_t *ptr) { return *ptr; }
static void store1(uint16_t *ptr, uint32_t x) { *ptr = static_cast<uint32_t>(x); }
static __m256 load8(const uint16_t *ptr)
{
__m256i x = _mm256_castsi128_si256(_mm_loadu_si128((const __m128i *)ptr));
x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(0, 1, 0, 0));
x = _mm256_unpacklo_epi16(x, _mm256_setzero_si256());
return _mm256_cvtepi32_ps(x);
}
static void store8(uint16_t *ptr, __m256i x)
{
x = _mm256_packus_epi32(x, x);
x = _mm256_permute4x64_epi64(x, _MM_SHUFFLE(0, 0, 2, 0));
_mm_storeu_si128((__m128i *)ptr, _mm256_castsi256_si128(x));
}
};
template <>
struct error_diffusion_traits<PixelType::HALF> {
typedef uint16_t type;
static float load1(const uint16_t *ptr)
{
return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(*ptr)));
}
static __m256 load8(const uint16_t *ptr) {
return _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *)ptr));
}
};
template <>
struct error_diffusion_traits<PixelType::FLOAT> {
typedef float type;
static float load1(const float *ptr) { return *ptr; }
static __m256 load8(const float *ptr) { return _mm256_loadu_ps(ptr); }
};
inline FORCE_INLINE float fma(float a, float b, float c)
{
return _mm_cvtss_f32(_mm_fmadd_ss(_mm_set_ss(a), _mm_set_ss(b), _mm_set_ss(c)));
}
inline FORCE_INLINE float max(float x, float y)
{
return _mm_cvtss_f32(_mm_max_ss(_mm_set_ss(x), _mm_set_ss(y)));
}
inline FORCE_INLINE float min(float x, float y)
{
return _mm_cvtss_f32(_mm_min_ss(_mm_set_ss(x), _mm_set_ss(y)));
}
inline FORCE_INLINE float extract_hi_ps(__m256 x)
{
__m128 y = _mm256_extractf128_ps(x, 1);
return _mm_cvtss_f32(_mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(y), 12)));
}
inline FORCE_INLINE __m256 rotate_insert_lo(__m256 x, float y)
{
__m256i mask = _mm256_set_epi32(6, 5, 4, 3, 2, 1, 0, 7);
x = _mm256_permutevar8x32_ps(x, mask);
x = _mm256_blend_ps(x, _mm256_castps128_ps256(_mm_set_ss(y)), 1);
return x;
}
template <PixelType SrcType, PixelType DstType>
void error_diffusion_scalar(const void *src, void *dst, const float * RESTRICT error_top, float * RESTRICT error_cur,
float scale, float offset, unsigned bits, unsigned width)
{
typedef error_diffusion_traits<SrcType> src_traits;
typedef error_diffusion_traits<DstType> dst_traits;
const typename src_traits::type *src_p = static_cast<const typename src_traits::type *>(src);
typename dst_traits::type *dst_p = static_cast<typename dst_traits::type *>(dst);
float err_left = error_cur[0];
float err_top_right = error_top[1 + 1];
float err_top = error_top[0 + 1];
float err_top_left = error_top[0];
for (unsigned j = 0; j < width; ++j) {
// Error array is padded by one on each side.
unsigned j_err = j + 1;
float x = fma(src_traits::load1(src_p + j), scale, offset);
float err, err0, err1;
err0 = err_left * (7.0f / 16.0f);
err0 = fma(err_top_right, 3.0f / 16.0f, err0);
err1 = err_top * (5.0f / 16.0f);
err1 = fma(err_top_left, 1.0f / 16.0f, err1);
err = err0 + err1;
x += err;
x = min(max(x, 0.0f), static_cast<float>(1L << bits) - 1);
uint32_t q = _mm_cvt_ss2si(_mm_set_ss(x));
err = x - static_cast<float>(q);
dst_traits::store1(dst_p + j, q);
error_cur[j_err] = err;
err_left = err;
err_top_left = err_top;
err_top = err_top_right;
err_top_right = error_top[j_err + 2];
}
}
decltype(&error_diffusion_scalar<PixelType::BYTE, PixelType::BYTE>) select_error_diffusion_scalar_func(PixelType pixel_in, PixelType pixel_out)
{
if (pixel_in == PixelType::BYTE && pixel_out == PixelType::BYTE)
return error_diffusion_scalar<PixelType::BYTE, PixelType::BYTE>;
else if (pixel_in == PixelType::BYTE && pixel_out == PixelType::WORD)
return error_diffusion_scalar<PixelType::BYTE, PixelType::WORD>;
else if (pixel_in == PixelType::WORD && pixel_out == PixelType::BYTE)
return error_diffusion_scalar<PixelType::WORD, PixelType::BYTE>;
else if (pixel_in == PixelType::WORD && pixel_out == PixelType::WORD)
return error_diffusion_scalar<PixelType::WORD, PixelType::WORD>;
else if (pixel_in == PixelType::HALF && pixel_out == PixelType::BYTE)
return error_diffusion_scalar<PixelType::HALF, PixelType::BYTE>;
else if (pixel_in == PixelType::HALF && pixel_out == PixelType::WORD)
return error_diffusion_scalar<PixelType::HALF, PixelType::WORD>;
else if (pixel_in == PixelType::FLOAT && pixel_out == PixelType::BYTE)
return error_diffusion_scalar<PixelType::FLOAT, PixelType::BYTE>;
else if (pixel_in == PixelType::FLOAT && pixel_out == PixelType::WORD)
return error_diffusion_scalar<PixelType::FLOAT, PixelType::WORD>;
else
error::throw_<error::InternalError>("no conversion between pixel types");
}
inline FORCE_INLINE void error_diffusion_wf_avx2_xiter(__m256 &v, unsigned j, const float *error_top, float *error_cur, const __m256 &max_val,
const __m256 &err_left_w, const __m256 &err_top_right_w, const __m256 &err_top_w, const __m256 &err_top_left_w,
__m256 &err_left, __m256 &err_top_right, __m256 &err_top, __m256 &err_top_left)
{
unsigned j_err = j + 1;
__m256 x, y, err0, err1;
__m256i q;
err0 = _mm256_mul_ps(err_left_w, err_left);
err0 = _mm256_fmadd_ps(err_top_right_w, err_top_right, err0);
err1 = _mm256_mul_ps(err_top_w, err_top);
err1 = _mm256_fmadd_ps(err_top_left_w, err_top_left, err1);
err0 = _mm256_add_ps(err0, err1);
x = _mm256_add_ps(v, err0);
x = _mm256_max_ps(x, _mm256_setzero_ps());
x = _mm256_min_ps(x, max_val);
q = _mm256_cvtps_epi32(x);
v = _mm256_castsi256_ps(q);
y = _mm256_cvtepi32_ps(q);
err0 = _mm256_sub_ps(x, y);
error_cur[j_err + 0] = extract_hi_ps(err0);
err_left = err0;
err_top_left = err_top;
err_top = err_top_right;
err_top_right = rotate_insert_lo(err0, error_top[j_err + 14 + 2]);
}
template <PixelType SrcType, PixelType DstType, class T, class U>
void error_diffusion_wf_avx2(const graph::ImageBuffer<const T> &src, const graph::ImageBuffer<U> &dst, unsigned i,
const float *error_top, float *error_cur, error_state *state, float scale, float offset, unsigned bits, unsigned width)
{
typedef error_diffusion_traits<SrcType> src_traits;
typedef error_diffusion_traits<DstType> dst_traits;
typedef typename src_traits::type src_type;
typedef typename dst_traits::type dst_type;
static_assert(std::is_same<T, src_type>::value, "wrong type");
static_assert(std::is_same<U, dst_type>::value, "wrong type");
const __m256 err_left_w = _mm256_set1_ps(7.0f / 16.0f);
const __m256 err_top_right_w = _mm256_set1_ps(3.0f / 16.0f);
const __m256 err_top_w = _mm256_set1_ps(5.0f / 16.0f);
const __m256 err_top_left_w = _mm256_set1_ps(1.0f / 16.0f);
const __m256 scale_ps = _mm256_set1_ps(scale);
const __m256 offset_ps = _mm256_set1_ps(offset);
const __m256 max_val = _mm256_set1_ps(static_cast<float>((1UL << bits) - 1));
__m256 err_left = _mm256_load_ps(state->err_left);
__m256 err_top_right = _mm256_load_ps(state->err_top_right);
__m256 err_top = _mm256_load_ps(state->err_top);
__m256 err_top_left = _mm256_load_ps(state->err_top_left);
#define XITER error_diffusion_wf_avx2_xiter
#define XARGS error_top, error_cur, max_val, err_left_w, err_top_right_w, err_top_w, err_top_left_w, err_left, err_top_right, err_top, err_top_left
for (unsigned j = 0; j < width; j += 8) {
__m256 v0 = src_traits::load8(src[i + 0] + j + 14);
__m256 v1 = src_traits::load8(src[i + 1] + j + 12);
__m256 v2 = src_traits::load8(src[i + 2] + j + 10);
__m256 v3 = src_traits::load8(src[i + 3] + j + 8);
__m256 v4 = src_traits::load8(src[i + 4] + j + 6);
__m256 v5 = src_traits::load8(src[i + 5] + j + 4);
__m256 v6 = src_traits::load8(src[i + 6] + j + 2);
__m256 v7 = src_traits::load8(src[i + 7] + j + 0);
v0 = _mm256_fmadd_ps(v0, scale_ps, offset_ps);
v1 = _mm256_fmadd_ps(v1, scale_ps, offset_ps);
v2 = _mm256_fmadd_ps(v2, scale_ps, offset_ps);
v3 = _mm256_fmadd_ps(v3, scale_ps, offset_ps);
v4 = _mm256_fmadd_ps(v4, scale_ps, offset_ps);
v5 = _mm256_fmadd_ps(v5, scale_ps, offset_ps);
v6 = _mm256_fmadd_ps(v6, scale_ps, offset_ps);
v7 = _mm256_fmadd_ps(v7, scale_ps, offset_ps);
mm256_transpose8_ps(v0, v1, v2, v3, v4, v5, v6, v7);
XITER(v0, j + 0, XARGS);
XITER(v1, j + 1, XARGS);
XITER(v2, j + 2, XARGS);
XITER(v3, j + 3, XARGS);
XITER(v4, j + 4, XARGS);
XITER(v5, j + 5, XARGS);
XITER(v6, j + 6, XARGS);
XITER(v7, j + 7, XARGS);
mm256_transpose8_ps(v0, v1, v2, v3, v4, v5, v6, v7);
dst_traits::store8(dst[i + 0] + j + 14, _mm256_castps_si256(v0));
dst_traits::store8(dst[i + 1] + j + 12, _mm256_castps_si256(v1));
dst_traits::store8(dst[i + 2] + j + 10, _mm256_castps_si256(v2));
dst_traits::store8(dst[i + 3] + j + 8, _mm256_castps_si256(v3));
dst_traits::store8(dst[i + 4] + j + 6, _mm256_castps_si256(v4));
dst_traits::store8(dst[i + 5] + j + 4, _mm256_castps_si256(v5));
dst_traits::store8(dst[i + 6] + j + 2, _mm256_castps_si256(v6));
dst_traits::store8(dst[i + 7] + j + 0, _mm256_castps_si256(v7));
}
#undef XITER
#undef XARGS
_mm256_store_ps(state->err_left, err_left);
_mm256_store_ps(state->err_top_right, err_top_right);
_mm256_store_ps(state->err_top, err_top);
_mm256_store_ps(state->err_top_left, err_top_left);
}
template <PixelType SrcType, PixelType DstType>
void error_diffusion_avx2(const graph::ImageBuffer<const void> &src, const graph::ImageBuffer<void> &dst, unsigned i,
const float *error_top, float *error_cur, float scale, float offset, unsigned bits, unsigned width)
{
typedef error_diffusion_traits<SrcType> src_traits;
typedef error_diffusion_traits<DstType> dst_traits;
typedef typename src_traits::type src_type;
typedef typename dst_traits::type dst_type;
const graph::ImageBuffer<const src_type> &src_buf = graph::static_buffer_cast<const src_type>(src);
const graph::ImageBuffer<dst_type> &dst_buf = graph::static_buffer_cast<dst_type>(dst);
error_state state alignas(32) = {};
float error_tmp[7][24] = {};
// Prologue.
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 0], dst_buf[i + 0], error_top, error_tmp[0], scale, offset, bits, 14);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 1], dst_buf[i + 1], error_tmp[0], error_tmp[1], scale, offset, bits, 12);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 2], dst_buf[i + 2], error_tmp[1], error_tmp[2], scale, offset, bits, 10);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 3], dst_buf[i + 3], error_tmp[2], error_tmp[3], scale, offset, bits, 8);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 4], dst_buf[i + 4], error_tmp[3], error_tmp[4], scale, offset, bits, 6);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 5], dst_buf[i + 5], error_tmp[4], error_tmp[5], scale, offset, bits, 4);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 6], dst_buf[i + 6], error_tmp[5], error_tmp[6], scale, offset, bits, 2);
// Wavefront.
state.err_left[0] = error_tmp[0][13 + 1];
state.err_left[1] = error_tmp[1][11 + 1];
state.err_left[2] = error_tmp[2][9 + 1];
state.err_left[3] = error_tmp[3][7 + 1];
state.err_left[4] = error_tmp[4][5 + 1];
state.err_left[5] = error_tmp[5][3 + 1];
state.err_left[6] = error_tmp[6][1 + 1];
state.err_left[7] = 0.0f;
state.err_top_right[0] = error_top[15 + 1];
state.err_top_right[1] = error_tmp[0][13 + 1];
state.err_top_right[2] = error_tmp[1][11 + 1];
state.err_top_right[3] = error_tmp[2][9 + 1];
state.err_top_right[4] = error_tmp[3][7 + 1];
state.err_top_right[5] = error_tmp[4][5 + 1];
state.err_top_right[6] = error_tmp[5][3 + 1];
state.err_top_right[7] = error_tmp[6][1 + 1];
state.err_top[0] = error_top[14 + 1];
state.err_top[1] = error_tmp[0][12 + 1];
state.err_top[2] = error_tmp[1][10 + 1];
state.err_top[3] = error_tmp[2][8 + 1];
state.err_top[4] = error_tmp[3][6 + 1];
state.err_top[5] = error_tmp[4][4 + 1];
state.err_top[6] = error_tmp[5][2 + 1];
state.err_top[7] = error_tmp[6][0 + 1];
state.err_top_left[0] = error_top[13 + 1];
state.err_top_left[1] = error_tmp[0][11 + 1];
state.err_top_left[2] = error_tmp[1][9 + 1];
state.err_top_left[3] = error_tmp[2][7 + 1];
state.err_top_left[4] = error_tmp[3][5 + 1];
state.err_top_left[5] = error_tmp[4][3 + 1];
state.err_top_left[6] = error_tmp[5][1 + 1];
state.err_top_left[7] = 0.0f;
unsigned vec_count = floor_n(width - 14, 8);
error_diffusion_wf_avx2<SrcType, DstType>(src_buf, dst_buf, i, error_top, error_cur, &state, scale, offset, bits, vec_count);
error_tmp[0][13 + 1] = state.err_top_right[1];
error_tmp[0][12 + 1] = state.err_top[1];
error_tmp[0][11 + 1] = state.err_top_left[1];
error_tmp[1][11 + 1] = state.err_top_right[2];
error_tmp[1][10 + 1] = state.err_top[2];
error_tmp[1][9 + 1] = state.err_top_left[2];
error_tmp[2][9 + 1] = state.err_top_right[3];
error_tmp[2][8 + 1] = state.err_top[3];
error_tmp[2][7 + 1] = state.err_top_left[3];
error_tmp[3][7 + 1] = state.err_top_right[4];
error_tmp[3][6 + 1] = state.err_top[4];
error_tmp[3][5 + 1] = state.err_top_left[4];
error_tmp[4][5 + 1] = state.err_top_right[5];
error_tmp[4][4 + 1] = state.err_top[5];
error_tmp[4][3 + 1] = state.err_top_left[5];
error_tmp[5][3 + 1] = state.err_top_right[6];
error_tmp[5][2 + 1] = state.err_top[6];
error_tmp[5][1 + 1] = state.err_top_left[6];
error_tmp[6][1 + 1] = state.err_top_right[7];
error_tmp[6][0 + 1] = state.err_top[7];
error_tmp[6][0] = state.err_top_left[7];
// Epilogue.
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 0] + vec_count + 14, dst_buf[i + 0] + vec_count + 14, error_top + vec_count + 14, error_tmp[0] + 14,
scale, offset, bits, width - vec_count - 14);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 1] + vec_count + 12, dst_buf[i + 1] + vec_count + 12, error_tmp[0] + 12, error_tmp[1] + 12,
scale, offset, bits, width - vec_count - 12);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 2] + vec_count + 10, dst_buf[i + 2] + vec_count + 10, error_tmp[1] + 10, error_tmp[2] + 10,
scale, offset, bits, width - vec_count - 10);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 3] + vec_count + 8, dst_buf[i + 3] + vec_count + 8, error_tmp[2] + 8, error_tmp[3] + 8,
scale, offset, bits, width - vec_count - 8);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 4] + vec_count + 6, dst_buf[i + 4] + vec_count + 6, error_tmp[3] + 6, error_tmp[4] + 6,
scale, offset, bits, width - vec_count - 6);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 5] + vec_count + 4, dst_buf[i + 5] + vec_count + 4, error_tmp[4] + 4, error_tmp[5] + 4,
scale, offset, bits, width - vec_count - 4);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 6] + vec_count + 2, dst_buf[i + 6] + vec_count + 2, error_tmp[5] + 2, error_tmp[6] + 2,
scale, offset, bits, width - vec_count - 2);
error_diffusion_scalar<SrcType, DstType>(src_buf[i + 7] + vec_count + 0, dst_buf[i + 7] + vec_count + 0, error_tmp[6] + 0, error_cur + vec_count + 0,
scale, offset, bits, width - vec_count - 0);
}
decltype(&error_diffusion_avx2<PixelType::BYTE, PixelType::BYTE>) select_error_diffusion_avx2_func(PixelType pixel_in, PixelType pixel_out)
{
if (pixel_in == PixelType::BYTE && pixel_out == PixelType::BYTE)
return error_diffusion_avx2<PixelType::BYTE, PixelType::BYTE>;
else if (pixel_in == PixelType::BYTE && pixel_out == PixelType::WORD)
return error_diffusion_avx2<PixelType::BYTE, PixelType::WORD>;
else if (pixel_in == PixelType::WORD && pixel_out == PixelType::BYTE)
return error_diffusion_avx2<PixelType::WORD, PixelType::BYTE>;
else if (pixel_in == PixelType::WORD && pixel_out == PixelType::WORD)
return error_diffusion_avx2<PixelType::WORD, PixelType::WORD>;
else if (pixel_in == PixelType::HALF && pixel_out == PixelType::BYTE)
return error_diffusion_avx2<PixelType::HALF, PixelType::BYTE>;
else if (pixel_in == PixelType::HALF && pixel_out == PixelType::WORD)
return error_diffusion_avx2<PixelType::HALF, PixelType::WORD>;
else if (pixel_in == PixelType::FLOAT && pixel_out == PixelType::BYTE)
return error_diffusion_avx2<PixelType::FLOAT, PixelType::BYTE>;
else if (pixel_in == PixelType::FLOAT && pixel_out == PixelType::WORD)
return error_diffusion_avx2<PixelType::FLOAT, PixelType::WORD>;
else
error::throw_<error::InternalError>("no conversion between pixel types");
}
class ErrorDiffusionAVX2 final : public graph::ImageFilter {
decltype(&error_diffusion_scalar<PixelType::BYTE, PixelType::BYTE>) m_scalar_func;
decltype(&error_diffusion_avx2<PixelType::BYTE, PixelType::BYTE>) m_avx2_func;
PixelType m_pixel_in;
PixelType m_pixel_out;
float m_scale;
float m_offset;
unsigned m_depth;
unsigned m_width;
unsigned m_height;
void process_scalar(void *ctx, const void *src, void *dst, bool parity) const
{
float *ctx_a = reinterpret_cast<float *>(ctx);
float *ctx_b = reinterpret_cast<float *>(static_cast<unsigned char *>(ctx) + get_context_size() / 2);
float *error_top = parity ? ctx_a : ctx_b;
float *error_cur = parity ? ctx_b : ctx_a;
m_scalar_func(src, dst, error_top, error_cur, m_scale, m_offset, m_depth, m_width);
}
void process_vector(void *ctx, const graph::ImageBuffer<const void> &src, const graph::ImageBuffer<void> &dst, unsigned i) const
{
float *ctx_a = reinterpret_cast<float *>(ctx);
float *ctx_b = reinterpret_cast<float *>(static_cast<unsigned char *>(ctx) + get_context_size() / 2);
float *error_top = (i / 8) % 2 ? ctx_a : ctx_b;
float *error_cur = (i / 8) % 2 ? ctx_b : ctx_a;
m_avx2_func(src, dst, i, error_top, error_cur, m_scale, m_offset, m_depth, m_width);
}
public:
ErrorDiffusionAVX2(unsigned width, unsigned height, const PixelFormat &format_in, const PixelFormat &format_out) :
m_scalar_func{ select_error_diffusion_scalar_func(format_in.type, format_out.type) },
m_avx2_func{ select_error_diffusion_avx2_func(format_in.type, format_out.type) },
m_pixel_in{ format_in.type },
m_pixel_out{ format_out.type },
m_scale{},
m_offset{},
m_depth{ format_out.depth },
m_width{ width },
m_height{ height }
{
zassert_d(width <= pixel_max_width(format_in.type), "overflow");
zassert_d(width <= pixel_max_width(format_out.type), "overflow");
if (!pixel_is_integer(format_out.type))
error::throw_<error::InternalError>("cannot dither to non-integer format");
std::tie(m_scale, m_offset) = get_scale_offset(format_in, format_out);
}
filter_flags get_flags() const override
{
filter_flags flags{};
flags.has_state = true;
flags.same_row = true;
flags.in_place = pixel_size(m_pixel_in) == pixel_size(m_pixel_out);
flags.entire_row = true;
return flags;
}
image_attributes get_image_attributes() const override
{
return{ m_width, m_height, m_pixel_out };
}
pair_unsigned get_required_row_range(unsigned i) const override
{
unsigned last = std::min(i, UINT_MAX - 8) + 8;
return{ i, std::min(last, m_height) };
}
pair_unsigned get_required_col_range(unsigned, unsigned) const override
{
return{ 0, get_image_attributes().width };
}
unsigned get_simultaneous_lines() const override { return 8; }
unsigned get_max_buffering() const override { return 8; }
size_t get_context_size() const override
{
try {
checked_size_t size = (static_cast<checked_size_t>(m_width) + 2) * sizeof(float) * 2;
return size.get();
} catch (const std::overflow_error &) {
error::throw_<error::OutOfMemory>();
}
}
size_t get_tmp_size(unsigned, unsigned) const override { return 0; }
void init_context(void *ctx) const override
{
std::fill_n(static_cast<unsigned char *>(ctx), get_context_size(), 0);
}
void process(void *ctx, const graph::ImageBuffer<const void> *src, const graph::ImageBuffer<void> *dst, void *, unsigned i, unsigned, unsigned) const override
{
if (m_height - i < 8) {
bool parity = !!((i / 8) % 2);
for (unsigned ii = i; ii < m_height; ++ii) {
process_scalar(ctx, (*src)[ii], (*dst)[ii], parity);
parity = !parity;
}
} else {
process_vector(ctx, *src, *dst, i);
}
}
};
} // namespace
std::unique_ptr<graph::ImageFilter> create_error_diffusion_avx2(unsigned width, unsigned height, const PixelFormat &pixel_in, const PixelFormat &pixel_out)
{
if (width < 14)
return nullptr;
return ztd::make_unique<ErrorDiffusionAVX2>(width, height, pixel_in, pixel_out);
}
} // namespace depth
} // namespace zimg
#endif // ZIMG_X86
| [
"noreply@example.com"
] | noreply@example.com |
19e99652a3cd1d8ae20bee63fce71ccb92acba79 | 007121abc29fbc2650a085aca8caa32aab6f9b9f | /text-justification.cc | 413a49c43b8b903156f03be8140e716b2163fcc7 | [] | no_license | basecoded/leetcode | c2999d8e542160b6c8848d9c6ce7bd50fb345b01 | 04d3e8fc794db2016e1ee4d78e03cc768299584d | refs/heads/master | 2021-06-10T01:30:03.854888 | 2016-11-18T22:50:14 | 2016-11-18T22:50:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,787 | cc | class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> result;
const int n = words.size();
int begin = 0, len = 0; // 当前行的起点,当前长度
for (int i = 0; i < n; ++i) {
if (len + words[i].size() + (i - begin) > L) {
result.push_back(connect(words, begin, i - 1, len, L, false));
begin = i;
len = 0;
}
len += words[i].size();
}
// 最后一行不足L
result.push_back(connect(words, begin, n - 1, len, L, true));
return result;
}
/**
* @brief 将words[begin, end] 连成一行
* @param[in] words 单词列表
* @param[in] begin 开始
* @param[in] end 结束
* @param[in] len words[begin, end] 所有单词加起来的长度
* @param[in] L 题目规定的一行长度
* @param[in] is_last 是否是最后一行
* @return 对齐后的当前行
*/
string connect(vector<string> &words, int begin, int end,
int len, int L, bool is_last) {
string s;
int n = end - begin + 1;
for (int i = 0; i < n; ++i) {
s += words[begin + i];
addSpaces(s, i, n - 1, L - len, is_last);
}
if (s.size() < L) s.append(L - s.size(), ' ');
return s;
}
/**
* @brief 添加空格.
* @param[inout]s 一行
* @param[in] i 当前空隙的序号
* @param[in] n 空隙总数
* @param[in] L 总共需要添加的空额数
* @param[in] is_last 是否是最后一行
* @return 无
*/
void addSpaces(string &s, int i, int n, int L, bool is_last) {
if (n < 1 || i > n - 1) return;
int spaces = is_last ? 1 : (L / n + (i < (L % n) ? 1 : 0));
s.append(spaces, ' ');
}
};
| [
"yg54123@126.com"
] | yg54123@126.com |
e01db6d8f78c09d3e797f2a3f0b2522078fdb3f8 | f3fae9127712341f6d2c9e55fe90d68742f9aab4 | /1A2S/MP/Frogger/Pantalla.cpp | 4e8d41cf9ab6b408f455a992b47390b7fba481e8 | [] | no_license | corollari/UAB_projects | ae6114269f6da06efb62247266897a9406b63b40 | 02c0cde05653e0b7db8be32c32dbd43e48f65fe5 | refs/heads/master | 2020-03-18T15:05:11.338030 | 2018-05-25T18:07:39 | 2018-05-25T18:07:39 | 134,886,208 | 1 | 0 | null | 2018-05-25T17:31:03 | 2018-05-25T17:31:03 | null | ISO-8859-1 | C++ | false | false | 12,763 | cpp | #include "Pantalla.h"
/**
* Constructor de la Pantalla.
* Aquesta pantalla té una sola cova imaginària ja que no té parets.
*/
Pantalla::Pantalla()
{
// Carreguem els components grafics
m_graficTemps[0].crea("data/numeros/numero0000.png");
m_graficTemps[1].crea("data/numeros/numero0001.png");
m_graficTemps[2].crea("data/numeros/numero0002.png");
m_graficTemps[3].crea("data/numeros/numero0003.png");
m_graficTemps[4].crea("data/numeros/numero0004.png");
m_graficTemps[5].crea("data/numeros/numero0005.png");
m_graficTemps[6].crea("data/numeros/numero0006.png");
m_graficTemps[7].crea("data/numeros/numero0007.png");
m_graficTemps[8].crea("data/numeros/numero0008.png");
m_graficTemps[9].crea("data/numeros/numero0009.png");
m_velocitat[0] = 3;
m_velocitat[1] = 1;
m_velocitat[2] = 2;
m_velocitat[3] = 1;
m_velocitat[4] = 2;
m_graficVehicle[0].crea("data/GraficsGranota/Cotxe_3.png");
m_graficVehicle[1].crea("data/GraficsGranota/Camio.png");
m_graficVehicle[2].crea("data/GraficsGranota/Cotxe_2.png");
m_graficVehicle[3].crea("data/GraficsGranota/Tractor.png");
m_graficVehicle[4].crea("data/GraficsGranota/Cotxe_1.png");
m_graficGranota[ADALT_1].crea("data/GraficsGranota/Granota_Amunt_1.png");
m_graficGranota[ADALT_2].crea("data/GraficsGranota/Granota_Amunt_2.png");
m_graficGranota[ABAIX_1].crea("data/GraficsGranota/Granota_Avall_1.png");
m_graficGranota[ABAIX_2].crea("data/GraficsGranota/Granota_Avall_2.png");
m_graficGranota[ESQUERRA_1].crea("data/GraficsGranota/Granota_Esquerra_1.png");
m_graficGranota[ESQUERRA_2].crea("data/GraficsGranota/Granota_Esquerra_2.png");
m_graficGranota[DRETA_1].crea("data/GraficsGranota/Granota_Dreta_1.png");
m_graficGranota[DRETA_2].crea("data/GraficsGranota/Granota_Dreta_2.png");
m_graficCova.crea("data/GraficsGranota/Cova120.png");
m_graficFons.crea("data/GraficsGranota/Fons.png");
m_graficVides.crea("data/GraficsGranota/Granota_Amunt_1.png");
// Inicialitzem l'area total de la pantalla, així com l'espai pels carrils, el número de carrils i instanciem els objectes granota i cova.
m_areaTotal = Area(INICI_X, FI_X, INICI_Y, FI_Y);
m_iniciCarrilsY = INICI_Y + m_graficCova.getScaleY();
m_granota = Granota(m_graficGranota, (FI_X - INICI_X - m_graficGranota[ADALT_1].getScaleX()) / 2, FI_Y - m_graficGranota[ADALT_1].getScaleY());
int k = 0;
for (k = 0; k < MAX_COVA; k++)
{
m_cova[k] = Cova(m_graficCova, INICI_X + k * m_graficCova.getScaleX(), INICI_Y);
}
int i = 0;
for (i = 0; i < MAX_CARRIL; i++)
{
m_carril[i] = Carril(m_graficVehicle[i], m_iniciCarrilsY + i *((FI_Y - m_graficGranota[ADALT_1].getScaleY() - m_iniciCarrilsY) / MAX_CARRIL), m_velocitat[i], i+1);
m_carril[i].afegeix();
}
int j = 0;
for (j = 0; j < MAX_TEMPS_DIGIT; j++)
{
m_temps[j] = 0;
m_tempsVides[j] = 9;
m_puntuacio[j] = 0;
}
m_comptadorTemps = 0;
m_restadorTemps = 0;
m_vides = 0;
m_ObjecteExtra = ObjecteExtra(m_graficGranota[ABAIX_2]);
// Fixem l'hora actual com a llavor pel generador d'aleatoris.
std::srand(std::time(0));
}
/**
* Destructor per defecte
*/
Pantalla::~Pantalla()
{
m_graficFons.destrueix();
m_graficCova.destrueix();
m_graficVides.destrueix();
int j = 0;
for (j = 0; j < MAX_GRAFIC_GRANOTA; j++)
{
m_graficGranota[j].destrueix();
}
int i = 0;
for (i = 0; i < MAX_CARRIL; i++)
{
m_graficVehicle[i].destrueix();
m_carril[i].~Carril();
}
int k = 0;
for (k = 0; k < MAX_GRAFIC_TEMPS; k++)
{
m_graficTemps[k].destrueix();
}
}
/**
* Inicia la pantalla instanciant els vehicles i colocant la granota i els vehicles a la posició inicial.
* Col·loca les coves lliures i actualitza la velocitat del vehicles
* @param nivell Nivell de la pantalla.
*/
void Pantalla::inicia(int nivell)
{
m_velocitat[0] = nivell*3;
m_velocitat[1] = nivell;
m_velocitat[2] = nivell * 2;
m_velocitat[3] = nivell/2;
m_velocitat[4] = nivell*2;
// Eliminem tots els vehicles existents
// Afegim un vehicle
// movem aquest vehicle a la seva posicio inicial
int i = 0;
for (i = 0; i < MAX_CARRIL; i++)
{
m_carril[i].~Carril();
m_carril[i].afegeix();
m_carril[i].mouIniciCarril();
}
// iniciem totes les coves lliures, al iniciar el nivell
int j = 0;
for (j = 0; j < MAX_COVA; j++)
{
m_cova[j].setLliure();
}
m_ObjecteExtra.setPosicioX();
m_ObjecteExtra.setPosicioY();
}
/**
* Mou la granota a la posicio inicial seva
*/
void Pantalla::iniciaGranota()
{
m_granota.mouAPosicioInicial();
}
/**
* Actualitza l'atribut de vides que te el mateix valor que les vides del joc
* @param vides Vides actuals en el joc
*/
void Pantalla::setVides(int vides)
{
m_vides += vides;
}
/**
* Retorna les vides actuals del joc utilitzant la classe pantalla envers la variable de joc.cpp
* @return vides Vides actuals en el joc
*/
int Pantalla::getVides()
{
return m_vides;
}
/**
* Retorna el nivell actual del joc
* @return nivell del joc actual
*/
int Pantalla::getNivell()
{
return m_nivell;
}
/**
* Actualitza l'atribut de nivell dintre de la classe pantalla
* @param nivell del joc
*/
void Pantalla::setNivell(int nivell)
{
m_nivell = nivell;
}
/**
* en construccio
*/
int Pantalla::getPuntuacio()
{
int number = 0;
number += m_puntuacio[0] + 10 * m_puntuacio[1] + 100 * m_puntuacio[2];
return number;
}
/**
* en construccio
*/
void Pantalla::setPuntuacio(int novaPuntuacio)
{
int i = 0;
if (m_puntuacio[0] == 9 && m_puntuacio[1] == 9 && m_puntuacio[2] == 9)
{
}
else
{
if (novaPuntuacio < MAX_NUMBER_PUNTUACIO)
{
i = 1;
}
else
{
if (novaPuntuacio < MAX_NUMBER_PUNTUACIO_2)
{
i = 2;
}
else
{
i = 3;
}
}
}
switch (i)
{
case 1:
if (m_puntuacio[2] != 9)
{
m_puntuacio[2]++;
}
else
{
m_puntuacio[2] = 0;
if (m_puntuacio[1] != 9)
{
m_puntuacio[1]++;
}
else
{
m_puntuacio[1] = 0;
if (m_puntuacio[0] != 9)
{
m_puntuacio[0]++;
}
}
}
break;
case 2:
if (m_puntuacio[1] != 9)
{
m_puntuacio[1]++;
}
else
{
m_puntuacio[1] = 0;
if (m_puntuacio[0] != 9)
{
m_puntuacio[0]++;
}
}
break;
case 3:
if (m_puntuacio[0] != 9)
{
m_puntuacio[0]++;
}
break;
default:
break;
}
}
/**
* Suma el temps de la partida i el distribueix en 3 digits
*/
void Pantalla::sumaTemps()
{
if (m_comptadorTemps < MAX_COMPTADOR_TEMPS)
{
m_comptadorTemps++;
}
else
{
m_comptadorTemps = 0;
if (m_temps[0] == 9 && m_temps[1] == 9 && m_temps[2] == 9)
{
m_temps[0] = 0;
m_temps[1] = 0;
m_temps[2] = 0;
}
else
{
if (m_temps[0] == 9)
{
m_temps[0] = 0;
if (m_temps[1] == 9)
{
m_temps[1] = 0;
if (m_temps[2] == 9)
{
}
else
{
m_temps[2]++;
}
}
else
{
m_temps[1]++;
}
}
else
{
m_temps[0]++;
}
}
}
}
void Pantalla::restaTemps()
{
if (m_restadorTemps < MAX_RESTADOR_TEMPS)
{
m_restadorTemps += 1 * m_nivell;
}
else
{
m_restadorTemps = 0;
if (m_tempsVides[0] == 0 && m_tempsVides[1] == 0 && m_tempsVides[2] == 0)
{
setVides(-1);
m_tempsVides[0] = 9;
m_tempsVides[1] = 9;
m_tempsVides[2] = 9;
}
else
{
if (m_tempsVides[0] == 0)
{
m_tempsVides[0] = 9;
if (m_tempsVides[1] == 0)
{
m_tempsVides[1] = 9;
if (m_tempsVides[2] == 0)
{
}
else
{
m_tempsVides[2]--;
}
}
else
{
m_tempsVides[1]--;
}
}
else
{
m_tempsVides[0]--;
}
}
}
}
void Pantalla::resetTempsVides()
{
int i = 0;
for (i = 0; i < MAX_TEMPS_DIGIT; i++)
{
m_tempsVides[i] = 9;
}
}
/**
* Comprova si una àrea donada es troba dins la cova.
* L'area donada sera sempre la posicio ADALT_1 de la granota
* @return true si l'àrea es troba dins la cova i false si no s'hi troba.
*/
bool Pantalla::esGranotaDinsCova()
{
bool resultat = false;
int i = 0;
while (i < MAX_COVA && !resultat)
{
resultat = m_cova[i].esDins(m_granota.getAreaOcupada(ADALT_1));
i++;
}
if (resultat)
{
resetTempsVides();
setPuntuacio(10);
}
return resultat;
}
/**
* Comprova si una àrea donada es troba dins l'espai permés de moviment.
* L'espai permes de moviment es el terreny de joc o area total
* @param area Area a comprovar si es troba dins l'espai permés de moviment.
* @return true si l'àrea es troba dins l'espai permés de moviment i false si no és així.
*/
bool Pantalla::espaiPermes(Area area)
{
bool resultat = false;
if (m_areaTotal.inclou(area))
{
resultat = true;
}
return resultat;
}
/**
* Dibuixa tots els elements grafics a la posició on es troben.
*/
void Pantalla::dibuixa()
{
m_graficFons.dibuixa(INICI_X, INICI_Y);
int l = 0;
for (l = 0; l < MAX_COVA; l++)
{
m_cova[l].dibuixa();
if (m_cova[l].getOcupada())
{
m_graficGranota[ADALT_1].dibuixa(m_cova[l].getPosicioOcupadaX(), m_cova[l].getPosicioOcupadaY());
}
}
m_granota.dibuixa(m_granota.getPosicio());
int i = 0;
for (i = 0; i < MAX_CARRIL; i++)
{
m_carril[i].dibuixa();
}
int j = 0;
for (j = 0; j < getVides(); j++)
{
m_graficVides.dibuixa(INICI_X + j*m_graficVides.getScaleX(),FI_Y);
}
int k = 0;
for (k = 0; k < MAX_TEMPS_DIGIT; k++)
{
m_graficTemps[m_temps[k]].dibuixa(FI_X - k * m_graficTemps[0].getScaleX() - m_graficTemps[0].getScaleX(), FI_Y);
m_graficTemps[m_tempsVides[k]].dibuixa(FI_X - k * m_graficTemps[0].getScaleX() - m_graficTemps[0].getScaleX(), FI_Y + m_graficTemps[0].getScaleY());
m_graficTemps[m_puntuacio[k]].dibuixa(INICI_X + k * m_graficTemps[0].getScaleX(), FI_Y + m_graficVides.getScaleY());
}
if (m_ObjecteExtra.getVisibilitat())
{
m_ObjecteExtra.dibuixa();
}
}
/**
* Mou els vehicles dintre dels carrils.
* Afegeix de nous aleatoriament
* Si es treuen tots els cotxes i no n'hi ha mes a la cua, n'afegeix per a que no quedi el carril buit
*/
void Pantalla::mouVehicle()
{
int i = 0;
for (i = 0; i < MAX_CARRIL; i++)
{
if ( espaiPermes(m_carril[i].getAreaOc()) )
{
m_carril[i].mouVehicle();
if (m_carril[i].afegirCotxeRand(getNivell()))
{
m_carril[i].afegeix();
}
}
else
{
m_carril[i].treu();
if (m_carril[i].esBuida())
{
m_carril[i].afegeix();
}
}
}
}
/**
* Comprova si la granota ha mort.
* @return true si la granota és morta i false si és viva.
*/
bool Pantalla::haMortLaGranota()
{
bool mort = false;
int i = 0;
while (i < MAX_CARRIL && !mort)
{
if ( m_carril[i].chocGranota(m_granota.getAreaOcupada(m_granota.getPosicio())) )
{
mort = true;
}
else
{
i++;
}
}
return mort;
}
/**
* Mou la granota en la direcció donada.
* Comproba em el cas de les coves, que siguin accessibles
* @param direccio Direcció cap a on s'ha de moure la granota.
*/
void Pantalla::mouGranota(int direccio)
{
bool esAccesible = true;
bool solapaParet = true;
if (espaiPermes(m_granota.getAreaOcupada(ADALT_1)))
{
switch (direccio)
{
case AMUNT:
if (m_granota.getAreaOcupada(ADALT_1).getMinY() > m_areaTotal.getMinY())
{
if (m_granota.getMoviment())
{
int i = 0;
while (i < MAX_COVA && solapaParet && esAccesible)
{
if (!m_cova[i].esAccessible(m_granota.getAreaOcupada(m_granota.getPosicio())))
{
esAccesible = false;
}
if (!m_cova[i].noSolapaParet(m_granota.getAreaOcupada(m_granota.getPosicio())))
{
solapaParet = false;
}
i++;
}
if (esAccesible && solapaParet)
{
m_granota.mouAmunt();
}
}
}
break;
case AVALL:
if (m_granota.getAreaOcupada(ABAIX_1).getMaxY() < m_areaTotal.getMaxY())
{
if (m_granota.getMoviment())
{
m_granota.mouAvall();
}
}
break;
case DRETA:
if (m_granota.getAreaOcupada(DRETA_1).getMaxX() < m_areaTotal.getMaxX())
{
if (m_granota.getMoviment())
{
m_granota.mouDreta();
}
}
break;
case ESQUERRA:
if (m_granota.getAreaOcupada(ESQUERRA_1).getMinX() > m_areaTotal.getMinX())
{
if (m_granota.getMoviment())
{
m_granota.mouEsquerra();
}
}
break;
default:
break;
}
}
}
/**
* Funcio que ens indica si el nivell esta superat comprobant l'ocupacio de totes les coves
* @return true si el nivell esta superat, false de lo contrari
*/
bool Pantalla::nivellSuperat()
{
bool resultat = true;
int i = 0;
while (i < MAX_COVA && resultat)
{
if (m_cova[i].getOcupada())
{
i++;
}
else
{
resultat = false;
}
}
return resultat;
}
bool Pantalla::chocObjecte()
{
bool obtencio = false;
if (m_ObjecteExtra.obtencio(m_granota.getAreaOcupada(m_granota.getPosicio())))
{
obtencio = true;
setPuntuacio(m_ObjecteExtra.getPunts());
setVides(m_ObjecteExtra.getVides());
m_ObjecteExtra.setInivisible();
}
return obtencio;
} | [
"rguimerao@gmail.com"
] | rguimerao@gmail.com |
b3c5c6357a1fd0a9017f10c4ce674172f08ea717 | 6572a9a9865ba799fd37aa77c8c26f370d2c3594 | /Bubble_sort/main.cpp | 7e027357c6683f2c7d6b917f9132aa8c2f22d71e | [] | no_license | Bondok6/Algorithm | c00d0027d8b9fcfa583cce4bf11d70f276a948af | 3c6b19fc97d0cb079d9cd7c504589a0feba9e632 | refs/heads/master | 2020-12-26T05:46:32.172697 | 2020-03-13T01:19:36 | 2020-03-13T01:19:36 | 237,405,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | /*
Bubble Sort
order N^2
intelligence (if array already sorted don't need to continue)
Not Blind
in place
*/
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"enter Size >> "; cin>>n;
int a[n],m;
for(m=0;m<n;m++)
{
cout<<"enter element["<<m+1<<"] >> ";
cin>>a[m];
cout<<endl;
}
int i,j;
for(i=0;i<n-1;i++){
for(j=0;j<n-i-1;j++){
if(a[j+1]<a[j]){
int temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
int k;
for(k=0;k<n;k++){
cout<<"element["<<k+1<<"] >> "<<a[k]<<endl;
}
return 0;
}
| [
"kirolousbondok6@gmail.com"
] | kirolousbondok6@gmail.com |
a96d0113c810b245b68954502698c6351e1940cf | facd6716d65d351e74860bad6649c3bc05d32e1f | /ComputerAnimation_project_final ver/BaseLib/GL4U/GL_VBOVAO.h | b43f7f98e87ffbdd961ac356bb32092089472b92 | [] | no_license | jihye032/Univ_project | 611a9d0065f13b2d61aa7dceec38ebdbf75e689f | bd9b20191108cb38a55e300194ead8635ad5abc0 | refs/heads/master | 2023-06-12T07:28:32.755930 | 2021-07-06T09:43:41 | 2021-07-06T09:43:41 | 383,399,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,449 | h |
#pragma once
#include "BaseLib/CmlExt/CmlExt.h"
#include "BaseLib/Geometry/Mesh.h"
#include "GL/glew.h"
#include <set>
#include <map>
class PmHuman;
namespace mg
{
class GL_RenderableObj;
class GL_Material;
class GL_VBO
{
public:
GL_VBO();
GL_VBO(GLenum data_type, int vec_dim, int num_of_vectors, void *data, GLenum target=GL_ARRAY_BUFFER, GLenum usage=GL_STATIC_DRAW);
~GL_VBO();
// vec_dim is 1, 2,3 or 4.
// total buffer size (*data) must be sizeof(data_type)*vec_dim*num_of_vectors bytes.
void GenAndBind(GLenum data_type, int vec_dim, int num_of_vectors, void *data, GLenum target=GL_ARRAY_BUFFER, GLenum usage=GL_STATIC_DRAW);
void Update(void *data);
void Bind();
void Delete();
GLuint vbo_id() const { return vbo_id_; }
GLenum data_type() const { return data_type_; }
int vec_dim() const { return vec_dim_; }
int num_of_vectors() const { return num_of_vectors_; }
GLenum target() const { return target_; }
GLenum usage() const { return usage_; }
protected:
GLuint vbo_id_;
GLenum data_type_;
int vec_dim_;
int num_of_vectors_;
GLenum target_;
GLenum usage_;
};
class GL_VBOGroup
{
friend class GL_ResourceManager;
private:
GL_VBOGroup();
GL_VBOGroup(int num_vertices);
public:
enum { VERTEX_VBO=0, NORMAL_VBO, TEX_COORD_VBO, COLOR_VBO, BONE_ID_VBO, BONE_WEIGHT_VBO };
virtual ~GL_VBOGroup();
void Init(int num_vertices);
virtual void Delete();
///////////////////
// VBO
/*
content_type: VERTEX_VBO, NORMAL_VBO, UV_VBO, or COLOR_VBO
data_type: GL_FLOAT, GL_INT ...
vec_dim: 1, 2, 3 or 4
data: It' byte size is "sizeof(data_type)*vec_dim*num_vertices()".
*/
virtual void SetVBO(int content_type, GLenum data_type, int vec_dim, void *data);
virtual GL_VBO* GetVBO(int content_type) const { return vbos_[content_type]; }
virtual void UpdateVBO(int content_type, GLenum data_type, int vec_dim, void *data);
/*
It create and set a GL_ELEMENT_ARRAY_BUFFER.
*/
virtual void SetElementIndices(int num_indices, unsigned int *data);
virtual void SetByMesh(const mg::Mesh &mesh);
/*
virtual void SetByAssimp(const std::string filename);
virtual void SetByAssimp(const std::string filename, std::vector< std::pair<std::string, cml::matrix44d_c> > &out_bone_name_and_mat);
virtual void SetByAssimp(const std::string filename, const std::map<std::string, int> &in_bonename_to_pmjoint);
virtual void SetByAssimp(const std::string filename, const std::map<std::string, int> &in_bonename_to_pmjoint, std::vector< std::pair<std::string, cml::matrix44d_c> > &out_bone_name_and_mat);
*/
// Old style
void BeginVertex();
void glNormal(cml::vector3f n);
void glUV(cml::vector2f uv);
void glColor(cml::vector4f c);
void glVertex(cml::vector3f v);
void EndVertex();
void BeginUpdate();
void glUpdateNormal(cml::vector3f n);
void glUpdateUV(cml::vector2f uv);
void glUpdateColor(cml::vector4f c);
void glUpdateVertex(cml::vector3f v);
void EndUpdate();
/*
drawing_mode is GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_STRIP...
*/
inline void drawing_mode(GLenum drawing_mode) { drawing_mode_ = drawing_mode; }
inline GLuint ibo_id() const { return ibo_id_; }
inline int num_vertices() const { return num_vertices_; }
inline int num_indices() const { return num_indices_; }
inline GLenum drawing_mode() const { return drawing_mode_; }
virtual void BindVBO();
protected:
GLuint ibo_id_; // GL_ELEMENT_ARRAY_BUFFER (Triangle indices)
std::vector<GL_VBO*> vbos_;
int num_vertices_;
int num_indices_;
GLenum drawing_mode_;
};
class GL_VAO
{
friend class GL_ResourceManager;
private:
GL_VAO(GL_VBOGroup* vbo_group);
public:
virtual ~GL_VAO();
void Bind();
void Delete();
GLuint vao_id() const { return vao_id_; }
virtual void Draw() const;
GL_VBOGroup* vbo_group() const { return vbo_group_; }
protected:
virtual void GenAndBind();
protected:
GLuint vao_id_;
GL_VBOGroup *vbo_group_;
std::set<int> using_bone_matrix_ids_;
std::map<int, cml::matrix44d_c> bone_offset_matrices_;
std::map<int, cml::matrix44d_c> bone_matrices_;
};
GL_RenderableObj* CreateRenderableObjByUsingAssimp(const std::string filename,
const std::string renderable_obj_name,
const std::map<std::string, int> &in_bonename_to_pmjoint,
std::vector< std::pair<std::string, cml::matrix44d_c> > &out_bone_name_and_mat);
GL_VBOGroup* CreatePmHumanVBO(PmHuman *p, double size = 2.0);
//GL_RenderableObj* CreatePmHumanRObj(PmHuman *p, double size=2.0);
}; | [
"jihae032@naver.com"
] | jihae032@naver.com |
6b72935f2f271a137727e9e6b923e7dec3c40fca | 6721eca45d0315b50b9774800cf2a430b4d3dcf5 | /d05/ex02/Bureaucrat.cpp | b86b46197a6d64539074ca1d1a82930aaedbbf7d | [] | no_license | skidne/piscine_cpp | 2ac6a98327b6f6dbc6c0f5059d81a2947e9c7d90 | 64d6ab0944dcde51bbc9eca5eb18aff16652cd68 | refs/heads/master | 2021-07-03T16:22:13.864066 | 2017-09-26T17:35:04 | 2017-09-26T17:35:04 | 104,917,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,313 | cpp | //
// Created by Alen BADRAJAN on 7/26/17.
//
#include "Form.hpp"
Bureaucrat::Bureaucrat() : _name("Bureaucrat")
{
set_grade(150);
}
Bureaucrat::Bureaucrat(STR const n, int const gr) : _name(n)
{
set_grade(gr);
}
Bureaucrat::Bureaucrat(Bureaucrat const &b) : _name(b.get_name())
{
Bureaucrat::set_grade(b.get_grade());
}
Bureaucrat &Bureaucrat::operator=(Bureaucrat &b)
{
Bureaucrat::set_grade(b.get_grade());
return *this;
}
Bureaucrat::~Bureaucrat()
{
}
const std::string &Bureaucrat::get_name() const
{
return _name;
}
int Bureaucrat::get_grade() const
{
return _grade;
}
void Bureaucrat::set_grade(int _grade)
{
Bureaucrat::_grade = _grade;
}
void Bureaucrat::incrementGrade()
{
GradeTooHighException();
}
void Bureaucrat::decrementGrade()
{
GradeTooLowException();
}
void Bureaucrat::GradeTooHighException()
{
try
{
/* do some stuff with bureaucrats */
if (Bureaucrat::get_grade() - 1 < 1)
throw std::exception();
else
set_grade(get_grade() - 1);
}
catch (std::exception & e)
{
OUT << "Grade is too high!\n";
set_grade(1);
}
}
void Bureaucrat::GradeTooLowException()
{
try
{
/* do some stuff with bureaucrats */
if (Bureaucrat::get_grade() + 1 > 150)
throw std::exception();
else
set_grade(get_grade() + 1);
}
catch (std::exception & e)
{
OUT << "Grade is too low!\n";
set_grade(150);
}
}
void Bureaucrat::signForm(Form *f)
{
if (f->beSigned(*this))
OUT << get_name() << " signs " << f->get_name() << ENDL;
else
OUT << get_name() << "cannot sign " << f->get_name() << " because grade is too low\n";
}
void Bureaucrat::executeForm(Form const &form)
{
try
{
if (!form.is_isSigned() || this->get_grade() < form.get_grade_execute())
throw std::exception();
else
OUT << this->get_name() << " executes " << form.get_name() <<"\n";
}
catch (std::exception & e)
{
OUT << "OOps, something is wrong my little Bureaucrat!\n";
}
}
std::ostream &operator<<(std::ostream &o, Bureaucrat const &r)
{
o << r.get_name() << ", bureaucrat grade " << r.get_grade() << ".\n";
return o;
}
| [
"skdne@yahoo.com"
] | skdne@yahoo.com |
ec19b7220bab427131f746ce9815e200bfd4751b | df6a7072020c0cce62a2362761f01c08f1375be7 | /include/oglplus/draw_buffer_index.hpp | 52a2c175604c47ea03f39fc68a8210c80b0f778e | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 816 | hpp | /**
* @file oglplus/draw_buffer_index.hpp
* @brief DrawBufferIndex object
*
* @author Matus Chochlik
*
* Copyright 2010-2015 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_DRAW_BUFFER_INDEX_1405030825_HPP
#define OGLPLUS_DRAW_BUFFER_INDEX_1405030825_HPP
#include <oglplus/limited_value.hpp>
namespace oglplus {
#if OGLPLUS_DOCUMENTATION_ONLY
/// Type for the draw buffer index (implementation-dependent limited) number
class DrawBufferIndex
: public LimitedCount
{
public:
DrawBufferIndex(GLuint count);
};
#else
OGLPLUS_DECLARE_LIMITED_COUNT_TYPE(
DrawBufferIndex,
MAX_DRAW_BUFFERS
)
#endif
} // namespace oglplus
#endif // include guard
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
ea1fb3a61bff0f09deb4af72e66cbb2ad72fbaf8 | 142983463f9b638a119b6657e9c8df60ecbef170 | /ACM/usaco/Chapter-3/3.1/contact.cpp | 2df50690c3e930b192e05c677b60adb17617f15a | [] | no_license | djsona12/ProgramsInUndergrad | 300264e0701dbc8a53bb97a0892284f57477402c | bbf1ee563660f55ca4bdbf4b7ab85604ab96149e | refs/heads/master | 2021-06-28T15:34:31.030557 | 2017-08-28T04:48:27 | 2017-08-28T04:48:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | /*
PROB : contact
USER : weng_xo2
LANG : C++
*/
#include <cctype>
#include <cstdio>
#include <cstring>
#include <utility>
#include <vector>
const int MaxN = 200010;
int A, B, N, hsh[13][1 << 12], len;
char s[MaxN];
std :: vector< std :: pair<int, int> > cnt[MaxN];
int main(){
freopen("contact.in", "r", stdin);
freopen("contact.out", "w", stdout);
scanf("%d%d%d", &A, &B, &N);
for(char *hd = s;(*hd = getchar()) != -1;isdigit(*hd) ? ++ hd : hd);
s[strlen(s) - 1] = 0;
for(int i = A;i <= B;++ i){
for(int j = 0, cur = 0;s[j];++ j){
cur = cur << 1 | s[j] - '0';
if(j + 1 >= i)
++ hsh[i][cur & (1 << i) - 1];
}
for(int j = 0;j < 1 << i;++ j)
if(hsh[i][j])
cnt[hsh[i][j]].push_back(std :: make_pair(i, j));
}
for(int i = MaxN - 1;i >= 0 && N;-- i)
if(cnt[i].size()){
N --;
printf("%d\n", i);
for(unsigned j = 0;j < cnt[i].size();++ j){
for(int k = cnt[i][j].first - 1;k >= 0;-- k)
putchar('0' + (cnt[i][j].second >> k & 1));
printf(j % 6 == 5 || j + 1 == cnt[i].size() ? "\n" : " ");
}
}
return 0;
}
| [
"“wereFluke@gmail.com”"
] | “wereFluke@gmail.com” |
72601f7f11c2d2807c7fe522ad81e97adf8a65a3 | 2277375bd4a554d23da334dddd091a36138f5cae | /ThirdParty/Havok/Source/Common/Base/Memory/Allocator/LargeBlock/hkLargeBlockAllocator.h | ed78da30c81f806d660dbdc643b340b4bd3a8558 | [] | no_license | kevinmore/Project-Nebula | 9a0553ccf8bdc1b4bb5e2588fc94516d9e3532bc | f6d284d4879ae1ea1bd30c5775ef8733cfafa71d | refs/heads/master | 2022-10-22T03:55:42.596618 | 2020-06-19T09:07:07 | 2020-06-19T09:07:07 | 25,372,691 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 22,067 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_LARGE_BLOCK_ALLOCATOR_H
#define HK_LARGE_BLOCK_ALLOCATOR_H
class hkMemorySnapshot;
/// This is a large memory block allocator, which is designed to handle allocations 256 bytes or larger. Smaller
/// allocations will be serviced but will internally degenerate to a 256 byte block. Thus this allocator is not
/// best used for small high performance chunks of memory. In that situation a freelist or pool memory style
/// allocator is more suitable.
///
/// What this allocator does allow for is good usage of varying sized chunks of memory. A 128k chunk of memory or a 2.7k
/// chunk of memory both have the same small overhead.
///
/// The allocator is designed to be fast and efficient. When a block is requested a search is performed down a tree
/// of available blocks to find the one most suitable. Most of the complexity of the algorithm comes from this inplace
/// tree traversal.
///
/// The allocator is designed to have good cache usage
///
/// Some notes on the algorithm:
///
/// - Adjacent free chunks are always merged - thus the chunks adjacent to a free chunk must be in use.
/// - Each chunk consists of a header, which records the size of this block, and therefore implicitly the start of the next
/// block.
/// - Each header records: If this chunk is in use, if the previous chunk is in use, if the previous
/// chunk is NOT in use, how large the previous chunk is.
/// - When a chunk is not in use its header is 'extended' into the payload - such that the block can be a tree member
/// - There is the concept of the 'top block' for allocations in a contiguous chunk of memory, this is where an
/// allocation would take place when all else fails. In this algorithm the top block is special
/// because its contents may not be correctly constructed
/// - Allocations of actual memory go through the hkMemoryBlockServer. Multiple non contiguous
/// allocations are possible :) When this happens internally blocks are set up so the chunks
/// of memory between the blocks owned by this allocator appear as 'inuse', when in reality they
/// don't belong to this allocator.
/// - Allocations from the hkMemoryBlockServer are held in hkMemPages
class hkLargeBlockAllocator : public hkMemoryAllocator, public hkMemoryAllocator::ExtendedInterface
{
//+hk.MemoryTracker(ignore=True)
public:
HK_DECLARE_PLACEMENT_ALLOCATOR();
typedef unsigned int BinIndex;
typedef unsigned int BinMap;
/// Has the same amount of bits as a hk_size_t but is signed.
typedef int SignedSizeT;
// Internal
struct MemChunk
{
//+hk.MemoryTracker(ignore=True)
static const hk_size_t PINUSE_BIT = 1;
static const hk_size_t CINUSE_BIT = 2;
static const hk_size_t INUSE_BITS = 3;
static const hk_size_t ALIGN = HK_REAL_ALIGNMENT;
static const hk_size_t ALIGN_MASK = ALIGN-1;
/// The bytes from the MemChunk to the payload inside.
/// Would be better to do sizeof(MemChunk), but I can't do that here - so I do sizeof(hk_size_t)*2
static const hk_size_t PAYLOAD_OFFSET = (sizeof(hk_size_t)*2 + ALIGN_MASK)&~ALIGN_MASK;
/// Returns true if the previous block is in use
HK_FORCE_INLINE bool isPinuse() const { return (head&PINUSE_BIT)!=0; }
/// Returns true if this block is in use
HK_FORCE_INLINE bool isInuse() const { return (head&CINUSE_BIT)!=0; }
/// The chunk size is the total size (including the hkMallocChunk data)
HK_FORCE_INLINE hk_size_t getChunkSize() const { return (head&~INUSE_BITS); }
/// Clear the previous in use flag
HK_FORCE_INLINE void clearPinuse() { head &= ~PINUSE_BIT; }
/// Clear the in use flag
HK_FORCE_INLINE void clearInuse() { head &= ~CINUSE_BIT; }
/// Returns the next chunks previous in use
HK_FORCE_INLINE bool isNextPinuse() { return nextChunk()->isPinuse(); }
/// Get the address of the next chunk
HK_FORCE_INLINE MemChunk* nextChunk() { return (MemChunk*)(((char*)this) + getChunkSize()); }
/// Get the address of the previous chunk
HK_FORCE_INLINE MemChunk* previousChunk() { return (MemChunk*)(((char*)this) - prevFoot); }
/// Return memory as chunk x bytes after the chunk
HK_FORCE_INLINE MemChunk* chunkPlusOffset(hk_size_t s) { return (MemChunk*)(((char*)this)+s); }
/// Return memory as chunk x bytes before the chunk
HK_FORCE_INLINE MemChunk* chunkMinusOffset(hk_size_t s) { return (MemChunk*)(((char*)this)-s); }
/// Return the address of the contained data
HK_FORCE_INLINE void* getPayload() { return (void*)(((char*)this) + PAYLOAD_OFFSET); }
/// Get the size of the payload
HK_FORCE_INLINE hk_size_t getPayloadSize() { return getChunkSize() - PAYLOAD_OFFSET; }
/// Turn an address into a memory block
HK_FORCE_INLINE static MemChunk* toChunk(void* in) { return (MemChunk*)(((char*)in) - PAYLOAD_OFFSET); }
/// Set cinuse and pinuse of this chunk and pinuse of next chunk
HK_FORCE_INLINE void setInuseAndPinuse(hk_size_t s)
{
head = (s|PINUSE_BIT|CINUSE_BIT);
MemChunk* next = chunkPlusOffset(s);
next->head |= PINUSE_BIT;
}
/// Set inuse
HK_FORCE_INLINE void setInuse(hk_size_t s)
{
head = (head & PINUSE_BIT)|s|CINUSE_BIT;
MemChunk* next = chunkPlusOffset(s);
next->head |= PINUSE_BIT;
}
/// Set ths size, inuse and pinuse of the chunk
HK_FORCE_INLINE void setSizeAndPinuseOfInuseChunk(hk_size_t s)
{
head = (s|PINUSE_BIT|CINUSE_BIT);
}
/// Get size at footer
HK_FORCE_INLINE hk_size_t getFoot(hk_size_t s) { return ((MemChunk*)(((char*)this)+s))->prevFoot; }
/// Set the footer size
HK_FORCE_INLINE void setFoot(hk_size_t s) { ((MemChunk*)(((char*)this) + s))->prevFoot = s; }
/// Set size, pinuse bit, and foot
HK_FORCE_INLINE void setSizeAndPinuseOfFreeChunk(hk_size_t s)
{
head = (s|PINUSE_BIT);
setFoot(s);
}
/// Set size, pinuse bit, foot, and clear next pinuse
HK_FORCE_INLINE void setFreeWithPinuse(hk_size_t s,MemChunk* n)
{
n->clearPinuse();
setSizeAndPinuseOfFreeChunk(s);
}
/// Returns true if a pointer is aligned appropriately
static bool isAligned(const void* ptr){ return (((hk_size_t)(ptr))&ALIGN_MASK)==0; }
// Members
/// Size of previous chunk including header etc (if free).
hk_size_t prevFoot;
/// Size and inuse bits.
hk_size_t head;
};
// Assumes the fields are placed after MemChunk
struct FreeMemChunk : public MemChunk
{
//+hk.MemoryTracker(ignore=True)
// double links -- used only if free.
FreeMemChunk* next;
FreeMemChunk* prev;
};
struct MemTreeChunk : public FreeMemChunk
{
//+hk.MemoryTracker(ignore=True)
MemTreeChunk* child[2];
MemTreeChunk* parent;
BinIndex index;
/// The leftmost child
MemTreeChunk* leftMostChild() const { return child[0]?child[0]:child[1]; }
};
// Internal
struct MemPage
{
//+hk.MemoryTracker(ignore=True)
/// The previous memory block
MemPage* m_prev;
/// The next memory block
MemPage* m_next;
/// Stores the amount of allocations in this page
int m_numAllocs;
/// The total size as passed back from the interface
int m_size;
/// The payload start
char* m_start;
/// The payload end
char* m_end;
/// The first chunk in this page
MemChunk* getFirstChunk() const { return (MemChunk*)m_start; }
/// The last chunk in this page
MemChunk* getFooter() const { return (MemChunk*)(m_end - MemChunk::PAYLOAD_OFFSET); }
/// If there is nothing in the page this is the size of a chunk from the start of available space
/// up to the footer. Its the largest free block that can be stored in a page.
hk_size_t getMaxChunkSize() const { return (m_end - m_start) - MemChunk::PAYLOAD_OFFSET; }
// The contents size
hk_size_t getContentsSize() const { return hk_size_t(m_end - m_start); }
/// Gets the start of the contents
char* getStart() const { return m_start; }
/// Gets a byte past the end
char* getEnd() { return m_end; }
};
// Internal
struct FixedMemoryBlockServer : public hkMemoryAllocator
{
//+hk.MemoryTracker(ignore=True)
HK_DECLARE_PLACEMENT_ALLOCATOR();
/// Give it a block of memory you want it to use. Will automatically align in ctor - but that means
/// m_start may not be the start you passed in if it wasn't aligned.
FixedMemoryBlockServer(void* start, int size);
virtual void* bufAlloc(int& nbytes) HK_OVERRIDE;
virtual void bufFree(void* p, int nbytes) HK_OVERRIDE;
virtual void* blockAlloc(int nbytes) HK_OVERRIDE { HK_ASSERT(0x438afc1b, 0); return HK_NULL; }
virtual void blockFree(void* p, int nbytes) HK_OVERRIDE { HK_ASSERT(0x438afc1b, 0); }
virtual int getAllocatedSize(const void* obj, int nbytes) const HK_OVERRIDE { return nbytes; }
virtual void getMemoryStatistics(MemoryStatistics& s) const HK_OVERRIDE;
inline bool inUse() { return m_start != HK_NULL; }
bool resize(void* data, int oldSize, hk_size_t newSize, hk_size_t& sizeOut);
/// Is 16 byte aligned
char* m_start;
/// The end address in bytes
char* m_end;
/// Where the limit is currently set to
char* m_limit;
/// The current break point (the boundary between allocated and unallocated)
char* m_break;
};
/// Listener for limited memory situations.
class LimitedMemoryListener
{
//+hk.MemoryTracker(ignore=True)
public:
HK_DECLARE_PLACEMENT_ALLOCATOR();
virtual ~LimitedMemoryListener(){}
/// Called when a request is denied. An implementation can free up memory, and on
/// returning from this call the allocator will try and allocate again.
virtual void cannotAllocate(hk_size_t size) =0;
/// This is called when the allocator has given up allocating. Generally this will be called after
/// a call to cannotAllocate, although that is not a requirement of an implementation.
virtual void allocationFailure(hk_size_t size) = 0;
};
enum AllocType { CRITICAL_ALLOC,NORMAL_ALLOC };
/// Used for finding all of the used blocks
typedef void (HK_CALL *MemBlockCallback)(void* start, hk_size_t blockSize,void* param);
/// Ctor
hkLargeBlockAllocator(hkMemoryAllocator* server);
/// Ctor
hkLargeBlockAllocator(void* block, int size);
void init(hkMemoryAllocator* server) { m_server = server; }
/// Dtor
~hkLargeBlockAllocator();
// hkMemoryAllocator interface
virtual void* blockAlloc( int numBytes ) HK_OVERRIDE;
virtual void blockFree( void* p, int numBytes ) HK_OVERRIDE;
virtual void getMemoryStatistics( MemoryStatistics& u ) const HK_OVERRIDE;
virtual int getAllocatedSize(const void* obj, int nbytes) const HK_OVERRIDE;
/// hkMemoryAllocator::ExtendedInterface interface
virtual void garbageCollect();
virtual void incrementalGarbageCollect(int numBlocks);
virtual hkResult setMemorySoftLimit(hk_size_t maxMemory);
virtual hk_size_t getMemorySoftLimit() const;
virtual bool canAllocTotal( int numBytes );
virtual hkResult walkMemory(MemoryWalkCallback callback, void* param);
virtual int addToSnapshot( hkMemorySnapshot& snap, int /*hkMemorySnapshot::ProviderId*/ parentId );
virtual hkMemoryAllocator::ExtendedInterface* getExtendedInterface() { return this; }
virtual hk_size_t getApproxTotalAllocated() const;
virtual void setScrubValues(hkUint32 allocValue, hkUint32 freeValue);
/// Try to find the given ptr.
hkBool isValidAlloc(void* in);
/// Frees all allocations
void freeAll();
/// Called for all of the allocated chunks of memory
void forAllAllocs(MemBlockCallback callback,void* param);
///// Resizes a block - is guaranteed to succeed if the size is less than or equal to the size returned by getSize.
///// Does not allow to make a block bigger than what was returned from getAllocSize
///// disabled - has a nasty bug
//void resizeAlloc(void* p,hk_size_t newSize);
///// Determines if mem points to a valid block
//hkBool checkAlloc(void* mem);
/// Runs thru all the allocations making sure they appear valid. Will return false if any seems invalid
hkBool checkAllocations(void** allocs,int size);
/// Set the limited memory listener
void setLimitedMemoryListener(LimitedMemoryListener* listener) { m_limitedListener = listener; }
/// Get the limited memory listener
LimitedMemoryListener* getLimitedMemoryListener() const { return m_limitedListener; }
/// Works out what the largest block available is
hk_size_t findLargestBlockSize() const;
/// Get the top block size
hk_size_t getTopBlockSize() const { return m_topsize; }
/// Returns the total amount of memory returned to the application
hk_size_t getSumAllocatedSize() const { return m_sumAllocatedSize; }
/// Same as getSumAllocatedSize() plus internal overhead
hk_size_t getSumAllocatedWithOverhead() const { return m_sumAllocatedWithMgrOverhead; }
/// Returns the total amount of memory allocated in bytes: Should be getSumAllocatedWithOverhead plus free memory with its overhead
hk_size_t calculateMemoryUsedByThisAllocator() const;
class Iterator
{
//+hk.MemoryTracker(ignore=True)
public:
Iterator(MemChunk* chunk, MemPage* page, MemChunk* end):
m_chunk(chunk),
m_page(page),
m_end(end)
{}
Iterator():
m_chunk(HK_NULL) ///< Make invalid
{}
hkBool isValid() const { return m_chunk != HK_NULL; }
hk_size_t getSize() const { return m_chunk->getChunkSize(); }
void* getAddress() const { return m_chunk->getPayload(); }
hkBool isInuse() const { return m_chunk->isInuse(); }
MemChunk* m_chunk;
MemPage* m_page;
MemChunk* m_end;
};
/// Gets an iterator.
/// Doing any allocations/frees will cause undefined behaviour.
/// Blocks will be returned in order from lowest to highest in memory
Iterator getIterator();
/// Moves the iterator to the next block of memory. Returns false if the iterator is now invalid
hkBool nextBlock(Iterator& iter);
/// Get the block server
hkMemoryAllocator* getBlockServer() const { return m_server; }
/// Ctor
hkLargeBlockAllocator();
#ifdef HK_DEBUG
static void HK_CALL selfTest();
static void HK_CALL allocatorTest(hkLargeBlockAllocator& allocator,int testSize);
#endif
protected:
/// Number of tree bins
static const unsigned int NTREEBINS = (32U);
/// The shift used to get tree bins
static const unsigned int TREEBIN_SHIFT = (8U);
/// The minimum large block size
static const hk_size_t MIN_LARGE_SIZE = hk_size_t(1)<< TREEBIN_SHIFT;
/// Amount of bits in a size_t
static const hk_size_t SIZE_T_BITSIZE = (sizeof(hk_size_t) << 3);
/// Returns true if an allocated block looks correctly formed
bool _checkUsedAlloc(const void* mem) const;
/// If called after a successful free should return true
hkBool _checkFreeChunk( MemChunk* p);
/// The amount of memory used is cached - and returned by getTotalMemoryUsed. This method works out by traversing
/// all the blocks how much memory is used
hk_size_t _calculateUsed() const;
hk_size_t _findLargestTreeBlockSize(MemTreeChunk* t,hk_size_t largest) const;
void _markTreeMap(BinIndex i) { m_treemap |= (1<<i); }
void _clearTreeMap(BinIndex i) { m_treemap &= ~(1<<i); }
bool _isTreeMapMarked(BinIndex i) const { return (m_treemap&(1<<i))!=0; }
void _insertLargeChunk( MemTreeChunk* x, hk_size_t s);
void _unlinkLargeChunk( MemTreeChunk* x);
void* _allocLarge( hk_size_t nb);
void* _allocFromTop(hk_size_t bytes);
void _makeTopValid() const;
void* _alloc(hk_size_t nb);
void _init();
// How the hades does this work?
static BinIndex _computeTreeIndex(hk_size_t s)
{
hk_size_t x = s >> TREEBIN_SHIFT;
if (x == 0) { return 0; }
if (x > 0xFFFF) { return NTREEBINS-1; }
unsigned int y = (unsigned int)x;
unsigned int n = ((y - 0x100) >> 16) & 8;
unsigned int k = (((y <<= n) - 0x1000) >> 16) & 4;
n += k;
n += k = (((y <<= k) - 0x4000) >> 16) & 2;
k = 14 - n + ((y <<= k) >> 15);
return (BinIndex)((k << 1) + ((s >> (k + (TREEBIN_SHIFT-1)) & 1)));
}
static BinIndex _bitToIndex(unsigned int x)
{
unsigned int y = x - 1;
unsigned int k = y >> (16-4) & 16;
unsigned int n = k; y >>= k;
n += k = y >> (8-3) & 8; y >>= k;
n += k = y >> (4-2) & 4; y >>= k;
n += k = y >> (2-1) & 2; y >>= k;
n += k = y >> (1-0) & 1; y >>= k;
return n+y;
}
/// pad request bytes into a usable size
HK_FORCE_INLINE static hk_size_t _padRequest(hk_size_t req)
{
return (req + MemChunk::PAYLOAD_OFFSET + MemChunk::ALIGN_MASK)&~MemChunk::ALIGN_MASK;
}
/// Bit representing maximum resolved size in a treebin at i
static int _bitForTreeIndex(int i)
{
return (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2);
}
/// Shift placing maximum resolved bit in a treebin at i as sign bit
static int _leftShiftForTreeIndex(int i)
{
return ((i == NTREEBINS-1)? 0 : ((SIZE_T_BITSIZE-hk_size_t(1)) - ((i >> 1) + TREEBIN_SHIFT - 2)));
}
/// The size of the smallest chunk held in bin with index i
static hk_size_t _minSizeForTreeIndex(int i)
{
return ((hk_size_t(1) << (((i) >> 1) + TREEBIN_SHIFT)) | (((hk_size_t)((i) & hk_size_t(1))) << (((i) >> 1) + TREEBIN_SHIFT - 1)));
}
/// Tries to resize the page allocated from a SingleBlockServer. If successful will fix up the top block etc
hkBool _resizeSingleBlockServerPage(hk_size_t newSize);
/// Returns true if n is greater than p
template <typename S,typename T>
static bool _okNext(const S* p,const T* n) { return ((const char*)(p) < (const char*)(n)); }
/// Does noddy checks to see if an address is possibly correct
HK_FORCE_INLINE bool _isOkAddress(const void *a)const { return ((char*)(a) >= m_leastAddr); }
/// isolate the least set bit of a bitmap
HK_FORCE_INLINE static int _leastBit(int x) { return ((x) & -(x)); }
/// mask with all bits to left of least bit of x on
HK_FORCE_INLINE static int _leftBits(int x) { return ((x<<1) | -(x<<1)); }
/// An index to a set bit
HK_FORCE_INLINE static int _indexToBit(int x) { return 1<<x; }
/// mask with all bits to left of or equal to least bit of x on
HK_FORCE_INLINE static int _sameOrLeftBits(int x) { return ((x) | -(x)); }
static HK_FORCE_INLINE hkBool _comparePointers( void* a,void* b)
{
return (char*)a < (char*)b;
}
/// True if there are no allocated pages
hkBool _hasPages() { return m_pages.m_next != &m_pages; }
static void HK_CALL _addAlloc(void* data,hk_size_t size,void* param);
protected:
// A listener which handles situations when memory allocation gets tight
LimitedMemoryListener* m_limitedListener;
// A bit field with a bit indicating if a tree bucket has contents or not
BinMap m_treemap;
//
char* m_leastAddr;
// The 'topmost memory' chunk
MemChunk* m_top;
// Cached size of topmost block
hk_size_t m_topsize;
// The tree bins
MemTreeChunk* m_treebins[NTREEBINS];
// Fixed block memory, if using. Check with inUse() method.
FixedMemoryBlockServer m_fixedBlockServer;
// Server for getting large memory blocks. Either points to internal fixed memory block or to another allocator.
hkMemoryAllocator* m_server;
// Used as top when starting up
MemChunk m_zeroChunk;
// This dummy page is the start of a doubly linked list of memory pages allocated through the server interface
MemPage m_pages;
// The total amount of allocated memory with overhead
hk_size_t m_sumAllocatedWithMgrOverhead;
/// The sum of all allocated memory
hk_size_t m_sumAllocatedSize;
};
#endif // HK_LARGE_BLOCK_ALLOCATOR_H
/*
* Havok SDK - Base file, BUILD(#20130912)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
| [
"dingfengyu@gmail.com"
] | dingfengyu@gmail.com |
d24e54b65c9a3028a8fb422c4dcd0ea15d9eae81 | 6e1ea8d65052f025060453f66819ac446a7592d8 | /zoj/3575.cpp | 944e5de8b3b127db87726fc74018db7c1e10c0b1 | [] | no_license | csJd/oj-codes | bc38b79b9227b45d34139c84f9ef1e830f6b996c | 2bd65d0070adc3400ee5bee8d1cf02a038de540b | refs/heads/master | 2022-03-21T20:21:40.153833 | 2019-11-28T13:11:54 | 2019-11-28T13:11:54 | 47,266,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 205;
const double eps = 1e-8;
double a, b, x0, y0;
double x[N], y[N];
int main()
{
while(~scanf("%lf%lf", &a, &b))
{
scanf("%d", &n);
for(int i = 0; i < n; ++i)
scanf("%lf%lf", &x[i] ,&y[i]);
if(!n || !a || !b)
{
puts("0");
continue;
}
return 0;
}
//Last modified : 2015-08-02 16:13
| [
"ddwust@gmail.com"
] | ddwust@gmail.com |
6e18c7697fe5ef3ea3b876e68f9342ea2af30bed | 43a258c00bc46b57081eaa829d20bf75bfe9487d | /unstable/check_for_pseudogene.cpp | 2f8d91bddfaaf7950ebb170ca8a97ae9977c2edc | [] | no_license | HealthVivo/mumdex | 96dbfb7110ae253abcfdcfd49d85fbea6ee9f430 | 25e1f2f2da385bafbdfae61dc61afedb044041b8 | refs/heads/master | 2023-09-03T12:56:44.843200 | 2021-11-23T18:26:31 | 2021-11-23T18:26:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,881 | cpp | //
// check_for_pseudogene
//
// find denovo pseudogenes in candidate list
//
// Copyright 2017 Peter Andrews @ CSHL
//
#include <exception>
#include <iostream>
#include <fstream>
#include <string>
#include "error.h"
#include "genes.h"
#include "mumdex.h"
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::ifstream;
using std::string;
using paa::ChromosomeIndexLookup;
using paa::Error;
using paa::GeneXrefs;
using paa::JunctionInfo;
using paa::KnownGene;
using paa::KnownGenes;
using paa::Reference;
int main(int argc, char* argv[]) try {
if (--argc != 2) throw Error("usage: check_for_pseudogenes ref cand_file");
const string ref_name{argv[1]};
const Reference ref{ref_name};
const ChromosomeIndexLookup chr_lookup{ref};
const KnownGenes genes{chr_lookup, ref};
const GeneXrefs xref{ref};
ifstream candidates{argv[2]};
if (!candidates) throw Error("Could not open candidates file") << argv[2];
string chr_name[2];
unsigned int pos[2];
bool high[2];
int invariant;
int offset;
const unsigned int exon_tolerance{20};
const unsigned int invariant_tolerance{20};
while (candidates >> chr_name[0] >> pos[0] >> high[0]
>> chr_name[1] >> pos[1] >> high[1]
>> invariant >> offset) {
const unsigned int chr[2]{chr_lookup[chr_name[0]], chr_lookup[chr_name[1]]};
bool is_pseudogene{false};
// Only look at deletions for pseudogenes
if (chr[0] == chr[1] && high[0] != high[1] && invariant < 0) {
for (const KnownGene & gene : genes) {
if (chr[0] != gene.chr) continue;
// cout << "here " << gene.n_exons << " " << gene.name;
for (unsigned int e{0}; e + 1 != gene.n_exons; ++e) {
// cout << " " << gene.exon_starts[e] << " " << gene.exon_stops[e];
if ((labs(static_cast<int64_t>(pos[0]) -
static_cast<int64_t>(gene.exon_stops[e])) <
exon_tolerance ||
labs(static_cast<int64_t>(pos[1]) -
static_cast<int64_t>(gene.exon_stops[e])) <
exon_tolerance) &&
labs(invariant +
(static_cast<int64_t>(gene.exon_starts[e + 1]) -
static_cast<int64_t>(gene.exon_stops[e]))) <
invariant_tolerance) {
is_pseudogene = true;
}
}
// cout << endl;
}
}
cout << chr_name[0] << " " << pos[0] << " " << high[0]
<< " " << chr_name[1] << " " << pos[1] << " " << high[1]
<< " " << invariant << " " << offset << " " << is_pseudogene << endl;
}
return 0;
} catch (Error & e) {
cerr << "paa::Error:" << endl;
cerr << e.what() << endl;
return 1;
} catch (exception & e) {
cerr << "std::exception" << endl;
cerr << e.what() << endl;
return 1;
} catch (...) {
cerr << "unknown exception was caught" << endl;
return 1;
}
| [
"paa@drpa.us"
] | paa@drpa.us |
4fdcb28dbf5da82fe4aea979576fff72929ce5bf | e000dfb2e1ddfe62598da937d2e0d40d6efff61b | /venusmmi/app/Cosmos/Contact/ContactCore/vapp_contact_entry.h | 5223cea5791e5688e201a377b444eff7fb0bb86b | [] | no_license | npnet/KJX_K7 | 9bc11e6cd1d0fa5996bb20cc6f669aa087bbf592 | 35dcd3de982792ae4d021e0e94ca6502d1ff876e | refs/heads/master | 2023-02-06T09:17:46.582670 | 2020-12-24T02:55:29 | 2020-12-24T02:55:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,106 | h | /*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2005
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*******************************************************************************
* Filename:
* ---------
* vapp_contact_entry.h
*
* Project:
* --------
* Venus
*
* Description:
* ------------
*
*
* Author:
* -------
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include "MMI_features.h"
#include "vapp_phb_gprot.h"
#ifndef __CONTACT_ENTRY_H__
#define __CONTACT_ENTRY_H__
#include "vfx_uc_include.h"
#include "mmi_rp_vapp_contact_def.h"
#include "mmi_rp_srv_phb_def.h"
#include "vapp_contact_storage.h"
#ifdef __cplusplus
extern "C"
{
#endif
#include "PhbSrvGprot.h"
#include "FileMgrSrvGprot.h"
#include "ProfilesSrvGprot.h"
#ifdef __cplusplus
}
#endif
/*****************************************************************************
* enum
*****************************************************************************/
typedef enum
{
VAPP_CONTACT_TYPE_DEFAULT, // will deside by contact id or storage type
VAPP_CONTACT_TYPE_PHONE, // phone contact
VAPP_CONTACT_TYPE_SIM, // SIM contact
VAPP_CONTACT_TYPE_USIM, // USIM contact
VAPP_CONTACT_TYPE_CARD, // card
VAPP_CONTACT_TYPE_MYCARD, // mycard
VAPP_CONTACT_TYPE_TOTAL // enum end
} vapp_contact_type_enum;
/*****************************************************************************
* Class VappContactFieldBase
*****************************************************************************/
class VappContactFieldBase: public VfxBase
{
public:
// default constructor
VappContactFieldBase()
: m_label(), m_type(0)
{}
// constructor
VappContactFieldBase(const VfxWString &label, VfxU32 type)
: m_label(label), m_type(type)
{}
// copy constructor
VappContactFieldBase(const VappContactFieldBase& field)
{
m_label = field.getLabel();
m_type = field.getType();
}
// operator=
VappContactFieldBase& operator= (const VappContactFieldBase& field)
{
m_label = field.getLabel();
m_type = field.getType();
return *this;
}
// set label
void setLabel(const VfxWString &label)
{
m_label = label;
}
// get label
const VfxWString& getLabel() const
{
return m_label;
}
// set type
void setType(VfxU32 type)
{
m_type = type;
}
// get type
VfxU32 getType() const
{
return m_type;
}
private:
VfxWString m_label;
VfxU32 m_type;
};
/*****************************************************************************
* Class VappContactField
*****************************************************************************/
class VappContactField: public VappContactFieldBase
{
public:
// default constructor
VappContactField()
: VappContactFieldBase(), m_subType(0), m_subId(MMI_PHB_SUB_ID_NEW), m_primary(VFX_FALSE)
{};
// constructor
VappContactField(const VfxWString& label, VfxU32 type, VfxU32 subType, VfxU32 subId, VfxBool isPrimary)
: VappContactFieldBase(label, type), m_subType(subType), m_subId(subId), m_primary(isPrimary)
{}
// copy constructor
VappContactField(const VappContactField& field)
: VappContactFieldBase(field)
{
m_subType = field.getSubType();
m_subId = field.getSubId();
m_primary = field.getPrimary();
};
// operator=
VappContactField& operator= (const VappContactField& field)
{
VappContactFieldBase::operator=(field);
m_subType = field.getSubType();
m_subId = field.getSubId();
m_primary = field.getPrimary();
return *this;
}
// set subType
void setSubType(VfxU32 subType)
{
m_subType = subType;
}
// get subType
VfxU32 getSubType() const
{
return m_subType;
}
// set subId
void setSubId(VfxU32 subId)
{
m_subId = subId;
}
// get subId
VfxU32 getSubId() const
{
return m_subId;
}
// set primary
void setPrimary(VfxBool primary)
{
m_primary = primary;
}
// get primary
VfxBool getPrimary() const
{
return m_primary;
}
private:
// sub type
VfxU32 m_subType;
// sub id
VfxU32 m_subId;
// primary
VfxBool m_primary;
};
/*****************************************************************************
* Class VappContactName
*****************************************************************************/
class VappContactName: public VappContactFieldBase
{
public:
// default constructor
VappContactName()
: VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_NAME), MMI_PHB_CONTACT_FIELD_NAME)
{
m_family[0] = 0;
m_given[0] = 0;
}
// constructor
VappContactName(
const VfxWChar* family,
const VfxWChar* given,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_NAME),
VfxU32 type = MMI_PHB_CONTACT_FIELD_NAME)
: VappContactFieldBase(label, type)
{
setFamily(family);
setGiven(given);
}
// copy constructor
VappContactName(const VappContactName& name)
: VappContactFieldBase(name)
{
setFamily(name.getFamilyBuf());
setGiven(name.getGivenBuf());
}
// operator=
VappContactName& operator= (const VappContactName& name)
{
VappContactFieldBase::operator=(name);
setFamily(name.getFamilyBuf());
setGiven(name.getGivenBuf());
return *this;
}
// set family
void setFamily(const VfxWChar* family)
{
if (family == NULL)
{
m_family[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_family, (WCHAR*)family, MMI_PHB_NAME_FIELD_LENGTH);
srv_phb_remove_invalid_name((U16*)m_family);
}
}
// set given
void setGiven(const VfxWChar* given)
{
if (given == NULL)
{
m_given[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_given, (WCHAR*)given, MMI_PHB_NAME_FIELD_LENGTH);
srv_phb_remove_invalid_name((U16*)m_given);
}
}
// get family
VfxWChar* getFamilyBuf() const
{
return (VfxWChar*)m_family;
}
// get given
VfxWChar* getGivenBuf() const
{
return (VfxWChar*)m_given;
}
// get name
VfxWString getString() const
{
VfxWChar name[MMI_PHB_NAME_LENGTH + 1];
srv_phb_convert_to_name(name, (U16*)m_given, (U16*)m_family, MMI_PHB_NAME_LENGTH);
return VFX_WSTR_MEM(name);
}
// get length
VfxU32 getLength()
{
return MMI_PHB_NAME_FIELD_LENGTH;
}
// is empty
VfxBool isEmpty()
{
if (m_family[0] == 0 && m_given[0] == 0)
{
return VFX_TRUE;
}
else
{
return VFX_FALSE;
}
}
private:
VfxWChar m_family[MMI_PHB_NAME_FIELD_LENGTH + 1];
VfxWChar m_given[MMI_PHB_NAME_FIELD_LENGTH + 1];
};
#ifdef __MMI_PHB_USIM_SUPPORT__
/*****************************************************************************
* Class VappContactNickname
*****************************************************************************/
class VappContactNickname: public VappContactFieldBase
{
public:
// default constructor
VappContactNickname()
: VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_NICKNAME), MMI_PHB_CONTACT_FIELD_NICK)
{
m_value[0] = 0;
}
// constructor
VappContactNickname(
const VfxWChar* value,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_NICKNAME),
VfxU32 type = MMI_PHB_CONTACT_FIELD_NICK)
: VappContactFieldBase(label, type)
{
setValue(value);
}
// copy constructor
VappContactNickname(const VappContactNickname& nickname)
: VappContactFieldBase(nickname)
{
setValue(nickname.getBuf());
}
// operator=
VappContactNickname& operator= (const VappContactNickname& nickname)
{
VappContactFieldBase::operator=(nickname);
setValue(nickname.getBuf());
return *this;
}
// set nickname
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_NAME_FIELD_LENGTH);
srv_phb_remove_invalid_name((U16*)value);
}
}
// get nickname
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_NAME_FIELD_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_NAME_FIELD_LENGTH + 1];
};
#endif /* __MMI_PHB_USIM_SUPPORT__ */
/*****************************************************************************
* Class VappContactNumber
*****************************************************************************/
class VappContactNumber: public VappContactField
{
public:
// default constructor
VappContactNumber()
: VappContactField(
VFX_WSTR_RES(VAPP_PHB_STR_MOBILE),
MMI_PHB_CONTACT_FIELD_NUMBER,
MMI_PHB_NUM_TYPE_MOBILE,
MMI_PHB_SUB_ID_NEW,
VFX_FALSE)
{
m_value[0] = 0;
}
// constructor
VappContactNumber(const VfxWChar* value)
: VappContactField(
VFX_WSTR_RES(VAPP_PHB_STR_MOBILE),
MMI_PHB_CONTACT_FIELD_NUMBER,
MMI_PHB_NUM_TYPE_MOBILE,
MMI_PHB_SUB_ID_NEW,
VFX_FALSE)
{
setValue(value);
}
// constructor
VappContactNumber(
const VfxWChar* value,
const VfxWString &label,
VfxU32 type,
VfxU32 subType,
VfxU32 subId,
VfxBool isPrimary = VFX_FALSE)
: VappContactField(label, type, subType, subId, isPrimary)
{
if (label.isEmpty())
{
setSubType(MMI_PHB_NUM_TYPE_MOBILE);
setLabel(VFX_WSTR_RES(VAPP_PHB_STR_MOBILE));
}
setValue(value);
}
// copy constructor
VappContactNumber(const VappContactNumber& number)
: VappContactField(number)
{
setValue(number.getBuf());
}
// operator=
VappContactNumber& operator= (const VappContactNumber& number)
{
VappContactField::operator=(number);
setValue(number.getBuf());
return *this;
}
// set number
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_NUMBER_LENGTH + 1);
srv_phb_remove_invalid_number((U16*)m_value);
}
}
// get number
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_NUMBER_LENGTH + 1;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_NUMBER_LENGTH + 1 + 1];
};
/*****************************************************************************
* Class VappContactEmail
*****************************************************************************/
class VappContactEmail: public VappContactField
{
public:
// default constructor
VappContactEmail()
: VappContactField(
VFX_WSTR_RES(VAPP_PHB_STR_WORK),
MMI_PHB_CONTACT_FIELD_EMAIL,
MMI_PHB_EMAIL_TYPE_OFFICE,
MMI_PHB_SUB_ID_NEW,
VFX_FALSE)
{
m_value[0] = 0;
}
// constructor
VappContactEmail(const VfxWChar* value)
: VappContactField(
VFX_WSTR_RES(VAPP_PHB_STR_WORK),
MMI_PHB_CONTACT_FIELD_EMAIL,
MMI_PHB_EMAIL_TYPE_OFFICE,
MMI_PHB_SUB_ID_NEW,
VFX_FALSE)
{
setValue(value);
}
// constructor
VappContactEmail(
const VfxWChar* value,
const VfxWString &label,
VfxU32 type,
VfxU32 subType,
VfxU32 subId,
VfxBool isPrimary = VFX_FALSE)
: VappContactField(label, type, subType, subId, isPrimary)
{
if (label.isEmpty())
{
setSubType(MMI_PHB_EMAIL_TYPE_OFFICE);
setLabel(VFX_WSTR_RES(VAPP_PHB_STR_WORK));
}
setValue(value);
}
// copy constructor
VappContactEmail(const VappContactEmail& email)
: VappContactField(email)
{
setValue(email.getBuf());
}
// operator=
VappContactEmail& operator= (const VappContactEmail& email)
{
VappContactField::operator=(email);
setValue(email.getBuf());
return *this;
}
// set email
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_EMAIL_LENGTH);
}
}
// get email
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_EMAIL_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_EMAIL_LENGTH + 1];
};
#ifdef __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__
/*****************************************************************************
* Class VappContactCompany
*****************************************************************************/
class VappContactCompany: public VappContactFieldBase
{
public:
VappContactCompany():
VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_COMPANY), MMI_PHB_CONTACT_FIELD_COMPANY)
{
m_value[0] = 0;
}
VappContactCompany(
const VfxWChar* value,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_COMPANY),
VfxU32 type = MMI_PHB_CONTACT_FIELD_COMPANY)
: VappContactFieldBase(label, type)
{
setValue(value);
}
VappContactCompany(const VappContactCompany& company):
VappContactFieldBase(company)
{
setValue(company.getBuf());
}
VappContactCompany& operator= (const VappContactCompany& company)
{
VappContactFieldBase::operator=(company);
setValue(company.getBuf());
return *this;
}
// set company
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_COMPANY_LENGTH);
}
}
// get company
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_COMPANY_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_COMPANY_LENGTH + 1];
};
#endif /* __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__ */
#ifdef __MMI_PHB_INFO_FIELD__
/*****************************************************************************
* Class VappContactTitle
*****************************************************************************/
class VappContactTitle: public VappContactFieldBase
{
public:
VappContactTitle():
VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_TITLE), MMI_PHB_CONTACT_FIELD_TITLE)
{
m_value[0] = 0;
}
VappContactTitle(
const VfxWChar* value,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_TITLE),
VfxU32 type = MMI_PHB_CONTACT_FIELD_TITLE)
: VappContactFieldBase(label, type)
{
setValue(value);
}
VappContactTitle(const VappContactTitle& title):
VappContactFieldBase(title)
{
setValue(title.getBuf());
}
VappContactTitle& operator= (const VappContactTitle& title)
{
VappContactFieldBase::operator=(title);
setValue(title.getBuf());
return *this;
}
// set title
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_TITLE_LENGTH);
}
}
// get title
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_TITLE_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_TITLE_LENGTH + 1];
};
/*****************************************************************************
* Class VappContactURL
*****************************************************************************/
class VappContactURL: public VappContactFieldBase
{
public:
VappContactURL():
VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_URL), MMI_PHB_CONTACT_FIELD_URL)
{
m_value[0] = 0;
}
VappContactURL(const VfxWChar* value,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_URL),
VfxU32 type = MMI_PHB_CONTACT_FIELD_URL)
: VappContactFieldBase(label, type)
{
setValue(value);
}
VappContactURL(const VappContactURL& url):
VappContactFieldBase(url)
{
setValue(url.getBuf());
}
VappContactURL& operator= (const VappContactURL& url)
{
VappContactFieldBase::operator=(url);
setValue(url.getBuf());
return *this;
}
// set url
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_URL_LENGTH);
}
}
// get url
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_URL_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_URL_LENGTH + 1];
};
/*****************************************************************************
* Class VappContactNote
*****************************************************************************/
class VappContactNote: public VappContactFieldBase
{
public:
VappContactNote():
VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_NOTE), MMI_PHB_CONTACT_FIELD_NOTE)
{
m_value[0] = 0;
}
VappContactNote(
const VfxWChar* value,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_NOTE),
VfxU32 type = MMI_PHB_CONTACT_FIELD_NOTE)
: VappContactFieldBase(label, type)
{
setValue(value);
}
VappContactNote(const VappContactNote& note):
VappContactFieldBase(note)
{
setValue(note.getBuf());
}
VappContactNote& operator= (const VappContactNote& note)
{
VappContactFieldBase::operator=(note);
setValue(note.getBuf());
return *this;
}
// set note
void setValue(const VfxWChar* value)
{
if (value == NULL)
{
m_value[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_value, (WCHAR*)value, MMI_PHB_NOTE_LENGTH);
}
}
// get note
VfxWString getString() const
{
return VFX_WSTR_MEM(m_value);
}
// get buffer
VfxWChar* getBuf() const
{
return (VfxWChar*) m_value;
}
// get length
VfxU32 getLength()
{
return MMI_PHB_NOTE_LENGTH;
}
// is empty
VfxBool isEmpty()
{
return (m_value[0] != 0) ? VFX_FALSE : VFX_TRUE;
}
private:
VfxWChar m_value[MMI_PHB_NOTE_LENGTH + 1];
};
/*****************************************************************************
* Class VappContactAddress
*****************************************************************************/
class VappContactAddress: public VappContactFieldBase
{
public:
// default constructor
VappContactAddress():
VappContactFieldBase(VFX_WSTR_RES(VAPP_PHB_STR_ADDRESS), MMI_PHB_CONTACT_FIELD_ADDRESS)
{
m_pobox[0] = 0;
m_extension[0] = 0;
m_street[0] = 0;
m_city[0] = 0;
m_state[0] = 0;
m_postalcode[0] = 0;
m_country[0] = 0;
}
// constructor
VappContactAddress(const VappContactAddress& addr):
VappContactFieldBase(addr)
{
setPobox(addr.getPoboxBuf());
setExtension(addr.getExtensionBuf());
setPostalcode(addr.getPostalcodeBuf());
setStreet(addr.getStreetBuf());
setCity(addr.getCityBuf());
setCountry(addr.getCountryBuf());
setState(addr.getStateBuf());
}
// operator=
VappContactAddress& operator= (const VappContactAddress& addr)
{
VappContactFieldBase::operator=(addr);
setPobox(addr.getPoboxBuf());
setExtension(addr.getExtensionBuf());
setPostalcode(addr.getPostalcodeBuf());
setStreet(addr.getStreetBuf());
setCity(addr.getCityBuf());
setCountry(addr.getCountryBuf());
setState(addr.getStateBuf());
return *this;
}
// set pobox
void setPobox(const VfxWChar *pobox)
{
if (pobox == NULL)
{
m_pobox[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_pobox, (WCHAR*)pobox, MMI_PHB_ADDRESS_LENGTH);
}
}
// get pobox
VfxWChar* getPoboxBuf() const
{
return (VfxWChar*)m_pobox;
}
// set extension
void setExtension(const VfxWChar *extension)
{
if (extension == NULL)
{
m_extension[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_extension, (WCHAR*)extension, MMI_PHB_ADDRESS_LENGTH);
}
}
// get extension
VfxWChar* getExtensionBuf() const
{
return (VfxWChar*)m_extension;
}
// set street
void setStreet(const VfxWChar *street)
{
if (street == NULL)
{
m_street[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_street, (WCHAR*)street, MMI_PHB_ADDRESS_LENGTH);
}
}
// get street
VfxWChar* getStreetBuf() const
{
return (VfxWChar*)m_street;
}
// set city
void setCity(const VfxWChar *city)
{
if (city == NULL)
{
m_city[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_city, (WCHAR*)city, MMI_PHB_ADDRESS_LENGTH);
}
}
// get city
VfxWChar* getCityBuf() const
{
return (VfxWChar*)m_city;
}
// set state
void setState(const VfxWChar *state)
{
if (state == NULL)
{
m_state[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_state, (WCHAR*)state, MMI_PHB_ADDRESS_LENGTH);
}
}
// get state
VfxWChar* getStateBuf() const
{
return (VfxWChar*)m_state;
}
// set postalcode
void setPostalcode(const VfxWChar *postalcode)
{
if (postalcode == NULL)
{
m_postalcode[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_postalcode, (WCHAR*)postalcode, MMI_PHB_ADDRESS_LENGTH);
}
}
// get postalcode
VfxWChar* getPostalcodeBuf() const
{
return (VfxWChar*)m_postalcode;
}
// set country
void setCountry(const VfxWChar *country)
{
if (country == NULL)
{
m_country[0] = 0;
}
else
{
mmi_wcsncpy((WCHAR*)m_country, (WCHAR*)country, MMI_PHB_ADDRESS_LENGTH);
}
}
// get country
VfxWChar* getCountryBuf() const
{
return (VfxWChar*)m_country;
}
// get address
VfxWString getString()
{
VfxWString address;
VfxBool append = VFX_FALSE;
if (m_pobox[0])
{
address += VFX_WSTR_MEM(m_pobox);
append = VFX_TRUE;
}
if (m_extension[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_extension);
append = VFX_TRUE;
}
if (m_street[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_street);
append = VFX_TRUE;
}
if (m_city[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_city);
append = VFX_TRUE;
}
if (m_state[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_state);
append = VFX_TRUE;
}
if (m_postalcode[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_postalcode);
append = VFX_TRUE;
}
if (m_country[0])
{
if (append)
{
address += VFX_WSTR_RES(VAPP_PHB_STR_COMMA);
}
address += VFX_WSTR_MEM(m_country);
}
return address;
}
// get buffer
void getBuf(mmi_phb_address_struct *address)
{
mmi_wcscpy(address->city, m_city);
mmi_wcscpy(address->country, m_country);
mmi_wcscpy(address->extension, m_extension);
mmi_wcscpy(address->pobox, m_pobox);
mmi_wcscpy(address->postalcode, m_postalcode);
mmi_wcscpy(address->state, m_state);
mmi_wcscpy(address->street, m_street);
}
// get length
VfxU32 getLength()
{
return MMI_PHB_ADDRESS_LENGTH;
}
// is empty
VfxBool isEmpty()
{
if (m_pobox[0] == 0 && m_extension[0] == 0 && m_street[0] == 0 && m_city[0] == 0 && m_state[0] == 0 && m_postalcode[0] == 0 && m_country[0] == 0)
{
return VFX_TRUE;
}
else
{
return VFX_FALSE;
}
}
private:
VfxWChar m_pobox[MMI_PHB_ADDRESS_LENGTH + 1]; /* pobox field */
VfxWChar m_extension[MMI_PHB_ADDRESS_LENGTH + 1]; /* extension field */
VfxWChar m_street[MMI_PHB_ADDRESS_LENGTH + 1]; /* street field */
VfxWChar m_city[MMI_PHB_ADDRESS_LENGTH + 1]; /* city field */
VfxWChar m_state[MMI_PHB_ADDRESS_LENGTH + 1]; /* state field */
VfxWChar m_postalcode[MMI_PHB_ADDRESS_LENGTH + 1]; /* postalcode field */
VfxWChar m_country[MMI_PHB_ADDRESS_LENGTH + 1]; /* country field */
};
#endif /* __MMI_PHB_INFO_FIELD__ */
/*****************************************************************************
* Class VappContactBday
*****************************************************************************/
#ifdef __MMI_PHB_BIRTHDAY_FIELD__
class VappContactBday: public VappContactFieldBase
{
public:
VappContactBday()
: m_year(0), m_month(0), m_day(0)
{}
VappContactBday(
VfxU16 year,
VfxU8 month,
VfxU8 day,
const VfxWString &label = VFX_WSTR_RES(VAPP_PHB_STR_BDAY),
VfxU32 type = MMI_PHB_CONTACT_FIELD_BDAY)
: VappContactFieldBase(label, type), m_year(year), m_month(month), m_day(day)
{}
VappContactBday(const VappContactBday& bday)
: VappContactFieldBase(bday)
{
m_year = bday.getYear();
m_month = bday.getMonth();
m_day = bday.getDay();
}
VappContactBday& operator= (const VappContactBday& bday)
{
VappContactFieldBase::operator=(bday);
m_year = bday.getYear();
m_month = bday.getMonth();
m_day = bday.getDay();
return *this;
}
void setYear(VfxU16 year)
{
m_year = year;
}
VfxU16 getYear() const
{
return m_year;
}
void setMonth(VfxU8 month)
{
m_month = month;
}
VfxU8 getMonth() const
{
return m_month;
}
void setDay(VfxU8 day)
{
m_day = day;
}
VfxU8 getDay() const
{
return m_day;
}
VfxBool checkBday()
{
if (m_year >= MMI_PHB_BDAY_MIN_YEAR_INT && m_year <= MMI_PHB_BDAY_MAX_YEAR_INT
&& m_month > 0 && m_month <= 12 && m_day > 0 && m_day <= 31)
{
return VFX_TRUE;
}
return VFX_FALSE;
}
VfxWString getString()
{
if (!checkBday())
{
return VFX_WSTR_EMPTY;
}
VfxDateTime data;
data.setDate(m_year, m_month, m_day);
VfxWChar dataStr[15];
data.getDateTimeString(
VFX_DATE_TIME_DATE_YEAR | VFX_DATE_TIME_DATE_MONTH | VFX_DATE_TIME_DATE_DAY,
dataStr,
15);
return VFX_WSTR_MEM(dataStr);
}
private:
VfxU16 m_year;
VfxU8 m_month;
VfxU8 m_day;
};
#endif /* __MMI_PHB_BIRTHDAY_FIELD__ */
/*****************************************************************************
* Class VappContactRes
*****************************************************************************/
class VappContactRes: public VappContactFieldBase
{
public:
VappContactRes()
: m_path(), m_resId(0)
{}
VappContactRes(const VfxWChar* path, VfxU16 resId, VfxU32 type)
: VappContactFieldBase(VFX_WSTR_EMPTY, type), m_path(VFX_WSTR_MEM(path)), m_resId(resId)
{}
VappContactRes(const VfxWChar* path, VfxU16 resId, const VfxWString &label, VfxU32 type)
: VappContactFieldBase(label, type), m_path(VFX_WSTR_MEM(path)), m_resId(resId)
{}
VappContactRes(const VappContactRes& res)
: VappContactFieldBase(res)
{
m_path = res.getPath();
m_resId = res.getResId();
}
VappContactRes& operator= (const VappContactRes& res)
{
VappContactFieldBase::operator=(res);
m_path = res.getPath();
m_resId = res.getResId();
return *this;
}
void setPath(const VfxWString &path)
{
m_path = path;
}
VfxWString getPath() const
{
return m_path;
}
void setResId(VfxU16 resId)
{
m_resId = resId;
}
VfxU16 getResId() const
{
return m_resId;
}
VfxWString getString()
{
if (getType() == MMI_PHB_CONTACT_FIELD_RING)
{
if (m_resId == 0 && m_path.isEmpty())
{
return VFX_WSTR_RES(VAPP_PHB_STR_DEFAULT);
}
else if (!m_path.isEmpty())
{
return VFX_WSTR_MEM(srv_fmgr_path_get_filename_const_ptr(m_path.getBuf()));
}
else
{
VfxU16 offset;
srv_prof_audio_resource_type_enum type = srv_prof_get_audio_info_from_audio_resourece(m_resId, &offset);
if (type == SRV_PROF_AUDIO_RES_NONE)
{
return VFX_WSTR_RES(VAPP_PHB_STR_DEFAULT);
}
else
{
return VFX_WSTR_RES(srv_prof_get_string_id_from_audio_resourece(type, offset));
}
}
}
return VFX_WSTR_EMPTY;
}
VfxImageSrc getImageSrc()
{
if (getType() == MMI_PHB_CONTACT_FIELD_IMAGE)
{
if (!m_path.isEmpty())
{
return VfxImageSrc(m_path);
}
else if (m_resId != 0 && m_resId != IMG_PHB_DEFAULT)
{
return VfxImageSrc(m_resId);
}
}
return VfxImageSrc();
}
private:
VfxWString m_path;
VfxU16 m_resId;
};
/*
* Notice: the object in the vector must be inherit from VfxBase directly
*/
/*****************************************************************************
* Class ContactStack
*****************************************************************************/
template <class _contact_stack_base>
class ContactStack: public VfxObject
{
public:
class Element: public VfxBase
{
public:
_contact_stack_base m_element;
};
typedef Element* ElementPtr;
public:
ContactStack():
m_elementArray(NULL),
m_size(0),
m_top(0){}
ContactStack(VfxU32 size):
m_elementArray(NULL),
m_size(size),
m_top(0){}
const _contact_stack_base& operator[] (VfxU32 index) const
{
VFX_ASSERT(index < m_size);
return m_elementArray[index]->m_element;
}
// set size
void setSize(VfxU32 size)
{
freeStack();
m_size = size;
buildStack();
}
// get size
VfxU32 getSize() const
{
return m_size;
}
// get count
VfxU32 getCount() const
{
return m_top;
}
void pushValue(const _contact_stack_base& base)
{
VFX_ASSERT(m_top < m_size);
m_elementArray[m_top++]->m_element = base;
}
_contact_stack_base& popValue()
{
VFX_ASSERT(m_top > 0);
return m_elementArray[--m_top]->m_element;
}
_contact_stack_base& getValue(VfxU32 index)
{
VFX_ASSERT(index < m_size);
return m_elementArray[index]->m_element;
}
void setValue(const _contact_stack_base& base, VfxU32 index)
{
VFX_ASSERT(index < m_size);
if (index >= m_top)
{
pushValue(base);
}
else
{
m_elementArray[index]->m_element = base;
}
}
void insertValue(const _contact_stack_base& base, VfxU32 index)
{
VFX_ASSERT(index < m_size);
if (index < m_top)
{
VFX_ASSERT(m_top < m_size);
VfxU32 i = m_top - 1;
while (i >= index)
{
m_elementArray[i + 1]->m_element = m_elementArray[i]->m_element;
i--;
}
}
m_elementArray[index]->m_element = base;
m_top++;
setValue(base, index);
}
void removeValue(VfxU32 index)
{
VFX_ASSERT(index < m_size);
VFX_ASSERT(index < m_top);
VFX_ASSERT(m_top > 0);
m_top--;
while (index < m_top)
{
m_elementArray[index]->m_element = m_elementArray[index + 1]->m_element;
index++;
}
}
VfxS32 find(const _contact_stack_base& base)
{
VfxU32 i;
for (i = 0; i < m_top; i++)
{
if (m_elementArray[i]->m_element == base)
{
return i;
}
}
return -1;
}
void reset()
{
m_top = 0;
}
protected:
virtual void onInit()
{
VfxObject::onInit();
buildStack();
}
virtual void onDeinit()
{
freeStack();
VfxObject::onDeinit();
}
private:
void buildStack()
{
if (m_size == 0)
{
return;
}
VFX_ALLOC_MEM(m_elementArray, sizeof(ElementPtr) * m_size, this);
for (VfxU32 i = 0; i < m_size; i++)
{
VFX_ALLOC_NEW(m_elementArray[i], Element, this);
}
}
void freeStack()
{
if (m_size == 0)
{
return;
}
for (VfxU32 i = 0; i < m_size; i++)
{
VFX_DELETE(m_elementArray[i]);
}
VFX_FREE_MEM(m_elementArray);
}
private:
ElementPtr *m_elementArray;
VfxU32 m_size;
VfxU32 m_top;
};
/*****************************************************************************
* Class VappContactStackList
*****************************************************************************/
template <class _contact_list_base>
class VappContactStackList: public VfxObject
{
public:
class Element: public VfxBase
{
public:
_contact_list_base* m_element;
Element *m_next;
Element *m_prev;
};
public:
VappContactStackList():
m_head(NULL),
m_tail(0),
m_top(0)
{}
// get count
VfxU32 getCount() const
{
return m_top;
}
const _contact_list_base& operator[] (VfxU32 index) const
{
VFX_ASSERT(index < m_top);
Element *element = m_head;
while (index > 0)
{
element = element->m_next;
index--;
}
_contact_list_base *base = element->m_element;
return *base;
}
void pushValue(_contact_list_base* base)
{
Element* node;
VFX_ALLOC_MEM(node, sizeof(Element), this);
node->m_element = base;
node->m_prev = m_tail;
node->m_next = NULL;
if (m_head == NULL)
{
m_head = node;
m_tail = node;
}
else
{
m_tail->m_next = node;
m_tail = node;
}
m_top++;
}
_contact_list_base* popValue()
{
VFX_ASSERT(m_top > 0);
Element* node = m_tail;
m_tail = node->m_prev;
m_top--;
if (m_top == 0)
{
m_head = NULL;
}
_contact_list_base *value = node->m_element;
VFX_FREE_MEM(node);
return value;
}
void insertValue(_contact_list_base* base, VfxU32 index)
{
Element* node;
VFX_ALLOC_MEM(node, sizeof(Element), this);
node->m_element = base;
node->m_prev = NULL;
node->m_next = NULL;
if (m_head == NULL)
{
m_head = node;
m_tail = node;
}
else if (index >= m_top)
{
m_tail->m_next = node;
node->m_prev = m_tail;
m_tail = node;
}
else
{
Element *temp1 = m_head;
VfxU32 i = 0;
while (i < index)
{
temp1 = temp1->m_next;
i++;
}
Element *temp2 = temp1->m_prev;
temp1->m_prev = node;
node->m_next = temp1;
node->m_prev = temp2;
temp2->m_next = node;
}
m_top++;
}
_contact_list_base* removeValue(VfxU32 index)
{
VFX_ASSERT(index < m_top);
VFX_ASSERT(m_top > 0);
Element *node = m_head;
VfxU32 i = 0;
while (i < index)
{
node = node->m_next;
i++;
}
return clearNode(node);
}
_contact_list_base* clearNode(Element* node)
{
VFX_ASSERT(node != NULL);
if (node->m_prev)
{
node->m_prev->m_next = node->m_next;
}
else
{
m_head = node->m_next;
}
if (node->m_next)
{
node->m_next->m_prev = node->m_prev;
}
else
{
m_tail = node->m_prev;
}
m_top--;
_contact_list_base *element = node->m_element;
VFX_FREE_MEM(node);
return element;
}
Element* getHead()
{
return m_head;
}
Element* getTail()
{
return m_tail;
}
Element* getNext(Element* node)
{
return (node ? node->m_next : NULL);
}
protected:
virtual void onDeinit()
{
VFX_ASSERT(m_top == 0);
VfxObject::onDeinit();
}
private:
Element *m_head;
Element *m_tail;
VfxU32 m_top;
};
typedef VappContactStackList<VappContactFieldBase> VappContactFieldStack;
typedef VappContactFieldStack::Element VappContactFieldStackNode;
/*****************************************************************************
* Class VappContactFieldList
*****************************************************************************/
template <class _contact_field_base>
class VappContactFieldList: public VfxObject
{
public:
VappContactFieldList()
: m_stack(NULL)
{}
VfxU32 getCount()
{
return m_stack->getCount();
}
void pushValue(const _contact_field_base& base)
{
VappContactFieldBase *value = buildValue(base);
m_stack->pushValue(value);
}
_contact_field_base* popValue()
{
return m_stack->popValue();
}
_contact_field_base& getValue(VfxU32 index)
{
VFX_ASSERT(index < getCount());
VappContactFieldStackNode *node = m_stack->getHead();
VfxU32 i = 0;
while (i < index)
{
node = node->m_next;
i++;
}
return *((_contact_field_base*) node->m_element);
}
void setValue(const _contact_field_base& base, VfxU32 index)
{
if (index >= getCount())
{
pushValue(base);
}
else
{
VappContactFieldStackNode *node = m_stack->getHead();
VfxU32 i = 0;
while (i < index)
{
i++;
node = node->m_next;
}
if (node == NULL)
{
pushValue(base);
}
else
{
VappContactFieldBase *temp = node->m_element;
node->m_element = buildValue(base);
VFX_DELETE(temp);
}
}
}
void insertValue(const _contact_field_base& base, VfxU32 index)
{
VappContactFieldBase *value = buildValue(base);
m_stack->insertValue(value, index);
}
void clear(VfxU32 index)
{
VappContactFieldBase *base = m_stack->removeValue(index);
VFX_DELETE(base);
}
void reset()
{
VfxU32 count = m_stack->getCount();
for (VfxU32 i = 0; i < count; i++)
{
VappContactFieldBase *base = m_stack->popValue();
VFX_DELETE(base);
}
}
protected:
virtual void onInit()
{
VfxObject::onInit();
VFX_OBJ_CREATE(m_stack, VappContactFieldStack, this);
}
virtual void onDeinit()
{
reset();
VFX_OBJ_CLOSE(m_stack);
VfxObject::onDeinit();
}
private:
VappContactFieldBase* buildValue(const _contact_field_base& base)
{
_contact_field_base *value;
VFX_ALLOC_NEW(value, _contact_field_base, this);
*value = base;
return value;
}
private:
VappContactFieldStack *m_stack;
};
typedef VappContactFieldList<VappContactNumber> ContactNumberStack;
typedef VappContactFieldList<VappContactEmail> ContactEmailStack;
/*****************************************************************************
* Class Contact
*****************************************************************************/
class Contact: public VfxObject
{
public:
// default constructor
Contact();
// contact type
Contact(vapp_contact_type_enum type);
// contact id
Contact(mmi_phb_contact_id id);
// get contact type
vapp_contact_type_enum getType();
// get contact id
mmi_phb_contact_id getId() const;
// get ability
VfxU32 getAbility();
// set storage
void setStorage(phb_storage_enum storage);
// get storage
phb_storage_enum getStorage();
// set name
void setName(const VappContactName& name);
// get name
VappContactName& getName();
#ifdef __MMI_PHB_USIM_SUPPORT__
// set nickname
void setNickname(const VappContactNickname &nickname);
// get nickname
VappContactNickname& getNickname();
#endif /* __MMI_PHB_USIM_SUPPORT__ */
// reset number
void resetNumber();
// get number count
VfxU32 getNumberCount();
// get max count
VfxU32 getNumberMaxCount();
// set number
void setNumber(const VappContactNumber& number, VfxU32 index = 0);
// get number
VappContactNumber& getNumber(VfxU32 index);
// remove number
void removeNumber(VfxU32 index);
// reset email
void resetEmail();
// get email count
VfxU32 getEmailCount();
// get email max count
VfxU32 getEmailMaxCount();
// set email
void setEmail(const VappContactEmail& email, VfxU32 index = 0);
// get email
VappContactEmail& getEmail(VfxU32 index);
// remove email
void removeEmail(VfxU32 index);
#ifdef __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__
// set company
void setCompany(const VappContactCompany &company);
// get company
VappContactCompany& getCompany();
#endif /* __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__ */
#ifdef __MMI_PHB_INFO_FIELD__
// set title
void setTitle(const VappContactTitle &title);
// get title
VappContactTitle& getTitle();
// set note
void setNote(const VappContactNote& note);
// get note
VappContactNote& getNote();
// set address
void setAddress(const VappContactAddress& address);
// get address
VappContactAddress& getAddress();
#endif /* __MMI_PHB_INFO_FIELD__ */
#ifdef __MMI_PHB_BIRTHDAY_FIELD__
// set bday
void setBday(const VappContactBday& bday);
#endif /* __MMI_PHB_BIRTHDAY_FIELD__ */
#ifdef __MMI_PHB_BIRTHDAY_FIELD__
// get bday
VappContactBday& getBday();
#endif /* __MMI_PHB_BIRTHDAY_FIELD__ */
// set ring tone
void setRingTone(const VappContactRes& ring);
// get ring tone
VappContactRes& getRingTone();
// set image
void setImage(const VappContactRes& img);
// get image
VappContactRes& getImage();
#ifdef __MMI_PHB_CALLER_GROUP__
void setGroupId(VfxU8 groupId);
VfxU32 getGroupId() const;
VfxWString getGroupName();
#endif /* MMI_PHB_CALLER_GROUP__ */
VfxBool getLabelSupport();
void read();
public:
void buildSrvContact(srv_phb_contact handle, VfxBool isNew);
#ifdef __MMI_PHB_MYCARD__
void buildMycard(mmi_phb_my_number_struct *myNumber);
#endif /* __MMI_PHB_MYCARD__ */
protected:
virtual void onInit();
private:
void readContact();
#ifdef __MMI_PHB_MYCARD__
void readMycard();
#endif /* __MMI_PHB_MYCARD__ */
private:
VappContactName m_name;
#ifdef __MMI_PHB_USIM_SUPPORT__
VappContactNickname m_nickname;
#endif
ContactNumberStack *m_number;
ContactEmailStack *m_email;
#ifdef __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__
VappContactCompany m_company;
#endif
#ifdef __MMI_PHB_INFO_FIELD__
VappContactTitle m_title;
VappContactNote m_note;
VappContactAddress m_address;
#endif /* __MMI_PHB_INFO_FIELD__ */
#ifdef __MMI_PHB_BIRTHDAY_FIELD__
VappContactBday m_bday;
#endif
VappContactRes m_ring;
VappContactRes m_image;
vapp_contact_type_enum m_type;
mmi_phb_contact_id m_id;
phb_storage_enum m_storage;
VfxU8 m_groupId;
};
/*****************************************************************************
* Class ContactEntry
*****************************************************************************/
class ContactEntry: public VfxBase
{
public:
ContactEntry(mmi_phb_contact_id id);
virtual ~ContactEntry();
public:
// get contact id
mmi_phb_contact_id getId() const;
// get field
VfxU32 getFieldMask();
// get name
VappContactName getName();
#ifdef __MMI_PHB_USIM_SUPPORT__
// get nickname
VappContactNickname getNickname();
#endif
// get number count
VfxU32 getNumberCount();
// get number: return number count, should call before getNextNumber
VfxU32 getNumber();
// get next number, must call getNumber first
VappContactNumber getNextNumber();
// get number by id
VappContactNumber getNumberById(mmi_phb_sub_id id);
// get email count
VfxU32 getEmailCount();
// get email: return email count, should call before getNextEmail
VfxU32 getEmail();
// get next email address, must call getEmail first
VappContactEmail getNextEmail();
// get email by id
VappContactEmail getEmailById(mmi_phb_sub_id id);
#ifdef __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__
// get company
VappContactCompany getCompany();
#endif /* __MMI_PHB_OPTIONAL_FIELD_ADDITIONAL__ */
#ifdef __MMI_PHB_INFO_FIELD__
// get title
VappContactTitle getTitle();
// get note
VappContactNote getNote();
// get address
VappContactAddress getAddress();
#endif /* __MMI_PHB_INFO_FIELD__ */
#ifdef __MMI_PHB_BIRTHDAY_FIELD__
// get bday
VappContactBday getBday();
#endif /* __MMI_PHB_BIRTHDAY_FIELD__ */
// get ring tone
VappContactRes getRingTone();
// get image
VappContactRes getImage();
// get storage
phb_storage_enum getStorage();
// get prefer SIM, VFX_TRUE for call, VFX_FALSE for message
mmi_sim_enum getPreferSim(mmi_phb_sub_id id, VfxBool call = VFX_TRUE);
public:
static VfxBool isValid(mmi_phb_contact_id id);
private:
void createHandle();
void closeHandle();
VfxBool isValid();
// default constructor
ContactEntry(){};
private:
mmi_phb_contact_id m_id;
srv_phb_contact m_contact;
srv_phb_field_filter m_filter;
srv_phb_iterator m_numLooper;
srv_phb_iterator m_emailLooper;
};
/*****************************************************************************
* Class ContactFieldType
*****************************************************************************/
class ContactFieldType: public VfxObject
{
public:
ContactFieldType(mmi_phb_contact_field_id_enum field, phb_storage_enum storage);
VfxU32 getDefaultTypeCount();
VfxU32 getCustomTypeCount();
VfxU32 getTotalCustomTypeCount();
VfxU32 getDefaultType(VfxU32 index);
VfxU32 getCustomType(VfxU32 index);
VfxWString getLabel(VfxU32 type);
#ifdef __MMI_PHB_CUSTOM_FIELD_TYPE__
VfxS32 addType(VfxWChar* label);
VfxBool deleteType(VfxU32 type);
#endif /* __MMI_PHB_CUSTOM_FIELD_TYPE__ */
mmi_phb_contact_field_id_enum getFieldType();
protected:
virtual void onInit();
private:
ContactFieldType(){}
private:
mmi_phb_contact_field_id_enum m_field;
phb_storage_enum m_storage;
VfxU8 m_typeArray[MMI_PHB_FIELD_LABEL_COUNT + 4];
VfxU8 m_typeCount;
};
#define VAPP_PHB_CUSTOM_LABEL_LENGTH (10)
/*****************************************************************************
* Class VappContactFieldObjList
*****************************************************************************/
class VappContactFieldObjList: public VfxObject
{
public:
class FieldNode
{
public:
VappContactFieldBase *m_field;
FieldNode *m_next;
};
public:
VappContactFieldObjList();
void setField(const VfxWChar* data, VfxU32 length, VfxU32 id, VfxU32 type);
FieldNode* getHead();
FieldNode* getTail();
VfxU32 getCount() const;
protected:
virtual void onDeinit();
private:
FieldNode *m_head;
FieldNode *m_tail;
VfxU32 m_count;
};
#endif /* __CONTACT_ENTRY_H__ */
| [
"3447782@qq.com"
] | 3447782@qq.com |
4c118df22b16ee8356d56dd0495f2e48792f6082 | 24a6977ceee6681fa00c2967d09930bb1d1a2bfb | /MapEditor/src/Block.cpp | 9f12c4b0c8e829c6a5cc55377508994eb061de86 | [] | no_license | Ch4ll3ng3r/cs2d | 5bef28452943d1e562f72fae7d9df146d2797f73 | 301af327d1075a53c8c11106d42911b4ea4419cf | refs/heads/master | 2021-01-23T22:07:56.108932 | 2014-03-23T13:41:14 | 2014-03-23T13:41:14 | 16,150,962 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | #include "../include/Block.hpp"
CBlock::CBlock ()
{
m_pSprite = nullptr;
m_fPos.x = 0.f;
m_fPos.y = 0.f;
m_BlockPos.x = 0;
m_BlockPos.y = 0;
m_Type = GROUND;
}
CBlock::~CBlock ()
{
if (m_pSprite != nullptr)
m_pSprite = nullptr;
}
void CBlock::SetSprite (sf::Sprite *pSprite)
{
m_pSprite = pSprite;
m_pSprite->setPosition (m_fPos);
m_pSprite->setOrigin (30.f, 30.f);
}
void CBlock::SetPos (sf::Vector2i Pos)
{
m_BlockPos = Pos;
m_fPos.x = static_cast<float> (Pos.x * 60 + 30);
m_fPos.y = static_cast<float> (Pos.y * 60 + 30);
m_pSprite->setPosition (m_fPos);
}
void CBlock::SetType (EBlockType Type)
{
m_Type = Type;
}
EBlockType CBlock::GetType ()
{
return m_Type;
}
void CBlock::SetTexture (sf::Texture &rTexture)
{
m_pSprite->setTexture (rTexture);
}
sf::Vector2f CBlock::GetPos ()
{
return m_fPos;
}
| [
"racer.simon@web.de"
] | racer.simon@web.de |
d6a58ef313e3819a0f9eba7cd9d6d9d89d778782 | fe765f287b685e9136a88f3012293a9ba22a055e | /applications/ROSLIB/ros/time.h | 935c4a6669bdc5f6929e94c323721d23b31287e1 | [] | no_license | 269785814zcl/Smartkiller | fbfe257c79c37bafca2499a4e7fbc8fa18477687 | ca94333da8df813fd7f2973605a61760406da56f | refs/heads/main | 2023-01-14T15:51:35.531353 | 2020-11-15T13:30:09 | 2020-11-15T13:30:09 | 313,037,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, 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 prducts 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_
#define ROS_TIME_H_
#include "duration.h"
#include <math.h>
namespace ros
{
void normalizeSecNSec(unsigned long &sec, unsigned long &nsec);
class Time
{
public:
unsigned long sec, nsec;
Time() : sec(0), nsec(0) {}
Time(unsigned long _sec, unsigned long _nsec) : sec(_sec), nsec(_nsec)
{
normalizeSecNSec(sec, nsec);
}
double toSec() const { return (double)sec + 1e-9*(double)nsec; };
void fromSec(double t) { sec = (unsigned long) floor(t); nsec = (unsigned long)ros_round((t-sec) * 1e9); };
unsigned long toNsec() { return (unsigned long)sec*1000000000ull + (unsigned long)nsec; };
Time& fromNSec(long t);
Time& operator +=(const Duration &rhs);
Time& operator -=(const Duration &rhs);
static Time now();
static void setNow( Time & new_now);
};
}
#endif
| [
"269785814@qq.com"
] | 269785814@qq.com |
b3bcd7f9d9953fd915f97cbc4b940df067bde1c4 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/beast/subtree/unit_test/include/boost/beast/unit_test/reporter.hpp | 58c4e053aa5f735a91b83bae6ce91cf3afc0e5dc | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,043 | hpp | //
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BOOST_BEAST_UNIT_TEST_REPORTER_HPP
#define BOOST_BEAST_UNIT_TEST_REPORTER_HPP
#include <sstd/boost/beast/unit_test/amount.hpp>
#include <sstd/boost/beast/unit_test/recorder.hpp>
#include <algorithm>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
namespace boost {
namespace beast {
namespace unit_test {
namespace detail {
/** A simple test runner that writes everything to a stream in real time.
The totals are output when the object is destroyed.
*/
template<class = void>
class reporter : public runner
{
private:
using clock_type = std::chrono::steady_clock;
struct case_results
{
std::string name;
std::size_t total = 0;
std::size_t failed = 0;
explicit
case_results(std::string name_ = "")
: name(std::move(name_))
{
}
};
struct suite_results
{
std::string name;
std::size_t cases = 0;
std::size_t total = 0;
std::size_t failed = 0;
typename clock_type::time_point start = clock_type::now();
explicit
suite_results(std::string name_ = "")
: name(std::move(name_))
{
}
void
add(case_results const& r);
};
struct results
{
using run_time = std::pair<std::string,
typename clock_type::duration>;
enum
{
max_top = 10
};
std::size_t suites = 0;
std::size_t cases = 0;
std::size_t total = 0;
std::size_t failed = 0;
std::vector<run_time> top;
typename clock_type::time_point start = clock_type::now();
void
add(suite_results const& r);
};
std::ostream& os_;
results results_;
suite_results suite_results_;
case_results case_results_;
public:
reporter(reporter const&) = delete;
reporter& operator=(reporter const&) = delete;
~reporter();
explicit
reporter(std::ostream& os = std::cout);
private:
static
std::string
fmtdur(typename clock_type::duration const& d);
virtual
void
on_suite_begin(suite_info const& info) override;
virtual
void
on_suite_end() override;
virtual
void
on_case_begin(std::string const& name) override;
virtual
void
on_case_end() override;
virtual
void
on_pass() override;
virtual
void
on_fail(std::string const& reason) override;
virtual
void
on_log(std::string const& s) override;
};
//------------------------------------------------------------------------------
template<class _>
void
reporter<_>::
suite_results::add(case_results const& r)
{
++cases;
total += r.total;
failed += r.failed;
}
template<class _>
void
reporter<_>::
results::add(suite_results const& r)
{
++suites;
total += r.total;
cases += r.cases;
failed += r.failed;
auto const elapsed = clock_type::now() - r.start;
if(elapsed >= std::chrono::seconds{1})
{
auto const iter = std::lower_bound(top.begin(),
top.end(), elapsed,
[](run_time const& t1,
typename clock_type::duration const& t2)
{
return t1.second > t2;
});
if(iter != top.end())
{
top.emplace(iter, r.name, elapsed);
if(top.size() > max_top)
top.resize(max_top);
}
}
}
//------------------------------------------------------------------------------
template<class _>
reporter<_>::
reporter(std::ostream& os)
: os_(os)
{
}
template<class _>
reporter<_>::~reporter()
{
if(results_.top.size() > 0)
{
os_ << "Longest suite times:\n";
for(auto const& i : results_.top)
os_ << std::setw(8) <<
fmtdur(i.second) << " " << i.first << '\n';
}
auto const elapsed = clock_type::now() - results_.start;
os_ <<
fmtdur(elapsed) << ", " <<
amount{results_.suites, "suite"} << ", " <<
amount{results_.cases, "case"} << ", " <<
amount{results_.total, "test"} << " total, " <<
amount{results_.failed, "failure"} <<
std::endl;
}
template<class _>
std::string
reporter<_>::fmtdur(typename clock_type::duration const& d)
{
using namespace std::chrono;
auto const ms = duration_cast<milliseconds>(d);
if(ms < seconds{1})
return std::to_string(ms.count()) + "ms";
std::stringstream ss;
ss << std::fixed << std::setprecision(1) <<
(ms.count()/1000.) << "s";
return ss.str();
}
template<class _>
void
reporter<_>::
on_suite_begin(suite_info const& info)
{
suite_results_ = suite_results{info.full_name()};
}
template<class _>
void
reporter<_>::on_suite_end()
{
results_.add(suite_results_);
}
template<class _>
void
reporter<_>::
on_case_begin(std::string const& name)
{
case_results_ = case_results(name);
os_ << suite_results_.name <<
(case_results_.name.empty() ? "" :
(" " + case_results_.name)) << std::endl;
}
template<class _>
void
reporter<_>::
on_case_end()
{
suite_results_.add(case_results_);
}
template<class _>
void
reporter<_>::
on_pass()
{
++case_results_.total;
}
template<class _>
void
reporter<_>::
on_fail(std::string const& reason)
{
++case_results_.failed;
++case_results_.total;
os_ <<
"#" << case_results_.total << " failed" <<
(reason.empty() ? "" : ": ") << reason << std::endl;
}
template<class _>
void
reporter<_>::
on_log(std::string const& s)
{
os_ << s;
}
} // detail
using reporter = detail::reporter<>;
} // unit_test
} // beast
} // boost
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.