blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4e4385799e2ab2405cc58ab0eabad83f90b9ae36 | f89bcfea60a40e191908f2404e84b265acdc4623 | /src/philoProcessPool.h | c23e12f54950977635457b4ca071b0551ee7f874 | [] | no_license | chinatyc/ProcessPool | c7668e3481749c33eef1ea4aa688179b59b46c60 | 96b825594e8140760cba2c34037ac389f5bd61ae | refs/heads/master | 2021-01-10T13:37:00.198157 | 2015-10-31T03:32:22 | 2015-10-31T03:32:22 | 45,286,984 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | h | philoProcessPool.h | #ifndef PHILO_PROCESS_POOL_H
#define PHILP_PROCESS_POOL_H
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<assert.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/epoll.h>
#include<signal.h>
#include<sys/wait.h>
#include<sys/stat.h>
class Process
{
public:
Process(){
m_pid=-1;
};
pid_t m_pid;//进程id
int m_pipefd[2];//用于和父进程进行通信
};
template<typename T>
class PhiloProcessPool
{
private:
PhiloProcessPool(int listenfd, int process_number=4);//单例模式
public:
static PhiloProcessPool<T>* create(int listenfd, int process_number=4){
if(!m_instance){
m_instance=new PhiloProcessPool<T>(listenfd,process_number);
return m_instance;
}
};
void run();//入口函数;
~PhiloProcessPool(){
delete [] m_sub_process;
};
private:
static PhiloProcessPool<T>* m_instance;
void setup_sig_pipe();
void run_parent();
void run_child();
static const int MAX_PROCESS_NUMBER=16;//进程池最大进程数
static const int USER_PER_PROCESS=65536;//每个进程处理的最大连接数;
static const int MAX_EVENT_NUMBER=10000;
int m_process_number; //进程池中当前进程数
int m_idx;//当前进程的进程序号,父进程为-1;
int m_epollfd;//每个进程都一个epoll;
int m_listenfd;//当前进程池监听的套接字
int m_stop;//进程是否执行标记;
Process* m_sub_process;
};
#endif |
48204d691e80304320ae20c983926ad73d0b2565 | aa0bb841ea70a535f2a6239409c1527239923b3e | /window.h | dcd4bf56d2e63ab57bb16272140853e87ccc28e8 | [] | no_license | Dwillnio/GameOfLife | 622b8d53409dc5cda2716cb2c5bdf68ea359559a | d3923bab96fe3ac221f8beefd03003586b7ea6c2 | refs/heads/master | 2023-03-08T22:15:43.599926 | 2021-03-04T21:38:12 | 2021-03-04T21:38:12 | 343,587,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | h | window.h | #ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include <QPainter>
#include <QTimer>
#include <QKeyEvent>
#include <chrono>
#include "game.h"
#define CELL_WIDTH 2
#define TIMER_LENGTH 30
#define TIMER_ADJUST 1.3
#define DEBUG_WINDOW
class window : public QWidget
{
Q_OBJECT
public:
explicit window(game* gm_, QWidget* parent = 0);
public slots:
void timerupdate();
protected:
void keyPressEvent(QKeyEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void paintEvent(QPaintEvent* event) override;
private:
QTimer t;
game* gm;
#ifdef DEBUG_WINDOW
std::chrono::steady_clock::time_point time;
#endif
int timer_len;
};
#endif // WINDOW_H
|
eb442ac0ffabf5a421ebbc93ba8fae88d0174141 | 7b4a0a266f8488f2b2596d95e6f5c985c8f232b9 | /algos_and_data_structures/algo/diameter_of_tree.cpp | d59c970030dc45f063377c3e230c6e3908da9fd1 | [] | no_license | shishirkumar1996/cp | 811d8607d5f460fcec445db9af4853c550aee685 | e89cb840e5b3fd91be4b9402a6fdcb20bb3466c6 | refs/heads/master | 2020-03-10T11:06:17.696405 | 2019-01-04T07:12:45 | 2019-01-04T07:12:45 | 129,348,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | diameter_of_tree.cpp | #include<bits/stdc++.h>
#define lld long long int
#define faster ios_base::sync_with_stdio(false);cin.tie(0);
#define vi vector< int >
#define vii vector< vi >
#define NUM 100007
using namespace std;
int x,n;
int max_count = 0;
bool visited[NUM];
vii graph(NUM);
void dfs(int v,int ct){
visited[v] = true;
if(ct>max_count){max_count = ct;x = v;}
for(int i=0;i<graph[v].size();i++){
int child = graph[v][i];
if(visited[child])continue;
dfs(child,ct+1);
}
}
void diam(){
for(int i=0;i<n;i++) visited[i] = false;
dfs(1,0);
for(int i=0;i<n;i++)visited[i] = false;
dfs(x,0);
}
int main(){
n = 5;
graph[0].push_back(1);graph[1].push_back(0);
graph[2].push_back(1);graph[1].push_back(2);
graph[0].push_back(3);graph[3].push_back(0);
graph[2].push_back(4); graph[4].push_back(2);
diam();
cout<<max_count<<endl;
}
|
2acb72e8df5ff89f851b62c42ef3c359f7f76dd5 | 9ac10380ac79cdc434adcf7678105b5cd6fd2ee8 | /source/cpp_coding/Utility.cpp | 4aa4ccf16fedb5eaabdb7583965614d0bdced6de | [] | no_license | adrinamin/playground | 424c9718d9a2f673ac625bf92054608f5f79683f | 8cd2f508de884a37f70a5a136996ea2e46aa435d | refs/heads/master | 2023-02-22T17:22:32.938697 | 2022-03-10T06:33:27 | 2022-03-10T06:33:27 | 155,109,657 | 0 | 0 | null | 2023-02-08T01:13:54 | 2018-10-28T19:53:45 | C# | UTF-8 | C++ | false | false | 897 | cpp | Utility.cpp | #include <iostream>
#include "Utility.h"
bool IsPrime(int x)
{
bool prime = true;
for (int i=2; i<=x/i; i=i+1)
{
int factor = x/i;
if (factor*i == x)
{
std::cout << "factor found: " << factor << std::endl;
prime = false;
break;
}
}
return prime;
}
// bool Is2MorePrime(int& x) -> take it by reference to save the copy, but that is pretty dangerous
// bool Is2MorePrime(int const& x) -> you can avoid it with const&.
// So you can take it by reference without changing the value, plus you don't have the copy ()
bool Is2MorePrime(int x)
{
x = x+2;
return IsPrime(x);
}
// return int by reference -> also very dangerous -> dangling reference
// returning a reference is a very advanced thing.
// int& BadFunction()
// {
// int a = 3;
// return a;
// }
// savest thing is to return by value |
4a2a352ebf5554d4a4932d826591568058731b81 | 3b21691f1e5931aeaeab0e338b289c83c83acad4 | /Code03/FuncPro_demo1.cpp | e0728d356b2b708c15d500c2d377511bc372262a | [] | no_license | FHangH/Cpp_Code_Plus_01 | 3cc09003ffd82a8ed57ffa13b282b38f90ed7c2c | 65e211f839e85897d0c1399b9ebbcf2298b1c3dc | refs/heads/master | 2023-05-31T02:51:18.996788 | 2021-06-25T09:11:42 | 2021-06-25T09:11:42 | 340,883,475 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 851 | cpp | FuncPro_demo1.cpp | //
// Created by FHang on 2020/8/6.
//
#include <iostream>
using namespace std;
// 无默认值参数,通过调用函数传入参数值
int func01(int a, int b, int c)
{
return a + b + c;
}
// 有默认值参数,可以通过调用函数传入参数值,也可以不传参数值
int func02(int a = 10, int b = 20, int c = 30)
{
return a + b + c;
}
// 当函数定义中,有默认参数值的一项形参,其之后的其他形参也要有形参
//int func03(int a = 10, int b, int c)
//{
// return a + b + c;
//}
// 函数在声明时,形参有默认值,定义时,形参不得定义默认值
int func04(int a = 10, int b = 20);
//int func04(int a = 20, int b = 10)
//{
// return a + b;
//}
int main()
{
cout << "Func01: " << func01(10, 20, 30) << endl;
cout << "Func02: " << func02() << endl;
return 0;
} |
913851cb048e773bbb60916c387cad63d2315580 | 4a6eb31b6efd60be0f3d4c32b3a88e02cc1885ac | /jcpp/src/main/cpp/jcpp/lang/reflect/JMethod.h | fa4f35c38374ee33ee8257932f821dcb16284f6b | [] | no_license | jeffedlund/rpc | 3f84389973651ff77ad09b53459778953843e310 | 17cba8f2ab4fce50361693db8f59ccf46c19ae78 | refs/heads/master | 2021-01-10T20:14:04.687475 | 2013-06-10T09:16:29 | 2013-06-10T09:16:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,531 | h | JMethod.h | #ifndef JMETHOD_H
#define JMETHOD_H
#include "JString.h"
#include "JObject.h"
#include "JAccessibleObject.h"
#include "JCPP.h"
#include "JMember.h"
using namespace std;
using namespace jcpp::lang;
//TODO fill modifiers for field/method
namespace jcpp{
namespace lang{
namespace reflect{
class JCPP_LIBRARY_EXPORT JMethod : public JAccessibleObject, public JMember{
public:
typedef JObject* (*invocation)(JObject* objet,vector<JObject*>*args);
private:
JString* name;
JClass* declaringClass;
JClass* returnType;
vector<JClass*>* parameterType;
invocation inv;
jint modifiers;
public:
JMethod(JString name,JClass* declaringClass,JClass* returnType,vector<JClass*>* parameterType,invocation inv);
static JClass* getClazz();
virtual JString* getName();
virtual JClass* getDeclaringClass();
virtual jint getModifiers();
virtual jbool isSynthetic();
virtual JClass* getReturnType();
virtual vector<JClass*>* getParameterType();
virtual JObject* invoke(JObject* object, vector<JObject*>*args);
virtual jbool equals(JObject* o);
virtual jint hashCode();
virtual JString toString();
virtual ~JMethod();
};
}
}
}
#endif // JMETHOD_H
|
9e3edd98cd7f1e8d561cf6ad7a7ee1085a635264 | 6c79afb9c25c780afb50c064b5e9339fc1846b85 | /katri/20191023_Processing/katri-processingsystem_ui_new_process/src/mediator/IMediator.h | a6fc93fc5f21e1095195cc8a86737294db8fc5c6 | [] | no_license | caonguyenheo/app | b8fb4a6a6088681e5d97da98acba378108817b2d | b61dfd39bd80493e9162c35a6bc41ee98c6671ec | refs/heads/master | 2020-08-27T21:57:06.191375 | 2019-10-25T09:20:32 | 2019-10-25T09:20:32 | 217,497,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | h | IMediator.h | #ifndef IMEDIATOR_H_
#define IMEDIATOR_H_
#include <QString>
#include <QPointer>
#include "common.h"
#include "viewerpanel.h"
//#include "../broadcast/SchedulerThread.h"
class SchedulerThread;
class IColleague;
class IMediator : public QObject
{
Q_OBJECT
public:
IMediator();
virtual ~IMediator();
virtual void clearIColleagueList();
void broadcast(EventType eventType, EventObject *eventObject);
void addNewRegistered(QPointer<IColleague>, QString);
void loadData(QString kittiPath);
void resetSyncStatus();
void updateSyncStatus(EventObject *eventObject);
void setSeekPosition(EventObject *eventObject);
public Q_SLOTS:
void receiveSignalPosition(int TimeStamp);
Q_SIGNALS:
void signalPosition(int value);
void signalSendTimestamp(QVector<int> *vectorTemp);
private:
QList<QPointer<IColleague>> colleagueList;
QMap<QString,bool> renderState;
SchedulerThread *m_scheduler;
QMutex m_mutex;
};
#endif //IMEDIATOR_H
|
5a53090f8a0d6324309a81c071f34d244aa736fc | 8da58f5590fddc514e65451ad9e3c87c1e2d44af | /WPSP_Testaufgabe_CPP/WPSP_Testaufgabe_CPP/CSpieler.h | 7093f7aeca1695d0a31b27c697e805aa25d3e35b | [] | no_license | KajcsaRenataGabriela/WPSP_Football | 0c209688775ec64a3f9eb88462436dd1037fab6c | 653115c77e640d1c2107e568e43947aa4312689b | refs/heads/master | 2023-01-28T11:54:40.197210 | 2020-12-13T14:39:20 | 2020-12-13T14:39:20 | 320,586,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | CSpieler.h | #pragma once
#include "CPerson.h"
class CSpieler : public CPerson
{
public:
enum e_position { torwart, abwehr, mittelfeld, sturm };
virtual void print() const override {};
protected:
e_position position = torwart;
unsigned int nummer = 0;
}; |
04125f547ef230cc64dd6c58d9689c7de712d7a2 | 1d0adb03725890fad103fc6946e8629ad68b03ac | /atcoder/ABC125/C/main.cpp | 90c75a6f414d6a9407b3aeb2c682916abd8aea2a | [] | no_license | morix1500/atcoder | b4df0589dea93f69da9692c1712aabf2141a7e6d | 3183abe66fb19a1b258ea63223c3390cfaf972d1 | refs/heads/master | 2020-05-05T06:48:05.571434 | 2019-08-27T06:11:57 | 2019-08-27T06:11:57 | 179,801,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | main.cpp | #include <bits/stdc++.h>
using namespace std;
static const int MAX = 100000;
int n;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
cin >> n;
vector<int> A(n);
for (int i = 0; i < n; i++) {
cin >> A[i];
}
if (n == 2) {
int m = max(A[1], A[2]);
cout << m << endl;
return 0;
}
vector<int> L(n + 1);
vector<int> R(n + 1);
for (int i = 0; i < n; i++) {
L[i + 1] = gcd(L[i], A[i]);
}
for (int i = n - 1; i >= 0; i--) {
R[i] = gcd(R[i + 1], A[i]);
}
int res = 0;
for (int i = 0; i < n; i++) {
res = max(res, gcd(L[i], R[i + 1]));
}
cout << res << endl;
} |
9ae4d44c635d9a7a7ab27badc28a4c466db1d435 | edd8e5c132bd588f3774e0523a0a2b200db12bde | /codeforces/1327/A.cpp | d2d456743ddc689b069927412f8a70a6b1defa45 | [] | no_license | Mehedi-Hassan/Competitive-Programming | 397efed4962a8943b694fabfe1318a0c62bc4867 | da75dfc133f33b7592a33a47faa60805c7acacb3 | refs/heads/master | 2023-04-08T08:58:13.693616 | 2021-01-16T12:10:00 | 2021-04-19T09:43:55 | 324,949,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,038 | cpp | A.cpp | #include<bits/stdc++.h>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define inf 2000000000
#define infLL 2000000000000000000
#define MAX 200005
#define sf(a) scanf("%d", &a)
#define sfl(a) scanf("%lld", &a)
#define pf(a) printf("%d ", a)
#define pfl(a) printf("%lld\n", a)
#define Case(t) printf("Case %d: ", t)
#define pii pair<int, int>
#define MOD 1000000007
#define mod 998244353
#define PI acos(-1.0)
#define eps 1e-9
#define mem(a, b) memset(a, b, sizeof(a))
#define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
inline int Set(int N, int pos){return N=N | (1<<pos);}
inline int Reset(int N, int pos){return N=N & ~(1<<pos);}
inline bool Check(int N, int pos){return (bool)(N & (1<<pos));}
inline void normal(ll &a) { a %= mod; (a < 0) && (a += mod); }
inline ll modMul(ll a, ll b) { a %= mod, b %= mod; normal(a), normal(b); return (a * b) % mod; }
inline ll modAdd(ll a, ll b) { a %= mod, b %= mod; normal(a), normal(b); return (a + b) % mod; }
inline ll modSub(ll a, ll b) { a %= mod, b %= mod; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while (p) { if (p & 1LL) r = modMul(r, b); b = modMul(b, b); p >>= 1LL; } return r; }
inline ll modInverse(ll a) { return modPow(a, mod - 2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
using namespace std;
int main()
{
FASTIO;
int t;
cin>>t;
while(t--){
ll n, k;
cin>>n>>k;
if((n%2 == 0 && k%2 == 1) || (n%2 == 1 && k%2 == 0)){
cout<<"NO"<<endl;
continue;
}
ll sum = (k-2)*(k-1) + k-1;
if(sum >= n || (n-sum)%2 == 0 || (n-sum)<2*k-1){
cout<<"NO"<<endl;
continue;
}
cout<<"YES"<<endl;
}
}
|
a776a0f9ad157cde06dce27184859d0c1be3bbe9 | 7a4ad5096ed8a414304b44138e0dbeaf2e55b6c6 | /include/gui/validator/unique_string_validator.h | 079648052534b2a433c17cbcefb6bc5479e573e6 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | nutc4k3/hal | 88f7f4de9a4b8eee41795cb4ea8da6af2c03a1bb | 702c8b69ed5ee18a05833871382be9f6cc4cdfbc | refs/heads/master | 2022-09-28T08:50:55.244395 | 2020-05-28T17:44:29 | 2020-05-28T17:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | unique_string_validator.h | #ifndef UNIQUE_STRING_VALIDATOR_H
#define UNIQUE_STRING_VALIDATOR_H
#include "validator/validator.h"
#include <QStringList>
class unique_string_validator : public validator
{
public:
unique_string_validator(const QStringList &unique_strings);
bool validate(const QString &input);
private:
const QStringList &m_unique_strings;
};
#endif // UNIQUE_STRING_VALIDATOR_H
|
a0cc486c53d28c75c30ae3cc9d795d79812c20c4 | 02456746ea13b254940ca803bc529c868b423bd1 | /linear_algebra/cxx/linear_algebra.h | 6b7674850682b83a26f11471f3459571166b1187 | [] | no_license | unh-hpc-2021/class-13 | ed8679221052ce101e8279c30460cd5ed4c59866 | 52c6dc9fbc7b36fdbc7bfaea94f2d2167595f9e3 | refs/heads/main | 2023-03-21T09:42:35.331836 | 2021-03-23T17:21:45 | 2021-03-23T17:21:45 | 350,698,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | linear_algebra.h |
#ifndef LINEAR_ALGEBRA_H
#define LINEAR_ALGEBRA_H
#include <assert.h>
#define BOUNDS_CHECK
#include <vector>
#include <ostream>
class vector
{
public:
vector(int n);
int size() const;
double operator()(int i) const;
double& operator()(int i);
private:
std::vector<double> data_;
};
bool operator==(const vector& x, const vector& y);
std::ostream& operator<<(std::ostream& os, const vector& v);
double dot(const vector& x, const vector& y);
vector operator+(const vector& x, const vector& y);
class matrix
{
public:
matrix(int n_rows, int n_cols);
double operator()(int i, int j) const;
double& operator()(int i, int j);
int n_rows() const { return m_; }
int n_cols() const { return n_; }
private:
int m_, n_;
std::vector<double> data_;
};
bool operator==(const matrix& A, const matrix& B);
std::ostream& operator<<(std::ostream& os, const matrix& A);
void matrix_vector_mul(const matrix& A, const vector& x, vector& y);
void matrix_matrix_mul(const matrix& A, const matrix& B, matrix& C);
// ----------------------------------------------------------------------
#include <stdio.h>
#define HERE \
fprintf(stderr, "HERE at %s:%d (%s)\n", __FILE__, __LINE__, __FUNCTION__)
#endif
|
50347fbd4da936c8a48916e29555e29e947cf703 | fa78fd798c2ea502f9aefe5ae20e6c12873f406a | /src/main/cpp/FieldInfo.cpp | 4a1027b56f87fe273b650ac8e8e1314d6e594330 | [
"MIT"
] | permissive | nunesgrf/JavaVirtualMachine | 6ffcc6d8022b2d3cba2861aa9806faa2cd4d219e | 4dcc988482d286d52573002d4547dab1c21502ba | refs/heads/master | 2020-04-10T14:01:42.966918 | 2018-12-09T17:46:04 | 2018-12-09T17:46:04 | 161,065,398 | 0 | 0 | MIT | 2018-12-09T17:46:05 | 2018-12-09T17:44:49 | C++ | UTF-8 | C++ | false | false | 1,233 | cpp | FieldInfo.cpp | /** @file FieldInfo.cpp
@brief Funções que mexerão com as informações das fields, armazendo os mesmos a partir da leitura dos bytecodes;
*/
#include "../hpp/FieldInfo.hpp"
#include "../hpp/ByteReader.hpp"
/** @class FieldInfo::~FieldInfo
* @brief Destrutor de FieldInfo.
* @param sem parâmetros.
* @return void
*/
FieldInfo::~FieldInfo() {
for(auto a : this->attributes) {
a->~AttributeInfo();
free(a);
}
}
/** @class FieldInfo::read
* @brief setting inicial do FieldInfo a partir de um arquivo.
* @param *fp ponteiro de arquivo @param trueCpInfo vetor de cpInfo.
* @return void
*/
void FieldInfo::read(FILE *fp, std::vector<CpInfo *> trueCpInfo)
{
ByteReader<uint16_t> TwoByte;
access_flags = TwoByte.byteCatch(fp);
name_index = TwoByte.byteCatch(fp);
descriptor_index = TwoByte.byteCatch(fp);
attributes_count = TwoByte.byteCatch(fp);
for(int i = 0; i < attributes_count; i++)
{
/* Allocate a attribute */
AttributeInfo * attribute = (AttributeInfo *)calloc(1, sizeof(*attribute));
attribute[i].read(fp,trueCpInfo);
/* Puts into the vector of attributes */
attributes.push_back(attribute);
}
}
|
24e8bf3759632b0ef2924376388bba97a1127959 | dbe2cad0d1bc32779d339944f897355ee41b246c | /src/Debugger.cpp | aaa8efaaca780cfa314f7213ff825f0cbf125521 | [
"MIT"
] | permissive | silverweed/mfemu | 25277ae4c28fde537d13ec9b6c708ef9a3a2b70f | e0a7654cde89e56f8fcaf1b6609d758266ec4678 | refs/heads/master | 2020-12-29T01:54:15.393314 | 2015-06-03T12:13:28 | 2015-06-03T12:13:28 | 36,118,740 | 0 | 0 | null | 2015-05-23T10:42:42 | 2015-05-23T10:42:42 | null | UTF-8 | C++ | false | false | 6,119 | cpp | Debugger.cpp | #include "Debugger.h"
#include <iostream>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <utility>
#include <map>
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#include <unistd.h>
#include <csignal>
#elif _WIN32 || _WIN64
#include <windows.h>
#endif
using namespace Debug;
static Debugger *_debugger = nullptr;
// While the debugger is running, trap the SIGINT to pause the emulation.
static void interrupt_handler(int s) {
if (_debugger == nullptr) return;
if (_debugger->getEmulator()->cpu.running) {
_debugger->getEmulator()->cpu.running = false;
std::clog << "Emulation paused. Type 'run' to resume." << std::endl;
return;
}
exit(s);
}
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
static void setup_signal_trap() {
struct sigaction sigintHandler;
sigintHandler.sa_handler = interrupt_handler;
sigemptyset(&sigintHandler.sa_mask);
sigintHandler.sa_flags = 0;
sigaction(SIGINT, &sigintHandler, NULL);
}
#elif _WIN32 || _WIN64
static BOOL InterruptHandlerProxy(DWORD ctrlType) {
switch (ctrlType) {
case CTRL_C_EVENT:
interrupt_handler();
return TRUE;
}
return FALSE;
}
#endif
// { cmd_string => { command, n.args } }
static const std::map<std::string, std::pair<DebugInstr, int>> debugInstructions = {
{ "run", std::make_pair(CMD_RUN, 0) },
{ "print", std::make_pair(CMD_PRINT, 0) },
{ "break", std::make_pair(CMD_BREAK, 1) },
{ "quit", std::make_pair(CMD_QUIT, 0) },
{ "exit", std::make_pair(CMD_QUIT, 0) },
{ "step", std::make_pair(CMD_STEP, 0) },
{ "cont", std::make_pair(CMD_CONTINUE, 0) },
{ "continue", std::make_pair(CMD_CONTINUE, 0) },
{ "verb", std::make_pair(CMD_VERB, 1) },
{ "help", std::make_pair(CMD_HELP, 0) },
{ "?", std::make_pair(CMD_HELP, 0) }
};
Debugger::Debugger(Emulator *_emulator, uint8_t _opts) {
emulator = _emulator;
opts = _opts;
}
Debugger::~Debugger() {}
void Debugger::Run() {
emulator->cpu.running = false;
// Trap SIGINT to pause the execution
_debugger = this;
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
setup_signal_trap();
#elif _WIN32 || _WIN64
SetConsoleCtrlHandler((PHANDLER_ROUTINE)InterruptHandlerProxy, TRUE);
#endif
while (true) {
if (!emulator->cpu.running || opts & DBG_INTERACTIVE) {
DebugCmd cmd = getCommand("(mfemu)");
switch (cmd.instr) {
case CMD_RUN:
std::clog << "Starting emulation..." << std::endl;
emulator->cpu.running = true;
break;
case CMD_PRINT:
printInstruction(emulator->cpu.PC);
break;
case CMD_BREAK: {
std::stringstream ss(cmd.args.front());
uint16_t arg;
ss >> std::hex >> arg;
setBreakpoint(arg);
break;
}
case CMD_STEP:
if (emulator->cpu.running) {
if (!(opts & DBG_NOGRAPHICS)) {
SDL_RenderClear(emulator->renderer);
}
emulator->cpu.Step();
printInstruction(emulator->cpu.PC);
} else {
std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
}
break;
case CMD_CONTINUE:
if (emulator->cpu.running) {
opts &= ~DBG_INTERACTIVE;
} else {
std::cerr << "CPU is not running: type `run` to start emulation." << std::endl;
}
break;
case CMD_HELP:
std::cout
<< "run Start emulation" << std::endl
<< "print Print current instruction" << std::endl
<< "break <addr> Set breakpoint at <addr>" << std::endl
<< "step Fetch and execute a single instruction" << std::endl
<< "continue Resume execution" << std::endl
<< "verb <on|off> Toggle instruction printing" << std::endl
<< "help Print a help message" << std::endl
<< "quit Quit the debugger" << std::endl;
break;
case CMD_VERB:
if (cmd.args.front() == "on") {
opts |= DBG_PRINTINSTR;
std::clog << "Verbosity is on." << std::endl;
} else if (cmd.args.front() == "off") {
opts &= ~DBG_PRINTINSTR;
std::clog << "Verbosity is off." << std::endl;
} else {
std::cerr << "Error: expected 'on' or 'off' after 'verb'." << std::endl;
}
break;
case CMD_QUIT:
std::clog << "...quitting." << std::endl;
return;
default:
std::cerr << "Invalid command" << std::endl;
}
} else {
// Execute instructions until a breakpoint is found
uint16_t PC = emulator->cpu.PC;
if (breakPoints.find(PC) != breakPoints.end()) {
opts |= DBG_INTERACTIVE;
std::cout << "Breakpoint reached: " << std::hex << (int)PC << std::endl;
continue;
}
uint8_t opcode = emulator->cpu.Read(PC);
if (opts & DBG_PRINTINSTR)
printInstruction(PC);
emulator->cpu.Execute(opcode);
if (!(opts & DBG_NOGRAPHICS))
SDL_RenderClear(emulator->renderer);
++emulator->cpu.PC;
}
}
}
// Reads a command from stdin and returns a struct { cmd, args }.
// Currently only takes 1 argument.
DebugCmd Debugger::getCommand(const char* prompt) {
static DebugCmd latest = { CMD_INVALID };
std::cout << prompt << " " << std::flush;
std::string line;
std::string instr;
DebugCmd cmd;
std::getline(std::cin, line);
if ((std::cin.rdstate() & std::cin.eofbit) != 0) {
cmd.instr = CMD_QUIT;
return cmd;
}
// rtrim spaces
line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());
std::stringstream ss(line);
if (line.length() < 1) {
if (latest.instr != CMD_INVALID) {
// repeat latest command
return latest;
} else {
return getCommand(prompt);
}
} else {
ss >> instr;
}
auto inst_pair = debugInstructions.find(instr);
if (inst_pair != debugInstructions.end()) {
cmd.instr = inst_pair->second.first;
for (int i = 0; i < inst_pair->second.second; ++i) {
std::string arg;
ss >> arg;
cmd.args.push_back(arg);
}
} else {
cmd.instr = CMD_INVALID;
}
latest = cmd;
return cmd;
}
void Debugger::setBreakpoint(uint16_t addr) {
breakPoints.insert(addr);
std::clog << "Set breakpoint to " << std::setfill('0') << std::setw(4) << std::hex << (int)addr << std::endl;
}
|
24d680c3552d167cbc6d8bbc47057b4158b1d198 | 39901f7851ab34323d971dd903817d13a760739a | /_130.cpp | fbcd5f8b6fd2ac70ede394e1184b06cd1e8b9d5a | [] | no_license | qinzhaokun/leetcodeCplusplus | 27ca9301a82cb1d691dfe484567fc639a6c99312 | a6e0171c336e9bb399b640e6bd4904f3ac093c1d | refs/heads/master | 2020-05-21T14:57:23.167684 | 2017-05-02T03:14:31 | 2017-05-02T03:14:31 | 65,661,672 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | cpp | _130.cpp | class Solution {
public:
void solve(vector<vector<char>>& board) {
int m = board.size();
if(m == 0) return;
int n = board[0].size();
for(int i = 0;i < n;i++){
if(board[0][i] == 'O'){
bfs(board,0,i);
}
if(board[m-1][i] == 'O'){
bfs(board,m-1,i);
}
}
for(int i = 1;i < m-1;i++){
if(board[i][0] == 'O'){
bfs(board,i,0);
}
if(board[i][n-1] == 'O'){
bfs(board,i,n-1);
}
}
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}
else if(board[i][j] == 'T'){
board[i][j] = 'O';
}
}
}
}
void bfs(vector<vector<char>> &b, int i, int j){
b[i][j] = 'T';
int d[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int n = b[0].size();
queue<int> q;
q.push(i*n+j);
while(!q.empty()){
int t = q.front();
int ii = t/n;int jj = t%n;
//b[ii][jj] = 'T';
q.pop();
for(int k = 0;k < 4;k++){
int newI = ii + d[k][0];
int newJ = jj + d[k][1];
if(newI >= 0 && newI < b.size() && newJ >= 0 && newJ < b[0].size() && b[newI][newJ] == 'O'){
b[newI][newJ] = 'T';
q.push(newI*n+newJ);
}
}
}
}
};
|
c9d8b2f307b5b7a2c8ad0cc5e7579bb72f0ce0d1 | 939bde670db8657723cacda891692727bcb19eef | /Tarea 20/Tarea 20.cpp | 339650799f2579afb46f978656ff60d7d8b109d5 | [] | no_license | cfonseca2/Computadoras-y-programacion-2018 | ec26fa07757a484b53d42de612237da81f46c7e7 | c537f621dce9adb2c2a44eb0681e199325fcfa39 | refs/heads/master | 2021-01-21T22:25:38.557490 | 2017-11-23T04:55:56 | 2017-11-23T04:55:56 | 102,157,484 | 0 | 1 | null | 2017-12-02T22:18:34 | 2017-09-01T22:27:08 | C++ | ISO-8859-1 | C++ | false | false | 433 | cpp | Tarea 20.cpp | #include <iostream>
int fncuadro (int, int);
int main() {
int a=0;
int b=0;
printf ("¿De que tamaño quieres el largo?");
scanf ("%d", &a);
printf ("¿De que tamaño quieres el ancho?");
scanf ("%d", &b);
fncuadro(a, b);
return (0);
}
int fncuadro (int a, int b){
int j=0;
int k=0;
for (k=1; k<=a; k++){
printf ("\n");
for (j=1; j<=b; j++){
printf ("+");
}
}
return 0;
}
|
1fb7904c2eed400000975879960634b73df9ef1f | 68b6aa96e955e39688838e1c069fe2e1ab2e89d0 | /Src/Tools/NeuralNetwork/Tensor.h | 8f3682938d373476ab6127a2c28739d18ac6788f | [
"BSD-2-Clause"
] | permissive | taokehao/RobCup2021 | 96963093e8ec16ceb2864054973680f8caada3ac | 0e02edcf43e3d8d4ba6a80af38d79b314e7cc7ab | refs/heads/main | 2023-06-06T01:49:16.908718 | 2021-07-04T16:59:26 | 2021-07-04T16:59:26 | 382,896,248 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,166 | h | Tensor.h | /**
* Declares a class for storing a n-dimensional tensor.
*
* @author Felix Thielke
*/
#pragma once
#include "Platform/BHAssert.h"
#include "Tools/Math/BHMath.h"
#include "Tools/Math/NeumaierSum.h"
#include <array>
#include <vector>
#include <algorithm>
#include <type_traits>
namespace NeuralNetwork
{
/**
* A class for storing a n-dimensional tensor.
*/
template<unsigned int rank, typename T = float, size_t alignment = 16>
class Tensor
{
static_assert(rank >= 1, "");
static_assert(alignment == 1 || alignment == 2 || alignment == 4 || alignment == 8 || alignment == 16 || alignment == 32 || alignment == 64, "Alignment must be 2^n, n in [0..6].");
private:
std::array<unsigned int, rank> dimensions;
std::vector<unsigned char> buffer;
T* dataOffset;
static constexpr size_t alignmentShift = std::max(sizeof(T), alignment) - 1;
inline constexpr unsigned int computeIndex(const std::array<unsigned int, rank>& indices) const
{
unsigned int index = indices[0];
for(unsigned int i = 1; i < rank; i++)
index = index * dimensions[i] + indices[i];
return index;
}
public:
Tensor() = default;
Tensor(const std::array<unsigned int, rank>& dimensions, const size_t minCapacity = 0)
{
reshape(dimensions, minCapacity);
}
Tensor(const Tensor<rank>& other) : Tensor(other.dimensions)
{
std::copy_n(other.data(), other.size(), data());
}
inline Tensor& operator=(const Tensor<rank>& other)
{
reshape(other.dimensions);
std::copy_n(other.data(), other.size(), data());
return *this;
}
inline Tensor& copyFrom(const Tensor& other)
{
const size_t size = this->size();
ASSERT(size == other.size());
std::copy_n(other.data(), size, data());
return *this;
}
inline void reshape(const std::array<unsigned int, rank>& dimensions, const size_t minCapacity = 0)
{
this->dimensions = dimensions;
const size_t size = std::max(minCapacity, this->size()) * sizeof(T) + alignmentShift;
if(buffer.size() < size)
{
buffer.resize(size);
dataOffset = reinterpret_cast<T*>((reinterpret_cast<uintptr_t>(buffer.data()) + alignmentShift) & (~alignmentShift));
}
}
template<typename... Indices> inline void reshape(const Indices... indices) { reshape({ { static_cast<unsigned int>(indices)... } }); }
inline void reshapeDim(const size_t dim, const unsigned int size)
{
if(dim >= rank)
return;
const unsigned int oldSize = dimensions[dim];
dimensions[dim] = size;
if(size > oldSize)
reserve(this->size());
}
inline void reserve(const size_t minCapacity)
{
const size_t size = minCapacity * sizeof(T) + alignmentShift;
if(buffer.size() < size)
{
buffer.resize(size);
dataOffset = reinterpret_cast<T*>((reinterpret_cast<uintptr_t>(buffer.data()) + alignmentShift) & (~alignmentShift));
}
}
inline T absError(const Tensor<rank, T>& other, const bool l2)
{
ASSERT(dimensions == other.dimensions);
using SumType = typename std::conditional<std::is_floating_point<T>::value, NeumaierSum<T>, T>::type;
SumType sum;
const T* p0 = begin();
const T* p1 = other.begin();
if(l2)
{
for(size_t size = this->size(); size; --size)
sum += sqr(*(p0++) - *(p1++));
}
else
{
for(size_t size = this->size(); size; --size)
sum += std::abs(*(p0++) - *(p1++));
}
return l2 ? std::sqrt(static_cast<T>(sum)) : static_cast<T>(sum);
}
inline T relError(const Tensor<rank, T>& other, const bool l2)
{
ASSERT(dimensions == other.dimensions);
using SumType = typename std::conditional<std::is_floating_point<T>::value, NeumaierSum<T>, T>::type;
SumType sum;
const T* p0 = begin();
const T* p1 = other.begin();
if(l2)
{
for(size_t size = this->size(); size; --size)
{
const T val0 = *(p0++);
const T val1 = *(p1++);
if(val0 != T(0) && val1 != T(0))
sum += sqr(T(1) - val1 / val0);
}
}
else
{
for(size_t size = this->size(); size; --size)
{
const T val0 = *(p0++);
const T val1 = *(p1++);
if(val0 != T(0) && val1 != T(0))
sum += std::abs(T(1) - val1 / val0);
}
}
return l2 ? std::sqrt(static_cast<T>(sum)) : static_cast<T>(sum);
}
inline T sad(const Tensor<rank, T>& other) const
{
return absError(other, false);
}
inline const T* data() const { return dataOffset; }
inline T* data() { return dataOffset; }
inline const T* begin() const { return data(); }
inline T* begin() { return data(); }
inline const T* end() const { return data() + size(); }
inline T* end() { return data() + size(); }
inline const std::array<unsigned int, rank>& dims() const { return dimensions; }
inline unsigned int dims(const size_t i) const { return dimensions[i]; }
inline constexpr size_t size() const
{
auto it = dimensions.cbegin();
size_t size = *it;
for(it++; it != dimensions.cend(); it++)
size *= *it;
return size;
}
inline const T& operator[](const size_t index) const { return *(dataOffset + index); }
inline T& operator[](const size_t index) { return *(dataOffset + index); }
inline const T& operator()(const std::array<unsigned int, rank>& indices) const { return (*this)[computeIndex(indices)]; }
inline T& operator()(const std::array<unsigned int, rank>& indices) { return (*this)[computeIndex(indices)]; }
template<typename... Indices> inline const T& operator()(const Indices... indices) const { return (*this)({ {static_cast<unsigned int>(indices)...} }); }
template<typename... Indices> inline T& operator()(const Indices... indices) { return (*this)({ {static_cast<unsigned int>(indices)...} }); }
};
using Tensor2 = Tensor<2>;
using Tensor3 = Tensor<3>;
using Tensor4 = Tensor<4>;
}
|
b5e99aedc8e39df4f75d52784b3cba14e0174ee4 | 9a7501a7508b579c7d554ba5fd0e30d748841328 | /lkh/2504.cpp | 7d0a711d7624ef2898b2d5df79bbd909eaec1c7c | [] | no_license | algorithm5/baekjoon | 01b79dfc6dbe8b53da89d45475fd8ecf204c4b53 | 5ad8f97844079b077aecb572c311b31c85aca0d3 | refs/heads/master | 2020-05-17T17:37:14.623679 | 2019-08-18T04:48:58 | 2019-08-18T04:48:58 | 183,858,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | 2504.cpp | #include<iostream>
#include<stack>
#include<cstring>
#include<string>
using namespace std;
int main()
{
char str[31];
stack<char> s;
int val = 1;
int sum = 0;
bool wrong = false;
cin >> str;
for (int i = 0; i < str[i]; i++) {
switch (str[i]) {
case '(':
val *= 2;
s.push('(');
break;
case '[':
val *= 3;
s.push('[');
break;
case ')':
if (str[i - 1] == '(')
sum += val;
if (s.empty()) {
cout << 0;
return 0;
}
if (s.top() == '(')
s.pop();
val /= 2;
break;
case ']':
if (str[i - 1] == '[')
sum += val;
if (s.empty()) {
cout << 0;
return 0;
}
if (s.top() == '[')
s.pop();
val /= 3;
break;
}
}
if (!s.empty()) {
cout << 0;
return 0;
}
cout << sum;
} |
e865f39595f0e76dc3e5b9884704936d3af1020d | a97a05980339b7ca677489c56540573da9fa23b1 | /base/Thread.cpp | 6b6a5b3ec599340eee88fdf1a33db355d0b31b84 | [] | no_license | chenlujiu/server | 13ced4a645b8ee30249308c2c35c72935951b15c | a85dbd31ed96d2019b147223dc888743866a0c94 | refs/heads/master | 2020-04-29T10:46:13.706466 | 2019-04-07T04:28:38 | 2019-04-07T04:28:38 | 176,073,900 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | cpp | Thread.cpp | // @Author Chenlujiu
// @Email 434425042@qq.com
#include"Thread.h"
#include"CurrentThread.h"
#include<memory>
#include<errno.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/prctl.h>
#include<sys/types.h>
#include<linux/unistd.h>
#include<stdint.h>
#include<assert.h>
#include<iostream>
using namespace std;
namespace CurrentThread
{
__thread int t_cachedTid=0;
__thread char t_tidString[32];
__thread int t_tidStringLength=6;
__thread const char* t_threadName="default";
}
pid_t gettid()
{
return static_cast<pid_t>(::syscall(SYS_gettid));
}
void CurrentThread::cacheTid()
{
if(t_cachedTid==0)
{
t_cachedTid=gettid();
t_tidStringLength=snprintf(t_tidString,sizeof(t_tidString),"%5d",t_cachedTid);
}
}
struct ThreadData
{
typedef Thread::ThreadFunc ThreadFunc;
ThreadFunc func_;
string name_;
pid_t* tid_;
CountDownLatch* latch_;
ThreadData(const ThreadFunc &func,const string& name,pid_t*tid,CountDownLatch *latch)
: func_(func),
name_(name),
tid_(tid),
latch_(latch)
{}
void runInThread()
{
*tid_=CurrentThread::tid();
tid_=NULL;
latch_->countDown();
latch_=NULL;
CurrentThread::t_threadName=name_.empty()?"Thread":name_.c_str();
prctl(PR_SET_NAME,CurrentThread::t_threadName);
func_();
CurrentThread::t_threadName="finished";
}
};
void* startThread(void* obj)
{
ThreadData* data=static_cast<ThreadData*>(obj);
data->runInThread();
delete data;
return NULL;
}
Thread::Thread(const ThreadFunc&func,const string&n)
:started_(false),
joined_(false),
pthreadId_(0),
tid_(0),
func_(func),
name_(n),
latch_(1)
{
setDefaultName();
}
Thread::~Thread()
{
if(started_&&!joined_)
pthread_detach(pthreadId_);
}
void Thread::setDefaultName()
{
if(name_.empty())
{
char buf[32];
snprintf(buf,sizeof(buf),"Thread");
name_=buf;
}
}
void Thread::start()
{
assert(!started_);
started_=true;
ThreadData* data=new ThreadData(func_,name_,&tid_,&latch_);
if(pthread_create(&pthreadId_,NULL,&startThread,data))
{
started_=false;
delete data;
}
else
{
latch_.wait();
assert(tid_>0);
}
}
int Thread::join()
{
assert(started_);
assert(!joined_);
joined_=true;
return pthread_join(pthreadId_,NULL);
} |
01d8a8ec6b7e7d85723ce2e234afba4a65ec13e1 | 9457d9481e5e7fad451bb8f74d7f7de825c26d5f | /Toro/Lamp.h | 1001ef4caa189a982437d7a390c85dc01ff6afc0 | [] | no_license | francisco-polaco/cg-micro-machines-2015-ist | 123ffe83fb0079876d4e7e959341c585bb509537 | 292ca505fffdf7c2a1ce571310db63344fd484ec | refs/heads/master | 2021-06-10T14:17:40.283907 | 2016-04-30T17:56:54 | 2016-04-30T17:56:54 | 57,392,706 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | Lamp.h | #pragma once
#include "LightSource.h"
#include "Material.h"
#include "Cubo.h"
#define CENTER_X 10.0
#define CENTER_Y 10.0
class Lamp :
public LightSource
{
private:
float _height = 1.5;
Material *_poste, *_lampada, *_pavio;
int _nlamps;
public:
Lamp(GLenum number, Vector4 position, Vector4 ambientLight, Vector4 diffuseLight, Vector4 specularLight);
virtual ~Lamp();
virtual void draw();
float getHeight();
};
|
f66b47d914fd84bcd97c3c50f55642462a7a7203 | e7b50b4c849ec95e3b21b00f2916d361716ab4e8 | /LeetCode 高级算法/3. [数组和字符串] 四数相加.cpp | 0dd2af2345c3c74bfbf72dbdee77d0817f7a8c13 | [] | no_license | eyeeco/MyCode | c001582454b3b356cadee582496761f62cc6e00a | de0b22d76a0acb62ff898cbcc8b4e3c72f3a596d | refs/heads/master | 2021-01-23T05:51:03.607176 | 2019-03-05T12:33:57 | 2019-03-05T12:33:57 | 102,478,825 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | 3. [数组和字符串] 四数相加.cpp | class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
map<int,int> dic;
int num = 0;
for(int i=0;i<A.size();i++){
for(int j=0;j<B.size();j++){
dic[-(A[i]+B[j])]++;
}
}
for(int i=0;i<C.size();i++){
for(int j=0;j<D.size();j++){
if(dic.count(C[i]+D[j])){
num+=dic[C[i]+D[j]];
}
}
}
return num;
}
};
|
c6537b0bd1fbc1b2066b77f31e166983c457af5c | 727eca003d70aaed8129d84c8c6cbf53023384f9 | /pgadmin/schema/pgIndexConstraint.cpp | 2c4b2d36a93268b3870baedf56e69b3f817f0701 | [
"PostgreSQL"
] | permissive | allentc/pgadmin3-lts | 833484e5ada99be4629369a984c13cfb59180600 | d69b58b473ee501fd5be016ceea6f7c21f10336a | refs/heads/master | 2023-05-26T16:42:23.572751 | 2023-05-22T02:40:57 | 2023-05-22T02:40:57 | 174,668,882 | 25 | 34 | NOASSERTION | 2023-05-22T02:40:58 | 2019-03-09T08:36:29 | C++ | UTF-8 | C++ | false | false | 14,879 | cpp | pgIndexConstraint.cpp | //////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// pgIndexConstraint.cpp - IndexConstraint class: Primary Key, Unique
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
// App headers
#include "pgAdmin3.h"
#include "utils/misc.h"
#include "schema/pgConstraints.h"
#include "schema/pgIndexConstraint.h"
wxString pgIndexConstraint::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on index constraint");
message += wxT(" ") + GetName();
break;
case REFRESHINGDETAILS:
message = _("Refreshing index constraint");
message += wxT(" ") + GetName();
break;
case GRANTWIZARDTITLE:
message = _("Privileges for index constraint");
message += wxT(" ") + GetName();
break;
case DROPINCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop index constraint \"%s\" including all objects that depend on it?"),
GetFullIdentifier().c_str());
break;
case DROPEXCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop index constraint \"%s\"?"),
GetFullIdentifier().c_str());
break;
case DROPCASCADETITLE:
message = _("Drop index constraint cascaded?");
break;
case DROPTITLE:
message = _("Drop index constraint?");
break;
case PROPERTIESREPORT:
message = _("Index constraint properties report");
message += wxT(" - ") + GetName();
break;
case PROPERTIES:
message = _("Index constraint properties");
break;
case DDLREPORT:
message = _("Index constraint DDL report");
message += wxT(" - ") + GetName();
break;
case DDL:
message = _("Index constraint DDL");
break;
case STATISTICSREPORT:
message = _("Index constraint statistics report");
message += wxT(" - ") + GetName();
break;
case OBJSTATISTICS:
message = _("Index constraint statistics");
break;
case DEPENDENCIESREPORT:
message = _("Index constraint dependencies report");
message += wxT(" - ") + GetName();
break;
case DEPENDENCIES:
message = _("Index constraint dependencies");
break;
case DEPENDENTSREPORT:
message = _("Index constraint dependents report");
message += wxT(" - ") + GetName();
break;
case DEPENDENTS:
message = _("Index constraint dependents");
break;
}
return message;
}
bool pgIndexConstraint::DropObject(wxFrame *frame, ctlTree *browser, bool cascaded)
{
wxString sql = wxT("ALTER TABLE ") + qtIdent(GetIdxSchema()) + wxT(".") + qtIdent(GetIdxTable())
+ wxT(" DROP CONSTRAINT ") + GetQuotedIdentifier();
if (cascaded)
sql += wxT(" CASCADE");
return GetDatabase()->ExecuteVoid(sql);
}
wxString pgIndexConstraint::GetDefinition()
{
wxString sql = wxEmptyString;
if (wxString(GetTypeName()).Upper() == wxT("EXCLUDE"))
sql += wxT("\n USING ") + GetIndexType() + wxT(" ");
sql += wxT("(") + GetQuotedColumns() + wxT(")");
if (GetConnection()->BackendMinimumVersion(8, 2) && GetFillFactor().Length() > 0)
sql += wxT("\n WITH (FILLFACTOR=") + GetFillFactor() + wxT(")");
if (GetConnection()->BackendMinimumVersion(8, 0) && GetTablespace() != GetDatabase()->GetDefaultTablespace())
sql += wxT("\n USING INDEX TABLESPACE ") + qtIdent(GetTablespace());
if (GetConstraint().Length() > 0)
sql += wxT(" WHERE (") + GetConstraint() + wxT(")");
if (GetDeferrable())
{
sql += wxT("\n DEFERRABLE INITIALLY ");
if (GetDeferred())
sql += wxT("DEFERRED");
else
sql += wxT("IMMEDIATE");
}
return sql;
}
wxString pgIndexConstraint::GetCreate()
{
wxString sql;
sql = GetQuotedIdentifier() + wxT(" ")
+ GetTypeName().Upper() + GetDefinition();
return sql;
};
wxString pgIndexConstraint::GetSql(ctlTree *browser)
{
if (sql.IsNull())
{
sql = wxT("-- Constraint: ") + GetQuotedFullIdentifier()
+ wxT("\n\n-- ALTER TABLE ") + GetQuotedSchemaPrefix(GetIdxSchema()) + qtIdent(GetIdxTable())
+ wxT(" DROP CONSTRAINT ") + GetQuotedIdentifier() + wxT(";")
+ wxT("\n\nALTER TABLE ") + GetQuotedSchemaPrefix(GetIdxSchema()) + qtIdent(GetIdxTable())
+ wxT("\n ADD CONSTRAINT ")
+ GetCreate()
+ wxT(";\n");
if (!GetComment().IsNull())
{
sql += wxT("COMMENT ON CONSTRAINT ") + GetQuotedIdentifier() + wxT(" ON ") + GetQuotedSchemaPrefix(GetIdxSchema()) + qtIdent(GetIdxTable())
+ wxT(" IS ") + qtDbString(GetComment()) + wxT(";\n");
}
}
return sql;
}
void pgIndexConstraint::ShowTreeDetail(ctlTree *browser, frmMain *form, ctlListView *properties, ctlSQLBox *sqlPane)
{
ReadColumnDetails();
if (properties)
{
CreateListColumns(properties);
properties->AppendItem(_("Name"), GetName());
properties->AppendItem(_("OID"), GetConstraintOid());
properties->AppendItem(_("Index OID"), GetOid());
if (GetConnection()->BackendMinimumVersion(8, 0))
properties->AppendItem(_("Tablespace"), GetTablespace());
if (GetProcName().IsNull())
properties->AppendItem(_("Columns"), GetColumns());
else
{
properties->AppendItem(_("Procedure "), GetSchemaPrefix(GetProcNamespace()) + GetProcName() + wxT("(") + GetTypedColumns() + wxT(")"));
properties->AppendItem(_("Operator classes"), GetOperatorClasses());
}
properties->AppendYesNoItem(_("Unique?"), GetIsUnique());
properties->AppendYesNoItem(_("Primary?"), GetIsPrimary());
properties->AppendYesNoItem(_("Clustered?"), GetIsClustered());
properties->AppendYesNoItem(_("Valid?"), GetIsValid());
properties->AppendItem(_("Access method"), GetIndexType());
properties->AppendItem(_("Constraint"), GetConstraint());
properties->AppendYesNoItem(_("System index?"), GetSystemObject());
if (GetConnection()->BackendMinimumVersion(8, 2))
properties->AppendItem(_("Fill factor"), GetFillFactor());
properties->AppendItem(_("Comment"), firstLineOnly(GetComment()));
}
}
wxString pgPrimaryKey::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on primary key");
message += wxT(" ") + GetName();
break;
case REFRESHINGDETAILS:
message = _("Refreshing primary key");
message += wxT(" ") + GetName();
break;
case GRANTWIZARDTITLE:
message = _("Privileges for primary key");
message += wxT(" ") + GetName();
break;
case DROPINCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop primary key \"%s\" including all objects that depend on it?"),
GetFullIdentifier().c_str());
break;
case DROPEXCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop primary key \"%s\"?"),
GetFullIdentifier().c_str());
break;
case DROPCASCADETITLE:
message = _("Drop primary key cascaded?");
break;
case DROPTITLE:
message = _("Drop primary key?");
break;
case PROPERTIESREPORT:
message = _("Primary key properties report");
message += wxT(" - ") + GetName();
break;
case PROPERTIES:
message = _("Primary key properties");
break;
case DDLREPORT:
message = _("Primary key DDL report");
message += wxT(" - ") + GetName();
break;
case DDL:
message = _("Primary key DDL");
break;
case STATISTICSREPORT:
message = _("Primary key statistics report");
message += wxT(" - ") + GetName();
break;
case OBJSTATISTICS:
message = _("Primary key statistics");
break;
case DEPENDENCIESREPORT:
message = _("Primary key dependencies report");
message += wxT(" - ") + GetName();
break;
case DEPENDENCIES:
message = _("Primary key dependencies");
break;
case DEPENDENTSREPORT:
message = _("Primary key dependents report");
message += wxT(" - ") + GetName();
break;
case DEPENDENTS:
message = _("Primary key dependents");
break;
}
return message;
}
pgObject *pgPrimaryKey::Refresh(ctlTree *browser, const wxTreeItemId item)
{
pgObject *index = 0;
pgCollection *coll = browser->GetParentCollection(item);
if (coll)
index = primaryKeyFactory.CreateObjects(coll, 0, wxT("\n AND cls.oid=") + GetOidStr());
return index;
}
wxString pgUnique::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on unique constraint");
message += wxT(" ") + GetName();
break;
case REFRESHINGDETAILS:
message = _("Refreshing unique constraint");
message += wxT(" ") + GetName();
break;
case GRANTWIZARDTITLE:
message = _("Privileges for unique constraint");
message += wxT(" ") + GetName();
break;
case DROPINCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop unique constraint \"%s\" including all objects that depend on it?"),
GetFullIdentifier().c_str());
break;
case DROPEXCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop unique constraint \"%s\"?"),
GetFullIdentifier().c_str());
break;
case DROPCASCADETITLE:
message = _("Drop unique constraint cascaded?");
break;
case DROPTITLE:
message = _("Drop unique constraint?");
break;
case PROPERTIESREPORT:
message = _("Unique constraint properties report");
message += wxT(" - ") + GetName();
break;
case PROPERTIES:
message = _("Unique constraint properties");
break;
case DDLREPORT:
message = _("Unique constraint DDL report");
message += wxT(" - ") + GetName();
break;
case DDL:
message = _("Unique constraint DDL");
break;
case STATISTICSREPORT:
message = _("Unique constraint statistics report");
message += wxT(" - ") + GetName();
break;
case OBJSTATISTICS:
message = _("Unique constraint statistics");
break;
case DEPENDENCIESREPORT:
message = _("Unique constraint dependencies report");
message += wxT(" - ") + GetName();
break;
case DEPENDENCIES:
message = _("Unique constraint dependencies");
break;
case DEPENDENTSREPORT:
message = _("Unique constraint dependents report");
message += wxT(" - ") + GetName();
break;
case DEPENDENTS:
message = _("Unique constraint dependents");
break;
}
return message;
}
pgObject *pgUnique::Refresh(ctlTree *browser, const wxTreeItemId item)
{
pgObject *index = 0;
pgCollection *coll = browser->GetParentCollection(item);
if (coll)
index = uniqueFactory.CreateObjects(coll, 0, wxT("\n AND cls.oid=") + GetOidStr());
return index;
}
wxString pgExclude::GetTranslatedMessage(int kindOfMessage) const
{
wxString message = wxEmptyString;
switch (kindOfMessage)
{
case RETRIEVINGDETAILS:
message = _("Retrieving details on exclusion constraint");
message += wxT(" ") + GetName();
break;
case REFRESHINGDETAILS:
message = _("Refreshing exclusion constraint");
message += wxT(" ") + GetName();
break;
case GRANTWIZARDTITLE:
message = _("Privileges for exclusion constraint");
message += wxT(" ") + GetName();
break;
case DROPINCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop exclusion constraint \"%s\" including all objects that depend on it?"),
GetFullIdentifier().c_str());
break;
case DROPEXCLUDINGDEPS:
message = wxString::Format(_("Are you sure you wish to drop exclusion constraint \"%s\"?"),
GetFullIdentifier().c_str());
break;
case DROPCASCADETITLE:
message = _("Drop exclusion constraint cascaded?");
break;
case DROPTITLE:
message = _("Drop exclusion constraint?");
break;
case PROPERTIESREPORT:
message = _("Exclusion constraint properties report");
message += wxT(" - ") + GetName();
break;
case PROPERTIES:
message = _("Exclusion constraint properties");
break;
case DDLREPORT:
message = _("Exclusion constraint DDL report");
message += wxT(" - ") + GetName();
break;
case DDL:
message = _("Exclusion constraint DDL");
break;
case STATISTICSREPORT:
message = _("Exclusion constraint statistics report");
message += wxT(" - ") + GetName();
break;
case OBJSTATISTICS:
message = _("Exclusion constraint statistics");
break;
case DEPENDENCIESREPORT:
message = _("Exclusion constraint dependencies report");
message += wxT(" - ") + GetName();
break;
case DEPENDENCIES:
message = _("Exclusion constraint dependencies");
break;
case DEPENDENTSREPORT:
message = _("Exclusion constraint dependents report");
message += wxT(" - ") + GetName();
break;
case DEPENDENTS:
message = _("Exclusion constraint dependents");
break;
}
return message;
}
pgObject *pgExclude::Refresh(ctlTree *browser, const wxTreeItemId item)
{
pgObject *index = 0;
pgCollection *coll = browser->GetParentCollection(item);
if (coll)
index = excludeFactory.CreateObjects(coll, 0, wxT("\n AND cls.oid=") + GetOidStr());
return index;
}
pgObject *pgPrimaryKeyFactory::CreateObjects(pgCollection *collection, ctlTree *browser, const wxString &where)
{
return pgIndexBaseFactory::CreateObjects(collection, browser, wxT(" AND contype='p'\n") + where);
}
pgObject *pgUniqueFactory::CreateObjects(pgCollection *collection, ctlTree *browser, const wxString &where)
{
return pgIndexBaseFactory::CreateObjects(collection, browser, wxT(" AND contype='u'\n") + where);
}
pgObject *pgExcludeFactory::CreateObjects(pgCollection *collection, ctlTree *browser, const wxString &where)
{
return pgIndexBaseFactory::CreateObjects(collection, browser, wxT(" AND contype='x'\n") + where);
}
#include "images/primarykey.pngc"
pgPrimaryKeyFactory::pgPrimaryKeyFactory()
: pgIndexBaseFactory(__("Primary Key"), __("New Primary Key..."), __("Create a new Primary Key constraint."), primarykey_png_img)
{
metaType = PGM_PRIMARYKEY;
collectionFactory = &constraintCollectionFactory;
}
pgPrimaryKeyFactory primaryKeyFactory;
#include "images/unique.pngc"
pgUniqueFactory::pgUniqueFactory()
: pgIndexBaseFactory(__("Unique"), __("New Unique Constraint..."), __("Create a new Unique constraint."), unique_png_img)
{
metaType = PGM_UNIQUE;
collectionFactory = &constraintCollectionFactory;
}
pgUniqueFactory uniqueFactory;
#include "images/exclude.pngc"
pgExcludeFactory::pgExcludeFactory()
: pgIndexBaseFactory(__("Exclude"), __("New Exclusion Constraint..."), __("Create a new Exclusion constraint."), exclude_png_img)
{
metaType = PGM_EXCLUDE;
collectionFactory = &constraintCollectionFactory;
}
pgExcludeFactory excludeFactory;
|
98254aeed03e9e6c9ce3ab63e887372a2cd0023b | 2b027e4b2043a17471282b008f205dd2ac221281 | /src/S605th/src/BabyFeed/babyscreen.h | c7128561899dee8c541c2e0b2706fccf7dfae3cc | [] | no_license | hmiguellima/babyfeed | cd93bcfd7e62b5429089b42b2804fad4588b73c1 | 162ecf24c742dedd5e856638db3bcb1ba187063e | refs/heads/master | 2020-04-07T16:25:37.174103 | 2019-02-17T16:33:16 | 2019-02-17T16:33:16 | 158,528,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | h | babyscreen.h | #ifndef BABYSCREEN_H
#define BABYSCREEN_H
#include <QWidget>
#include "screen.h"
#include "flickable/qscrollareakineticscroller.h"
#include "baby.h"
#include <QAction>
#include <QMenu>
#include <QByteArray>
#include <QImage>
#include "contactsmodel.h"
#include <QComboBox>
#include "notification.h"
namespace Ui {
class BabyScreen;
}
class BabyScreen : public Screen
{
Q_OBJECT
public:
explicit BabyScreen(MainWindow* window);
~BabyScreen();
protected:
virtual void showHandler();
private:
Ui::BabyScreen *ui;
QScrollAreaKineticScroller kineticScroller1;
QScrollAreaKineticScroller kineticScroller2;
QAction *saveAction;
Baby baby;
ContactsModel *contactsModel;
QComboBox *notfMenu;
private slots:
void onShowBabyScreen(Baby &baby);
void onBabyPhotoCaptured(QByteArray data);
void onBabyPhotoAborted();
void saveBaby();
void deleteBaby();
void takePhoto();
void showNotfMenu(QModelIndex index);
void changeNotification(int notfType);
};
#endif // BABYSCREEN_H
|
6a998e9f437c0b5811cd44fa6433b3bb10eee10a | bfb1c7ff905065f0e3914b66c9a932bc811640a5 | /branches/savegame-manager-gx_R126/trunk/source/Tools/lstub.cpp | 57080371056ee9f8fb71da649ebea58f79cb1829 | [] | no_license | djskual/savegame-manager-gx | 1ddcdcfcdaf7a4043b7fd756136ec8cca0fbf5f3 | ae3cb59cb5bbae91bf65d48cb61961ed49d896d3 | refs/heads/master | 2020-06-03T05:11:20.735987 | 2015-04-14T13:16:49 | 2015-04-14T13:16:49 | 33,944,551 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,021 | cpp | lstub.cpp | //!functions for manipulating the HBC stub by giantpune
#include <string.h>
#include <ogcsys.h>
#include <malloc.h>
#include <stdio.h>
#include "lstub.h"
#include "../System/nandtitle.h"
extern const u8 stub_bin[];
extern const u32 stub_bin_size;
static char* determineStubTIDLocation()
{
u32 *stubID = (u32*) 0x80001818;
//!HBC stub 1.0.6 and lower, and stub.bin
if (stubID[0] == 0x480004c1 && stubID[1] == 0x480004f5)
return (char *) 0x800024C6;
//!HBC stub changed @ version 1.0.7. this file was last updated for HBC 1.0.8
else if (stubID[0] == 0x48000859 && stubID[1] == 0x4800088d) return (char *) 0x8000286A;
return NULL;
}
s32 Set_Stub(u64 reqID)
{
if (NandTitles.IndexOf(reqID) < 0) return WII_EINSTALL;
char *stub = determineStubTIDLocation();
if (!stub) return -68;
stub[0] = TITLE_7( reqID );
stub[1] = TITLE_6( reqID );
stub[8] = TITLE_5( reqID );
stub[9] = TITLE_4( reqID );
stub[4] = TITLE_3( reqID );
stub[5] = TITLE_2( reqID );
stub[12] = TITLE_1( reqID );
stub[13] = ((u8) (reqID));
DCFlushRange(stub, 0x10);
return 1;
}
s32 Set_Stub_Split(u32 type, const char* reqID)
{
char tmp[4];
u32 lower;
sprintf(tmp, "%c%c%c%c", reqID[0], reqID[1], reqID[2], reqID[3]);
memcpy(&lower, tmp, 4);
u64 reqID64 = TITLE_ID( type, lower );
return Set_Stub(reqID64);
}
void loadStub()
{
char *stubLoc = (char *) 0x80001800;
memcpy(stubLoc, stub_bin, stub_bin_size);
DCFlushRange(stubLoc, stub_bin_size);
}
u64 getStubDest()
{
if (!hbcStubAvailable()) return 0;
char ret[8];
u64 retu = 0;
char *stub = determineStubTIDLocation();
if (!stub) return 0;
ret[0] = stub[0];
ret[1] = stub[1];
ret[2] = stub[8];
ret[3] = stub[9];
ret[4] = stub[4];
ret[5] = stub[5];
ret[6] = stub[12];
ret[7] = stub[13];
memcpy(&retu, ret, 8);
return retu;
}
u8 hbcStubAvailable()
{
char * sig = (char *) 0x80001804;
return (sig[0] == 'S' && sig[1] == 'T' && sig[2] == 'U' && sig[3] == 'B' && sig[4] == 'H' && sig[5] == 'A'
&& sig[6] == 'X' && sig[7] == 'X') ? 1 : 0;
}
|
db3dc9967186cbf1f827700925e0bac1648ec73e | 6aad659eb2a8f074b9b4d08a827bc5811fffa994 | /FinalProjShare/FirmOwnership/placeData.h | 7e9e8d4976845d5bfcb5d4c57f5d4509629fb9dc | [] | no_license | bzamora020/data-exploration-research | 9fa3ffd725fe42ef97972f9a21b81a6c508981ab | c587e18837e38beb5d47c71108929f92df16fa97 | refs/heads/master | 2023-06-10T21:31:07.680213 | 2021-06-14T00:52:23 | 2021-06-14T00:52:23 | 355,040,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | placeData.h | #ifndef PLACE_H
#define PLACE_H
#include <string>
#include <iostream>
#include <memory>
class Visitor;
using namespace std;
/* very general data type for any kind of place data - very simple for lab04 */
class placeData : public std::enable_shared_from_this<placeData>{
//TODO define
public:
placeData(string s):
region(s){}
std::shared_ptr<placeData> getptr() {
return shared_from_this();
}
string getState() const { return region; }
friend std::ostream& operator<<(std::ostream &out, const placeData& DD){
return DD.print(out);
}
virtual ~placeData(){}
virtual void accept(class Visitor &v) = 0;
protected:
virtual std::ostream& print(std::ostream &out) const = 0;
protected:
string region;
};
#endif
|
54b016c1c7731d6fbb444298338e8fd91f68fd39 | 6e10af5fbd8414b9801772dcee40c75b614ef4d0 | /OlcMud/main.cpp | f2f6b76b191acd6d22e8d8024d78742aa0263d9d | [] | no_license | Operation-MUD/Rebellimud | 64696ad65368a505fde981bb0c317d855cd09f1d | 6ab5b3d5209797a08e35909398161f726b8ec4e8 | refs/heads/main | 2022-12-25T13:34:31.892398 | 2020-10-04T23:34:43 | 2020-10-04T23:34:43 | 301,128,391 | 1 | 0 | null | 2020-10-04T23:34:44 | 2020-10-04T12:48:13 | C++ | UTF-8 | C++ | false | false | 696 | cpp | main.cpp | #include "MudEngine.hpp"
#define VERSION_MAJOR 0
#define VERSION_MINOR 1
// TODO: Logging system
// This is epic, thank you very cool
// wow much comment
// on a serious note, i can do this, i have a logging system i need to fix first though
int main( int argc, char** argv )
{
MudEngine mudEngine;
SettupANSI();
std::cout << "Welcome to the CollabMud v"
<< VERSION_MAJOR << "." << VERSION_MINOR
<< std::endl << std::endl << std::endl;
mudEngine.NetInit();
// TODO: add a delay to ready or checks
// so that it does not start while other
// threads are still starting up
mudEngine.Ready();
// Prevent closing
//getchar();
return 0;
}
|
b55db3ccf65e684b4a6df5eba78c6401fdd5cfc8 | 1439f3f81b1f98772a522f88357a4fc988f640e2 | /classes/PlaneUserData.cpp | e7a28fb11b6fa6b38e4cae092ecb64aaf635387c | [] | no_license | jybhaha/plane | a993392b85620af8cd262c33f531171f13adcb54 | 0be61dd885575e18c6d95dbd529fe424cb858076 | refs/heads/master | 2021-01-10T09:35:29.401062 | 2015-12-20T13:40:25 | 2015-12-20T13:40:25 | 48,314,685 | 12 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | PlaneUserData.cpp | #include "PlaneUserData.h"
#include "cocos2d.h"
PlaneUserData::PlaneUserData(int initHP):HP(initHP){
}
bool PlaneUserData::isAliveUnderAttack(int damage){
this->HP -= damage;
if(this->HP <= 0){
return false;
}else{
return true;
}
}
int PlaneUserData::getHP() const{
return this->HP;
}
void PlaneUserData::addBlood(int num){
this->HP += num;
} |
34b32ffd29fe7aec5e515d8045461e541f13002d | b1de5e065b7951ae4fb5594d5dce025f8c417fc4 | /utilities/matrix.cpp | 223d4b37ae2327cbad6f3d9129c7dafb7b4f0a61 | [] | no_license | KarimIO/Linear-Algebra-Math-Library-Test | 59e629bacb91b71c7c68e86922d1a05a39742e18 | 9232e2516f76e7305e5670b91e8953d63f642d74 | refs/heads/master | 2021-08-24T06:48:14.159773 | 2017-12-08T13:26:20 | 2017-12-08T13:26:20 | 107,056,488 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | matrix.cpp | #include "matrix.hpp"
#include <iostream>
Matrix::Matrix(float i) : mat_ {
{i, 0.0f, 0.0f, 0.0f},
{0.0f, i, 0.0f, 0.0f},
{0.0f, 0.0f, i, 0.0f},
{0.0f, 0.0f, 0.0f, i}
} {
}
const float * const Matrix::getMatrix() {
return &mat_[0][0];
}
/*Matrix::Matrix(Vector a1, Vector a2, Vector a3, Vector a4) : mat_ {
{a1.X(), a1.Y(), a1.Z(), a1.W()},
{a2.X(), a2.Y(), a2.Z(), a2.W()},
{a3.X(), a3.Y(), a3.Z(), a3.W()},
{a4.X(), a4.Y(), a4.Z(), a4.W()}} {
}*/
Matrix::Matrix( float a11, float a12, float a13, float a14,
float a21, float a22, float a23, float a24,
float a31, float a32, float a33, float a34,
float a41, float a42, float a43, float a44) : mat_ {
a11, a12, a13, a14,
a21, a22, a23, a24,
a31, a32, a33, a34,
a41, a42, a43, a44
} {
}
Matrix Matrix::operator+(const Matrix &r) const {
Matrix out;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
out[i][j] = mat_[i][j] + r.mat_[i][j];
}
}
return out;
}
Matrix Matrix::operator-(const Matrix &r) const {
Matrix out;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
out[i][j] = mat_[i][j] - r.mat_[i][j];
}
}
return out;
}
Matrix Matrix::operator*(const Matrix &r) const {
Matrix out;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
out[i][j] = mat_[i][0] * r.mat_[0][j];
for (int k = 1; k < 4; ++k) {
out[i][j] += mat_[i][k] * r.mat_[k][j];
}
}
}
return out;
}
void Matrix::print() const {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
std::cout << mat_[i][j] << " ";
}
std::cout << "\n";
}
}
float* Matrix::operator[](long unsigned int p) {
return mat_[p];
}
const float* Matrix::operator[](long unsigned int p) const {
return mat_[p];
} |
c7c302d81fd76eed7416ccd906bea645bf3d0ae9 | 8807f174a180d86d8c9d16bc644deec052f2b0d3 | /data_structure/persistent_stack.cpp | ae4620acdf7e0550609aad144aa8b9266590553c | [
"CC0-1.0"
] | permissive | noshi91/Library | 38fe0d628074db07e13e4644ded0ac815c28b82d | 991c68f07261b88f1fb90abe1d588844d710ec38 | refs/heads/master | 2023-03-05T09:44:37.417970 | 2023-02-26T05:39:40 | 2023-02-26T05:39:40 | 124,523,531 | 35 | 8 | null | 2020-03-05T01:00:03 | 2018-03-09T10:07:43 | C++ | UTF-8 | C++ | false | false | 947 | cpp | persistent_stack.cpp | #include <cassert>
#include <memory>
#include <utility>
template <class T> class persistent_stack {
using Self = persistent_stack<T>;
class node_type;
using node_ptr = std::shared_ptr<const node_type>;
class node_type {
public:
T value;
node_ptr next;
node_type(T value, node_ptr next) : value(value), next(next) {}
};
node_ptr root;
persistent_stack(node_ptr root) : root(root) {}
public:
persistent_stack() = default;
bool empty() const { return not root; }
T top() const {
assert(not empty());
return root->value;
}
Self push(T x) const {
return Self(std::make_shared<const node_type>(x, root));
}
Self pop() const {
assert(not empty());
return Self(root->next);
}
Self reverse() const {
Self ret;
Self x = *this;
while (not x.empty()) {
ret = ret.push(x.top());
x = x.pop();
}
return ret;
}
};
/**
* @brief Persistent Stack
*/
|
7a47c0087656cd3c671434bf9339303721a1e9e3 | e6b5b881206037d76d58fdf49620b388d3ff4ec0 | /ONP.cpp | 07baffcec5e9e94985b6c9643df849368d8b0d6b | [] | no_license | hsmfawaz/UVA-Solutions-cpp | e684f005cc7461c38ccadf04f79dcf94acd02fdc | 5b56dcfbca5de8f7a21b8c0f165ade8109bbf246 | refs/heads/master | 2021-05-10T21:41:37.780423 | 2018-04-20T13:41:48 | 2018-04-20T13:41:48 | 118,236,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | ONP.cpp | #include <bits/stdc++.h>
using namespace std;
#define FastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define sz(a) int((a).size())
#define sza(a) (int)(sizeof(a)/sizeof((a)[0]))
#define all(c) (c).begin(),(c).end()
#define rep(i,a,n) for (int i=(a);i<(n);i++)
#define clr(x) memset(x,0,sizeof x)
#define ft first
#define sd second
typedef vector<int> vi;
typedef unsigned long long ll;
typedef unsigned long ul;
const int MX = 10e5 + 1;
void Solution() {
int n;
cin >> n;
while (n--) {
string s, res = "";
cin >> s;
stack<char> x;
rep(i,0,sz(s))
{
if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '^'
|| s[i] == '*')
x.push(s[i]);
else if (s[i] == ')')
res += x.top(), x.pop();
else if (s[i] != '(')
res += s[i];
}
cout << res << endl;
}
}
int main() {
FastIO;
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
Solution();
return 0;
}
|
60ad6c8c51ae624deee7b92998310326c721ad5f | ad7cbb9616b28e9d4b7fbd669c15f5281bedc5e9 | /src/codegen/llvm/Context.cpp | 523df06f8b6f5b0a8caca4321ccd64da78012d2a | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kFo/kyfoo | aa047417431cc671fe4de36ce11bd719021284aa | d510c737b8d4e2e3cd8bf91053694f756020807a | refs/heads/master | 2021-06-01T13:13:38.559533 | 2019-09-09T20:26:52 | 2019-12-05T18:03:17 | 96,374,740 | 19 | 3 | null | 2017-09-11T22:09:40 | 2017-07-06T01:18:07 | C++ | UTF-8 | C++ | false | false | 11,647 | cpp | Context.cpp | #include "Context.hpp"
#include "Visitors.hpp"
namespace kyfoo::codegen::llvm {
Context::Context(Diagnostics& dgn,
ast::ModuleSet& moduleSet,
stringv targetTriple)
: myDgn(dgn)
, myModuleSet(moduleSet)
, myContext(mk<::llvm::LLVMContext>())
{
init(mkString(targetTriple));
}
Context::~Context()
{
for ( auto& m : myModuleSet.modules() )
m->setCodegenData(nullptr);
}
void Context::write(ast::Module const& module, std::filesystem::path const& path)
{
auto m = customData(module)->module.get();
auto sourcePath = module.path();
if ( sourcePath.empty() ) {
myDgn.error(module, diag::module_no_name);
return;
}
std::error_code ec;
::llvm::raw_fd_ostream outFile(path.string(), ec, ::llvm::sys::fs::F_None);
if ( ec ) {
myDgn.error(module, diag::module_cannot_write_object_file);
// .reason(ec.message()); // todo
return;
}
::llvm::legacy::PassManager pass;
if ( myTargetMachine->addPassesToEmitFile(pass, outFile, nullptr, ::llvm::TargetMachine::CGFT_ObjectFile) ) {
myDgn.error(module, diag::module_unsupported_target);
// .subject(myTargetTriple);
return;
}
pass.run(*m);
outFile.flush();
}
void Context::writeIR(ast::Module const& module, std::filesystem::path const& path)
{
auto sourcePath = module.path();
if ( sourcePath.empty() ) {
myDgn.error(module, diag::module_no_name);
return;
}
std::error_code ec;
::llvm::raw_fd_ostream outFile(path.string(), ec, ::llvm::sys::fs::F_None);
if ( ec ) {
myDgn.error(module, diag::module_cannot_write_object_file);
// .reason(ec.message()); // todo
return;
}
customData(module)->module->print(outFile, nullptr);
}
void Context::generate(ast::Module const& module)
{
module.setCodegenData(mk<LLVMCustomData<ast::Module>>());
auto mdata = customData(module);
mdata->module = mk<::llvm::Module>(mkString(module.name()), *myContext);
mdata->module->setTargetTriple(myTargetTriple);
mdata->module->setDataLayout(*myDefaultDataLayout);
ast::ShallowApply<CodeGenPass> gen(myDgn, *this, mdata->module.get(), module);
for ( auto d : module.templateInstantiations() )
gen(*d);
for ( auto d : module.scope()->childDeclarations() )
gen(*d);
for ( auto d : module.scope()->childLambdas() )
gen(*d);
gen.getOperator().generateProcBodies();
if ( verifyModule(*mdata->module, &::llvm::errs()) ) {
#ifndef NDEBUG
mdata->module->dump();
#endif
myDgn.die("LLVM module errors");
}
}
void Context::generate(ast::Declaration const& decl)
{
if ( decl.codegenData() )
return;
auto& mod = decl.scope().module();
auto mdata = customData(mod);
ast::ShallowApply<CodeGenPass> gen(myDgn, *this, mdata->module.get(), mod);
gen(decl);
}
void Context::generate(ast::DataTypeDeclaration const& dt)
{
if ( !dt.symbol().prototype().isConcrete() || dt.codegenData() )
return;
dt.setCodegenData(mk<LLVMCustomData<ast::DataTypeDeclaration>>());
auto dtData = customData(dt);
if ( auto t = intrinsicType(dt) ) {
dtData->intrinsic = t;
return;
}
auto defn = dt.definition();
if ( !defn ) {
if ( auto s = dt.super() ) {
::llvm::Type* fieldTypes[] = { toType(*s) };
constexpr auto isPacked = false;
dtData->type = ::llvm::StructType::create(
*myContext,
fieldTypes,
strRef(dt.symbol().token().lexeme()),
isPacked);
}
return;
}
ab<::llvm::Type*> fieldTypes;
auto fields = defn->fields();
auto variations = defn->variations();
{
auto n = fields.card();
if ( variations )
++n;
if ( dt.super() )
++n;
fieldTypes.reserve(n);
}
if ( dt.super() )
fieldTypes.append(toType(*dt.super()));
if ( variations ) {
auto const bits = trunc<unsigned>(log2(roundUpToPow2(variations.card())));
dtData->tagType = ::llvm::cast<::llvm::IntegerType>(myDefaultDataLayout->getSmallestLegalIntType(*myContext, bits));
fieldTypes.append(dtData->tagType);
}
for ( uz i = 0; i < fields.card(); ++i ) {
fields[i]->setCodegenData(mk<LLVMCustomData<ast::Field>>());
customData(*fields[i])->index = static_cast<u32>(i);
auto d = getDeclaration(fields[i]->type());
auto type = toType(*resolveIndirections(d));
if ( !type )
myDgn.die("type is not registered");
fieldTypes.append(type);
}
constexpr auto isPacked = false;
dtData->type = ::llvm::StructType::create(
*myContext,
arrRef(fieldTypes()),
strRef(dt.symbol().token().lexeme()),
isPacked);
if ( variations ) {
generate(*variations.front());
dtData->largestSubtype = ::llvm::cast<::llvm::StructType>(toType(*variations.front()));
uz size = *sizeOf(*variations.front());
for ( variations.popFront(); variations; variations.popFront() ) {
generate(*variations.front());
auto s = *sizeOf(*variations.front());
if ( s > size ) {
dtData->largestSubtype = ::llvm::cast<::llvm::StructType>(toType(*variations.front()));
size = s;
}
}
}
}
std::optional<uz> Context::sizeOf(ast::Declaration const& decl)
{
auto type = toType(decl);
if ( !type )
return {};
return myDefaultDataLayout->getTypeAllocSize(type);
}
std::optional<uz> Context::sizeOf(ast::Expression const& expr)
{
auto type = toType(expr);
if ( !type )
return {};
return myDefaultDataLayout->getTypeAllocSize(type);
}
::llvm::Type* Context::toType(ast::Declaration const& decl)
{
auto d = resolveIndirections(&decl);
if ( !d->codegenData() )
generate(*d);
if ( auto dt = d->as<ast::DataTypeDeclaration>() ) {
auto dtData = customData(*dt);
if ( dtData->intrinsic )
return dtData->intrinsic;
return dtData->type;
}
return nullptr;
}
::llvm::Type* Context::toType(ast::Expression const& expr)
{
auto e = resolveIndirections(&expr);
if ( auto decl = getDeclaration(*e) )
return toType(*decl);
if ( auto t = e->as<ast::TupleExpression>() ) {
if ( !t->expressions() && t->kind() == ast::TupleKind::Open )
return ::llvm::Type::getVoidTy(*myContext);
::llvm::Type* elementType = nullptr;
if ( t->expressions().card() > 1 ) {
ab<::llvm::Type*> types;
types.reserve(t->expressions().card());
for ( auto const& te : t->expressions() )
types.append(toType(*te));
elementType = ::llvm::StructType::get(*myContext, arrRef(types()));
}
else {
elementType = toType(*t->expressions()[0]);
}
if ( t->elementsCount() > 1 )
return ::llvm::ArrayType::get(elementType, t->elementsCount());
return elementType;
}
if ( auto a = e->as<ast::ArrowExpression>() ) {
enum { NotVarArg = false };
ab<::llvm::Type*> params;
if ( auto tup = a->from().as<ast::TupleExpression>() ) {
if ( !tup->expressions() )
return ::llvm::PointerType::getUnqual(::llvm::FunctionType::get(toType(a->to()), NotVarArg));
if ( tup->kind() == ast::TupleKind::Open ) {
params.reserve(tup->expressions().card());
for ( auto texpr : tup->expressions() )
params.append(toType(*texpr));
}
}
if ( !params )
params.append(toType(a->from()));
return ::llvm::PointerType::getUnqual(::llvm::FunctionType::get(toType(a->to()), arrRef(params()), NotVarArg));
}
return nullptr;
}
::llvm::Type* Context::intrinsicType(ast::Declaration const& decl)
{
auto dt = decl.as<ast::DataTypeDeclaration>();
if ( !dt )
return nullptr;
auto dtData = customData(*dt);
if ( dtData->intrinsic )
return dtData->intrinsic;
if ( dt == axioms().intrinsic(ast::intrin::type::IntegerLiteralType )
|| dt == axioms().intrinsic(ast::intrin::type::RationalLiteralType) )
{
dtData->intrinsic = (::llvm::Type*)0x1; // todo: choose width based on expression
return dtData->intrinsic;
}
auto const& sym = dt->symbol();
if ( rootTemplate(sym) == &axioms().intrinsic(ast::intrin::type::PointerTemplate )->symbol()
|| rootTemplate(sym) == &axioms().intrinsic(ast::intrin::type::ReferenceTemplate)->symbol() )
{
auto t = toType(*sym.prototype().pattern().front());
if ( t->isVoidTy() )
dtData->intrinsic = ::llvm::Type::getInt8PtrTy(*myContext);
else
dtData->intrinsic = ::llvm::PointerType::getUnqual(t);
return dtData->intrinsic;
}
if ( dt == axioms().intrinsic(ast::intrin::type::u1 ) ) return dtData->intrinsic = ::llvm::Type::getInt1Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::u8 ) ) return dtData->intrinsic = ::llvm::Type::getInt8Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::u16 ) ) return dtData->intrinsic = ::llvm::Type::getInt16Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::u32 ) ) return dtData->intrinsic = ::llvm::Type::getInt32Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::u64 ) ) return dtData->intrinsic = ::llvm::Type::getInt64Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::u128) ) return dtData->intrinsic = ::llvm::Type::getInt128Ty(*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::s8 ) ) return dtData->intrinsic = ::llvm::Type::getInt8Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::s16 ) ) return dtData->intrinsic = ::llvm::Type::getInt16Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::s32 ) ) return dtData->intrinsic = ::llvm::Type::getInt32Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::s64 ) ) return dtData->intrinsic = ::llvm::Type::getInt64Ty (*myContext);
else if ( dt == axioms().intrinsic(ast::intrin::type::s128) ) return dtData->intrinsic = ::llvm::Type::getInt128Ty(*myContext);
return nullptr;
}
void Context::init(std::string targetTriple)
{
/*
InitializeAllTargetInfos();
InitializeAllTargets();
InitializeAllTargetMCs();
*/
::llvm::InitializeNativeTarget();
/*
InitializeAllAsmParsers();
*/
::llvm::InitializeNativeTargetAsmParser();
/*
InitializeAllAsmPrinters();
*/
::llvm::InitializeNativeTargetAsmPrinter();
if ( targetTriple.empty() )
targetTriple = ::llvm::sys::getDefaultTargetTriple();
myTargetTriple = std::move(targetTriple);
std::string err;
auto target = ::llvm::TargetRegistry::lookupTarget(myTargetTriple, err);
ENFORCE(target, err);
auto cpu = "generic";
auto features = "";
::llvm::TargetOptions opt;
auto rm = ::llvm::Optional<::llvm::Reloc::Model>();
myTargetMachine = target->createTargetMachine(myTargetTriple, cpu, features, opt, rm);
myDefaultDataLayout = mk<::llvm::DataLayout>(myTargetMachine->createDataLayout());
}
ast::AxiomsModule const& Context::axioms() const
{
return myModuleSet.axioms();
}
} // kyfoo::codegen::llvm
|
dd1616af4537e83b8dc8acf7830ae370586ebac8 | be175d0dd5b8fb9b9890d9305eaa963371fdaf10 | /hello.cc | c3b9cbda3be7aee5cae0e737a5858e8d3d4d0a45 | [] | no_license | subhankar7/kvstore-2pc | 274d59e5e7bf40bc4004df324d8cfb2ab8b8188d | da061054b560b4c3cb9cc0b35581511239ed5ab4 | refs/heads/master | 2021-01-10T03:31:04.012393 | 2015-12-21T02:26:50 | 2015-12-21T02:26:50 | 48,346,141 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,111 | cc | hello.cc | /* Example Usage. This is the client using the coordinator service through local RPC calls */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <grpc++/grpc++.h>
#include <sys/stat.h>
#include <time.h>
#include "greeter_client.h"
#include "helloworld.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
static GreeterClient *ctx;
unsigned long
hash(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
int main(int argc, char *argv[])
{
GreeterClient greeter(
grpc::CreateChannel("localhost:12348", grpc::InsecureCredentials()));
ctx = &greeter;
char path[PATH_MAX];
/* for (int i=0; i<10; i++) {
sprintf(path, "nhello%d", i);
for(int j=0; j<10; j++) {
ctx->Store(std::string(path), (const char *)"Hello World", strlen("Hello World"));
}
} */
struct timespec before, after, delta;
clock_gettime(CLOCK_MONOTONIC, &before);
ctx->Store("nhello", (const char *)"Hello World", strlen("Hello World"));
clock_gettime(CLOCK_MONOTONIC, &after);
//ctx->Delete(std::string(path));
delta = diff(before, after);
printf("%llu\n", delta.tv_sec*1000000000LLU+delta.tv_nsec);
char *buf;
int size;
int rc = ctx->Fetch("nhello", &buf, &size);
printf("%s\n", buf);
return 0;
}
|
a31382a4a184d95ddf31c030e2d88ba2a969075f | 25f5ab0e299755cdd6df226bca602f3b774ca963 | /src/test/bz2search_test.cc | ee2758fb649d2580d01b9be01c73148deedceafa | [] | no_license | takada-at/logbinsearch | 886f61ec55404e7a137679e3d672d3b5a7569146 | d4e5b8948f6bf66b1bd81307d67aa338fc766433 | refs/heads/master | 2021-01-10T19:51:27.671113 | 2015-02-16T09:37:29 | 2015-02-16T09:37:29 | 30,334,729 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,119 | cc | bz2search_test.cc | extern "C"
{
#include "bz2search.c"
}
#include <Python.h>
#include "gtest/gtest.h"
#include <stdio.h>
#define SAMPLE "../../logbinsearch/test/sample/sample.bz2"
#define SAMPLE2 "../../logbinsearch/test/sample/sample_1block.bz2"
TEST(AddTest, Test1)
{
ASSERT_EQ(2, 1+1);
}
TEST(getBitsTest, Test1)
{
FILE *file = fopen(SAMPLE, "r");
if (file == NULL) {
printf("fopen error\n");
exit(EXIT_FAILURE);
}
BitStream* bs = (BitStream*)malloc( sizeof(BitStream) );
bs->file = file;
bs->buffer = 0;
bs->buffsize = 0;
int b = 0, i = 24;
for(i=0; i< 24; ++i){
b = (b<<1) | (getBits(bs) & 1);
}
ASSERT_EQ(4348520, b);
fclose(file);
free(bs);
}
TEST(BZ2SearchTest, Test1)
{
FILE *fp;
BlockReader *self;
int res;
PyObject *p;
Py_Initialize();
printf(SAMPLE"\n");
fp = fopen(SAMPLE, "rb");
if (fp == NULL) {
printf("fopen error\n");
exit(EXIT_FAILURE);
}
int fd = fileno(fp);
self = (BlockReader*)malloc(sizeof(BlockReader));
if (self == NULL){
printf("malloc error\n");
exit(EXIT_FAILURE);
}
long pos = bz2s_searchBlock(fp, 5);
ASSERT_LT(100, pos);
lseek( fd, 0, SEEK_SET );
printf("pos: %ld\n", pos);
res = bz2s_initBlock(self, fd, pos);
ASSERT_EQ(0, res);
ASSERT_NE((bunzip_data*)NULL, self->bd);
p = Reader_iternext(self);
ASSERT_NE((PyObject*)NULL, p);
long pos2, prev;
pos2 = 0;
prev = pos2;
while(1){
fp = fopen(SAMPLE, "rb");
pos2 = bz2s_searchBlock(fp, (prev+8)/8);
printf("prev: %ld, pos2: %ld\n", prev, pos2);
if(pos2==prev)
break;
if(pos2<0)
break;
prev = pos2;
}
ASSERT_EQ(-1, pos2);
lseek( fd, 0, SEEK_SET );
printf("prev: %ld\n", prev);
res = bz2s_initBlock(self, fd, prev);
ASSERT_EQ(0, res);
ASSERT_NE((bunzip_data*)NULL, self->bd);
ASSERT_NE((PyObject*)NULL, p);
while(p!=NULL){
p = Reader_iternext(self);
}
free(self);
ASSERT_FALSE(PyErr_Occurred());
if (PyErr_Occurred())
PyErr_Print();
}
TEST(BZ2SearchTest2, Test1)
{
FILE *fp;
BlockReader *self;
PyObject *p;
int res;
Py_Initialize();
printf(SAMPLE2"\n");
fp = fopen(SAMPLE2, "rb");
if (fp == NULL) {
printf("fopen error\n");
exit(EXIT_FAILURE);
}
self = (BlockReader*)malloc(sizeof(BlockReader));
if (self == NULL){
printf("malloc error\n");
exit(EXIT_FAILURE);
}
long pos = bz2s_searchBlock(fp, 0);
ASSERT_EQ(32, pos);
fp = fopen(SAMPLE2, "rb");
int fd = fileno(fp);
lseek( fd, 0, SEEK_SET );
res = bz2s_initBlock(self, fd, pos);
ASSERT_EQ(0, res);
ASSERT_NE((bunzip_data*)NULL, self->bd);
p = Reader_iternext(self);
ASSERT_NE((PyObject*)NULL, p);
PyObject *pyfile = PyFile_FromFile(fp, SAMPLE2, "r", fclose);
res = bz2s_reset(self, pyfile, 0);
ASSERT_EQ(0, res);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
3d8b4c667905675344dda180630737f147bd6f7d | 0f14f6febcf7b065716d3b08f18189b1381d43b7 | /MatchCatalogue.cpp | 161c8acb5152c3810514e0e53b28a5881c6a0af5 | [] | no_license | Varinara/FootballTicketingSystem | 6d0e4c0dcfcfa5af88ff4eee80fb0be34387818d | 7a1ed25acd5c2c7b770a80389e6996dcdc0db0db | refs/heads/main | 2023-04-15T12:26:40.981323 | 2021-04-08T10:05:53 | 2021-04-08T10:05:53 | 355,853,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | cpp | MatchCatalogue.cpp | #pragma once
#include <bits/stdc++.h>
#include "Match.cpp"
using namespace std;
class MatchCatalogue {
public:
vector<Match> matches;
vector<Place> emptyStadiumMap;
public:
MatchCatalogue(vector<Place> newEmptyStadiumMap) {
emptyStadiumMap = newEmptyStadiumMap;
matches = vector<Match>();
}
public:
void AddMatch(string matchName, time_t date) {
matches.emplace_back(Match(matches.size(), matchName, emptyStadiumMap, date));
}
public:
void WriteMatchces() {
for (auto iter = matches.begin(); iter != matches.end(); iter++)
iter->writeMatch();
}
}; |
8a90f1a443df16d29c0d40b8f8efe1b6889f956a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_3579_git-2.14.0.cpp | ffc18f0e3f0da5d033d9bdd693591b6ad5249f95 | [] | 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 | 150 | cpp | git_repos_function_3579_git-2.14.0.cpp | static time_t rerere_created_at(struct rerere_id *id)
{
struct stat st;
return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
} |
4c66c688c850192da3b3c34506df2fffe67ad397 | 78501600c7dc1616c99fad9b151baf070595db52 | /src/SalmonEngineAndroid.cpp | 2abaaacde56b167cc39684cd0a3ba54ae1f99797 | [] | no_license | mephi1984/tes-engine | a9c3c52c49924eb2d0da03be23b48a52e67a4616 | 4cfc6e91cc3749d4c099c5fd8d6214c90e966cf9 | refs/heads/master | 2023-05-31T08:21:35.654767 | 2017-09-05T08:18:08 | 2017-09-05T08:18:08 | 379,933,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | SalmonEngineAndroid.cpp | #include "include/SalmonEngineAndroid.h"
#include "include/Utils/Utils.h"
namespace SE
{
void CreateEngine()
{
Console = new TJavaConsole;
*Console<<std::string("Console successfully started!!!");
ResourceManager = new TResourceManager;
Renderer = new TSalmonRendererAndroid;
}
void DestroyEngine()
{
if (ResourceManager != NULL)
{
delete ResourceManager;
ResourceManager = NULL;
}
if (Console != NULL)
{
*Console<<"Resource manager deleted, deleting salmon render";
}
if (Renderer != NULL)
{
delete Renderer;
Renderer = NULL;
}
if (Console != NULL)
{
*Console<<"salmon render deleted";
}
if (Console != NULL)
{
delete Console;
Console = NULL;
}
}
} //namespace SE |
826189c4917fd6afba0d1b7d6b087c4ab28deba0 | 4051dc0d87d36c889aefb2864ebe32cd21e9d949 | /Algos Practice/A Distance Maximizing Problem.cpp | 7faa67e9df2d574a8c87f9a67a2a73077f63bc76 | [] | no_license | adityax10/ProgrammingCodes | e239971db7f3c4de9f2b060434a073932925ba4d | 8c9bb45e1a2a82f76b66f375607c65037343dcd9 | refs/heads/master | 2021-01-22T22:53:01.382230 | 2014-11-07T10:35:00 | 2014-11-07T10:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | cpp | A Distance Maximizing Problem.cpp | #include<bits/stdc++.h>
using namespace std;
/*
Given an array A of integers, find the maximum of j-i subjected to the constraint of A[i] < A[j].
*/
int cmp(const pair<int,int> &a,const pair<int,int> &b)
{
if(a.first == b.first)
return a.second<b.second;
return a.first < b.first;
}
int main()
{
// O(nlog(n))
vector< pair<int,int> > v;
int a[] = {4,5,2,1,3,2,3};
int n = sizeof(a)/sizeof(int);
for(int i=0;i<n;i++)
{
v.push_back(make_pair(a[i],i));
}
sort(v.begin(),v.end(),cmp);
for(int i=0;i<n;i++)
{
cout<<v[i].first<<" "<<v[i].second<<endl;
}
int min_index = v[0].second;
int max_diff = 0;
for(int i=1;i<n;i++)
{
min_index = min ( min_index , v[i].second);
max_diff = max ( max_diff, v[i].second - min_index );
}
cout<<max_diff<<endl;
return 0;
}
|
aa60f34f80058deb67816c253c072a71f36856c6 | d39640cc5486ac05ac3c50cfb3715a70df07eba9 | /bebas.h | 51d77969d94f5b2ef6d8b289dbc4222a12d516e9 | [] | no_license | Hadiid164/Magang | e183d543406f825129d0370884de1a97e0de4d8a | 22f6ef0bb4c0b09f58528056265655ac201ea1ef | refs/heads/master | 2021-01-08T02:05:06.223728 | 2020-02-23T04:07:28 | 2020-02-23T04:07:28 | 241,880,673 | 0 | 0 | null | 2020-02-20T12:39:19 | 2020-02-20T12:39:19 | null | UTF-8 | C++ | false | false | 1,474 | h | bebas.h | /* File : bebas.h */
/* Tanggal : 21 Februari 2020 */
/* Topik : Tugas cakru programming pandago pertama */
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sstream>
#ifndef BEBAS_H
#define BEBAS_H
#include "boolean.h"
string ke_str(int N){
string z;
z.push_back((char)(N+'0'));
return z;
}
void PrintHaiNTimes (int N){
/* Menulis "Hai" diakhiri newline sebanyak N kali */
int i = 0;
while(i<N){
printf("Hai\n");
i += 1;
}
}
void GanjilOrGenap (int X){
/* Jika X adalah bilangan ganjil maka muncul pesan
*/
/* std::string Xstr = to_string(X);
*/
string Xstr = ke_str(X);
if(X%2==0){
cout<<Xstr +" adalah bilangan genap"<<endl;
}
else{
cout<<Xstr + " adalah bilangan ganjil\n"<<endl;
}
}
int DeretArit50 ();
/* Menghasilkan nilai dari
1 + 2 + 3 + ... + 50 */
/* Harus dikerjakan menggunakan sistem looping (for atau while) */
void ModNumber (int X, int Y){
/* Mengirimkan hasil dari X mod Y ke layar (diakhiri newline) */
/* Contoh : X = 10; Y = 3
Output :
Hasil dari 10 mod 3 adalah 1 */
int Z = Z%Y;
cout<<"Hasil dari " +ke_str(X) + " mod "+ke_str(Y)+" adalah " ke_str(Z)<<endl;
}
int TambahOrKurang (int A, int B, int C);
/* Jika A adalah ganjil maka menghasilkan nilai dari
pertambahan B dan C */
/* Jika sebaliknya maka menghasilkan pengurangan dari B oleh C */
boolean IsPrima (int X);
/* Mengirimkan true jika X adalah bilangan prima */
/* Asumsi : X <= 10 */
#endif |
3f61718a6380dfd6efed769cb9331fa5653ec1c8 | df00e15e314e15bc4b99f76d5cd2468ed8c1af41 | /medium/29_divide_two_integer.cpp | 941b831953840350610f23a6e7e5028782076d93 | [] | no_license | wangkainlp/leetcode | 2265174ee5f4413c3b0df7dcd438b56b96d1b678 | f31249b0742f9f3d00b9f22595c68e2c5430534d | refs/heads/master | 2020-06-01T08:03:08.485189 | 2019-10-30T02:50:18 | 2019-10-30T02:50:18 | 190,711,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,656 | cpp | 29_divide_two_integer.cpp | #include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
#include <climits>
using namespace std;
class Solution {
public:
long positive_divide(long dividend, long divisor) {
if (divisor == 1) { return dividend; }
if (dividend == 0) { return 0L; }
if (dividend == divisor) {
return 1L;
} else if (dividend < divisor) {
return 0L;
}
int nums[11];
memset(nums, 0, 11 * sizeof(int));
int idx = 0;
int num = dividend;
while (num > 0) {
int n = num % 10;
num = num / 10;
nums[idx++] = n;
}
int nums_[11];
memset(nums_, 0, 11 * sizeof(int));
idx = 0;
num = dividend;
while (num > 0) {
int n = num % 10;
num = num / 10;
nums[idx++] = n;
}
long num = dividend;
long sum = 0;
long quotient = 0;
for (long i = 1; i <= INT_MAX&& sum <= dividend; ++i) {
sum += divisor;
quotient++;
// cout << "sum:" << sum << endl;
if (sum >= dividend) {
break;
}
}
if (sum == dividend) {
// pass
} else {
quotient--;
}
// cout << "quotient:" << quotient << endl;
return quotient;
}
int divide(int dividend, int divisor) {
if (dividend == 0) { return 0; }
int flag = (dividend >> 31) & 0x01;
if (dividend > 0) {
if (divisor > 0) {
flag = 1;
} else {
flag = -1;
}
} else {
if (divisor > 0) {
flag = -1;
} else {
flag = 1;
}
}
long dividend_L = dividend;
long divisor_L = divisor;
dividend_L = abs(dividend_L);
divisor_L = abs(divisor_L);
long quotient = positive_divide(dividend_L, divisor_L);
// cout << "flag:" << flag << endl;
// cout << "quotient:" << quotient << endl;
quotient = flag * quotient;
if (quotient > INT_MAX) {
quotient = INT_MAX;
}
if (quotient < INT_MIN) {
quotient = INT_MIN;
}
return quotient;
}
};
int main() {
int a = 10;
int b = 3;
cout << a << "/" << b << endl;
cout << Solution().divide(a, b) << endl;;
cout << Solution().divide(-2147483648, -1) << endl;;
cout << Solution().divide(7, -3) << endl;;
cout << Solution().divide(-2147483648, 2) << endl;;
return 0;
}
|
4526e270aacac485ffee1d9ba5d906347fc0ce14 | 8194c153de598eaca637559443f71d13b729d4d2 | /ogsr_engine/xrGame/character_community.h | 76f965ac2b4f3263aa759456899556d4a6dac83f | [
"Apache-2.0"
] | permissive | NikitaNikson/X-Ray_Renewal_Engine | 8bb464b3e15eeabdae53ba69bd3c4c37b814e33e | 38cfb4a047de85bb0ea6097439287c29718202d2 | refs/heads/dev | 2023-07-01T13:43:36.317546 | 2021-08-01T15:03:31 | 2021-08-01T15:03:31 | 391,685,134 | 4 | 4 | Apache-2.0 | 2021-08-01T16:52:09 | 2021-08-01T16:52:09 | null | UTF-8 | C++ | false | false | 2,032 | h | character_community.h | //////////////////////////////////////////////////////////////////////////
// character_community.h: структура представления группировки
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "ini_id_loader.h"
#include "ini_table_loader.h"
#include "character_info_defs.h"
struct COMMUNITY_DATA
{
COMMUNITY_DATA (CHARACTER_COMMUNITY_INDEX, CHARACTER_COMMUNITY_ID, LPCSTR);
CHARACTER_COMMUNITY_ID id;
CHARACTER_COMMUNITY_INDEX index;
u8 team;
};
class CHARACTER_COMMUNITY;
class CHARACTER_COMMUNITY:
public CIni_IdToIndex<1, COMMUNITY_DATA, CHARACTER_COMMUNITY_ID, CHARACTER_COMMUNITY_INDEX, CHARACTER_COMMUNITY>
{
private:
typedef CIni_IdToIndex<1, COMMUNITY_DATA, CHARACTER_COMMUNITY_ID, CHARACTER_COMMUNITY_INDEX, CHARACTER_COMMUNITY> inherited;
friend inherited;
public:
CHARACTER_COMMUNITY ();
~CHARACTER_COMMUNITY ();
void set (CHARACTER_COMMUNITY_ID);
void set (CHARACTER_COMMUNITY_INDEX index) {m_current_index = index;};
CHARACTER_COMMUNITY_ID id () const;
CHARACTER_COMMUNITY_INDEX index () const {return m_current_index;};
u8 team () const;
private:
CHARACTER_COMMUNITY_INDEX m_current_index;
static void InitIdToIndex ();
public:
//отношение между группировками
static CHARACTER_GOODWILL relation (CHARACTER_COMMUNITY_INDEX from, CHARACTER_COMMUNITY_INDEX to);
CHARACTER_GOODWILL relation (CHARACTER_COMMUNITY_INDEX to);
static float sympathy (CHARACTER_COMMUNITY_INDEX);
static void DeleteIdToIndexData ();
private:
typedef CIni_Table<CHARACTER_GOODWILL, CHARACTER_COMMUNITY> GOODWILL_TABLE;
friend GOODWILL_TABLE;
static GOODWILL_TABLE m_relation_table;
//таблица коэффициентов "сочуствия" между участниками группировки
typedef CIni_Table<float, CHARACTER_COMMUNITY> SYMPATHY_TABLE;
friend SYMPATHY_TABLE;
static SYMPATHY_TABLE m_sympathy_table;
}; |
426aa07dd05f3445b281e3e35881fb4240ee60ee | 4e97e81fc5d896c58666368609a1536300bb9323 | /OpenCLTutorial/main.cpp | 42f924ad8d0dcab9cbdcc358f4c51ff63efc8142 | [] | no_license | tkhubert/OpenCL | 54f1c6b0e7ec5797975d65e8b6c16151aec3713f | 96cfa6c05dc06d045c1a6e52e795bd9cc60b1990 | refs/heads/master | 2021-01-10T02:39:04.454832 | 2015-05-21T20:01:21 | 2015-05-21T20:01:21 | 36,034,442 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | main.cpp | //
// main.cpp
// OpenCLTutorial
//
// Created by Thomas Hubert on 01/04/2015.
// Copyright (c) 2015 Thomas Hubert. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[])
{
//DeviceInfo();
//VectAdd_C();
return 0;
}
|
5f27bbc514f601495b0b7ce6aeb0935af0d6435c | 57040e855ec1d81b8e6ae3d9db8cbecc1bb0a0e2 | /C++/算法/知中后序遍历.cpp | b3d26930915d43ac746ce665444e6018c264c6af | [] | no_license | TRLVMMR/algorithm | 32f2a06fef0228c98766bb4a19895eed737d2602 | b11f4096f234efe0473e4adc096a02e0ef1e4fa7 | refs/heads/master | 2020-03-18T17:36:41.174465 | 2018-12-02T13:49:25 | 2018-12-02T13:49:25 | 135,039,099 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,802 | cpp | 知中后序遍历.cpp | /*
思路总结:
*使用分治法建树--------从大树分成子树,从子树建成大树
*每次分治都得保证两个数组里元素一样------------每次都是某颗子树的中后序遍历
将数组分割-----------分出左右子树
*后序遍历last元素为root
中序分治 :*知道root,就在中序遍历中分左右子树
后序分治 :
*右子树len = 后序遍历中右儿子 - 左儿子 - 1
*左子树len = 左边的到左儿子
*/
#include<cstdio>
#include<iostream>
#include<queue>
#define MAXV 256
using namespace std;
struct Node
{
int date;
Node *rchild, *lchild;
Node(int key)
{
date = key;
lchild = rchild = NULL;
}
Node()
{
lchild = rchild = NULL;
}
};
int post_order[MAXV], in_order[MAXV];
//在中序遍历中找到根节点位置
int find_root(int root, int L, int R)
{
for(int i = L; i <= R; i++)
{
if(in_order[i] == root)
{
return i;
}
}
}
//将post数组分段, 即在post_inder中找到下一个root的位置(也即现在root的儿子)
int cur_lchild(int Rp, int Li, int Ri)
{
//右子树长度
int len = Ri - Li + 1;
//左子树位置
return Rp - len;
}
//分治递归建树 ,需保持in_order与post_order数组里的节点相同
Node* create_tree(int Lp, int Rp, int Li, int Ri)
{
//先分治成一个个的节点,再合起来建树
if(Lp > Rp || Li > Ri)
return NULL;
//把post_order最后一个节点给root
Node *root = new Node(post_order[Rp]);
/*
将in_order数组分段成左右子树
根据根节点左右边分即可
*/
int inRoot = find_root(root->date, Li, Ri);
/*
将post_order数组,分段成左右子树
右儿子为:根节点 - 1
左儿子为:右儿子 - 右子树长度
*/
int postLchild = cur_lchild(Rp, inRoot, Ri);
//post里,右儿子为root - 1,左儿子为右儿子减右子树长度
root->lchild = create_tree(Lp, postLchild, Li, inRoot - 1);
root->rchild = create_tree(postLchild + 1, Rp - 1, inRoot + 1, Ri);
return root;
}
//层续遍历
void bfs(Node* root)
{
queue<Node*> q;
q.push(root);
cout << root->date;
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp->lchild != NULL)
{
cout << " " << temp->lchild->date;
q.push(temp->lchild);
}
if(temp->rchild != NULL)
{
cout << " " << temp->rchild->date;
q.push(temp->rchild);
}
}
cout << endl;
}
int main()
{
int n;
freopen("树中后序遍历.in", "r", stdin);
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> in_order[i];
}
for(int i = 0; i < n; i++)
{
cin >> post_order[i];
}
Node *root = create_tree(0, n-1, 0, n-1);
bfs(root);
//此程序比较短,因此就不删除节点了
return 0;
}
|
6d6a6d2b96085634c4a14b34d581c0bac3a39113 | 1de7a240da831a499d8a3092a390edb8c04dd83e | /backup/work/Calculate.h | 65d40c2375addc7688752dc60b1b762465e67699 | [] | no_license | wxxhub/OpenCV_Experiment | c7e5410899278f765399d86102d0263130e24a26 | 7b67a044f8ea528e62201d789a6f70aeda23dbb4 | refs/heads/master | 2020-03-30T03:51:21.804303 | 2018-10-18T08:14:23 | 2018-10-18T08:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | h | Calculate.h | // Calculate.h: interface for the CCalculate class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CALCULATE_H__16AFB289_7C32_4DE5_9BA4_093E8A38B03B__INCLUDED_)
#define AFX_CALCULATE_H__16AFB289_7C32_4DE5_9BA4_093E8A38B03B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CCalculate
{
public:
CCalculate();
virtual ~CCalculate();
void SetSegmentalPoint(int p_x, int p_y, int a_x, int a_y);
int GetSegmentalProvess(int value);
void GetSegmentalProvess(int &b, int &g, int &r);
private:
struct SegmentPoint
{
int first_x_;
int first_y_;
int second_x_;
int second_y_;
};
SegmentPoint segment_point_;
};
#endif // !defined(AFX_CALCULATE_H__16AFB289_7C32_4DE5_9BA4_093E8A38B03B__INCLUDED_)
|
924f70b974fa2702c729261d0b1482dbe383e45a | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/ue/sys/database/C_SDSTableLoadingContext.h | 8d55c06419026742d441bf2621803417e5d545fc | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 705 | h | C_SDSTableLoadingContext.h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <ue/sys/core/I_SDSLoadingContext.h>
namespace ue
{
namespace sys
{
namespace database
{
/** ue::sys::database::C_SDSTableLoadingContext (VTable=0x01E87C40) */
class C_SDSTableLoadingContext : public ue::sys::core::I_SDSLoadingContext
{
public:
virtual void vfn_0001_BD6F42C7() = 0;
virtual void vfn_0002_BD6F42C7() = 0;
virtual void vfn_0003_BD6F42C7() = 0;
virtual void vfn_0004_BD6F42C7() = 0;
virtual void vfn_0005_BD6F42C7() = 0;
virtual void vfn_0006_BD6F42C7() = 0;
virtual void vfn_0007_BD6F42C7() = 0;
virtual void vfn_0008_BD6F42C7() = 0;
};
} // namespace database
} // namespace sys
} // namespace ue
|
6cbe48da5da5aa77efcb453f662cb8271ca1f5a8 | 93376006df2e645ae7406ff739aa43643df9b3d5 | /CODE/testeng.cpp | 803f4d5b249e9bd2f1d13a0a9ec2f9981a5a233b | [] | no_license | omer4d/OldCodeBackup | fd5f84e660cc91ab32cb08032848f779ced66053 | d836c14006fa72f6e660bcf39d2315e69dc292f8 | refs/heads/master | 2021-01-10T05:54:20.340232 | 2015-12-13T14:44:10 | 2015-12-13T14:44:10 | 47,922,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,599 | cpp | testeng.cpp | #include <stdio.h>
#include <conio.h>
#include <math.h>
#include <atomic>
#include <map>
#include <functional>
#include <allegro.h>
#include <list>
#include <tuple>
#include <vector>
#include "Buffer.hpp"
BITMAP* buffer;
#define PIXEL(bmp, x, y) ((long*)(bmp)->line[(y)])[(x)]
void init()
{
allegro_init();
install_mouse();
install_keyboard();
set_color_depth(32);
set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800, 600, 0, 0);
buffer = create_bitmap(SCREEN_W, SCREEN_H);
}
void deinit()
{
destroy_bitmap(buffer);
}
void crash(char const* msg)
{
printf("%s\n", msg);
int* t = nullptr;
*t = 0;
}
class Entity;
class Component {
Entity* owner;
void setOwner(Entity* owner)
{
this->owner = owner;
}
public:
Entity* getOwner() const
{
return owner;
}
virtual char const* getClassName() const = 0;
Component()
{
owner = NULL;
}
virtual ~Component()
{
}
friend class Entity;
};
#define COMPONENT_START(X) class X: public Component { \
public: \
static char const* getClassNameStatic() \
{ \
return #X; \
} \
\
char const* getClassName() const \
{ \
return X::getClassNameStatic(); \
} \
\
private: \
#define COMPONENT_END };
#define DERIVED_COMPONENT_START(X, Y) class X: Y, public Component { \
public: \
static char const* getClassType() \
{ \
return #X; \
} \
\
char const* getType() const \
{ \
return X::getClassType(); \
} \
\
private: \
#define DERIVED_COMPONENT_END };
#define CLASSES(...) __VA_ARGS__
class Entity {
int mId;
bool mRequestedDeath;
int mFramesSinceDeathRequest;
std::function<void(float dt)> mLogicCallback;
std::map<std::string, Component*> mComponents;
static int generateUniqueId() // Thread-safe!
{
static std::atomic<int> id{0};
return ++id;
}
public:
Entity()
{
mId = generateUniqueId();
mRequestedDeath = false;
mFramesSinceDeathRequest = 0;
}
~Entity()
{
clearComponents();
}
int getId() const
{
return mId;
}
bool getRequestedDeath() const
{
return mRequestedDeath;
}
int getFramesSinceDeathRequest() const
{
return mFramesSinceDeathRequest;
}
void requestDeath()
{
mRequestedDeath = true;
}
void setLogicCallback(std::function<void(float dt)> logicCallback)
{
mLogicCallback = logicCallback;
}
void clearComponents()
{
for(auto& kv : mComponents)
delete kv.second;
mComponents.clear();
}
void addComponent(Component* comp)
{
if(mComponents.find(comp->getClassName()) != mComponents.end())
crash("Entity already has this component!");
mComponents[comp->getClassName()] = comp;
}
template <class T>
T* getComponent() const
{
auto kv = mComponents.find(T::getClassNameStatic());
return (kv != mComponents.end()) ? (T*)kv->second : nullptr;
}
Component* getComponent(std::string const& className)
{
auto kv = mComponents.find(className);
return (kv != mComponents.end()) ? kv->second : nullptr;
}
void logic(float dt)
{
if(mRequestedDeath)
++mFramesSinceDeathRequest;
if(mLogicCallback)
mLogicCallback(dt);
}
};
class System {
public:
virtual ~System() = 0;
virtual void addEntity(Entity* ent) = 0;
virtual void removeEntity(Entity* ent) = 0;
virtual bool caresAbout(Entity* ent) = 0;
virtual void logic(float dt) = 0;
};
class EntityManager {
std::list<Entity*> mNewEntityQueue;
std::list<Entity*> mEntities;
std::list<System*> mLogicSystems;
std::list<System*> mConstraintSystems;
void addEntityToSystems(Entity* ent)
{
for(auto logSys : mLogicSystems)
if(logSys->caresAbout(ent))
logSys->addEntity(ent);
for(auto conSys : mConstraintSystems)
if(conSys->caresAbout(ent))
conSys->addEntity(ent);
}
void removeEntityFromSystems(Entity* ent)
{
for(auto conSys : mConstraintSystems)
if(conSys->caresAbout(ent))
conSys->removeEntity(ent);
for(auto sys : mSystems)
if(sys->caresAbout(ent))
sys->removeEntity(ent);
}
void addQueuedEntities()
{
while(!mNewEntityQueue.empty())
{
Entity* ent = mNewEntityQueue.front();
addEntityToSystems(ent);
mEntities.push_back(ent);
mNewEntityQueue.pop_front();
}
}
public:
EntityManager()
{
}
~EntityManager()
{
clearEntities();
clearSystems();
}
void clearEntities()
{
for(auto ent : mEntities)
delete ent;
mEntities.clear();
}
void clearSystems()
{
for(auto sys : mSystems)
delete sys;
mSystems.clear();
}
void clearConstraints()
{
for(auto cons : mConstraints)
delete cons;
mConstraints.clear();
}
void addEntity(Entity* ent)
{
mNewEntityQueue.push_back(ent);
}
void logic(float dt)
{
addQueuedEntities();
for(auto iter = mEntities.begin(); iter != mEntities.end(); )
{
Entity* ent = *iter;
if(ent->getRequestedDeath() && ent->getFramesSinceDeathRequest() > 0)
{
removeEntityFromSystems(ent);
mEntities.erase(iter);
delete ent;
}
else
{
ent->logic(dt);
++iter;
}
}
}
};
COMPONENT_START(TestComp)
COMPONENT_END
//void mainLogicLoop()
//{
// if(object.isDead()) // c1
// doSomething();
//
// object.kill();
//
// if(object.isDead())
// removeAndDelete(object);
//
// // Problem:
// // c1 will attempt to read a field from a freed object.
//
// // Solutions:
// // 1. delay removal and destruction by one frame. Systems ignore entities if death flag is set.
// // Cons: Referring objects have to check if the referred to entity is dead each frame.
// // 2. proxy with smart ptr.
// // Cons: possibly slow.
// // 3. shared_ptr
// // Cons: no single chunk of code responsible for freeing the object.
// // 4. no direct reference. Assign each entity unique id. Do lookup/search by name or id
// // Cons: possibly slow.
// // Conclusion: avoid keeping references to other entities, use 2 or 4 when unavoidable!
//}
template <typename T>
struct ChangeTracker {
T old;
T* trackPtr;
// Problem: relies on continued existence of tracked field.
// Solutions:
// 1.
ChangeTracker(T* ptr)
{
old = *ptr;
trackPtr = ptr;
}
bool changed()
{
bool res = (old != *trackPtr);
old = *trackPtr;
return res;
}
};
int main()
{
bool exit = false;
init();
ChangeTracker<volatile int> ct(&mouse_b);
ChangeTracker<volatile int> ct2(&mouse_x);
printf("%s\n", TestComp::getClassNameStatic());
printf("%s\n", TestComp().getClassName());
Entity ent;
ent.addComponent(new TestComp());
TestComp* tc = ent.getComponent<TestComp>();
printf("%s\n", tc->getClassName());
while(!exit)
{
if(key[KEY_ESC]) exit = true;
if(ct.changed())
printf("%d\n", mouse_b);
if(ct2.changed())
printf("%d\n", mouse_x);
clear_to_color(buffer, makecol(64, 64, 64));
draw_sprite(buffer, mouse_sprite, mouse_x, mouse_y);
blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
}
deinit();
return 0;
}END_OF_MAIN()
|
7a187bc9b3f6d8a82e3f151f29cc9e85b7ad193b | 1a51e3e3ca7bc7151181b85ecaf896cee4aa37d6 | /rendering_service/vertex.cpp | 533283173f89d3b4514e13800057ad61480a6ff9 | [] | no_license | jingjing54007/mmo | f04f0c9db1cbc0c15664c476aba4fc193d91e9e9 | 3a48a719c87bc6b3557130873ae39115cca93cc0 | refs/heads/master | 2021-01-19T19:59:53.737222 | 2014-02-05T16:50:42 | 2014-02-05T16:50:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,782 | cpp | vertex.cpp | #include "stdafx.h"
#include "Vertex.h"
static char* POINTER_OFFSET(size_t i)
{
return (char*)NULL + i;
}
void create_vertex_buffer_from_array_3d(VertexBuffer* vb)
{
const static int vertex_size = sizeof(VertexData3D); // sizeof(float)*8; // x, y, z, u, v, nx, ny, nz
glActiveTexture(GL_TEXTURE0);
glGenBuffers(1, &vb->vbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vb->vbuffer);
glBufferData(GL_ARRAY_BUFFER, vertex_size * vb->len, vb->data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//printf("buffer_name = %d\n", vb->vbuffer);
glGenVertexArrays(1, &vb->varray);
glBindVertexArray(vb->varray);
{
static const VertexSemantic semantics[] = { POSITION, TEXCOORD, NORMAL, COLOR };
static const int offsets[] = { 3, 2, 3, 4 };
glBindBuffer(GL_ARRAY_BUFFER, vb->vbuffer);
{
int acc = 0;
for (size_t i = 0; i < _countof(semantics); ++i)
{
glVertexAttribPointer(semantics[i], offsets[i], GL_FLOAT, GL_FALSE, vertex_size, POINTER_OFFSET(sizeof(float)*acc));
acc += offsets[i];
}
assert(sizeof(float)*acc == sizeof(VertexData3D));
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
for (VertexSemantic vs : semantics)
{
glEnableVertexAttribArray(vs);
}
}
glBindVertexArray(0);
//printf("vert_array_name = %d\n", vb->varray);
return;
}
void create_vertex_buffer_from_heightmap_3d(VertexBuffer* vertbuf, float cellw, float cellh, int pcx, int pcy, float* pz)
{
if (!vertbuf || pcx < 2 || pcy < 2)
return;
if (vertbuf->data || vertbuf->len != 0 || vertbuf->vbuffer != 0 || vertbuf->varray != 0)
return;
int totalVertCount = (pcx - 1) * (pcy - 1) * 3 * 2;
vertbuf->data = (VertexData3D*)calloc(totalVertCount, sizeof(VertexData3D));
vertbuf->len = totalVertCount;
int vi = 0;
for (int i = 0; i < pcy-1; ++i)
{
for (int j = 0; j < pcx-1; ++j)
{
float za = *(pz + ( i * pcx) + j );
float zb = *(pz + ( i * pcx) + j + 1);
float zc = *(pz + ((i+1) * pcx) + j );
float zd = *(pz + ((i+1) * pcx) + j + 1);
float xa = cellw * j;
float xb = cellw * (j+1);
float xc = xa;
float xd = xb;
float ya = cellh * i;
float yb = ya;
float yc = cellh * (i+1);
float yd = yc;
float ua = (float) j /(pcx-1);
float ub = (float)(j+1)/(pcx-1);
float uc = ua;
float ud = ub;
float va = (float) i /(pcy-1);
float vb = va;
float vc = (float)(i+1)/(pcy-1);
float vd = vc;
//
// C +---+ D
// | /|
// | / |
// |/ |
// A +---+ B
//
// Normal for A
float ab[3] = { xb - xa, yb - ya, zb - za };
float ac[3] = { xc - xa, yc - ya, zc - za };
float abcN[3] = {
ab[1]*ac[2] - ab[2]*ac[1],
ab[2]*ac[0] - ab[0]*ac[2],
ab[0]*ac[1] - ab[1]*ac[0]
};
float abcNLen = sqrtf(abcN[0]*abcN[0] + abcN[1]*abcN[1] + abcN[2]*abcN[2]);
abcN[0] /= abcNLen;
abcN[1] /= abcNLen;
abcN[2] /= abcNLen;
// Normal for B
float bd[3] = { xd - xb, yd - yb, zd - zb };
float ba[3] = { xa - xb, ya - yb, za - zb };
float bdaN[3] = {
bd[1]*ba[2] - bd[2]*ba[1],
bd[2]*ba[0] - bd[0]*ba[2],
bd[0]*ba[1] - bd[1]*ba[0]
};
float bdaNLen = sqrtf(bdaN[0]*bdaN[0] + bdaN[1]*bdaN[1] + bdaN[2]*bdaN[2]);
bdaN[0] /= bdaNLen;
bdaN[1] /= bdaNLen;
bdaN[2] /= bdaNLen;
// Normal for C
float ca[3] = { xa - xc, ya - yc, za - zc };
float cd[3] = { xd - xc, yd - yc, zd - zc };
float cadN[3] = {
ca[1]*cd[2] - ca[2]*cd[1],
ca[2]*cd[0] - ca[0]*cd[2],
ca[0]*cd[1] - ca[1]*cd[0]
};
float cadNLen = sqrtf(cadN[0]*cadN[0] + cadN[1]*cadN[1] + cadN[2]*cadN[2]);
cadN[0] /= cadNLen;
cadN[1] /= cadNLen;
cadN[2] /= cadNLen;
// Normal for D
float dc[3] = { xc - xd, yc - yd, zc - zd };
float db[3] = { xb - xd, yb - yd, zb - zd };
float dcbN[3] = {
dc[1]*db[2] - dc[2]*db[1],
dc[2]*db[0] - dc[0]*db[2],
dc[0]*db[1] - dc[1]*db[0]
};
float dcbNLen = sqrtf(dcbN[0]*dcbN[0] + dcbN[1]*dcbN[1] + dcbN[2]*dcbN[2]);
dcbN[0] /= dcbNLen;
dcbN[1] /= dcbNLen;
dcbN[2] /= dcbNLen;
float points[][8] = {
{ xa, ya, za, ua, va, abcN[0], abcN[1], abcN[2] }, // A
{ xb, yb, zb, ub, vb, bdaN[0], bdaN[1], bdaN[2] }, // B
{ xd, yd, zd, ud, vd, dcbN[0], dcbN[1], dcbN[2] }, // D
{ xa, ya, za, ua, va, abcN[0], abcN[1], abcN[2] }, // A
{ xd, yd, zd, ud, vd, dcbN[0], dcbN[1], dcbN[2] }, // D
{ xc, yc, zc, uc, vc, cadN[0], cadN[1], cadN[2] }, // C
};
for (int k = 0; k < _countof(points); ++k)
{
VertexData3D& d = vertbuf->data[vi];
d.x = points[k][0];
d.y = points[k][1];
d.z = points[k][2];
d.u = points[k][3];
d.v = points[k][4];
d.nx = points[k][5];
d.ny = points[k][6];
d.nz = points[k][7];
d.r = 1.0f;
d.g = 1.0f;
d.b = 1.0f;
d.a = 1.0f;
++vi;
}
}
}
create_vertex_buffer_from_array_3d(vertbuf);
}
void create_vertex_buffer_pie(VertexBuffer* vertbuf, float r, int count)
{
std::vector<VertexData3D> v(count+1);
VertexData3D origin;
memset(&origin, 0, sizeof(VertexData3D));
origin.r = 1.0f;
origin.g = 1.0f;
origin.b = 1.0f;
origin.a = 1.0f;
origin.nz = 1.0f;
v[0] = origin;
for (int i = 0; i < count; ++i)
{
float rad = (float)M_PI/2/(count-1)*i;
origin.x = r * cosf(rad);
origin.y = r * sinf(rad);
/*origin.u = cosf(rad);
origin.v = sinf(rad);*/
v[i + 1] = origin;
}
vertbuf->data = &v[0];
vertbuf->len = v.size();
create_vertex_buffer_from_array_3d(vertbuf);
vertbuf->data = nullptr;
}
|
e1123d723e3ef27fe4828aed9662f4e0f7dfdc63 | d0966bf382f0eb739bf59d61ae967e0f83d004cc | /csharp/csharp/sccomp/emitter.h | 28d3c5a3c38c77851cca19dfd5afadd2e5670127 | [] | no_license | mattwarren/GenericsInDotNet | 7b6f871808c411cbd05c538c5652618ddf162e20 | 2714ccac6f18f0f6ff885567b90484013b31e007 | refs/heads/master | 2021-04-30T04:56:03.409728 | 2018-02-13T16:09:33 | 2018-02-13T16:09:33 | 121,404,138 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,378 | h | emitter.h | // ==++==
//
//
// Copyright (c) 2002 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// This file contains modifications of the base SSCLI software to support generic
// type definitions and generic methods, THese modifications are for research
// purposes. They do not commit Microsoft to the future support of these or
// any similar changes to the SSCLI or the .NET product. -- 31st October, 2002.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// ===========================================================================
// File: emitter.h
//
// Defines the structures used to emit COM+ metadata and create executable files.
// ===========================================================================
#include <iceefilegen.h>
#define CTOKREF 1000 // Number of token refs per block. Fits nicely in a page.
// structure for saving security attributes.
struct SECATTRSAVE {
SECATTRSAVE * next;
mdToken ctorToken;
METHSYM * method;
BYTE * buffer;
unsigned bufferSize;
};
/*
* The class that handles emitted PE files, and generating the metadata
* database within the files.
*/
class EMITTER
#ifdef DEBUG
// We implement this just for debug purposes.
: IMapToken
#endif //DEBUG
{
public:
EMITTER();
~EMITTER();
void Term();
COMPILER * compiler();
bool BeginOutputFile();
bool EndOutputFile(bool writeFile);
void SetEntryPoint(METHSYM *sym);
void FindEntryPoint(OUTFILESYM *outfile);
void FindEntryPointInClass(PARENTSYM *parent);
void EmitAggregateDef(PAGGSYM sym);
void EmitAggregateSpecialFields(PAGGSYM sym);
void EmitAggregateBases(PAGGSYM sym);
void EmitMembVarDef(PMEMBVARSYM sym);
void EmitPropertyDef(PPROPSYM sym);
void EmitEventDef(PEVENTSYM sym);
void EmitMethodDef(PMETHSYM sym);
void EmitMethodInfo(PMETHSYM sym, PMETHINFO info);
void EmitMethodImpl(PMETHSYM sym);
void DefineParam(mdToken tokenMethProp, int index, mdToken *paramToken);
void EmitParamProp(mdToken tokenMethProp, int index, TYPESYM *type, PARAMINFO *paramInfo);
void *EmitMethodRVA(PMETHSYM sym, ULONG cbCode, ULONG alignment);
void ResetMethodFlags(METHSYM *sym);
DWORD GetMethodFlags(METHSYM *sym);
DWORD GetMembVarFlags(MEMBVARSYM *sym);
DWORD GetPropertyFlags(PROPSYM *sym);
DWORD GetEventFlags(EVENTSYM *sym);
void EmitDebugMethodInfoStart(METHSYM * sym);
void EmitDebugMethodInfoStop(METHSYM * sym, int ilOffsetEnd);
void EmitDebugBlock(METHSYM * sym, int count, unsigned int * offsets, unsigned int * lines, unsigned int * cols, unsigned int * endLines, unsigned int * endCols);
void EmitDebugTemporary(TYPESYM * type, LPCWSTR name, unsigned slot);
void EmitDebugLocal(LOCVARSYM * sym, int ilOffsetStart, int ilOffsetEnd);
void EmitDebugLocalConst(LOCVARSYM * sym);
void EmitDebugScopeStart(int ilOffsetStart);
void EmitDebugScopeEnd(int ilOffsetEnd);
void EmitCustomAttribute(BASENODE *parseTree, INFILESYM *infile, mdToken token, METHSYM *method, BYTE *buffer, unsigned bufferSize);
bool HasSecurityAttributes() { return cSecAttrSave > 0; }
void EmitSecurityAttributes(BASENODE *parseTree, INFILESYM *infile, mdToken token);
void ReemitAggregateFlags(PAGGSYM sym);
void ReemitMembVar(MEMBVARSYM *sym);
void ReemitMethod(METHSYM *sym);
void ReemitProperty(PROPSYM *sym);
void ReemitEvent(EVENTSYM *sym);
void DeleteToken(mdToken token);
void DeleteCustomAttributes(INFILESYM *inputfile, mdToken token);
void DeletePermissions(INFILESYM *inputfile, mdToken token);
void DeleteRelatedParamTokens(INFILESYM *inputfile, mdToken token);
void DeleteRelatedMethodTokens(INFILESYM *inputfile, mdToken token);
void DeleteRelatedTypeTokens(INFILESYM *inputfile, mdToken token);
void DeleteRelatedFieldTokens(INFILESYM *inputfile, mdToken token);
void DeleteRelatedAssemblyTokens(INFILESYM *inputfile, mdToken token);
mdToken GetMethodRefAtConstructedType(PINSTAGGMETHSYM sym, mdToken tkClassParent, mdToken tkMethodParent);
mdToken GetMethodRef(PMETHSYM sym);
mdToken GetMethodInstantiation(SYM *instmeth, mdToken parent, unsigned short cMethArgs, PTYPESYM *ppMethArgs, mdToken *slot, mdToken tkClassParent, mdToken tkMethodParent);
mdToken GetMembVarRef(PMEMBVARSYM sym);
mdToken GetMembVarRefAtConstructedType(PINSTAGGMEMBVARSYM sym);
mdToken GetTypeRef(PTYPESYM sym, bool noDefAllowed = false, mdToken tkClassParent = mdTokenNil, mdToken tkMethodParent = mdTokenNil);
mdToken GetArrayMethodRef(PARRAYSYM sym, ARRAYMETHOD methodId);
mdToken GetSignatureRef(int cTypes, PTYPESYM * arrTypes);
mdString GetStringRef(const STRCONST * string);
mdToken GetModuleToken();
mdToken GetGlobalFieldDef(METHSYM * sym, unsigned int count, TYPESYM * type, unsigned int size = 0);
mdToken GetGlobalFieldDef(METHSYM * sym, unsigned int count, unsigned int size, BYTE ** pBuffer);
void DefineTokenLoc(int offset);
void Copy(EMITTER &emit);
#ifdef DEBUG
// IMapToken implementation,
STDMETHOD(QueryInterface)(REFIID riid,void __RPC_FAR *__RPC_FAR *ppvObject);
STDMETHOD_(ULONG, AddRef)();
STDMETHOD_(ULONG, Release)();
STDMETHOD(Map)(mdToken tkImp, mdToken tkEmit);
#endif //DEBUG
protected:
void CheckHR(HRESULT hr);
void CheckHR(int errid, HRESULT hr);
void CheckHRDbg(HRESULT hr);
void MetadataFailure(HRESULT hr);
void DebugFailure(HRESULT hr);
void MetadataFailure(int errid, HRESULT hr);
DWORD FlagsFromAccess(ACCESS access);
PCOR_SIGNATURE BeginSignature();
PCOR_SIGNATURE EmitSignatureByte(PCOR_SIGNATURE curSig, BYTE b);
PCOR_SIGNATURE EmitSignatureUInt(PCOR_SIGNATURE curSig, ULONG b);
PCOR_SIGNATURE EmitSignatureToken(PCOR_SIGNATURE curSig, mdToken token);
PCOR_SIGNATURE EmitSignatureType(PCOR_SIGNATURE sig, PTYPESYM type);
PCOR_SIGNATURE EmitSignatureForMethInst(PCOR_SIGNATURE sig, unsigned short cMethArgs, PTYPESYM *ppMethArgs);
mdToken GetTypeSpec(PTYPESYM sym, bool noDefAllowed, mdToken tkClassParent, mdToken tkMethodParent);
PCOR_SIGNATURE GrowSignature(PCOR_SIGNATURE curSig);
PCOR_SIGNATURE EnsureSignatureSize(ULONG cb);
PCOR_SIGNATURE EndSignature(PCOR_SIGNATURE curSig, int * cbSig);
PCOR_SIGNATURE SignatureOfMembVar(PMEMBVARSYM sym, int * cbSig);
PCOR_SIGNATURE SignatureOfMethodOrProp(PMETHPROPSYM sym, int * cbSig);
BYTE GetConstValue(PMEMBVARSYM sym, LPVOID tempBuff, LPVOID * ppValue, size_t * pcb);
bool VariantFromConstVal(TYPESYM * type, CONSTVAL * cv, VARIANT * v);
mdToken GetScopeForTypeRef(SYM *sym);
void EmitDebugNamespace(NSSYM * ns);
mdToken GetMethodRefGivenParent(PMETHSYM sym, mdToken parent);
mdToken GetMembVarRefGivenParent(PMEMBVARSYM sym, mdToken parent);
void RecordEmitToken(mdToken * tokref);
void EraseEmitTokens();
void RecordGlobalToken(mdToken token, INFILESYM *infile);
void HandleAttributeError(HRESULT hr, BASENODE *parseTree, INFILESYM *infile, METHSYM *method);
void SaveSecurityAttribute(mdToken token, mdToken ctorToken, METHSYM * method, BYTE * buffer, unsigned bufferSize);
void FreeSavedSecurityAttributes();
// For accumulating security attributes
SECATTRSAVE * listSecAttrSave;
unsigned cSecAttrSave;
mdToken tokenSecAttrSave;
// cache a local copy of these
IMetaDataEmit* metaemit;
IMetaDataAssemblyEmit *metaassememit;
ISymUnmanagedWriter * debugemit;
// Scratch area for signature creation.
#ifdef DEBUG
bool sigBufferInUse;
#endif
PCOR_SIGNATURE sigBuffer;
PCOR_SIGNATURE sigEnd; // End of allocated area.
// Heap for storing token addresses.
struct TOKREFS {
struct TOKREFS * next;
mdToken * tokenAddrs[CTOKREF];
};
NRHEAP tokrefHeap; // Heap to allocate from.
TOKREFS * tokrefList; // Head of the tokref list.
int iTokrefCur; // Current index within tokrefList.
NRMARK mark;
};
|
56dcdc0c5280cfb5a6e754a5f03fe6f497baf23d | 7f041147e9a40340a446832b134172a871d90e34 | /ZF/ZFCore/zfsrc/ZFCore/protocol/ZFProtocolZFPath.h | 956f933c62e9a497e8d24aaf03e78c9eecf6af7e | [
"MIT"
] | permissive | ZFFramework/ZFFramework | cf5eaff500b30469e9a7f975a23812b05147442f | f7b6daed830232e3d883e1520d097f8422c38800 | refs/heads/master | 2023-08-31T21:38:34.437769 | 2023-08-30T10:31:08 | 2023-08-30T10:31:08 | 43,946,097 | 60 | 22 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | h | ZFProtocolZFPath.h | /**
* @file ZFProtocolZFPath.h
* @brief protocol for ZFFile
*/
#ifndef _ZFI_ZFProtocolZFPath_h_
#define _ZFI_ZFProtocolZFPath_h_
#include "ZFCore/ZFProtocol.h"
#include "ZFCore/ZFFile.h"
ZF_NAMESPACE_GLOBAL_BEGIN
/**
* @brief protocol for ZFFile
*/
ZFPROTOCOL_INTERFACE_BEGIN(ZFLIB_ZFCore, ZFPath)
public:
/**
* @brief see #ZFPathForModule
*/
virtual const zfchar *pathForModule(void) zfpurevirtual;
/**
* @brief see #ZFPathForModuleFile
*/
virtual const zfchar *pathForModuleFile(void) zfpurevirtual;
/**
* @brief see #ZFPathForSetting
*/
virtual const zfchar *pathForSetting(void) zfpurevirtual;
/**
* @brief see #ZFPathForSetting
*/
virtual void pathForSetting(ZF_IN const zfchar *path) zfpurevirtual;
/**
* @brief see #ZFPathForStorage
*/
virtual const zfchar *pathForStorage(void) zfpurevirtual;
/**
* @brief see #ZFPathForStorage
*/
virtual void pathForStorage(ZF_IN const zfchar *path) zfpurevirtual;
/**
* @brief see #ZFPathForStorageShared
*/
virtual const zfchar *pathForStorageShared(void) zfpurevirtual;
/**
* @brief see #ZFPathForStorageShared
*/
virtual void pathForStorageShared(ZF_IN const zfchar *path) zfpurevirtual;
/**
* @brief see #ZFPathForCache
*/
virtual const zfchar *pathForCache(void) zfpurevirtual;
/**
* @brief see #ZFPathForCache
*/
virtual void pathForCache(ZF_IN const zfchar *path) zfpurevirtual;
/**
* @brief see #ZFPathForCacheClear
*/
virtual void pathForCacheClear(void) zfpurevirtual;
ZFPROTOCOL_INTERFACE_END(ZFPath)
ZF_NAMESPACE_GLOBAL_END
#endif // #ifndef _ZFI_ZFProtocolZFPath_h_
|
554cdccb0e14c941aa640fa7fef94dc46ac1b529 | 8598b7319b49383e802f81345de0fe82d8e3df85 | /ext/DatadogMemHash/include/datadog/memhash.hh | 91369fc1a0d7ee1107c7b95905ffb7ea22ca8259 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | remicollet/dd-trace-php | 4dbdb40e39717a79a0af83b639568d1c7c1a474f | 78269847de271a7fa10586da4ae9ff50361f7434 | refs/heads/master | 2022-08-03T05:03:51.601889 | 2021-07-13T10:02:49 | 2021-07-13T10:02:49 | 164,420,117 | 0 | 0 | BSD-3-Clause | 2019-01-07T11:04:14 | 2019-01-07T11:04:14 | null | UTF-8 | C++ | false | false | 3,972 | hh | memhash.hh | #ifndef DATADOG_MEMHASH_HH
#define DATADOG_MEMHASH_HH
#include <cstdint>
namespace datadog {
namespace {
constexpr uint64_t rotl64(uint64_t x, uint8_t r) { return (x << r) | (x >> (64u - r)); }
//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche
constexpr uint64_t fmix64(uint64_t k) noexcept {
k ^= k >> 33u;
k *= UINT64_C(0xff51afd7ed558ccd);
k ^= k >> 33u;
k *= UINT64_C(0xc4ceb9fe1a85ec53);
k ^= k >> 33u;
return k;
}
//-----------------------------------------------------------------------------
void MurmurHash3_x64_128(const void *key, const uint64_t len, const uint32_t seed, void *out) noexcept {
auto *data = (const char *)key;
const uint64_t nblocks = len / 16u;
uint64_t h1 = seed;
uint64_t h2 = seed;
const uint64_t c1 = UINT64_C(0x87c37b91114253d5);
const uint64_t c2 = UINT64_C(0x4cf5ad432745937f);
//----------
// body
auto *blocks = (const uint64_t *)(key);
for (uint64_t i = 0; i < nblocks; i++) {
uint64_t k1 = blocks[(i * 2 + 0)];
uint64_t k2 = blocks[(i * 2 + 1)];
k1 *= c1;
k1 = rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
h1 = rotl64(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= c2;
k2 = rotl64(k2, 33);
k2 *= c1;
h2 ^= k2;
h2 = rotl64(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
//----------
// tail
auto *tail = (const uint8_t *)(data + nblocks * 16);
uint64_t k1 = 0;
uint64_t k2 = 0;
switch (len & 15u) {
case 15:
k2 ^= ((uint64_t)tail[14]) << 48u;
case 14:
k2 ^= ((uint64_t)tail[13]) << 40u;
case 13:
k2 ^= ((uint64_t)tail[12]) << 32u;
case 12:
k2 ^= ((uint64_t)tail[11]) << 24u;
case 11:
k2 ^= ((uint64_t)tail[10]) << 16u;
case 10:
k2 ^= ((uint64_t)tail[9]) << 8u;
case 9:
k2 ^= ((uint64_t)tail[8]) << 0u;
k2 *= c2;
k2 = rotl64(k2, 33);
k2 *= c1;
h2 ^= k2;
case 8:
k1 ^= ((uint64_t)tail[7]) << 56u;
case 7:
k1 ^= ((uint64_t)tail[6]) << 48u;
case 6:
k1 ^= ((uint64_t)tail[5]) << 40u;
case 5:
k1 ^= ((uint64_t)tail[4]) << 32u;
case 4:
k1 ^= ((uint64_t)tail[3]) << 24u;
case 3:
k1 ^= ((uint64_t)tail[2]) << 16u;
case 2:
k1 ^= ((uint64_t)tail[1]) << 8u;
case 1:
k1 ^= ((uint64_t)tail[0]) << 0u;
k1 *= c1;
k1 = rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
}
//----------
// finalization
h1 ^= len;
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
((uint64_t *)out)[0] = h1;
((uint64_t *)out)[1] = h2;
}
template <uint64_t N>
struct log2 {
constexpr static uint64_t value = 1 + log2<(N >> 1u)>::value;
};
template <>
struct log2<1> {
constexpr static uint64_t value = 0;
};
} // namespace
inline uint64_t memhash(uint64_t size, const char str[]) noexcept {
uint64_t buffer[2] = {0, 0};
MurmurHash3_x64_128(str, size, 0, buffer);
return buffer[0];
}
/**
* Hashes two integers using the cantor pairing function:
* https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
*
* This hash is perfect until overflow occurs, and then there are repeating
* patterns due to the wrapped overflow. The hashes f(1, 2) and f(2, 1) are
* different.
*
* This makes it a good hash for two ints that are offsets into an array.
*/
constexpr uint64_t cantor_hash(uint64_t x, uint64_t y) noexcept {
return (x + y) * (x + y + 1) / 2 + y;
}
} // namespace datadog
#endif // DATADOG_MEMHASH_HH
|
925d08d1e4e50ede1fc6983516149c5a733adb8e | db2ab59ca17e04c7d3f03c559f22acccf346ab42 | /codeforces/trees.cpp | 35632a62c302fa97f78f2212b556f1e95316a087 | [] | no_license | ashsek/Competetive-Codes | 274821d8054b2278e1583bb1415d9ea2dc0a6828 | 9e700de53334b38f26dbad65235b83884c933ba2 | refs/heads/master | 2021-06-12T04:34:43.904710 | 2021-01-08T05:35:58 | 2021-01-08T05:35:58 | 115,346,203 | 0 | 0 | null | 2019-10-19T03:47:49 | 2017-12-25T15:09:30 | HTML | UTF-8 | C++ | false | false | 342 | cpp | trees.cpp | #include <bits/stdc++.h>
using namespace std;
#define F(i,a,b) for(int i= int(a);i<=int(b);i++)
#define ll long long
int main()
{
ll int l,r,k,f=0;
cin>>l>>r>>k;
F(i,0,65)
{
ll int x=pow(k,i);
if(x>=l && x<=r)
{
cout<<x<<" ";
f=1;
}
else if(x>r)
break;
}
if(f==0)
cout<<-1;
cout<<endl;
} |
bfc9b58d3c63082c808206fd47a115789b1b4634 | 1833ae4251af1dc5832057e3a320b97f8c85d6eb | /Tests/Matrix/invert_test.cpp | 98a45093c821d26f894314794717285ab5520d71 | [] | no_license | Andrew2a1/SimpleMatrix | 131aad2e25f9aeb18cda88cb4afc69b37c8b4474 | 9f20f928da9186953f49c3065db36eef34ecb049 | refs/heads/master | 2021-07-13T13:25:37.204999 | 2021-02-18T17:10:04 | 2021-02-18T17:10:04 | 229,477,951 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | invert_test.cpp | #include "Tests/catch.hpp"
#include "matrix.h"
TEST_CASE("Inversing matrixes", "[Matrix]")
{
Matrix<> mat2x2 = {{2, -1},
{9, 2}};
Matrix<> mat3x3 = {{2, -1, 0},
{1, 3, -2},
{1, 0, 7}};
Matrix<> I_2x2 = {{1, 0},
{0, 1}};
Matrix<> I_3x3 = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
Matrix<> invalid = {{2, 3, 0},
{1, 0, 2}};
SECTION("Check invert possibility") {
REQUIRE(mat2x2.isInvertible());
REQUIRE(mat3x3.isInvertible());
}
SECTION("Non square matrixes are not invertible") {
REQUIRE_FALSE(invalid.isInvertible());
REQUIRE_THROWS_AS(invalid.getInversed(), InvalidDeterminantException);
}
SECTION("Inverse matrix") {
REQUIRE(mat2x2.getInversed() * mat2x2 == I_2x2);
REQUIRE(mat3x3.getInversed() * mat3x3 == I_3x3);
}
}
|
7355e62be54b744aba9c155f8b7b58ef86fb4f7a | d34491914a659b09e9e1e86ca304643d03735592 | /examples/protorpc/router.h | 70bae91e3378b7e03f2289adbff1baf77730f8a3 | [
"BSD-3-Clause"
] | permissive | ithewei/libhv | acfa23901ebff7445631df7abfb4ac832af4cef6 | 23ed8fbe22a4b270cef70d2924bab4f3f8fff2c2 | refs/heads/master | 2023-09-03T19:14:57.606708 | 2023-08-29T13:36:08 | 2023-08-29T13:36:08 | 146,397,768 | 6,015 | 1,171 | BSD-3-Clause | 2023-09-12T03:31:03 | 2018-08-28T05:47:15 | C | UTF-8 | C++ | false | false | 892 | h | router.h | #ifndef HV_PROTO_RPC_ROUTER_H_
#define HV_PROTO_RPC_ROUTER_H_
#include "generated/base.pb.h"
typedef void (*protorpc_handler)(const protorpc::Request& req, protorpc::Response* res);
typedef struct {
const char* method;
protorpc_handler handler;
} protorpc_router;
void error_response(protorpc::Response* res, int code, const std::string& message);
void not_found(const protorpc::Request& req, protorpc::Response* res);
void bad_request(const protorpc::Request& req, protorpc::Response* res);
void calc_add(const protorpc::Request& req, protorpc::Response* res);
void calc_sub(const protorpc::Request& req, protorpc::Response* res);
void calc_mul(const protorpc::Request& req, protorpc::Response* res);
void calc_div(const protorpc::Request& req, protorpc::Response* res);
void login(const protorpc::Request& req, protorpc::Response* res);
#endif // HV_PROTO_RPC_ROUTER_H_
|
74eaac387e649d195139af6d9298381820bac7e5 | ec89e41ca41970c0704a80544f5f579f3fc42cb3 | /internal/platform/implementation/windows/generated/winrt/impl/Windows.Devices.Lights.Effects.0.h | 5366676a5859e8a78083a441f1f679578101336e | [
"Apache-2.0"
] | permissive | google/nearby | 0feeea41a96dd73d9d1b8c06e101622411e770c5 | 55194622a7b7e9066f80f90675b06eb639612161 | refs/heads/main | 2023-08-17T01:36:13.900851 | 2023-08-17T01:11:43 | 2023-08-17T01:13:11 | 258,325,401 | 425 | 94 | Apache-2.0 | 2023-09-14T16:40:13 | 2020-04-23T20:41:37 | C++ | UTF-8 | C++ | false | false | 36,545 | h | Windows.Devices.Lights.Effects.0.h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220531.1
#pragma once
#ifndef WINRT_Windows_Devices_Lights_Effects_0_H
#define WINRT_Windows_Devices_Lights_Effects_0_H
WINRT_EXPORT namespace winrt::Windows::Devices::Lights
{
struct LampArray;
}
WINRT_EXPORT namespace winrt::Windows::Foundation
{
struct EventRegistrationToken;
struct Size;
template <typename TSender, typename TResult> struct __declspec(empty_bases) TypedEventHandler;
}
WINRT_EXPORT namespace winrt::Windows::Foundation::Collections
{
template <typename T> struct __declspec(empty_bases) IIterable;
}
WINRT_EXPORT namespace winrt::Windows::Graphics::Imaging
{
struct SoftwareBitmap;
}
WINRT_EXPORT namespace winrt::Windows::UI
{
struct Color;
}
WINRT_EXPORT namespace winrt::Windows::Devices::Lights::Effects
{
enum class LampArrayEffectCompletionBehavior : int32_t
{
ClearState = 0,
KeepState = 1,
};
enum class LampArrayEffectStartMode : int32_t
{
Sequential = 0,
Simultaneous = 1,
};
enum class LampArrayRepetitionMode : int32_t
{
Occurrences = 0,
Forever = 1,
};
struct ILampArrayBitmapEffect;
struct ILampArrayBitmapEffectFactory;
struct ILampArrayBitmapRequestedEventArgs;
struct ILampArrayBlinkEffect;
struct ILampArrayBlinkEffectFactory;
struct ILampArrayColorRampEffect;
struct ILampArrayColorRampEffectFactory;
struct ILampArrayCustomEffect;
struct ILampArrayCustomEffectFactory;
struct ILampArrayEffect;
struct ILampArrayEffectPlaylist;
struct ILampArrayEffectPlaylistStatics;
struct ILampArraySolidEffect;
struct ILampArraySolidEffectFactory;
struct ILampArrayUpdateRequestedEventArgs;
struct LampArrayBitmapEffect;
struct LampArrayBitmapRequestedEventArgs;
struct LampArrayBlinkEffect;
struct LampArrayColorRampEffect;
struct LampArrayCustomEffect;
struct LampArrayEffectPlaylist;
struct LampArraySolidEffect;
struct LampArrayUpdateRequestedEventArgs;
}
namespace winrt::impl
{
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffectFactory>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffectFactory>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffectFactory>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffectFactory>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylistStatics>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffectFactory>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs>{ using type = interface_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapEffect>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapRequestedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayBlinkEffect>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayColorRampEffect>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayCustomEffect>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArraySolidEffect>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs>{ using type = class_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayEffectCompletionBehavior>{ using type = enum_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayEffectStartMode>{ using type = enum_category; };
template <> struct category<winrt::Windows::Devices::Lights::Effects::LampArrayRepetitionMode>{ using type = enum_category; };
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapEffect> = L"Windows.Devices.Lights.Effects.LampArrayBitmapEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapRequestedEventArgs> = L"Windows.Devices.Lights.Effects.LampArrayBitmapRequestedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayBlinkEffect> = L"Windows.Devices.Lights.Effects.LampArrayBlinkEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayColorRampEffect> = L"Windows.Devices.Lights.Effects.LampArrayColorRampEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayCustomEffect> = L"Windows.Devices.Lights.Effects.LampArrayCustomEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist> = L"Windows.Devices.Lights.Effects.LampArrayEffectPlaylist";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArraySolidEffect> = L"Windows.Devices.Lights.Effects.LampArraySolidEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs> = L"Windows.Devices.Lights.Effects.LampArrayUpdateRequestedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayEffectCompletionBehavior> = L"Windows.Devices.Lights.Effects.LampArrayEffectCompletionBehavior";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayEffectStartMode> = L"Windows.Devices.Lights.Effects.LampArrayEffectStartMode";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::LampArrayRepetitionMode> = L"Windows.Devices.Lights.Effects.LampArrayRepetitionMode";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect> = L"Windows.Devices.Lights.Effects.ILampArrayBitmapEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffectFactory> = L"Windows.Devices.Lights.Effects.ILampArrayBitmapEffectFactory";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs> = L"Windows.Devices.Lights.Effects.ILampArrayBitmapRequestedEventArgs";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect> = L"Windows.Devices.Lights.Effects.ILampArrayBlinkEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffectFactory> = L"Windows.Devices.Lights.Effects.ILampArrayBlinkEffectFactory";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect> = L"Windows.Devices.Lights.Effects.ILampArrayColorRampEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffectFactory> = L"Windows.Devices.Lights.Effects.ILampArrayColorRampEffectFactory";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect> = L"Windows.Devices.Lights.Effects.ILampArrayCustomEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffectFactory> = L"Windows.Devices.Lights.Effects.ILampArrayCustomEffectFactory";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffect> = L"Windows.Devices.Lights.Effects.ILampArrayEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist> = L"Windows.Devices.Lights.Effects.ILampArrayEffectPlaylist";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylistStatics> = L"Windows.Devices.Lights.Effects.ILampArrayEffectPlaylistStatics";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect> = L"Windows.Devices.Lights.Effects.ILampArraySolidEffect";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffectFactory> = L"Windows.Devices.Lights.Effects.ILampArraySolidEffectFactory";
template <> inline constexpr auto& name_v<winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs> = L"Windows.Devices.Lights.Effects.ILampArrayUpdateRequestedEventArgs";
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect>{ 0x3238E065,0xD877,0x4627,{ 0x89,0xE5,0x2A,0x88,0xF7,0x05,0x2F,0xA6 } }; // 3238E065-D877-4627-89E5-2A88F7052FA6
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffectFactory>{ 0x13608090,0xE336,0x4C8F,{ 0x90,0x53,0xA9,0x24,0x07,0xCA,0x7B,0x1D } }; // 13608090-E336-4C8F-9053-A92407CA7B1D
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs>{ 0xC8B4AF9E,0xFE63,0x4D51,{ 0xBA,0xBD,0x61,0x9D,0xEF,0xB4,0x54,0xBA } }; // C8B4AF9E-FE63-4D51-BABD-619DEFB454BA
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect>{ 0xEBBF35F6,0x2FC5,0x4BB3,{ 0xB3,0xC3,0x62,0x21,0xA7,0x68,0x0D,0x13 } }; // EBBF35F6-2FC5-4BB3-B3C3-6221A7680D13
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffectFactory>{ 0x879F1D97,0x9F50,0x49B2,{ 0xA5,0x6F,0x01,0x3A,0xA0,0x8D,0x55,0xE0 } }; // 879F1D97-9F50-49B2-A56F-013AA08D55E0
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect>{ 0x2B004437,0x40A7,0x432E,{ 0xA0,0xB9,0x0D,0x57,0x0C,0x21,0x53,0xFF } }; // 2B004437-40A7-432E-A0B9-0D570C2153FF
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffectFactory>{ 0x520BD133,0x0C74,0x4DF5,{ 0xBE,0xA7,0x48,0x99,0xE0,0x26,0x6B,0x0F } }; // 520BD133-0C74-4DF5-BEA7-4899E0266B0F
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect>{ 0xEC579170,0x3C34,0x4876,{ 0x81,0x8B,0x57,0x65,0xF7,0x8B,0x0E,0xE4 } }; // EC579170-3C34-4876-818B-5765F78B0EE4
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffectFactory>{ 0x68B4774D,0x63E5,0x4AF0,{ 0xA5,0x8B,0x3E,0x53,0x5B,0x94,0xE8,0xC9 } }; // 68B4774D-63E5-4AF0-A58B-3E535B94E8C9
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffect>{ 0x11D45590,0x57FB,0x4546,{ 0xB1,0xCE,0x86,0x31,0x07,0xF7,0x40,0xDF } }; // 11D45590-57FB-4546-B1CE-863107F740DF
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist>{ 0x7DE58BFE,0x6F61,0x4103,{ 0x98,0xC7,0xD6,0x63,0x2F,0x7B,0x91,0x69 } }; // 7DE58BFE-6F61-4103-98C7-D6632F7B9169
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylistStatics>{ 0xFB15235C,0xEA35,0x4C7F,{ 0xA0,0x16,0xF3,0xBF,0xC6,0xA6,0xC4,0x7D } }; // FB15235C-EA35-4C7F-A016-F3BFC6A6C47D
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect>{ 0x441F8213,0x43CC,0x4B33,{ 0x80,0xEB,0xC6,0xDD,0xDE,0x7D,0xC8,0xED } }; // 441F8213-43CC-4B33-80EB-C6DDDE7DC8ED
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffectFactory>{ 0xF862A32C,0x5576,0x4341,{ 0x96,0x1B,0xAE,0xE1,0xF1,0x3C,0xF9,0xDD } }; // F862A32C-5576-4341-961B-AEE1F13CF9DD
template <> inline constexpr guid guid_v<winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs>{ 0x73560D6A,0x576A,0x48AF,{ 0x85,0x39,0x67,0xFF,0xA0,0xAB,0x35,0x16 } }; // 73560D6A-576A-48AF-8539-67FFA0AB3516
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapEffect>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapRequestedEventArgs>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayBlinkEffect>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayColorRampEffect>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayCustomEffect>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArraySolidEffect>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect; };
template <> struct default_interface<winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs>{ using type = winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs; };
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Duration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_Duration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_StartDelay(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_StartDelay(int64_t) noexcept = 0;
virtual int32_t __stdcall get_UpdateInterval(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_UpdateInterval(int64_t) noexcept = 0;
virtual int32_t __stdcall get_SuggestedBitmapSize(winrt::Windows::Foundation::Size*) noexcept = 0;
virtual int32_t __stdcall add_BitmapRequested(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_BitmapRequested(winrt::event_token) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffectFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateInstance(void*, uint32_t, int32_t*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_SinceStarted(int64_t*) noexcept = 0;
virtual int32_t __stdcall UpdateBitmap(void*) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Color(struct struct_Windows_UI_Color*) noexcept = 0;
virtual int32_t __stdcall put_Color(struct struct_Windows_UI_Color) noexcept = 0;
virtual int32_t __stdcall get_AttackDuration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_AttackDuration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_SustainDuration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_SustainDuration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_DecayDuration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_DecayDuration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_RepetitionDelay(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_RepetitionDelay(int64_t) noexcept = 0;
virtual int32_t __stdcall get_StartDelay(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_StartDelay(int64_t) noexcept = 0;
virtual int32_t __stdcall get_Occurrences(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_Occurrences(int32_t) noexcept = 0;
virtual int32_t __stdcall get_RepetitionMode(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_RepetitionMode(int32_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffectFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateInstance(void*, uint32_t, int32_t*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Color(struct struct_Windows_UI_Color*) noexcept = 0;
virtual int32_t __stdcall put_Color(struct struct_Windows_UI_Color) noexcept = 0;
virtual int32_t __stdcall get_RampDuration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_RampDuration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_StartDelay(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_StartDelay(int64_t) noexcept = 0;
virtual int32_t __stdcall get_CompletionBehavior(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_CompletionBehavior(int32_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffectFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateInstance(void*, uint32_t, int32_t*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Duration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_Duration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_UpdateInterval(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_UpdateInterval(int64_t) noexcept = 0;
virtual int32_t __stdcall add_UpdateRequested(void*, winrt::event_token*) noexcept = 0;
virtual int32_t __stdcall remove_UpdateRequested(winrt::event_token) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffectFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateInstance(void*, uint32_t, int32_t*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_ZIndex(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_ZIndex(int32_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall Append(void*) noexcept = 0;
virtual int32_t __stdcall OverrideZIndex(int32_t) noexcept = 0;
virtual int32_t __stdcall Start() noexcept = 0;
virtual int32_t __stdcall Stop() noexcept = 0;
virtual int32_t __stdcall Pause() noexcept = 0;
virtual int32_t __stdcall get_EffectStartMode(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_EffectStartMode(int32_t) noexcept = 0;
virtual int32_t __stdcall get_Occurrences(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_Occurrences(int32_t) noexcept = 0;
virtual int32_t __stdcall get_RepetitionMode(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_RepetitionMode(int32_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylistStatics>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall StartAll(void*) noexcept = 0;
virtual int32_t __stdcall StopAll(void*) noexcept = 0;
virtual int32_t __stdcall PauseAll(void*) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_Color(struct struct_Windows_UI_Color*) noexcept = 0;
virtual int32_t __stdcall put_Color(struct struct_Windows_UI_Color) noexcept = 0;
virtual int32_t __stdcall get_Duration(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_Duration(int64_t) noexcept = 0;
virtual int32_t __stdcall get_StartDelay(int64_t*) noexcept = 0;
virtual int32_t __stdcall put_StartDelay(int64_t) noexcept = 0;
virtual int32_t __stdcall get_CompletionBehavior(int32_t*) noexcept = 0;
virtual int32_t __stdcall put_CompletionBehavior(int32_t) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffectFactory>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateInstance(void*, uint32_t, int32_t*, void**) noexcept = 0;
};
};
template <> struct abi<winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall get_SinceStarted(int64_t*) noexcept = 0;
virtual int32_t __stdcall SetColor(struct struct_Windows_UI_Color) noexcept = 0;
virtual int32_t __stdcall SetColorForIndex(int32_t, struct struct_Windows_UI_Color) noexcept = 0;
virtual int32_t __stdcall SetSingleColorForIndices(struct struct_Windows_UI_Color, uint32_t, int32_t*) noexcept = 0;
virtual int32_t __stdcall SetColorsForIndices(uint32_t, struct struct_Windows_UI_Color*, uint32_t, int32_t*) noexcept = 0;
};
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayBitmapEffect
{
[[nodiscard]] auto Duration() const;
auto Duration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto StartDelay() const;
auto StartDelay(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto UpdateInterval() const;
auto UpdateInterval(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto SuggestedBitmapSize() const;
auto BitmapRequested(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapEffect, winrt::Windows::Devices::Lights::Effects::LampArrayBitmapRequestedEventArgs> const& handler) const;
using BitmapRequested_revoker = impl::event_revoker<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect, &impl::abi_t<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect>::remove_BitmapRequested>;
[[nodiscard]] auto BitmapRequested(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Devices::Lights::Effects::LampArrayBitmapEffect, winrt::Windows::Devices::Lights::Effects::LampArrayBitmapRequestedEventArgs> const& handler) const;
auto BitmapRequested(winrt::event_token const& token) const noexcept;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayBitmapEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayBitmapEffectFactory
{
auto CreateInstance(winrt::Windows::Devices::Lights::LampArray const& lampArray, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapEffectFactory>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayBitmapEffectFactory<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayBitmapRequestedEventArgs
{
[[nodiscard]] auto SinceStarted() const;
auto UpdateBitmap(winrt::Windows::Graphics::Imaging::SoftwareBitmap const& bitmap) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayBitmapRequestedEventArgs>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayBitmapRequestedEventArgs<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayBlinkEffect
{
[[nodiscard]] auto Color() const;
auto Color(winrt::Windows::UI::Color const& value) const;
[[nodiscard]] auto AttackDuration() const;
auto AttackDuration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto SustainDuration() const;
auto SustainDuration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto DecayDuration() const;
auto DecayDuration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto RepetitionDelay() const;
auto RepetitionDelay(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto StartDelay() const;
auto StartDelay(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto Occurrences() const;
auto Occurrences(int32_t value) const;
[[nodiscard]] auto RepetitionMode() const;
auto RepetitionMode(winrt::Windows::Devices::Lights::Effects::LampArrayRepetitionMode const& value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayBlinkEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayBlinkEffectFactory
{
auto CreateInstance(winrt::Windows::Devices::Lights::LampArray const& lampArray, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayBlinkEffectFactory>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayBlinkEffectFactory<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayColorRampEffect
{
[[nodiscard]] auto Color() const;
auto Color(winrt::Windows::UI::Color const& value) const;
[[nodiscard]] auto RampDuration() const;
auto RampDuration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto StartDelay() const;
auto StartDelay(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto CompletionBehavior() const;
auto CompletionBehavior(winrt::Windows::Devices::Lights::Effects::LampArrayEffectCompletionBehavior const& value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayColorRampEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayColorRampEffectFactory
{
auto CreateInstance(winrt::Windows::Devices::Lights::LampArray const& lampArray, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayColorRampEffectFactory>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayColorRampEffectFactory<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayCustomEffect
{
[[nodiscard]] auto Duration() const;
auto Duration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto UpdateInterval() const;
auto UpdateInterval(winrt::Windows::Foundation::TimeSpan const& value) const;
auto UpdateRequested(winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Devices::Lights::Effects::LampArrayCustomEffect, winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs> const& handler) const;
using UpdateRequested_revoker = impl::event_revoker<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect, &impl::abi_t<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect>::remove_UpdateRequested>;
[[nodiscard]] auto UpdateRequested(auto_revoke_t, winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::Devices::Lights::Effects::LampArrayCustomEffect, winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs> const& handler) const;
auto UpdateRequested(winrt::event_token const& token) const noexcept;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayCustomEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayCustomEffectFactory
{
auto CreateInstance(winrt::Windows::Devices::Lights::LampArray const& lampArray, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayCustomEffectFactory>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayCustomEffectFactory<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayEffect
{
[[nodiscard]] auto ZIndex() const;
auto ZIndex(int32_t value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayEffectPlaylist
{
auto Append(winrt::Windows::Devices::Lights::Effects::ILampArrayEffect const& effect) const;
auto OverrideZIndex(int32_t zIndex) const;
auto Start() const;
auto Stop() const;
auto Pause() const;
[[nodiscard]] auto EffectStartMode() const;
auto EffectStartMode(winrt::Windows::Devices::Lights::Effects::LampArrayEffectStartMode const& value) const;
[[nodiscard]] auto Occurrences() const;
auto Occurrences(int32_t value) const;
[[nodiscard]] auto RepetitionMode() const;
auto RepetitionMode(winrt::Windows::Devices::Lights::Effects::LampArrayRepetitionMode const& value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylist>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayEffectPlaylist<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayEffectPlaylistStatics
{
auto StartAll(param::iterable<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist> const& value) const;
auto StopAll(param::iterable<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist> const& value) const;
auto PauseAll(param::iterable<winrt::Windows::Devices::Lights::Effects::LampArrayEffectPlaylist> const& value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayEffectPlaylistStatics>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayEffectPlaylistStatics<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArraySolidEffect
{
[[nodiscard]] auto Color() const;
auto Color(winrt::Windows::UI::Color const& value) const;
[[nodiscard]] auto Duration() const;
auto Duration(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto StartDelay() const;
auto StartDelay(winrt::Windows::Foundation::TimeSpan const& value) const;
[[nodiscard]] auto CompletionBehavior() const;
auto CompletionBehavior(winrt::Windows::Devices::Lights::Effects::LampArrayEffectCompletionBehavior const& value) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffect>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArraySolidEffect<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArraySolidEffectFactory
{
auto CreateInstance(winrt::Windows::Devices::Lights::LampArray const& lampArray, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArraySolidEffectFactory>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArraySolidEffectFactory<D>;
};
template <typename D>
struct consume_Windows_Devices_Lights_Effects_ILampArrayUpdateRequestedEventArgs
{
[[nodiscard]] auto SinceStarted() const;
auto SetColor(winrt::Windows::UI::Color const& desiredColor) const;
auto SetColorForIndex(int32_t lampIndex, winrt::Windows::UI::Color const& desiredColor) const;
auto SetSingleColorForIndices(winrt::Windows::UI::Color const& desiredColor, array_view<int32_t const> lampIndexes) const;
auto SetColorsForIndices(array_view<winrt::Windows::UI::Color const> desiredColors, array_view<int32_t const> lampIndexes) const;
};
template <> struct consume<winrt::Windows::Devices::Lights::Effects::ILampArrayUpdateRequestedEventArgs>
{
template <typename D> using type = consume_Windows_Devices_Lights_Effects_ILampArrayUpdateRequestedEventArgs<D>;
};
}
#endif
|
4f8d4103d3e93855b78d0a72e4020bae48d304ee | 482752a7894d5bb6cd06d62663f83b5420f4c620 | /src/cloudcv.hpp | 12164aefef4cb1f7d09e452eb3a1555a9cd526a0 | [
"BSD-3-Clause"
] | permissive | BloodAxe/CloudCVBackend | 782066bd07786cc2d1820802335ffaeaa6e98193 | fb93b8d6620453fb4fecc9c8d310617a8a4f0540 | refs/heads/master | 2020-04-09T08:38:58.222846 | 2015-07-07T16:31:01 | 2015-07-07T16:31:01 | 12,459,754 | 5 | 8 | null | 2015-01-29T21:38:09 | 2013-08-29T12:38:34 | C++ | UTF-8 | C++ | false | false | 233 | hpp | cloudcv.hpp | #pragma once
#include <v8.h>
#include <nan.h>
namespace cloudcv
{
NAN_METHOD(version);
NAN_METHOD(buildInformation);
NAN_METHOD(analyzeImage);
NAN_METHOD(calibrationPatternDetect);
NAN_METHOD(calibrateCamera);
} |
76ee8ecd8e463f804f85440260c500bcd41be893 | 23e40c63da98484e7a9775f95dc43ca254208457 | /containters/other/valarray/3 slice.cpp | 54b83b1493a0fc5e9658c5c005f8d5c80a8f00d6 | [] | no_license | faxinwang/cppNotes | 92309162625fc496ab95c0864ae526c687827aac | f190c1b90063dd01d28374dc6cb5843ad4c0e36c | refs/heads/master | 2021-01-15T09:19:39.983474 | 2017-08-07T12:15:15 | 2017-08-07T12:15:15 | 99,574,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | 3 slice.cpp | #include<iostream>
#include<valarray>
using namespace std;
//print valarray line-by-line
template<class T>
void printValarray(const valarray<T>& va,int num){
for(int i=0;i<va.size()/num;++i){
for(int j=0;j<num;++j){
cout<<va[i*num+j]<<' ';
}
cout<<endl;
}
cout<<endl;
}
int main(){
// valarray with 12 elements four rows three columns
valarray<double> va(12);
for(int i=0;i<12;++i){
va[i]=i;
}
printValarray(va,3);
//first columu = second column raised to the third column
va[slice(0,4,3)]=pow(valarray<double>(va[slice(1,4,3)]),
valarray<double>(va[slice(2,4,3)]));
printValarray(va,3);
//create valarray with three times the thrid elements of va
valarray<double> vb(va[slice(2,4,0)]);
//multiply the third column by the elements of vb
va[slice(2,4,3)] *= vb;
printValarray(va,3);
//print the square root of the elements in the second row
// printValarray( sqrt( valarray<double>(va[slice(3,3,1)]) ), 3);
//double the elements in the third row
va[slice(2,4,3)] = valarray<double>(va[slice(2,4,3)])*2.0;
printValarray(va,3);
return 0;
}
|
b8b9c9f563db555ff1b6824e6a94c004e5d472d0 | 93e14e68023621809ae8d3f64db8189ad00c89a5 | /Classes/inkFish.cpp | 1e1d6f3e7cf4e2f9f9cb7d99441b8834bb5d6060 | [] | no_license | adrianhihi/HelloNinja | 7e31ede824a7a2d443bcf0f36a8d670c4bb6c2bf | e403e6735eb142bae831eac323140366e95ae54c | refs/heads/master | 2016-09-16T16:08:13.940829 | 2015-04-25T20:20:44 | 2015-04-25T20:20:44 | 30,392,885 | 0 | 2 | null | 2015-04-20T23:12:27 | 2015-02-06T03:21:56 | C++ | UTF-8 | C++ | false | false | 20 | cpp | inkFish.cpp | #include "inkFish.h" |
5aed21e091a7e8d77848a14f484aa5705db6c63f | bbcda48854d6890ad029d5973e011d4784d248d2 | /trunk/win/Source/BT_PhotoCropGesture.cpp | 94c9684419b60f3c1f2b8738e29836f809a91e7e | [
"MIT",
"curl",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"Zlib",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MS-LPL"
] | permissive | dyzmapl/BumpTop | 9c396f876e6a9ace1099b3b32e45612a388943ff | 1329ea41411c7368516b942d19add694af3d602f | refs/heads/master | 2020-12-20T22:42:55.100473 | 2020-01-25T21:00:08 | 2020-01-25T21:00:08 | 236,229,087 | 0 | 0 | Apache-2.0 | 2020-01-25T20:58:59 | 2020-01-25T20:58:58 | null | UTF-8 | C++ | false | false | 11,881 | cpp | BT_PhotoCropGesture.cpp | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "BT_Common.h"
#include "BT_Camera.h"
#include "BT_FileSystemActor.h"
#include "BT_GestureContext.h"
#include "BT_GLTextureManager.h"
#include "BT_OverlayComponent.h"
#include "BT_SceneManager.h"
#include "BT_QtUtil.h"
#include "BT_Util.h"
#include "BT_WindowsOS.h"
#include "BT_PhotoCropGesture.h"
const QColor PhotoCropGesture::CROP_COLOR = QColor(153, 153, 153, 204);
const float PhotoCropGesture::CROP_LINE_WIDTH = 6.0f;
const float PhotoCropGesture::CROP_LINE_PATTERN_SCALE = 15.0f;
PhotoCropGesture::PhotoCropGesture() :
Gesture("PhotoCrop", 2, 2, true)
{
clearGesture();
}
PhotoCropGesture::Detected PhotoCropGesture::isRecognizedImpl(GestureContext *gestureContext)
{
// Photo crop can only be done in slideshow mode
if (!isSlideshowModeActive())
return gestureRejected("Not in slideshow mode");
_gestureTouchPaths = gestureContext->getActiveTouchPaths();
// Find the stationary finger which "holds" the photo. If it can't be found,
// the gesture is not recognized yet.
// XXX: Should check that this finger is actually on the photo
if (_gestureTouchPaths[0]->isStationary())
{
_stationaryPath = _gestureTouchPaths[0];
_cropPath = _gestureTouchPaths[1];
}
else if (_gestureTouchPaths[1]->isStationary())
{
_stationaryPath = _gestureTouchPaths[1];
_cropPath = _gestureTouchPaths[0];
}
else
{
return Maybe;
}
// Check if the second finger is swiping horizontally or vertically
if (isCropPathValid())
{
printUnique(QString("MT_Gesture"), QT_TR_NOOP("Photo Crop Mode"));
return gestureAccepted();
}
return Maybe;
}
bool PhotoCropGesture::processGestureImpl(GestureContext *gestureContext)
{
uint numTouchPoints = gestureContext->getNumActiveTouchPoints();
if (numTouchPoints <= 2)
{
QList<Path*> activeTouchPaths = gestureContext->getActiveTouchPaths();
// The gesture is active as long as the "holding" finger is still down
if (activeTouchPaths.contains(_stationaryPath))
{
// See if a new crop line is being drawn
if ((numTouchPoints == 2) && !activeTouchPaths.contains(_cropPath))
{
if (activeTouchPaths[0] == _stationaryPath)
_cropPath = activeTouchPaths[1];
else
_cropPath = activeTouchPaths[0];
}
return true; // Continue processing this gesture
}
else if (isCropPathValid())
{
ObjectType watchedObjectType = cam->getHighlightedWatchedActor()->getObjectType();
// Only crop on an image
if (watchedObjectType != ObjectType(BumpActor, FileSystem, Image))
{
printUnique(QString("MT_Gesture"), QT_TR_NOOP("Only images can be cropped"));
return false;
}
// Don't crop a photo frame
if (watchedObjectType == ObjectType(BumpActor, FileSystem, PhotoFrame))
{
printUnique(QString("MT_Gesture"), QT_TR_NOOP("Photo frames cannot be cropped"));
return false;
}
// We assume that the middle of the line is on the photo
Vec3 winPoint, actorPercentage;
winPoint.x = (_cropPath->getFirstTouchPoint().x + _cropPath->getLastTouchPoint().x) / 2;
winPoint.y = (_cropPath->getFirstTouchPoint().y + _cropPath->getLastTouchPoint().y) / 2;
winPoint.z = 0;
actorPercentage = windowToActorPercent(winPoint);
// Check if crop path is on the image
if (actorPercentage.x == 0.0f && actorPercentage.y == 0.0f)
{
return false;
}
Vec3 midCropPoint = (_cropPath->getTotalDisplacementVector() / 2.0f) + _cropPath->getFirstTouchPoint().getPositionVector();
Vec3 midStationaryPoint = _stationaryPath->getFirstTouchPoint().getPositionVector();
bool result = true;
float topCrop = 0.0f;
float rightCrop = 0.0f;
float bottomCrop = 0.0f;
float leftCrop = 0.0f;
if (_cropPath->isApproximatelyHorizontal())
{
// If the crop is happening below the stationary point, crop the bottom portion
// Otherwise crop the top portion
if (midCropPoint.y > midStationaryPoint.y)
bottomCrop = actorPercentage.y;
else
topCrop = 1.0f - actorPercentage.y;
}
else
{
// If the crop is happening to the left of the stationary point, crop the left portion
// Otherwise crop the right portion
if (midCropPoint.x < midStationaryPoint.x)
leftCrop = actorPercentage.x;
else
rightCrop = 1.0f - actorPercentage.x;
}
// Check if an original version of this photo exists in the hidden directory
FileSystemActor *actor = dynamic_cast<FileSystemActor *>(cam->getHighlightedWatchedActor());
if (!hasOriginalPhoto(actor))
{
result = backupOriginalPhoto(actor);
}
if (result)
{
if (texMgr->cropPhoto(actor->getFullPath(), actor->getFullPath(), topCrop, rightCrop, bottomCrop, leftCrop))
{
cam->getRestoreOriginalPhotoControl()->show();
printUnique(QString("MT_Gesture"), QT_TR_NOOP("Cropping..."));
return false;
}
}
printStr(QT_TR_NOOP("Crop failed!"));
}
}
return false;
}
void PhotoCropGesture::onRender()
{
BumpObject* photo = cam->getHighlightedWatchedActor();
if (_cropPath && isCropPathValid() && photo)
{
QList<Vec3> pointList;
TouchPoint& firstPoint = _cropPath->getFirstTouchPoint();
TouchPoint& lastPoint = _cropPath->getLastTouchPoint();
Vec3 midCropPoint = (_cropPath->getTotalDisplacementVector() / 2.0f) + _cropPath->getFirstTouchPoint().getPositionVector();
Vec3 midStationaryPoint = _stationaryPath->getFirstTouchPoint().getPositionVector();
bool horizontal, aboveOrRight;
if (_cropPath->isApproximatelyVertical())
{
horizontal = false;
// Find out if we are cropping the right or left side of the image
aboveOrRight = midCropPoint.x > midStationaryPoint.x;
Vec3 start(firstPoint.x, 0.0f, 0.0f);
Vec3 end(firstPoint.x, lastPoint.y, 0.0f);
if (lastPoint.y < firstPoint.y)
{
start.y = winOS->GetWindowHeight();
}
pointList.push_back(start);
pointList.push_back(end);
}
else
{
horizontal = true;
// Find out if we are cropping the top or bottom side of the image
aboveOrRight = midStationaryPoint.y > midCropPoint.y;
Vec3 start(0.0f, firstPoint.y, 0.0f);
Vec3 end(lastPoint.x, firstPoint.y, 0.0f);
if (lastPoint.x < firstPoint.x)
{
start.x = winOS->GetWindowWidth();
}
pointList.push_back(start);
pointList.push_back(end);
}
// Get the world space bounding box surrounding the image
Box box = photo->getBox();
Vec3 points[8];
float pixelsCut;
Vec3 shiftDisplacement(0.0f);
// Set the crop point to the middle of the image/screen and then adjust either the x
// or y value of this point to the correct value determined by the crop line.
Vec3 cropPoint(winOS->GetWindowWidth() / 2.0f, winOS->GetWindowHeight() / 2.0f, 0.0f);
if (horizontal)
cropPoint.sety(pointList.front().y);
else
cropPoint.setx(pointList.front().x);
// Calculate the position of the mid point of the crop line, in percent of the image.
Vec3 percent = windowToActorPercent(cropPoint);
if (horizontal)
{
if (aboveOrRight)
{
// Determine the amount of pixels, in world space, we need to
// cut off the image.
pixelsCut = box.extents.y * percent.y;
shiftDisplacement.sety(pixelsCut);
}
else
{
// Determine the amount of pixels, in world space, we need to
// cut off the image.
pixelsCut = box.extents.y * (1.0f - percent.y);
shiftDisplacement.sety(-pixelsCut);
}
// Shrink the dimensions of the bounding box to reflect a crop.
box.extents.y -= pixelsCut;
}
else
{
if (aboveOrRight)
{
// Determine the amount of pixels, in world space, we need to
// cut off the image.
pixelsCut = box.extents.x * percent.x;
shiftDisplacement.setx(-pixelsCut);
}
else
{
// Determine the amount of pixels, in world space, we need to
// cut off the image.
pixelsCut = box.extents.x * (1.0f - percent.x);
shiftDisplacement.setx(pixelsCut);
}
// Shrink the dimensions of the bounding box to reflect a crop.
box.extents.x -= pixelsCut;
}
// When the bounding box's dimensions are changed, they shrink or grow
// from both sides, about the middle. This means we need to shift the box
// as well to properly cut off a piece of the bounding box.
box.center += box.GetRot() * shiftDisplacement;
// Find the points of all the vertices in the bounding box
box.computePoints(points);
// Only the first four points make up the top plane, so only
// calculate their client coordinates.
for (int n = 0; n < 4; n++)
{
points[n] = WorldToClient(points[n]);
// Invert the Y coordinates
points[n].y = winOS->GetWindowHeight() - points[n].y;
}
// Draw an overlay to represent the area to be cropped.
#ifdef DXRENDER
// Due to imprecisions when projecting the box to the screen, add a 1 pixel border around the
// crop 'selection'
Vec3 size(abs(points[0].x - points[1].x) + 2.0f, abs(points[1].y - points[2].y) + 2.0f, 0.0f);
points[1] = points[1] - Vec3(1.0f, 1.0f, 0.0f);
dxr->device->SetTransform(D3DTS_WORLD, &dxr->identity);
dxr->device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
dxr->device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG2);
dxr->renderBillboard(points[1], size, D3DXCOLOR(CROP_COLOR.red() / 255.0f, CROP_COLOR.green() / 255.0f, CROP_COLOR.blue() / 255.0f, CROP_COLOR.alpha() / 255.0f));
dxr->device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
dxr->device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
dxr->renderLine(pointList, QColor(0, 0, 0, 255), CROP_LINE_WIDTH, CROP_LINE_PATTERN_SCALE, CROP_COLOR);
#else
glPushAttribToken token(GL_ENABLE_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glColor4f(0.6f, 0.6f, 0.6f, 0.8f);
glBegin(GL_QUADS);
glVertex2f(points[1].x, points[1].y);
glVertex2f(points[0].x, points[0].y);
glVertex2f(points[3].x, points[3].y);
glVertex2f(points[2].x, points[2].y);
glEnd();
RenderLine(pointList, true, 15, 6);
#endif
}
}
void PhotoCropGesture::clearGesture()
{
_stationaryPath = NULL;
_cropPath = NULL;
}
bool PhotoCropGesture::isCropPathValid()
{
return ((NULL != _cropPath)
&& (_cropPath->getTotalDisplacementVector().magnitude() >= MINIMUM_CROP_LINE_LENGTH)
&& (_cropPath->isApproximatelyHorizontal() || _cropPath->isApproximatelyVertical()));
}
Vec3 PhotoCropGesture::windowToActorPercent(Vec3& windowPoint)
{
tuple<NxActorWrapper*, BumpObject*, Vec3> t = pick((int)windowPoint.x, (int)windowPoint.y);
BumpObject *pickedObject = t.get<1>();
if (pickedObject == NULL)
return Vec3(0.0f);
Vec3 stabPointActorSpace = t.get<2>();
Vec3 dims = pickedObject->getDims();
Vec3 actorPercentage;
actorPercentage.x = (-stabPointActorSpace.x + dims.x) / (2.0f * dims.x);
actorPercentage.y = (stabPointActorSpace.y + dims.y) / (2.0f * dims.y);
actorPercentage.z = 0;
return actorPercentage;
}
|
51e5bee7e8a387f87266e8aff4f1df5ab927f755 | b8ef9738c2e37f60c8232514c5e72949431cf207 | /src/href_extractor.cpp | a4b2a0ea7e2eb032b366e3d4701bb51066558137 | [] | no_license | noonvalefox/libcurl_playground | ca008df5b6b9b8cb8b32f8a20bded5de7d9584b1 | 66ced0e0c1638d4f0486fcf1e6ca62153c74c02a | refs/heads/master | 2021-08-17T01:58:51.317041 | 2017-11-20T14:35:52 | 2017-11-20T14:35:52 | 111,440,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,146 | cpp | href_extractor.cpp | /**
* author: Anton Baldin
* date: 2017-11-13
*
* A href extractor with a buildin filter function.
* Uses a HTML parser for finding the hrefs.
*
* The HTML parser is found at http://code.google.com/p/htmlstreamparser/
*/
#include "href_extractor.h"
using namespace std;
size_t href_extractor::write_callback(void *buffer, size_t size, size_t nmemb,
void *extractor) {
// extract members from object
auto *hsp = static_cast<href_extractor *>(extractor)->hsp;
auto filter = static_cast<href_extractor *>(extractor)->filter;
auto &links = static_cast<href_extractor *>(extractor)->extractedLinks;
size_t realsize = size * nmemb, p;
for (p = 0; p < realsize; p++) {
html_parser_char_parse(hsp, ((char *)buffer)[p]);
if (html_parser_cmp_tag(hsp, "a", 1))
if (html_parser_cmp_attr(hsp, "href", 4))
if (html_parser_is_in(hsp, HTML_VALUE_ENDED)) {
html_parser_val(hsp)[html_parser_val_length(hsp)] = '\0';
// printf("%s\n", html_parser_val((HTMLSTREAMPARSER *)hsp));
char *link = html_parser_val(hsp);
if (filter(link))
links.insert(link);
}
}
return realsize;
}
href_extractor::href_extractor() {
curl = curl_easy_init();
hsp = html_parser_init();
html_parser_set_tag_to_lower(hsp, 1);
html_parser_set_attr_to_lower(hsp, 1);
html_parser_set_tag_buffer(hsp, tag, sizeof(tag));
html_parser_set_attr_buffer(hsp, attr, sizeof(attr));
html_parser_set_val_buffer(hsp, val, sizeof(val) - 1);
}
href_extractor::~href_extractor() {
curl_easy_cleanup(curl);
html_parser_cleanup(hsp);
}
set<string> &href_extractor::extract(string link) {
extractedLinks.clear();
curl_easy_setopt(curl, CURLOPT_URL, link.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA,
this); // static callback workaround: pass pointer to object
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_perform(curl);
return extractedLinks;
}
void href_extractor::setFilter(function<bool(string)> f) { filter = f; }
|
1663e53d67c8e0e108cb4e1c0f725b414d304fa3 | cae1454819f080ad850ebed4a2726436e07aca3a | /Сборник моих алгоритмов/Графы/DFS.cpp | 17f3890521afa2aab631f808b0c2e955670991ff | [] | no_license | jigyasa3003/Algorithms | 3b67c31446601cb5e0fc9a7ea44b3680aeee862e | 5d91d76aa9235f5da3c198dcbfe4468609955d0c | refs/heads/master | 2021-12-10T19:33:07.531515 | 2014-11-29T06:42:45 | 2014-11-29T06:42:45 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,514 | cpp | DFS.cpp | //Обход в глубину(DFS).Для списка рёбер
#include <iostream>
#include<vector>
using namespace std;
//для списка рёбер
const int maxe=100,maxv=100;//максимум рёбер и вершин
int ef[maxe],es[maxe],ev[maxe],next[maxe],first[maxv],last[maxv],i,x,y,z;
vector<char> used(maxe);//массив меток "был ли посещён"
//функция добавления ребра
void add(int v1,int v2,int value,int &count)
{
++count;
ef[count]=v1;es[count]=v2;ev[count]=value;
if(!first[v1]) first[v1]=count;
if(last[v1]) next[last[v1]]=count;
last[v1]=count;
}
//иницилизируем граф
void init()
{
int count=0;
for(i=0;i<5;++i)
{
cin>>x>>y>>z;
add(x,y,z,count);
add(y,x,z,count);
}
}
//Сама функция обхода.Работает так:функция рекурсивна.Вызываем её от корневой вершины(оттой, с которой хотим начать обход).
//Ставим метку, что посетили эту вершину, и смотрим всё рёбра, которые выходят из этой вершины: если второй конец ребра не был посещён(то есть метка равна false)
//то вызываем функцию от 2-ого конца ребра.И получается, что мы идём как бы в глубину графа.Если мы дойдем до тупика, то рекурсивно алгоритм вернется обратно
//и будет дальше пытаться пропихнуть себя по какому-либо пути.И таким образом мы обойдем весь граф(ну или компоненту связности).
//В некоторых заданиях из-за переполнения системного стека лучше заменить рекусрсию на стек - изменения будут минимальные:
//Нужно просто ложить вершину в стек, если она не посещена, а потом извлекать.
void dfs(int from)
{
used[from]=true;
for(int h=first[from];h;h=next[h])
if(!used[es[h]])
dfs(es[h]);
}
//Тут просто вызываем обход в глубину от первой вершины
int main()
{
init();
dfs(1);
system("pause");
}
|
04a2e736376444b9735b30bad4021a95fd92a5ea | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/modules/audio_coding/neteq/tools/neteq_stats_getter.h | b1b12bb1f8da170192d5a50bdc8c18f215d022b0 | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | 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 | 3,530 | h | neteq_stats_getter.h | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_STATS_GETTER_H_
#define MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_STATS_GETTER_H_
#include <memory>
#include <string>
#include <vector>
#include "modules/audio_coding/neteq/tools/neteq_delay_analyzer.h"
#include "modules/audio_coding/neteq/tools/neteq_test.h"
namespace webrtc {
namespace test {
class NetEqStatsGetter : public NetEqGetAudioCallback {
public:
// This struct is a replica of webrtc::NetEqNetworkStatistics, but with all
// values stored in double precision.
struct Stats {
double current_buffer_size_ms = 0.0;
double preferred_buffer_size_ms = 0.0;
double jitter_peaks_found = 0.0;
double packet_loss_rate = 0.0;
double expand_rate = 0.0;
double speech_expand_rate = 0.0;
double preemptive_rate = 0.0;
double accelerate_rate = 0.0;
double secondary_decoded_rate = 0.0;
double secondary_discarded_rate = 0.0;
double clockdrift_ppm = 0.0;
double added_zero_samples = 0.0;
double mean_waiting_time_ms = 0.0;
double median_waiting_time_ms = 0.0;
double min_waiting_time_ms = 0.0;
double max_waiting_time_ms = 0.0;
};
struct ConcealmentEvent {
uint64_t duration_ms;
size_t concealment_event_number;
int64_t time_from_previous_event_end_ms;
std::string ToString() const;
};
// Takes a pointer to another callback object, which will be invoked after
// this object finishes. This does not transfer ownership, and null is a
// valid value.
explicit NetEqStatsGetter(std::unique_ptr<NetEqDelayAnalyzer> delay_analyzer);
void set_stats_query_interval_ms(int64_t stats_query_interval_ms) {
stats_query_interval_ms_ = stats_query_interval_ms;
}
void BeforeGetAudio(NetEq* neteq) override;
void AfterGetAudio(int64_t time_now_ms,
const AudioFrame& audio_frame,
bool muted,
NetEq* neteq) override;
double AverageSpeechExpandRate() const;
NetEqDelayAnalyzer* delay_analyzer() const { return delay_analyzer_.get(); }
const std::vector<ConcealmentEvent>& concealment_events() const {
// Do not account for the last concealment event to avoid potential end
// call skewing.
return concealment_events_;
}
const std::vector<std::pair<int64_t, NetEqNetworkStatistics>>* stats() const {
return &stats_;
}
const std::vector<std::pair<int64_t, NetEqLifetimeStatistics>>*
lifetime_stats() const {
return &lifetime_stats_;
}
Stats AverageStats() const;
private:
std::unique_ptr<NetEqDelayAnalyzer> delay_analyzer_;
int64_t stats_query_interval_ms_ = 1000;
int64_t last_stats_query_time_ms_ = 0;
std::vector<std::pair<int64_t, NetEqNetworkStatistics>> stats_;
std::vector<std::pair<int64_t, NetEqLifetimeStatistics>> lifetime_stats_;
size_t current_concealment_event_ = 1;
uint64_t voice_concealed_samples_until_last_event_ = 0;
std::vector<ConcealmentEvent> concealment_events_;
int64_t last_event_end_time_ms_ = 0;
};
} // namespace test
} // namespace webrtc
#endif // MODULES_AUDIO_CODING_NETEQ_TOOLS_NETEQ_STATS_GETTER_H_
|
c805a3d2ddf66703ecf3882e16e3b3a0d54b0e69 | 58911d9bf2fa17c6809b8faddbaca0f769fdd6e9 | /MAIN2.CPP | 191be28e10af151cdc5de029dd7f006afe4ca40e | [] | no_license | FernandoMartinelli/Polar_coordinates_printer_2004 | 09f37eb37643c76835eb3235b6657d8ba9f60449 | 3e2c1332214f1ebead5f01be641a95ec029a13f3 | refs/heads/master | 2021-01-21T14:40:20.486945 | 2017-06-24T21:48:53 | 2017-06-24T21:48:53 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,563 | cpp | MAIN2.CPP | #include<iostream>
#include<stdlib.h>
#include<dos.h>
#include<windows.h>
#include<time.h>
#include "circunferencia.h"
#include "geral.h"
using namespace std;
typedef short _stdcall (*inpfuncPtr)(short portaddr);
typedef void _stdcall (*oupfuncPtr)(short portaddr, short datum);
/******************************************************************************/
int main(void)
{
HINSTANCE hLib;
inpfuncPtr inp32;
oupfuncPtr oup32;
/* Carrega a biblioteca */
hLib = LoadLibrary("inpout32.dll");
if (hLib == NULL)
{
printf("LoadLibrary Failed.\n");
return -1;
}
/* Pega o endereço da função */
inp32 = (inpfuncPtr) GetProcAddress(hLib, "Inp32");
if (inp32 == NULL) //Caso não consiga carregar a função
{
printf("GetProcAddress for Inp32 Failed.\n");
return -1;
}
oup32 = (oupfuncPtr) GetProcAddress(hLib, "Out32");
if (oup32 == NULL) //Caso não consiga carregar a função
{
printf("GetProcAddress for Oup32 Failed.\n");
return -1;
}
Geral geral();
Circunferencia bolinha1(60,200);
bolinha1.imprimeParametros();
bolinha1.imprimeCircunferencia();
} //fim main
/*
motor1(int velocidade) // 1 a 500
{ if(velocidade>0)
{
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11110011);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11110110);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11111100);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11111001);
(oup32)(0x378, trem);
}
else
{
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11110011);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11111001);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11111100);
(oup32)(0x378, trem);
atual = (inp32)(0x378);
espera(501-velocidade);
trem = binaryAND(atual,11110110);
(oup32)(0x378, trem);
}
(oup32)(0x378, b);
entra = (inp32)(0x378);
espera(tempo);
printf("Entra %x", entra);
(oup32)(0x378, c);
entra = (inp32)(0x378);
espera(tempo);
printf("Entra %x", entra);
(oup32)(0x378, d);
entra = (inp32)(0x378);
espera(tempo);
printf("Entra %x", entra);
}
}
*/
|
e878a8c5a49125eacc4563741610febac3898224 | 74539a85a5dd877d3538d3c6ec546828be9794ff | /plottingScripts/biasVsLayer.cpp | bb3f972faccaf931f344ddc74580e8b7bf0e9a9a | [] | no_license | chrispap95/deadCellRegression | 450b7a12060d3cb73df3333b6dcf9fd69faacfbb | 59ff82d28c001cdeb7c43e599ad20fdda45fbc77 | refs/heads/master | 2021-06-18T07:34:52.704589 | 2021-03-29T19:47:21 | 2021-03-29T19:47:21 | 186,055,358 | 0 | 0 | null | 2020-08-05T20:48:28 | 2019-05-10T21:16:19 | C | UTF-8 | C++ | false | false | 971 | cpp | biasVsLayer.cpp | {
// Import tree & variables
TCanvas* c = new TCanvas("c","c",1);
gStyle->SetOptStat(0);
TFile* f = TFile::Open("data/training_sample_full_8samples.root");
TTree* t = dynamic_cast< TTree* >(f->Get("t1"));
float dead, down, up, layer;
t->SetBranchAddress("MLlayer",&layer);
t->SetBranchAddress("MLdead",&dead);
t->SetBranchAddress("MLndown",&down);
t->SetBranchAddress("MLnup",&up);
gPad->SetLogz();
TH2F* h1 = new TH2F("h1","Bias vs Layer;layer;bias [GeV]",28,0,28,50,-9,1);
for (long i = 0; i < t->GetEntries(); ++i) {
t->GetEntry(i);
if (dead < 0.4) h1->Fill(layer,dead-up/2-down/2);
}
h1->Draw("colz");
gPad->SetTickx();
gPad->SetTicky();
TLine* l = new TLine(0,0,0.4,0);
h1->GetXaxis()->SetTitleOffset(1.2);
TLatex ltx;
l->Draw();
ltx.SetTextSize(0.035);
ltx.DrawLatex(0+0.003,h1->GetYaxis()->GetXmax()*1.05,
"HGCAL#scale[0.8]{#font[12]{Internal}}");
}
|
8c9ca741cb2f2525cebe4b80e1bbc7bda3306bb9 | cd060892280983a64d1d463fcea7b3edbf843cf8 | /includes/Graphics/bk/RenderNode.h | 109504c2adbe77f7d560be7c717a60a597a34bd9 | [] | no_license | zhvirus/zhangtina | c8741d3cab4cc0929db6776dde3ce5a4733fabe1 | 88a6f85992861862e22cd9edbe852f45b8a62775 | refs/heads/master | 2021-01-21T04:31:30.673821 | 2016-06-29T03:14:16 | 2016-06-29T03:14:16 | 14,973,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,633 | h | RenderNode.h | #ifndef RENDER_NODE_H
#define RENDER_NODE_H
#include <map>
#include <string>
#include "Common/ZHSTD.h"
#include "Graphics/Resource.h"
#include "Graphics/RenderItem.h"
#include "Util/Array.h"
#include "Math/Matrix4x4_f.h"
namespace ZH{
namespace Graphics{
class ZH_GRAPHICS_DLL RenderNode : public Resource
{
CLASS_IDENTIFIER( E_CID_RENDER_NODE );
public:
virtual ~RenderNode();
virtual bool isValid();
// World matrix
const ZH::Math::matrix4x4_f& worldMatrix() { return m_worldMatrix; }
void worldMatrix( const ZH::Math::matrix4x4_f& mat ) { m_worldMatrix = mat; }
virtual bool addRenderItem( RenderItem* );
virtual bool removeRenderItem( const char* const );
RenderItem* findRenderItem( const char* const );
void enableRenderItem( const char* const );
void disableRenderItem( const char* const );
void clear();
protected:
// World matrix
ZH::Math::matrix4x4_f m_worldMatrix;
// Render items of this node
RenderItemMap* m_pRenderItems;
protected:
virtual bool prepareDefaultData();
RenderNode( const char* const );
friend class ResourceFactory;
};
typedef std::map<std::string, RenderNode*> RenderNodeMap;
ZH_GRAPHICS_EXTERN template class ZH_GRAPHICS_DLL ZH::UTIL::Array<RenderNode*>;
typedef ZH::UTIL::Array<RenderNode*> RenderNodePtrArray;
} // namespace Graphics
} // namespace ZH
#endif
|
c9c5f5c5ac5786d04239660ff3bfdcf907714df8 | 45ce394ca1fc18194f7ed9dc1d3a7bfcb5d7fb99 | /Codeforces/371A.cpp | 856d99dede0f8d6c2f26b0e8b8c2bc30d0bf94c4 | [] | no_license | lethanhtam1604/MyAPCodes | 4bd34c19538ebd7271dde9b9cd6100cad7893e77 | d2528cda1ef8051839067a0bc05294bc34b357ea | refs/heads/master | 2021-01-23T16:26:06.383769 | 2018-02-10T12:46:10 | 2018-02-10T12:46:10 | 93,297,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | cpp | 371A.cpp | #include <stdio.h>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int N=105;
int a[N], b[2];
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/TamLe/Documents/Input.txt", "rt", stdin);
#endif
int n, k;
scanf("%d %d", &n, &k);
int res = 0;
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (int t = 0; t < k; t++) {
for(int i = t; i < n; i+= k) {
if (a[i] == 1) {
b[0]++;
}
else {
b[1]++;
}
}
res += min(b[0], b[1]);
b[0] = 0;
b[1] = 0;
}
printf("%d", res);
return 0;
}
|
3b9dab849ef0ba18a071b8bc8791b1cbcc56fcf3 | f9c7d0848e4a4fd6f98d76e6b4d4dab4215e402d | /MSCNProblem/MSCNProblem/include/utilities/RandomGenerator.h | b0576861a3d687ff80ce8a717d9a39436ff09935 | [
"MIT"
] | permissive | Ukasz09/Multi-echelon-supply-chain-network | ae3b5778543d4535f44e1898b008bc71452e20a0 | baba35a5c6cc555282ae6266bb9617920671ade9 | refs/heads/master | 2020-12-08T02:46:32.503481 | 2020-03-05T13:01:50 | 2020-03-05T13:01:50 | 232,862,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | h | RandomGenerator.h | #pragma once
#include <random>
#include <ctime>
template <class T=int>
class RandomGenerator {
private:
unsigned int seed;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public:
RandomGenerator(unsigned int seed);
RandomGenerator();
~RandomGenerator() = default;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public:
T getRandom(T min, T max);
private:
double getRandomRealNumber(double min, double max);
};
template <class T>
RandomGenerator<T>::RandomGenerator(unsigned int seed) {
this->seed = seed;
srand(seed);
}
template <class T>
RandomGenerator<T>::RandomGenerator() {
this->seed = time(nullptr);
srand(seed);
}
template <>
inline float RandomGenerator<float>::getRandom(float min, float max) {
return getRandomRealNumber(min, max);
}
template <>
inline double RandomGenerator<double>::getRandom(double min, double max) {
return getRandomRealNumber(min, max);
}
template <class T>
T RandomGenerator<T>::getRandom(T min, T max) {
int range = max - min + 1;
return (std::rand() % range) + min;
}
template <class T>
double RandomGenerator<T>::getRandomRealNumber(double min, double max) {
min *= 100;
max *= 100;
int range = max - min + 1;
return ((std::rand() % range) + min) / 100;
}
|
5da25ee63d9c4ec1582aa3ec49a3e120efd57bc6 | 488ed82c1064b522830c08f771200243b29e2fdd | /Lecture: DP3/dilemma.cpp | efcc0b514aa96852446a610e9776060ac155e9eb | [] | no_license | DevaishiT/Coding-Ninjas-Competitive | 5f65a8291e90388360932d2141285b2001f9895a | 2328a4966f1b545d1c9bc96b13388994dbdf3018 | refs/heads/master | 2021-05-25T14:14:37.050915 | 2020-04-26T08:57:34 | 2020-04-26T08:57:34 | 253,785,480 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | cpp | dilemma.cpp | //partially correct
#include<bits/stdc++.h>
using namespace std;
int count_set_bits(int n, int x)
{
int num = 0;
for(int i=0;i<n;i++)
if( (x&(1<<i)) != 0)
num++;
return num;
}
int rec_solver(vector<vector<int>> &dp, int mask, int pos, vector<string> &v, int n)
{
int y = count_set_bits(n,mask);
// the two bases cases
if (y == 1) return 0;
if (pos == n || y == 0) return 100000;
// in case of overlapping
if (dp[mask][pos] != -1)
return dp[mask][pos];
int mask1 = mask;
int mask2 = mask;
for(int i=0; i<n; i++)
{
if ((mask & (1<<i)) != 0)
{
if (v[i][pos] == '1')
{
mask1 = (mask1 & ~(1<<i));
}
else mask2 = (mask2 & ~(1<<i));
}
}
//cout << mask << " " << mask1 << " " << mask2 << endl;
int val = min(rec_solver(dp,mask1,pos+1,v,n) + rec_solver(dp,mask2,pos+1,v,n) + y
, rec_solver(dp,mask,pos+1,v,n));
dp[mask][pos] = val;
return val;
}
int minimumTouchesRequired(int n, vector<string> v) {
/* Don't write main().
* Don't read input, they are passed as function arguments.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
int len = v[0].length();
int size = pow(2,n);
vector<vector<int>> dp(size, vector<int>(len,-1));
size--;
return rec_solver(dp, size, 0, v, n);
} |
579459594319beb16d5e85aa5fb527fd707f592e | b660510bd4756b94aad7fe23faaf1bbb86c7e30b | /AS_Practics/Include/figureDraw.cpp | 818f11d891106ebdbdada2216692015abe64be30 | [] | no_license | michaelkimm/Winapi_MoonLighter | 4524819871d942ab48445c89cf84858f34ab8c21 | 8a8615f7ad2a41b81e2fda4c2f71e03e6d5f3c38 | refs/heads/main | 2023-07-09T08:52:42.778458 | 2021-08-16T06:59:50 | 2021-08-16T06:59:50 | 390,154,430 | 0 | 0 | null | 2021-08-05T05:28:14 | 2021-07-27T23:21:55 | C++ | UHC | C++ | false | false | 12,151 | cpp | figureDraw.cpp |
#include <iostream>
#include <vector>
#include <tchar.h>
#include "figureDraw.h"
#ifndef PI
#define PI 3.141592
#endif // !PI
void DrawGrid(HDC hdc, POINT p1, POINT p2, UINT n) // 시작 위치, 끝 위치, 선의 개수
{
LONG dx = (p2.x - p1.x) / n; // 가로 칸 개수
LONG dy = (p2.y - p1.y) / n; // 세로 칸 개수
// 가로 선 그리기
for (LONG j = p1.y; j <= p2.y; j += dy)
{
MoveToEx(hdc, p1.x, j, NULL);
LineTo(hdc, p2.x, j);
}
// 세로 선 그리기
for (LONG i = p1.x; i <= p2.x; i += dx)
{
MoveToEx(hdc, i, p1.y, NULL);
LineTo(hdc, i, p2.y);
}
}
void DrawGrid(HDC hdc, POINT c1, UINT dx, UINT n) // 중심 위치, 간격, 선의 개수
{
LONG d = (n / 2) * dx;
POINT p1{ c1.x - d, c1.y - d };
POINT p2{ c1.x + d, c1.y + d };
DrawGrid(hdc, p1, p2, n); // 중심 위치와 간격을 알면, 시작 위치와 끝 위치를 알 수 있어요. 이를 이용해서 DrawGrid 위 함수를 재사용 했습니다.
}
void DrawEllipse(HDC hdc, POINT c1, LONG r)
{
Ellipse(hdc, c1.x - r, c1.y - r, c1.x + r, c1.y + r);
}
void DrawSunFlower(HDC hdc, POINT c1, LONG r1, LONG r2) // 외곽원 반지름으로 그리기 해바라기 그리기
{
// n_out 구하기
LONG n_out = (LONG)(round(180 / (asin((double)r2 / (r1 + r2)) * (180 / PI)))); // 기준 원 곁에 원이 몇개가 생기나? 기하학적 관계 이용했습니다. sin역함수가 사용되네요
// 작은 원 그리기
for (LONG theta = 0; theta < 360; theta += (360 / n_out)) // 기준 원 곁에 있는 원들의 중심이 r1+r2반지름을 가지는 원임에서 착안했습니다. 원의 모든 점은 sin cos으로 표현됩니다.
{
LONG x2{ (LONG)(c1.x + (double)(r1 + r2) * cos(theta * PI / 180)) };
LONG y2{ (LONG)(c1.y + (double)(r1 + r2) * sin(theta * PI / 180)) };
DrawEllipse(hdc, POINT{ x2,y2 }, r2);
}
}
void DrawSunFlowerN(HDC hdc, POINT c1, LONG r1, LONG n) // 외곽원 갯수로 그리기 해바라기 그리기
{
// r2 구하기
double s = sin(360 / n / 2 * PI / 180);
LONG r2 = (LONG)(round((r1 * (sin(s) / (1 - sin(s)))))); // DrawEllipseFlower에서 n_out구하는 공식을 변형하면 되요
// 작은 원 그리기
for (LONG theta = 0; theta < 360; theta += (360 / n)) // 기준 원 곁에 있는 원들의 중심이 r1+r2반지름을 가지는 원임에서 착안했습니다. 원의 모든 점은 sin cos으로 표현됩니다.
{
LONG x2{ (LONG)(c1.x + (double)(r1 + r2) * cos(theta * PI / 180)) };
LONG y2{ (LONG)(c1.y + (double)(r1 + r2) * sin(theta * PI / 180)) };
DrawEllipse(hdc, POINT{ x2,y2 }, r2);
}
}
void DrawRectangle(HDC hdc, POINT c1, LONG w, LONG h) // 핸들, 중심점 위치, 가로, 세로
{
Rectangle(hdc, c1.x - w / 2, c1.y - h / 2, c1.x + w / 2, c1.y + h / 2);
}
void DrawRectangle(HDC hdc, POINT c1, LONG w, LONG h, float tilt) // 핸들, 중심점 위치, 가로, 세로, 회전한 각도
{
// p1234는 원점에서의 사각형 위치 pts는 translation & rotation 변환 후 네점 위치 저장 공간
POINT p1234[4] = { -w / 2, -h / 2, w / 2, -h / 2, w / 2, h / 2, -w / 2, h / 2 };
POINT pts[4] = { NULL, };
// 변환 행렬 적용
getRectPoints(c1, w, h, tilt, pts);
// 그리기
DrawRectangle(hdc, pts);
}
void DrawRectangle(HDC hdc, POINT *c1) // 핸들, 중심점 위치, 가로, 세로, 회전한 각도
{
int i;
for (i = 0; i < 3; i++)
{
MoveToEx(hdc, c1[i].x, c1[i].y, NULL);
LineTo(hdc, c1[i + 1].x, c1[i + 1].y);
}
MoveToEx(hdc, c1[i].x, c1[i].y, NULL);
LineTo(hdc, c1[0].x, c1[0].y);
}
void DrawInputText(HDC hdc, RECT r1, LPCTSTR str, UINT Flags, bool Caret)
{
// 사각형 그리기
POINT c1{ (r1.left + r1.right) / 2, (r1.top + r1.bottom) / 2 };
LONG w{ r1.right - r1.left };
LONG h{ r1.bottom - r1.top };
DrawRectangle(hdc, c1, w, h);
// 텍스트 그리기
LONG gap = 2;
RECT r2{ r1.left + gap, r1.top + gap, r1.right - gap, r1.bottom - gap }; // 캐럿 크기 생각해서 작게 사각형 생성
// 텍스트 캐럿 설정
if (Caret == true)
{
SIZE size;
GetTextExtentPoint(hdc, str, _tcslen(str), &size);
SetCaretPos(r2.left + size.cx, r1.top);
}
// 텍스트 그리기
DrawText(hdc, str, _tcslen(str), &r2, Flags);
}
void DrawInputText(HDC hdc, POINT c, LONG w, LONG h, LPCTSTR str, UINT Flags, bool Caret)
{
// 사각형 그리기
DrawRectangle(hdc, c, w, h);
// 텍스트 그리기
LONG gap = 2;
RECT r2{ c.x - w / 2 + gap, c.y - h / 2 + gap, c.x + w / 2 - gap, c.y + h / 2 - gap }; // 캐럿 크기 생각해서 작게 사각형 생성
// 텍스트 캐럿 설정
if (Caret == true)
{
SIZE size;
GetTextExtentPoint(hdc, str, _tcslen(str), &size);
SetCaretPos(c.x - w / 2 + size.cx, c.y - h / 2);
}
// 텍스트 그리기
DrawText(hdc, str, _tcslen(str), &r2, Flags);
}
void DrawStar(HDC hdc, POINT c, LONG r)
{
double double_d; // 중심에서 점까지 거리
POINT point[10]; // 바깥 꼭지점 및 안 꼭지점 집합
LONG pointIdx = 0; // 꼭지점 인덱스
int theta = 90 - 2 * (360 / (2 * 5));
double theta2rad = PI / 180;
double short_d = r * sin(theta * theta2rad) / cos(theta * theta2rad); // 중심에서 안쪽 꼭지점까지 거리
for (theta = 0; theta < 360; theta += (360 / 10))
{
// 각도에 따라 달라지는 d 설정
if (theta / (360 / 10) % 2 == 1)
double_d = short_d;
else
double_d = r;
// 바깥 꼭지점 및 안 꼭지점 설정
double x = cos(theta * theta2rad) * double_d + c.x; // 평행이동 행렬 & 회전 행렬을 생각하셔도 되고, 벡터로 생각하셔도 됩니다.
double y = sin(theta * theta2rad) * double_d + c.y;
point[pointIdx++] = { (LONG)x, (LONG)y };
}
// 별 그리기
Polygon(hdc, point, 10);
}
void DrawStarN(HDC hdc, POINT c, LONG r, LONG n)
{
double double_d; // 중심에서 점까지 거리
POINT * point = new POINT[2 * n]; // 바깥 꼭지점 및 안 꼭지점 집합
LONG pointIdx = 0; // 꼭지점 인덱스
int theta = 90 - 2 * (360 / (2 * n)); // 꼭지점 사이 각도
double theta2rad = PI / 180;
// 각도가 커지면서 꼭지점 위치를 하나씩 point 배열에 대입
double short_d = r * sin(theta * theta2rad) / cos(theta * theta2rad); // 중심에서 안쪽 꼭지점까지 거리
for (theta = 0; theta < 360; theta += (360 / (2 * n)))
{
// 각도에 따라 달라지는 d 설정
if (theta / (360 / (2 * n)) % 2 == 1)
double_d = short_d;
else
double_d = r;
// 바깥 꼭지점 및 안 꼭지점 설정
double x = cos(theta * theta2rad) * double_d + c.x; // 평행이동 행렬 & 회전 행렬을 생각하셔도 되고, 벡터로 생각하셔도 됩니다.
double y = sin(theta * theta2rad) * double_d + c.y;
point[pointIdx++] = { (LONG)x, (LONG)y };
}
// 별 그리기
Polygon(hdc, point, 2 * n);
delete[] point;
}
void arrowKeysColor(HDC hdc, POINT c, LONG d, COLORREF crcolor, LONG keyVal)
{
POINT left_c = { c.x - d, c.y };
POINT top_c = { c.x, c.y - d };
POINT right_c = { c.x + d, c.y };
// 방향키 4개 그리기
DrawInputText(hdc, top_c, d, d, _T("Up"), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
DrawInputText(hdc, c, d, d, _T("Down"), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
DrawInputText(hdc, left_c, d, d, _T("Left"), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
DrawInputText(hdc, right_c, d, d, _T("Right"), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
// keyVal != 0 이면
// 그 위에 빨강 그리기
if (keyVal != 0)
{
HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 255));
HBRUSH oldBrush = (HBRUSH)SelectObject(hdc, hBrush);
switch (keyVal)
{
case VK_LEFT:
DrawRectangle(hdc, left_c, d, d);
break;
case VK_RIGHT:
DrawRectangle(hdc, right_c, d, d);
break;
case VK_UP:
DrawRectangle(hdc, top_c, d, d);
break;
case VK_DOWN:
DrawRectangle(hdc, c, d, d);
break;
default:
{
}
}
SelectObject(hdc, oldBrush);
DeleteObject(hBrush);
}
}
void getRectPoints(POINT c1, LONG w, LONG h, float tilt, POINT *pts) // 핸들, 중심점 위치, 가로, 세로, 회전한 각도
{
// p1234는 원점에서의 사각형 위치 pts는 translation & rotation 변환 후 네점 위치 저장 공간
POINT p1234[4] = { -w / 2, -h / 2, w / 2, -h / 2, w / 2, h / 2, -w / 2, h / 2 };
// 변환 행렬 적용
for (int i = 0; i < 4; i++)
{
POINT pt{ NULL, };
pts[i].x = (long)(p1234[i].x * cos((double)tilt) - p1234[i].y * sin((double)tilt) + c1.x);
pts[i].y = (long)(p1234[i].x * sin((double)tilt) + p1234[i].y * cos((double)tilt) + c1.y);
}
}
template <typename T>
T pointDotProduct(POINT a, POINT b)
{
return a.x * b.x + a.y * b.y;
}
bool satAlgorithm(POINT *object1Pt, POINT *object2Pt, float &shortest_distance, std::pair<float, float> &shortest_normal_vector)
{
// 두 벡터로 겹치는지 여부 판단
// 노멀 벡터 구하기
// obj1 각 변의 법선 벡터
std::vector<std::pair<float, float>> norms;
float fdistance = 0.f; // 법선 단위 벡터 만드는 스칼라 값
for (int i = 0; i < 3; i++)
{
fdistance = getfDistance(object1Pt[i], object1Pt[i + 1]);
norms.emplace_back(std::pair<float, float>{ -(object1Pt[i + 1].y - object1Pt[i].y) / fdistance, (object1Pt[i + 1].x - object1Pt[i].x) / fdistance });
}
fdistance = getfDistance(object1Pt[0], object1Pt[3]);
norms.emplace_back(std::pair<float, float>{ -(object1Pt[0].y - object1Pt[3].y) / fdistance, (object1Pt[0].x - object1Pt[3].x) / fdistance });
// obj2 각 변의 법선 벡터
for (int i = 0; i < 3; i++)
{
fdistance = getfDistance(object2Pt[i], object2Pt[i + 1]);
norms.emplace_back(std::pair<float, float>{ -(object2Pt[i + 1].y - object2Pt[i].y) / fdistance, (object2Pt[i + 1].x - object2Pt[i].x) / fdistance });
}
fdistance = getfDistance(object2Pt[0], object2Pt[3]);
norms.emplace_back(std::pair<float, float>{ -(object2Pt[0].y - object2Pt[3].y) / fdistance, (object2Pt[0].x - object2Pt[3].x) / fdistance });
// 각 노멀 벡터에 정사영한 값 구하기
// 겹치는지 판단
// 각 도형의 최대 최소 값 구하기
// (최대 - 최소), (최소 - 최대) 중 절대값 작은 것이 최소 거리
// 그 벡터도 저장
auto pairFloat2DotProduct = [](POINT p1, std::pair<float, float> v1) // 내적 인라인 함수
{
return p1.x * v1.first + p1.y * v1.second;
};
// 각 법선 벡터에 대해 obj들의 점 정사영
float min_abs = 3.4E+37f;
for (std::pair<float, float> &norm : norms)
{
// 해당 법선 벡터에 대해 obj1 정사영
float proj1 = pairFloat2DotProduct(object1Pt[0], norm);
float obj1_proj_max = proj1, obj1_proj_min = proj1;
for (int i = 1; i < 4; i++)
{
proj1 = pairFloat2DotProduct(object1Pt[i], norm);
if (proj1 >= obj1_proj_max) obj1_proj_max = proj1; // 최대 최소 판정 및 업데이트
if (proj1 <= obj1_proj_min) obj1_proj_min = proj1;
}
// 해당 법선 벡터에 대해 obj2 정사영
proj1 = pairFloat2DotProduct(object2Pt[0], norm);
float obj2_proj_max = proj1, obj2_proj_min = proj1;
for (int i = 1; i < 4; i++)
{
proj1 = pairFloat2DotProduct(object2Pt[i], norm);
if (proj1 >= obj2_proj_max) obj2_proj_max = proj1; // 최대 최소 판정 및 업데이트
if (proj1 <= obj2_proj_min) obj2_proj_min = proj1;
}
if (obj1_proj_min <= obj2_proj_max && obj1_proj_max >= obj2_proj_min)
{
// 겹치다
// 최소 절대값 구하기
fabs(obj2_proj_max - obj1_proj_min) <= fabs(obj1_proj_max - obj2_proj_min) ?
min_abs = fabs(obj2_proj_max - obj1_proj_min) : min_abs = fabs(obj1_proj_max - obj2_proj_min); // 현재 최소 절대값 업데이트
if (min_abs <= shortest_distance) // 이전 최소 절대값과 비교 후 최소값 및 법선 벡터 업데이트
{
shortest_distance = min_abs;
shortest_normal_vector = norm;
}
}
else
return false; // 안겹침
}
// 겹침
return true;
}
bool doCirclesOverlap(float x1, float y1, float r1, float x2, float y2, float r2)
{
return (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) <= (r1 + r2)*(r1 + r2);
}
float getfDistance(POINT p1, POINT p2)
{
return sqrtf((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
float getL2N(float a, float b)
{
return sqrtf(a*a + b * b);
} |
251211c71dea9d15e47ec2eca83a2a74d16246cd | c45ed46065d8b78dac0dd7df1c95b944f34d1033 | /TC-SRM-593-div1-450/yjq.cpp | cee5b3bdf8db4962812662600b18a00f2995e277 | [] | no_license | yzq986/cntt2016-hw1 | ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e | 12e799467888a0b3c99ae117cce84e8842d92337 | refs/heads/master | 2021-01-17T11:27:32.270012 | 2017-01-26T03:23:22 | 2017-01-26T03:23:22 | 84,036,200 | 0 | 0 | null | 2017-03-06T06:04:12 | 2017-03-06T06:04:12 | null | UTF-8 | C++ | false | false | 587 | cpp | yjq.cpp | #include <bits/stdc++.h>
using namespace std ;
const int MAXN = 1000010 ;
bitset<MAXN> dp ;
class MayTheBestPetWin {
public :
int calc(vector<int> A, vector<int> B) {
int n = A.size() ;
dp.set(0) ;
int tota = 0, totb = 0;
for (int i = 0; i < n; i ++) {
tota += A[i], totb += B[i] ;
dp |= (dp << (A[i] + B[i])) ;
}
int ans = 1 << 30 ;
for (int i = 0; i <= tota + totb;i ++) {
if (dp[i]) {
ans = min(ans, max(i - tota, totb - i)) ;
}
}
return ans ;
}
} ;
|
837cac6ab6a944962fd0ada87d9940ab192591aa | 8a6ccc34fe0afab6a854f9d9a93395a5c77d274d | /Camera/camx/src/core/hal/camxentry.cpp | a16befa68e0e33d754f613807732871c89691786 | [
"Apache-2.0"
] | permissive | Smartype/camx | e7ffbcc6ec437c1654b24680c85812f3bdfdb6a5 | a9e37cf33f6383760b51ebdb5953fbb5f40b8e80 | refs/heads/master | 2023-08-10T14:47:58.280280 | 2021-01-21T09:03:00 | 2021-01-21T09:03:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,105 | cpp | camxentry.cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016-2017 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file camxentry.cpp
/// @brief CamX HAL3 Entry Points
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "camxentry.h"
#include "camxhal3.h"
#include "camxincs.h"
CAMX_NAMESPACE_BEGIN
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dispatch::Dispatch
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Dispatch::Dispatch(
VOID* pAPIJumpTable)
: m_pJumpTable(pAPIJumpTable)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dispatch::GetJumpTableHAL3
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID* Dispatch::GetJumpTable()
{
VOID* pJumpTable = NULL;
// Ensure a consistent pointer value is read
#if _LP64
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT64));
pJumpTable = reinterpret_cast<VOID*>(CamxAtomicLoadU64(reinterpret_cast<UINT64*>(&m_pJumpTable)));
#elif _WIN64
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT64));
pJumpTable = reinterpret_cast<VOID*>(CamxAtomicLoadU64(reinterpret_cast<UINT64*>(&m_pJumpTable)));
#else
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT32));
pJumpTable = reinterpret_cast<VOID*>(CamxAtomicLoadU32(reinterpret_cast<UINT32*>(&m_pJumpTable)));
#endif // _LP64
CAMX_ASSERT(NULL != pJumpTable);
return pJumpTable;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dispatch::SetJumpTableHAL3
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID Dispatch::SetJumpTable(
VOID* pJumpTable)
{
// Ensure a consistent pointer value is written
#if _LP64
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT64));
CamxAtomicStoreU64(reinterpret_cast<UINT64*>(&m_pJumpTable), reinterpret_cast<UINT64>(pJumpTable));
#elif _WIN64
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT64));
CamxAtomicStoreU64(reinterpret_cast<UINT64*>(&m_pJumpTable), reinterpret_cast<UINT64>(pJumpTable));
#else
CAMX_STATIC_ASSERT(sizeof(VOID*) == sizeof(UINT32));
CamxAtomicStoreU32(reinterpret_cast<UINT32*>(&m_pJumpTable), reinterpret_cast<UINT32>(pJumpTable));
#endif // _LP64
}
CAMX_NAMESPACE_END
|
61c52d4fae48be752be79efcdb0adb2cbc8a58c0 | bc3f2f7e3c97a19de4b7b7a2e0a7b0923be1dea8 | /MagicalRobot/Temp/StagingArea/Data/il2cppOutput/Il2CppReversePInvokeWrapperTable.cpp | 827b5f4f2cdfbabe553f2b33285104f0ee935088 | [] | no_license | ericrosenbrown/CARebot | 38aca50c1b4fc6865490bed41c0de2ace1f7d6ed | b3fc101a07bcc3ac550a29799d0fab54ba6a05c6 | refs/heads/master | 2022-07-12T15:35:31.316175 | 2020-05-15T21:20:40 | 2020-05-15T21:20:40 | 264,301,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,192 | cpp | Il2CppReversePInvokeWrapperTable.cpp | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.String
struct String_t;
struct MLCameraResultExtras_t1014470651 ;
struct MLCameraOutput_t2680920266_marshaled_pinvoke;
struct MLInputControllerTouchpadGesture_t3269538253 ;
struct MLMusicServiceMetadata_t2439823319 ;
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t3528271667* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t3528271667* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t3528271667** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t3528271667* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef MLMUSICSERVICEERRORTYPE_T2790926119_H
#define MLMUSICSERVICEERRORTYPE_T2790926119_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLMusicServiceErrorType
struct MLMusicServiceErrorType_t2790926119
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLMusicServiceErrorType::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLMusicServiceErrorType_t2790926119, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLMUSICSERVICEERRORTYPE_T2790926119_H
#ifndef MLMUSICSERVICESTATUS_T1169446984_H
#define MLMUSICSERVICESTATUS_T1169446984_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLMusicServiceStatus
struct MLMusicServiceStatus_t1169446984
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLMusicServiceStatus::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLMusicServiceStatus_t1169446984, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLMUSICSERVICESTATUS_T1169446984_H
#ifndef SSLSTATUS_T191981556_H
#define SSLSTATUS_T191981556_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Mono.AppleTls.SslStatus
struct SslStatus_t191981556
{
public:
// System.Int32 Mono.AppleTls.SslStatus::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SslStatus_t191981556, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SSLSTATUS_T191981556_H
#ifndef MLINPUTCONTROLLERBUTTON_T2856573125_H
#define MLINPUTCONTROLLERBUTTON_T2856573125_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLInputControllerButton
struct MLInputControllerButton_t2856573125
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLInputControllerButton::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLInputControllerButton_t2856573125, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLINPUTCONTROLLERBUTTON_T2856573125_H
#ifndef MLCAMERAERROR_T1947259653_H
#define MLCAMERAERROR_T1947259653_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLCameraError
struct MLCameraError_t1947259653
{
public:
// System.Int32 UnityEngine.XR.MagicLeap.MLCameraError::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLCameraError_t1947259653, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLCAMERAERROR_T1947259653_H
#ifndef MLMUSICSERVICEPLAYBACKSTATE_T1137889811_H
#define MLMUSICSERVICEPLAYBACKSTATE_T1137889811_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLMusicServicePlaybackState
struct MLMusicServicePlaybackState_t1137889811
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLMusicServicePlaybackState::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLMusicServicePlaybackState_t1137889811, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLMUSICSERVICEPLAYBACKSTATE_T1137889811_H
#ifndef MLMUSICSERVICESHUFFLESTATE_T1943773829_H
#define MLMUSICSERVICESHUFFLESTATE_T1943773829_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLMusicServiceShuffleState
struct MLMusicServiceShuffleState_t1943773829
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLMusicServiceShuffleState::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLMusicServiceShuffleState_t1943773829, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLMUSICSERVICESHUFFLESTATE_T1943773829_H
#ifndef MLMUSICSERVICEREPEATSTATE_T1444330312_H
#define MLMUSICSERVICEREPEATSTATE_T1444330312_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.XR.MagicLeap.MLMusicServiceRepeatState
struct MLMusicServiceRepeatState_t1444330312
{
public:
// System.UInt32 UnityEngine.XR.MagicLeap.MLMusicServiceRepeatState::value__
uint32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MLMusicServiceRepeatState_t1444330312, ___value___2)); }
inline uint32_t get_value___2() const { return ___value___2; }
inline uint32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(uint32_t value)
{
___value___2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // MLMUSICSERVICEREPEATSTATE_T1444330312_H
extern "C" int32_t DEFAULT_CALL ReversePInvokeWrapper_AppleTlsContext_NativeReadCallback_m2315213031(intptr_t ___ptr0, intptr_t ___data1, intptr_t* ___dataLength2);
extern "C" int32_t DEFAULT_CALL ReversePInvokeWrapper_AppleTlsContext_NativeWriteCallback_m2714148351(intptr_t ___ptr0, intptr_t ___data1, intptr_t* ___dataLength2);
extern "C" int32_t CDECL ReversePInvokeWrapper_DeflateStreamNative_UnmanagedRead_m255710264(intptr_t ___buffer0, int32_t ___length1, intptr_t ___data2);
extern "C" int32_t CDECL ReversePInvokeWrapper_DeflateStreamNative_UnmanagedWrite_m232731864(intptr_t ___buffer0, int32_t ___length1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceAvailableCallback_m3969742651(intptr_t ___data0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceUnavailableCallback_m2084882024(intptr_t ___data0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceOpenedCallback_m638013595(intptr_t ___data0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceClosedCallback_m2256987599(intptr_t ___data0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceDisconnectedCallback_m764838951(intptr_t ___data0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnDeviceErrorCallback_m1201638698(int32_t ___error0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnCaptureStartedCallback_m2701034731(MLCameraResultExtras_t1014470651 * ___extra0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnCaptureFailedCallback_m2114035890(MLCameraResultExtras_t1014470651 * ___extra0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnCaptureBufferLostCallback_m1185316435(MLCameraResultExtras_t1014470651 * ___extra0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnCaptureProgressedCallback_m2172038068(uint64_t ___metadataHandle0, MLCameraResultExtras_t1014470651 * ___extra1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnCaptureCompletedCallback_m3255642694(uint64_t ___metadataHandle0, MLCameraResultExtras_t1014470651 * ___extra1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLCamera_OnImageBufferAvailableCallback_m1619805317(MLCameraOutput_t2680920266_marshaled_pinvoke* ___output0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureStartNative_m1933966868(uint8_t ___controllerId0, MLInputControllerTouchpadGesture_t3269538253 * ___touchpadGesture1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureContinueNative_m1229656175(uint8_t ___controllerId0, MLInputControllerTouchpadGesture_t3269538253 * ___touchpadGesture1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureEndNative_m3946959706(uint8_t ___controllerId0, MLInputControllerTouchpadGesture_t3269538253 * ___touchpadGesture1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerButtonDownNative_m3277904802(uint8_t ___controllerId0, uint32_t ___button1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerButtonUpNative_m501076513(uint8_t ___controllerId0, uint32_t ___button1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerConnectNative_m1934554086(uint8_t ___controllerId0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLInput_OnControllerDisconnectNative_m4196954462(uint8_t ___controllerId0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerReadyHandler_m3019168940(int32_t ___mediaPlayerID0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerCompleteHandler_m3874404068(int32_t ___mediaPlayerID0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerBufferingUpdateHandler_m975547798(int32_t ___percent0, int32_t ___mediaPlayerID1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerErrorHandler_m929478255(int32_t ___result0, intptr_t ___error1, int32_t ___mediaPlayerID2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerInfoHandler_m693427627(int32_t ___info0, int32_t ___extra1, int32_t ___mediaPlayerID2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerVideoSizeChangedHandler_m4130819638(int32_t ___width0, int32_t ___height1, int32_t ___mediaPlayerID2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerSeekCompletedHandler_m1169662868(int32_t ___mediaPlayerID0);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnPlaybackStateChangeCallback_m568888217(uint32_t ___state0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnRepeatStateChangeCallback_m2896970088(uint32_t ___state0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnShuffleStateChangeCallback_m2300479439(uint32_t ___state0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnMetadataChangeCallback_m1406700751(MLMusicServiceMetadata_t2439823319 * ___metadata0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnPositionChangeCallback_m577591537(int32_t ___position0, intptr_t ___data1);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnErrorCallback_m1420100273(uint32_t ___errorType0, int32_t ___errorCode1, intptr_t ___data2);
extern "C" void DEFAULT_CALL ReversePInvokeWrapper_MLMusicService_OnStatusChangeCallback_m4021757046(uint32_t ___status0, intptr_t ___data1);
extern const Il2CppMethodPointer g_ReversePInvokeWrapperPointers[37] =
{
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_AppleTlsContext_NativeReadCallback_m2315213031),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_AppleTlsContext_NativeWriteCallback_m2714148351),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_DeflateStreamNative_UnmanagedRead_m255710264),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_DeflateStreamNative_UnmanagedWrite_m232731864),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceAvailableCallback_m3969742651),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceUnavailableCallback_m2084882024),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceOpenedCallback_m638013595),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceClosedCallback_m2256987599),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceDisconnectedCallback_m764838951),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnDeviceErrorCallback_m1201638698),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnCaptureStartedCallback_m2701034731),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnCaptureFailedCallback_m2114035890),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnCaptureBufferLostCallback_m1185316435),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnCaptureProgressedCallback_m2172038068),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnCaptureCompletedCallback_m3255642694),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLCamera_OnImageBufferAvailableCallback_m1619805317),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureStartNative_m1933966868),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureContinueNative_m1229656175),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerTouchpadGestureEndNative_m3946959706),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerButtonDownNative_m3277904802),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerButtonUpNative_m501076513),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerConnectNative_m1934554086),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLInput_OnControllerDisconnectNative_m4196954462),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerReadyHandler_m3019168940),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerCompleteHandler_m3874404068),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerBufferingUpdateHandler_m975547798),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerErrorHandler_m929478255),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerInfoHandler_m693427627),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerVideoSizeChangedHandler_m4130819638),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMediaPlayerLumin_PlayerSeekCompletedHandler_m1169662868),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnPlaybackStateChangeCallback_m568888217),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnRepeatStateChangeCallback_m2896970088),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnShuffleStateChangeCallback_m2300479439),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnMetadataChangeCallback_m1406700751),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnPositionChangeCallback_m577591537),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnErrorCallback_m1420100273),
reinterpret_cast<Il2CppMethodPointer>(ReversePInvokeWrapper_MLMusicService_OnStatusChangeCallback_m4021757046),
};
|
2836941688f31db4e678066eac45138ad1d1398e | 7ded04bd59db7747b861e71d208f7fc9a1127b0f | /NuyEngine/NuyEngine-core/Source/Maths/Vector4.cpp | b257f4332a9a5904d8a3de8b78d26b0236171c57 | [] | no_license | andreybicalho/NuyEngine | b436216fbef0cbdbe703c59cae96d3106cf146ca | 86a700f41463b934fc61d2e3690c2f7a61b70913 | refs/heads/master | 2021-09-20T18:33:07.432838 | 2018-08-14T02:30:31 | 2018-08-14T02:30:31 | 135,965,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,819 | cpp | Vector4.cpp | #include "Vector4.h"
namespace nuy { namespace maths {
// globals static initialization
const Vector4 Vector4::ZeroVector(0.0f, 0.0f, 0.0f, 0.0f);
const Vector4 Vector4::UnitVector(1.0f, 1.0f, 1.0f, 1.0f);
Vector4::Vector4(float scalar)
: X(scalar), Y(scalar), Z(scalar), W(scalar)
{
}
Vector4::Vector4(float x, float y, float z, float w)
: X(x), Y(y), Z(z), W(w)
{
}
// arithmetics
Vector4 Vector4::operator+(const Vector4& other) const
{
return Vector4(X + other.X, Y + other.Y, Z + other.Z, W + other.W);
}
Vector4 Vector4::operator+(const float scalar) const
{
return Vector4(X + scalar, Y + scalar, Z + scalar, W + scalar);
}
Vector4 Vector4::operator-(const Vector4& other) const
{
return Vector4(X - other.X, Y - other.Y, Z - other.Z, W - other.W);
}
Vector4 Vector4::operator-(const float scalar) const
{
return Vector4(X - scalar, Y - scalar, Z - scalar, W - scalar);
}
Vector4 Vector4::operator*(const Vector4& other) const
{
return Vector4(X * other.X, Y * other.Y, Z * other.Z, W * other.W);
}
Vector4 Vector4::operator*(const float scalar) const
{
return Vector4(X * scalar, Y * scalar, Z * scalar, W * scalar);
}
Vector4 Vector4::operator/(const Vector4& other) const
{
return Vector4(X / other.X, Y / other.Y, Z / other.Z, W / other.W);
}
Vector4 Vector4::operator/(const float scalar) const
{
return Vector4(X / scalar, Y / scalar, Z / scalar, W / scalar);
}
Vector4 Vector4::Add(const Vector4& other)
{
X += other.X;
Y += other.Y;
Z += other.Z;
W += other.W;
return *this;
}
Vector4 Vector4::Subtract(const Vector4& other)
{
X -= other.X;
Y -= other.Y;
Z -= other.Z;
W -= other.W;
return *this;
}
Vector4 Vector4::Multiply(const Vector4& other)
{
X *= other.X;
Y *= other.Y;
Z *= other.Z;
W *= other.W;
return *this;
}
Vector4 Vector4::Divide(const Vector4& other)
{
X /= other.X;
Y /= other.Y;
Z /= other.Z;
W /= other.W;
return *this;
}
Vector4 Vector4::operator+=(const float scalar)
{
X += scalar;
Y += scalar;
Z += scalar;
W += scalar;
return *this;
}
Vector4 Vector4::operator-=(const float scalar)
{
X -= scalar;
Y -= scalar;
Z -= scalar;
W -= scalar;
return *this;
}
Vector4 Vector4::operator*=(const float scalar)
{
X *= scalar;
Y *= scalar;
Z *= scalar;
W *= scalar;
return *this;
}
Vector4 Vector4::operator/=(const float scalar)
{
X /= scalar;
Y /= scalar;
Z /= scalar;
W /= scalar;
return *this;
}
Vector4 Vector4::operator+=(const Vector4& other)
{
return Add(other);
}
Vector4 Vector4::operator-=(const Vector4& other)
{
return Subtract(other);
}
Vector4 Vector4::operator*=(const Vector4& other)
{
return Multiply(other);
}
Vector4 Vector4::operator/=(const Vector4& other)
{
return Divide(other);
}
// logic
bool Vector4::operator==(const Vector4& other) const
{
return X == other.X && Y == other.Y && Z == other.Z && W == other.W;
}
bool Vector4::operator!=(const Vector4& other) const
{
return !(*this == other);
}
bool Vector4::operator<(const Vector4 & other) const
{
return X < other.X && Y < other.Y && Z < other.Z && W < other.W;
}
bool Vector4::operator<=(const Vector4& other) const
{
return X <= other.X && Y <= other.Y && Z <= other.Z && W <= other.W;
}
bool Vector4::operator>(const Vector4& other) const
{
return X > other.X && Y > other.Y && Z > other.Z && W > other.W;
}
bool Vector4::operator>=(const Vector4& other) const
{
return X >= other.X && Y >= other.Y && Z >= other.Z && W >= other.W;
}
// visualization
std::ostream& operator<<(std::ostream& stream, const Vector4& vector)
{
stream << "Vector4: (" << vector.X << ", " << vector.Y << ", " << vector.Z << ", " << vector.W << ")";
return stream;
}
} } |
f2bb9ddfd031bfa9c4047d15fba56344420cfd65 | addf488ba98b8d09b0c430779ebd2649d29a3fea | /kdepim/kaddressbook/printing/printprogress.h | fd2a494f89923fb2f770aa9196dc31bb5970d63b | [] | no_license | iegor/kdesktop | 3d014d51a1fafaec18be2826ca3aa17597af9c07 | d5dccbe01eeb7c0e82ac5647cf2bc2d4c7beda0b | refs/heads/master | 2020-05-16T08:17:14.972852 | 2013-02-19T21:47:05 | 2013-02-19T21:47:05 | 9,459,573 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,884 | h | printprogress.h | /*
This file is part of KAddressBook.
Copyright (c) 1996-2002 Mirko Boehm <mirko@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#ifndef PRINTPROGRESS_H
#define PRINTPROGRESS_H
#include <qwidget.h>
class QProgressBar;
class QString;
class QTextBrowser;
namespace KABPrinting {
/**
This defines a simple widget to display print progress
information. It is provided to all print styles during a print
process. It displays messages and a a progress bar.
*/
class PrintProgress : public QWidget
{
Q_OBJECT
public:
PrintProgress( QWidget *parent, const char *name = 0 );
~PrintProgress();
/**
Add a message to the message log. Give the user something to admire :-)
*/
void addMessage( const QString& );
/**
Set the progress to a certain amount. Steps are from 0 to 100.
*/
void setProgress( int );
private:
QStringList mMessages;
QTextBrowser* mLogBrowser;
QProgressBar* mProgressBar;
};
}
#endif
|
c354f10ac76ad733257979d0d77b91491c17b34c | f654ca71af356cc87b5019741029b28dcecf76f1 | /Sassafras/main.cpp | 9f48514099cdbd3bb7f052125fcc39eefb837e02 | [] | no_license | No-Face-the-3rd/Graphics | 1205af54bea496815d5152528ca1b4bb6cd039fd | aadbc215c7359cc056a78218f1f226a4fd7a845c | refs/heads/master | 2020-04-18T01:15:41.735989 | 2016-10-20T16:05:00 | 2016-10-20T16:05:00 | 66,578,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | main.cpp |
#include "gManager.h"
const int screenWidth = 1360, screenHeight = 768;
const char *name = "Meow";
void main()
{
gManager manager(screenWidth, screenHeight, name);
manager.init();
while (manager.step())
{
manager.draw();
}
manager.term();
}
|
8953325256b0b18915a5c472cdd9ff387ad80e49 | e753f8ab10eb6732f272217169e48ab4754295ee | /devel/open-beagle/dragonfly/patch-PACC_Math_Vector.hpp | 43be910aa6aa812f79c5fe30abf51803acc69443 | [
"BSD-2-Clause"
] | permissive | DragonFlyBSD/DPorts | dd2e68f0c11a5359bf1b3e456ab21cbcd9529e1c | 4b77fb40db21fdbd8de66d1a2756ac1aad04d505 | refs/heads/master | 2023-08-12T13:54:46.709702 | 2023-07-28T09:53:12 | 2023-07-28T09:53:12 | 6,439,865 | 78 | 52 | NOASSERTION | 2023-09-02T06:27:16 | 2012-10-29T11:59:35 | null | UTF-8 | C++ | false | false | 230 | hpp | patch-PACC_Math_Vector.hpp | --- PACC/Math/Vector.hpp.orig 2007-09-11 05:25:55.000000000 +0300
+++ PACC/Math/Vector.hpp
@@ -42,6 +42,7 @@
#include "XML/Document.hpp"
#include "XML/Streamer.hpp"
#include <cmath>
+#include <algorithm>
namespace PACC {
|
149e55ad5d5e59fbc2ca97e4f4a57fd7ffa38e53 | 6a9a323a38c4788e4f44e4335efc7a1be8551942 | /src/MyMath.h | e84bff54507ce8cb24df2b233def35ee064c028e | [
"MIT"
] | permissive | jintiao/miura | 23ae0f5571c717dd5ee4f865e7b17c76621adbb7 | 0e12d948880bbc618c58f5c62e4477a67861ef58 | refs/heads/master | 2020-12-25T15:17:31.677349 | 2016-09-08T02:49:00 | 2016-09-08T02:49:00 | 66,853,778 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 847 | h | MyMath.h | #pragma once
#ifdef _WIN
#pragma warning(disable : 4201)
#endif
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
namespace Math
{
static const float pi = (float)M_PI;
typedef glm::vec2 Vector2;
typedef glm::vec3 Vector3;
typedef glm::mat4 Matrix4;
float Degree2Radians (float degree);
Matrix4 CreatePerspectiveMatrix (float fov, float ratio, float near, float far);
Matrix4 CreateLookatMatrix (const Vector3 &eye, const Vector3 &at, const Vector3 &up);
Vector3 Cross (const Vector3 &lhs, const Vector3 &rhs);
float Dot (const Vector2 &lhs, const Vector2 &rhs);
float Dot (const Vector3 &lhs, const Vector3 &rhs);
float Length (const Vector2 &v);
Vector2 Normalize (const Vector2 &v);
Vector3 Normalize (const Vector3 &v);
Matrix4 Invert (const Matrix4 &m);
Matrix4 Transpose (const Matrix4 &m);
} // namespace Math
|
d3be3e14a2b9faef056fb6f238dfaff7e75dcc93 | 5ccdbfcdb4777205bd426498a71ed1debf094b78 | /Assignment 3/Q4/University.h | fc524877e51cf8aa6ca2446d91591ebf6fc1b91a | [] | no_license | QUaSaR14/ioom | ba49e51302d97c63afe5b4724ed7bcf95060699b | 7b2410efda8826dafed310244db766c984e5d97c | refs/heads/master | 2020-07-10T11:24:26.321939 | 2019-10-02T18:27:07 | 2019-10-02T18:27:07 | 204,252,003 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | h | University.h | #include<string>
#include<iostream>
using namespace std;
class University
{
protected:
string name;
string department;
string person_name;
public:
University();
string getName();
string getDepartment();
string getPerson();
void setName(const string& n);
void setDepartment(const string& d);
void setPerson(const string& p);
University(const string& n,const string& d,const string& p);
University(const University& obj);
~University();
void display();
};
|
2f703e6c9c89a9ce86107c9c4e5d99af203ad64d | 3150892592086d717b22c9189e56fd63405c9a9f | /apps/pipeline/inc/pipeline_app.hpp | d7ad75c7e79409f50c4401fd6acc92deb26a4433 | [
"MIT"
] | permissive | CrankOne/StromaV | 701d2197486cc03a6b3e886abf951a7f41e88d39 | ef271444d496f7a2552058638c023bc86684e780 | refs/heads/master | 2021-01-12T07:57:04.344438 | 2017-04-15T10:09:15 | 2017-04-15T10:09:15 | 77,057,562 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | hpp | pipeline_app.hpp | /*
* Copyright (c) 2016 Renat R. Dusaev <crank@qcrypt.org>
* Author: Renat R. Dusaev <crank@qcrypt.org>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
# ifndef H_P348_ANALYSIS_TIME_READING_APPLICATION_H_HPP
# define H_P348_ANALYSIS_TIME_READING_APPLICATION_H_HPP
# include "app/analysis.hpp"
namespace sV {
class App : public sV::AnalysisApplication {
protected:
virtual int _V_run() override;
public:
App( sV::po::variables_map * vmPtr ) :
AbstractApplication(vmPtr),
sV::AnalysisApplication(vmPtr) {}
~App(){}
}; // class Application
} // namespace p348
# endif // H_P348_ANALYSIS_TIME_READING_APPLICATION_H_HPP
|
5c9e12f3201217ae5159ea1132c12c36b9a91c42 | d093e5dbdf4fb08eacbe2ec3cfc070e4c58c0f3e | /Source/Core/TornadoEngine/Components/Graphic/UniverseCameraComponent.h | 1a68cb17c283b688f83e47f1fcef157a2fd784a4 | [
"MIT"
] | permissive | RamilGauss/MMO-Framework | 3bd57e800f20b6447b494009eb3d7a49dfeb1402 | fa4ec6427a3a891954f97311af626f8753023ec2 | refs/heads/master | 2023-09-02T17:50:25.742920 | 2023-09-01T09:17:26 | 2023-09-01T09:17:26 | 15,496,543 | 32 | 20 | MIT | 2023-05-11T07:10:07 | 2013-12-28T17:54:28 | C++ | UTF-8 | C++ | false | false | 887 | h | UniverseCameraComponent.h | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#pragma once
#include "TypeDef.h"
#include <string>
#include <ECS/include/IComponent.h>
#include "GraphicEngine/Camera.h"
namespace nsGraphicWrapper
{
struct DllExport TUniverseCameraComponent : nsECSFramework::IComponent
{
std::string universeGuid;
#pragma IGNORE_ATTRIBUTE
mutable nsGraphicEngine::TCamera* value = nullptr;
bool IsLess(const IComponent* pOther) const override
{
return universeGuid < ((TUniverseCameraComponent*)pOther)->universeGuid;
}
bool IsEqual(const IComponent* pOther) const override
{
return universeGuid == ((TUniverseCameraComponent*)pOther)->universeGuid;
}
};
} |
35cd6070bc854d15f1bd1cef58bb050ca04af87f | 9b4b0c3faa5f3002ed85c3054164e0b9fb427f56 | /Codes/1300/1302.cpp | e848c99fe9b313940e22a88147c8d60b14034432 | [] | no_license | calofmijuck/BOJ | 246ae31b830d448c777878a90e1d658b7cdf27f4 | 4b29e0c7f487aac3186661176d2795f85f0ab21b | refs/heads/master | 2023-04-27T04:47:11.205041 | 2023-04-17T01:53:03 | 2023-04-17T01:53:03 | 155,859,002 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | 1302.cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, cnt = 0;
string str, ans;
cin >> n;
map<string, int> mp;
for(int i = 0; i < n; ++i) {
cin >> str;
mp[str]++;
}
for(auto s : mp) {
if(mp[s.first] > cnt) {
ans = s.first;
cnt = mp[s.first];
}
}
cout << ans;
return 0;
}
|
cf24dd935142844058a342c7a0465f8d0ac6af39 | afb650120fa5502593b7e8641ba621a6a27ce638 | /qt/qt1/main.cpp | 8880c65fade1442a2efae8764c02bb96ffc6ce15 | [] | no_license | navyzhou926/qt-test | 0997d8844ff9fdb1843f66abe22cd218b925249c | a0e8a97a06c4a795f5d516d858fb9ac243d2364f | refs/heads/master | 2020-12-24T16:49:23.653763 | 2011-03-28T09:22:04 | 2011-03-28T09:22:04 | 1,535,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | cpp | main.cpp | #include <QApplication>
#include <QWidget>
#include <QTextEdit>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget win;
win.show();
QVBoxLayout *layout = new QVBoxLayout(&win);
QTextEdit EditLeftTop(&win);
// EditLeftTop.show();
QTextEdit EditLeftDown;
// EditLeftDown.show();
layout->addWidget(&EditLeftTop, 8);
layout->addWidget(&EditLeftDown, 1);
return app.exec();
}
|
8778e63ede0ae5a35cb6f4fd6467682c49d550ab | 793c8848753f530aab28076a4077deac815af5ac | /src/dskphone/ui/t48/directoryui/src/contactdetailtitle.cpp | c7c7ce5ee0e49ff1ed896fa37f256bc957819ed0 | [] | no_license | Parantido/sipphone | 4c1b9b18a7a6e478514fe0aadb79335e734bc016 | f402efb088bb42900867608cc9ccf15d9b946d7d | refs/heads/master | 2021-09-10T20:12:36.553640 | 2018-03-30T12:44:13 | 2018-03-30T12:44:13 | 263,628,242 | 1 | 0 | null | 2020-05-13T12:49:19 | 2020-05-13T12:49:18 | null | UTF-8 | C++ | false | false | 11,608 | cpp | contactdetailtitle.cpp | #include <QtGui>
#include "contactdetailtitle.h"
#include "directorylistaction.h"
#include "baseui/t4xpicpath.h"
#include "imagemanager/modimagemanager.h"
#include "uikernel/qwidgetutility.h"
#include "qtcommon/qmisc.h"
#include "qtcommon/xmlhelper.h"
#include "configparser/modconfigparser.h"
#include <configiddefine.h>
#include "uikernel/languagehelper.h"
#include "translateiddefine.h"
#include "directorymgr.h"
namespace
{
#define CONTACT_DETAIL_TITLE_HEIGHT 73
#define CONTACT_DETAIL_TITLE_BTN_COMMON_TOP 0
#define CONTACT_DETAIL_TITLE_BTN_COMMON_WIDTH 82
#define CONTACT_DETAIL_TITLE_BTN_COMMON_HEIGHT 71
#define CONTACT_DETAIL_TITLE_ICON_COMMON_TOP 15
#define CONTACT_DETAIL_TITLE_TEXT_COMMON_TOP 39
#define CONTACT_DETAIL_TITLE_BTN_RIGHT 0
#define CONTACT_DETAIL_TITLE_BTN_SPACE 1
#define CONTACT_DETAIL_TITLE_BTN_SEPARATE 1
#define CONTACT_DETAIL_TREE_TITLE_SEPARATE_TOP 21
#define CONTACT_DETAIL_TREE_TITLE_SEPARATE_WIDTH 1
#define CONTACT_DETAIL_TREE_TITLE_SEPARATE_HEIGHT 30
#define CONTACT_DETAIL_TITLE_FONT_SIZE_BTN_BAR 14
}
CContactDetailTitle::CContactDetailTitle(CFrameList * pFrameList/* = NULL*/,
IFrameTitleAction * pAction/* = NULL*/)
: CFrameListTitle(FRAME_LIST_TITLE_TYPE_CONTACT_DETAIL_TITLE, pFrameList, pAction)
, m_btnDial(this)
, m_btnMove(this)
, m_btnEdit(this)
, m_btnBlackList(this)
, m_btnBar(this, false)
, m_btnDel(this)
#if IF_FEATURE_METASWITCH_DIRECTORY
, m_btnAddMtswContact(this)
#endif
#if IF_FEATURE_FAVORITE_DIR
, m_btnFavorite(this)
, m_btnRemoveFavorite(this)
#endif
, m_nBtnCount(0)
{
setGeometry(0, 0, 0, CONTACT_DETAIL_TITLE_HEIGHT);
qWidgetUtility::setFontStyle(this, CONTACT_DETAIL_TITLE_FONT_SIZE_BTN_BAR);
setObjectName("CContactDetailTitle");
}
CContactDetailTitle::~CContactDetailTitle(void)
{
}
bool CContactDetailTitle::IsContactDetailTitle(CFrameListTitlePtr pTitle)
{
if (NULL != pTitle && FRAME_LIST_TITLE_TYPE_CONTACT_DETAIL_TITLE == pTitle->GetType())
{
return true;
}
return false;
}
void CContactDetailTitle::SetBtnCount(int nCount)
{
if (nCount > MAX_BTN_COUNT)
{
return;
}
m_btnBar.SetBtnCount(nCount);
m_nBtnCount = 0;
m_btnDial.SetRect(0, 0, 0, 0);
m_btnMove.SetRect(0, 0, 0, 0);
m_btnEdit.SetRect(0, 0, 0, 0);
m_btnBlackList.SetRect(0, 0, 0, 0);
m_btnDel.SetRect(0, 0, 0, 0);
#if IF_FEATURE_METASWITCH_DIRECTORY
m_btnAddMtswContact.SetRect(0, 0, 0, 0);
#endif
#if IF_FEATURE_FAVORITE_DIR
m_btnFavorite.SetRect(0, 0, 0, 0);
m_btnRemoveFavorite.SetRect(0, 0, 0, 0);
#endif
m_btnDial.ResetDown();
m_btnMove.ResetDown();
m_btnEdit.ResetDown();
m_btnBlackList.ResetDown();
m_btnDel.ResetDown();
#if IF_FEATURE_METASWITCH_DIRECTORY
m_btnAddMtswContact.ResetDown();
#endif
#if IF_FEATURE_FAVORITE_DIR
m_btnFavorite.ResetDown();
m_btnRemoveFavorite.ResetDown();
#endif
for (int i = 0; i < MAX_BTN_COUNT; ++i)
{
m_arrTitle[i] = "";
}
}
void CContactDetailTitle::AddButton(int nAction, const QString & strTitle)
{
if (m_nBtnCount >= MAX_BTN_COUNT)
{
return;
}
CTitleButton * pBtn = NULL;
switch (nAction)
{
case LIST_TITLE_ACTION_DEL_CONTACT:
{
pBtn = &m_btnDel;
}
break;
case LIST_TITLE_ACTION_MOVE_CONTACT:
{
pBtn = &m_btnMove;
}
break;
case LIST_TITLE_ACTION_ADD_BLACKLIST:
{
pBtn = &m_btnBlackList;
}
break;
case LIST_TITLE_ACTION_DIAL_CONTACT:
{
pBtn = &m_btnDial;
}
break;
case LIST_TITLE_ACTION_EDIT_CALLLOG:
{
pBtn = &m_btnEdit;
}
break;
#if IF_FEATURE_METASWITCH_DIRECTORY
case LIST_TITLE_ACTION_MOVE_MTSW_CONTACT:
{
pBtn = &m_btnAddMtswContact;
}
break;
#endif
#if IF_FEATURE_FAVORITE_DIR
case LIST_TITLE_ACTION_ADD_FAVORITE:
{
pBtn = &m_btnFavorite;
}
break;
case LIST_TITLE_ACTION_REMOVE_FAVORITE:
{
pBtn = &m_btnRemoveFavorite;
}
break;
#endif
default:
break;
}
if (NULL == pBtn)
{
return;
}
m_btnBar.SetBtn(m_nBtnCount, pBtn);
m_arrTitle[m_nBtnCount] = strTitle;
++m_nBtnCount;
}
void CContactDetailTitle::mousePressEvent(QMouseEvent * pEvent)
{
m_btnBar.ProcessMousePress(pEvent);
}
void CContactDetailTitle::mouseReleaseEvent(QMouseEvent * pEvent)
{
CButtonWrapper * pBtn = m_btnBar.ProcessMouseRelease(pEvent);
if (NULL == pBtn)
{
return;
}
if (pBtn == &m_btnDel)
{
DoAction(LIST_TITLE_ACTION_DEL_CONTACT);
}
else if (pBtn == &m_btnMove)
{
DoAction(LIST_TITLE_ACTION_MOVE_CONTACT);
}
else if (pBtn == &m_btnBlackList)
{
DoAction(LIST_TITLE_ACTION_ADD_BLACKLIST);
}
else if (pBtn == &m_btnDial)
{
DoAction(LIST_TITLE_ACTION_DIAL_CONTACT);
}
else if (pBtn == &m_btnEdit)
{
DoAction(LIST_TITLE_ACTION_EDIT_CALLLOG);
}
#if IF_FEATURE_METASWITCH_DIRECTORY
else if (pBtn == &m_btnAddMtswContact)
{
DoAction(LIST_TITLE_ACTION_MOVE_MTSW_CONTACT);
}
#endif
#if IF_FEATURE_FAVORITE_DIR
else if (pBtn == &m_btnFavorite)
{
if (configParser_GetConfigInt(kszFavoriteDirAutoSetSwitch) == 1)
{
DoAction(LIST_TITLE_ACTION_ADD_FAVORITE);
}
}
else if (pBtn == &m_btnRemoveFavorite)
{
if (configParser_GetConfigInt(kszFavoriteDirAutoSetSwitch) == 1)
{
DoAction(LIST_TITLE_ACTION_REMOVE_FAVORITE);
}
}
#endif
}
void CContactDetailTitle::paintEvent(QPaintEvent * pEvent)
{
QStylePainter stylePainter(this);
int nBtnCount = m_nBtnCount;
if (nBtnCount > MAX_BTN_COUNT)
{
nBtnCount = MAX_BTN_COUNT;
}
for (int i = 0; i < nBtnCount; ++i)
{
CTitleButton * pBtn = (CTitleButton *)m_btnBar.GetBtn(i);
if (NULL == pBtn)
{
continue;
}
// 画按钮
const QString & strTitle = m_arrTitle[i];
if (pBtn == &m_btnDial)
{
if (g_DirectoryMgr.GetIsInSelecting())
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_MODIFIED_GROUP_SELECT,
LANG_TRANSLATE(TRID_SELECT));
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
else
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DIAL, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
}
else if (pBtn == &m_btnMove)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_ADD_CONTACT, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
else if (pBtn == &m_btnEdit)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_CALLLOG_EDIT, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
else if (pBtn == &m_btnBlackList)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_ADD_BLACKLIST, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
else if (pBtn == &m_btnDel)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DEL_CONTACT, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
#if IF_FEATURE_METASWITCH_DIRECTORY
else if (pBtn == &m_btnAddMtswContact)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_ADD_CONTACT, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
#endif
#if IF_FEATURE_FAVORITE_DIR
else if (configParser_GetConfigInt(kszFavoriteDirAutoSetSwitch) == 1
&& pBtn == &m_btnFavorite)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_ADD_FAVORITE, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
else if (configParser_GetConfigInt(kszFavoriteDirAutoSetSwitch) == 1
&& pBtn == &m_btnRemoveFavorite)
{
pBtn->PaintVButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_REMOVE_FAVORITE, strTitle);
pBtn->PaintButton(stylePainter, NULL, PIC_DIRECTORY_DIRECTORY_DETAIL_BTN_CLICK);
}
#endif
// 画分隔线
if ((i + 1) != nBtnCount)
{
QRect rcBtn = pBtn->GetRect();
QRect rcSeparate(rcBtn.right() + CONTACT_DETAIL_TITLE_BTN_SEPARATE,
CONTACT_DETAIL_TREE_TITLE_SEPARATE_TOP,
CONTACT_DETAIL_TREE_TITLE_SEPARATE_WIDTH, CONTACT_DETAIL_TREE_TITLE_SEPARATE_HEIGHT);
QPixmap pmSeparate = THEME_GET_BMP(PIC_DIRECTORY_DIRECTORY_SEPARATE);
if (!pmSeparate.isNull())
{
stylePainter.drawPixmap(rcSeparate, pmSeparate);
}
}
}
}
void CContactDetailTitle::Relayout()
{
QRect rcTitle = rect();
int nTotalWidth = CONTACT_DETAIL_TITLE_BTN_COMMON_WIDTH * m_nBtnCount +
CONTACT_DETAIL_TITLE_BTN_SPACE * (m_nBtnCount - 1);
int nLeft = rcTitle.right() - CONTACT_DETAIL_TITLE_BTN_RIGHT - nTotalWidth;
int nBtnCount = m_nBtnCount;
if (nBtnCount > MAX_BTN_COUNT)
{
nBtnCount = MAX_BTN_COUNT;
}
for (int i = 0; i < nBtnCount; ++i)
{
CTitleButton * pBtn = (CTitleButton *)m_btnBar.GetBtn(i);
if (NULL == pBtn)
{
continue;
}
pBtn->SetRect(nLeft, CONTACT_DETAIL_TITLE_BTN_COMMON_TOP,
CONTACT_DETAIL_TITLE_BTN_COMMON_WIDTH, CONTACT_DETAIL_TITLE_BTN_COMMON_HEIGHT);
pBtn->SetIconTop(CONTACT_DETAIL_TITLE_ICON_COMMON_TOP);
pBtn->SetTextTop(CONTACT_DETAIL_TITLE_TEXT_COMMON_TOP);
nLeft += (CONTACT_DETAIL_TITLE_BTN_COMMON_WIDTH + CONTACT_DETAIL_TITLE_BTN_SPACE);
}
}
#ifdef IF_ENABLE_TESTABILITY
QString CContactDetailTitle::GetTestInfo()
{
xml_document doc;
xml_node nodeRoot = doc.append_child("testinfo");
AddBtnNode(nodeRoot, m_btnDial, BTN_DIAL, fromQString(m_btnDial.GetText()));
AddBtnNode(nodeRoot, m_btnMove, BTN_MOVE, fromQString(m_btnMove.GetText()));
AddBtnNode(nodeRoot, m_btnEdit, BTN_EDIT, fromQString(m_btnEdit.GetText()));
AddBtnNode(nodeRoot, m_btnBlackList, BTN_BLACKLIST, fromQString(m_btnBlackList.GetText()));
#if IF_FEATURE_METASWITCH_DIRECTORY
// Metaswitch按钮
AddBtnNode(nodeRoot, m_btnAddMtswContact, BTN_ADD, fromQString(m_btnAddMtswContact.GetText()));
#endif
#if IF_FEATURE_FAVORITE_DIR
if (configParser_GetConfigInt(kszFavoriteDirAutoSetSwitch) == 1)
{
AddBtnNode(nodeRoot, m_btnFavorite, BTN_ADD, fromQString(m_btnFavorite.GetText()));
AddBtnNode(nodeRoot, m_btnRemoveFavorite, BTN_ADD, fromQString(m_btnRemoveFavorite.GetText()));
}
#endif
AddBtnNode(nodeRoot, m_btnDel, BTN_DELETE, fromQString(m_btnDel.GetText()));
QString strTestinfo;
GetStringFromXml(doc, strTestinfo);
return strTestinfo;
}
#endif |
bd6e2f75d291c653e80eb4a86d2948078a777a25 | 76d02d9f63c90f36a74f0c9fb2ee00d7838001c2 | /src/ias/rule/rule_condition_static.cpp | dc1512fd2ac63a9f6826073c1e88cdfe18314f29 | [
"Apache-2.0"
] | permissive | JoeriHermans/Intelligent-Automation-System | 7630d33922fbef87ee3a673282da0b7809643c19 | b09c9f2b0c018ac5d12ab01d25297a0a92724e4c | refs/heads/master | 2020-12-20T07:42:22.062147 | 2016-04-12T09:31:39 | 2016-04-12T09:31:39 | 22,039,895 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,299 | cpp | rule_condition_static.cpp | /**
* A class which describes the properties and actions of a static
* condition rule.
*
* @date Aug 1, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
// Application dependencies.
#include <ias/rule/rule_condition_static.h>
// END Includes. /////////////////////////////////////////////////////
void RuleConditionStatic::setDevice( Device * device ) {
// Checking the precondition.
assert( device != nullptr );
mDevice = device;
}
void RuleConditionStatic::setMember( const std::string & member ) {
// Checking the precondition.
assert( member.length() > 0 );
mMemberIdentifier = member;
}
void RuleConditionStatic::setValue( const std::string & value ) {
// Checking the precondition.
assert( value.length() > 0 );
mValue = value;
}
void RuleConditionStatic::setOperator( const Operator * op ) {
// Checking the precondition.
assert( op != nullptr );
mOperator = op;
}
RuleConditionStatic::RuleConditionStatic( Device * device,
const std::string & memberIdentifier,
const std::string & value,
const Operator * op ) {
setDevice(device);
setMember(memberIdentifier);
setValue(value);
setOperator(op);
}
RuleConditionStatic::~RuleConditionStatic( void ) {
// Nothing to do here.
}
bool RuleConditionStatic::evaluate( void ) const {
return ( mOperator->evaluate(mDevice->get(mMemberIdentifier),mValue) );
}
|
7a6d888ce19ea23eff395fb4a54a514b02112a33 | dc50e57268914984cb96f411f7a78eec7b3bb795 | /sprite.cpp | 539bae2a0a050eb104d9a8a25132f4f1d7bbc6d3 | [] | no_license | nanasesakamoto/game_1 | 0359eff1b076e94d18050b5d4684a419aa828cd5 | 8ee4de937456885ee394a99567cc9299cf3f23b8 | refs/heads/master | 2021-01-16T16:31:43.735850 | 2020-03-04T14:51:11 | 2020-03-04T14:51:11 | 243,184,316 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,683 | cpp | sprite.cpp |
#include <d3dx9.h>
#include <math.h>
#include "mydirect3d.h"
#include "texture.h"
/*------------------------------------------------------------------------------
構造体宣言
------------------------------------------------------------------------------*/
// 2Dポリゴン頂点構造体
typedef struct Vertex2D_tag
{
D3DXVECTOR4 position; // 頂点座標(座標変換済み頂点)
D3DCOLOR color;
D3DXVECTOR2 texcoord;
} Vertex2D;
#define FVF_VERTEX2D (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) // 2Dポリゴン頂点フォーマット
/*------------------------------------------------------------------------------
グローバル変数宣言
------------------------------------------------------------------------------*/
static D3DCOLOR g_Color = 0xffffffff;
// static D3DCOLOR g_Color = D3DCOLOR_RGBA(255, 255, 255, 255);
/*------------------------------------------------------------------------------
関数定義
------------------------------------------------------------------------------*/
// スプライトポリゴンの頂点カラー設定
void Sprite_SetColor(D3DCOLOR color)
{
g_Color = color;
}
// スプライト描画
// ※テクスチャ切り取り幅、高さと同じ大きさのスプライトを指定座標に描画する
void Sprite_Draw(TextureIndex texture_index, float dx, float dy, int tx, int ty,int tw, int th, float sx, float sy)
{
LPDIRECT3DDEVICE9 pDevice = MyDirect3D_GetDevice();
if( !pDevice ) return;
float w = (float)Texture_GetWidth(texture_index);
float h = (float)Texture_GetHeight(texture_index);
// UV座標計算
float u[2], v[2];
u[0] = (float)tx / w;
v[0] = (float)ty / h;
u[1] = (float)(tx + tw) / w;
v[1] = (float)(ty + th) / h;
Vertex2D vertexes[] = {
{ D3DXVECTOR4((dx - 0.5f)*sx, (dy - 0.5f)*sy, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[0]) },
{ D3DXVECTOR4((dx + tw - 0.5f)*sx, (dy - 0.5f)*sy, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[0]) },
{ D3DXVECTOR4((dx - 0.5f)*sx, (dy + th - 0.5f)*sy, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[0], v[1]) },
{ D3DXVECTOR4((dx + tw - 0.5f)*sx, (dy + th - 0.5f)*sy, 0.0f, 1.0f), g_Color, D3DXVECTOR2(u[1], v[1]) },
};
pDevice->SetFVF(FVF_VERTEX2D);
pDevice->SetTexture(0, Texture_GetTexture(texture_index));
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D));
}
//明滅用スプライト描画
void Sprite_Draw2(TextureIndex texture_index, float dx, float dy, int tx, int ty, int tw, int th, int Alpha)
{
D3DCOLOR color; // 頂点カラー
// 半透明処理をするかどうかを判断し、頂点カラーを決定
if (Alpha == 255) color = D3DCOLOR_XRGB(255, 255, 255);
else color = D3DCOLOR_RGBA(255, 255, 255, Alpha);
LPDIRECT3DDEVICE9 pDevice = MyDirect3D_GetDevice();
if (!pDevice) return;
float w = (float)Texture_GetWidth(texture_index);
float h = (float)Texture_GetHeight(texture_index);
// UV座標計算
float u[2], v[2];
u[0] = (float)tx / w;
v[0] = (float)ty / h;
u[1] = (float)(tx + tw) / w;
v[1] = (float)(ty + th) / h;
Vertex2D vertexes[] = {
{ D3DXVECTOR4(dx - 0.5f, dy - 0.5f, 0.0f, 1.0f), color, D3DXVECTOR2(u[0], v[0]) },
{ D3DXVECTOR4(dx + tw - 0.5f, dy - 0.5f, 0.0f, 1.0f), color, D3DXVECTOR2(u[1], v[0]) },
{ D3DXVECTOR4(dx - 0.5f, dy + th - 0.5f, 0.0f, 1.0f), color, D3DXVECTOR2(u[0], v[1]) },
{ D3DXVECTOR4(dx + tw - 0.5f, dy + th - 0.5f, 0.0f, 1.0f), color, D3DXVECTOR2(u[1], v[1]) },
};
pDevice->SetFVF(FVF_VERTEX2D);
pDevice->SetTexture(0, Texture_GetTexture(texture_index));
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, vertexes, sizeof(Vertex2D));
}
|
0e5695f9b5d4b658c4196dda6d6d50d994d2b9b5 | a766ee23c2243f850ebdb83a69d0fb8a5359c07d | /Fall 2018/数据结构/9.26_HW/remove-duplicates-from-sorted-list-ii.cpp | b0375dbf8ac033b2639500ae985b2edc08b830b8 | [
"MIT"
] | permissive | jasha64/jasha64 | 24e127e57dd8852e5a006ba98be6c17312733597 | 653881f0f79075a628f98857e77eac27aef1919d | refs/heads/master | 2021-06-23T08:34:27.220649 | 2021-06-20T06:05:50 | 2021-06-20T06:05:50 | 218,268,953 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 992 | cpp | remove-duplicates-from-sorted-list-ii.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head -> next == NULL) return head;
ListNode* pre = new ListNode(0); pre -> next = head;
ListNode *c0 = pre, *c1 = pre -> next, *c2 = pre -> next -> next;
while (c2 != NULL)
{
if (c1 -> val != c2 -> val) {fw(c0); fw(c1); fw(c2);}
else {
while (c2 -> next != NULL && c2 -> val == c2 -> next -> val) c2 = c2 -> next;
while (c1 -> next != c2) {ListNode* c3 = c1 -> next; c1 -> next = c3 -> next; delete c3;}
c0 -> next = c2 -> next; delete c1; delete c2;
c1 = c0 -> next; c2 = c1 ? c1 -> next : NULL;
}
}
return pre -> next;
}
private:
void fw(ListNode*& p) {p = p -> next;}
};
|
81d802d83893f7631ac6176d0bf0650b73c047e5 | ecf1bba56ac8e4cdf9fc64ae7ba2692e74a1a517 | /YOHAN/Player.cpp | 2e0f1f68b479bd754633edaaca05ec4ba2695217 | [] | no_license | fufux/YOHAN | c62dbdd45771c8cc84717c2291377541a980f476 | 6884aa527c5aacc3fbae6bfc9b301495c7ba2bbb | refs/heads/master | 2020-12-02T05:02:59.409360 | 2010-03-11T20:20:31 | 2010-03-11T20:20:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,928 | cpp | Player.cpp | #include "irrlicht/XEffects/Source/XEffects.h"
#include "Player.h"
#include "PlayerFrame.h"
#include "Editor.h"
extern IrrlichtDevice* device;
extern IVideoDriver* driver;
extern ISceneManager* smgr;
extern IGUIEnvironment* env;
extern EffectHandler* effect;
extern scene::ICameraSceneNode* camera[CAMERA_COUNT];
Player::Player(scene::ITerrainSceneNode* terrain, core::array<scene::ISceneNode*> skydomes)
{
this->debugData = scene::EDS_MESH_WIRE_OVERLAY;
this->er = new PlayerEventReceiver(this);
this->currFrame = NULL;
this->sceneFile = "";
this->is_playing = false;
this->currentFrame = -1;
this->is_running = false;
this->editor = NULL;
this->name = "untitled";
this->baseDir = device->getFileSystem()->getWorkingDirectory();
this->frames_size = 0;
this->improve_rendering = false;
this->defaultObjectTexture = driver->getTexture("irrlicht/media/wall.bmp");
this->noneObjectTexture = driver->getTexture("irrlicht/media/red.bmp");
this->terrain = terrain;
this->skydomes = skydomes;
}
Player::~Player(void)
{
}
void Player::start()
{
this->clear();
this->createGUI();
device->setEventReceiver(this->er);
this->is_running = true;
effect->setAmbientColor(SColor(255, 32, 32, 32));
}
void Player::stop()
{
this->is_running = false;
this->clear();
}
void Player::switchToEditor()
{
if (editor != NULL)
{
this->stop();
editor->start();
// reset the working directory
device->getFileSystem()->changeWorkingDirectoryTo( baseDir.c_str() );
editor->load("saved_scenes/tmp.xml");
}
}
bool Player::isRunning()
{
return is_running;
}
void Player::clear(bool clear_gui)
{
/*for (u32 i=0; i < frames_size; i++)
delete frames[i];
this->frames.clear();*/
improveRendering(false);
framesFileNames.clear();
if (currFrame) delete currFrame;
this->currFrame = NULL;
this->sceneFile = "";
this->currentFrame = -1;
this->is_playing = false;
this->playSpeed = 100;
this->accumulatedDeltaT = 0;
this->frames_size = 0;
this->improve_rendering = false;
// clear GUI
if (clear_gui)
{
device->clearSystemMessages();
device->setEventReceiver(NULL);
device->clearSystemMessages();
core::list<IGUIElement*> children = env->getRootGUIElement()->getChildren();
core::list<IGUIElement*>::Iterator it;
for (it = children.begin(); it != children.end(); ++it)
{
IGUIElement* e = (IGUIElement*)(*it);
if (e->getID() > GUI_ID_ref && e->getID() < GUI_ID_ref + 1000)
e->remove();
}
}
}
void Player::setEditor(Editor* editor)
{
this->editor = editor;
}
void Player::displayNextFrame()
{
this->is_playing = false;
s32 nextId = currentFrame+1;
if (nextId < 0)
nextId = (s32)framesFileNames.size() - 1;
if (nextId >= (s32)framesFileNames.size())
nextId = 0;
displayFrameById(nextId);
}
void Player::displayPreviousFrame()
{
this->is_playing = false;
s32 nextId = currentFrame-1;
if (nextId < 0)
nextId = (s32)framesFileNames.size() - 1;
if (nextId >= (s32)framesFileNames.size())
nextId = 0;
displayFrameById(nextId);
}
void Player::displayFrameById(s32 id, bool volumic)
{
if (framesFileNames.size() == 0 || id < 0 || id >= (s32)framesFileNames.size())
{
updateFrameNumber();
return;
}
if (currFrame && currFrame != NULL)
delete currFrame;
currFrame = new PlayerFrame(this, framesFileNames[id], volumic);
if (currFrame->getNodes().size() == 0)
{
delete currFrame;
currentFrame = -1;
currFrame = NULL;
return;
}
currentFrame = currFrame->getID();
if (volumic)
accumulatedDeltaT = currFrame->getTimestamp();
currFrame->display();
setDebugDataVisible( this->debugData, volumic );
updateFrameNumber();
}
void Player::playNextFrame(double deltaT)
{
if (deltaT == 0)// || frames_size == 0)
return;
// deltaT is in milliseconds
accumulatedDeltaT += deltaT / 1000.0;
s32 old_currentFrame = currentFrame;
double min = 100000000;
if (old_currentFrame >= 0 && old_currentFrame < (s32)frames_size)
{
for (u32 i=old_currentFrame; i < frames_size && i < (u32)old_currentFrame + 1000; i++)
{
if (abs(framesFileNames[i].timestamp - accumulatedDeltaT) < min)
{
min = abs(framesFileNames[i].timestamp - accumulatedDeltaT);
currentFrame = i;
}
}
for (u32 i=0; i < frames_size && i < 1000; i++)
{
if (abs(framesFileNames[i].timestamp - accumulatedDeltaT) < min)
{
min = abs(framesFileNames[i].timestamp - accumulatedDeltaT);
currentFrame = i;
}
}
}
else
{
currentFrame = 0;
}
// display the new frame
/*if (old_currentFrame >= 0 && old_currentFrame < (s32)frames_size)
frames[old_currentFrame]->hide();
if (currentFrame >= 0 && currentFrame < (s32)frames_size)
frames[currentFrame]->display();*/
displayFrameById(currentFrame, false);
// force looping
if (currentFrame == frames_size-1)
accumulatedDeltaT = 0;
setDebugDataVisible( this->debugData );
updateFrameNumber();
}
void Player::updateFrameNumber()
{
// update Frame number in the edit box
if (env->getRootGUIElement()->getElementFromId(GUI_ID_PLAYER_FRAME_NUMBER, true))
{
IGUIEditBox* box = (IGUIEditBox*)(env->getRootGUIElement()->getElementFromId(GUI_ID_PLAYER_FRAME_NUMBER, true));
box->setText( stringw(this->currentFrame).c_str() );
}
// update play/pause button
if (env->getRootGUIElement()->getElementFromId(GUI_ID_PLAYER_PLAY, true))
{
if (is_playing)
{
IGUIButton* b = (IGUIButton*)env->getRootGUIElement()->getElementFromId(GUI_ID_PLAYER_PLAY, true);
b->setImage(er->image_pause);
b->setToolTipText(L"Pause");
}
else
{
IGUIButton* b = (IGUIButton*)env->getRootGUIElement()->getElementFromId(GUI_ID_PLAYER_PLAY, true);
b->setImage(er->image_play);
b->setToolTipText(L"Play");
}
}
}
// load the video xml file and stor its info in framesFileNames
bool Player::load(irr::core::stringc filename)
{
// reset the working directory
device->getFileSystem()->changeWorkingDirectoryTo( baseDir.c_str() );
IReadFile* file = device->getFileSystem()->createAndOpenFile( filename );
if (!file)
{
device->getLogger()->log("Could not open the file.");
return false;
}
IXMLReader* xml = device->getFileSystem()->createXMLReader( file );
if (!xml)
return false;
// parse the file until end reached
/*
<video name="video01">
<frame nodefile="mesh.node" elefile="mesh.ele" id="3" />
</video>
*/
bool firstLoop = true;
bool is_valid_file = false;
stringc video_dir = device->getFileSystem()->getFileDir( filename );
video_dir += "/";
while(xml->read())
{
switch(xml->getNodeType())
{
case io::EXN_ELEMENT:
{
// the element should be "scene"
if (firstLoop)
{
firstLoop = false;
if (stringw("video") != xml->getNodeName())
{
env->addMessageBox(
CAPTION_ERROR, L"This is not a valid video file !");
return false;
}
else
{
is_valid_file = true;
// clean current scene
this->clear();
this->createGUI();
device->setEventReceiver(this->er);
// get number of frames and reallocate arrays
u32 nbf = xml->getAttributeValueAsInt(L"frames");
//frames.reallocate( nbf );
framesFileNames.reallocate( nbf );
}
}
if (stringw("frame") == xml->getNodeName())
{
FrameInfo fi;
fi.id = xml->getAttributeValueAsInt(L"id");
fi.timestamp = xml->getAttributeValueAsFloat(L"timestamp");
framesFileNames.push_back( fi );
}
else if (stringw("object") == xml->getNodeName())
{
framesFileNames.getLast().nodefiles.push_back( video_dir + xml->getAttributeValueSafe(L"nodefile") );
framesFileNames.getLast().facefiles.push_back( video_dir + xml->getAttributeValueSafe(L"facefile") );
framesFileNames.getLast().elefiles.push_back( video_dir + xml->getAttributeValueSafe(L"elefile") );
framesFileNames.getLast().bbfiles.push_back( video_dir + xml->getAttributeValueSafe(L"bbfile") );
}
}
default:
break;
}
}
xml->drop();
if (!is_valid_file)
{
env->addMessageBox(CAPTION_ERROR, L"This is not a valid video file !");
}
else
{
for (u32 i=0; i < framesFileNames.size(); i++)
{
if (framesFileNames[i].nodefiles.size() == 0 ||
framesFileNames[i].facefiles.size() == 0 ||
framesFileNames[i].elefiles.size() == 0)
{
framesFileNames.erase(i);
}
}
for (u32 i=0; i < framesFileNames.size()-1; i++)
{
framesFileNames[i].bbfiles = framesFileNames[i+1].bbfiles;
}
frames_size = framesFileNames.size();
}
return is_valid_file;
}
// this calls load and then pre-loads all frames, but only with surfacic meshes
/*bool Player::loadAll()
{
u16 size = framesFileNames.size();
for (u16 i=0; i < size; i++)
{
frames.push_back(new PlayerFrame(this, framesFileNames[i], false));
if (frames.getLast()->getNodes().size() == 0)
{
delete frames.getLast();
frames.erase(frames.size()-1);
}
}
frames_size = frames.size();
return true;
}*/
void Player::createGUI()
{
gui::IGUIElement* root = env->getRootGUIElement();
// create menu
gui::IGUIContextMenu* menu;
if (root->getElementFromId(GUI_ID_MENU, true))
((gui::IGUIContextMenu*)root->getElementFromId(GUI_ID_MENU, true))->remove();
//menu = (gui::IGUIContextMenu*)root->getElementFromId(GUI_ID_MENU, true);
menu = env->addMenu(0, GUI_ID_MENU);
menu->addItem(L"File", -1, true, true);
menu->addItem(L"View", -1, true, true);
menu->addItem(L"Camera", -1, true, true);
menu->addItem(L"Help", -1, true, true);
gui::IGUIContextMenu* submenu;
submenu = menu->getSubMenu(0);
submenu->addItem(L"Open animation...", GUI_ID_PLAYER_OPEN_VIDEO);
submenu->addSeparator();
submenu->addItem(L"Switch to editor", GUI_ID_SWITCH_TO_EDITOR);
submenu->addItem(L"Quit", GUI_ID_PLAYER_QUIT);
submenu = menu->getSubMenu(1);
submenu->addItem(L"Views", GUI_ID_PLAYER_TOGGLE_DEBUG_INFO, true, true);
submenu->addItem(L"Don't Improve Rendering", GUI_ID_PLAYER_IMPROVE_RENDERING_NONE);
submenu->addItem(L"Cloudy day", GUI_ID_PLAYER_IMPROVE_RENDERING_1);
submenu->addItem(L"Sunset", GUI_ID_PLAYER_IMPROVE_RENDERING_2);
submenu = submenu->getSubMenu(0);
submenu->addItem(L"Off", GUI_ID_PLAYER_DEBUG_OFF, true, false, (isDebugDataVisible() == scene::EDS_OFF));
submenu->addItem(L"Bounding Box", GUI_ID_PLAYER_DEBUG_BOUNDING_BOX, true, false, (isDebugDataVisible() == scene::EDS_BBOX));
submenu->addItem(L"Normals", GUI_ID_PLAYER_DEBUG_NORMALS, true, false, (isDebugDataVisible() == scene::EDS_NORMALS));
submenu->addItem(L"Wire overlay", GUI_ID_PLAYER_DEBUG_WIRE_OVERLAY, true, false, (isDebugDataVisible() == scene::EDS_MESH_WIRE_OVERLAY));
submenu->addItem(L"Half-Transparent", GUI_ID_PLAYER_DEBUG_HALF_TRANSPARENT, true, false, (isDebugDataVisible() == scene::EDS_HALF_TRANSPARENCY));
submenu->addItem(L"Buffers bounding boxes", GUI_ID_PLAYER_DEBUG_BUFFERS_BOUNDING_BOXES, true, false, (isDebugDataVisible() == scene::EDS_BBOX_BUFFERS));
submenu->addItem(L"All", GUI_ID_PLAYER_DEBUG_ALL, true, false, (isDebugDataVisible() == scene::EDS_FULL));
submenu = menu->getSubMenu(2);
submenu->addItem(L"Maya Style", GUI_ID_PLAYER_CAMERA_MAYA);
submenu->addItem(L"First Person", GUI_ID_PLAYER_CAMERA_FIRST_PERSON);
submenu = menu->getSubMenu(3);
submenu->addItem(L"About", GUI_ID_PLAYER_ABOUT);
/*
Below the menu we want a toolbar, onto which we can place colored
buttons and important looking stuff like a senseless combobox.
*/
// create toolbar
gui::IGUIToolBar* bar;
if (root->getElementFromId(GUI_ID_TOOLBAR, true))
((gui::IGUIToolBar*)root->getElementFromId(GUI_ID_TOOLBAR, true))->remove();
bar = env->addToolBar(0, GUI_ID_TOOLBAR);
video::ITexture* image = driver->getTexture("open.png");
bar->addButton(GUI_ID_PLAYER_OPEN_VIDEO_BUTTON, 0, L"Open animation", image, 0, false, true);
image = driver->getTexture("previous.png");
bar->addButton(GUI_ID_PLAYER_PREVIOUS_FRAME, 0, L"Previous Frame", image, 0, false, true);
image = driver->getTexture("next.png");
bar->addButton(GUI_ID_PLAYER_NEXT_FRAME, 0, L"Next Frame", image, 0, false, true);
image = er->image_play;
bar->addButton(GUI_ID_PLAYER_PLAY, 0, L"Play", image, 0, false, true);
image = driver->getTexture("help.png");
bar->addButton(GUI_ID_PLAYER_HELP_BUTTON, 0, L"Open Help", image, 0, false, true);
env->addEditBox(stringw( -1 ).c_str(), core::rect<s32>(200,4,300,24), true, bar, GUI_ID_PLAYER_FRAME_NUMBER);
image = driver->getTexture("goto.png");
IGUIButton* b = bar->addButton(GUI_ID_PLAYER_FRAME_NUMBER_BUTTON, 0, L"Go to this frame", image, 0, false, true);
b->setRelativePosition( core::rect<s32>(304,4,324,24) );
// add speed control %
env->addStaticText(L"Speed Control (100%):",
core::rect<s32>(350,8,440,24), false, false, bar, GUI_ID_PLAYER_SPEED_TEXT);
IGUIScrollBar* scrollbar = env->addScrollBar(true,
core::rect<s32>(445,6,775,22), bar, GUI_ID_PLAYER_SPEED_SCROLLBAR);
scrollbar->setMax(200);
scrollbar->setPos(100);
scrollbar->setLargeStep(5);
scrollbar->setSmallStep(1);
}
void Player::setDebugDataVisible(scene::E_DEBUG_SCENE_TYPE state, bool f)
{
/*if (currentFrame >= 0 && currentFrame < (s32)frames_size)
{
for (u16 j=0; j < frames[currentFrame]->getNodes().size(); j++)
frames[currentFrame]->getNodes()[j]->setDebugDataVisible(state);
}*/
if (currFrame && (!improve_rendering || f))
{
for (u16 j=0; j < currFrame->getNodes().size(); j++)
currFrame->getNodes()[j]->setDebugDataVisible(state);
this->debugData = state;
}
else if (currFrame)
{
for (u16 j=0; j < currFrame->getNodes().size(); j++)
currFrame->getNodes()[j]->setDebugDataVisible(scene::EDS_OFF);
}
}
s32 Player::isDebugDataVisible()
{
return debugData;
}
void Player::improveRendering(bool enable, s32 type)
{
if (enable)
{
effect->removeShadowFromNode(terrain);
effect->addShadowToNode(terrain, EFT_8PCF, ESM_RECEIVE);
if (type == 0)
{
skydomes[0]->setVisible(true);
skydomes[1]->setVisible(false);
effect->getShadowLight(0).setPosition(vector3df(0, 600.0f, -50.0f));
effect->setAmbientColor(SColor(255, 132, 132, 132));
}
else if (type == 1)
{
skydomes[0]->setVisible(false);
skydomes[1]->setVisible(true);
effect->getShadowLight(0).setPosition(vector3df(0, 320.0f, -800.0f));
effect->setAmbientColor(SColor(255, 32, 32, 32));
}
}
else
{
if (currFrame)
{
for (u32 i=0; i < currFrame->getNodes().size(); i++)
effect->removeShadowFromNode(currFrame->getNodes()[i]);
}
effect->removeShadowFromNode(terrain);
setDebugDataVisible(this->debugData);
for (u32 i=0; i < skydomes.size(); i++)
skydomes[i]->setVisible(false);
}
this->improve_rendering = enable;
terrain->setMaterialFlag(video::EMF_WIREFRAME, !enable);
}
bool Player::isImproveRendering()
{
return improve_rendering;
}
video::ITexture* Player::getDefaultObjectTexture()
{
return defaultObjectTexture;
}
video::ITexture* Player::getNoneObjectTexture()
{
return noneObjectTexture;
}
void Player::play()
{
if (framesFileNames.size() == 0)
return;
if (currFrame && currFrame != NULL)
{
delete currFrame;
currFrame = NULL;
}
/*if (frames_size == 0)
loadAll();*/
is_playing = true;
lastTime = device->getTimer()->getTime();
}
void Player::pause()
{
is_playing = false;
}
void Player::run()
{
if (!this->is_running)
return;
if (framesFileNames.size() == 0)
return;
if (is_playing)
{
// we always display 30 images per second. The speed will interact with the frames timestamp
double fps = 1000.0/30;
if (device->getTimer()->getTime() - lastTime > fps)
{
lastTime = device->getTimer()->getTime();
this->playNextFrame(fps * ((double)this->playSpeed) / 100);
if (currFrame && currFrame->getNodes().size() > 0 &&
currFrame->getNodes()[0]->getMesh()->getMeshBufferCount() > 0 &&
currFrame->getNodes()[0]->getMesh()->getMeshBuffer(0)->getVertexCount() > 0)
{
S3DVertex *v = (S3DVertex*)currFrame->getNodes()[0]->getMesh()->getMeshBuffer(0)->getVertices();
effect->getShadowLight(0).setTarget(v[0].Pos);
}
}
}
}
|
617cd72141254bc83df325814a83050e1a22e69c | d85870d79a3cf3378e3a3fa045b48715eb93bb54 | /STL/S-04/4.7/4.7a/main.cpp | c49973b51c9291bd89dc456922c4525e382dfbe0 | [] | no_license | simorgh10/CPlusPlus | 706414e4c5b81cf9c88c25141a99c6722355f0d5 | 9dec56c5744ea7c0ed69e68663e801371788f999 | refs/heads/master | 2022-08-18T19:14:04.942363 | 2020-05-20T17:21:40 | 2020-05-20T17:21:40 | 265,637,253 | 1 | 0 | null | 2020-05-20T17:22:34 | 2020-05-20T17:22:33 | null | UTF-8 | C++ | false | false | 1,166 | cpp | main.cpp | #include <iostream>
#include <vector>
using namespace std;
/**
* Random Access Iterators allow the operations of pointer arithmetic:
* addition of arbitrary offsets, subscripting, and subtraction of one
* iterator from another to find a distance. These are the most
* powerful iterators and are like regular pointers but they are also
* smart, e.g., they can hold state.
*
* In addition doing all that bidirectional iterators do, random
* access iterators can do the following as well:
* . operator+ (int)
* . operator+= (int)
* . operator- (int)
* . operator-= (int)
* . operator- (random access iterator)
* . operator[] (int)
* . operator < (random access iterator)
* . operator > (random access iterator)
* . operator >= (random access iterator)
* . operator <= (random access iterator)
*
* The vector class provides a random access iterator that can be used
* as follows:
*/
int main() {
vector<int> v({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
int total_even = 0;
for (auto iter = v.begin();
iter != v.end();
iter += 2)
total_even += *iter;
cout << "Total even = " << total_even << endl;
return 0;
}
|
1ee4b8d5bb4dbb2b560bec24f8d7a5d8dbae1963 | 8ea46b28b74145e5651ef21721ed4286b3d25c90 | /tests/test-threads.cpp | 5e301de9a960321268b64149fdee0e4a7927685f | [
"BSD-2-Clause"
] | permissive | SundyHuJian/umundo | 56a73d5888788a2b1b61856ceb7f51ee88ec6b9a | 31da28e24c6c935370099745311dd78c80763bd8 | refs/heads/master | 2022-03-23T05:35:48.437492 | 2017-01-06T13:17:58 | 2017-01-06T13:17:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,332 | cpp | test-threads.cpp | #include "umundo.h"
#include <iostream>
using namespace umundo;
bool testRMutex() {
RMutex mutex;
UMUNDO_LOCK(mutex);
if(!mutex.try_lock()) {
UM_LOG_ERR("tryLock should be possible from within the same thread");
assert(false);
}
UMUNDO_LOCK(mutex);
// can we unlock it as well?
UMUNDO_UNLOCK(mutex);
UMUNDO_UNLOCK(mutex);
return true;
}
static RMutex testMutex;
bool testThreads() {
class Thread1 : public Thread {
void run() {
if(testMutex.try_lock()) {
UM_LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // blocks
Thread::sleepMs(50);
UMUNDO_UNLOCK(testMutex);
Thread::sleepMs(100);
}
};
/**
* tl=tryLock, l=lock, u=unlock b=block, sN=sleep(N)
* thread1: start tl l l s50 u
* main: start l s50 u s20 tl l join
* t-> 0 50 70 100
*/
UMUNDO_LOCK(testMutex);
Thread1 thread1;
thread1.start();
Thread::sleepMs(50); // thread1 will trylock and block on lock
UMUNDO_UNLOCK(testMutex); // unlock
Thread::sleepMs(20); // yield cpu and sleep
// thread1 sleeps with lock on mutex
if(testMutex.try_lock()) {
UM_LOG_ERR("tryLock should return false with a mutex locked in another thread");
assert(false);
}
UMUNDO_LOCK(testMutex); // thread1 will unlock and sleep
thread1.join(); // join with thread1
if(thread1.isStarted()) {
UM_LOG_ERR("thread still running after join");
assert(false);
}
return true;
}
static Monitor testMonitor;
static int passedMonitor = 0;
bool testMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
RScopeLock lock(testMutex);
testMonitor.wait(testMutex);
Thread::sleepMs(10); // avoid clash with other threads
passedMonitor++;
}
};
TestThread thread1(0);
TestThread thread2(5);
TestThread thread3(10);
RMutex testMutex;
for (int i = 0; i < 10; i++) {
passedMonitor = 0;
// all will block on monitor
thread1.start();
thread2.start();
thread3.start();
Thread::sleepMs(5); // give threads a chance to run into wait
if(passedMonitor != 0) {
UM_LOG_ERR("%d threads already passed the monitor", passedMonitor);
assert(false);
}
{
UMUNDO_SIGNAL(testMonitor); // signal a single thread
Thread::sleepMs(40); // thread will increase passedMonitor
if(passedMonitor != 1) {
UM_LOG_ERR("Expected 1 threads to pass the monitor, but %d did", passedMonitor);
assert(false);
}
}
UMUNDO_BROADCAST(testMonitor); // signal all other threads
Thread::sleepMs(40);
if (thread1.isStarted() || thread2.isStarted() || thread3.isStarted()) {
UM_LOG_ERR("Threads ran to completion but still insist on being started");
assert(false);
}
}
return true;
}
static RMutex testTimedMutex;
static Monitor testTimedMonitor;
static int passedTimedMonitor = 0;
bool testTimedMonitors() {
struct TestThread : public Thread {
int _ms;
TestThread(int ms) : _ms(ms) {}
void run() {
RScopeLock lock(testTimedMutex);
testTimedMonitor.wait(testTimedMutex, _ms);
passedTimedMonitor++;
}
};
TestThread thread1(1000);
TestThread thread2(0); // waits forever
TestThread thread3(0); // waits forever
TestThread thread4(0); // waits forever
TestThread thread5(0); // waits forever
RMutex testTimedMutex;
for (int i = 0; i < 2; i++) {
// test waiting for a given time
passedTimedMonitor = 0;
thread1.start(); // wait for 100ms at mutex before resuming
Thread::sleepMs(100);
assert(passedTimedMonitor == 0); // thread1 should not have passed
Thread::sleepMs(1500);
assert(passedTimedMonitor == 1); // thread1 should have passed
assert(!thread1.isStarted());
// test signalling a set of threads
passedTimedMonitor = 0;
thread2.start();
thread3.start();
thread4.start();
thread5.start();
Thread::sleepMs(50);
testTimedMonitor.signal(2); // signal 2 threads
Thread::sleepMs(50);
assert(passedTimedMonitor == 2);
testTimedMonitor.signal(1); // signal another thread
Thread::sleepMs(50);
assert(passedTimedMonitor == 3);
testTimedMonitor.broadcast(); // signal last thread
Thread::sleepMs(50);
assert(passedTimedMonitor == 4);
assert(!thread2.isStarted() && !thread3.isStarted() && !thread4.isStarted() && !thread5.isStarted());
// test timed and unlimited waiting
passedTimedMonitor = 0;
thread1.start();
thread2.start(); // with another thread
thread3.start(); // with another thread
Thread::sleepMs(10);
testTimedMonitor.signal(); // explicit signal
Thread::sleepMs(50);
assert(passedTimedMonitor == 1);
// wo do not know which thread passed
assert(!thread1.isStarted() || !thread2.isStarted() || !thread3.isStarted());
if (thread1.isStarted()) {
// thread1 is still running, just wait
Thread::sleepMs(1000);
assert(passedTimedMonitor == 2);
}
testTimedMonitor.broadcast(); // explicit signal
Thread::sleepMs(100);
assert(passedTimedMonitor == 3);
assert(!thread1.isStarted() && !thread2.isStarted() && !thread3.isStarted());
}
return true;
}
int main(int argc, char** argv) {
if(!testRMutex())
return EXIT_FAILURE;
if(!testThreads())
return EXIT_FAILURE;
if(!testMonitors())
return EXIT_FAILURE;
if(!testTimedMonitors())
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
|
659fcee62e21733d9f27cef013dae7c8dc057282 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /mojo/core/entrypoints.h | 8e2cb418d4af1ab1027b308c1e4fdf72c4b16fd9 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 823 | h | entrypoints.h | // Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MOJO_CORE_ENTRYPOINTS_H_
#define MOJO_CORE_ENTRYPOINTS_H_
#include "mojo/core/system_impl_export.h"
#include "mojo/public/c/system/thunks.h"
namespace mojo {
namespace core {
// Initializes the global Core object.
MOJO_SYSTEM_IMPL_EXPORT void InitializeCore();
// Destroys the global Core object.
MOJO_SYSTEM_IMPL_EXPORT void ShutDownCore();
// Returns a MojoSystemThunks2 struct populated with the EDK's implementation
// of each function. This may be used by embedders to populate thunks for
// application loading.
MOJO_SYSTEM_IMPL_EXPORT const MojoSystemThunks2& GetSystemThunks();
} // namespace core
} // namespace mojo
#endif // MOJO_CORE_ENTRYPOINTS_H_
|
29ffb3baf6757f39cf6640db009e2b229bb64e3b | b389f1f3075092f7cb25f45ee9bf910c55250735 | /WorkInProgress/UVa Online Judge/10369 - Arctic Network/sol.cpp | f0070325c094ea88f555b019c462d749c5a426dd | [] | no_license | leostd/Competitive-Programming | 7b3c4c671e799216c79aeefd2ca7d68c5d463fa6 | 4db01b81314f82c4ebb750310e5afb4894b582bd | refs/heads/master | 2023-05-13T07:04:40.512100 | 2023-05-06T10:58:28 | 2023-05-06T10:58:28 | 87,685,033 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,240 | cpp | sol.cpp | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <random>
#include <chrono>
#include <complex>
#include <algorithm>
#include <utility>
#include <functional>
#include <cmath>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
#define mp make_pair
#define pb push_back
#define forn(i, n) for(int i = 0; i < (int)(n); ++i)
#define for1(i, n) for(int i = 1; i < (int)(n); ++i)
#define nfor(i, n) for(int i = int(n) - 1; i >= 0; --i)
#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)
#define correct(x, y, n, m) (0 <= x && x < n && 0 <= y && y < m)
#define all(x) (x).begin(), (x).end()
#define fst first
#define snd second
#define endl "\n"
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef tuple<int,int,int> iii;
template<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); }
template<typename T> inline T sqr(T a){ return a * a; }
template<class T> T gcd(T a, T b) { return a ? gcd (b % a, a) : b; }
template<class T> T lcm(T a, T b) { return a / gcd (a, b) * b; }
template<class T> T sign(T a) { return a > 0 ? 1 : (a < 0 ? -1 : 0); }
string to_string(string s) {
return '"' + s + '"';
}
string to_string(const char* s) {
return to_string((string) s);
}
string to_string(bool b) {
return (b ? "true" : "false");
}
template <typename A, typename B>
string to_string(pair<A, B> p) {
return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template <typename A>
string to_string(A v) {
bool first = true;
string res = "{";
for (const auto &x : v) {
if (!first) {
res += ", ";
}
first = false;
res += to_string(x);
}
res += "}";
return res;
}
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << to_string(H);
debug_out(T...);
}
void fastIO() {
cin.sync_with_stdio(false);
cin.tie(0);
}
template<typename T>
vector<T> make_unique(vector<T> v) {
sort(all(v));
return v.resize(unique(all(v)) - v.begin());
}
int nxt() {
int x;
cin >> x;
return x;
}
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
const int dxKn[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int dyKn[8] = { 1, 2, 2, 1, -1, -2, -2, -1};
const int dxK[8] = {0, 0, 1, -1, 1, 1, -1, -1};
const int dyK[8] = {1, -1, 0, 0, 1, -1, 1, -1};
const int MOD = int(1e9) + 7;
const int INF = int(1e9) + 100;
const ll INF64 = 2e18;
const ld PI = ld(3.1415926535897932384626433832795);
const ld e = ld(2.7182818284590452353602874713527);
const ld EPS = 1e-9;
//#############################
const int MAXN = 1000005;
int parent[1000];
vector<tuple<double, int,int>> edg;
int uf_find(int x){
edg.clear();
if (x == parent[x])
return x;
return parent[x] = uf_find(parent[x]);
}
void uf_union(int x, int y){
int rootx = uf_find(x);
int rooty = uf_find(y);
if (rootx != rooty){
parent[rooty] = rootx;
}
}
void init() {
forn(i, 1000)
parent[i] = i;
}
double dist(int x, int y, int x1, int y1) {
return sqrt(sqr(x-x1) + sqr(y-y1));
}
int main() {
fastIO();
int t = nxt();
while(t--) {
int s = nxt(), p = nxt();
vector<pii> points(p, mp(0,0));
forn(i,p)
cin >> points[i].fst >> points[i].snd;
forn(i, p){
fore(j, i+1, p){
edg.push_back(make_tuple(dist(points[i].fst, points[i].snd, points[j].fst, points[j].snd), i, j));
}
}
// debug_out(points);
sort(all(edg));
forn(j, edg.size()){
double x;
int y, z;
tie(x,y,z) = edg[j];
// debug_out(x, y, z);
}
vector<tuple<double, int, int>> mst;
// Picture it. If we have s satellites we will have a connected component, connected by radio
// and a connected component connected by satellite. It will be enough only one edge from component
// to another to comply with the problem statement.
// By definition, given a graph with N nodes, an MST will have N-1 edges. In this case, we will have N - (S-1)
// There will be N - S cities connected by radio. MST for that component will have N - S - 1 edges. Given that we need to
// connect both components, we need another edge, so we end up with N-S edges.
int cur = 0;
double ans = 0;
init();
while(mst.size() < p - s){
int x, y, z;
// debug_out(mst.size(), p-s, cur);
tuple<double, int, int> aux = edg[cur++];
tie(x, y, z) = aux;
// debug_out(x, y, z);
if (uf_find(get<1>(aux)) != uf_find(get<2>(aux))){
uf_union(get<1>(aux), get<2>(aux));
ans = get<0>(aux);
mst.push_back(aux);
}
}
cout << setprecision(2) << fixed;
cout << ans << endl;
}
return 0;
} |
9bedc405cfc32e5ad003234c7981598b3ffa3b41 | 71c390fcd23a512375b98e9560eeb530f3346be4 | /HttpServer.h | 1b0684279ab352a59080a20814e1964fd4084e24 | [] | no_license | destiny9797/BlogPoster | 55aabf405f34514b3cb1f8781f447aca64cb5501 | d4e682c6bbd9988bfac4346c420a5dce352cfc0d | refs/heads/master | 2023-06-18T07:10:41.576983 | 2021-07-19T02:48:43 | 2021-07-19T02:48:43 | 381,579,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | HttpServer.h | //
// Created by zhujiaying on 2021/6/19.
//
#ifndef MYWEBSERVER_HTTPSERVER_H
#define MYWEBSERVER_HTTPSERVER_H
#include "ThreadPool.h"
//#include "HttpParser.h"
#include <string>
#include <memory>
#include <vector>
class TcpServer;
class TaskPool;
class HttpServer{
public:
typedef std::shared_ptr<TcpServer> spTcpServer;
typedef std::shared_ptr<TaskPool> spTaskPool;
static HttpServer& getInstance();
static std::string getPath();
static std::string getHomepage();
void Init(int port, const std::string& homepage);
void Start();
void Quit();
private:
HttpServer();
~HttpServer();
spTaskPool _taskpool;
spTcpServer _tcpserver;
static std::string _homepage;
bool _inited;
};
#endif //MYWEBSERVER_HTTPSERVER_H
|
1563186a4b581f067f2f79968612f345a8cd6f88 | dcf214a6dcb004cedda28f461ae2f0a1e9b21768 | /HVVPlatform/console_test/console_test.cpp | 9dc0c97b25451e84001d57b1a6e599ac93ee438e | [] | no_license | tars-c/HVVPlatform | c96fe70b502d7d07f5069cf1402f059a1c1d0367 | d9bdd3863f3b19cdb69143a05f921b8ed12ce9b6 | refs/heads/main | 2023-03-03T01:11:55.718250 | 2021-02-14T06:33:21 | 2021-02-14T06:33:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,409 | cpp | console_test.cpp | // console_test.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
//
#include <Windows.h>
#include <iostream>
#include <filesystem>
#include <chrono>
#include <execution>
#include <memory>
#include <array>
#include <any>
#include <interpreter.h>
#include <exception.h>
#include <primitive_object.h>
#include <image.h>
std::string current_directory()
{
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
return std::string(buffer).substr(0, pos);
}
int main()
{
auto current_path = current_directory();
hv::v1::interpreter::init_v8_startup_data(current_path + "\\");
hv::v1::interpreter::init_v8_platform();
hv::v1::interpreter::init_v8_engine();
hv::v1::interpreter::set_v8_flag("--use_strict");
hv::v1::interpreter::set_v8_flag("--max_old_space_size=8192");
hv::v1::interpreter::set_v8_flag("--expose_gc");
hv::v1::interpreter interpreter1;
//hv::v1::interpreter interpreter2;
interpreter1.set_module_path(current_path);
while (true) {
try {
interpreter1.run_file("C:\\Github\\HVVPlatform\\test_script\\opencv.js");
}
catch (hv::v1::script_error e) {
std::cout << e.what() << std::endl;
}
}
}
|
fabe7ef44cfdfac64165c56b3baf32a0517b54df | 92a9f837503a591161330d39d061ce290c996f0e | /SiNDY-e/AttributeDlg/AttrHeightNode/AttrHeightNode.h | eea5b9f64b1b365f6c8dc88facf2272ab4c28449 | [] | no_license | AntLJ/TestUploadFolder | 53a7dae537071d2b1e3bab55e925c8782f3daa0f | 31f9837abbd6968fc3a0be7610560370c4431217 | refs/heads/master | 2020-12-15T21:56:47.756829 | 2020-01-23T07:33:23 | 2020-01-23T07:33:23 | 235,260,509 | 1 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 9,173 | h | AttrHeightNode.h | /*
* Copyright (C) INCREMENT P CORP. All Rights Reserved.
*
* THIS SOFTWARE IS PROVIDED BY INCREMENT P CORP., 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 HOLDER BE LIABLE FOR ANY
* CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
#pragma once
#include "RelativeLinks.h"
typedef CAttrBaseDlg ATTR_BASE_CLASS;
const unsigned int WM_REFRESHFEATURE = RegisterWindowMessage(_T("WM_REFRESHFEATURE")); //!< 再描画命令を受けるためのメッセージ
/////////////////////////////////////////////////////////////////////////////
// CAttrHeightNode
class CAttrHeightNode :
public ATTR_BASE_CLASS,
public CExportDlg
{
public:
/////////////////////////////////////////////////////////////////////////////
//
// CAttrHeightNode メッセージマップ
//
/////////////////////////////////////////////////////////////////////////////
BEGIN_MSG_MAP(CAttrHeightNode)
MESSAGE_HANDLER(WM_WINMGR, OnWinMgr)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
MESSAGE_HANDLER(WM_GETMINMAXINFO, OnGetMinMaxInfo)
MESSAGE_HANDLER(WM_CTLCOLOREDIT, OnCtlColorEdit)
MESSAGE_HANDLER(WM_CTLCOLORBTN, OnCtlColorEdit)
MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnCtlColorEdit)
COMMAND_HANDLER( IDC_COMBO_HEIGHT1, CBN_SELCHANGE, OnHeightChange )
COMMAND_HANDLER( IDC_COMBO_HEIGHT2, CBN_SELCHANGE, OnHeightChange )
COMMAND_HANDLER( IDC_COMBO_HEIGHT1, CBN_SETFOCUS, OnHeightFocus )
COMMAND_HANDLER( IDC_COMBO_HEIGHT2, CBN_SETFOCUS, OnHeightFocus )
COMMAND_HANDLER( IDC_COMBO_HEIGHT1, CBN_KILLFOCUS, OnHeightKillFocus )
COMMAND_HANDLER( IDC_COMBO_HEIGHT2, CBN_KILLFOCUS, OnHeightKillFocus )
MESSAGE_HANDLER(WM_COMMAND, OnCommand)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_REFRESHFEATURE, OnRefresh)
ALT_MSG_MAP(IDC_EDIT_SOURCE)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
ALT_MSG_MAP(IDC_COMBO_HEIGHT1)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
ALT_MSG_MAP(IDC_COMBO_HEIGHT2)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
// 以下のコントロールのサブクラス化がないとなぜか落ちるようになったので追加
ALT_MSG_MAP(IDC_COMBO_LAYER1)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
ALT_MSG_MAP(IDC_COMBO_LAYER2)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
ALT_MSG_MAP(IDC_EDIT_ID1)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
ALT_MSG_MAP(IDC_EDIT_ID2)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
END_MSG_MAP()
/////////////////////////////////////////////////////////////////////////////
//
// CAttrHeightNode メッセージハンドラ
//
/////////////////////////////////////////////////////////////////////////////
/**
* ダイアログ作成する際に一番最初に呼ばれます。ここでダイアログの初期化をしてください
*/
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
// コントロール
CreateControlRelation();
// サブクラス化
for( auto& it : m_mapSubClass)
{
it.second.SubclassWindow( GetDlgItem( it.first ) );
}
return ATTR_BASE_CLASS::OnInitDialog( uMsg, wParam, lParam, bHandled );
}
/**
* WM_COMMAND 用イベントハンドラ
*
* 各コモンコントロールで変更があった場合、ここで処理します
* 現在はエディットボックス、チェックボックス、コンボボックスの処理が行われます
*/
LRESULT OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
// SetCurrentFeatureDefIndex() の最中はキャンセル(タイミングによってはおかしくなるため)
if( !m_bFinishInit ) return 0;
INT msg = HIWORD(wParam); // 操作メッセージ
INT nTargetControl = (INT)LOWORD(wParam); // 操作対象コントロール
// エディットボックスの時に全選択にする
if( msg == EN_SETFOCUS )
SelectDlgItem( nTargetControl );
// コンボボックスのリストボックスの長さを調節
if( msg == CBN_DROPDOWN )
SetComboboxList( nTargetControl );
// コンボボックス、エディットボックス、チェックボックスのメッセージ処理
if( ( msg == CBN_SELCHANGE ) || ( msg == BN_CLICKED ) || ( msg == EN_UPDATE ) ) {
// 変更されたかどうかチェックし、変更されていたら他のコントロールにも反映させる
m_cControlRel.ControlChanged( (INT)LOWORD(wParam) );
// ダイアログを更新領域に追加します
InvalidateRect( NULL, FALSE );
// 変更された場合はボタンを Enable に
SetButton( Changed() );
}
return 0;
}
private:
/**
* @brief 再描画命令を受け取ったときの処理
*/
LRESULT OnRefresh( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled );
/**
* @brief 高さが変更されたときの処理
*/
LRESULT OnHeightChange(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
/**
* @brief フォーカスを取得したときの処理
*/
LRESULT OnHeightFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
/**
* @brief フォーカスが外れたときの処理
*/
LRESULT OnHeightKillFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
/**
* @brief コントロール背景色変更
* @note 本来の役割ではないが、論理チェックエラーがある際に「OK」を潰すのに使用する。
*/
LRESULT OnCtlColorEdit(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
/////////////////////////////////////////////////////////////////////////////
//
// CAttrHeightNode メンバ関数定義
//
/////////////////////////////////////////////////////////////////////////////
public:
virtual HWND Create(HWND hWndParent, LPARAM dwInitParam = NULL);
virtual void Delete();
virtual void SetArcHelper( IApplication* ipApp ){ ATTR_BASE_CLASS::SetArcHelper( ipApp ); };
virtual void SetAliasOrField( BOOL bAliasOrField ){ ATTR_BASE_CLASS::m_cControlRel.SetAliasOrField( bAliasOrField ); };
virtual void SetFeatureDefList( std::list<CLQRowDef>* pFeatureDefList ){};
virtual void SetFeatureDefList( std::list<CFeatureDef>* pFeatureDefList ){ ATTR_BASE_CLASS::SetFeatureDefList( pFeatureDefList ); };
virtual void ClearFeatureDefs(){ ATTR_BASE_CLASS::ClearFeatureDefs(); };
virtual HWND GetDlg(){ return m_hWnd; };
virtual LRESULT SendMessage( UINT message, WPARAM wParam, LPARAM lParam ){ return ::SendMessage( m_hWnd, message, wParam, lParam ); };
virtual BOOL ErrorCheck(){ return TRUE; };
virtual LONG GetTabNum(){ return -1; };
virtual void SetTabNum(LONG lTabNum){};
virtual void SetFeatureClassName(LPCTSTR lpcszFeatureClassName){};
CAttrHeightNode();
BOOL SetCurrentFeatureDefIndex( LONG lFeatureIndex, LONG lTableIndex, LONG lRowIndex, BOOL bForce, BOOL bEditable );
BOOL CheckReturnKeyItem(INT nClassID){ return TRUE; }
BOOL CheckEscKeyItem(INT nClassID){ return TRUE; }
private:
void CreateControlRelation();
/**
* @brief 歩行者種別をエディットボックスに反映する
* @note 歩行者種別は自前で管理する必要がある。
*/
void SetWalkclassToCtrl();
/**
* @brief m_relativeLinksで管理する値を書くコントロールに反映する
* @note 新規の場合は作り直す必要があるので結局必要。。
*/
void ApplyToCtrl();
/**
* @brief 高さのコンボボックスを作る
* @note リストはベタ書き
* @param id [in] コントロールID
* @return height [in] 作成と同時に選択しておく高さ(-2 〜 2)
*/
void CreateHeightCombo( UINT id, long height );
/**
* @brief コントロールの有効・無効
* @note 高さ以外はeditingによらず常に編集不可にする
* @param editing [in] 編集開始しているか
*/
void EnableControls( bool editing );
/**
* @brief 「OK」ボタンの有効・無効
* @param changed [in] 有効にするならTRUE
*/
void SetButton( BOOL changed );
/////////////////////////////////////////////////////////////////////////////
//
// CAttrHeightNode メンバ変数定義
//
/////////////////////////////////////////////////////////////////////////////
private:
std::map<int, CContainedWindow> m_mapSubClass; //!< 各コントロールウィンドウ
CRelativeLinks m_relativeLinks; //<! 交差する2リンクを管理する
linkNo::eCode m_focusedHeight; //<! フォーカスされているリンク(ID1 or ID2 の記憶用)
bool m_forceCancel; //<! 不正な場所に作成された場合に保存させない用
};
|
0677d175f77adc75846119d433651fb66bb28aec | cb444ecbcf02c08d7a24f79c5a229b0f143cca73 | /3.面试笔试算法/1.上/1.编程能力提升-Euler/euler25.cpp | 4968c103ba73d911318431ba661fc7c227433edb | [] | no_license | liangzai951/hzcla | 809b5f3a2baab8aa060ee16201787c6289ad2ec4 | 0c97ba5666e9f497891e0e996ab958460998b238 | refs/heads/main | 2023-07-29T04:11:52.075724 | 2021-09-07T16:01:32 | 2021-09-07T16:01:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | cpp | euler25.cpp | /*************************************************************************
> File Name: euler25.cpp
> Author: Double
> Mail: doubleliu3@gmail.com
> Created Time: Fri 30 Oct 2020 06:12:06 PM CST
************************************************************************/
#include <iostream>
using namespace std;
// 大整数加法,大的数n1加到小的数n2里
int func(int *n1, int *n2) {
n2[0] = n1[0]; // 被加数的位数调整为长的那一个n1,保证n1是大的
for (int i = 1; i <= n2[0]; i++) {
n2[i] += n1[i];
// 如果有进位,↓
if (n2[i] > 9) {
n2[i + 1] += n2[i] / 10;
n2[i] %= 10;
if (i == n2[0]) {
n2[0]++;
}
}
}
return n2[0] == 1000; // >=也可以,可能更安全
}
int main() {
int num[2][1100] = {{1, 1}, {1, 1}}; // 前两个数初始为1、1,其它位初始为0
int a = 0, b = 1; // 用来指代num[0]、num[1],只针对索引交换,nice!
// 两个变量循环加、存储
for (int i = 3; 1; i++) {
// 判断位数是否达到1000位
if (func(num[a], num[b]) == 1) {
cout << i << endl;
break;
}
swap(a, b); // 每次大的数的索引对应a
}
return 0;
}
|
ce8620a13e380812aef25d7cd8c2a97ca604803b | f275719aead1a8d5e0898ed9ff3b88d96b03d5ce | /hella.cpp | f680f2605d72a3cbb38a906d13fdf23c58b32119 | [] | no_license | sushmanthreddy/A20J-LADDERS-1300 | bbcc0d792d366f486ee0452943462796599548d5 | 37989428befcd2e1fddc69001a2979a9dad2aab0 | refs/heads/main | 2023-08-25T18:42:44.544198 | 2021-10-07T09:17:50 | 2021-10-07T09:17:50 | 363,836,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | cpp | hella.cpp | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
typedef long long int ll;
typedef unsigned long long ull;
typedef long double lld;
ll gcd(ll a, ll b) {
return b ? gcd(b, a % b) : a;
}
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
typedef struct array {
int first, second;
} point;
ll min(ll a, ll b) {
return a < b ? a : b;
}
ll max(ll a, ll b) {
return a > b ? a : b;
}
int cmpfunc (const void * a, const void * b) {
return ( * (int*)a - * (int*)b );
}
int cmc(const void *a, const void *b) {
return *(char *)b - *(char *)a;
}
int comp(const void* a, const void* b) {
long long i = (long long)a;
long long j = (long long)b;
return (int)((i > j) - (i < j));
}
#define pr printf
#define sc scanf
#define re(i,a,b) for(int i=a;i<b;i++)
#define I 1e18
#define in32(x) scanf("%d", &x)
#define out32(x) printf("%d\n", x)
//qsort(a, n, sizeof(int), cmpfunc);
void test();
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
scanf("%d", &t);
while (t--)
{
test();
}
}
void test()
{
int n, i, j, k, l = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
l = 0; k = 2 * n - (i - 1) * 2;
for (j = 1; j <= 2 * n; j++)
{
if (i == 1)
{
if (j <= n)
{
pr("(");
}
else
{
pr(")");
}
}
else
{
if (j <= (i - 1) * 2)
{
if (j & 1)
{
pr("(");
}
else
{
pr(")");
}
}
else
{
l++;
if (l <= k / 2 )
{
pr("(");
}
else
{
pr(")");
}
}
}
}
pr("\n");
}
} |
7c7cf8740620fc1a3ead20f8ef2f0bb36da3edd6 | ad5c44ba4927bc4fe863910fcf3f78b757aad93c | /src/MesaDLL/os2mesa.cpp | c86443f05de5e5436c9598f59a574614c0bd43d5 | [
"MIT"
] | permissive | OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library | cf495403bd10ed60b27c40379a9e136feee5ce56 | c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3 | refs/heads/master | 2020-05-18T01:20:21.489699 | 2019-04-29T14:53:25 | 2019-04-29T14:53:25 | 184,088,102 | 0 | 0 | null | null | null | null | IBM866 | C++ | false | false | 58,526 | cpp | os2mesa.cpp | /* os2mesa.c,v 0.1 27/02/2000 EK */
#include <stdio.h>
#include <stdlib.h>
#include "WarpGL.h"
#include "GL/os2mesa.h"
#include "os2mesadef.h"
#include "colors.h"
#include "context.h"
#include "colormac.h"
#include "extensions.h"
#include "matrix.h"
#include "texformat.h"
#include "texstore.h"
#include "array_cache/acache.h"
#include "swrast_setup/swrast_setup.h"
#include "swrast/s_alphabuf.h"
#include "tnl/tnl.h"
#include "tnl/t_context.h"
#include "tnl/t_pipeline.h"
#include "glutint.h"
/* ???? */
#include "swrast/swrast.h"
/* external functions */
BOOL DiveFlush(PWMC pwc);
int DivePMInit(WMesaContext c);
void
_swrast_CopyPixels( GLcontext *ctx,
GLint srcx, GLint srcy, GLsizei width, GLsizei height,
GLint destx, GLint desty,
GLenum type );
/**********************/
/* internal functions */
/**********************/
static void OS2mesa_update_state( GLcontext* ctx, GLuint new_state );
BOOL wmFlush(PWMC pwc);
void wmSetPixel(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
void wmSetPixel_db1(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
void wmSetPixel_db2(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
void wmSetPixel_db3(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
void wmSetPixel_db4(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
void wmSetPixel_sb(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b);
int wmGetPixel(PWMC pwc, int x, int y);
void wmCreateDIBSection(
HDC hDC,
PWMC pwc, // handle of device context
CONST BITMAPINFO2 *pbmi// address of structure containing bitmap size, format, and color data
);
//, UINT iUsage) // color data type indicator: RGB values or palette indices
BYTE DITHER_RGB_2_8BIT( int r, int g, int b, int x, int y);
/*******************/
/* macros */
/*******************/
#define LONGFromRGB(R,G,B) (LONG)(((LONG)R<<16)+((LONG)G<<8)+(LONG)B)
/* Windos use inverse order for Red and Blue */
#define GetRValue(rgb) ((BYTE)((rgb)>>16))
#define GetGValue(rgb) ((BYTE)((rgb)>> 8))
#define GetBValue(rgb) ((BYTE)(rgb))
#define MAKEWORD(a, b) ((short int)(((BYTE)(a)) | (((short int)((BYTE)(b))) << 8)))
/*
* Useful macros:
Modified from file osmesa.c
*/
//#define PIXELADDR(X,Y) ((GLubyte *)Current->pbPixels + (Current->height-Y-1)* Current->ScanWidth + (X)*nBypp)
#define PIXELADDR(X,Y) ((GLubyte *)Current->pbPixels + (Y)* Current->ScanWidth + (X)*nBypp)
#define PIXELADDR1( X, Y ) \
((GLubyte *)wmesa->pbPixels + (Y) * wmesa->ScanWidth + (X))
//((GLubyte *)wmesa->pbPixels + (wmesa->height-Y-1) * wmesa->ScanWidth + (X))
#define PIXELADDR2( X, Y ) \
((GLubyte *)wmesa->pbPixels + (Y) * wmesa->ScanWidth + (X)*2)
//((GLubyte *)wmesa->pbPixels + (wmesa->height - Y - 1) * wmesa->ScanWidth + (X)*2)
#define PIXELADDR4( X, Y ) \
((GLubyte *)wmesa->pbPixels + (Y) * wmesa->ScanWidth + (X)*4)
//((GLubyte *)wmesa->pbPixels + (wmesa->height-Y-1) * wmesa->ScanWidth + (X)*4)
#define PIXELADDR_1( X, Y ) \
((GLubyte *)pwc->pbPixels + (Y) * pwc->ScanWidth + (X))
#define PIXELADDR_2( X, Y ) \
((GLubyte *)pwc->pbPixels + (Y) * pwc->ScanWidth + (X)*2)
#define PIXELADDR_3( X, Y ) \
((GLubyte *)pwc->pbPixels + (Y) * pwc->ScanWidth + (X)*3)
#define PIXELADDR_4( X, Y ) \
((GLubyte *)pwc->pbPixels + (Y) * pwc->ScanWidth + (X)*4)
/*
* Values for the format parameter of OSMesaCreateContext()
*/
#define OSMESA_COLOR_INDEX GL_COLOR_INDEX
#define OSMESA_RGBA GL_RGBA
#define OSMESA_BGRA 0x1
#define OSMESA_ARGB 0x2
#define OSMESA_RGB GL_RGB
#define OSMESA_BGR 0x4
#define OSMESA_RGB_565 0x5
/*******************/
/* local constants */
/*******************/
/* static */
PWMC Current = NULL;
GLenum stereoCompile = GL_FALSE ;
GLenum stereoShowing = GL_FALSE ;
GLenum stereoBuffer = GL_FALSE;
GLint stereo_flag = 0 ;
static void wmSetPixelFormat( PWMC wc, HDC hDC)
{
if(wc->rgb_flag)
{ long Alarray[4];
long lFormats[24];/* Formats supported by the device */
int Nformats;
/*
{ int i;
long cAlarray[104];
FILE *fp;
i = 64;
DevQueryCaps(hDC,CAPS_FAMILY,i, cAlarray);
fp=fopen("test.txt","w");
for(i=0;i<64;i++)
fprintf(fp,"%2i, %x\n",i,cAlarray[i]);
fclose(fp);
}
*/
DevQueryCaps(hDC,CAPS_BITMAP_FORMATS,1, Alarray);
Nformats = (int)Alarray[0];
if(Nformats > 12) Nformats=12;
/* Get screen supportable formats */
GpiQueryDeviceBitmapFormats(wc->hps, Nformats*2, lFormats);
// pbmInfo.cPlanes = (USHORT) lFormats[0] ;
// pbmInfo.cBitCount = (USHORT) lFormats[1];
DevQueryCaps(hDC,CAPS_COLOR_BITCOUNT,1, Alarray);
wc->nColorBits = (int) Alarray[0];
printf("CAPS_COLOR_BITCOUNT=%i ",wc->nColorBits);
if(wc->nColorBits == 24 && wc->useDive && (wc->DiveCaps.ulDepth == 32)) /* Matrox driver */
wc->nColorBits = 32;
else
{ if(wc->nColorBits == 8 /* && wc->useDive */ )
{ wc->nColorBits = 24;
// wc->useDive = 0;
} else if(wc->nColorBits < 24){
wc->nColorBits = 24;
} else if(wc->nColorBits == 32){
/* Вещь, специфическая для PM'а ?*/
// wc->nColorBits = 24;
wc->nColorBits = 32;
}
}
// else if(wc->nColorBits == 16 && wc->useDive)
// { wc->nColorBits = 24;
// }
} else
wc->nColorBits = 8;
printf("wc->nColorBits=%i\n",wc->nColorBits);
switch(wc->nColorBits){
case 8:
if(wc->dither_flag != GL_TRUE)
wc->pixelformat = PF_INDEX8;
else
wc->pixelformat = PF_DITHER8;
break;
case 16:
wc->pixelformat = PF_5R6G5B;
break;
case 24:
wc->pixelformat = PF_8R8G8B;
break;
case 32:
wc->pixelformat = PF_8A8B8G8R;//PF_8R8G8B;
break;
default:
wc->pixelformat = PF_BADFORMAT;
}
}
//
// This function creates the DIB section that is used for combined
// GL and GDI calls
//
BOOL wmCreateBackingStore(PWMC pwc, long lxSize, long lySize)
{
HDC hdc = pwc->hDC;
BITMAPINFO2 *pbmi_mem = &(pwc->memb.bmi_mem);
BITMAPINFOHEADER2 *pbmi = &(pwc->bmi);
pbmi->cbFix = sizeof(BITMAPINFOHEADER2);
pbmi->cx = lxSize;
pbmi->cy = lySize;
pbmi->cPlanes = 1;
if(pwc->rgb_flag)
{ LONG *pVC_Caps;
pVC_Caps = GetVideoConfig(pwc->hDC);
pbmi->cBitCount = pVC_Caps[CAPS_COLOR_BITCOUNT];
printf("1 pbmi->cBitCount=%i\n",pbmi->cBitCount);
if(pbmi->cBitCount == 24 && pwc->useDive && (pwc->DiveCaps.ulDepth == 32)) /* Matrox driver */
pbmi->cBitCount = 32;
else
{
if(pbmi->cBitCount == 8)
{ if(pwc->useDive&0x0f)
pwc->useDive |= 0x200; /* use dithering for DIVE */
pbmi->cBitCount = 24;
} else {
if(pbmi->cBitCount == 16 && (pwc->useDive&0x0f) )
pwc->useDive |= 0x100;
//tmpDEBUG pbmi->cBitCount = 24;
if(pbmi->cBitCount < 32)
pbmi->cBitCount = 24;
}
}
}
else
pbmi->cBitCount = 8;
printf("pbmi->cBitCount=%i, useDive=%x\n",pbmi->cBitCount,pwc->useDive);
pbmi->ulCompression = BCA_UNCOMP;
pbmi->cbImage = 0;
pbmi->cxResolution = 0;
pbmi->cyResolution = 0;
pbmi->cclrUsed = 0;
pbmi->cclrImportant = 0;
pbmi->usUnits = BRU_METRIC;
pbmi->usReserved = 0;
pbmi->usRecording = BRA_BOTTOMUP;
pbmi->usRendering = BRH_NOTHALFTONED;
pbmi->cSize1 = 0;
pbmi->cSize2 = 0;
pbmi->ulColorEncoding = BCE_RGB;
pbmi->ulIdentifier = 1;
// iUsage = (pbmi->cBitCount <= 8) ? DIB_PAL_COLORS : DIB_RGB_COLORS;
pwc->nColorBits = pbmi->cBitCount;
pwc->ScanWidth = pwc->pitch = (int)lxSize;
memcpy((void *)pbmi_mem, (void *)pbmi, sizeof(BITMAPINFOHEADER2));
// pbmi_mem->argbColor[0] = 0;
wmCreateDIBSection(hdc, pwc, pbmi_mem);
// if ((iUsage == DIB_PAL_COLORS) && !(pwc->hGLPalette)) {
// wmCreatePalette( pwc );
// wmSetDibColors( pwc );
// }
wmSetPixelFormat(pwc, pwc->hDC);
return(TRUE);
}
//
// Free up the dib section that was created
//
BOOL wmDeleteBackingStore(PWMC pwc)
{
if(pwc->memb.pBmpBuffer)
{ free(pwc->memb.pBmpBuffer);
pwc->memb.pBmpBuffer = NULL;
}
pwc->pbPixels = NULL;
if(pwc->hbm) GpiDeleteBitmap(pwc->hbm);
pwc->hbm = 0;
//free( pbmi);
GpiDestroyPS(pwc->memb.hpsMem); /* destroys presentation space */
DevCloseDC(pwc->memb.hdcMem); /* closes device context */
return TRUE;
}
/***********************************************/
/* Return characteristics of the output buffer. */
/***********************************************/
static void get_buffer_size( GLframebuffer *buffer, GLuint *width, GLuint *height )
{
int New_Size;
RECTL CR;
GET_CURRENT_CONTEXT(ctx);
WinQueryWindowRect(Current->Window,&CR);
*width = (GLuint) (CR.xRight - CR.xLeft);
*height = (GLuint) (CR.yTop - CR.yBottom);
New_Size=((*width)!=Current->width) || ((*height)!=Current->height);
if (New_Size){
Current->width=*width;
Current->height=*height;
Current->ScanWidth=Current->width;
if ((Current->ScanWidth%sizeof(long))!=0)
Current->ScanWidth+=(sizeof(long)-(Current->ScanWidth%sizeof(long)));
if (Current->db_flag){
if (Current->rgb_flag==GL_TRUE && Current->dither_flag!=GL_TRUE){
wmDeleteBackingStore(Current);
wmCreateBackingStore(Current, Current->width, Current->height);
}
}
// Resize OsmesaBuffer if in Parallel mode
}
}
//
// We cache all gl draw routines until a flush is made
//
static void flush(GLcontext* ctx)
{
if((Current->rgb_flag /*&& !(Current->dib.fFlushed)*/&&!(Current->db_flag))
||(!Current->rgb_flag))
{
wmFlush(Current);
}
}
/*
* Set the color index used to clear the color buffer.
*/
static void clear_index(GLcontext* ctx, GLuint index)
{
Current->clearpixel = index;
}
/*
* Set the color used to clear the color buffer.
*/
static void clear_color( GLcontext* ctx, const GLfloat color[4] )
{
GLubyte col[4];
CLAMPED_FLOAT_TO_UBYTE(col[0], color[0]);
CLAMPED_FLOAT_TO_UBYTE(col[1], color[1]);
CLAMPED_FLOAT_TO_UBYTE(col[2], color[2]);
Current->clearpixel = LONGFromRGB(col[0], col[1], col[2]);
}
/*
* Clear the specified region of the color buffer using the clear color
* or index as specified by one of the two functions above.
*
* This procedure clears either the front and/or the back COLOR buffers.
* Only the "left" buffer is cleared since we are not stereo.
* Clearing of the other non-color buffers is left to the swrast.
* We also only clear the color buffers if the color masks are all 1's.
* Otherwise, we let swrast do it.
*/
static void clear(GLcontext* ctx, GLbitfield mask,
GLboolean all, GLint x, GLint y, GLint width, GLint height)
{ RECTL rect;
if (all)
{ x=y=0;
width=Current->width;
height=Current->height;
}
/* clear alpha */
if ((mask & (DD_FRONT_LEFT_BIT | DD_BACK_RIGHT_BIT)) &&
ctx->DrawBuffer->UseSoftwareAlphaBuffers &&
ctx->Color.ColorMask[ACOMP]) {
_mesa_clear_alpha_buffers( ctx );
}
if(Current->db_flag==GL_TRUE)
{
int dwColor;
short int wColor;
BYTE bColor;
int *lpdw = (int *)Current->pbPixels;
short int *lpw = (short int *)Current->pbPixels;
PBYTE lpb = Current->pbPixels;
int lines;
if(Current->db_flag==GL_TRUE){
UINT nBypp = Current->nColorBits / 8;
int i = 0;
int iSize = 0;
if(nBypp ==1 ){
/* Need rectification */
iSize = Current->width/4;
bColor = (BYTE) BGR8(GetRValue(Current->clearpixel),
GetGValue(Current->clearpixel),
GetBValue(Current->clearpixel));
wColor = MAKEWORD(bColor,bColor);
dwColor = (int) MAKELONG(wColor, wColor);
}
if(nBypp == 2){
int r,g,b;
r = GetRValue(Current->clearpixel);
g = GetGValue(Current->clearpixel);
b = GetBValue(Current->clearpixel);
iSize = Current->width / 2;
wColor = BGR16(GetRValue(Current->clearpixel),
GetGValue(Current->clearpixel),
GetBValue(Current->clearpixel));
dwColor = (int)MAKELONG(wColor, wColor);
}
else if(nBypp == 4){
iSize = Current->width;
dwColor = (int)BGR32(GetRValue(Current->clearpixel),
GetGValue(Current->clearpixel),
GetBValue(Current->clearpixel));
}
while(i < iSize){
*lpdw = dwColor;
lpdw++;
i++;
}
//
// This is the 24bit case
//
if (nBypp == 3) {
iSize = Current->width *3/4;
dwColor = (int)BGR24(GetRValue(Current->clearpixel),
GetGValue(Current->clearpixel),
GetBValue(Current->clearpixel));
while(i < iSize){
*lpdw = dwColor;
lpb += nBypp;
lpdw = (int *)lpb;
i++;
}
}
i = 0;
if (stereo_flag)
lines = height /2;
else
lines = height;
do {
memcpy(lpb, Current->pbPixels, iSize*4);
lpb += Current->ScanWidth;
i++;
}
while (i<lines-1);
}
mask &= ~DD_FRONT_LEFT_BIT;
} else { // For single buffer
rect.xLeft = x;
rect.xRight = x + width;
rect.yBottom = y;
rect.yTop = y + height;
WinFillRect(Current->hps, &rect, Current->clearpixel);
mask &= ~DD_FRONT_LEFT_BIT;
}
/* Call swrast if there is anything left to clear (like DEPTH) */
if (mask)
_swrast_Clear( ctx, mask, all, x, y, width, height );
}
static void enable( GLcontext* ctx, GLenum pname, GLboolean enable )
{
if (!Current)
return;
if (pname == GL_DITHER) {
if(enable == GL_FALSE){
Current->dither_flag = GL_FALSE;
if(Current->nColorBits == 8)
Current->pixelformat = PF_INDEX8;
}
else{
if (Current->rgb_flag && Current->nColorBits == 8){
Current->pixelformat = PF_DITHER8;
Current->dither_flag = GL_TRUE;
}
else
Current->dither_flag = GL_FALSE;
}
}
}
static void set_buffer(GLcontext *ctx, GLframebuffer *colorBuffer,
GLuint bufferBit )
{
/* XXX todo - examine bufferBit and set read/write pointers */
return;
}
/* Set the current color index. */
static void set_index(GLcontext* ctx, GLuint index)
{
Current->pixel=index;
}
/* Set the current RGBA color. */
static void set_color( GLcontext* ctx, GLubyte r, GLubyte g, GLubyte b, GLubyte a )
{
Current->pixel = LONGFromRGB( r, g, b );
}
/* Set the index mode bitplane mask. */
static GLboolean index_mask(GLcontext* ctx, GLuint mask)
{
/* can't implement */
return GL_FALSE;
}
/* Set the RGBA drawing mask. */
static GLboolean color_mask( GLcontext* ctx,
GLboolean rmask, GLboolean gmask,
GLboolean bmask, GLboolean amask)
{
/* can't implement */
return GL_FALSE;
}
/*
* Set the pixel logic operation. Return GL_TRUE if the device driver
* can perform the operation, otherwise return GL_FALSE. If GL_FALSE
* is returned, the logic op will be done in software by Mesa.
*/
GLboolean logicop( GLcontext* ctx, GLenum op )
{
/* can't implement */
return GL_FALSE;
}
/**********************************************************************/
/***** Span-based pixel drawing *****/
/**********************************************************************/
/* Write a horizontal span of 32-bit color-index pixels with a boolean mask. */
static void write_ci32_span( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLuint index[],
const GLubyte mask[] )
{
GLuint i;
PBYTE Mem=Current->ScreenMem + y*Current->ScanWidth + x;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++)
if (mask[i])
Mem[i]=index[i];
}
/* Write a horizontal span of 8-bit color-index pixels with a boolean mask. */
static void write_ci8_span( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLubyte index[],
const GLubyte mask[] )
{
GLuint i;
PBYTE Mem=Current->ScreenMem + y *Current->ScanWidth+x;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++)
if (mask[i])
Mem[i]=index[i];
}
/*
* Write a horizontal span of pixels with a boolean mask. The current
* color index is used for all pixels.
*/
static void write_mono_ci_span(const GLcontext* ctx,
GLuint n,GLint x,GLint y,
GLuint colorIndex, const GLubyte mask[])
{
GLuint i;
BYTE *Mem=Current->ScreenMem + y * Current->ScanWidth+x;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++)
if (mask[i])
Mem[i]= (BYTE) colorIndex;
}
/* Write a horizontal span of RGBA color pixels with a boolean mask. */
static void write_rgba_span( const GLcontext* ctx, GLuint n, GLint x, GLint y,
const GLubyte rgba[][4], const GLubyte mask[] )
{
PWMC pwc = Current;
GLuint i;
// if (pwc->rgb_flag==GL_TRUE)
{
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
unsigned short int *lpw;
if(Current->db_flag)
{
UINT nBypp = pwc->nColorBits / 8;
lpb += pwc->ScanWidth * y;
// Now move to the desired pixel
lpb += x * nBypp;
// lpb = (PBYTE)PIXELADDR(x, iScanLine);
//#define PIXELADDR(X,Y) ((GLubyte *)Current->pbPixels + (Y+1)* Current->ScanWidth + (X)*nBypp)
// ???
if (mask) {
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel(pwc, y, x + i, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else {
// pаскpываем все вызовы
// for (i=0; i<n; i++)
// wmSetPixel(pwc, y, x + i, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP] );
if(nBypp == 1)
{
if(pwc->dither_flag)
for (i=0; i<n; i++,lpb++)
*lpb = DITHER_RGB_2_8BIT(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP],y,x);
else
for (i=0; i<n; i++,lpb++)
*lpb = (BYTE) BGR8(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else if(nBypp == 2) {
lpw = (unsigned short int *)lpb;
for (i=0; i<n; i++,lpw++)
*lpw = BGR16(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else if (nBypp == 3) {
for (i=0; i<n; i++)
{ *lpb++ = rgba[i][BCOMP]; // in memory: b-g-r bytes
*lpb++ = rgba[i][GCOMP];
*lpb++ = rgba[i][RCOMP];
}
} else if (nBypp == 4) {
lpdw = (UINT *)lpb;
//??? memcpy(lpb,rgba,n*4);
for (i=0; i<n; i++,lpdw++)
*lpdw = ((UINT)rgba[i][BCOMP]) | (((UINT)rgba[i][GCOMP])<<8 )| (((UINT)rgba[i][RCOMP])<<16);
// *lpdw = BGR32(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
//#define BGR32(r,g,b) (unsigned long)((DWORD)(((BYTE)(b)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(r))<<16)))
}
}
} else { // (!Current->db_flag)
POINTL ptl;
int col=-1, colold=-1,iold=0;
ptl.y = y;
ptl.x = x;
if (mask)
{
for (i=0; i<n; i++,ptl.x++)
if (mask[i])
{ GpiSetColor(pwc->hps,LONGFromRGB(rgba[i][RCOMP],rgba[i][GCOMP], rgba[i][BCOMP]));
GpiSetPel(pwc->hps, &ptl);
}
} else {
GpiMove(pwc->hps,&ptl);
for (i=0; i<n; i++,ptl.x++)
{ col = (int) LONGFromRGB(rgba[i][RCOMP],rgba[i][GCOMP], rgba[i][BCOMP]);
if(col != colold)
{ GpiSetColor(pwc->hps,col);
GpiLine(pwc->hps,&ptl);
colold = col;
iold = i;
}
}
if(iold != n-1)
{ ptl.x--;
// GpiSetColor(pwc->hps,col);
GpiLine(pwc->hps,&ptl);
}
} //endif(mask)
} //endif(Current->db_flag)
}
// endofif (pwc->rgb_flag==GL_TRUE)
}
/* Write a horizontal span of RGB color pixels with a boolean mask. */
static void write_rgb_span( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLubyte rgb[][3], const GLubyte mask[] )
{
PWMC pwc = Current;
GLuint i;
if(pwc->db_flag)
{
if (mask) {
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel(pwc, y, x + i, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
}
else {
for (i=0; i<n; i++)
wmSetPixel(pwc, y, x + i, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP] );
}
} else { // (!pwc->db_flag)
POINTL ptl;
int col=-1, colold=-1,iold=0;
ptl.y = y;
ptl.x = x;
if (mask)
{
for (i=0; i<n; i++,ptl.x++)
if (mask[i])
{ GpiSetColor(pwc->hps,LONGFromRGB(rgb[i][RCOMP],rgb[i][GCOMP], rgb[i][BCOMP]));
GpiSetPel(pwc->hps, &ptl);
}
} else {
GpiMove(pwc->hps,&ptl);
for (i=0; i<n; i++,ptl.x++)
{ col = (int) LONGFromRGB(rgb[i][RCOMP],rgb[i][GCOMP], rgb[i][BCOMP]);
if(col != colold)
{ GpiSetColor(pwc->hps,col);
GpiLine(pwc->hps,&ptl);
colold = col;
iold = i;
}
}
if(iold != n-1)
{ ptl.x--;
// GpiSetColor(pwc->hps,col);
GpiLine(pwc->hps,&ptl);
}
} //endif(mask)
} //endif(pwc->db_flag)
}
/*
* Write a horizontal span of pixels with a boolean mask all with the same color
*/
static void write_mono_rgba_span( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLchan color[4], const GLubyte mask[])
{
GLuint i;
PWMC pwc = Current;
assert(Current->rgb_flag==GL_TRUE);
if(pwc->db_flag)
{ if(mask)
{ for (i=0; i<n; i++)
if (mask[i])
wmSetPixel(pwc,y,x+i,color[RCOMP], color[GCOMP], color[BCOMP]);
} else {
for (i=0; i<n; i++)
wmSetPixel(pwc,y,x+i,color[RCOMP], color[GCOMP], color[BCOMP]);
}
} else {
POINTL Point; /* Position in world coordinates. */
LONG l_Color = LONGFromRGB(color[RCOMP], color[GCOMP], color[BCOMP]);
Point.y = y;
GpiSetColor(pwc->hps,l_Color);
if(mask)
{ for (i=0; i<n; i++)
if (mask[i])
{ Point.x = x+i;
GpiSetPel(pwc->hps, &Point);
}
} else {
Point.x = x;
if(n <= 1) GpiSetPel(pwc->hps, &Point);
else
{ GpiMove(pwc->hps,&Point);
Point.x += n-1;
GpiLine(pwc->hps,&Point);
}
}
}
}
/*************************************************/
/*** optimized N-bytes per pixel functions ****/
/*************************************************/
//static void write_clear_rgba_span_4rgb_db( const GLcontext* ctx, GLuint n, GLint x, GLint y,
// const GLubyte rgba[4])
static void write_mono_rgba_span_4rgb_db( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLchan color[4], const GLubyte mask[])
{
PWMC pwc = Current;
GLuint i;
PBYTE lpb = pwc->pbPixels;
UINT *lpdw, col;
// Now move to the desired pixel
lpdw = (UINT *)(lpb + pwc->ScanWidth * y);
lpdw += x;
col = ((UINT)color[BCOMP]) | (((UINT)color[GCOMP])<<8 ) |
(((UINT)color[RCOMP])<<16)| (((UINT)color[ACOMP])<<24);
if (mask)
{ for (i=0; i<n; i++)
if (mask[i])
{ lpdw[i] = col;
}
} else {
for (i=0; i<n; i++,lpdw++) *lpdw = col;
}
}
//static void write_clear_rgba_span_3rgb_db( const GLcontext* ctx, GLuint n, GLint x, GLint y,
// const GLubyte rgba[4])
static void write_mono_rgba_span_3rgb_db( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
const GLchan color[4], const GLubyte mask[])
{
PWMC pwc = Current;
GLuint i;
PBYTE lpb = pwc->pbPixels, pixel;
UINT *lpdw, col;
// Now move to the desired pixel
lpb += pwc->ScanWidth * y +x*3;
if (mask)
{ for (i=0; i<n; i++)
if (mask[i])
{ pixel = lpb+i*3;
pixel[0] = color[2];
pixel[1] = color[1];
pixel[2] = color[0];
}
} else {
col = ((UINT)color[BCOMP]) | (((UINT)color[GCOMP])<<8 ) | (((UINT)color[RCOMP])<<16);
for (i=0; i<n-1; i++,lpb+=3)
{ lpdw = (UINT *)lpb;
*lpdw = col;
}
lpdw = (UINT *)lpb;
*lpdw = col | ((*lpdw)&0xff0000);
}
}
/* Write a horizontal span of RGBA color pixels with a boolean mask. */
static void write_rgba_span_4rgb_db( const GLcontext* ctx, GLuint n, GLint x, GLint y,
const GLubyte rgba[][4], const GLubyte mask[] )
{
PWMC pwc = Current;
GLuint i;
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
lpb += pwc->ScanWidth * y;
// Now move to the desired pixel
lpb += x * 4;
if (mask)
{
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel_db4(pwc, y, x + i, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else {
lpdw = (UINT *)lpb;
//??? memcpy(lpb,rgba,n*4);
for (i=0; i<n; i++,lpdw++)
*lpdw = ((UINT)rgba[i][BCOMP]) | (((UINT)rgba[i][GCOMP])<<8 )| (((UINT)rgba[i][RCOMP])<<16);
// *lpdw = BGR32(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
//#define BGR32(r,g,b) (unsigned long)((DWORD)(((BYTE)(b)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(r))<<16)))
}
}
/* Write a horizontal span of RGBA color pixels with a boolean mask. */
static void write_rgba_span_3rgb_db( const GLcontext* ctx, GLuint n, GLint x, GLint y,
const GLubyte rgba[][4], const GLubyte mask[] )
{
PWMC pwc = Current;
GLuint i;
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
lpb += pwc->ScanWidth * y;
// Now move to the desired pixel
lpb += x * 3;
if (mask)
{
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel_db3(pwc, y, x + i, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else {
for (i=0; i<n; i++)
{
/// *lpdw = ((UINT)rgba[i][BCOMP]) | (((UINT)rgba[i][GCOMP])<<8 )| (((UINT)rgba[i][RCOMP])<<16);
*lpb++ = rgba[i][BCOMP]; // in memory: b-g-r bytes
*lpb++ = rgba[i][GCOMP];
*lpb++ = rgba[i][RCOMP];
}
// *lpdw = BGR32(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
//#define BGR32(r,g,b) (unsigned long)((DWORD)(((BYTE)(b)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(r))<<16)))
}
}
/* Write a horizontal span of RGBA color pixels with a boolean mask. */
static void write_rgba_span_2rgb_db( const GLcontext* ctx, GLuint n, GLint x, GLint y,
const GLubyte rgba[][4], const GLubyte mask[] )
{
PWMC pwc = Current;
GLuint i;
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
unsigned short int *lpw;
lpb += pwc->ScanWidth * y;
// Now move to the desired pixel
lpb += x * 2;
if (mask)
{
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel_db2(pwc, y, x + i, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else {
lpw = (unsigned short int *)lpb;
for (i=0; i<n; i++,lpw++)
*lpw = BGR16(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
}
}
/**********************************************************************/
/***** Array-based pixel drawing *****/
/**********************************************************************/
/* Write an array of 32-bit index pixels with a boolean mask. */
static void write_ci32_pixels( const GLcontext* ctx,
GLuint n, const GLint x[], const GLint y[],
const GLuint index[], const GLubyte mask[] )
{
GLuint i;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++) {
if (mask[i]) {
BYTE *Mem=Current->ScreenMem + y[i] * Current->ScanWidth + x[i];
*Mem = index[i];
}
}
}
/*
* Write an array of pixels with a boolean mask. The current color
* index is used for all pixels.
*/
static void write_mono_ci_pixels( const GLcontext* ctx,
GLuint n,
const GLint x[], const GLint y[],
GLuint colorIndex, const GLubyte mask[] )
{
GLuint i;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++) {
if (mask[i]) {
BYTE *Mem=Current->ScreenMem + y[i] * Current->ScanWidth + x[i];
*Mem = (BYTE) colorIndex;
}
}
}
/* Write an array of RGBA pixels with a boolean mask. */
static void write_rgba_pixels( const GLcontext* ctx,
GLuint n, const GLint x[], const GLint y[],
const GLubyte rgba[][4], const GLubyte mask[] )
{
GLuint i;
PWMC pwc = Current;
// HDC DC=DD_GETDC;
assert(Current->rgb_flag==GL_TRUE);
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel(pwc, y[i],x[i],rgba[i][RCOMP],rgba[i][GCOMP],rgba[i][BCOMP]);
// DD_RELEASEDC;
}
/*
* Write an array of pixels with a boolean mask. The current color
* is used for all pixels.
*/
static void write_mono_rgba_pixels( const GLcontext* ctx,
GLuint n,
const GLint x[], const GLint y[],
const GLchan color[4],
const GLubyte mask[] )
{
GLuint i;
PWMC pwc = Current;
// HDC DC=DD_GETDC;
assert(Current->rgb_flag==GL_TRUE);
for (i=0; i<n; i++)
if (mask[i])
wmSetPixel(pwc, y[i],x[i],color[RCOMP],
color[GCOMP], color[BCOMP]);
// DD_RELEASEDC;
}
/**********************************************************************/
/***** Read spans/arrays of pixels *****/
/**********************************************************************/
/* Read a horizontal span of color-index pixels. */
static void read_ci32_span( const GLcontext* ctx, GLuint n, GLint x, GLint y,
GLuint index[])
{
GLuint i;
BYTE *Mem=Current->ScreenMem + y *Current->ScanWidth+x;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++)
index[i]=Mem[i];
}
/* Read an array of color index pixels. */
static void read_ci32_pixels( const GLcontext* ctx,
GLuint n, const GLint x[], const GLint y[],
GLuint indx[], const GLubyte mask[] )
{
GLuint i;
assert(Current->rgb_flag==GL_FALSE);
for (i=0; i<n; i++) {
if (mask[i]) {
indx[i]=*(Current->ScreenMem + y[i] * Current->ScanWidth+x[i]);
}
}
}
/* Read a horizontal span of color pixels. */
static void read_rgba_span( const GLcontext* ctx,
GLuint n, GLint x, GLint y,
GLubyte rgba[][4] )
{
UINT i;
LONG Color;
PWMC pwc = Current;
if(Current->db_flag)
{ UINT nBypp = pwc->nColorBits / 8;
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
unsigned short int *lpw;
lpb += pwc->ScanWidth * y;
lpb += x * nBypp;
/*********************/
if(nBypp == 1)
{
for (i=0; i<n; i++,lpb++)
{ Color = (int) *lpb;
rgba[i][RCOMP] = GetRValue(Color);
rgba[i][GCOMP] = GetGValue(Color);
rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
}
} else if(nBypp == 2) {
lpw = (unsigned short int *)lpb;
for (i=0; i<n; i++,lpw++)
{ Color = (int) (*lpw);
rgba[i][RCOMP] = GetRValue(Color);
rgba[i][GCOMP] = GetGValue(Color);
rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
}
} else if (nBypp == 3) {
for (i=0; i<n; i++,lpb+=3)
{ // GLubyte rtst[4];
lpdw = (UINT *)lpb;
// Color = (int) (*lpdw);
// *((int *)&rtst) = Color;
// rtst[RCOMP] = GetRValue(Color);
// rtst[GCOMP] = GetGValue(Color);
// rtst[BCOMP] = GetBValue(Color);
// rtst[ACOMP] = 255;
*((int *)&rgba[i]) = (int) (*lpdw);
// rgba[i][RCOMP] = GetRValue(Color);
// rgba[i][GCOMP] = GetGValue(Color);
// rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
}
// *lpdw = BGR24(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
} else if (nBypp == 4) {
lpdw = (UINT *)lpb;
for (i=0; i<n; i++,lpdw++)
{ Color = (int) (*lpdw);
rgba[i][RCOMP] = GetRValue(Color);
rgba[i][GCOMP] = GetGValue(Color);
rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
}
// *lpdw = ((UINT)rgba[i][BCOMP]) | (((UINT)rgba[i][GCOMP])<<8 )| (((UINT)rgba[i][RCOMP])<<16);
// *lpdw = BGR32(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
//#define BGR32(r,g,b) (unsigned long)((DWORD)(((BYTE)(b)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(r))<<16)))
}
/*********************/
} else {
for (i=0; i<n; i++,x++)
{
Color = wmGetPixel(pwc,x, y); // GpiQueryPel(Current->hps, &Point);
rgba[i][RCOMP] = GetRValue(Color);
rgba[i][GCOMP] = GetGValue(Color);
rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
}
}
}
/* Read an array of color pixels. */
static void read_rgba_pixels( const GLcontext* ctx,
GLuint n, const GLint x[], const GLint y[],
GLubyte rgba[][4], const GLubyte mask[] )
{
GLuint i;
LONG Color;
PWMC pwc = Current;
assert(Current->rgb_flag==GL_TRUE);
for (i=0; i<n; i++) {
if (mask[i]) {
// Color = GpiQueryPel(Current->hps, &Point);
Color = wmGetPixel(pwc,x[i], y[i]); // GpiQueryPel(Current->hps, &Point);
rgba[i][RCOMP] = GetRValue(Color);
rgba[i][GCOMP] = GetGValue(Color);
rgba[i][BCOMP] = GetBValue(Color);
rgba[i][ACOMP] = 255;
//?? rgba[i][ACOMP] = 0;
}
}
}
static const GLubyte *OS2get_string( GLcontext *ctx, GLenum name )
{
switch (name)
{ case GL_RENDERER:
return (const GLubyte *) "WarpMesaGL OS/2 PM GPI";
case GL_VENDOR:
return (const GLubyte *) "Evgeny Kotsuba";
default:
return NULL;
}
}
static void SetFunctionPointers(GLcontext *ctx)
{
struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
ctx->Driver.GetString = OS2get_string;
// ctx->Driver.UpdateState = wmesa_update_state;
ctx->Driver.UpdateState = OS2mesa_update_state;
ctx->Driver.ResizeBuffers = _swrast_alloc_buffers;
ctx->Driver.GetBufferSize = get_buffer_size;
ctx->Driver.Accum = _swrast_Accum;
ctx->Driver.Bitmap = _swrast_Bitmap;
ctx->Driver.Clear = clear;
// warning EDC0068: Operation between types
// "void(* _Optlink)(struct __GLcontextRec*,unsigned int,unsigned char,int,int,int,int)" and
// "unsigned int(* _Optlink)(struct __GLcontextRec*,unsigned int,unsigned char,int,int,int,int)" is not allowed.
ctx->Driver.Flush = flush;
ctx->Driver.ClearIndex = clear_index;
ctx->Driver.ClearColor = clear_color;
// warning EDC0068: Operation between types
//"void(* _Optlink)(struct __GLcontextRec*,const float*)" and
//"void(* _Optlink)(struct __GLcontextRec*,unsigned char,unsigned char,unsigned char,unsigned char)" is not allowed.
ctx->Driver.Enable = enable;
ctx->Driver.CopyPixels = _swrast_CopyPixels;
ctx->Driver.DrawPixels = _swrast_DrawPixels;
ctx->Driver.ReadPixels = _swrast_ReadPixels;
ctx->Driver.DrawBuffer = _swrast_DrawBuffer;
ctx->Driver.ChooseTextureFormat = _mesa_choose_tex_format;
ctx->Driver.TexImage1D = _mesa_store_teximage1d;
ctx->Driver.TexImage2D = _mesa_store_teximage2d;
ctx->Driver.TexImage3D = _mesa_store_teximage3d;
ctx->Driver.TexSubImage1D = _mesa_store_texsubimage1d;
ctx->Driver.TexSubImage2D = _mesa_store_texsubimage2d;
ctx->Driver.TexSubImage3D = _mesa_store_texsubimage3d;
ctx->Driver.TestProxyTexImage = _mesa_test_proxy_teximage;
ctx->Driver.CompressedTexImage1D = _mesa_store_compressed_teximage1d;
ctx->Driver.CompressedTexImage2D = _mesa_store_compressed_teximage2d;
ctx->Driver.CompressedTexImage3D = _mesa_store_compressed_teximage3d;
ctx->Driver.CompressedTexSubImage1D = _mesa_store_compressed_texsubimage1d;
ctx->Driver.CompressedTexSubImage2D = _mesa_store_compressed_texsubimage2d;
ctx->Driver.CompressedTexSubImage3D = _mesa_store_compressed_texsubimage3d;
ctx->Driver.CopyTexImage1D = _swrast_copy_teximage1d;
ctx->Driver.CopyTexImage2D = _swrast_copy_teximage2d;
ctx->Driver.CopyTexSubImage1D = _swrast_copy_texsubimage1d;
ctx->Driver.CopyTexSubImage2D = _swrast_copy_texsubimage2d;
ctx->Driver.CopyTexSubImage3D = _swrast_copy_texsubimage3d;
ctx->Driver.CopyColorTable = _swrast_CopyColorTable;
ctx->Driver.CopyColorSubTable = _swrast_CopyColorSubTable;
ctx->Driver.CopyConvolutionFilter1D = _swrast_CopyConvolutionFilter1D;
ctx->Driver.CopyConvolutionFilter2D = _swrast_CopyConvolutionFilter2D;
swdd->SetBuffer = set_buffer;
/* Pixel/span writing functions: */
swdd->WriteRGBASpan = write_rgba_span;
swdd->WriteRGBSpan = write_rgb_span;
swdd->WriteMonoRGBASpan = write_mono_rgba_span;
swdd->WriteRGBAPixels = write_rgba_pixels;
swdd->WriteMonoRGBAPixels = write_mono_rgba_pixels;
swdd->WriteCI32Span = write_ci32_span;
swdd->WriteCI8Span = write_ci8_span;
swdd->WriteMonoCISpan = write_mono_ci_span;
swdd->WriteCI32Pixels = write_ci32_pixels;
swdd->WriteMonoCIPixels = write_mono_ci_pixels;
swdd->ReadCI32Span = read_ci32_span;
swdd->ReadRGBASpan = read_rgba_span;
swdd->ReadCI32Pixels = read_ci32_pixels;
swdd->ReadRGBAPixels = read_rgba_pixels;
// switch(ctx->DriverCtx.format)
// { case OSMESA_RGB:
// break;
// }
}
static void OS2mesa_update_state4( GLcontext* ctx, GLuint new_state )
{
struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
OS2mesa_update_state( ctx,new_state );
ctx->Driver.UpdateState = OS2mesa_update_state4;
swdd->WriteRGBASpan = write_rgba_span_4rgb_db;
swdd->WriteMonoRGBASpan = write_mono_rgba_span_4rgb_db;
// swdd->WriteClearRGBASpan = write_clear_rgba_span_4rgb_db;
}
static void OS2mesa_update_state3( GLcontext* ctx, GLuint new_state )
{
struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
OS2mesa_update_state( ctx,new_state );
ctx->Driver.UpdateState = OS2mesa_update_state3;
swdd->WriteRGBASpan = write_rgba_span_3rgb_db;
swdd->WriteMonoRGBASpan = write_mono_rgba_span_3rgb_db;
// swdd->WriteClearRGBASpan = write_clear_rgba_span_3rgb_db;
}
static void OS2mesa_update_state2( GLcontext* ctx, GLuint new_state )
{
struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
OS2mesa_update_state( ctx,new_state );
ctx->Driver.UpdateState = OS2mesa_update_state2;
swdd->WriteRGBASpan = write_rgba_span_2rgb_db;
// swdd->WriteClearRGBASpan = write_clear_rgba_span_2rgb_db;
}
static void OS2mesa_update_state1( GLcontext* ctx, GLuint new_state )
{
// struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
OS2mesa_update_state( ctx,new_state );
ctx->Driver.UpdateState = OS2mesa_update_state1;
// ctx->Driver.WriteRGBASpan = write_rgba_span_3rgb_db;
// ctx->Driver.WriteClearRGBASpan = write_clear_rgba_span_3rgb_db;
}
static void OS2mesa_update_state( GLcontext* ctx, GLuint new_state )
{
struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
TNLcontext *tnl = TNL_CONTEXT(ctx);
/*
* XXX these function pointers could be initialized just once during
* context creation since they don't depend on any state changes.
* kws - This is true - this function gets called a lot and it
* would be good to minimize setting all this when not needed.
*/
#ifndef SET_FPOINTERS_ONCE
SetFunctionPointers(ctx);
#endif // !SET_FPOINTERS_ONCE
tnl->Driver.RunPipeline = _tnl_run_pipeline;
_swrast_InvalidateState( ctx, new_state );
_swsetup_InvalidateState( ctx, new_state );
_ac_InvalidateState( ctx, new_state );
_tnl_InvalidateState( ctx, new_state );
}
/***********************************************/
WMesaContext WMesaCreateContext
( HWND hWnd, HPAL* Pal, HPS hpsCurrent, HAB hab,
GLboolean rgb_flag, GLboolean db_flag, int useDive )
//todo ?? GLboolean alpha_flag )
{
RECTL CR;
WMesaContext c;
GLboolean true_color_flag;
UINT nBypp;
int rc;
c = (struct wmesa_context * ) calloc(1,sizeof(struct wmesa_context));
if (!c)
return NULL;
c->Window=hWnd;
c->hDC = WinQueryWindowDC(hWnd);
c->hps = hpsCurrent;
c->hab = hab;
if(!db_flag)
useDive = 0; /* DIVE can be used only with db */
c->hDive = NULLHANDLE;
//printf("2 useDive=%i\n",useDive);
if(useDive)
{ rc = DivePMInit(c);
if(rc)
{ useDive = 0;
}
}
c->useDive = useDive;
//?? true_color_flag = GetDeviceCaps(c->hDC, BITSPIXEL) > 8;
true_color_flag = 1;
c->dither_flag = GL_FALSE;
#ifdef DITHER
if ((true_color_flag==GL_FALSE) && (rgb_flag == GL_TRUE)){
c->dither_flag = GL_TRUE;
c->hPalHalfTone = WinGCreateHalftonePalette();
}
else
c->dither_flag = GL_FALSE;
#else
c->dither_flag = GL_FALSE;
#endif
if (rgb_flag==GL_FALSE)
{
c->rgb_flag = GL_FALSE;
// c->pixel = 1;
c->db_flag = db_flag =GL_TRUE; // WinG requires double buffering
printf("Single buffer is not supported in color index mode, setting to double buffer.\n");
}
else
{
c->rgb_flag = GL_TRUE;
// c->pixel = 0;
}
WinQueryWindowRect(c->Window,&CR);
c->width=CR.xRight - CR.xLeft;
c->height=CR.yTop - CR.yBottom;
if (db_flag)
{
c->db_flag = 1;
/* Double buffered */
#ifndef DDRAW
// if (c->rgb_flag==GL_TRUE && c->dither_flag != GL_TRUE )
{
wmCreateBackingStore(c, c->width, c->height);
}
#endif
}
else
{
/* Single Buffered */
if (c->rgb_flag)
c->db_flag = 0;
}
#ifdef DDRAW
if (DDInit(c,hWnd) == GL_FALSE) {
free( (void *) c );
exit(1);
}
#endif
c->gl_visual = _mesa_create_visual(rgb_flag,
db_flag, /* db_flag */
GL_FALSE, /* stereo */
8,8,8,8, /* r, g, b, a bits , todo: alpha_flag ? 8 : 0, alpha bits */
0, /* index bits */
16, /* depth_bits */
8, /* stencil_bits */
16,16,16,/* accum_bits */
16, /* todo: alpha_flag ? 16 : 0, alpha accum */
1);
if (!c->gl_visual) {
return NULL;
}
/* allocate a new Mesa context */
c->gl_ctx = _mesa_create_context( c->gl_visual, NULL, (void *) c, GL_FALSE );
if (!c->gl_ctx) {
_mesa_destroy_visual( c->gl_visual );
free(c);
return NULL;
}
_mesa_enable_sw_extensions(c->gl_ctx);
_mesa_enable_1_3_extensions(c->gl_ctx);
_mesa_enable_1_4_extensions(c->gl_ctx);
c->gl_buffer = _mesa_create_framebuffer( c->gl_visual,
c->gl_visual->depthBits > 0,
c->gl_visual->stencilBits > 0,
c->gl_visual->accumRedBits > 0,
1 /* alpha_flag s/w alpha */ );
if (!c->gl_buffer) {
_mesa_destroy_visual( c->gl_visual );
_mesa_free_context_data( c->gl_ctx );
free(c);
return NULL;
}
nBypp = c->nColorBits / 8;
if(useDive)
{
printf("\aTodo Dive\n");
exit(1);
// if(nBypp == 4)
// c->gl_ctx->Driver.UpdateState = OS2Dive_mesa_update_state4;
// else
// if(nBypp == 3)
// c->gl_ctx->Driver.UpdateState = OS2Dive_mesa_update_state3;
// else
// if(nBypp == 2)
// c->gl_ctx->Driver.UpdateState = OS2Dive_mesa_update_state2;
// else
// c->gl_ctx->Driver.UpdateState = OS2Dive_mesa_update_state1;
} else {
if(db_flag && rgb_flag)
{
if(nBypp == 4)
c->gl_ctx->Driver.UpdateState = OS2mesa_update_state4;
else
if(nBypp == 3)
c->gl_ctx->Driver.UpdateState = OS2mesa_update_state3;
else
if(nBypp == 2)
c->gl_ctx->Driver.UpdateState = OS2mesa_update_state2;
else
c->gl_ctx->Driver.UpdateState = OS2mesa_update_state1;
}
else
c->gl_ctx->Driver.UpdateState = OS2mesa_update_state;
}
/* Initialize the software rasterizer and helper modules.
*/
{
GLcontext *ctx = c->gl_ctx;
_swrast_CreateContext( ctx );
_ac_CreateContext( ctx );
_tnl_CreateContext( ctx );
_swsetup_CreateContext( ctx );
#ifdef SET_FPOINTERS_ONCE
SetFunctionPointers(ctx);
#endif // SET_FPOINTERS_ONCE
_swsetup_Wakeup( ctx );
}
#ifdef COMPILE_SETPIXEL
ChooseSetPixel(c);
#endif
return c;
}
void WMesaDestroyContext( void )
{
}
void WMesaMakeCurrent( WMesaContext c )
{
if(!c){
Current = c;
return;
}
if(Current == c)
return;
Current = c;
c->gl_ctx->Driver.UpdateState(c->gl_ctx,0);
_mesa_make_current(c->gl_ctx, c->gl_buffer);
if (Current->gl_ctx->Viewport.Width==0) {
/* initialize viewport to window size */
_mesa_Viewport( 0, 0, Current->width, Current->height );
Current->gl_ctx->Scissor.Width = Current->width;
Current->gl_ctx->Scissor.Height = Current->height;
}
if ((c->nColorBits <= 8 ) && (c->rgb_flag == GL_TRUE)){
WMesaPaletteChange(c->hPalHalfTone);
}
}
void WMesaSwapBuffers( void )
{
// HDC DC = Current->hDC;
if (Current->db_flag)
{ if( Current->useDive)
DiveFlush(Current);
else
wmFlush(Current);
}
}
void WMesaPaletteChange(HPAL Pal)
{
int vRet;
#if POKA
LPPALETTEENTRY pPal;
if (Current && (Current->rgb_flag==GL_FALSE || Current->dither_flag == GL_TRUE))
{
pPal = (PALETTEENTRY *)malloc( 256 * sizeof(PALETTEENTRY));
Current->hPal=Pal;
// GetPaletteEntries( Pal, 0, 256, pPal );
GetPalette( Pal, pPal );
vRet = SetDIBColorTable(Current->dib.hDC,0,256,pPal);
free( pPal );
}
#endif /* POKA */
}
void wmSetPixel(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b)
{
POINTL ptl;
if(Current->db_flag)
{
PBYTE lpb; /* = pwc->pbPixels; */
UINT *lpdw;
unsigned short int *lpw;
UINT nBypp = pwc->nColorBits >>3; /* /8 */
// UINT nOffset = iPixel % nBypp;
// Move the pixel buffer pointer to the scanline that we
// want to access
// pwc->dib.fFlushed = FALSE;
// lpb += pwc->ScanWidth * iScanLine;
// Now move to the desired pixel
// lpb += iPixel * nBypp;
lpb = (PBYTE)PIXELADDR(iPixel, iScanLine);
if(nBypp == 1)
{
if(pwc->dither_flag)
*lpb = DITHER_RGB_2_8BIT(r,g,b,iScanLine,iPixel);
else
*lpb = BGR8(r,g,b);
} else if(nBypp == 2) {
lpw = (unsigned short int *)lpb;
*lpw = BGR16(r,g,b);
} else if (nBypp == 3) {
*lpb++ = b;
*lpb++ = g;
*lpb = r;
// lpdw = (UINT *)lpb;
// *lpdw = BGR24(r,g,b);
} else if (nBypp == 4) {
lpdw = (UINT *)lpb;
*lpdw = BGR32(r,g,b);
}
} else {
ptl.y = iScanLine;
ptl.x = iPixel;
GpiSetColor(pwc->hps,LONGFromRGB(r,g,b));
GpiSetPel(pwc->hps, &ptl);
}
}
void wmSetPixel_db1(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b)
{
PBYTE lpb;
// UINT nBypp = 1
// Move the pixel buffer pointer to the scanline that we
// want to access
lpb = (PBYTE)PIXELADDR_1(iPixel, iScanLine);
if(pwc->dither_flag)
*lpb = DITHER_RGB_2_8BIT(r,g,b,iScanLine,iPixel);
else
*lpb = BGR8(r,g,b);
}
void wmSetPixel_db2(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b)
{
unsigned short int *lpw;
// UINT nBypp = 2
// Move the pixel buffer pointer to the scanline that we
// want to access
lpw = (unsigned short int *)PIXELADDR_2(iPixel, iScanLine);
*lpw = BGR16(r,g,b);
}
void wmSetPixel_db3(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b)
{
// UINT *lpdw;
// UINT lpdw;
PBYTE lpb;
// UINT nBypp = 3
lpb = ( PBYTE)PIXELADDR_3(iPixel, iScanLine);
// lpdw = (UINT *)PIXELADDR_3(iPixel, iScanLine);
// lpdw = BGR24(r,g,b);
*lpb++ = b;
*lpb++ = g;
*lpb = r;
}
void wmSetPixel_db4(PWMC pwc, int iScanLine, int iPixel, BYTE r, BYTE g, BYTE b)
{
UINT *lpdw;
// UINT nBypp = 4
lpdw = (UINT *)PIXELADDR_4(iPixel, iScanLine);
*lpdw = BGR32(r,g,b);
}
int wmGetPixel(PWMC pwc, int x, int y)
{
int val;
if(Current->db_flag)
{
PBYTE lpb = pwc->pbPixels;
UINT *lpdw;
unsigned short int *lpw;
UINT nBypp = pwc->nColorBits / 8;
// UINT nOffset = x % nBypp;
// Move the pixel buffer pointer to the scanline that we
// want to access
// pwc->dib.fFlushed = FALSE;
// lpb += pwc->ScanWidth * y;
// Now move to the desired pixel
// lpb += x * nBypp;
lpb = (PBYTE)PIXELADDR(x, y);
if(nBypp == 1)
{
//?? if(pwc->dither_flag)
//?? *lpb = DITHER_RGB_2_8BIT(r,g,b,iScanLine,iPixel);
//?? else
val = (int) (*lpb);
} else if(nBypp == 2) {
lpw = (unsigned short int *)lpb;
val = (int) (*lpw);
} else if (nBypp == 3) {
lpdw = (UINT *)lpb;
val = ((int)(*lpdw)) & 0xffffff;
} else if (nBypp == 4) {
lpdw = (UINT *)lpb;
val = (int) (*lpdw);
}
} else {
POINTL ptl;
ptl.y = y;
ptl.x = x;
val = GpiQueryPel(pwc->hps, &ptl);
}
return val;
}
void wmCreateDIBSection( HDC hDC,
PWMC pwc, // handle of device context
CONST BITMAPINFO2 *pbmi // address of structure containing bitmap size, format, and color data
)
// ,UINT iUsage) // color data type indicator: RGB values or palette indices
{
int dwSize = 0,LbmpBuff;
int dwScanWidth;
UINT nBypp = pwc->nColorBits / 8;
HDC hic;
PSZ pszData[4] = { "Display", NULL, NULL, NULL };
SIZEL sizlPage = {0, 0};
LONG alData[2];
dwScanWidth = (((pwc->ScanWidth * nBypp)+ 3) & ~3);
pwc->ScanWidth =pwc->pitch = dwScanWidth;
// if (stereo_flag)
// pwc->ScanWidth = 2* pwc->pitch;
dwSize = sizeof(BITMAPINFO) + (dwScanWidth * pwc->height);
pwc->memb.bNx = (pwc->width/32+1)*32;
pwc->memb.bNy = (pwc->height/32+1)*32;
pwc->memb.BytesPerBmpPixel = nBypp;
LbmpBuff = pwc->memb.BytesPerBmpPixel * pwc->memb.bNx * pwc->memb.bNy+4;
if(pwc->memb.pBmpBuffer)
{ if(pwc->memb.LbmpBuff != LbmpBuff)
{ pwc->memb.pBmpBuffer = (BYTE *) realloc(pwc->memb.pBmpBuffer,LbmpBuff);
}
} else {
pwc->memb.pBmpBuffer = (BYTE *)malloc(LbmpBuff);
}
pwc->pbPixels = pwc->memb.pBmpBuffer;
pwc->memb.LbmpBuff = LbmpBuff;
pwc->memb.hdcMem = DevOpenDC(pwc->hab, OD_MEMORY, "*", 4, (PDEVOPENDATA) pszData, NULLHANDLE);
pwc->memb.hpsMem = GpiCreatePS(pwc->hab, pwc->memb.hdcMem, &sizlPage,
PU_PELS | GPIA_ASSOC | GPIT_MICRO);
}
BYTE DITHER_RGB_2_8BIT( int red, int green, int blue, int pixel, int scanline)
{
char unsigned redtemp, greentemp, bluetemp, paletteindex;
//*** now, look up each value in the halftone matrix
//*** using an 8x8 ordered dither.
redtemp = aDividedBy51[red]
+ (aModulo51[red] > aHalftone8x8[(pixel%8)*8
+ scanline%8]);
greentemp = aDividedBy51[(char unsigned)green]
+ (aModulo51[green] > aHalftone8x8[
(pixel%8)*8 + scanline%8]);
bluetemp = aDividedBy51[(char unsigned)blue]
+ (aModulo51[blue] > aHalftone8x8[
(pixel%8)*8 +scanline%8]);
//*** recombine the halftoned rgb values into a palette index
paletteindex =
redtemp + aTimes6[greentemp] + aTimes36[bluetemp];
//*** and translate through the wing halftone palette
//*** translation vector to give the correct value.
return aWinGHalftoneTranslation[paletteindex];
}
//
// Blit memory DC to screen DC
//
BOOL wmFlush(PWMC pwc)
{
BOOL bRet = 0;
int dwErr = 0;
POINTL aptl[4];
extern GLUTwindow * __glutCurrentWindow;
HBITMAP hbmpold;
LONG rc;
// Now search through the torus frames and mark used colors
if(pwc->db_flag)
{
// if(isChange)
{ if(pwc->hbm)
GpiDeleteBitmap(pwc->hbm);
pwc->hbm = GpiCreateBitmap(pwc->memb.hpsMem, &pwc->bmi, CBM_INIT,
(PBYTE)pwc->memb.pBmpBuffer, &(pwc->memb.bmi_mem));
if(pwc->hbm == 0)
{ printf("Error creating Bitmap\n");
}
hbmpold = GpiSetBitmap(pwc->memb.hpsMem,pwc->hbm);
}
// else
// { GpiSetBitmap(hpsMem,hbm);
// GpiSetBitmapBits(hpsMem, 0,bmp.cy,(PBYTE) pBmpBuffer, pbmi);
// }
aptl[0].x = 0; /* Lower-left corner of destination rectangle */
aptl[0].y = 0; /* Lower-left corner of destination rectangle */
aptl[1].x = pwc->bmi.cx; /* Upper-right corner of destination rectangle */
aptl[1].y = pwc->bmi.cy; /* Upper-right corner of destination rectangle */
/* Source-rectangle dimensions (in device coordinates) */
aptl[2].x = 0; /* Lower-left corner of source rectangle */
aptl[2].y = 0; /* Lower-left corner of source rectangle */
aptl[3].x = pwc->bmi.cx;
aptl[3].y = pwc->bmi.cy;
rc = GpiBitBlt(pwc->hps, pwc->memb.hpsMem, 3, /* 4 Number of points in aptl */
aptl, ROP_SRCCOPY, BBO_IGNORE/* | BBO_PAL_COLORS*/ );
if(rc = GPI_ERROR)
{ printf("Error GpiBitBlt\n");
}
//?? bRet = BitBlt(pwc->hDC, 0, 0, pwc->width, pwc->height,
//?? pwc->dib.hDC, 0, 0, SRCCOPY);
GpiSetBitmap(pwc->memb.hpsMem,hbmpold);
}
return(TRUE);
}
static struct VideoDevConfigCaps VideoDevConfig = { 0 };
/* Получить видеоконфигуpацию по полной пpогpамме */
LONG *GetVideoConfig(HDC hdc)
{
LONG lCount = CAPS_PHYS_COLORS;
LONG lStart = CAPS_FAMILY; /* 0 */
BOOL rc;
if( hdc || !VideoDevConfig.sts)
{ rc = DevQueryCaps( hdc, lStart, lCount, VideoDevConfig.Caps );
if(rc)
{ VideoDevConfig.sts = 1;
return VideoDevConfig.Caps;
}
} else {
return VideoDevConfig.Caps;
}
return NULL;
}
|
246863480579147823b8faa9ebf9abebf602561b | fb4db9b9e15295f6623589ada2761903d70e39db | /Sorting/nusu.cpp | 42c33f921b281961fbad1b76e848c8b365cca466 | [] | no_license | Muzahid037/Algorithms | 533aa4cd25f98febee2fe58a91c8b639120a5049 | fd2f0dbf1b4976fe586d1326025abae6ded2ec4c | refs/heads/master | 2022-03-03T04:24:11.936411 | 2022-02-05T10:21:35 | 2022-02-05T10:21:35 | 235,582,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | nusu.cpp | #include<iostream>
using namespace std;
int main()
{
int n,a[100],temp,s;
cin>>n;
for (int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
if(s%2==0)
{
s=(n/2);
}
else{
(s=n/2)+1;
}
cout<<a[s]<<endl;
return 0;
}
|
fe5eb9dba6a8588b5f6b172326fe374604ab806b | d24e1babfdbf99a9c7fda46f333a1962e7086e93 | /toms743_prb.cpp | bde29bb6413ae71309445b20c9935cdf9c371ed9 | [] | no_license | emsr/maths_burkhardt | 37b19f6bd56bef1037f08f64bd035f58b493ecc0 | 756b5408ebe80eac1a194cdceb21e521495410a1 | refs/heads/master | 2022-03-19T13:07:31.796449 | 2022-03-09T19:54:13 | 2022-03-09T19:54:13 | 109,426,897 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 29,944 | cpp | toms743_prb.cpp | # include <cstdlib>
# include <iostream>
# include <iomanip>
# include <cmath>
# include "toms743.hpp"
int main ( );
void test01 ( int nbits );
void test02 ( int nbits, double dx, int n );
void test03 ( int nbits, double xmin, double xmax, int n );
//****************************************************************************80
int main ( )
//****************************************************************************80
//
// Purpose:
//
// MAIN is the main program for TOMS743_PRB.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2014
//
// Author:
//
// Original FORTRAN77 version by Andrew Barry, S. J. Barry,
// Patricia Culligan-Hensley.
// This C++ version by John Burkardt.
//
// Reference:
//
// Andrew Barry, S. J. Barry, Patricia Culligan-Hensley,
// Algorithm 743: WAPR - A Fortran routine for calculating real
// values of the W-function,
// ACM Transactions on Mathematical Software,
// Volume 21, Number 2, June 1995, pages 172-181.
//
{
double dx;
int n;
int nbits;
double xmax;
double xmin;
timestamp ( );
std::cout << "\n";
std::cout << "TOMS743_PRB\n";
std::cout << " C++ version\n";
std::cout << " Test the TOMS743 library.\n";
nbits = nbits_compute ( );
std::cout << "\n";
std::cout << " Number of bits in mantissa - 1 = " << nbits << "\n";
test01 ( nbits );
dx = + 1.0E-09;
n = 10;
test02 ( nbits, dx, n );
xmin = 0.0;
xmax = 1.0E+20;
n = 20;
test03 ( nbits, xmin, xmax, n );
//
// Terminate.
//
std::cout << "\n";
std::cout << "TOMS743_PRB\n";
std::cout << " Normal end of execution.\n";
std::cout << "\n";
timestamp ( );
return 0;
}
//****************************************************************************80
void test01 ( int nbits )
//****************************************************************************80
//
// Purpose:
//
// TEST01 compares WAPR to stored values.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2014
//
// Author:
//
// Original FORTRAN77 version by Andrew Barry, S. J. Barry,
// Patricia Culligan-Hensley.
// This C version by John Burkardt.
//
// Parameters:
//
// Input, int NBITS, the number of bits in the mantissa.
//
{
static double dx1[68] = {
1.E-40,2.E-40,3.E-40,4.E-40,5.E-40,6.E-40,7.E-40,8.E-40,
9.E-40,1.E-39,1.E-30,2.E-30,3.E-30,4.E-30,5.E-30,6.E-30,
7.E-30,8.E-30,9.E-30,1.E-29,1.E-20,2.E-20,3.E-20,4.E-20,
5.E-20,6.E-20,7.E-20,8.E-20,9.E-20,1.E-19,1.E-10,2.E-10,
3.E-10,4.E-10,5.E-10,6.E-10,7.E-10,8.E-10,9.E-10,1.E-9,1.E-5,
2.E-5,3.E-5,4.E-5,5.E-5,6.E-5,7.E-5,8.E-5,9.E-5,1.E-4,2.E-4,
3.E-4,4.E-4,5.E-4,6.E-4,7.E-4,8.E-4,9.E-4,1.E-3,2.E-3,3.E-3,
4.E-3,5.E-3,6.E-3,7.E-3,8.E-3,9.E-3,1.E-2 };
double em;
int i;
int nd;
int nerror;
double w;
static double wm1[68] = {
-1.000000000000000000023316439815971242034,
-1.000000000000000000032974425414002562937,
-1.000000000000000000040385258412884114431,
-1.000000000000000000046632879631942484068,
-1.000000000000000000052137144421794383842,
-1.000000000000000000057113380167442850121,
-1.000000000000000000061689501212464534966,
-1.000000000000000000065948850828005125875,
-1.000000000000000000069949319447913726103,
-1.000000000000000000073733056744706376448,
-1.000000000000002331643981597126015551422,
-1.000000000000003297442541400259918073073,
-1.000000000000004038525841288416879599233,
-1.000000000000004663287963194255655478615,
-1.00000000000000521371444217944744506897,
-1.000000000000005711338016744295885146596,
-1.000000000000006168950121246466181805002,
-1.000000000000006594885082800527084897688,
-1.000000000000006994931944791388919781579,
-1.000000000000007373305674470655766501228,
-1.000000000233164398177834299194683872234,
-1.000000000329744254176269387087995047343,
-1.00000000040385258418320678088280150237,
-1.000000000466328796391912356113774800963,
-1.000000000521371444308553232716574598644,
-1.00000000057113380178315977436875260197,
-1.000000000616895012251498501679602643872,
-1.000000000659488508425026289634430354159,
-1.000000000699493194642234170768892572882,
-1.000000000737330567628282553087415117543,
-1.000023316621036696460620295453277856456,
-1.000032974787857057404928311684626421503,
-1.000040385802079313048521250390482335902,
-1.00004663360452259016530661221213359488,
-1.0000521380505373899860247162705706318,
-1.000057114467508637629346787348726350223,
-1.000061690769779852545970707346938004879,
-1.000065950300622136103491886720203687457,
-1.00006995095046930174807034225078340539,
-1.000073734868993836022551364404248563489,
-1.007391489031309264813153180819941418531,
-1.010463846806564696239430620915659099361,
-1.012825626038880105597738761474228363542,
-1.014819592594577564927398399257428492725,
-1.016578512742400177512255407989807698099,
-1.018170476517182636083407324035097024753,
-1.019635932177973215702948823070039007361,
-1.021001233780440980009663527189756124983,
-1.022284686760270309618528459224732558767,
-1.023499619082082348038906498637836105447,
-1.033342436522109918536891072083243897233,
-1.040939194524944844012076988438386306843,
-1.047373634492196231421755878017895964061,
-1.053065496629607111615572634090884988897,
-1.058230030703619902820337106917657189605,
-1.06299509412938704964298950857825124135,
-1.067443986111355120560366087010834293872,
-1.071634561663924136735470389832541413862,
-1.07560894118662498941494486924522316597,
-1.108081880631165502564629660944418191031,
-1.133487001006868638317076487349933855181,
-1.155245851821528613609784258821055266176,
-1.174682608817289477552149783867901714817,
-1.192475850408615960644596781702366026321,
-1.209028378276581220769059281765172085749,
-1.224602449817731587352403997390766826335,
-1.239380103200799714836392811991400433357,
-1.253493791367214516100457405907304877145};
static double wm2[68] = {
-96.67475603368003636615083422832414231073,
-95.97433737593292677679699834708774152264,
-95.56459382507349364043974513871359837914,
-95.27386489130628866261760496192716897551,
-95.0483515329550645558378163981346085731,
-94.86408948075132603599669916724611501067,
-94.70829516116125928735505687861553800851,
-94.57333777268864473984718625104978190798,
-94.45429521137271454134108055166168787618,
-94.34780665137385269060032461028588648619,
-73.37311031382297679706747875812087452918,
-72.67033891766978907253811160121558649554,
-72.25920015786413889986246462168541066725,
-71.9674726772681844325410195162521230103,
-71.74117979478106456261839111929684980709,
-71.55627755942675731851469544735603279342,
-71.39993966508440988906136771384270319452,
-71.26450969134836299738230265916604879247,
-71.14504894849287026061378869987876478469,
-71.03818524971357411174259539994036186653,
-49.96298427667447244531514297262540669957,
-49.25557728489066973476436802404294348267,
-48.84167348449764278180827692232244878061,
-48.54795966722336777861228992424053274064,
-48.32011181512544381639923088992262632623,
-48.13392971864323755677656581326964166718,
-47.97650308277095858785998266172487372203,
-47.84012504158555569017852884133421231303,
-47.71982419568730714141619502661365943996,
-47.61220592218922310708330388890925734186,
-26.29523881924692569411012882185491823773,
-25.57429135222126159950976461862116397347,
-25.15218334705420805339928870686463192335,
-24.85251554543232259250342343156454440592,
-24.61997095867949438248843689371454503831,
-24.42989922074834124324823589226341161866,
-24.26914663885402405126372567664280388966,
-24.12985944288624210229238972590881794092,
-24.00697058168597098928369714836882130512,
-23.8970195845316574350263109196222825525,
-14.16360081581018300910955630361089957762,
-13.41624453595298662833544556875899262976,
-12.97753279184081358418630625949303360266,
-12.66551396826200331850774017793451747947,
-12.42304039760186078066171146072124458063,
-12.22461776385387453853455424320739669321,
-12.05663003490708840623665404674007291018,
-11.91094134143842011964821167497982287763,
-11.78229922740701885487699061601349928173,
-11.66711453256635441837882744697047370583,
-10.90655739570090676132157335673785028979,
-10.45921112040100393534625826514848865968,
-10.14059243262036578763968437893562720385,
-9.892699522704254067620287857665824159861,
-9.689637966382397752838283301312347921626,
-9.517569762038614935107630230444563521109,
-9.368222172408836799233763466046500781388,
-9.236251966692597369166416348621131600216,
-9.11800647040274012125833718204681427427,
-8.335081377982507150789361715143483020265,
-7.872521380098708883395239767904984410792,
-7.541940416432904084217222998374802941589,
-7.283997135099081646930521042317118095276,
-7.072162048994701667487346245044653243434,
-6.892241486671583156187212318718730022068,
-6.735741661607793269808533725369490789074,
-6.597171733627119347342347717832724288261,
-6.472775124394004694741057892724488037104};
static double wp1[68] = {
-.9999999999999999999766835601840287579665,
-.9999999999999999999670255745859974370634,
-.9999999999999999999596147415871158855702,
-.9999999999999999999533671203680575159335,
-.9999999999999999999478628555782056161596,
-.9999999999999999999428866198325571498809,
-.9999999999999999999383104987875354650364,
-.9999999999999999999340511491719948741275,
-.9999999999999999999300506805520862739007,
-.9999999999999999999262669432552936235556,
-.9999999999999976683560184028776088243496,
-.9999999999999967025574585997473306784697,
-.9999999999999959614741587115939935280812,
-.9999999999999953367120368057588420244704,
-.9999999999999947862855578205706768098859,
-.9999999999999942886619832557258611080314,
-.9999999999999938310498787535591888253966,
-.999999999999993405114917199501910108482,
-.9999999999999930050680552086436996003626,
-.9999999999999926266943255293804772564852,
-.9999999997668356018584094585181033975713,
-.9999999996702557458962181283375794922681,
-.9999999995961474159255244922555603070484,
-.9999999995336712037530626747373742782638,
-.9999999994786285558726655558473617503914,
-.9999999994288661984343027719079710168757,
-.9999999993831049880022078023099082447845,
-.9999999993405114918649237720678678043098,
-.9999999993005068056839596486461928553989,
-.9999999992626694327341550240404575805522,
-.9999766837414008807143234266407434345965,
-.9999670259370180970391011806287847685011,
-.9999596152852334187587360603177913882165,
-.9999533678452277190993205651165793258207,
-.9999478637616504968301143759542621752943,
-.9999428877071168268324462680980110604599,
-.999938311767283189655618359697592754013,
-.999934052598878483932035240348113191731,
-.9999300523114688962155368933174163936848,
-.9999262687553819399632780281900349826094,
-.9926447551971221136721993073029112268763,
-.9896086425917686478635208903220735023288,
-.9872831094708759013315476674998231771112,
-.9853253899681719161468126266199947992874,
-.9836027178149637071691226667555243369797,
-.9820470029764667038452666345865058694192,
-.9806177971936827573257045283891513709368,
-.97928874641099293421931043027104578327,
-.9780415451927629881943028498821429186059,
-.9768628655744219140604871252425961901255,
-.967382626983074241885253344632666448927,
-.9601485420712594199373375259293860324633,
-.9540768694875733222057908617314370634111,
-.9487478690765183543410579996573536771348,
-.9439462911219380338176477772712853402016,
-.9395442782590063946376623684916441100361,
-.9354585313336439336066341889767099608018,
-.9316311953818583253420613278986500351794,
-.9280201500545670487600430252549212247489,
-.8991857663963733198571950343133631348347,
-.8774287170665477623395641312875506084256,
-.8593275036837387237312746018678000939451,
-.8435580020488052057849697812109882706542,
-.8294416857114015557682843481727604063558,
-.8165758053803078481644781849709953302847,
-.8046981564792468915744561969751509934994,
-.7936267540949175059651534957734689407879,
-.7832291989812967764330746819464532478021};
static double wp2[40] = {
9.999999990000000014999999973333333385417E-10,
1.9999999960000000119999999573333335E-9,
2.999999991000000040499999784000001265625E-9,
3.999999984000000095999999317333338666667E-9,
4.999999975000000187499998333333349609375E-9,
5.999999964000000323999996544000040499999E-9,
6.99999995100000051449999359733342086979E-9,
7.999999936000000767999989077333503999997E-9,
8.999999919000001093499982504000307546869E-9,
9.999999900000001499999973333333854166656E-9,
9.901473843595011885336326816570107953628E-3,
1.961158933740562729168248268298370977812E-2,
2.913845916787001265458568152535395243296E-2,
3.848966594197856933287598180923987047561E-2,
4.767230860012937472638890051416087074706E-2,
5.669304377414432493107872588796066666126E-2,
6.555812274442272075701853672870305774479E-2,
7.427342455278083997072135190143718509109E-2,
8.284448574644162210327285639805993759142E-2,
9.127652716086226429989572142317956865312E-2,
-1.000000001000000001500000002666666671875E-9,
-2.000000004000000012000000042666666833333E-9,
-3.000000009000000040500000216000001265625E-9,
-4.000000016000000096000000682666672E-9,
-5.000000025000000187500001666666682942709E-9,
-6.000000036000000324000003456000040500001E-9,
-7.000000049000000514500006402666754203126E-9,
-8.000000064000000768000010922666837333336E-9,
-9.000000081000001093500017496000307546881E-9,
-1.000000010000000150000002666666718750001E-8,
-1.010152719853875327292018767138623973671E-2,
-2.041244405580766725973605390749548004159E-2,
-3.094279498284817939791038065611524917276E-2,
-4.170340843648447389872733812553976786256E-2,
-5.270598355154634795995650617915721289428E-2,
-6.396318935617251019529498180168867456393E-2,
-7.548877886579220591933915955796681153525E-2,
-8.729772086157992404091975866027313992649E-2,
-9.940635280454481474353567186786621057821E-2,
-1.118325591589629648335694568202658422726E-1};
static double wp3[10] = {
1.745528002740699383074301264875389911535,
3.385630140290050184888244364529726867492,
5.249602852401596227126056319697306282521,
7.231846038093372706475618500141253883968,
9.284571428622108983205132234759581939317,
11.38335808614005262200015678158500428903,
13.5143440103060912090067238511621580283,
15.66899671545096218719628189389457073619,
17.84172596742146918254060066535711011039,
20.02868541330495078123430607181488729749};
static double x2[20] = {
1.E-9,2.E-9,3.E-9,4.E-9,5.E-9,6.E-9,7.E-9,8.E-9,9.E-9,1.E-8,
1.E-2,2.E-2,3.E-2,4.E-2,5.E-2,6.E-2,7.E-2,8.E-2,9.E-2,1.E-1};
static double x3[10] = {
1.E1,1.E2,1.E3,1.E4,1.E5,1.E6,1.E7,1.E8,1.E9,1.E10};
//
// Compare the approximations of WAPR with the given exact values.
//
std::cout << "\n";
std::cout << "TEST01\n";
std::cout << " Compare WAPR(X) to stored values.\n";
//
// Wp results for x near -exp(-1).
//
std::cout << "\n";
std::cout << " Wp results for x near -exp(-1)\n";
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (EXACT) Digits Correct\n";
std::cout << "\n";
for ( i = 0; i < 68; i++ )
{
if ( dx1[i] == 0.0 )
{
em = - exp ( -1.0 );
w = wapr ( em, 0, nerror, 0 );
}
else
{
w = wapr ( dx1[i], 0, nerror, 1 );
}
if ( w == wp1[i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wp1[i] / ( w - wp1[i] ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << dx1[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wp1[i] << " "
<< std::setw(3) << nd << "\n";
}
//
// Wp results for x near 0.
//
std::cout << "\n";
std::cout << " Wp results for x near 0\n";
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (EXACT) Digits Correct\n";
std::cout << "\n";
for ( i = 0; i < 20; i++ )
{
w = wapr ( x2[i], 0, nerror, 0 );
if ( w == wp2[i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wp2[i] / ( w - wp2[i] ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x2[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wp2[i] << " "
<< std::setw(3) << nd << "\n";
}
for ( i = 0; i < 20; i++ )
{
w = wapr ( -x2[i], 0, nerror, 0 );
if ( w == wp2[20+i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wp2[20+i] / ( w - wp2[20+i] ) ) ) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << -x2[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wp2[20+i] << " "
<< std::setw(3) << nd << "\n";
}
//
// Other Wp results.
//
std::cout << "\n";
std::cout << " Other Wp results\n";
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (EXACT) Digits Correct\n";
std::cout << "\n";
for ( i = 0; i < 10; i++ )
{
w = wapr ( x3[i], 0, nerror, 0 );
if ( w == wp3[i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wp3[i] / ( w - wp3[i] ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x3[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wp3[i] << " "
<< std::setw(3) << nd << "\n";
}
//
// Wm results for x near -exp(-1).
//
std::cout << "\n";
std::cout << " Wm results for x near 0\n";
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (EXACT) Digits Correct\n";
std::cout << "\n";
for ( i = 0; i < 68; i++ )
{
w = wapr ( dx1[i], 1, nerror, 1 );
if ( w == wm1[i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wm1[i] / ( w - wm1[i] ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << dx1[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wm1[i] << " "
<< std::setw(3) << nd << "\n";
}
//
// Wm results for x near 0.
// Check for underflow.
//
std::cout << "\n";
std::cout << " Wm results for x near -exp(-1)\n";
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (EXACT) Digits Correct\n";
std::cout << "\n";
for ( i = 0; i < 68; i++ )
{
if ( 0.0 < dx1[i] )
{
w = wapr ( -dx1[i], 1, nerror, 0 );
if ( w == wm2[i] )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( wm2[i] / ( w - wm2[i] ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << -dx1[i]
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << wm2[i] << " "
<< std::setw(3) << nd << "\n";
}
}
return;
}
//****************************************************************************80
void test02 ( int nbits, double dx, int n )
//****************************************************************************80
//
// Purpose:
//
// TEST02 tests WAPR(X) when X is the offset of the argument from -exp(-1).
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2014
//
// Author:
//
// Original FORTRAN77 version by Andrew Barry, S. J. Barry,
// Patricia Culligan-Hensley.
// This C++ version by John Burkardt.
//
// Parameters:
//
// Input, int NBITS, the number of bits in the mantissa.
//
// Input, double DX, the initial offset.
//
// Input, int N, the number of offset arguments to generate.
//
{
int i;
int ifmt;
int iw;
int l;
int nd;
int ner;
int nerror;
double w;
double we;
double x;
double xmax;
double xmin;
std::cout << "\n";
std::cout << "TEST02\n";
std::cout << " Input X is the offset from -exp(-1).\n";
l = 1;
ifmt = 0;
xmax = n * dx - exp ( -1.0 );
xmin = 0.0;
if ( xmax <= 0.0 )
{
iw = 1;
std::cout << " Both branches of the W function will be checked.\n";
}
else
{
iw = 0;
std::cout << " Wp has been selected (maximum x is > 0)\n";
}
std::cout << "\n";
std::cout << " Results for Wp(x):\n";
if ( ifmt == 0 )
{
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
else
{
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
std::cout << "\n";
for ( i = 1; i <= n + 1; i++ )
{
x = xmin + i * dx;
w = wapr ( x, 0, nerror, l );
if ( nerror == 1 )
{
std::cout << " The value of X = " << x << " is out of range.\n";
}
else
{
we = bisect ( x, 0, ner, l );
if ( ner == 1 )
{
std::cout << "\n";
std::cout << " BISECT did not converge for x = " << x << "\n";
std::cout << " Try reducing NBITS.\n";
}
if ( w == we )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( we / ( w - we ) ) ) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << we << " "
<< std::setw(3) << nd << "\n";
}
}
if ( iw == 1 )
{
std::cout << "\n";
std::cout << " Results for Wm(x):\n";
if ( ifmt == 0 )
{
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
else
{
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
std::cout << "\n";
for ( i = 1; i <= n + 1; i++ )
{
x = xmin + i * dx;
w = wapr ( x, 1, nerror, l );
if ( nerror == 1 )
{
std::cout << " The value of X = " << x << " is out of range.\n";
}
else
{
we = bisect ( x, 1, ner, l );
if ( ner == 1 )
{
std::cout << "\n";
std::cout << " BISECT did not converge for x = " << x << "\n";
std::cout << " Try reducing NBITS.\n";
}
if ( w == we )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( we / ( w - we ) ) ) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << we << " "
<< std::setw(3) << nd << "\n";
}
}
}
return;
}
//****************************************************************************80
void test03 ( int nbits, double xmin, double xmax, int n )
//****************************************************************************80
//
// Purpose:
//
// TEST03 tests WAPR(X) when X is the argument.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 17 June 2014
//
// Author:
//
// Original FORTRAN77 version by Andrew Barry, S. J. Barry,
// Patricia Culligan-Hensley.
// This C++ version by John Burkardt.
//
// Parameters:
//
// Input, int NBITS, the number of bits in the mantissa.
//
// Input, double XMIN, XMAX, the range.
//
// Input, int N, the number of equally spaced values
// in the range at which arguments are to be chosen.
//
{
double dx;
int i;
int ifmt;
int iw;
int l;
int nd;
int ner;
int nerror;
double temp;
double w;
double we;
double x;
std::cout << "\n";
std::cout << "TEST03\n";
std::cout << " Input X is the argument.\n";
l = 0;
ifmt = 1;
if ( xmax < xmin )
{
temp = xmin;
xmin = xmax;
xmax = temp;
}
dx = ( xmax - xmin ) / double( n );
xmin = xmin - dx;
if ( xmax <= 0.0 )
{
iw = 1;
std::cout << " Both branches of the W function will be checked.\n";
}
else
{
iw = 0;
std::cout << " Wp has been selected (maximum x is > 0)\n";
}
std::cout << "\n";
std::cout << " Results for Wp(x):\n";
if ( ifmt == 0 )
{
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
else
{
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
std::cout << "\n";
for ( i = 1; i <= n + 1; i++ )
{
x = xmin + i * dx;
w = wapr ( x, 0, nerror, l );
if ( nerror == 1 )
{
std::cout << " The value of X = " << x << " is out of range.\n";
}
else
{
we = bisect ( x, 0, ner, l );
if ( ner == 1 )
{
std::cout << "\n";
std::cout << " BISECT did not converge for x = " << x << "\n";
std::cout << " Try reducing NBITS.\n";
}
if ( w == we )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( we / ( w - we ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << we << " "
<< std::setw(3) << nd << "\n";
}
}
if ( iw == 1 )
{
std::cout << "\n";
std::cout << " Results for Wm(x):\n";
if ( ifmt == 0 )
{
std::cout << "\n";
std::cout << " Offset x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
else
{
std::cout << "\n";
std::cout << " x W(x) (WAPR)";
std::cout << " W(x) (BISECT) Digits Correct\n";
}
for ( i = 1; i <= n + 1; i++ )
{
x = xmin + i * dx;
w = wapr ( x, 1, nerror, l );
if ( nerror == 1 )
{
std::cout << " The value of X = " << x << " is out of range.\n";
}
else
{
we = bisect ( x, 1, ner, l );
if ( ner == 1 )
{
std::cout << "\n";
std::cout << " BISECT did not converge for x = " << x << "\n";
std::cout << " Try reducing NBITS.\n";
}
if ( w == we )
{
nd = ( int ) ( log10 ( pow ( 2.0, nbits ) ) + 0.5 );
}
else
{
nd = ( int ) ( log10 ( fabs ( we / ( w - we ))) + 0.5 );
}
std::cout << std::setprecision(8) << std::setw(17) << x
<< std::setprecision(8) << std::setw(17) << w
<< std::setprecision(8) << std::setw(17) << we << " "
<< std::setw(3) << nd << "\n";
}
}
}
return;
}
|
1c66cd164ee0e0c425e572d63bf507a2ec21d828 | 5a1b14f7281471bc8e858b7378461c6f5f405b44 | /Genetic Algorithm/src/data_utility.cpp | f91a4341029a1d17e18f592ddad02a1efa3ecbda | [] | no_license | Rafid013/Data-Mining-Project | 59909787db674330ea757bec4b5532b9df7e2463 | 1a5bad409211d742b69bd3baed24294020e46a18 | refs/heads/main | 2023-05-09T00:29:25.831827 | 2021-06-01T14:27:16 | 2021-06-01T14:27:16 | 372,586,354 | 0 | 0 | null | 2021-06-01T13:39:49 | 2021-05-31T17:43:58 | C++ | UTF-8 | C++ | false | false | 27,979 | cpp | data_utility.cpp |
/*
* Author: Cheng Long
* Email: clong@cse.ust.hk
*/
#include "data_utility.h"
#include "irtree.h"
#include <unordered_map>
#ifndef WIN32
/*
* GetCurTime is used to get the current running time in the current process.
*
* @Param curTime gets back the time information.
*
* @Return void.
*/
void GetCurTime(rusage* curTime)
{
int ret = getrusage(RUSAGE_SELF, curTime);
if (ret != 0) {
fprintf(stderr, "The running time info couldn't be collected successfully.\n");
//FreeData( 2);
exit(0);
}
}
/*
* GetTime is used to get the 'float' format time from the start and end rusage structure.
*
* @Param timeStart, timeEnd indicate the two time points.
* @Param userTime, sysTime get back the time information.
*
* @Return void.
*/
void GetTime(struct rusage* timeStart, struct rusage* timeEnd, float* userTime, float* sysTime)
{
(*userTime) = ((float)(timeEnd->ru_utime.tv_sec - timeStart->ru_utime.tv_sec)) + ((float)(timeEnd->ru_utime.tv_usec - timeStart->ru_utime.tv_usec)) * 1e-6;
(*sysTime) = ((float)(timeEnd->ru_stime.tv_sec - timeStart->ru_stime.tv_sec)) + ((float)(timeEnd->ru_stime.tv_usec - timeStart->ru_stime.tv_usec)) * 1e-6;
}
#endif
/*
* IRTree_read_config reads the configuration info fro constructing the IRTree.
*/
IRTree_config_t* read_config_irtree()
{
//char des[MAX_DESCRIPTION_LENG];
FILE* c_fp;
IRTree_config_t* cfg = (IRTree_config_t*)malloc(sizeof(IRTree_config_t));
if ((c_fp = fopen(CONFIG_FILE, "r")) == NULL) {
fprintf(stderr, "The config file cannot be opened.\n");
exit(0);
}
//reads the configuration info.
fscanf(c_fp, "%s%s%s", cfg->loc_file, cfg->doc_file, cfg->tree_file);
fscanf(c_fp, "%i%i%i", &cfg->obj_n, &cfg->key_n, &cfg->dim); //data related.
//fscanf( c_fp, "%i%i%i", &(cfg->M), &(cfg->m), &( cfg->split_opt));//R-tree related.
fscanf(c_fp, "%i", &(cfg->split_opt)); //R-tree related.
//fscanf( c_fp, "%i", &cfg->key_n); //IF related.
fclose(c_fp);
return cfg;
}
/*
* Read the configuration for the Co-location mining problem.
* return an colocation_config_t pointer pointing to an object that storing the config
*/
colocation_config_t* read_config_colocation()
{
colocation_config_t* cfg;
FILE* c_fp;
cfg = (colocation_config_t*)malloc(sizeof(colocation_config_t));
memset(cfg, 0, sizeof(colocation_config_t));
if ((c_fp = fopen(COLOCATION_CONFIG_FILE, "r")) == NULL) {
fprintf(stderr, "The colocation_config file cannot be opened.\n");
exit(0);
}
//algorithm option.
fscanf(c_fp, "%i", &cfg->alg_opt);
//data.
fscanf(c_fp, "%i%i%s", &cfg->cost, &cfg->obj_n, cfg->loc_file);
fscanf(c_fp, "%i%s", &cfg->key_n, cfg->doc_file);
fscanf(c_fp, "%i%s", &cfg->tree_tag, cfg->tree_file);
fscanf(c_fp, "%i", &cfg->query_n);
//colocation pattern mining.
fscanf(c_fp, "%f", &cfg->min_sup);
//fscanf(c_fp, "%f", &cfg->min_conf);
fscanf(c_fp, "%f", &cfg->dist_thr);
fclose(c_fp);
return cfg;
}
/*
* Add a key to the keyword list. //!!k_node_v is the pointer pointing the last element of the list!!
*/
void add_keyword_entry(k_node_t*& k_node_v, KEY_TYPE key)
{
k_node_v->next = (k_node_t*)malloc(sizeof(k_node_t));
memset(k_node_v->next, 0, sizeof(k_node_t));
k_node_v->next->key = key;
k_node_v = k_node_v->next;
/*s*/
stat_v.memory_v += sizeof(k_node_t);
if (stat_v.memory_v > stat_v.memory_max)
stat_v.memory_max = stat_v.memory_v;
/*s*/
}
/*
* Copy the k_list info of @k_head2 to @k_head1.
*/
void copy_k_list(k_node_t* k_head1, k_node_t* k_head2)
{
k_node_t *k_node_iter1, *k_node_iter2;
k_node_iter1 = k_head1;
k_node_iter2 = k_head2->next;
while (k_node_iter2 != NULL) {
add_keyword_entry(k_node_iter1, k_node_iter2->key);
k_node_iter2 = k_node_iter2->next;
}
}
/*
* Print the a list of keywords @k_head in @o_fp.
*/
void print_k_list(k_node_t* k_head, FILE* o_fp)
{
k_node_t* k_node_iter;
k_node_iter = k_head->next;
while (k_node_iter != NULL) {
fprintf(o_fp, "%.0lf ", k_node_iter->key);
k_node_iter = k_node_iter->next;
}
fprintf(o_fp, "\n");
}
/****
* Print the location @k_head in @o_fp.
****/
void print_loc(loc_t* loc_v, FILE* o_fp)
{
int i;
for (i = 0; i < loc_v->dim; i++) {
fprintf(o_fp, "%0.4lf ", loc_v->coord[i]);
}
fprintf(o_fp, "\n");
}
/*
* Print the statistics maintained in stat_v.
*/
void print_colocation_stat(colocation_config_t* cfg, int cnt)
{
FILE* s_fp;
if (!(s_fp = fopen(COLOCATION_STAT_FILE, "w"))) {
fprintf(stderr, "Cannot open the coskq_stat file.\n");
exit(0);
}
// //average cost.
// fprintf( s_fp, "%lf\n", stat_v.aver_cost);
// //average size.
// fprintf( s_fp, "%lf\n\n", stat_v.aver_size);
//time.
fprintf(s_fp, "%f\n%f\n\n", stat_v.irtree_build_time, stat_v.q_time);
//memory.
fprintf(s_fp, "%f\n", stat_v.memory_max / (1024 * 1024));
//IR-tree memory.
fprintf(s_fp, "%f\n\n", stat_v.tree_memory_max / (1024 * 1024));
//Method 4 related
fprintf(s_fp, "%lf\n%lf\n%lf\n%lf\n\n", stat_v.S3_sum, stat_v.S1_sum, stat_v.S2_sum, stat_v.S5_sum);
fprintf(s_fp, "%lf\n%lf\n%lf\n%lf\n",stat_v.S3_time, stat_v.S1_time, stat_v.S2_time, stat_v.S5_time);
fclose(s_fp);
}
/*
* Allocate the memory for an object.
*/
void alloc_obj(obj_t* obj_v, int dim)
{
//obj_v = ( obj_t*)malloc( sizeof( obj_t));
//memset( obj_v, 0, sizeof( obj_t));
obj_v->MBR = (range*)malloc(dim * sizeof(range));
memset(obj_v->MBR, 0, dim * sizeof(range));
// obj_v->N_o_f = new std::unordered_map<FEA_TYPE, int>();
//
// obj_v->N_o_f2 = new std::unordered_map<FEA_TYPE, int>();
//
// obj_v->frac_f = new std::unordered_map<FEA_TYPE, float>();
//
}
/*
* Read the data based on the IRTree_config_t info.
*/
data_t* read_data_irtree(IRTree_config_t* cfg)
{
int i, j;
KEY_TYPE key;
char des;
char keys[TEXT_COL_MAX];
char* tok;
k_node_t* k_node_v;
FILE* i_fp;
data_t* data_v = (data_t*)malloc(sizeof(data_t));
memset(data_v, 0, sizeof(data_t));
data_v->dim = cfg->dim;
data_v->obj_n = cfg->obj_n;
data_v->key_n = cfg->key_n;
data_v->obj_v = (obj_t*)malloc(sizeof(obj_t) * data_v->obj_n);
memset(data_v->obj_v, 0, sizeof(obj_t) * data_v->obj_n);
//data_v->key_freq_v = bst_ini( );
//Read the loc info.
if ((i_fp = fopen(cfg->loc_file, "r")) == NULL) {
fprintf(stderr, "Cannot open the loc file.\n");
exit(0);
}
for (i = 0; i < data_v->obj_n; i++) {
alloc_obj(data_v->obj_v + i, data_v->dim);
fscanf(i_fp, "%i", &(data_v->obj_v[i].id));
for (j = 0; j < data_v->dim; j++) {
fscanf(i_fp, "%c%f", &des, &(data_v->obj_v[i].MBR[j].min));
data_v->obj_v[i].MBR[j].max = data_v->obj_v[i].MBR[j].min;
}
}
fclose(i_fp);
//Read the keywords info.
if ((i_fp = fopen(cfg->doc_file, "r")) == NULL) {
fprintf(stderr, "Cannot open the doc file.\n");
exit(0);
}
for (i = 0; i < data_v->obj_n; i++) {
// k_node_v = ( k_node_t*)malloc( sizeof( k_node_t));
// memset( k_node_v, 0, sizeof( k_node_t));
// data_v->obj_v[ i].k_head = k_node_v;
fgets(keys, TEXT_COL_MAX, i_fp);
tok = strtok(keys, " ,");
while ((tok = strtok(NULL, " ,"))) {
key = atoi(tok);
data_v->obj_v[i].fea = key;
// add_keyword_entry( k_node_v, key);
/*
//Update the frequency info of the keyword.
bst_node_v = bst_search( data_v->key_freq_v, key);
if( bst_node_v == NULL)
{
bst_node_v = ( bst_node_t*)malloc( sizeof( bst_node_t));
memset( bst_node_v, 0, sizeof( bst_node_t));
bst_node_v->key = key;
bst_node_v->freq = 1.0 / data_v->obj_n;
bst_insert( data_v->key_freq_v, bst_node_v);
}
else
bst_node_v->freq += 1.0 / data_v->obj_n;
*/
}
}
fclose(i_fp);
return data_v;
}
/*
*
*/
data_t* alloc_data(int num)
{
data_t* data_v;
data_v = (data_t*)malloc(sizeof(data_t));
memset(data_v, 0, sizeof(data_t));
data_v->obj_n = num;
data_v->obj_v = (obj_t*)malloc(sizeof(obj_t) * data_v->obj_n);
memset(data_v->obj_v, 0, sizeof(obj_t) * data_v->obj_n);
return data_v;
}
/*
* Read the data based on the colocation_config_t info.
*/
data_t* read_data_colocation(colocation_config_t* cfg)
{
int i, j;
KEY_TYPE key;
char des;
char keys[TEXT_COL_MAX];
char* tok;
data_t* data_v;
FILE* i_fp;
data_v = alloc_data(cfg->obj_n);
// performed inside alloc_data function: data_v->obj_n = cfg->obj_n;
data_v->dim = cfg->dim;
data_v->key_n = cfg->key_n;
//data_v->key_freq_v = bst_ini( );
///--------------------------------------------------
//Read the loc info.
/// from the loc file
if ((i_fp = fopen(cfg->loc_file, "r")) == NULL) {
fprintf(stderr, "Cannot open the loc file.\n");
exit(0);
}
for (i = 0; i < data_v->obj_n; i++) {
alloc_obj(data_v->obj_v + i, data_v->dim);
fscanf(i_fp, "%i ", &(data_v->obj_v[i].id));
for (j = 0; j < data_v->dim; j++) {
fscanf(i_fp, "%c%f", &des, &(data_v->obj_v[i].MBR[j].min));
data_v->obj_v[i].MBR[j].max = data_v->obj_v[i].MBR[j].min;
}
}
fclose(i_fp);
///--------------------------------------------------
//Read the keywords info.
///from the doc file
if ((i_fp = fopen(cfg->doc_file, "r")) == NULL) {
fprintf(stderr, "Cannot open the doc file.\n");
exit(0);
}
for (i = 0; i < data_v->obj_n; i++) {
fgets(keys, TEXT_COL_MAX, i_fp);
tok = strtok(keys, " ,");
while ((tok = strtok(NULL, " ,"))) {
key = atoi(tok);
data_v->obj_v[i].fea = key;
}
}
fclose(i_fp);
return data_v;
}
/*
* Release a list.
*/
void release_k_list(k_node_t* k_node_v)
{
k_node_t* k_node_v1;
while (k_node_v->next != NULL) {
k_node_v1 = k_node_v;
k_node_v = k_node_v->next;
free(k_node_v1);
}
free(k_node_v);
}
/*
* IRTree_free_data release the data read by 'IRTree_read_data'.
*/
void release_data(data_t* data_v)
{
int i;
for (i = 0; i < data_v->obj_n; i++) {
free(data_v->obj_v[i].MBR);
}
free(data_v->obj_v);
free(data_v);
}
/*
* Generates a number between [min, max] randomly.
*/
int rand_i(int min, int max)
{
int i_rand;
float ratio;
if (min > max)
return 0;
if (max - min > RAND_MAX) {
//printf( "rand_i: [%i, %i] out of range.\n", min, max);
//exit( 0);
ratio = rand_f(0, 1);
i_rand = min + (int)(ratio * (max - min));
return i_rand;
}
//srand( time( NULL));
if (min == max)
i_rand = 0;
else
i_rand = rand() % (max - min + 1);
return i_rand + min;
}
/*
* Generate a random float value in [min_v, max_v].
*/
float rand_f(float min_v, float max_v)
{
float rand_v;
if (min_v > max_v)
return 0;
//srand( time(NULL));
rand_v = float(rand()) / RAND_MAX; //rand_v falls in [0,1] randomly.
return (max_v - min_v) * rand_v + min_v;
}
/*
* Generate a float value that satisfy the normal/gaussian distribution N[mean, s_var^2].
*
* Polar form method, modified from the Internet.
*/
float gaussian_f(float mean, float s_var)
{
float x1, x2, w, y1, y2;
do {
x1 = 2 * rand_f(0, 1) - 1;
x2 = 2 * rand_f(0, 1) - 1;
w = x1 * x1 + x2 * x2;
} while (w >= 1);
w = float(sqrt(float(-2.0 * log(w)) / w));
y1 = x1 * w; //y1 follows N[0, 1^2].
y2 = y1 * s_var + mean; //y2 follows N[mean, s_var^2].
return y2;
}
/*
* Check whether an variable has been generated before.
*
*/
bool is_old(int* rand_v, int cur, int var)
{
int i;
for (i = 0; i < cur; i++) {
if (rand_v[i] == var)
return true;
}
return false;
}
/*
*
*/
range* collect_data_range(data_t* data_v)
{
int i, j;
range* MBR;
MBR = (range*)malloc(data_v->dim * sizeof(range));
memset(MBR, 0, data_v->dim * sizeof(range));
for (i = 0; i < data_v->dim; i++) {
MBR[i].min = FLT_MAX;
MBR[i].max = -FLT_MAX;
for (j = 0; j < data_v->obj_n; j++) {
if (data_v->obj_v[j].MBR[i].min < MBR[i].min)
MBR[i].min = data_v->obj_v[j].MBR[i].min;
if (data_v->obj_v[j].MBR[i].max > MBR[i].max)
MBR[i].max = data_v->obj_v[j].MBR[i].max;
}
}
return MBR;
}
/*
*
*/
void print_data(data_t* data_v, syn_config_t* s_cfg)
{
int i, j;
FILE *loc_fp, *doc_fp;
if ((loc_fp = fopen(s_cfg->loc_file, "w")) == NULL || (doc_fp = fopen(s_cfg->doc_file, "w")) == NULL) {
printf("Cannot open loc/doc files.\n");
exit(0);
}
//Print the loc info.
for (i = 0; i < data_v->obj_n; i++) {
fprintf(loc_fp, "%i", data_v->obj_v[i].id);
for (j = 0; j < data_v->dim; j++)
fprintf(loc_fp, ",%f", data_v->obj_v[i].MBR[j].min);
fprintf(loc_fp, "\n");
}
//Print the doc info.
for (i = 0; i < data_v->obj_n; i++) {
fprintf(doc_fp, "%i", data_v->obj_v[i].id);
fprintf(doc_fp, "%i", (int)data_v->obj_v[i].fea);
fprintf(doc_fp, "\n");
}
fclose(loc_fp);
fclose(doc_fp);
}
//Following the paper "Discovering Spatial Co-location Patterns" in SSTD01
void gen_syn_data(syn_config_t* s_cfg)
{
//parameters
int Ncoloc = s_cfg->Ncoloc; //number of colocation
int lambda1 = s_cfg->lambda1; //size of each colocation pattern
int lambda2 = s_cfg->lambda2; //size of each table instance of a colocation pattern
int seed1 = s_cfg->seed1; //random seed for lambda1
int seed2 = s_cfg->seed2; //random seed for lambda2
double D1 = s_cfg->D1, D2 = s_cfg->D2;
double d = s_cfg->d;
double r_noise_fea = s_cfg->r_noise_fea; //number of *additional* features for noise / number of original features
double r_global = s_cfg->r_global; //number of *additional* instances from noise features
double r_local = s_cfg->r_local; //number of *additional* instances from original features
// printf("D1:%f\tD2:%f\n",D1,D2);
//----------------
int objectID = 1; //starting objectID
int feaID = 1; //starting feature ID
int num_instance = 0; //number of instances
FILE *loc_fp, *doc_fp;
if ((loc_fp = fopen(s_cfg->loc_file, "w")) == NULL || (doc_fp = fopen(s_cfg->doc_file, "w")) == NULL) {
printf("Cannot open loc/doc files.\n");
exit(0);
}
std::default_random_engine generator1, generator2;
std::poisson_distribution<int> distribution1(lambda1), distribution2(lambda2);
generator1.seed(seed1); //[1,infty)
generator2.seed(seed2); //[1,infty)
int* patternSize = new int[Ncoloc];
//generate N patterns size
for (int i = 0; i < Ncoloc; i++) {
patternSize[i] = distribution1(generator1);
int tableSize = distribution2(generator2);
// printf("tableSize:%d\tpatternSize:%d\n",tableSize, patternSize[i]);
num_instance += tableSize * patternSize[i];
//create objects for each row instance in the table
for (int j = 0; j < tableSize; j++) {
double rectX = rand_f(0, D1 - d); //bottom left
double rectY = rand_f(0, D2 - d);
//each object correspond to one feature
for (int k = 0; k < patternSize[i]; k++) {
int fea = feaID + k;
double locX = rectX + rand_f(0, d);
double locY = rectY + rand_f(0, d);
// printf("%d\t%d\t%0.3lf\t%0.3lf\n",objectID,fea,locX, locY);
fprintf(loc_fp, "%d,%f,%f\n", objectID, locX, locY);
fprintf(doc_fp, "%d,%d\n", objectID, fea);
objectID++;
}
// printf("\n");
}
feaID += patternSize[i];
// printf("===============\n");
}
// printf("objID:%d\tnum_instance:%d\tfeaID:%d\n", objectID, num_instance, feaID);
// printf("------------ local noise -----------\n");
//generate local noise
for (int i = 0; i < r_local * num_instance; i++) {
//pick from existing features
int fea = rand_i(1, feaID);
double locX = rand_f(0, D1);
double locY = rand_f(0, D2);
// printf("%d\t%d\t%0.3lf\t%0.3lf\n",objectID,fea,locX, locY);
fprintf(loc_fp, "%d,%f,%f\n", objectID, locX, locY);
fprintf(doc_fp, "%d,%d\n", objectID, fea);
objectID++;
}
// printf("------------ global noise -----------\n");
int originalFeaID = feaID;
feaID = int(double(feaID) * (1.0 + r_noise_fea));
//generate global noise
for (int i = 0; i < r_global * num_instance; i++) {
//pick from new features
int fea = rand_i(originalFeaID, feaID);
double locX = rand_f(0, D1);
double locY = rand_f(0, D2);
// printf("%d\t%d\t%0.3lf\t%0.3lf\n",objectID,fea,locX, locY);
fprintf(loc_fp, "%d,%f,%f\n", objectID, locX, locY);
fprintf(doc_fp, "%d,%d\n", objectID, fea);
objectID++;
}
printf("total number of obj:%d\ntotal number of feature:%d\n", --objectID, feaID);
printf("*fea[%d,%d] are original, [%d,%d] are noise\n", 1, originalFeaID, originalFeaID + 1, feaID);
fclose(loc_fp);
fclose(doc_fp);
}
/*
*
*/
void batch_gen_syn_data()
{
int ins_n;
syn_config_t s_cfg;
FILE* c_fp;
if ((c_fp = fopen(SYN_CONFIG_FILE, "r")) == NULL) {
printf("Cannot open the syn_config file.\n");
exit(0);
}
ins_n = 1;
while (fscanf(c_fp, "%s%s", s_cfg.loc_file, s_cfg.doc_file) != EOF) {
printf("#Instance %i ...\n", ins_n++);
//read the config.
fscanf(c_fp, "%i%i%i", &s_cfg.Ncoloc, &s_cfg.lambda1, &s_cfg.lambda2);
fscanf(c_fp, "%i%i", &s_cfg.seed1, &s_cfg.seed2);
fscanf(c_fp, "%lf%lf%lf", &s_cfg.D1, &s_cfg.D2, &s_cfg.d);
fscanf(c_fp, "%lf%lf%lf", &s_cfg.r_noise_fea, &s_cfg.r_global, &s_cfg.r_local);
fscanf(c_fp, "%lf%lf", &s_cfg.m_overlap, &s_cfg.m_clump);
//generate the synthetic data.
gen_syn_data(&s_cfg);
}
}
//----------------------------------
/*
* generate synethetic datasets in batch, each row in syn_config.txt correposnd to a dataset
*/
void batch_gen_syn_data2()
{
int ins_n;
syn_config_t s_cfg;
FILE* c_fp;
if ((c_fp = fopen(SYN_CONFIG_FILE, "r")) == NULL) {
printf("Cannot open the syn_config file.\n");
exit(0);
}
ins_n = 1;
while (fscanf(c_fp, "%s%s", s_cfg.loc_file, s_cfg.doc_file) != EOF) {
printf("#Instance %i ...\n", ins_n++);
//read the config.
fscanf(c_fp, "%i%i%i", &s_cfg.Ncoloc, &s_cfg.lambda1, &s_cfg.lambda2);
fscanf(c_fp, "%i%i", &s_cfg.seed1, &s_cfg.seed2);
fscanf(c_fp, "%lf%lf%lf", &s_cfg.D1, &s_cfg.D2, &s_cfg.d);
fscanf(c_fp, "%lf%lf%lf", &s_cfg.r_noise_fea, &s_cfg.r_global, &s_cfg.r_local);
fscanf(c_fp, "%lf%lf%i", &s_cfg.m_overlap, &s_cfg.m_clump, &s_cfg.m_clump_type);
//generate the synthetic data.
gen_syn_data2(&s_cfg);
}
}
//Following the paper "Discovering colocation patterns from spatial data sets: A general approach" in TKDE04
void gen_syn_data2(syn_config_t* s_cfg)
{
//parameters
int Ncoloc = s_cfg->Ncoloc; //number of colocation
int lambda1 = s_cfg->lambda1; //size of each colocation pattern
int lambda2 = s_cfg->lambda2; //size of each table instance of a colocation pattern
int seed1 = s_cfg->seed1; //random seed for lambda1
int seed2 = s_cfg->seed2; //random seed for lambda2
double D1 = s_cfg->D1; //D2 should always same as D1 and thus D2 is not used
double d = s_cfg->d;
double r_noise_fea = s_cfg->r_noise_fea; //number of *additional* features for noise / number of original features
double r_local = s_cfg->r_local;
double r_global = s_cfg->r_global; //number of *additional* instances from noise features
double m_overlap = s_cfg->m_overlap;
double m_clump = s_cfg->m_clump;
int m_clump_type = s_cfg->m_clump_type;
//----------------
int objectID = 1; //starting objectID
int feaID = 1; //starting feature ID
int num_instance = 0; //number of instances
FILE *loc_fp, *doc_fp;
if ((loc_fp = fopen(s_cfg->loc_file, "w")) == NULL || (doc_fp = fopen(s_cfg->doc_file, "w")) == NULL) {
printf("Cannot open loc/doc files.\n");
exit(0);
}
std::default_random_engine generator1, generator2, generator3;
std::poisson_distribution<int> distribution1(lambda1), distribution2(lambda2), distribution3(m_clump);
generator1.seed(seed1); //[1,infty)
generator2.seed(seed2); //[1,infty)
generator3.seed(seed2);
int* patternSize = new int[Ncoloc]; //storing the size |C| (number of features) of each pattern
//generate N patterns size
for (int i = 0; i < Ncoloc; i++) {
patternSize[i] = distribution1(generator1);
//generate m_overlap maximal colocation for each core colocation
for (int a = 0; a < m_overlap; a++) {
int tableSize = distribution2(generator2);
printf("%d\t%d\t\t%d\n", patternSize[i] + 1, tableSize, feaID);
int extrafeaID = feaID + patternSize[i] + a; //the one more spatial feature in each maximal colocation
//---
//generate m_clump value for each feature in this pattern
//m_clump_type ==0: all same fxied value m_clump
//1: random
int* m_clump_value = new int[patternSize[i] + 1];
for (int k = 0; k < patternSize[i] + 1; k++) {
if (m_clump_type == 0)
m_clump_value[k] = m_clump;
else if (m_clump_type == 1)
m_clump_value[k] = rand_i(1, m_clump);
printf("%d\t", m_clump_value[k]);
}
printf("\n");
//---
//create objects for each row instance in the table
for (int j = 0; j < tableSize; j++) {
double rectX = rand_f(0, D1 - d); //bottom left
double rectY = rand_f(0, D1 - d);
//each object is associated with one feature
for (int k = 0; k < patternSize[i]; k++) {
for (int b = 0; b < m_clump_value[k]; b++) {
gen_syn_obj(loc_fp, doc_fp, objectID, feaID + k, rectX, rectY, d);
//generate additional objects right next to the current cell
// if(m_clump_type==1)
// gen_syn_obj(loc_fp, doc_fp, objectID, feaID + k, rectX+d, rectY, d);
}
}
//create an object for the one more spatial feature
for (int b = 0; b < m_clump_value[patternSize[i]]; b++) {
gen_syn_obj(loc_fp, doc_fp, objectID, extrafeaID, rectX, rectY, d);
// if(m_clump_type==1)
// gen_syn_obj(loc_fp, doc_fp, objectID, extrafeaID, rectX+d, rectY, d);
}
}
num_instance += tableSize * (patternSize[i] + 1) * m_clump;
}
feaID += patternSize[i] + m_overlap;
// printf("\n");
}
// if(m_clump_type==1)
// num_instance *=2;
// printf("objID:%d\tnum_instance:%d\tfeaID:%d\n", objectID, num_instance, feaID);
//------generate local noise-------
gen_syn_noise(r_local * num_instance, loc_fp, doc_fp, objectID, 1, feaID, 0, 0, D1);
// printf("------------ global noise -----------\n");
int originalFeaID = feaID;
feaID = int(double(feaID) * (1.0 + r_noise_fea));
gen_syn_noise(r_global * num_instance, loc_fp, doc_fp, objectID, originalFeaID, feaID, 0, 0, D1);
printf("total number of obj:%d\ntotal number of feature:%d\n", --objectID, feaID);
printf("*fea[%d,%d] are original, [%d,%d] are noise\n", 1, originalFeaID - 1, originalFeaID, feaID);
fclose(loc_fp);
fclose(doc_fp);
}
/**
* generate *one* object id @objectID with feature @fea randomly in [rectX, rectY] to [rectX+d, rectY+d]
*/
void gen_syn_obj(FILE* loc_fp, FILE* doc_fp, int& objectID, int fea, double rectX, double rectY, double d)
{
double locX = rectX + rand_f(0, d);
double locY = rectY + rand_f(0, d);
// printf("%d\t%d\t%0.3lf\t%0.3lf\n",objectID,fea,locX, locY);
fprintf(loc_fp, "%d,%f,%f\n", objectID, locX, locY);
fprintf(doc_fp, "%d,%d\n", objectID, fea);
objectID++;
}
/**
* generate local noise and global noise
* @num_noise_obj noise objects
* each randomly pick fea in range [feaStart, feaEnd]
*
*/
void gen_syn_noise(int num_noise_obj, FILE* loc_fp, FILE* doc_fp, int& objectID, int feaStart, int feaEnd, double rectX, double rectY, double d)
{
if (num_noise_obj > 0) {
for (int i = 0; i < num_noise_obj; i++) {
//pick from new features
int fea = rand_i(feaStart, feaEnd);
gen_syn_obj(loc_fp, doc_fp, objectID, fea, 0, 0, d);
}
}
}
/*
* generate scalability test dataset from real
*
*/
void gen_scalability_data(data_t* data_v)
{
FILE *loc_fp, *doc_fp;
if ((loc_fp = fopen("sca_loc.txt", "w")) == NULL || (doc_fp = fopen("sca_doc.txt", "w")) == NULL) {
printf("Cannot open loc/doc files.\n");
exit(0);
}
// int total = 1000000;
// for (int cnt = 1; cnt <= total; cnt++) {
//pick an object and copy its feature
// int i = rand_i(0, data_v->obj_n - 1);
int cnt = 1;
for (int i = 0; i < data_v->obj_n; i++) {
//number of times
for (int t = 0; t < 28; t++) {
//pick two objects and use mid point as new location
int j = rand_i(0, data_v->obj_n - 1);
// int k = rand_i(0, data_v->obj_n - 1);
int fea = data_v->obj_v[i].fea;
double x = (data_v->obj_v[j].MBR[0].min + data_v->obj_v[i].MBR[0].min) / 2.0;
double y = (data_v->obj_v[j].MBR[1].min + data_v->obj_v[i].MBR[1].min) / 2.0;
//print a new object
fprintf(loc_fp, "%d,%f,%f\n", cnt, x, y);
fprintf(doc_fp, "%d,%d\n", cnt, fea);
cnt++;
}
}
fclose(loc_fp);
fclose(doc_fp);
}
/* scalability based on number of features
* for each object, we randomize its feature
*/
void gen_scalability_data2(data_t* data_v)
{
FILE *loc_fp, *doc_fp;
if ((loc_fp = fopen("sca_loc.txt", "w")) == NULL || (doc_fp = fopen("sca_doc.txt", "w")) == NULL) {
printf("Cannot open loc/doc files.\n");
exit(0);
}
int cnt = 1;
for (int i = 0; i < data_v->obj_n; i++) {
//pick an object and copy its feature
int r = rand_i(0,1)*36;
//pick two objects and use mid point as new location
// int j = rand_i(0, data_v->obj_n - 1);
// int k = rand_i(0, data_v->obj_n - 1);
int fea = data_v->obj_v[i].fea+r;
// double x = (data_v->obj_v[j].MBR[0].min +data_v->obj_v[k].MBR[0].min)/2.0;
// double y = (data_v->obj_v[j].MBR[1].min +data_v->obj_v[k].MBR[1].min)/2.0;
double x=data_v->obj_v[i].MBR[0].min;
double y=data_v->obj_v[i].MBR[1].min;
//print a new object
fprintf(loc_fp, "%d,%f,%f\n", cnt, x, y);
fprintf(doc_fp, "%d,%d\n", cnt, fea);
cnt++;
}
fclose(loc_fp);
fclose(doc_fp);
}
|
e7b802bc8a9482f9c399bb67faa1f0739843c7f1 | db82161c3c36b0c12d3abb80b117643aa406fcba | /include/ad/dual/variablle_manager.h | a03f1342b1c4ad4560a48d5ca09c72df933f20a2 | [] | no_license | IgnorantCoder/AutomaticDifferentiation | 5ca9c1217a658f65530b7d61670d99f8b33f84a8 | 5b6c00b529d2b633ac7645833f2bf3c308fe9e66 | refs/heads/master | 2021-01-20T19:33:28.057049 | 2017-05-02T15:24:37 | 2017-05-02T15:24:37 | 85,557,896 | 0 | 2 | null | 2017-05-02T15:24:38 | 2017-03-20T09:27:29 | C++ | UTF-8 | C++ | false | false | 2,213 | h | variablle_manager.h | #pragma once
#include <map>
#include "ad/type_traits/head.h"
#include "ad/dual/variable.h"
#include "ad/dual/detail/create_mapping.h"
namespace ad { namespace dual {
template <typename V>
class variable_manager {
public:
using value_type = V;
public:
variable_manager(
std::map<value_type const*, std::size_t>&& index_mapper);
public:
variable<V> get_variable(const value_type& x) const;
private:
std::map<value_type const*, std::size_t> _index_mapper;
};
template<typename V>
inline variable_manager<V>::variable_manager(
std::map<value_type const*, std::size_t>&& index_mapper)
: _index_mapper(std::move(index_mapper))
{
}
template<typename V>
inline variable<V> variable_manager<V>::get_variable(
const value_type& x) const
{
std::vector<value_type> dx(_index_mapper.size(), 0);
const auto it = _index_mapper.find(std::addressof(x));
if (it != _index_mapper.cend()) {
dx[it->second] = 1.0;
}
return variable<value_type>(x, dx, _index_mapper);
}
/**
@brief dispatcher of variable_manager
*/
template <typename ... T>
variable_manager<typename type_traits::head<T...>::type>
create_variable_manager(const T& ...t)
{
auto&& index_mapper = detail::create_mapping(t...);
return variable_manager<
typename type_traits::head<T...>::type
>(std::move(index_mapper));
}
/**
@brief dispatcher of variable_manager
*/
template<typename V>
variable_manager<V>
create_variable_manager(const std::vector<V>& data)
{
std::map<V const*, std::size_t>&& index_mapper
= detail::create_mapping(data);
return variable_manager<V>(std::move(index_mapper));
}
/**
@brief dispatcher of variable_manager
*/
template<typename V, std::size_t N>
variable_manager<V>
create_variable_manager(const std::array<V, N>& data)
{
std::map<V const*, std::size_t>&& index_mapper
= detail::create_mapping(data);
return variable_manager<V>(std::move(index_mapper));
}
} } |
9d81b94fecfe962213a6a18c0f2176832d7d0439 | 1ee20178bf69d1b1c42e150bc0b754f58776e3c7 | /HA 提高级代码/HA-00020/zoo.cpp | 4d3db7280544db5dabee40bc6b5a62c368a58e82 | [] | no_license | botmagician/CSP-S-2020HA | fc3579f63781a20570b1d19dd26518d38a2df44d | 56fe9d34ec503880c9fcc1f723bbab74d3703c5d | refs/heads/master | 2023-01-13T05:15:46.171341 | 2020-11-09T12:33:33 | 2020-11-09T12:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 988 | cpp | zoo.cpp | #include<bits/stdc++.h>
#define DMY_AK_CSP2020 return 0
using namespace std;
int k,n,m,c,tmp[3];
int a[100001],q[100001],ans;
bool s[100000001][2],f[100000001];
bool v[100000001];
bool w;
inline lowbit_(int x){return x&(-x);}
bool search(int x){
if(v[x]) return f[x];
if(x-lowbit_(x)){
bool res;
res=search(x-lowbit_(x));
res=(res&(s[q[lowbit_(x)]][1]));
v[x]=1;
return f[x]=res;
}else{
v[x]=1;
return f[x]=(!s[q[x]][0])|(s[q[x]][1]);
}
}
int main()
{
freopen("zoo.in","r",stdin);
freopen("zoo.out","w",stdout);
scanf("%d%d%d%d",&n,&m,&c,&k);
memset(q,0,sizeof(q));
memset(s,0,sizeof(s));
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
for(int i=1;i<=m;++i){
scanf("%d%d",tmp+0,tmp+1);
q[tmp[0]]=tmp[1];s[tmp[1]][0]=1;
}
for(int i=1;i<=n;++i){
int tmp=a[i];
for(int j=0;j<k&&tmp<=(1<<j);++j)
{
if((tmp&(1<<j))&&q[j])
s[q[j]][1]=1;
}
}
for(int w=0;w<(1<<k);++w){
if(!v[w]) search(w);
if(f[w]) ++ans;
}
printf("%d",0);
DMY_AK_CSP2020;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.